Skip to content

Test MLX RoPE Position Offsets on a Cloud Mac

A long prompt produces repetitive output when you feed it to the model in chunks, but works normally when passed in one go. Before changing sampling parameters, check the positions. If every chunk computes RoPE starting at position zero, tensor shapes can remain correct and generation can continue, even though the positional relationship between queries and keys has changed. On a cloud Mac, verifying this contract with small tensors before integrating a real model makes the problem easier to isolate than repeatedly loading weights.

Define the Position Contract

RoPE rotates pairs of components along the feature dimension. Here, the input axes are batch, attention heads, sequence, and head dimension, with the sequence axis second to last. offset is the logical position of the first token in the current input—not the chunk index or the batch index.

Suppose a sequence starts at position 37. You process two tokens, then three, then one. The three chunks start at 37, 39, and 42, respectively. Decoding the final token on its own must also use 42.

Chunking should change only how computation is grouped, not the positional encoding of any given token. Establish this before discussing generation quality.

These checks cover only a standard scalar offset, with traditional=False, the frequency base, and the scale parameter held fixed. Do not apply the conclusion directly to mixed-length batches, sliding windows, or model-specific position-scaling schemes.

Pin the Environment

Run these commands in a dedicated directory on the cloud Mac. First, confirm that the terminal is running under the native architecture and that a working Python installation is available. After installation, save the dependency list. Use that same list for subsequent checks rather than resolving the latest dependencies every time.

uname -m
sw_vers
python3 --version
python3 -m venv .venv
.venv/bin/python -m pip install mlx
.venv/bin/python -m pip freeze > requirements.lock

The architecture should be arm64. Also record the operating system version, Python version, and machine environment; the dependency list alone does not capture these conditions. This experiment requires neither a model download nor an inference service.

If installation fails, first check the system support requirements for your Python version and MLX. Do not work around the error by switching to a different process architecture: doing so removes the common baseline for the comparisons that follow.

Write the Assertions

Save the following as rope_contract.py. Construct the input from increasing values so that an all-zero tensor cannot hide an incorrect offset by producing the same result. Set the head dimension to 12 and rotate only the first 8 dimensions, allowing the unrotated tail to be checked as well.

import mlx.core as mx

x = mx.arange(2 * 3 * 6 * 12, dtype=mx.float32)
x = x.reshape(2, 3, 6, 12) / 1000.0

def rotate(value, offset):
    return mx.fast.rope(
        value,
        dims=8,
        traditional=False,
        base=10000.0,
        scale=1.0,
        offset=offset,
    )

def max_error(left, right):
    return mx.max(mx.abs(left - right)).item()

def assert_close(left, right, tolerance=1e-4):
    assert left.shape == right.shape
    error = max_error(left, right)
    assert error <= tolerance, f"max_error={error}"

full = rotate(x, 37)

chunked = mx.concatenate(
    [
        rotate(x[:, :, :2, :], 37),
        rotate(x[:, :, 2:5, :], 39),
        rotate(x[:, :, 5:, :], 42),
    ],
    axis=2,
)
assert_close(full, chunked)

decoded = mx.concatenate(
    [rotate(x[:, :, i:i + 1, :], 37 + i) for i in range(6)],
    axis=2,
)
assert_close(full, decoded)

assert_close(full[..., 8:], x[..., 8:])

before = mx.sum(x[..., :8] ** 2, axis=-1)
after = mx.sum(full[..., :8] ** 2, axis=-1)
assert_close(before, after)

wrong = mx.concatenate(
    [
        rotate(x[:, :, :2, :], 37),
        rotate(x[:, :, 2:5, :], 37),
        rotate(x[:, :, 5:, :], 37),
    ],
    axis=2,
)
assert max_error(full, wrong) > 1e-3

Run .venv/bin/python rope_contract.py. It should finish silently on success and exit with a nonzero status if an assertion fails. Reading the error scalar with .item() also ensures that the relevant computation finishes before the check is evaluated.

The four positive checks cover equivalence under chunking, equivalence under token-by-token execution, an unchanged tail, and norm preservation under rotation. The final check deliberately resets the position for subsequent chunks and requires a clear difference from the correct result. This prevents the test from consisting only of positive cases that merely appear to pass.

Diagnose Differences

Check Axis Order First

A real attention layer may initially produce a tensor in batch, sequence, heads, dimension order. If passed directly to the operator, its head axis will be treated as the sequence axis. Assert the shape at the wrapper function's entry point, then check the transpose. A tensor having four dimensions does not mean its layout is correct.

Then Check Where Positions Come From

Accumulate the number of tokens already consumed in the current logical sequence, not the number of requests. If one call supplies three tokens, the next starting position must advance by three. With a sliding window, the retained cache length may be smaller than the cumulative position, so cache length cannot simply replace the position counter.

Likewise, do not blindly use one scalar offset for a padded batch. Preserve each sequence's position semantics according to the model implementation, then validate them by comparing single-sequence and batched results.

Check Precision Last

Get the float32 test above to pass before introducing the actual precision and larger positions. The tolerance here is specific to this small test fixture, not a universal threshold for every length and data type. When a discrepancy appears, record the maximum error, input shape, and positions before increasing the tolerance.

Validate the Integration

Apply the same chunking pattern to the real attention layer. Hold weights, inputs, and execution mode fixed, then compare outputs at corresponding positions between full-sequence and chunked execution. Compare numerical outputs first, then generated results; identical text may simply mean that sampling did not expose the difference.

Check each of the following during integration:

  • Queries and keys use compatible position rules, with configuration parameters taken from the same model definition.
  • The cache is explicitly defined to store either pre-rotation or post-rotation keys, avoiding a second rotation after retrieval.
  • Each new request resets its own position state rather than inheriting the previous request's counter.
  • Tests cover single-token inputs, uneven chunks, and nonzero starting positions, with failing inputs saved.

This fixture verifies position-offset consistency; it does not prove that the frequency-pairing scheme matches a particular model. After integration, retain trusted reference outputs for that model as well. Commit the script, dependency list, and error records together. When upgrading MLX or changing the attention implementation, rerun this small contract test before launching a full inference task.

Frequently asked questions

How should offset advance across RoPE chunks?

Use the logical position of the first token in the current chunk. For a continuous sequence, add the number of previously processed tokens to the starting position; do not reset each chunk to zero.

Do passing assertions prove that model decoding is correct?

No. They check the rotation operator's offset and dimension contract. Also verify attention tensor axes, query and key positions, and whether cached keys are rotated twice.

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.