Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
feat(stream): DeepSeek-V3 architecture in layer streaming (#1914)
Alpamys Makazhanb98ad586f453
diff --git a/changelog.d/0.76.0/1914.added.md b/changelog.d/0.76.0/1914.added.mdnew file mode 100644index 00000000..363f3b3c--- /dev/null+++ b/changelog.d/0.76.0/1914.added.md@@ -0,0 +1,8 @@+- **Layer streaming supports the DeepSeek-V3 architecture** (`model_type: deepseek_v3`: MLA+ attention, routed plus shared experts, dense first layers), gated on resident-vs-streamed parity+ forward and backward. The sharder stacks per-expert keys into the fused expert tensors, drops the+ MTP layers stored past `num_hidden_layers`, and keeps the router's `e_score_correction_bias` at+ fp32; the runtime loads that buffer from the shard (the streamed skeleton would otherwise run it+ at zero). FP8 checkpoints (`F8_*` tensors or `*_scale_inv` block scales) are refused by the+ sharder instead of being cast without their scales. Kimi K2's `kimi_k2` model type stays refused.+ (#1914)diff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.mdindex d2cf60cd..4c351932 100644--- a/docs/performance-and-quantization.md+++ b/docs/performance-and-quantization.md@@ -722,7 +722,7 @@ prints this advice when it sees you accumulating.- a disk-tier run whose host staging (`stream_read_ahead` layers, plus one slot each for the embedding and an untied `lm_head`) plus the resident extras will not fit the free-RAM headroom → refused by name, naming the depth to lower. Refused rather than clamped: a depth you set is a decision, and silently lowering it would hand back a slower run than the one you configured- more than 8 distinct layer shapes in one shard index → refused. Staging is allocated per shape and a shape with one member takes a full slot at any depth, so an index whose every layer differed would hold most of the model in staging at once — page-locked when the box allows it and `stream_pin` is not false, a loud pageable fallback otherwise, and a refusal only under `stream_pin: true` on a CUDA target — which is what the disk tier exists to avoid. A real model has one to three- `stream_vram_probe` on any task other than `sft` → the probe runs a plain causal-LM step, which *is* the SFT step but is not a preference loss. Measured at one matching shape it is conservative there too (6.02 GB against a real DPO step's 5.30 GB, +13.5%), but one shape is not a validation, so it is not offered for `dpo`/`orpo`/`simpo`/`kto` yet-- an architecture outside the supported list (llama / qwen2 / qwen3, including qwen3_5_moe text aliases / qwen4_exp text / mistral / gemma / gemma2 / gemma3_text / phi / phi3) → named explicitly+- an architecture outside the supported list (llama / qwen2 / qwen3, including qwen3_5_moe text aliases / qwen4_exp text / mistral / gemma / gemma2 / gemma3_text / phi / phi3 / deepseek_v3) → named explicitly. `deepseek_v3` is the DeepSeek-V3 family (MLA attention, routed experts plus a shared expert); a Kimi K2 checkpoint uses the same decoder but declares `model_type: kimi_k2`, which transformers does not register, so it is refused under that name. Under `quantization: 4bit` its attention, shared-expert and dense-MLP projections are NF4 while the routed experts stay at the stream dtype: they are 3-D parameters, not `nn.Linear` modules, so a DeepSeek-V3 layer streams most of its bytes unquantised**Config example:**@@ -795,7 +795,7 @@ output: ./output- **"base exceeds the physical RAM safety ceiling"** — `stream_source: auto` fell back to the NVMe disk tier because the RAM tier would keep the store plus resident extras above Soup's physical-host ceiling. Set `stream_source: ram` only when you want that case to refuse instead of falling back.- **"layer streaming needs NVMe or more RAM … the detected disk is 'hdd'"** on a fast cloud disk — a virtio device reports `rotational=1` with no media hint. Detection now measures the disk when the flag is unreliable; if it still misreads yours, set `training.stream_disk_kind: nvme` to force the tier on (`ssd`/`hdd` force it off).- **"could not page-lock the base … falling back to a PAGEABLE RAM store"** — expected on a busy machine. Training continues, more slowly. Close other applications to keep the pinned store. Since #901 the fallback also prints `after the failed page-lock: cleared the stale CUDA out-of-memory error … and released N GB of page-locked memory it left cached` — a failed page-lock leaves the CUDA runtime holding a stale "out of memory" that the run's first kernel launch would otherwise report as a real one (the report's `AcceleratorError: CUDA error: out of memory` inside `SFTTrainer.__init__`, with gigabytes of VRAM free), and the blocks pinned before the failure stay in torch's host cache until released. Both are handled before the pageable store is built. The store also pins in power-of-two arenas now, so the fallback itself is rarer: a 9.93 GB 14B NF4 store page-locks as 10 GiB where per-tensor pinning asked for ~17 GB.-- **"layer streaming does not support model_type=…"** — the supported list is llama / qwen2 / qwen3, including `qwen3_5_moe` text aliases / qwen4_exp text / mistral / gemma / gemma2 / gemma3_text / phi / phi3. Multimodal `gemma3` is excluded on purpose; use `gemma3_text`.+- **"layer streaming does not support model_type=…"** — the supported list is llama / qwen2 / qwen3, including `qwen3_5_moe` text aliases / qwen4_exp text / mistral / gemma / gemma2 / gemma3_text / phi / phi3 / deepseek_v3. Multimodal `gemma3` is excluded on purpose; use `gemma3_text`.- **"predicted peak … exceeds free VRAM" and you believe it is wrong** — lower `batch_size` or `data.max_length` first. Otherwise there are two escape hatches and they are not interchangeable. `training.stream_vram_probe: true` (`sft` only) **measures** one real forward+backward at your configured shape and decides on that, printing the prediction beside it; it costs one step (1–5 s measured) and it can also refuse a run the formula accepted. `training.stream_vram_override: <bytes>` instead **replaces** the free-VRAM figure the check runs against — that is an assertion you are making, not a measurement, so raising it past a real limit is an OOM on Linux and a silent spill on Windows. Prefer the probe when you want to be told the truth; use the override when you know something the driver cannot report.- **The prediction is not equally trustworthy at every sequence length.** Measured on a 4 GB RTX 3050 with SmolLM2-135M streamed in bf16 at batch 1, the formula over-predicts by 8% at seq 4352 (safe) and then **under-predicts — 0.934x the real peak at seq 5120 and 0.787x at 6144**. The grid it was fitted on only ever varied batch size, at seq 256 and 512, so long-context streaming is exactly where it has the least evidence behind it. If you are streaming at multi-thousand-token sequences, turn on `stream_vram_probe`. Record: [`benchmarks/gate-v0.73.1-measured-vram-fit.md`](../benchmarks/gate-v0.73.1-measured-vram-fit.md).- **The pre-flight reports the whole card on a capped or shared GPU** — `torch.cuda.mem_get_info()` is a device-level driver query and cannot see `set_per_process_memory_fraction`, a MIG slice, or another process on the same card. Set `training.stream_vram_override` to what your process may actually use; the check then refuses configurations that would exceed *that*, which is also how you rehearse a 4 GB card on a 16 GB one.diff --git a/src/soup_cli/trainer/stream_setup.py b/src/soup_cli/trainer/stream_setup.pyindex 0d72f198..1a3d0328 100644--- a/src/soup_cli/trainer/stream_setup.py+++ b/src/soup_cli/trainer/stream_setup.py@@ -711,6 +711,7 @@ class StreamingSetupMixin:resolve_shard_dir,shard_cache_disk_bytes,shard_checkpoint,+ source_identity_includes_config,source_weight_bytes,stripe_dirs,)@@ -817,7 +818,7 @@ class StreamingSetupMixin:source_components = checkpoint_source_components(weights_plan.weights_dir,weights_plan.source_files,- include_config=arch == "qwen4_exp",+ include_config=source_identity_includes_config(arch),)cached, _reason = inspect_shard_cache(shard_dir,@@ -947,6 +948,13 @@ class StreamingSetupMixin:quant_device=str(self.device),stripe_roots=stripe_roots,notify=console.print,+ # DeepSeek-V3 / Kimi K2 store their MTP module as layers past the last+ # decoder layer; the sharder drops them against the config's count.+ num_hidden_layers=(+ int(self._stream_shape_config(model_config).num_hidden_layers)+ if arch == "deepseek_v3"+ else None+ ),)# R4: decided once, from the roots the index actually carries (a reused cache keeps its# own), so the plan's staging figure, the host pre-flight and the reader all agree. Readdiff --git a/src/soup_cli/utils/layer_shard.py b/src/soup_cli/utils/layer_shard.pyindex 70622f66..a5633e46 100644--- a/src/soup_cli/utils/layer_shard.py+++ b/src/soup_cli/utils/layer_shard.py@@ -110,10 +110,31 @@ _QWEN4_PLE_SHARD_RE = re.compile(_QWEN4_OQ_PLE_SHARD_RE = re.compile(r"^(?P<prefix>.+\.ple\.ple_embedding\.ngram_embedding)\.shards\.(?P<part>\d+)\.weight$")-_QWEN4_EXPERT_RE = re.compile(+_PER_EXPERT_RE = re.compile(r"^(?P<prefix>model\.layers\.\d+\.mlp\.experts)\."r"(?P<expert>\d+)\.(?P<projection>gate_proj|up_proj|down_proj)\.weight$")+#: Architectures whose transformers module holds the routed experts as fused+#: 3-D ``gate_up_proj`` [E, 2I, H] / ``down_proj`` [E, H, I] parameters while+#: the checkpoint stores one 2-D tensor per expert and projection (the+#: ``qwen2_moe`` conversion in transformers' ``conversion_mapping.py``: gate+#: rows first, experts in index order). Value = the name used in messages.+_STACKED_EXPERT_ARCHS = {"qwen4_exp": "Qwen4", "deepseek_v3": "DeepSeek-V3"}+#: Per-layer BUFFERS the checkpoint carries and a streamed run must use. The+#: skeleton is built under ``init_empty_weights()``, which leaves buffers at+#: their ``__init__`` value, so the runtime loads exactly these from the layer+#: shard (``layer_stream_runtime._load_layer_buffers``); every other buffer+#: keeps its init value, as it always has (a qwen4_exp integer buffer, for one,+#: reaches the shard cast to the stream dtype and must not be loaded back).+#: Stored at float32 whatever the stream dtype: transformers keeps them in fp32+#: on load (``_keep_in_fp32_modules_strict``), so a resident bf16 run routes with+#: the fp32 values and the streamed run must as well.+_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, ())_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$"@@ -824,6 +845,17 @@ def _source_file_components(shards: List[str]) -> Tuple[Tuple[str, int, int], ..return tuple(components)+def source_identity_includes_config(arch: str) -> bool:+ """Whether ``config.json`` is part of a shard cache's source identity.++ ``qwen4_exp`` reads its PLE layout from the config; for ``deepseek_v3`` the+ config's layer count decides which (multi-token-prediction) layers are+ dropped. The pre-sharding planner and the sharder must agree on this, or+ the planner predicts a cache miss the sharder then does not see.+ """+ return arch in ("qwen4_exp", "deepseek_v3")++def checkpoint_source_components(weights_dir: str,components: Tuple[Tuple[str, int, int], ...],@@ -1215,6 +1247,7 @@ def shard_checkpoint(quant_device: Optional[str] = None,notify: Optional[Callable[[str], None]] = None,stripe_roots: Sequence[str] = (),+ num_hidden_layers: Optional[int] = None,) -> ShardIndex:"""Rewrite an HF checkpoint into per-layer safetensors shards.@@ -1231,12 +1264,29 @@ def shard_checkpoint(``i`` is written to root ``i mod N`` (root 0 is ``out_dir``), each extraroot gets a per-model folder named like ``out_dir`` plus a ``stripe.json``marker, and the index records the placement.++ For ``arch`` in :data:`_STACKED_EXPERT_ARCHS` the per-expert routed-expert+ keys (``mlp.experts.E.{gate,up,down}_proj.weight``) are stacked into the+ fused ``mlp.experts.gate_up_proj`` / ``mlp.experts.down_proj`` tensors the+ transformers module holds, the same conversion ``from_pretrained`` applies.+ 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."""if dtype not in _SUPPORTED_DTYPES:raise ValueError(f"unsupported dtype {dtype!r} for layer streaming; "f"supported: {', '.join(_SUPPORTED_DTYPES)}")+ if num_hidden_layers is not None and (+ isinstance(num_hidden_layers, bool)+ or not isinstance(num_hidden_layers, int)+ or not 1 <= num_hidden_layers <= _MAX_LAYERS+ ):+ raise ValueError(+ f"num_hidden_layers must be an int in [1, {_MAX_LAYERS}], "+ f"got {num_hidden_layers!r}"+ )suffixes = _validate_quant_request(quant, quant_suffixes)quantise = quant == QUANT_NF4device = (quant_device or _default_quant_device()) if quantise else "cpu"@@ -1244,6 +1294,10 @@ def shard_checkpoint(# index stores that so the cache check below stays stable across ordinals.device_kind = str(device).split(":", 1)[0] if quantise else ""external_mode = "qwen4_ple" if arch == "qwen4_exp" else ""+ stack_experts = arch in _STACKED_EXPERT_ARCHS+ expert_label = _STACKED_EXPERT_ARCHS.get(arch, arch)+ fp32_layer_keys = layer_buffer_keys(arch)+ drop_extra_layers = arch == "deepseek_v3" and num_hidden_layers is not Noneshards = _discover_safetensors(weights_dir)resolved_out = _validate_out_dir(out_dir)@@ -1277,7 +1331,7 @@ def shard_checkpoint(source_files = checkpoint_source_components(weights_dir,_source_file_components(shards),- include_config=bool(external_mode),+ include_config=source_identity_includes_config(arch),)fingerprint = _fingerprint_components(source_files)if not force:@@ -1328,6 +1382,9 @@ def shard_checkpoint(for source_key in handle.keys():if external_mode and source_key.endswith((".biases", ".scales")):saw_oq_companion = True+ if source_key.endswith("_scale_inv"):+ # Before any byte is read or written: see _refuse_fp8.+ _refuse_fp8(source_key, str(handle.get_slice(source_key).get_dtype()))key = _canonical_stream_key(source_key)prior = where.get(key)if prior is not None and prior != (path, source_key):@@ -1395,6 +1452,19 @@ def shard_checkpoint(if (match := _LAYER_RE.match(key)) is not None}+ 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).+ # The CausalLM has no such layer and transformers drops the keys on+ # load; kept here they would make a shard the skeleton cannot place.+ where = {+ key: location+ for key, location in where.items()+ if (match := _LAYER_RE.match(key)) is None+ or int(match.group(1)) < num_hidden_layers+ }+ layer_ids = {layer for layer in layer_ids if layer < num_hidden_layers}+external_tensors: Dict[str, Any] = {}for logical_key, indexed_parts in external_parts.items():indexed_parts.sort(key=lambda item: item[0])@@ -1533,7 +1603,7 @@ def shard_checkpoint(for idx in range(n_layers):prefix = f"model.layers.{idx}."blob = {}- qwen4_experts: Dict[str, Dict[int, Tuple[str, str]]] = {}+ stacked_experts: Dict[str, Dict[int, Tuple[str, str]]] = {}oq_experts: Dict[str, str] = {}for key, location in where.items():if not key.startswith(prefix):@@ -1548,11 +1618,11 @@ def shard_checkpoint(if oq_expert_match:oq_experts[oq_expert_match.group("projection")] = keycontinue- expert_match = _QWEN4_EXPERT_RE.match(key) if external_mode else None+ expert_match = _PER_EXPERT_RE.match(key) if stack_experts else Noneif expert_match:projection = expert_match.group("projection")expert = int(expert_match.group("expert"))- qwen4_experts.setdefault(projection, {})[expert] = location+ stacked_experts.setdefault(projection, {})[expert] = locationcontinuepath, source_key = locationshort = key[len(prefix):]@@ -1561,7 +1631,8 @@ def shard_checkpoint(handles, where, key, oq_config=oq_config, dtype=dtype)else:- tensor = _read_tensor(handles[path], source_key, dtype)+ stored = "float32" if short in fp32_layer_keys else dtype+ tensor = _read_tensor(handles[path], source_key, stored)total_params += tensor.numel()if quantise and short in suffixes:sidecars, spec, code, nested_code = _quantize_nf4(@@ -1587,27 +1658,27 @@ def shard_checkpoint(for logical_key, spec in external_tensors.items():if logical_key.startswith(prefix):total_params += math.prod(spec.shape)- if qwen4_experts:+ if stacked_experts:import torchexpected_projections = {"gate_proj", "up_proj", "down_proj"}- if set(qwen4_experts) != expected_projections:+ if set(stacked_experts) != expected_projections:raise ValueError(- f"Qwen4 layer {idx} has incomplete expert projections: "- f"{sorted(qwen4_experts)}"+ f"{expert_label} layer {idx} has incomplete expert projections: "+ f"{sorted(stacked_experts)}")- expert_ids = sorted(qwen4_experts["gate_proj"])+ expert_ids = sorted(stacked_experts["gate_proj"])if expert_ids != list(range(len(expert_ids))) or any(- sorted(qwen4_experts[name]) != expert_ids+ sorted(stacked_experts[name]) != expert_idsfor name in expected_projections):raise ValueError(- f"Qwen4 layer {idx} expert ids must be contiguous and "+ f"{expert_label} layer {idx} expert ids must be contiguous and ""identical across gate/up/down projections")def _expert_tensor(projection: str, expert: int):- path, source_key = qwen4_experts[projection][expert]+ path, source_key = stacked_experts[projection][expert]return _read_tensor(handles[path], source_key, dtype)gate_up = []@@ -1621,7 +1692,8 @@ def shard_checkpoint(total_params += gate.numel() + up.numel() + down_tensor.numel()if "mlp.experts.gate_up_proj" in blob or "mlp.experts.down_proj" in blob:raise ValueError(- f"Qwen4 layer {idx} contains both packed and per-expert weights"+ 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)@@ -2098,11 +2170,25 @@ def _own(view: Any, candidate: Any) -> Any:return view.clone() if candidate is view else candidate+def _refuse_fp8(key: str, stored_dtype: str) -> None:+ """FP8 weights carry block scales (``*.weight_scale_inv``) the sharder has no+ path for; a plain cast keeps the raw e4m3 values and trains on wrong weights,+ while the resident load (which dequantises) looks fine."""+ if stored_dtype.upper().startswith("F8") or key.endswith("_scale_inv"):+ raise ValueError(+ f"checkpoint tensor {key!r} is FP8 ({stored_dtype}) or an FP8 block scale. "+ f"Layer streaming has no FP8 path: casting would drop the scales. "+ f"Dequantise the checkpoint to bf16 first."+ )++def _read_tensor(handle: Any, key: str, dtype: str) -> "Any":"""Materialise one OWNED tensor, size-capped, converted to the target dtype."""import torch- shape = handle.get_slice(key).get_shape()+ sliced = handle.get_slice(key)+ _refuse_fp8(key, str(sliced.get_dtype()))+ shape = sliced.get_shape()elements = math.prod(int(dim) for dim in shape)if elements > _MAX_TENSOR_ELEMENTS:raise ValueError(diff --git a/src/soup_cli/utils/layer_stream.py b/src/soup_cli/utils/layer_stream.pyindex 84efee7f..ff4321ec 100644--- a/src/soup_cli/utils/layer_stream.py+++ b/src/soup_cli/utils/layer_stream.py@@ -85,6 +85,11 @@ FLOPS_PER_PARAM_PER_TOKEN = 6#: reports ``model_type='gemma3'`` for the vision-capable wrapper, and streaming#: a multimodal wrapper as though it were a causal LM is exactly the failure the#: allowlist exists to prevent.+#:+#: ``deepseek_v3`` is the DeepSeek-V3 family (MLA attention, DeepSeekMoE with+#: a shared expert, the first ``first_k_dense_replace`` layers dense). Kimi K2+#: ships the same decoder under ``model_type='kimi_k2'``, which transformers+#: does not register, so that name stays refused here too.SUPPORTED_STREAM_ARCHS = ("llama","qwen2",@@ -96,6 +101,7 @@ SUPPORTED_STREAM_ARCHS = ("gemma3_text","phi","phi3",+ "deepseek_v3",)# Model types whose text decoders reuse an admitted streaming family. Eachdiff --git a/src/soup_cli/utils/layer_stream_runtime.py b/src/soup_cli/utils/layer_stream_runtime.pyindex 1079cc93..8b2f5b33 100644--- a/src/soup_cli/utils/layer_stream_runtime.py+++ b/src/soup_cli/utils/layer_stream_runtime.py@@ -2952,6 +2952,54 @@ def _layer_name_map(layer: Any) -> Dict[str, str]:}+def _load_layer_buffers(+ layers: Any, paths: Sequence[str], specs: Sequence[Any], keys: Sequence[str]+) -> int:+ """Copy the named persistent buffers of each decoder layer from its shard.++ ``keys`` (``layer_shard.layer_buffer_keys(arch)``) are the only buffers+ loaded. The skeleton is built under ``init_empty_weights()``, which leaves+ buffers as real tensors holding their ``__init__`` value: DeepSeek-V3's+ router ``e_score_correction_bias`` would otherwise run at zero, which routes+ tokens to different experts with no error. Buffers are not trained, so they+ are loaded once and stay resident, at the dtype the shard stores them in. A+ listed buffer absent from a layer's shard keeps its init value, as+ ``from_pretrained`` would. Returns the count loaded.+ """+ from safetensors import safe_open++ wanted_keys = frozenset(keys)+ if not wanted_keys:+ return 0+ loaded = 0+ for idx, (layer, path) in enumerate(zip(layers, paths)):+ wanted = []+ for name, buf in layer.named_buffers():+ owner_name, _, leaf = name.rpartition(".")+ owner = layer.get_submodule(owner_name) if owner_name else layer+ if buf is None or leaf in owner._non_persistent_buffers_set:+ continue+ key = name.replace(".base_layer.", ".")+ if key in wanted_keys and key in specs[idx]:+ wanted.append((owner, leaf, key, buf))+ if not wanted:+ continue+ with safe_open(path, framework="pt") as handle:+ for owner, leaf, key, buf in wanted:+ value = handle.get_tensor(key)+ if tuple(value.shape) != tuple(buf.shape):+ raise ValueError(+ f"decoder layer {idx} buffer {key!r} has shape "+ f"{tuple(value.shape)} in the shard but {tuple(buf.shape)} "+ f"in the model — reshard the checkpoint"+ )+ # copy=True: on a CPU target `.to` would return the mapped view,+ # keeping the whole layer file mapped for the model's lifetime.+ setattr(owner, leaf, value.to(device=buf.device, copy=True))+ loaded += 1+ return loaded++def install_streaming(model: Any,*,@@ -2988,6 +3036,7 @@ def install_streaming(QUANT_NF4,large_shard_path,large_weight_role,+ layer_buffer_keys,layer_paths,)@@ -3088,6 +3137,11 @@ def install_streaming(needed_specs_by_layer.append(needed)active_keys_by_layer.append(tuple(sorted(needed)))spec = RamSource.merge_layer_specs(needed_specs_by_layer)+ # Before the source exists: a refusal here leaves no reader thread or+ # page-locked staging behind.+ _load_layer_buffers(+ layers, decoder_paths, layer_specs, layer_buffer_keys(getattr(index, "arch", ""))+ )large_source_indices = {key: n_layers + offset for offset, key in enumerate(large_keys)}source_specs = needed_specs_by_layer + [{key: large_specs[key]} for key in large_keys]diff --git a/tests/test_deepseek_v3_streaming.py b/tests/test_deepseek_v3_streaming.pynew file mode 100644index 00000000..e4c6d83d--- /dev/null+++ b/tests/test_deepseek_v3_streaming.py@@ -0,0 +1,501 @@+"""Layer streaming for the DeepSeek-V3 architecture (MLA + DeepSeekMoE).++The gate for admitting an architecture is resident-vs-streamed parity on a+real (tiny) model, forward and backward stated separately, the same rule every+other entry of ``SUPPORTED_STREAM_ARCHS`` passed.+"""++from __future__ import annotations++from types import SimpleNamespace++import pytest++_LORA_TARGETS = ["q_proj", "q_b_proj", "kv_a_proj_with_mqa", "kv_b_proj", "o_proj"]+++# --------------------------------------------------------------------------+# allowlist+# --------------------------------------------------------------------------+def test_deepseek_v3_is_an_admitted_stream_arch():+ from soup_cli.utils.layer_stream import SUPPORTED_STREAM_ARCHS, stream_arch_of++ assert "deepseek_v3" in SUPPORTED_STREAM_ARCHS+ assert stream_arch_of(SimpleNamespace(model_type="deepseek_v3")) == "deepseek_v3"+++def test_kimi_k2_model_type_is_still_refused_naming_the_allowlist():+ """transformers registers no ``kimi_k2`` config, so the name stays refused;+ the message must point at the admitted family."""+ from soup_cli.utils.layer_stream import stream_arch_of++ with pytest.raises(ValueError, match="deepseek_v3") as caught:+ stream_arch_of(SimpleNamespace(model_type="kimi_k2"))+ assert "kimi_k2" in str(caught.value)+++# --------------------------------------------------------------------------+# sharder: synthetic safetensors, no model+# --------------------------------------------------------------------------+def _write_layer_checkpoint(path, *, n_layers, n_experts, extra_layer_keys=()):+ import torch+ from safetensors.torch import save_file++ hidden, inter = 4, 3+ state = {+ "model.embed_tokens.weight": torch.zeros(8, hidden),+ "model.norm.weight": torch.ones(hidden),+ "lm_head.weight": torch.zeros(8, hidden),+ }+ for layer in range(n_layers):+ prefix = f"model.layers.{layer}."+ state[prefix + "input_layernorm.weight"] = torch.ones(hidden)+ state[prefix + "mlp.gate.weight"] = torch.full((n_experts, hidden), float(layer))+ state[prefix + "mlp.gate.e_score_correction_bias"] = torch.tensor(+ [0.1 + 1e-3 * expert for expert in range(n_experts)], dtype=torch.float32+ )+ for expert in range(n_experts):+ base = 1000.0 * layer + 10.0 * expert+ state[prefix + f"mlp.experts.{expert}.gate_proj.weight"] = torch.full(+ (inter, hidden), base + 1.0+ )+ state[prefix + f"mlp.experts.{expert}.up_proj.weight"] = torch.full(+ (inter, hidden), base + 2.0+ )+ state[prefix + f"mlp.experts.{expert}.down_proj.weight"] = torch.full(+ (hidden, inter), base + 3.0+ )+ for key in extra_layer_keys:+ state[key] = torch.ones(hidden)+ path.mkdir(parents=True, exist_ok=True)+ save_file(state, str(path / "model.safetensors"))+ (path / "config.json").write_text('{"model_type": "deepseek_v3"}', encoding="utf-8")+ return str(path)+++def _layer_file(shards, index, layer):+ from soup_cli.utils.layer_shard import layer_paths++ return layer_paths(str(shards), index)[layer]+++def test_per_expert_keys_stack_gate_first_in_numeric_expert_order(tmp_path):+ """11 experts: a lexical sort would put expert 10 before expert 2."""+ import torch+ from safetensors.torch import load_file++ from soup_cli.utils.layer_shard import shard_checkpoint++ weights = _write_layer_checkpoint(tmp_path / "w", n_layers=2, n_experts=11)+ index = shard_checkpoint(+ weights, str(tmp_path / "s"), dtype="float32", arch="deepseek_v3", num_hidden_layers=2+ )+ for layer in range(2):+ tensors = load_file(_layer_file(tmp_path / "s", index, layer))+ assert not any(".experts.0." in key for key in tensors)+ gate_up = tensors["mlp.experts.gate_up_proj"]+ down = tensors["mlp.experts.down_proj"]+ assert tuple(gate_up.shape) == (11, 6, 4)+ assert tuple(down.shape) == (11, 4, 3)+ for expert in range(11):+ base = 1000.0 * layer + 10.0 * expert+ assert torch.equal(gate_up[expert, :3], torch.full((3, 4), base + 1.0))+ assert torch.equal(gate_up[expert, 3:], torch.full((3, 4), base + 2.0))+ assert torch.equal(down[expert], torch.full((4, 3), base + 3.0))+++def test_mtp_layers_past_num_hidden_layers_are_dropped(tmp_path):+ from soup_cli.utils.layer_shard import shard_checkpoint++ mtp = ("model.layers.2.enorm.weight", "model.layers.2.hnorm.weight")+ weights = _write_layer_checkpoint(+ tmp_path / "w", n_layers=2, n_experts=2, extra_layer_keys=mtp+ )+ index = shard_checkpoint(+ weights, str(tmp_path / "s"), dtype="float32", arch="deepseek_v3", num_hidden_layers=2+ )+ assert index.n_layers == 2+++def test_mtp_control_without_the_layer_count_keeps_the_extra_layer(tmp_path):+ """The control for the test above: the extra layer is real input."""+ from soup_cli.utils.layer_shard import shard_checkpoint++ mtp = ("model.layers.2.enorm.weight", "model.layers.2.hnorm.weight")+ weights = _write_layer_checkpoint(+ tmp_path / "w", n_layers=2, n_experts=2, extra_layer_keys=mtp+ )+ index = shard_checkpoint(weights, str(tmp_path / "s"), dtype="float32", arch="deepseek_v3")+ assert index.n_layers == 3++[email protected]("bad", [True, 0, -1, 2.0, "2", 100000])+def test_num_hidden_layers_is_validated(tmp_path, bad):+ from soup_cli.utils.layer_shard import shard_checkpoint++ weights = _write_layer_checkpoint(tmp_path / "w", n_layers=2, n_experts=2)+ with pytest.raises(ValueError, match="num_hidden_layers must be an int"):+ shard_checkpoint(+ weights, str(tmp_path / "s"), dtype="float32", arch="deepseek_v3",+ num_hidden_layers=bad,+ )+++def test_router_correction_bias_stays_fp32_under_a_bf16_stream(tmp_path):+ """transformers keeps ``e_score_correction_bias`` in fp32 on load; a bf16+ shard would route with rounded values the resident model never sees."""+ import torch+ from safetensors.torch import load_file++ from soup_cli.utils.layer_shard import shard_checkpoint++ weights = _write_layer_checkpoint(tmp_path / "w", n_layers=2, n_experts=4)+ index = shard_checkpoint(+ weights, str(tmp_path / "s"), dtype="bfloat16", arch="deepseek_v3", num_hidden_layers=2+ )+ tensors = load_file(_layer_file(tmp_path / "s", index, 1))+ bias = tensors["mlp.gate.e_score_correction_bias"]+ assert bias.dtype == torch.float32+ assert torch.equal(bias, torch.tensor([0.1, 0.101, 0.102, 0.103], dtype=torch.float32))+ assert tensors["mlp.gate.weight"].dtype == torch.bfloat16+ assert tensors["mlp.experts.gate_up_proj"].dtype == torch.bfloat16++[email protected]("fp8_key", ["weight", "scale"])+def test_fp8_checkpoint_is_refused_before_anything_is_written(tmp_path, fp8_key):+ """DeepSeek-V3 / Kimi K2 publish FP8 weights plus ``weight_scale_inv`` block+ scales. A cast would keep the raw e4m3 values and drop the scales."""+ import torch+ from safetensors.torch import save_file++ from soup_cli.utils.layer_shard import shard_checkpoint++ weights = tmp_path / "w"+ weights.mkdir()+ state = {+ "model.embed_tokens.weight": torch.zeros(8, 4),+ "model.layers.0.input_layernorm.weight": torch.ones(4),+ "model.layers.0.self_attn.o_proj.weight": torch.zeros(4, 4),+ }+ if fp8_key == "weight":+ state["model.layers.0.self_attn.o_proj.weight"] = torch.zeros(4, 4).to(+ torch.float8_e4m3fn+ )+ else:+ state["model.layers.0.self_attn.o_proj.weight_scale_inv"] = torch.ones(1, 1)+ save_file(state, str(weights / "model.safetensors"))+ with pytest.raises(ValueError, match="Dequantise the checkpoint to bf16 first"):+ shard_checkpoint(str(weights), str(tmp_path / "s"), dtype="bfloat16", arch="deepseek_v3")+ assert not (tmp_path / "s" / "index.json").exists()+++def test_layer_buffers_load_from_the_shard_at_the_stored_dtype(tmp_path):+ """Covers each branch of `_load_layer_buffers` on a hand-built layer: a+ persistent buffer is replaced by the shard's (fp32 over a bf16 skeleton);+ a non-persistent one and one the shard lacks keep their init values; a+ LoRA-style ``.base_layer.`` segment maps to the checkpoint name."""+ import torch+ import torch.nn as nn+ from safetensors.torch import save_file++ from soup_cli.utils.layer_stream_runtime import _load_layer_buffers++ layer = nn.Module()+ layer.gate = nn.Module()+ layer.gate.register_buffer("bias", torch.zeros(3, dtype=torch.bfloat16))+ layer.gate.register_buffer("scratch", torch.zeros(3), persistent=False)+ layer.gate.register_buffer("absent", torch.full((2,), 5.0))+ layer.proj = nn.Module()+ layer.proj.base_layer = nn.Module()+ layer.proj.base_layer.register_buffer("table", torch.zeros(2))+ layer.proj.register_buffer("counts", torch.arange(4))+ shard = {+ "gate.bias": torch.tensor([0.1, 0.2, 0.3], dtype=torch.float32),+ "gate.scratch": torch.ones(3),+ "proj.table": torch.tensor([7.0, 8.0]),+ # An integer buffer the sharder cast to the stream dtype (qwen4_exp has+ # one): not listed, so it must keep the skeleton's own value and dtype.+ "proj.counts": torch.zeros(4),+ }+ path = str(tmp_path / "layer_000.safetensors")+ save_file(shard, path)+ specs = [{key: (tuple(value.shape), "x") for key, value in shard.items()}]+ keys = ("gate.bias", "gate.scratch", "gate.absent", "proj.table")++ assert _load_layer_buffers([layer], [path], specs, keys) == 2+ assert layer.gate.bias.dtype == torch.float32+ assert torch.equal(layer.gate.bias, shard["gate.bias"])+ assert torch.equal(layer.gate.scratch, torch.zeros(3))+ assert torch.equal(layer.gate.absent, torch.full((2,), 5.0))+ assert torch.equal(layer.proj.base_layer.table, shard["proj.table"])+ assert torch.equal(layer.proj.counts, torch.arange(4))+++def test_only_deepseek_v3_streams_a_layer_buffer():+ from soup_cli.utils.layer_shard import layer_buffer_keys++ assert layer_buffer_keys("deepseek_v3") == ("mlp.gate.e_score_correction_bias",)+ for arch in ("llama", "qwen4_exp", "qwen3", ""):+ assert layer_buffer_keys(arch) == ()+++def test_layer_buffer_shape_mismatch_names_the_buffer(tmp_path):+ import torch+ import torch.nn as nn+ from safetensors.torch import save_file++ from soup_cli.utils.layer_stream_runtime import _load_layer_buffers++ layer = nn.Module()+ layer.register_buffer("bias", torch.zeros(4))+ path = str(tmp_path / "layer_000.safetensors")+ save_file({"bias": torch.zeros(3)}, path)+ with pytest.raises(ValueError, match="buffer 'bias' has shape"):+ _load_layer_buffers([layer], [path], [{"bias": ((3,), "F32")}], ("bias",))+++def _deepseek_setup_cfg():+ return SimpleNamespace(+ model_type="deepseek_v3",+ hidden_size=4,+ num_hidden_layers=1,+ vocab_size=8,+ intermediate_size=8,+ )+++ ("arch", "expected"), [("deepseek_v3", 1), ("llama", None)], ids=["deepseek_v3", "llama"]+)+def test_setup_hands_the_config_layer_count_to_the_sharder_for_deepseek_v3_only(+ tmp_path, monkeypatch, arch, expected+):+ """Without it a real DeepSeek-V3 (61 layers + the MTP layer 61) shards 62+ layers and the install refuses with "model has 61 decoder layers"."""+ from tests.test_issue602_qwen4_ple_streaming import _drive_qwen4_streaming_setup++ calls = []+ model_cfg = _deepseek_setup_cfg()+ model_cfg.model_type = arch+ _drive_qwen4_streaming_setup(+ tmp_path, monkeypatch, arch=arch, model_cfg=model_cfg, shard_calls=calls+ )+ assert len(calls) == 1+ assert calls[0]["num_hidden_layers"] == expected+++def test_planner_fingerprints_config_json_for_deepseek_v3(tmp_path, monkeypatch):+ """The planner must agree with the sharder (`source_identity_includes_config`),+ or it reports a stale cache as reusable and the disk pre-flight under-counts."""+ import types++ import torch+ from safetensors.torch import save_file++ import soup_cli.utils.layer_shard as layer_shard+ from tests.test_issue602_qwen4_ple_streaming import _drive_qwen4_streaming_setup++ seen = []+ real = layer_shard.checkpoint_source_components++ def _recording(weights_dir, source_files, *, include_config):+ seen.append(include_config)+ return real(weights_dir, source_files, include_config=include_config)++ monkeypatch.setattr(layer_shard, "checkpoint_source_components", _recording)+ weights = tmp_path / "weights"+ weights.mkdir()+ blob = weights / "model.safetensors"+ save_file({"model.layers.0.proj.weight": torch.ones(2, 2)}, str(blob))+ (weights / "config.json").write_text('{"model_type": "deepseek_v3"}', encoding="utf-8")+ stat = blob.stat()+ plan = types.SimpleNamespace(+ weights_dir=str(weights),+ source_bytes=stat.st_size,+ materialized_copy_bytes=0,+ materialize_bytes=0,+ needs_materialization=False,+ source_files=((str(blob), stat.st_size, int(stat.st_mtime)),),+ )++ def _resolve(_base, *, before_materialize=None):+ if before_materialize is not None:+ before_materialize(plan)+ return str(weights)++ _drive_qwen4_streaming_setup(+ tmp_path, monkeypatch, resolve_weights=_resolve, arch="deepseek_v3",+ model_cfg=_deepseek_setup_cfg(),+ )+ assert seen == [True], seen+++def test_config_is_part_of_the_cache_identity_for_deepseek_v3():+ from soup_cli.utils.layer_shard import source_identity_includes_config++ assert source_identity_includes_config("deepseek_v3") is True+ assert source_identity_includes_config("qwen4_exp") is True+ assert source_identity_includes_config("llama") is False+++# --------------------------------------------------------------------------+# resident vs streamed parity on a real tiny DeepseekV3ForCausalLM (CPU fp32)+# --------------------------------------------------------------------------+def _tiny_deepseek_v3_dir(tmp_path, *, q_lora_rank):+ 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=q_lora_rank,+ 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[config.first_k_dense_replace :]:+ # Large enough to change which experts win: the streamed run must+ # load it from the shard, not keep the skeleton's zeros.+ bias = layer.mlp.gate.e_score_correction_bias+ bias.copy_(torch.randn(bias.shape, generator=generator) * 2.0)+ weights = tmp_path / "model"+ model.save_pretrained(str(weights))+ return str(weights), model+++def _tiny_lora():+ from peft import LoraConfig, TaskType++ return LoraConfig(+ r=4, lora_alpha=8, lora_dropout=0.0, bias="none",+ target_modules=_LORA_TARGETS, task_type=TaskType.CAUSAL_LM,+ )+++def _build(tmp_path, *, q_lora_rank):+ from soup_cli.utils.layer_shard import shard_checkpoint+ from soup_cli.utils.layer_stream_runtime import build_streamed_model++ weights, resident = _tiny_deepseek_v3_dir(tmp_path, q_lora_rank=q_lora_rank)+ shards = str(tmp_path / "shards")+ index = shard_checkpoint(+ weights, shards, dtype="float32", arch="deepseek_v3", num_hidden_layers=3+ )+ model, runtime = build_streamed_model(+ model_id=weights, shard_dir=shards, index=index,+ lora_config=_tiny_lora(), device="cpu", dtype="float32",+ buffers=2, pin=False, seed=3,+ )+ return model, runtime, resident+++def _copy_lora(src, dst):+ def norm(key):+ return key.replace(".inner.", ".")++ src_lora = {norm(k): v for k, v in src.state_dict().items() if "lora_" in k}+ dst_lora = {norm(k): v for k, v in dst.state_dict().items() if "lora_" in k}+ assert src_lora and set(src_lora) == set(dst_lora)+ for key, val in src_lora.items():+ dst_lora[key].copy_(val)+++def _paired(tmp_path, q_lora_rank):+ import torch+ from peft import get_peft_model++ model, runtime, resident = _build(tmp_path, q_lora_rank=q_lora_rank)+ ref = get_peft_model(resident, _tiny_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)+ _copy_lora(model, ref)+ model.eval()+ ref.eval()+ ids = torch.randint(0, 128, (2, 12), generator=generator)+ return model, runtime, ref, ids++[email protected]("q_lora_rank", [24, None], ids=["q_lora", "q_proj"])+def test_streamed_forward_matches_resident_bit_exactly(tmp_path, q_lora_rank):+ import torch++ model, runtime, ref, ids = _paired(tmp_path, q_lora_rank)+ 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)+ runtime.close()++[email protected]("q_lora_rank", [24, None], ids=["q_lora", "q_proj"])+def test_streamed_backward_matches_resident_lora_gradients_bit_exactly(tmp_path, q_lora_rank):+ import torch++ from soup_cli.utils.layer_stream_runtime import canonical_named_parameters++ model, runtime, ref, ids = _paired(tmp_path, q_lora_rank)+ model.zero_grad(set_to_none=True)+ ref.zero_grad(set_to_none=True)+ model(input_ids=ids, labels=ids).loss.backward()+ 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)+ # Every MoE layer's attention adapters receive gradient through the+ # streamed experts of the layers above them.+ assert any(".layers.0." in name for name in streamed)+ assert any(float(gradient.abs().sum()) > 0.0 for gradient in streamed.values())+ for name, gradient in streamed.items():+ assert torch.equal(gradient, resident[name]), name+ runtime.close()+++def test_router_bias_is_loaded_and_the_tiny_model_depends_on_it(tmp_path):+ """Makes the parity tests above sensitive to the bias: a zero bias changes+ the logits of this model, and the streamed layers hold the checkpoint's."""+ import torch++ model, runtime, ref, ids = _paired(tmp_path, 24)+ base = ref.get_base_model()+ streamed_layers = model.get_base_model().model.layers+ for idx in range(1, 3):+ want = base.model.layers[idx].mlp.gate.e_score_correction_bias+ got = streamed_layers[idx].inner.mlp.gate.e_score_correction_bias+ assert float(want.abs().sum()) > 0.0+ assert got.dtype == want.dtype+ assert torch.equal(got, want)+ with torch.no_grad():+ before = ref(input_ids=ids).logits+ for idx in range(1, 3):+ base.model.layers[idx].mlp.gate.e_score_correction_bias.zero_()+ after = ref(input_ids=ids).logits+ assert not torch.equal(before, after)+ runtime.close()diff --git a/tests/test_issue602_qwen4_ple_streaming.py b/tests/test_issue602_qwen4_ple_streaming.pyindex 7469ebc1..ebc3a5f3 100644--- a/tests/test_issue602_qwen4_ple_streaming.py+++ b/tests/test_issue602_qwen4_ple_streaming.py@@ -685,7 +685,15 @@ def test_qwen4_ram_ple_refusal_is_independent_of_base_stream_source():)-def _drive_qwen4_streaming_setup(tmp_path, monkeypatch, resolve_weights=None):+def _drive_qwen4_streaming_setup(+ tmp_path,+ monkeypatch,+ resolve_weights=None,+ *,+ arch="qwen4_exp",+ model_cfg=None,+ shard_calls=None,+):"""Drive the real `_setup_streaming_transformers()` for a qwen4_exp base.THE harness. Extracted by the maintainer after review so the seam test and@@ -697,6 +705,10 @@ def _drive_qwen4_streaming_setup(tmp_path, monkeypatch, resolve_weights=None):stub ignores the `before_materialize` callback, which is where the shard-cache fingerprint is computed -- so a test about that callback has to supplyits own and actually call it.++ `arch` / `model_cfg` drive the same seam for another architecture+ (`tests/test_deepseek_v3_streaming.py`); `shard_calls`, when a list, receives+ the keyword arguments of every `shard_checkpoint` call."""import sysimport types@@ -743,15 +755,16 @@ def _drive_qwen4_streaming_setup(tmp_path, monkeypatch, resolve_weights=None):alpha_pattern=None,),)- model_cfg = types.SimpleNamespace(- model_type="qwen4_exp",- text_config=types.SimpleNamespace(- hidden_size=4,- num_hidden_layers=1,- vocab_size=8,- intermediate_size=8,- ),- )+ if model_cfg is None:+ model_cfg = types.SimpleNamespace(+ model_type="qwen4_exp",+ text_config=types.SimpleNamespace(+ hidden_size=4,+ num_hidden_layers=1,+ vocab_size=8,+ intermediate_size=8,+ ),+ )external = types.SimpleNamespace(bits=4, nbytes=1_024, storage_nbytes=256)index = types.SimpleNamespace(n_layers=1,@@ -801,15 +814,18 @@ def _drive_qwen4_streaming_setup(tmp_path, monkeypatch, resolve_weights=None):)monkeypatch.setattr("peft.LoraConfig", lambda **kwargs: types.SimpleNamespace(**kwargs))monkeypatch.setattr(- "soup_cli.utils.layer_stream.stream_arch_of", lambda *_a, **_k: "qwen4_exp"+ "soup_cli.utils.layer_stream.stream_arch_of", lambda *_a, **_k: arch)monkeypatch.setattr("soup_cli.utils.layer_shard.resolve_shard_dir",lambda *_a, **_k: str(tmp_path / "shards"),)- monkeypatch.setattr(- "soup_cli.utils.layer_shard.shard_checkpoint", lambda *_a, **_k: index- )+ def _shard(*_args, **kwargs):+ if shard_calls is not None:+ shard_calls.append(kwargs)+ return index++ monkeypatch.setattr("soup_cli.utils.layer_shard.shard_checkpoint", _shard)monkeypatch.setattr("soup_cli.utils.layer_shard.source_weight_bytes", lambda *_a, **_k: 1_024)