Skip to content

deepseek41: the original V4.1-Flash-1017 folder opens, plans its ranks and lists each rank's reads - #1160

Merged
juliankang4 merged 1 commit into
midagedev:mainfrom
juliankang4:dgx-spark-tp4-pr1a
Nov 4, 2026
Merged

juliankang4 merged 1 commit into
midagedev:mainfrom
juliankang4:dgx-spark-tp4-pr1a

Conversation

@juliankang4

@juliankang4 juliankang4 commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator

DeepSeek V4.1 Flash 원본 폴더를 열고, 랭크별 배치와 읽을 범위를 계획하는 기능입니다.

What and why

The original DeepSeek-V4.1-Flash-1017 checkpoint folder (MXFP4 experts, MXFP8 dense weights, Engram tables, Hugging Face tokenizer) now opens through the common folder reader. A tensor-parallel cut table, a per-rank memory preflight and a per-rank read-set are built on top of it, so a rank can be planned and loaded from the original files. A rank count that does not divide a cut's units is refused by name.

  • model_hf::arch::deepseek41::Ds41Map maps the trunk tensors to the deepseek41 names. The Engram hash constants and the token map come from config.json and tokenizer.json.
  • hf::modelopt reads MXFP4 and MXFP8 (E8M0 scales); hf::vocab and tokenizer::Pre::DeepseekV3Hf read the folder's tokenizer.
  • model::arch::deepseek41::tp holds the cut table (heads, groups, experts, head rows, Engram columns). placement::tp::preflight checks every rank's weights and buffers against its pool and names the item that does not fit.
  • model_hf::arch::deepseek41::rank_reads lists the byte ranges a rank reads, merged where they lie within 1 MiB.
  • generate_ds41 --preflight counts every rank against one unified pool and refuses a card with its own memory by name, since a rank's need adds device allocations to host ones.
  • placement::row_room counts MXFP8 part-source rows as separate code and scale planes, the way it already counted NVFP4 rows, so the preflight's row_cache is the host base pages those planes touch.
  • fixture ds41-folder <source> <out> [--seed N] writes a small folder in the original format for tests and gates; generate_ds41 --preflight <folder> --ranks N[,N...] prints one tp need record per rank.

Release notes: Added: DeepSeek V4.1 Flash original checkpoint folders open and plan their tensor-parallel ranks.

Code shape

  • No second copy. Logic two models (or two call sites) share has one common owner; I lifted it there instead of
    copying it (AGENTS.md "Common code first", docs/rust-quality.md R14). Where I found an existing copy, I
    named it below.
  • Model code holds only architecture facts. A model's own files carry only what its architecture forces
    (tensor shapes, the attention kind, the quant). A common owner gained no per-model branch, flag or trait method.
  • Dead code is gone. Nothing I made unused is left behind (functions, flags, gate clauses, docs).
  • No silent failure. Undefined input is a named error or panic, never a defined-looking output.
  • Comments state what is true now. No dates, issue numbers or how a bug was found (tools/check-comments.sh).
  • No relaxed gate. No band, tolerance or lint moved to make a check pass; a re-pin carries PIN(YYYY-MM-DD):
    and its reason.
  • cargo fmt and cargo clippy are clean on what I touched; the lint count did not go up.

Duplication found or removed (path:line): crates/model/src/arch/deepseek41/tp.rs and crates/model/src/arch/glm5next/tp.rs both had the cut and span bodies; they now live once in placement::tp::{cut_blocks, span_of, cut_units} and each family keeps a one-line wrapper with its own cut rule. The tokenizer's Hugging Face corpus comparisons (crates/tokenizer/src/pretok.rs) share one hf_pieces helper instead of three copies.

What I ran

Upstream base c446bc7420e365a0b15d1181fa7efc20a723f5af, PR head 511f1a8af2cfa9f0b203f81e7119eab417f22428.

Card:

$ nvidia-smi
Tue Nov  3 22:39:13 2026
+-----------------------------------------------------------------------------------------+
| NVIDIA-SMI 615.71.09              KMD Version: 615.71.09     CUDA UMD Version: 13.4     |
+-----------------------------------------+------------------------+----------------------+
| GPU  Name                 Persistence-M | Bus-Id          Disp.A | Volatile Uncorr. ECC |
| Fan  Temp   Perf          Pwr:Usage/Cap |           Memory-Usage | GPU-Util  Compute M. |
|                                         |                        |               MIG M. |
|=========================================+========================+======================|
|   0  NVIDIA GB10                    On  |   0000000F:01:00.0 Off |                  N/A |
| N/A   47C    P8              4W /  N/A  | Not Supported          |      0%      Default |
|                                         |                        |                  N/A |
+-----------------------------------------+------------------------+----------------------+

