Skip to content

armgit / Soup

Public Imported from GitHub
0

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

feat(stream): training.stream_expert_layout lets soup train stream MoE experts (#2029)

Alpamys Makazhan07900ee74396
diff --git a/benchmarks/probe-rtx5070-moonlight-16b.md b/benchmarks/probe-rtx5070-moonlight-16b.md
index 9d4fb7d5..7fc35589 100644
--- a/benchmarks/probe-rtx5070-moonlight-16b.md
+++ b/benchmarks/probe-rtx5070-moonlight-16b.md
@@ -100,6 +100,26 @@ What Soup reported:
**COMPLETES:** finite loss, adapter written. A 9-row dataset says nothing about quality; this
shows that the CLI path, from config to adapter, runs on this base on an 8 GB card.
+### 4.2 Product path with `training.stream_expert_layout: per_expert` (#2029)
+
+2026-10-19 12:32:19Z to 12:52:59Z, AC power, 6 GB RAM free at start. The other sessions were told
+beforehand; free RAM dipped near zero during the run because a foreign WSL VM held ~6.5 GB.
+
+Setup: the same config and command as section 4.1, plus `stream_expert_layout: per_expert`, with
+`SOUP_LAYER_STREAM_CACHE_DIR=D:/soup-bench/soup-cache-experts`. Code: the #2029 branch at
+c40776c1b plus its uncommitted changes, which are what 76bab8e7 committed.
+
+What Soup reported:
+- **Store.** The per-expert NF4 cache came to 8.7 GB, so `auto` chose the RAM tier: 1.81 GB pinned (the dense parts); the experts are read from the cache volume.
+- **Pre-flight.** It printed `experts 0.044 GB for the routed expert in flight`.
+- **Steps.** 27 steps in 1,128 s, ~41.8 s per step, against ~15.7 s in section 4.1.
+- **Loss.** Training loss 4.775 at step 10, then 3.165 at step 20; mean 3.827; validation loss 3.611 after epoch 3.
+- **GPU peak.** 1.0 of 7.9 GB, against 3.1 GB in section 4.1.
+- **Adapter.** Written: `adapter_model.safetensors`, 7,134,912 bytes.
+
+**COMPLETES:** finite loss, adapter written. Under 4bit the routed experts are NF4 here and bf16
+in section 4.1, so the two runs' losses come from numerically different bases.
+
## 5. Verdict
**Both arms COMPLETE.** LoRA training steps of Moonlight-16B, a 16 B-parameter DeepSeek-V3-architecture MoE that does not fit this 8 GB card resident, run on the laptop:
diff --git a/changelog.d/0.76.0/2029.added.md b/changelog.d/0.76.0/2029.added.md
new file mode 100644
index 00000000..bd55324a
--- /dev/null
+++ b/changelog.d/0.76.0/2029.added.md
@@ -0,0 +1,7 @@
+- **`training.stream_expert_layout: per_expert` streams a DeepSeek-V3-family MoE one routed expert
+ at a time from `soup train`** (default `fused`). The layer buffers then hold only the dense part, so
+ the VRAM bound no longer grows with the expert count. In `soup train` on an 8 GB laptop card,
+ Moonlight-16B LoRA peaked at 1.0 GB of GPU memory against 3.1 GB fused, at about 2.7x the step
+ time (`benchmarks/probe-rtx5070-moonlight-16b.md`). Other architectures are refused at setup,
+ `moe_lora` is refused with it, the VRAM pre-flight charges the expert in flight, and a cache volume
+ that is not NVMe is warned about. (#2029)
diff --git a/docs/config-reference.md b/docs/config-reference.md
index 63fb4206..e375d460 100644
--- a/docs/config-reference.md
+++ b/docs/config-reference.md
@@ -285,7 +285,7 @@ Sections:
| `training.loss_watchdog_threshold` | `float` | `3.0` | `> 0`, `<= 100.0` | Stop training if loss exceeds this threshold |
| `training.loss_watchdog_patience` | `int` | `5` | `>= 1`, `<= 1000` | Consecutive high-loss steps before stopping |
| `training.rewind_log` | `bool` | `true` | | Write &lt;output>/rewind.jsonl: the dataset rows in every training micro-batch with each row's loss, read by `soup rewind` to name the rows behind a loss spike. SFT only (transformers and MLX, single process); resumed runs and packing turn it off with one warning. |
-| `training.loss_spike_recovery` | `bool` | `false` | | On watchdog trigger: write &lt;output>/spike_recovery.json with decayed LR and attempt count for re-launch (instead of bare stop). Requires loss_watchdog=true. |
+| `training.loss_spike_recovery` | `bool` | `false` | | On watchdog trigger: write &lt;output>/spike_recovery.json with decayed LR and attempt count for re-launch (tracks attempts and caps recovery). Requires loss_watchdog=true. |
| `training.loss_spike_recovery_max_attempts` | `int` | `3` | `>= 1`, `<= 10` | Max number of spike-recovery attempts before giving up |
| `training.loss_spike_recovery_lr_decay` | `float` | `0.5` | `> 0.0`, `< 1.0` | Multiply LR by this factor on each spike recovery (0.5 = halve) |
| `training.relora_steps` | `int \| null` | `null` | `>= 1`, `<= 10000000` | Fire a paper-faithful ReLoRA restart every N global steps: merge the LoRA update into the base weight, reinitialize lora_A/lora_B, and optionally clear optimizer state. None disables. Requires float LoRA (training.quantization defaults to '4bit' and must be set to 'none'; incompatible with VeRA, DoRA, layer streaming, and FSDP2 compile). |
@@ -316,6 +316,7 @@ Sections:
| `training.stream_vram_override` | `int \| null` | `null` | `>= 0` | Bytes to assume free instead of measuring torch.cuda.mem_get_info(). mem_get_info() is a device-level driver query, so it cannot see a per-process cap (set_per_process_memory_fraction, a MIG slice, a card another process is also using), so on that hardware the pre-flight sees the whole device's free VRAM regardless of what this process can actually use. Set this to replace the measured figure in either direction: raise it to let a known-safe over-prediction through, or lower it to make the pre-flight enforce a cap the driver itself cannot report. |
| `training.stream_vram_probe` | `bool` | `false` | | Decide the layer-streaming VRAM pre-flight on a MEASUREMENT instead of the fitted formula. One real forward+backward runs at the configured shape after the streamed model is built, and its peak decides whether the run proceeds; the prediction is printed beside it so a divergence is visible. The formula under-predicts past seq 4352 (measured 0.934x the real peak at seq 5120 and 0.787x at 6144), which is the direction that does not announce itself — an OOM on Linux, a silent spill to host memory on Windows. Against the probe the same formula reads 0.992x at seq 4096 and 0.830x at 5120, because the probe itself runs 12.5-14.3% above the real training step — the direction that makes it safe as a gate. Off by default: it costs one step (1-5 s measured) and it can refuse a run the formula accepts. task='sft' only: the probe runs a plain causal-LM forward+backward, which IS the SFT step but not a preference loss. At the one preference shape measured it reads +13.5% high (probe 6.021 GB against a real DPO step's 5.304 GB) — the same safe direction it shows for SFT — but one shape is not a validation, so the restriction stands until it is measured across shapes. |
| `training.stream_nf4_scale_cache` | `bool` | `false` | | Keep each streamed NF4 weight's expanded fp32 block scales on the compute device after its first use. A double-quantised weight stores its scales as 8-bit codes plus a nested scale and offset, and bitsandbytes' dequantise + linear path expands them on every visit (forward and checkpoint recompute): two extra kernels and a temporary per projection. The base is frozen, so the expansion is done once per (layer, weight) and reused; results are bit-identical. Costs 4 bytes per 64-element block of VRAM for the whole run (416 MiB on Mistral-7B), which the pre-flight charges up front. bitsandbytes' fused 4-bit GEMM path expands the scales inside its kernel and is left unchanged. Needs quantization='4bit' with double quantization (the default). Off by default. |
+| `training.stream_expert_layout` | `str` | `"fused"` | one of `"fused"`, `"per_expert"` | How a MoE base's routed experts are streamed. 'fused' (the default) keeps each MoE layer's experts inside its layer file, so the largest layer bounds the card. 'per_expert' writes them to their own file, one pair of matrices per expert (NF4 per matrix under quantization='4bit'), and reads an expert only when the router picks it, again in the backward: the decoder-layer buffers hold the dense part alone, so the VRAM bound no longer grows with the expert count. Each routed expert is read about three times per step from the cache volume, so expect slower steps (an NVMe volume is recommended). Under quantization='4bit' the routed experts are NF4 here but stay at the stream dtype with 'fused', so the two layouts train against numerically different bases. Admitted for DeepSeek-V3-family bases (model_type deepseek_v3); adapters on the routed experts (moe_lora) are refused with it. |
| `training.stream_disk_kind` | `str \| null` | `null` | one of `"nvme"`, `"ssd"`, `"hdd"` | Override the auto-detected disk media type for the streaming disk overflow tier. Detection classifies a device by a measured sequential read when the kernel's rotational flag is unreliable — virtio and other paravirtual disks report spinning with no media hint, so a fast cloud disk is otherwise refused (#365). Set this for the case where even that is wrong: 'nvme' forces the disk tier on, 'ssd'/'hdd' force it off. The resolved value is printed beside what was detected. |
| `training.packing` | `bool` | `false` | | Pack multiple short samples into one sequence for faster training |
| `training.multipack` | `bool` | `false` | | Use FFD bin-packing sampler to maximise tokens-per-batch on uneven-length data. Mutually exclusive with packing. Only supported for sft / pretrain tasks (transformers backend). (v0.37.0). |
diff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.md
index 7dcf7545..b7caca5b 100644
--- a/docs/performance-and-quantization.md
+++ b/docs/performance-and-quantization.md
@@ -479,16 +479,33 @@ 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).
+**Expert-granularity streaming (`training.stream_expert_layout: per_expert`, DeepSeek-V3 family).**
+
+What it does:
+- The sharder stores each MoE layer's routed experts in their own file, one pair of matrices per expert, NF4 per matrix under `quantization: 4bit`.
+- The runtime reads an expert only when the router picks it, and again in the backward, so the layer buffers hold just the dense part (attention, norms, router, shared expert).
+- The VRAM bound no longer grows with the expert count.
+
+Measured (all in the [Moonlight-16B record](../benchmarks/probe-rtx5070-moonlight-16b.md) unless linked):
+- **Numerics.** It matches transformers' eager experts bit for bit, forward and backward, on the same weights ([gate](../benchmarks/gate-expert-streaming.md)).
+- **Harness steps** (seq 512): peak allocated VRAM 1,882 MiB against 3,993 MiB fused, at 17.5-18.0 s against 8.9-9.8 s per step.
+- **`soup train`** (9 short rows): Soup reported a GPU peak of 1.0 GB against 3.1 GB fused, at about 42 s against 16 s per step.
+
+It buys capacity, not speed:
+- Each routed expert is read from the cache volume about three times per step (forward, recompute, backward), one at a time. Expect slower steps, and keep the cache on NVMe: Soup warns when the volume is not.
+- The default stays `fused`.
+- Under `quantization: 4bit` the routed experts are NF4 here but stay at the stream dtype with `fused`, so the two layouts train against numerically different bases.
+
+What the VRAM pre-flight counts:
+- the layer buffers, measured from the dense-only layer files;
+- plus one routed expert in flight, shown as an `experts` line.
+
+The disk pre-flight charges the NF4 rate to every parameter, which is close to this layout's cache (8.7 GB for Moonlight) and under-counts a fused MoE cache, whose experts stay unquantised (30.6 GB).
+
+Limits and refusals:
+- **Architecture.** Only `model_type: deepseek_v3` is admitted. Any other base is refused before weights are resolved.
+- **Adapters on routed experts.** `moe_lora` is refused with this layout, because a streamed expert has nowhere to keep an adapter between its visits. Adapt attention or the shared expert instead.
+- **Older Soup versions.** A Soup from before this layout accepts a per-expert cache as reusable and then fails at install ("shard is missing decoder weights"). Delete the cache directory, or re-shard with `fused`, before going back to an older version.
**`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,
@@ -738,7 +755,8 @@ prints this advice when it sees you accumulating.
- `unfrozen_parameters`, `lisa_enabled`, `packing`, `multipack`, `use_fsdp2_compile`, `train_router_only`, `expand_layers` → each independently rewrites or re-freezes the same layers
- `use_cut_ce` is refused with `stream_layers` (#1206): streamed setup does not install the resident CCE patch. Disable CCE to stream with the conservative full-logits budget, or disable streaming to use resident CCE. A tiny local streamed Llama was exercised through sharding, forward/loss and backward on CPU; this is no CUDA memory measurement.
- `use_liger` / `use_flash_attn` → **not reached at all** under streaming (#1692). Both are read by the *resident* setup: Liger patches the MLP forward there, and flash-attn is handed to `from_pretrained` as `attn_implementation`. A streamed model is built by `from_config` with no attention argument and no Liger patch, and `_liger_applied` is never set, so `use_liger_kernel` misses `TrainingArguments` too. These are the switches you reach for when a streamed run will not fit, so they are refused rather than dropped; each is offered again once it is wired and shown to engage on a streamed model. On every task outside `{sft, tts}` they are already refused at config load (#806)
-- `stream_source` / `stream_ngram_source` / `stream_buffers` / `stream_read_ahead` / `stream_vram_override` / `stream_vram_probe` / `stream_nf4_scale_cache` / `stream_disk_kind` / `stream_pin` set while `stream_layers: false` → a footgun, refused
+- `stream_source` / `stream_ngram_source` / `stream_buffers` / `stream_read_ahead` / `stream_vram_override` / `stream_vram_probe` / `stream_nf4_scale_cache` / `stream_expert_layout` / `stream_disk_kind` / `stream_pin` set while `stream_layers: false` → a footgun, refused
+- `stream_expert_layout: per_expert` with `moe_lora` → refused: a routed expert streamed one at a time has nowhere to keep an adapter. On a base that is not `model_type: deepseek_v3` → refused at setup, before the weights are resolved
- `stream_nf4_scale_cache` without `quantization: 4bit` and double quantization → refused: there are no nested NF4 scales to cache
- a non-default `stream_read_ahead` beside `stream_source: ram` → refused. The read-ahead reader belongs to the NVMe disk tier and `ram` never falls back to it, so the setting would validate, be documented, and reach nothing. The default is accepted, because a default is not a decision
- 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
diff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.py
index c353733d..5c34eaa4 100644
--- a/src/soup_cli/config/schema.py
+++ b/src/soup_cli/config/schema.py
@@ -3714,6 +3714,25 @@ class TrainingConfig(BaseModel):
"double quantization (the default). Off by default."
),
)
+ stream_expert_layout: Literal["fused", "per_expert"] = Field(
+ default="fused",
+ description=(
+ "How a MoE base's routed experts are streamed. 'fused' (the default) "
+ "keeps each MoE layer's experts inside its layer file, so the largest "
+ "layer bounds the card. 'per_expert' writes them to their own file, one "
+ "pair of matrices per expert (NF4 per matrix under quantization='4bit'), "
+ "and reads an expert only when the router picks it, again in the "
+ "backward: the decoder-layer buffers hold the dense part alone, so the "
+ "VRAM bound no longer grows with the expert count. Each routed expert "
+ "is read about three times per step from the cache volume, so expect "
+ "slower steps (an NVMe volume is recommended). Under quantization='4bit' "
+ "the routed experts are NF4 here but stay at the stream dtype with "
+ "'fused', so the two layouts train against numerically different "
+ "bases. Admitted for DeepSeek-V3-family bases (model_type "
+ "deepseek_v3); adapters on the routed experts (moe_lora) are refused "
+ "with it."
+ ),
+ )
stream_disk_kind: Optional[Literal["nvme", "ssd", "hdd"]] = Field(
default=None,
description=(
@@ -6761,6 +6780,7 @@ class SoupConfig(BaseModel):
or tcfg.stream_vram_override is not None
or tcfg.stream_vram_probe
or tcfg.stream_nf4_scale_cache
+ or tcfg.stream_expert_layout != "fused"
or tcfg.stream_disk_kind is not None
or tcfg.stream_pin is not None
):
@@ -6768,8 +6788,9 @@ class SoupConfig(BaseModel):
"training.stream_source / training.stream_ngram_source / "
"training.stream_buffers / training.stream_read_ahead / "
"training.stream_vram_override / training.stream_vram_probe "
- "/ training.stream_nf4_scale_cache / training.stream_disk_kind "
- "/ training.stream_pin set but stream_layers is false; set "
+ "/ training.stream_nf4_scale_cache / training.stream_expert_layout "
+ "/ training.stream_disk_kind / training.stream_pin set but "
+ "stream_layers is false; set "
"stream_layers=true to stream the base layer-by-layer."
)
return self
@@ -6786,6 +6807,15 @@ class SoupConfig(BaseModel):
f"bnb_4bit_use_double_quant={tcfg.bnb_4bit_use_double_quant!r}. "
"Without them there are no nested NF4 scales to cache."
)
+ if tcfg.stream_expert_layout == "per_expert" and tcfg.moe_lora:
+ # Each routed expert is fetched, used and dropped one at a time; an
+ # adapter on it would have nowhere to live between the visits.
+ raise ValueError(
+ "training.stream_expert_layout='per_expert' streams the routed "
+ "experts one at a time and cannot train adapters on them; unset "
+ "training.moe_lora (adapt attention or the shared expert instead) "
+ "or use stream_expert_layout='fused'."
+ )
# #971 — `stream_source: 'ram'` INSISTS on the RAM tier: 'ram' insists,
# 'disk' forces, 'auto' falls back (trainer/stream_setup.py). The
# read-ahead reader belongs to the NVMe disk tier, so a non-default
diff --git a/src/soup_cli/trainer/stream_setup.py b/src/soup_cli/trainer/stream_setup.py
index 8713b9fb..d663948d 100644
--- a/src/soup_cli/trainer/stream_setup.py
+++ b/src/soup_cli/trainer/stream_setup.py
@@ -735,7 +735,9 @@ class StreamingSetupMixin:
# is worse than finding out now.
refuse_if_data_parallel(self.device)
+ from soup_cli.utils.expert_stream import EXPERT_LAYOUT_PER_EXPERT
from soup_cli.utils.layer_shard import (
+ PER_EXPERT_LAYOUT_ARCHS,
QUANT_NF4,
QUANT_NONE,
checkpoint_source_components,
@@ -797,6 +799,20 @@ class StreamingSetupMixin:
# Allowlist, not a heuristic — a half-supported architecture streams
# weights into the wrong module and mis-trains silently.
arch = stream_arch_of(model_config)
+ # training.stream_expert_layout, in the sharder's spelling ("" = fused).
+ # Refused here for an architecture the layout is not gated on: before any
+ # weight is resolved, downloaded or sharded.
+ expert_layout = (
+ EXPERT_LAYOUT_PER_EXPERT
+ if getattr(tcfg, "stream_expert_layout", "fused") == "per_expert"
+ else ""
+ )
+ if expert_layout and arch not in PER_EXPERT_LAYOUT_ARCHS:
+ raise ValueError(
+ "training.stream_expert_layout='per_expert' is gated on resident parity "
+ f"per architecture; admitted: {', '.join(PER_EXPERT_LAYOUT_ARCHS)}; this "
+ f"base streams as {arch!r}. Use stream_expert_layout='fused'."
+ )
on_cuda = str(self.device).startswith("cuda")
# #385 — ASK THE CARD. bf16 needs Ampere, and a T4 (Colab free), a P100
@@ -868,6 +884,7 @@ class StreamingSetupMixin:
quant_device_kind,
"qwen4_ple" if arch == "qwen4_exp" else "",
stripe_roots=stripe_roots,
+ expert_layout=expert_layout,
)
cached_bytes = None
if cached is not None:
@@ -983,7 +1000,22 @@ class StreamingSetupMixin:
if arch == "deepseek_v3"
else None
),
+ expert_layout=expert_layout,
)
+ if expert_layout:
+ # Whatever the tier, per_expert reads every routed expert from the cache
+ # volume (about three times per step: forward, recompute, backward); the
+ # RAM tier holds only the dense part, so the tier choice never looks at it.
+ experts_disk = resolve_disk_kind(
+ shard_dir, tcfg.stream_disk_kind, notify=console.print
+ )
+ if experts_disk.kind != "nvme":
+ console.print(
+ "[yellow]training.stream_expert_layout='per_expert' reads every routed "
+ "expert from the cache volume about three times per step, and that "
+ f"volume reads as {for_terminal(repr(str(experts_disk.kind)))}, not NVMe: "
+ "expect steps bound by that disk.[/]"
+ )
# 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. Read
# with getattr like `external_tensors` below: an index without the field is one root.
@@ -1378,11 +1410,16 @@ class StreamingSetupMixin:
prediction is demoted to advice instead, because refusing here would
prevent the measurement that exists to overrule it.
"""
+ from soup_cli.utils.expert_stream import (
+ EXPERT_LAYOUT_PER_EXPERT,
+ expert_stream_vram_bytes,
+ )
from soup_cli.utils.layer_stream import (
LOGITS_BYTES_PER_ELEMENT,
accumulation_advice,
calibrated_logits_bytes_per_element,
decide_stream_fit,
+ dtype_bytes,
estimate_logits_bytes,
estimate_stream_peak_vram,
forecast_stream_throughput,
@@ -1398,6 +1435,17 @@ class StreamingSetupMixin:
if getattr(tcfg, "stream_nf4_scale_cache", False)
else 0
)
+ # training.stream_expert_layout='per_expert': the layer buffers above hold
+ # only the dense part (the layer files no longer carry the experts); one
+ # routed expert is in flight at a time on top of them.
+ expert_bytes = 0
+ expert_shapes = getattr(index, "expert_shapes", None)
+ if getattr(index, "expert_layout", "") == EXPERT_LAYOUT_PER_EXPERT and expert_shapes:
+ expert_bytes = expert_stream_vram_bytes(
+ expert_shapes,
+ dtype_bytes=dtype_bytes(index.dtype),
+ quantised=bool(getattr(index, "expert_quant_specs", None)),
+ )
shape_cfg = self._stream_shape_config(model_config)
vocab = int(getattr(shape_cfg, "vocab_size", 0) or 0)
@@ -1441,7 +1489,7 @@ class StreamingSetupMixin:
batch_size=rows,
logits_bytes_per_element=calibrated,
large_layer_bytes=large_layer_bytes,
- persistent_bytes=scale_cache_bytes,
+ persistent_bytes=scale_cache_bytes + expert_bytes,
)
logits = estimate_logits_bytes(
vocab_size=vocab, seq_len=seq_len, batch_size=rows, bytes_per_element=calibrated
@@ -1458,6 +1506,11 @@ class StreamingSetupMixin:
f" scale cache {scale_cache_bytes / 1e9:.2f} GB resident "
"(training.stream_nf4_scale_cache), included above"
)
+ if expert_bytes:
+ lines.append(
+ f" experts {expert_bytes / 1e9:.3f} GB for the routed expert in flight "
+ "(training.stream_expert_layout='per_expert'), included above"
+ )
if calibrated > LOGITS_BYTES_PER_ELEMENT:
lines.append(
f" logits calibrated {calibrated:.3f} B/element on this stack, "
diff --git a/src/soup_cli/utils/layer_shard.py b/src/soup_cli/utils/layer_shard.py
index 51eb0510..e12386c4 100644
--- a/src/soup_cli/utils/layer_shard.py
+++ b/src/soup_cli/utils/layer_shard.py
@@ -145,6 +145,8 @@ def layer_buffer_keys(arch: str) -> Tuple[str, ...]:
#: 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",)
+#: Public name for the trainer's early refusal (``training.stream_expert_layout``).
+PER_EXPERT_LAYOUT_ARCHS = _PER_EXPERT_LAYOUT_ARCHS
_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$"
diff --git a/tests/fixtures/recipe_config_snapshots.json b/tests/fixtures/recipe_config_snapshots.json
index 0b809ce6..15d277ea 100644
--- a/tests/fixtures/recipe_config_snapshots.json
+++ b/tests/fixtures/recipe_config_snapshots.json
@@ -267,6 +267,7 @@
"training.skip_zero_advantage": false,
"training.stream_buffers": 2,
"training.stream_disk_kind": null,
+ "training.stream_expert_layout": "fused",
"training.stream_layers": false,
"training.stream_nf4_scale_cache": false,
"training.stream_ngram_source": "auto",
diff --git a/tests/test_issue602_qwen4_ple_streaming.py b/tests/test_issue602_qwen4_ple_streaming.py
index 2bed5058..5e02803c 100644
--- a/tests/test_issue602_qwen4_ple_streaming.py
+++ b/tests/test_issue602_qwen4_ple_streaming.py
@@ -701,6 +701,9 @@ def _drive_qwen4_streaming_setup(
shard_calls=None,
load_calls=None,
trust_remote_code=False,
+ tcfg_overrides=None,
+ disk_kind="ssd",
+ disk_calls=None,
):
"""Drive the real `_setup_streaming_transformers()` for a qwen4_exp base.
@@ -718,7 +721,10 @@ def _drive_qwen4_streaming_setup(
(`tests/test_deepseek_v3_streaming.py`); `shard_calls`, when a list, receives
the keyword arguments of every `shard_checkpoint` call; `load_calls`, when a
dict, receives the keyword arguments of the tokenizer, config and
- `build_streamed_model` calls under "tokenizer", "config" and "build".
+ `build_streamed_model` calls under "tokenizer", "config" and "build";
+ `tcfg_overrides`, when a dict, sets extra training-config attributes;
+ `disk_kind` is what the stubbed `resolve_disk_kind` reports; `disk_calls`,
+ when a list, receives the (path, override) of every call to it.
"""
import sys
import types
@@ -765,6 +771,8 @@ def _drive_qwen4_streaming_setup(
alpha_pattern=None,
),
)
+ for name, value in (tcfg_overrides or {}).items():
+ setattr(tcfg, name, value)
if model_cfg is None:
model_cfg = types.SimpleNamespace(
model_type="qwen4_exp",
@@ -868,10 +876,12 @@ def _drive_qwen4_streaming_setup(
"soup_cli.utils.layer_stream_runtime.large_layer_buffer_bytes",
lambda *_a, **_k: 0,
)
- monkeypatch.setattr(
- "soup_cli.utils.layer_stream.resolve_disk_kind",
- lambda *_a, **_k: types.SimpleNamespace(kind="ssd"),
- )
+ def _resolve_disk_kind(path=None, override=None, **_kwargs):
+ if disk_calls is not None:
+ disk_calls.append((path, override))
+ return types.SimpleNamespace(kind=disk_kind)
+
+ monkeypatch.setattr("soup_cli.utils.layer_stream.resolve_disk_kind", _resolve_disk_kind)
monkeypatch.setattr(
"soup_cli.utils.layer_stream.render_stream_panel", lambda *_a, **_k: "panel"
)
diff --git a/tests/test_stream_expert_layout.py b/tests/test_stream_expert_layout.py
new file mode 100644
index 00000000..ce2f3df4
--- /dev/null
+++ b/tests/test_stream_expert_layout.py
@@ -0,0 +1,366 @@
+"""``training.stream_expert_layout``: expert-granularity streaming from ``soup train``.
+
+``per_expert`` shards a DeepSeek-V3-family base with each MoE layer's routed
+experts in their own file and streams one expert at a time
+(``utils/expert_stream.py``), so the VRAM bound no longer grows with the expert
+count. The setup passes the layout to the sharder and to the pre-flight's cache
+check, charges the expert path's VRAM, and refuses an architecture the layout is
+not gated on before anything is downloaded or written.
+"""
+
+from types import SimpleNamespace
+
+import pytest
+
+from soup_cli.config.loader import load_config_from_string
+
+
+def _cfg(**training):
+ body = "\n".join(f" {k}: {v}" for k, v in training.items())
+ return (
+ "base: HuggingFaceTB/SmolLM2-135M\n"
+ "task: sft\n"
+ "data:\n"
+ " train: d.jsonl\n"
+ " max_length: 512\n"
+ "training:\n"
+ " batch_size: 1\n"
+ " lora:\n"
+ " r: 8\n" + body + "\n"
+ )
+
+
+# --------------------------------------------------------------------------
+# schema
+# --------------------------------------------------------------------------
+class TestSchema:
+ def test_default_is_fused(self):
+ cfg = load_config_from_string(_cfg(stream_layers="true"))
+ assert cfg.training.stream_expert_layout == "fused"
+
+ def test_per_expert_parses_with_streaming_on(self):
+ cfg = load_config_from_string(
+ _cfg(stream_layers="true", quantization="4bit", stream_expert_layout="per_expert")
+ )
+ assert cfg.training.stream_expert_layout == "per_expert"
+
+ def test_per_expert_without_streaming_is_the_stream_footgun(self):
+ with pytest.raises(ValueError) as exc:
+ load_config_from_string(_cfg(stream_expert_layout="per_expert"))
+ text = str(exc.value)
+ assert "training.stream_expert_layout" in text
+ assert "stream_layers is false" in text
+
+ def test_an_explicit_fused_without_streaming_is_not_the_footgun(self):
+ cfg = load_config_from_string(_cfg(stream_expert_layout="fused"))
+ assert cfg.training.stream_expert_layout == "fused"
+
+ def test_an_unknown_layout_is_refused(self):
+ with pytest.raises(ValueError, match="stream_expert_layout"):
+ load_config_from_string(_cfg(stream_layers="true", stream_expert_layout="experts"))
+
+ @pytest.mark.parametrize("quantization", ["none", "4bit", "8bit"])
+ def test_per_expert_refuses_adapters_on_the_routed_experts(self, quantization):
+ with pytest.raises(ValueError) as exc:
+ load_config_from_string(
+ _cfg(
+ stream_layers="true",
+ stream_expert_layout="per_expert",
+ moe_lora="true",
+ quantization=quantization,
+ )
+ )
+ text = str(exc.value)
+ assert "training.stream_expert_layout='per_expert'" in text
+ assert "moe_lora" in text
+
+
+# --------------------------------------------------------------------------
+# setup wiring (the shared driver in tests/test_issue602_qwen4_ple_streaming.py)
+# --------------------------------------------------------------------------
+def _deepseek_cfg(model_type="deepseek_v3"):
+ return SimpleNamespace(
+ model_type=model_type,
+ hidden_size=4,
+ num_hidden_layers=1,
+ vocab_size=8,
+ intermediate_size=8,
+ )
+
+
+ ("layout", "expected"),
+ [("per_expert", "per_expert"), ("fused", "")],
+ ids=["per_expert", "fused"],
+)
+def test_setup_hands_the_layout_to_the_sharder(tmp_path, monkeypatch, layout, expected):
+ from tests.test_issue602_qwen4_ple_streaming import _drive_qwen4_streaming_setup
+
+ calls = []
+ _drive_qwen4_streaming_setup(
+ tmp_path, monkeypatch, arch="deepseek_v3", model_cfg=_deepseek_cfg(),
+ shard_calls=calls, tcfg_overrides={"stream_expert_layout": layout},
+ )
+ assert len(calls) == 1
+ assert calls[0]["expert_layout"] == expected
+
+
+def test_a_fake_training_config_without_the_field_still_shards_fused(tmp_path, monkeypatch):
+ """Older trainer configs and test fakes have no attribute: fused, as before."""
+ from tests.test_issue602_qwen4_ple_streaming import _drive_qwen4_streaming_setup
+
+ calls = []
+ _drive_qwen4_streaming_setup(
+ tmp_path, monkeypatch, arch="deepseek_v3", model_cfg=_deepseek_cfg(), shard_calls=calls
+ )
+ assert calls[0]["expert_layout"] == ""
+
+
+def test_setup_refuses_per_expert_for_an_ungated_arch_before_sharding(tmp_path, monkeypatch):
+ from tests.test_issue602_qwen4_ple_streaming import _drive_qwen4_streaming_setup
+
+ def _resolve_must_not_run(*_args, **_kwargs):
+ raise AssertionError("weights were resolved before the refusal")
+
+ calls = []
+ with pytest.raises(ValueError) as exc:
+ _drive_qwen4_streaming_setup(
+ tmp_path, monkeypatch, resolve_weights=_resolve_must_not_run, arch="llama",
+ model_cfg=_deepseek_cfg("llama"), shard_calls=calls,
+ tcfg_overrides={"stream_expert_layout": "per_expert"},
+ )
+ text = str(exc.value)
+ assert "training.stream_expert_layout='per_expert'" in text
+ assert "deepseek_v3" in text and "llama" in text
+ assert calls == []
+
+
+def _captured_setup_output(tmp_path, monkeypatch, *, layout, disk_kind, **driver_kwargs):
+ import io
+ import re
+
+ from rich.console import Console
+
+ import soup_cli.trainer.stream_setup as stream_setup
+ from tests.test_issue602_qwen4_ple_streaming import _drive_qwen4_streaming_setup
+
+ buffer = io.StringIO()
+ monkeypatch.setattr(stream_setup, "console", Console(file=buffer, width=400))
+ _drive_qwen4_streaming_setup(
+ tmp_path, monkeypatch, arch="deepseek_v3", model_cfg=_deepseek_cfg(),
+ tcfg_overrides={"stream_expert_layout": layout}, disk_kind=disk_kind,
+ **driver_kwargs,
+ )
+ plain = re.sub(r"\x1b\[[0-9;]*m", "", buffer.getvalue())
+ return " ".join(plain.split())
+
+
[email protected]("disk_kind", ["ssd", "hdd", "unknown"])
+def test_a_non_nvme_cache_volume_is_warned_about_for_per_expert(
+ tmp_path, monkeypatch, disk_kind
+):
+ text = _captured_setup_output(
+ tmp_path, monkeypatch, layout="per_expert", disk_kind=disk_kind
+ )
+ assert "reads every routed expert from the cache volume" in text
+ assert f"'{disk_kind}', not NVMe" in text
+
+
+def test_the_volume_probe_reads_the_cache_dir_with_the_users_override(tmp_path, monkeypatch):
+ """The experts are read from the shard cache, not the weights, and a
+ training.stream_disk_kind override wins there as it does for the tier."""
+ from tests.test_issue602_qwen4_ple_streaming import _drive_qwen4_streaming_setup
+
+ seen = []
+ _drive_qwen4_streaming_setup(
+ tmp_path, monkeypatch, arch="deepseek_v3", model_cfg=_deepseek_cfg(),
+ tcfg_overrides={"stream_expert_layout": "per_expert", "stream_disk_kind": "hdd"},
+ disk_kind="hdd", disk_calls=seen,
+ )
+ assert (str(tmp_path / "shards"), "hdd") in seen, seen
+
+
+def test_an_nvme_cache_volume_is_not_warned_about(tmp_path, monkeypatch):
+ text = _captured_setup_output(tmp_path, monkeypatch, layout="per_expert", disk_kind="nvme")
+ assert "not NVMe" not in text
+
+
+def test_the_fused_layout_never_warns_about_the_volume(tmp_path, monkeypatch):
+ text = _captured_setup_output(tmp_path, monkeypatch, layout="fused", disk_kind="hdd")
+ assert "routed expert from the cache volume" not in text
+
+
+def test_the_planner_checks_the_cache_for_the_requested_layout(tmp_path, monkeypatch):
+ """A cached fused store must read as a miss for a per_expert request, or the
+ disk pre-flight under-counts the re-shard it is about to write."""
+ 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 = []
+ monkeypatch.setattr(
+ layer_shard,
+ "inspect_shard_cache",
+ lambda *args, **kwargs: (seen.append(kwargs), (None, "miss"))[1],
+ )
+ 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_cfg(), tcfg_overrides={"stream_expert_layout": "per_expert"},
+ )
+ assert [call.get("expert_layout") for call in seen] == ["per_expert"]
+
+
+# --------------------------------------------------------------------------
+# the pre-flight charges the expert path
+# --------------------------------------------------------------------------
+class _Lora:
+ r = 8
+ target_modules = ["q_proj", "v_proj"]
+
+
+class _ModelConfig:
+ vocab_size = 64
+ hidden_size = 8
+ intermediate_size = 16
+ num_hidden_layers = 4
+
+
+class _Config:
+ data = SimpleNamespace(max_length=4)
+
+
+class _TrainConfig:
+ batch_size = 1
+ stream_buffers = 2
+ stream_vram_probe = False
+ stream_nf4_scale_cache = False
+ lora = _Lora()
+
+
+class _ScaleCacheTrainConfig(_TrainConfig):
+ stream_nf4_scale_cache = True
+
+
+_SMALL_SHAPES = {"gate_up": (64, 32), "down": (32, 32)}
+
+
+def _index(layout, *, dtype="bfloat16", quantised=False, shapes=None, quant_specs=None):
+ shapes = (shapes or _SMALL_SHAPES) if layout else {}
+ return SimpleNamespace(
+ n_layers=4,
+ quant_specs=quant_specs or {},
+ dtype=dtype,
+ expert_layout=layout,
+ expert_shapes=shapes,
+ expert_quant_specs={"gate_up": object(), "down": object()} if quantised else {},
+ )
+
+
+def _charged(monkeypatch, layout, *, tcfg=None, **index_kwargs):
+ from soup_cli.trainer.stream_setup import StreamingSetupMixin
+ from soup_cli.utils import layer_stream
+
+ real = layer_stream.estimate_stream_peak_vram
+ seen = {}
+
+ def capture(**kwargs):
+ seen.update(kwargs)
+ return real(**kwargs)
+
+ monkeypatch.setattr(layer_stream, "estimate_stream_peak_vram", capture)
+ lines, _plan = StreamingSetupMixin()._stream_budget_lines(
+ _Config(),
+ tcfg or _TrainConfig(),
+ model_config=_ModelConfig(),
+ layer_bytes=1000,
+ embed_bytes=0,
+ index=_index(layout, **index_kwargs),
+ on_cuda=False,
+ )
+ return seen.get("persistent_bytes", 0), "\n".join(lines)
+
+
+def test_the_preflight_charges_one_expert_in_flight_for_per_expert(monkeypatch):
+ from soup_cli.utils.expert_stream import expert_stream_vram_bytes
+
+ charged, text = _charged(monkeypatch, "per_expert")
+ want = expert_stream_vram_bytes(
+ {"gate_up": (64, 32), "down": (32, 32)}, dtype_bytes=2, quantised=False
+ )
+ assert want > 0
+ assert charged == want
+ assert "experts" in text and "stream_expert_layout" in text
+
+
+def test_the_experts_line_prints_the_charge_in_gb(monkeypatch):
+ from soup_cli.utils.expert_stream import expert_stream_vram_bytes
+
+ shapes = {"gate_up": (4096, 2048), "down": (2048, 2048)}
+ charged, text = _charged(monkeypatch, "per_expert", shapes=shapes)
+ want = expert_stream_vram_bytes(shapes, dtype_bytes=2, quantised=False)
+ assert charged == want
+ assert 0.001 < want / 1e9 < 1.0
+ assert f"experts {want / 1e9:.3f} GB for the routed expert in flight" in text
+
+
+def test_the_charge_adds_the_scale_cache_to_the_expert_in_flight(monkeypatch):
+ from soup_cli.utils import layer_stream
+ from soup_cli.utils.expert_stream import expert_stream_vram_bytes
+
+ quant_specs = {"w": SimpleNamespace(shape=(128, 128), blocksize=64, nested=True)}
+ charged, text = _charged(
+ monkeypatch, "per_expert", tcfg=_ScaleCacheTrainConfig(), quant_specs=quant_specs
+ )
+ experts = expert_stream_vram_bytes(_SMALL_SHAPES, dtype_bytes=2, quantised=False)
+ cache = layer_stream.nf4_scale_cache_bytes(quant_specs, 4)
+ assert cache > 0 and experts > 0
+ assert charged == cache + experts
+ assert "scale cache" in text and "experts" in text
+
+
+ ("dtype", "width", "quantised"),
+ [("float32", 4, False), ("bfloat16", 2, True), ("float32", 4, True)],
+ ids=["fp32", "nf4-bf16", "nf4-fp32"],
+)
+def test_the_expert_charge_follows_the_store_dtype_and_quantisation(
+ monkeypatch, dtype, width, quantised
+):
+ from soup_cli.utils.expert_stream import expert_stream_vram_bytes
+
+ charged, _text = _charged(monkeypatch, "per_expert", dtype=dtype, quantised=quantised)
+ shapes = {"gate_up": (64, 32), "down": (32, 32)}
+ assert charged == expert_stream_vram_bytes(shapes, dtype_bytes=width, quantised=quantised)
+ assert charged != expert_stream_vram_bytes(
+ shapes, dtype_bytes=2 if width == 4 else 4, quantised=quantised
+ )
+
+
+def test_a_fused_store_is_charged_nothing_extra(monkeypatch):
+ charged, text = _charged(monkeypatch, "")
+ assert charged == 0
+ assert "stream_expert_layout" not in text