Skip to content

Fix TF32 test-oracle flakiness in the Gemma4 chunk-invariance tests - #485

Merged
davidkoski merged 1 commit into
ml-explore:mainfrom
GoodOlClint:pr/gemma4-test-tf32-guard
Jul 31, 2026
Merged

davidkoski merged 1 commit into
ml-explore:mainfrom
GoodOlClint:pr/gemma4-test-tf32-guard

Conversation

@GoodOlClint

Copy link
Copy Markdown
Contributor

Proposed changes

Fixes #357. On devices with a NAX, Gemma4ChunkedPrefillTests.chunkSizeInvariance and Gemma4UnifiedTests.textOnlyPrefillChunkSizeInvariant fail.

Both tests build a synthetic model from a JSON config, which leaves the MLXNN Linear/Embedding weights at their random float32 defaults, then assert that chunked and single-pass prefill agree to a tolerance calibrated for exact float32. Those two paths are mathematically equivalent, but with TF32 enabled the GPU can select different matmul/attention kernels and reduction orders depending on shape, so the logits drift past that tolerance. This is the test oracle, not the chunking logic — as diagnosed by @aleroot and @davidkoski on the issue.

Per that discussion:

  • Cast both synthetic models to f16, matching what fix speculative decode tests #326 did for SpeculativeDecodingTests. Real models never run float32.
  • Pin the initializer weights so the drift is reproducible.
  • Compare max absolute difference instead of allClose in Gemma4ChunkedPrefillTests — these logits pass through zero, where relative error is meaningless — and widen that bound to 5e-2.

The exact cache-offset assertions are unchanged throughout. Those are the half of the oracle that catches real chunk-boundary bugs, and they are not precision-sensitive.

Pinning uses withRandomState, not MLXRandom.seed

Worth calling out, because the obvious version does not work. MLXRandom.seed mutates process-global state, and swift-testing runs these tests concurrently — all four chunkSize cases plus the sibling tests build their models at overlapping times, so their seeding and their draws interleave on one stream. Measured with a global seed: 0.0 drift running the test alone, 4.0 with one sibling test running alongside (max |logit| is ~3.0). It also leaks a fixed key into every other suite drawing from that stream.

withRandomState is task-local, so each model construction gets its own stream and nothing escapes the closure.

Tolerance

With the weights actually pinned, the drift is deterministic — identical on every run, and unchanged with MLX_ENABLE_TF32=0:

chunk size 16 8 5 3
max abs drift 6.2e-3 8.4e-3 6.4e-3 6.2e-3

5e-2 leaves ~6× margin over the worst case. For the other direction — that the oracle still discriminates — injecting cache/mask defects into the 37-token model moves the logits by 1.0 (token just outside the sliding window flipped), 1.7 (two in-window tokens swapped), and 2.4 (first token dropped), i.e. 20–48× the bound.

Gemma4UnifiedTests keeps its original 1e-4. With the model in f16 that test is bitwise equal, so only the cast was needed there and widening it would only lower the bar.

One assertion the cast affected indirectly

unbatchedTokensAccepted shares makeTinyModel() and so silently started comparing f16 output at rtol: 1e-4, atol: 1e-5 — a budget of ~4e-4 where one f16 ulp at these magnitudes is ~2e-3, i.e. finer than the dtype can represent. It passes only because the 1-D and [1, N] paths are bitwise identical. Converted to the same max-abs-diff form with a bound above one ulp.

Verification

On an M5 Max (the affected hardware):

  • xcodebuild test -scheme mlx-swift-lm-Package -destination 'platform=macOS' -skipPackagePluginValidation — full suite green: 282 XCTest, 314 swift-testing, 0 failures.
  • The two affected suites specifically: 5/5 runs pass with TF32 on, 5/5 with MLX_ENABLE_TF32=0.
  • pre-commit run --all-files — passes (swift-format 603.0.0, matching the CI pin).

Checklist

  • 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)

On devices with a NAX these two tests fail (ml-explore#357). Both build a synthetic
model from config, leaving the MLXNN weights at their random float32
defaults, then assert that chunked and single-pass prefill agree to a
tolerance calibrated for exact float32. The two paths are mathematically
equivalent, but TF32 can select different kernels and reduction orders by
shape, so the logits drift past that tolerance. The chunking logic is
correct; the oracle is not.

- Cast both synthetic models to f16, as merged ml-explore#326 did for
  SpeculativeDecodingTests. Real models never run float32.
- Pin the initializer weights with withRandomState. The tests in these
  suites run concurrently, so MLXRandom.seed would not work here: it
  mutates process-global state that the other tests draw from.
- In Gemma4ChunkedPrefillTests, compare max absolute difference rather
  than allClose, since these logits pass through zero where relative
  error is meaningless, and widen the bound to 5e-2.

Gemma4UnifiedTests keeps its 1e-4 bound: with the model in f16 that test
is bitwise equal, so only the cast was needed.

unbatchedTokensAccepted moves to the same max-abs-diff form. Its old
rtol 1e-4 / atol 1e-5 was finer than one f16 ulp (~2e-3 at these
magnitudes) once the shared factory started returning an f16 model.

Exact cache-offset assertions are unchanged throughout; those catch the
chunk-boundary bugs these tests exist for and are not precision
sensitive.

With the weights pinned the drift is deterministic: 6.2e-3, 8.4e-3,
6.4e-3, 6.2e-3 for chunk sizes 16/8/5/3, identical across runs and
unchanged with MLX_ENABLE_TF32=0. 5e-2 leaves ~6x margin, while an
injected cache/mask defect moves these logits by 1.0-2.4.

@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.

Great update -- thank you!

@davidkoski
davidkoski merged commit 83f3ef6 into ml-explore:main Jul 31, 2026
2 checks passed
@GoodOlClint
GoodOlClint deleted the pr/gemma4-test-tf32-guard branch August 1, 2026 16:44
roryford added a commit to ManifoldKit/mlx-swift-lm that referenced this pull request Sep 20, 2026
Apply ml-explore#485 (83f3ef6) so chunk-invariance tests use seeded float16 synthetic models and a measured absolute drift bound. Keep production model code and exact cache-offset assertions unchanged.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] tests fail due to TF32

2 participants