Skip to content

Add DeepSeek-V4 (deepseek_v4) text model - #796

Open
Augustas11 wants to merge 47 commits into
ml-explore:mainfrom
Augustas11:deepseek-v4-text-model
Open

Augustas11 wants to merge 47 commits into
ml-explore:mainfrom
Augustas11:deepseek-v4-text-model

Conversation

@Augustas11

@Augustas11 Augustas11 commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Proposed changes

Adds the deepseek_v4 text model (DeepSeek-V4-Flash). With the MXFP4 MLX conversion (158.0 GB resident, wired limit set to that; 0.57 tok/s without one, not re-measured at this head), an M3 Ultra (256 GB), macOS 27.0.1, decoding a 1K prompt with TokenIterator (local harness) gives 28.7 tok/s, 2.5 s to first token and 160.1 GB peak at this head, against 27.5 tok/s, 2.5 s and 160.0 GB at 7324f75; 256 of 256 greedy tokens equal the 7324f75 run's. At 8K / 32K: 25.9 / 24.8 tok/s, peak 166.0 / 166.2 GB (7324f75, not re-measured at this head).

Ported from mlx-vlm 0.7.10, corrected in review to DeepSeek's inference/model.py. I removed the opt-in HISA indexer selection taken from mlx-vlm: none of the 45 readable MLX conversion configs I surveyed sets its keys, nor does the official config. A config that carries the keys gets exact top-k; the keys are ignored (not tested). Every compared value comes from DeepSeek's code.

Architecture

  • Hyper-connections: 4 residual streams, Sinkhorn mixing, fused GPU kernel.
  • Attention: shared KV head, sliding window, ratio-4/128 pools, exact top-k indexer.

Outside the model file

One SwitchGLU initializer; registry and model-list lines.

Tests

tools/deepseek-v4-reference.py runs the pinned, sha256-checked model.py on a tiny hashed-weight model and writes DeepseekV4ReferenceValues.swift. tools/deepseek-v4-reference/kernel.py replaces DeepSeek's CUDA kernels with float32 CPU versions; act_quant, fp4_act_quant and rotate_activation are identity. DeepseekV4Tests rebuilds the weights; on the CPU it checks exact greedy tokens, top-4 log-probabilities within 4.3e-6 and 5.2e-6 (45 and 250 prompt tokens), tolerance 2e-5.

xcodebuild test -scheme mlx-swift-lm-Package -destination 'platform=macOS' -skipPackagePluginValidation \
  -only-testing:MLXLMTests/DeepseekV4Tests

At this head on an M5 (32 GB, macOS 27.0.1): 19 tests, 2 skipped, 0 failures. The call-split and bfloat16-load checks are skipped unless MLX_DEEPSEEK_V4_LONG=1 is set (TEST_RUNNER_MLX_DEEPSEEK_V4_LONG=1 for xcodebuild); with it, 0 skipped, 0 failures.

Deliberate bugs: dropping ape from the overlap gate fails 4 tests (up to 99,000x tolerance); shifting hash routing by one, 4 (up to 230,000x). A 19-iteration Sinkhorn is caught only by the fused-kernel-versus-ops GPU test (1.5e-4 against 3.6e-6, 42x), not by the reference comparison.

IntegrationTesting/.../DeepseekV4CheckpointTests checks the module tree and finite logits over a 512-token prefill and 8 decode steps. With the real checkpoint on the M3 Ultra (Xcode 26.6, mlx-swift 0.33.0) both pass at this head.

Limits

  • Not included: MTP head, vision, batched decode, cache trimming, activation quantization. Prompt-cache save and load are not supported.
  • Not done at this head: unit tests off the M5, the full suite, the generator's download.
  • The Sinkhorn check needs a Metal device; without one that test skips.
  • Tiny float32 reference; bfloat16 checked only in pooling, routing, kernel.
  • RoPE and SDPA attention run in the activation dtype, not float32; maxKVSize and KV quantization are ignored.
  • On an M5 GPU, float32 runs as TF32 unless MLX_ENABLE_TF32=0, and MLX's gathered quantized matmul can return NaN for K not a multiple of 64; parity runs on the CPU.
  • Full size: no correctness reference. Greedy tokens equal mlx-vlm's on one repetitive prompt; log-probabilities differ by up to 4.40, unexplained.

Checklist

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

AI usage

  • I have read this PR description in full and approve it as my own, and it
    accurately describes the code changes.
  • AI usage disclosure: An AI coding agent wrote the port, tests and generator under my direction and drafted this description. I reviewed the code and the results.

Augustas from Malibu

@aleroot

aleroot commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

Thanks @Augustas11, nice work, and the kernel is fine with me: it's JIT, it has a fallback, and the gain makes sense.
About my comment in #221: porting a server-side model from Python is fine. This is at the end quite a big model, so in this context my comment does not necessarily apply. The point is what the reference is. For V4 it is DeepSeek's inference/model.py, not mlx-vlm, and comparing with it I see two differences:

  1. Overlap compression. DeepSeek's Compressor keeps the previous window in kv_state[:, :ratio] during decode. Here the first window of every call gets zeros/-inf, so all ratio-4 entries built during generation, and at each prefill chunk boundary, lose the overlap. One-shot prefill, chunked prefill and token-by-token decode should give the same pool. That test needs no Python oracle.
  2. HISA on by default. index_block/index_keep aren't in the official or TensorFold configs, so 64/16 turns on an approximation the model wasn't trained with. In decode, the most recent partial block can't be selected. I'd default to exact top-k and tile the exact path to bound prefill memory.

Could the 4.3 log-probability gap be HISA? Running both sides with index_block = 0 should tell.

Minor: the fallback compress_ratios doesn't match the official layout (it can just be required), the pool could grow in steps like KVCacheSimple instead of concatenating, and the RoPE tables can be built in init without the lock.

P.S.: mlx-vlm's generator wires memory by default (manage_wired_limit=True), which probably explains your 0.57 tok/s mystery.

- index_block / index_keep default to 0: exact top-k over the visible
  pooled entries, as DeepSeek's reference. HISA stays an opt-in mlx-vlm
  approximation; its trailing partial block is documented.
- The exact indexer path scores queries in tiles to bound the
  [B, H, L, P] scores; selections equal the untiled computation.
- compress_ratios is required; a configuration without it fails to
  decode instead of falling back to a guessed layout.
- The compressed pool grows in steps of 256 entries like KVCacheSimple
  and readers use its logical length.
