Repository navigation
Merge upstream ml-explore/mlx-swift-lm main d02948b9 (2026-10-22) - #339
Merged
Merged
Conversation
Port of mlx-lm's mamba2.py — the first pure state-space-model in MLXLLM (prior SSM code was hybrid: NemotronH, FalconH1, Jamba). Reuses the in-tree SSM machinery: ssmUpdate selective scan, MambaCache (conv + ssm state), createSSMMask, and Conv1d depthwise conv. Block mirrors NemotronH's Mamba2 mixer; the gated norm is the simpler ungrouped variant (silu(gate)*x then a single-group RMS norm). Provides a custom newCache returning one MambaCache per layer (no attention KV). sanitize swaps the HF depthwise conv1d weight axes ([C,1,K] -> [C,K,1]). Optional tied embeddings. Registered as "mamba2". Tests (Mamba2Tests, no model download): forward-pass logits shape over a multi-token prompt, per-layer MambaCache creation, and conv1d weight axis swap (and no-op when already correct). Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Port of mlx-lm's mixtral.py: Mistral-style attention (GQA, RoPE, no bias) with a sparse MoE block — gate (no bias) → top-k → softmax over the selected expert logits → SwitchGLU. Mirrors the in-tree PhiMoE structure; differs in using RMSNorm (not LayerNorm), plain RoPE (not SuScaled), bias-free projections, and optional tied embeddings. sanitize() stacks per-expert w1/w2/w3 (weight/scales/biases) into switch_mlp.gate_proj/down_proj/up_proj, so both full-precision and pre-quantized Mixtral checkpoints load. Registered as "mixtral". Tests (MixtralTests): forward-pass logits shape on a synthetic 1-layer config, and sanitize() expert-stacking shape/key remap. Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The gemma4_unified 12B safetensors include a top-level vision_embedder
submodule alongside the existing embed_vision / vision_tower keys. Without
this entry in the skip list, Gemma4Model.sanitize leaves those weights in
the dictionary and loadWeights aborts with:
Unhandled keys ["vision_embedder"] in Gemma4Model
Add vision_embedder to the prefix filter so language-only loading of the
12B unified model succeeds.
Co-authored-by: Sura Watthanalamlert <sura.watthanalamlert@dkbcodefactory.com>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
Identical fix but with a comment -- see also #366
Support correlated tool call transcripts Add tool-call IDs so assistant tool calls and tool results can be correlated in transcripts. - Add optional `ToolCall.id`; parsers (JSON/Llama3/Mistral) extract supplied ids, including OpenAI-style top-level and nested forms - Add `Chat.Message.Tool` metadata and `MessageGenerator.addToolMetadata`, emitting OpenAI-style `tool_calls` / `tool_call_id`; wire through all six VLM generators and `DefaultMessageGenerator` - ToolCallProcessor dedups and regenerates ids per turn, with format-aware generation (9-char for Mistral, `call_`-prefixed default) - ChatSession pairs each tool result with its originating call id
**Port Qwen25VL MROPE fix (#239) to Qwen2VL** Qwen2-VL was applying plain 1-D RoPE instead of 3-D multimodal positional encoding. Image tokens got sequential positions; generated tokens landed at inflated positions, causing spatial drift that grew with generation length. Text was correct but bounding boxes were wrong/short (visible in layout tasks like MinerU2.5). PR #239 fixed this for Qwen2.5-VL. This is a direct port to `Qwen2VL.swift` — the spatial-position scheme is identical between models. Ported sites are marked `// #239: Qwen25VL <symbol>`. Three coupled changes (matching #239): - **MROPE section layout** via slice-replacement (`mropeCosSin` / `mropeSectionRaw`) - **`rope_deltas` reconstruction** for decode - **`_invFreq` underscore prefix** so the weight loader skips it Verified against the Python mlx-vlm reference: layout boxes now match coordinates exactly.
Add optional seed to GenerateParameters for reproducible sampling TopPSampler and CategoricalSampler each create a private RandomState seeded from DispatchTime.now(), making temperature > 0 sampling non-reproducible and ignoring MLXRandom.seed. Adds seed: UInt64? to GenerateParameters, threaded through sampler() into each sampler's RandomState(seed:). Fully backward-compatible: nil preserves the existing entropy-seeded behavior; argmax is unaffected. A fixed seed makes (seed, prompt, parameters) deterministic, and per-request seeds in GenerateParameters make this concurrency-safe with no shared global RNG. Tests cover: same-seed determinism for both samplers, distinct-seed divergence, seed threading through GenerateParameters, and nil-seed preservation.
Aligns the body of #if/#else/#endif blocks with the directive instead of indenting it one level deeper. Co-authored-by: Cori Park <coripark@apple.com>
…in validation) + swift-format 603 conformance (#404) * CI: pass -skipPackagePluginValidation to xcodebuild mlx-swift 0.31.5 attached the CudaBuild build-tool plugin to the Cmlx target. Xcode requires a one-time interactive trust approval per package plugin; non-interactive xcodebuild has no way to grant it, so every mac_build_and_test run since 0.31.5 was published fails during package preparation with: Validate plug-in "CudaBuild" in package "mlx-swift" ** TEST BUILD FAILED ** -skipPackagePluginValidation is the standard flag for building a plugin-bearing SwiftPM graph on CI. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Fix swift-format 603.0.0 import ordering in MTPSpeculativeTokenIteratorTests The lint job builds the latest swift-format release; 603.0.0 orders attributed imports after plain imports, so this file (formatted clean under the previous release) now fails pre-commit on every PR merge ref. This is the exact diff swift-format emits. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
The lint job resolved swift-format from `releases/latest`, so a new upstream release could silently change formatting rules. When 603.0.0 shipped, its OrderedImports rule started grouping attributed imports (@_spi/@testable) into a trailing block — reformatting MTPSpeculativeTokenIteratorTests.swift, a file no in-flight PR had touched. Because the lint step runs `pre-commit run --all` over the whole repo, this turned lint red on every open PR simultaneously, with a diff unrelated to any of them. Pin the version (603.0.0, what `latest` resolved to at pin time) so lint is reproducible and only changes when someone deliberately bumps it, and reformat the one drifted file to satisfy it. Note: the pre-commit hook is `language: system`, so contributors' local swift-format still isn't version-locked to CI; matching a pinned tool version locally is the reliable way to reproduce lint.
…#346) Gemma3TextModel.prepare previously returned the whole prompt to the TokenIterator, which then ran the 262k-vocabulary lm_head over every prompt position just to produce the first token. Instead, prefill all but the last token through the inner model (which has no lm_head), updating only the KV cache, and hand just the final token to the iterator. The chunk size honours an explicit GenerateParameters.prefillStepSize and otherwise defaults to 128, tuned for this path on Apple Silicon for the best asyncEval CPU/GPU pipelining. To make that default reachable, prefillStepSize becomes optional (nil = let the model choose); other models keep their 512 default via `windowSize ?? 512`. Measured on translategemma-4b-it-4bit (Apple Silicon, 577-token prompt, greedy): prompt prefill 177 -> 463 tok/s (2.6x), 3253 -> 1246 ms. Greedy output is byte-identical to before, including prompts longer than the 1024 sliding window where the rotating KV cache rotates. Co-authored-by: David Koski <46639364+davidkoski@users.noreply.github.com>
…#390) fix: build Gemma 4 KV-shared layers with kvSharedOnly Tail layers (layer_idx >= num_hidden_layers - num_kv_shared_layers) reuse an earlier layer's K/V and own no k_proj/v_proj/k_norm. The attention, sanitizer, and drafter already handled this, but Gemma4TextBackbone.init built every layer with kvSharedOnly: false — causing strict-loader failures on real checkpoints (e.g. gemma-4-e4b-it-4bit: 42 layers, 18 shared → keyNotFound(…layers.24.self_attn.v_proj.weight…)). Wire init to the same predicate the rest of the stack already uses. Runtime behavior is unchanged; only the dead, unfillable parameters are removed. Gemma4Unified and configs with num_kv_shared_layers: 0 are unaffected. Adds Gemma4KVSharedLoadTests: structural check that KV-shared layers own no local K/V projections, and a load round-trip reproducing the exact keyNotFound failure (sanitized checkpoint → model.update(verify: [.all])).
…413) The generation task from generateTask() is unstructured, so cancelling streamMap's task (stream onTermination) never propagated to it. A caller that stops consuming mid-stream (barge-in) and immediately issues the next request deadlocks: 'await genTask.value' waits for the full generation while holding the session's serial cache lock. Cancel the generation task explicitly on consumer termination and on task cancellation; the generate loop already checks Task.isCancelled per token, so it stops promptly.
…418) Qwen3Model.callAsFunction accepts an attentionMask parameter and discarded it: the backbone ran with a plain causal mask, so padding tokens participated as attention keys for any position after them. With left padding (the Hugging Face default for Qwen3-Embedding) every real token attends to the pads that precede it, corrupting the hidden states that last-token pooling reads. Fold the [B, L] key-padding mask into the causal mask (causal AND key-not-padding, broadcast to [B, 1, L, L]) whenever a caller provides one. Right-padded causal batches are unaffected by construction — pads there sit after the real tokens, which causality already hides.
CoreImage filters run in a linear-light working space and asMLXArray renders with a nil colorSpace, so the image path fed the model linearized values instead of the gamma-encoded sRGB bytes the HF reference preprocesses. Bright content survives that error; dark content does not — near-black text (luminance 23/255 on a 6/255 background) reached the ViT with ~12x less contrast than reference and was unreadable. The sibling Qwen25VL/Qwen2VL image paths and this file's own video path already apply the tone-curve step; the port dropped it in the image path. Measured on the incident screenshot: faint-band signal vs background was 0.011 without the step, 0.126 with it (reference: 0.133). Adds a regression test pinning the model-side extrema of a faint dark-theme fixture to the gamma-encoded reference values. Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* Convert Gemma tool parameters by schema type (#10) GemmaFunctionParser.parse(content:tools:) was missing calls to convertParameterValue(_:paramName:funcName:tools:), which means that all tool call arguments were being passed as strings instead of being coerced into the types the functions expected. This pull request adds the missing calls to convertParameterValue(_:paramName:funcName:tools:) and a unit test to verify the fix.
…ath (#419) Qwen2.5-VL seeds its MROPE positionIds/ropeDeltas into the per-call LMOutput.State during prefill, but prepare()'s .logits branch never carried result.state into self.state, so the first decode step ran without them — position drift after an image-token block, degenerate empty output on dense frames. The .tokens branch already gets the carry via step(previous:) and the speculative iterator sets mainState = result.state; this makes the standard path consistent.
#403) MLXVLM Qwen35.sanitize applied the RMSNorm `+1` weight offset unconditionally, while MLXLLM Qwen35 gates it behind `hasMTPWeights || hasUnsanitizedConv1d`. On a pre-converted MLX checkpoint (conv1d already sanitized, no MTP tensors) the weights are already shifted, so the VLM path double-shifted every layernorm and produced garbage tokens — while the same weights via the MLXLLM path decoded correctly. Mirror the LLM gate so the two paths agree. Adds sanitize unit tests covering both the pre-converted (no shift) and raw-checkpoint (shift) cases.
* fix(load): honor safetensors index
…es multi-turn M-RoPE drift) (#399) feat(vlm): windowed prefill for Qwen3.5/3.6, with warm cross-turn continuation Adds chunked ("windowed") prefill for Qwen3.5, bounding attention scratch to `[heads, window, L]` instead of `[heads, L, L]`, which was OOMing on long image prompts. Batched inputs still use the single-shot path. `LanguageModel.prepare` now threads an optional `LMOutput.State` (M-RoPE position state) through, so Qwen3.5 can continue an already-warmed KV cache across turns instead of resetting rope positions to zero. `ChatSession`/`TokenIterator` persist this state across turns and tool-call restarts. Other model conformers accept and ignore the parameter. This also fixes a live cross-turn bug: since M-RoPE state wasn't previously carried between turns, warm continuations silently recomputed positions from scratch, causing measurable logit drift (0.43 max-abs vs. a 8.3e-07 noise floor) on repeated turns with images. Other changes: - `getRopeIndex` supports an offset-aware `positionOffset` for computing new-image rope positions from a warm cache's anchor. - Vision-embedding preamble factored into `visionInputEmbeddings`, shared across prepare paths. - Windowed loop uses `asyncEval` per chunk + trailing eval (matches Gemma3's chunked-prefill pattern). - `Qwen3VLProcessorConfiguration` now decodes new-style `size.{longest_edge,shortest_edge}` pixel budgets, fixing silent fallback for newer Qwen3-VL configs. - Added `Qwen35ContinuationTests` (5 tiny-model equivalence tests) and `Qwen3VLProcessorConfigTests`.
DeepseekV3Model and its members (callAsFunction, sanitize, kvHeads, model, loraLayers) are already public, but the initializer is internal, so it can't be constructed from another module. Make it public, matching GLM4MoEModel, so downstream code can wrap the DeepSeek V3 architecture without copying it.
* Make MLXLLM compilable on Linux * Fix UserInput.VideoFrame not being compatible with previous versions * Make AudioFormat and AudioProcessing independent from the platform
…results (#409) ChatSession appended only the role:tool result messages before restarting generation. Chat templates that render tool results by forward-scanning from an assistant message carrying tool_calls (e.g. Gemma 4) therefore dropped the results from the rendered prompt, and the restarted generation answered as if the tool had returned nothing. Append the assistant turn that made the calls first, matching the transcript shape asserted by ToolCallIdTests. Adds a ChatSession-level regression test driving a real round trip with a scripted tokenizer.
On iOS, GPU work submitted while an app is in the background is rejected by the system, and the resulting Metal command-buffer error is thrown as a C++ exception from a completion handler where nothing can catch it, aborting the process. Token generation already checks Task.isCancelled between tokens, but the prompt prefill loop did not - so a multi-second prefill of a long prompt could not be stopped before the app finished transitioning to the background. Check Task cancellation between prefill windows so callers can cancel generation (e.g. on UIApplication.willResignActiveNotification) before further GPU work is enqueued. Ref: ml-explore/mlx-swift-examples#230
* Check cancellation before iterator.next() to prevent post-cancel GPU submission
TokenIterator.next() calls asyncEval() to pipeline the next GPU evaluation. The
3.x loop `tokenLoop: while let token = iterator.next()` checked Task.isCancelled
only AFTER next() had already submitted work, allowing one extra asyncEval after
cancellation was observed.
Reorder to `while !Task.isCancelled { guard let token = iterator.next() else { break } }`
so the check happens before next(). The existing post-loop block already assigns
stopReason = .cancelled on a cancelled exit, and Stream().synchronize() still settles
any in-flight evaluation at the end of the task body, so the settlement boundary is
unchanged.
…#334) Add MLXFoundationModels: an MLX-backed FoundationModels LanguageModel MLXLanguageModel conforms to FoundationModels.LanguageModel, allowing a local MLX model to work with LanguageModelSession. It is built from a ModelConfiguration and loaded through mlx-swift-lm's existing model factory, so any architecture the package already runs is reachable through FoundationModels. A model's capabilities — .guidedGeneration, .toolCalling, .reasoning, .vision — are declared at construction. A new standalone library, MLXGuidedGeneration, constrains any MLX model's output to a JSON Schema, EBNF grammar, or structural tag by masking token logits at each decoding step. It uses a vendored, namespace-isolated copy of XGrammar (the MLXCXGrammar C++ target), with no FoundationModels dependency. It runs on macOS 14 / iOS 17 and later. The FoundationModels adapter is gated by one default-on SwiftPM trait, FoundationModelsIntegration, and is available on iOS/macOS/visionOS 27.0 (canImport(FoundationModels, _version: 2)). With the trait turned off, or when building against an older SDK, MLXFoundationModels compiles to an empty module and the vendored XGrammar C++ is not built. The package's minimum OS versions are unchanged from upstream. A #huggingFaceLanguageModel macro fills in the HuggingFace download and tokenizer setup. The MLXLanguageModel initializer can be used directly to provide a path to locally stored weights, or a different downloader or tokenizer. Co-authored-by: Cori Tymoszek Park 31750745+ctymoszek@users.noreply.github.com Co-authored-by: Christopher Webb 207731778+thechriswebb@users.noreply.github.com
Fixing minor copy paste typos.
Some sentence-transformers pooling configs (e.g. all-MiniLM-L6-v2) omit pooling_mode keys such as `pooling_mode_lasttoken`. The synthesized Codable decoder required all four flags, so decoding threw and `loadPooling` silently fell back to the model's built-in strategy instead of honoring the config. Add a custom `init(from:)` that decodes each pooling_mode flag with `decodeIfPresent(...) ?? false` (an absent key means that mode is off), keeping `word_embedding_dimension` required. Mirrors the optional-decode pattern already used by Qwen3Configuration / Gemma3Configuration. Fixes #26
…398) feat(qwen3vl): cap per-image/frame vision-token budget at 1,280 (min(config.maxPixels, 1280*factor²), overflow-safe), matching Qwen2.5-VL clamp to avoid unbounded O(patches²) attention blowup on full-res images. See ADR-0014.
The test cache without object files was 1.60 GB against 1.86 GB for the build cache, because the test bundle is 1.1 GB. It restored no faster and its save added 41 s before the test jobs could start. The test jobs restore the build cache again. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
… 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>
…9911269310 Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
MTPSpeculativeTokenIterator (upstream 4cc5504) set mainState to nil after switchToPassthrough. That dropped the model's own state with the drafter keys, so a Qwen VLM decoded the rest of the stream without its M-RoPE delta after a media prompt (silently wrong positions; the Qwen 3.5 VLM refuses a warm cache without it). switchToPassthrough already clears every drafter key; the model state now stays. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
- Each run keeps its groups, units and tests as separate parts, so the skip of one group does not change another part. - The strict groups and the units of a shard run in one swift test process. test_shards.py checks each strict group from the XCTest log and the Swift Testing event stream: the group fails when it executed zero tests or skipped a test. This is the check of run-nested-suite.sh, which stays for developers. - A group with its own environment, fixture or Metal library setting still runs in its own process. - The rest run takes each test that no other run selects. - The build restores Package.resolved from the cached build. - test_shards.py plan made 16 shards from the durations of run 39913075467. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Sixteen shards restore the 1.86 GB build cache sixteen times, and run 39915424644 hit the cache egress limit of the account. Ten shards leave runners for the other repositories and use less cache egress. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
3 of 5 tasks
davidtai
marked this pull request as ready for review
October 23, 2026 08:45
davidtai
marked this pull request as draft
October 23, 2026 12:36
Author
|
Back to draft (2026-10-23, David's rulings): (1) the VNKV 32K smoke decode-time failures on hosted runners get investigated before any decision on the timing check; (2) the pre-existing NemotronSuperBatchedDecodeTests float32 SSM-state flake (2/19 on fork main) gets root-caused and fixed in this PR. Everything else is green at c4465b4. |
ci: build once and run the tests in parallel shards
mlx 83dbdb04 (upstream mlx through afc03c511: wider affine qmv_wide row tiles, large-offset gather/scatter fixes); mlx-c cb19abf6. No Swift API change. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…ter shard 4's main run testCancellationAndShutdownDrainCapturedWindowOwner waits 5 s for the engine's first checkpoint evaluate. In the sharded CI it was the first engine work in shard 4's process (only BaseConfigurationTests ran before it), so its first step paid the Metal pipeline compile on a fresh hosted VM with a cold shader cache: 0.42, 2.36, 0.42, 3.97 s, then a timeout (run 39966880999), against 0.13-0.19 s on main and 0.195 s in the serial job, where earlier GPU tests had compiled the pipelines. A group with "own_process": true now runs in its own process after the main run, and plan keeps it there. The new strict group contiguous-historical-checkpoint uses it. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
davidtai
marked this pull request as ready for review
October 23, 2026 15:43
The Nemotron Super tests failed intermittently with 1-ulp float32 differences (MambaStep, SSM state) and bf16 token flips (MTP). A test that runs a model inside Device.withDefaultDevice(.cpu) recorded a CPU trace of the shared compiled MLXNN silu; a later GPU call on the same thread replayed it. Layr-Labs/mlx-swift#62 keys each compiled trace by the task default stream. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…measures testVarianceNormalizedKVCache32KIngestAndDecodePeakMetalMemorySmoke failed about half the time on GitHub-hosted macos-26 runners. The timed decode was the first decode of the process. It included the one-time Metal pipeline compile: 0.45 s on a cold shader cache, 0.05 s warm, 5-10 ms steady. One untimed decode step now runs first. The 0.25 s bound stays the same. The memory baseline was sometimes sampled while one 128 MiB float32 temporary of MLXRandom.normal was still live. The peak workspace was 451.8 MB or 586.0 MB for the same 720.3 MB absolute peak. Stream.gpu.synchronize() now runs before the baseline is sampled. The 768 MiB bound stays the same. fork.yaml names the change in a new section. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…s timed CI attempt 2 on #348 failed at 0.322 s with one warm-up step. After the 32K ingest the raw tail is empty. The first decode only starts the tail. The second decode is the first to concatenate onto the tail and to run the two-token tail path, so it still compiled pipelines when it was the timed step. The test now runs two untimed steps. It prints their times. The 0.25 s bound stays the same. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
test: warm up the decode and settle memory before the VNKV 32K smoke measures
Fix the intermittent Nemotron Super bitwise mismatches: pin mlx-swift with compiled traces keyed by the task stream
javiech1
pushed a commit
to javiech1/mlx-swift-lm
that referenced
this pull request
Oct 24, 2026
…abs#340) swift.org's signed prebuilt swift-syntax artifacts are keyed per swift-syntax tag and exact toolchain, and 600.x/601.x artifacts are no longer published for current toolchains. A package graph that resolves below 602 silently falls back to compiling swift-syntax from source (~200 build tasks). Raising the floor keeps consumers on the prebuilt path. See Layr-Labs#339 for measurements.
jonathan308
added a commit
that referenced
this pull request
Oct 24, 2026
Brings in #339 (upstream sync 2026-10-22, mlx-swift 6c31f9f1 / mlx 83dbdb04), #349 (Nemotron Super bitwise flake: compiled traces keyed by the task's default stream) and #348 (VNKV smoke warmup). Conflict: Libraries/MLXLLM/Models/NemotronH.swift, observedAttentionKVDTypes(). Kept #354's public visibility (the Super adapter's complete-checkpoint KV types call it from MLXVLM) with main's body, which probes through try? newCache(parameters: nil) now that newCache throws (#339). Every other file merged cleanly.
jonathan308
added a commit
that referenced
this pull request
Oct 26, 2026
Merges origin/main aee6ebb into darkbloom/tp-engine 8411247. Main is 377 commits past the merge base 889fe3c: the upstream sync to ml-explore d02948b (#339), the mlx-swift pin eedca444 (#358), the provider 0.10.2 set (#356, #357, #359, #360), GLM long-context decode (#362), balanced checkpoints for GLM-5.3-Flash and Nemotron Super (#363), GLM video at the track's average rate (#340) and the Flint decode work (#336-#338). Package.swift keeps the cluster's mlx-swift pin 9fe34405; everything else is main's (swift-tools 6.2, the swift-syntax 602 floor, the new targets). Conflicts: - GLM5NextMoEDecodeKernel.swift: the cluster's file (the dense-MLP two-launch path, the non-private header) in main's swift-format layout, with main's two changes: GLM5NextNVFP4Linear.weightScale2 (renamed because MLXNN QuantizedLinear now declares globalScale) and the copied MLX sigmoid with metal::precise::exp (main 1ba5e73). - PagedSegmentAttention.swift: main's first-bucket scratch allocation and seqinfo cache, plus the cluster's multi-query verification kernel and the non-private merge kernel it uses. - GatedDelta.swift: main moved it to MLXLMCommon and added useKernel. The cluster's fuseQwen35Gates stays; its compiled gates move beside gatedDeltaUpdate (qwen35GatedDeltaGates, package) because MLXLMCommon cannot reach MLXLLM's Qwen35DecodeFusions, which now forwards to it. The traced ops are the cluster's (sigmoid(b) to float32, then exp(-exp(float32(A_log)) * softplus(a + dt_bias))), so the decode gates keep their bits. Qwen35DecodeFusionsTests compares against the separate ops, since main made computeGatedDeltaG itself a compiled closure. - GLM5NextProcessor.swift: main's image.source switch with the cluster's GLM5NextRGBDecoder; main's variable-frame-rate decoding auto-merged. - Package.swift: see above. Merged without textual conflict but adjusted: - PagedLayerCache.writePromptKVWithoutAttention (main, Flint) advances the offsets through advancePositionOffsets, so the cluster's hostPositionOffsets stay in step with the device offsets. - PagedAttentionKVTests: main's newCache throws. Numerics: main changed every copied MLX sigmoid to metal::precise::exp (1ba5e73, 3794edf) to follow MLX #4461: the GLM hyper-connection coefficients, the GLM MoE decode and prefill clamped GLU, Nemotron Super and MiMo. They follow the merged MLX core. The cluster core pinned here still has metal::exp, so GLM on the pair changes bits when it runs with these kernels; see the merge record. Tests: swift build --build-tests against main's mlx-swift eedca444 with two compile-only stand-ins for the cluster mlx-swift API (MLXArray.sharingArray, metalKernel fencedInputs): complete. The CPU unit group (^MLXLMTests.UnitTests/, no Metal library): 437 tests, one failure, the pre-existing GLM5NextProcessorMediaTests Metal dependency. The tree does not build at its own pin 9fe34405 (main needs mlx-swift API such as MLXArray.maskFill); it builds once the pin moves to the merged mlx-swift. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
DRAFT. Waits for fork CI on the final head (cbc07e6 and later). It also waits on Layr-Labs/mlx-swift PR 59, which this PR pins.
Proposed changes
This PR merges upstream
ml-explore/mlx-swift-lmmainat d02948b (2026-10-22) into the fork with a merge commit.mainmain)Upstream additions: Qwen 3.8 (text, VLM, MTP), Qwen3-VL-MoE, Gemma 4 12B unified and E-series MTP, Muse Glimmer, EmbeddingGemma 2, Mixtral, Mamba2, Helium, Nanbeige, Hunyuan dense, DeepSeek-V2, Mellum 2.1, Nemotron Labs Diffusion,
MLXRerankers,MLXFoundationModels,MLXGuidedGeneration(vendored xgrammar),MLXScriptedLM, ParoQuant, TurboQuant and variance-normalized KV caches, typed KV cache configuration,PrefillParameters, prompt-cache persistence, tool-call parser hardening, Harmony and ATEM parsers, generation observability, LoRA dropout, and many fixes.The fork keeps its behavior where both sides changed the same code: ContinuousBatchingV2, paged KV, prefix checkpoints, MTP drafters, Bonsai 2, GPT-OSS, Qwen 3.5/3.6/3.8 DeltaNet numerics, the OpenAI-compatible server and the benchmarks.
Pins
Package.swiftpinsLayr-Labs/mlx-swiftat a615e8f57298e2c4aec5e3c873fe8adcf65a3e6c (Layr-Labs/mlx-swift PR 59). It pins Layr-Labs/mlx 83dbdb04 and Layr-Labs/mlx-c cb19abf6.mainthe pin was 67dc752856ca. The task brief named d7c1d3dc, which was not the pin onmain.MLXArray.maskFill(for:). So the merge and the re-pin are one PR.swift-syntaxfloor is 602.0.0, as upstream.Merge order
Use merge commits. A squash removes the PR-head shas that the next repository pins. If a dependency is squashed, re-pin this PR before it merges.
d-inference and darkbloom-platform pin this fork by revision. This PR does not change them.
GatedDelta move
Upstream moved
Libraries/MLXLLM/Models/GatedDelta.swifttoLibraries/MLXLMCommon/GatedDelta.swift, so MLXLLM and MLXVLM share one implementation. The fork follows. Git carried the fork's DeltaNet edits (bit-exact four-row prompt kernels, Qwen 3.8, precision fixes) to the new path. Upstream's fp32 state,Dk % 32fallback and differentiable recurrence are merged in; kernels run only whenuseKernelis true.Qwen4ExpFusions.swiftandQwen4ExpGDNBlocked.swiftmove to MLXLMCommon withpackageaccess, becauseGatedDelta.swiftcalls them.Conflict resolutions
Package.swiftcxxLanguageStandard..github/workflows/pull_request.ymlml-explore/mlx-swift-lmand skip here.README.md,CONTRIBUTING.md,Documentation.md,MLXVLM/README.mdMLXLMCommon/Evaluate.swift(32)state:,components:,wiredMemoryTicket:, tools:, genericgenerateTask) and upstreamTokenLoopHandler; fork validation inprepare; forkrepetitionPenaltyskip and public iterator counters kept.MLXLMCommon/KVCache.swift(22)MLXLMCommon/GatedDelta.swift(5)MLXLMCommon/Load.swift(3)MLXLMCommon/ModelContainer.swift,ModelFactory.swiftMLXLMCommon/Chat.swift,ChatSession.swift,BaseConfiguration.swifttemplateFieldsplus upstreamaudios/tool; upstream session cache policy;quantization_configandtext_config).MLXLMCommon/SwitchLayers.swift(13)openclasses, transform hooks and direct-reduction predicate. UpstreamFusedGateUpSwitchGLUdropped (forkSwitchGLU(fuseGateUp:)does the same).MLXLMCommon/RoPEApplication.swiftCompilableKVCacheandCompilableRotatingKVCachereturn their offset as a graph array.MLXLMCommon/Tool/*(10 files)ToolCallProcessorkeeps two state machines (see below). Upstream parsers and hardening; fork Gemma superset, Qwen 3.5 framing, Flint, GLM5, Nemotron, Harmony.MLXLMCommon/Tokenizer.swift,UserInput.swift.source, audio, processing options); fork memory-backed video and pixel clip kept.MLXLLM/Models/Gemma4Text.swift(30),Gemma4.swiftScaledLineartoLinear, SPI encoder surface, tied head sanitize,loraLayers,toolCallFormat, newprepare). Upstream MoE block, fused RMSNorm/GELU and softcap not taken (fork has its own).MLXLLM/Models/Qwen35.swift(19),Qwen35MTP.swift,Qwen3Next.swiftlayer_types), MTP predictor types,nextTokenLogits, throwingnewCache, chat conventions.MLXLLM/Models/{NemotronH,GPTOSS,DeepseekV3,FalconH1,GLM4,LFM2MoE,Olmo3,SSM,Gemma3nText}.swift,LLMModelFactory.swiftMLXVLM/Models/Gemma4.swift(10)Gemma4Unified, its processor and the message generator.MLXVLM/Models/{Qwen3VL,Qwen35,Qwen35MoE,Qwen2VL}.swiftMLXVLM/MediaProcessing.swift,VLMModelFactory.swift, other VLM modelsToolCallProcessordefault (ruled by David, 2026-10-23)The default is unchanged from fork
main: the fork's frame state machine. A failed, incomplete or undeclared tool-call frame comes back as visible text.ToolCallPolicy.returnsFailedCallsAsTextis the one switch. Defaulttrue(fork).falseselects upstream's recovery state machine, which reports a failed call as aRejectedToolCallevent.BatchedToolStreamHandler(mlx-server),MLXModelContainerEngine, and upstream'sTokenStreamDecoder(generate and ChatSession).MLXFoundationModelsAllowedToolOutputRouterpassesfalse: its rejection events come only from the recovery machine.falseexplicitly (ToolTests, ToolCallPolicyTests, TextToolCallRecoveryTests, ToolCallIdTests, ChatSessionTests rejection helper and the others listed in commit 4f8bcb7).ToolCallProcessoroutside their vendored copy; their behavior does not change on re-pin.Numerics changes
Rule (David, 2026-10-23): where fork numerics and upstream numerics differ, the fork's numerics win and upstream tests are adapted. The changes below follow from the merged MLX core.
rmsNorm(eps: 1e-6 / D)(transformersl2norm)rmsNorm(eps: 1e-6), as mlx-lm Pythonqwen3_5.py:181andqwen3_next.py:284; one eps across the fork's Qwen family. MLXVLM Qwen 3.5 and Qwen3-Next had taken c408452 in the clean part of the merge and are put back (e235fd3)GatedDeltaQKNormTests(3 cases) expects the fork's epsGemma4Text.swift)Gemma4TextTestssoftcap test now expects float32GLM5NextMoEDecodeKernel.swift,GLM5NextMoEPrefillKernel.swift), Nemotron Super Mamba step (NemotronSuperMambaStep.swift), Nemotron Super MoE routing (NemotronSuperMoEKernels.swift), GLM5 hyper-connection (GLM5NextHyperConnectionKernel.swift), MiMo V2.6 experts (MiMoV26NAXGateUpMetalSources.swift,MiMoV26DecodeExpertMetal.swift)1 / (1 + metal::exp(metal::abs(x)))1 / (1 + metal::precise::exp(metal::abs(x))). The fork invariant is fused == native, and native changed with mlx 365bd0fb (#4461), which moved MLX's Sigmoid functor tometal::precise::expnvfp4FusedDecodeMatchesNativeCombineOnGPU,NemotronSuperMambaStepTests,NemotronSuperMoEKernelTests,NemotronSuperGraphExecutionTests,NemotronSuperBatchedDecodeTests,NemotronSuperMTPGraphTestsmainnone differed. The fused outputs again equal the op chains bit for bitModelOptNVFP4Weights.calibratedMatmul)qqmmcall for all rows; since mlx 3eb822ca (#4483) bfloat16 calls with global scales take the tiled matrix kernel fromget_qmv_batch_limitrows on (6 to 33 by device)qqmmon at most 4 rows per call, one matrix-vector product per row, the graph's.rowwiseaccumulationNemotronSuperGraphExecutionTests(cached decode, mixed FP8 trunk, NVFP4 sorted prefill),ModelOptGraphParityTests.sortedPrefillRowKernelIsBitwise(fork invariant: graph == eager).eagerReferencepathssmAttnrecurrent state dtypecomputeDtacross windows without rounding, as mlx-lm does; the Nemotron Super fused SSD and prefill oracles depend on that stateSSMTests.testSSMAttnPreservesRecurrentStateDTypeAcrossChunksexpects a float32 state; output dtype unchangedBugs found
update(parameters:)through an internal method, so a nested module'supdate(parameters:)override runs only when the update starts at that moduleParameterUpdateObserving(MLXLMCommon): modules that can start an update forward the updated keys to the GDN layers (MLXLLM and MLXVLM Qwen 3.5), commit 7952553whereis_donatable()requires an owned buffer, and mlx-cmlx_array_get_buffer_inforeporteduniquefromis_donatable()capacityExhausted); the same check inCheckpointAllocationFootprint, MiMo MTP state and GLM5 MTP refused wrapped buffersarray::is_uniquely_referenced()(reference counts only; donation unchanged), Layr-Labs/mlx-c e1b98733 reportsuniquefrom it, pinned through mlx-swift 6ff0b344 and later. No lm-side bypass;info.isUniqueis the one notion of uniquenessBaseConfigurationfall back toquantization_config; a ParoQuant config (quant_method: paroquant,krot: 8) was decoded as MLX per-layer quantization, withkrottaken as a layerDecodingError.typeMismatchatquantization_config.krotquantization_configis read only when it is MLX's format (noquant_method,mlx, or an MLX quantization mode); new fork testBaseConfigurationTests.testForeignQuantizationConfigIsNotPerLayerQuantizationapplyMaskexpands a 4D mask to 5D for its GQA score layout; the fork's quantized scores are 4DquantizedAttentionAppliesABatchedArrayMask)min(window, cache.offset); the mergedRotatingKVCachepresentswindow - 1 + trows for at-token writebroadcast_shapesabort for a multi-token write past the window (the abort ended the test process:VLMTextOnlyContinuationTestsministral3)createAttentionMask(h:cache:windowSize:), as upstream); without a cache the mask stays causal and windowedmodel(tokens, cache:)callAsFunction(_:cache:state:); the fork's callers use the stateless one, whose protocol default callsfatalErrorLanguageModel.swift:436) that ended test shards 7 and 14callAsFunction(_:cache:)restored; it carries no M-RoPE delta, so a decode after a media prompt uses the typed call with thepreparestateGemma4Processorwas not coveredChatSessionprompt-cache reuseLMInput(tokens:); media prompts keep the maskMTPSpeculativeTokenIteratorsetmainStateto nil after falling back to passthroughswitchToPassthroughclears only the drafter keys, commit c4465b4CBv2ContiguousHistoricalCheckpointTests.testCancellationAndShutdownDrainCapturedWindowOwnertimed outmainand in the serial jobtest_shards.pygroup setting"own_process": true(own process after the main run, kept byplan); new strict groupcontiguous-historical-checkpoint. The test is unchanged. After: 0.532 s (run 39975636046), commit 0201877keepsLeadingTextChatSessionToolRoundTripTests)Stream.gpu/Stream.cputo the current task, soStreamOrDevice.default.stream == Stream.gpuis also true on a custom streamMLXProcessStreams(MLXLMCommon), one helper for every stream check, commit 1ba5e73QwenXMLPayloadScannersearched>byCharacter; a value that starts with U+0301 merges with>Downstream API changes
Each item breaks or changes code that pins this fork. No compatibility shims are added.
LanguageModel.newCache(parameters:)nowthrows; wrappers that forward it must throw toomakePromptCache(...)andmakePromptCacheWithLayerCount(...)nowthrowKVCacheSimple.toQuantized(groupSize:bits:)nowthrowssanitize(weights:)isthrowsin the protocolprepare(_:cache:windowSize:)replaced byprepare(_:cache:state:prefill:); chunking default is.balanced(use.remainderfor the old boundaries)LMOutput.Stateis a typed key store (LMOutput.Key<T>);crossAttentionStatesis goneUserInput.ImageandUserInput.Videoare structs; switch on.source;VideoFrame.frameis deprecated for.imageGenerationhas a new case.rejectedToolCall; exhaustive switches must handle itgenerate(...)andgenerateTask(...):wiredMemoryTicket:comes beforetools:; newstate:andcomponents:labelsGemma4TextModel.modeland related members are@_spi(GemmaEncoder)Gemma4TextConfiguration,Gemma4AssistantConfiguration,Gemma4AssistantDraftModel,Gemma4Configuration; code that imports MLXLLM and MLXVLM must qualify these namesvisualMask:replaced byvisualIndices:andstate:loadProcessorConfig(from:fallback:):fallbackhas no default; the fork keepsloadProcessorConfig(from:)layer_typesvalues now throwToolCallProcessor: the default is unchanged from forkmain(frame state machine); upstream's recovery machine needsToolCallPolicy(returnsFailedCallsAsText: false)compile(shapeless:_:); mlx-swift's own@Sendableoverloads applyGLM5NextNVFP4Linear.globalScalerenamedweightScale2(MLXNNQuantizedLinearnow has an optionalglobalScale)RotatingKVCache.metaStatehas 7 values: keep, maxSize, step, offset, idx, capacity origin, wrapped flag (was 5); readers that parse it must accept the two new values. No external reader found in d-inference, darkbloom-platform or the engine repos outside their vendored copyCompilableRotatingKVCache.init(maxSize:keep:step:)is no longer anoverride(upstream addedrewindCapacity:)LMOutput.State), not a model instance variable. External callers that decode after a media prompt must pass the state thatpreparereturned tocallAsFunction(_:cache:state:)on every step. The statelesscallAsFunction(_:cache:)carries no delta and gives wrong positions after a media promptFork callers checked for the M-RoPE request state (decode after a VLM prompt):
TokenIterator(generate,generateTask,ModelContainer.generate)preparestate into the first and every later stepTokenIterator(draft model)MTPSpeculativeTokenIteratorChatSessionTokenIterator; prompt-cache snapshots keep the state with the cacheMLXModelContainerEngine(mlx-server,MLXLMServer)preparethengenerate(TokenIterator)GuidedGenerationLoopprepareand every stepEngineV2refuses a causal multimodal request without request position state, and M-RoPE models run through positioned forwarding; no model-held delta is readBenchmarkHelpers(vision benchmarks),BenchCBv2ModelContainer.generate(TokenIterator);BenchCBv2RealModelruns a one-token, cache-free probe onlyWiredMemoryUtilsmeasurement,Rerankerpreparestate when they move to this head (see the row above)Tests: renamed, restored and adapted
Test files missing at the head (
comm -23ofgit ls-tree -r --name-only <side> -- Testsagainst the head):mainTests/MLXLMTests/LFM2MoERoutingTests.swift,Tests/MLXLMTests/Unit/Tool/ToolCallProcessorStreamingTests.swiftmainRenames (forced by clashes with new upstream files):
LFM2MoERoutingTests.swifttoLFM2MoESigmoidRoutingTests.swift(R098). Upstream addedLFM2MoeRoutingTests.swift; on a case-insensitive file system both names are one file.Unit/Tool/ToolCallProcessorStreamingTests.swifttoUnit/Tool/ToolCallProcessorFrameStreamingTests.swift(R078). Upstream addedToolCallProcessorStreamingTests.swiftin the same test target; SwiftPM refuses two sources with one basename in a module. Each constructor passesreturnsFailedCallsAsText: true, which selects the state machine these tests specify.Upstream tests changed for the fork (no case skipped, no assertion removed):
Qwen35FusedGDNProjectionTestsprojectInputs(_:B:S:), non-throwingprepareFusedInputProjection()); unfused references use projection copies that cannot fuse. "Forward does not fuse lazily" becomes "first forward fuses, keys and output unchanged" (fork contract). The model-release case checks every GDN layer ran fused instead of the LLM segment count. VLM cases unchanged.Qwen35GDNDecodeBitwiseTestsdecodeConv(convState:qkv:); the full-window reference moved into the test. New case: the conv state of a cached decode step equals the reference bit for bit.Gemma4VideoInputTestsvideo_token_iddefault 258884,video_processor.max_soft_tokensdefault 70, image and video scatter agreement, per-frame tokens from the patch grid (the fork does not truncate), frames throughGemma4Processor.prepare(input:).CompiledDecodeWeightUpdateTestscompiledGDNTraceCount > 0on the quantized-KV path.CompiledTraceTestsMLX.compile(inputs: [], outputs: [])for the capture hazard, because the pinned mlx-swift's statelesscompiletakes a@Sendablebody.Qwen35DirectExpertReductionTestsblock(input)instead of upstream'sblock.forward(input).Qwen3VLMoETestshidden_act: gelu_pytorch_tanh, as published checkpoints do. The fork's Qwen3-VL vision default staysgelu(fe01df9, over upstream cd1ab3d) and MoE vision configs must name their activation.Gemma4AssistantDraftModelTests,Qwen3VLMoETests,Qwen35SanitizeTests,Qwen35MRoPETests,ToolTests,MediaProcessingTests,Qwen3VLToneCurveTestsFork unit tables changed by the merge (no field assertion removed):
modelType(3d292ec), Qwen 3.5layerTypes,mtpUseDedicatedEmbeddings,resolvedLayerTypes(4cc5504; new case: an explicitlayer_typeslist wins over the interval), Gemma 4doNormalize(67b146e port), LFM2VL transformers 5 keys (48114ee), Qwen3VL processorsize(65be34c). NemotronH and NemotronH35 MoE keys moved out of the required keys (7e4024e made them optional); the JSON keeps them.ParserUtilitiesTestsexpects upstream's schema normalizer (a56aee3): a string-admitting union or unknown type keeps the text, null needs"null", an unconvertible value keeps its text. These lines checked old upstream behavior, not fork behavior; added lines keep the null, integer, array and false conversions checked.MediaGeometryTestsexpectsmaxVideoFramesfromvideo_sampling.max_frames(648693c) instead of the old hard-coded 20.Fork tests adapted to deliberate upstream behavior after the #341 sharded run:
QwenVLProcessorTests: Qwen2-VLpreparereturns the logits of every prompt position (e31237a); tied-embedding sanitize dropslm_head(3de04ab), and untied Qwen2-VL and Qwen2.5-VL variants keep thelm_headrename check; Qwen3-VL text-only prepare has no mask (72d9fdb), test renamedqwen3VLPrepareOfTextHasABatchAxisAndNoMask.Qwen3VLForwardPassTestsandVisionModelForwardPassTestsdecodeAfterThePromptMatchesALongerPrompt: the M-RoPE delta is request state since 3f9c86f (fix(pixtral): keep the pixel layout and merge the features of more than one image #283), so the decode step passes the state thatpreparereturned. On forkmainthe delta was a model instance variable.QwenVisionSeamTests: the Qwen 3.5 norm shift applies only to a raw checkpoint, detected by a raw GDN conv1d (28a7f30, Qwen3.5: don't shift norm weights just because a checkpoint has MTP tensors ml-explore/mlx-swift-lm#598); the source fixtures carry one, and new assertions check the conv1d relayout and that a converted conv1d leaves the norms unshifted.SmolVLM2ProcessorTests.textOnlyPromptHasNoPixels: no text-only mask (77f4e03).VisionModelExtraPathTests.fastVLMMaskAndImagePosition: a FastVLM prompt without image token -200 throws (648693c); the mask and padding checks are unchanged.WiredMemoryMeasurementTests.tuneFromAUserInputUsesTheProcessor: the token count comes from the sharedTestInputProcessor, whose tokenizer changed in a86ee6a.PrismHadamardProcessorTests: the legacy Qwen3-VL processor reads thesizeblock (65be34c), so a 64x64 image takes the configured minimum (16x16 grid).PromptCacheFileTests: the 7-valueRotatingKVCachemetaState (ruled).EvalTests.testVarianceNormalizedKVCache32KIngestAndDecodePeakMetalMemorySmokefailed its 0.25 s one-layer decode time limit (0.472 s) on one runner; peak workspace was byte-identical (451808476 bytes) to a passing run (0.160 s decode). Runner timing, not a memory regression.fork.yaml
base.hashis d02948b. The base comment, the overview andFORKDIFF.mdstate the policy: the fork merges upstream when David directs it; each merge movesbase.hashand re-validates every section; between merges, fixes are ported one at a time.Olmo3.swiftandFalconH1.swift, whose fixes upstream now has.scripts/check_forkdiff.py --upstream-ref upstream/mainpasses locally.Known flaky tests
Counts are failed runs out of completed Fork Tests runs that ran the test. Fork
mainand main-based PRs: 19 runs, 2026-10-21 to 2026-10-23. Sync branch: this PR and the sharded #341 runs.mainNemotronSuperBatchedDecodeTests.rowExactBatchedDecodeIsBitwiseSerial,pagedBatchedRowsEqualEachRequestAlone); MambaStep float32convolveMatchesConcatConvSilu/gatedNormMatchesModule; MTP batched window in graph bf16-modelopt tiled fixtures (NemotronSuperMTPBatchedWindowTests,NemotronSuperMTPRoundTests,NemotronSuperCoScheduledServingTests)main. Not per VM. A test that runs a model insideDevice.withDefaultDevice(.cpu)(GLM5NextCBv2Tests) records a CPU trace of the shared compiled MLXNNsilu. MLX keys compiled traces by the C++ thread default stream, but mlx-swift scopes the default stream to the task, so a later GPU call on the same thread replays the CPU trace (about 1 ulp off in float32)EvalTests.testVarianceNormalizedKVCache32KIngestAndDecodePeakMetalMemorySmokemain(upstream 6745899)Stream.gpu.synchronize()before sampling the baseline. The test is unchanged in this PR[METAL] Command buffer execution failed: GPU Timeout (kIOGPUCommandBufferCallbackErrorTimeout)inQwen35VLMCompiledDecodeTests(testBFloat16UsesExactCompiledRoutesonce,testModelDeallocatesAfterQuantizedFallbackDecodeonce)testBFloat16UsesExactCompiledRoutestakes 5.6-14.4 s on #349 and 9.7-15.6 s on #339, andtestTurboQuantCacheUsesExactPerLayerFallbacktakes 31.6-68.7 s and 51.0-52.2 s. Both runner images (20261013, 20261021) show it and also passMiMoV26OpenRouterMediaTests.testCapturedVideosDecodeAudioAndKeepVisionPeakIndependentOfFrameCountinconsistentFramesat 1474da9 only)Test plan
swift build --build-system native --build-tests): exit 0 for every target at c4465b4 (later commits change only Package.swift, CI files and the shard map). No tests ran on the box.fork.yaml describes the fork: green at 115ae04.fork.yaml describes the forkgreen; Fork Tests run 39975636046: 9/10 shards, "Each test ran once" and Coverage green; shard 9 failed in both attempts only on the VNKV smoke time bound (0.536 s, 0.585 s), fixed by test: warm up the decode and settle memory before the VNKV 32K smoke measures #348.fork.yaml describes the forkand Fork Tests (run 39914582297) green. The sharded CI-speed run ci: build once and run the tests in parallel shards #341 at ac5aa1c (contains c4465b4): 15/16 shards green plus "Each test ran once"; shard 5 failed only the VNKV smoke time bound above.Checklist
swift formatand.swift-format(the fork lint job checks only the changed files)AI usage
🤖 Generated with Claude Code