Test MLX Attention Masks on a Cloud Mac

Test MLX Attention Masks on a Cloud Mac

Test MLX Attention Masks on a Cloud Mac

The same prompt works correctly on its own, but produces different results when included in a batch. Before switching models or adding unified memory, check the isolation boundaries—especially if you have modified an MLX attention layer, batching logic, or masks in a fused kernel. A cloud Mac is useful for keeping an isolated environment in which to reproduce the issue, but testing should start with a few fixed tensors rather than loading the full model weights.

Define the Mask Contract First

This article tests a reference implementation for a single sequence and a single attention head, with inputs shaped [T, D]. Positional encoding, caching, and grouped-query attention are outside its scope. You need a native Apple Silicon Python environment with an importable MLX installation:

python3 -m venv .venv
source .venv/bin/activate
python -m pip install mlx
python -m pip freeze > requirements.lock
python -c 'import platform; print(platform.machine())'

The architecture should be arm64. Save the dependency list and operating system version so subsequent tests can use the same environment.

The contract is that a Boolean value of True means attention is allowed. A query position may attend only to valid keys at its own position or earlier, and invalid queries must produce zero output. That last rule is an explicit choice for this reference function, not a universal requirement for every model layer.

Different interfaces may interpret Boolean masks in opposite ways. When porting an implementation, verify whether a value means “allow” or “block”; do not infer this from the variable name alone.

Build a Readable Reference Implementation

Save the following code as mask_check.py. Scores are computed in single-precision floating point to establish an easy-to-inspect correctness baseline, not to maximize throughput.

import mlx.core as mx

def attention(q, k, v, valid):
    q = q.astype(mx.float32)
    k = k.astype(mx.float32)
    v = v.astype(mx.float32)
    t = q.shape[0]
    pos = mx.arange(t)
    causal = pos[:, None] >= pos[None, :]
    allowed = causal & valid[:, None] & valid[None, :]
    scores = (q @ k.T) / (q.shape[-1] ** 0.5)
    masked = mx.where(allowed, scores, -float("inf"))
    has_key = mx.any(allowed, axis=-1, keepdims=True)
    safe = mx.where(has_key, masked, mx.zeros_like(masked))
    weights = mx.where(allowed, mx.softmax(safe, axis=-1), 0.0)
    return weights @ v

q = mx.arange(12, dtype=mx.float32).reshape(4, 3) / 10
k = mx.flip(q, axis=0)
v = mx.arange(8, dtype=mx.float32).reshape(4, 2)
valid = mx.ones((4,), dtype=mx.bool_)
base = attention(q, k, v, valid)

def same(a, b):
    assert bool(mx.allclose(a, b, atol=1e-5, rtol=1e-5).item())

assert bool(mx.all(mx.isfinite(base)).item())

Passing a fully masked row directly into softmax can produce NaNs when the negative infinities are normalized. This implementation first supplies safe inputs for those rows, then sets their weights to zero. Do not apply a blanket “NaN cleanup” to the final output: doing so can also hide errors in upstream computations.

Test for Future Leakage with Perturbations

Append this code to the same file. It changes only the key and value at the final position. The first three outputs must remain unchanged; the final output is allowed to change.

k_future = mx.concatenate([k[:3], k[3:] + 100], axis=0)
v_future = mx.concatenate([v[:3], v[3:] + 100], axis=0)
changed = attention(q, k_future, v_future, valid)
same(base[:3], changed[:3])

This is stronger evidence than inspecting a triangular matrix: it checks that the mask actually constrains the computed results. If the test fails, first check the direction of the comparison operator, whether the key and query axes have been swapped, and whether the mask is being broadcast incorrectly.

Also perturb each position in turn and compare the outputs before it. Fixed tensors make failures reproducible, but a single example cannot expose every implementation error. Add different sequence lengths and multiple deterministically generated inputs to broaden coverage.

Check Padding Isolation and All-Invalid Inputs

Append two invalid positions on the right, deliberately filling them with large but finite values. Valid outputs should remain unchanged, and padded queries should produce zero output.

qp = mx.concatenate([q, mx.full((2, 3), 100.0)], axis=0)
kp = mx.concatenate([k, mx.full((2, 3), 100.0)], axis=0)
vp = mx.concatenate([v, mx.full((2, 2), 100.0)], axis=0)
validp = mx.array([True, True, True, True, False, False])
padded = attention(qp, kp, vp, validp)
same(base, padded[:4])
same(padded[4:], mx.zeros((2, 2)))

empty = attention(q, k, v, mx.zeros((4,), dtype=mx.bool_))
assert bool(mx.all(mx.isfinite(empty)).item())
same(empty, mx.zeros((4, 2)))

Do not use NaN as a padding value to test this implementation: during matrix multiplication, a zero weight multiplied by NaN can still contaminate the result. If the system permits non-finite values in padding tensors, either reject them at the input boundary or explicitly sanitize invalid positions before multiplication.

Left padding needs a separate test. Although the real tokens remain in order, their physical indices have shifted; models with positional encoding need the correct position IDs. When comparing results, select only valid queries and align them with the semantic positions in the unpadded sequence. Do not compare the entire output tensors directly.

Turn the Reference into an Optimization Gate

Run python mask_check.py. It exits silently on success and returns a nonzero status if an assertion fails. Keep the script, then connect the actual model layer or fused kernel and compare results using the same inputs.

The acceptance checklist should include at least:

For a multi-head implementation, explicitly add the batch and head axes rather than relying on broadcasting that happens to work. Incremental decoding with a cache also requires separate tests: query positions must include the cache offset, so the zero-based square-matrix indices used here cannot be reused unchanged.

If you only call an unmodified, established model interface, there is no need to rewrite its attention layer; prioritize retaining output comparisons between standalone and batched inference. If you are replacing kernels, this small reference implementation is worth keeping long-term. Prove that the isolation boundaries hold before discussing speed, and debugging will have a much clearer scope.

Frequently asked questions

Why not apply softmax directly to a fully masked row?

Normalizing a row of negative infinities can produce NaN. Detect rows with no allowed keys, provide safe inputs, then explicitly zero their weights and verify that their outputs are finite and zero.

Does passing a right-padding test also validate left padding?

No. Left padding shifts the physical indices of real tokens. Check position IDs separately and align the real-token outputs with the corresponding positions in an unpadded sequence.

Check memory before deciding whether to rent

If your local machine can’t handle the model, compare the three unified memory options: M4 16GB, M4 24GB, and M4 Pro 64GB. If your current device is enough, there’s no need to rent. Every plan includes a dedicated physical machine, not a virtual machine.

Plan your next test run

Choose a configuration based on the model, context length, and runtime you need. If you’re unsure about connectivity or environment requirements, start with the getting started guide.