+-----------------------------------------------------------------------------------------+
| Processes:                                                                              |
|  GPU   GI   CI              PID   Type   Process name                        GPU Memory |
|        ID   ID                                                               Usage      |
|=========================================================================================|
|  No running processes found                                                             |
+-----------------------------------------------------------------------------------------+
$ nvidia-smi --query-gpu=name,driver_version --format=csv,noheader
NVIDIA GB10, 615.71.09

Original-format fixture folder, written from the DeepSeek-V4.1-Flash-1017 folder ($DS41_1017, mounted read-only):

$ cargo build --release -p bloomery-model-hf --bin fixture && target/release/fixture ds41-folder $DS41_1017 $FIXTURES/v41-folder --seed 1
ds41-folder: $FIXTURES/v41-folder: layers [0, 1, 2, 3, 14, 20, 21, 24, 25] of $DS41_1017, ff 384, seed 1, 15316438376 data bytes

generate_ds41 --preflight on that folder, built and run on the GB10. Every rank count plans, and each line lists the rank's weights, buffers and the bytes it reads:

$ cargo oxide build --arch sm_121a -- -p bloomery-gpu-gates --features deepseek41 --release --bin generate_ds41; target/release/generate_ds41 --preflight $FIXTURES/v41-folder --ranks 1,2,4 --ctx 4352
    Finished `release` profile [optimized] target(s) in 10m 08s
✓ Cargo build succeeded
tp need rank=0/1 node=local pool=124107063296 split=12980910336 whole=269606296 kv=12337152 shadow=40108032 row_staging=25344 row_cache=393216 gathers=245760 scratch=351272960 load_peak=5295329288 total=18950228384 left=105156834912 reads=15326617508 read_runs=15
tp need rank=0/2 node=local pool=124107063296 split=6525936768 whole=269606296 kv=12337152 shadow=40108032 row_staging=12672 row_cache=196608 gathers=491520 scratch=351272960 load_peak=9928724488 total=17128686496 left=106978376800 reads=14219125044 read_runs=38
tp need rank=1/2 node=local pool=124107063296 split=6525936768 whole=269606296 kv=12337152 shadow=40108032 row_staging=12672 row_cache=196608 gathers=491520 scratch=351272960 load_peak=9928724488 total=17128686496 left=106978376800 reads=14219974596 read_runs=38
tp need rank=0/4 node=local pool=124107063296 split=3262968384 whole=269606296 kv=12337152 shadow=40108032 row_staging=6336 row_cache=98304 gathers=983040 scratch=351272960 load_peak=8935854088 total=12873234592 left=111233828704 reads=13639180196 read_runs=56
tp need rank=1/4 node=local pool=124107063296 split=3262968384 whole=269606296 kv=12337152 shadow=40108032 row_staging=6336 row_cache=98304 gathers=983040 scratch=351272960 load_peak=8935854088 total=12873234592 left=111233828704 reads=13667140852 read_runs=57
tp need rank=2/4 node=local pool=124107063296 split=3262968384 whole=269606296 kv=12337152 shadow=40108032 row_staging=6336 row_cache=98304 gathers=983040 scratch=351272960 load_peak=8935854088 total=12873234592 left=111233828704 reads=13665953876 read_runs=59
tp need rank=3/4 node=local pool=124107063296 split=3262968384 whole=269606296 kv=12337152 shadow=40108032 row_staging=6336 row_cache=98304 gathers=983040 scratch=351272960 load_peak=8935854088 total=12873234592 left=111233828704 reads=13639793732 read_runs=56

The same binary builds for the RTX 5090 machine's card family:

$ cargo oxide build --arch sm_120a -- -p bloomery-gpu-gates --features deepseek41 --release --bin generate_ds41
    Finished `release` profile [optimized] target(s) in 6m 34s

Unit tests and the rank read-set gate. For each of the 4 ranks at N=4, the gate loads a sparse folder holding only that rank's read-set and compares its parts, values and scales byte for byte with the whole folder:

