Repository navigation
Conversation
garrett361
left a comment
There was a problem hiding this comment.
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.
- The mHC gates are rounded to bf16, while vLLM computes them in fp32.
- The receive-side clone adds back memory #3365 removed, for every model.
- The default
freeze_engram_tables = falsefails at the startup weight broadcast. - The filesystem and ModelExpress senders gather every table and run out of memory.
- LoRA now takes other models' n-gram tables out of FSDP.
- The SM90
topk_lengthworkaround changes V4 for a limit the pinned FlashMLA doesn't have. - The model doesn't follow the
PreTrainedModelPrimeRLcontract. - The configs don't follow the recipes layout.
mainmoved configs out ofexamples/(#4861). AGENTS.md asks forrecipes/<model>/{rl,sft}.tomlwithgpu/{rl,sft}/<hw>.tomloverlays, no self-contained configs, and entries in the README recipes table and therecipes/README.mdcoverage grid, whose rules also call for 256k context (the RL config usesseq_len = 8192). The shippedrl/math.tomlalso differs from the run behind the KL table (7 + 1 nodes, lr1e-7, bf16 dense layers versus 8 + 2,1e-6, FP8). deps/rendererspoints at no merged branch:bafef2cis renderers#192's draft head merged with renderersmain, onmario/deepseek-v4.1-renderer. Re-pin to renderersmainonce #192 merges, as the PR body notes.- No parity or invariance test covers V4.1. V4 has a
Caseintest_vllm_parity.pyandtest_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 bytest_deepseek_v41.py). Suggest a parityCaseand invariance casesdeepseek_v41-ep2and one withfreeze_engram_tables = true. - 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. - Context parallelism. V4.1 all-gathers its keys; V4 now exchanges only the halo each rank needs (#4355).
- 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'sMHCPreDelayedOp, would serve both.prime-rl/src/prime_rl/trainer/models/deepseek_v41/hyperconnections.py
Lines 49 to 56 in ba2fac1
161c02b to
bdb80a2
Compare
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 2 potential issues.
❌ 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.
bdb80a2 to
74cf4fb
Compare
garrett361
left a comment
There was a problem hiding this comment.
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.
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.
1382ca8 to
0a4bc4f
Compare

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 withNGramRows.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'sfp8_ds_mlacache, and context parallelism. It runs RL with an NCCL weight broadcast that skips the frozen tables.Review fixes (
5e6287366)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 fp32fninto 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.freeze_engram_tables: V4.1 setsrequires_frozen_engram_tables, so setup fails with a clear error when the flag is off. The trainer docstring says so.drop_frozen_ngram_tablesnow lives inutils/weights.pyand 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).config.freeze_engram_tables, not on everyNGramTable.topk_lengthworkaround removed: the V4/V4.1 GPU and CP tests pass on H200 without it.PreTrainedModelPrimeRLcontract: no HF class attributes orGenerationMixin. The inner model subclasses the base and returnsTextModelOutput, and the LM setssupports_tied_word_embeddings.recipes/deepseek-v4.1-flash/{rl,sft}.tomlwithgpu/{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.deepseek_v41-ep2anddeepseek_v41-cp2_ep2, both withfreeze_engram_tables, and adeepseek_v41case intest_vllm_parity.py. The parity case serves the Engram tables in fp8 with e8m0 scales, the checkpoint format.Also:
"\ue000".pre_mix,engram_rows,compressed_kv,index_k) are inDYNAMIC_TENSOR_ARG_DIMS, and thePackedContexttensors 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)model.freeze_engram_tableswithweight_broadcast.type = "modelexpress"fails config validation (trainer,rlandsft). 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.mdlists the limitation.freeze_engram_tables.layer_kindsfalls back tocompress_ratioswhen a config has nolayer_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.kv_normat 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.recipes/deepseek-v4.1-flash/sft.tomlno longer setslr, whichrecipes/data/sft/math.tomloverrides (1e-5, as for GLM-5.3's Sign-SGD recipe).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 paritydeepseek_v41: passed.deepseek_v41-ep2loss 4.0e-5, grad norm 3.2e-4, worst grad 4.2%.deepseek_v41-cp2_ep2: 3.4e-5, 1.2e-4, 4.1%.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:
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.deepseek_v41-ep2(loss err 4.7e-5, grad norm 5.4e-4, worst grad 4.5%) anddeepseek_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.deepseek_v4anddeepseek_v41pass. With the V4.1 tables row-shuffled, route agreement drops from 0.987 to 0.71, so the case catches a wrong lookup.test_configs, the V4.1 recipe compositions pass except the SWE one, which fails only because thescaleswetaskset isn't installed here (V4's does the same).rl.toml+gpu/rl/h200.toml+data/rl/fake.tomlon 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 everynum_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:ep2has loss 4.3e-5, grad norm 4.2e-4 and worst grad 4.5%, andcp2_ep2has 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 atbdb80a239: 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 withtrainer.model.offload = "full"and evals off are in progress and will replace this table: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.Compile fix
At compress ratio 1,
entry_local_idx * 1folded to the graph input. Under activation checkpointing, Inductor tagged that input as recomputable and failed withNode ... 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
deps/renderersbe re-pinned to renderersmainbefore this lands. Until then it points atd12c96e, renderersmain(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 requiresmodel.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_replayby default, and clones NCCL bucket views under expert parallelism to avoid pinned multi-tensor buckets. Weight send paths sharedrop_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.