Skip to content

feat: DeepSeek-V4.1-Flash model definition and RL, rebased onto main - #4843

Open
MarioSieg wants to merge 8 commits into
mainfrom
mario/deepseek-v41-model
Open

MarioSieg wants to merge 8 commits into
mainfrom
mario/deepseek-v41-model

Conversation

@MarioSieg

@MarioSieg MarioSieg commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Rebased onto main (447ebd9). #4863 (async engram) has merged, and V4.1's engram tables use its shared n-gram modules: the model starts every table's lookup before the first layer (NGramEmbeddings.start) and each engram layer reads its rows with NGramRows.embed, so the lookups overlap the layers before them. It uses #4863's deduplicating row-sharded lookup (deduplicate_lookups=True) and non-persistent layout buffers. The V4.1 config fields follow #4919's layout (components/trainer/model.py, components/engine/__init__.py).

Adds DeepSeek-V4.1-Flash (deepseek-ai/DeepSeek-V4.1-Flash, text model) to the trainer and RL. The model has shared compressed attention, delayed mHC gates, frozen row-sharded Engram tables, FP8 KV rounding that matches vLLM's fp8_ds_mla cache, and context parallelism. It runs RL with an NCCL weight broadcast that skips the frozen tables.

Review fixes (5e6287366)

  1. mHC gates in fp32: the hyper-connections are fp32_modules() and are called through .forward(), so FSDP keeps them fp32 and their hooks stay outside the compiled layer. The mixes GEMM splits the fp32 fn into a bf16 head and a bf16 tail, each a bf16 GEMM with fp32 accumulation. That gives about 2^-16 relative precision, finer than vLLM's TF32, without upcasting the streams.
  2. NCCL receiver: bucket views are cloned only when vLLM runs with expert parallelism.
  3. freeze_engram_tables: V4.1 sets requires_frozen_engram_tables, so setup fails with a clear error when the flag is off. The trainer docstring says so.
  4. Filesystem and ModelExpress senders: drop_frozen_ngram_tables now lives in utils/weights.py and runs in the NCCL and filesystem (gather_weights_parallel) senders. All senders reject unchunked trainable tables. ModelExpress with frozen tables is rejected at config time (see the second round below).
  5. LoRA: FSDP excludes the tables on config.freeze_engram_tables, not on every NGramTable.
  6. SM90 topk_length workaround removed: the V4/V4.1 GPU and CP tests pass on H200 without it.
  7. PreTrainedModelPrimeRL contract: no HF class attributes or GenerationMixin. The inner model subclasses the base and returns TextModelOutput, and the LM sets supports_tied_word_embeddings.
  8. Recipes: recipes/deepseek-v4.1-flash/{rl,sft}.toml with gpu/{rl,sft}/h200.toml, 256k context, a README table row, the coverage grid and a fits-table row. examples/advanced/deepseek-v4.1-flash/ is removed.
  9. Renderers pin: still waiting on renderers#192 (see below).
  10. Tests: distributed-invariance cases deepseek_v41-ep2 and deepseek_v41-cp2_ep2, both with freeze_engram_tables, and a deepseek_v41 case in test_vllm_parity.py. The parity case serves the Engram tables in fp8 with e8m0 scales, the checkpoint format.
  11. Dedup lookup: comes from Sync the shared n-gram modules with prime-pt: overlapped lookups, deduplicating lookup, NCCL warm-up #4863.

Also:

  • The sentinel is written as "\ue000".
  • Compiled layers take keyword args. The V4.1 inputs (pre_mix, engram_rows, compressed_kv, index_k) are in DYNAMIC_TENSOR_ARG_DIMS, and the PackedContext tensors are marked dynamic. On a tiny model with AC and compile, 5 rows of different lengths compile 6 graphs (one per layer type) on the first row and none after it.

