Repository navigation
hf, model: prepare a GGUF split from a ModelOpt Qwen3.8 checkpoint folder - #540
Conversation
…e tensor scale an expert for a routed stack modelopt::linear reads the triple <stem>.weight (U8, two E2M1 codes a byte), <stem>.weight_scale (F8_E4M3, one a 16-value group) and <stem>.weight_scale_2 (one F32) and emits the existing 36-byte NVFP4 block (type 40) plus the tensor scale the GGUF file keeps as <stem>.scale. The nibbles move from ModelOpt's order (value 2i low, 2i+1 high) to the block's (j low, j+8 high); the scale bytes are copied, and a byte with bit 7 set or 0x7F is refused naming the tensor, row and group with the block decode's reason. modelopt::experts stacks a routed layer's experts as [k, rows, n_expert] with one tensor scale an expert, the layout of llama.cpp's _flush_nvfp4_experts. input_scale is named in the result and not read. Each tensor a lookup returns must hold exactly the bytes its shape needs, and a k/2 whose double overflows usize is refused, so a lookup other than the parser's cannot drop rows or wrap the width. The oracle is the ModelOpt rule e2m1 x weight_scale x weight_scale_2 in tests/fixtures/modelopt_nvfp4.py, which decodes both formats from their definitions: every row of a synthetic tensor (every defined scale byte, every code at every group position) and of the first four rows of layer 0's gate_proj of experts 0 and 1 of nvidia/Qwen3.8-Flash-Next-NVFP4 (range-read from shard 1 at fc694b54) decodes through dequant_row times the tensor scale to the reference's f32 bits.
… parts Q8Block::quantize_ref is quantize_row_q8_0_ref, the rule llama-quantize and the converters write Q8_0 weights with: d = amax / 127 stored as f16, each code roundf(x * (1 / d)). The engine's other two Q8_0 rules (the activation rule and ik's requant) code with 127 / amax and round half to even, and differ from it on about one code in a thousand, so a Q8_0 weight bloomery writes from BF16 needs this one to equal a mainline file's bytes. A value that is not finite, which the rule would code as 0, gives None. Q8Block::to_bytes is from_bytes's inverse. The decision crate's head fixture, which wrote the same rule out by hand, now calls it. Writer::tensor_parts takes a tensor's bytes as a sequence of parts, so a tensor larger than memory (a 48 GiB row table) goes out a part at a time; parts that do not add up to the declared size are refused after the fact and leave the writer broken. Writer::tensor still refuses a wrong length before writing. The test's fixture is eight blocks of Qwen3.8's layer-0 shared-expert gate: the BF16 values of nvidia/Qwen3.8-Flash-Next-NVFP4 (fc694b54) and the Q8_0 blocks unsloth's UD-Q4_K_XL (766911a6) holds for them. All eight equal the reference rule's bytes; in six the 127 / amax rule codes a value differently.
…lder prepare (a model bin) reads a Hugging Face folder through the folder reader, places every tensor in a format by the folder's quantization config, names and lays it out by the model's map, writes each format as its GGUF type by one table, and writes a split the server opens as it opens any GGUF. Shards are written as .part and renamed when whole; the output's filesystem must have the split and a tenth more free (model::fileio::free_bytes). A row table stored in parts reads each part by its own place and refuses a part whose type or tensor scale is not the first's. When the last shard is written, the split is opened with gguf::Split and its hyperparameters read by the server's own Hparams::read, so a split the server would refuse is not left as a success. hf::modelopt holds the table: type_of and normalize take a tensor's format and how its role reads it (a matrix a kernel reads, or a row table) to its GGUF type and repack. NVFP4 becomes GGUF's NVFP4 block with its tensor scale, one an expert for a routed stack (linear and experts, unchanged); BF16 and F32 become ggml's reference Q8_0, F32 or BF16 as the role asks; FP8 with one tensor scale read as rows becomes the F8 row type, bytes as stored. Every other pair, FP8 block and OCP MXFP4 among them, is refused by name: no GGUF type yet. logical_shape gives a packed weight's element shape for the map. hf::vocab writes a byte-level BPE tokenizer as GGUF's tokenizer keys by llama.cpp's rules: [PAD<id>] for an id without a token, added tokens control when special or shaped <|...|>, else user-defined, the merges, the special ids from tokenizer_config.json then the configs (of a list, the first; an id outside the vocabulary is refused by name), the repo's chat template. hf::schema names every key a reader accepts with the values it allows, and refuses any other key or value by name: tokenizer.json, its model and added tokens, tokenizer_config.json and generation_config.json each have a table, and an ignored key says why no result depends on it. Added tokens whose texts overlap (a proper suffix of one starting another) are refused, so serving's longest-first split equals the tokenizers library's leftmost one. Before any shard is written, the tokenizer serving builds from the header must split on exactly the added tokens and end generation at every id generation_config.json stops at. model::arch::qwen35moe::hf maps Qwen3.8-Flash-Next's checkpoint to the qwen4exp names, roles and keys as llama.cpp's converter (qwen4exp.py, qwen.py at 098ce526) writes them: the gated delta-rule V heads from grouped to tiled (the V rows of in_proj_qkv, in_proj_z, in_proj_a and b, the V channels of the conv taps, A_log, dt_bias and the columns of out_proj), A_log as -exp computed in f64 and rounded once, +1 on the zero-centred gammas, the indexer's index_qk_proj split into q and k rows (BF16), the conv taps squeezed, the routed experts stacked by id, and the 128 PLE parts in part order as one row table with its scale. The keys come from config.json and the PLE constants from the I64 tensors as stored. config.json, its text_config and rope_parameters have schema tables too: a setting qwen4exp computes with one value (norm_topk_prob, hidden_act, interleaved M-RoPE and the like) allows only that value. The next-token layers and the vision tower are left out. The tests map layers 0, 1 and 3 and the unlayered tensors of nvidia/Qwen3.8-Flash-Next-NVFP4 (fc694b54), placed by its config, to exactly the names and ggml dims of unsloth's UD-Q4_K_XL (766911a6), each Q8_0, F32 and BF16 tensor of that file to the same type; its qwen4exp keys equal those the map writes from config.json; each layout step against its definition on a small geometry; the table's lines and refusals; the tokenizer keys of a small BPE repo; and every schema key with one accepted and one refused value.
There was a problem hiding this comment.
Verdict: CLEAN: No must-fix behavior or quality defect survived the checks.
Non-blocking
⚠ Separate tokenizer import stages: crates/hf/src/vocab.rs:313 combines vocabulary construction, merge validation, special-token resolution and template selection in one function (R12).
Split vocabulary/merge import and special-ID/stop resolution into two local stage functions. Keep schema tables and output assembly in their current owner. This makes each accepted-input contract easier to audit before more formats arrive.
⚠ Repeat the complete conversion at this head: crates/model/src/bin/prepare.rs:268 validates the finished split, but the reported complete conversion predates changes to scale lookup and shard planning.
Run prepare on the NVFP4 checkpoint at the head SHA and attach its exit status, shard sizes and final split-open output. This closes the integration evidence gap before the serving change depends on these files.
Checked
Duplicates: 135 new Rust declarations searched. All four dryer pairs read: short error constructors and binary entry boilerplate; extraction would add elements. No actionable duplicate found.
Complexity: new HF vocabulary keys, Qwen parse/map/layer/apply, ModelOpt normalize/append and prepare run/served_as_hf were examined. Layer/apply growth is operation dispatch; the parsers and converter combine stages. Existing Vocab::load and Bpe::new grow to validate HF contracts.
Silent failure: 24 added fallback/conversion sites followed. Invalid conversions reach named errors; optional-file and absent-key defaults preserve their declared contracts.
Tests: static mutation review only; tests were not executed here. Changing Q8Block::quantize_ref's reciprocal/rounding, Writer::tensor_parts' length guard, expert_stack's ID check, schema::check's rejection, or normalize's companion lookup reaches assertions.
Tests: changing Step::apply's head permutation or numeric transform, part-scale equality, plan_shards' metadata budget, shard-size overflow check, or served_as_hf's identity checks reaches assertions.
Tests: dropping NFC, explicit stops, Unicode folding/classes, duplicate-merge ranking or unknown-byte removal reaches ID/attribute assertions; reading input_scale changes the asserted blocks. The corpus gate asserts exact HF IDs and reports a FAIL-first NFC run.
Gates: no tolerance moved; new model-tax rows carry dated PIN reasons. The corpus gate is hw_-prefixed and ignored.
Escapes: no C1–C4 pattern matched. Missing projections are rejected by the final Qwen4Exp required-tensor check.
Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bind.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)
Filed outside this PR: #541
|
The review is done and the contribution check passed, so I'm merging this. |
NVIDIA의 ModelOpt NVFP4 Qwen3.8 체크포인트 폴더를 서버가 그대로 여는 GGUF split으로 바꾸는
prepare도구를 추가하고, 함께 쓰는 tokenizer가 Hugging Face와 같은 token id를 내도록 맞춥니다.What and why
Part of #493, the line "NVFP4 reader: ModelOpt weights into bloomery's NVFP4 block".
nvidia/Qwen3.8-Flash-Next-NVFP4stores the routed experts as ModelOpt NVFP4 triples, the PLE table as F8_E4M3 parts with one scale, and the rest in BF16. Bloomery serves Qwen3.8 from a GGUF split. This PR addsprepare <folder> <out prefix> [--shard-gib n]incrates/model. It reads the folder with the safetensors reader and quantization config already on main, and writes a split thatSplit::openandBody38read as they read any GGUF. The tokenizer in that split encodes text to the same ids, and decodes ids to the same text, as the checkpoint's Hugging Face tokenizer.The four commits:
6c2f9ed1btokenizer: NFC runs only when the header saystokenizer.ggml.normalizer = "NFC", so existing GGUF files keep their encoding.94a0304ffhf: ModelOpt NVFP4 weights become GGUF's NVFP4 block with one tensor scale, or one scale an expert for a routed stack.11b5b4031gguf:Q8Block::quantize_ref, the reference Q8_0 weight rule (quantize_row_q8_0_ref), andWriter::tensor_parts, which writes one tensor part by part so the PLE table goes out one checkpoint part at a time.189c1b38bhf, model:prepare, the Qwen3.8 map, the tokenizer import and the input schema described below.What
preparechecks and writes:hf::modelopt::type_ofandnormalizemap a tensor's format and the way its role reads it to one GGUF type and repack. NVFP4 becomes the NVFP4 block with<stem>.scale. BF16 and F32 become Q8_0, F32 or BF16 as the role asks. FP8 with one tensor scale, read as a row table, becomes the F8 row type with its bytes as stored. Every other pair, FP8 block and OCP MXFP4 among them, is refused by name.Placed.companions), and the conversion reads exactly those. A table whose parts share a parent module's scale reads the parent's. An NVFP4 source must have two companions (block scale, then tensor scale); another count, a source the plan does not place, or a stack with mixed formats is refused by name.hf::safetensors::expert_stackchecks a routed stack for both the GLM and the Qwen3.8 map: expert ids exactly0..count, 2-D tensors of one shape, sources in id order.glm5next/hf.rsnow calls it.model::arch::qwen35moe::hfgives Qwen3.8's names, roles, layout steps andqwen4exp.*keys in the layout of the reference GGUF file: the gated delta-rule V heads from grouped to tiled order,A_logas-exp,+1on the zero-centred gammas, the indexer'sindex_qk_projsplit into q and k, routed experts stacked by id and the 128 PLE parts in part order. The next-token layers and the vision tower are left out.hf::schemagives every JSON filepreparereads a table of the keys it accepts and the values each key allows:config.jsonwithtext_configandrope_parameters,tokenizer.json,tokenizer_config.jsonandgeneration_config.json. Any other key or value is refused by name, for example<path>.<key> is not a key this converter reads. A setting Qwen3.8's compute path implements with one value (hidden_act,norm_topk_prob, interleaved M-RoPE and the like) allows only that value, because GGUF has no key for it and another value would be served as this one.hf::quant_configuses the same check for its layer entries.tokenizer.bloomery.eog_token_ids, a sorted, nonempty U32 array, and the tokenizer stops at exactly that set when the key is present. A header without the key keeps the name-based defaults. Before any shard is written,prepareopens its header through the serving tokenizer and refuses it unless the added-token split, the stop set, the control types, the BOS/EOS flags and the special ids equal Hugging Face's.--shard-gib(48 by default) unless one tensor with its scale is larger by itself.model.vocab. A repeated pair keeps its last rank, as Hugging Face's BPE does. When the serving tokenizer loads an imported header, it compares every token's rendered bytes with the Hugging Face ByteLevel decoding of the original spelling and refuses a mismatch with the id and spelling. Added tokens keep their spelling: serving matches and decodes them as written, so▁xstays▁x.qwen35vocabulary with that key encodes by Hugging Face's rules: the regex classes of Unicode 14.0 (characters added in 15.0 and 15.1 get no letter, mark or digit class), Unicode case folding in contractions ('ſmatches like's), and BPE that skips a symbol a sparse vocabulary does not have. A header with the key and another pre-tokenizer, or with SentencePiece, is refused by name. Declared NFC uses the Unicode 9.0 tables Hugging Face normalizes with. GGUF files without the key encode as before.prepareimports the checkpoint reader and tensor map directly frommodel::arch::qwen35moe::hf. Its entry callsCheckpoint::parse, which refuses anyarchitecturesvalue other thanQwen4ExpForConditionalGenerationby name before it maps a tensor. For that reasontools/check-arch.shgets onedispatchentry,'crates/model/src/bin/prepare.rs use', under the same policy as the existingr8conv.rs useentry for a family-specific binary. The entry covers only the binary'suselines. Intools/model-tax.tsvthe registry's qwen row stays at its baseline of 16. The converter gets a dated qwen row of 1, andcrates/hf/src/vocab.rsa dated row of 5 for theqwen35tokenizer pipeline name and regex.New dependency:
unicode-normalization-alignments = "=0.1.12"incrates/tokenizer, which addssmallvec 1.16.3toCargo.lock. Hugging Facetokenizers0.21.0 normalizes with this crate, whose tables are Unicode 9.0.unicode-normalization0.1.24 has Unicode 16 tables: it composesU+11935 U+11930and reordersa U+0305 U+0EBA, so a tokenizer using it gives other ids than Hugging Face for such text. The crate is MIT or Apache-2.0 and not yanked; its 0.1.12 release is from 2019-12-30. It passescargo denywith the existing policy (results below).Release notes: Added:
preparewrites a GGUF split from NVIDIA's ModelOpt NVFP4 checkpoint of Qwen3.8-Flash-Next.Code shape
The review reads these first. A box left unticked needs one line of why.
linearandexperts. Packed shapes come fromquant_config::Format::logical, the F8 row type isGgmlType::F8E4M3_ROWS, and names come fromqwen35moe::names. JSON files are read by onehf::read_json, key tables are checked by onehf::schema::check, and routed stacks are built by oneexpert_stackthat GLM and Qwen3.8 share. A tensor's scale names come only from the plan.vocab_sizeand the embedding rows. A merge outside the vocabulary, a token whose served bytes differ from Hugging Face's decoding, and a V-head column move that would split a quantization block are refused before anything is written.unsafe. The two newmodel-tax.tsvrows carryPIN(2026-10-20)and their reasons.cargo fmtandcargo clippyare clean on what I touched; the lint count did not go up.Duplication found or removed (
path:line):crates/hf/src/quant_config.rs:253(the JSON read, nowhf::read_json),crates/hf/src/quant_config.rs:363(a hand-written key list, nowhf::schema::check),crates/model/src/arch/glm5next/hf.rs:182(the expert stack checks, nowhf::safetensors::expert_stack) andcrates/decision/src/gguf_head.rs:522(the Q8_0 rule written out by hand, nowQ8Block::quantize_ref).What I ran
This head (
189c1b38), on a Linux machinejust contrib-check --tier t0:DONE tier=t0 total=94 red=0 wall=503s.cargo test --release --locked -p bloomery-hf:test result: ok. 82 passed; 0 failed.cargo test --release --locked -p bloomery-model --lib qwen35moe::hf:test result: ok. 6 passed; 0 failed.cargo test --release --locked -p bloomery-model --bin prepare:test result: ok. 3 passed; 0 failed; 1 ignored. The ignored test is the corpus gate below, which needs a checkpoint folder.bash tools/check-arch.sh:check-arch: ok.bash tools/check-model-tax.sh check --base 819d3d70:check-model-tax: ok.cargo fmt --all -- --checkandcargo clippy --release --locked --all-targets -p bloomery-hf -p bloomery-tokenizer -p bloomery-gguf -p bloomery-model -- -D warningsexit 0 with no warnings.Tokenizer against Hugging Face
The oracle is Hugging Face
tokenizers0.21.0 on the pinnedtokenizer.json(SHA-2560997f410c57a1f4e53b09e4be8f4a172d90edd9564368fb0847030937229b9f3), which both checkpoint folders hold:nvidia/Qwen3.8-Flash-Next-NVFP4atfc694b54andnvidia/Qwen3.8-Flash-Next-FP4-Localatb9ce18a6. The test checks that digest before it compares.just gate-prepare-corpusimports the folder's tokenizer, writes its GGUF header, loads it through the serving tokenizer and encodes the 2,396 inputs ofcrates/hf/tests/fixtures/qwen3.8-hf-encode.json.gz. The inputs cover the tokenizer gate's cases, added tokens, NFC pairs, Unicode 15.0 and 15.1 characters, contractions in every case, Korean, code, emoji, and a sample of assigned codepoints, each in six contexts. Reproduce with:(
BLOOMERY_BOX_LOCAL=1runs it on the local machine.)These checks ran at
4d608b8d. Between that commit and this head, the tokenizer, the importer and every function body inprepareare the same; the diff is four files with six insertions and six deletions inuselines, a doc link and thecheck-arch.shandmodel-tax.tsvrows.HF-ENCODE cases=2396 ids=27616 differences=0,test result: ok. 1 passedHF-ENCODE cases=2396 ids=27616 differences=0,test result: ok. 1 passedHF-ENCODE cases=2396 ids=27616 differences=636,test result: FAILED, exit 101exported=248320 hf_ids=248077 unused=243 rejected=0The 243 unused ids have no Hugging Face token. They are exported as
[PAD<id>]fillers and decode to nothing.A wider sweep ran at
56ee45f5, where the tokenizer crate,crates/hf/src/vocab.rsand the test fixtures are the same as at this head. It encodes 447,619 texts built from every assigned, unassigned and private-use codepoint, NFC composites and combining marks:HF-ENCODE cases=447619 ids=8805582 differences=0.Corpus gate output at 4d608b8d (both folders and the FAIL-first run)
The
source=field names the folder the corpus fixture was generated from. For the FP4-Local run the test checks that this folder'stokenizer.jsonhas the same SHA-256. In the FAIL-first output, 636 lines list an input with both id sequences; four are shown.Full conversion against a reference GGUF, on one DGX Spark
The reference is unsloth's
UD-Q4_K_XLof the same model (unsloth/Qwen3.8-Flash-Next-GGUFat766911a6), converted from the base model's BF16. Every tensor that file keeps in F32, Q8_0 or BF16 is compared byte for byte with the tensor of the same name in the prepared split.This conversion ran at
db05af59. That commit has the format table, the Q8_0 rule, the layout steps and the map, but not yet the input schema, the stop-set key, the Hugging Face encode rules, the scale lookup through the plan or the shard budget. The full conversion was not repeated at this head.UD-Q4_K_XLheaderstest arch::qwen35moe::hf::tests::layers_map_to_unsloth_s_names_dims_and_types ... okqwen4exp.*keys fromconfig.jsonUD-Q4_K_XLkeystest arch::qwen35moe::hf::tests::keys_equal_unsloth_s ... okUD-Q4_K_XLbytescompared F32/Q8_0/BF16 tensors: equal 1062, different 22, absent in ours 0qwen4exp.*keys of the real splitUD-Q4_K_XLkeysqwen4exp keys: 37 of 37 equal; differ: []UD-Q4_K_XLtokenizer.ggml.merges: equal1,062 of the 1,084 compared tensors are byte-equal to the reference. Of the other 22, 17 are
ssm_atensors that differ in one or two of their 48 values by one unit in the last place (see below). The other 5 areffn_down_expsof layers 2, 4, 30, 46 and 47, which theUDmix requantizes to Q8_0 from BF16; the NVFP4 checkpoint stores them in NVFP4, so the split keeps them NVFP4.nvidia/Qwen3.8-Flash-Next-NVFP4atfc694b54:ours: 1369 tensors, 124653850116 bytesin 4 shards,prepare rc 0 secs 314.preparethen opened it withgguf::Splitand read it with the server'sHparams::read:prepare: the split opens: 48 layers, 1369 tensors.0f0668deran the importer and the map on both folders' tokenizer files and safetensors headers, without tensor data. Both map 1224 tensors, with all 144 routed stacks in expert order (MAP-OK ... mapped=1224 stacks=144). The NVFP4 folder gives every mapped tensor a GGUF type (with_gguf_type=1224).Dependency
cargo deny checkwith cargo-deny 0.20.2 at704e9282, which has this head'sCargo.tomlfiles andCargo.lock:advisories ok, bans ok, licenses ok, sources ok.What I ran into
None of these block this PR.
ssm_avalues come from a float32exp, which is not correctly rounded;preparecomputes-exp(A_log)in f64 and rounds once. 17 of the 36ssm_atensors differ in one or two values by one unit in the last place, for exampleDIFF blk.1.ssm_a: 1 of 48 f32 values, max relative 9.3e-08.chat_template.jinja. The reference GGUF ships an edited template, so the two differ.Body38, which is a separate change. The PR that serves Qwen3.8 from this split records its decode speed.Hardware (if the change is for a machine)
The change is for DGX Spark.
prepareis host-only Rust. The full conversion ran on one DGX Spark. The tests, the corpus gate, the decode check, the sweep andcargo denyran on a Linux machine.AI help
AI 코딩 에이전트가 코드를 작성한 후 설명을 썼고, 테스트를 마쳤습니다. diff 리뷰와 PR 초안 리뷰는 제가 직접 했습니다.