Testing MLX Tensor Shapes, Broadcasting, and Reduction Axes
You move your local inference code to a cloud Mac. The model loads, and the output shapes look right, but applying a different weight to each token produces unexpected results. The problem may have nothing to do with the model or hardware: MLX broadcasts according to dimension rules, without knowing whether an axis represents tokens or features. The small, model-independent tests below pin down what the computation should mean before you reconnect it to a real pipeline.
Define the Axis Contract Before Running a Large Model
Let the input x have shape (B, T, D), representing batch size, sequence length, and feature count. Token weights have shape (T,): every feature of a given token should receive the same weight, and those weights are shared across all batches.
If each sample needs its own weights, define a separate interface accepting (B, T). Do not make one function guess between the two interpretations. This article also explicitly rejects empty sequences. Applications that need to support empty inputs should define the return value separately rather than rely on incidental behavior in the underlying reduction.
Run the following commands in a native Apple Silicon Python environment, saving the code below as shape_contract.py. Once the dependencies are installed, capture their versions and use the same lock file when reproducing the results.
python3 -m venv .venv
source .venv/bin/activate
python -m pip install mlx
python -m pip freeze > requirements.lock.txt
python shape_contract.py
These tests allocate only small tensors. There is no need to load a full model just to reproduce a broadcasting error. They are useful for validating inference preprocessing and training helper functions, not for assessing model quality or device throughput.
Use Equal-Length Axes to Expose Silent Errors
Broadcasting aligns dimensions from the trailing axis. If you write x * weights, the one-dimensional weights align with the feature axis; MLX does not automatically find the sequence axis. When T and D differ, this will usually raise a shape error. When they are equal, the mistake can go unnoticed.
The following test deliberately makes both axes length four and uses asymmetric input values and weights. It checks both that the incorrect expression produces a different result and that the correct expression matches an elementwise reference. This prevents all-zero inputs or all-one weights from hiding the bug.
import mlx.core as mx
def apply_token_weights(x, weights):
if x.ndim != 3 or weights.ndim != 1:
raise ValueError("Expected rank-3 input and rank-1 weights")
if any(size == 0 for size in x.shape):
raise ValueError("Empty dimensions are not supported")
if weights.shape[0] != x.shape[1]:
raise ValueError("Token axis length mismatch")
return x * weights.reshape(1, x.shape[1], 1)
x = mx.arange(1, 33, dtype=mx.float32).reshape(2, 4, 4)
weights = mx.array([1, 2, 3, 4], dtype=mx.float32)
actual = apply_token_weights(x, weights)
wrong = x * weights
mx.eval(actual, wrong)
assert actual.shape == x.shape
assert not bool(mx.array_equal(actual, wrong).item())
source = x.tolist()
expected = [
[
[value * (token + 1) for value in features]
for token, features in enumerate(batch)
]
for batch in source
]
assert actual.tolist() == expected
The small integers used here are exactly representable, so strict equality checks are appropriate. For general floating-point computations, set tolerances according to the numerical precision of the operations, but never make them loose enough to conceal an entire axis being misaligned.
Matching shapes only prove that two tensors fit into the same box, not that each value came from the right position. Broadcasting tests must check both shape and numerical meaning.
Keep Reduced Dimensions for Unambiguous Broadcasting
To compute a mean along the sequence axis and subtract it from the original input, the mean should have shape (B, 1, D). Retaining the length-one axis makes the intent explicit: center each feature independently within each batch.
Append the following snippet to the same file. This test uses unequal axis lengths and checks the mean residual along the sequence axis for every batch and feature, rather than checking only the overall mean of the tensor.
y = mx.arange(1, 25, dtype=mx.float32).reshape(2, 3, 4)
mean = mx.mean(y, axis=1, keepdims=True)
centered = y - mean
residual = mx.mean(centered, axis=1)
mx.eval(mean, centered, residual)
assert mean.shape == (2, 1, 4)
assert centered.shape == (2, 3, 4)
assert bool(mx.all(mx.abs(residual) < 1e-6).item())
Do not omit axis: the default global reduction may still produce a valid result, but it changes the definition of the computation. Nor should you patch shape errors with an arbitrary reshape; rearranging dimensions does not automatically restore the intended meaning of the axes.
Reject Invalid Inputs, Then Test Degenerate Dimensions
At production entry points, reject invalid inputs with explicit exceptions rather than relying solely on assert, since optimization mode can remove assertions. The assertions below are part of the tests themselves, so do not run them with -O.
def expect_rejection(x, weights):
try:
apply_token_weights(x, weights)
except ValueError:
return
raise AssertionError("Invalid input was accepted")
expect_rejection(mx.zeros((2, 3, 4)), mx.ones((4,)))
expect_rejection(mx.zeros((2, 3, 4)), mx.ones((2, 3)))
expect_rejection(mx.zeros((2, 0, 4)), mx.ones((0,)))
single = apply_token_weights(
mx.ones((1, 1, 3)),
mx.array([2.0])
)
mx.eval(single)
assert single.tolist() == [[[2.0, 2.0, 2.0]]]
Also add a valid case with a batch size greater than one and different sequence and feature lengths. Length-one axes deserve particular attention: calling squeeze() without an axis argument can remove the batch axis too. Recheck the axis contract after transposing as well. In particular, swapping equal-length axes changes their meaning without changing the dimensions, so shape checks alone cannot catch it.
Run the Small Tests Before the Real Workload
Run the standalone script first. Only after it passes should you proceed to load weights, batch data, and run training steps. Stop immediately if it fails; do not continue producing evaluation results that merely look plausible. Record the Python, MLX, and operating system versions along with the code commit identifier so that code changes can be distinguished from environment changes.
When integrating real data, check shapes in order: after tokenization, after batching, before weighting, and after reduction. Log only dimensions and data types, not raw prompts or data contents. If the weights later gain a batch dimension, update the contract and add tests rather than silently accepting more input forms.
The final acceptance checklist is short: invalid shapes are explicitly rejected, the equal-length-axis case exposes the bug, unequal-length axes produce correct results, singleton axes remain intact, and reduced values match the per-axis reference. Get these small tests passing reliably before discussing model size or execution speed.
Frequently asked questions
Why check values when the output shape is correct?
When sequence length equals feature count, broadcasting along the wrong axis can produce the expected output shape. Asymmetric inputs and elementwise reference values expose the mismatch.
Should every reduction use keepdims=True?
No. Keeping dimensions is useful when the result will be combined with the original tensor. A final output can drop the axis, provided its expected shape is checked explicitly.
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.