Review fixes, second round (0a4bc4f14)

  1. ModelExpress: model.freeze_engram_tables with weight_broadcast.type = "modelexpress" fails config validation (trainer, rl and sft). The trainer leaves frozen tables out of every update, but a ModelExpress refit must write every vLLM parameter, and vLLM's V4.1 tables are fp8/fp32 parameters (CPU-pinned, shared across DP). The ModelExpress sender no longer filters frozen tables. docs/model-express.md lists the limitation.
  2. Compile suite: the V4.1 cases set freeze_engram_tables. layer_kinds falls back to compress_ratios when a config has no layer_types: the sliding-window layer 0 and the ratio-2 consumer layer 2 hold the same submodules, so the suite counted 5 kinds against the 6 graphs the layers compile.
  3. Compressor rounding: the latent stays fp32 through kv_norm at both ratios and is rounded once after it, as in vLLM. At ratio 1 the norm runs before the CP gather, which still moves bf16.
  4. SFT lr: recipes/deepseek-v4.1-flash/sft.toml no longer sets lr, which recipes/data/sft/math.toml overrides (1e-5, as for GLM-5.3's Sign-SGD recipe).
  5. SWA bounded replay: vLLM always gets swa_bounded_replay = False, and a config that enables it fails validation.

Tested on H200, on the pre-rebase head (1382ca8) with these fixes:

  • test_compile.py -k deepseek_v41: 2 passed (dp2, dp2-router_replay).
  • test_deepseek_v41.py: 5 passed, 1 skipped. vLLM parity deepseek_v41: passed.
  • Distributed invariance: deepseek_v41-ep2 loss 4.0e-5, grad norm 3.2e-4, worst grad 4.2%. deepseek_v41-cp2_ep2: 3.4e-5, 1.2e-4, 4.1%.
  • CPU: test_configs.py, test_deepseek_v41_cpu.py, tests/unit/transports, test_modelexpress_server.py: 546 passed.

Test plan (first round)

On H200 via Slurm:

  • GPU (test_deepseek_v41.py, test_deepseek_v4.py, test_deepseek_v4_kernels.py, test_embeddings.py, test_scratch_init.py, inference/test_routed_experts.py): 111 passed, 49 skipped. The V4.1 CP test passes at cp=2 and cp=4 with the SM90 workaround removed.
  • Distributed invariance: deepseek_v41-ep2 (loss err 4.7e-5, grad norm 5.4e-4, worst grad 4.5%) and deepseek_v41-cp2_ep2 (5.4e-5, 4.0e-4, 4.5%) pass. A deliberately wrong lookup fails all three tolerances (worst grad 142%). V4's cases are unchanged.
  • vLLM parity: deepseek_v4 and deepseek_v41 pass. With the V4.1 tables row-shuffled, route agreement drops from 0.987 to 0.71, so the case catches a wrong lookup.
  • CPU: the V4.1, n-gram, embedding, scratch-init, chunked-conversion and transport tests pass. In test_configs, the V4.1 recipe compositions pass except the SWE one, which fails only because the scaleswe taskset isn't installed here (V4's does the same).
  • 256k trainer fit: rl.toml + gpu/rl/h200.toml + data/rl/fake.toml on 7 nodes (cp 8, ep 8): 59.8k tok/s, 130.8 GiB allocated (139.9 GiB reserved) per GPU.

Determinism fix (716c3d24d)

The mHC post-BDA Triton kernels (dsv4_mhc.py, shared with V4) picked their tile config by timing. The tile sets the order of the backward's sums over the hidden dim and changes a few forward outputs (forced over the same inputs, the 48 forward configs gave five different results). So the same model and row could give different losses in different processes: 2625.2222 or 2625.3174 on the tiny model. Both kernels now use a fixed tile chosen from the hidden size only. At hidden 4096 that is the fastest measured backward config and within 2% of the best forward. After the fix, 4 processes on 2 GPUs give the identical loss, the sinkhorn backward is bitwise equal at every num_warps, and the V4, V4.1 and kernel GPU tests pass (111 passed, 49 skipped).

Open: V4.1 invariance tolerance

The V4.1 invariance cases still need {"loss": 1e-4, "grad_norm": 3e-3, "grad": 1e-1}. After the determinism fix: ep2 has loss 4.3e-5, grad norm 4.2e-4 and worst grad 4.5%, and cp2_ep2 has 5.0e-5, 3.1e-4 and 4.5%. The sharded model matches the unsharded reference bitwise through layer 0 and drifts from the first compressing layer on. The source of that first difference is not found yet.

RL mismatch KL

