Skip to content

Test MLX KV cache isolation: branches, prefix reuse and rollback

You generate a response to a prompt, then branch from that same prompt to try a different continuation—only to find that the second result is influenced by the first. Before changing sampling parameters, check whether the two requests share the same mutable KV cache and whether reads still reach the old tail after a rollback. On a cloud Mac, start with deterministic tests using small tensors before loading model weights. This separates cache bugs from the randomness of generation.

Define the contract

A KV cache stores the keys and values already computed by attention layers. Here, we fix the layout as [batch, heads, sequence, dimensions], with the sequence axis second from last. Capacity is not the same as valid length: no matter how much space is preallocated, only committed tokens may be read.

Start with three requirements:

  • After an append, the output for the new segment must match the corresponding positions in a full-sequence computation.
  • When two branches are created from the same prefix, updating one must not change the other.
  • Rolling back to length p and appending again must be equivalent to never having processed the discarded tail.

These tests check cache state, not generation quality. Do not substitute “the answer looks normal” for tensor assertions, or use randomly sampled outputs to decide whether caches are isolated.

Set up a reference

Install MLX in a native arm64 Python environment. Using your existing Python 3 installation, first check the interpreter architecture, then create an isolated environment. Do not mix in dependencies installed under a different interpreter.

python3 -c 'import platform; assert platform.machine() == "arm64"'
python3 -m venv .venv
source .venv/bin/activate
python -m pip install mlx
python -m pip freeze > requirements.lock
sw_vers > system-version.txt

Save the following code as cache_contract.py. It uses a single batch, a single head, and fixed inputs, deliberately leaving out projection layers and positional encoding. It tests only cache storage, append positions, and the visible range. The inputs are not actual model tokens; they are Q, K, and V tensors that have already been computed.

import mlx.core as mx

def close(a, b):
    error = mx.max(mx.abs(a - b)).item()
    assert error < 1e-5, error

def attention(q, k, v, offset):
    nq, nk = q.shape[-2], k.shape[-2]
    visible = (
        mx.arange(nk)[None, :]
        <= offset + mx.arange(nq)[:, None]
    )
    scores = (q @ mx.swapaxes(k, -1, -2)) / (q.shape[-1] ** 0.5)
    scores = mx.where(visible, scores, -float("inf"))
    return mx.softmax(scores, axis=-1) @ v

def append(state, q, k, v):
    old_k, old_v = state
    offset = old_k.shape[-2]
    new_k = mx.concatenate([old_k, k], axis=-2)
    new_v = mx.concatenate([old_v, v], axis=-2)
    return attention(q, new_k, new_v, offset), (new_k, new_v)

def cut(x, start, end):
    return x[:, :, start:end, :]

q = mx.sin(mx.arange(32, dtype=mx.float32)).reshape(1, 1, 8, 4)
k = mx.cos(mx.arange(32, dtype=mx.float32)).reshape(1, 1, 8, 4)
v = mx.arange(32, dtype=mx.float32).reshape(1, 1, 8, 4) / 32
p = 3
prefix = (cut(k, 0, p), cut(v, 0, p))
full = attention(q, k, v, 0)

state = prefix
for i in range(p, 8):
    out, state = append(
        state, cut(q, i, i + 1), cut(k, i, i + 1), cut(v, i, i + 1)
    )
    close(out, cut(full, i, i + 1))

snapshot = mx.array(prefix[0])
out_a, branch_a = append(
    prefix, cut(q, p, 8), cut(k, p, 8), cut(v, p, 8)
)
kb = -cut(k, p, 8)
vb = cut(v, p, 8) + 2
out_b, branch_b = append(prefix, cut(q, p, 8), kb, vb)
ref_b = attention(
    q,
    mx.concatenate([prefix[0], kb], axis=-2),
    mx.concatenate([prefix[1], vb], axis=-2),
    0
)
close(out_a, cut(full, p, 8))
close(out_b, cut(ref_b, p, 8))
close(prefix[0], snapshot)
assert branch_a[0].shape[-2] == branch_b[0].shape[-2] == 8

rolled = tuple(cut(x, 0, p) for x in branch_a)
out_rollback, _ = append(rolled, cut(q, p, 8), kb, vb)
close(out_rollback, out_b)

Run python cache_contract.py. A normal exit means the tests passed. A failed assertion returns a nonzero exit code, so the script can be plugged directly into a job's validation step. The tolerance here applies only to these small float32 tensors; do not carry it over unchanged to quantized models.

Check branch isolation

The reference implementation returns new arrays on every concatenation, so both branches can safely reference a read-only prefix. Real models often write in place to preallocated buffers. Simply copying the outer list does not copy the underlying storage.

When connecting a real cache class, keep the test inputs and reference outputs above, and replace append with a cache adapter. Have branch A write its tail first, then run B, and finally read A again. All three results must match their respective independently computed references. Add another round with the execution order reversed, so a fixed order cannot hide a bug.

Separate ownership concerns

For paged implementations, check page tables, write positions, and reference counts separately. Sharing physical pages may be valid; sharing a mutable page table may not be. Canceling one request must not reclaim pages that another request is still using.

Verify rollback

The script uses slicing to express logical truncation. A production cache may update only its valid length without shrinking the actual arrays. That is also acceptable, but the attention kernel must receive the correct valid range.

Build a more sensitive failure case: fill the V tail to be discarded with clearly different finite values, roll back, and append a different continuation. If the old tail still affects the output, the valid length is usually not reaching the read path, or the mask is incorrectly based on allocated capacity.

Also cover rolling back to zero, keeping the current length, and appending in chunks after a rollback. Requests for negative lengths or lengths beyond the current valid length must be explicitly rejected; do not rely on slicing to clamp them automatically. If the cache also stores a positional offset, rollback must restore it as well, rather than updating only K and V.

Integrate acceptance checks

Maintain two layers of tests. The first is the cache contract shown here: it requires no weight downloads and makes failures quick to isolate. The second loads the actual model and uses fixed tokens to compare logits from cached decoding against an uncached forward pass—not the final generated text.

At a minimum, acceptance records should include the dependency lockfile, system version, cache implementation type, data type, chunking scheme, and maximum error. Quantized caches need their own tolerances; do not keep loosening thresholds until failures disappear.

Finally, add an empty prefix, different prefix lengths, and repeated consecutive rollbacks, and verify that the valid cache length agrees across all layers. Integrate prefix reuse into actual request scheduling only after all three conditions pass: equivalence to a full forward pass, independent branches, and no reads from the old tail after rollback.

Frequently asked questions

Can requests with identical prompts share a mutable cache?

Not the same mutable cache object. Share a read-only prefix only when each request owns its valid length and append state. In-place caches need copying, copy-on-write or separate page tables.

Must rollback zero out the unused tail?

Not necessarily. All reads must respect the valid length, and subsequent writes must resume at the correct offset. Cross-tenant erasure and access isolation require separate checks.

Rent a Mac for your project

Dedicated physical Mac mini, not a virtual machine. Choose a daily, weekly, monthly, or quarterly rental. It stops when your term ends unless you renew. Export your project files and logs before your rental ends.

Choose a plan

Start for your project, stop when you're done

Choose a dedicated physical Mac mini and rent it by the day, week, month, or quarter.