- RoPE frequency tables are built in init for the known head widths;
  the lock is gone.
Ratio-4 compressors pool each window together with the first half of
the window before it (the reference's overlap_transform and its decode
kv_state[:, :ratio]). The port gave the first window of every call no
previous window, so chunked prefill and every decode-time ratio-4 entry
lost the overlap. The pool cache now keeps the raw kv/gate rows of the
last completed window and hands them to the next call; they are part of
the cache state and its copies. Only the first window of the sequence
has no previous window, so the pool no longer depends on how the tokens
are split into calls.

Also fix the window buffer for a multi-token call that completes no
window while rows are already buffered: it now appends every row of the
call instead of slicing from a negative start.

The tiny fixture's mlx-vlm oracle has the old behaviour, so its
teacher-forced and token-iterator parity tests now differ on cases with
chunked prefill or decode-time ratio-4 entries.
The oracle now comes from DeepSeek's inference/model.py, imported unmodified
on a float32 CPU shim of its kernel.py (activation quantization identity),
instead of mlx-vlm. The generator takes --reference-dir, writes the weights
with a NumPy MXFP4/MXFP8 quantizer that matches MLX bit for bit
(check_mxfp.py), and gives every hash-routing row distinct experts. Seed 26
passes the margin rule; tolerance 9.5e-05.
Match where DeepSeek's reference model.py computes in float32 and where it
stays in the activation dtype:

- RMSNorm in float32 with a float32 weight, rounded once
- compressor projections, buffered rows, softmax and pooling in float32,
  entries cast back before the norm
- router matmul in float32
- expert SwiGLU in float32; routed and shared outputs summed in float32
- sparse pooled attention scores, softmax and sink in float32
- logits as a float32 projection
- query head normalization and exact indexer scores in the activation dtype

Float32 runs are unchanged. A bfloat16 test checks overlap pooling and
router weights against the same computations done in float32.
The logits head, the compressor projections and the router weight are
float32 parameters in the reference. sanitize now casts them to float32
when the checkpoint holds them dense (no scales), so the forward pass
does not cast them each step. Quantized modules are left as they are and
keep the cast at use, which is also the path if a caller later casts
these weights to another dtype.

A test loads the bfloat16 tiny checkpoint, checks which parameters are
float32, and compares prefill and decode logits with the cast-at-use
path exactly.
@Augustas11

Copy link
Copy Markdown
Contributor Author

Thanks @aleroot. You are right on both points, and both came from the same mistake: I ported from mlx-vlm and tested against mlx-vlm, so its differences from DeepSeek's inference/model.py came along and no test could see them. I have pushed five commits (d849fe4, 3c56fb1, 89b68d3, 45f6efb, 7324f75).

1. Overlap compression. DeepseekV4PoolCache now keeps the previous window (keys and gate) and the ratio-4 compressor reads it, as Compressor does with kv_state[:, :ratio]. Only the first window of a sequence has no previous window. The test you described is in: one-shot prefill, uneven chunks and token-by-token give the same pools and the same logits on the tiny model, for ratio-4 and ratio-128 layers (largest difference 6.0e-6 in the pools and 5.3e-6 in the logits; the test bounds are 1e-5 and 1e-4). Writing it also exposed a bug of mine: a multi-token call that completed no window while rows were already buffered sliced from a negative index. That is fixed and covered.

2. HISA. index_block and index_keep now default to 0, which is exact top-k as in the reference. The exact path is tiled over the query length to bound prefill memory, with a test that tiled and untiled selections are identical. The block selection is still there for a config that sets the two fields, documented as an mlx-vlm approximation that never selects the trailing partial block. I am happy to delete it instead if you would rather not carry it.

Minor points. compress_ratios is required (a config without it fails to decode). The pool grows in steps of 256 with a logical length. The RoPE tables are built in init and the lock is gone.

3. Float32 placement, which you did not raise. Checking the port against model.py instead of mlx-vlm showed a third difference of the same kind: the reference computes several steps in float32 where the port used the activation dtype. I went through the places where model.py pins or changes precision and made the port follow most of them (45f6efb): the RMSNorm, the compressor (its comment says "compression need fp32"), the sparse-attention scores and softmax, the router, the expert SwiGLU, the expert sum and the output head now run in float32, and the index score and the query norm, which the port had in float32, now run in the activation dtype as the reference does. The head and compressor weights are float32 parameters in the reference, and the router weight is cast to float32 on every call there; the port stores all three in float32 at load when they are not quantized, so none is cast per token (7324f75). That raises the resident weights from 156.2 to 158.0 GB, and with them the wired limit a caller should pass. A new bfloat16 test of the compressor and the router fails without the change; the other steps have no bfloat16 test. Not followed: RoPE (MLX rotates in the activation dtype, the reference in float32); attention wherever MLX's SDPA is used, including its sinks: always on the window-only and ratio-128 layers, and on the ratio-4 layers until their pool exceeds index_topk (only that top-k path has float32 scores); the kernel's bfloat16 rounding of the exponentiated scores before the value product (the port keeps float32 there); and the routing weight, which the reference applies before w2 and the port after. The hyper-connection kernel is unchanged. In float32 all of this is a no-op: the parity result is unchanged.

This one costs speed and memory, see the table below. If you prefer the faster placement for some of these steps, tell me which and I will change them back.

The fixture now comes from DeepSeek's code. make_tiny_fixture.py --reference-dir <inference folder> imports model.py unmodified and generates the oracle from it, with new seeded weights. The Swift parity test agrees with it within 5.7e-6 on a base M5 (debug) and 6.2e-6 on an M3 Ultra (Release). The tolerance is 9.5e-5, set by the generator's rounding rule (it was 7.2e-5 with the old fixture). 18 tests, 1 skipped, 0 failures on both. Its limits:

  • kernel.py is replaced by a small CPU re-implementation (in tools/deepseek_v4_parity/reference_shim), and the model is built and run in float32 on the CPU. The generator's docstring lists every patch.
  • So it checks the reference's arithmetic in float32, not its bfloat16 kernels. I ran the real kernel.py kernels on an RTX 5080 against a CPU version of mine that includes the quantization: act_quant, in-place fp4_act_quant and fp4_gemm are bit-identical. fp8_gemm is bit-identical in 16 of 20 cases; in the four full-size cases with 249 rows, 3 to 11 elements out of 255 thousand to 1 million differ, by at most 0.1% of the largest output. hc_split_sinkhorn agrees within 2.4e-7. sparse_attn differs by at most 0.3 to 0.6% of the largest output, about one bfloat16 step at that size; the kernel rounds the exponentiated scores to bfloat16 before the value product, which I take to be the cause. It was checked up to full width with 16 heads. fast_hadamard_transform would not install there, so that one is not checked.
  • Activation quantization and the Hadamard rotation are left out on both sides (see the question below).
  • The three HISA cases patch mlx-vlm's block selection into the reference indexer, because the reference has no HISA. The three exact top-k cases use the reference's own indexer.