The table below is from the earlier examples/ config at bdb80a239: math env, batch 64 × group 8, sign-SGD lr 1e-7, compile on, router replay on. Every step is below 0.015 (max 0.0007, mean 0.00061). The shipped recipe (rl.toml + gpu/rl/h200.toml + data/rl/math.toml) runs out of memory in the trainer warmup at 256k with real routing. Three 20-step runs at 256k with trainer.model.offload = "full" and evals off are in progress and will replace this table:

  • FP8: DeepGEMM FP8 trainer experts, vLLM online FP8 experts, 7 trainer + 1 inference node.
  • bf16 trainer experts, vLLM online FP8 experts, 7 + 1.
  • bf16 experts on both sides, 6 trainer + 1 DEP16 inference replica over 2 nodes.

The overlay will take offload = "full" if they fit. data/rl/math.toml's step-0 AIME eval (240 rollouts of up to 256k tokens) kept one inference node busy for over 2 hours before any training rollout, so these runs pass --no-orchestrator.eval.

step mismatch KL entropy
1 0.0007 0.486
2 0.0005 0.342
3 0.0006 0.362
4 0.0006 0.422
5 0.0006 0.441
6 0.0006 0.385
7 0.0006 0.473
8 0.0006 0.501
9 0.0006 0.469
10 0.0007 0.510
11 0.0006 0.436
12 0.0006 0.484
13 0.0006 0.473
14 0.0006 0.506
15 0.0007 0.516
16 0.0006 0.524
17 0.0007 0.528
18 0.0006 0.448
19 0.0006 0.433
20 0.0006 0.474

Compile fix

At compress ratio 1, entry_local_idx * 1 folded to the graph input. Under activation checkpointing, Inductor tagged that input as recomputable and failed with Node ... was invalid, but is output. Ratio-1 layers now use the layout tensor directly, so V4.1 compiles under AC again.

Not in this PR

  • pipeline parallelism and Mega MoE
  • a tested FP8-trainer RL recipe
  • NVFP4 KV rounding on SM100
  • checkpoint conversion in the normal load path
  • renderers#192 has to merge and deps/renderers be re-pinned to renderers main before this lands. Until then it points at d12c96e, renderers main (70df271, up to Revert "add pool for preftecher (#227)" #230) merged into the V4.1 renderer branch.

Note

High Risk
Large new model stack touching attention, distributed training, weight sync, and inference parity; engram freeze/broadcast rules are correctness-critical for RL at 256k context.

Overview
Adds DeepSeek-V4.1-Flash (deepseek_v41) as a first-class PrimeRL model: shared compressed sparse attention with cross-layer KV/index handoff, delayed mHC gates, hashed Engram n-gram tables, V4 MoE reuse, HF↔Prime weight conversion, and CP-aware forwards. The model requires model.freeze_engram_tables; setup enforces this and keeps frozen tables out of FSDP, gradients, and NCCL/filesystem broadcasts (with ModelExpress explicitly rejected when engrams are frozen).

Trainer / inference alignment: extends DSA/KV config to V4.1, registers V4.1 indexer ops for activation checkpointing, disables vLLM swa_bounded_replay by default, and clones NCCL bucket views under expert parallelism to avoid pinned multi-tensor buckets. Weight send paths share drop_frozen_ngram_tables; ModelExpress refreshes state via chunked-conversion checks.

Recipes & docs: ships recipes/deepseek-v4.1-flash/ (RL/SFT + H200 overlays), README/coverage updates, and documents CP behavior for V4.1 plus ModelExpress limitations for frozen engrams.

Kernels / stability: new TileLang/cuDNN V4.1 indexer top-k paths; V4 KV fake-quant gains configurable tile width (32 for SM100-style rounding); mHC post-BDA Triton kernels use fixed tiles instead of autotune for bitwise-consistent multi-process training.

Tests: CPU/GPU unit tests for config, conversion, engram hashing, backward/CP/packed docs; vLLM parity with fp8 engram checkpoint formatting; compile/invariance hooks for freeze_engram_tables.

Reviewed by Cursor Bugbot for commit 0a4bc4f. Bugbot is set up for automated code reviews on this repo. Configure here.

@MarioSieg
MarioSieg marked this pull request as ready for review November 30, 2026 15:45

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

Comment thread docs/advanced.md Resolved
@garrett361
garrett361 self-requested a review December 1, 2026 14:58

@garrett361 garrett361 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wild model. Great start, there are mostly some edge cases and a few best-practices that have landed on main since you started this that I think we should get in first. See the below?

Also I see there are merge conflicts.

Inline comments are mostly agent-written. Generated below, for your agent:


