Skip to content

Drop the attention mask from text-only VLM prompts - #700

Merged
davidkoski merged 2 commits into
ml-explore:mainfrom
aleroot:alessio/gemma4-text-mask
Oct 15, 2026
Merged

davidkoski merged 2 commits into
ml-explore:mainfrom
aleroot:alessio/gemma4-text-mask

Conversation

@aleroot

@aleroot aleroot commented Oct 14, 2026

Copy link
Copy Markdown
Contributor

Proposed changes

FastVLM, Gemma 3, Gemma 4 (Gemma4Processor, Gemma4UnifiedProcessor), Mistral 3 and SmolVLM attach an all-ones attention mask to every prompt, including prompts with no media. ChatSession sets carriesAttentionMask: input.text.mask != nil, and every prompt-cache reuse rule rejects a turn that carries a mask. On these models, every text turn and every tool follow-up prefills the whole conversation again.

A text-only prompt is one unpadded sequence, so the mask carries nothing.
None of these models reads it without media:

  • Gemma 4 never reads text.mask.
  • Gemma 3 and FastVLM read it only on the image path.

Their text-only prompts now carry no mask, as Qwen2-VL, Qwen3-VL, GLM-OCR, LFM2-VL and Muse-Glimmer already do. Prompts with media are unchanged.

gemma-4-12B-it-4bit, 1 tool call + 2 turns Before After
Cached positions reused per pass after the first 0, 0, 0 175, 226, 267
Prompt time of those passes 3.1–3.9 s ≈1.0 s

Checklist

Put an x in the boxes that apply.

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

AI usage

  • I have read this PR description in full and approve it as my own, and it
    accurately describes the code changes.
  • AI usage disclosure:

FastVLM, Gemma 3, Gemma 4 (both processors), Mistral 3 and SmolVLM
paired every prompt with an all-ones attention mask, including prompts
with no media. `ChatSession` reads any mask as a reason not to resume a
cache (`carriesAttentionMask`), so on these models every text turn and
every tool follow-up prefilled the whole conversation again.

A text-only prompt is one unpadded sequence, so the mask carries
nothing, and none of these models reads it without media. Their
text-only prompts now carry no mask, as Qwen2-VL, Qwen3-VL, GLM-OCR,
LFM2-VL and Muse-Glimmer already do. Prompts with media are unchanged.

Measured on gemma-4-12B-it-4bit (Gemma4UnifiedProcessor), one tool call
and two follow-up turns: the passes after the first reused 175, 226 and
267 cached positions instead of 0, and their prompt time fell from
3.1-3.9 s to about 1.0 s.
@davidkoski

Copy link
Copy Markdown
Member

infrastructure failure in CI, retriggering

Comment on lines -1025 to +1026
let tokensArray = MLXArray(promptTokens).expandedDimensions(axis: 0)
let mask = ones(like: tokensArray)
return LMInput(text: .init(tokens: tokensArray, mask: mask), image: nil)
// No mask: one unpadded sequence needs none, and a mask stops prompt-cache reuse.
return LMInput(tokens: MLXArray(promptTokens).expandedDimensions(axis: 0))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mistral3, FastVLM and SmolVLM2 don't handle 1-D

    @Test
    func mistral3DropAttentionTest() throws {
        // e.g. in VLMImageTokenMismatchTests -- not the right place for it,
        // but it builds the model we want
        let model = try Self.makeTinyMistral3()
        
        let cache = try model.newCache(parameters: nil)
        
        // Turn 1: the processor's [1, L] prompt
        
        _ = try model.prepare(
            LMInput(tokens: MLXArray([Int32(1), 2, 3, 4]).expandedDimensions(axis: 0)),
            cache: cache, state: nil, prefill: .init(stepSize: 512))
        
        // Turn 2: 1-D
        //    case .appendSuffix(let suffixStart, _):
        //        input = LMInput(
        //            tokens: MLXArray(Array(promptTokenIds[suffixStart...])))

        _ = try model.prepare(
            LMInput(tokens: MLXArray([Int32(5), 6, 7])),
            cache: cache, state: nil, prefill: .init(stepSize: 512))
    }

these models assume a [1, L] input always. I think it is sufficient to expand dimensions if ndim is 1.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, I did not think about. Also fixed a Ministral warm-cache mask mismatch using the existing cache-aware helper, see update

@davidkoski davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Change looks good but see note on 3 models not handling [L] inputs.

@davidkoski davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Change looks good, thank you!

@davidkoski
davidkoski merged commit 77f4e03 into ml-explore:main Oct 15, 2026
5 checks passed
davidtai added a commit to Layr-Labs/mlx-swift-lm that referenced this pull request Oct 23, 2026
… text-only masks

- Qwen2-VL, Qwen2.5-VL, GLM-OCR, Qwen3-VL-MoE: restore the stateless
  callAsFunction(_:cache:). Upstream (e31237a, cc712f4, 3f9c86f) left only
  the typed entry point, so `model(tokens, cache:)` hit the protocol default
  fatalError and aborted the test process (shards 7 and 14).
- ModelOptNVFP4Weights.calibratedMatmul: fork keeps its numerics over mlx
  3eb822ca (#4483). qqmm with global scales on bfloat16 now takes the tiled
  matrix kernel from get_qmv_batch_limit rows on; the eager reference calls
  qqmm on at most 4 rows so it stays one matrix-vector product per row, the
  graph's .rowwise accumulation (NemotronSuperGraphExecution and
  ModelOptGraphParity bitwise tests).
