Skip to content

Merge upstream ml-explore/mlx-swift-lm main d02948b9 (2026-10-22) - #339

Merged
davidtai merged 324 commits into
mainfrom
sync/upstream-2026-10-22
Oct 24, 2026
Merged

davidtai merged 324 commits into
mainfrom
sync/upstream-2026-10-22

Conversation

@davidtai

@davidtai davidtai commented Oct 23, 2026 •

Copy link
Copy Markdown

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-lm main at d02948b (2026-10-22) into the fork with a merge commit.

Item Value
Merge-base before 7e2b710 (2026-04-17)
Upstream commits merged 289 (tags 3.31.3, 3.31.4, 3.32.3 are in the range)
Fork commits on main 389
Files with conflicts 67 (about 360 hunks)
Merge commit 29ce6a0 (748 files changed against fork main)

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.swift pins Layr-Labs/mlx-swift at a615e8f57298e2c4aec5e3c873fe8adcf65a3e6c (Layr-Labs/mlx-swift PR 59). It pins Layr-Labs/mlx 83dbdb04 and Layr-Labs/mlx-c cb19abf6.
  • On fork main the pin was 67dc752856ca. The task brief named d7c1d3dc, which was not the pin on main.
  • 67dc7528 cannot build the merged code: upstream code calls mlx-swift APIs from 0.31.5 and later, for example MLXArray.maskFill(for:). So the merge and the re-pin are one PR.
  • swift-syntax floor is 602.0.0, as upstream.

Merge order

  1. Layr-Labs/mlx, 2. Layr-Labs/mlx-c, 3. Layr-Labs/mlx-swift PR 59, 4. this PR.
    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.swift to Libraries/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 % 32 fallback and differentiable recurrence are merged in; kernels run only when useKernel is true. Qwen4ExpFusions.swift and Qwen4ExpGDNBlocked.swift move to MLXLMCommon with package access, because GatedDelta.swift calls them.

Conflict resolutions

File Resolution
Package.swift Both sides' products and targets. Fork dependencies, upstream swift-syntax floor, upstream cxxLanguageStandard.
.github/workflows/pull_request.yml Fork (format-only lint). Upstream-only workflows are gated to ml-explore/mlx-swift-lm and skip here.
README.md, CONTRIBUTING.md, Documentation.md, MLXVLM/README.md Both. CONTRIBUTING states that the fork does not run the Xcode integration tests.
MLXLMCommon/Evaluate.swift (32) Upstream signatures (state:, components:, wiredMemoryTicket:, tools:, generic generateTask) and upstream TokenLoopHandler; fork validation in prepare; fork repetitionPenalty skip and public iterator counters kept.
MLXLMCommon/KVCache.swift (22) Combined: upstream typed caches, restore and rewind; fork CBv2/MTP rollback hooks; fork prompt-cache validation on the formats it knows.
MLXLMCommon/GatedDelta.swift (5) See above. Fork numerics win.
MLXLMCommon/Load.swift (3) One parallel loader: upstream's (byte-balanced groups, index handling, component-aware loading, loader-thread errors). Fork prefetch, stage instrumentation, checkpoint filters, Prism and bf16 conversion kept. The fork's recursive safetensors enumeration is dropped.
MLXLMCommon/ModelContainer.swift, ModelFactory.swift Upstream argument order.
MLXLMCommon/Chat.swift, ChatSession.swift, BaseConfiguration.swift Both (templateFields plus upstream audios/tool; upstream session cache policy; quantization_config and text_config).
MLXLMCommon/SwitchLayers.swift (13) Fork kernels and routes; upstream open classes, transform hooks and direct-reduction predicate. Upstream FusedGateUpSwitchGLU dropped (fork SwitchGLU(fuseGateUp:) does the same).
MLXLMCommon/RoPEApplication.swift Both. CompilableKVCache and CompilableRotatingKVCache return their offset as a graph array.
MLXLMCommon/Tool/* (10 files) Union of formats. ToolCallProcessor keeps 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 Upstream (structs with .source, audio, processing options); fork memory-backed video and pixel clip kept.
MLXLLM/Models/Gemma4Text.swift (30), Gemma4.swift Fork file with upstream changes ported one by one (quantized KV attention, ScaledLinear to Linear, SPI encoder surface, tied head sanitize, loraLayers, toolCallFormat, new prepare). Upstream MoE block, fused RMSNorm/GELU and softcap not taken (fork has its own).
MLXLLM/Models/Qwen35.swift (19), Qwen35MTP.swift, Qwen3Next.swift Fork GDN, MoE and MTP; upstream schedule (layer_types), MTP predictor types, nextTokenLogits, throwing newCache, chat conventions.
MLXLLM/Models/{NemotronH,GPTOSS,DeepseekV3,FalconH1,GLM4,LFM2MoE,Olmo3,SSM,Gemma3nText}.swift, LLMModelFactory.swift Per file in commit 29ce6a0; fork wins on behavior (fp32 SSM state, GPT-OSS sinks, NemotronH MTP); upstream where both made the same fix. Factory: union of registrations; fork tool-format inference first.
MLXVLM/Models/Gemma4.swift (10) Fork file (CBv2 vision and video seam) plus upstream's Gemma4Unified, its processor and the message generator.
MLXVLM/Models/{Qwen3VL,Qwen35,Qwen35MoE,Qwen2VL}.swift Combined; upstream state-threaded positions, PreparedInputSplitting, MoE; fork seams, fused gate+up and vision GELU kept.
MLXVLM/MediaProcessing.swift, VLMModelFactory.swift, other VLM models Combined; upstream prefill API and processor loading rules; fork metadata, cancellation and processor overrides.
Tests (17 add/add or content conflicts) Both sets of tests kept; duplicate names renamed.

ToolCallProcessor default (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.returnsFailedCallsAsText is the one switch. Default true (fork). false selects upstream's recovery state machine, which reports a failed call as a RejectedToolCall event.
  • Fork call sites use the default: BatchedToolStreamHandler (mlx-server), MLXModelContainerEngine, and upstream's TokenStreamDecoder (generate and ChatSession).
  • MLXFoundationModels AllowedToolOutputRouter passes false: its rejection events come only from the recovery machine.
  • Upstream tool tests that test the recovery machine pass false explicitly (ToolTests, ToolCallPolicyTests, TextToolCallRecoveryTests, ToolCallIdTests, ChatSessionTests rejection helper and the others listed in commit 4f8bcb7).
  • External callers (d-inference, darkbloom-platform, mlx-serve, the engine repos) construct no ToolCallProcessor outside their vendored copy; their behavior does not change on re-pin.
  • Follow-up: fold the two state machines into one (no-duplicates rule).

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.

Kernel Before After Test it fixes Measured
GDN q/k L2 norm in MLXLLM Qwen 3.5, MLXLLM Qwen3-Next, MLXVLM Qwen 3.5 upstream c408452 (ml-explore#633): rmsNorm(eps: 1e-6 / D) (transformers l2norm) fork: rmsNorm(eps: 1e-6), as mlx-lm Python qwen3_5.py:181 and qwen3_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 eps Relative error 0.984 only for tokens scaled to 1e-6 (sum of squares near the eps); at normal activation sizes the difference is far below bf16 resolution
Gemma 4 final-logit softcap (Gemma4Text.swift) upstream 34a3fd2 (ml-explore#675) keeps the logits' dtype fork keeps float32 softcap logits (fork 8a212b4, vMLX decode port) Gemma4TextTests softcap test now expects float32 fp16 and bf16 cases differed by up to 0.0266 (max abs) from upstream's expectation; float32 case was already bit-identical
The copied MLX sigmoid in six fused kernels: GLM5 MoE decode and prefill (GLM5NextMoEDecodeKernel.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 to metal::precise::exp nvfp4FusedDecodeMatchesNativeCombineOnGPU, NemotronSuperMambaStepTests, NemotronSuperMoEKernelTests, NemotronSuperGraphExecutionTests, NemotronSuperBatchedDecodeTests, NemotronSuperMTPGraphTests GLM5 MoE before the fix: 6.10e-5 of the routed activations differed from the native path (max difference 2.09e-6, E288 D4096 I2048 S2048 K8, 1 token); on fork main none differed. The fused outputs again equal the op chains bit for bit
Eager NVFP4 reference (ModelOptNVFP4Weights.calibratedMatmul) one qqmm call for all rows; since mlx 3eb822ca (#4483) bfloat16 calls with global scales take the tiled matrix kernel from get_qmv_batch_limit rows on (6 to 33 by device) fork keeps its numerics over mlx 3eb822ca: qqmm on at most 4 rows per call, one matrix-vector product per row, the graph's .rowwise accumulation NemotronSuperGraphExecutionTests (cached decode, mixed FP8 trunk, NVFP4 sorted prefill), ModelOptGraphParityTests.sortedPrefillRowKernelIsBitwise (fork invariant: graph == eager) bf16 only, calls of 20+ rows; float32 and short calls were unaffected. Cost only on the .eagerReference path
ssmAttn recurrent state dtype upstream 771e4ee (#331) rounds the state to the input dtype fork returns the fp32 state of computeDt across windows without rounding, as mlx-lm does; the Nemotron Super fused SSD and prefill oracles depend on that state SSMTests.testSSMAttnPreservesRecurrentStateDTypeAcrossChunks expects a float32 state; output dtype unchanged No value change; the state is not rounded

Bugs found

Bug Cause Effect Fix
Fused GDN input projection stale after a parameter update mlx-swift 9bd73fc7 (#418, in the pinned mlx-swift) runs a recursive update(parameters:) through an internal method, so a nested module's update(parameters:) override runs only when the update starts at that module An update that starts at a decoder layer or a model (adapter load, weight update) did not invalidate the fused projection; compiled segments kept the old projection. Latent in production for MLXLLM Qwen 3.5 too ParameterUpdateObserving (MLXLMCommon): modules that can start an update forward the updated keys to the GDN layers (MLXLLM and MLXVLM Qwen 3.5), commit 7952553
Quantized SDPA returned float32 for fp16/bf16 fork a9e0ee1 (#43): the fused no-sink softmax used a float32 zero literal in where Attention output promoted to float32 on the legacy single-stream path (the CBv2 engine has no KV quantization since fork f5d0616); exact compiled routes for quantized KV caches turned off Zero in the scores dtype; softmax values unchanged, output keeps the input dtype, commit cbc07e6
Wrapped buffers never reported unique upstream mlx 5dbe9991 (#4634, "Fix foreign buffer ownership"): is_donatable() requires an owned buffer, and mlx-c mlx_array_get_buffer_info reported unique from is_donatable() Host-zeroed paged KV segment growth threw (reported as capacityExhausted); the same check in CheckpointAllocationFootprint, MiMo MTP state and GLM5 MTP refused wrapped buffers Fixed at the source: Layr-Labs/mlx 699649d3 adds array::is_uniquely_referenced() (reference counts only; donation unchanged), Layr-Labs/mlx-c e1b98733 reports unique from it, pinned through mlx-swift 6ff0b344 and later. No lm-side bypass; info.isUnique is the one notion of uniqueness
ParoQuant checkpoints failed to load fork ed55bee made BaseConfiguration fall back to quantization_config; a ParoQuant config (quant_method: paroquant, krot: 8) was decoded as MLX per-layer quantization, with krot taken as a layer DecodingError.typeMismatch at quantization_config.krot quantization_config is read only when it is MLX's format (no quant_method, mlx, or an MLX quantization mode); new fork test BaseConfigurationTests.testForeignQuantizationConfigIsNotPerLayerQuantization
Quantized SDPA mask had the wrong rank upstream's applyMask expands a 4D mask to 5D for its GQA score layout; the fork's quantized scores are 4D Reshape fatal for a batched array mask (quantizedAttentionAppliesABatchedArrayMask) The mask broadcasts on the 4D scores as it is
Ministral 3 sliding-window mask had the wrong width with a cache fork c8440b4 built the sliding mask with offset min(window, cache.offset); the merged RotatingKVCache presents window - 1 + t rows for a t-token write broadcast_shapes abort for a multi-token write past the window (the abort ended the test process: VLMTextOnlyContinuationTests ministral3) The sliding cache builds the mask (createAttentionMask(h:cache:windowSize:), as upstream); without a cache the mask stays causal and windowed
Qwen2-VL, Qwen2.5-VL, GLM-OCR and Qwen3-VL-MoE aborted on model(tokens, cache:) upstream e31237a (#345), cc712f4 and 3f9c86f left only the typed callAsFunction(_:cache:state:); the fork's callers use the stateless one, whose protocol default calls fatalError Process abort (LanguageModel.swift:436) that ended test shards 7 and 14 Stateless callAsFunction(_:cache:) restored; it carries no M-RoPE delta, so a decode after a media prompt uses the typed call with the prepare state
Gemma 4 text-only prompts kept a mask upstream 77f4e03 (ml-explore#700) dropped the text-only mask from every VLM processor; the fork's own Gemma4Processor was not covered A mask stops ChatSession prompt-cache reuse Text-only prompts return LMInput(tokens:); media prompts keep the mask
MTP passthrough lost the M-RoPE delta upstream 4cc5504 (#545): MTPSpeculativeTokenIterator set mainState to nil after falling back to passthrough A Qwen VLM decoded the rest of the stream with wrong positions after a media prompt (the Qwen 3.5 VLM refuses a warm cache without the delta) Keep the model state; switchToPassthrough clears only the drafter keys, commit c4465b4
Sharded CI: CBv2ContiguousHistoricalCheckpointTests.testCancellationAndShutdownDrainCapturedWindowOwner timed out the merged sharded CI (#341) ran it as the first engine work of shard 4's process, so its first step paid the Metal pipeline compile on a fresh hosted VM; the test waits 5 s for the first checkpoint evaluate 0.42, 2.36, 0.42, 3.97 s, then a timeout (run 39966880999), against 0.13-0.20 s on main and in the serial job test_shards.py group setting "own_process": true (own process after the main run, kept by plan); new strict group contiguous-historical-checkpoint. The test is unchanged. After: 0.532 s (run 39975636046), commit 0201877
Split tool start tag lost the text before it the frame machine dropped leading text before a partial start tag unless keepsLeadingText Raw-cache tool restart changed the legacy fragment shape (ChatSessionToolRoundTripTests) Text before a partial start tag is always emitted
Fused kernels ran on custom streams mlx-swift now scopes Stream.gpu / Stream.cpu to the current task, so StreamOrDevice.default.stream == Stream.gpu is also true on a custom stream GLM5 vision attention, DiffusionGemma expert reduction and soft embedding, MiMo working sets used their default-stream-only kernels on custom streams MLXProcessStreams (MLXLMCommon), one helper for every stream check, commit 1ba5e73
Fused NVFP4 scaled projections the fork's GDN fusion did not refuse projections with an NVFP4 global scale (upstream fixed its own fusion in 1dc19ef) A scaled NVFP4 checkpoint would fuse with the global scale lost Port of 1dc19ef to the fork's fusion, commit bddfc5d
Qwen 3.5 XML tool tags with a combining mark upstream's QwenXMLPayloadScanner searched > by Character; a value that starts with U+0301 merges with > The tag end was not found; the call was not parsed Scalar-based search, commit 4f8bcb7

Downstream API changes

Each item breaks or changes code that pins this fork. No compatibility shims are added.

Change Upstream commit
LanguageModel.newCache(parameters:) now throws; wrappers that forward it must throw too 5d8def8 (#514)
makePromptCache(...) and makePromptCacheWithLayerCount(...) now throw 5d8def8 (#514), 38927f5 (#453)
KVCacheSimple.toQuantized(groupSize:bits:) now throws 38927f5 (#453)
sanitize(weights:) is throws in the protocol 6d84ef6 (ml-explore#679)
prepare(_:cache:windowSize:) replaced by prepare(_:cache:state:prefill:); chunking default is .balanced (use .remainder for the old boundaries) 4c7874b (#470), 65be34c (#399)
LMOutput.State is a typed key store (LMOutput.Key<T>); crossAttentionStates is gone 3f9c86f (#283)
UserInput.Image and UserInput.Video are structs; switch on .source; VideoFrame.frame is deprecated for .image 0493daf (#535), 381469a (#534)
Generation has a new case .rejectedToolCall; exhaustive switches must handle it d7dc03d (#512)
generate(...) and generateTask(...): wiredMemoryTicket: comes before tools:; new state: and components: labels cb432f5 (#167), 405146b (#472)
Gemma4TextModel.model and related members are @_spi(GemmaEncoder) d667610 (#530)
MLXVLM now declares public Gemma4TextConfiguration, Gemma4AssistantConfiguration, Gemma4AssistantDraftModel, Gemma4Configuration; code that imports MLXLLM and MLXVLM must qualify these names 0767814 (#327), 78eaa5b (#415)
Qwen3-VL language model: visualMask: replaced by visualIndices: and state: 4b0b416 (#475)
loadProcessorConfig(from:fallback:): fallback has no default; the fork keeps loadProcessorConfig(from:) 60985ee (#565)
Qwen 3.5 configs: unknown layer_types values now throw 4cc5504 (#545)
Weight loading reads the top-level safetensors files (index first); subdirectories are not scanned f5f18ed (#408), d661402 (#562)
ToolCallProcessor: the default is unchanged from fork main (frame state machine); upstream's recovery machine needs ToolCallPolicy(returnsFailedCallsAsText: false) merge resolution (David)
MLXLMCommon no longer shadows compile(shapeless:_:); mlx-swift's own @Sendable overloads apply merge resolution (mlx-swift PR 59)
GLM5NextNVFP4Linear.globalScale renamed weightScale2 (MLXNN QuantizedLinear now has an optional globalScale) merge resolution (mlx-swift PR 59)
RotatingKVCache.metaState has 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 copy 604fae7 (#584), 12d935f (ml-explore#622)
CompilableRotatingKVCache.init(maxSize:keep:step:) is no longer an override (upstream added rewindCapacity:) 12d935f (ml-explore#622)
The M-RoPE position delta of Qwen2-VL, Qwen2.5-VL, Qwen3-VL, Qwen3-VL-MoE, GLM-OCR and Qwen 3.5 VLM is request state (LMOutput.State), not a model instance variable. External callers that decode after a media prompt must pass the state that prepare returned to callAsFunction(_:cache:state:) on every step. The stateless callAsFunction(_:cache:) carries no delta and gives wrong positions after a media prompt 3f9c86f (#283), e31237a (#345)

Fork callers checked for the M-RoPE request state (decode after a VLM prompt):

Caller Result
TokenIterator (generate, generateTask, ModelContainer.generate) carries the prepare state into the first and every later step
Speculative TokenIterator (draft model) main model state carried; the draft model is a text model
MTPSpeculativeTokenIterator carried; fixed in c4465b4: the passthrough fallback set the whole state to nil and decoded without the delta; now it clears only the drafter keys
ChatSession through TokenIterator; prompt-cache snapshots keep the state with the cache
MLXModelContainerEngine (mlx-server, MLXLMServer) prepare then generate (TokenIterator)
GuidedGenerationLoop carries the state from prepare and every step
CBv2 engine and runners request-owned positions: EngineV2 refuses a causal multimodal request without request position state, and M-RoPE models run through positioned forwarding; no model-held delta is read
BenchmarkHelpers (vision benchmarks), BenchCBv2 ModelContainer.generate (TokenIterator); BenchCBv2RealModel runs a one-token, cache-free probe only
WiredMemoryUtils measurement, Reranker prefill or one forward only; no decode
d-inference, darkbloom-platform pin this fork by revision and must pass the prepare state when they move to this head (see the row above)

Tests: renamed, restored and adapted

Test files missing at the head (comm -23 of git ls-tree -r --name-only <side> -- Tests against the head):

Side Missing paths With rename detection
fork main Tests/MLXLMTests/LFM2MoERoutingTests.swift, Tests/MLXLMTests/Unit/Tool/ToolCallProcessorStreamingTests.swift none
upstream main none none

Renames (forced by clashes with new upstream files):

  • LFM2MoERoutingTests.swift to LFM2MoESigmoidRoutingTests.swift (R098). Upstream added LFM2MoeRoutingTests.swift; on a case-insensitive file system both names are one file.
  • Unit/Tool/ToolCallProcessorStreamingTests.swift to Unit/Tool/ToolCallProcessorFrameStreamingTests.swift (R078). Upstream added ToolCallProcessorStreamingTests.swift in the same test target; SwiftPM refuses two sources with one basename in a module. Each constructor passes returnsFailedCallsAsText: true, which selects the state machine these tests specify.

Upstream tests changed for the fork (no case skipped, no assertion removed):

Test file What changed
Qwen35FusedGDNProjectionTests LLM cases check the fork's fused GDN projection (projectInputs(_:B:S:), non-throwing prepareFusedInputProjection()); 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.
Qwen35GDNDecodeBitwiseTests Runs against the fork's new decodeConv(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.
Gemma4VideoInputTests Checks the fork's Gemma 4 video path: video_token_id default 258884, video_processor.max_soft_tokens default 70, image and video scatter agreement, per-frame tokens from the patch grid (the fork does not truncate), frames through Gemma4Processor.prepare(input:).
CompiledDecodeWeightUpdateTests Qwen 3.5 cases run on the MLXVLM Qwen 3.5 language model (it has the compiled segments); all upstream assertions kept, plus compiledGDNTraceCount > 0 on the quantized-KV path.
CompiledTraceTests Uses MLX.compile(inputs: [], outputs: []) for the capture hazard, because the pinned mlx-swift's stateless compile takes a @Sendable body.
Qwen35DirectExpertReductionTests Calls the fork block block(input) instead of upstream's block.forward(input).
Qwen3VLMoETests The MoE vision config declares hidden_act: gelu_pytorch_tanh, as published checkpoints do. The fork's Qwen3-VL vision default stays gelu (fe01df9, over upstream cd1ab3d) and MoE vision configs must name their activation.
Gemma4AssistantDraftModelTests, Qwen3VLMoETests, Qwen35SanitizeTests, Qwen35MRoPETests, ToolTests, MediaProcessingTests, Qwen3VLToneCurveTests Add/add merges: both sides' tests kept; MLXLLM vs MLXVLM names qualified; duplicates renamed.

Fork unit tables changed by the merge (no field assertion removed):

  • Configuration decoding tables list the fields upstream added: Llama modelType (3d292ec), Qwen 3.5 layerTypes, mtpUseDedicatedEmbeddings, resolvedLayerTypes (4cc5504; new case: an explicit layer_types list wins over the interval), Gemma 4 doNormalize (67b146e port), LFM2VL transformers 5 keys (48114ee), Qwen3VL processor size (65be34c). NemotronH and NemotronH35 MoE keys moved out of the required keys (7e4024e made them optional); the JSON keeps them.
  • ParserUtilitiesTests expects 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.
  • MediaGeometryTests expects maxVideoFrames from video_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-VL prepare returns the logits of every prompt position (e31237a); tied-embedding sanitize drops lm_head (3de04ab), and untied Qwen2-VL and Qwen2.5-VL variants keep the lm_head rename check; Qwen3-VL text-only prepare has no mask (72d9fdb), test renamed qwen3VLPrepareOfTextHasABatchAxisAndNoMask.
  • Qwen3VLForwardPassTests and VisionModelForwardPassTests decodeAfterThePromptMatchesALongerPrompt: 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 that prepare returned. On fork main the 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 shared TestInputProcessor, whose tokenizer changed in a86ee6a.
  • PrismHadamardProcessorTests: the legacy Qwen3-VL processor reads the size block (65be34c), so a 64x64 image takes the configured minimum (16x16 grid).
  • PromptCacheFileTests: the 7-value RotatingKVCache metaState (ruled).
  • Not changed: EvalTests.testVarianceNormalizedKVCache32KIngestAndDecodePeakMetalMemorySmoke failed 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.hash is d02948b. The base comment, the overview and FORKDIFF.md state the policy: the fork merges upstream when David directs it; each merge moves base.hash and re-validates every section; between merges, fixes are ported one at a time.
  • Section "Selective upstream port (embedders, macros, helpers)" is replaced by "Hugging Face macros and the Gemma 4 masked embedder test": the earlier ports are now part of the merge.
  • 9 stale globs removed (files that now equal upstream), for example Olmo3.swift and FalconH1.swift, whose fixes upstream now has.
  • New section "Upstream tests adapted to the fork".
  • scripts/check_forkdiff.py --upstream-ref upstream/main passes locally.

Known flaky tests

Counts are failed runs out of completed Fork Tests runs that ran the test. Fork main and main-based PRs: 19 runs, 2026-10-21 to 2026-10-23. Sync branch: this PR and the sharded #341 runs.

Test Fork main Sync branch Cause Fix
Nemotron Super per-VM bitwise mismatches: float32 SSM state (NemotronSuperBatchedDecodeTests.rowExactBatchedDecodeIsBitwiseSerial, pagedBatchedRowsEqualEachRequestAlone); MambaStep float32 convolveMatchesConcatConvSilu / gatedNormMatchesModule; MTP batched window in graph bf16-modelopt tiled fixtures (NemotronSuperMTPBatchedWindowTests, NemotronSuperMTPRoundTests, NemotronSuperCoScheduledServingTests) 2/19 (runs 39691356044, 39863770254; SSM state) SSM state 2/4; the MambaStep and MTP signatures only on #348's run 39972026730 (jobs 120492217906, 120492218163), green on this PR at the same pin (run 39975636046) Pre-existing on main. Not per VM. A test that runs a model inside Device.withDefaultDevice(.cpu) (GLM5NextCBv2Tests) records a CPU trace of the shared compiled MLXNN silu. 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) Layr-Labs/mlx-swift#62 keys each trace by the task default stream. #349 pins it: every target test green in 10/10 runs. #348 on top of it: all green (before: 3/3 and 5/5 red)
EvalTests.testVarianceNormalizedKVCache32KIngestAndDecodePeakMetalMemorySmoke not on main (upstream 6745899) 4/6, only the 0.25 s one-layer decode time limit Measured in CI on a hosted M1 VM: the timed first decode in a process pays the Metal pipeline compile. That takes 0.45-0.80 s when the VM's shader cache is cold; steady-state decode is 5-10 ms, and CPU graph build is under 1 ms. The 451.8 MB vs 586.0 MB "peak workspace" is not an extra copy. The absolute peak is 720.3 MB every time, and the baseline sometimes still counts one float32 random-input temporary that is released after its command buffer completes. Upstream's self-hosted Mac keeps a warm shader cache (steady 0.13 s) #348: one warm-up decode before the timed one, and Stream.gpu.synchronize() before sampling the baseline. The test is unchanged in this PR
Shard 6 process crash: [METAL] Command buffer execution failed: GPU Timeout (kIOGPUCommandBufferCallbackErrorTimeout) in Qwen35VLMCompiledDecodeTests (testBFloat16UsesExactCompiledRoutes once, testModelDeallocatesAfterQuantizedFallbackDecode once) 0 in the last 25 failed Fork Tests runs 0/2 on this PR; on #349 1/10 at 7f7da6b (run 40016603080 attempt 1) plus 1 earlier diagnostic run (39993284135) Hosted-VM GPU watchdog. Shard 6 has the same suites in the same order on #339 and #349. The test durations do not grow: testBFloat16UsesExactCompiledRoutes takes 5.6-14.4 s on #349 and 9.7-15.6 s on #339, and testTurboQuantCacheUsesExactPerLayerFallback takes 31.6-68.7 s and 51.0-52.2 s. Both runner images (20261013, 20261021) show it and also pass none
MiMoV26OpenRouterMediaTests.testCapturedVideosDecodeAudioAndKeepVisionPeakIndependentOfFrameCount 0/19 1/5 (inconsistentFrames at 1474da9 only) One-off, not reproduced none

Test plan

  • Box compile (ai-server, Swift 6.4, 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.
  • Lint and fork.yaml describes the fork: green at 115ae04.
  • Fork CI at 0201877 (final chain, mlx-swift a615e8f5): Lint, fork.yaml describes the fork green; 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.
  • Earlier: Fork CI at c4465b4: Lint, fork.yaml describes the fork and 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

  • I have read the CONTRIBUTING document
  • Format: the Swift files this PR changes are formatted with swift format and .swift-format (the fork lint job checks only the changed files)
  • I have added tests that prove my fix is effective or that my feature works (a merge; upstream and fork tests both run in CI)
  • I have updated the necessary documentation (FORKDIFF.md, fork.yaml, CONTRIBUTING.md)

AI usage

  • I have read this PR description in full and approve it as my own, and it accurately describes the code changes. (For David.)
  • AI usage disclosure: Claude Code (Claude Opus 5.5) made the merge, resolved the conflicts, wrote the fixes and this description. Compile checks ran on ai-server. Tests run in fork CI only.

🤖 Generated with Claude Code

GoodOlClint and others added 30 commits June 29, 2026 09:02
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>
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.
davidtai and others added 7 commits October 23, 2026 01:24
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>
@davidtai
davidtai marked this pull request as ready for review October 23, 2026 08:45
@davidtai
davidtai marked this pull request as draft October 23, 2026 12:36
@davidtai

Copy link
Copy Markdown
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.

davidtai and others added 2 commits October 23, 2026 08:57
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
davidtai marked this pull request as ready for review October 23, 2026 15:43
davidtai and others added 5 commits October 23, 2026 15:06
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
@davidtai
davidtai merged commit 755bdf6 into main Oct 24, 2026
7 checks passed
@davidtai
davidtai deleted the sync/upstream-2026-10-22 branch October 24, 2026 11:43
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>
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.