With deliberate errors put into the port, the tests fail: overlap carry reverted, one expert index changed, and the overlap gate dropped are each more than 10,000 times the tolerance; 19 Sinkhorn iterations instead of 20 is 3.8 times. I ran those four at 89b68d3, before the float32 commits.

Full size (M3 Ultra, same setup as in the description, one run per cell; three runs on the same day):

Decode 1K / 8K / 32K TTFT at 32K Peak MLX memory at 32K
As opened 29.8 / 26.8 / 26.5 tok/s 93.1 s 160.2 GB
After points 1 and 2 (89b68d3) 29.5 / 27.8 / 26.4 tok/s 102.1 s 160.5 GB
After float32 placement (7324f75) 27.5 / 25.9 / 24.8 tok/s 106.0 s 166.2 GB
mlx-vlm, same session as the last row 31.5 / 28.2 / 27.7 tok/s

Points 1 and 2 moved decode by -0.9%, +3.7% and -0.2% and added 9.7% to TTFT at 32K, most likely the exact top-k in prefill; I have not separated it from the overlap change. The float32 placement costs 6.0 to 6.8% of decode, 3.8% more TTFT at 32K and 5.7 GB of peak memory at 8K and 32K (2.2 GB at 1K). I have not measured which of its steps carries the cost.

The 4.3 gap. I do not think it is HISA alone. As opened, the gap against mlx-vlm was 2.06 at 1K, 4.31 at 8K and 4.13 at 32K. At 1K the ratio-4 pool has 256 to 259 entries in the compared steps. That is below index_topk (512) and below the 1,024 (index_block * index_keep) where HISA starts in both the port and mlx-vlm, so neither side selected anything there, and the gap was already 2.06. It is now 2.35, 3.09 and 4.40, with the port differing from mlx-vlm in three more ways. I have not run mlx-vlm with index_block = 0; I can if it is still useful now that mlx-vlm is not the yardstick.

One more thing I have to correct. The full-size greedy tokens are still 256 of 256 equal to mlx-vlm after all of this, and equal to what the port produced as opened. So that comparison cannot see any of these changes: my prompt is a repeated block of text and the continuation is repetitive (51 distinct tokens in 256). It was a weak check and I should not have leaned on it. I have no full-size reference that follows DeepSeek's code: inference/ needs CUDA, and on the RTX 5080 I have access to the 64-head sparse_attn kernel fails to launch (a shared-memory limit), and its 16 GB could not hold the model anyway. So at full size the port is checked only for speed and memory, and for greedy tokens equal to mlx-vlm's on that one prompt.

Wired memory. In my comparison I ran mlx-vlm without its wired limit: my oracle script (not in this PR; I can share it) calls generate_step directly, and I ran it with its --no-wired-limit switch, so mlx-vlm's wired_limit context was skipped. It still decoded at 31.5 tok/s, so I do not think the default wiring explains why Swift needs the limit. That is still open.

Two things I found in model.py that I would like your view on.

  1. Activation quantization. The reference rounds the non-RoPE dimensions of the window KV to FP8 on every layer ("FP8-simulate non-rope dims to match QAT"), does the same to the compressed attention entries, and applies a Hadamard rotation plus FP4 rounding to the indexer's keys and queries. It also rounds the inputs of its FP8 and FP4 linears. This port does none of it, and I did not find it in mlx-vlm 0.7.10 either. I could not size its effect. On a tiny random model with the real kernels in bfloat16, switching all of the reference's quantization on (FP8 and FP4 linears with input rounding, KV and compressed-entry rounding, indexer FP4 rounding, with a float32 stand-in for the Hadamard kernel) moves the first-step log-probabilities by 1.2 to 1.6. With all of it off, swapping only the real sparse_attn and hc_split_sinkhorn for my re-implementations in the same bfloat16 model already moves them by 0.4 to 0.7. A tiny random model is too sensitive to tell. Do you want it in this PR, as a follow-up, or left out?
  2. A repeated expert in a hash-routing row. The reference's y[idx] += ... keeps one contribution when a row lists an expert twice; the port adds both. The TensorFold MXFP4 conversion has no such row (0 of 387,840 rows in its three tid2eid tables), so I left the port as it is and made the fixture's rows distinct.

Full suite on the M5 at the new head: 995 XCTest run, 9 skipped, and the same failing tests as on main. I will rewrite the description to match, since its mlx-vlm comparison no longer describes what the code does.

Augustas from Malibu

@aleroot

aleroot commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

@Augustas11 I see you have been doing nice work, however, I think there is still room for improvement and we should be careful not to trade correctness for performance before understanding where the actual cost comes from.

On activation quantization, I would keep it for a follow-up, but it's worth investigating with real checkpoints(unfortunately I do not have a Mac Studio so I cannot really help you more). The Hadamard rotation and FP4 rounding should be considered together, since the rotation preserves dot products before quantization. I would also keep the current duplicate-expert accumulation rather than reproduce PyTorch's indexed update semantics.

Performance-wise, I think the biggest opportunity is in the sparse attention and indexer paths. We are materializing fairly large intermediate tensors and promoting them to FP32. A fused Metal implementation could reduce memory traffic significantly while preserving FP32 accumulation where it matters. I would profile those paths before reverting any precision changes. Also, storing BF16 checkpoint weights as FP32 doesn't recover precision, so that's another area worth measuring.

If this is going to speed up even further, you're making me tempted to buy a Mac Studio as well, because these are starting to look like interesting numbers... I just need to find the budget first! 😅

@aleroot

aleroot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Another thing: this work would potentially pair with my #708, which keeps lookup tables on disk and reads only the rows a token uses. For V4-Flash that's only the 1 GB embedding, but it matters for V4.1-Flash, whose Engram n-gram tables are about 203 GB in Big-MoE's EXL3 conversion.