$ cargo test -p bloomery-model-hf --lib deepseek41; cargo test -p bloomery-model --lib tp::; cargo test -p bloomery-placement --lib tp; cargo test -p bloomery-gpu-gates --lib tp_need; cargo test --release -p bloomery-model-hf --lib -- --ignored hw_rank_read_set --nocapture
test result: ok. 6 passed; 0 failed; 1 ignored; 0 measured; 141 filtered out; finished in 2.67s
test result: ok. 56 passed; 0 failed; 0 ignored; 0 measured; 599 filtered out; finished in 0.05s
test result: ok. 13 passed; 0 failed; 0 ignored; 0 measured; 220 filtered out; finished in 0.00s
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 198 filtered out; finished in 0.00s
test arch::deepseek41::rank::tests::hw_rank_read_set_loads_its_parts_as_the_whole_folder_does ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 147 filtered out; finished in 5.95s

Host-side gates on the PR head, run on the GB10 with just gate-ds41-place (the V4.1 --place word, the llama launch seats, the GLM generator and the preflight's unified-pool test):

$ just gate-ds41-place
test result: ok. 18 passed; 0 failed; 0 ignored; 0 measured; 301 filtered out; finished in 0.01s
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 318 filtered out; finished in 0.00s
test result: ok. 14 passed; 0 failed; 0 ignored; 0 measured; 305 filtered out; finished in 0.00s
test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
test ds41_preflight::tests::preflight_counts_only_a_unified_pool ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 329 filtered out; finished in 0.00s

The preflight's refusal fails first: with the unified-memory check replaced by if false, the same test is red.

test ds41_preflight::tests::preflight_counts_only_a_unified_pool ... ok
thread 'ds41_preflight::tests::preflight_counts_only_a_unified_pool' panicked at crates/gpu-gates/src/ds41_preflight.rs:118:53:
called `Result::unwrap_err()` on an `Ok` value: RankPool { node: "local", pool_bytes: 107374182400, device: Some(DeviceId { ordinal: 0, uuid: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] }) }
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 329 filtered out; finished in 0.00s

The rank read-set gate (just gate-ds41-reads) checks the row page count. It passes, and it fails when the count goes back to two pages a row, when a plane is counted as one page, or when the MXFP8 plane arm is removed. The unit test the_row_room_counts_the_hosts_base_page fails without the MXFP8 arm:

$ cargo test -p bloomery-placement --lib the_row_room_counts_the_hosts_base_page
test placement::tests::legs::the_row_room_counts_the_hosts_base_page ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 232 filtered out; finished in 0.00s
$ cargo test -p bloomery-tokenizer --lib hf_pieces_are_hugging_faces
test pretok::tests::qwen2_hf_pieces_are_hugging_faces ... ok
test pretok::tests::deepseek_v3_hf_pieces_are_hugging_faces ... ok
test pretok::tests::minimax_m2_hf_pieces_are_hugging_faces ... ok
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 59 filtered out; finished in 0.16s
$ just gate-ds41-reads
test arch::deepseek41::rank::tests::hw_rank_read_set_loads_its_parts_as_the_whole_folder_does ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 147 filtered out; finished in 5.75s
$ just gate-ds41-reads   # two pages a row
thread 'arch::deepseek41::rank::tests::hw_rank_read_set_loads_its_parts_as_the_whole_folder_does' panicked at crates/model-hf/src/arch/deepseek41/rank.rs:335:17:
  left: 196608
 right: 393216
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 147 filtered out; finished in 1.52s
$ just gate-ds41-reads   # a plane counted as one page
  left: 196608
 right: 393216
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 147 filtered out; finished in 1.60s
$ just gate-ds41-reads   # MXFP8 plane arm removed
  left: 196608
 right: 393216
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 147 filtered out; finished in 1.59s
$ cargo test -p bloomery-placement --lib the_row_room_counts_the_hosts_base_page   # MXFP8 plane arm removed
thread 'placement::tests::legs::the_row_room_counts_the_hosts_base_page' panicked at crates/placement/src/placement/tests/legs.rs:1091:9:
  left: 8192
 right: 16384
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 232 filtered out; finished in 0.00s

Hardware (if the change is for a machine)

  • DGX Spark: NVIDIA GB10, driver 615.71.09, CUDA UMD 13.4 (nvidia-smi above).
  • RTX 5090 machine: sm_120a build of generate_ds41 above.

AI help

AI 코딩 에이전트가 코드를 작성한 후 설명을 썼고, 테스트를 마쳤습니다. diff 리뷰와 PR 초안 리뷰는 제가 직접 했습니다.

@github-actions github-actions Bot added gpu The card engine: crates/gpu*, crates/app host Host crates: qdot, threads, engram, engram-lab, runtime, sampler, levers, decision, vision, refset model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja needs-gpu Changes code a card must check, and carries no gate run on a card placement Placement planning: crates/placement tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo labels Nov 4, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: MUST_FIX: The preflight mixes memory pools, undercounts row pages, and adds a duplicate test harness.

Must fix

1. Reject discrete cards before comparing host bytes with VRAM

crates/gpu-gates/src/ds41_preflight.rs:44 Kind A. On a discrete card, RankPool::of supplies VRAM. The call through rank_ledgers to placement::tp::preflight sums device allocations with host ring shadows, row pages and read buffers against that pool. Increasing --ctx grows the host shadows; when the sum crosses VRAM, preflight returns Short even if device allocations fit and RAM holds the host allocations. Host capacity is never checked.
Guard the new entry point now, before callers depend on these admission results. Until separate host and device checks exist, replace the pool declaration with:

let spec = workstation::spec_of_device(here);
if workstation::unified_of(&spec).is_none() {
    return Err(
        "--preflight requires unified memory; host and device budgets are separate on this card"
            .into(),
    );
}
let pool = RankPool::of("local".into(), &spec);

2. Count every page a gathered plane can touch

crates/model/src/arch/deepseek41/tp.rs:287 Kind A. folder::table_rows retains the value and scale file ranges without a page-alignment guard. For the 256-byte value and 8-byte scale rows, an unaligned row can touch more than the two 4,096-byte pages reserved here (up to four [derived]). rank_need passes the understated reserve to preflight, so a pool between the computed and required totals is accepted. The read-set gate never asserts row_cache.
Reuse crates/placement/src/placement/room.rs:219 now so both planners keep one sizing rule (R14). Add this arm before its fallback:

(RowTableSource::Parts, GgmlType::MXFP8) => {
    let groups = bytes / 33;
    span(groups * 32) + span(groups)
}

Replace the new page-cache calculation with:

let page = crate::placement::host_lock::page_bytes()?;
let mut tables = roles::classify(split, hp)?;
for t in &mut tables.tensors {
    t.gathered_rows = t.gathered_rows.map(|_| cols.end - cols.start);
}
row_cache = crate::placement::row_room(
    &tables,
    run.batch,
    page,
    crate::placement::RowTableSource::Parts,
)?;

Assert the resulting page reserve in the gate; replacing the common page-span calculation with one page per plane must turn it red.

3. Share the corpus comparison harness

crates/tokenizer/src/pretok.rs:1606 Kind B. This duplicates crates/tokenizer/src/pretok.rs:1552. Their 46-line definitions are identical after substituting the function name, fixture and pre-tokenizer. The replacement below reduces the two definitions and their test attributes to 38 lines [derived].
Extract the shared comparison now so future assertion fixes have one owner (R14). Replace both definitions, including their test attributes, with:

fn hf_pieces(pre: Pre, fixture: &str) {
    let path = format!(
        "{}/../hf/tests/fixtures/{fixture}.json.gz",
        env!("CARGO_MANIFEST_DIR")
    );
    let corpus: serde_json::Value = serde_json::from_reader(
        flate2::read::GzDecoder::new(
            std::fs::File::open(&path).unwrap_or_else(|e| panic!("{path}: {e}")),
        ),
    ).unwrap();
    let cases = corpus["cases"].as_array().unwrap();
    assert!(cases.len() >= 11_000, "{} cases in {path}", cases.len());
    let mut scratch = Scratch::default();
    for case in cases {
        let text = case["text"].as_str().unwrap();
        let want: Vec<usize> = serde_json::from_value(case["pieces"].clone()).unwrap();
        let cpts: Vec<u32> = text.chars().map(u32::from).collect();
        let mut at = 0;
        let got: Vec<usize> = split(pre, &cpts, &mut scratch).iter().map(|&n| {
            let bytes = cpts[at..at + n].iter()
                .map(|&c| char::from_u32(c).unwrap().len_utf8())
                .sum();
            at += n;
            bytes
        }).collect();
        assert_eq!(got, want, "{path}: {text:?}");
    }
}

#[test]
fn qwen2_hf_pieces_are_hugging_faces() {
    hf_pieces(Pre::Qwen2Hf, "qwen2-hf-pieces");
}