Request changes. Please address items 1-9 before merging; 10-11 can follow. Details for items 1-7 and 11 are in the inline comments.

  1. The mHC gates are rounded to bf16, while vLLM computes them in fp32.
  2. The receive-side clone adds back memory #3365 removed, for every model.
  3. The default freeze_engram_tables = false fails at the startup weight broadcast.
  4. The filesystem and ModelExpress senders gather every table and run out of memory.
  5. LoRA now takes other models' n-gram tables out of FSDP.
  6. The SM90 topk_length workaround changes V4 for a limit the pinned FlashMLA doesn't have.
  7. The model doesn't follow the PreTrainedModelPrimeRL contract.
  8. The configs don't follow the recipes layout. main moved configs out of examples/ (#4861). AGENTS.md asks for recipes/<model>/{rl,sft}.toml with gpu/{rl,sft}/<hw>.toml overlays, no self-contained configs, and entries in the README recipes table and the recipes/README.md coverage grid, whose rules also call for 256k context (the RL config uses seq_len = 8192). The shipped rl/math.toml also differs from the run behind the KL table (7 + 1 nodes, lr 1e-7, bf16 dense layers versus 8 + 2, 1e-6, FP8).
  9. deps/renderers points at no merged branch: bafef2c is renderers#192's draft head merged with renderers main, on mario/deepseek-v4.1-renderer. Re-pin to renderers main once #192 merges, as the PR body notes.
  10. No parity or invariance test covers V4.1. V4 has a Case in test_vllm_parity.py and test_distributed_invariance.py; V4.1 has neither, so its trainer/vLLM logprobs, EP, the deduplicating lookup and the frozen-table FSDP path are untested (CP is covered by test_deepseek_v41.py). Suggest a parity Case and invariance cases deepseek_v41-ep2 and one with freeze_engram_tables = true.
  11. Use #4863's deduplicating lookup once it lands.

Later consolidation (not for this PR)

