Skip to content

test: add kernel forward-pass tests for more text models - #185

Merged
Gajesh2007 merged 24 commits into
mainfrom
test/kernel-forward-text
Oct 2, 2026
Merged

Gajesh2007 merged 24 commits into
mainfrom
test/kernel-forward-text

Conversation

@davidtai

@davidtai davidtai commented Sep 30, 2026 •

Copy link
Copy Markdown

Proposed changes

PR C of the kernel forward-pass series. It adds forward-pass tests with tiny random models for the other text models with low coverage. It uses the helper of #183 (SyntheticModel, ForwardPassChecks, ModelCase).

Merge order: this PR merges after #174, #175, #179 and #183. It is based on test/kernel-forward-core (#183). It does not depend on #184.

What it adds

Tests/MLXLMTests/Kernel/LLM/TextModelForwardPassTests.swift runs the ModelCase checks on a table of 15 models: Apertus, InternLM2, Mistral 3 text (sliding window and Llama 4 query scaling), MiniMax, Bailing MoE (grouped routing), GLM-4 MoE, AfMoE, LFM2, LFM2 MoE, MiMo V2 Flash (sliding window with attention sinks), GLM-4 MoE Lite (multi-head latent attention), Granite MoE hybrid (Mamba 2), Falcon H1 (parallel Mamba and attention), Jamba and Baichuan M1. Each model has hidden size 32, 2 or 3 layers and vocabulary 64; the MoE models have 4 experts with top-2 routing.

For every model the checks are: logits shape and dtype for batch 1 and 2, finite values, determinism, cache consistency (prompt in chunks 5, 3, then 3 decode steps, batch 1 and 2), batch invariance, causality, checkpoint keys and shapes, a load through loadWeights in the checkpoint layout (for MiniMax, GLM-4 MoE, AfMoE, LFM2 MoE, MiMo V2 Flash and GLM-4 MoE Lite with one tensor per expert, for LFM2 and LFM2 MoE with PyTorch convolution layout, for Granite with the fused input_linear), with extra keys that sanitize(weights:) must drop, and a wrong shape that must be rejected.

Extra tests: Jamba per-expert checkpoint, Baichuan M1 tied embeddings and head normalization, the InternLM2 dynamic NTK RoPE layer, and DeepseekV3ForwardPassTests.swift.

Tolerances: 1e-4 for float32 comparisons of cached and full passes, batch invariance and causality (only the order of sums differs; measured differences are near 1e-6). Loads are exact, except Baichuan M1 (1e-5, because sanitize(weights:) divides the head rows by their length plus 1e-7).

Production defects found (tests kept, marked with withKnownIssue)

All paths are in Libraries/MLXLLM/Models/.

  1. AfMoE.swift:466: without a cache, Array(repeating: nil as KVCache?, ...) as? [KVCache] fails, so layerCache is nil and the sliding-window layers get no mask. The full pass is not causal.
  2. LFM2MoE.swift:405-411: without a cache the attention mask is .none. The full pass is not causal.
  3. GraniteMoeHybrid.swift:464-470: the same as 2.
  4. FalconH1.swift:611-620: the private createAttentionMask always returns nil, so a prompt runs attention without a causal mask.
  5. Jamba.swift:537: sanitize(weights:) stacks experts only under block_sparse_moe.experts.N.w1 and writes block_sparse_moe.switch_mlp, but the module path is feed_forward.switch_mlp. A Hugging Face checkpoint with one tensor per expert does not load.
  6. BaichuanM1.swift:223: the sliding-window layer gets a mask without the window, so a prompt longer than the window attends to all earlier tokens, while decode with its RotatingKVCache attends to the window only.
  7. BaichuanM1.swift:254-261: with tied embeddings there is no head, and callAsFunction returns the hidden states instead of logits.
  8. Internlm2.swift:41: the dynamic NTK RoPE takes the sequence length from x.dim(1), which is the head count for [B, heads, L, D] input. A long prompt never gets the scaled base.
  9. DeepseekV3.swift:417: kvHeads is [], so the default newCache(parameters:) gives no cache, and the model then indexes out of range. The test checks the cache count and does not run the model with it, because that stops the process.
  10. DeepseekV3.swift:206 and :214: the attention updates the cache with cache.update and again in attentionWithCacheUpdate, so the cache holds every key twice.
  11. DeepseekV3.swift:435-470: sanitize(weights:) stacks the experts but keeps the per-expert tensors, so a per-expert checkpoint fails the strict update.

Force of the assertions

Each fault was made in a local copy of production code, then the tests ran. No fault is committed.

Fault Result
MiniMax.swift sanitize: w1 and w3 swapped (gate and up) the MiniMax loader check fails
AfMoE.swift sanitize: experts stacked in reverse order the AfMoE loader check fails
LFM2.swift: the short convolution cache keeps one token less the LFM2 cache check fails (differences 2.3 to 5.0, tolerance 1e-4)
MiMoV2Flash.swift: sliding cache 1 slot larger no test fails. This fault has no effect: the window mask of the decode step still limits attention to 4 tokens, so the logits do not change.

CI evidence

Fork Tests run 36654186812 on head 81631852: success. Lint and Fork Diff Check: success.

Line coverage from the coverage-report artifact (before: #183 run 36653788601; after: this run):

File Lines Before After
MLXLLM/Models/Apertus.swift 261 0.00% 75.86%
MLXLLM/Models/Internlm2.swift 228 0.00% 78.95%
MLXLLM/Models/Mistral3Text.swift 340 0.00% 86.47%
MLXLLM/Models/MiniMax.swift 232 0.00% 88.79%
MLXLLM/Models/BailingMoe.swift 219 0.00% 93.61%
MLXLLM/Models/GLM4MOE.swift 302 0.00% 93.05%
MLXLLM/Models/GLM4MOELite.swift 515 0.00% 75.34%
MLXLLM/Models/AfMoE.swift 429 0.00% 92.54%
MLXLLM/Models/LFM2.swift 300 0.00% 94.33%
MLXLLM/Models/LFM2MoE.swift 366 19.13% 97.81%
MLXLLM/Models/MiMoV2Flash.swift 385 0.00% 82.86%
MLXLLM/Models/GraniteMoeHybrid.swift 515 0.00% 89.13%
MLXLLM/Models/FalconH1.swift 553 0.00% 82.46%
MLXLLM/Models/Jamba.swift 443 0.00% 81.49%
MLXLLM/Models/BaichuanM1.swift 196 0.00% 96.43%
MLXLLM/Models/DeepseekV3.swift 343 0.00% 82.80%
Total (sources without Tests and .build) 106947 64.55% 69.04%

Not covered: the GLM-4 MoE Lite conversion of kv_b_proj into embed_q and unembed_out (the test loads the converted layout only), and the FP8 and quantized branches of the sanitizers.

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 (ran swift format format --in-place --configuration .swift-format on the changed Swift files; no diff after)
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

🤖 Generated with Claude Code

davidtai and others added 14 commits September 28, 2026 21:22
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Nine DiffusionGemma tests compare float bits with frozen references.
On the hosted macos-26 runner (Apple M1 VM) they differ in the low bits,
with no change in shape, dtype or sign. Add a `.referenceHardware`
Swift Testing trait that runs a test only when MLX_REFERENCE_HARDWARE=1,
and mark the nine tests with it. Elsewhere they report as skipped with
the reason. No assertion, tolerance or reference changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Three gated tests also held checks that pass on any hardware. Split them
so only the bit-for-bit comparison is gated:

- prefixIdentityTokensOwnerAndEmptyStateFailClosed() runs its
  fail-closed probes on all hardware. The donor-logits bit comparison
  moves to failClosedProbesLeaveDonorLogitsBitExact().
- nativeFactoryLoadsExactStateAndReleasesItsModel() keeps the load and
  model-release checks on all hardware. The logits bit comparison moves
  to nativeFactoryDenoiseMatchesReferenceBits().
- The two parameterized vision tests run their bf16 case on all
  hardware. The fp32 case moves to a separate gated test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…a tests

Split the three tests that were still gated whole, so their checks that
pass on any hardware run everywhere:

- chunkedSessionBoundsPrefillAndCanCancelAfterPrefill() keeps the
  prefill bounds, the complete flag, the counters, cancel, the emitted
  checkpoint and the released cache for widths 1, 3 and 7. The KV and
  logits bit comparisons move to chunkedSessionMatchesIndependentNativeReference().
- sharedWeightsConditioningKeepsCommittedCacheState() keeps the fixture
  checks, both cache positions and the unchanged encoder KV after the
  provisional canvas. The reference comparisons stay in
  sharedWeightsConditioningAndCommittedCacheMatchReference().
- committedPrefixRestoreKeepsPositionsAfterDonorRetirement() keeps the
  token count, retained bytes, donor release and both positions. The
  reference comparisons stay in
  committedPrefixRestoreIsExactAfterDonorAppendAndRetirement().

Each pair shares one helper. The fixture reference, case-count and
parameter-count checks of the block and fp32 vision fixtures also run
everywhere now, in blockOracleFixtureIsPinned() and fp32FixtureIsPinned().
CONTRIBUTING.md says which comparisons the gate covers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
slotCapLeavesRoomForServing() sized its request from bytesReserved.
bytesReserved includes the paged pool's physical-floor overhead, which a
request's target KV replaces when it reserves. The overhead depends on
the buffer sizes the MLX allocator returns: a 36,864-byte segment gets a
49,152-byte buffer, or a 65,536-byte buffer reused from the process-wide
cache. When earlier work left 64 KiB buffers in the cache, the capped
arm left more than 5.5 windows of real slack instead of half a window,
and the uncapped arm's reservation fit.

Find the largest request the ledger accepts beside the capped set with
trial reservations, then take half a window off it. The assertions do
not change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add the Swift Testing tags unit, kernel, integration and reference in
Tests/MLXLMTests/TestTypeTags.swift, and the UnitTests parent suite
that gives the unit tag to the suites under Tests/MLXLMTests/Unit.

Fork Tests runs the unit tests before it builds the Metal library.
swift test cannot select tests by tag, so the step selects the
UnitTests suite by name. CONTRIBUTING.md describes the four types.

Add two example unit suites for JSONValue and ToolCall.execute.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Other test targets, such as MLXLMServerTests, can then add unit tests
with their own TestTypeTags.swift and no change to the workflow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Delete every cached *.metallib, not only mlx.metallib, before the
  build and before the cache is saved, so the unit step guard sees the
  same set of files.
- The guard prints the found libraries, then one ::error:: line.
- Add scripts/check-unit-test-files.sh: it fails when a Swift file
  under Tests/<Target>/Unit/ has no extension UnitTests. The unit step
  runs it, and scripts/test-run-nested-suite.sh proves it red on a bad
  file.
- CONTRIBUTING.md: folders for each test target, the sentence on files
  without a type tag, and the section Xcode integration tests.
- fork.yaml: unit tests are under Tests/<Target>/Unit/ for each test
  target; describe the new script.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add the KernelTests suite and a shared helper for kernel tests.
SyntheticModel builds a tiny model from a configuration dictionary,
gives it seeded random weights and evaluates them before use. It also
loads a synthetic checkpoint through loadWeights. ForwardPassChecks
checks the logits shape, dtype and finite values, determinism, cache
consistency, batch invariance and causality.

Add forward-pass tests for Laguna, Qwen3-Next and Qwen3-MoE, behavior
tests for the caches, masks and quantized attention in KVCache.swift,
and tests of the RoPE scaling types against reference rotations.

Two tests show defects and use withKnownIssue: ChunkedKVCache.copy()
after maybeTrimFront() and ArraysCache.copy() with an empty slot.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ModelCase describes one tiny model: how to build it, the checkpoint keys
and shapes it must have, the keys that sanitize(weights:) must drop, and
a conversion to the original checkpoint layout. ModelCaseChecks runs the
standard checks on a table of such models. A check that fails because of
a known production defect runs inside withKnownIssue, with the defect
named.

SyntheticModel.randomize now also handles 0-D parameters and float64
initial values. checkCacheConsistency takes an optional cache for models
whose newCache(parameters:) is not usable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…models

Add forward-pass tests with tiny random models for DeepSeek V4, BitNet
(with a check of the BitLinear Metal kernel against the unpacked matrix
product), Gemma 3n, Qwen 2, Qwen 3 and Qwen 3.5 MoE, and loader tests for
the Nemotron-H 3.5 MTP head.

Tests that show production defects run inside withKnownIssue and name
the defect: DeepSeek V4 pool masks, cache factory, FP8 loading and the
hyper-connection kernel; Gemma 3n query RoPE, KV sharing, sliding mask
and vocabulary cut.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add a table of tiny random models to the kernel tests: Apertus,
InternLM2, Mistral 3 text, MiniMax, Bailing MoE, GLM-4 MoE, AfMoE, LFM2,
LFM2 MoE, MiMo V2 Flash, GLM-4 MoE Lite, Granite MoE hybrid, Falcon H1,
Jamba and Baichuan M1. Each runs the ModelCase checks, and the MoE models
load a checkpoint with one tensor per expert. Add DeepSeek V3 tests.

Tests that show production defects run inside withKnownIssue and name
the defect.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
davidtai and others added 5 commits September 30, 2026 05:55
Every withKnownIssue block took any failure inside it as the known
issue, so a new failure in the block would hide. Each block now passes
a matching predicate on the comment of the expectation that the defect
fails. Another failed expectation, or a thrown error, fails the test.

ModelCase.run matches only the expectations in Check.failingExpectations.
For the loading check, a thrown error of the load is also the known
issue, because a wrong sanitize(weights:) makes the strict update throw.
The loading check runs the shape checks and the wrong-shape rejection
outside the known issue.

The two KVCacheBehaviorTests blocks give each expectation a comment and
match on it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Carries the known-issue matching change of test/kernel-forward-core.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Carries the known-issue matching change of test/kernel-forward-core.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Every withKnownIssue block now passes a matching predicate on the
comment of the expectation that the defect fails, so a new failure in
the block fails the test. The newCache block gives each of its three
expectations a comment. The FP8 loader block also matches the thrown
error of the load, because the strict update throws for the unused keys.

The hcPre text now says which side differs from the reference: the ops
path divides pre by its row sum, while mlx-lm deepseek_v41.py:241 and
the Metal kernel use sigmoid + eps with no normalization.

The Gemma 3n KV-sharing text no longer calls the own keys and values of
a shared layer without a cache a defect. The reference mlx-lm
gemma3n.py:131 does the same.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…ation

Every withKnownIssue block now passes a matching predicate on the
comment of the expectation that the defect fails, so a new failure in
the block fails the test. The DeepSeek V3 loader block also matches the
thrown error of the load, because the strict update throws for the
unused keys. The DeepSeek V3 comment strings used a double backslash at
the line ends, which put a backslash into the text; they now use a line
continuation.

The Jamba loader known issue now also compares the loaded logits with
the reference, as ModelCaseChecks.loading does, so the test asserts
values once the sanitize path is fixed.

The BaichuanM1 tied-head text now says that the reference mlx-lm has no
tied path either.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@Gajesh2007
Gajesh2007 changed the base branch from test/kernel-forward-core to main October 2, 2026 22:57
@Gajesh2007
Gajesh2007 merged commit 2a6e379 into main Oct 2, 2026
4 of 5 checks passed
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.

2 participants