[BUG] MiniCPM3 batch generation ignores the left-padding mask
Describe the bug
For a model (I use MiniCPM3 because it's small), the first generated token's log-probability vector changes when the same prompt is run as the shorter member of a batch.
To Reproduce
No model weights or tokenizer downloads are needed. The script uses float32 parameters, a fixed random seed, and prompts of lengths 12 and 3. The shorter prompt receives nine padding positions. Save it as repro.py.
python3 -m venv .venv
source .venv/bin/activate
python -m pip install "mlx==0.32.2" "mlx-lm==0.31.3"
python repro.py# No weights needed: a tiny randomly initialised MiniCPM3, float32, greedy.
# The same prompt, generated alone and as the shorter (left-padded) member of a batch.
import mlx.core as mx
import mlx_lm
from mlx_lm.generate import BatchGenerator, generate_step
from mlx_lm.models.minicpm3 import Model, ModelArgs
mx.random.seed(0)
model = Model(ModelArgs(
model_type="minicpm3", hidden_size=64, dim_model_base=64, num_hidden_layers=2,
intermediate_size=128, num_attention_heads=4, num_key_value_heads=4, rms_norm_eps=1e-5,
vocab_size=100, q_lora_rank=32, qk_nope_head_dim=8, qk_rope_head_dim=8, kv_lora_rank=16,
scale_depth=1.4, scale_emb=1.0, max_position_embeddings=512,
rope_scaling={"type": "longrope", "long_factor": [1.0] * 4, "short_factor": [1.0] * 4,
"original_max_position_embeddings": 512}))
mx.eval(model.parameters())
long_prompt, short_prompt = list(range(1, 13)), [7, 8, 9] # the short one gets 9 pad positions
def alone(prompt):
_, logprobs = next(iter(generate_step(mx.array(prompt), model, max_tokens=1)))
return logprobs
gen = BatchGenerator(model, max_tokens=1, stop_tokens=None)
uids = gen.insert([long_prompt, short_prompt])
batched = {}
while len(batched) < 2:
for r in gen.next_generated():
batched.setdefault(r.uid, r.logprobs)
gen.close()
print("mlx", mx.__version__, "| mlx-lm", mlx_lm.__version__)
for name, uid, prompt in (("unpadded", uids[0], long_prompt), ("padded ", uids[1], short_prompt)):
diff = mx.abs(batched[uid] - alone(prompt)).max().item()
print(f"{name} member: max |logprobs in batch - logprobs alone| = {diff:.3e}")
assert diff < 1e-4, f"{name} member of the batch differs from the same prompt alone by {diff:.3f}"Observed behavior
Recorded output (exit code 1; only the local traceback path has been shortened):
ProductName: macOS ProductVersion: 26.6.1 BuildVersion: 25G76
Apple M1 Ultra
mlx 0.32.2 | mlx-lm 0.31.3
unpadded member: max |logprobs in batch - logprobs alone| = 4.768e-07
padded member: max |logprobs in batch - logprobs alone| = 1.348e+00
Traceback (most recent call last):
File "repro.py", line 38, in <module>
assert diff < 1e-4, f"{name} member of the batch differs from the same prompt alone by {diff:.3f}"
^^^^^^^^^^^
AssertionError: padded member of the batch differs from the same prompt alone by 1.348
exit code: 1Expected behavior
Each prompt's first-step log probabilities should agree between standalone and batched generation within floating-point tolerance. The script uses an absolute tolerance of 1e-4.
Desktop (please complete the following information):
- OS Version: macOS 26.6.1 (25G76)
- Hardware: Apple M1 Ultra
- MLX: 0.32.2
- MLX-LM: 0.31.3
- Device: Metal GPU
Additional context
AI assistance was used to prepare the reproduction code and this Additional context.
In MiniCPM3's model call, create_attention_mask(h, cache) receives the list of per-layer caches. The helper in base.py only calls make_mask when the supplied object has that method. A list does not, so the helper returns a causal mask for prefill and None for a single-token step. The BatchKVCache padding mask is skipped.
The call should use a layer's cache, with the no-cache case handled, as other models do. This explains why the padded member differs while the unpadded member agrees. The attached reproduction exercises BatchGenerator; it does not exercise the HTTP server.
Source: ml-explore/mlx-lm