- Gemma4Processor: text-only prompts carry no mask, as upstream 77f4e03
  (ml-explore#700) does for every other VLM processor (a mask stops prompt-cache reuse).
- Tests adapted to deliberate upstream behavior: Qwen2VL prepare returns all
  prompt logits (e31237a); tied-embedding sanitize drops lm_head (3de04ab),
  untied variants keep the rename check; M-RoPE delta is request state
  (3f9c86f), decode tests pass the prepare state; Qwen 3.5 norm shift needs
  a raw conv1d (28a7f30), fixtures carry one; Qwen3-VL text-only and SmolVLM2
  text-only have no mask (72d9fdb, 77f4e03); FastVLM without -200 throws
  (648693c); TestInputProcessor tokenizer (a86ee6a); Qwen3-VL size block
  (65be34c); RotatingKVCache 7-value metaState (ruled).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
ximyro pushed a commit to ximyro/mlx-swift-lm that referenced this pull request Nov 4, 2026
Brings in ml-explore#622 (exact prefix rewinds in rotating KV caches), ml-explore#619 (streaming
detokenizers), ml-explore#698, ml-explore#699, ml-explore#700, ml-explore#701, ml-explore#705, ml-explore#697 and ml-explore#695.

Conflicts: AttentionUtils.swift keeps TurboKV telemetry next to upstream's
SharedAttentionKVCache; KVCache.swift takes upstream's serialization and
rotating-cache view/trim while keeping the fork's TurboQuant state, public
cache fields and temporallyOrdered.

Follow-ups for upstream behavior the fork had changed: the Qwen2VL audio
placeholder no longer indexes content.count - 1 when a tool-call message has no
text part, and Gemma4MessageGenerator uses content parts for every non-system
role.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
davidkoski pushed a commit that referenced this pull request Nov 19, 2026
)

* Chunk every DiffusionGemma prompt and reuse its cache across turns

`DiffusionGemma4Processor` attached an attention mask and token types to
every prompt, including prompts with no media. The token types made
`DiffusionGemmaLanguageCore.prepareDiffusion` skip its chunking and
encode the whole prompt in one pass. On an M5 (NAX) GPU a pass of 1024
tokens or more with head dimension 256 selects the JIT kernel
`steel_attention_dsplit_...`, which MLX fails to build
(ml-explore/mlx#4832), so the process stopped in a fatalError. The mask
also made `ChatSession` prefill the whole conversation on every turn.

Fix the three DiffusionGemma gaps:

- `prepareDiffusion` chunks every prompt by `windowSize`. A chunk never
  cuts a visual block: the cut moves back to the start of the block, or
  past its end when the block starts the chunk. A chunk without visual
  positions takes the causal mask.
- `DiffusionGemma4Processor` returns a text-only prompt with no mask and
  no token types, as #700 did for the other VLM processors.
- `DiffusionGemma.reasoningConfig` is `.gemma4`, so reasoning streams as
  reasoning instead of raw channel markup.

The visual block rule keeps chunking exact: positions inside a block
attend to each other in both directions, so a block split across two
chunks would lose half of its attention. With the block kept whole,
chunked encoding matches one pass, and the tests compare the two.

* Apply custom logit processors to the DiffusionGemma canvas

`BlockDiffusionTokenIterator` threw `invalidDiffusionConfiguration` for
any custom logit processor. An application that adds a processor to
every turn, such as a presence penalty or an observer that counts the
generated tokens, failed every DiffusionGemma turn, so it had to check
the model kind and rebuild its components for block diffusion.

Apply them as the Transformers reference does:

- The custom processor runs on every canvas position at each denoising
  step, before the temperature schedule.
- Its history is the prompt and the emitted tokens: `didSample(token:)`
  runs as each token leaves the canvas, never for provisional canvas
  tokens. `didEmit(token:)` and `finalizeGeneration()` run as in
  `TokenIterator`.
- A `SequentialLogitProcessor` steers one token at a time, so a canvas
  cannot apply it. `ThinkingBudgetProcessor` is one; the iterator drops
  it from the chain with a warning and generates without it.
- The public initializer passes its components on instead of
  dropping them after validation.

The built-in penalties of `GenerateParameters` still do not apply, as
before: Transformers rejects them in the diffusion generation config,
and `GenerateParameters.diffusion` holds the diffusion controls.

Live with diffusiongemma-26B-A4B-it-mxfp4, a 1,563-token prompt with a
thinking budget, a presence penalty and a counting observer answers
correctly: the budget is skipped and the other two apply.

* Keep a banned token from disabling diffusion early stopping

A custom processor that bans a token sets its logit to `-inf`. The
canvas entropy then computed `0 * -inf = NaN` for every position, so
entropy-bound acceptance compared NaN and the mean-entropy stop never
fired: each canvas ran every denoising step. Transformers does not have
this problem, because `torch.distributions.Categorical.entropy` gives a
zero-probability token no weight.

- `entropy(logits:)` leaves zero-probability tokens out of the sum.
- Self-conditioning is unchanged. As in Transformers, the next step
  conditions on the processed logits; its softmax gives a `-inf` logit
  zero weight. A test proves both self-conditioning paths (dense and
  quantized embeddings) match a finite `-1e4` logit exactly.
- `LogitProcessor.removingAll(where:)` returns a processor without the
  processors a predicate selects. The default applies the predicate to
  the processor itself; `ChainedLogitProcessor` and
  `CompositeLogitProcessor` apply it to each processor they contain.
- `SequentialLogitProcessor` is public and lives next to
  `LogitProcessor`, so processors outside the package can opt out of
  block diffusion too.

The block-diffusion iterator used to know `ChainedLogitProcessor` only,
so a sequential processor inside a `CompositeLogitProcessor` (from
MLXGuidedGeneration, which MLXLMCommon cannot see) stayed on the canvas.
With the filter as a capability, every container handles its own
structure, and the iterator keeps only its policy: remove sequential
processors and log a warning.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants