Skip to content

model : add DeepSeek-V4.1-Flash-1017 (deepseek41), exact reference implementation - #289

Draft
danielhanchen wants to merge 10 commits into
base/upstream-797de63b2from
dsv41-slim
Draft

danielhanchen wants to merge 10 commits into
base/upstream-797de63b2from
dsv41-slim

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

Adds DeepSeek-V4.1-Flash-1017 (deepseek41) as a plain reference implementation: exact, unoptimized, and as small as the model allows. Performance work, quantized KV cache, the DSpark draft, the chat template and DSML tool-call parsing, and vision come as separate PRs stacked on this one.

The branch is based on upstream 797de63b2, which is tag b11716. The diff is only this change: 33 files, +1661/-51. The only ggml/ change is a gather-only MXFP8 type for the Engram table (see below).

What it adds

  • Architecture (src/models/deepseek41.cpp, reusing the DeepSeek-V4 loader and graph helpers):
    • Engram n-gram embedding on layers 1 and 14. The 2..4-gram hashes are computed on the host from the token history, and the rows are gathered from the table.
    • Single-pass mHC: each sublayer reuses the input-mix coefficients of the previous one. The HC mix computation is split out of build_hc_pre, and DeepSeek-V4 output is unchanged.
    • Compressed KV with ratios 1 and 2, with cross-layer KV, index-K and top-k sharing.
    • Lightning indexer with top-k 512, plus the two-level candidate block selection that masks the later layers.
    • Every compressed layer attends densely over [window | all compressed rows], with the top-k selection applied as a mask. This is the unfused reference path.
    • The indexer score, candidate blocks and top-k are computed per chunk of query tokens. This keeps the [index heads, tokens, rows] intermediate near 2^26 elements at long context, and short prompts run as a single chunk.
    • The router, HC and indexer matmuls request GGML_PREC_F32. Router weights are normalized by sum + 1e-20, as in the reference.
  • Engram table as per_layer_token_embd:
    • The tables of both layers are one tensor, per_layer_token_embd.weight [256, 768,022,850], with layer 1's rows first.
    • It is described by the same PLE keys as qwen4exp (ple.layers, ple.ngram_size, ple.heads_per_ngram, ple.layer_multipliers, ple.head_offsets, ple.head_vocab_sizes). Only the compressed token map and the pad token id are new keys.
    • The table is read lazily from the mapping, like the qwen4exp n-gram table: --lazy-mode auto is the default and applies to tensors over 4 GiB. Each ubatch prefetches the rows of both layers in one llama_prefetch_rows call.
  • KV cache (src/llama-kv-cache-dsv4.*):
    • Compress ratios come from the slot state instead of the V4 constants. For V4.1 the CSA slot is ratio 2 and the HCA slot ratio 1, without overlap and without the lightning-indexer cache.
    • The index K is stored next to the compressed KV, and only the KV source layers own rows.
    • The window cells keep their token ids, saved and restored with the state, so the n-gram history survives state save/load.
  • MXFP8 type (ggml/, gguf-py/): the OCP microscaling FP8 block, 32 E4M3 values with one E8M0 scale (33 bytes), as GGML_TYPE_MXFP8 = 43.
    • It is gather-only: CPU and CUDA support GET_ROWS from it, and supports_op refuses every other op, so any other use fails at scheduling.
    • It halves the table against the exact BF16 lookup (203 GB vs 393 GB) with identical dequantized values.
    • gguf-py has the type and a reference (de)quantizer; test-backend-ops covers GET_ROWS.
  • Converter (conversion/deepseek41.py):
    • FP8 32x32 linears are dequantized to BF16, which is exact.
    • Routed experts are copied bit-exact as MXFP4.
    • The Engram tables are copied bit-exact as MXFP8 (the checkpoint stores e4m3 rows with one e8m0 scale per 32 elements). DSV41_ENGRAM_TYPE=bf16 writes the exact BF16 lookup instead, streamed in bounded chunks.
    • The router and Engram gate stay F32.
    • --outtype f32 keeps every dense tensor in F32 (and the table too with DSV41_ENGRAM_TYPE=bf16).
    • The chat template is the one shipped with the model. The inherited DeepSeek-V4 default template is not written, since V4.1 does not use it.
  • Tests:
    • test-llama-archs gets a 6-layer config covering window-only, Engram, ratio-2 and ratio-1 KV sources, top-k reuse and a candidate-masked index layer. The model saver writes the new keys, and the round trip is covered.

Verification

All results are local, on B200 (CUDA sm_100a) and x86 CPU.

  • Converter:

    • The real checkpoint converts to 698.8 GB with the BF16 table; with the MXFP8 table the model is 508 GB (the published UD-Q8_K_XL).
    • 12,480 sampled Engram rows match the official e4m3 * 2^(e8m0-127) lookup bit for bit. The sample covers both tables, all 24 hash columns, and the first and last rows. A seeded off-by-one fails the check.
  • Fixture gates on CPU against the official F32 reference (model.py, matched precision):

    • The fixture has 14 layers, F32 weights, the real tokenizer and Engram map, and every mechanism active inside the prompt.
    • With prompts of 100 to 3,001 tokens and ubatch 1, 7 and 512, mean KL is 9e-12 to 2.3e-5, with 100% top-1 agreement. That covers 127/128/129 at the window edge and 1025/1027 at the group and block edges. With flash attention on it is 6.5e-8 to 1.2e-4.
    • On a 20,001-token prompt, mean KL is 5.1e-4 to 7.8e-4 (ubatch 7 and 512, flash attention off and on) against a gate of 1e-3: PASS.
    • An MXFP8 Engram table gives logits bit-identical to the BF16 table (CPU and CUDA, lazy reading on and off), and a BF16 table bit-identical to an F32 table.
    • test-backend-ops: GET_ROWS 249/249 on CPU and 225/225 on CUDA, including the MXFP8 cases.
  • Seeded bugs: the gate was calibrated with seeded bugs, and every one of them fails it:

    • the Engram signed sqrt dropped;
    • the n-gram history order reversed;
    • mHC not lagged;
    • the wrong compressor softmax axis;
    • the indexer ReLU dropped;
    • the candidate mask dropped;
    • top-k reuse replaced.
  • Full model on CUDA (2 x B200, the published UD-Q8_K_XL GGUF with the MXFP8 table, read lazily; the BF16 table gives the same numbers) against the official F32 reference, on this branch's head: mean KL 4.76e-3 on wiki1100 and 2.81e-3 / 2.85e-3 on long17k, with top-1 agreement 98.6% and 98.7%. The official native kernels score 2.6e-2 / 1.5e-2 against the same reference.

    • The published UD-Q4_K_XL (MXFP4 experts, Q8_0 dense) on 3 x B200: mean KL 9.00e-3 on wiki1100 and 4.46e-3 on long17k, top-1 98.2% and 98.6%.
    • llama-server loads both published files with default settings and answers chat requests with the template embedded in the GGUF. With -ot per_layer_token_embd.weight=CPU automatic fitting is off, so a context size has to be given (-c 32768 works); the full default context needs a large compute buffer on the reference attention path.
    • Both published files fail to load on the parent revision with "invalid ggml type 43".
    • wiki1100 is bit-identical across runs. long17k lands in one of two bit-reproducible outcomes (KL 8.3e-4 between them, diverging at token 1991), with lazy reading on or off. With the stacked CUDA PR ggml-cuda : deterministic radix top-k, honour GGML_PREC_F32 for F32 x F32 MUL_MAT #292 (deterministic radix top-k, F32 precision honoured at every batch size) both texts are bit-identical across 4 runs on 3 different card pairs, so the split comes from the CUDA paths that PR changes.
  • Revisions since the first gated revision:

    • Review fixes: the multi-sequence and embedding-input aborts, sgn(0) in the Engram signed sqrt, the embeddings output width, the per-chunk indexer, and GGUF validation.
    • The chat template, template detection and DSML parser were moved out of this PR, and comments were trimmed. Logits are unchanged.
    • The per_layer_token_embd layout with lazy reading and prefetch.
    • CPU logits are bit-identical to the gated revision on every fixture config.
    • The MXFP8 type was added; logits with BF16/F32 tables are unchanged bit for bit (CPU 14/14, CUDA 10/10 configs).
  • Lazy table on a cold NVMe page cache (a quantized model whose non-table weights total 114 GiB, 2 GPUs):

    mode tg (tok/s) pp (tok/s) RSS after run
    lazy + prefetch (default) 111-127 419-816 1.6-1.8 GiB
    lazy, prefetch disabled 45-60 91-468 2.0 GiB
    --lazy-mode off (table resident) 126-133 263-990 190 GiB
  • Runtime:

    • State save/load round trips are bit-identical, including the Engram history.
    • llama-batched -np 2 and -np 4 match -np 1.
    • Forced indexer chunking is bit-identical to the single-chunk graph.
    • At 64k context on CUDA, the compute buffers are 5.7 / 21.9 / 43.8 GB at ubatch 512 / 2048 / 4096, with no abort.
  • Other models:

    • Every architecture that upstream test-llama-archs -o can write (134 random models) was run on CPU with this branch and with the base, at ubatch 512 and 7. Logits are bit-identical in all 264 runs; the 4 others (diffusion models at ubatch 7) abort the same way on both.
    • DeepSeek-V4 logits on a random model are bit-identical to the base at ubatch 512 and 7.
    • test-llama-archs passes 140/140 on CPU (139 on the base, plus deepseek41), and test-chat passes.
    • test-llama-context passes on the generated deepseek41 and deepseek4 models; the quantized KV case is skipped for deepseek41 (context creation fails with an error, quantized KV comes in a stacked PR).
    • Builds with LLAMA_FATAL_WARNINGS=ON.

Known gaps