The next step would be doing the same for experts. Of the 158 GB, routed experts are about 147 GB, and a token reads only about 3.45 GB of them (6 per layer). With an expert cache in memory and the rest read from SSD, as Big-MoE-Small-Box does, it could run on a 96–128 GB Mac Studio, at a speed that depends on how often experts are reused. Your 0.57 tok/s run without a wired limit shows that OS paging alone won't do it.

@Augustas11 if you could log how often consecutive tokens reuse the same experts on your Mac Studio, that would tell us whether this is worth building. It would also tell me whether a Mac Studio Ultra with 96 GB would be enough, or whether I need more memory. Thank you.

@aleroot aleroot mentioned this pull request Nov 14, 2026
9 of 19 tasks
The reference's RMSNorm weights are float32. Like the head, compressor and
router weights, they are now kept in float32 at load, so the norm's cast of
its weight is a no-op on every call instead of one dispatch per norm. The norm
still casts at use, so a weight set to another dtype works as before. bfloat16
to float32 is exact: the values are the same.
Same ops in the activation dtype as before, each rounded as when run one by
one: on the GPU they run as one compiled graph, so the steps after the
reduction fuse into one kernel. The mean is written as its sum times
1 / head_dim so the traced graph holds a constant. The CPU keeps the plain
ops, since its compiled float32 kernel rounds differently.
The two compressors of a ratio-4 layer project the same float32 copy of the
layer input instead of casting it twice. When a window completes, the pooled
entries' round trip through the input dtype runs as one kernel and the norm
takes the float32 result directly, through a norm entry point for float32
inputs. The values are the same as before.
MLX looks up a compiled graph by function id, input shapes and dtypes and the
C++ default stream. Device.withDefaultDevice changes only the Swift
task-local default, so a function traced under the CPU replays its CPU
kernels when called under the GPU, and the other way round. Each compiled
function is now built once per device type and picked by the current
default device.
A norm weight set with update(parameters:) after a forward pass gives
exactly the logits of a fresh model with that weight.

float32 logits on each device are bit for bit the same whether or not the
other device ran first. Each run starts on a new thread, whose MLX compile
cache is empty, so the check does not depend on what ran earlier in the
process. Skipped without a GPU.
@Augustas11

Copy link
Copy Markdown
Contributor Author

@aleroot thanks, both comments were useful. I profiled before touching any precision, as you said, and logged the expert routing you asked for. Everything below is on the M3 Ultra (256 GB) with the MXFP4 conversion unless it says otherwise.

1. Where the cost of the float32-placement commit comes from

One model load, greedy, 256 decode steps, two rounds per cell. Each row turns one step of that commit back to what it was before and leaves the rest as in the PR. For most rows that means the activation dtype instead of float32. For the query norm it means the fused MLXFast.rmsNorm instead of separate ops in the activation dtype, and for the index score it means float32 again. Baseline was 27.51 tok/s at 1K and 25.53 at 8K.

Step turned back Decode at 1K Decode at 8K Other
All of them +6.5% +7.2% peak -2.2 GB / -5.7 GB
RMSNorm +2.7% +1.9%
Query norm +1.8% +2.2%
Compressor +5.1% +3.8% TTFT +20% at 1K, +8.6% at 8K (see below)
Sparse-attention scores path not active (pool below index_topk) +0.8% at 8K: TTFT -5.1%, peak -3.4 GB
Expert sum +0.1% +0.9%
Expert SwiGLU, index score within ±0.5% within ±0.5%
Head, compressor and router weights cast per call instead of stored float32 -12.8% -11.3%

Three things I take from it:

  • The decode cost I can attribute is in the two norms, not in the sparse attention. At 8K the sparse-attention scores cost 0.8% of decode (+1.1% and +0.5% in the two rounds), less than half of either norm. They do cost prefill time and memory at long context, so that is where a fused kernel would pay: TTFT and peak, not tok/s. The router and the head are not in the table: with their weights stored in float32, turning either back alone changes nothing.
  • The compressor row is not a clean number. From the code, with that step turned back the pooled entries come out float32 (its weights are stored float32), and that promotes the hidden state to float32 in the layers after it. I did not log a dtype in that run, but the worse TTFT fits. So the row measures a different model, and I do not have a clean compressor cost.
  • On storing the head, compressor and router weights in float32: agreed that it recovers no precision. bfloat16 to float32 is exact, so the stored copy and a per-call cast give the same result. It is only there to avoid the cast, and that is worth 11 to 13% of decode for 1.8 GB.

2. What I changed, with no precision change

Four commits, pushed now (53b39aa, fb74094, 7fda001, ca80ba9), with two tests in b11433c:

  • The RMSNorm weights are kept in float32 at load, like the three above, so the norm no longer casts its weight on every call (235 tensors, 0.9 MB more).
  • The query-head normalization is one compiled function on the GPU.
  • The two compressors of a ratio-4 layer share one float32 cast of their input, and the round trip through the activation dtype is one kernel.
  • The compiled functions are built once per device type (see 3).

Checked on the M3 Ultra against logits captured there from the code before these commits, tiny model, bfloat16 and float32, in a process that runs the CPU cases and then the GPU cases, 30 iterations: the first three commits change no bit (360 of 360 comparisons). I have no GPU-only capture of the code before the commits, so in float32 the GPU side of that check is subject to what section 3 describes. At full size, same window, same method as the table:

Decode at 1K Decode at 8K TTFT at 8K Peak at 8K
PR head 27.73 tok/s 25.81 tok/s 24.34 s 166.0 GB
With the four commits 28.71 tok/s (+3.5%) 26.32 tok/s (+2.0%) 24.34 s 166.0 GB

Greedy tokens are equal in both, with the caveat from my last comment that this prompt is a weak check. The four commits recover about half of the float32-placement commit's cost at 1K and less than a third at 8K. Peak at 1K went from 159.96 to 160.14 GB, which I have not explained. These full-size numbers and the bit checks were run on my local profiling branch, which carries the same four commits plus profiling switches that are off by default; the commits as pushed have so far only run the tiny tests on the M5 (20 tests, 1 skipped, 0 failures). What is left in the norms is the cast of the input and output around MLXFast.rmsNorm; removing it needs a fused float32-accumulating norm kernel, which I have not written.

3. A device-order problem I found on the way

