Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

feat(stream): admit Kimi K2 through transformers' own DeepseekV3Config behind a guard (#2107)

Alpamys Makazhan90e492178dd2
diff --git a/benchmarks/gate-kimi-k2-admission.md b/benchmarks/gate-kimi-k2-admission.md
new file mode 100644
index 00000000..44895340
--- /dev/null
+++ b/benchmarks/gate-kimi-k2-admission.md
@@ -0,0 +1,579 @@
+# Gate: layer streaming admits Kimi K2 through transformers' own DeepseekV3Config
+
+Status: **G1a fails as registered on transformers' rope_scaling normalisation; G1b, G1c, G2
+and G3 pass** (CPU only; run 2026-10-21, re-run after the review round in section 7, which
+hardened the guard). G1a: FAIL, 42 of 43 fields. Sections 1-3 are the rule
+as committed in `a236a4e49` before any gate run, unchanged since; sections 4-6 are filled from the
+run. No GPU, no K2 weight download, no K2 or 1T training run.
+
+## 1. Question
+
+Kimi-K2-Base and Kimi-K2-Instruct (moonshotai) publish a `config.json` with
+`model_type: "kimi_k2"` and an `auto_map` onto the repository's own
+`configuration_deepseek.DeepseekV3Config` and `modeling_deepseek.DeepseekV3ForCausalLM`.
+Their weights are DeepSeek-V3's published FP8 block format. Layer streaming is Soup's
+implementation of layer-to-layer streaming of a frozen base (L2L, Pudipeddi et al. 2020),
+and since #1933 it builds the streamed model from transformers' own class with
+`trust_remote_code=False`. A real K2 therefore never reaches the architecture allowlist:
+`AutoConfig.from_pretrained(trust_remote_code=False)` raises transformers' "contains custom
+code" error first (`trainer/stream_setup.py` and `build_meta_skeleton` in
+`utils/layer_stream_runtime.py`).
+
+The change under test loads the raw `config.json` dict into transformers' native
+`DeepseekV3Config` (`model_type` rewritten to `deepseek_v3`, `auto_map` dropped), but only
+after a guard finds no field whose value would make the native class compute differently
+from K2's own modelling code. Every K2 variant that fails the guard is refused by name,
+naming the field and its value; Kimi-K2-Thinking (compressed-tensors INT4) is one of them.
+transformers does the same mapping itself for the text tower of Kimi K2.5
+(`Kimi_K25Config.__post_init__` maps a `kimi_k2` text config onto `deepseek_v3`).
+
+Does the rewritten config carry every K2 field (G1)? Does the streamed native model then train
+on exactly the numbers a resident native model on the same weights does (G2)? Does the disk
+pre-flight size a real K2 cache from its real index (G3)?
+
+## 2. Decision rules (written before any run)
+
+Every tensor comparison is `torch.equal` (bit-exact). No tolerance is substituted after the
+fact; a failing check is reported with its maximum absolute difference.
+
+Inputs, read as JSON data only; no K2 Python file is imported or executed anywhere in this
+gate. The files were fetched (text only) into the session scratchpad:
+
+| file | revision | sha256 |
+|---|---|---|
+| Kimi-K2-Base `config.json` | `ce72df012259dcc55d945e890f815fe7ef69159c` | `8c13ae1049df55f29b3bdcae69a562433f243ff70dac251d819ecad8dbdf7439` |
+| Kimi-K2-Instruct `config.json` | `fd1984e2b7a3350dbf7305fe73a4ede25c14de50` | same bytes as Base |
+| Kimi-K2-Thinking `config.json` | `a51ccc050d73dab088bf7b0e2dd9b30ae85a4e55` | `666ee58fc3871ecc369a22bc8c100075c2ad24ccbe8b3e336fa5f726e6111c15` |
+| Kimi-K2-Base `model.safetensors.index.json` | as Base | `c1f1d16c853f20467ae81361d2a92223650d39efa005f9c872a7cc14425ddcbc` |
+| `modeling_deepseek.py` (all three) | as above | `ce753fc9076ce13ce9557e680e2f5bd68ae8929a8225772968a9a22a1d17b7d4` |
+
+### G1, config (CPU, no model)
+
+**G1a, mapping.** Soup's loader (`load_stream_model_config`) is run on a temporary folder
+holding the real Base `config.json`, and again on one holding the Instruct file. It must
+return a `DeepseekV3Config` whose `model_type` is `deepseek_v3` and that has no `auto_map`.
+For every key of the raw JSON except `model_type` and `auto_map`, the loaded config must hold
+the same value: `getattr(config, key) == raw[key]`. Two transformers normalisations are
+named here in advance; an exploratory probe during design (a scratch script, before this
+rule was written) showed that transformers applies them to any `config.json`, and they are
+the only ones admitted:
+
+- `rope_theta` is read as `config.rope_parameters["rope_theta"]`;
+- `torch_dtype` is compared as `str(config.torch_dtype) == "torch." + raw["torch_dtype"]`.
+
+Also: every key of the raw `rope_scaling` equals `config.rope_parameters[key]`, and
+`config.rope_parameters["rope_type"] == "yarn"`.
+
+Controls (each must hold, or G1a pins nothing):
+
+- today's failure: `AutoConfig.from_pretrained(folder, trust_remote_code=False)` on the same
+ folder raises `ValueError`;
+- AutoConfig equivalence: the same dict with `model_type: deepseek_v3` and no `auto_map`,
+ written to a second folder and loaded by `AutoConfig.from_pretrained`, gives a `to_dict()`
+ equal to the K2 path's `to_dict()` except `_name_or_path`;
+- the loader never calls transformers' dynamic-module loader
+ (`get_class_from_dynamic_module` replaced by a function that fails the test), and the raw
+ dict it reads is not mutated.
+
+Reported, no threshold: every warning or log record at WARNING level or above emitted
+during the load.
+
+**G1b, the guard.** The guard checks, in this order, and a failure names the field and its
+value:
+
+| field | admitted | why the native class would compute differently otherwise |
+|---|---|---|
+| `architectures` | exactly `["DeepseekV3ForCausalLM"]` | another head is not the decoder this mapping was checked on |
+| `topk_method` | `"noaux_tc"` | K2's router implements only this; the native router always runs it |
+| `scoring_func` | `"sigmoid"` | K2's router implements only this; the native router always uses it |
+| `n_group` | `1` | K2 masks unselected groups with 0.0, the native router with -inf; with one group nothing is masked |
+| `topk_group` | `1` | as `n_group` |
+| `num_experts_per_tok` | an int >= 2 when `norm_topk_prob` is true or absent | K2 renormalises the top-k weights only when top-k > 1; the native router always does |
+| `moe_layer_freq` | absent or 1 | K2 makes only every n-th layer an MoE layer; the native class makes every layer past `first_k_dense_replace` one |
+| `ep_size` | absent or an int <= 1 | K2 splits the experts across processes |
+| `n_routed_experts` | an int >= 1 | `None` makes K2 all-dense; the native class cannot build it |
+| `n_shared_experts` | an int >= 0 | `None` drops K2's shared expert; the native class always builds one |
+| `num_key_value_heads` | absent or equal to `num_attention_heads` | K2's MLA ignores it; the native class divides by it |
+| `rope_interleave` | absent or true | K2 always applies the interleaved rotary layout; the native class reads this flag |
+| `rope_scaling` | absent, or a yarn dict as below | |
+| `quantization_config` | absent, or a spelling `utils/fp8_block.py`'s `fp8_block_size` accepts | Soup dequantises only DeepSeek-V3's block FP8 |
+
+A `rope_scaling` dict is admitted only when: its `type` is `"yarn"` (and `rope_type`, if
+present, is too); it has no key outside `type`, `rope_type`, `factor`,
+`original_max_position_embeddings`, `beta_fast`, `beta_slow`, `mscale`, `mscale_all_dim` (the
+keys K2's yarn reads; the native yarn reads more, such as `attention_factor` and `truncate`);
+`factor` is a number; `original_max_position_embeddings` is present (K2 defaults it to 4096,
+the native class to `max_position_embeddings`); `beta_fast` and `beta_slow` are not 0 where
+present (the native yarn replaces a 0 with its default); and `mscale` is consistent with
+`mscale_all_dim` (if `mscale_all_dim` is non-zero, `mscale` must be non-zero; otherwise
+`mscale` must be absent or 1), the cases where the native attention factor equals K2's.
+
+- **PASS (guard)**: the unmodified Base and Instruct dicts pass. For every row above (and for
+ each `rope_scaling` condition), a copy of the real Base dict with exactly that one field
+ changed to a failing value is refused with `UnsupportedKimiK2Error`, whose message names the
+ field and the value. The FP8 spellings `fp8_block_size` accepts (with `scale_fmt: "float"`,
+ without `fmt`) pass. Thinking is refused; the record names the first failing field
+ (expected, by reading: `quantization_config`, `compressed-tensors`). A refusal never prints a
+ raw control byte from the config.
+
+**G1c, the guard is necessary on the numeric rows (reference transcribed by hand).** K2's
+remote code does not import on transformers 5.17 (the investigation), and this gate does not
+try to run it. Instead the router (`MoEGate.forward`) and the yarn rotary embedding plus its
+softmax scale are transcribed from `modeling_deepseek.py`, read as text, into the test file,
+and compared with the native `DeepseekV3TopkRouter`, the native rotary embedding and the
+native attention's `scaling`:
+
+- equal (`torch.equal` / `==`) on K2's own values and on every admitted value tested;
+- different on each refused variant tested: `n_group` 2 with a negative router bias,
+ `num_experts_per_tok` 1 with `norm_topk_prob`, no `original_max_position_embeddings`,
+ `mscale_all_dim` without `mscale`, `mscale` != 1 without `mscale_all_dim`, a 0 `beta_fast`,
+ and an `attention_factor` key. A transcription that raises where the native module computes
+ counts as different (by reading, a 0 `beta_fast` divides by zero in K2's yarn).
+
+A transcription can be wrong; this is evidence for the guard, not vendor-code parity.
+
+### G2, streamed-vs-resident parity on a tiny K2-like checkpoint (CPU fp32)
+
+Model: a seeded random native `DeepseekV3ForCausalLM`: vocab 128, hidden 64, 3 layers with
+`first_k_dense_replace=1`, 8 routed experts plus a shared expert, top-k 2, `n_group=1`,
+`topk_group=1`, `q_lora_rank` 24, `kv_lora_rank` 16, `qk_nope_head_dim` 16,
+`qk_rope_head_dim` 8, `v_head_dim` 16, 4 heads, yarn rope (`factor` 32,
+`original_max_position_embeddings` 64, `max_position_embeddings` 2048, `beta_fast` 1,
+`beta_slow` 1, `mscale` 1, `mscale_all_dim` 1, `rope_theta` 50000), `routed_scaling_factor`
+2.827, and `e_score_correction_bias` set to large random values. Weights saved bf16 (the
+bias float32). `config.json` is the real Base dict with these dimensions substituted: it
+keeps `model_type: kimi_k2`, `auto_map`, `architectures`, `topk_method`, `scoring_func`,
+`moe_layer_freq`, `seq_aux`, `aux_loss_alpha` and `num_nextn_predict_layers: 0`. Every layer
+also carries a stale BF16 `model.layers.N.self_attn.rotary_emb.inv_freq` (shape [7], filled
+with a constant no rope uses), as the real checkpoint carries 61 of them. The folder holds no
+`.py` file. The FP8 copy is written by `benchmarks/harness/fp8_block_quantize.py` (block
+16 x 32) from the bf16 checkpoint.
+
+Resident control: `DeepseekV3ForCausalLM` from a `DeepseekV3Config` built in the test from
+keyword arguments (the native `rope_parameters` spelling, not through Soup's loader), fp32,
+`load_state_dict(strict=True)` from the checkpoint's tensors minus the stale `inv_freq` keys
+(the dropped set must be exactly those keys); for the FP8 cells, from the test's independent
+block-loop dequantisation of the FP8 copy. `per_expert` cells set the resident experts
+implementation to `eager`, as the FP8 gate does. LoRA: the targets Soup resolves for the
+loaded config under `target_modules: auto`, rank 4, the same seeded adapters on both sides.
+
+Cells, CPU, `dtype=float32`, `quantization: none`: {fused, per_expert} x {bf16 source, FP8
+block source}.
+
+- **PASS (model)**: in every cell the streamed model's logits, loss and every LoRA gradient
+ equal the resident control's; both have the same set of LoRA gradients, and at least one
+ layer-0 LoRA gradient is non-zero.
+- **PASS (stale key)**: the runtime streams no `rotary_emb.inv_freq` key into any layer, and
+ the streamed model has no per-layer `rotary_emb` module. Whether the sharder writes the key
+ into the layer files is reported.
+- **Controls** (each must hold, or the cells pin nothing): the resident model with the
+ default rope instead of yarn gives different logits; zeroing the router bias changes the
+ logits; the FP8-dequantised resident differs from the bf16 resident; the streamed model's
+ config is a `DeepseekV3Config` with `model_type` `deepseek_v3`, no `auto_map` and (FP8
+ cells) no `quantization_config`; no dynamic-module load happens.
+- **FAIL**: any check false.
+
+### G3, the real index (CPU, headers only, nothing downloaded)
+
+No K2 shard is local, so the headers are synthesised: names from the real Base index,
+shapes from the real config, and dtypes from the header facts the investigation recorded:
+F8_E4M3 for every `*.weight` that has a `*.weight_scale_inv` beside it; F32 for those scales
+(shape `[ceil(rows/128), ceil(cols/128)]`) and for `mlp.gate.e_score_correction_bias`; BF16
+for the norms, the embeddings, `lm_head`, the router weight and the stale
+`rotary_emb.inv_freq`. The stale key's shape is [56]: during design, a probe showed that it
+is the shape for which the map's byte total equals the index's `total_size` exactly ([32],
+`qk_rope_head_dim / 2`, leaves 2,928 B unaccounted for).
+
+- **G3a, PASS**: the synthetic map's key set equals the index's key set (139,644 keys), and
+ its byte total equals the index's `metadata.total_size`, 1,029,173,256,720 B.
+- **G3b**: Soup's `estimate_shard_cache_bytes` runs over the map (only `read_header` is
+ replaced, to serve it; every other step is Soup's), with `dtype=bfloat16`, the arch
+ `stream_arch_of` returns for the config Soup's loader builds from the real `config.json`,
+ `quant=nf4`, double quantisation on, the quant suffixes of
+ `quantised_layer_suffixes(build_meta_skeleton(<folder with the real config>, quant="nf4"))`,
+ `num_hidden_layers` 61, the config's `quantization_config`, in both layouts.
+ **PASS**: no refusal, and in both layouts every layer's payload and the payload outside the
+ layers equal an oracle computed in the gate script from the shapes alone (NF4 with double
+ quantisation per weight of `n` elements: `ceil(n/2) + ceil(n/64) + 4*ceil(ceil(n/64)/256) + 4`
+ bytes; everything else at its stored dtype).
+- Reported: the total (payload plus the header and index allowances) and the RAM-tier bytes
+ for each layout, compared with the investigation's figures (per_expert about
+ 533,246,623,322 B, fused about 2,039,152,149,798 B). An exact match is reported as one; a
+ difference is reported with its size and explained, not adjusted, and is not a FAIL by
+ itself.
+
+### Mutation checks
+
+Each guard row, each `rope_scaling` condition and each rewrite step (`model_type`, `auto_map`)
+is altered in the source, a named test must fail, and the file is restored byte for byte
+(sha256 checked). A mutation no test catches is reported and the test strengthened.
+
+## 3. Not shown here
+
+- **Parity with K2's own code.** Not run: the remote code does not import on transformers
+ 5.17, and Soup never executes it. G1c compares against a hand transcription only.
+- **Known numeric differences from K2's own code**, not gated: the MoE combine (K2 sums the
+ weighted expert outputs in fp32 and rounds once; the native class rounds each weighted
+ output to the model dtype and accumulates with `index_add_`, bf16 rounding noise), eager
+ versus sdpa attention, and the router bias held as a Parameter (K2) versus a float32
+ buffer (native; both float32 in the checkpoint).
+- **The tokenizer.** K2's tokenizer exists only as remote code and needs `tiktoken`; it is
+ not exercised here.
+- No GPU, no NF4 model parity (those tests run only on CUDA), no real K2 weights, no K2 or 1T
+ training run, no throughput.
+
+## 4. Box state
+
+- The RTX 5070 Laptop box with its GPU unused: every process ran with `CUDA_VISIBLE_DEVICES=-1`
+ (`torch.cuda.is_available()` False in the gate report). 32 logical CPUs, 31.7 GiB RAM
+ (34,070,192,128 B); 11,084,537,856 B (10.3 GiB) available when the gate script started, and at
+ least 6 GiB free before every pytest process. Other Claude sessions shared the machine.
+- Software: Python 3.12.10, Windows 11 26200, torch 2.14.0+cu130, transformers 5.17.0,
+ bitsandbytes 0.50.2 (CPU), safetensors 0.8.0. `tiktoken` 0.14.0 happens to be installed; no
+ tokenizer was loaded.
+- Code: the rule is `a236a4e49`. Every gate ran on `c5b723dfc` (code, tests and docs), with a
+ clean working tree: G2, and the in-test halves of G1 and G3, as `tests/test_kimi_k2_streaming.py`
+ (115 tests, all passed, 24.6 s); G1 and G3 on the real files as
+ `benchmarks/harness/kimi_k2_gate.py --k2-dir <the scratchpad copies>` (peak RSS 1.0 GB).
+- Nothing was downloaded. The real files were text-only copies fetched earlier into the session
+ scratchpad (section 2's table; sha256 re-checked by the gate script). No K2 Python file was
+ imported or executed: the loader's dynamic-module hook was replaced by a function that fails,
+ and it was called 0 times.
+
+## 5. Results
+
+### G1, config: G1a FAIL; G1b PASS; G1c PASS
+
+**G1a: FAIL, 42 of 43 fields.** On the real Base and Instruct files (byte-identical, sha256
+`8c13ae10...7439`; the test file's `K2_BASE_CONFIG` equals the real Base dict), Soup's loader
+returns a `DeepseekV3Config` with `model_type` `deepseek_v3` and no `auto_map`. Of the 43 raw keys
+compared, 42 hold the same value under the rule, with its two named normalisations (`rope_theta`
+and `torch_dtype`). The 43rd, `rope_scaling`, does not compare equal: transformers adds two keys to
+it, `rope_theta: 50000.0` and `rope_type: "yarn"`. The rule admits no other normalisation, so G1a
+fails as registered. The verdict stands; the rule is not amended.
+
+Controls, all held, on both files:
+- today's failure: `AutoConfig.from_pretrained(trust_remote_code=False)` raises `ValueError: The
+ repository ... contains custom code which must be executed ...`;
+- AutoConfig equivalence: the loader's `to_dict()` equals `AutoConfig`'s for the same dict spelled
+ `deepseek_v3` without `auto_map`, except `_name_or_path`, and each `name_or_path` is its folder;
+- no dynamic-module load (0 calls); `config.json` bytes unchanged; the in-memory raw dict is not
+ mutated (deep copy, pinned by a test and by the `rewrite-deepcopy` mutation).
+
+Reported: no Python warning and no `transformers` log record at WARNING or above during either
+load.
+
+#### G1a: analysis done after the verdict (not part of the registered rule)
+
+- **The same additions on a native config.** `AutoConfig.from_pretrained` on the real Base dict
+ spelled `deepseek_v3` without `auto_map` gives a `DeepseekV3Config` whose `rope_scaling` holds K2's
+ seven keys plus the same two, `rope_theta: 50000.0` and `rope_type: "yarn"`. They come from
+ transformers' rope standardisation, which writes into the `rope_scaling` dict it is handed, for any
+ DeepSeek-V3 config.
+- **Nothing K2 declares is lost or changed.** Each of K2's seven `rope_scaling` keys keeps its
+ value, and `rope_parameters` holds all of them plus those two.
+- **Why the rule missed it.** The exploratory probe before the rule handed transformers a shallow
+ copy, so the raw dict it then compared against had received the same two keys.
+- **Why it does not block admission.** G2 compares what the config computes. The streamed model,
+ built from the `kimi_k2` folder through this loader, is bit-exact against a resident model whose
+ config was built independently in the native spelling, with the same yarn rope, in every cell.
+- `tests/test_kimi_k2_streaming.py` pins the observed behaviour exactly: the seven values equal,
+ the two additions named.
+
+**G1b.** Unmodified Base and Instruct pass. 39 refusal cases on the real Base dict (every row of the
+table, each `rope_scaling` condition, absent spellings, non-int and non-mapping spellings) are each
+refused with `UnsupportedKimiK2Error`, naming exactly that one field and its value; 21 admitted
+variants pass (absent optional fields, the accepted FP8 spellings with `scale_fmt: "float"` and
+without `fmt`, an `mscale` pair, top-1 without renormalisation, and Thinking's own non-quantisation
+values). A refusal never carries a raw ESC, BEL or U+202E and is bounded in length.
+
+Thinking (sha256 `666ee58f...1c15`) is refused. Its only guard failure, so the first, is
+`quantization_config.quant_method='compressed-tensors'`, as expected by reading. It differs from
+Base in 57 keys, most of them serialised generation defaults; the guard-relevant ones are
+`quantization_config`, `rms_norm_eps` (1e-05), `rope_scaling.factor` (64.0),
+`max_position_embeddings` (262144), `ep_size` (1) and the token ids, and all but
+`quantization_config` are admitted values. With its `quantization_config` removed it passes the
+guard (`thinking-unquantised`); that copy was not streamed.
+
+**G1c.** The hand transcriptions of K2's `MoEGate.forward` and its yarn rotary embedding and
+softmax scale agree with the native modules where the guard admits, and differ where it refuses:
+- router at K2's values (384 experts, top-8, `n_group` 1, `topk_group` 1): indices and weights
+ `torch.equal`. `n_group` 2 with an all-negative biased score: different experts (K2's 0.0 fill
+ beats them). Top-1 with `norm_topk_prob`: same expert, different weight (K2 does not
+ renormalise);
+- rope over 4096 positions: cos, sin and the attention scale equal on 7 admitted variants (the
+ published yarn, no scaling, `mscale` 1 alone, no `mscale` pair, an `mscale` pair of 0.707,
+ default betas, factor 8); different on 4 refused ones (no `original_max_position_embeddings`,
+ `mscale_all_dim` without `mscale`, `mscale` 0.707 alone, an `attention_factor`), and on a zero
+ `beta_fast` the transcription raises `ZeroDivisionError` where the native class silently uses 32.
+
+### G2, parity: PASS
+
+- **Model, 4 of 4 cells** (`test_the_streamed_k2_matches_the_resident_native_model_bit_exactly`):
+ fused / per_expert x bf16 source / FP8 block source (16 x 32). Logits, loss and every LoRA
+ gradient of the streamed model, built from the `kimi_k2` folder through Soup's loader, are
+ `torch.equal` to the resident control's; both have the same set of LoRA gradients (the targets
+ Soup resolves: `q_a_proj`, `q_b_proj`, `kv_a_proj_with_mqa`, `kv_b_proj`, `o_proj`), and each cell
+ has a non-zero layer-0 LoRA gradient. No dynamic-module load in any cell.
+- **Stale key**: the sharder writes `self_attn.rotary_emb.inv_freq` into every layer file as stored
+ (pinned), the runtime streams it into no layer (no `rotary_emb` key in any layer's active keys),
+ and the streamed model has no per-layer `rotary_emb` module, in both layouts.
+- **Controls**, all held: the default-rope resident differs from the yarn resident; zeroing the
+ router bias changes the logits; the FP8-dequantised resident differs from the bf16 resident; the
+ streamed config is a `DeepseekV3Config`, `model_type` `deepseek_v3`, no `auto_map`, no
+ `quantization_config` (both sources), and its decoder linears are plain `nn.Linear`.
+- **Deviation from the rule's wording**: the resident control is loaded with
+ `DeepseekV3ForCausalLM.from_pretrained(output_loading_info=True)` from a copy of the checkpoint
+ without the stale keys, and the test requires empty `missing_keys`, `unexpected_keys` and
+ `mismatched_keys`, instead of `load_state_dict(strict=True)` with the stale keys dropped.
+ transformers 5.17 saves the fused experts as per-expert keys (the real index's layout), which
+ only `from_pretrained`'s conversion maps back onto the fused module, so `load_state_dict` could
+ not load them. The check is at least as strict.
+- **Sensitivity** (section 6): the cells fail when the rewrite drops `rope_scaling` or changes
+ `rms_norm_eps`, when the loader stops taking the K2 path, and when `build_meta_skeleton` stops
+ using the loader.
+
+### G3, the real index: G3a PASS, G3b PASS
+
+**G3a.** The header map rebuilt from the real Base index names (sha256 `c1f1d16c...dcbc`) and the
+config has the index's 139,644 keys and file assignments, and its byte total equals the index's
+`metadata.total_size`, **1,029,173,256,720 B** (F8_E4M3 1,023,893,241,856; BF16 5,029,941,936; F32
+250,072,928). It equals, key for key, the map `tests/test_kimi_k2_streaming.py` derives from the
+config alone, which the test pins at the same count and total.
+
+**G3b.** The meta probe of the real config (61 layers, NF4, 5.0 s on the meta device) reports 11
+quantised suffixes: the five MLA projections, the dense MLP's three, and the shared expert's three;
+the router weight is not among them. Over the map, with `dtype=bfloat16`, arch `deepseek_v3`,
+double quantisation on and the 61 real source files, `estimate_shard_cache_bytes` refuses nothing
+and equals the shape-only oracle in every layer and outside the layers, in both layouts:
+
+| layout | layer payload | other payload | header + index allowance | total | RAM tier |
+|---|---|---|---|---|---|
+| per_expert | 528,527,512,320 | 4,697,635,904 | 21,460,490 + 25,216 | **533,246,633,930** | 9,779,755,776 |
+| fused | 2,034,454,168,320 | 4,697,635,904 | 330,710 + 25,472 | **2,039,152,160,406** | 2,039,151,803,136 |
+
+Layer 0 (dense) is 256,669,440 B in both; an MoE layer is 8,804,514,048 B per_expert (of which
+the experts file holds 8,724,089,856) and 33,903,291,648 B fused. The fused cache is 3.82x the
+per_expert one because the fused routed experts stay bf16 under NF4.
+
+Against the investigation's figures (533,246,623,322 and 2,039,152,149,798 B) both totals are
+**10,608 B higher**, the same in both layouts. Explained and reproduced: the investigation sized
+the map as one source file and the stale `inv_freq` at [32]. One file instead of 61 removes 60
+index entries (7,680 B of index allowance); [32] instead of [56] removes 61 x 24 x 2 = 2,928 B of
+payload; with both, the estimator returns exactly the investigation's two figures (scratch probe,
+`k2_g3_delta_probe.py`). The [56] here is the shape the index's `total_size` requires (G3a).
+
+What this means for a real run (arithmetic, not measured): under `quantization: 4bit` a Kimi K2
+layer cache needs about 533 GB of disk with `per_expert` and about 2.04 TB with `fused`; the
+`per_expert` RAM tier holds 9.8 GB (the routed experts are read from disk on every tier).
+
+## 6. Mutation run
+
+49 mutations of `src/soup_cli/utils/kimi_k2.py`, `src/soup_cli/trainer/stream_setup.py` and
+`src/soup_cli/utils/layer_stream_runtime.py`, one pytest process each over the named tests of
+`tests/test_kimi_k2_streaming.py` (scratch driver `k2_mutate.py`). Each file was restored byte for
+byte after its mutation (sha256 checked after each, and all three again at the end, equal to the
+files committed in `c5b723dfc`).
+
+- Every guard row: `architectures`, `topk_method`, `scoring_func`, `n_group`, `topk_group`,
+ `num_experts_per_tok` (the top-k rule, its integer check, the `norm_topk_prob` default),
+ `moe_layer_freq`, `ep_size`, `n_routed_experts`, `n_shared_experts`, `num_key_value_heads`,
+ `rope_interleave`; every `rope_scaling` condition (not a dict, `type`, `rope_type`, extra keys,
+ `factor`, `original_max_position_embeddings`, zero betas, the `mscale` rule and each of its two
+ halves); `quantization_config` (the FP8 refusal, other methods, a non-mapping); a non-mapping
+ config.
+- Each rewrite step: `model_type`, `auto_map`, the deep copy; and two config changes that must
+ break G2 (`rope_scaling` dropped, `rms_norm_eps` changed).
+- The loader: the K2 path, the guard call, the `trust_remote_code` branch, the revision kwargs to
+ each read, `name_or_path`; the message's truncation, `repr` and the rope key's rendering; the
+ tokenizer hint (the tiktoken clause, the K2-only check, the print); the setup's loader call, hint
+ call and re-raise; `build_meta_skeleton`'s loader call.
+
+**48 caught on the first run, 1 survived:** `num_experts_per_tok-bool` (dropping the integer check
+of the top-k rule). Its test case, `num_experts_per_tok: true`, was refused anyway, because
+`True >= 2` is false. The case was replaced by `8.0` (a float that passes the comparison) and `true`
+with `norm_topk_prob: false`; the mutation is then caught, and the re-run of it and of the
+`num_experts_per_tok` mutation caught both. Tests added after the mutation run only add assertions
+(the stale key in the layer files, the K2.5 refusal).
+
+## 7. Review round (after the results; the rule in sections 1-3 is unchanged)
+
+An independent review of `9d14ba561` returned CHANGES NEEDED. It found the loader itself safe:
+it reads JSON only, gates on `model_type == "kimi_k2"` exactly, and has two streaming call sites;
+the Moonlight cache fingerprint is unchanged. It then proved holes in the guard with tiny probes:
+
+- **HIGH.** A transformers-5 `rope_parameters` (no `rope_scaling`) carrying `attention_factor` and
+ `truncate` was admitted, and the native config uses both.
+- **HIGH.** `num_key_value_heads` absent was admitted. The native default is 128 against K2's 64
+ heads, so `num_key_value_groups` is 0 and the forward crashes. Section 5's G1b admitted list
+ pinned that case as passing.
+- **MEDIUM.** A top-level `partial_rotary_factor` or `head_dim` was admitted. The native rope reads
+ them, K2 ignores them, and the forward crashes.
+- **MEDIUM.** The tokenizer loaded before the guard ran, so a Kimi-K2-Thinking user was first told
+ to pass `--trust-remote-code` and install `tiktoken`, and only then refused.
+- **Surviving mutants of the review's own:**
+ - the hint test raised a `ValueError` where a missing `tiktoken` really surfaces as an
+ `ImportError`;
+ - `partial_rotary_factor` inside `rope_scaling` was not pinned;
+ - an empty `rope_scaling` had no defined path;
+ - nothing pinned that a failure inside the hint never masks the tokenizer's own error.
+
+### Changes (`cfe1699d6`, then `acad7a66e`)
+
+- **The guard is also an allowlist of top-level keys.** It admits the 45 keys of the published
+ Base / Instruct `config.json` plus three metadata keys, each justified in the code:
+ - `_commit_hash`, which transformers' own reader adds to every dict it returns;
+ - `_name_or_path`;
+ - `dtype`.
+
+ Any other key is refused by name, after the registered rows, with "training.stream_layers admits
+ kimi_k2 only with the published K2 config fields".
+- **The `ep_size` and `rope_interleave` rows are gone.** Neither key is in the published file, so
+ both are now refused whenever present; before, the rows admitted `ep_size <= 1` and
+ `rope_interleave: true`. Their registered refusal cases are still refused, naming the field and
+ its value.
+- **`num_key_value_heads` is required** and must equal `num_attention_heads`.
+- **An empty `rope_scaling` is refused on its own.** K2 indexes `rope_scaling['type']` whenever
+ `rope_scaling` is not null. `null` keeps its defined path: both classes use their plain rope
+ (G1c "no-scaling").
+- **The setup runs the guard before the tokenizer** by loading the model config first.
+- **The loader import moved** (`acad7a66e`). It now sits beside the tokenizer import, because next
+ to the `fp8_block` import it conflicted with `fix/stream-refuse-packed-quant` (tip `454e57113`).
+ `git merge-tree` is clean now. On that merged tree, `test_kimi_k2_streaming` (127),
+ `test_deepseek_v3_streaming` (30), `test_fp8_block_streaming` (157) and
+ `test_stream_refuses_packed_quant` (211) pass.
+
+### G1b cases added after the review (not part of the registered rule)
+
+- **Refused**, each naming exactly its field and value:
+ - `num_key_value_heads` absent, and 32 (which divides 64);
+ - a top-level `rope_parameters` with `attention_factor` / `truncate`;
+ - top-level `partial_rotary_factor` and `head_dim`;
+ - `rope_scaling['partial_rotary_factor']`;
+ - `rope_scaling: {}`;
+ - `ep_size: 1` and `rope_interleave: true`;
+ - `pad_token_id` and `sliding_window`;
+ - outside the 50-case list, the control-bytes test adds a top-level key made of control bytes,
+ which is refused and rendered escaped.
+- **Removed from the admitted list:** `ep_size` 1 and 0, `num_key_value_heads` absent,
+ `rope_interleave: true`, and Thinking without its quantization. The last is now refused naming
+ `ep_size` and `pad_token_id`.
+- **Added to the admitted list:** the three metadata keys.
+
+G1b now has 50 refusal cases and 17 admitted variants. The allowlist is pinned to equal the real
+Base key set.
+
+### Re-run on `acad7a66e`
+
+- **Tests.** `tests/test_kimi_k2_streaming.py`: 127 passed. `test_deepseek_v3_streaming` (30),
+ `test_fp8_block_streaming` (157), `test_issue602_qwen4_ple_streaming` (33, 2 skipped) and
+ `test_terminal_output_hygiene` (31) passed, and ruff is clean. So did the other files that drive
+ the setup: `test_qwen35_streaming`, `test_issue803_*`, `test_stream_moe_lora_targets`,
+ `test_mla_lora_targets`, `test_stream_expert_layout`, `test_stream_disk_preflight_moe` and
+ `test_cli_startup_is_light`.
+- **G1** (gate script on the real files):
+ - G1a is unchanged: FAIL, 42 of 43 fields, `rope_scaling`.
+ - The controls hold, with 0 dynamic-module loads.
+ - Thinking's first failure is still `quantization_config.quant_method='compressed-tensors'`. The
+ allowlist then names 50 more fields of its file: its serialised generation defaults, `ep_size`
+ and `pad_token_id`. Section 5's "its only guard failure" describes the guard before this round.
+- **G2** is unchanged: 4 of 4 cells bit-exact.
+- **G3** is unchanged: G3a holds, and the estimate equals the oracle in both layouts, with the same
+ totals (533,246,633,930 and 2,039,152,160,406 B).
+
+### Mutation re-run
+
+61 mutants were run on the review-round code:
+
+- **46 of section 6's 49, unchanged.** The other 3 target code this round replaced (the `ep_size`
+ row, the `rope_interleave` row, the old `num_key_value_heads` condition).
+- **15 new ones:**
+ - the allowlist: switched off; admitting `ep_size` / `rope_interleave`; admitting
+ `rope_parameters` / `partial_rotary_factor` / `head_dim`; dropping `_commit_hash`; one extra
+ metadata key; raw key names in the message; the reason text;
+ - `num_key_value_heads`: absent admitted; any integer admitted;
+ - `rope_scaling`: the empty-dict branch off; a falsy `rope_scaling` admitted; `partial_rotary_factor`
+ added to the rope keys;
+ - the setup's `except` narrowed to `ValueError`; the hint's own `except` narrowed;
+ - the guard moved back after the tokenizer.
+
+**All 61 caught.** Three of them (`hint-print`, `setup-hint-call`, `setup-reraise`) failed their
+tests on the first pass, but the driver still named the test id from before it was parametrised.
+With the ids corrected they were re-run and caught. After the import move, the five `stream_setup.py`
+mutants were run again on `acad7a66e`: 5 of 5 caught. Each file was restored byte for byte, with its
+sha256 checked.
+
+### Correction: "does not import on transformers 5.17"
+
+Sections 2 and 3 say K2's own code "does not import on transformers 5.17", quoting the
+investigation. That was not observed here: K2's code was never run. It is an inference from
+reading the code. Line 56 of `modeling_deepseek.py` imports `is_torch_fx_available` from
+`transformers.utils.import_utils`, and transformers 5.17.0 does not define that name (checked by
+`hasattr` and in its source); every other name the file imports from transformers exists. The docs
+now state it this way.
+
+### Round 2: review READY, survivors killed
+
+The second review returned READY. It confirmed that the allowlist equals the union of the real Base
+and Instruct keys (45 of 45), that all first-round holes are closed, and that the Moonlight cache
+is unchanged. Under the house rule, each survivor it listed now has a test that kills it:
+
+- **r2.** The setup could have handed the user's `trust_remote_code` to the config loader without
+ any test noticing, because every test ran with the flag off. A K2 base would then run its
+ repository's configuration code. The new test
+ `test_trust_remote_code_reaches_the_tokenizer_but_never_the_streamed_config` drives the setup
+ with the flag on: the loader gets `False`, and the tokenizer gets `True`.
+- **r1.** A key outside the allowlist with a null value is refused like any other value: refusal
+ case `head_dim: null`.
+- **r3.** A non-ASCII key name was shown raw. Refusals now render key names and values with
+ `ascii()`, which escapes every control and non-ASCII character, so a Cyrillic homoglyph cannot
+ read as an ASCII name; the CLI's error printer then applies `for_terminal`. Pinned by
+ `test_non_ascii_key_names_and_values_are_shown_escaped`.
+- **LOW 1.** A 200,000-character identifier key produced a 400 KB message. Key names are now always
+ bounded to 80 characters, and a refusal lists at most 10 fields, then "and N more". Pinned by
+ `test_a_refusal_stays_bounded_whatever_the_key_names_and_their_number`.
+- **LOW 2** (a known limit; no code change): `quantization_config` is checked only by
+ `fp8_block_size`. Its sub-keys are not allowlisted against K2's published ones, so for example
+ `weight_block_size: [64, 64]` or a `modules_to_not_convert` list is admitted. Nothing in Soup reads
+ `modules_to_not_convert` today.
+
+Mutants: r1, r2, r3 (on the key and on the value) and three for LOW 1 (unbounded name, uncapped list,
+no "and N more"). All 7 caught, with sha256 verified. `tests/test_kimi_k2_streaming.py`: 131
+passed. G1b now has 51 refusal cases and 17 admitted variants.
+
+### Second review of the pushed PR (after the results; the rule in sections 1-3 is unchanged)
+
+A review of the pushed head `050ca40b` found CI red and three guard or path findings. After a merge
+of `origin/main` (with #2094, which pins `build_meta_skeleton`'s config read to the bound commit):
+
+- **CI, contract test.** #1972's contract looked for `AutoConfig.from_pretrained` in
+ `stream_setup.py`, and the read had moved into the loader. The contract now runs the setup's own
+ `load_stream_model_config(...)` call through the real loader, with strict receivers on both of
+ its reads (`AutoConfig`, and the raw `config.json` read of a K2 file).
+- **CI, `_commit_hash`.** CI installs transformers 5.19.0, whose reader adds no `_commit_hash` at
+ all, not even for a Hub snapshot folder (5.17 adds `None` for a plain folder and the commit for a
+ snapshot), and whose config then has no `_commit_hash` attribute. The test runs on both folder
+ shapes and asserts only what holds on both versions: the config keeps whatever the reader
+ recorded, or nothing.
+- **CI, Linux.** The NF4 suffix fixture built the full-size skeleton, and transformers allocates
+ each MoE layer's fused experts on the CPU before they move to meta: 22,548,578,304 B at once,
+ refused on a 16 GB runner. The probe now runs on a size twin of the published config (only size
+ fields differ) and must report the same 11 suffixes as the full-size probe in G3b.
+- **MEDIUM.** The streamed tokenizer load did not get `config=`, so with `--trust-remote-code`
+ `AutoTokenizer` re-read the config with that flag and imported the repository's
+ `configuration_deepseek.py` (traced by the review on 5.17). It now gets the loaded native config.
+ A test runs the setup's tokenizer call with the real `AutoTokenizer` on a local K2 folder whose
+ `configuration_deepseek.py` writes a sentinel file when imported; the file must not appear.
+- **LOW.** Every published key must be present (only `auto_map` and `quantization_config` may be
+ absent; `torch_dtype` may be spelled `dtype`), so a missing scalar cannot take the native
+ default. `rope_scaling` absent and `moe_layer_freq` absent move from the admitted list to the
+ refused one (`rope_scaling: null` is still admitted).
+- **LOW.** Every refusal now says, before its field list, that other K2 releases
+ (Kimi-K2-Instruct-0905, Kimi-K2-Thinking) are out of scope for now. The 0905 `config.json`
+ (revision `ac6c49f0`, sha256 `4cd10b0f...07cc`; the review downloaded that file and nothing else)
+ is refused naming exactly the keys it adds.
+
+G1b now has 57 refusal cases, 16 admitted variants and 43 required-key cases.
+`tests/test_kimi_k2_streaming.py`: 186 passed. 32 mutants (14 new, the review's 8 not run before,
+10 earlier ones on code this round touched): all 32 caught, each file restored and its sha256
+checked.
diff --git a/benchmarks/harness/kimi_k2_gate.py b/benchmarks/harness/kimi_k2_gate.py
new file mode 100644
index 00000000..fe5066d0
--- /dev/null
+++ b/benchmarks/harness/kimi_k2_gate.py
@@ -0,0 +1,389 @@
+"""G1 and G3 of ``benchmarks/gate-kimi-k2-admission.md`` on the real Kimi K2 files.
+
+Reads ``config.json`` and ``model.safetensors.index.json`` as JSON data only: no K2 Python
+file is imported or executed, and nothing is downloaded. CPU only.
+
+ CUDA_VISIBLE_DEVICES=-1 PYTHONPATH=<tree>/src python benchmarks/harness/kimi_k2_gate.py \
+ --k2-dir <folder holding base/ instruct/ thinking/> --report <out.json>
+
+``--k2-dir`` holds one sub-folder per variant with that variant's text files. G1 loads the
+Base and Instruct ``config.json`` (each copied alone into a fresh folder) through Soup's
+loader and compares them field by field with the raw JSON, runs the controls, and runs the
+guard on the Thinking file. G3 rebuilds the Base checkpoint's header map from the index
+names and the config, checks it against the index and against the structure-derived map the
+tests use, then runs Soup's disk pre-flight estimator over it in both expert layouts and holds
+it against the shape-only oracle in ``tests/test_kimi_k2_streaming.py``.
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import logging
+import math
+import os
+import platform
+import re
+import shutil
+import sys
+import tempfile
+import time
+import warnings
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+ROOT = os.path.dirname(os.path.dirname(HERE))
+if ROOT not in sys.path:
+ sys.path.insert(0, ROOT)
+
+#: The investigation's figures for the estimate's total (payload + header and index allowances).
+INVESTIGATION_TOTALS = {"per_expert": 533_246_623_322, "fused": 2_039_152_149_798}
+_SIZE = {"F8_E4M3": 1, "BF16": 2, "F32": 4}
+
+
+def _sha256(path: str) -> str:
+ digest = hashlib.sha256()
+ with open(path, "rb") as handle:
+ for chunk in iter(lambda: handle.read(1 << 20), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+
+def _load_json(path: str):
+ with open(path, encoding="utf-8") as handle:
+ return json.load(handle)
+
+
+def _alone(config_path: str, scratch: str, name: str) -> str:
+ """A fresh folder holding only a copy of ``config_path``."""
+ folder = os.path.join(scratch, name)
+ os.makedirs(folder)
+ shutil.copyfile(config_path, os.path.join(folder, "config.json"))
+ return folder
+
+
+class _Records(logging.Handler):
+ def __init__(self):
+ super().__init__(level=logging.WARNING)
+ self.messages: list = []
+
+ def emit(self, record):
+ self.messages.append(f"{record.levelname}: {record.getMessage()[:300]}")
+
+
+def _field_by_field(config, raw: dict) -> list:
+ """One row per raw key: the rule of G1a, with its two named normalisations."""
+ rows = []
+ for key, value in raw.items():
+ if key in ("model_type", "auto_map"):
+ continue
+ if key == "torch_dtype":
+ ok = str(config.torch_dtype) == "torch." + value
+ rows.append({"key": key, "equal": ok, "note": f"str(torch_dtype)={config.torch_dtype}"})
+ continue
+ got = config.rope_parameters["rope_theta"] if key == "rope_theta" else getattr(
+ config, key, "<absent>"
+ )
+ row = {"key": key, "equal": got == value}
+ if key == "rope_scaling" and isinstance(got, dict):
+ row["raw_keys_equal"] = {name: got.get(name) for name in value} == value
+ row["added_keys"] = {name: got[name] for name in sorted(set(got) - set(value))}
+ if not row["equal"]:
+ row["got"] = repr(got)[:300]
+ rows.append(row)
+ return rows
+
+
+def gate_g1(k2_dir: str, scratch: str) -> dict:
+ import transformers
+ import transformers.dynamic_module_utils as dynamic
+ import transformers.models.auto.configuration_auto as configuration_auto
+ from transformers import AutoConfig, DeepseekV3Config
+
+ from soup_cli.utils.kimi_k2 import (
+ UnsupportedKimiK2Error,
+ kimi_k2_guard_failures,
+ load_stream_model_config,
+ )
+ from tests.test_kimi_k2_streaming import K2_BASE_CONFIG, K2_THINKING_CHANGES
+
+ paths = {
+ variant: os.path.join(k2_dir, variant, "config.json")
+ for variant in ("base", "instruct", "thinking")
+ }
+ out: dict = {"sha256": {variant: _sha256(path) for variant, path in paths.items()}}
+ out["instruct_bytes_equal_base"] = open(paths["base"], "rb").read() == open(
+ paths["instruct"], "rb"
+ ).read()
+ raw = _load_json(paths["base"])
+ out["test_constant_is_the_real_base_config"] = raw == K2_BASE_CONFIG
+
+ calls = []
+ real_dynamic = (dynamic.get_class_from_dynamic_module,
+ configuration_auto.get_class_from_dynamic_module)
+
+ def _spy(*args, **kwargs):
+ calls.append(args[:1])
+ raise AssertionError("remote code was loaded")
+
+ dynamic.get_class_from_dynamic_module = _spy
+ configuration_auto.get_class_from_dynamic_module = _spy
+ try:
+ for variant in ("base", "instruct"):
+ folder = _alone(paths[variant], scratch, f"g1-{variant}")
+ before = open(os.path.join(folder, "config.json"), "rb").read()
+ records = _Records()
+ logger = logging.getLogger("transformers")
+ logger.addHandler(records)
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always")
+ config = load_stream_model_config(folder)
+ logger.removeHandler(records)
+ rows = _field_by_field(config, _load_json(paths[variant]))
+ entry = {
+ "type": type(config).__name__,
+ "is_deepseek_v3_config": type(config) is DeepseekV3Config,
+ "model_type": config.model_type,
+ "auto_map": getattr(config, "auto_map", None),
+ "rope_parameters": config.rope_parameters,
+ "fields": len(rows),
+ "unequal": [row for row in rows if not row["equal"]],
+ "rope_scaling_row": next(row for row in rows if row["key"] == "rope_scaling"),
+ "warnings": [str(item.message)[:300] for item in caught],
+ "log_records_warning_or_above": records.messages,
+ "config_json_unchanged": open(os.path.join(folder, "config.json"), "rb").read()
+ == before,
+ }
+ try:
+ AutoConfig.from_pretrained(folder, trust_remote_code=False)
+ entry["autoconfig_alone"] = "loaded (control FAILED)"
+ except ValueError as exc:
+ entry["autoconfig_alone"] = "ValueError: " + str(exc)[:200]
+ native_raw = {k: v for k, v in _load_json(paths[variant]).items() if k != "auto_map"}
+ native_raw["model_type"] = "deepseek_v3"
+ native_folder = os.path.join(scratch, f"g1-{variant}-native")
+ os.makedirs(native_folder)
+ with open(os.path.join(native_folder, "config.json"), "w", encoding="utf-8") as fh:
+ json.dump(native_raw, fh)
+ left = config.to_dict()
+ right = AutoConfig.from_pretrained(native_folder).to_dict()
+ left.pop("_name_or_path")
+ right.pop("_name_or_path")
+ entry["autoconfig_equivalent"] = left == right
+ if left != right:
+ entry["autoconfig_differences"] = sorted(
+ key for key in set(left) | set(right) if left.get(key) != right.get(key)
+ )
+ out[variant] = entry
+ finally:
+ dynamic.get_class_from_dynamic_module = real_dynamic[0]
+ configuration_auto.get_class_from_dynamic_module = real_dynamic[1]
+ out["dynamic_module_calls"] = len(calls)
+
+ thinking = _load_json(paths["thinking"])
+ differs = sorted(
+ key for key in set(thinking) | set(raw) if thinking.get(key, "<absent>") != raw.get(
+ key, "<absent>"
+ )
+ )
+ failures = kimi_k2_guard_failures(thinking)
+ out["thinking"] = {
+ "keys_differing_from_base": differs,
+ "trimmed_constant_matches": all(
+ thinking[key] == value for key, value in K2_THINKING_CHANGES.items()
+ ),
+ "guard_failures": [failure._asdict() for failure in failures],
+ "first_failing_field": failures[0].field if failures else None,
+ }
+ folder = _alone(paths["thinking"], scratch, "g1-thinking")
+ try:
+ load_stream_model_config(folder)
+ out["thinking"]["loader"] = "admitted (FAILED)"
+ except UnsupportedKimiK2Error as exc:
+ out["thinking"]["loader"] = "UnsupportedKimiK2Error: " + str(exc)[:600]
+ out["transformers"] = transformers.__version__
+ return out
+
+
+def index_header_map(raw: dict, index: dict) -> dict:
+ """name -> (file, dtype, shape) from the index NAMES and the config (dtype facts: G3)."""
+ hidden, heads = raw["hidden_size"], raw["num_attention_heads"]
+ q_head = raw["qk_nope_head_dim"] + raw["qk_rope_head_dim"]
+ shared = raw["n_shared_experts"] * raw["moe_intermediate_size"]
+ moe, dense, experts = raw["moe_intermediate_size"], raw["intermediate_size"], raw[
+ "n_routed_experts"
+ ]
+ block = raw["quantization_config"]["weight_block_size"]
+ linears = {
+ "self_attn.q_a_proj": (raw["q_lora_rank"], hidden),
+ "self_attn.q_b_proj": (heads * q_head, raw["q_lora_rank"]),
+ "self_attn.kv_a_proj_with_mqa": (raw["kv_lora_rank"] + raw["qk_rope_head_dim"], hidden),
+ "self_attn.kv_b_proj": (heads * (raw["qk_nope_head_dim"] + raw["v_head_dim"]),
+ raw["kv_lora_rank"]),
+ "self_attn.o_proj": (hidden, heads * raw["v_head_dim"]),
+ "mlp.gate_proj": (dense, hidden), "mlp.up_proj": (dense, hidden),
+ "mlp.down_proj": (hidden, dense),
+ "mlp.shared_experts.gate_proj": (shared, hidden),
+ "mlp.shared_experts.up_proj": (shared, hidden),
+ "mlp.shared_experts.down_proj": (hidden, shared),
+ }
+ norms = {
+ "input_layernorm.weight": (hidden,), "post_attention_layernorm.weight": (hidden,),
+ "self_attn.q_a_layernorm.weight": (raw["q_lora_rank"],),
+ "self_attn.kv_a_layernorm.weight": (raw["kv_lora_rank"],),
+ }
+ weight_map = index["weight_map"]
+ out = {}
+ for name, file in weight_map.items():
+ if name in ("model.embed_tokens.weight", "lm_head.weight"):
+ out[name] = (file, "BF16", (raw["vocab_size"], hidden))
+ continue
+ if name == "model.norm.weight":
+ out[name] = (file, "BF16", (hidden,))
+ continue
+ short = re.match(r"model\.layers\.\d+\.(.+)$", name).group(1)
+ if short in norms:
+ out[name] = (file, "BF16", norms[short])
+ elif short == "self_attn.rotary_emb.inv_freq":
+ out[name] = (file, "BF16", (56,))
+ elif short == "mlp.gate.weight":
+ out[name] = (file, "BF16", (experts, hidden))
+ elif short == "mlp.gate.e_score_correction_bias":
+ out[name] = (file, "F32", (experts,))
+ else:
+ expert = re.match(r"mlp\.experts\.\d+\.(gate_proj|up_proj|down_proj)\.(weight.*)$",
+ short)
+ if expert is not None:
+ shape = (moe, hidden) if expert.group(1) != "down_proj" else (hidden, moe)
+ part = expert.group(2)
+ else:
+ module, part = short.rsplit(".", 1)
+ shape = linears[module]
+ if part == "weight":
+ assert name + "_scale_inv" in weight_map, name
+ out[name] = (file, "F8_E4M3", shape)
+ else:
+ assert part == "weight_scale_inv", name
+ out[name] = (file, "F32", (-(-shape[0] // block[0]), -(-shape[1] // block[1])))
+ return out
+
+
+def gate_g3(k2_dir: str, scratch: str) -> dict:
+ from soup_cli.utils import safetensors_reader
+ from soup_cli.utils.kimi_k2 import load_stream_model_config
+ from soup_cli.utils.layer_shard import estimate_shard_cache_bytes
+ from soup_cli.utils.layer_stream import stream_arch_of
+ from soup_cli.utils.layer_stream_runtime import build_meta_skeleton, quantised_layer_suffixes
+ from soup_cli.utils.safetensors_reader import _DTYPES, TensorRange
+ from tests.test_kimi_k2_streaming import k2_cache_oracle, k2_header_map
+
+ base = os.path.join(k2_dir, "base")
+ raw = _load_json(os.path.join(base, "config.json"))
+ index_path = os.path.join(base, "model.safetensors.index.json")
+ index = _load_json(index_path)
+ out: dict = {"index_sha256": _sha256(index_path),
+ "index_tensors": len(index["weight_map"]),
+ "index_total_size": index["metadata"]["total_size"]}
+ from_index = index_header_map(raw, index)
+ from_config = k2_header_map(raw)
+ out["map_keys_equal_index"] = set(from_index) == set(index["weight_map"])
+ out["map_from_index_equals_map_from_config"] = from_index == from_config
+ total = sum(math.prod(shape) * _SIZE[dtype] for _f, dtype, shape in from_index.values())
+ out["map_total_bytes"] = total
+ out["map_total_equals_index_total_size"] = total == index["metadata"]["total_size"]
+ by_dtype: dict = {}
+ for _f, dtype, shape in from_index.values():
+ by_dtype[dtype] = by_dtype.get(dtype, 0) + math.prod(shape) * _SIZE[dtype]
+ out["map_bytes_by_dtype"] = by_dtype
+
+ folder = _alone(os.path.join(base, "config.json"), scratch, "g3-config")
+ config = load_stream_model_config(folder)
+ arch = stream_arch_of(config)
+ started = time.perf_counter()
+ probe = build_meta_skeleton(folder, dtype="bfloat16", quant="nf4")
+ suffixes = quantised_layer_suffixes(probe)
+ out["meta_probe_seconds"] = round(time.perf_counter() - started, 2)
+ del probe
+ out["arch"] = arch
+ out["quant_suffixes"] = sorted(suffixes)
+
+ by_file: dict = {}
+ for name, (file, dtype, shape) in from_index.items():
+ by_file.setdefault(file, []).append((name, dtype, shape))
+
+ def _read_header(path):
+ entries, cursor = {}, 8
+ for name, dtype, shape in by_file[os.path.basename(path)]:
+ size = math.prod(shape) * _SIZE[dtype]
+ entries[name] = TensorRange(name=name, dtype=_DTYPES[dtype], shape=tuple(shape),
+ start=cursor, end=cursor + size)
+ cursor += size
+ return entries
+
+ real_read_header = safetensors_reader.read_header
+ safetensors_reader.read_header = _read_header
+ try:
+ paths = [os.path.join(scratch, "k2-headers", file) for file in sorted(by_file)]
+ for label, layout in (("per_expert", "per_expert"), ("fused", "")):
+ started = time.perf_counter()
+ estimate = estimate_shard_cache_bytes(
+ paths, dtype="bfloat16", arch=arch, quant="nf4", quant_suffixes=suffixes,
+ double_quant=True, expert_layout=layout, num_hidden_layers=config.num_hidden_layers,
+ quantization_config=config.quantization_config,
+ )
+ seconds = round(time.perf_counter() - started, 2)
+ layer_bytes, other_bytes = k2_cache_oracle(from_index, suffixes, layout)
+ out[label] = {
+ "seconds": seconds,
+ "layers": len(estimate.layer_bytes),
+ "payload_layers": sum(estimate.layer_bytes),
+ "payload_other": estimate.other_bytes,
+ "header_bytes": estimate.header_bytes,
+ "index_bytes": estimate.index_bytes,
+ "expert_file_bytes": estimate.expert_file_bytes,
+ "total_bytes": estimate.total_bytes,
+ "ram_tier_bytes": estimate.ram_tier_bytes,
+ "layer0_bytes": estimate.layer_bytes[0],
+ "layer1_bytes": estimate.layer_bytes[1],
+ "oracle_layers_equal": estimate.layer_bytes == layer_bytes,
+ "oracle_other_equal": estimate.other_bytes == other_bytes,
+ "investigation_total": INVESTIGATION_TOTALS[label],
+ "delta_vs_investigation": estimate.total_bytes - INVESTIGATION_TOTALS[label],
+ }
+ finally:
+ safetensors_reader.read_header = real_read_header
+ return out
+
+
+def main(argv=None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ parser.add_argument("--k2-dir", required=True)
+ parser.add_argument("--report", required=True)
+ args = parser.parse_args(argv)
+
+ import psutil
+ import torch
+
+ report: dict = {
+ "box": {
+ "python": platform.python_version(),
+ "platform": platform.platform(),
+ "torch": torch.__version__,
+ "cuda_available": torch.cuda.is_available(),
+ "available_ram_bytes_at_start": psutil.virtual_memory().available,
+ }
+ }
+ with tempfile.TemporaryDirectory(prefix="k2-gate-") as scratch:
+ report["g1"] = gate_g1(args.k2_dir, scratch)
+ report["g3"] = gate_g3(args.k2_dir, scratch)
+ report["box"]["peak_rss_bytes"] = psutil.Process().memory_info().peak_wset if hasattr(
+ psutil.Process().memory_info(), "peak_wset"
+ ) else None
+ with open(args.report, "w", encoding="utf-8") as handle:
+ json.dump(report, handle, indent=2, default=str)
+ print(json.dumps(report, indent=2, default=str)[:20000])
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/changelog.d/0.76.0/2107.added.md b/changelog.d/0.76.0/2107.added.md
new file mode 100644
index 00000000..a80fe7b0
--- /dev/null
+++ b/changelog.d/0.76.0/2107.added.md
@@ -0,0 +1,38 @@
+- **Layer streaming admits Kimi K2 (`model_type: kimi_k2`).** Kimi-K2-Base and Kimi-K2-Instruct are
+ DeepSeek-V3's decoder in DeepSeek-V3's FP8 block format, but their `config.json` declares
+ `model_type: kimi_k2` with an `auto_map` onto the repository's own code, so `AutoConfig` refused
+ them as custom code before the architecture list was reached (layer streaming never runs a
+ repository's model code). The streamed model's config is now read from that file as plain data
+ into transformers' own `DeepseekV3Config` (`model_type` set to `deepseek_v3`, `auto_map` dropped),
+ after a guard that admits a K2 config only where that class computes what K2's own code computes:
+ `noaux_tc` sigmoid routing with one expert group, top-k of at least 2 under renormalisation, every
+ layer past `first_k_dense_replace` an MoE layer, `num_key_value_heads` equal to the head count,
+ only the yarn rope keys K2 reads, unquantised or DeepSeek-V3 block FP8 weights, every top-level
+ field of the published K2-Base / K2-Instruct `config.json` present (only `auto_map` and
+ `quantization_config` may be left out: a missing `rope_theta` would otherwise take the native
+ default 10000.0), and no field outside it (besides three metadata keys). A config that fails
+ any of them is refused before the tokenizer or any weight is loaded, naming every such field and
+ its value and saying that other K2 releases are out of scope for now; Kimi-K2-Thinking
+ (compressed-tensors INT4) is refused as `quantization_config.quant_method='compressed-tensors'`,
+ and Kimi-K2-Instruct-0905 for the fields its file adds (`ep_size`, `pad_token_id` and serialised
+ defaults).
+ In the gate (`benchmarks/gate-kimi-k2-admission.md`) the field-by-field config check fails as
+ registered on one field: transformers adds `rope_theta` and `rope_type` to `rope_scaling`, as it
+ does for any DeepSeek-V3 config. The other checks pass. A tiny K2-like checkpoint (the published
+ config with tiny dimensions) streams bit for bit like a resident `DeepseekV3ForCausalLM` on the
+ same weights (logits, loss, LoRA gradients; `fused` and `per_expert`; bf16 and FP8 block), and the
+ disk pre-flight sizes the published Base layout exactly:
+ 533.2 GB per_expert and 2.04 TB fused under `quantization: 4bit`
+ (`benchmarks/gate-kimi-k2-admission.md`; CPU only, no K2 weights downloaded, nothing trained on
+ K2). K2's tokenizer is repository code: it needs `--trust-remote-code`, which reaches the tokenizer
+ only, and `pip install tiktoken`, which Soup does not install; a failed tokenizer load on a K2
+ base now says so. The streamed tokenizer load is handed the config already loaded: before, with
+ `--trust-remote-code`, `AutoTokenizer` read the config again with that flag and, for a repository
+ with an `auto_map`, imported and ran its configuration module (`configuration_deepseek.py` on K2,
+ and on Moonlight-16B since #1933). Known differences from K2's own code remain: the MoE combine's
+ rounding and eager versus sdpa attention. Known limit: on a full-size K2, transformers'
+ `DeepseekV3NaiveMoe` briefly allocates `torch.empty(384, 4096, 7168)` bf16 on the CPU per MoE
+ layer (about 22.5 GB of commit) before accelerate moves it to meta, in the setup's NF4 /
+ `moe_lora` probe and in `build_streamed_model`; RSS barely moves, but a box without that commit
+ headroom fails with a raw `DefaultCPUAllocator` error (DeepSeek-V3 had the same before, at about
+ 15 GB). (#2107)
diff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.md
index cab7888e..5dab0a39 100644
--- a/docs/performance-and-quantization.md
+++ b/docs/performance-and-quantization.md
@@ -468,6 +468,8 @@ code. For example, Moonlight-16B-A3B needs that flag for its tokenizer while its
expert shards. Streaming requires a supported native model implementation; the
flag does not enable custom model code on this path. The dated Moonlight hardware
runs are recorded in the [probe report](../benchmarks/probe-rtx5070-moonlight-16b.md).
+A Kimi K2 base is read the same way, through a guarded rewrite of its `config.json`
+(see "Kimi K2" below).
**How it works.** LoRA adapters + their gradients + optimizer state stay resident in VRAM (they are small). The frozen base lives in CPU RAM, page-locked when the machine allows it, and is streamed: each decoder layer is copied into one of two pre-allocated VRAM buffers on a dedicated CUDA stream while the previous layer is still computing, so the load overlaps the compute. Vocabulary-sized `embed_tokens` and an untied `lm_head` use one additional shared slot: the embedding is loaded for the model input, then the same allocation is reused for the output head, whose copy is issued right after the embedding lookup (`StreamPrefetcher.head_prefetch_layer`, default `0`) rather than at the last decoder layer, and the embedding is reloaded into it at the tail of that step's backward pass so the copy overlaps the remaining compute instead of blocking the next step's first lookup. Each decoder layer is read **twice** per step — once in the forward pass and once when the backward pass recomputes it — because `dL/dx = Wᵀ · dL/dy` needs the weights to reach the layers below. That is physics, not an implementation detail, and it is why streaming costs time.
@@ -504,7 +506,7 @@ What the VRAM pre-flight counts:
What the disk pre-flight counts: the cache the sharder will write in the layout you chose, sized from the source safetensors headers (see "Disk pre-flight and shard cache" below). Under `quantization: 4bit` that is the experts at NF4 here and at the stream dtype with `fused`: for Moonlight it charges 9.24 GB here and 30.60 GB fused, within 0.01% of the caches the sharder then wrote. (Before, it charged the NF4 rate to every parameter, 8.23 GB in both layouts, so a fused run could pass the check and fill the disk mid-shard.)
Limits and refusals:
-- **Architecture.** Only `model_type: deepseek_v3` is admitted. Any other base is refused before weights are resolved.
+- **Architecture.** Only `model_type: deepseek_v3` is admitted, which includes a Kimi K2 base that passes the guard in "Kimi K2" below (it streams as `deepseek_v3`). Any other base is refused before weights are resolved.
- **Adapters on routed experts.** `moe_lora` is refused with this layout, because a streamed expert has nowhere to keep an adapter between its visits. Adapt attention or the shared expert instead.
- **Older Soup versions.** A Soup from before this layout accepts a per-expert cache as reusable and then fails at install ("shard is missing decoder weights"). Delete the cache directory, or re-shard with `fused`, before going back to an older version.
@@ -530,13 +532,41 @@ Measured:
- **A real checkpoint, CPU only.** Moonlight-16B-A3B, converted to this format, sharded in 93 s (27 layers, NF4, `fused`). The 30.60 GB cache came within 0.0002% of the pre-flight's figure (0.000115%: 35,336 bytes), and every FP8-derived tensor checked in three layers equals an independent dequantisation of the source. A GPU `soup train` comparison against the bf16 source is recorded in [`probe-rtx5070-moonlight-fp8-source.md`](../benchmarks/probe-rtx5070-moonlight-fp8-source.md) (pre-registered verdict FAIL on per-step loss and step time; see the record).
Limits and refusals:
-- **Architecture.** Only `model_type: deepseek_v3` is admitted. A Kimi K2 checkpoint declares `model_type: kimi_k2` and is still refused by name, FP8 or not.
+- **Architecture.** Only bases that stream as `model_type: deepseek_v3` are admitted: DeepSeek-V3 itself, and a Kimi K2 base (`model_type: kimi_k2`) whose config passes the guard in "Kimi K2" below.
- **Other FP8 formats.** Each of these is refused, and the message names the supported format: per-tensor scales, `e5m2` weights, `compressed-tensors`, ue8m0 (power-of-two) scales, static activation scales, a missing or misshapen scale, an FP8 tensor without a scale, and a scale without its tensor. A `weight_block_size` axis outside [1, 1048576] is refused too. A spelling the config already gives away is refused at setup, before any weight is resolved or downloaded; the rest before the first byte of the cache is written.
- **Integer and packed formats.** Kimi-K2-Thinking's compressed-tensors `pack-quantized` INT4 (int32 `weight_packed`, `weight_scale`, int64 `weight_shape`) is not dequantised, and nor is any other integer quantiser; see the refusal list below.
- **Damaged values.** A weight that is NaN after dequantisation (the e4m3fn bytes 0x7F and 0xFF), a negative scale, a non-finite scale, and a weight past float16's range under a float16 stream (pre-Ampere cards; stream it in bfloat16) are refused, naming the tensor, when that tensor is read: before the cache index is written, though files of earlier layers may already be on disk (no index names them, so they are never used, and the next run shards again). A zero scale, as an all-zero block has, is kept.
- **Cache identity.** For `deepseek_v3`, `config.json` is part of the cache's source identity, as are the weight files, so a cache sharded from the bf16 checkpoint is never reused for its FP8 copy at the same path, nor the reverse.
- **After training.** The adapter is trained against the dequantised weights. Merging it or serving it loads the base through transformers' own FP8 path, which is a different numerical path from the one the adapter was trained on.
+**Kimi K2 (`model_type: kimi_k2`).** Kimi-K2-Base and Kimi-K2-Instruct are DeepSeek-V3's decoder (MLA attention, 384 routed experts plus a shared one, 61 layers, about 1T parameters) in DeepSeek-V3's FP8 block format, but their `config.json` declares `model_type: kimi_k2` and an `auto_map` onto the repository's own code. transformers registers no `kimi_k2` config, and layer streaming never runs a repository's model code, so such a base used to fail with transformers' "contains custom code" error before the architecture list was even checked. Layer streaming (Soup's layer-to-layer streaming of a frozen base, L2L: Pudipeddi et al. 2020) now reads that `config.json` as plain data into transformers' own `DeepseekV3Config`, with `model_type` set to `deepseek_v3` and `auto_map` dropped (transformers does the same for the text tower of Kimi K2.5), and streams the base as `deepseek_v3`: its FP8 weights are dequantised as described above, both expert layouts are available, and `target_modules: auto` adapts the same MLA projections as on DeepSeek-V3. There is no config key; the rewrite is chosen from `config.json`.
+
+A guard runs first, before the tokenizer is loaded. It admits the config only where transformers' class computes what K2's own `modeling_deepseek.py` computes, and otherwise refuses before any weight is resolved, naming every field that differs and its value:
+- `architectures` exactly `["DeepseekV3ForCausalLM"]`, `topk_method: noaux_tc` and `scoring_func: sigmoid` (the only router K2's code implements, and the one transformers always runs);
+- `n_group: 1` and `topk_group: 1`: K2 masks the expert groups it does not pick with 0.0 and transformers with -inf, which can pick different experts; with one group nothing is masked;
+- `num_experts_per_tok` of at least 2 while `norm_topk_prob` is on: K2 renormalises the top-k weights only above one expert;
+- `moe_layer_freq` 1, integer `n_routed_experts` and `n_shared_experts`, and `num_key_value_heads` equal to `num_attention_heads`: K2's attention ignores it, while transformers divides by it and defaults it to 128;
+- every top-level field of the published Base / Instruct `config.json` present, except `auto_map` and `quantization_config`, which may be left out (`torch_dtype` may be spelled `dtype`). A missing field is not read by any row above, and transformers' class would compute with its own default for it: `rope_theta` 10000.0 where K2 publishes 50000.0, `routed_scaling_factor` 2.5 where K2 publishes 2.827;
+- no top-level field outside the published Base / Instruct `config.json` except three metadata keys (`_commit_hash`, which transformers' reader adds; `_name_or_path`; `dtype`). transformers' class can read a field K2's code ignores, such as `head_dim`, `partial_rotary_factor`, a transformers-5 `rope_parameters`, `ep_size` or `rope_interleave`, and then compute differently or crash, so any such field is refused by name;
+- `rope_scaling` null, or yarn holding only the keys K2's yarn reads, with `factor` and `original_max_position_embeddings` set, no zero `beta_fast` or `beta_slow`, and an `mscale` consistent with `mscale_all_dim`: otherwise the two compute different rotary frequencies or attention factors;
+- `quantization_config` absent, or DeepSeek-V3's block FP8 as above.
+
+Kimi-K2-Base and -Instruct as published pass it. Other K2 releases are out of scope for now, and the refusal says so before it lists the fields. Kimi-K2-Thinking does not pass: its weights are compressed-tensors INT4, refused as `quantization_config.quant_method='compressed-tensors'`, and its file carries 50 more fields the published one does not, each named. Kimi-K2-Instruct-0905 has the same decoder, but its file adds `ep_size`, `pad_token_id` and the serialised `PretrainedConfig` defaults, so it is refused too. Kimi K2.5 and K2.6 (`model_type: kimi_k25`, a vision-language wrapper) are not admitted either.
+
+**The K2 tokenizer.** It exists only as code in the repository (`tokenization_kimi.py`), so a K2 run needs `--trust-remote-code`, and Soup prints its REMOTE CODE WARNING panel for it. Under layer streaming that flag reaches the tokenizer only; the config and the model are transformers' own classes. The tokenizer load is handed the config Soup already loaded, so `AutoTokenizer` does not read the config again with the flag (it would import and run the repository's `configuration_deepseek.py`; Moonlight-16B's tokenizer load did that before this change). The tokenizer also imports `tiktoken`, which Soup does not install: `pip install tiktoken`. When the tokenizer fails to load on a K2 base, Soup names both requirements before the error.
+
+Measured ([gate](../benchmarks/gate-kimi-k2-admission.md), CPU only):
+- **Config.** The published Base and Instruct `config.json` load into `DeepseekV3Config`. The gate's field-by-field check fails as registered on one of 43 fields, `rope_scaling`: transformers adds `rope_theta` and `rope_type` to it, as it does for any DeepSeek-V3 config, and every value K2 declares is kept. The result equals what `AutoConfig` builds from the same file spelled `deepseek_v3`.
+- **Numerics.** On a tiny K2-like checkpoint (its `config.json` the published one with tiny dimensions: `kimi_k2`, `auto_map`, one expert group, yarn), the streamed model matches a resident `DeepseekV3ForCausalLM` on the same weights bit for bit, in its logits, loss and LoRA gradients, in both expert layouts, from a bf16 checkpoint and from its FP8 block copy.
+- **The real index.** A header map rebuilt from the published Base index (no weights downloaded) has its 139,644 tensors and its exact byte total, 1,029,173,256,720 B. Over it, the disk pre-flight sizes each layer of the cache exactly as an independent count from the shapes does: under `quantization: 4bit` (bf16), **533.2 GB** with `per_expert` (533,246,633,930 B, of which the RAM tier holds 9.8 GB) and **2.04 TB** `fused` (2,039,152,160,406 B), 3.8x larger because the fused routed experts stay bf16.
+
+Not measured:
+- No K2 weights were downloaded, nothing was trained on K2, and no GPU ran. The cache sizes above are the pre-flight's arithmetic, not a cache written to disk.
+- **A brief 22.5 GB CPU allocation per MoE layer.** On a full-size K2, transformers' `DeepseekV3NaiveMoe` allocates its fused experts with `torch.empty(384, 4096, 7168)` in bf16 on the CPU, about 22.5 GB of commit, before accelerate moves them to meta. This happens in the setup's NF4 / `moe_lora` probe and in `build_streamed_model`. RSS barely moves, but the commit charge needs that headroom, and a box short of it fails with a raw `DefaultCPUAllocator` error. DeepSeek-V3 had the same before this change, at about 15 GB.
+- Parity with K2's own code: Soup never executes it. Read as text, it would not import under transformers 5.17: it imports `is_torch_fx_available`, which 5.17 does not define. That is an inference from reading the code, not an observed error. Its router asserts it is not training and its MoE block fails in training mode, so it is inference-only anyway; transformers' class is the training path. The guard was derived by reading it, and its numeric rows were checked against a hand transcription of its router and yarn.
+- Known numeric differences from K2's own code that remain: the MoE combine (K2 sums the weighted expert outputs in fp32 and rounds once; transformers rounds each weighted output to the model dtype before accumulating, which is bf16 rounding noise), eager versus sdpa attention, and the router bias kept as a float32 buffer rather than a Parameter (float32 in the checkpoint either way).
+- The checkpoint carries 61 stale `self_attn.rotary_emb.inv_freq` tensors. The sharder writes them into the layer files as stored, and nothing streams or reads them: K2's code keeps that buffer non-persistent, and transformers computes the rope from the config.
+
**`stream_nf4_scale_cache` (opt-in).** On the dequantise + `F.linear` path, a
double-quantised NF4 weight expands its 8-bit block scales to fp32 on every visit,
forward and recompute alike: two small kernels and a temporary per projection.
@@ -871,7 +901,8 @@ prints this advice when it sees you accumulating.
- `stream_vram_probe` on any task other than `sft` → the probe runs a plain causal-LM step, which *is* the SFT step but is not a preference loss. Measured at one matching shape it is conservative there too (6.02 GB against a real DPO step's 5.30 GB, +13.5%), but one shape is not a validation, so it is not offered for `dpo`/`orpo`/`simpo`/`kto` yet
- `stream_loss_chunk` on any task other than `sft`, or with `data.format: raft` → the chunked step rebuilds the causal-LM cross-entropy and returns no logits. A preference loss reduces the logits to per-token log-probs instead, and RAFT's weighted loss reads all of them (#1693)
- `stream_loss_chunk` beside `use_cut_ce` → each replaces how the loss over the logits is computed. Refused before the `use_cut_ce` refusal above, with a message that names both fields (#1693)
-- an architecture outside the supported list (llama / qwen2 / qwen3, including qwen3_5_moe text aliases / qwen4_exp text / mistral / gemma / gemma2 / gemma3_text / phi / phi3 / deepseek_v3) → named explicitly. `deepseek_v3` is the DeepSeek-V3 family (MLA attention, routed experts plus a shared expert); a Kimi K2 checkpoint uses the same decoder but declares `model_type: kimi_k2`, which transformers does not register, so it is refused under that name. Under `quantization: 4bit` its attention, shared-expert and dense-MLP projections are NF4 while the routed experts stay at the stream dtype: they are 3-D parameters, not `nn.Linear` modules, so a DeepSeek-V3 layer streams most of its bytes unquantised
+- an architecture outside the supported list (llama / qwen2 / qwen3, including qwen3_5_moe text aliases / qwen4_exp text / mistral / gemma / gemma2 / gemma3_text / phi / phi3 / deepseek_v3) → named explicitly. `deepseek_v3` is the DeepSeek-V3 family (MLA attention, routed experts plus a shared expert); a Kimi K2 checkpoint uses the same decoder under `model_type: kimi_k2` and is admitted through the guard in "Kimi K2" above. Under `quantization: 4bit` its attention, shared-expert and dense-MLP projections are NF4 while the routed experts stay at the stream dtype: they are 3-D parameters, not `nn.Linear` modules, so a DeepSeek-V3 layer streams most of its bytes unquantised
+- a Kimi K2 config (`model_type: kimi_k2`) that transformers' DeepSeek-V3 class would compute differently from K2's own code → refused before any weight is resolved, naming every such field and its value (Kimi-K2-Thinking: `quantization_config.quant_method='compressed-tensors'`). The fields, and why each matters, are under "Kimi K2" above
**Config example:**
@@ -945,6 +976,7 @@ output: ./output
- **"layer streaming needs NVMe or more RAM … the detected disk is 'hdd'"** on a fast cloud disk — a virtio device reports `rotational=1` with no media hint. Detection now measures the disk when the flag is unreliable; if it still misreads yours, set `training.stream_disk_kind: nvme` to force the tier on (`ssd`/`hdd` force it off).
- **"could not page-lock the base … falling back to a PAGEABLE RAM store"** — expected on a busy machine. Training continues, more slowly. Close other applications to keep the pinned store. Since #901 the fallback also prints `after the failed page-lock: cleared the stale CUDA out-of-memory error … and released N GB of page-locked memory it left cached` — a failed page-lock leaves the CUDA runtime holding a stale "out of memory" that the run's first kernel launch would otherwise report as a real one (the report's `AcceleratorError: CUDA error: out of memory` inside `SFTTrainer.__init__`, with gigabytes of VRAM free), and the blocks pinned before the failure stay in torch's host cache until released. Both are handled before the pageable store is built. The store also pins in power-of-two arenas now, so the fallback itself is rarer: a 9.93 GB 14B NF4 store page-locks as 10 GiB where per-tensor pinning asked for ~17 GB.
- **"layer streaming does not support model_type=…"** — the supported list is llama / qwen2 / qwen3, including `qwen3_5_moe` text aliases / qwen4_exp text / mistral / gemma / gemma2 / gemma3_text / phi / phi3 / deepseek_v3. Multimodal `gemma3` is excluded on purpose; use `gemma3_text`.
+- **"Kimi K2 (model_type 'kimi_k2') streams through transformers' own DeepseekV3 class …"** — your K2 `config.json` sets a field that transformers' class would compute differently from K2's own code, leaves out a published field, or adds one; the message names each one and its value. Kimi-K2-Base and -Instruct as published pass. Other K2 releases (Kimi-K2-Instruct-0905, Kimi-K2-Thinking) are out of scope for now, and Kimi-K2-Thinking's compressed-tensors INT4 is not dequantised by layer streaming.
- **"predicted peak … exceeds free VRAM" and you believe it is wrong** — lower `batch_size` or `data.max_length` first. Otherwise there are two escape hatches and they are not interchangeable. `training.stream_vram_probe: true` (`sft` only) **measures** one real forward+backward at your configured shape and decides on that, printing the prediction beside it; it costs one step (1–5 s measured) and it can also refuse a run the formula accepted. `training.stream_vram_override: <bytes>` instead **replaces** the free-VRAM figure the check runs against — that is an assertion you are making, not a measurement, so raising it past a real limit is an OOM on Linux and a silent spill on Windows. Prefer the probe when you want to be told the truth; use the override when you know something the driver cannot report.
- **The prediction is not equally trustworthy at every sequence length.** Measured on a 4 GB RTX 3050 with SmolLM2-135M streamed in bf16 at batch 1, the formula over-predicts by 8% at seq 4352 (safe) and then **under-predicts — 0.934x the real peak at seq 5120 and 0.787x at 6144**. The grid it was fitted on only ever varied batch size, at seq 256 and 512, so long-context streaming is exactly where it has the least evidence behind it. If you are streaming at multi-thousand-token sequences, turn on `stream_vram_probe`. Record: [`benchmarks/gate-v0.73.1-measured-vram-fit.md`](../benchmarks/gate-v0.73.1-measured-vram-fit.md).
- **The pre-flight reports the whole card on a capped or shared GPU** — `torch.cuda.mem_get_info()` is a device-level driver query and cannot see `set_per_process_memory_fraction`, a MIG slice, or another process on the same card. Set `training.stream_vram_override` to what your process may actually use; the check then refuses configurations that would exceed *that*, which is also how you rehearse a 4 GB card on a 16 GB one.
diff --git a/src/soup_cli/trainer/stream_setup.py b/src/soup_cli/trainer/stream_setup.py
index 39a88445..ff1c2ac0 100644
--- a/src/soup_cli/trainer/stream_setup.py
+++ b/src/soup_cli/trainer/stream_setup.py
@@ -889,7 +889,9 @@ class StreamingSetupMixin:
from dataclasses import replace
from peft import TaskType
- from transformers import AutoConfig, AutoTokenizer
+ from transformers import AutoTokenizer
+
+ from soup_cli.utils.kimi_k2 import load_stream_model_config
# BEFORE the tokenizer load, the weight resolve and the shard write:
# this configuration cannot work, and finding out minutes into disk I/O
@@ -945,20 +947,37 @@ class StreamingSetupMixin:
from soup_cli.utils.stripe_roots import resolve_stripe_roots
from soup_cli.utils.terminal import for_terminal
- console.print(f"[dim]Loading tokenizer: {cfg.base}[/]")
- self.tokenizer = AutoTokenizer.from_pretrained(
- cfg.base, trust_remote_code=self._trust_remote_code,
+ # The streamed decoder is always transformers' own class (see
+ # _STREAM_NATIVE_MODEL_CODE); trust_remote_code reaches the tokenizer only. A Kimi K2
+ # config (model_type kimi_k2: custom code to AutoConfig) loads into the native
+ # DeepseekV3Config behind a guard that refuses by name what that class would compute
+ # differently (utils/kimi_k2.py). Before the tokenizer: a refused K2 is told so first,
+ # not sent to install the tokenizer's requirements.
+ model_config = load_stream_model_config(
+ cfg.base, trust_remote_code=self._STREAM_NATIVE_MODEL_CODE,
**base_revision_kwargs(cfg.base),
)
+
+ console.print(f"[dim]Loading tokenizer: {cfg.base}[/]")
+ try:
+ # config=: without it AutoTokenizer reads the config again, with the user's
+ # trust_remote_code, and for a repository with an auto_map (Kimi K2, Moonlight)
+ # imports and runs its configuration module (second review of #2107). The
+ # native config is what the tokenizer is resolved against; the flag still
+ # reaches the tokenizer's own code (K2's tokenization_kimi.py).
+ self.tokenizer = AutoTokenizer.from_pretrained(
+ cfg.base, config=model_config, trust_remote_code=self._trust_remote_code,
+ **base_revision_kwargs(cfg.base),
+ )
+ except Exception:
+ # Kimi K2's tokenizer is repository code that imports tiktoken: say so by name.
+ from soup_cli.utils.kimi_k2 import print_kimi_k2_tokenizer_hint
+
+ print_kimi_k2_tokenizer_hint(cfg.base, console, **base_revision_kwargs(cfg.base))
+ raise
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
- # The streamed decoder is always transformers' own class (see
- # _STREAM_NATIVE_MODEL_CODE); trust_remote_code reaches the tokenizer only.
- model_config = AutoConfig.from_pretrained(
- cfg.base, trust_remote_code=self._STREAM_NATIVE_MODEL_CODE,
- **base_revision_kwargs(cfg.base),
- )
# Allowlist, not a heuristic — a half-supported architecture streams
# weights into the wrong module and mis-trains silently.
arch = stream_arch_of(model_config)
diff --git a/src/soup_cli/utils/kimi_k2.py b/src/soup_cli/utils/kimi_k2.py
new file mode 100644
index 00000000..9fc1cfbe
--- /dev/null
+++ b/src/soup_cli/utils/kimi_k2.py
@@ -0,0 +1,489 @@
+"""Kimi K2 on layer streaming: its ``config.json`` loaded into transformers' own
+``DeepseekV3Config``, behind a guard.
+
+Kimi-K2-Base and -Instruct (moonshotai) declare ``model_type: "kimi_k2"`` and an ``auto_map``
+onto their repository's own ``configuration_deepseek`` / ``modeling_deepseek``. The decoder is
+DeepSeek-V3's: the configuration class there declares ``model_type = "deepseek_v3"``, the
+checkpoints declare ``DeepseekV3ForCausalLM``, and transformers itself maps a ``kimi_k2`` text
+config onto ``deepseek_v3`` (``Kimi_K25Config``). transformers registers no ``kimi_k2`` config,
+though, so ``AutoConfig.from_pretrained(trust_remote_code=False)`` refuses the repository as
+custom code, and layer streaming never runs a repository's modelling code
+(``StreamingSetupMixin._STREAM_NATIVE_MODEL_CODE``, #1933).
+
+:func:`load_stream_model_config` is the one config loader of the streamed model (the trainer
+setup and :func:`~soup_cli.utils.layer_stream_runtime.build_meta_skeleton`). Any config
+``AutoConfig`` loads is returned exactly as before. A ``kimi_k2`` config that ``AutoConfig``
+refuses is read as a plain dict (no code runs), checked by :func:`kimi_k2_guard_failures`, and
+loaded into ``DeepseekV3Config`` with ``model_type`` rewritten to ``deepseek_v3`` and
+``auto_map`` dropped: the rewrite ``AutoConfig`` would do if the file said ``deepseek_v3``.
+
+The guard admits a config only where the native class computes what K2's own
+``modeling_deepseek.py`` computes; each row names the difference it rules out. Every key of the
+published file must be present (``auto_map`` and ``quantization_config`` may be absent), and no
+other key may be. A config that fails any row is refused with :class:`UnsupportedKimiK2Error`,
+naming every failing field and its value, and saying that other K2 releases are out of scope for
+now. Kimi-K2-Thinking (compressed-tensors INT4) and Kimi-K2-Instruct-0905 (serialised defaults,
+``ep_size``, ``pad_token_id``) are refused this way. The evidence is
+``benchmarks/gate-kimi-k2-admission.md``.
+
+Known numeric differences from K2's own code, which the guard does not and cannot remove: the
+MoE combine (K2 sums the weighted expert outputs in fp32 and rounds once; the native class
+rounds each weighted output to the model dtype before ``index_add_``), eager versus sdpa
+attention, and the router bias held as a Parameter (K2) versus a float32 buffer (native).
+
+No top-level torch or transformers: the trainer imports this on its setup path.
+"""
+
+from __future__ import annotations
+
+import copy
+import importlib.util
+from typing import Any, Mapping, NamedTuple, Optional, Tuple
+
+KIMI_K2_MODEL_TYPE = "kimi_k2"
+#: The ``model_type`` the rewritten config carries: transformers' native DeepSeek-V3.
+NATIVE_MODEL_TYPE = "deepseek_v3"
+#: Keys the rewrite drops: ``auto_map`` points at the repository's own code.
+_DROPPED_KEYS = ("auto_map",)
+_ARCHITECTURES = ["DeepseekV3ForCausalLM"]
+#: Every top-level key of the published Kimi-K2-Base and Kimi-K2-Instruct ``config.json``
+#: (byte-identical files; revisions in ``benchmarks/gate-kimi-k2-admission.md``). The guard is an
+#: allowlist: a key outside this set and :data:`_METADATA_KEYS` is refused by name, because the
+#: native class may read a key K2's own code ignores (``head_dim``, ``partial_rotary_factor``, a
+#: transformers-5 ``rope_parameters`` ...) and then compute differently or crash.
+_PUBLISHED_KEYS = frozenset(
+ {
+ "architectures", "attention_bias", "attention_dropout", "auto_map", "aux_loss_alpha",
+ "bos_token_id", "eos_token_id", "first_k_dense_replace", "hidden_act", "hidden_size",
+ "initializer_range", "intermediate_size", "kv_lora_rank", "max_position_embeddings",
+ "model_type", "moe_intermediate_size", "moe_layer_freq", "n_group", "n_routed_experts",
+ "n_shared_experts", "norm_topk_prob", "num_attention_heads", "num_experts_per_tok",
+ "num_hidden_layers", "num_key_value_heads", "num_nextn_predict_layers", "pretraining_tp",
+ "q_lora_rank", "qk_nope_head_dim", "qk_rope_head_dim", "quantization_config",
+ "rms_norm_eps", "rope_theta", "routed_scaling_factor", "rope_scaling", "scoring_func",
+ "seq_aux", "tie_word_embeddings", "topk_group", "topk_method", "torch_dtype",
+ "transformers_version", "use_cache", "v_head_dim", "vocab_size",
+ }
+)
+#: Keys outside the published file, admitted because neither class computes with them.
+_METADATA_KEYS = frozenset(
+ {
+ # Added by transformers' own reader (``get_config_dict``) on 5.17, to every dict it
+ # returns (a Hub snapshot's commit, or None); 5.19 adds it to none.
+ # ``PreTrainedConfig`` pops it as the Hub revision of the file, not a model setting.
+ "_commit_hash",
+ # Written by ``save_pretrained`` as the source path: a provenance stamp only.
+ "_name_or_path",
+ # transformers 5's spelling of the published ``torch_dtype``: the checkpoint's storage
+ # dtype, which the streamed model does not use (it is built at the stream dtype).
+ "dtype",
+ }
+)
+_ALLOWED_KEYS = _PUBLISHED_KEYS | _METADATA_KEYS
+_UNEXPECTED_REASON = (
+ "unexpected field {name}: training.stream_layers admits kimi_k2 only with the published K2 "
+ "config fields"
+)
+#: Published keys a config may leave out: the rewrite drops ``auto_map`` anyway, and a copy
+#: dequantised to bf16 carries no ``quantization_config``. Every other published key must be
+#: present: a missing one would not be refused by the allowlist, and the native class would
+#: compute with its own default for it (``rope_theta`` 10000.0 where K2 publishes 50000.0,
+#: ``routed_scaling_factor`` 2.5 where K2 publishes 2.827, ...).
+_OPTIONAL_PUBLISHED_KEYS = frozenset({"auto_map", "quantization_config"})
+_REQUIRED_KEYS = tuple(sorted(_PUBLISHED_KEYS - _OPTIONAL_PUBLISHED_KEYS))
+#: A required key either spelling satisfies: transformers 5 writes ``torch_dtype`` as ``dtype``.
+_KEY_SPELLINGS = {"torch_dtype": ("torch_dtype", "dtype")}
+_MISSING_REASON = (
+ "missing field: the published Kimi-K2-Base / -Instruct config sets it, and without it the "
+ "native DeepseekV3Config would use its own default, which need not be K2's value"
+)
+#: Said in every refusal, before the field list (which a release's file can make long).
+_OUT_OF_SCOPE = (
+ "Other Kimi K2 releases (Kimi-K2-Instruct-0905, Kimi-K2-Thinking) and copies whose config "
+ "fields differ from the published Base / Instruct file are out of scope for now: layer "
+ "streaming does not admit them yet."
+)
+#: The ``rope_scaling`` keys K2's yarn reads. The native yarn reads more (``attention_factor``,
+#: ``truncate``, ``partial_rotary_factor``), each of which K2 ignores.
+_ROPE_KEYS = frozenset(
+ {
+ "type",
+ "rope_type",
+ "factor",
+ "original_max_position_embeddings",
+ "beta_fast",
+ "beta_slow",
+ "mscale",
+ "mscale_all_dim",
+ }
+)
+#: Longest rendering of a config value or key in a message; both come from an untrusted file.
+_BRIEF_LIMIT = 80
+#: Fields a refusal lists before "and N more": a file can hold any number of unexpected keys.
+_MAX_LISTED = 10
+_ABSENT = object()
+
+
+class UnsupportedKimiK2Error(ValueError):
+ """A ``kimi_k2`` config the native DeepSeek-V3 class would not compute like K2's own code."""
+
+
+class GuardFailure(NamedTuple):
+ """One field the guard refuses: its name, its value as shown, and what would differ."""
+
+ field: str
+ value: str
+ reason: str
+
+
+def _bounded(text: str) -> str:
+ return text if len(text) <= _BRIEF_LIMIT else text[: _BRIEF_LIMIT - 3] + "..."
+
+
+def _brief(value: Any) -> str:
+ """``ascii`` of an untrusted value, truncated; ``absent`` for a missing one.
+
+ ``ascii`` escapes every control and non-ASCII character (ESC, BEL, U+202E, a Cyrillic
+ homoglyph ...), so a value is shown as the bytes it is; the CLI's error printer then applies
+ ``for_terminal`` to the whole message (``utils/errors.py``).
+ """
+ if value is _ABSENT:
+ return "absent"
+ return _bounded(ascii(value))
+
+
+def _key_name(key: Any) -> str:
+ """A top-level key as a refusal names it: a plain ASCII identifier as it is, anything else
+ through :func:`_brief`; both bounded."""
+ if isinstance(key, str) and key.isascii() and key.isidentifier():
+ return _bounded(key)
+ return _brief(key)
+
+
+def _is_int(value: Any) -> bool:
+ return isinstance(value, int) and not isinstance(value, bool)
+
+
+def _is_number(value: Any) -> bool:
+ return isinstance(value, (int, float)) and not isinstance(value, bool)
+
+
+def _rope_failures(rope: Any) -> list:
+ """The ``rope_scaling`` rows: a yarn dict K2's yarn and the native yarn compute alike."""
+ if rope is _ABSENT or rope is None:
+ return [] # both use their plain rotary embedding (G1c "no-scaling")
+ if not isinstance(rope, Mapping):
+ return [
+ GuardFailure(
+ "rope_scaling", _brief(rope), "K2 reads rope_scaling as a dict (or none at all)"
+ )
+ ]
+ if not rope:
+ return [
+ GuardFailure(
+ "rope_scaling", _brief(dict(rope)),
+ "K2 indexes rope_scaling['type'] whenever rope_scaling is not null, so an empty "
+ "dict fails there, while the native class treats it as no scaling",
+ )
+ ]
+ failures = []
+ rope_kind = rope.get("type", _ABSENT)
+ if rope_kind != "yarn":
+ failures.append(
+ GuardFailure(
+ "rope_scaling.type", _brief(rope_kind),
+ "only K2's yarn is admitted (K2 reads 'type'; its linear and dynamic NTK "
+ "embeddings are not the native ones)",
+ )
+ )
+ if rope.get("rope_type", "yarn") != "yarn":
+ failures.append(
+ GuardFailure(
+ "rope_scaling.rope_type", _brief(rope.get("rope_type")),
+ "the native class reads rope_type, K2 reads type: both must say yarn",
+ )
+ )
+ for key in rope:
+ if key not in _ROPE_KEYS:
+ failures.append(
+ GuardFailure(
+ f"rope_scaling[{_brief(key)}]", _brief(rope[key]),
+ "K2's yarn ignores this key and the native yarn may read it",
+ )
+ )
+ if not _is_number(rope.get("factor", _ABSENT)):
+ failures.append(
+ GuardFailure(
+ "rope_scaling.factor", _brief(rope.get("factor", _ABSENT)),
+ "K2's yarn needs a numeric factor",
+ )
+ )
+ if "original_max_position_embeddings" not in rope:
+ failures.append(
+ GuardFailure(
+ "rope_scaling.original_max_position_embeddings", "absent",
+ "K2 defaults it to 4096, the native class to max_position_embeddings",
+ )
+ )
+ for key, default in (("beta_fast", 32), ("beta_slow", 1)):
+ if key in rope and not rope[key]:
+ failures.append(
+ GuardFailure(
+ f"rope_scaling.{key}", _brief(rope[key]),
+ f"the native yarn replaces a zero with {default}; K2 divides by it",
+ )
+ )
+ mscale = rope.get("mscale", _ABSENT)
+ if rope.get("mscale_all_dim"):
+ consistent = mscale is not _ABSENT and bool(mscale)
+ else:
+ consistent = mscale is _ABSENT or mscale == 1
+ if not consistent:
+ failures.append(
+ GuardFailure(
+ "rope_scaling.mscale", _brief(mscale),
+ "the native yarn applies mscale only beside a non-zero mscale_all_dim (and "
+ "assumes 1 otherwise); K2 always applies both, so their attention factors "
+ "differ",
+ )
+ )
+ return failures
+
+
+def _quantization_failures(quant: Any) -> list:
+ """Unquantised, or the FP8 block spelling the sharder dequantises (``utils/fp8_block``)."""
+ from soup_cli.utils.fp8_block import UnsupportedFP8Error, fp8_block_size
+
+ if quant is _ABSENT or quant is None:
+ return []
+ try:
+ block = fp8_block_size(quant, arch=NATIVE_MODEL_TYPE)
+ except UnsupportedFP8Error as exc:
+ return [GuardFailure("quantization_config", _brief(quant), str(exc))]
+ if block is not None:
+ return []
+ if isinstance(quant, Mapping) and "quant_method" in quant:
+ return [
+ GuardFailure(
+ "quantization_config.quant_method", _brief(quant["quant_method"]),
+ "layer streaming reads Kimi K2 unquantised or in DeepSeek-V3's block FP8 (the "
+ "format K2-Base and K2-Instruct are published in); it does not dequantise this "
+ "one (Kimi-K2-Thinking's is compressed-tensors INT4)",
+ )
+ ]
+ return [
+ GuardFailure(
+ "quantization_config", _brief(quant),
+ "not a quantization_config layer streaming can read",
+ )
+ ]
+
+
+def kimi_k2_guard_failures(raw: Mapping[str, Any]) -> Tuple[GuardFailure, ...]:
+ """Every field of a ``kimi_k2`` config the native class would not compute like K2, in
+ guard order; ``()`` when the config is admitted.
+
+ The order is the table in ``benchmarks/gate-kimi-k2-admission.md`` (G1b), then every
+ published key that is absent (second review; ``auto_map`` and ``quantization_config`` may
+ be), then the allowlist of top-level keys added in the review round. Its ``ep_size`` and
+ ``rope_interleave`` rows are now the allowlist's: neither key is in the published file, so
+ either is refused whenever present.
+ """
+
+ def value(key: str) -> Any:
+ return raw.get(key, _ABSENT)
+
+ failures = []
+
+ def check(key: str, admitted: bool, reason: str) -> None:
+ if not admitted:
+ failures.append(GuardFailure(key, _brief(value(key)), reason))
+
+ check(
+ "architectures", value("architectures") == _ARCHITECTURES,
+ "the published checkpoints declare exactly ['DeepseekV3ForCausalLM'], the decoder "
+ "this mapping was checked on",
+ )
+ check(
+ "topk_method", value("topk_method") == "noaux_tc",
+ "K2's router implements only 'noaux_tc'; the native router always runs it",
+ )
+ check(
+ "scoring_func", value("scoring_func") == "sigmoid",
+ "K2's router implements only 'sigmoid'; the native router always uses it",
+ )
+ group_reason = (
+ "K2 fills unselected expert groups with 0.0 and the native router with -inf; with one "
+ "group (and one group picked) nothing is masked, so the two pick the same experts"
+ )
+ check("n_group", _is_int(value("n_group")) and value("n_group") == 1, group_reason)
+ check("topk_group", _is_int(value("topk_group")) and value("topk_group") == 1, group_reason)
+ top_k = value("num_experts_per_tok")
+ renormalised = raw.get("norm_topk_prob", True)
+ check(
+ "num_experts_per_tok", _is_int(top_k) and (top_k >= 2 or not renormalised),
+ "K2 renormalises the top-k weights only when top-k > 1; the native router always does",
+ )
+ check(
+ "moe_layer_freq", value("moe_layer_freq") is _ABSENT or (
+ _is_int(value("moe_layer_freq")) and value("moe_layer_freq") == 1
+ ),
+ "K2 makes only every n-th layer an MoE layer; the native class makes every layer past "
+ "first_k_dense_replace one",
+ )
+ check(
+ "n_routed_experts",
+ _is_int(value("n_routed_experts")) and value("n_routed_experts") >= 1,
+ "without routed experts K2 builds dense layers; the native class cannot",
+ )
+ check(
+ "n_shared_experts",
+ _is_int(value("n_shared_experts")) and value("n_shared_experts") >= 0,
+ "without it K2 drops the shared expert; the native class always builds one",
+ )
+ check(
+ "num_key_value_heads",
+ _is_int(value("num_key_value_heads"))
+ and value("num_key_value_heads") == value("num_attention_heads"),
+ "K2's MLA ignores it, while the native class divides num_attention_heads by it (and "
+ "defaults it to 128 when absent): only equal to num_attention_heads, as published, do "
+ "the two compute alike",
+ )
+ failures.extend(_rope_failures(value("rope_scaling")))
+ failures.extend(_quantization_failures(value("quantization_config")))
+ # Every published key present (second review): absent, the native class would compute
+ # with its own default for it. A key whose row above already refused it is named once.
+ named = {failure.field for failure in failures}
+ for key in _REQUIRED_KEYS:
+ if key not in named and not any(
+ spelling in raw for spelling in _KEY_SPELLINGS.get(key, (key,))
+ ):
+ failures.append(GuardFailure(key, _brief(_ABSENT), _MISSING_REASON))
+ # Last, so the registered rows above keep their order (added in the review round).
+ for key in raw:
+ if key not in _ALLOWED_KEYS: # whatever the value, null included
+ name = _key_name(key)
+ quoted = name if name.startswith(("'", '"')) else f"'{name}'"
+ failures.append(
+ GuardFailure(name, _brief(raw[key]), _UNEXPECTED_REASON.format(name=quoted))
+ )
+ return tuple(failures)
+
+
+def _refusal(failures: Tuple[GuardFailure, ...]) -> UnsupportedKimiK2Error:
+ listed = "; ".join(
+ f"{item.field}={item.value} ({item.reason})" for item in failures[:_MAX_LISTED]
+ )
+ if len(failures) > _MAX_LISTED:
+ listed += f"; and {len(failures) - _MAX_LISTED} more"
+ return UnsupportedKimiK2Error(
+ f"Kimi K2 (model_type '{KIMI_K2_MODEL_TYPE}') streams through transformers' own "
+ f"DeepseekV3 class, admitted only for a config it computes like K2's own modelling "
+ f"code: Kimi-K2-Base and Kimi-K2-Instruct as published (FP8 block, or dequantised to "
+ f"bf16). {_OUT_OF_SCOPE} This config differs: {listed}."
+ )
+
+
+def kimi_k2_native_config_dict(raw: Any) -> dict:
+ """The guarded rewrite: a deep copy of ``raw`` with ``model_type`` set to ``deepseek_v3``
+ and ``auto_map`` dropped. Raises :class:`UnsupportedKimiK2Error` naming every field the
+ guard refuses. ``raw`` itself is never changed (transformers' rope standardisation writes
+ into the ``rope_scaling`` dict it is handed, hence the deep copy).
+ """
+ if not isinstance(raw, Mapping):
+ raise UnsupportedKimiK2Error(
+ f"a Kimi K2 config.json must hold a JSON object; got {_brief(raw)}, "
+ f"which is not a JSON object"
+ )
+ failures = kimi_k2_guard_failures(raw)
+ if failures:
+ raise _refusal(failures)
+ native = {key: value for key, value in copy.deepcopy(dict(raw)).items()
+ if key not in _DROPPED_KEYS}
+ native["model_type"] = NATIVE_MODEL_TYPE
+ return native
+
+
+def _raw_config_dict(model_id: str, kwargs: Mapping[str, Any]) -> Optional[tuple]:
+ """``(config dict, unused kwargs)`` exactly as ``AutoConfig.from_pretrained`` reads them,
+ or ``None`` when the file cannot be read. Reads JSON only: no code is imported or run."""
+ try:
+ from transformers import PretrainedConfig
+
+ # AutoConfig hands name_or_path through get_config_dict to from_dict the same way.
+ config_dict, unused = PretrainedConfig.get_config_dict(
+ model_id, **dict(kwargs, name_or_path=model_id)
+ )
+ except Exception: # noqa: BLE001 -- unreadable means "not a K2 we can admit"
+ return None
+ if not isinstance(config_dict, dict):
+ return None
+ return config_dict, unused
+
+
+def load_stream_model_config(model_id: str, *, trust_remote_code: bool = False, **kwargs: Any):
+ """The streamed model's config: ``AutoConfig``'s, or a guarded native one for Kimi K2.
+
+ ``kwargs`` (a pinned ``revision``) reach both reads. ``trust_remote_code=True`` is handed
+ to ``AutoConfig`` unchanged, with no K2 handling: that is the repository's own config.
+ Otherwise every config ``AutoConfig`` loads is returned as it loads it. When ``AutoConfig``
+ refuses (a ``ValueError``: K2 is "custom code" to it), the raw ``config.json`` is read;
+ anything but ``model_type: kimi_k2`` gets ``AutoConfig``'s own error back, and a K2 config
+ goes through :func:`kimi_k2_native_config_dict` into ``DeepseekV3Config``.
+ """
+ from transformers import AutoConfig
+
+ if trust_remote_code:
+ return AutoConfig.from_pretrained(model_id, trust_remote_code=True, **kwargs)
+ try:
+ return AutoConfig.from_pretrained(model_id, trust_remote_code=False, **kwargs)
+ except ValueError:
+ read = _raw_config_dict(model_id, kwargs)
+ if read is None or read[0].get("model_type") != KIMI_K2_MODEL_TYPE:
+ raise
+ config_dict, unused = read
+ native = kimi_k2_native_config_dict(config_dict)
+
+ from transformers import DeepseekV3Config
+
+ return DeepseekV3Config.from_dict(native, **unused)
+
+
+def _tiktoken_available() -> bool:
+ return importlib.util.find_spec("tiktoken") is not None
+
+
+def kimi_k2_tokenizer_hint(model_id: str, **kwargs: Any) -> Optional[str]:
+ """What to tell a user whose tokenizer load failed on a Kimi K2 base, or ``None``.
+
+ Called only on that failure path. ``None`` unless the base's ``config.json`` declares
+ ``model_type: kimi_k2``.
+ """
+ read = _raw_config_dict(model_id, kwargs)
+ if read is None or read[0].get("model_type") != KIMI_K2_MODEL_TYPE:
+ return None
+ hint = (
+ "Kimi K2's tokenizer exists only as code in its repository (tokenization_kimi.py), so "
+ "it needs --trust-remote-code. Under layer streaming that flag reaches the tokenizer "
+ "only: the config and the model are still transformers' own DeepseekV3 classes, never "
+ "the repository's code."
+ )
+ if not _tiktoken_available():
+ hint += (
+ " That tokenizer also imports the tiktoken package, which Soup does not install: "
+ "pip install tiktoken."
+ )
+ return hint
+
+
+def print_kimi_k2_tokenizer_hint(model_id: str, console: Any, **kwargs: Any) -> None:
+ """Print :func:`kimi_k2_tokenizer_hint` after a failed tokenizer load, if there is one.
+
+ Never raises: the caller re-raises the tokenizer's own error, which a hint must not hide.
+ """
+ try:
+ hint = kimi_k2_tokenizer_hint(model_id, **kwargs)
+ if hint:
+ console.print(hint, style="yellow", markup=False, highlight=False)
+ except Exception: # noqa: BLE001 -- a hint never replaces the real error
+ return
diff --git a/src/soup_cli/utils/layer_stream.py b/src/soup_cli/utils/layer_stream.py
index 5d2cb9c3..e4ab77c3 100644
--- a/src/soup_cli/utils/layer_stream.py
+++ b/src/soup_cli/utils/layer_stream.py
@@ -89,7 +89,10 @@ FLOPS_PER_PARAM_PER_TOKEN = 6
#: ``deepseek_v3`` is the DeepSeek-V3 family (MLA attention, DeepSeekMoE with
#: a shared expert, the first ``first_k_dense_replace`` layers dense). Kimi K2
#: ships the same decoder under ``model_type='kimi_k2'``, which transformers
-#: does not register, so that name stays refused here too.
+#: does not register. The streamed model's config loader (``utils/kimi_k2.py``)
+#: reads such a config into the native ``DeepseekV3Config`` behind a guard, so a
+#: K2 that passes it streams as ``deepseek_v3``; the name ``kimi_k2`` is not in
+#: this list, and a config still carrying it did not pass that guard.
SUPPORTED_STREAM_ARCHS = (
"llama",
"qwen2",
diff --git a/src/soup_cli/utils/layer_stream_runtime.py b/src/soup_cli/utils/layer_stream_runtime.py
index 86af91df..cec24ec5 100644
--- a/src/soup_cli/utils/layer_stream_runtime.py
+++ b/src/soup_cli/utils/layer_stream_runtime.py
@@ -2560,8 +2560,9 @@ def build_meta_skeleton(
views land in modules that know how to consume them.
"""
from accelerate import init_empty_weights
- from transformers import AutoConfig, AutoModelForCausalLM
+ from transformers import AutoModelForCausalLM
+ from soup_cli.utils.kimi_k2 import load_stream_model_config
from soup_cli.utils.layer_shard import QUANT_NF4, SUPPORTED_STREAM_QUANTS
from soup_cli.utils.run_provenance import base_revision_kwargs
@@ -2571,7 +2572,9 @@ def build_meta_skeleton(
f"{', '.join(SUPPORTED_STREAM_QUANTS)}"
)
torch_dtype = _torch_dtype(dtype)
- config = AutoConfig.from_pretrained(
+ # AutoConfig's config, or for Kimi K2 the guarded native one (utils/kimi_k2.py); both
+ # reads pinned to the run's bound base commit (#2094).
+ config = load_stream_model_config(
model_id, trust_remote_code=trust_remote_code, **base_revision_kwargs(model_id),
)
config.use_cache = False
diff --git a/tests/test_backend_base_revision.py b/tests/test_backend_base_revision.py
index f222eb8b..3b0a276d 100644
--- a/tests/test_backend_base_revision.py
+++ b/tests/test_backend_base_revision.py
@@ -62,7 +62,9 @@ def test_stream_setup_pins_tokenizer_and_architecture_config(monkeypatch, moving
with pytest.raises(AfterConfigError):
wrapper._setup_streaming_transformers(cfg, cfg.training)
assert identity.revision == SHA
- assert calls == ["tokenizer", "config"]
+ # The model config is read first (#2107: a refused Kimi K2 config is reported before
+ # the tokenizer load), and both reads are pinned to the one bound commit.
+ assert calls == ["config", "tokenizer"]
moving_hub.assert_called_once()
diff --git a/tests/test_base_loader_contracts.py b/tests/test_base_loader_contracts.py
index 17f75738..e867c32b 100644
--- a/tests/test_base_loader_contracts.py
+++ b/tests/test_base_loader_contracts.py
@@ -85,11 +85,7 @@ def test_every_actual_base_loader_call_receives_the_bound_commit(call, receiver,
assert seen == [(BASE, REVISION)]
[email protected]("receiver,remote_code", [("AutoConfig", False), ("AutoTokenizer", True)])
-def test_streamed_loads_preserve_native_model_policy_and_bound_revision(
- receiver, remote_code, monkeypatch,
-):
- """Execute the merged calls: tokenizer trust must not enable remote model code."""
+def _stream_setup_tree():
path = ROOT / "src/soup_cli/trainer/stream_setup.py"
tree = ast.parse(path.read_text(encoding="utf-8"))
model_code = next(
@@ -100,29 +96,111 @@ def test_streamed_loads_preserve_native_model_policy_and_bound_revision(
)
)
assert model_code is False
+ return tree, model_code
+
+
+def _from_pretrained_calls(tree, receiver):
+ return [node for node in ast.walk(tree)
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
+ and isinstance(node.func.value, ast.Name) and node.func.value.id == receiver
+ and node.func.attr == "from_pretrained"]
+
+
+def _bind_revision(monkeypatch):
+ monkeypatch.setattr(provenance, "get_hf_api", lambda: SimpleNamespace(
+ model_info=lambda *args, **kwargs: SimpleNamespace(sha=REVISION),
+ ))
+ monkeypatch.delenv("HF_HUB_OFFLINE", raising=False)
+ monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising=False)
+
+
[email protected]("kimi_k2", [False, True], ids=["autoconfig", "kimi-k2-raw-read"])
+def test_streamed_config_load_preserves_native_model_policy_and_bound_revision(
+ kimi_k2, monkeypatch,
+):
+ """Execute the merged call through the real loader: tokenizer trust must not enable remote
+ model code, and every read the loader makes carries the bound commit.
+
+ #2107 moved the streamed model's config read from ``AutoConfig.from_pretrained`` in
+ stream_setup into ``utils/kimi_k2.load_stream_model_config``, which reads ``AutoConfig``
+ and, for a Kimi K2 file ``AutoConfig`` refuses as custom code, the raw ``config.json``.
+ Both reads are strict receivers here: a dropped revision or a True policy fails."""
+ pytest.importorskip("transformers")
+ from transformers import AutoConfig, PretrainedConfig
+
+ from soup_cli.utils.kimi_k2 import load_stream_model_config
+ from tests.test_kimi_k2_streaming import K2_BASE_CONFIG
+
+ tree, model_code = _stream_setup_tree()
+ # No second, unguarded config read beside the loader.
+ assert _from_pretrained_calls(tree, "AutoConfig") == []
calls = [node for node in ast.walk(tree)
- if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
- and isinstance(node.func.value, ast.Name) and node.func.value.id == receiver
- and node.func.attr == "from_pretrained"]
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name)
+ and node.func.id == "load_stream_model_config"]
+ assert len(calls) == 1
+ seen = []
+ native = object()
+
+ def auto_config(model_id, *, trust_remote_code, revision):
+ assert model_id == BASE and revision == REVISION
+ assert trust_remote_code is False
+ seen.append("AutoConfig")
+ if kimi_k2:
+ raise ValueError("The repository contains custom code")
+ return native
+
+ def raw_read(model_id, *, revision, name_or_path):
+ assert model_id == name_or_path == BASE and revision == REVISION
+ seen.append("get_config_dict")
+ return dict(K2_BASE_CONFIG), {}
+
+ monkeypatch.setattr(AutoConfig, "from_pretrained", auto_config)
+ monkeypatch.setattr(PretrainedConfig, "get_config_dict", raw_read)
+ env = {
+ "cfg": SimpleNamespace(base=BASE),
+ "self": SimpleNamespace(_trust_remote_code=True, _STREAM_NATIVE_MODEL_CODE=model_code),
+ "load_stream_model_config": load_stream_model_config,
+ "base_revision_kwargs": provenance.base_revision_kwargs,
+ }
+ _bind_revision(monkeypatch)
+ with provenance.base_revision_scope(provenance.BaseRevision(BASE)):
+ config = eval(
+ compile(ast.Expression(body=calls[0]), "<streamed config load>", "eval"), env,
+ )
+ if kimi_k2:
+ assert seen == ["AutoConfig", "get_config_dict"]
+ assert config.model_type == "deepseek_v3"
+ else:
+ assert seen == ["AutoConfig"]
+ assert config is native
+
+
+def test_streamed_tokenizer_load_keeps_user_trust_bound_revision_and_the_native_config(
+ monkeypatch,
+):
+ """The tokenizer gets the user's trust flag, the bound commit, and the model config already
+ loaded: without ``config=``, ``AutoTokenizer`` reads the config again with the user's flag
+ and, for a repository with an ``auto_map`` (Kimi K2, Moonlight), imports its code."""
+ tree, model_code = _stream_setup_tree()
+ calls = _from_pretrained_calls(tree, "AutoTokenizer")
assert len(calls) == 1
seen = []
+ model_config = object()
- def load(model_id, *, trust_remote_code, revision):
+ def load(model_id, *, config, trust_remote_code, revision):
assert model_id == BASE and revision == REVISION
- assert trust_remote_code is remote_code
+ assert config is model_config
+ assert trust_remote_code is True
seen.append(model_id)
env = {
"cfg": SimpleNamespace(base=BASE),
"self": SimpleNamespace(_trust_remote_code=True, _STREAM_NATIVE_MODEL_CODE=model_code),
- receiver: SimpleNamespace(from_pretrained=load),
+ "AutoTokenizer": SimpleNamespace(from_pretrained=load),
+ "model_config": model_config,
"base_revision_kwargs": provenance.base_revision_kwargs,
}
- monkeypatch.setattr(provenance, "get_hf_api", lambda: SimpleNamespace(
- model_info=lambda *args, **kwargs: SimpleNamespace(sha=REVISION),
- ))
- monkeypatch.delenv("HF_HUB_OFFLINE", raising=False)
- monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising=False)
+ _bind_revision(monkeypatch)
with provenance.base_revision_scope(provenance.BaseRevision(BASE)):
- eval(compile(ast.Expression(body=calls[0]), "<streamed base load>", "eval"), env)
+ eval(compile(ast.Expression(body=calls[0]), "<streamed tokenizer load>", "eval"), env)
assert seen == [BASE]
diff --git a/tests/test_deepseek_v3_streaming.py b/tests/test_deepseek_v3_streaming.py
index 3c1b76a4..40a29652 100644
--- a/tests/test_deepseek_v3_streaming.py
+++ b/tests/test_deepseek_v3_streaming.py
@@ -24,9 +24,41 @@ def test_deepseek_v3_is_an_admitted_stream_arch():
assert stream_arch_of(SimpleNamespace(model_type="deepseek_v3")) == "deepseek_v3"
-def test_kimi_k2_model_type_is_still_refused_naming_the_allowlist():
- """transformers registers no ``kimi_k2`` config, so the name stays refused;
- the message must point at the admitted family."""
+def test_kimi_k2_is_admitted_through_the_guarded_config_loader(tmp_path):
+ """Kimi-K2-Base / -Instruct declare ``model_type: kimi_k2``, which AutoConfig refuses as
+ custom code. The streamed model's config loader (``utils/kimi_k2.py``) reads it into the
+ native ``DeepseekV3Config`` after a guard, so a K2 that passes streams as this family. The
+ gate is ``tests/test_kimi_k2_streaming.py`` (benchmarks/gate-kimi-k2-admission.md)."""
+ import json
+
+ pytest.importorskip("transformers")
+ from soup_cli.utils.kimi_k2 import load_stream_model_config
+ from soup_cli.utils.layer_stream import stream_arch_of
+ from tests.test_kimi_k2_streaming import K2_BASE_CONFIG
+
+ (tmp_path / "config.json").write_text(json.dumps(K2_BASE_CONFIG), encoding="utf-8")
+ assert stream_arch_of(load_stream_model_config(str(tmp_path))) == "deepseek_v3"
+
+
+def test_kimi_k2_that_fails_the_guard_is_refused_by_name(tmp_path):
+ """Kimi-K2-Thinking (compressed-tensors INT4) among them: the field and value are named."""
+ import json
+
+ pytest.importorskip("transformers")
+ from soup_cli.utils.kimi_k2 import UnsupportedKimiK2Error, load_stream_model_config
+ from tests.test_kimi_k2_streaming import K2_BASE_CONFIG, K2_THINKING_CHANGES
+
+ thinking = dict(K2_BASE_CONFIG, **K2_THINKING_CHANGES)
+ (tmp_path / "config.json").write_text(json.dumps(thinking), encoding="utf-8")
+ with pytest.raises(UnsupportedKimiK2Error) as caught:
+ load_stream_model_config(str(tmp_path))
+ assert "quantization_config.quant_method='compressed-tensors'" in str(caught.value)
+ assert "kimi_k2" in str(caught.value)
+
+
+def test_a_kimi_k2_config_that_bypassed_the_loader_is_still_refused_naming_the_allowlist():
+ """``kimi_k2`` itself is not an admitted name: a config still carrying it (K2's own remote
+ config class keeps it) did not pass the guard, and the message points at the family."""
from soup_cli.utils.layer_stream import stream_arch_of
with pytest.raises(ValueError, match="deepseek_v3") as caught:
diff --git a/tests/test_kimi_k2_streaming.py b/tests/test_kimi_k2_streaming.py
new file mode 100644
index 00000000..8751703e
--- /dev/null
+++ b/tests/test_kimi_k2_streaming.py
@@ -0,0 +1,1824 @@
+"""Layer streaming admits Kimi K2 through transformers' own ``DeepseekV3Config``.
+
+The gate is ``benchmarks/gate-kimi-k2-admission.md`` (G1-G3, pre-registered). Kimi-K2-Base and
+-Instruct declare ``model_type: kimi_k2`` and an ``auto_map`` onto their repository's own code,
+which layer streaming never runs (#1933), so ``AutoConfig`` refused them as custom code before
+the architecture allowlist was reached. ``utils/kimi_k2.py`` loads the raw ``config.json`` into
+the native class (``model_type`` -> ``deepseek_v3``, ``auto_map`` dropped) behind a guard; every
+variant the guard refuses is refused by name, naming the field and its value.
+
+Nothing here imports or executes K2's own Python. The router and yarn references in the G1c
+section are transcribed by hand from K2's ``modeling_deepseek.py`` read as text.
+"""
+
+from __future__ import annotations
+
+import copy
+import json
+import math
+import os
+import re
+import shutil
+from types import SimpleNamespace
+
+import pytest
+
+#: moonshotai/Kimi-K2-Base ``config.json`` at revision ce72df012259dcc55d945e890f815fe7ef69159c
+#: (sha256 8c13ae1049df55f29b3bdcae69a562433f243ff70dac251d819ecad8dbdf7439), verbatim. The
+#: Kimi-K2-Instruct file at revision fd1984e2b7a3350dbf7305fe73a4ede25c14de50 is byte-identical.
+K2_BASE_CONFIG = {
+ "architectures": ["DeepseekV3ForCausalLM"],
+ "attention_bias": False,
+ "attention_dropout": 0.0,
+ "auto_map": {
+ "AutoConfig": "configuration_deepseek.DeepseekV3Config",
+ "AutoModel": "modeling_deepseek.DeepseekV3Model",
+ "AutoModelForCausalLM": "modeling_deepseek.DeepseekV3ForCausalLM",
+ },
+ "aux_loss_alpha": 0.001,
+ "bos_token_id": 163584,
+ "eos_token_id": 163585,
+ "first_k_dense_replace": 1,
+ "hidden_act": "silu",
+ "hidden_size": 7168,
+ "initializer_range": 0.02,
+ "intermediate_size": 18432,
+ "kv_lora_rank": 512,
+ "max_position_embeddings": 131072,
+ "model_type": "kimi_k2",
+ "moe_intermediate_size": 2048,
+ "moe_layer_freq": 1,
+ "n_group": 1,
+ "n_routed_experts": 384,
+ "n_shared_experts": 1,
+ "norm_topk_prob": True,
+ "num_attention_heads": 64,
+ "num_experts_per_tok": 8,
+ "num_hidden_layers": 61,
+ "num_key_value_heads": 64,
+ "num_nextn_predict_layers": 0,
+ "pretraining_tp": 1,
+ "q_lora_rank": 1536,
+ "qk_nope_head_dim": 128,
+ "qk_rope_head_dim": 64,
+ "quantization_config": {
+ "activation_scheme": "dynamic",
+ "fmt": "e4m3",
+ "quant_method": "fp8",
+ "weight_block_size": [128, 128],
+ },
+ "rms_norm_eps": 1e-06,
+ "rope_theta": 50000.0,
+ "routed_scaling_factor": 2.827,
+ "rope_scaling": {
+ "beta_fast": 1.0,
+ "beta_slow": 1.0,
+ "factor": 32.0,
+ "mscale": 1.0,
+ "mscale_all_dim": 1.0,
+ "original_max_position_embeddings": 4096,
+ "type": "yarn",
+ },
+ "scoring_func": "sigmoid",
+ "seq_aux": True,
+ "tie_word_embeddings": False,
+ "topk_group": 1,
+ "topk_method": "noaux_tc",
+ "torch_dtype": "bfloat16",
+ "transformers_version": "4.48.3",
+ "use_cache": True,
+ "v_head_dim": 128,
+ "vocab_size": 163840,
+}
+
+#: The fields moonshotai/Kimi-K2-Thinking's ``config.json`` (revision
+#: a51ccc050d73dab088bf7b0e2dd9b30ae85a4e55, sha256
+#: 666ee58fc3871ecc369a22bc8c100075c2ad24ccbe8b3e336fa5f726e6111c15) sets differently from Base,
+#: trimmed: its serialised generation defaults (``do_sample``, ``top_k``, ...) are left out.
+K2_THINKING_CHANGES = {
+ "eos_token_id": 163586,
+ "ep_size": 1,
+ "max_position_embeddings": 262144,
+ "pad_token_id": 163839,
+ "quantization_config": {
+ "config_groups": {
+ "group_0": {
+ "input_activations": None,
+ "output_activations": None,
+ "targets": ["Linear"],
+ "weights": {
+ "actorder": None,
+ "block_structure": None,
+ "dynamic": False,
+ "group_size": 32,
+ "num_bits": 4,
+ "observer": "minmax",
+ "observer_kwargs": {},
+ "strategy": "group",
+ "symmetric": True,
+ "type": "int",
+ },
+ }
+ },
+ "format": "pack-quantized",
+ "ignore": [
+ "lm_head",
+ "re:.*self_attn.*",
+ "re:.*shared_experts.*",
+ "re:.*mlp\\.(gate|up|gate_up|down)_proj.*",
+ ],
+ "kv_cache_scheme": None,
+ "quant_method": "compressed-tensors",
+ "quantization_status": "compressed",
+ },
+ "rms_norm_eps": 1e-05,
+ "rope_scaling": {
+ "beta_fast": 1.0,
+ "beta_slow": 1.0,
+ "factor": 64.0,
+ "mscale": 1.0,
+ "mscale_all_dim": 1.0,
+ "original_max_position_embeddings": 4096,
+ "type": "yarn",
+ },
+ "transformers_version": "4.51.3",
+}
+
+#: Every field moonshotai/Kimi-K2-Instruct-0905's ``config.json`` (revision
+#: ac6c49f04883bd0a0598b790693a72061c676629, sha256
+#: 4cd10b0f3cb1c1dfdbfcdd2f303057500f570b24f671ce5eb7650b6a511807cc; the file only, read by the
+#: second review) sets differently from Base, untrimmed. It drops no Base key. The decoder is
+#: the same; beyond max_position_embeddings, rms_norm_eps and the yarn factor it adds
+#: ``ep_size``, ``pad_token_id`` and the serialised ``PretrainedConfig`` defaults.
+K2_INSTRUCT_0905_CHANGES = {
+ "_attn_implementation_autoset": False, "_name_or_path": "", "add_cross_attention": False,
+ "bad_words_ids": None, "begin_suppress_tokens": None, "chunk_size_feed_forward": 0,
+ "cross_attention_hidden_size": None, "decoder_start_token_id": None,
+ "diversity_penalty": 0.0, "do_sample": False, "early_stopping": False,
+ "encoder_no_repeat_ngram_size": 0, "ep_size": 1, "exponential_decay_length_penalty": None,
+ "finetuning_task": None, "forced_bos_token_id": None, "forced_eos_token_id": None,
+ "id2label": {"0": "LABEL_0", "1": "LABEL_1"}, "is_decoder": False,
+ "is_encoder_decoder": False, "label2id": {"LABEL_0": 0, "LABEL_1": 1},
+ "length_penalty": 1.0, "max_length": 20, "max_position_embeddings": 262144, "min_length": 0,
+ "no_repeat_ngram_size": 0, "num_beam_groups": 1, "num_beams": 1, "num_return_sequences": 1,
+ "output_attentions": False, "output_hidden_states": False, "output_scores": False,
+ "pad_token_id": 163839, "prefix": None, "problem_type": None, "pruned_heads": {},
+ "remove_invalid_values": False, "repetition_penalty": 1.0, "return_dict": True,
+ "return_dict_in_generate": False, "rms_norm_eps": 1e-05,
+ "rope_scaling": {
+ "beta_fast": 1.0, "beta_slow": 1.0, "factor": 64.0, "mscale": 1.0, "mscale_all_dim": 1.0,
+ "original_max_position_embeddings": 4096, "type": "yarn",
+ },
+ "sep_token_id": None, "suppress_tokens": None, "task_specific_params": None,
+ "temperature": 1.0, "tf_legacy_loss": False, "tie_encoder_decoder": False,
+ "tokenizer_class": None, "top_k": 50, "top_p": 1.0, "torchscript": False,
+ "transformers_version": "4.51.3", "typical_p": 1.0, "use_bfloat16": False,
+}
+
+
+def _base(**changes):
+ raw = copy.deepcopy(K2_BASE_CONFIG)
+ raw.update(copy.deepcopy(changes))
+ return raw
+
+
+def _without(*keys, raw=None):
+ raw = _base() if raw is None else raw
+ for key in keys:
+ raw.pop(key)
+ return raw
+
+
+def _rope(**changes):
+ rope = dict(K2_BASE_CONFIG["rope_scaling"], **changes)
+ return {"rope_scaling": rope}
+
+
+def _rope_without(*keys):
+ rope = dict(K2_BASE_CONFIG["rope_scaling"])
+ for key in keys:
+ rope.pop(key)
+ return {"rope_scaling": rope}
+
+
+def _write_config(directory, raw):
+ directory.mkdir(parents=True, exist_ok=True)
+ (directory / "config.json").write_text(json.dumps(raw), encoding="utf-8")
+ return str(directory)
+
+
+def _native_dict(raw):
+ """The rewrite done by hand: what the tests compare Soup's against."""
+ native = {key: value for key, value in copy.deepcopy(raw).items() if key != "auto_map"}
+ native["model_type"] = "deepseek_v3"
+ return native
+
+
+# ==========================================================================
+# G1a: the rewritten config carries every K2 field
+# ==========================================================================
+def test_the_published_base_config_loads_into_deepseek_v3_field_by_field(tmp_path):
+ pytest.importorskip("transformers")
+ from transformers import DeepseekV3Config
+
+ from soup_cli.utils.kimi_k2 import load_stream_model_config
+
+ config = load_stream_model_config(_write_config(tmp_path / "k2", K2_BASE_CONFIG))
+ assert type(config) is DeepseekV3Config
+ assert config.model_type == "deepseek_v3"
+ assert getattr(config, "auto_map", None) is None
+ for key, value in K2_BASE_CONFIG.items():
+ if key in ("model_type", "auto_map"):
+ continue
+ if key == "torch_dtype":
+ assert str(config.torch_dtype) == "torch." + value
+ continue
+ got = config.rope_parameters["rope_theta"] if key == "rope_theta" else getattr(config, key)
+ if key == "rope_scaling":
+ # transformers' rope standardisation adds two keys to the dict it is handed (a
+ # native deepseek_v3 config.json gets the same); every K2 key keeps its value.
+ assert {name: got[name] for name in value} == value
+ assert {name: got[name] for name in set(got) - set(value)} == {
+ "rope_theta": K2_BASE_CONFIG["rope_theta"], "rope_type": "yarn"
+ }
+ continue
+ assert got == value, key
+ for key, value in K2_BASE_CONFIG["rope_scaling"].items():
+ assert config.rope_parameters[key] == value, key
+ assert config.rope_parameters["rope_type"] == "yarn"
+
+
+def test_autoconfig_alone_still_refuses_the_k2_folder_as_custom_code(tmp_path):
+ """Today's failure, the control for the test above: the admission is the rewrite."""
+ pytest.importorskip("transformers")
+ from transformers import AutoConfig
+
+ folder = _write_config(tmp_path / "k2", K2_BASE_CONFIG)
+ with pytest.raises(ValueError, match="custom code"):
+ AutoConfig.from_pretrained(folder, trust_remote_code=False)
+
+
+def test_the_k2_path_builds_what_autoconfig_builds_for_the_same_dict(tmp_path):
+ pytest.importorskip("transformers")
+ from transformers import AutoConfig
+
+ from soup_cli.utils.kimi_k2 import load_stream_model_config
+
+ k2_folder = _write_config(tmp_path / "k2", K2_BASE_CONFIG)
+ native_folder = _write_config(tmp_path / "native", _native_dict(K2_BASE_CONFIG))
+ k2 = load_stream_model_config(k2_folder)
+ native = AutoConfig.from_pretrained(native_folder)
+ assert (k2.name_or_path, native.name_or_path) == (k2_folder, native_folder)
+ left, right = k2.to_dict(), native.to_dict()
+ left.pop("_name_or_path")
+ right.pop("_name_or_path")
+ assert left == right
+
+
+def test_the_loader_never_loads_remote_code(tmp_path, monkeypatch):
+ pytest.importorskip("transformers")
+ import transformers.dynamic_module_utils as dynamic
+ import transformers.models.auto.configuration_auto as configuration_auto
+
+ from soup_cli.utils.kimi_k2 import load_stream_model_config
+
+ def _refuse(*_args, **_kwargs):
+ raise AssertionError("remote code was loaded")
+
+ monkeypatch.setattr(dynamic, "get_class_from_dynamic_module", _refuse)
+ monkeypatch.setattr(configuration_auto, "get_class_from_dynamic_module", _refuse)
+ config = load_stream_model_config(_write_config(tmp_path / "k2", K2_BASE_CONFIG))
+ assert config.model_type == "deepseek_v3"
+
+
+def test_the_rewrite_copies_deeply_and_changes_only_model_type_and_auto_map():
+ from soup_cli.utils.kimi_k2 import kimi_k2_native_config_dict
+
+ raw = _base()
+ native = kimi_k2_native_config_dict(raw)
+ assert raw == K2_BASE_CONFIG
+ assert native == _native_dict(K2_BASE_CONFIG)
+ # transformers' rope standardisation writes into the rope dict it is handed.
+ assert native["rope_scaling"] is not raw["rope_scaling"]
+ assert native["quantization_config"] is not raw["quantization_config"]
+
+
+def test_a_config_that_is_not_k2_goes_through_autoconfig_unchanged(tmp_path):
+ pytest.importorskip("transformers")
+ from transformers import AutoConfig
+
+ from soup_cli.utils.kimi_k2 import load_stream_model_config
+
+ llama = {
+ "model_type": "llama", "hidden_size": 8, "intermediate_size": 16,
+ "num_attention_heads": 2, "num_hidden_layers": 1, "vocab_size": 32,
+ }
+ folder = _write_config(tmp_path / "llama", llama)
+ got, want = load_stream_model_config(folder), AutoConfig.from_pretrained(folder)
+ assert type(got) is type(want)
+ assert got.to_dict() == want.to_dict()
+
+
+def test_another_custom_code_repo_keeps_transformers_own_error(tmp_path):
+ pytest.importorskip("transformers")
+ from transformers import AutoConfig
+
+ from soup_cli.utils.kimi_k2 import UnsupportedKimiK2Error, load_stream_model_config
+
+ raw = {"model_type": "acme_lm", "auto_map": {"AutoConfig": "configuration_acme.AcmeConfig"}}
+ folder = _write_config(tmp_path / "acme", raw)
+ with pytest.raises(ValueError) as soup_error:
+ load_stream_model_config(folder)
+ with pytest.raises(ValueError) as hf_error:
+ AutoConfig.from_pretrained(folder, trust_remote_code=False)
+ assert not isinstance(soup_error.value, UnsupportedKimiK2Error)
+ assert str(soup_error.value) == str(hf_error.value)
+
+
+def test_a_folder_without_a_config_keeps_transformers_own_error(tmp_path):
+ pytest.importorskip("transformers")
+ from transformers import AutoConfig
+
+ from soup_cli.utils.kimi_k2 import UnsupportedKimiK2Error, load_stream_model_config
+
+ folder = tmp_path / "empty"
+ folder.mkdir()
+ with pytest.raises(Exception) as soup_error:
+ load_stream_model_config(str(folder))
+ with pytest.raises(Exception) as hf_error:
+ AutoConfig.from_pretrained(str(folder), trust_remote_code=False)
+ assert not isinstance(soup_error.value, UnsupportedKimiK2Error)
+ assert type(soup_error.value) is type(hf_error.value)
+ assert str(soup_error.value) == str(hf_error.value)
+
+
+def test_trust_remote_code_true_goes_to_autoconfig_without_a_rewrite(monkeypatch):
+ pytest.importorskip("transformers")
+ import transformers
+
+ from soup_cli.utils.kimi_k2 import load_stream_model_config
+
+ seen = []
+ monkeypatch.setattr(
+ transformers.AutoConfig, "from_pretrained",
+ staticmethod(lambda model_id, **kwargs: seen.append((model_id, kwargs)) or "remote"),
+ )
+ assert load_stream_model_config("some/repo", trust_remote_code=True) == "remote"
+ assert seen == [("some/repo", {"trust_remote_code": True})]
+
+
+def test_revision_kwargs_reach_both_config_reads(monkeypatch):
+ pytest.importorskip("transformers")
+ import transformers
+
+ from soup_cli.utils.kimi_k2 import load_stream_model_config
+
+ seen = {}
+
+ def _auto(model_id, **kwargs):
+ seen["auto"] = (model_id, kwargs)
+ raise ValueError("contains custom code")
+
+ def _raw(cls, model_id, **kwargs):
+ seen["raw"] = (model_id, kwargs)
+ return copy.deepcopy(K2_BASE_CONFIG), {}
+
+ monkeypatch.setattr(transformers.AutoConfig, "from_pretrained", staticmethod(_auto))
+ monkeypatch.setattr(transformers.PretrainedConfig, "get_config_dict", classmethod(_raw))
+ config = load_stream_model_config("moonshotai/Kimi-K2-Base", revision="abc123")
+ assert config.model_type == "deepseek_v3"
+ assert seen["auto"] == (
+ "moonshotai/Kimi-K2-Base", {"trust_remote_code": False, "revision": "abc123"}
+ )
+ assert seen["raw"][0] == "moonshotai/Kimi-K2-Base"
+ assert seen["raw"][1]["revision"] == "abc123"
+
+
+def test_the_kimi_k2_model_type_alone_is_still_refused_by_the_allowlist():
+ """A config that did not come through the guarded loader (K2's own remote config class
+ keeps ``model_type == 'kimi_k2'``) is still refused, naming the admitted family."""
+ from soup_cli.utils.layer_stream import stream_arch_of
+
+ with pytest.raises(ValueError, match="deepseek_v3") as caught:
+ stream_arch_of(SimpleNamespace(model_type="kimi_k2"))
+ assert "kimi_k2" in str(caught.value)
+
+
[email protected]("text_type", ["kimi_k2", "deepseek_v3"])
+def test_kimi_k25_stays_refused_by_name(text_type):
+ """K2.5 / K2.6 are a vision-language wrapper (``kimi_k25``): not a K2 the guard admits."""
+ from soup_cli.utils.layer_stream import stream_arch_of
+
+ text_config = SimpleNamespace(model_type=text_type)
+ config = SimpleNamespace(model_type="kimi_k25", text_config=text_config)
+ with pytest.raises(ValueError, match="kimi_k25"):
+ stream_arch_of(config)
+
+
+def test_the_rewritten_k2_is_keyed_like_deepseek_v3_everywhere_streaming_keys_on_arch(tmp_path):
+ pytest.importorskip("transformers")
+ from soup_cli.utils.fp8_block import FP8_BLOCK_ARCHS, fp8_block_size
+ from soup_cli.utils.kimi_k2 import load_stream_model_config
+ from soup_cli.utils.layer_shard import (
+ PER_EXPERT_LAYOUT_ARCHS,
+ layer_buffer_keys,
+ source_identity_includes_config,
+ )
+ from soup_cli.utils.layer_stream import stream_arch_of
+
+ config = load_stream_model_config(_write_config(tmp_path / "k2", K2_BASE_CONFIG))
+ arch = stream_arch_of(config)
+ assert arch == "deepseek_v3"
+ assert arch in PER_EXPERT_LAYOUT_ARCHS and arch in FP8_BLOCK_ARCHS
+ assert layer_buffer_keys(arch) == ("mlp.gate.e_score_correction_bias",)
+ assert source_identity_includes_config(arch) is True
+ assert fp8_block_size(config.quantization_config, arch=arch) == (128, 128)
+
+
[email protected]("q_lora_rank", [1536, None], ids=["q_lora", "q_proj"])
+def test_lora_targets_are_the_ones_the_kimi_k2_row_gives(tmp_path, q_lora_rank):
+ """#2071's ``kimi_k2`` rows and the ``deepseek_v3`` rows agree, so the rewrite does not
+ change what ``target_modules: auto`` adapts."""
+ pytest.importorskip("transformers")
+ from soup_cli.utils.kimi_k2 import load_stream_model_config
+ from soup_cli.utils.peft_wiring import resolve_lora_target_modules
+
+ raw = _base(q_lora_rank=q_lora_rank)
+ config = load_stream_model_config(_write_config(tmp_path / "k2", raw))
+ as_kimi = SimpleNamespace(model_type="kimi_k2", q_lora_rank=q_lora_rank)
+ got = resolve_lora_target_modules(config, "auto")
+ assert tuple(got) == tuple(resolve_lora_target_modules(as_kimi, "auto"))
+ assert ("q_proj" in got) is (q_lora_rank is None)
+
+
+# ==========================================================================
+# G1b: the guard
+# ==========================================================================
+_THINKING_QUANT = K2_THINKING_CHANGES["quantization_config"]
+
+#: (id, changes to the Base dict or a callable building the dict, field named, value shown)
+_REFUSED = [
+ ("architectures", {"architectures": ["DeepseekV3ForSequenceClassification"]},
+ "architectures", "['DeepseekV3ForSequenceClassification']"),
+ ("architectures-absent", lambda: _without("architectures"), "architectures", "absent"),
+ ("topk_method", {"topk_method": "greedy"}, "topk_method", "'greedy'"),
+ ("topk_method-absent", lambda: _without("topk_method"), "topk_method", "absent"),
+ ("scoring_func", {"scoring_func": "softmax"}, "scoring_func", "'softmax'"),
+ ("scoring_func-absent", lambda: _without("scoring_func"), "scoring_func", "absent"),
+ ("n_group", {"n_group": 8}, "n_group", "8"),
+ ("n_group-absent", lambda: _without("n_group"), "n_group", "absent"),
+ ("topk_group", {"topk_group": 4}, "topk_group", "4"),
+ ("num_experts_per_tok", {"num_experts_per_tok": 1}, "num_experts_per_tok", "1"),
+ ("num_experts_per_tok-float", {"num_experts_per_tok": 8.0}, "num_experts_per_tok", "8.0"),
+ ("num_experts_per_tok-bool", {"num_experts_per_tok": True, "norm_topk_prob": False},
+ "num_experts_per_tok", "True"),
+ ("moe_layer_freq", {"moe_layer_freq": 2}, "moe_layer_freq", "2"),
+ ("ep_size", {"ep_size": 8}, "ep_size", "8"),
+ ("ep_size-text", {"ep_size": "1"}, "ep_size", "'1'"),
+ ("n_routed_experts", {"n_routed_experts": None}, "n_routed_experts", "None"),
+ ("n_shared_experts", {"n_shared_experts": None}, "n_shared_experts", "None"),
+ ("num_key_value_heads", {"num_key_value_heads": 8}, "num_key_value_heads", "8"),
+ ("rope_interleave", {"rope_interleave": False}, "rope_interleave", "False"),
+ ("rope-not-a-dict", {"rope_scaling": "yarn"}, "rope_scaling", "'yarn'"),
+ ("rope-type", _rope(type="linear"), "rope_scaling.type", "'linear'"),
+ ("rope-type-absent", _rope_without("type"), "rope_scaling.type", "absent"),
+ ("rope-rope_type", _rope(rope_type="dynamic"), "rope_scaling.rope_type", "'dynamic'"),
+ ("rope-truncate", _rope(truncate=False), "rope_scaling['truncate']", "False"),
+ ("rope-attention_factor", _rope(attention_factor=1.5),
+ "rope_scaling['attention_factor']", "1.5"),
+ ("rope-factor-absent", _rope_without("factor"), "rope_scaling.factor", "absent"),
+ ("rope-factor-text", _rope(factor="32"), "rope_scaling.factor", "'32'"),
+ ("rope-original-absent", _rope_without("original_max_position_embeddings"),
+ "rope_scaling.original_max_position_embeddings", "absent"),
+ ("rope-beta_fast-zero", _rope(beta_fast=0), "rope_scaling.beta_fast", "0"),
+ ("rope-beta_slow-zero", _rope(beta_slow=0.0), "rope_scaling.beta_slow", "0.0"),
+ ("rope-mscale-absent", _rope_without("mscale"), "rope_scaling.mscale", "absent"),
+ ("rope-mscale-zero", _rope(mscale=0), "rope_scaling.mscale", "0"),
+ ("rope-mscale-alone", _rope(mscale=0.707, mscale_all_dim=0), "rope_scaling.mscale", "0.707"),
+ ("quant-compressed-tensors", {"quantization_config": _THINKING_QUANT},
+ "quantization_config.quant_method", "'compressed-tensors'"),
+ ("quant-gptq", {"quantization_config": {"quant_method": "gptq", "bits": 4}},
+ "quantization_config.quant_method", "'gptq'"),
+ ("quant-not-a-dict", {"quantization_config": "fp8"}, "quantization_config", "'fp8'"),
+ ("quant-fp8-per-tensor", {"quantization_config": {"quant_method": "fp8"}},
+ "quantization_config", "per-tensor FP8 scales"),
+ ("quant-fp8-e5m2", {"quantization_config": dict(K2_BASE_CONFIG["quantization_config"],
+ fmt="e5m2")},
+ "quantization_config", "e5m2"),
+ # Added in the review round (benchmarks/gate-kimi-k2-admission.md, section 7): the guard is an
+ # allowlist of the published top-level keys, and num_key_value_heads is required.
+ ("num_key_value_heads-absent", lambda: _without("num_key_value_heads"),
+ "num_key_value_heads", "absent"),
+ ("num_key_value_heads-divides", {"num_key_value_heads": 32}, "num_key_value_heads", "32"),
+ ("rope_parameters", {"rope_parameters": {"rope_type": "yarn", "factor": 32.0,
+ "attention_factor": 1.5, "truncate": False}},
+ "rope_parameters", "'attention_factor': 1.5"),
+ ("partial_rotary_factor", {"partial_rotary_factor": 0.5}, "partial_rotary_factor", "0.5"),
+ ("head_dim", {"head_dim": 128}, "head_dim", "128"),
+ ("rope-partial_rotary_factor", _rope(partial_rotary_factor=0.5),
+ "rope_scaling['partial_rotary_factor']", "0.5"),
+ ("rope-empty", {"rope_scaling": {}}, "rope_scaling", "{}"),
+ ("ep_size-1", {"ep_size": 1}, "ep_size", "1"),
+ ("rope_interleave-true", {"rope_interleave": True}, "rope_interleave", "True"),
+ ("pad_token_id", {"pad_token_id": 163839}, "pad_token_id", "163839"),
+ ("sliding_window", {"sliding_window": 4096}, "sliding_window", "4096"),
+ # Round-2 review: a null value of a key outside the allowlist is refused like any other.
+ ("head_dim-null", {"head_dim": None}, "head_dim", "None"),
+ # Second review (LOW 3): a published key may not be left out, or the native class would
+ # compute with its own default (rope_theta 10000.0, routed_scaling_factor 2.5, ...). The
+ # first two were admitted before; every published key is covered by the test below.
+ ("moe_layer_freq-absent", lambda: _without("moe_layer_freq"), "moe_layer_freq", "absent"),
+ ("rope_scaling-absent", lambda: _without("rope_scaling"), "rope_scaling", "absent"),
+ ("rope_theta-absent", lambda: _without("rope_theta"), "rope_theta", "absent"),
+ ("routed_scaling_factor-absent", lambda: _without("routed_scaling_factor"),
+ "routed_scaling_factor", "absent"),
+ ("rms_norm_eps-absent", lambda: _without("rms_norm_eps"), "rms_norm_eps", "absent"),
+ ("norm_topk_prob-absent", lambda: _without("norm_topk_prob"), "norm_topk_prob", "absent"),
+ ("torch_dtype-absent", lambda: _without("torch_dtype"), "torch_dtype", "absent"),
+]
+
+
+def _refused_raw(changes):
+ return changes() if callable(changes) else _base(**changes)
+
+
+ ("changes", "field", "shown"), [case[1:] for case in _REFUSED], ids=[c[0] for c in _REFUSED]
+)
+def test_each_guard_failure_is_refused_naming_the_field_and_its_value(changes, field, shown):
+ from soup_cli.utils.kimi_k2 import (
+ UnsupportedKimiK2Error,
+ kimi_k2_guard_failures,
+ kimi_k2_native_config_dict,
+ )
+
+ raw = _refused_raw(changes)
+ failures = kimi_k2_guard_failures(raw)
+ assert [failure.field for failure in failures] == [field]
+ with pytest.raises(UnsupportedKimiK2Error) as caught:
+ kimi_k2_native_config_dict(raw)
+ message = str(caught.value)
+ assert f"{field}=" in message
+ assert shown in message
+ assert "kimi_k2" in message
+ assert "out of scope for now" in message
+
+
+#: Published keys a K2 config may leave out: the rewrite drops ``auto_map``, and a copy
+#: dequantised to bf16 has no ``quantization_config``.
+_OPTIONAL_PUBLISHED = {"auto_map", "quantization_config"}
+
+
[email protected]("key", sorted(set(K2_BASE_CONFIG) - _OPTIONAL_PUBLISHED))
+def test_every_published_key_but_auto_map_and_quantization_config_is_required(key):
+ """Second review (LOW 3): a K2 file without a published key was admitted when no row read
+ that key, and the native class then computed with its own default for it."""
+ from soup_cli.utils.kimi_k2 import UnsupportedKimiK2Error, kimi_k2_native_config_dict
+
+ with pytest.raises(UnsupportedKimiK2Error) as caught:
+ kimi_k2_native_config_dict(_without(key))
+ assert f"{key}=absent" in str(caught.value)
+
+
[email protected]("key", sorted(_OPTIONAL_PUBLISHED))
+def test_auto_map_and_quantization_config_may_be_absent(key):
+ from soup_cli.utils.kimi_k2 import kimi_k2_guard_failures
+
+ assert kimi_k2_guard_failures(_without(key)) == ()
+
+
+def test_top_1_without_norm_topk_prob_is_refused_on_both_rows():
+ """Absent, ``norm_topk_prob`` reads as renormalising, which K2 skips at top-1; the
+ presence row names the missing key as well."""
+ from soup_cli.utils.kimi_k2 import kimi_k2_guard_failures
+
+ raw = _without("norm_topk_prob", raw=_base(num_experts_per_tok=1))
+ failures = kimi_k2_guard_failures(raw)
+ assert [failure.field for failure in failures] == ["num_experts_per_tok", "norm_topk_prob"]
+ assert [failure.value for failure in failures] == ["1", "absent"]
+
+
+def test_a_key_its_own_row_refuses_as_absent_is_named_once():
+ from soup_cli.utils.kimi_k2 import kimi_k2_guard_failures
+
+ failures = kimi_k2_guard_failures(_without("architectures", "n_group"))
+ assert [failure.field for failure in failures] == ["architectures", "n_group"]
+
+
+def test_the_refusal_is_a_value_error_raised_by_the_loader_before_any_model(tmp_path):
+ pytest.importorskip("transformers")
+ from soup_cli.utils.kimi_k2 import UnsupportedKimiK2Error, load_stream_model_config
+
+ folder = _write_config(tmp_path / "k2", _base(n_group=8))
+ with pytest.raises(UnsupportedKimiK2Error, match=r"n_group=8") as caught:
+ load_stream_model_config(folder)
+ assert isinstance(caught.value, ValueError)
+
+
+def test_thinking_is_refused_and_quantization_config_is_the_first_failing_field(tmp_path):
+ pytest.importorskip("transformers")
+ from soup_cli.utils.kimi_k2 import (
+ UnsupportedKimiK2Error,
+ kimi_k2_guard_failures,
+ load_stream_model_config,
+ )
+
+ raw = _base(**K2_THINKING_CHANGES)
+ # The registered rows first; the review round's allowlist then names the two fields of
+ # Thinking's file that the published Base / Instruct file does not have.
+ assert [failure.field for failure in kimi_k2_guard_failures(raw)] == [
+ "quantization_config.quant_method", "ep_size", "pad_token_id"
+ ]
+ with pytest.raises(UnsupportedKimiK2Error) as caught:
+ load_stream_model_config(_write_config(tmp_path / "thinking", raw))
+ assert "quantization_config.quant_method='compressed-tensors'" in str(caught.value)
+
+
+_ADMITTED = [
+ ("published", {}),
+ ("rope_scaling-null", {"rope_scaling": None}),
+ ("rope-rope_type-yarn", _rope(rope_type="yarn")),
+ ("rope-mscale-pair-absent", _rope_without("mscale", "mscale_all_dim")),
+ ("rope-mscale-1-alone", _rope(mscale=1.0, mscale_all_dim=0)),
+ ("rope-mscale-pair-other", _rope(mscale=0.707, mscale_all_dim=0.707)),
+ ("rope-betas-absent", _rope_without("beta_fast", "beta_slow")),
+ ("rope-factor-int", _rope(factor=32)),
+ ("quantization_config-absent", lambda: _without("quantization_config")),
+ ("quantization_config-null", {"quantization_config": None}),
+ ("fp8-scale_fmt-float", {"quantization_config": dict(K2_BASE_CONFIG["quantization_config"],
+ scale_fmt="float")}),
+ ("fp8-no-fmt", lambda: _base(quantization_config={
+ "activation_scheme": "dynamic", "quant_method": "fp8", "weight_block_size": [128, 128]})),
+ ("top-1-without-norm", {"num_experts_per_tok": 1, "norm_topk_prob": False}),
+ ("n_shared_experts-0", {"n_shared_experts": 0}),
+ ("metadata", {"_commit_hash": "ce72df012259dcc55d945e890f815fe7ef69159c",
+ "_name_or_path": "moonshotai/Kimi-K2-Base", "dtype": "bfloat16"}),
+ # transformers 5 spells the published torch_dtype as dtype: either satisfies the key.
+ ("torch_dtype-as-dtype", lambda: _without("torch_dtype", raw=_base(dtype="bfloat16"))),
+]
+
+
+def test_thinking_without_its_quantization_is_still_refused_by_the_allowlist():
+ """Thinking's file carries fields the published Base / Instruct file does not."""
+ from soup_cli.utils.kimi_k2 import kimi_k2_guard_failures
+
+ raw = _without("quantization_config", raw=_base(**K2_THINKING_CHANGES))
+ failures = kimi_k2_guard_failures(raw)
+ assert [failure.field for failure in failures] == ["ep_size", "pad_token_id"]
+ assert all("unexpected field" in failure.reason for failure in failures)
+ assert all("training.stream_layers" in failure.reason for failure in failures)
+
+
+def test_kimi_k2_instruct_0905_is_refused_as_out_of_scope_before_its_field_list(tmp_path):
+ """Second review (LOW 4): the 0905 file was refused with a long list of serialised defaults
+ and "and N more", never saying that the release is not admitted. Every refusal now says so,
+ before the list; the fields it names are exactly the keys the published file lacks."""
+ pytest.importorskip("transformers")
+ from soup_cli.utils.kimi_k2 import (
+ _METADATA_KEYS,
+ UnsupportedKimiK2Error,
+ kimi_k2_guard_failures,
+ load_stream_model_config,
+ )
+
+ raw = _base(**K2_INSTRUCT_0905_CHANGES)
+ extra = [key for key in raw if key not in K2_BASE_CONFIG and key not in _METADATA_KEYS]
+ assert [failure.field for failure in kimi_k2_guard_failures(raw)] == extra
+ with pytest.raises(UnsupportedKimiK2Error) as caught:
+ load_stream_model_config(_write_config(tmp_path / "0905", raw))
+ message = str(caught.value)
+ scope = message.index("Other Kimi K2 releases (Kimi-K2-Instruct-0905, Kimi-K2-Thinking)")
+ assert "out of scope for now" in message[scope:message.index("This config differs:")]
+ assert message.index("This config differs:") > scope
+ assert f"and {len(extra) - 10} more" in message
+
+
+def test_the_allowlist_is_exactly_the_published_keys_plus_named_metadata():
+ from soup_cli.utils.kimi_k2 import _METADATA_KEYS, _PUBLISHED_KEYS
+
+ assert _PUBLISHED_KEYS == set(K2_BASE_CONFIG)
+ assert _METADATA_KEYS == {"_commit_hash", "_name_or_path", "dtype"}
+
+
+_BASE_REVISION = "ce72df012259dcc55d945e890f815fe7ef69159c"
+
+
[email protected]("layout", ["hub-snapshot", "plain-folder"])
+def test_the_loader_admits_the_metadata_transformers_reader_adds(tmp_path, layout):
+ """transformers' reader adds ``_commit_hash`` to the dict on 5.17 (None for a plain folder,
+ the commit for a Hub cache's ``snapshots/<commit>/`` folder) and not at all on 5.19 (CI runs
+ 39626025729, 39758361029), where the config has no ``_commit_hash`` attribute either. So
+ presence is asserted for neither: whatever the reader records, the loader admits and keeps."""
+ pytest.importorskip("transformers")
+ from transformers import PretrainedConfig
+
+ from soup_cli.utils.kimi_k2 import _METADATA_KEYS, load_stream_model_config
+
+ if layout == "hub-snapshot":
+ directory = tmp_path / "models--moonshotai--Kimi-K2-Base" / "snapshots" / _BASE_REVISION
+ else:
+ directory = tmp_path / "k2"
+ folder = _write_config(directory, K2_BASE_CONFIG)
+ read = PretrainedConfig.get_config_dict(folder)[0]
+ assert set(read) - set(K2_BASE_CONFIG) <= _METADATA_KEYS
+ config = load_stream_model_config(folder)
+ assert config.model_type == "deepseek_v3"
+ # Whatever commit the reader recorded survives the rewrite (the snapshot's, on 5.17); on
+ # 5.19 neither the dict nor the config carries one.
+ assert getattr(config, "_commit_hash", None) == read.get("_commit_hash")
+
+
[email protected]("changes", [case[1] for case in _ADMITTED], ids=[c[0] for c in _ADMITTED])
+def test_admitted_variants_pass_the_guard(changes):
+ from soup_cli.utils.kimi_k2 import kimi_k2_guard_failures, kimi_k2_native_config_dict
+
+ raw = _refused_raw(changes)
+ assert kimi_k2_guard_failures(raw) == ()
+ assert kimi_k2_native_config_dict(raw)["model_type"] == "deepseek_v3"
+
+
+def test_every_failure_is_listed_in_guard_order():
+ from soup_cli.utils.kimi_k2 import UnsupportedKimiK2Error, kimi_k2_native_config_dict
+
+ raw = _base(
+ quantization_config=_THINKING_QUANT, n_group=8, architectures=["X"], **_rope(truncate=1)
+ )
+ with pytest.raises(UnsupportedKimiK2Error) as caught:
+ kimi_k2_native_config_dict(raw)
+ message = str(caught.value)
+ positions = [
+ message.index(name)
+ for name in ("architectures=", "n_group=", "rope_scaling['truncate']=",
+ "quantization_config.quant_method=")
+ ]
+ assert positions == sorted(positions)
+
+
+def test_a_refusal_never_quotes_raw_control_bytes_and_stays_short():
+ from soup_cli.utils.kimi_k2 import UnsupportedKimiK2Error, kimi_k2_native_config_dict
+
+ hostile_key = "\x1b[2Jkey\u202e"
+ hostile = "\x1b[31mred\x1b[0m\u202e" + "x" * 5000
+ raw = _base(topk_method=hostile, **_rope(**{"\x1b]0;title\x07": 1}))
+ raw[hostile_key] = hostile
+ with pytest.raises(UnsupportedKimiK2Error) as caught:
+ kimi_k2_native_config_dict(raw)
+ message = str(caught.value)
+ assert "\x1b" not in message and "\u202e" not in message and "\x07" not in message
+ assert len(message) < 2500
+
+
+def test_non_ascii_key_names_and_values_are_shown_escaped():
+ """Round-2 review: a homoglyph key (Cyrillic U+0435 in "head_dim") or value (U+043E in
+ "noaux_tc") must not reach the message raw, where it would read as the ASCII name."""
+ from soup_cli.utils.kimi_k2 import UnsupportedKimiK2Error, kimi_k2_native_config_dict
+
+ key = "h" + chr(0x435) + "ad_dim"
+ value = "n" + chr(0x43E) + "aux_tc"
+ raw = _base(topk_method=value)
+ raw[key] = 128
+ with pytest.raises(UnsupportedKimiK2Error) as caught:
+ kimi_k2_native_config_dict(raw)
+ message = str(caught.value)
+ assert message.isascii()
+ assert "u0435" in message and "u043e" in message
+
+
+def test_a_refusal_stays_bounded_whatever_the_key_names_and_their_number():
+ """Round-2 review: a 200,000-character identifier key gave a 400 KB message."""
+ from soup_cli.utils.kimi_k2 import (
+ UnsupportedKimiK2Error,
+ kimi_k2_guard_failures,
+ kimi_k2_native_config_dict,
+ )
+
+ raw = _base()
+ raw["k" * 200_000] = 1
+ for idx in range(99):
+ raw[f"extra_field_{idx}"] = idx
+ assert len(kimi_k2_guard_failures(raw)) == 100
+ with pytest.raises(UnsupportedKimiK2Error) as caught:
+ kimi_k2_native_config_dict(raw)
+ message = str(caught.value)
+ assert len(message) < 3000
+ assert "and 90 more" in message
+ assert "k" * 81 not in message
+
+
+def test_the_guard_reads_a_mapping_only():
+ from soup_cli.utils.kimi_k2 import UnsupportedKimiK2Error, kimi_k2_native_config_dict
+
+ with pytest.raises(UnsupportedKimiK2Error, match="not a JSON object"):
+ kimi_k2_native_config_dict(["kimi_k2"])
+
+
+# ==========================================================================
+# G1c: the numeric guard rows, against a hand transcription of K2's code
+# ==========================================================================
+def _k2_gate(hidden, weight, bias, *, top_k, n_group, topk_group, norm_topk_prob, scaling):
+ """K2's ``MoEGate.forward`` for ``noaux_tc`` + ``sigmoid``, transcribed from
+ ``modeling_deepseek.py`` (sha256 ce753fc9...) read as text."""
+ import torch
+ from torch.nn.functional import linear
+
+ bsz, seq_len, h = hidden.shape
+ hidden = hidden.view(-1, h)
+ logits = linear(hidden.type(torch.float32), weight.type(torch.float32), None)
+ scores = logits.sigmoid()
+ n_routed = weight.shape[0]
+ scores_for_choice = scores.view(bsz * seq_len, -1) + bias.unsqueeze(0)
+ group_scores = (
+ scores_for_choice.view(bsz * seq_len, n_group, -1).topk(2, dim=-1)[0].sum(dim=-1)
+ )
+ group_idx = torch.topk(group_scores, k=topk_group, dim=-1, sorted=False)[1]
+ group_mask = torch.zeros_like(group_scores)
+ group_mask.scatter_(1, group_idx, 1)
+ score_mask = (
+ group_mask.unsqueeze(-1)
+ .expand(bsz * seq_len, n_group, n_routed // n_group)
+ .reshape(bsz * seq_len, -1)
+ )
+ tmp_scores = scores_for_choice.masked_fill(~score_mask.bool(), 0.0)
+ _, topk_idx = torch.topk(tmp_scores, k=top_k, dim=-1, sorted=False)
+ topk_weight = scores.gather(1, topk_idx)
+ if top_k > 1 and norm_topk_prob:
+ denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
+ topk_weight = topk_weight / denominator
+ return topk_idx, topk_weight * scaling
+
+
+def _router_pair(*, n_group=1, topk_group=1, top_k=8, experts=384, bias_shift=0.0):
+ """(K2 transcription, native router) on the same random weights."""
+ import torch
+ from transformers import DeepseekV3Config
+ from transformers.models.deepseek_v3.modeling_deepseek_v3 import DeepseekV3TopkRouter
+
+ hidden_size = 32
+ config = DeepseekV3Config(
+ hidden_size=hidden_size, n_routed_experts=experts, num_experts_per_tok=top_k,
+ n_group=n_group, topk_group=topk_group, norm_topk_prob=True, routed_scaling_factor=2.827,
+ )
+ generator = torch.Generator().manual_seed(5)
+ weight = torch.randn(experts, hidden_size, generator=generator)
+ bias = torch.randn(experts, generator=generator) * 0.1 + bias_shift
+ hidden = torch.randn(2, 9, hidden_size, generator=generator)
+ router = DeepseekV3TopkRouter(config)
+ with torch.no_grad():
+ router.weight.copy_(weight)
+ router.e_score_correction_bias.copy_(bias)
+ _logits, native_weight, native_idx = router(hidden)
+ k2_idx, k2_weight = _k2_gate(
+ hidden, weight, bias, top_k=top_k, n_group=n_group, topk_group=topk_group,
+ norm_topk_prob=True, scaling=2.827,
+ )
+
+ def by_expert(idx, weights):
+ order = idx.argsort(dim=-1)
+ return idx.gather(1, order), weights.gather(1, order)
+
+ return by_expert(k2_idx, k2_weight), by_expert(native_idx, native_weight)
+
+
+def test_the_native_router_equals_k2s_at_k2s_group_and_top_k_values():
+ import torch
+
+ pytest.importorskip("transformers")
+ (k2_idx, k2_weight), (native_idx, native_weight) = _router_pair()
+ assert torch.equal(k2_idx, native_idx)
+ assert torch.equal(k2_weight, native_weight)
+
+
+def test_the_routers_differ_once_a_group_is_masked_so_n_group_is_guarded():
+ """K2 fills masked experts with 0.0: an all-negative biased score loses to them."""
+ import torch
+
+ pytest.importorskip("transformers")
+ (k2_idx, _), (native_idx, _) = _router_pair(
+ n_group=2, topk_group=1, top_k=2, experts=8, bias_shift=-5.0
+ )
+ assert not torch.equal(k2_idx, native_idx)
+
+
+def test_the_routers_differ_at_top_1_so_num_experts_per_tok_is_guarded():
+ import torch
+
+ pytest.importorskip("transformers")
+ (k2_idx, k2_weight), (native_idx, native_weight) = _router_pair(top_k=1, experts=8)
+ assert torch.equal(k2_idx, native_idx)
+ assert not torch.equal(k2_weight, native_weight)
+
+
+def _k2_mscale(scale, mscale=1):
+ return 1.0 if scale <= 1 else 0.1 * mscale * math.log(scale) + 1.0
+
+
+def _k2_softmax_scale(q_head_dim, rope_scaling):
+ """``DeepseekV3Attention.softmax_scale`` in K2's code, in the same operation order."""
+ scale = q_head_dim ** (-0.5)
+ if rope_scaling is not None:
+ mscale_all_dim = rope_scaling.get("mscale_all_dim", 0)
+ if mscale_all_dim:
+ mscale = _k2_mscale(rope_scaling["factor"], mscale_all_dim)
+ scale = scale * mscale * mscale
+ return scale
+
+
+def _k2_rope(dim, base, rope_scaling, seq_len):
+ """K2's rotary cos/sin cache (``DeepseekV3RotaryEmbedding`` or its yarn subclass),
+ transcribed from ``modeling_deepseek.py``."""
+ import torch
+
+ if rope_scaling is None:
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
+ t = torch.arange(seq_len, dtype=inv_freq.dtype)
+ emb = torch.cat((torch.outer(t, inv_freq),) * 2, dim=-1)
+ return emb.cos(), emb.sin()
+ factor = rope_scaling["factor"]
+ original = rope_scaling.get("original_max_position_embeddings", 4096)
+ beta_fast = rope_scaling.get("beta_fast", 32)
+ beta_slow = rope_scaling.get("beta_slow", 1)
+ mscale = rope_scaling.get("mscale", 1)
+ mscale_all_dim = rope_scaling.get("mscale_all_dim", 0)
+
+ def correction_dim(rotations):
+ return (dim * math.log(original / (rotations * 2 * math.pi))) / (2 * math.log(base))
+
+ low = max(math.floor(correction_dim(beta_fast)), 0)
+ high = min(math.ceil(correction_dim(beta_slow)), dim - 1)
+ freq_extra = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim))
+ freq_inter = 1.0 / (factor * base ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim))
+ top = high + 0.001 if low == high else high
+ ramp = torch.clamp((torch.arange(dim // 2, dtype=torch.float32) - low) / (top - low), 0, 1)
+ inv_freq_mask = 1.0 - ramp
+ inv_freq = freq_inter * (1 - inv_freq_mask) + freq_extra * inv_freq_mask
+ t = torch.arange(seq_len, dtype=torch.float32)
+ emb = torch.cat((torch.outer(t, inv_freq),) * 2, dim=-1)
+ attention = float(_k2_mscale(factor, mscale) / _k2_mscale(factor, mscale_all_dim))
+ return emb.cos() * attention, emb.sin() * attention
+
+
+def _k2_reference(raw, seq_len):
+ """(cos, sin, softmax scale) K2's code computes for a config dict, by transcription."""
+ rope_scaling = raw.get("rope_scaling")
+ cos, sin = _k2_rope(raw["qk_rope_head_dim"], raw["rope_theta"], rope_scaling, seq_len)
+ q_head_dim = raw["qk_nope_head_dim"] + raw["qk_rope_head_dim"]
+ return cos, sin, _k2_softmax_scale(q_head_dim, rope_scaling)
+
+
+def _native_rope(raw, seq_len):
+ """(cos, sin, attention scaling) of the native class for a K2 dict, guard bypassed."""
+ import torch
+ from transformers import DeepseekV3Config
+ from transformers.models.deepseek_v3.modeling_deepseek_v3 import (
+ DeepseekV3Attention,
+ DeepseekV3RotaryEmbedding,
+ )
+
+ config = DeepseekV3Config.from_dict(_native_dict(raw))
+ rotary = DeepseekV3RotaryEmbedding(config)
+ positions = torch.arange(seq_len)[None, :]
+ cos, sin = rotary(torch.zeros(1, dtype=torch.float32), positions)
+ with torch.device("meta"):
+ attention = DeepseekV3Attention(config, layer_idx=0)
+ return cos[0], sin[0], attention.scaling
+
+
+#: The investigation's claim was bit-identity at 4096 positions.
+_ROPE_SEQ = 4096
+
+
+ "changes",
+ [{}, {"rope_scaling": None}, _rope(mscale=1.0, mscale_all_dim=0),
+ _rope_without("mscale", "mscale_all_dim"), _rope(mscale=0.707, mscale_all_dim=0.707),
+ _rope_without("beta_fast", "beta_slow"), _rope(factor=8.0)],
+ ids=["published", "no-scaling", "mscale-1-alone", "no-mscale", "mscale-pair",
+ "default-betas", "factor-8"],
+)
+def test_the_native_rope_equals_k2s_on_admitted_values(changes):
+ import torch
+
+ pytest.importorskip("transformers")
+ raw = _base(**changes)
+ k2_cos, k2_sin, k2_scale = _k2_reference(raw, _ROPE_SEQ)
+ cos, sin, scale = _native_rope(raw, _ROPE_SEQ)
+ assert torch.equal(cos, k2_cos)
+ assert torch.equal(sin, k2_sin)
+ assert scale == k2_scale
+
+
+ "changes",
+ [_rope_without("original_max_position_embeddings"), _rope_without("mscale"),
+ _rope(mscale=0.707, mscale_all_dim=0), _rope(attention_factor=1.5), _rope(beta_fast=0)],
+ ids=["no-original", "mscale_all_dim-alone", "mscale-alone", "attention_factor", "beta-0"],
+)
+def test_the_ropes_differ_on_each_refused_rope_variant(changes):
+ import torch
+
+ pytest.importorskip("transformers")
+ raw = _base(**changes)
+ cos, sin, scale = _native_rope(raw, _ROPE_SEQ)
+ try:
+ k2_cos, k2_sin, k2_scale = _k2_reference(raw, _ROPE_SEQ)
+ except ZeroDivisionError:
+ assert changes == _rope(beta_fast=0)
+ return # K2's own code cannot compute it; the native class silently would
+ assert not (torch.equal(cos, k2_cos) and torch.equal(sin, k2_sin) and scale == k2_scale)
+
+
+# ==========================================================================
+# G2: streamed vs resident parity on a tiny K2-like checkpoint (CPU fp32)
+# ==========================================================================
+_TINY = dict(
+ vocab_size=128, hidden_size=64, intermediate_size=128, moe_intermediate_size=32,
+ num_hidden_layers=3, first_k_dense_replace=1, num_attention_heads=4,
+ num_key_value_heads=4, n_shared_experts=1, n_routed_experts=8, n_group=1, topk_group=1,
+ num_experts_per_tok=2, kv_lora_rank=16, q_lora_rank=24, qk_nope_head_dim=16,
+ qk_rope_head_dim=8, v_head_dim=16, max_position_embeddings=2048, bos_token_id=0,
+ eos_token_id=1,
+)
+_TINY_YARN = {
+ "beta_fast": 1.0, "beta_slow": 1.0, "factor": 32.0, "mscale": 1.0, "mscale_all_dim": 1.0,
+ "original_max_position_embeddings": 64,
+}
+_TINY_LAYERS = 3
+_BLOCK = (16, 32)
+#: The real checkpoint carries 61 of these (BF16 [56]); neither K2's code (non-persistent
+#: buffer) nor the native class (no per-layer rotary module) reads them.
+_STALE_INV_FREQ = "self_attn.rotary_emb.inv_freq"
+_STALE_VALUE = 12345.0
+
+
+def _tiny_k2_raw():
+ """The real Base ``config.json`` with tiny dimensions substituted."""
+ raw = _without("quantization_config", raw=_base(**_TINY))
+ raw["rope_scaling"] = dict(_TINY_YARN, type="yarn")
+ return raw
+
+
+def _native_tiny_config(*, yarn=True):
+ """The resident control's config, from keyword arguments: never through Soup's loader."""
+ from transformers import DeepseekV3Config
+
+ rope = {"rope_type": "yarn", "rope_theta": 50000.0, **_TINY_YARN}
+ if not yarn:
+ rope = {"rope_type": "default", "rope_theta": 50000.0}
+ return DeepseekV3Config(
+ **_TINY, rope_parameters=rope, rms_norm_eps=1e-6, routed_scaling_factor=2.827,
+ norm_topk_prob=True, tie_word_embeddings=False, num_mtp_layers=0,
+ )
+
+
+def _fp8_tools():
+ from tests.test_fp8_block_streaming import _harness, _reference_dequant
+
+ return _harness(), _reference_dequant
+
+
[email protected](scope="module")
+def k2_checkpoints(tmp_path_factory):
+ """{"bf16": (K2 folder, resident folder), "fp8": (...)}: the same seeded weights."""
+ torch = pytest.importorskip("torch")
+ pytest.importorskip("transformers")
+ from safetensors.torch import load_file, save_file
+ from transformers import DeepseekV3ForCausalLM
+
+ root = tmp_path_factory.mktemp("kimi-k2-tiny")
+ torch.manual_seed(11)
+ model = DeepseekV3ForCausalLM(_native_tiny_config()).to(torch.float32).eval()
+ generator = torch.Generator().manual_seed(23)
+ with torch.no_grad():
+ for layer in model.model.layers[1:]:
+ bias = layer.mlp.gate.e_score_correction_bias
+ bias.copy_(torch.randn(bias.shape, generator=generator) * 2.0)
+ for parameter in model.parameters():
+ parameter.data = parameter.data.to(torch.bfloat16)
+ native = root / "native-bf16"
+ model.save_pretrained(str(native))
+ state = load_file(str(native / "model.safetensors"))
+ # The real index's per-expert spelling, which the sharder stacks.
+ assert "model.layers.1.mlp.experts.0.gate_proj.weight" in state
+ stale = {
+ f"model.layers.{idx}.{_STALE_INV_FREQ}": torch.full((7,), _STALE_VALUE).to(torch.bfloat16)
+ for idx in range(_TINY_LAYERS)
+ }
+ k2 = root / "k2-bf16"
+ k2.mkdir()
+ save_file({**state, **stale}, str(k2 / "model.safetensors"), metadata={"format": "pt"})
+ (k2 / "config.json").write_text(json.dumps(_tiny_k2_raw()), encoding="utf-8")
+
+ harness, reference_dequant = _fp8_tools()
+ fp8 = root / "k2-fp8"
+ harness.convert_checkpoint(str(k2), str(fp8), block=_BLOCK, log=lambda _line: None)
+ fp8_state = load_file(str(fp8 / "model.safetensors"))
+ assert any(value.dtype == torch.float8_e4m3fn for value in fp8_state.values())
+ ref_state = {}
+ for key, value in fp8_state.items():
+ if key.endswith("_scale_inv") or key.endswith(_STALE_INV_FREQ):
+ continue
+ scale = fp8_state.get(key + "_scale_inv")
+ ref_state[key] = value if scale is None else reference_dequant(value, scale, _BLOCK)
+ ref = root / "native-fp8-ref"
+ ref.mkdir()
+ save_file(ref_state, str(ref / "model.safetensors"), metadata={"format": "pt"})
+ shutil.copyfile(native / "config.json", ref / "config.json")
+ assert not any(name.endswith(".py") for folder in (k2, fp8) for name in os.listdir(folder))
+ return {"bf16": (str(k2), str(native)), "fp8": (str(fp8), str(ref))}
+
+
+def _resident(weights, layout="", config=None):
+ import torch
+ from transformers import DeepseekV3ForCausalLM
+
+ extra = {} if config is None else {"config": config}
+ model, info = DeepseekV3ForCausalLM.from_pretrained(
+ weights, dtype=torch.float32, output_loading_info=True, **extra
+ )
+ assert not (info["missing_keys"] or info["unexpected_keys"] or info["mismatched_keys"]), info
+ if layout == "per_expert":
+ # The streamed experts follow the eager loop; the resident control must too.
+ model.set_experts_implementation("eager")
+ return model.eval()
+
+
+def _lora_config(model_config):
+ from peft import LoraConfig, TaskType
+
+ from soup_cli.utils.peft_wiring import resolve_lora_target_modules
+
+ return LoraConfig(
+ r=4, lora_alpha=8, lora_dropout=0.0, bias="none",
+ target_modules=list(resolve_lora_target_modules(model_config, "auto")),
+ task_type=TaskType.CAUSAL_LM,
+ )
+
+
+def _streamed(tmp_path, weights, layout):
+ from soup_cli.utils.kimi_k2 import load_stream_model_config
+ from soup_cli.utils.layer_shard import shard_checkpoint
+ from soup_cli.utils.layer_stream import stream_arch_of
+ from soup_cli.utils.layer_stream_runtime import build_streamed_model
+
+ config = load_stream_model_config(weights)
+ arch = stream_arch_of(config)
+ shards = str(tmp_path / "shards")
+ index = shard_checkpoint(
+ weights, shards, dtype="float32", arch=arch,
+ num_hidden_layers=config.num_hidden_layers, expert_layout=layout,
+ )
+ model, runtime = build_streamed_model(
+ model_id=weights, shard_dir=shards, index=index, lora_config=_lora_config(config),
+ device="cpu", dtype="float32", buffers=2, pin=False, seed=3,
+ )
+ return model, runtime, config, shards, index
+
+
+def _paired(tmp_path, k2_checkpoints, source, layout):
+ import torch
+ from peft import get_peft_model
+
+ weights, resident_weights = k2_checkpoints[source]
+ model, runtime, config, shards, index = _streamed(tmp_path, weights, layout)
+ resident = get_peft_model(_resident(resident_weights, layout), _lora_config(config))
+ generator = torch.Generator().manual_seed(17)
+ with torch.no_grad():
+ for name, parameter in model.named_parameters():
+ if "lora_B" in name:
+ parameter.copy_(torch.randn(parameter.shape, generator=generator) * 0.02)
+ src = {k.replace(".inner.", "."): v for k, v in model.state_dict().items() if "lora_" in k}
+ dst = {k: v for k, v in resident.state_dict().items() if "lora_" in k}
+ assert src and set(src) == set(dst)
+ for key, value in src.items():
+ dst[key].copy_(value)
+ model.eval()
+ resident.eval()
+ ids = torch.randint(0, 128, (2, 12), generator=generator)
+ return SimpleNamespace(
+ model=model, runtime=runtime, resident=resident, ids=ids, shards=shards, index=index
+ )
+
+
+def _refuse_remote_code(monkeypatch):
+ import transformers.dynamic_module_utils as dynamic
+ import transformers.models.auto.configuration_auto as configuration_auto
+
+ def _refuse(*_args, **_kwargs):
+ raise AssertionError("remote code was loaded")
+
+ monkeypatch.setattr(dynamic, "get_class_from_dynamic_module", _refuse)
+ monkeypatch.setattr(configuration_auto, "get_class_from_dynamic_module", _refuse)
+
+
+_G2_CELLS = [("", "bf16"), ("per_expert", "bf16"), ("", "fp8"), ("per_expert", "fp8")]
+
+
+ ("layout", "source"), _G2_CELLS, ids=[f"{lay or 'fused'}-{src}" for lay, src in _G2_CELLS]
+)
+def test_the_streamed_k2_matches_the_resident_native_model_bit_exactly(
+ tmp_path, k2_checkpoints, monkeypatch, layout, source
+):
+ import torch
+
+ from soup_cli.utils.layer_stream_runtime import canonical_named_parameters
+
+ _refuse_remote_code(monkeypatch)
+ pair = _paired(tmp_path, k2_checkpoints, source, layout)
+ try:
+ with torch.no_grad():
+ got = pair.model(input_ids=pair.ids, labels=pair.ids)
+ want = pair.resident(input_ids=pair.ids, labels=pair.ids)
+ assert torch.equal(got.logits, want.logits), (got.logits - want.logits).abs().max()
+ assert torch.equal(got.loss, want.loss)
+
+ pair.model.zero_grad(set_to_none=True)
+ pair.resident.zero_grad(set_to_none=True)
+ pair.model(input_ids=pair.ids, labels=pair.ids).loss.backward()
+ pair.resident(input_ids=pair.ids, labels=pair.ids).loss.backward()
+
+ def grads(net):
+ return {
+ name: parameter.grad
+ for name, parameter in canonical_named_parameters(net)
+ if "lora_" in name and parameter.grad is not None
+ }
+
+ streamed, resident = grads(pair.model), grads(pair.resident)
+ assert streamed and set(streamed) == set(resident)
+ assert any(
+ ".layers.0." in name and float(gradient.abs().sum()) > 0
+ for name, gradient in streamed.items()
+ )
+ for name, gradient in streamed.items():
+ assert torch.equal(gradient, resident[name]), name
+ finally:
+ pair.runtime.close()
+
+
[email protected]("layout", ["", "per_expert"], ids=["fused", "per_expert"])
+def test_the_stale_rotary_inv_freq_is_never_streamed(tmp_path, k2_checkpoints, layout):
+ """The sharder writes the stale key into each layer file as stored (the docs say so), and
+ the runtime never streams it: no module of either implementation reads it."""
+ from safetensors.torch import load_file
+
+ from soup_cli.utils.layer_shard import layer_paths
+
+ pair = _paired(tmp_path, k2_checkpoints, "bf16", layout)
+ try:
+ for path in layer_paths(pair.shards, pair.index):
+ assert _STALE_INV_FREQ in load_file(path)
+ assert all(
+ not any("rotary_emb" in key for key in keys)
+ for keys in pair.runtime.pool.active_keys_by_layer
+ )
+ assert not any(
+ name.endswith("self_attn.rotary_emb") for name, _ in pair.model.named_modules()
+ )
+ finally:
+ pair.runtime.close()
+
+
+def test_the_streamed_k2_is_built_from_the_native_config(tmp_path, k2_checkpoints):
+ import torch.nn as nn
+ from transformers import DeepseekV3Config
+
+ for source in ("bf16", "fp8"):
+ pair = _paired(tmp_path / source, k2_checkpoints, source, "")
+ try:
+ base = pair.model.get_base_model()
+ assert type(base.config) is DeepseekV3Config
+ assert base.config.model_type == "deepseek_v3"
+ assert getattr(base.config, "auto_map", None) is None
+ assert getattr(base.config, "quantization_config", None) is None
+ attention = base.model.layers[0].inner.self_attn
+ assert type(attention.o_proj.base_layer) is nn.Linear
+ finally:
+ pair.runtime.close()
+
+
+def test_controls_the_yarn_rope_the_router_bias_and_the_fp8_loss_each_move_the_logits(
+ k2_checkpoints,
+):
+ """Without these the parity above could pass on a model insensitive to them."""
+ import torch
+
+ _k2, native = k2_checkpoints["bf16"]
+ _fp8, fp8_ref = k2_checkpoints["fp8"]
+ ids = torch.randint(0, 128, (2, 12), generator=torch.Generator().manual_seed(5))
+ with torch.no_grad():
+ yarn = _resident(native).forward(input_ids=ids).logits
+ default = _resident(native, config=_native_tiny_config(yarn=False)).forward(
+ input_ids=ids
+ ).logits
+ unbiased_model = _resident(native)
+ for layer in unbiased_model.model.layers[1:]:
+ layer.mlp.gate.e_score_correction_bias.zero_()
+ unbiased = unbiased_model.forward(input_ids=ids).logits
+ dequantised = _resident(fp8_ref).forward(input_ids=ids).logits
+ assert not torch.equal(yarn, default)
+ assert not torch.equal(yarn, unbiased)
+ assert not torch.equal(yarn, dequantised)
+
+
+# ==========================================================================
+# G3: the disk pre-flight over the real Kimi-K2-Base header layout
+# ==========================================================================
+#: From the real Base ``model.safetensors.index.json`` (sha256 c1f1d16c...ddcbc):
+#: its key count and ``metadata.total_size``.
+K2_INDEX_TENSORS = 139_644
+K2_INDEX_TOTAL_SIZE = 1_029_173_256_720
+#: The stale per-layer ``rotary_emb.inv_freq`` shape: the one for which the header map's byte
+#: total equals ``total_size`` exactly (benchmarks/gate-kimi-k2-admission.md, G3).
+K2_STALE_INV_FREQ_SHAPE = (56,)
+_ITEMSIZE = {"F8_E4M3": 1, "BF16": 2, "F32": 4}
+
+
+def k2_header_map(raw, *, block=(128, 128)):
+ """name -> (file, safetensors dtype, shape) of the published K2 checkpoint, from its config.
+
+ One decoder layer per file (``model-<N+1>-of-61.safetensors``), the embedding in the first,
+ the final norm and the head in the last, as the real index lays them out. Every linear
+ weight is F8_E4M3 with an F32 ``weight_scale_inv``; norms, embeddings, head, router weight
+ and the stale ``inv_freq`` are BF16; the router bias is F32.
+ """
+ hidden = raw["hidden_size"]
+ heads = raw["num_attention_heads"]
+ q_head = raw["qk_nope_head_dim"] + raw["qk_rope_head_dim"]
+ shared = raw["n_shared_experts"] * raw["moe_intermediate_size"]
+ moe, dense = raw["moe_intermediate_size"], raw["intermediate_size"]
+ n_layers, experts, vocab = raw["num_hidden_layers"], raw["n_routed_experts"], raw["vocab_size"]
+ files = [f"model-{idx + 1}-of-{n_layers}.safetensors" for idx in range(n_layers)]
+ out = {
+ "model.embed_tokens.weight": (files[0], "BF16", (vocab, hidden)),
+ "model.norm.weight": (files[-1], "BF16", (hidden,)),
+ "lm_head.weight": (files[-1], "BF16", (vocab, hidden)),
+ }
+
+ def linear(prefix, rows, cols, file):
+ out[prefix + ".weight"] = (file, "F8_E4M3", (rows, cols))
+ out[prefix + ".weight_scale_inv"] = (
+ file, "F32", (-(-rows // block[0]), -(-cols // block[1]))
+ )
+
+ for idx in range(n_layers):
+ file, layer = files[idx], f"model.layers.{idx}."
+ for name, size in (("input_layernorm", hidden), ("post_attention_layernorm", hidden),
+ ("self_attn.q_a_layernorm", raw["q_lora_rank"]),
+ ("self_attn.kv_a_layernorm", raw["kv_lora_rank"])):
+ out[layer + name + ".weight"] = (file, "BF16", (size,))
+ out[layer + _STALE_INV_FREQ] = (file, "BF16", K2_STALE_INV_FREQ_SHAPE)
+ linear(layer + "self_attn.q_a_proj", raw["q_lora_rank"], hidden, file)
+ linear(layer + "self_attn.q_b_proj", heads * q_head, raw["q_lora_rank"], file)
+ linear(layer + "self_attn.kv_a_proj_with_mqa",
+ raw["kv_lora_rank"] + raw["qk_rope_head_dim"], hidden, file)
+ linear(layer + "self_attn.kv_b_proj",
+ heads * (raw["qk_nope_head_dim"] + raw["v_head_dim"]), raw["kv_lora_rank"], file)
+ linear(layer + "self_attn.o_proj", hidden, heads * raw["v_head_dim"], file)
+ if idx < raw["first_k_dense_replace"]:
+ linear(layer + "mlp.gate_proj", dense, hidden, file)
+ linear(layer + "mlp.up_proj", dense, hidden, file)
+ linear(layer + "mlp.down_proj", hidden, dense, file)
+ continue
+ out[layer + "mlp.gate.weight"] = (file, "BF16", (experts, hidden))
+ out[layer + "mlp.gate.e_score_correction_bias"] = (file, "F32", (experts,))
+ linear(layer + "mlp.shared_experts.gate_proj", shared, hidden, file)
+ linear(layer + "mlp.shared_experts.up_proj", shared, hidden, file)
+ linear(layer + "mlp.shared_experts.down_proj", hidden, shared, file)
+ for expert in range(experts):
+ linear(layer + f"mlp.experts.{expert}.gate_proj", moe, hidden, file)
+ linear(layer + f"mlp.experts.{expert}.up_proj", moe, hidden, file)
+ linear(layer + f"mlp.experts.{expert}.down_proj", hidden, moe, file)
+ return out
+
+
+def serve_header_map(monkeypatch, header_map, root="k2"):
+ """Replace ``read_header`` so it serves ``header_map``; return the source paths."""
+ from soup_cli.utils import safetensors_reader
+ from soup_cli.utils.safetensors_reader import _DTYPES, TensorRange
+
+ by_file = {}
+ for name, (file, dtype, shape) in header_map.items():
+ by_file.setdefault(file, []).append((name, dtype, shape))
+
+ def _read_header(path):
+ entries, cursor = {}, 8
+ for name, dtype, shape in by_file[os.path.basename(path)]:
+ size = math.prod(shape) * _ITEMSIZE[dtype]
+ entries[name] = TensorRange(
+ name=name, dtype=_DTYPES[dtype], shape=tuple(shape), start=cursor,
+ end=cursor + size,
+ )
+ cursor += size
+ return entries
+
+ monkeypatch.setattr(safetensors_reader, "read_header", _read_header)
+ return [os.path.join(root, file) for file in sorted(by_file)]
+
+
+def _nf4_bytes(numel):
+ """NF4 under double quantisation, written independently of Soup's helper."""
+ blocks = -(-numel // 64)
+ return -(-numel // 2) + blocks + 4 * -(-blocks // 256) + 4
+
+
+def k2_cache_oracle(header_map, suffixes, layout):
+ """(per-layer payload, payload outside the layers) of a bf16 NF4 K2 cache, by hand."""
+ layer_re = re.compile(r"model\.layers\.(\d+)\.(.+)$")
+ expert_re = re.compile(r"mlp\.experts\.(\d+)\.(gate|up|down)_proj\.weight$")
+ layers, other = {}, 16 * 4 + 256 * 4 # the two shared NF4 code tables
+ experts = {}
+ for name, (_file, _dtype, shape) in header_map.items():
+ if name.endswith("_scale_inv"):
+ continue
+ numel = math.prod(shape)
+ match = layer_re.match(name)
+ if match is None:
+ other += 2 * numel
+ continue
+ idx, short = int(match.group(1)), match.group(2)
+ expert = expert_re.match(short)
+ if expert is not None:
+ pair = experts.setdefault((idx, int(expert.group(1))), [0, 0])
+ pair[expert.group(2) == "down"] += numel
+ continue
+ if short in suffixes:
+ stored = _nf4_bytes(numel)
+ elif short == "mlp.gate.e_score_correction_bias":
+ stored = 4 * numel
+ else:
+ stored = 2 * numel
+ layers[idx] = layers.get(idx, 0) + stored
+ for (idx, _expert), (gate_up, down) in experts.items():
+ if layout == "per_expert":
+ layers[idx] += _nf4_bytes(gate_up) + _nf4_bytes(down)
+ else:
+ layers[idx] += 2 * (gate_up + down)
+ return tuple(layers[idx] for idx in range(len(layers))), other
+
+
+def test_the_k2_header_map_reproduces_the_real_index_totals():
+ header_map = k2_header_map(K2_BASE_CONFIG)
+ assert len(header_map) == K2_INDEX_TENSORS
+ total = sum(math.prod(shape) * _ITEMSIZE[dtype] for _f, dtype, shape in header_map.values())
+ assert total == K2_INDEX_TOTAL_SIZE
+
+
+#: The published config at small sizes, every other field (and so every module the skeleton
+#: builds and names) as published. build_meta_skeleton on the full config makes each MoE layer's
+#: fused experts with ``torch.empty`` on the CPU before ``init_empty_weights`` moves them to
+#: meta: 22.5 GB in one allocation, which Linux refuses on a 16 GB CI runner (run 39626025729,
+#: ubuntu 3.11 and 3.12: "DefaultCPUAllocator: can't allocate memory").
+_K2_SIZE_TWIN = {
+ "hidden_size": 64, "intermediate_size": 128, "moe_intermediate_size": 32,
+ "num_hidden_layers": 3, "num_attention_heads": 4, "num_key_value_heads": 4,
+ "n_routed_experts": 8, "kv_lora_rank": 16, "q_lora_rank": 24, "qk_nope_head_dim": 16,
+ "qk_rope_head_dim": 8, "v_head_dim": 16,
+}
+#: What the meta probe of the full-size published config reported (gate G3b, 11 suffixes): the
+#: five MLA projections, the dense MLP's three and the shared expert's three.
+K2_QUANT_SUFFIXES = frozenset({
+ "self_attn.q_a_proj.weight", "self_attn.q_b_proj.weight",
+ "self_attn.kv_a_proj_with_mqa.weight", "self_attn.kv_b_proj.weight",
+ "self_attn.o_proj.weight", "mlp.gate_proj.weight", "mlp.up_proj.weight",
+ "mlp.down_proj.weight", "mlp.shared_experts.gate_proj.weight",
+ "mlp.shared_experts.up_proj.weight", "mlp.shared_experts.down_proj.weight",
+})
+
+
[email protected](scope="module")
+def k2_quant_suffixes(tmp_path_factory):
+ """(full-size config folder, the meta probe's NF4 suffixes), the probe run on the size twin:
+ module names do not depend on sizes, and the twin's set must equal the full probe's."""
+ pytest.importorskip("transformers")
+ pytest.importorskip("bitsandbytes")
+ from soup_cli.utils.layer_stream_runtime import build_meta_skeleton, quantised_layer_suffixes
+
+ twin = _base(**_K2_SIZE_TWIN)
+ assert {key for key in K2_BASE_CONFIG if twin[key] != K2_BASE_CONFIG[key]} == set(
+ _K2_SIZE_TWIN
+ )
+ assert twin["num_hidden_layers"] > twin["first_k_dense_replace"] # dense and MoE layers
+ folder = _write_config(tmp_path_factory.mktemp("k2-full"), K2_BASE_CONFIG)
+ probe = build_meta_skeleton(
+ _write_config(tmp_path_factory.mktemp("k2-twin"), twin), dtype="bfloat16", quant="nf4"
+ )
+ suffixes = quantised_layer_suffixes(probe)
+ del probe
+ assert suffixes == K2_QUANT_SUFFIXES
+ return folder, suffixes
+
+
[email protected]("layout", ["per_expert", ""], ids=["per_expert", "fused"])
+def test_the_disk_preflight_sizes_the_real_k2_cache_exactly(
+ monkeypatch, k2_quant_suffixes, layout
+):
+ from soup_cli.utils.kimi_k2 import load_stream_model_config
+ from soup_cli.utils.layer_shard import estimate_shard_cache_bytes
+ from soup_cli.utils.layer_stream import stream_arch_of
+
+ folder, suffixes = k2_quant_suffixes
+ assert "self_attn.kv_a_proj_with_mqa.weight" in suffixes
+ assert "mlp.gate.weight" not in suffixes
+ config = load_stream_model_config(folder)
+ header_map = k2_header_map(K2_BASE_CONFIG)
+ paths = serve_header_map(monkeypatch, header_map)
+ estimate = estimate_shard_cache_bytes(
+ paths, dtype="bfloat16", arch=stream_arch_of(config), quant="nf4",
+ quant_suffixes=suffixes, double_quant=True, expert_layout=layout,
+ num_hidden_layers=config.num_hidden_layers,
+ quantization_config=config.quantization_config,
+ )
+ layer_bytes, other_bytes = k2_cache_oracle(header_map, suffixes, layout)
+ assert estimate.layer_bytes == layer_bytes
+ assert estimate.other_bytes == other_bytes
+
+
+# ==========================================================================
+# the trainer setup
+# ==========================================================================
+def _deepseek_setup_cfg():
+ return SimpleNamespace(
+ model_type="deepseek_v3", hidden_size=4, num_hidden_layers=1, vocab_size=8,
+ intermediate_size=8,
+ )
+
+
+def test_the_setup_loads_the_model_config_through_the_k2_loader(tmp_path, monkeypatch):
+ import soup_cli.utils.kimi_k2 as kimi_k2
+ from tests.test_issue602_qwen4_ple_streaming import _drive_qwen4_streaming_setup
+
+ seen = []
+ model_cfg = _deepseek_setup_cfg()
+
+ def _loader(base, **kwargs):
+ seen.append((base, kwargs))
+ return model_cfg
+
+ monkeypatch.setattr(kimi_k2, "load_stream_model_config", _loader)
+ _drive_qwen4_streaming_setup(tmp_path, monkeypatch, arch="deepseek_v3", model_cfg=model_cfg)
+ assert seen == [("qwen4-test", {"trust_remote_code": False})]
+
+
+def test_trust_remote_code_reaches_the_tokenizer_but_never_the_streamed_config(
+ tmp_path, monkeypatch
+):
+ """Round-2 review: with --trust-remote-code the config loader must still get False, or a K2
+ base would run its repository's configuration code; the tokenizer keeps the user's flag."""
+ import soup_cli.utils.kimi_k2 as kimi_k2
+ from tests.test_issue602_qwen4_ple_streaming import _drive_qwen4_streaming_setup
+
+ seen = []
+ model_cfg = _deepseek_setup_cfg()
+
+ def _loader(base, **kwargs):
+ seen.append(kwargs)
+ return model_cfg
+
+ calls = {}
+ monkeypatch.setattr(kimi_k2, "load_stream_model_config", _loader)
+ _drive_qwen4_streaming_setup(
+ tmp_path, monkeypatch, arch="deepseek_v3", model_cfg=model_cfg, load_calls=calls,
+ trust_remote_code=True,
+ )
+ assert [kwargs["trust_remote_code"] for kwargs in seen] == [False]
+ assert [call["trust_remote_code"] for call in calls["tokenizer"]] == [True]
+ # Second review (MEDIUM 2): the tokenizer is handed the native config, so AutoTokenizer
+ # does not read the config again with the user's flag.
+ assert [call["config"] for call in calls["tokenizer"]] == [model_cfg]
+
+
+def _sentinel_k2_repository(root, sentinel):
+ """A local K2 base: the published config.json (its auto_map onto configuration_deepseek),
+ a ``configuration_deepseek.py`` that writes ``sentinel`` when imported, and a tiny native
+ fast tokenizer (no tokenizer code in the folder)."""
+ from tokenizers import Tokenizer, models, pre_tokenizers
+
+ folder = root / "kimi-k2-local"
+ _write_config(folder, K2_BASE_CONFIG)
+ (folder / "configuration_deepseek.py").write_text(
+ "import pathlib\n"
+ f"pathlib.Path({str(sentinel)!r}).write_text('imported', encoding='utf-8')\n"
+ "from transformers import PretrainedConfig\n\n\n"
+ "class DeepseekV3Config(PretrainedConfig):\n"
+ " model_type = 'kimi_k2'\n",
+ encoding="utf-8",
+ )
+ vocab = {"<unk>": 0, "<s>": 1, "</s>": 2, "hello": 3, "world": 4}
+ tokenizer = Tokenizer(models.WordLevel(vocab, unk_token="<unk>"))
+ tokenizer.pre_tokenizer = pre_tokenizers.Whitespace()
+ tokenizer.save(str(folder / "tokenizer.json"))
+ (folder / "tokenizer_config.json").write_text(json.dumps({
+ "tokenizer_class": "PreTrainedTokenizerFast", "bos_token": "<s>", "eos_token": "</s>",
+ "unk_token": "<unk>",
+ }), encoding="utf-8")
+ return str(folder)
+
+
+def test_the_streamed_tokenizer_load_never_imports_the_repositorys_config_code(
+ tmp_path, monkeypatch
+):
+ """Second review (MEDIUM 2), with the real AutoTokenizer: the setup's own tokenizer call,
+ with --trust-remote-code, must not import the repository's configuration module. Without
+ ``config=`` AutoTokenizer calls AutoConfig with the user's flag first, which follows the
+ auto_map and runs the module (traced on transformers 5.17; this test fails then)."""
+ pytest.importorskip("transformers")
+ pytest.importorskip("tokenizers")
+ import ast
+ import sys
+
+ import transformers
+ import transformers.dynamic_module_utils as dynamic
+
+ from soup_cli.utils.kimi_k2 import load_stream_model_config
+ from soup_cli.utils.run_provenance import base_revision_kwargs
+
+ sentinel = tmp_path / "configuration_deepseek-was-imported"
+ folder = _sentinel_k2_repository(tmp_path, sentinel)
+ # Should the module be imported after all, its copy lands in tmp_path, not the user cache.
+ monkeypatch.setattr(dynamic, "HF_MODULES_CACHE", str(tmp_path / "hf-modules"))
+ monkeypatch.setattr(sys, "path", list(sys.path))
+ source_path = os.path.join(
+ os.path.dirname(__file__), os.pardir, "src", "soup_cli", "trainer", "stream_setup.py"
+ )
+ with open(source_path, encoding="utf-8") as handle:
+ tree = ast.parse(handle.read())
+ calls = [node for node in ast.walk(tree)
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
+ and isinstance(node.func.value, ast.Name) and node.func.value.id == "AutoTokenizer"
+ and node.func.attr == "from_pretrained"]
+ assert len(calls) == 1
+ env = {
+ "cfg": SimpleNamespace(base=folder),
+ "self": SimpleNamespace(_trust_remote_code=True),
+ "AutoTokenizer": transformers.AutoTokenizer,
+ "model_config": load_stream_model_config(folder, trust_remote_code=False),
+ "base_revision_kwargs": base_revision_kwargs,
+ }
+ assert not sentinel.exists() # the config loader ran no repository code
+ expression = compile(ast.Expression(body=calls[0]), "<stream tokenizer>", "eval")
+ # A load that imported the module may then fail on its stand-in class: the sentinel is
+ # checked first, so the failure is this test's own, not the stand-in's AttributeError.
+ try:
+ tokenizer, load_error = eval(expression, env), None
+ except Exception as error: # noqa: BLE001 -- reported below, after the sentinel check
+ tokenizer, load_error = None, error
+ assert not sentinel.exists(), "the tokenizer load imported configuration_deepseek.py"
+ assert load_error is None, repr(load_error)
+ assert tokenizer("hello world")["input_ids"][-2:] == [3, 4]
+
+
+def test_the_setup_refuses_a_guard_failure_before_resolving_any_weight(tmp_path, monkeypatch):
+ import soup_cli.utils.kimi_k2 as kimi_k2
+ from tests.test_issue602_qwen4_ple_streaming import _drive_qwen4_streaming_setup
+
+ def _loader(_base, **_kwargs):
+ raise kimi_k2.UnsupportedKimiK2Error("Kimi K2 ... n_group=8")
+
+ def _resolve(*_args, **_kwargs):
+ raise AssertionError("weights were resolved")
+
+ calls = {}
+ monkeypatch.setattr(kimi_k2, "load_stream_model_config", _loader)
+ with pytest.raises(kimi_k2.UnsupportedKimiK2Error, match="n_group=8"):
+ _drive_qwen4_streaming_setup(
+ tmp_path, monkeypatch, _resolve, arch="deepseek_v3", model_cfg=_deepseek_setup_cfg(),
+ load_calls=calls,
+ )
+ # Before the tokenizer too (review round): a refused K2 is not first sent to install the
+ # tokenizer's requirements.
+ assert "tokenizer" not in calls
+
+
+def test_the_meta_skeleton_loads_its_config_through_the_k2_loader(monkeypatch):
+ import soup_cli.utils.kimi_k2 as kimi_k2
+ from soup_cli.utils.layer_stream_runtime import build_meta_skeleton
+
+ seen = []
+
+ def _loader(model_id, **kwargs):
+ seen.append((model_id, kwargs))
+ raise RuntimeError("stop here")
+
+ monkeypatch.setattr(kimi_k2, "load_stream_model_config", _loader)
+ with pytest.raises(RuntimeError, match="stop here"):
+ build_meta_skeleton("some/base", dtype="float32")
+ assert seen == [("some/base", {"trust_remote_code": False})]
+
+
+def _drive_failed_tokenizer(monkeypatch, failure, hint):
+ """The real setup up to its tokenizer load, which raises ``failure``; returns
+ (the raised exception, what was printed)."""
+ import sys
+ from io import StringIO
+
+ from rich.console import Console
+
+ import soup_cli.trainer.stream_setup as stream_setup
+ import soup_cli.utils.kimi_k2 as kimi_k2
+
+ def _tokenizer(*_args, **_kwargs):
+ raise failure
+
+ monkeypatch.setitem(
+ sys.modules, "transformers",
+ SimpleNamespace(
+ AutoConfig=SimpleNamespace(from_pretrained=None),
+ AutoTokenizer=SimpleNamespace(from_pretrained=_tokenizer),
+ ),
+ )
+ monkeypatch.setitem(
+ sys.modules, "peft", SimpleNamespace(TaskType=SimpleNamespace(CAUSAL_LM="CAUSAL_LM"))
+ )
+ monkeypatch.setattr(kimi_k2, "kimi_k2_tokenizer_hint", hint)
+ # The config loads first (review round), so this drive starts past it.
+ monkeypatch.setattr(
+ kimi_k2, "load_stream_model_config", lambda *_a, **_k: _deepseek_setup_cfg()
+ )
+ buffer = StringIO()
+ monkeypatch.setattr(stream_setup, "console", Console(file=buffer, width=200))
+
+ class _Wrapper(stream_setup.StreamingSetupMixin):
+ device = "cpu"
+ _trust_remote_code = False
+
+ cfg = SimpleNamespace(base="moonshotai/Kimi-K2-Base", task="sft")
+ with pytest.raises(BaseException) as caught:
+ _Wrapper()._setup_streaming_transformers(cfg, SimpleNamespace())
+ return caught.value, buffer.getvalue()
+
+
+ "failure",
+ [ImportError("This modeling file requires the following packages: tiktoken"),
+ ValueError("the tokenizer needs custom code")],
+ ids=["tiktoken-missing", "custom-code"],
+)
+def test_a_failed_tokenizer_load_prints_the_k2_hint_and_reraises(monkeypatch, failure):
+ """A missing tiktoken surfaces as an ImportError from transformers' remote-code loader."""
+ seen = []
+
+ def _hint(base, **kwargs):
+ seen.append((base, kwargs))
+ return "Kimi K2 tokenizer: pip install tiktoken"
+
+ raised, printed = _drive_failed_tokenizer(monkeypatch, failure, _hint)
+ assert raised is failure
+ assert seen == [("moonshotai/Kimi-K2-Base", {})]
+ assert "pip install tiktoken" in printed
+
+
+def test_a_hint_that_fails_never_masks_the_tokenizers_own_error(monkeypatch):
+ failure = ImportError("tiktoken")
+
+ def _broken_hint(*_args, **_kwargs):
+ raise RuntimeError("the hint itself broke")
+
+ raised, printed = _drive_failed_tokenizer(monkeypatch, failure, _broken_hint)
+ assert raised is failure
+ assert "the hint itself broke" not in printed
+
+
+# ==========================================================================
+# the tokenizer hint
+# ==========================================================================
[email protected]("available", [False, True], ids=["tiktoken-missing", "tiktoken-present"])
+def test_the_tokenizer_hint_for_a_k2_base(tmp_path, monkeypatch, available):
+ pytest.importorskip("transformers")
+ import soup_cli.utils.kimi_k2 as kimi_k2
+
+ monkeypatch.setattr(kimi_k2, "_tiktoken_available", lambda: available)
+ hint = kimi_k2.kimi_k2_tokenizer_hint(_write_config(tmp_path / "k2", K2_BASE_CONFIG))
+ assert hint is not None
+ assert "--trust-remote-code" in hint
+ assert "DeepseekV3" in hint
+ assert ("pip install tiktoken" in hint) is (not available)
+
+
+def test_the_tokenizer_hint_stays_quiet_off_k2(tmp_path):
+ pytest.importorskip("transformers")
+ from soup_cli.utils.kimi_k2 import kimi_k2_tokenizer_hint
+
+ llama = {"model_type": "llama", "hidden_size": 8, "num_attention_heads": 2}
+ assert kimi_k2_tokenizer_hint(_write_config(tmp_path / "llama", llama)) is None
+ empty = tmp_path / "empty"
+ empty.mkdir()
+ assert kimi_k2_tokenizer_hint(str(empty)) is None
+
+
+def test_the_kimi_k2_module_is_import_light():
+ """Imported on the trainer path before torch is needed: no torch or transformers at
+ module level (the runtime property is pinned for the CLI in test_cli_startup_is_light)."""
+ import ast
+ import inspect
+
+ import soup_cli.utils.kimi_k2 as kimi_k2
+
+ tree = ast.parse(inspect.getsource(kimi_k2))
+ top = [node for node in tree.body if isinstance(node, (ast.Import, ast.ImportFrom))]
+ names = {
+ (node.module or "") if isinstance(node, ast.ImportFrom) else alias.name
+ for node in top
+ for alias in getattr(node, "names", [])
+ }
+ assert not any(name.split(".")[0] in ("torch", "transformers") for name in names), names