FP8 32x32 linears are dequantized to BF16 (exact), routed experts are copied
bit-exact as MXFP4, Engram tables are precomputed as BF16 (e4m3 * 2^e8m0, exact)
and streamed in bounded chunks, router and Engram gate are kept in F32.
--outtype f32 keeps every dense tensor and the Engram tables in F32.

The Engram tables of all layers are written as one per_layer_token_embd (rows
concatenated in layer order) with the PLE keys of qwen4exp: ple.layers,
ple.ngram_size, ple.heads_per_ngram, ple.layer_multipliers, ple.head_offsets
(absolute rows), ple.head_vocab_sizes and embedding_length_per_layer_input.
The compressed token map and the pad token id stay deepseek41.engram keys.
…upport

- arch, KV keys and Engram tensors for deepseek41; the Engram tables of all layers are one per_layer_token_embd
  described by the qwen4exp PLE keys, the compressed token map and the pad token id are the only new Engram keys
- hparams for the cross-layer KV / indexer sharing and the two-level candidate selection
- DSV4 KV cache: compress ratios are taken from the slot state instead of the V4 constants; for V4.1 the CSA slot
  is ratio 2, the HCA slot ratio 1, without overlap and without the lightning-indexer cache, the index K is stored
  next to the compressed KV and only the KV source layers own rows
- the window cells keep the token ids (saved and restored with the state) for the Engram n-gram history
Engram (host-side n-gram hash, rows gathered on the CPU from per_layer_token_embd, which is read lazily from the
mapping like the qwen4exp n-gram table, its rows prefetched per ubatch), single-pass mHC, ratio 1/2 compressors with
cross-layer KV / index-K / top-k sharing and the two-level candidate block selection. Every compressed layer
attends densely over [window | all compressed rows] with the top-k applied as a mask. The indexer score,
candidate blocks and top-k are computed per chunk of query tokens, so the [index heads, tokens, rows]
intermediate stays near 2^26 elements at long context (a single chunk, the plain graph, whenever it fits).
Tokens shared by several sequences are supported; embedding input skips Engram, like the masked positions of
the reference. The model reuses the DeepSeek-V4 loader and graph helpers; the HC mix computation is split out
of build_hc_pre (unchanged for V4). The F32 router, HC and indexer matmuls request F32 precision, and the
router weights are normalized by sum + 1e-20 as in the reference. hash_layer_count is optional for V4.1: it has no
hash layers, and V4.1 GGUFs converted before the key was written lack it.
…d DSML tool calls

- test-llama-archs: a 6-layer config with window-only, Engram, ratio-2 and ratio-1 KV sources, top-k reuse and
  a candidate-masked index layer; the model saver writes the deepseek41 sharing and Engram keys (round trip)
- the official chat template (ported from encoding.py), template detection, and the DSML tool call parser for the
  V4.1 tag names (leading space: <|DSML| calls>, <|DSML| invoke>, <|DSML| parameter>)
- a V4.1 content continuation in thinking mode consumes the bare </think> of the generation prompt
- remove the V4.1 chat template file, its template detection, the DSML parser change and their test-chat
  cases; the converter drops the inherited DeepSeek-V4 default template (a template shipped with the model
  is still added by set_vocab)
- hash_layer_count is required again (the converter writes 0 for V4.1)
- the converter no longer imports sympy
- engram_index moves out of models.h; comments that restate the code are removed
MXFP8 is the OCP microscaling FP8 format: 32 E4M3 values sharing one
E8M0 scale (33 bytes per block). DeepSeek-V4.1 stores its Engram tables
this way; keeping them as MXFP8 halves the table size against the exact
BF16 lookup (203 GB vs 393 GB) with identical dequantized values.

The type is gather-only: CPU and CUDA support GET_ROWS (source 0) and
refuse every other op in supports_op, so misuse fails at scheduling.
Row (de)quantizers use 64-bit block loops since the tables exceed 2^31
elements. gguf-py gains the type and a reference (de)quantizer;
test-backend-ops covers GET_ROWS.

MXFP8 takes the next free type id, 43.
The checkpoint's Engram tables are e4m3 rows with one e8m0 scale per 32
elements, i.e. MXFP8 block for block: copy them bit-exact as
[e8m0 | 32 x e4m3] blocks into per_layer_token_embd instead of
precomputing the BF16 lookup. NaN scale or code bytes are rejected.
DSV41_ENGRAM_TYPE=bf16 keeps the exact BF16 table (F32 with
--outtype f32).
@danielhanchen

Copy link
Copy Markdown
Member Author

Pushed f42144f: the final projection now goes through build_lora_mm(model.output, cur) instead of ggml_mul_mat, so an output.weight LoRA adapter is applied. Before, it loaded but changed nothing.

CPU repro on a six-layer fixture with rank-1 adapters (128 logits):

run logits changed
output adapter, before 0/128
attention adapter (control) 128/128
output adapter, after 128/128

No-adapter logits are bit-identical before and after for F32 and Q8_0 output heads.

This branch has not been deployed

No deployments
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.

1 participant