Places where V4.1 and V4 could share code later:

  • Indexer scoring. V4.1's two-level candidate filter (one layer picks each query's top blocks, later layers score only inside them) has no V4 counterpart and needs its own kernel. Without candidates, both models compute the same fp8 score and top-k, but V4 uses DeepGEMM fp8_mqa_logits (#4276) with a CP balance plan (#4811), while V4.1 uses the Triton kernel #4276 retired, or cuDNN on Blackwell.
    top_k, candidates = dsv41_index_topk(
  • Context parallelism. V4.1 all-gathers its keys; V4 now exchanges only the halo each rank needs (#4355).
    kv = torch.ops._c10d_functional.all_gather_into_tensor(
  • mHC. V4.1 reuses V4's Sinkhorn and post kernels but not fused_mhc_pre, because it collapses the streams one sublayer later; a delayed mode, like vLLM's MHCPreDelayedOp, would serve both.
    def forward(self, mhc_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
    hc = self.hc_mult
    flat = mhc_states.flatten(start_dim=2)
    # RMSNorm then projection == projection scaled by the row's rstd. Both operands hold bf16
    # values, so a bf16 GEMM accumulating into fp32 matches the fp32 product without
    # materializing the streams in fp32.
    rstd = torch.rsqrt(flat.float().square().mean(-1, keepdim=True) + self.input_norm.eps)
    mixes = _MixesMatmul.apply(flat.reshape(-1, flat.shape[-1]), self.fn.to(flat.dtype))

Comment thread src/prime_rl/transports/weights/nccl.py Resolved
Comment thread src/prime_rl/trainer/model.py Resolved
@MarioSieg
MarioSieg force-pushed the mario/deepseek-v41-model branch from 161c02b to bdb80a2 Compare December 2, 2026 21:00
@MarioSieg
MarioSieg changed the base branch from main to mario/async-engram December 2, 2026 21:00

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 2 potential issues.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit bdb80a2. Configure here.

@MarioSieg
MarioSieg force-pushed the mario/deepseek-v41-model branch from bdb80a2 to 74cf4fb Compare December 3, 2026 14:28
@github-actions github-actions Bot removed the gpu-ci label Dec 3, 2026
Base automatically changed from mario/async-engram to main December 3, 2026 14:57
@MarioSieg
MarioSieg requested a review from garrett361 December 3, 2026 16:45

@garrett361 garrett361 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My agent pointed out a few issues, seems like MX will fail (have you tested?), and then some CI issues, and a small config issue. See below.

Inline comments are mostly agent-written. Generated below, for your agent:


Request changes. Items 1-7, 10 and 11 of the last review are resolved in code. Still open and already known: a shipped RL overlay that fits at 256k with its KL table, and re-pinning deps/renderers once renderers#192 merges.

Before merging, please also settle ModelExpress for V4.1 and fix the V4.1 compile-suite cases. The compressor rounding and the SFT learning rate are smaller. Details are in the inline comments.

The EP receive-side clone in worker/nccl.py overlaps #4544, which makes the same change for every model; worth coordinating whichever lands first.

Comment thread tests/unit/train/tiny_models.py Resolved
Comment thread recipes/deepseek-v4.1-flash/sft.toml Resolved
samsja and others added 7 commits December 3, 2026 22:15
Squash of #4057 (previous head 796d5c1) onto main a1598d9.

- Engram tables use main's shared n-gram module (#4293): DeepseekV41NGramHasher,
  NGramEmbeddings with non-persistent layout buffers and a deduplicating row-sharded lookup.
  AllToAllEmbeddingParallel and the V4.1 table special cases are gone.
- RL weight sync: the NCCL sender skips frozen n-gram tables (inference keeps the checkpoint
  copy); the engram row-chunk relay and its vLLM writer are dropped.
- vLLM 0.34 loads the attention sinks and streams V4.1 weight updates itself, so the sink patch
  and the text-only model registration are dropped.
- FP8 on the routed experts only: trainer deepgemm_fp8 experts, vLLM `quantization = "online"`
  with `quantization_config = { moe = "fp8_per_block" }` (new `online` choice).
- deps/renderers -> 72049f6 (renderers#192 merged with main).
The pad token falls back to EOS, a real token in the training data, so the
embedding must not set padding_idx (matches DeepSeek-V4 and the other models).
…checkpointing

At compress ratio 1, `entry_local_idx * 1` folds to the graph input itself.
Activation checkpointing then tags that input as recomputable, and Inductor's
partitioner fails with "Node ... was invalid, but is output". Use the layout
tensor directly at ratio 1.
…he math RL example

Router replay is what the KL runs used. The math env's LLM-judge fallback needs an
API key; without one its scoring fails and the rollouts are dropped.
… V4.1 tests

- mHC gates are fp32 modules; the mixes GEMM splits fp32 `fn` into two bf16 halves with fp32 accumulation.
- The NCCL receiver clones bucket views only under expert parallelism.
- V4.1 requires `freeze_engram_tables` and fails at setup without it; FSDP excludes tables on that flag.
- Filesystem and ModelExpress senders drop frozen n-gram tables like the NCCL sender.
- Follow the PreTrainedModelPrimeRL contract; drop the SM90 `topk_length` workaround.
- Compiled layers take keyword args with dynamic V4.1 inputs and packed-context tensors.
- Move configs to recipes/deepseek-v4.1-flash (256k, H200 RL and SFT overlays).
- Add V4.1 distributed-invariance cases (ep2, cp2_ep2) and a vLLM parity case.
The tile sizes set the order of the backward's reductions over the hidden dim and the forward's FMA
contraction, so a timing-picked config made results depend on the process. The fixed tiles are the
fastest measured at hidden 4096 (forward within 2% of the best). Reword the V4.1 invariance tolerance
note: the remaining drift is not this.
… lr, SWA replay

- Reject model.freeze_engram_tables with weight_broadcast.type = "modelexpress" at config
  validation (trainer, rl and sft): the trainer leaves frozen tables out of every update, but a
  ModelExpress refit must write every vLLM parameter. The ModelExpress sender no longer filters
  frozen tables.
- Compile suite: V4.1 cases set freeze_engram_tables, and layer_kinds falls back to
  compress_ratios when a config has no layer_types (a sliding-window layer and a compressed layer
  reading another layer's entries hold the same submodules).
- Compressor: keep the latent fp32 through kv_norm and round once after it, as vLLM does.
- recipes/deepseek-v4.1-flash/sft.toml: drop lr, which the data config overrides.
- Always pass swa_bounded_replay = False to vLLM and reject configs that enable it.
@MarioSieg
MarioSieg force-pushed the mario/deepseek-v41-model branch from 1382ca8 to 0a4bc4f Compare December 3, 2026 22:25

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.

3 participants