The PR's compiled functions (hyper-connection expand and Sinkhorn, the expert SwiGLU, the two compressor functions) are traced once and replayed. MLX looks a compiled function up by the C++ default stream, and Swift's Device.withDefaultDevice does not change that stream, so a function first traced inside a CPU scope replays its CPU kernels when it is later called inside a GPU scope on the same thread. On the M3 Ultra a GPU-only process and a CPU-then-GPU process give different float32 logits on the tiny model (88 to 92% of elements, by at most 3.6e-6; bfloat16 is identical; measured with the first three commits applied). It is small, but the device a caller asked for is not the one that runs. The fourth commit builds one compiled function per device type; with it the GPU logits are bit-identical whichever device ran first, and a GPU-only process is unchanged bit for bit. There is a test for it that fails without the commit (512 of 512 logits differ, on the M5), and one that a norm weight changed with update(parameters:) reaches the next forward.

Two things from my base M5, neither caused by the device-order problem:

  • On the M5 the tiny model's float32 GPU logits differ from its CPU logits by 1.0 to 1.4 (on the M3 Ultra by about 1e-5). That is MLX's TF32 path for float32 matmul-family ops, which is on by default on that GPU: with MLX_ENABLE_TF32=0 the same binary agrees with the M3 Ultra's GPU logits within 2e-6 (float32 cases; the bfloat16 cases differ between the two GPUs by 1 to 3 with or without the switch, about the size of the bfloat16 GPU-versus-CPU gap on either machine, so I have not isolated what TF32 does to the bfloat16 model). It is not specific to this port, but it means the float32 steps run at TF32 precision on an M5 unless that is switched off, and a float32 GPU parity check there needs the switch. The PR's tests do not see it because the parity tests pin the CPU.
  • NaN. On 14 November the tiny GPU bit-identity test returned NaN in 5 of 28 runs on the M5; I did not record which work-in-progress tree each ran. Today on the M5: 0 in 26 GPU iterations on the default path, and 3 in 16 when I replace the fused hyper-connection kernel by the plain-op path on the GPU (a path the real model does not take on the GPU). On the M3 Ultra: 0 in 13 thirty-iteration loops, three of them on the plain-op path (those three ran the CPU cases first, while the M5 NaNs today came from GPU-only processes). I have not found the cause.

4. Expert reuse

I recorded the selected experts for every layer and token on five workloads (an English explanation, a second unrelated turn in the same chat, a coding task, a Chinese question, and a question after about 8K tokens of mixed documents), greedy, 512 decode tokens each. Limits first: the conversion has no chat template, so the prompts use a hand-written DeepSeek V3 style non-thinking format (the outputs read as normal answers); 512 tokens is short; and the cache numbers are a simulation, I did not build anything.

Sizes, from the loaded arrays: 157.9 GB total, 147.2 GB routed experts, 10.8 GB shared. One expert is 12.75 MiB, and a token selects 258 of the 11,008 (6 in each of 43 layers), 3.45 GB. Your figures were right.

Experts shared with the previous token, decode 38% on average (2.3 of 6 per layer)
The same, 40 score-routed layers 40%
The same, 3 hash-routed layers (0 to 2) 2.4%, which is chance (6/256)
Distinct experts touched in 16 / 64 / 256 / 512 decode tokens 19-24 / 42-53 / 72-87 / 87-102 GiB
Share of all experts touched in 512 decode tokens 64 to 74%
Share touched by prefilling the 8K-token prompt 99.6% (136.5 of 137.1 GiB)

LRU over single experts, decode only, with the shared weights resident and 8 GiB left free (budgets read as GiB):

Machine Expert cache Hit rate, cache empty at first decode token Hit rate, cache warm from the prompt Reads per token (warm)
64 46 GiB 84-90% 85-92% 21-38 experts, 0.26-0.47 GiB
96 78 GiB 92-95% 95-97% 8-13 experts, 0.10-0.16 GiB
128 110 GiB 94-95% 97-98% 4-7 experts, 0.05-0.09 GiB

How I read it for your question. The reuse between neighbouring tokens is real but partial, and the set of experts in use keeps growing: after 512 tokens it is already larger than a 96 GB machine's cache, and it was still growing when the runs stopped, so the 96 GB misses do not die out: in the last quarter of each run a 96 GB cache still reads 5 to 11 experts per token (63 to 148 MB), and that rate had stopped falling between the third and the last quarter in four of the five runs, while at 128 it was still falling. At 128 the cache is larger than what any of these 512-token generations touched, so most of its misses are first touches, except after the 8K prompt, where they are re-reads of experts the prefill pushed out. On whether 96 GB is enough: over 512 tokens 96 and 128 differ little (95-97% against 97-98% warm), and at 96 each token waits for roughly 60 to 150 MB of expert reads once the cache has filled, more at the start. Whether that is fast enough depends on the read speed, which I did not measure, so I will not turn it into tok/s. Two cautions. Long prompts are the harder case: an 8K prefill touches nearly every expert, so prefill would read almost the whole 147 GB at least once whatever the cache size. And the 8 GiB I left free is tight at long context: at 8K the measured peak is 8.1 GB above the weights. The three hash-routed layers have no locality between neighbouring tokens (their experts follow the token id); they are 9.6 GiB together.

I can run longer generations, or other prompts if you have a set you care about, and I can share the per-token traces (a few MB) and the script that produced these tables.

On your other two points: agreed on both. Activation quantization stays out of this PR as a follow-up, with the Hadamard rotation and the FP4 rounding taken together, and the duplicate-expert accumulation stays as it is.

Next from my side, if you agree: a fused kernel for the norms (decode) and for the sparse-attention path (TTFT and memory at long context) as separate steps, each compared against the current float32 results with the differences reported.

Augustas from Malibu

MLX's sorted gathered quantized matmul reads past the last weight column on
some GPUs when the reduction width is not a multiple of 64. The fixture's
expert down projection has width 32, so a GPU forward over 16 or more tokens
can turn the last output column NaN, depending on the memory after the
weights. Feeding the 300-token prompt in chunks of 7 keeps every expert call
at 14 routes, below the 16 at which SwitchGLU sorts them; the ratio-4 and
ratio-128 windows still complete.
@Augustas11

Copy link
Copy Markdown
Contributor Author

A correction to my last comment, on the NaN from the M5. I have the cause now, and part of what I wrote does not hold.

What does not hold. I reported the NaN in 3 of 16 GPU iterations when the fused hyper-connection kernel was replaced by the plain-op path, and in 0 of 26 on the default path. That split did not hold up. In longer GPU loops of the same tiny-model check (TF32 off, so only the bfloat16 cases take the kernel described below), the default path gave NaN in 25 of 150 iterations and the plain-op path (three variants of it) in 18 of 120. The hyper-connection code has nothing to do with it.

The cause is in MLX. On an M5-class GPU the sorted gathered quantized matmul (what a quantized SwitchLinear runs once the routes are sorted) reads weight columns past K when K is not a multiple of 64. For the last weight row that read goes past the end of the buffers, and if the bytes there decode to NaN or Inf, the last output column becomes NaN for the routes on the last expert. Whether that happens depends on what lies after the buffers, hence the intermittency. MLX selects that kernel for sorted one-row inputs once there are at least 4 routes per expert (32 routes with this fixture's 8 experts, so 16 tokens), in bfloat16 or in float32 with TF32 on, which is the default. The tiny fixture's expert down projection has K = 32, so a GPU forward over a chunk of 16 or more tokens can hit it.

Evidence:

  • In the model, in the 6 events I probed layer by layer, the first NaN was in the MoE branch output, and the chunk had 16 or more tokens every time.
  • With the M5's kernel family switched off (MLX_METAL_GPU_ARCH=applegpu_g16g) the same loops gave 0 NaN in 180 iterations (one of the three loops with TF32 on). On the CPU, 0 in 30.
  • Without any model, at the mlx commit that mlx-swift 0.33.0 pins (36969c0), sorted gatherQuantizedMM with E = 8, N = 64, K = 32, 96 or 160 and 32 or 128 routes: when the weights are a slice of a larger array whose next expert has NaN scales, the output has NaN in all 24 bfloat16 cells (28 to 30 of 30 trials each), and in all 24 float32 cells with TF32 on, for mxfp4, mxfp8 and affine 4-bit and 8-bit. With plain random arrays it is intermittent: 5 of 24 bfloat16 cells (22 of 720 trials, none of them mxfp4) and 14 of 24 float32 cells with TF32 on (116 of 720). Never for K = 64, 128 or 2048, for 16 routes, for unsorted routes, for float32 with TF32 off, or with that kernel family off. Every NaN is in the last output column, and no other element is off beyond rounding.

It is in the same K tail as ml-explore/mlx#3887; the fix for that (ml-explore/mlx#4009) bounded the activation tile by the K remainder, and the weight tile still is not. I have not run mlx main; the two kernel bodies and their loaders are the same there as at 36969c0. I found no existing report of it, so I will file one on mlx with the model-free reproduction.

What it means for this PR.

  • The real checkpoint is not exposed: its expert projections have K = 4096 (gate and up) and 2048 (down).
  • One test ran the tiny model on the GPU over a long chunk, the device-order check (300-token prefill), so it could fail at random on an M5. It now prefills in 7-token chunks, which keeps the expert call below the sorted path (b516e59). It still fails without ca80ba9 (512 of 512 logits differ) and passed 11 of 11 runs on the M5. I did not reproduce the NaN in that test before the change, so that the chunking avoids it rests on the code path, not on a failing run.
  • The other tests run the model on the CPU. The fused-kernel test runs only the hyper-connection module on the GPU.

One more data point on the bfloat16 gap between the two GPUs that I mentioned: with the M5's kernel family switched off, the M5's bfloat16 GPU logits on the tiny model are bit-identical to the M3 Ultra's. So that gap comes from that kernel family and not from the port. In the model-free runs the sorted kernel agrees with the unsorted one within bfloat16 rounding whenever no NaN appears, so I do not think it is this bug, but I have not found which kernel it is or whether it is only rounding.

Augustas from Malibu

@Augustas11

Copy link
Copy Markdown
Contributor Author

Four results from a second session on the M3 Ultra, 15 November. They cover three things I had left open (longer expert traces, the PR branch's tests on the M3 Ultra, the norm kernel) and re-measure against mlx-vlm. Still open from my earlier comments: the mlx issue for the gathered-matmul read, the bfloat16 difference between the two GPUs, the 1K peak, and the sparse-attention kernel I proposed, which I have not started.

1. Longer expert traces. The 512-token runs were too short to show what a 96 GiB machine's cache settles to. I reran the five workloads with a 4,096-token cap (the second turn now follows the complete first answer, so it is not the same generation as before). Four answers ended on their own (2,328, 743, 1,871 and 1,432 decode tokens); the coding task ran to the cap.

512-token runs Longer runs
Experts shared with the previous token, decode (pooled; per run) 38%; 34 to 43% 35%; 30 to 41%
Share of all experts touched by the decode tokens of one generation 64 to 74% 70 to 88% (96 to 121 GiB)
96 GiB machine, warm cache: hit rate 95-97% 95-98%
96 GiB machine: reads per token in the last quarter 5-11 experts, 63-148 MB 5-12 experts, 66-154 MB
128 GiB machine: reads per token in the last quarter 2.1-3.4 experts, 28-46 MB 0.4-2.5 experts, 5-33 MB

The 96 GiB reading holds with more data; the 128 GiB one changes. At 96 GiB the reads level off at about 5 to 12 experts per token in four runs; in the long English answer they rose again in the last quarter (6.0, 6.7, 9.5 over the last three quarters). With a warm cache, 66 to 100% of the last-quarter reads are re-reads of experts the cache had dropped, not first touches. At 128 GiB they drop to 0.4 to 2.5 experts per token. Two runs were still falling at the end; in the other three the last quarter was level or higher than the third. Four of the five generations now touch more than the 110 GiB cache, and in those three runs 39 to 100% of the last-quarter reads are re-reads. The decode tokens of the five generations together touched 99.3% of all experts, so across a varied session nearly every expert is needed sooner or later. Same limits as before: the cache is simulated, the prompts use my hand-written chat format, and I did not measure read speed.

2. The PR branch on the M3 Ultra. At b516e59, Release: 20 tests, 1 skipped, 0 failures, and 0 failures in 10 further iterations of the class. That covers the two tests I had only run on the M5.

3. A fused norm kernel, measured. I wrote the kernel I mentioned for the cast around MLXFast.rmsNorm: one Metal kernel that reads the activation dtype, accumulates in float32 and writes the activation dtype. It follows MLX's own rms_norm kernel step by step. Result:

  • Bit-identical to the current path at every norm width the model uses (powers of two up to 4096), on the M5 and the M3 Ultra, and the tiny model's GPU logits do not change in any of 60 comparisons on the M3 Ultra (6 cases, 10 iterations). At some widths that are not a power of two (37, 1001 and 4095 of those I tried) the float32 output differs by at most 1.4e-6 in up to 65% of the elements, with the same counts and the same largest difference on both machines; bfloat16 and float16 outputs do not differ. So the kernel is only used for power-of-two widths and the rest keep the current path. I have not found out why those widths differ.
  • Gain at full size, one model load, two rounds: +0.56% decode at 1K and +1.3% at 8K.

The norm row of the split was 2.7% at 1K and 1.9% at 8K, measured before 53b39aa. 53b39aa then removed the weight cast; the kernel recovers a further 0.56% and 1.3%: little at 1K, about two thirds of the row at 8K. It is not in the PR. I can add it if you think a second custom kernel is worth that much; my own view is that it is not, on these numbers.

4. Full size against mlx-vlm in the same window. Same setup as the table in the description, one run per cell; mlx-vlm ran as a separate process about 15 to 30 minutes after the Swift cells. The Swift numbers are from my local branch, which carries the PR's library changes plus the norm kernel from point 3 and the profiling and tracing hooks (off):

Prompt Swift decode mlx-vlm decode Swift TTFT Swift peak
1K 28.7 tok/s 31.8 tok/s 2.5 s 160.1 GB
8K 26.4 tok/s 28.3 tok/s 24.3 s 166.0 GB
32K 25.5 tok/s 27.5 tok/s 106.0 s 166.2 GB

With the kernel switched off on the same branch (the mean of the two rounds in point 3; not the PR branch itself) decode was 28.45 tok/s at 1K and 26.09 at 8K; 32K was not measured that way. That is 10.4% below mlx-vlm at 1K and 7.8% at 8K, against 12.9% and 8.2% at 7324f75. The same library code without the kernel measured 28.71 and 26.32 in the first session, about ten hours earlier, so sessions differ by about 1%, which is more than the kernel gains at 1K. mlx-vlm ran without its wired limit, as before.

I am now looking at where the remaining decode time goes relative to mlx-vlm, one decode step side by side, before changing anything else.

Augustas from Malibu

@aleroot

aleroot commented Nov 15, 2026

Copy link
Copy Markdown
Contributor

Thanks @Augustas11, the longer runs are very useful...

If you still have the traces, two things would settle it:

  1. Misses per token for expert caches from 40 to 130 GiB, not just three sizes (LRU stack distances give all of them in one pass).
  2. If you run layer l+1's router on layer l's FFN input, how many of its 6 experts does it get right? That's how Big-MoE prefetches, and it tells whether misses can be hidden.

On the norm kernel I agree, on these numbers it's not worth a second custom kernel.

@Augustas11

Copy link
Copy Markdown
Contributor Author

Both done, on the same five 4,096-cap workloads as the longer runs above. I reran them for the prediction; the expert ids of the rerun are byte-identical to the earlier traces, so the two parts describe the same generations.

1. Misses per token from 40 to 130 GiB. One pass of LRU stack distances over the decode tokens. Every (layer, expert) unit is the same size here (13,369,344 bytes), so the stack distance is exact, and it matched a direct LRU simulation in all 110 cases I compared (5 workloads, cold, warm and the second turn after its first, 10 sizes). I took 40 to 130 GiB as machine sizes, as before: the cache is what is left of the machine after 8 GiB headroom and the 10.04 GiB of shared weights, so the cache column runs from 22 to 112 GiB. Pooled over the five workloads, cache warm after the prompt (for the second turn that is its own prompt only, not the first turn):

Machine GiB Cache GiB Reads per token, all decode MB per token Reads per token, last quarter MB per token
40 22.0 73.7 985 75.9 1015
48 30.0 54.9 734 56.3 753
56 38.0 40.7 544 42.1 563
64 46.0 29.3 392 31.3 418
72 54.0 21.1 282 22.3 298
80 62.0 14.7 197 15.0 201
88 70.0 10.4 139 10.2 137
96 78.0 7.3 97 7.0 94
104 86.0 5.2 70 4.8 64
112 94.0 3.8 51 3.1 41
120 102.0 2.9 39 1.9 25
128 110.0 2.4 32 1.0 14
130 112.0 2.3 31 0.9 12

A token routes to 258 experts (43 layers, 6 each), so 73.7 reads at 40 GiB is 29% of them. Last-quarter reads fall below 12 per token from an 85 GiB machine, below 5 from 104, below 2 from 120 and below 1 from 129. Above the table little changes: a 120 GiB cache reads 2.1 experts per token (0.6 in the last quarter) and a 130 GiB cache 2.0 (0.5). With no cache limit the reads are 1.9 per token over all decode and 0.5 in the last quarter, all first touches. All routed experts together are 137.1 GiB. Per workload the last-quarter figure spans 21.6 to 40.1 at 64 GiB, 4.9 to 11.5 at 96 and 0.4 to 2.5 at 128. I have the table in 1 GiB steps if you want it.

2. Layer l+1's router on layer l's FFN input. "Layer l's FFN input" can be read three ways in this model, because each layer first collapses the 4 residual streams with its own mixer and then applies its own norm before the gate. I recorded all three:

  • A: layer l+1's gate on the tensor layer l's gate sees (after layer l's mixer and norm).
  • B: layer l+1's norm and gate on layer l's collapsed FFN input (after layer l's mixer, before its norm).
  • C: layer l+1's mixer, norm and gate on the 4-stream residual that enters layer l's FFN block.

Layers 0 to 2 route by token id, so layer 3 is the first predicted target: 40 predicted layers per token. Decode tokens, pooled (418,800 token-layer pairs):

Predictor Right, of 6 All 6 right Per workload
A 4.10 9.1% 3.80 to 4.46
B 4.10 9.1% 3.80 to 4.46
C 4.38 14.6% 4.05 to 4.76
Same layer's experts at the previous token 2.23 0.7% 1.93 to 2.65
Layer l's own expert ids 0.14 0.0% 0.13 to 0.15

Chance is 0.14 of 6. The norm makes almost no difference (A and B agree within 0.02 at every layer); the mixer does. From target layer 19 up C is ahead at 21 of 24 layers, most at 19, 35 and 36 (5.05 against 2.62, 5.11 against 3.70, 5.11 against 3.51). Below layer 19 C is not better: the two are within 0.04 at 11 of the 16 layers, C is ahead at layer 3 (3.81 against 3.69) and behind at layers 4, 5, 9 and 14 (most at 5 and 14: 2.90 against 3.39, 3.92 against 4.37). By target layer A spans 2.62 to 4.81 and C 2.90 to 5.11.

What matters for hiding misses is whether the experts that miss the cache are among the predicted ones. With the same simulated LRU cache, warm after the prompt, decode tokens, pooled:

Machine Misses per token at predicted layers In A's 6 In C's 6
96 GiB 6.9 45% (3.1 per token) 51% (3.5 per token)
128 GiB 2.3 45% (1.0 per token) 51% (1.2 per token)

Per workload A covers 38 to 51% and C 44 to 57%. So a prefetch issued one layer early from the next router's top 6 would have about half of the missing experts in flight, and the other half would still be read on demand. The misses are harder to predict than the average expert (about 73% of all experts are predicted by C, 51% of the missing ones), which fits: a miss is an expert not used recently, and the previous token predicts none of them by construction.

Limits: I only stored each predictor's top 6, so I cannot say what a wider prefetch (top 12, say) would cover. The cache is simulated and never inserts predicted experts, so wrong prefetches cost nothing here. And I did not measure read speed. One layer of lead is about 0.8 ms at the 1K decode rate of my last comment (28.7 tok/s, 35 ms per token over 43 layers, everything in memory). Reading one 13.4 MB expert inside that would need about 16 GB/s, so one layer of lead shortens a miss but does not hide it.

The predictions are computed inside the forward on my local branch behind a trace hook; logits are bit-identical with it on and off (tiny model, CPU and GPU, bfloat16 and float32, on the M3 Ultra), and nothing of it is in the PR.

Agreed on the norm kernel; I leave it out.

Augustas from Malibu

The integration test imported Jinja, which the IntegrationTesting project does not link. It now downloads the pinned DeepSeek-V4-Flash tokenizer and renders each fixture case with applyChatTemplate(messages:chatTemplate:tools:additionalContext:), the path LLMModelFactory uses, and compares the tokens and their decoded text with the jinja2 output.
ThinkingBudgetProcessor threw unsupportedReasoningProtocol for ReasoningConfig.deepseekV4 unless the caller passed a transitionOverride. Declare .immediate, closing the span with </think> (token 128822) alone, as Qwen3.5 does: DeepSeek's encoder writes every reply straight after a bare </think>. The ThinkingBudget tests now run without an override.
@Augustas11

Copy link
Copy Markdown
Contributor Author

@aleroot, the review items are now implemented on this branch (updated with main).

  • Kernel (D % 4): static_assert(D % 4 == 0) in the hyper-connection kernel, Swift sends widths not divisible by 4 down the op path, with a unit test for the fallback.
  • kvCachePlan: newCache validates the plan and throws the existing typed errors for maxKVSize and KV quantization requests that DeepSeek-V4 cannot honour.
  • Trim and save: DeepseekV4PoolCache now implements isTrimmable, trim (bounded to the retained window), and state/metaState save and restore (with shape/offset validation on restore), registered for prompt-cache loading when the model is constructed.
    • Correction to my previous note on MTP: KVCacheStorage.beginRound already supports CacheList on main (via CacheListRoundStrategy). DeepseekV4LayerCache still expects RotatingKVCache rather than RotatingStagedKVCache, so MTP weight loading, staged-round wiring, and speculative decoding stay in a follow-up PR.
  • Tool calls (DSML): .deepseekV4 format, DSML parser, recovery scanner support for the missing opening token, and model_type == "deepseek_v4" format inference.
  • Reasoning: reasoningConfig with a string-valued thinking_mode prompt strategy and DeepSeek-V4's budget transition.
  • Chat template: fallback DeepSeek-V4 template (used only when the checkpoint template does not already prompt DSML, written without tojson for swift-jinja compatibility), with a fixture test in IntegrationTesting (DeepseekV4ChatTemplateTests) checking tokenizer rendering against DeepSeek's reference encoder.

Tests (release test build with compiled Metal library on M3 Ultra, at 8973e81):

  • swift test --skip-build --filter DeepseekV4: 27 executed, 2 skipped (MLX_DEEPSEEK_V4_LONG=1 gated), 0 failures.
  • swift test --skip-build --filter 'DeepSeekV4ToolCall|ChatTemplateOverride|ReasoningConfig|ThinkingBudget|ToolCallFormatInference': 106 executed (38 XCTest, 68 Swift Testing), 0 skipped, 0 failures.

(AI-assisted note; I checked the code and the test results.)

Augustas from Malibu

@aleroot

aleroot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

Thanks @Augustas11, nice job.

A few things before the next CI run:

  • Docs: verify-docs.sh fails because ChatConventionsProviding.chatTemplate links chatTemplate(replacingTemplateIn:), which is package.
  • Tokenizer API: instead of a new requirement whose default throws, a refinement like protocol ChatTemplateRendering: Tokenizer that the macro-generated adapters adopt, with overridingTemplate casting to it, would keep Tokenizer unchanged and make the capability visible in the type, like KVCacheDimensionProvider. cc @davidkoski

@Augustas11

Copy link
Copy Markdown
Contributor Author

@aleroot, both pushed and ready for the next CI run:

  • Docs (3afcaf3): switched the links to chatTemplate(replacingTemplateIn:) in ChatConventions.swift and ModelConfiguration.swift to code voice so verify-docs.sh does not try to resolve a package symbol.
  • Tokenizer API (74fb152, c243213): left Tokenizer unchanged, added public protocol ChatTemplateRendering: Tokenizer in Tokenizer.swift with applyChatTemplate(messages:overridingTemplate:...) casting self as? any ChatTemplateRendering, adopted MLXLMCommon.ChatTemplateRendering on the macro-generated TokenizerBridge, and updated ChatTemplateOverrideTests and DeepseekV4ChatTemplateTests.

(AI-assisted commits and note; I reviewed the diff.)

Augustas from Malibu

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

Copy link
Copy Markdown
Contributor Author

@aleroot, I merged current main into this branch (5b0316e), so it is ready for another CI run. The PR's own diff is unchanged.

The last run failed only in two Qwen3PrefillLogitsTests cases. It ran on a main from before #858, which fixes them.

The Reset CI state workflow is failing at startup on other PRs too, so this one still has the needs-changes label.

(AI-assisted merge and note.)

Augustas from Malibu

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants