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(streaming): stream frozen experts and preserve autocast in backward (#2008)

Alpamys Makazhan208bfc652758
diff --git a/benchmarks/gate-expert-streaming.md b/benchmarks/gate-expert-streaming.md
new file mode 100644
index 00000000..4b4da1bf
--- /dev/null
+++ b/benchmarks/gate-expert-streaming.md
@@ -0,0 +1,86 @@
+# Gate: expert-granularity streaming is bit-exact against the resident MoE block
+
+Status: **PASS**: first run 2026-10-14 18:36Z (harness at 06fe28f16), re-run at the reviewed tip f5281f96f (2026-10-14T19:04:45Z, after the reader gained its size checks), PASS again. The rule in section 2 was committed in 74f0a08b, before the first run.
+
+## 1. Question
+
+`utils/expert_stream.py` replaces a MoE layer's routed-experts module with
+`StreamedExperts`, which reads one expert at a time from a per-layer experts file
+and fetches it again in the backward. Does it give the same numbers as the
+resident experts module on a REAL MoE checkpoint, not only on the random tiny
+models of `tests/test_expert_stream.py`?
+
+## 2. Decision rule (written before any run)
+
+Model: `allenai/OLMoE-1B-7B-0924` from the local Hugging Face cache (64 experts,
+top-8, 16 layers; already on disk since the #992 coverage probe). Layers 0, 7
+and 15. For each layer:
+
+- the resident control is transformers' `OlmoeExperts` holding that layer's real
+ expert weights, run with `experts_implementation="eager"`;
+- the streamed arm is `StreamedExperts` over an experts file written by
+ `write_expert_shard` from the same tensors;
+- the routing is the layer's real router (`mlp.gate.weight`) applied to the
+ input: softmax then top-8, as `OlmoeTopKRouter` does;
+- the input is 512 tokens of N(0, 1) hidden states (seed 1234), scaled by the
+ layer's `post_attention_layernorm` weight (the norm the MoE block reads), and
+ an N(0, 1) output gradient (seed 4321).
+
+Harness: `benchmarks/harness/expert_stream_gate.py`; raw JSON under
+`benchmarks/results/probe-rtx5070/expert-stream/`.
+
+Cells: (a) CPU fp32, unquantised; (b) CUDA bf16, unquantised; (c) CUDA bf16 with
+every expert matrix NF4-quantised by the sharder, the control holding the
+dequantised weights. Each cell compares, with `torch.equal`: the output, the
+gradient of the input, and the gradient of the routing weights.
+
+- **PASS**: `torch.equal` holds for all 3 layers x 3 cells x 3 tensors (27 checks),
+ and the streamed arm read each routed-to expert exactly twice (forward +
+ backward) and no other expert.
+- **FAIL**: any check false. The record then states the max absolute difference
+ per failing tensor; no tolerance is substituted after the fact.
+
+Not measured here: speed (expert streaming promises none; the #992 probe found a
+step routes to 96.7-100% of experts), a whole-model step, any DeepSeek-V3 weights.
+
+## 3. Box state
+
+- 2026-10-14 18:36:59Z; AC power on; 10.8 GB RAM free before the run.
+- GPU: 0 MiB in use before the run; the harness saw 7,013 of 8,123 MiB free once CUDA was up.
+- Foreign activity: a 32 GB model download writing to D: (this lane's own). No other session ran pytest or used the GPU; the run is a correctness check, so timing noise does not affect the verdict.
+- Software: Python 3.12.10, Windows 11 26200, torch 2.14.0+cu130, transformers 5.17.0, bitsandbytes 0.50.2, safetensors 0.8.0.
+- Harness commit 06fe28f16 for the first run; f5281f96f for the re-run, whose JSON is the one committed (`benchmarks/results/probe-rtx5070/expert-stream/gate.json`). Both runs: 27/27 equal, every fetch count 2 x routed.
+
+## 4. Results
+
+Every one of the 27 checks is `torch.equal`, max abs difference 0.0:
+`output`, `grad_input` and `grad_routing` x cells `cpu-fp32`, `cuda-bf16` and `cuda-bf16-nf4` x layers 0, 7 and 15.
+
+| layer | cell | experts routed to | expert reads | reads == 2 x routed |
+|---|---|---|---|---|
+| 0 | cpu-fp32 | 64 / 64 | 128 | yes |
+| 0 | cuda-bf16 | 64 / 64 | 128 | yes |
+| 0 | cuda-bf16-nf4 | 64 / 64 | 128 | yes |
+| 7 | cpu-fp32 | 64 / 64 | 128 | yes |
+| 7 | cuda-bf16 | 64 / 64 | 128 | yes |
+| 7 | cuda-bf16-nf4 | 64 / 64 | 128 | yes |
+| 15 | cpu-fp32 | 64 / 64 | 128 | yes |
+| 15 | cuda-bf16 | 64 / 64 | 128 | yes |
+| 15 | cuda-bf16-nf4 | 64 / 64 | 128 | yes |
+
+512 tokens routed to all 64 experts in every layer, which matches the #992 coverage
+probe (96.7-100%). The JSON also holds the wall seconds of each arm. They are NOT a
+timing measurement: one run each, first-call warm-up included (layer 0's resident
+CUDA arm, 6.1 s, is CUDA start-up). The rule asks for no speed figure.
+
+## 5. Verdict
+
+**PASS.** On real OLMoE-1B-7B weights, `StreamedExperts` equals the resident
+eager experts block bit for bit:
+
+- forward output, input gradient and routing-weight gradient;
+- fp32 on CPU, bf16 on CUDA, and NF4 against the dequantised control;
+- each routed-to expert read exactly twice per forward + backward, and no other expert read.
+
+Not shown here: whole-model steps on real DeepSeek-V3-family weights (the tiny-model
+parity tests in `tests/test_expert_stream.py` cover the whole-model path), and speed.
diff --git a/benchmarks/harness/expert_stream_gate.py b/benchmarks/harness/expert_stream_gate.py
new file mode 100644
index 00000000..f0da3f6a
--- /dev/null
+++ b/benchmarks/harness/expert_stream_gate.py
@@ -0,0 +1,219 @@
+"""Gate harness: StreamedExperts vs the resident OLMoE experts block, bit for bit.
+
+Rule and verdict: ``benchmarks/gate-expert-streaming.md`` (the rule was
+committed before this ran). Reads ONE decoder layer's experts from a local
+OLMoE checkpoint at a time, so the whole 13.8 GB model is never resident.
+
+ python benchmarks/harness/expert_stream_gate.py \
+ --model-dir <HF snapshot of allenai/OLMoE-1B-7B-0924> \
+ --scratch <empty folder for the experts files> --out result.json
+"""
+
+from __future__ import annotations
+
+import argparse
+import glob
+import json
+import os
+import platform
+import sys
+import time
+
+CELLS = ("cpu-fp32", "cuda-bf16", "cuda-bf16-nf4")
+
+
+def _args(argv=None):
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ parser.add_argument("--model-dir", required=True)
+ parser.add_argument("--scratch", required=True)
+ parser.add_argument("--out", required=True)
+ parser.add_argument("--layers", type=int, nargs="+", default=[0, 7, 15])
+ parser.add_argument("--tokens", type=int, default=512)
+ parser.add_argument("--cells", nargs="+", choices=CELLS, default=list(CELLS))
+ return parser.parse_args(argv)
+
+
+def _layer_tensors(model_dir, layer):
+ """{short key: tensor} for one decoder layer, read file by file."""
+ from safetensors import safe_open
+
+ prefix = f"model.layers.{layer}."
+ found = {}
+ for path in sorted(glob.glob(os.path.join(model_dir, "*.safetensors"))):
+ with safe_open(path, framework="pt") as handle:
+ for key in handle.keys():
+ if key.startswith(prefix) and (".mlp." in key or "post_attention" in key):
+ found[key[len(prefix):]] = handle.get_tensor(key).clone()
+ return found
+
+
+def _experts_module(config, tensors, n_experts, device, dtype):
+ import torch
+ from transformers.models.olmoe.modeling_olmoe import OlmoeExperts
+
+ config._experts_implementation = "eager"
+ module = OlmoeExperts(config)
+ with torch.no_grad():
+ for expert in range(n_experts):
+ gate = tensors[f"mlp.experts.{expert}.gate_proj.weight"]
+ up = tensors[f"mlp.experts.{expert}.up_proj.weight"]
+ module.gate_up_proj[expert].copy_(torch.cat((gate, up)))
+ module.down_proj[expert].copy_(tensors[f"mlp.experts.{expert}.down_proj.weight"])
+ module.requires_grad_(False)
+ return module.to(device=device, dtype=dtype)
+
+
+def _nf4_roundtrip(module):
+ """Replace every expert matrix by its NF4 dequantisation (the NF4 control)."""
+ import torch
+ from bitsandbytes.functional import dequantize_4bit, quantize_4bit
+
+ with torch.no_grad():
+ for param in (module.gate_up_proj, module.down_proj):
+ for expert in range(param.shape[0]):
+ packed, state = quantize_4bit(
+ param[expert].contiguous(), blocksize=64, compress_statistics=True,
+ quant_type="nf4",
+ )
+ param[expert].copy_(dequantize_4bit(packed, quant_state=state))
+
+
+def _run_cell(cell, layer, config, tensors, args):
+ import torch
+
+ from soup_cli.utils.expert_stream import (
+ ExpertFetcher,
+ ExpertShardReader,
+ streamed_experts_class,
+ write_expert_shard,
+ )
+ from soup_cli.utils.layer_shard import NF4_CODE_KEY, NF4_NESTED_CODE_KEY
+
+ device = "cpu" if cell.startswith("cpu") else "cuda"
+ dtype = torch.float32 if cell.endswith("fp32") else torch.bfloat16
+ quantise = cell.endswith("nf4")
+ n_experts = int(config.num_experts)
+ top_k = int(config.num_experts_per_tok)
+ module = _experts_module(config, tensors, n_experts, device, dtype)
+
+ path = os.path.join(args.scratch, f"experts_{layer:03d}_{cell}.safetensors")
+ pairs = (
+ (module.gate_up_proj[e].detach(), module.down_proj[e].detach())
+ for e in range(n_experts)
+ )
+ info = write_expert_shard(path, pairs, quantise=quantise, double_quant=True, device=device)
+ codes = {}
+ if quantise:
+ _nf4_roundtrip(module)
+ codes = {
+ NF4_CODE_KEY: info.codes[0].to(device),
+ NF4_NESTED_CODE_KEY: info.codes[1].to(device),
+ }
+ reader = ExpertShardReader(
+ path, count=info.count, shapes=info.shapes, quant_specs=info.quant_specs,
+ dtype="float32" if dtype == torch.float32 else "bfloat16",
+ )
+ streamed = streamed_experts_class()(
+ reader,
+ ExpertFetcher(device=device, dtype=reader.dtype, codes=codes),
+ module.act_fn,
+ layer,
+ )
+
+ hidden = config.hidden_size
+ generator = torch.Generator().manual_seed(1234)
+ norm = tensors["post_attention_layernorm.weight"].float()
+ states = (torch.randn(args.tokens, hidden, generator=generator) * norm).to(device, dtype)
+ grad_out = torch.randn(args.tokens, hidden, generator=torch.Generator().manual_seed(4321))
+ grad_out = grad_out.to(device, dtype)
+ router = tensors["mlp.gate.weight"].to(device, dtype)
+ with torch.no_grad():
+ probs = torch.softmax(torch.nn.functional.linear(states, router).float(), dim=-1)
+ weights, index = torch.topk(probs, top_k, dim=-1)
+ weights = weights.to(dtype)
+
+ results = {}
+ outputs = {}
+ for arm, net in (("resident", module), ("streamed", streamed)):
+ x = states.clone().requires_grad_(True)
+ w = weights.clone().requires_grad_(True)
+ started = time.perf_counter()
+ out = net(x, index, w)
+ out.backward(grad_out)
+ if device == "cuda":
+ torch.cuda.synchronize()
+ outputs[arm] = (out.detach(), x.grad, w.grad)
+ results[f"{arm}_seconds"] = round(time.perf_counter() - started, 4)
+ hit = int(torch.unique(index).numel())
+ for name, slot in (("output", 0), ("grad_input", 1), ("grad_routing", 2)):
+ want, got = outputs["resident"][slot], outputs["streamed"][slot]
+ equal = bool(torch.equal(got, want))
+ results[name] = {
+ "equal": equal,
+ "max_abs_diff": 0.0 if equal else float((got.float() - want.float()).abs().max()),
+ }
+ results["experts_hit"] = hit
+ results["fetches"] = reader.fetches
+ results["fetches_ok"] = reader.fetches == 2 * hit
+ reader.close()
+ os.remove(path)
+ return results
+
+
+def _box():
+ import torch
+
+ stamp = {
+ "python": platform.python_version(),
+ "platform": platform.platform(),
+ "torch": torch.__version__,
+ "cuda": torch.version.cuda,
+ "time_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
+ }
+ if torch.cuda.is_available():
+ stamp["gpu"] = torch.cuda.get_device_name(0)
+ free, total = torch.cuda.mem_get_info()
+ stamp["gpu_free_mib"] = free // 2**20
+ stamp["gpu_total_mib"] = total // 2**20
+ for name in ("transformers", "bitsandbytes", "safetensors"):
+ try:
+ stamp[name] = __import__(name).__version__
+ except ImportError:
+ stamp[name] = None
+ return stamp
+
+
+def main(argv=None):
+ import torch
+ from transformers import OlmoeConfig
+
+ args = _args(argv)
+ os.makedirs(args.scratch, exist_ok=True)
+ if any(cell.startswith("cuda") for cell in args.cells) and not torch.cuda.is_available():
+ print("SKIP: a CUDA cell was asked for and CUDA is not available")
+ return 0
+ config = OlmoeConfig.from_pretrained(args.model_dir)
+ report = {"box": _box(), "args": vars(args), "layers": {}}
+ passed = True
+ for layer in args.layers:
+ tensors = _layer_tensors(args.model_dir, layer)
+ report["layers"][str(layer)] = {}
+ for cell in args.cells:
+ cell_result = _run_cell(cell, layer, config, tensors, args)
+ report["layers"][str(layer)][cell] = cell_result
+ passed &= all(
+ cell_result[name]["equal"] for name in ("output", "grad_input", "grad_routing")
+ ) and cell_result["fetches_ok"]
+ print(layer, cell, json.dumps(cell_result))
+ with open(args.out, "w", encoding="utf-8") as handle:
+ json.dump(report, handle, indent=2)
+ del tensors
+ report["verdict"] = "PASS" if passed else "FAIL"
+ with open(args.out, "w", encoding="utf-8") as handle:
+ json.dump(report, handle, indent=2)
+ print(report["verdict"])
+ return 0 if passed else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/benchmarks/harness/moe_stream_step.py b/benchmarks/harness/moe_stream_step.py
new file mode 100644
index 00000000..c650bab9
--- /dev/null
+++ b/benchmarks/harness/moe_stream_step.py
@@ -0,0 +1,218 @@
+"""One measured LoRA training step on an expert-streamed DeepSeek-V3-family store.
+
+Loads a shard cache built with ``expert_layout="per_expert"`` (by the sharder
+or by ``synth_moe_store.py``), installs layer + expert streaming, and runs
+``--steps`` optimizer steps of LoRA on the attention projections: forward,
+backward, AdamW. Writes step seconds, tokens per second, peak VRAM, the
+process's peak host memory, and the bytes the expert readers read. On a
+synthetic store every number is "random weights, shape only".
+
+ python benchmarks/harness/moe_stream_step.py --store D:/soup-bench/moe-k2-synth \
+ --seq 512 --steps 1 --out step.json
+
+With ``--weights`` a real checkpoint is sharded into ``--store`` first (NF4 on
+CUDA, the way ``soup train`` does it: native transformers class, the config's
+layer count, ``--expert-layout``), unless ``--store`` already holds an index.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import sys
+import time
+
+_ATTENTION = ["q_proj", "q_a_proj", "q_b_proj", "kv_a_proj_with_mqa", "kv_b_proj", "o_proj"]
+
+
+def _args(argv=None):
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ parser.add_argument("--store", required=True, help="shard cache dir")
+ parser.add_argument("--weights", default=None, help="checkpoint to shard into --store")
+ parser.add_argument(
+ "--model", default=None, help="dir with config.json (default: --weights, else --store)"
+ )
+ parser.add_argument("--expert-layout", choices=("fused", "per_expert"), default="per_expert")
+ parser.add_argument("--out", required=True)
+ parser.add_argument("--seq", type=int, default=512)
+ parser.add_argument("--batch", type=int, default=1)
+ parser.add_argument("--steps", type=int, default=1)
+ parser.add_argument("--lora-r", type=int, default=8)
+ parser.add_argument("--buffers", type=int, default=2)
+ parser.add_argument("--tier", choices=("ram", "disk"), default="ram")
+ parser.add_argument("--no-pin", action="store_true")
+ parser.add_argument("--seed", type=int, default=3)
+ parser.add_argument("--label", default="random weights, shape only")
+ parser.add_argument(
+ "--route", choices=("model", "uniform"), default="model",
+ help="uniform: every MoE router sends token t to experts 8t..8t+k-1 (mod E), so a "
+ "step routes to every expert the way a trained model nearly does (probe #992); "
+ "random weights otherwise collapse routing onto a few experts",
+ )
+ return parser.parse_args(argv)
+
+
+def _shard(args):
+ """Shard ``--weights`` into ``--store`` the way the streamed trainer does."""
+ from transformers import AutoConfig
+
+ from soup_cli.utils.layer_shard import shard_checkpoint
+ from soup_cli.utils.layer_stream_runtime import build_meta_skeleton, quantised_layer_suffixes
+
+ config = AutoConfig.from_pretrained(args.weights, trust_remote_code=False)
+ probe = build_meta_skeleton(args.weights, dtype="bfloat16", quant="nf4")
+ suffixes = quantised_layer_suffixes(probe)
+ del probe
+ started = time.perf_counter()
+ shard_checkpoint(
+ args.weights, args.store, dtype="bfloat16", arch="deepseek_v3", quant="nf4",
+ quant_suffixes=suffixes, double_quant=True, quant_device="cuda",
+ num_hidden_layers=int(config.num_hidden_layers),
+ expert_layout="" if args.expert_layout == "fused" else "per_expert",
+ notify=print,
+ )
+ return round(time.perf_counter() - started, 1)
+
+
+def _uniform_routing(model):
+ """Replace every DeepSeek-V3 router's choice with a fixed round robin.
+
+ Returns the number of routers replaced. The router's own weight still
+ streams (it is in the layer file) but is not used; the expert MLPs, the
+ shared expert and the attention are untouched.
+ """
+ import types
+
+ import torch
+
+ replaced = 0
+ for module in model.modules():
+ if type(module).__name__ != "DeepseekV3TopkRouter":
+ continue
+ top_k, experts = int(module.top_k), int(module.num_experts)
+
+ def forward(self, hidden_states, top_k=top_k, experts=experts):
+ rows = hidden_states.reshape(-1, hidden_states.shape[-1]).shape[0]
+ device = hidden_states.device
+ index = (
+ torch.arange(rows, device=device)[:, None] * top_k
+ + torch.arange(top_k, device=device)[None, :]
+ ) % experts
+ weights = torch.full((rows, top_k), 1.0 / top_k, device=device)
+ logits = torch.zeros(rows, experts, device=device)
+ return logits, weights, index
+
+ module.forward = types.MethodType(forward, module)
+ replaced += 1
+ return replaced
+
+
+def _peak_host_bytes():
+ try:
+ import psutil
+
+ info = psutil.Process().memory_info()
+ return int(getattr(info, "peak_wset", 0) or getattr(info, "rss", 0))
+ except ImportError:
+ return None
+
+
+def main(argv=None):
+ import torch
+ from peft import LoraConfig, TaskType
+
+ from soup_cli.utils.layer_shard import read_shard_index, shard_cache_disk_bytes
+ from soup_cli.utils.layer_stream_runtime import build_streamed_model
+
+ args = _args(argv)
+ if not torch.cuda.is_available():
+ print("SKIP: needs CUDA")
+ return 0
+ model_dir = args.model or args.weights or args.store
+ report = {"label": args.label, "args": vars(args), "steps": []}
+ if args.weights and not os.path.exists(os.path.join(args.store, "index.json")):
+ report["shard_seconds"] = _shard(args)
+ index = read_shard_index(args.store)
+ report["store_bytes"] = shard_cache_disk_bytes(args.store, index)
+ # What the store holds, not what was asked for: an existing store is reused.
+ report["store_expert_layout"] = index.expert_layout or "fused"
+ report["store_quant"] = index.quant
+ report["store_double_quant"] = bool(index.double_quant)
+ lora = LoraConfig(
+ r=args.lora_r, lora_alpha=2 * args.lora_r, lora_dropout=0.0, bias="none",
+ target_modules=_ATTENTION, task_type=TaskType.CAUSAL_LM,
+ )
+ started = time.perf_counter()
+ model, runtime = build_streamed_model(
+ model_id=model_dir, shard_dir=args.store, index=index, lora_config=lora,
+ device="cuda", dtype=index.dtype, buffers=args.buffers, pin=not args.no_pin,
+ tier=args.tier, seed=args.seed, quant=index.quant,
+ double_quant=bool(index.double_quant),
+ )
+ report["build_seconds"] = round(time.perf_counter() - started, 2)
+ model.train()
+ if args.route == "uniform":
+ report["routers_overridden"] = _uniform_routing(model)
+ report["label"] += "; routing forced uniform (token t -> experts kt..kt+k-1 mod E)"
+ trainable = [param for param in model.parameters() if param.requires_grad]
+ optimizer = torch.optim.AdamW(trainable, lr=1e-4)
+ report["trainable_params"] = sum(param.numel() for param in trainable)
+ vocab = model.config.vocab_size
+ generator = torch.Generator().manual_seed(17)
+ torch.cuda.reset_peak_memory_stats()
+ try:
+ for step in range(args.steps):
+ ids = torch.randint(0, vocab, (args.batch, args.seq), generator=generator).cuda()
+ before = runtime.stats()
+ torch.cuda.synchronize()
+ torch.cuda.reset_peak_memory_stats()
+ tick = time.perf_counter()
+ loss = model(input_ids=ids, labels=ids).loss
+ loss.backward()
+ torch.cuda.synchronize()
+ seconds_to_grads = time.perf_counter() - tick
+ # Checked here, before the optimizer consumes and zeroes the grads.
+ grads = [param.grad for param in trainable]
+ grads_present = sum(grad is not None for grad in grads)
+ grads_finite = grads_present > 0 and all(
+ bool(torch.isfinite(grad).all()) for grad in grads if grad is not None
+ )
+ tick_opt = time.perf_counter()
+ optimizer.step()
+ optimizer.zero_grad(set_to_none=True)
+ torch.cuda.synchronize()
+ seconds = seconds_to_grads + (time.perf_counter() - tick_opt)
+ after = runtime.stats()
+ report["steps"].append(
+ {
+ "step": step,
+ "seconds": round(seconds, 2),
+ "tokens_per_second": round(args.batch * args.seq / seconds, 3),
+ "loss": float(loss.detach()),
+ "loss_finite": bool(torch.isfinite(loss.detach())),
+ "grads_finite": grads_finite,
+ "grads_present": grads_present,
+ "expert_fetches": after["expert_fetches"] - before["expert_fetches"],
+ "expert_bytes_read": after["expert_bytes_read"] - before["expert_bytes_read"],
+ "layer_loads": after["layer_loads"] - before["layer_loads"],
+ # This step's peaks (reset at its start); the host figure is the
+ # process's peak working set so far (Windows ``peak_wset``).
+ "peak_vram_mib": torch.cuda.max_memory_allocated() // 2**20,
+ "peak_reserved_mib": torch.cuda.max_memory_reserved() // 2**20,
+ "peak_host_bytes_so_far": _peak_host_bytes(),
+ }
+ )
+ print(json.dumps(report["steps"][-1]))
+ with open(args.out, "w", encoding="utf-8") as handle:
+ json.dump(report, handle, indent=2)
+ finally:
+ runtime.close()
+ report["stats"] = runtime.stats()
+ with open(args.out, "w", encoding="utf-8") as handle:
+ json.dump(report, handle, indent=2)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/benchmarks/harness/synth_moe_store.py b/benchmarks/harness/synth_moe_store.py
new file mode 100644
index 00000000..85ea06d4
--- /dev/null
+++ b/benchmarks/harness/synth_moe_store.py
@@ -0,0 +1,384 @@
+"""Write a SYNTHETIC DeepSeek-V3-family shard cache directly: random weights, shape only.
+
+A Kimi K2-shaped checkpoint is ~1 T parameters: ~2 TB at bf16, more than the
+disk that would hold its ~0.58 TB NF4 shard cache. So this skips the bf16
+source and writes the cache ``layer_shard.shard_checkpoint`` would have made
+with ``quant="nf4", expert_layout="per_expert"``: an ``index.json`` the runtime
+accepts, NF4 decoder-layer files, one experts file per MoE layer, the extras
+and the untied embedding / head. The NF4 layout is the sharder's default,
+double quantisation (uint8 absmax codes, an fp32 nested absmax per 256 blocks, a
+scalar offset). Every packed NF4 byte comes from one seeded random pool reused
+at rotating offsets; every block's absmax decodes to ``1/sqrt(fan_in)``. Numbers
+measured on it are labelled "random weights, shape only" wherever they appear.
+
+ python benchmarks/harness/synth_moe_store.py --out D:/soup-bench/moe-k2-synth --shape k2
+ python benchmarks/harness/synth_moe_store.py --out <tmp> --shape tiny # the test shape
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import math
+import os
+import struct
+import sys
+import time
+
+SHAPES = {
+ # moonshotai/Kimi-K2-Instruct config.json, model_type rewritten to deepseek_v3
+ # (transformers registers no kimi_k2) and its FP8 quantization_config dropped.
+ "k2": dict(
+ hidden_size=7168, intermediate_size=18432, moe_intermediate_size=2048,
+ num_hidden_layers=61, first_k_dense_replace=1, num_attention_heads=64,
+ num_key_value_heads=64, n_routed_experts=384, n_shared_experts=1,
+ num_experts_per_tok=8, n_group=1, topk_group=1, kv_lora_rank=512,
+ q_lora_rank=1536, qk_nope_head_dim=128, qk_rope_head_dim=64, v_head_dim=128,
+ vocab_size=163840, routed_scaling_factor=2.827, norm_topk_prob=True,
+ rope_theta=50000.0, max_position_embeddings=131072,
+ rope_scaling={
+ "type": "yarn", "factor": 32.0, "beta_fast": 1.0, "beta_slow": 1.0,
+ "mscale": 1.0, "mscale_all_dim": 1.0, "original_max_position_embeddings": 4096,
+ },
+ ),
+ # Small enough for a unit test; same structure.
+ "tiny": dict(
+ 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_routed_experts=8, n_shared_experts=1,
+ num_experts_per_tok=2, n_group=1, topk_group=1, kv_lora_rank=16,
+ q_lora_rank=24, qk_nope_head_dim=16, qk_rope_head_dim=8, v_head_dim=16,
+ vocab_size=128, routed_scaling_factor=1.0, norm_topk_prob=True,
+ rope_theta=10000.0, max_position_embeddings=128,
+ ),
+}
+
+_POOL_BYTES = 2**28
+
+
+def config_dict(shape: dict) -> dict:
+ out = {
+ "architectures": ["DeepseekV3ForCausalLM"],
+ "model_type": "deepseek_v3",
+ "hidden_act": "silu",
+ "attention_bias": False,
+ "rms_norm_eps": 1e-6,
+ "tie_word_embeddings": False,
+ "num_nextn_predict_layers": 0,
+ "torch_dtype": "bfloat16",
+ "use_cache": False,
+ }
+ out.update(shape)
+ return out
+
+
+def _linears(shape: dict, layer: int) -> dict:
+ """short key -> (out_features, in_features) of every nn.Linear in one layer."""
+ hidden = shape["hidden_size"]
+ heads = shape["num_attention_heads"]
+ qk_head = shape["qk_nope_head_dim"] + shape["qk_rope_head_dim"]
+ out = {
+ "self_attn.q_a_proj.weight": (shape["q_lora_rank"], hidden),
+ "self_attn.q_b_proj.weight": (heads * qk_head, shape["q_lora_rank"]),
+ "self_attn.kv_a_proj_with_mqa.weight": (
+ shape["kv_lora_rank"] + shape["qk_rope_head_dim"], hidden,
+ ),
+ "self_attn.kv_b_proj.weight": (
+ heads * (shape["qk_nope_head_dim"] + shape["v_head_dim"]), shape["kv_lora_rank"],
+ ),
+ "self_attn.o_proj.weight": (hidden, heads * shape["v_head_dim"]),
+ }
+ if layer < shape["first_k_dense_replace"]:
+ inter = shape["intermediate_size"]
+ prefix = "mlp."
+ else:
+ inter = shape["moe_intermediate_size"] * shape["n_shared_experts"]
+ prefix = "mlp.shared_experts."
+ out[prefix + "gate_proj.weight"] = (inter, hidden)
+ out[prefix + "up_proj.weight"] = (inter, hidden)
+ out[prefix + "down_proj.weight"] = (hidden, inter)
+ return out
+
+
+def _dense(shape: dict, layer: int) -> dict:
+ """short key -> (shape, safetensors dtype, fill) of the unquantised layer tensors."""
+ hidden = shape["hidden_size"]
+ out = {
+ "input_layernorm.weight": ((hidden,), "BF16", 1.0),
+ "post_attention_layernorm.weight": ((hidden,), "BF16", 1.0),
+ "self_attn.q_a_layernorm.weight": ((shape["q_lora_rank"],), "BF16", 1.0),
+ "self_attn.kv_a_layernorm.weight": ((shape["kv_lora_rank"],), "BF16", 1.0),
+ }
+ if layer >= shape["first_k_dense_replace"]:
+ experts = shape["n_routed_experts"]
+ out["mlp.gate.weight"] = ((experts, hidden), "BF16", None)
+ out["mlp.gate.e_score_correction_bias"] = ((experts,), "F32", 0.0)
+ return out
+
+
+class _Pool:
+ """Seeded random bytes, handed out at rotating offsets."""
+
+ def __init__(self, seed: int, size: int = _POOL_BYTES):
+ import numpy as np
+
+ self.data = np.random.default_rng(seed).integers(0, 256, size, dtype=np.uint8)
+ self.offset = 0
+
+ def take(self, nbytes: int):
+ import numpy as np
+
+ parts = []
+ while nbytes:
+ if self.offset >= self.data.size:
+ self.offset = 0
+ chunk = min(nbytes, self.data.size - self.offset)
+ parts.append(self.data[self.offset : self.offset + chunk])
+ self.offset += chunk + 4099 # rotate: consecutive takes do not repeat
+ nbytes -= chunk
+ return parts[0] if len(parts) == 1 else np.concatenate(parts)
+
+
+_NESTED_BLOCK = 256
+
+
+def _nf4_entries(name: str, out_features: int, in_features: int):
+ n = out_features * in_features
+ if n % 64:
+ raise ValueError(f"{name}: {n} weights is not a multiple of the NF4 block (64)")
+ blocks = n // 64
+ nested = -(-blocks // _NESTED_BLOCK)
+ return [
+ (name, "U8", (n // 2, 1), n // 2),
+ (name + "::absmax", "U8", (blocks,), blocks),
+ (name + "::nested_absmax", "F32", (nested,), nested * 4),
+ (name + "::nested_offset", "F32", (), 4),
+ ]
+
+
+def _nf4_payload(pool: _Pool, out_features: int, in_features: int, code_index: int):
+ """Packed bytes, then the double-quantised absmax: every block's uint8 code
+ points at the nested table's 1.0 entry, so absmax = nested_absmax = 1/sqrt(fan_in)."""
+ import numpy as np
+
+ n = out_features * in_features
+ blocks = n // 64
+ nested = -(-blocks // _NESTED_BLOCK)
+ return [
+ pool.take(n // 2),
+ np.full(blocks, code_index, dtype=np.uint8),
+ np.full(nested, 1.0 / math.sqrt(in_features), dtype=np.float32),
+ np.zeros((), dtype=np.float32),
+ ]
+
+
+def _write_streaming(path: str, entries, payloads) -> None:
+ """A safetensors file written tensor by tensor; never more than one in RAM.
+
+ ``entries``: (name, dtype, shape, nbytes) in file order; ``payloads``
+ yields one numpy array per entry, in the same order.
+ """
+ header = {}
+ offset = 0
+ for name, dtype, shape, nbytes in entries:
+ header[name] = {
+ "dtype": dtype, "shape": list(shape), "data_offsets": [offset, offset + nbytes]
+ }
+ offset += nbytes
+ raw = json.dumps(header, separators=(",", ":")).encode("utf-8")
+ raw += b" " * ((8 - len(raw) % 8) % 8)
+ tmp = path + ".tmp"
+ with open(tmp, "wb") as handle:
+ handle.write(struct.pack("<Q", len(raw)))
+ handle.write(raw)
+ written = 0
+ for (name, _dtype, _shape, nbytes), payload in zip(entries, payloads):
+ data = memoryview(payload).cast("B")
+ if len(data) != nbytes:
+ raise ValueError(f"{name}: payload is {len(data)} bytes, header says {nbytes}")
+ handle.write(data)
+ written += nbytes
+ if written != offset:
+ raise ValueError(f"{path}: wrote {written} data bytes, header says {offset}")
+ os.replace(tmp, path)
+
+
+def _nf4_code():
+ """bitsandbytes' NF4 code table, as the sharder stores it in the extras."""
+ import torch
+ from bitsandbytes.functional import get_4bit_type
+
+ return get_4bit_type("nf4", device="cpu").to(torch.float32)
+
+
+def _nested_code():
+ """The table double quantisation codes absmax with (``quantize_blockwise``)."""
+ import torch
+ from bitsandbytes.functional import create_dynamic_map
+
+ return create_dynamic_map(signed=True).to(torch.float32)
+
+
+def _large_matrix(vocab: int, hidden: int, generator):
+ """A bf16 [vocab, hidden] N(0, 0.02) matrix built in row slices, so at most
+ one fp32 slice exists at once (the K2 vocabulary is 163840 x 7168)."""
+ import torch
+
+ out = torch.empty(vocab, hidden, dtype=torch.bfloat16)
+ for start in range(0, vocab, 8192):
+ stop = min(vocab, start + 8192)
+ out[start:stop] = torch.randn(stop - start, hidden, generator=generator) * 0.02
+ return out
+
+
+def write_store(out: str, shape_name: str, *, seed: int = 1234, log=print) -> dict:
+ import numpy as np
+ import torch
+ from safetensors.torch import save_file
+
+ from soup_cli import __version__
+ from soup_cli.utils.expert_stream import EXPERT_LAYOUT_PER_EXPERT, expert_shard_name
+ from soup_cli.utils.layer_shard import (
+ _SHARD_FORMAT_VERSION,
+ NF4_CODE_KEY,
+ NF4_NESTED_CODE_KEY,
+ NF4WeightSpec,
+ ShardIndex,
+ _atomic_write_index,
+ extras_shard_path,
+ large_shard_path,
+ layer_shard_path,
+ )
+
+ shape = SHAPES[shape_name]
+ os.makedirs(out, exist_ok=True)
+ with open(os.path.join(out, "config.json"), "w", encoding="utf-8") as handle:
+ json.dump(config_dict(shape), handle, indent=2)
+ pool = _Pool(seed)
+ nested_code = _nested_code()
+ one = int(nested_code.argmax())
+ if float(nested_code[one]) != 1.0:
+ raise ValueError("the nested code table has no exact 1.0 entry")
+ hidden = shape["hidden_size"]
+ vocab = shape["vocab_size"]
+ n_layers = shape["num_hidden_layers"]
+ experts = shape["n_routed_experts"]
+ inter = shape["moe_intermediate_size"]
+
+ def spec(out_features, in_features):
+ return NF4WeightSpec(
+ shape=(out_features, in_features), dtype="bfloat16", blocksize=64,
+ quant_type="nf4", nested=True, nested_blocksize=_NESTED_BLOCK,
+ )
+
+ quant_specs = {}
+ layer_keys = set()
+ total = 0
+ started = time.perf_counter()
+ written_bytes = 0
+ for layer in range(n_layers):
+ entries, payloads = [], []
+ for name, (o, i) in _linears(shape, layer).items():
+ quant_specs[name] = spec(o, i)
+ entries += _nf4_entries(name, o, i)
+ payloads += _nf4_payload(pool, o, i, one)
+ total += o * i
+ for name, (dims, dtype, fill) in _dense(shape, layer).items():
+ count = math.prod(dims)
+ if dtype == "F32":
+ payload = np.full(count, fill, dtype=np.float32)
+ elif fill is None:
+ payload = (torch.randn(count, generator=torch.Generator().manual_seed(layer))
+ * 0.02).to(torch.bfloat16).view(torch.int16).numpy()
+ else:
+ payload = torch.full((count,), fill, dtype=torch.bfloat16).view(torch.int16).numpy()
+ entries.append((name, dtype, dims, payload.nbytes))
+ payloads.append(payload)
+ total += count
+ layer_keys.update(entry[0] for entry in entries)
+ _write_streaming(layer_shard_path(out, layer), entries, payloads)
+ written_bytes += sum(entry[3] for entry in entries)
+ if layer >= shape["first_k_dense_replace"]:
+ expert_entries = []
+ for expert in range(experts):
+ expert_entries += _nf4_entries(f"{expert}.gate_up", 2 * inter, hidden)
+ expert_entries += _nf4_entries(f"{expert}.down", hidden, inter)
+
+ def expert_payloads():
+ for _ in range(experts):
+ yield from _nf4_payload(pool, 2 * inter, hidden, one)
+ yield from _nf4_payload(pool, hidden, inter, one)
+
+ _write_streaming(os.path.join(out, expert_shard_name(layer)), expert_entries,
+ expert_payloads())
+ written_bytes += sum(entry[3] for entry in expert_entries)
+ total += experts * 3 * inter * hidden
+ log(f"layer {layer + 1}/{n_layers}: {written_bytes / 1e9:.1f} GB written, "
+ f"{time.perf_counter() - started:.0f} s")
+
+ generator = torch.Generator().manual_seed(seed)
+ for key in ("model.embed_tokens.weight", "lm_head.weight"):
+ matrix = _large_matrix(vocab, hidden, generator)
+ save_file({key: matrix}, large_shard_path(out, key))
+ written_bytes += matrix.numel() * 2
+ total += matrix.numel()
+ del matrix
+ extras = {
+ "model.norm.weight": torch.ones(hidden, dtype=torch.bfloat16),
+ NF4_CODE_KEY: _nf4_code(),
+ NF4_NESTED_CODE_KEY: nested_code,
+ }
+ save_file(extras, extras_shard_path(out))
+ total += hidden
+
+ moe_layers = tuple(range(shape["first_k_dense_replace"], n_layers))
+ index = ShardIndex(
+ n_layers=n_layers,
+ layer_keys=tuple(sorted(layer_keys)),
+ extra_keys=tuple(sorted(extras)),
+ dtype="bfloat16",
+ total_params=total,
+ arch="deepseek_v3",
+ soup_version=__version__,
+ large_keys=("lm_head.weight", "model.embed_tokens.weight"),
+ format_version=_SHARD_FORMAT_VERSION,
+ source_fingerprint=f"synthetic-{shape_name}-seed{seed}",
+ source_files=(),
+ quant="nf4",
+ double_quant=True,
+ quant_device="cuda",
+ quant_specs=quant_specs,
+ expert_layout=EXPERT_LAYOUT_PER_EXPERT,
+ expert_layers=moe_layers,
+ expert_count=experts,
+ expert_shapes={"gate_up": (2 * inter, hidden), "down": (hidden, inter)},
+ expert_quant_specs={"gate_up": spec(2 * inter, hidden), "down": spec(hidden, inter)},
+ )
+ _atomic_write_index(index, out)
+ summary = {
+ "shape": shape_name,
+ "params": total,
+ "bytes_written": written_bytes,
+ "seconds": round(time.perf_counter() - started, 1),
+ "label": "random weights, shape only",
+ }
+ with open(os.path.join(out, "synth.json"), "w", encoding="utf-8") as handle:
+ json.dump(summary, handle, indent=2)
+ return summary
+
+
+def main(argv=None):
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ parser.add_argument("--out", required=True)
+ parser.add_argument("--shape", choices=sorted(SHAPES), default="k2")
+ parser.add_argument("--seed", type=int, default=1234)
+ args = parser.parse_args(argv)
+ if os.path.exists(os.path.join(args.out, "index.json")):
+ print(f"refusing: {args.out} already holds a shard cache")
+ return 2
+ print(json.dumps(write_store(args.out, args.shape, seed=args.seed), indent=2))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/benchmarks/note-k2-layer-on-24-32gb-cards.md b/benchmarks/note-k2-layer-on-24-32gb-cards.md
new file mode 100644
index 00000000..798fb3b6
--- /dev/null
+++ b/benchmarks/note-k2-layer-on-24-32gb-cards.md
@@ -0,0 +1,49 @@
+# Note: can a 24-32 GB card stream a whole Kimi K2 layer without expert streaming?
+
+Arithmetic only: nothing here was built or measured. Shapes from
+`moonshotai/Kimi-K2-Instruct`'s `config.json` (hidden 7168, 384 routed experts of
+`moe_intermediate_size` 2048, one shared expert, MLA attention, 61 layers).
+
+## One MoE layer
+
+| part | parameters | bf16 | NF4 (+ fp32 absmax per 64) |
+|---|---|---|---|
+| routed experts, 384 x 3 x 7168 x 2048 | 16.91 B | 33.8 GB | 8.5 GB + 1.06 GB = 9.5 GB |
+| attention (q_a, q_b, kv_a, kv_b, o) + shared expert + router | ~0.15 B | 0.29 GB | ~0.09 GB |
+
+## Layer streaming as it is today (`expert_layout` fused)
+
+The routed experts are 3-D parameters, not `nn.Linear` modules, so layer
+streaming's NF4 path does not touch them: a K2 layer streams at bf16, **33.8 GB**,
+and the pool holds at least two layer buffers (`stream_buffers` >= 2). That is
+68 GB of buffers: **no on 24 GB, no on 32 GB**, and no on an 80 GB card either
+once activations, the vocabulary slot (163840 x 7168 bf16 = 2.35 GB) and the
+transformers expert kernel's own working set are added.
+
+## If the fused experts were stored NF4 (not built)
+
+Two NF4 layer buffers are 19 GB, plus the vocabulary slot (2.35 GB), activations
+and LoRA state (a few GB at seq 512). The compute still needs bf16 expert
+weights: dequantising the whole layer at once is the 33.8 GB above again, so it
+would have to dequantise one expert at a time, which is the compute half of
+expert streaming anyway.
+
+- 32 GB card: plausible, ~23-25 GB peak (estimate).
+- 24 GB card: at the edge; one buffer less would be needed, and the current
+ floor is two.
+- Host side: the disk tier's staging is `stream_read_ahead` layers, 2 x 9.5 GB
+ page-locked, on top of the resident extras.
+
+## What expert streaming changes
+
+The streaming unit becomes one expert (24.8 MB at NF4); the pool holds the dense
+part of a layer (~0.1 GB) and one expert at a time. The VRAM bound no longer
+depends on the expert count. The bytes read per step do not shrink: a training
+step routes to ~97-100% of the experts (`probe-moe-expert-coverage.md`), and the
+backward reads them again. L2L (Pudipeddi et al. 2020) is the published method
+for amortising those reads across micro-batches; it is not used here.
+
+**Answer:** without expert streaming, no card from 24 to 32 GB holds a K2 layer
+as layer streaming stores it today (bf16 experts, 33.8 GB). With NF4 experts and
+per-expert dequantisation, a 32 GB card plausibly could; a 24 GB card would be at
+the edge. Both figures are estimates.
diff --git a/benchmarks/probe-rtx5070-giant-moe-step.md b/benchmarks/probe-rtx5070-giant-moe-step.md
new file mode 100644
index 00000000..a93b6717
--- /dev/null
+++ b/benchmarks/probe-rtx5070-giant-moe-step.md
@@ -0,0 +1,137 @@
+# Probe: one LoRA training step on a Kimi K2-shaped store, RTX 5070 Laptop 8 GB
+
+Status: **COMPLETES**, both runs. Run 1 (the model's own routing) is real but not a K2 step
+time (section 4.1). Run 2 (forced uniform routing, addendum rule in section 2.1 committed in
+1fe403a18 before it ran) read every expert: **one full LoRA step of a 1.026 T-parameter
+K2-shaped model took 868 s cold and 1,109 s next on the 8 GB laptop.** Random weights, shape only.
+
+**Every number in this record is "random weights, shape only".** The store is
+synthetic: the parameter count and tensor shapes of `moonshotai/Kimi-K2-Instruct`
+(~1.03 T parameters, 61 layers, 384 routed experts of 3 x 7168 x 2048 per MoE
+layer), random NF4 bytes. It says nothing about the quality, convergence or
+throughput of training the real model. Prior art for streaming layers through a
+small device memory is L2L (Pudipeddi et al. 2020, "Training Large Neural
+Networks with Constant Memory using a New Execution Algorithm"); this record
+does not use L2L's layer-major micro-batching.
+
+## 1. Question
+
+With layer streaming plus expert-granularity streaming (`expert_layout="per_expert"`,
+`benchmarks/gate-expert-streaming.md`), does ONE full LoRA training step (forward,
+backward, AdamW on attention adapters) of a K2-shaped model complete on this
+laptop, and what does it cost in time, VRAM, host RAM and bytes read?
+
+## 2. Decision rule (written before any run)
+
+Store: `benchmarks/harness/synth_moe_store.py --shape k2 --out D:/soup-bench/moe-k2-synth`.
+Step: `benchmarks/harness/moe_stream_step.py --seq 512 --batch 1 --steps 2 --lora-r 8`
+(step 0 is cold, step 1 is reported separately; neither is averaged into the other).
+
+- **COMPLETES** iff step 0 and step 1 both finish with a finite loss and finite
+ adapter gradients, the peak allocated VRAM is at most 7,500 MiB (the card has
+ 8,151 MiB; the margin is for the CUDA context, and Windows would otherwise spill
+ to shared memory silently), and the process's peak working set stays below
+ 20 GB (the box has 31.7 GB; the rule keeps the owner's 10 GB-free floor).
+- **DOES NOT COMPLETE** otherwise; the record then states which limit, at which
+ layer, with the error text.
+- Reported, no threshold: seconds per step, tokens per second, expert bytes read
+ per step against the 3 x routed-expert bytes the design predicts (forward,
+ checkpoint recompute, backward), layer loads.
+
+Estimate before the run (an estimate, not a measurement): ~570 GB of experts read
+3 times per step, ~1.7 TB. The async disk tier reads this drive at 4.09-4.14 GB/s
+(`probe-rtx5070-what-bounds-streaming.md` §21); the expert reader is synchronous
+(one expert, then its compute), so expect it slower: 7 minutes at 4.1 GB/s, about
+24 at 1.2 GB/s.
+
+## 2.1 Addendum rule for run 2 (written after run 1, before run 2)
+
+Run 1 routed 512 random tokens to only ~10 of the 384 experts per layer and pass
+(section 4.1). A trained model routes a 512-token step to 96.7-100% of its experts
+(`probe-moe-expert-coverage.md`), so run 1 does not measure what a K2 step reads. Run 2
+repeats the same command with `--route uniform`: every router sends token t to experts
+8t .. 8t+7 (mod 384), so each pass routes to all 384 experts of every MoE layer, the
+coverage a trained model nearly has. The router weights still stream; only its choice
+is replaced. Same thresholds as section 2: **COMPLETES** iff both steps finish with a
+finite loss and finite adapter gradients, peak allocated VRAM <= 7,500 MiB and peak
+working set < 20 GB. Reported, no threshold: seconds per step, expert reads (the design
+predicts 60 x 384 x 3 = 69,120 per step) and expert bytes per step. Label of every
+number: "random weights, shape only; routing forced uniform".
+
+## 3. Box state
+
+Run 2: 2026-10-14 19:21:23Z to 19:54:38Z; AC power on; 12.4 GB RAM free and GPU 0 MiB in
+use before; the same hold, extended on the board and by message; harness commit 1fe403a18,
+same command plus `--route uniform`.
+
+Run 1: 2026-10-14 19:17:00Z to 19:18:58Z; AC power on; 11.3 GB RAM free before;
+GPU 0 MiB in use before; D: 214 GB free after the 533 GB store was written; a
+measurement hold on the board, every other session confirmed idle. Harness commit
+0fa52150e. Run with `--tier disk --no-pin`: the RAM tier would pin the ~5 GB of
+dense layer files plus the two 2.35 GB vocabulary matrices on a box with ~11 GB
+free, and pinned disk-tier staging rounds to an 8 GiB arena (seen in a build-only
+check), so staging stays pageable. The rule did not fix the tier; this is the
+configuration that keeps the owner's free-RAM floor.
+
+Store: `synth_moe_store.py --shape k2`, 1,026,408,232,448 parameters,
+533,242,299,230 bytes, written in 588.6 s (`synth.json`), NF4 with double
+quantisation, `expert_layout: per_expert`.
+
+## 4. Results
+
+### 4.0 Run 1: the model's own routing (random weights, shape only)
+
+Build 4.22 s; 30,513,664 trainable parameters (LoRA r 8 on `q_a_proj`, `q_b_proj`,
+`kv_a_proj_with_mqa`, `kv_b_proj`, `o_proj` of all 61 layers). Raw JSON:
+`benchmarks/results/probe-rtx5070/giant-moe/k2-step.json`.
+
+| step | seconds | tokens/s | loss | grads finite | peak alloc VRAM | peak reserved | peak working set | expert reads | expert bytes | layer loads |
+|---|---|---|---|---|---|---|---|---|---|---|
+| 0 (cold) | 53.61 | 9.55 | 13.478 | 610 / 610 | 4,342 MiB | 5,052 MiB | 7.67 GB | 1,890 | 42.94 GB | 120 |
+| 1 | 45.21 | 11.33 | 13.473 | 610 / 610 | 4,723 MiB | 5,068 MiB | 7.68 GB | 1,752 | 39.80 GB | 118 |
+
+Against section 2: both steps finish, loss and all 610 adapter gradients finite, peak
+VRAM 4,723 MiB <= 7,500, peak working set 7.68 GB < 20 GB: **run 1 COMPLETES.**
+
+### 4.1 Why run 1's 45 s is not a K2 step time
+
+1,752 expert reads in a step is 1,752 / (60 MoE layers x 3 passes) = ~9.7 distinct
+experts per layer and pass out of 384: the 512 random tokens collapsed onto a few
+experts (with random attention weights every token attends to an average of the same
+prefix, so the hidden states, and with them the routing, nearly coincide). The design
+predicted ~1.5-1.7 TB of expert reads per step for a model routing like a trained one;
+run 1 read 40 GB. Its time is real for what it did, and says nothing about a real K2
+step. Run 2 (section 2.1) measures that case.
+
+### 4.2 Run 2: forced uniform routing (random weights, shape only; routing forced uniform)
+
+Raw JSON: `benchmarks/results/probe-rtx5070/giant-moe/k2-step-uniform.json`.
+
+| step | seconds | tokens/s | loss | grads finite | peak alloc VRAM | peak reserved | peak working set | expert reads | expert bytes | layer loads |
+|---|---|---|---|---|---|---|---|---|---|---|
+| 0 (cold) | 867.95 | 0.590 | 13.477 | 610 / 610 | 4,342 MiB | 5,052 MiB | 7.75 GB | 69,120 | 1,570.34 GB | 120 |
+| 1 | 1,108.77 | 0.462 | 13.470 | 610 / 610 | 4,723 MiB | 5,170 MiB | 7.89 GB | 69,120 | 1,570.34 GB | 118 |
+
+- Expert reads are exactly the predicted 60 x 384 x 3 = 69,120 per step.
+- Expert bytes per step, 1.57 TB, are 2.95 x the 533 GB store: each expert is read in forward, in the checkpoint's recompute, and in its own backward.
+- Seconds per expert byte: 1.81 GB/s of expert reads in step 0 and 1.42 GB/s in step 1, compute included.
+- Step 1 was slower than step 0. Nothing in the run says why; it is reported as measured.
+
+Against section 2.1, both steps finish:
+- loss and all 610 adapter gradients finite;
+- peak VRAM 4,723 MiB <= 7,500;
+- peak working set 7.89 GB < 20 GB.
+
+**Run 2 COMPLETES.**
+
+## 5. Verdict
+
+**COMPLETES.** On an RTX 5070 Laptop (8 GB) with 31.7 GB of RAM, layer streaming plus expert-granularity streaming runs a full LoRA training step (forward, backward, AdamW) of a Kimi K2-shaped model: 1,026,408,232,448 parameters, random weights, 533 GB NF4 on NVMe. Peak VRAM is 4,723 MiB.
+
+**A step takes 14.5-18.5 minutes (867.95 s and 1,108.77 s) when every expert is routed (run 2); a trained model routes nearly every expert (#992).** That is a capacity demonstration, not a training regime: at 512 tokens per step it is ~0.5 tokens/s. The time is the read volume, 1.57 TB per step, three passes over the experts. L2L (Pudipeddi et al. 2020) is the published way to amortise those reads across micro-batches, and this run does not use it.
+
+**Not shown:**
+- convergence or quality: the weights are random;
+- a real K2 checkpoint: it is FP8, which the sharder refuses;
+- more than two steps;
+- whether step 1's slowdown persists.
diff --git a/benchmarks/results/probe-rtx5070/expert-stream/gate.json b/benchmarks/results/probe-rtx5070/expert-stream/gate.json
new file mode 100644
index 00000000..a6fd841c
--- /dev/null
+++ b/benchmarks/results/probe-rtx5070/expert-stream/gate.json
@@ -0,0 +1,211 @@
+{
+ "box": {
+ "python": "3.12.10",
+ "platform": "Windows-11-10.0.26200-SP0",
+ "torch": "2.14.0+cu130",
+ "cuda": "13.0",
+ "time_utc": "2026-10-14T19:04:45Z",
+ "gpu": "NVIDIA GeForce RTX 5070 Laptop GPU",
+ "gpu_free_mib": 7013,
+ "gpu_total_mib": 8123,
+ "transformers": "5.17.0",
+ "bitsandbytes": "0.50.2",
+ "safetensors": "0.8.0"
+ },
+ "args": {
+ "model_dir": "C:/Users/user/.cache/huggingface/hub/models--allenai--OLMoE-1B-7B-0924/snapshots/6d84c48581ece794365f2b8e9cfb043c68ade9c5",
+ "scratch": "D:/soup-bench/expert-gate",
+ "out": "benchmarks/results/probe-rtx5070/expert-stream/gate.json",
+ "layers": [
+ 0,
+ 7,
+ 15
+ ],
+ "tokens": 512,
+ "cells": [
+ "cpu-fp32",
+ "cuda-bf16",
+ "cuda-bf16-nf4"
+ ]
+ },
+ "layers": {
+ "0": {
+ "cpu-fp32": {
+ "resident_seconds": 0.3604,
+ "streamed_seconds": 1.2883,
+ "output": {
+ "equal": true,
+ "max_abs_diff": 0.0
+ },
+ "grad_input": {
+ "equal": true,
+ "max_abs_diff": 0.0
+ },
+ "grad_routing": {
+ "equal": true,
+ "max_abs_diff": 0.0
+ },
+ "experts_hit": 64,
+ "fetches": 128,
+ "fetches_ok": true
+ },
+ "cuda-bf16": {
+ "resident_seconds": 0.759,
+ "streamed_seconds": 0.6264,
+ "output": {
+ "equal": true,
+ "max_abs_diff": 0.0
+ },
+ "grad_input": {
+ "equal": true,
+ "max_abs_diff": 0.0
+ },
+ "grad_routing": {
+ "equal": true,
+ "max_abs_diff": 0.0
+ },
+ "experts_hit": 64,
+ "fetches": 128,
+ "fetches_ok": true
+ },
+ "cuda-bf16-nf4": {
+ "resident_seconds": 0.0735,
+ "streamed_seconds": 0.4971,
+ "output": {
+ "equal": true,
+ "max_abs_diff": 0.0
+ },
+ "grad_input": {
+ "equal": true,
+ "max_abs_diff": 0.0
+ },
+ "grad_routing": {
+ "equal": true,
+ "max_abs_diff": 0.0
+ },
+ "experts_hit": 64,
+ "fetches": 128,
+ "fetches_ok": true
+ }
+ },
+ "7": {
+ "cpu-fp32": {
+ "resident_seconds": 0.3389,
+ "streamed_seconds": 1.2682,
+ "output": {
+ "equal": true,
+ "max_abs_diff": 0.0
+ },
+ "grad_input": {
+ "equal": true,
+ "max_abs_diff": 0.0
+ },
+ "grad_routing": {
+ "equal": true,
+ "max_abs_diff": 0.0
+ },
+ "experts_hit": 64,
+ "fetches": 128,
+ "fetches_ok": true
+ },
+ "cuda-bf16": {
+ "resident_seconds": 0.1389,
+ "streamed_seconds": 0.6553,
+ "output": {
+ "equal": true,
+ "max_abs_diff": 0.0
+ },
+ "grad_input": {
+ "equal": true,
+ "max_abs_diff": 0.0
+ },
+ "grad_routing": {
+ "equal": true,
+ "max_abs_diff": 0.0
+ },
+ "experts_hit": 64,
+ "fetches": 128,
+ "fetches_ok": true
+ },
+ "cuda-bf16-nf4": {
+ "resident_seconds": 0.1348,
+ "streamed_seconds": 0.4841,
+ "output": {
+ "equal": true,
+ "max_abs_diff": 0.0
+ },
+ "grad_input": {
+ "equal": true,
+ "max_abs_diff": 0.0
+ },
+ "grad_routing": {
+ "equal": true,
+ "max_abs_diff": 0.0
+ },
+ "experts_hit": 64,
+ "fetches": 128,
+ "fetches_ok": true
+ }
+ },
+ "15": {
+ "cpu-fp32": {
+ "resident_seconds": 0.3451,
+ "streamed_seconds": 1.2723,
+ "output": {
+ "equal": true,
+ "max_abs_diff": 0.0
+ },
+ "grad_input": {
+ "equal": true,
+ "max_abs_diff": 0.0
+ },
+ "grad_routing": {
+ "equal": true,
+ "max_abs_diff": 0.0
+ },
+ "experts_hit": 64,
+ "fetches": 128,
+ "fetches_ok": true
+ },
+ "cuda-bf16": {
+ "resident_seconds": 0.1511,
+ "streamed_seconds": 0.6537,
+ "output": {
+ "equal": true,
+ "max_abs_diff": 0.0
+ },
+ "grad_input": {
+ "equal": true,
+ "max_abs_diff": 0.0
+ },
+ "grad_routing": {
+ "equal": true,
+ "max_abs_diff": 0.0
+ },
+ "experts_hit": 64,
+ "fetches": 128,
+ "fetches_ok": true
+ },
+ "cuda-bf16-nf4": {
+ "resident_seconds": 0.1027,
+ "streamed_seconds": 0.5361,
+ "output": {
+ "equal": true,
+ "max_abs_diff": 0.0
+ },
+ "grad_input": {
+ "equal": true,
+ "max_abs_diff": 0.0
+ },
+ "grad_routing": {
+ "equal": true,
+ "max_abs_diff": 0.0
+ },
+ "experts_hit": 64,
+ "fetches": 128,
+ "fetches_ok": true
+ }
+ }
+ },
+ "verdict": "PASS"
+}
diff --git a/benchmarks/results/probe-rtx5070/giant-moe/k2-step-uniform.json b/benchmarks/results/probe-rtx5070/giant-moe/k2-step-uniform.json
new file mode 100644
index 00000000..0c071f39
--- /dev/null
+++ b/benchmarks/results/probe-rtx5070/giant-moe/k2-step-uniform.json
@@ -0,0 +1,77 @@
+{
+ "label": "random weights, shape only; routing forced uniform (token t -> experts kt..kt+k-1 mod E)",
+ "args": {
+ "store": "D:/soup-bench/moe-k2-synth",
+ "weights": null,
+ "model": null,
+ "expert_layout": "per_expert",
+ "out": "C:/Users/user/projects/soup-wt/moe-b1/benchmarks/results/probe-rtx5070/giant-moe/k2-step-uniform.json",
+ "seq": 512,
+ "batch": 1,
+ "steps": 2,
+ "lora_r": 8,
+ "buffers": 2,
+ "tier": "disk",
+ "no_pin": true,
+ "seed": 3,
+ "label": "random weights, shape only",
+ "route": "uniform"
+ },
+ "steps": [
+ {
+ "step": 0,
+ "seconds": 867.95,
+ "tokens_per_second": 0.59,
+ "loss": 13.47708511352539,
+ "loss_finite": true,
+ "grads_finite": true,
+ "grads_present": 610,
+ "expert_fetches": 69120,
+ "expert_bytes_read": 1570336174080,
+ "layer_loads": 120,
+ "peak_vram_mib": 4342,
+ "peak_reserved_mib": 5052,
+ "peak_host_bytes_so_far": 7749476352
+ },
+ {
+ "step": 1,
+ "seconds": 1108.77,
+ "tokens_per_second": 0.462,
+ "loss": 13.469831466674805,
+ "loss_finite": true,
+ "grads_finite": true,
+ "grads_present": 610,
+ "expert_fetches": 69120,
+ "expert_bytes_read": 1570336174080,
+ "layer_loads": 118,
+ "peak_vram_mib": 4723,
+ "peak_reserved_mib": 5170,
+ "peak_host_bytes_so_far": 7885430784
+ }
+ ],
+ "store_bytes": 533242299230,
+ "store_expert_layout": "per_expert",
+ "store_quant": "nf4",
+ "store_double_quant": true,
+ "build_seconds": 4.38,
+ "routers_overridden": 60,
+ "trainable_params": 30513664,
+ "stats": {
+ "n_layers": 61,
+ "buffers": 2,
+ "buffer_bytes": 2918596920,
+ "large_buffer_bytes": 2348810240,
+ "store_bytes": 5115134896,
+ "pinned": false,
+ "pinned_bytes": 0,
+ "tier": "disk",
+ "read_ahead": 2,
+ "disk_bytes": 9779642448,
+ "layer_loads": 238,
+ "large_loads": 5,
+ "device": "cuda",
+ "total_params": 1026408232448,
+ "expert_fetches": 138240,
+ "expert_bytes_read": 3140672348160
+ }
+}
diff --git a/benchmarks/results/probe-rtx5070/giant-moe/k2-step.json b/benchmarks/results/probe-rtx5070/giant-moe/k2-step.json
new file mode 100644
index 00000000..55c275a6
--- /dev/null
+++ b/benchmarks/results/probe-rtx5070/giant-moe/k2-step.json
@@ -0,0 +1,75 @@
+{
+ "label": "random weights, shape only",
+ "args": {
+ "store": "D:/soup-bench/moe-k2-synth",
+ "weights": null,
+ "model": null,
+ "expert_layout": "per_expert",
+ "out": "C:/Users/user/projects/soup-wt/moe-b1/benchmarks/results/probe-rtx5070/giant-moe/k2-step.json",
+ "seq": 512,
+ "batch": 1,
+ "steps": 2,
+ "lora_r": 8,
+ "buffers": 2,
+ "tier": "disk",
+ "no_pin": true,
+ "seed": 3,
+ "label": "random weights, shape only"
+ },
+ "steps": [
+ {
+ "step": 0,
+ "seconds": 53.61,
+ "tokens_per_second": 9.551,
+ "loss": 13.478171348571777,
+ "loss_finite": true,
+ "grads_finite": true,
+ "grads_present": 610,
+ "expert_fetches": 1890,
+ "expert_bytes_read": 42938879760,
+ "layer_loads": 120,
+ "peak_vram_mib": 4342,
+ "peak_reserved_mib": 5052,
+ "peak_host_bytes_so_far": 7671418880
+ },
+ {
+ "step": 1,
+ "seconds": 45.21,
+ "tokens_per_second": 11.326,
+ "loss": 13.472814559936523,
+ "loss_finite": true,
+ "grads_finite": true,
+ "grads_present": 610,
+ "expert_fetches": 1752,
+ "expert_bytes_read": 39803659968,
+ "layer_loads": 118,
+ "peak_vram_mib": 4723,
+ "peak_reserved_mib": 5068,
+ "peak_host_bytes_so_far": 7682801664
+ }
+ ],
+ "store_bytes": 533242299230,
+ "store_expert_layout": "per_expert",
+ "store_quant": "nf4",
+ "store_double_quant": true,
+ "build_seconds": 4.22,
+ "trainable_params": 30513664,
+ "stats": {
+ "n_layers": 61,
+ "buffers": 2,
+ "buffer_bytes": 2918596920,
+ "large_buffer_bytes": 2348810240,
+ "store_bytes": 5115134896,
+ "pinned": false,
+ "pinned_bytes": 0,
+ "tier": "disk",
+ "read_ahead": 2,
+ "disk_bytes": 9779642448,
+ "layer_loads": 238,
+ "large_loads": 5,
+ "device": "cuda",
+ "total_params": 1026408232448,
+ "expert_fetches": 3642,
+ "expert_bytes_read": 82742539728
+ }
+}
diff --git a/changelog.d/0.76.0/2008.added.md b/changelog.d/0.76.0/2008.added.md
new file mode 100644
index 00000000..df6d3a15
--- /dev/null
+++ b/changelog.d/0.76.0/2008.added.md
@@ -0,0 +1,9 @@
+- **Expert-granularity streaming for DeepSeek-V3 MoE layers.** `shard_checkpoint(...,
+ expert_layout="per_expert")` writes each MoE layer's routed experts to their own file, one pair of
+ matrices per expert (NF4 under `quant="nf4"`), and the streamed model reads an expert only when
+ the router picks it, so the VRAM bound no longer grows with the expert count. It is bit-exact
+ against transformers' eager experts on real OLMoE-1B-7B layers, forward and backward, in fp32,
+ bf16 and NF4. Measured on an RTX 5070 Laptop (8 GB): LoRA steps of a Kimi K2-shaped 1.03 T-parameter
+ model (random weights) at 4,723 MiB of peak VRAM, 14.5-18.5 minutes per step.
+ Reachable from the sharder API and the benchmark harnesses; no config field yet.
+ Backward recomputation preserves the forward autocast settings. (#2008)
diff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.md
index 306f9932..c33647ae 100644
--- a/docs/performance-and-quantization.md
+++ b/docs/performance-and-quantization.md
@@ -469,6 +469,17 @@ checkpointed step. The fused arm reduces saved-weight VRAM but its backward stil
dequantises because bitsandbytes exposes no transposed 4-bit GEMM; it is therefore a
bounded memory/time trade, not a claim that #842's full kernel ceiling is complete.
+**Expert-granularity streaming (DeepSeek-V3-family MoE, API/harness only).** For
+admitted DeepSeek-V3 checkpoints with per-expert source weights, `shard_checkpoint(..., expert_layout="per_expert")`
+stores routed experts separately so the runtime fetches one frozen expert at a time
+instead of holding the full routed-expert block in the layer buffer. This is a
+capacity option for unusually large MoE layers; it does not add a CLI or config knob.
+The current harness trains LoRA on attention projections: LoRA on streamed routed
+experts is unsupported, while attention and shared-expert LoRA remain resident. The
+fit planner still estimates the fused layer and does not account for per-expert
+streaming, so its recommendation is not an estimate of this layout's capacity. No
+production throughput claim is made; see the [expert streaming gate](../benchmarks/gate-expert-streaming.md).
+
**`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.
diff --git a/src/soup_cli/utils/expert_stream.py b/src/soup_cli/utils/expert_stream.py
new file mode 100644
index 00000000..cac6645f
--- /dev/null
+++ b/src/soup_cli/utils/expert_stream.py
@@ -0,0 +1,620 @@
+"""Expert-granularity streaming for MoE decoder layers.
+
+Layer streaming moves one decoder layer at a time, so the largest layer bounds
+the card. A DeepSeek-V3-class MoE layer is mostly routed experts: one Kimi K2
+layer (384 experts of 3 x 7168 x 2048) is ~9 GB at NF4, larger than an 8 GB
+card on its own. Here the routed experts of a MoE layer live in their own file,
+one tensor pair per expert, and the layer's experts module is replaced by
+``StreamedExperts``: it loads each expert the router picked, uses it, and drops
+it. The decoder-layer pool then carries only the dense part (attention, norms,
+router, shared expert).
+
+Numerics: ``StreamedExperts`` follows transformers' eager experts loop op for
+op (the same body in ``DeepseekV3Experts``, ``OlmoeExperts``,
+``Qwen3MoeExperts``, ``MixtralExperts``), so it equals a resident module run
+with ``experts_implementation="eager"`` bit for bit, forward and backward.
+Expert weights are frozen; the backward needs only the gradient of the
+expert's input, so it fetches the expert again and recomputes the expert MLP
+on a local graph. Inside a checkpointed decoder layer that is three reads of
+every routed-to expert per step (forward, recompute, backward).
+
+What it buys: the VRAM bound, nothing else. ``benchmarks/probe-moe-expert-coverage.md``
+measured that a training step routes to 96.7-100% of the experts of a layer, so
+an expert-streamed step reads at least the bytes a layer-streamed step reads.
+"""
+
+from __future__ import annotations
+
+import os
+from dataclasses import dataclass, field
+from typing import Any, Dict, Iterable, Mapping, Optional, Sequence, Tuple
+
+#: Tensor names inside a per-layer experts file: ``"<expert>.gate_up"`` is the
+#: ``[2I, H]`` matrix (gate rows first, as transformers' fused ``gate_up_proj``
+#: row ``e``), ``"<expert>.down"`` the ``[H, I]`` one.
+GATE_UP = "gate_up"
+DOWN = "down"
+EXPERT_PARTS = (GATE_UP, DOWN)
+#: The index's marker for a cache whose MoE layers keep their routed experts
+#: in per-layer experts files instead of inside the decoder-layer file.
+EXPERT_LAYOUT_PER_EXPERT = "per_expert"
+_MAX_EXPERTS = 4096
+#: One expert's stored bytes may not exceed this: the reader allocates its staging
+#: from the header, so an unbounded header would size an unbounded allocation. A
+#: Kimi K2 expert is ~25 MB at NF4, ~88 MB at bf16.
+_MAX_EXPERT_BYTES = 2**30
+
+
+def expert_key(expert: int, part: str) -> str:
+ """Shard key of one expert's matrix."""
+ return f"{expert}.{part}"
+
+
+def expert_shard_name(layer: int) -> str:
+ """File name of a MoE layer's experts file."""
+ return f"experts_{layer:03d}.safetensors"
+
+
+@dataclass(frozen=True)
+class ExpertShardInfo:
+ """What :func:`write_expert_shard` wrote for one MoE layer."""
+
+ count: int
+ #: part -> stored dense shape, e.g. {"gate_up": (2I, H), "down": (H, I)}
+ shapes: Mapping[str, Tuple[int, ...]]
+ #: part -> NF4WeightSpec; empty when unquantised
+ quant_specs: Mapping[str, Any] = field(default_factory=dict)
+ total_params: int = 0
+ #: the NF4 code tables seen while quantising (``code``, ``nested_code``)
+ codes: Tuple[Any, Any] = (None, None)
+
+
+def write_expert_shard(
+ path: str,
+ experts: Iterable[Tuple[Any, Any]],
+ *,
+ quantise: bool,
+ double_quant: bool = True,
+ device: str = "cpu",
+) -> ExpertShardInfo:
+ """Write one MoE layer's routed experts, one ``(gate_up, down)`` pair each.
+
+ ``experts`` yields the dense matrices in expert order, already at the
+ stream dtype. Under ``quantise`` each matrix is NF4-quantised on its own,
+ exactly as the decoder-layer sharder quantises one ``nn.Linear`` weight.
+ Every expert must have the shapes of the first one.
+ """
+ from soup_cli.utils.layer_shard import _atomic_save, _quantize_nf4
+
+ blob: Dict[str, Any] = {}
+ shapes: Dict[str, Tuple[int, ...]] = {}
+ specs: Dict[str, Any] = {}
+ code = nested_code = None
+ count = 0
+ total = 0
+ for expert, pair in enumerate(experts):
+ if expert >= _MAX_EXPERTS:
+ raise ValueError(f"a MoE layer may hold at most {_MAX_EXPERTS} experts")
+ for part, tensor in zip(EXPERT_PARTS, pair):
+ shape = tuple(int(dim) for dim in tensor.shape)
+ if len(shape) != 2:
+ raise ValueError(f"expert {expert} {part} must be 2-D, got {shape}")
+ prior = shapes.setdefault(part, shape)
+ if prior != shape:
+ raise ValueError(
+ f"expert {expert} {part} has shape {shape}; expert 0 has {prior}"
+ )
+ total += tensor.numel()
+ key = expert_key(expert, part)
+ if not quantise:
+ blob[key] = tensor.detach().contiguous()
+ continue
+ sidecars, spec, seen_code, seen_nested = _quantize_nf4(
+ tensor, double_quant=double_quant, device=device
+ )
+ prior_spec = specs.setdefault(part, spec)
+ if prior_spec != spec:
+ raise ValueError(f"expert {expert} {part} has inconsistent NF4 metadata")
+ code = seen_code if code is None else code
+ nested_code = seen_nested if nested_code is None else nested_code
+ for suffix, value in sidecars.items():
+ blob[key + suffix] = value
+ count += 1
+ if count == 0:
+ raise ValueError("a MoE layer needs at least one expert")
+ if shapes[GATE_UP][1] != shapes[DOWN][0] or shapes[GATE_UP][0] != 2 * shapes[DOWN][1]:
+ raise ValueError(
+ f"gate_up {shapes[GATE_UP]} and down {shapes[DOWN]} are not one expert MLP "
+ f"([2I, H] and [H, I])"
+ )
+ _atomic_save(blob, path)
+ return ExpertShardInfo(
+ count=count,
+ shapes=shapes,
+ quant_specs=specs,
+ total_params=total,
+ codes=(code, nested_code),
+ )
+
+
+def expert_bytes(
+ shapes: Mapping[str, Tuple[int, ...]], *, dtype_bytes: int, quantised: bool
+) -> Tuple[int, int]:
+ """(stored bytes, dense compute bytes) of ONE expert.
+
+ Stored NF4 is half a byte per weight plus one fp32 absmax per 64-weight
+ block (the nested statistics are smaller still and not counted).
+ """
+ weights = sum(shape[0] * shape[1] for shape in shapes.values())
+ dense = weights * dtype_bytes
+ if not quantised:
+ return dense, dense
+ stored = weights // 2 + (weights // 64) * 4
+ return stored, dense
+
+
+def expert_stream_vram_bytes(
+ shapes: Mapping[str, Tuple[int, ...]], *, dtype_bytes: int, quantised: bool
+) -> int:
+ """Peak VRAM the expert path adds to a step, for the pre-flight.
+
+ One expert's packed copy plus its dense weights, twice: the backward holds
+ the expert it recomputes while the caching allocator may still keep the
+ previous one's blocks.
+ """
+ stored, dense = expert_bytes(shapes, dtype_bytes=dtype_bytes, quantised=quantised)
+ packed = stored if quantised else 0
+ return 2 * (packed + dense)
+
+
+class ExpertShardReader:
+ """Reads one MoE layer's experts file, one expert at a time.
+
+ Each stored tensor of the expert is one positioned read of its own
+ sector-aligned span, through the shared ``safetensors_reader`` (its header
+ is validated against the file), so the file's tensor order does not matter.
+ No memory map: a live safetensors map charges Windows commit for the whole
+ file, and a 1T-class store has ~60 files of ~9 GB. Direct (unbuffered) I/O
+ when the platform has it, so a store far larger than RAM does not churn the
+ page cache of the whole box; buffered reads otherwise.
+
+ The header is read through the identity of a handle opened for it, and the
+ handle is closed again before ``__init__`` returns: a reader holds no OS
+ handle until its first fetch, so an install that fails after the readers
+ were built leaks nothing. The first fetch reopens the file and refuses it
+ unless its identity is still the one the header was read from, so a file
+ swapped in between is never read at stale offsets. From then on the handle
+ stays open, which on Windows also keeps the file from being replaced.
+ Every stored tensor's size is checked against the index (dense shape, NF4
+ spec), so a header-valid file cannot steer a read or a dequantisation past
+ the bytes it really holds.
+ """
+
+ def __init__(
+ self,
+ path: str,
+ *,
+ count: int,
+ shapes: Mapping[str, Tuple[int, ...]],
+ quant_specs: Mapping[str, Any],
+ dtype: str,
+ direct: bool = True,
+ ) -> None:
+ from soup_cli.utils.layer_stream_runtime import quant_sidecar_keys
+ from soup_cli.utils.safetensors_reader import (
+ aligned_span,
+ identity_of,
+ read_header_with_identity,
+ )
+
+ if isinstance(count, bool) or not isinstance(count, int) or not 1 <= count <= _MAX_EXPERTS:
+ raise ValueError(f"expert count must be an int in [1, {_MAX_EXPERTS}], got {count!r}")
+ self.path = path
+ self.count = count
+ self.shapes = {part: _checked_shape(part, shapes[part]) for part in EXPERT_PARTS}
+ self.quant_specs = dict(quant_specs)
+ self.dtype = dtype
+ self.direct = direct
+ self._handle: Optional[Any] = None
+ name = os.path.basename(path)
+ self._identity: Optional[Any] = None
+ handle = self._open()
+ header, identity = read_header_with_identity(path)
+ if identity_of(handle) != identity:
+ self.close()
+ raise ValueError(f"experts file {name} changed while it was being opened")
+ self._identity = identity
+ self._size = identity.size
+ expected = {
+ part: _expected_tensors(
+ expert_key(0, part), self.shapes[part], self.quant_specs.get(part)
+ )
+ for part in EXPERT_PARTS
+ }
+ stored_dtype = _stored_torch_dtype(dtype)
+ #: per expert: ((tensor name, entry), ...)
+ self._entries: list = []
+ largest = 0
+ for expert in range(count):
+ entries = []
+ for part in EXPERT_PARTS:
+ key = expert_key(expert, part)
+ spec = self.quant_specs.get(part)
+ wanted = quant_sidecar_keys(key, spec) if spec is not None else (key,)
+ for tensor_name, (want_shape, want_dtype) in zip(wanted, expected[part]):
+ entry = header.get(tensor_name)
+ if entry is None:
+ self.close()
+ raise ValueError(
+ f"experts file {name} has no tensor {tensor_name!r} "
+ f"— reshard the checkpoint"
+ )
+ got_dtype = _stored_torch_dtype(entry.dtype)
+ if want_dtype is None:
+ want_dtype = stored_dtype
+ if tuple(entry.shape) != want_shape or got_dtype != want_dtype:
+ self.close()
+ raise ValueError(
+ f"experts file {name}: {tensor_name!r} is {entry.dtype} "
+ f"{tuple(entry.shape)}, the index expects {want_dtype} "
+ f"{want_shape} — reshard the checkpoint"
+ )
+ if entry.start % got_dtype.itemsize:
+ self.close()
+ raise ValueError(
+ f"experts file {name}: {tensor_name!r} is not aligned to its dtype"
+ )
+ entries.append((tensor_name, entry))
+ need = 0
+ for _, entry in entries:
+ lo, hi = aligned_span(entry.start, entry.end)
+ need += hi - lo
+ if need > _MAX_EXPERT_BYTES:
+ self.close()
+ raise ValueError(
+ f"experts file {name}: expert {expert} needs {need} bytes, over the "
+ f"{_MAX_EXPERT_BYTES}-byte limit for one expert"
+ )
+ largest = max(largest, need)
+ self._entries.append(tuple(entries))
+ if expert_key(count, GATE_UP) in header or expert_key(count, DOWN) in header:
+ self.close()
+ raise ValueError(
+ f"experts file {name} holds more than {count} experts — reshard the checkpoint"
+ )
+ #: Staging bytes one expert needs (each tensor's span on sector bounds).
+ self.max_span = largest
+ self.fetches = 0
+ self.bytes_read = 0
+ self.close()
+
+ def _open(self) -> Any:
+ if self._handle is None:
+ if self.direct:
+ from soup_cli.utils.safetensors_reader import open_direct
+
+ try:
+ self._handle = open_direct(self.path)
+ except OSError:
+ # No direct I/O on this platform / filesystem: buffered reads.
+ self.direct = False
+ if self._handle is None:
+ self._handle = open(self.path, "rb", buffering=0)
+ if self._identity is not None:
+ from soup_cli.utils.safetensors_reader import identity_of
+
+ if identity_of(self._handle) != self._identity:
+ self.close()
+ raise ValueError(
+ f"experts file {os.path.basename(self.path)} changed on disk since "
+ f"its header was read — reshard the checkpoint and restart"
+ )
+ return self._handle
+
+ def read_host(self, expert: int, staging: Any) -> Dict[str, Any]:
+ """``expert``'s stored tensors as CPU views into ``staging``.
+
+ ``staging`` is a contiguous CPU uint8 tensor of at least ``max_span``
+ bytes whose address is sector-aligned (``aligned_staging``). The views
+ are valid until the next read into it.
+ """
+ from soup_cli.utils.safetensors_reader import aligned_span, read_range_into
+
+ if not 0 <= expert < self.count:
+ raise IndexError(f"expert {expert} outside [0, {self.count})")
+ if staging.numel() < self.max_span:
+ raise ValueError(f"staging holds {staging.numel()} bytes, a read needs {self.max_span}")
+ handle = self._open()
+ out: Dict[str, Any] = {}
+ cursor = 0
+ for tensor_name, entry in self._entries[expert]:
+ lo, hi = aligned_span(entry.start, entry.end)
+ region = staging[cursor : cursor + hi - lo]
+ read_range_into(handle, lo, region, min(hi, self._size) - lo)
+ raw = region[entry.start - lo : entry.end - lo]
+ out[tensor_name] = raw.view(_stored_torch_dtype(entry.dtype)).view(entry.shape)
+ cursor += hi - lo
+ self.bytes_read += entry.nbytes
+ self.fetches += 1
+ return out
+
+ def close(self) -> None:
+ if self._handle is not None:
+ self._handle.close()
+ self._handle = None
+
+ def __del__(self) -> None:
+ try:
+ self.close()
+ except Exception: # noqa: BLE001 - best effort at interpreter teardown
+ pass
+
+
+def _checked_shape(part: str, shape: Any) -> Tuple[int, ...]:
+ dims = tuple(int(dim) for dim in shape)
+ if len(dims) != 2 or any(dim < 1 for dim in dims) or dims[0] * dims[1] > 2**31:
+ raise ValueError(f"expert {part} shape must be two positive dims, got {tuple(shape)!r}")
+ return dims
+
+
+def _expected_tensors(key: str, shape: Tuple[int, int], spec: Any) -> Tuple[Tuple[Any, Any], ...]:
+ """(shape, torch dtype) of every stored tensor of one expert matrix, in the
+ order ``quant_sidecar_keys`` names them. ``None`` dtype = the stream dtype.
+
+ NF4 (bitsandbytes ``quantize_4bit``): packed nibbles ``[ceil(n/2), 1]`` uint8,
+ one absmax per ``blocksize`` weights (fp32, or uint8 codes under double
+ quantisation with an fp32 ``nested_absmax`` per ``nested_blocksize`` and a
+ scalar fp32 ``nested_offset``).
+ """
+ import torch
+
+ if spec is None:
+ return ((shape, None),)
+ if tuple(int(dim) for dim in spec.shape) != shape:
+ raise ValueError(f"{key}: NF4 spec shape {tuple(spec.shape)} is not the index's {shape}")
+ nested_ok = not spec.nested or int(spec.nested_blocksize) >= 1
+ if not 1 <= int(spec.blocksize) <= 4096 or not nested_ok:
+ raise ValueError(f"{key}: NF4 spec has an impossible block size")
+ weights = shape[0] * shape[1]
+ blocks = -(-weights // int(spec.blocksize))
+ out = [(((weights + 1) // 2, 1), torch.uint8)]
+ if spec.nested:
+ out.append(((blocks,), torch.uint8))
+ out.append(((-(-blocks // int(spec.nested_blocksize)),), torch.float32))
+ out.append(((), torch.float32))
+ else:
+ out.append(((blocks,), torch.float32))
+ return tuple(out)
+
+
+def aligned_staging(size: int) -> Tuple[Any, Any]:
+ """``(owner, view)``: ``size`` bytes of CPU memory starting on a sector."""
+ import torch
+
+ from soup_cli.utils.safetensors_reader import SECTOR_BYTES
+
+ owner = torch.empty(size + SECTOR_BYTES, dtype=torch.uint8, device="cpu")
+ pad = (-owner.data_ptr()) % SECTOR_BYTES
+ return owner, owner[pad : pad + size]
+
+
+def _stored_torch_dtype(name: str) -> Any:
+ import torch
+
+ # ``safetensors_reader`` reports torch names ("bfloat16"); the file format
+ # itself spells them "BF16". Either is accepted, nothing else is.
+ table = {
+ "BF16": torch.bfloat16,
+ "F16": torch.float16,
+ "F32": torch.float32,
+ "U8": torch.uint8,
+ "bfloat16": torch.bfloat16,
+ "float16": torch.float16,
+ "float32": torch.float32,
+ "uint8": torch.uint8,
+ }
+ if name not in table:
+ raise ValueError(f"experts file stores unsupported dtype {name!r}")
+ return table[name]
+
+
+class ExpertFetcher:
+ """Turns stored expert tensors into dense weights on the compute device.
+
+ Owns the one host staging buffer every reader it serves reads into, so a
+ 60-layer store costs one expert's span of host RAM, not sixty. Not
+ thread-safe: one fetch at a time (the streamed forward and backward are
+ sequential); a concurrent fetch would overwrite the staging under another.
+ """
+
+ def __init__(self, *, device: str, dtype: str, codes: Optional[Mapping[str, Any]] = None):
+ self.device = device
+ self.dtype = dtype
+ self.codes = dict(codes or {})
+ self._staging_owner: Any = None
+ self._staging: Any = None
+
+ def _staging_for(self, reader: ExpertShardReader) -> Any:
+ if self._staging is None or self._staging.numel() < reader.max_span:
+ self._staging_owner, self._staging = aligned_staging(reader.max_span)
+ return self._staging
+
+ def fetch(self, reader: ExpertShardReader, expert: int) -> Tuple[Any, Any]:
+ from soup_cli.utils.layer_stream_runtime import _torch_dtype, rebuild_quant_state
+
+ host = reader.read_host(expert, self._staging_for(reader))
+ target = _torch_dtype(self.dtype)
+ dense = []
+ for part in EXPERT_PARTS:
+ key = expert_key(expert, part)
+ spec = reader.quant_specs.get(part)
+ if spec is None:
+ # copy=True: on a CPU target `.to` would hand back the staging
+ # view, which the next read overwrites.
+ dense.append(host[key].to(device=self.device, dtype=target, copy=True))
+ continue
+ from bitsandbytes.functional import dequantize_4bit
+
+ moved = {
+ name: tensor.to(self.device, copy=True)
+ for name, tensor in host.items()
+ if name == key or name.startswith(key + "::")
+ }
+ state = rebuild_quant_state(key, moved, spec, self.codes)
+ dense.append(dequantize_4bit(moved[key], quant_state=state).to(target))
+ return dense[0], dense[1]
+
+
+def _build_streamed_experts_class():
+ import torch
+ import torch.nn as nn
+ import torch.nn.functional as functional
+
+ def expert_mlp(hidden: Any, gate_up: Any, down: Any, act_fn: Any) -> Any:
+ # transformers' eager experts body, line for line.
+ gate, up = functional.linear(hidden, gate_up).chunk(2, dim=-1)
+ current = act_fn(gate) * up
+ return functional.linear(current, down)
+
+ class _ExpertMLP(torch.autograd.Function):
+ @staticmethod
+ def forward(ctx, hidden, owner, expert): # noqa: D401 - autograd API
+ ctx.device_type = hidden.device.type
+ ctx.autocast_kwargs = {
+ "enabled": torch.is_autocast_enabled(ctx.device_type),
+ "dtype": torch.get_autocast_dtype(ctx.device_type),
+ "cache_enabled": torch.is_autocast_cache_enabled(),
+ }
+ gate_up, down = owner.fetch(expert)
+ out = expert_mlp(hidden, gate_up, down, owner.act_fn)
+ ctx.owner = owner
+ ctx.expert = expert
+ ctx.save_for_backward(hidden)
+ return out
+
+ @staticmethod
+ def backward(ctx, grad_out):
+ (hidden,) = ctx.saved_tensors
+ if not ctx.needs_input_grad[0]:
+ return None, None, None
+ gate_up, down = ctx.owner.fetch(ctx.expert)
+ # Backward usually runs outside the forward's autocast region.
+ with torch.enable_grad(), torch.autocast(ctx.device_type, **ctx.autocast_kwargs):
+ local = hidden.detach().requires_grad_(True)
+ out = expert_mlp(local, gate_up, down, ctx.owner.act_fn)
+ (grad_hidden,) = torch.autograd.grad(out, local, grad_out)
+ return grad_hidden, None, None
+
+ class StreamedExperts(nn.Module):
+ """Drop-in for a transformers experts module; fetches each expert on use."""
+
+ def __init__(self, reader, fetcher, act_fn, layer_idx):
+ super().__init__()
+ self.reader = reader
+ self.fetcher = fetcher
+ self.act_fn = act_fn
+ self.layer_idx = layer_idx
+ self.num_experts = reader.count
+
+ def fetch(self, expert):
+ return self.fetcher.fetch(self.reader, expert)
+
+ def forward(self, hidden_states, top_k_index, top_k_weights):
+ final_hidden_states = torch.zeros_like(hidden_states)
+ with torch.no_grad():
+ expert_mask = functional.one_hot(top_k_index, num_classes=self.num_experts)
+ expert_mask = expert_mask.permute(2, 1, 0)
+ expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
+
+ for expert_idx in expert_hit:
+ expert_idx = expert_idx[0]
+ if expert_idx == self.num_experts:
+ continue
+ top_k_pos, token_idx = torch.where(expert_mask[expert_idx])
+ current_state = hidden_states[token_idx]
+ current = _ExpertMLP.apply(current_state, self, int(expert_idx))
+ current = current * top_k_weights[token_idx, top_k_pos, None]
+ final_hidden_states.index_add_(0, token_idx, current.to(final_hidden_states.dtype))
+ return final_hidden_states
+
+ return StreamedExperts
+
+
+_STREAMED_EXPERTS_CLASS = None
+
+
+def streamed_experts_class() -> Any:
+ global _STREAMED_EXPERTS_CLASS
+ if _STREAMED_EXPERTS_CLASS is None:
+ _STREAMED_EXPERTS_CLASS = _build_streamed_experts_class()
+ return _STREAMED_EXPERTS_CLASS
+
+
+def find_experts_module(layer: Any) -> Optional[Tuple[Any, str, Any]]:
+ """``(parent, attribute, module)`` of a layer's fused routed-experts module.
+
+ Matched by shape of contract, not by class name: a child named ``experts``
+ holding 3-D ``gate_up_proj`` and ``down_proj`` parameters, the layout every
+ transformers 5.x MoE uses. ``None`` for a dense layer.
+ """
+ for name, module in layer.named_modules():
+ parent_name, _, leaf = name.rpartition(".")
+ if leaf != "experts":
+ continue
+ gate_up = getattr(module, "gate_up_proj", None)
+ down = getattr(module, "down_proj", None)
+ if getattr(gate_up, "dim", lambda: 0)() == 3 and getattr(down, "dim", lambda: 0)() == 3:
+ parent = layer.get_submodule(parent_name) if parent_name else layer
+ return parent, leaf, module
+ return None
+
+
+def install_expert_streaming(
+ layers: Sequence[Any],
+ readers: Mapping[int, ExpertShardReader],
+ fetcher: ExpertFetcher,
+) -> int:
+ """Replace each MoE layer's experts module with a ``StreamedExperts``.
+
+ Runs before the decoder-layer name maps are taken, so the fused expert
+ parameters leave the layer and the layer pool never allocates them.
+ Returns the number of layers converted.
+ """
+ cls = streamed_experts_class()
+ converted = 0
+ for idx, layer in enumerate(layers):
+ reader = readers.get(idx)
+ found = find_experts_module(layer)
+ if reader is None:
+ if found is not None:
+ raise ValueError(
+ f"decoder layer {idx} has a routed-experts module but the cache has "
+ f"no experts file for it — reshard the checkpoint"
+ )
+ continue
+ if found is None:
+ raise ValueError(
+ f"the cache has an experts file for decoder layer {idx}, which has no "
+ f"routed-experts module — reshard the checkpoint"
+ )
+ parent, attr, module = found
+ expected_gate_up = tuple(int(dim) for dim in module.gate_up_proj.shape)
+ expected_down = tuple(int(dim) for dim in module.down_proj.shape)
+ stored_gate_up = (reader.count, *reader.shapes[GATE_UP])
+ stored_down = (reader.count, *reader.shapes[DOWN])
+ if (expected_gate_up, expected_down) != (stored_gate_up, stored_down):
+ raise ValueError(
+ f"decoder layer {idx}: the model's experts are {expected_gate_up} / "
+ f"{expected_down} but the experts file holds {reader.count} x "
+ f"{reader.shapes[GATE_UP]} / {reader.shapes[DOWN]} — reshard the checkpoint"
+ )
+ names = [name for name, _ in module.named_parameters()]
+ if any(name.startswith("lora_") or ".lora_" in name for name in names):
+ raise ValueError(
+ f"decoder layer {idx}: adapters on the routed experts cannot be trained "
+ f"while the experts are streamed one at a time; target attention or the "
+ f"shared expert instead"
+ )
+ setattr(parent, attr, cls(reader, fetcher, module.act_fn, idx))
+ converted += 1
+ return converted
diff --git a/src/soup_cli/utils/layer_shard.py b/src/soup_cli/utils/layer_shard.py
index a5633e46..6529b3b2 100644
--- a/src/soup_cli/utils/layer_shard.py
+++ b/src/soup_cli/utils/layer_shard.py
@@ -46,6 +46,11 @@ from typing import (
)
from soup_cli import __version__
+from soup_cli.utils.expert_stream import (
+ EXPERT_LAYOUT_PER_EXPERT,
+ expert_shard_name,
+ write_expert_shard,
+)
logger = logging.getLogger(__name__)
@@ -135,6 +140,11 @@ _LAYER_BUFFER_KEYS = {"deepseek_v3": ("mlp.gate.e_score_correction_bias",)}
def layer_buffer_keys(arch: str) -> Tuple[str, ...]:
"""Short keys of the per-layer buffers streamed for ``arch`` (see above)."""
return _LAYER_BUFFER_KEYS.get(arch, ())
+
+
+#: Architectures admitted to ``expert_layout="per_expert"``: each one passed
+#: the resident-vs-streamed parity tests in ``tests/test_expert_stream.py``.
+_PER_EXPERT_LAYOUT_ARCHS = ("deepseek_v3",)
_QWEN4_OQ_EXPERT_RE = re.compile(
r"^(?P<prefix>model\.layers\.\d+\.mlp)\.switch_mlp\."
r"(?P<projection>gate_proj|up_proj|down_proj)\.weight$"
@@ -282,6 +292,22 @@ class ShardIndex:
#: Per decoder layer, the root holding its file (0 = this directory, k = stripe_roots[k-1]).
#: Empty == every layer here.
layer_roots: Tuple[int, ...] = ()
+ #: "" keeps a MoE layer's routed experts inside its decoder-layer file (the
+ #: fused 3-D tensors); "per_expert" writes them to ``experts_NNN.safetensors``
+ #: beside the layer file, one tensor pair per expert, streamed one expert at
+ #: a time (``utils/expert_stream.py``). Deliberately NOT a format-version
+ #: bump (that would invalidate every existing cache): a Soup from before this
+ #: field reads a per_expert cache as fused and refuses it at install with
+ #: "shard is missing decoder weights"; reshard with that version to use it.
+ expert_layout: str = ""
+ #: per_expert: the decoder layers that have an experts file, ascending.
+ expert_layers: Tuple[int, ...] = ()
+ #: per_expert: routed experts per MoE layer (the same in every MoE layer).
+ expert_count: int = 0
+ #: per_expert: stored dense shape of one expert's "gate_up" and "down".
+ expert_shapes: Mapping[str, Tuple[int, ...]] = field(default_factory=dict)
+ #: per_expert under NF4: the spec of "gate_up" and "down". Empty otherwise.
+ expert_quant_specs: Mapping[str, NF4WeightSpec] = field(default_factory=dict)
@dataclass(frozen=True)
@@ -559,6 +585,17 @@ def layer_paths(shard_dir: str, index: "ShardIndex") -> List[str]:
return [layer_shard_path(dirs[root], idx) for idx, root in enumerate(placement)]
+def expert_paths(shard_dir: str, index: "ShardIndex") -> Dict[int, str]:
+ """Decoder layer -> its experts file, beside the layer's own file (same root)."""
+ if getattr(index, "expert_layout", "") != EXPERT_LAYOUT_PER_EXPERT:
+ return {}
+ paths = layer_paths(shard_dir, index)
+ return {
+ layer: os.path.join(os.path.dirname(paths[layer]), expert_shard_name(layer))
+ for layer in index.expert_layers
+ }
+
+
def _same_roots(first: Sequence[str], second: Sequence[str]) -> bool:
"""Equal as folders, not as strings: case and a trailing separator differ on Windows."""
@@ -650,6 +687,28 @@ def read_shard_index(out_dir: str, *, index_name: str = _INDEX_NAME) -> ShardInd
raise ValueError("stripe_roots are set but layer_roots is empty")
if any(not 0 <= root <= len(stripe_roots) for root in layer_roots):
raise ValueError("layer_roots names a root the index does not have")
+ expert_layout = str(payload.get("expert_layout", ""))
+ if expert_layout not in ("", EXPERT_LAYOUT_PER_EXPERT):
+ raise ValueError(f"unknown expert_layout {expert_layout!r}")
+ expert_layers = tuple(int(layer) for layer in (payload.get("expert_layers") or ()))
+ if list(expert_layers) != sorted(set(expert_layers)) or any(
+ not 0 <= layer < n_layers for layer in expert_layers
+ ):
+ raise ValueError("expert_layers must be distinct ascending decoder layer indices")
+ expert_count = int(payload.get("expert_count", 0))
+ expert_shapes = {
+ str(part): tuple(int(dim) for dim in shape)
+ for part, shape in (payload.get("expert_shapes") or {}).items()
+ }
+ if bool(expert_layers) != (expert_layout == EXPERT_LAYOUT_PER_EXPERT) or (
+ expert_layers
+ and (
+ not 1 <= expert_count <= 4096
+ or set(expert_shapes) != {"gate_up", "down"}
+ or any(len(shape) != 2 or min(shape) < 1 for shape in expert_shapes.values())
+ )
+ ):
+ raise ValueError("the index's expert fields do not describe one layout")
return ShardIndex(
n_layers=n_layers,
layer_keys=tuple(payload["layer_keys"]),
@@ -678,6 +737,14 @@ def read_shard_index(out_dir: str, *, index_name: str = _INDEX_NAME) -> ShardInd
external_mode=str(payload.get("external_mode", "")),
stripe_roots=stripe_roots,
layer_roots=layer_roots,
+ expert_layout=expert_layout,
+ expert_layers=expert_layers,
+ expert_count=expert_count,
+ expert_shapes=expert_shapes,
+ expert_quant_specs={
+ str(part): NF4WeightSpec.from_json(value)
+ for part, value in (payload.get("expert_quant_specs") or {}).items()
+ },
)
@@ -960,6 +1027,13 @@ def _atomic_write_index(index: ShardIndex, out_dir: str) -> None:
payload["quant_specs"] = {
key: spec.to_json() for key, spec in index.quant_specs.items()
}
+ payload["expert_layers"] = list(index.expert_layers)
+ payload["expert_shapes"] = {
+ part: list(shape) for part, shape in index.expert_shapes.items()
+ }
+ payload["expert_quant_specs"] = {
+ part: spec.to_json() for part, spec in index.expert_quant_specs.items()
+ }
path = os.path.join(out_dir, _INDEX_NAME)
fd, tmp = tempfile.mkstemp(prefix=".soup.", suffix=".tmp", dir=out_dir)
try:
@@ -1019,6 +1093,7 @@ def inspect_shard_cache(
quant_device: str,
external_mode: str = "",
stripe_roots: Sequence[str] = (),
+ expert_layout: str = "",
) -> Tuple[Optional[ShardIndex], str]:
"""Return a reusable index or the precise reason it must be rewritten.
@@ -1055,6 +1130,11 @@ def inspect_shard_cache(
f"external tensor policy changed ({index.external_mode!r} -> "
f"{external_mode!r})"
)
+ if index.expert_layout != expert_layout:
+ return None, (
+ f"expert layout changed ({index.expert_layout or 'fused'!r} -> "
+ f"{expert_layout or 'fused'!r})"
+ )
if index.format_version != _SHARD_FORMAT_VERSION:
return None, (
f"shard format changed "
@@ -1091,7 +1171,7 @@ def inspect_shard_cache(
path = large_shard_path(out_dir, key)
if not os.path.exists(path):
return None, f"cached shard {os.path.basename(path)!r} is missing"
- for path in layer_paths(out_dir, index):
+ for path in [*layer_paths(out_dir, index), *expert_paths(out_dir, index).values()]:
if not os.path.exists(path):
if os.path.dirname(path) == out_dir:
return None, f"cached shard {os.path.basename(path)!r} is missing"
@@ -1108,6 +1188,7 @@ def _content_change_requires_index_quarantine(
double_quant: bool,
quant_device: str,
external_mode: str,
+ expert_layout: str = "",
) -> bool:
"""Return whether the next write could make the current index describe wrong bytes."""
try:
@@ -1122,6 +1203,7 @@ def _content_change_requires_index_quarantine(
index.quant != QUANT_NONE and index.quant_device != quant_device,
index.source_fingerprint != fingerprint,
index.external_mode != external_mode,
+ index.expert_layout != expert_layout,
index.format_version != _SHARD_FORMAT_VERSION,
)
)
@@ -1248,6 +1330,7 @@ def shard_checkpoint(
notify: Optional[Callable[[str], None]] = None,
stripe_roots: Sequence[str] = (),
num_hidden_layers: Optional[int] = None,
+ expert_layout: str = "",
) -> ShardIndex:
"""Rewrite an HF checkpoint into per-layer safetensors shards.
@@ -1272,7 +1355,22 @@ def shard_checkpoint(
For ``deepseek_v3``, ``num_hidden_layers`` (the config's value) drops the
multi-token-prediction layers a DeepSeek-V3 / Kimi K2 checkpoint stores
past the last decoder layer; transformers ignores them on load too.
+
+ ``expert_layout="per_expert"`` (stacked-expert architectures only) writes a
+ MoE layer's routed experts to ``experts_NNN.safetensors`` beside its layer
+ file, one ``(gate_up, down)`` pair per expert, NF4-quantised per matrix
+ under ``quant='nf4'``; the layer file then holds only the dense part.
"""
+ if expert_layout not in ("", EXPERT_LAYOUT_PER_EXPERT):
+ raise ValueError(
+ f"unsupported expert_layout {expert_layout!r}; supported: "
+ f"'' (fused) or {EXPERT_LAYOUT_PER_EXPERT!r}"
+ )
+ if expert_layout and arch not in _PER_EXPERT_LAYOUT_ARCHS:
+ raise ValueError(
+ f"expert_layout={expert_layout!r} is gated on resident parity per "
+ f"architecture; admitted: {', '.join(_PER_EXPERT_LAYOUT_ARCHS)}; got arch={arch!r}"
+ )
if dtype not in _SUPPORTED_DTYPES:
raise ValueError(
f"unsupported dtype {dtype!r} for layer streaming; "
@@ -1345,6 +1443,7 @@ def shard_checkpoint(
device_kind,
external_mode,
stripe_roots=stripe,
+ expert_layout=expert_layout,
)
if cached is not None:
if notify is not None:
@@ -1365,6 +1464,7 @@ def shard_checkpoint(
double_quant=double_quant,
quant_device=device_kind,
external_mode=external_mode,
+ expert_layout=expert_layout,
):
_quarantine_shard_index(resolved_out)
@@ -1452,6 +1552,11 @@ def shard_checkpoint(
if (match := _LAYER_RE.match(key)) is not None
}
+ if expert_layout and not any(_PER_EXPERT_RE.match(key) for key in where):
+ raise ValueError(
+ f"expert_layout={expert_layout!r} found no per-expert routed weights "
+ f"(model.layers.N.mlp.experts.E.*) in {weights_dir} to split"
+ )
if drop_extra_layers:
# DeepSeek-V3 / Kimi K2 store the multi-token-prediction module as the
# layer(s) after the last decoder layer (``model.layers.61.*`` of 61).
@@ -1597,6 +1702,8 @@ def shard_checkpoint(
# Collected here, deleted only after the new index commits — see the comment beside the
# deletion below for why.
stale_root0_copies: List[str] = []
+ expert_layers_written: List[int] = []
+ expert_meta: Optional[Tuple[int, Dict[str, Any], Dict[str, Any]]] = None
# At most _MAX_LIVE_SOURCE_HANDLES source files are mapped at once (#926);
# a failed open, or a raise anywhere below, still releases the live ones.
with _SourceHandles(shards, safe_open) as handles:
@@ -1604,6 +1711,7 @@ def shard_checkpoint(
prefix = f"model.layers.{idx}."
blob = {}
stacked_experts: Dict[str, Dict[int, Tuple[str, str]]] = {}
+ per_expert_ids: List[int] = []
oq_experts: Dict[str, str] = {}
for key, location in where.items():
if not key.startswith(prefix):
@@ -1681,6 +1789,10 @@ def shard_checkpoint(
path, source_key = stacked_experts[projection][expert]
return _read_tensor(handles[path], source_key, dtype)
+ if expert_layout == EXPERT_LAYOUT_PER_EXPERT:
+ # Written after the layer file, in its root (below).
+ per_expert_ids = expert_ids
+ expert_ids = []
gate_up = []
down = []
for expert in expert_ids:
@@ -1695,8 +1807,9 @@ def shard_checkpoint(
f"{expert_label} layer {idx} contains both packed and "
"per-expert weights"
)
- blob["mlp.experts.gate_up_proj"] = torch.stack(gate_up, dim=0)
- blob["mlp.experts.down_proj"] = torch.stack(down, dim=0)
+ if gate_up:
+ blob["mlp.experts.gate_up_proj"] = torch.stack(gate_up, dim=0)
+ blob["mlp.experts.down_proj"] = torch.stack(down, dim=0)
if oq_experts:
import torch
@@ -1778,6 +1891,35 @@ def shard_checkpoint(
f"Free space on that drive, or name another folder in {STRIPE_DIRS_ENV} "
f"(unset it to shard to one root).",
) from exc
+ if per_expert_ids:
+ import torch
+
+ def _expert_pairs(ids=per_expert_ids, read=_expert_tensor):
+ for expert in ids:
+ gate = read("gate_proj", expert)
+ gate_up_one = torch.cat((gate, read("up_proj", expert)))
+ yield gate_up_one, read("down_proj", expert)
+
+ info = write_expert_shard(
+ os.path.join(shard_dirs[root], expert_shard_name(idx)),
+ _expert_pairs(),
+ quantise=quantise,
+ double_quant=double_quant,
+ device=device,
+ )
+ if quantise:
+ tables.observe(f"{prefix}mlp.experts", *info.codes)
+ described = (info.count, dict(info.shapes), dict(info.quant_specs))
+ if expert_meta is None:
+ expert_meta = described
+ elif expert_meta != described:
+ raise ValueError(
+ f"{expert_label} layer {idx} experts differ from the first MoE "
+ f"layer's ({described[:2]} vs {expert_meta[:2]}); one expert layout "
+ f"serves every layer"
+ )
+ expert_layers_written.append(idx)
+ total_params += info.total_params
if root:
# A copy of this layer from an earlier one-root layout is now stale. It is
# Soup's own file inside the contained primary root, so it WILL go — but not
@@ -1790,6 +1932,11 @@ def shard_checkpoint(
stale = layer_shard_path(resolved_out, idx)
if os.path.exists(stale):
stale_root0_copies.append(stale)
+ # An experts file the new index will not name (an earlier per_expert
+ # layout, or one now written to a stripe root) goes the same way.
+ stale_experts = os.path.join(resolved_out, expert_shard_name(idx))
+ if (not per_expert_ids or root) and os.path.exists(stale_experts):
+ stale_root0_copies.append(stale_experts)
del blob
extras = {}
@@ -1865,6 +2012,11 @@ def shard_checkpoint(
external_mode=external_mode,
stripe_roots=stripe,
layer_roots=layer_roots,
+ expert_layout=expert_layout,
+ expert_layers=tuple(expert_layers_written),
+ expert_count=expert_meta[0] if expert_meta else 0,
+ expert_shapes=expert_meta[1] if expert_meta else {},
+ expert_quant_specs=expert_meta[2] if expert_meta else {},
)
_atomic_write_index(index, resolved_out)
resharding_index = os.path.join(resolved_out, _RESHARDING_INDEX_NAME)
@@ -1929,6 +2081,7 @@ def shard_cache_disk_bytes(shard_dir: str, index: ShardIndex) -> Optional[int]:
paths = [os.path.join(shard_dir, _INDEX_NAME), extras_shard_path(shard_dir)]
paths.extend(large_shard_path(shard_dir, key) for key in index.large_keys)
paths.extend(layer_paths(shard_dir, index))
+ paths.extend(expert_paths(shard_dir, index).values())
try:
return sum(os.path.getsize(path) for path in paths)
except (OSError, ValueError):
@@ -1980,7 +2133,8 @@ def _notify_unindexed_cache_files(
from soup_cli.utils.terminal import for_terminal
expected = {
- os.path.normcase(os.path.realpath(path)) for path in layer_paths(out_dir, index)
+ os.path.normcase(os.path.realpath(path))
+ for path in [*layer_paths(out_dir, index), *expert_paths(out_dir, index).values()]
}
directories = stripe_dirs(out_dir, index.stripe_roots)
for position, directory in enumerate(directories):
@@ -1994,7 +2148,10 @@ def _notify_unindexed_cache_files(
continue
for entry in entries:
if not (
- (entry.name.startswith("layer_") and entry.name.endswith(".safetensors"))
+ (
+ entry.name.startswith(("layer_", "experts_"))
+ and entry.name.endswith(".safetensors")
+ )
or (entry.name.startswith(".soup.") and entry.name.endswith(".tmp"))
):
continue
diff --git a/src/soup_cli/utils/layer_stream_runtime.py b/src/soup_cli/utils/layer_stream_runtime.py
index 8b2f5b33..11651675 100644
--- a/src/soup_cli/utils/layer_stream_runtime.py
+++ b/src/soup_cli/utils/layer_stream_runtime.py
@@ -2870,6 +2870,8 @@ class StreamRuntime:
external_sources: Tuple[Any, ...] = ()
#: training.stream_nf4_scale_cache — the layers' shared NF4ScaleCache, or None.
scale_cache: Any = None
+ #: Per MoE layer, the reader of its experts file (expert_layout "per_expert").
+ expert_readers: Tuple[Any, ...] = ()
def close(self) -> None:
"""Release the weight source and detach the prefetch hook.
@@ -2881,13 +2883,18 @@ class StreamRuntime:
mapping charges Windows commit for the file's whole size (#926).
A no-op for the RAM tier, which owns neither a thread nor handles.
"""
- source_close = getattr(self.source, "close", None)
- if callable(source_close):
- source_close()
- for external in self.external_sources:
- external_close = getattr(external, "close", None)
- if callable(external_close):
- external_close()
+ try:
+ source_close = getattr(self.source, "close", None)
+ if callable(source_close):
+ source_close()
+ for external in self.external_sources:
+ external_close = getattr(external, "close", None)
+ if callable(external_close):
+ external_close()
+ finally:
+ # One open handle per MoE layer's experts file (expert_layout "per_expert").
+ for reader in self.expert_readers:
+ reader.close()
if self.hook is not None:
self.hook.remove()
self.hook = None
@@ -2920,6 +2927,8 @@ class StreamRuntime:
"device": self.device,
"total_params": self.total_params,
"nf4_scale_cache_bytes": getattr(self.scale_cache, "nbytes", 0),
+ "expert_fetches": sum(reader.fetches for reader in self.expert_readers),
+ "expert_bytes_read": sum(reader.bytes_read for reader in self.expert_readers),
}
@@ -3000,6 +3009,48 @@ def _load_layer_buffers(
return loaded
+def _install_expert_streaming(
+ layers: Any,
+ shard_dir: str,
+ index: Any,
+ *,
+ device: str,
+ codes: Optional[Mapping[str, Any]],
+) -> Tuple[Any, ...]:
+ """Swap each MoE layer's experts module for a ``StreamedExperts``.
+
+ Only for a cache sharded with ``expert_layout="per_expert"``; returns the
+ experts-file readers (closed by ``StreamRuntime.close``).
+ """
+ from soup_cli.utils.expert_stream import (
+ EXPERT_LAYOUT_PER_EXPERT,
+ ExpertFetcher,
+ ExpertShardReader,
+ install_expert_streaming,
+ )
+ from soup_cli.utils.layer_shard import expert_paths
+
+ if getattr(index, "expert_layout", "") != EXPERT_LAYOUT_PER_EXPERT:
+ return ()
+ readers: Dict[int, Any] = {}
+ try:
+ for layer, path in expert_paths(shard_dir, index).items():
+ readers[layer] = ExpertShardReader(
+ path,
+ count=index.expert_count,
+ shapes=index.expert_shapes,
+ quant_specs=index.expert_quant_specs,
+ dtype=index.dtype,
+ )
+ fetcher = ExpertFetcher(device=device, dtype=index.dtype, codes=codes)
+ install_expert_streaming(layers, readers, fetcher)
+ except BaseException:
+ for reader in readers.values():
+ reader.close()
+ raise
+ return tuple(readers.values())
+
+
def install_streaming(
model: Any,
*,
@@ -3088,13 +3139,18 @@ def install_streaming(
f"{index.n_layers} — reshard the checkpoint"
)
+ _require_stripe_folders(shard_dir, index)
+ # Before the name maps: the fused expert parameters leave the layer here,
+ # so the layer pool never allocates them.
+ expert_readers = _install_expert_streaming(
+ layers, shard_dir, index, device=str(device), codes=codes
+ )
layer_name_maps = [_layer_name_map(layer) for layer in layers]
if not any(layer_name_maps):
raise RuntimeError(
"no meta decoder weights found — the base was materialised, which "
"defeats layer streaming entirely"
)
- _require_stripe_folders(shard_dir, index)
decoder_paths = layer_paths(shard_dir, index)
layer_specs = RamSource.layer_specs_from_paths(decoder_paths)
large_specs = large_layer_specs(shard_dir, index)
@@ -3284,6 +3340,7 @@ def install_streaming(
large_pool=large_pool,
hook=handle,
total_params=int(getattr(index, "total_params", 0) or 0),
+ expert_readers=expert_readers,
tier=tier,
scale_cache=scale_cache,
)
diff --git a/tests/test_expert_stream.py b/tests/test_expert_stream.py
new file mode 100644
index 00000000..dd78a54a
--- /dev/null
+++ b/tests/test_expert_stream.py
@@ -0,0 +1,947 @@
+"""Expert-granularity streaming (``utils/expert_stream.py``).
+
+The gate is bit-exactness against transformers' eager experts loop: the
+streamed module must equal the resident one forward AND backward, on the
+block alone and inside a streamed DeepSeek-V3 model.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+CUDA = pytest.mark.gpu(reason="NF4 dequantisation needs bitsandbytes on CUDA")
+
+
+# --------------------------------------------------------------------------
+# block level
+# --------------------------------------------------------------------------
+def _deepseek_v3_experts(seed):
+ import torch
+ from transformers import DeepseekV3Config
+ from transformers.models.deepseek_v3.modeling_deepseek_v3 import DeepseekV3Experts
+
+ config = DeepseekV3Config(
+ hidden_size=32, moe_intermediate_size=16, n_routed_experts=8, n_group=2,
+ topk_group=1, num_experts_per_tok=2,
+ )
+ config._experts_implementation = "eager"
+ torch.manual_seed(seed)
+ module = DeepseekV3Experts(config)
+ with torch.no_grad():
+ module.gate_up_proj.normal_(0.0, 0.2)
+ module.down_proj.normal_(0.0, 0.2)
+ module.requires_grad_(False)
+ return module, 8, 2
+
+
+def _olmoe_experts(seed):
+ import torch
+ from transformers import OlmoeConfig
+ from transformers.models.olmoe.modeling_olmoe import OlmoeExperts
+
+ config = OlmoeConfig(hidden_size=32, intermediate_size=16, num_experts=8, num_experts_per_tok=2)
+ config._experts_implementation = "eager"
+ torch.manual_seed(seed)
+ module = OlmoeExperts(config)
+ with torch.no_grad():
+ module.gate_up_proj.normal_(0.0, 0.2)
+ module.down_proj.normal_(0.0, 0.2)
+ module.requires_grad_(False)
+ return module, 8, 2
+
+
+def _streamed_copy(tmp_path, module, n_experts):
+ from soup_cli.utils.expert_stream import (
+ ExpertFetcher,
+ ExpertShardReader,
+ streamed_experts_class,
+ write_expert_shard,
+ )
+
+ path = str(tmp_path / "experts_001.safetensors")
+ pairs = (
+ (module.gate_up_proj[e].detach(), module.down_proj[e].detach())
+ for e in range(n_experts)
+ )
+ info = write_expert_shard(path, pairs, quantise=False)
+ reader = ExpertShardReader(
+ path, count=info.count, shapes=info.shapes, quant_specs={}, dtype="float32"
+ )
+ streamed = streamed_experts_class()(
+ reader, ExpertFetcher(device="cpu", dtype="float32"), module.act_fn, 1
+ )
+ return streamed, reader
+
+
+def _routing(n_tokens, n_experts, top_k, hidden, seed):
+ import torch
+
+ generator = torch.Generator().manual_seed(seed)
+ scores = torch.rand(n_tokens, n_experts, generator=generator)
+ top_k_index = scores.topk(top_k, dim=-1).indices
+ top_k_weights = torch.rand(n_tokens, top_k, generator=generator).requires_grad_(True)
+ states = torch.randn(n_tokens, hidden, generator=generator).requires_grad_(True)
+ grad_out = torch.randn(n_tokens, hidden, generator=generator)
+ return states, top_k_index, top_k_weights, grad_out
+
+
+ "build", [_deepseek_v3_experts, _olmoe_experts], ids=["deepseek_v3", "olmoe"]
+)
+def test_streamed_experts_forward_equals_eager_bit_exactly(tmp_path, build):
+ import torch
+
+ module, n_experts, top_k = build(5)
+ streamed, reader = _streamed_copy(tmp_path, module, n_experts)
+ states, index, weights, _ = _routing(24, n_experts, top_k, 32, 9)
+ with torch.no_grad():
+ want = module(states, index, weights)
+ got = streamed(states, index, weights)
+ assert torch.equal(got, want), (got - want).abs().max().item()
+ reader.close()
+
+
+ "build", [_deepseek_v3_experts, _olmoe_experts], ids=["deepseek_v3", "olmoe"]
+)
+def test_streamed_experts_backward_equals_eager_bit_exactly(tmp_path, build):
+ """Input and routing-weight gradients, the two a frozen expert passes on."""
+ import torch
+
+ module, n_experts, top_k = build(5)
+ streamed, reader = _streamed_copy(tmp_path, module, n_experts)
+ states, index, weights, grad_out = _routing(24, n_experts, top_k, 32, 9)
+
+ module(states, index, weights).backward(grad_out)
+ want_states, want_weights = states.grad.clone(), weights.grad.clone()
+ states.grad = None
+ weights.grad = None
+ streamed(states, index, weights).backward(grad_out)
+
+ assert float(want_states.abs().sum()) > 0.0
+ assert torch.equal(states.grad, want_states), (states.grad - want_states).abs().max().item()
+ assert torch.equal(weights.grad, want_weights)
+ reader.close()
+
+
[email protected]("autocast", [False, True], ids=["fp32-control", "cpu-bf16-autocast"])
+def test_streamed_experts_backward_preserves_forward_autocast(tmp_path, autocast):
+ """Recomputation must differentiate the forward precision after its AMP region exits."""
+ import torch
+
+ module, n_experts, top_k = _deepseek_v3_experts(5)
+ streamed, reader = _streamed_copy(tmp_path, module, n_experts)
+ states, index, weights, grad_out = _routing(24, n_experts, top_k, 32, 9)
+ try:
+ with torch.autocast("cpu", dtype=torch.bfloat16, enabled=autocast):
+ want = module(states, index, weights)
+ want.backward(grad_out)
+ want_states, want_weights = states.grad.clone(), weights.grad.clone()
+ states.grad = None
+ weights.grad = None
+
+ with torch.autocast("cpu", dtype=torch.bfloat16, enabled=autocast):
+ got = streamed(states, index, weights)
+ got.backward(grad_out)
+
+ assert torch.equal(got, want)
+ assert float(want_states.abs().sum()) > 0.0
+ assert torch.equal(states.grad, want_states), (states.grad - want_states).abs().max().item()
+ assert torch.equal(weights.grad, want_weights)
+ finally:
+ reader.close()
+
+
+def test_each_routed_expert_is_read_once_forward_and_once_backward(tmp_path):
+ """The cost the docstring states: an expert nobody routed to is never read."""
+ import torch
+
+ module, n_experts, _ = _deepseek_v3_experts(5)
+ streamed, reader = _streamed_copy(tmp_path, module, n_experts)
+ states = torch.randn(6, 32, requires_grad=True)
+ index = torch.tensor([[0, 3]] * 6)
+ weights = torch.full((6, 2), 0.5, requires_grad=True)
+ out = streamed(states, index, weights)
+ assert reader.fetches == 2
+ out.sum().backward()
+ assert reader.fetches == 4
+ reader.close()
+
+
+def test_fetched_weights_are_owned_not_views_of_the_staging_buffer(tmp_path):
+ """Every read lands in one shared staging buffer; a fetch must hand back
+ tensors the next read cannot overwrite (on a CPU target `.to` would not copy)."""
+ import torch
+
+ module, n_experts, _ = _deepseek_v3_experts(5)
+ streamed, reader = _streamed_copy(tmp_path, module, n_experts)
+ first = [tensor.clone() for tensor in streamed.fetch(0)]
+ held = streamed.fetch(0)
+ streamed.fetch(1)
+ assert torch.equal(held[0], first[0]) and torch.equal(held[1], first[1])
+ assert not torch.equal(first[0], module.gate_up_proj[1])
+ reader.close()
+
+
+def test_expert_weights_are_released_after_each_expert(tmp_path):
+ """The VRAM bound: nothing keeps a fetched expert alive once its MLP ran, not
+ the autograd graph after forward, not anything after backward."""
+ import gc
+ import weakref
+
+
+ module, n_experts, top_k = _deepseek_v3_experts(5)
+ streamed, reader = _streamed_copy(tmp_path, module, n_experts)
+ refs = []
+ real_fetch = streamed.fetch
+
+ def tracking_fetch(expert):
+ gate_up, down = real_fetch(expert)
+ refs.extend((weakref.ref(gate_up), weakref.ref(down)))
+ return gate_up, down
+
+ streamed.fetch = tracking_fetch
+ states, index, weights, grad_out = _routing(24, n_experts, top_k, 32, 9)
+ out = streamed(states, index, weights)
+ gc.collect()
+ assert refs and all(ref() is None for ref in refs), "forward kept expert weights alive"
+ refs.clear()
+ out.backward(grad_out)
+ gc.collect()
+ assert refs and all(ref() is None for ref in refs), "backward kept expert weights alive"
+ reader.close()
+
+
+def test_reader_direct_and_buffered_reads_agree(tmp_path):
+ import torch
+
+ from soup_cli.utils.expert_stream import (
+ ExpertShardReader,
+ aligned_staging,
+ write_expert_shard,
+ )
+
+ path = str(tmp_path / "experts_001.safetensors")
+ pairs = [(torch.randn(6, 4), torch.randn(4, 3)) for _ in range(3)]
+ info = write_expert_shard(path, pairs, quantise=False)
+ readers = [
+ ExpertShardReader(
+ path, count=3, shapes=info.shapes, quant_specs={}, dtype="float32", direct=direct
+ )
+ for direct in (True, False)
+ ]
+ assert readers[1].direct is False
+ for expert in range(3):
+ views = []
+ for reader in readers:
+ _owner, staging = aligned_staging(reader.max_span)
+ views.append({k: v.clone() for k, v in reader.read_host(expert, staging).items()})
+ assert views[0].keys() == views[1].keys()
+ for key in views[0]:
+ assert torch.equal(views[0][key], views[1][key])
+ assert torch.equal(views[0][f"{expert}.gate_up"], pairs[expert][0])
+ with pytest.raises(IndexError):
+ readers[0].read_host(3, aligned_staging(readers[0].max_span)[1])
+ with pytest.raises(ValueError, match="staging holds"):
+ readers[0].read_host(0, aligned_staging(16)[1])
+ for reader in readers:
+ reader.close()
+
+
[email protected]("expert", [-1, 3, 4])
+def test_read_host_refuses_an_expert_outside_the_file(tmp_path, expert):
+ """-1 would otherwise read the last expert through Python's negative index."""
+ import torch
+
+ from soup_cli.utils.expert_stream import (
+ ExpertShardReader,
+ aligned_staging,
+ write_expert_shard,
+ )
+
+ path = str(tmp_path / "experts_001.safetensors")
+ pairs = [(torch.randn(6, 4), torch.randn(4, 3)) for _ in range(3)]
+ info = write_expert_shard(path, pairs, quantise=False)
+ reader = ExpertShardReader(path, count=3, shapes=info.shapes, quant_specs={}, dtype="float32")
+ with pytest.raises(IndexError, match=r"outside \[0, 3\)"):
+ reader.read_host(expert, aligned_staging(reader.max_span)[1])
+ reader.close()
+
+
+def test_a_reader_holds_no_handle_until_its_first_fetch(tmp_path):
+ """An install that fails after the readers were built must not leave the
+ experts files open (Windows keeps an open file locked until collection)."""
+ import torch
+
+ from soup_cli.utils.expert_stream import (
+ ExpertShardReader,
+ aligned_staging,
+ write_expert_shard,
+ )
+
+ path = str(tmp_path / "experts_001.safetensors")
+ info = write_expert_shard(path, [(torch.zeros(6, 4), torch.zeros(4, 3))], quantise=False)
+ reader = ExpertShardReader(path, count=1, shapes=info.shapes, quant_specs={}, dtype="float32")
+ assert reader._handle is None
+ staging = aligned_staging(reader.max_span)[1]
+ reader.read_host(0, staging)
+ first = reader._handle
+ assert first is not None
+ reader.read_host(0, staging)
+ # One handle for the reader's life: a reopen per fetch would leak the last one.
+ assert reader._handle is first
+ reader.close()
+ assert reader._handle is None
+
+
+def test_a_file_replaced_after_the_header_was_read_is_refused_at_first_fetch(tmp_path):
+ import os
+
+ import torch
+
+ from soup_cli.utils.expert_stream import (
+ ExpertShardReader,
+ aligned_staging,
+ write_expert_shard,
+ )
+
+ path = str(tmp_path / "experts_001.safetensors")
+ info = write_expert_shard(path, [(torch.zeros(6, 4), torch.zeros(4, 3))], quantise=False)
+ reader = ExpertShardReader(path, count=1, shapes=info.shapes, quant_specs={}, dtype="float32")
+ replacement = str(tmp_path / "other.safetensors")
+ write_expert_shard(replacement, [(torch.ones(6, 4), torch.ones(4, 3))], quantise=False)
+ os.replace(replacement, path)
+ with pytest.raises(ValueError, match="changed on disk since its header was read"):
+ reader.read_host(0, aligned_staging(reader.max_span)[1])
+ assert reader._handle is None
+
+
+def test_install_refuses_mismatched_layers_and_expert_adapters(tmp_path):
+ import torch.nn as nn
+
+ from soup_cli.utils.expert_stream import ExpertFetcher, install_expert_streaming
+
+ module, n_experts, _ = _deepseek_v3_experts(5)
+ _, reader = _streamed_copy(tmp_path, module, n_experts)
+ fetcher = ExpertFetcher(device="cpu", dtype="float32")
+ with pytest.raises(ValueError, match="no experts file for it"):
+ install_expert_streaming([_holder(module)], {}, fetcher)
+ with pytest.raises(ValueError, match="which has no routed-experts module"):
+ install_expert_streaming([nn.Module()], {0: reader}, fetcher)
+ adapted = _holder(module)
+ adapted.mlp.experts.lora_A = nn.Parameter(module.gate_up_proj.new_zeros(2, 2))
+ with pytest.raises(ValueError, match="adapters on the routed experts"):
+ install_expert_streaming([adapted], {0: reader}, fetcher)
+ reader.close()
+
+
+ ("field", "value", "match"),
+ [
+ ("expert_layout", "experts", "unknown expert_layout"),
+ ("expert_layers", [2, 1], "distinct ascending"),
+ ("expert_layers", [9], "distinct ascending"),
+ ("expert_count", 5000, "do not describe one layout"),
+ ("expert_shapes", {"gate_up": [64, 0], "down": [64, 32]}, "do not describe one layout"),
+ ],
+)
+def test_read_shard_index_refuses_a_malformed_expert_layout(tmp_path, field, value, match):
+ import json
+
+ from soup_cli.utils.layer_shard import read_shard_index
+
+ weights, _ = _tiny_deepseek_v3(tmp_path)
+ _shard(tmp_path, weights, expert_layout="per_expert")
+ path = tmp_path / "shards" / "index.json"
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ payload[field] = value
+ path.write_text(json.dumps(payload), encoding="utf-8")
+ with pytest.raises(ValueError, match=match):
+ read_shard_index(str(tmp_path / "shards"))
+
+
+def test_missing_experts_file_is_a_cache_miss(tmp_path):
+ import os
+
+ from soup_cli.utils.layer_shard import expert_paths, inspect_shard_cache
+
+ weights, _ = _tiny_deepseek_v3(tmp_path)
+ index = _shard(tmp_path, weights, expert_layout="per_expert")
+ os.remove(expert_paths(str(tmp_path / "shards"), index)[2])
+ cached, reason = inspect_shard_cache(
+ str(tmp_path / "shards"), "float32", index.source_fingerprint, index.source_files,
+ "none", False, "", "", stripe_roots=(), expert_layout="per_expert",
+ )
+ assert cached is None and "experts_002.safetensors" in reason
+
+
+def test_resharding_to_the_fused_layout_removes_the_experts_files(tmp_path):
+ import os
+
+ from soup_cli.utils.layer_shard import shard_cache_disk_bytes
+
+ weights, _ = _tiny_deepseek_v3(tmp_path)
+ per_expert = _shard(tmp_path, weights, expert_layout="per_expert")
+ shards = tmp_path / "shards"
+ assert shard_cache_disk_bytes(str(shards), per_expert) > sum(
+ os.path.getsize(path) for path in shards.glob("layer_*.safetensors")
+ )
+ fused = _shard(tmp_path, weights)
+ assert fused.expert_layout == ""
+ assert not list(shards.glob("experts_*.safetensors"))
+
+
+def test_per_expert_layout_refuses_a_checkpoint_without_per_expert_keys_before_writing(tmp_path):
+ import torch
+ from safetensors.torch import save_file
+
+ from soup_cli.utils.layer_shard import shard_checkpoint
+
+ weights = tmp_path / "w"
+ weights.mkdir()
+ save_file(
+ {
+ "model.embed_tokens.weight": torch.zeros(8, 4),
+ "model.layers.0.mlp.experts.gate_up_proj": torch.zeros(2, 6, 4),
+ "model.layers.0.mlp.experts.down_proj": torch.zeros(2, 4, 3),
+ },
+ str(weights / "model.safetensors"),
+ )
+ with pytest.raises(ValueError, match="found no per-expert routed weights"):
+ shard_checkpoint(
+ str(weights), str(tmp_path / "s"), dtype="float32", arch="deepseek_v3",
+ expert_layout="per_expert",
+ )
+ assert not list((tmp_path / "s").glob("layer_*.safetensors"))
+
+
+# --------------------------------------------------------------------------
+# experts file + reader
+# --------------------------------------------------------------------------
+def test_expert_shard_stores_gate_rows_before_up_rows(tmp_path):
+ import torch
+ from safetensors.torch import load_file
+
+ from soup_cli.utils.expert_stream import write_expert_shard
+
+ gate_up = torch.cat((torch.full((3, 4), 1.0), torch.full((3, 4), 2.0)))
+ down = torch.full((4, 3), 3.0)
+ path = str(tmp_path / "experts_001.safetensors")
+ info = write_expert_shard(path, [(gate_up, down), (gate_up + 10, down + 10)], quantise=False)
+ stored = load_file(path)
+ assert info.count == 2 and dict(info.shapes) == {"gate_up": (6, 4), "down": (4, 3)}
+ assert torch.equal(stored["1.gate_up"][:3], torch.full((3, 4), 11.0))
+ assert torch.equal(stored["1.down"], torch.full((4, 3), 13.0))
+
+
+def test_expert_shard_refuses_an_inconsistent_expert(tmp_path):
+ import torch
+
+ from soup_cli.utils.expert_stream import write_expert_shard
+
+ good = (torch.zeros(6, 4), torch.zeros(4, 3))
+ bad = (torch.zeros(8, 4), torch.zeros(4, 3))
+ with pytest.raises(ValueError, match="expert 1 gate_up has shape"):
+ write_expert_shard(str(tmp_path / "x.safetensors"), [good, bad], quantise=False)
+
+
+def test_reader_refuses_a_file_missing_an_expert(tmp_path):
+ import torch
+
+ from soup_cli.utils.expert_stream import ExpertShardReader, write_expert_shard
+
+ path = str(tmp_path / "experts_001.safetensors")
+ info = write_expert_shard(path, [(torch.zeros(6, 4), torch.zeros(4, 3))], quantise=False)
+ with pytest.raises(ValueError, match="has no tensor '1.gate_up'"):
+ ExpertShardReader(path, count=2, shapes=info.shapes, quant_specs={}, dtype="float32")
+
+
+def _nf4_spec(shape, nested=False):
+ from soup_cli.utils.layer_shard import NF4WeightSpec
+
+ return NF4WeightSpec(
+ shape=shape, dtype="bfloat16", blocksize=64, quant_type="nf4",
+ nested=nested, nested_blocksize=256 if nested else 0,
+ )
+
+
+def _nf4_file(path, *, packed_bytes, absmax_blocks):
+ """A one-expert NF4 experts file with chosen sidecar sizes (no bitsandbytes)."""
+ import torch
+ from safetensors.torch import save_file
+
+ blob = {}
+ for part, weights in (("gate_up", 6 * 64), ("down", 64 * 3)):
+ n_packed = packed_bytes if part == "gate_up" else weights // 2
+ n_blocks = absmax_blocks if part == "gate_up" else weights // 64
+ blob[f"0.{part}"] = torch.zeros((n_packed, 1), dtype=torch.uint8)
+ blob[f"0.{part}::absmax"] = torch.ones(n_blocks)
+ save_file(blob, str(path))
+ return str(path)
+
+
+def test_reader_accepts_nf4_sidecars_of_exactly_the_spec_size(tmp_path):
+ from soup_cli.utils.expert_stream import ExpertShardReader
+
+ path = _nf4_file(tmp_path / "e.safetensors", packed_bytes=6 * 64 // 2, absmax_blocks=6)
+ specs = {"gate_up": _nf4_spec((6, 64)), "down": _nf4_spec((64, 3))}
+ reader = ExpertShardReader(
+ path, count=1, shapes={"gate_up": (6, 64), "down": (64, 3)},
+ quant_specs=specs, dtype="bfloat16",
+ )
+ reader.close()
+
+
+ ("packed_bytes", "absmax_blocks"), [(16, 6), (6 * 64 // 2, 2)], ids=["packed", "absmax"]
+)
+def test_reader_refuses_nf4_sidecars_smaller_than_the_spec(tmp_path, packed_bytes, absmax_blocks):
+ """The dequantisation reads prod(spec.shape) weights natively without a bounds
+ check, so a header-valid file holding fewer bytes than the spec must be refused
+ before any read (soup-c2's security read of this reader)."""
+ from soup_cli.utils.expert_stream import ExpertShardReader
+
+ path = _nf4_file(
+ tmp_path / "e.safetensors", packed_bytes=packed_bytes, absmax_blocks=absmax_blocks
+ )
+ specs = {"gate_up": _nf4_spec((6, 64)), "down": _nf4_spec((64, 3))}
+ with pytest.raises(ValueError, match="the index expects"):
+ ExpertShardReader(
+ path, count=1, shapes={"gate_up": (6, 64), "down": (64, 3)},
+ quant_specs=specs, dtype="bfloat16",
+ )
+
+
+def test_reader_refuses_an_nf4_spec_that_disagrees_with_the_index_shape(tmp_path):
+ from soup_cli.utils.expert_stream import ExpertShardReader
+
+ path = _nf4_file(tmp_path / "e.safetensors", packed_bytes=6 * 64 // 2, absmax_blocks=6)
+ specs = {"gate_up": _nf4_spec((12, 64)), "down": _nf4_spec((64, 3))}
+ with pytest.raises(ValueError, match="is not the index's"):
+ ExpertShardReader(
+ path, count=1, shapes={"gate_up": (6, 64), "down": (64, 3)},
+ quant_specs=specs, dtype="bfloat16",
+ )
+
+
+def test_reader_refuses_a_dense_dtype_other_than_the_index_dtype(tmp_path):
+ import torch
+
+ from soup_cli.utils.expert_stream import ExpertShardReader, write_expert_shard
+
+ path = str(tmp_path / "experts_001.safetensors")
+ info = write_expert_shard(path, [(torch.zeros(6, 4), torch.zeros(4, 3))], quantise=False)
+ with pytest.raises(ValueError, match="the index expects torch.bfloat16"):
+ ExpertShardReader(path, count=1, shapes=info.shapes, quant_specs={}, dtype="bfloat16")
+
+
+def test_reader_refuses_an_expert_over_the_byte_limit(tmp_path, monkeypatch):
+ import torch
+
+ import soup_cli.utils.expert_stream as expert_stream
+
+ path = str(tmp_path / "experts_001.safetensors")
+ info = expert_stream.write_expert_shard(
+ path, [(torch.zeros(6, 4), torch.zeros(4, 3))], quantise=False
+ )
+ monkeypatch.setattr(expert_stream, "_MAX_EXPERT_BYTES", 1024)
+ with pytest.raises(ValueError, match="over the 1024-byte limit"):
+ expert_stream.ExpertShardReader(
+ path, count=1, shapes=info.shapes, quant_specs={}, dtype="float32"
+ )
+
+
+def test_reader_refuses_a_file_swapped_while_it_opens(tmp_path, monkeypatch):
+ """The header is read through the identity of the handle the reads use."""
+ import dataclasses
+
+ import torch
+
+ import soup_cli.utils.safetensors_reader as safetensors_reader
+ from soup_cli.utils.expert_stream import ExpertShardReader, write_expert_shard
+
+ path = str(tmp_path / "experts_001.safetensors")
+ info = write_expert_shard(path, [(torch.zeros(6, 4), torch.zeros(4, 3))], quantise=False)
+ real = safetensors_reader.read_header_with_identity
+
+ def swapped(target):
+ header, identity = real(target)
+ return header, dataclasses.replace(identity, mtime_ns=identity.mtime_ns + 1)
+
+ monkeypatch.setattr(safetensors_reader, "read_header_with_identity", swapped)
+ with pytest.raises(ValueError, match="changed while it was being opened"):
+ ExpertShardReader(path, count=1, shapes=info.shapes, quant_specs={}, dtype="float32")
+
+
+def test_reader_refuses_a_file_with_more_experts_than_the_index(tmp_path):
+ import torch
+
+ from soup_cli.utils.expert_stream import ExpertShardReader, write_expert_shard
+
+ path = str(tmp_path / "experts_001.safetensors")
+ pair = (torch.zeros(6, 4), torch.zeros(4, 3))
+ info = write_expert_shard(path, [pair, (pair[0] + 1, pair[1] + 1)], quantise=False)
+ with pytest.raises(ValueError, match="holds more than 1 experts"):
+ ExpertShardReader(path, count=1, shapes=info.shapes, quant_specs={}, dtype="float32")
+
+
+# --------------------------------------------------------------------------
+# a whole streamed DeepSeek-V3 with per-expert layout vs the resident model
+# --------------------------------------------------------------------------
+def _tiny_deepseek_v3(tmp_path):
+ import torch
+ from transformers import DeepseekV3Config, DeepseekV3ForCausalLM
+
+ torch.manual_seed(11)
+ config = DeepseekV3Config(
+ 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=2,
+ 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=128,
+ )
+ model = DeepseekV3ForCausalLM(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))
+ weights = tmp_path / "model"
+ model.save_pretrained(str(weights))
+ # The streamed experts follow the eager loop; the resident control must too.
+ model.set_experts_implementation("eager")
+ return str(weights), model
+
+
+def _lora():
+ from peft import LoraConfig, TaskType
+
+ return LoraConfig(
+ r=4, lora_alpha=8, lora_dropout=0.0, bias="none",
+ target_modules=["q_b_proj", "kv_b_proj", "o_proj"], task_type=TaskType.CAUSAL_LM,
+ )
+
+
+def _shard(tmp_path, weights, **kwargs):
+ from soup_cli.utils.layer_shard import shard_checkpoint
+
+ return shard_checkpoint(
+ weights, str(tmp_path / "shards"), dtype="float32", arch="deepseek_v3",
+ num_hidden_layers=3, **kwargs,
+ )
+
+
+def _paired(tmp_path):
+ import torch
+ from peft import get_peft_model
+
+ from soup_cli.utils.layer_stream_runtime import build_streamed_model
+
+ weights, resident = _tiny_deepseek_v3(tmp_path)
+ index = _shard(tmp_path, weights, expert_layout="per_expert")
+ model, runtime = build_streamed_model(
+ model_id=weights, shard_dir=str(tmp_path / "shards"), index=index,
+ lora_config=_lora(), device="cpu", dtype="float32", buffers=2, pin=False, seed=3,
+ )
+ ref = get_peft_model(resident, _lora())
+ 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 ref.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()
+ ref.eval()
+ ids = torch.randint(0, 128, (2, 12), generator=generator)
+ return model, runtime, ref, ids, index
+
+
+def test_per_expert_layout_moves_routed_experts_out_of_the_layer_file(tmp_path):
+ from safetensors.torch import load_file
+
+ from soup_cli.utils.layer_shard import expert_paths, layer_paths, read_shard_index
+
+ weights, _ = _tiny_deepseek_v3(tmp_path)
+ index = _shard(tmp_path, weights, expert_layout="per_expert")
+ assert index.expert_layout == "per_expert"
+ assert index.expert_layers == (1, 2)
+ assert index.expert_count == 8
+ assert dict(index.expert_shapes) == {"gate_up": (64, 64), "down": (64, 32)}
+ assert read_shard_index(str(tmp_path / "shards")) == index
+ layer_one = load_file(layer_paths(str(tmp_path / "shards"), index)[1])
+ assert not any(key.startswith("mlp.experts") for key in layer_one)
+ assert "mlp.shared_experts.gate_proj.weight" in layer_one
+ assert set(expert_paths(str(tmp_path / "shards"), index)) == {1, 2}
+
+
+def test_streamed_per_expert_forward_matches_resident_eager_bit_exactly(tmp_path):
+ import torch
+
+ model, runtime, ref, ids, _ = _paired(tmp_path)
+ with torch.no_grad():
+ got = model(input_ids=ids, labels=ids)
+ want = ref(input_ids=ids, labels=ids)
+ assert torch.equal(got.logits, want.logits), (got.logits - want.logits).abs().max().item()
+ assert torch.equal(got.loss, want.loss)
+ assert runtime.stats()["expert_fetches"] > 0
+ assert runtime.expert_readers
+ assert all(reader._handle is not None for reader in runtime.expert_readers)
+ runtime.close()
+ # Closing the runtime releases every experts file (Windows keeps an open file locked).
+ assert all(reader._handle is None for reader in runtime.expert_readers)
+
+
+def test_streamed_per_expert_backward_matches_resident_lora_gradients(tmp_path):
+ import torch
+
+ from soup_cli.utils.layer_stream_runtime import canonical_named_parameters
+
+ model, runtime, ref, ids, _ = _paired(tmp_path)
+ loss = model(input_ids=ids, labels=ids).loss
+ forward_reads = runtime.stats()["expert_fetches"]
+ loss.backward()
+ # Under the checkpointed decoder layer a routed expert is read three times:
+ # forward, the checkpoint's recompute, and the expert's own backward.
+ assert runtime.stats()["expert_fetches"] == 3 * forward_reads > 0
+ ref(input_ids=ids, labels=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(model), grads(ref)
+ assert streamed and set(streamed) == set(resident)
+ # Layer 0's adapters sit below both MoE layers: their gradient crossed
+ # every streamed expert's backward.
+ assert any(".layers.0." in name and float(g.abs().sum()) > 0 for name, g in streamed.items())
+ for name, gradient in streamed.items():
+ assert torch.equal(gradient, resident[name]), name
+ runtime.close()
+
+
+def test_layout_change_is_a_cache_miss_naming_the_layout(tmp_path):
+ from soup_cli.utils.layer_shard import inspect_shard_cache
+
+ weights, _ = _tiny_deepseek_v3(tmp_path)
+ index = _shard(tmp_path, weights, expert_layout="per_expert")
+ cached, reason = inspect_shard_cache(
+ str(tmp_path / "shards"), "float32", index.source_fingerprint, index.source_files,
+ "none", False, "", "", stripe_roots=(), expert_layout="",
+ )
+ assert cached is None
+ assert "expert layout changed" in reason
+ reused = _shard(tmp_path, weights, expert_layout="per_expert")
+ assert reused == index
+
+
+def test_per_expert_layout_is_refused_for_an_unadmitted_arch(tmp_path):
+ from soup_cli.utils.layer_shard import shard_checkpoint
+
+ with pytest.raises(ValueError, match="admitted: deepseek_v3"):
+ shard_checkpoint(
+ str(tmp_path), str(tmp_path / "s"), dtype="float32", arch="qwen4_exp",
+ expert_layout="per_expert",
+ )
+
+
+def test_unknown_expert_layout_is_refused(tmp_path):
+ from soup_cli.utils.layer_shard import shard_checkpoint
+
+ with pytest.raises(ValueError, match="unsupported expert_layout"):
+ shard_checkpoint(
+ str(tmp_path), str(tmp_path / "s"), dtype="float32", arch="deepseek_v3",
+ expert_layout="experts",
+ )
+
+
+def test_install_refuses_a_model_whose_experts_disagree_with_the_file(tmp_path):
+ from soup_cli.utils.expert_stream import ExpertFetcher, install_expert_streaming
+
+ module, n_experts, _ = _deepseek_v3_experts(5)
+ _, reader = _streamed_copy(tmp_path, module, n_experts)
+ reader.count = 4 # what a stale index would claim
+ holder = _holder(module)
+ with pytest.raises(ValueError, match="reshard the checkpoint"):
+ install_expert_streaming(
+ [holder], {0: reader}, ExpertFetcher(device="cpu", dtype="float32")
+ )
+ reader.close()
+
+
+def _holder(experts):
+ import torch.nn as nn
+
+ class Layer(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.mlp = nn.Module()
+ self.mlp.experts = experts
+
+ return Layer()
+
+
+# --------------------------------------------------------------------------
+# NF4 experts (CUDA)
+# --------------------------------------------------------------------------
+@CUDA
+def test_sharder_writes_nf4_per_expert_files_a_streamed_model_runs_on(tmp_path):
+ """The NF4 path of shard_checkpoint(expert_layout="per_expert") end to end."""
+ pytest.importorskip("bitsandbytes")
+ import torch
+
+ from soup_cli.utils.layer_shard import shard_checkpoint
+ from soup_cli.utils.layer_stream_runtime import (
+ build_meta_skeleton,
+ build_streamed_model,
+ quantised_layer_suffixes,
+ )
+
+ weights, _ = _tiny_deepseek_v3(tmp_path)
+ probe = build_meta_skeleton(weights, dtype="bfloat16", quant="nf4")
+ suffixes = quantised_layer_suffixes(probe)
+ del probe
+ index = shard_checkpoint(
+ weights, str(tmp_path / "shards"), dtype="bfloat16", arch="deepseek_v3", quant="nf4",
+ quant_suffixes=suffixes, quant_device="cuda", num_hidden_layers=3,
+ expert_layout="per_expert",
+ )
+ assert index.expert_quant_specs["gate_up"].nested is True
+ model, runtime = build_streamed_model(
+ model_id=weights, shard_dir=str(tmp_path / "shards"), index=index,
+ lora_config=_lora(), device="cuda", dtype="bfloat16", buffers=2, pin=False,
+ quant="nf4", double_quant=True,
+ )
+ ids = torch.randint(0, 128, (1, 12), generator=torch.Generator().manual_seed(1)).cuda()
+ loss = model(input_ids=ids, labels=ids).loss
+ loss.backward()
+ assert torch.isfinite(loss)
+ assert runtime.stats()["expert_fetches"] > 0
+ runtime.close()
+
+
+@CUDA
+def test_nf4_streamed_experts_equal_the_dequantised_resident_block(tmp_path):
+ pytest.importorskip("bitsandbytes")
+ import torch
+ from bitsandbytes.functional import dequantize_4bit, quantize_4bit
+
+ from soup_cli.utils.expert_stream import (
+ ExpertFetcher,
+ ExpertShardReader,
+ streamed_experts_class,
+ write_expert_shard,
+ )
+ from soup_cli.utils.layer_shard import NF4_CODE_KEY, NF4_NESTED_CODE_KEY
+
+ module, n_experts, top_k = _deepseek_v3_experts(5)
+ module = module.to("cuda", torch.bfloat16)
+ path = str(tmp_path / "experts_001.safetensors")
+ pairs = [
+ (module.gate_up_proj[e].detach(), module.down_proj[e].detach())
+ for e in range(n_experts)
+ ]
+ info = write_expert_shard(path, iter(pairs), quantise=True, double_quant=True, device="cuda")
+ with torch.no_grad():
+ for e, (gate_up, down) in enumerate(pairs):
+ for target, tensor in ((module.gate_up_proj, gate_up), (module.down_proj, down)):
+ packed, state = quantize_4bit(
+ tensor, blocksize=64, compress_statistics=True, quant_type="nf4"
+ )
+ target[e].copy_(dequantize_4bit(packed, quant_state=state))
+ codes = {NF4_CODE_KEY: info.codes[0].cuda(), NF4_NESTED_CODE_KEY: info.codes[1].cuda()}
+ reader = ExpertShardReader(
+ path, count=info.count, shapes=info.shapes, quant_specs=info.quant_specs, dtype="bfloat16"
+ )
+ streamed = streamed_experts_class()(
+ reader, ExpertFetcher(device="cuda", dtype="bfloat16", codes=codes), module.act_fn, 1
+ )
+ states, index, weights, _ = _routing(24, n_experts, top_k, 32, 9)
+ states = states.detach().to("cuda", torch.bfloat16)
+ index = index.cuda()
+ weights = weights.detach().to("cuda", torch.bfloat16)
+ with torch.no_grad():
+ assert torch.equal(streamed(states, index, weights), module(states, index, weights))
+ reader.close()
+
+
+# --------------------------------------------------------------------------
+# the synthetic store writer and the one-step harness (benchmarks/harness)
+# --------------------------------------------------------------------------
+def _harness(name):
+ import importlib.util
+ import sys
+ from pathlib import Path
+
+ harness = Path(__file__).resolve().parent.parent / "benchmarks" / "harness"
+ if str(harness) not in sys.path:
+ sys.path.insert(0, str(harness))
+ spec = importlib.util.spec_from_file_location(name, harness / f"{name}.py")
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+def test_synthetic_tiny_store_is_a_cache_the_runtime_accepts(tmp_path):
+ """The writer skips the sharder, so its index and files must be exactly
+ what the sharder would write: the index reads back, every experts file
+ opens with the index's shapes and NF4 specs, and every linear has its
+ sidecars."""
+ from safetensors import safe_open
+
+ from soup_cli.utils.expert_stream import ExpertShardReader
+ from soup_cli.utils.layer_shard import expert_paths, layer_paths, read_shard_index
+
+ store = str(tmp_path / "store")
+ summary = _harness("synth_moe_store").write_store(store, "tiny", log=lambda _line: None)
+ assert summary["label"] == "random weights, shape only"
+ index = read_shard_index(store)
+ assert index.arch == "deepseek_v3" and index.quant == "nf4"
+ assert index.expert_layers == (1, 2) and index.expert_count == 8
+ for layer, path in expert_paths(store, index).items():
+ reader = ExpertShardReader(
+ path, count=index.expert_count, shapes=index.expert_shapes,
+ quant_specs=index.expert_quant_specs, dtype=index.dtype,
+ )
+ reader.close()
+ with safe_open(layer_paths(store, index)[1], framework="pt") as handle:
+ keys = set(handle.keys())
+ assert "self_attn.q_a_proj.weight::absmax" in keys
+ assert "self_attn.q_a_proj.weight::nested_offset" in keys
+ assert index.double_quant is True
+ assert index.expert_quant_specs["down"].nested is True
+ assert "mlp.shared_experts.down_proj.weight" in keys
+ assert "mlp.gate.e_score_correction_bias" in keys
+
+
+def test_synthetic_writer_refuses_an_existing_cache(tmp_path, capsys):
+ store = tmp_path / "store"
+ store.mkdir()
+ (store / "index.json").write_text("{}", encoding="utf-8")
+ assert _harness("synth_moe_store").main(["--out", str(store), "--shape", "tiny"]) == 2
+ assert "already holds a shard cache" in capsys.readouterr().out
+
+
+@CUDA
+def test_one_step_on_the_synthetic_tiny_store(tmp_path):
+ import json
+
+ pytest.importorskip("bitsandbytes")
+ store = str(tmp_path / "store")
+ _harness("synth_moe_store").write_store(store, "tiny", log=lambda _line: None)
+ out = tmp_path / "step.json"
+ assert _harness("moe_stream_step").main(
+ ["--store", store, "--out", str(out), "--seq", "16", "--steps", "2", "--no-pin"]
+ ) == 0
+ report = json.loads(out.read_text(encoding="utf-8"))
+ assert report["label"] == "random weights, shape only"
+ assert len(report["steps"]) == 2
+ for step in report["steps"]:
+ assert step["loss_finite"] and step["grads_finite"]
+ assert step["expert_fetches"] > 0