#[test]
fn deepseek_v3_hf_pieces_are_hugging_faces() {
    hf_pieces(Pre::DeepseekV3Hf, "deepseek-v3-hf-pieces");
}

Checked

Validated all three citations against added lines, followed the budget and stored-plane paths, and compared both corpus definitions. The read-set gate checks KV, shadows, staging and gathers but has no assertion on row_cache. No escape-catalog pattern or ledger lesson applies to these findings.

Notes

Validation used static inspection; no local Rust build or hardware gate was run.
The PR body lacks FAIL-first output for the new read-set gate. GPU evidence names earlier commits and provides no just gate-* output.

Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bin/generate_ds41.rs, crates/gpu-gates/src/ds41_preflight.rs, crates/gpu-gates/src/lib.rs … and carries no gate run on a card (CONTRIBUTING's evidence list); a maintainer adds gpu-verified after one.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

…s and lists each rank's reads

DeepSeek-V4.1-Flash-1017's checkpoint folder (model_type deepseek_v41) reads as deepseek41
(model_hf::arch::deepseek41::Ds41Map): every trunk tensor in the deepseek41 names, the routed
experts' MXFP4 codes and E8M0 scales as MXFP4 stacks, the 32 by 32 F8_E4M3 projections as
MXFP8, the Engram tables' two planes as MXFP8 row tables read where the folder stores them
(engram::rows::PlanarTable), the draft and the vision tower skipped by reason. The header's
keys come from the config; the Engram hash constants (multipliers, primes, offsets, token map)
are derived as the reference derives them (hf::engram), and the tokenizer reads as deepseek-v3
with its Hugging Face reading (Pre::DeepseekV3Hf).

Tensor parallel: model::arch::deepseek41::tp cuts each tensor (heads, output groups, inner
width, vocabulary rows, Engram hash columns) and counts a rank's need beside its weights;
placement::tp::preflight admits each rank by every item and refuses a short one with the
items. model_hf::arch::deepseek41::rank_reads lists the file bytes a rank reads, from the plan
the load reads by, the Engram rows of its hash columns at their original row ids.
generate_ds41 --preflight, in a build with the checkpoint feature, prints each rank's ledger;
fixture ds41-folder writes an original-format fixture folder. Added tokens marked normalized are
read under a normalizer that changes no text, unless one can overlap an unnormalized one.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Since the last review:

Verdict: CLEAN: All earlier must-fix items are resolved, and no new defect survived the interdiff review.

Checked

Duplicates: 3 new function definitions checked; no duplicate owner remains. Dryer supplied no pairs.
Complexity: one admission guard and one quant-format arm added; no kernel or decode-step changes. Crapper supplied no results.
Silent failure: 0 new fallback sites. Admission, malformed-row and sizing errors reach the preflight caller.
Tests, static mutation checks: removing the admission guard fails unwrap_err; deleting crates/placement/src/placement/room.rs:233 fails the four-page assertion; dropping crates/model/src/arch/deepseek41/tp.rs:291 fails the two- and four-rank assertions; forcing the wrong pre-tokenizer at crates/tokenizer/src/pretok.rs:1565 fails the corpus comparison.
Validation: the extracted helper preserves both existing comparison bodies. All three corpora meet its size and byte-coverage checks. Independent page arithmetic covers every offset on 4, 16 and 64 KiB pages, including unaligned planes.
Gates: no pin, threshold or assertion relaxed; existing corpus assertions retained.
Escape catalog: no matching pattern. No ledger lessons are in force.

Notes

Dryer and crapper did not run because their Python modules are missing.
No local Rust build or hardware gate ran. The PR body lacks FAIL-first output for the revised checks. Its card evidence names earlier commits and contains no just gate-* commands with output.

Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bin/generate_ds41.rs, crates/gpu-gates/src/ds41_preflight.rs, crates/gpu-gates/src/lib.rs … and carries no gate run on a card (CONTRIBUTING's evidence list); a maintainer adds gpu-verified after one.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

@juliankang4

Copy link
Copy Markdown
Collaborator Author

The review is done and the contribution check passed, so I'm merging this.

@juliankang4
juliankang4 merged commit beb9044 into midagedev:main Nov 4, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gpu The card engine: crates/gpu*, crates/app host Host crates: qdot, threads, engram, engram-lab, runtime, sampler, levers, decision, vision, refset model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja needs-gpu Changes code a card must check, and carries no gate run on a card placement Placement planning: crates/placement tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant