Skip to content

test: add kernel forward-pass tests for MiniCPM, OLMo 2, GLM-4, Gemma, Starcoder 2, Phi, ERNIE 4.5, Cohere and Lille - #236

Merged
Gajesh2007 merged 17 commits into
mainfrom
test/kernel-forward-llm-table-b
Oct 2, 2026
Merged

Gajesh2007 merged 17 commits into
mainfrom
test/kernel-forward-llm-table-b

Conversation

@davidtai

@davidtai davidtai commented Oct 1, 2026

Copy link
Copy Markdown

Proposed changes

This PR adds kernel forward-pass tests with tiny random models for dense text models that had low line coverage, and for the DeepSeek-V4 MTP head. It uses the ModelCase table of #183.

Merge order: this PR merges after #183. It is based on test/kernel-forward-core (#183).

What it adds

File What Checks
Kernel/LLM/DenseTextModelForwardPassTests.swift Table of 17 ModelCase cases: MiniCPM (untied with linear RoPE, scale_emb, scale_depth, dim_model_base; tied), OLMo 2 (tied; untied with biases, head_dim 16 and llama3 RoPE), GLM-4 (untied with biases; tied), Gemma, Starcoder 2 (tied; untied), Phi, ERNIE 4.5 (tied with head_dim 16; untied with biases), Cohere, Lille 130m, MiMo v1 (tied; untied with traditional linear RoPE), and the gemma4 LLM wrapper (nested text_config) shape and finite values, determinism, cache consistency (batch 1 and 2), batch invariance, causality, parameter keys and shapes, load through loadWeights with the keys that sanitize(weights:) drops (lm_head of tied models, rotary_emb.inv_freq, model.mtp_layers, Gemma 4 vision/audio keys and the model.language_model prefix), wrong shape rejected
same file 6 more tests Cohere logit scale (logits in the ratio of the scales), Cohere rope_traditional, GemmaRMSNorm against x / rms(x) * (1 + w), tied Starcoder 2 has no head, the Gemma 4 wrapper gives the same logits, caches, KV heads and LoRA layers as its text model, and decodes a flat configuration
Kernel/LLM/DeepseekV4MTPForwardPassTests.swift DeepSeek-V4 MTP head (1 local-attention layer and 1 MTP layer, configuration of #184) head attached only when _deepseekV4MTPEnabled is true, MTP parameter keys and shapes, callWithHidden logits equal to the forward pass (with and without the caches of makeCache), draft logits shape and finite values, chunked draft with the MTP cache against one pass, causality of the next tokens, load of a per-expert checkpoint for the backbone and the MTP layer, a checkpoint without mtp. keys detaches the head, wrong MTP shape rejected

MiMo here is the v1 model (MiMo.swift), not MiMo V2 Flash, which #185 tests.

The MTP suite is serialized, because DeepseekV4Model.init reads the global _deepseekV4MTPEnabled. Each build sets the flag and resets it to false. The DeepSeek-V4 tests of #184 use num_nextn_predict_layers 0, so the flag does not change their models.

Tolerances, and why: 1e-4 for cached against full passes, batch invariance and causality (float32, only the order of the sums differs). 1e-6 for the Cohere logit scale (a scale by a power of 2 is exact). 1e-5 for GemmaRMSNorm (float32 norm). The loads and the Gemma 4 wrapper against its text model are exact (the same operations run).

Production defects found (tests kept, marked with withKnownIssue)

  1. GLM-4 with tie_word_embeddings true: sanitize(weights:) drops lm_head.weight (Libraries/MLXLLM/Models/GLM4.swift:188-190), but GLM4Model always has its own lm_head (GLM4.swift:177) and does not use the embeddings as the head. The strict load then fails on the missing key.
  2. Cohere: CohereConfiguration.init(from:) never decodes rope_traditional (Libraries/MLXLLM/Models/Cohere.swift:198-226), so the model always uses the default true. The reference mlx-lm cohere.py passes args.rope_traditional to nn.RoPE.

Files skipped

None.

CI evidence

Fork Tests is running on head a168bdc3. This section gets the result.

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)

🤖 Generated with Claude Code

davidtai and others added 15 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>
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>
…pSeek-V4 MTP head

Add a table of tiny random models for MiniCPM, OLMo 2, GLM-4, Gemma,
Starcoder 2, Phi, ERNIE 4.5, Cohere, Lille 130m, MiMo and the Gemma 4
wrapper. Each case runs the standard checks: shape and finite values,
determinism, cache consistency, batch invariance, causality and the
checkpoint load. The cases cover tied and untied heads, RoPE scaling,
biases, the logit scale and the keys that sanitize(weights:) drops.

Add tests of the DeepSeek-V4 MTP head: the head parameters, the hidden
state of callWithHidden, the draft logits with and without the MTP
cache, causality, and the load of a per-expert checkpoint with and
without MTP weights.

Two production defects run as known issues: a tied GLM-4 checkpoint does
not load, and Cohere ignores rope_traditional.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
loadWeights converts float16 parameters to bfloat16, so the float16
layer_scalar of the Gemma 4 reference now gets values that both types
hold exactly.

The MTP detach test now loads into a new model that nothing has read.
sanitize(weights:) detaches the head with an assignment, and the module
tree of MLXNN keeps its cache of child modules after the first read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The known issue said that Cohere must read rope_traditional. That is
false: the reference mlx-lm cohere.py:67 hard-codes traditional=True and
has no rope_traditional field, and the Swift model matches. The test now
expects the same logits for both values of the key, without a known issue.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Gajesh2007
Gajesh2007 changed the base branch from test/kernel-forward-core to main October 2, 2026 22:58

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

Reviewed head 77257a3: dense model and DeepSeek MTP test blobs unchanged from the original reviewed head. Known issues retained. Normal signed main integration preserves all existing test topics, guards and documentation. Libraries and Package.swift match the authorized baseline hashes exactly. New CI pending; merging without waiting explicitly authorized.

@Gajesh2007
Gajesh2007 merged commit 21c6a46 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