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.

fix(stream): size the disk pre-flight's shard cache from the source headers (#2039)

Alpamys Makazhand500ae0dca7c
diff --git a/changelog.d/0.76.0/2039.fixed.md b/changelog.d/0.76.0/2039.fixed.md
new file mode 100644
index 00000000..447e2244
--- /dev/null
+++ b/changelog.d/0.76.0/2039.fixed.md
@@ -0,0 +1 @@
+- **The layer-streaming disk pre-flight no longer under-counts a fused MoE cache under `quantization: 4bit`.** It charged the NF4 rate to every parameter, but the default `fused` expert layout keeps the stacked routed experts at the stream dtype, so for Moonlight-16B-A3B (`deepseek_v3`) it charged 8.23 GB and the sharder then wrote 30.60 GB: a disk could pass the check and fill mid-shard. The cache is now sized from the source safetensors headers (no weight is loaded), tensor by tensor, by the same storage rules the sharder writes with, including the exact NF4 sidecar bytes; for Moonlight it lands within 0.01% of the cache written in both `fused` and `per_expert`. A striped cache splits that same figure over its drives. A dense base under `quantization: 4bit` is now charged more, because its embeddings, head and norms stay at the stream dtype (Llama-3.1-8B 4.14 GB -> 5.70 GB, Llama-3.2-1B 0.64 GB -> 1.03 GB), so a run that passed by less than that margin is now refused. A checkpoint the sharder would refuse is refused before anything is copied. When the files cannot be listed or a header cannot be read, the old rate is charged and the panel says "approximately", as it now also does for a qwen4_exp base that is not an oQ checkpoint. (#2039)
diff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.md
index b7caca5b..a0daed3a 100644
--- a/docs/performance-and-quantization.md
+++ b/docs/performance-and-quantization.md
@@ -500,7 +500,7 @@ 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).
+What the disk pre-flight counts: the cache the sharder will write in the layout you chose, sized from the source safetensors headers (see "Disk pre-flight and shard cache" below). Under `quantization: 4bit` that is the experts at NF4 here and at the stream dtype with `fused`: for Moonlight it charges 9.24 GB here and 30.60 GB fused, within 0.01% of the caches the sharder then wrote. (Before, it charged the NF4 rate to every parameter, 8.23 GB in both layouts, so a fused run could pass the check and fill the disk mid-shard.)
Limits and refusals:
- **Architecture.** Only `model_type: deepseek_v3` is admitted. Any other base is refused before weights are resolved.
@@ -901,15 +901,32 @@ above); it does not make the reference free.
reports the complete projected footprint: the HF/local source, any regular-file copy Soup
still needs, and the per-layer shard cache. Required writes are grouped by target volume and
the run refuses before either write when that volume lacks free space. With
-`SOUP_LAYER_STREAM_STRIPE_DIRS` set, each root is charged the bytes it will receive,
-read from the source safetensors headers (the primary root also holds the embedding,
-head and extras); when a header cannot be read or the model is qwen4_exp the split is
-even and the panel says approximately. Override the two cache roots with
-`SOUP_SPECTRUM_CACHE_DIR` and `SOUP_LAYER_STREAM_CACHE_DIR`; both retain Soup's
-home/cwd/tmp containment policy.
+`SOUP_LAYER_STREAM_STRIPE_DIRS` set, each root is charged the bytes it will receive
+(the primary root also holds the embedding, head and extras); when a header cannot be
+read or the model is qwen4_exp the split is even and the panel says approximately.
+Override the two cache roots with `SOUP_SPECTRUM_CACHE_DIR` and
+`SOUP_LAYER_STREAM_CACHE_DIR`; both retain Soup's home/cwd/tmp containment policy.
A shard cache Soup will reuse is reported at the size of its own files, on every drive it is
-striped over; one it has to write is reported at the estimate, or with two or more drives at
-the larger of the estimate and the bytes derived from the source headers.
+striped over. One it has to write is sized from the source safetensors headers (shapes and
+dtypes only: no weight is loaded), tensor by tensor, by the rules the sharder writes with:
+NF4 for the decoder weights the meta probe converts to 4-bit under `quantization: 4bit`,
+the stream dtype for norms, embeddings, the head, an MoE router and fused routed experts,
+float32 for the layer buffers the runtime loads back, plus an allowance for the file headers
+and the index. A snapshot that still has to be copied is read where the copy step reads it.
+A checkpoint the sharder would refuse (more than 512 decoder layers, a missing layer, an
+incomplete expert, one tensor spelled twice) is refused here, in the sharder's words, before
+anything is copied. When the files cannot be listed or a header cannot be read, the cache is
+charged the NF4 rate for every parameter and the panel says approximately; so does a
+qwen4_exp base that is not an oQ checkpoint, which keeps its source-size figure.
+
+This raises the figure for a dense base under `quantization: 4bit`, because the embeddings,
+an untied head and the norms stay at the stream dtype rather than NF4: Llama-3.1-8B goes from
+4.14 GB to 5.70 GB and Llama-3.2-1B from 0.64 GB to 1.03 GB (derived from their shapes), and
+Mistral-7B-Instruct-v0.3 from 3.74 GB to 4.14 GB, against a 4.14 GB cache measured on disk.
+A run that passed the pre-flight before by less than that margin is now refused: the old
+figure was low, and the sharder would have written the larger amount. The early RAM check
+(`stream_source: ram`, before sharding) still uses the flat NF4 rate; the check after sharding
+measures the real store.
**Two or more NVMe drives.** On a cold store larger than RAM the disk-tier step can wait on the
read (measured for a 70B-shaped store), and then one drive is the ceiling. Set
diff --git a/src/soup_cli/trainer/stream_setup.py b/src/soup_cli/trainer/stream_setup.py
index d663948d..1b5c112a 100644
--- a/src/soup_cli/trainer/stream_setup.py
+++ b/src/soup_cli/trainer/stream_setup.py
@@ -380,11 +380,16 @@ def estimate_stripe_write_shares(
quant: str = "none",
double_quant: bool = True,
arch: str = "",
+ estimate: Any = None,
) -> tuple[list[int], bool]:
"""Calculate per-root shard write shares, charging root 0 non-decoder bytes (#1612).
Returns ``(shares, approximate)``:
- - When source safetensors headers can be parsed without tensor loads:
+ - When ``estimate`` (a ``layer_shard.ShardCacheEstimate``) is given, its
+ per-layer and non-decoder bytes are what each root is charged: the same
+ header-derived sizes the pre-flight's total comes from. ``approximate`` is
+ False.
+ - Otherwise, when source safetensors headers can be parsed without tensor loads:
calculates the parameter count per decoder layer and for non-decoder weights.
Root k is charged decoder bytes for layers placed on root k according to
``layer_roots_for(n_layers, n_roots)``.
@@ -399,6 +404,13 @@ def estimate_stripe_write_shares(
return _stripe_write_shares(total_bytes, n_roots), n_roots > 1
if n_roots <= 1 or total_bytes <= 0:
return _stripe_write_shares(total_bytes, n_roots), False
+ if estimate is not None:
+ return _shares_from_layer_bytes(
+ dict(enumerate(estimate.layer_bytes)),
+ float(estimate.other_bytes),
+ total_bytes=total_bytes,
+ n_roots=n_roots,
+ )
if not weights_dir:
return _stripe_write_shares(total_bytes, n_roots), True
@@ -418,7 +430,6 @@ def estimate_stripe_write_shares(
NF4_BYTES_PER_PARAM_SINGLE,
)
from soup_cli.utils.safetensors_reader import _ITEMSIZE, read_header
- from soup_cli.utils.stripe_roots import layer_roots_for
shards = _discover_safetensors(resolved_dir)
itemsize = _ITEMSIZE.get(dtype, 2)
@@ -453,34 +464,110 @@ def estimate_stripe_write_shares(
else:
non_decoder_bytes += numel * itemsize
- if not decoder_layer_bytes:
- return _stripe_write_shares(total_bytes, n_roots), True
+ return _shares_from_layer_bytes(
+ decoder_layer_bytes, non_decoder_bytes, total_bytes=total_bytes, n_roots=n_roots
+ )
+ except Exception:
+ return _stripe_write_shares(total_bytes, n_roots), True
- n_layers = max(decoder_layer_bytes.keys()) + 1
- layer_roots = layer_roots_for(n_layers, n_roots)
- raw_root_shares = [0.0] * n_roots
- for layer_idx in range(n_layers):
- raw_root_shares[layer_roots[layer_idx]] += decoder_layer_bytes.get(layer_idx, 0.0)
- raw_root_shares[0] += non_decoder_bytes
- raw_total = sum(raw_root_shares)
- if raw_total <= 0:
- return _stripe_write_shares(total_bytes, n_roots), True
+def _shares_from_layer_bytes(
+ decoder_layer_bytes: dict,
+ non_decoder_bytes: float,
+ *,
+ total_bytes: int,
+ n_roots: int,
+) -> tuple[list[int], bool]:
+ """Split ``total_bytes`` over the roots in proportion to what each root receives.
- effective_total = max(int(total_bytes), int(math.ceil(raw_total)))
- raw_scaled = [effective_total * (s / raw_total) for s in raw_root_shares]
- shares = [int(v) for v in raw_scaled]
- remainder = effective_total - sum(shares)
- fractions = sorted(
- range(n_roots), key=lambda i: raw_scaled[i] - shares[i], reverse=True
- )
- for i in range(remainder):
- shares[fractions[i]] += 1
+ Root ``k`` gets the decoder layers ``layer_roots_for`` places on it; root 0 also
+ gets everything outside the decoder layers. The total is raised to the raw sum
+ when that is larger. Falls back to the even split when nothing was measured.
+ """
+ from soup_cli.utils.stripe_roots import layer_roots_for
- return shares, False
- except Exception:
+ if not decoder_layer_bytes:
+ return _stripe_write_shares(total_bytes, n_roots), True
+
+ n_layers = max(decoder_layer_bytes.keys()) + 1
+ layer_roots = layer_roots_for(n_layers, n_roots)
+ raw_root_shares = [0.0] * n_roots
+ for layer_idx in range(n_layers):
+ raw_root_shares[layer_roots[layer_idx]] += decoder_layer_bytes.get(layer_idx, 0.0)
+ raw_root_shares[0] += non_decoder_bytes
+
+ raw_total = sum(raw_root_shares)
+ if raw_total <= 0:
return _stripe_write_shares(total_bytes, n_roots), True
+ effective_total = max(int(total_bytes), int(math.ceil(raw_total)))
+ raw_scaled = [effective_total * (s / raw_total) for s in raw_root_shares]
+ shares = [int(v) for v in raw_scaled]
+ remainder = effective_total - sum(shares)
+ fractions = sorted(range(n_roots), key=lambda i: raw_scaled[i] - shares[i], reverse=True)
+ for i in range(remainder):
+ shares[fractions[i]] += 1
+
+ return shares, False
+
+
+def _planned_source_shards(weights_plan: Any) -> list[str]:
+ """The ``*.safetensors`` files the sharder will read, listed before any copy is made.
+
+ Without a copy that is the weight directory itself, listed the way the sharder
+ lists it. A symlinked Hugging Face snapshot is copied to a regular-file
+ directory first, and that copy does not exist yet when the pre-flight runs, so
+ its files are read where the copy step will read them, through the copy step's
+ own validation: a link is followed only into the snapshot's blob stores.
+ """
+ from soup_cli.utils.layer_shard import _discover_safetensors
+
+ if not weights_plan.needs_materialization:
+ return _discover_safetensors(weights_plan.weights_dir)
+ from soup_cli.utils.spectrum_scan import _snapshot_materialization_entries
+
+ revision = getattr(weights_plan, "source_revision", None)
+ if revision is None:
+ # The copy step refuses such a snapshot; the pre-flight does not guess around it.
+ raise ValueError("cannot read a symlinked Hub snapshot without its resolved revision")
+ entries = _snapshot_materialization_entries(
+ weights_plan.source_dir, source_revision=revision
+ )
+ return sorted(
+ resolved
+ for relative, resolved, _blob in entries
+ if relative.endswith(".safetensors") and not os.path.dirname(relative)
+ )
+
+
+#: What listing the source files can raise (a missing directory, a snapshot the copy
+#: step would refuse, a malformed plan); the pre-flight then falls back.
+_SOURCE_LISTING_ERRORS = (OSError, ValueError, TypeError, OverflowError)
+
+
+def _preflight_cache_estimate(weights_plan: Any, *, arch: str, **estimate_kwargs: Any) -> Any:
+ """The shard cache the sharder will write for this plan, or ``None``.
+
+ ``None`` for an architecture with its own estimator (``qwen4_exp``, whose
+ source is then not even listed), and when the source files cannot be listed
+ or a header cannot be read: the caller then charges the coarse NF4-rate
+ figure and labels it approximate. Nothing else falls back: a bad request
+ (dtype, layout, quant suffixes) and a checkpoint the sharder would refuse
+ raise here, before any copy or shard is written.
+ """
+ from soup_cli.utils.layer_shard import SourceHeaderError, estimate_shard_cache_bytes
+
+ if arch == "qwen4_exp":
+ return None
+ try:
+ source_shards = _planned_source_shards(weights_plan)
+ except _SOURCE_LISTING_ERRORS:
+ return None
+ try:
+ return estimate_shard_cache_bytes(source_shards, arch=arch, **estimate_kwargs)
+ except SourceHeaderError:
+ return None
+
def _render_stream_disk_preflight(
*,
@@ -852,14 +939,67 @@ class StreamingSetupMixin:
+ "[/]"
)
quant_device_kind = str(self.device).split(":", 1)[0] if quant == QUANT_NF4 else ""
+ # DeepSeek-V3 / Kimi K2 store their MTP module as layers past the last
+ # decoder layer; the sharder drops them against the config's count (and the
+ # disk pre-flight does not charge them).
+ stream_num_hidden_layers = (
+ int(self._stream_shape_config(model_config).num_hidden_layers)
+ if arch == "deepseek_v3"
+ else None
+ )
+
+ # The authoritative list of weights to quantise is whatever
+ # replace_with_bnb_linear actually converts, read off a meta skeleton —
+ # not a hard-coded name list that would drift per architecture.
+ #
+ # This builds a second, throwaway skeleton (build_streamed_model makes
+ # its own). Deliberate: a meta skeleton allocates NO weight storage, so
+ # the cost is module-tree construction only, and threading a pre-built
+ # model into build_streamed_model would couple suffix discovery to model
+ # construction for no memory saving.
+ #
+ # It runs BEFORE the weights are resolved: it needs only the config, and
+ # the disk pre-flight below sizes the shard cache by these same suffixes.
+ quant_suffixes = ()
+ moe_targets = None
+ # #798: the ONE helper that turns moe_lora into targets, and refuses a
+ # dropout peft cannot honour on fused experts. This path kept its own
+ # copy of the block, which is why it was the one path with no refusal.
+ # The probe is a meta skeleton and is the only model available here, so
+ # the call happens while it is alive rather than at the attach below.
+ if quant == QUANT_NF4:
+ probe = self._stream_meta_skeleton(cfg.base, dtype=dtype, quant=quant)
+ moe_targets = resolve_moe_lora_targets(probe, tcfg, None, console=console)
+ quant_suffixes = quantised_layer_suffixes(probe)
+ del probe
+ elif tcfg.moe_lora:
+ probe = self._stream_meta_skeleton(cfg.base, dtype=dtype, quant=quant)
+ moe_targets = resolve_moe_lora_targets(probe, tcfg, None, console=console)
+ del probe
def _disk_preflight(weights_plan) -> None:
- shard_estimate = estimate_stream_store_bytes(
- weights_plan.source_bytes,
+ # What the sharder will write, from the source headers and the sharder's
+ # own storage rules: fused routed experts stay at the stream dtype under
+ # NF4, which a flat NF4 rate under-counted ~3.6x on Moonlight-16B.
+ cache_estimate = _preflight_cache_estimate(
+ weights_plan,
dtype=dtype,
+ arch=arch,
quant=quant,
+ quant_suffixes=quant_suffixes,
double_quant=double_quant,
+ expert_layout=expert_layout,
+ num_hidden_layers=stream_num_hidden_layers,
)
+ if cache_estimate is not None:
+ shard_estimate = cache_estimate.total_bytes
+ else:
+ shard_estimate = estimate_stream_store_bytes(
+ weights_plan.source_bytes,
+ dtype=dtype,
+ quant=quant,
+ double_quant=double_quant,
+ )
oq_shard_estimate = estimate_oq_stream_cache_bytes(
weights_plan.weights_dir,
dtype=dtype,
@@ -900,9 +1040,12 @@ class StreamingSetupMixin:
quant=quant,
double_quant=double_quant,
arch=arch,
+ estimate=cache_estimate,
)
dirs = stripe_dirs(shard_dir, stripe_roots)
effective_shard_bytes = max(shard_estimate, sum(shares))
+ # The flat-rate fallback is a guess and says so; a measured cache is exact.
+ coarse = cache_estimate is None and oq_shard_estimate is None
_render_stream_disk_preflight(
source_bytes=weights_plan.source_bytes,
materialized_copy_bytes=weights_plan.materialized_copy_bytes,
@@ -912,7 +1055,7 @@ class StreamingSetupMixin:
shard_write_bytes=shares[0],
shard_path=shard_dir,
stripe_writes=tuple(zip(dirs[1:], shares[1:])),
- approximate=approximate and cached_bytes is None, # a measured cache is exact
+ approximate=(approximate or coarse) and cached_bytes is None,
)
weights_dir = resolve_model_weights(
@@ -953,32 +1096,6 @@ class StreamingSetupMixin:
f"free RAM, or pick a smaller base."
)
- # The authoritative list of weights to quantise is whatever
- # replace_with_bnb_linear actually converts, read off a meta skeleton —
- # not a hard-coded name list that would drift per architecture.
- #
- # This builds a second, throwaway skeleton (build_streamed_model makes
- # its own). Deliberate: a meta skeleton allocates NO weight storage, so
- # the cost is module-tree construction only, and threading a pre-built
- # model into build_streamed_model would couple suffix discovery to model
- # construction for no memory saving.
- quant_suffixes = ()
- moe_targets = None
- # #798: the ONE helper that turns moe_lora into targets, and refuses a
- # dropout peft cannot honour on fused experts. This path kept its own
- # copy of the block, which is why it was the one path with no refusal.
- # The probe is a meta skeleton and is the only model available here, so
- # the call happens while it is alive rather than at the attach below.
- if quant == QUANT_NF4:
- probe = self._stream_meta_skeleton(cfg.base, dtype=dtype, quant=quant)
- moe_targets = resolve_moe_lora_targets(probe, tcfg, None, console=console)
- quant_suffixes = quantised_layer_suffixes(probe)
- del probe
- elif tcfg.moe_lora:
- probe = self._stream_meta_skeleton(cfg.base, dtype=dtype, quant=quant)
- moe_targets = resolve_moe_lora_targets(probe, tcfg, None, console=console)
- del probe
-
console.print(f"[dim]Preparing layer shards -> {shard_dir}[/]")
index = shard_checkpoint(
weights_dir,
@@ -993,13 +1110,7 @@ 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
- ),
+ num_hidden_layers=stream_num_hidden_layers,
expert_layout=expert_layout,
)
if expert_layout:
diff --git a/src/soup_cli/utils/layer_shard.py b/src/soup_cli/utils/layer_shard.py
index e12386c4..1c05ac38 100644
--- a/src/soup_cli/utils/layer_shard.py
+++ b/src/soup_cli/utils/layer_shard.py
@@ -80,6 +80,9 @@ NF4_CODE_KEY = "__nf4_code"
NF4_NESTED_CODE_KEY = "__nf4_nested_code"
NF4_BLOCKSIZE = 64
+#: Blocks per float32 nested absmax under double quantisation (bitsandbytes'
+#: ``compress_statistics``); recorded per weight as ``nested_blocksize``.
+NF4_NESTED_BLOCKSIZE = 256
#: bitsandbytes' own 4-bit types. Read-back values are checked against this.
_SUPPORTED_QUANT_TYPES = ("nf4", "fp4")
#: An index claiming a wilder blocksize than bitsandbytes supports is corrupt.
@@ -904,6 +907,304 @@ def estimate_oq_stream_cache_bytes(
return elements * itemsize + 256 * 1024 * 1024
+#: Header bytes a safetensors file spends per tensor besides the tensor's name: its
+#: dtype, shape and offsets, with the file's 8-byte length field and alignment padding
+#: spread over its tensors (at most 87 per tensor on the Moonlight-16B caches).
+_HEADER_BYTES_PER_TENSOR = 96
+#: ``index.json``: its scalar fields plus a share per listed entry (source file,
+#: stored key, quantised suffix, decoder layer). Measured 62-91 bytes per entry, from
+#: a one-layer Llama to Moonlight-16B (7.9-8.7 KB for ~116 entries).
+_INDEX_BYTES_FIXED = 1024
+_INDEX_BYTES_PER_ENTRY = 128
+_PER_EXPERT_PROJECTIONS = frozenset({"gate_proj", "up_proj", "down_proj"})
+
+
+def nf4_weight_bytes(numel: int, *, double_quant: bool) -> int:
+ """Bytes :func:`_quantize_nf4` stores for ONE weight of ``numel`` elements.
+
+ The packed nibbles (``ceil(numel / 2)`` uint8) plus one absmax per
+ ``NF4_BLOCKSIZE`` block: float32 without double quantisation; with it a uint8
+ per block, one float32 nested absmax per ``NF4_NESTED_BLOCKSIZE`` blocks and
+ one float32 offset. Exact: pinned against bitsandbytes' own output.
+ """
+ if isinstance(numel, bool) or not isinstance(numel, int) or numel <= 0:
+ raise ValueError(f"an NF4 weight needs a positive element count; got {numel!r}")
+ blocks = -(-numel // NF4_BLOCKSIZE)
+ packed = (numel + 1) // 2
+ if not double_quant:
+ return packed + 4 * blocks
+ return packed + blocks + 4 * -(-blocks // NF4_NESTED_BLOCKSIZE) + 4
+
+
+def _nf4_sidecar_suffixes(double_quant: bool) -> Tuple[str, ...]:
+ """The stored key suffixes of one NF4 weight (see :func:`_quantize_nf4`)."""
+ nested = (NESTED_ABSMAX_SUFFIX, NESTED_OFFSET_SUFFIX) if double_quant else ()
+ return ("", ABSMAX_SUFFIX) + nested
+
+
+def _layer_tensor_storage(
+ short: str,
+ *,
+ dtype: str,
+ quantise: bool,
+ suffixes: Iterable[str],
+ fp32_keys: Iterable[str],
+) -> Tuple[str, bool]:
+ """``(stored dtype, NF4?)`` for one decoder-layer key that is not a routed expert.
+
+ The one rule :func:`shard_checkpoint` writes by and
+ :func:`estimate_shard_cache_bytes` sizes by: a key the meta probe found
+ converted to ``Linear4bit`` (``suffixes``) is NF4, a layer buffer the runtime
+ loads back stays float32, everything else is stored at ``dtype``.
+ """
+ stored = "float32" if short in fp32_keys else dtype
+ return stored, bool(quantise) and short in suffixes
+
+
+def _routed_experts_quantised(expert_layout: str, quantise: bool) -> bool:
+ """Whether a stacked-expert architecture's routed experts are stored as NF4.
+
+ ``per_expert`` quantises each expert matrix on its own under NF4. The default
+ fused layout stacks them into the 3-D ``mlp.experts.gate_up_proj`` /
+ ``down_proj`` parameters, which ``replace_with_bnb_linear`` does not convert
+ (they are not ``nn.Linear`` weights), so they stay at the stream dtype.
+ """
+ return bool(quantise) and expert_layout == EXPERT_LAYOUT_PER_EXPERT
+
+
+class SourceHeaderError(ValueError):
+ """A source safetensors header could not be read or parsed.
+
+ Its own type so the disk pre-flight can fall back to an approximate figure for
+ exactly this, while a bad request or a checkpoint the sharder refuses still raises.
+ """
+
+
+#: What reading and parsing one header can raise: a missing or unreadable file, a
+#: malformed header (``ValueError``), a null or nested dimension or offset
+#: (``TypeError``), an infinite one (``OverflowError``) and JSON nested deeper than
+#: the parser recurses (``RecursionError``: 200 KB of ``[`` is enough).
+_HEADER_READ_ERRORS = (OSError, ValueError, TypeError, OverflowError, RecursionError)
+
+
+def _read_source_shapes(shard_paths: Sequence[str]) -> Dict[str, Tuple[int, ...]]:
+ """Canonical key -> shape over every source file, from the headers alone.
+
+ A header that cannot be read becomes :class:`SourceHeaderError`. One tensor
+ spelled twice, or more than ``_MAX_TOTAL_TENSORS`` across the files, is
+ refused the way :func:`shard_checkpoint` refuses it.
+ """
+ from soup_cli.utils.safetensors_reader import read_header
+
+ shapes: Dict[str, Tuple[int, ...]] = {}
+ spelled: Dict[str, str] = {}
+ for path in shard_paths:
+ try:
+ header = read_header(path)
+ except _HEADER_READ_ERRORS as exc:
+ raise SourceHeaderError(
+ f"cannot read the safetensors header of {path}: {exc}"
+ ) from exc
+ for source_key, entry in header.items():
+ key = _canonical_stream_key(source_key)
+ prior = spelled.get(key)
+ if prior is not None:
+ raise ValueError(
+ f"checkpoint spells one streamed tensor twice: {prior!r} and "
+ f"{source_key!r} both canonicalise to {key!r}. Refusing rather than "
+ f"silently keeping one by safetensors key order."
+ )
+ spelled[key] = source_key
+ shapes[key] = entry.shape
+ if len(shapes) > _MAX_TOTAL_TENSORS:
+ raise ValueError(f"checkpoint declares more than {_MAX_TOTAL_TENSORS} tensors")
+ return shapes
+
+
+@dataclass(frozen=True)
+class ShardCacheEstimate:
+ """What :func:`shard_checkpoint` will write, sized from the source headers.
+
+ ``layer_bytes[i]`` is the tensor payload of decoder layer ``i``: its layer file
+ plus, under ``expert_layout="per_expert"``, its experts file (both are written
+ to the same root). ``other_bytes`` is the payload of the extras shard and the
+ large embed/head shards, all on root 0. Both are exact. ``header_bytes`` and
+ ``index_bytes`` bound the safetensors headers and ``index.json`` from above.
+ """
+
+ layer_bytes: Tuple[int, ...]
+ other_bytes: int
+ header_bytes: int
+ index_bytes: int
+
+ @property
+ def total_bytes(self) -> int:
+ return sum(self.layer_bytes) + self.other_bytes + self.header_bytes + self.index_bytes
+
+
+def estimate_shard_cache_bytes(
+ shard_paths: Sequence[str],
+ *,
+ dtype: str,
+ arch: str = "",
+ quant: str = QUANT_NONE,
+ quant_suffixes: Iterable[str] = (),
+ double_quant: bool = True,
+ expert_layout: str = "",
+ num_hidden_layers: Optional[int] = None,
+) -> Optional[ShardCacheEstimate]:
+ """Size the cache :func:`shard_checkpoint` writes for the same arguments.
+
+ Reads only the safetensors headers of ``shard_paths`` (shapes and dtypes; no
+ tensor is loaded and no file is mapped) and stores each tensor the way the
+ sharder does: :func:`_layer_tensor_storage` for every decoder key,
+ :func:`_routed_experts_quantised` for the routed experts of a stacked-expert
+ architecture, :func:`nf4_weight_bytes` for each NF4 weight, the same
+ multi-token-prediction drop for ``deepseek_v3`` and the stream ``dtype`` for
+ everything outside the decoder layers.
+
+ Returns ``None`` for ``qwen4_exp``, whose external PLE table and oQ layout
+ have their own estimators. The arguments are checked before any file is read
+ (``ValueError``). A header that cannot be read raises
+ :class:`SourceHeaderError`; a checkpoint the sharder would refuse raises
+ ``ValueError`` in the sharder's words, before anything is sized by its layer
+ count.
+ """
+ if arch == "qwen4_exp":
+ return None
+ if dtype not in _SUPPORTED_DTYPES:
+ raise ValueError(
+ f"unsupported dtype {dtype!r} for layer streaming; "
+ f"supported: {', '.join(_SUPPORTED_DTYPES)}"
+ )
+ 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}"
+ )
+ suffixes = _validate_quant_request(quant, quant_suffixes)
+ quantise = quant == QUANT_NF4
+
+ from soup_cli.utils.expert_stream import DOWN, GATE_UP, expert_key
+ from soup_cli.utils.safetensors_reader import _ITEMSIZE
+
+ shapes = _read_source_shapes(shard_paths)
+
+ itemsize = _ITEMSIZE[dtype]
+ stack_experts = arch in _STACKED_EXPERT_ARCHS
+ fp32_keys = layer_buffer_keys(arch)
+ drop_extra_layers = arch == "deepseek_v3" and num_hidden_layers is not None
+ experts_nf4 = _routed_experts_quantised(expert_layout, quantise)
+ sidecars = _nf4_sidecar_suffixes(double_quant)
+
+ layer_bytes: Dict[int, int] = {}
+ routed: Dict[int, Dict[int, Dict[str, int]]] = {}
+ other_bytes = 0
+ header_bytes = 0
+ stored_names: set = set()
+ any_nf4 = False
+
+ def _charge_names(names: Iterable[str], *, indexed: bool = True) -> int:
+ """Header bytes for ``names``; ``indexed`` ones are also listed in index.json."""
+ names = tuple(names)
+ if indexed:
+ stored_names.update(names)
+ return sum(len(name) + _HEADER_BYTES_PER_TENSOR for name in names)
+
+ for key, shape in shapes.items():
+ numel = math.prod(shape)
+ match = _LAYER_RE.match(key)
+ if match is None:
+ other_bytes += numel * itemsize
+ header_bytes += _charge_names((key,))
+ continue
+ idx = int(match.group(1))
+ if drop_extra_layers and idx >= num_hidden_layers:
+ continue
+ layer_bytes.setdefault(idx, 0)
+ expert_match = _PER_EXPERT_RE.match(key) if stack_experts else None
+ if expert_match:
+ expert = int(expert_match.group("expert"))
+ projections = routed.setdefault(idx, {}).setdefault(expert, {})
+ projections[expert_match.group("projection")] = numel
+ continue
+ short = match.group(2)
+ stored, nf4 = _layer_tensor_storage(
+ short, dtype=dtype, quantise=quantise, suffixes=suffixes, fp32_keys=fp32_keys
+ )
+ if nf4:
+ any_nf4 = True
+ layer_bytes[idx] += nf4_weight_bytes(numel, double_quant=double_quant)
+ header_bytes += _charge_names(short + suffix for suffix in sidecars)
+ else:
+ layer_bytes[idx] += numel * _ITEMSIZE[stored]
+ header_bytes += _charge_names((short,))
+
+ for idx, experts in routed.items():
+ for expert, projections in experts.items():
+ if set(projections) != _PER_EXPERT_PROJECTIONS:
+ raise ValueError(
+ f"layer {idx} expert {expert} has incomplete expert projections: "
+ f"{sorted(projections)}"
+ )
+ # gate and up are concatenated into ONE gate_up matrix before it is stored.
+ pairs = [
+ (projections["gate_proj"] + projections["up_proj"], projections["down_proj"])
+ for projections in experts.values()
+ ]
+ if experts_nf4:
+ any_nf4 = True
+ layer_bytes[idx] += sum(
+ nf4_weight_bytes(gate_up, double_quant=double_quant)
+ + nf4_weight_bytes(down, double_quant=double_quant)
+ for gate_up, down in pairs
+ )
+ else:
+ layer_bytes[idx] += sum(gate_up + down for gate_up, down in pairs) * itemsize
+ if expert_layout == EXPERT_LAYOUT_PER_EXPERT:
+ # experts_NNN.safetensors, whose keys index.json does not list.
+ parts = sidecars if experts_nf4 else ("",)
+ names = [
+ expert_key(expert, part) + suffix
+ for expert in experts
+ for part in (GATE_UP, DOWN)
+ for suffix in parts
+ ]
+ header_bytes += _charge_names(names, indexed=False)
+ else:
+ # Fused: the two stacked tensors in the layer file.
+ header_bytes += _charge_names(("mlp.experts.gate_up_proj", "mlp.experts.down_proj"))
+
+ if not layer_bytes:
+ raise ValueError(
+ "no decoder layer weights (model.layers.N.*) found; layer streaming has "
+ "nothing to stream"
+ )
+ n_layers = max(layer_bytes) + 1
+ # Before anything below is sized by the layer count: a header naming layer
+ # 8,000,000 would otherwise cost ~780 MB just to say the layers are missing.
+ if n_layers > _MAX_LAYERS:
+ raise ValueError(f"too many decoder layers ({n_layers} > {_MAX_LAYERS})")
+ if len(layer_bytes) != n_layers:
+ missing = sorted(set(range(n_layers)) - set(layer_bytes))
+ raise ValueError(f"decoder layer indices are not contiguous; missing {missing[:8]}")
+ if any_nf4:
+ # The shared code tables in extras: the 16 float32 NF4 levels, plus the
+ # 256-entry float32 nested map under double quantisation.
+ tables = {NF4_CODE_KEY: 16 * 4}
+ if double_quant:
+ tables[NF4_NESTED_CODE_KEY] = 256 * 4
+ other_bytes += sum(tables.values())
+ header_bytes += _charge_names(tables)
+ index_entries = len(shard_paths) + len(stored_names) + len(suffixes) + n_layers
+ return ShardCacheEstimate(
+ layer_bytes=tuple(layer_bytes[idx] for idx in range(n_layers)),
+ other_bytes=other_bytes,
+ header_bytes=header_bytes,
+ index_bytes=_INDEX_BYTES_FIXED + _INDEX_BYTES_PER_ENTRY * index_entries,
+ )
+
+
def source_weight_bytes(weights_dir: str) -> int:
"""Total bytes of the source ``*.safetensors`` — a cheap size probe that
lets a caller refuse an oversized base BEFORE spending minutes sharding."""
@@ -1403,6 +1704,9 @@ def shard_checkpoint(
external_mode = "qwen4_ple" if arch == "qwen4_exp" else ""
stack_experts = arch in _STACKED_EXPERT_ARCHS
expert_label = _STACKED_EXPERT_ARCHS.get(arch, arch)
+ # Fused routed experts are stacked at the stream dtype below and never quantised;
+ # per_expert ones are NF4 under quant='nf4'. The disk pre-flight sizes by this too.
+ experts_nf4 = _routed_experts_quantised(expert_layout, quantise)
fp32_layer_keys = layer_buffer_keys(arch)
drop_extra_layers = arch == "deepseek_v3" and num_hidden_layers is not None
shards = _discover_safetensors(weights_dir)
@@ -1743,15 +2047,22 @@ def shard_checkpoint(
continue
path, source_key = location
short = key[len(prefix):]
+ # The same rule estimate_shard_cache_bytes sizes the disk pre-flight by.
+ stored, as_nf4 = _layer_tensor_storage(
+ short,
+ dtype=dtype,
+ quantise=quantise,
+ suffixes=suffixes,
+ fp32_keys=fp32_layer_keys,
+ )
if saw_oq_companion and key.endswith(".weight"):
tensor = _read_oq_tensor(
handles, where, key, oq_config=oq_config, dtype=dtype
)
else:
- 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:
+ if as_nf4:
sidecars, spec, code, nested_code = _quantize_nf4(
tensor, double_quant=double_quant, device=device
)
@@ -1912,11 +2223,11 @@ def shard_checkpoint(
info = write_expert_shard(
os.path.join(shard_dirs[root], expert_shard_name(idx)),
_expert_pairs(),
- quantise=quantise,
+ quantise=experts_nf4,
double_quant=double_quant,
device=device,
)
- if quantise:
+ if experts_nf4:
tables.observe(f"{prefix}mlp.experts", *info.codes)
described = (info.count, dict(info.shapes), dict(info.quant_specs))
if expert_meta is None:
diff --git a/src/soup_cli/utils/layer_stream.py b/src/soup_cli/utils/layer_stream.py
index ff4321ec..a595243c 100644
--- a/src/soup_cli/utils/layer_stream.py
+++ b/src/soup_cli/utils/layer_stream.py
@@ -1014,9 +1014,13 @@ def estimate_stream_store_bytes(
Deliberately coarse: it assumes the source is stored at ``dtype`` and
charges the NF4 rate to every parameter, while layernorms and (in the shard
- set) the embeddings actually stay unquantised. That errs slightly LOW, which
- is the safe direction — the authoritative check runs after sharding, on the
- real shard sizes.
+ set) the embeddings actually stay unquantised. That errs LOW, which is the
+ safe direction for this RAM probe — the authoritative check runs after
+ sharding, on the real shard sizes. It errs far low for a fused MoE base,
+ whose stacked routed experts stay at ``dtype``, so the DISK pre-flight sizes
+ the cache from the source headers instead
+ (``layer_shard.estimate_shard_cache_bytes``) and falls back to this ratio
+ only when those headers cannot be read.
"""
if quant not in SUPPORTED_STREAM_QUANTS:
raise ValueError(
diff --git a/tests/test_stream_disk_preflight_moe.py b/tests/test_stream_disk_preflight_moe.py
new file mode 100644
index 00000000..075b20a4
--- /dev/null
+++ b/tests/test_stream_disk_preflight_moe.py
@@ -0,0 +1,1118 @@
+"""Layer streaming's disk pre-flight sizes the shard cache the way the sharder writes it.
+
+`soup train` with `training.stream_layers` shards the base into a per-layer cache and,
+before writing a byte, refuses when the cache volume cannot hold it. The estimate used
+to charge the NF4 rate to every parameter. In the default `fused` expert layout the
+sharder keeps the stacked routed experts at the stream dtype, so for Moonlight-16B-A3B
+(`deepseek_v3`) the pre-flight said ~8.4 GB and the sharder then wrote 30.6 GB: a disk
+could pass the check and fill mid-shard.
+
+The estimate now reads the source safetensors HEADERS (shapes and dtypes, no tensor is
+loaded or mapped) and applies the sharder's own storage decisions to each tensor:
+which decoder keys become NF4 (the `quant_suffixes` the meta probe found), which stay
+float32, what the routed experts become in each layout, and the exact NF4 sidecar bytes.
+"""
+
+import json
+import math
+import os
+import struct
+import types
+
+import pytest
+
+# --------------------------------------------------------------------------
+# a synthetic DeepSeek-V3-shaped checkpoint (real headers, zero payload)
+# --------------------------------------------------------------------------
+HIDDEN, DENSE_INTER, MOE_INTER, EXPERTS, VOCAB = 64, 128, 32, 4, 128
+N_LAYERS = 3 # layer 0 dense (first_k_dense_replace=1), layers 1-2 MoE
+_ITEMSIZE = {"BF16": 2, "F16": 2, "F32": 4}
+
+#: What the meta probe reports for this layout: every nn.Linear of a decoder layer.
+#: The router weight, the norms, the bias and the fused experts are not in it.
+SUFFIXES = frozenset(
+ {
+ "self_attn.q_proj.weight",
+ "self_attn.o_proj.weight",
+ "mlp.gate_proj.weight",
+ "mlp.up_proj.weight",
+ "mlp.down_proj.weight",
+ "mlp.shared_experts.gate_proj.weight",
+ "mlp.shared_experts.up_proj.weight",
+ "mlp.shared_experts.down_proj.weight",
+ }
+)
+
+
+def _moe_tensors(*, source_dtype="BF16", extra_layers=0, n_layers=N_LAYERS):
+ """name -> (safetensors dtype, shape) for a DeepSeek-V3-shaped base."""
+ dt = source_dtype
+ tensors = {
+ "model.embed_tokens.weight": (dt, (VOCAB, HIDDEN)),
+ "lm_head.weight": (dt, (VOCAB, HIDDEN)),
+ "model.norm.weight": (dt, (HIDDEN,)),
+ }
+ for idx in range(n_layers + extra_layers):
+ prefix = f"model.layers.{idx}."
+ tensors[prefix + "input_layernorm.weight"] = (dt, (HIDDEN,))
+ tensors[prefix + "post_attention_layernorm.weight"] = (dt, (HIDDEN,))
+ tensors[prefix + "self_attn.q_proj.weight"] = (dt, (HIDDEN, HIDDEN))
+ tensors[prefix + "self_attn.o_proj.weight"] = (dt, (HIDDEN, HIDDEN))
+ if idx == 0:
+ tensors[prefix + "mlp.gate_proj.weight"] = (dt, (DENSE_INTER, HIDDEN))
+ tensors[prefix + "mlp.up_proj.weight"] = (dt, (DENSE_INTER, HIDDEN))
+ tensors[prefix + "mlp.down_proj.weight"] = (dt, (HIDDEN, DENSE_INTER))
+ continue
+ tensors[prefix + "mlp.gate.weight"] = (dt, (EXPERTS, HIDDEN))
+ tensors[prefix + "mlp.gate.e_score_correction_bias"] = ("F32", (EXPERTS,))
+ for name in ("gate_proj", "up_proj"):
+ tensors[prefix + f"mlp.shared_experts.{name}.weight"] = (dt, (MOE_INTER, HIDDEN))
+ tensors[prefix + "mlp.shared_experts.down_proj.weight"] = (dt, (HIDDEN, MOE_INTER))
+ for expert in range(EXPERTS):
+ for name in ("gate_proj", "up_proj"):
+ key = prefix + f"mlp.experts.{expert}.{name}.weight"
+ tensors[key] = (dt, (MOE_INTER, HIDDEN))
+ tensors[prefix + f"mlp.experts.{expert}.down_proj.weight"] = (
+ dt,
+ (HIDDEN, MOE_INTER),
+ )
+ return tensors
+
+
+def _dense_tensors(*, source_dtype="BF16"):
+ """A Llama-shaped base: the same layout without the MoE layers."""
+ return _moe_tensors(source_dtype=source_dtype, n_layers=1)
+
+
+def _write_checkpoint(directory, tensors, name="model.safetensors"):
+ """A safetensors file with a real header and an all-zero payload; returns its path."""
+ directory.mkdir(parents=True, exist_ok=True)
+ header, cursor = {}, 0
+ for key, (dtype, shape) in tensors.items():
+ size = math.prod(shape) * _ITEMSIZE[dtype]
+ offsets = [cursor, cursor + size]
+ header[key] = {"dtype": dtype, "shape": list(shape), "data_offsets": offsets}
+ cursor += size
+ raw = json.dumps(header).encode("utf-8")
+ path = directory / name
+ with open(path, "wb") as handle:
+ handle.write(struct.pack("<Q", len(raw)))
+ handle.write(raw)
+ handle.write(b"\0" * cursor)
+ return str(path)
+
+
+#: Headers `read_header` cannot turn into shapes, by the exception each one raises there:
+#: a null or nested dimension and a null offset are TypeErrors, an infinite dimension is
+#: an OverflowError, 200 KB of nested brackets a RecursionError, the rest ValueErrors.
+_MALFORMED = {
+ "shape-null": '{"t":{"dtype":"BF16","shape":[null],"data_offsets":[0,2]}}',
+ "shape-nested": '{"t":{"dtype":"BF16","shape":[[2]],"data_offsets":[0,4]}}',
+ "offsets-null": '{"t":{"dtype":"BF16","shape":[2],"data_offsets":[null,4]}}',
+ "shape-infinite": '{"t":{"dtype":"BF16","shape":[Infinity],"data_offsets":[0,4]}}',
+ "nested-brackets": "[" * 200_000,
+ "not-json": "not json at all",
+ "fp8-dtype": '{"t":{"dtype":"F8_E4M3","shape":[2],"data_offsets":[0,2]}}',
+}
+
+
+def _layer_stack(n_layers):
+ """The smallest checkpoint with `n_layers` contiguous decoder layers."""
+ tensors = {"model.embed_tokens.weight": ("BF16", (4, 2))}
+ for idx in range(n_layers):
+ tensors[f"model.layers.{idx}.input_layernorm.weight"] = ("BF16", (2,))
+ return tensors
+
+
+def _write_raw(path, header_text, payload=b"\0" * 8):
+ """A file with an arbitrary header text after its length field, then a payload."""
+ raw = header_text.encode("utf-8")
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(struct.pack("<Q", len(raw)) + raw + payload)
+ return str(path)
+
+
+def _header_and_payload(path):
+ """(bytes of the length field + header, bytes of tensor data) of one safetensors file."""
+ with open(path, "rb") as handle:
+ (length,) = struct.unpack("<Q", handle.read(8))
+ return 8 + length, os.path.getsize(path) - 8 - length
+
+
+def _nf4(numel, double_quant=True):
+ """The oracle: packed nibbles + one absmax per 64 (uint8 + nested fp32 per 256 + offset)."""
+ blocks = -(-numel // 64)
+ packed = (numel + 1) // 2
+ if not double_quant:
+ return packed + 4 * blocks
+ return packed + blocks + 4 * -(-blocks // 256) + 4
+
+
+def _expected(layout, *, nf4, double_quant=True, itemsize=2, n_layers=N_LAYERS):
+ """(per-layer payload, other payload) the sharder writes for `_moe_tensors()`."""
+
+ def stored(numel, quantised):
+ return _nf4(numel, double_quant) if quantised else numel * itemsize
+
+ layers = []
+ for idx in range(n_layers):
+ total = 2 * HIDDEN * itemsize # the two norms stay at the stream dtype
+ total += 2 * stored(HIDDEN * HIDDEN, nf4) # q_proj, o_proj
+ if idx == 0:
+ total += 3 * stored(DENSE_INTER * HIDDEN, nf4)
+ else:
+ total += EXPERTS * HIDDEN * itemsize # the router weight is not an nn.Linear
+ total += EXPERTS * 4 # e_score_correction_bias is kept at float32
+ total += 3 * stored(MOE_INTER * HIDDEN, nf4) # the shared expert
+ if layout == "per_expert":
+ # one (gate_up, down) pair per expert, each matrix quantised on its own
+ total += EXPERTS * (
+ stored(2 * MOE_INTER * HIDDEN, nf4) + stored(HIDDEN * MOE_INTER, nf4)
+ )
+ else:
+ # fused: stacked 3-D gate_up_proj / down_proj at the stream dtype
+ total += EXPERTS * 3 * MOE_INTER * HIDDEN * itemsize
+ layers.append(total)
+ other = (2 * VOCAB * HIDDEN + HIDDEN) * itemsize
+ if nf4:
+ other += 16 * 4 + (256 * 4 if double_quant else 0) # the shared code tables
+ return tuple(layers), other
+
+
+def _estimate(paths, *, layout="", quant="nf4", suffixes=SUFFIXES, **kwargs):
+ from soup_cli.utils.layer_shard import estimate_shard_cache_bytes
+
+ kwargs.setdefault("dtype", "bfloat16")
+ kwargs.setdefault("arch", "deepseek_v3")
+ return estimate_shard_cache_bytes(
+ paths,
+ quant=quant,
+ quant_suffixes=suffixes if quant == "nf4" else (),
+ expert_layout=layout,
+ **kwargs,
+ )
+
+
+def _coarse(source_bytes, quant="nf4"):
+ """The pre-fix estimate: the NF4 rate charged to every parameter."""
+ from soup_cli.utils.layer_stream import estimate_stream_store_bytes
+
+ return estimate_stream_store_bytes(source_bytes, dtype="bfloat16", quant=quant)
+
+
+# --------------------------------------------------------------------------
+# NF4 byte accounting
+# --------------------------------------------------------------------------
+class TestNf4WeightBytes:
+ @pytest.mark.parametrize(
+ ("numel", "double_quant", "expected"),
+ [
+ (4096, True, 2048 + 64 + 4 + 4),
+ (4096, False, 2048 + 4 * 64),
+ (63, True, 32 + 1 + 4 + 4), # odd numel: one packed byte holds one nibble
+ (63, False, 32 + 4),
+ (42624, True, 21312 + 666 + 4 * 3 + 4), # 666 blocks -> three nested blocks
+ (2816 * 2048, True, 2975108), # one Moonlight expert gate_up matrix
+ (2816 * 2048, False, 3244032),
+ ],
+ )
+ def test_hand_counted_sizes(self, numel, double_quant, expected):
+ from soup_cli.utils.layer_shard import nf4_weight_bytes
+
+ assert nf4_weight_bytes(numel, double_quant=double_quant) == expected
+
+ @pytest.mark.parametrize("double_quant", [True, False], ids=["double", "single"])
+ @pytest.mark.parametrize("shape", [(64, 64), (7, 9), (128, 333), (300, 2048)])
+ def test_matches_what_the_sharder_stores(self, shape, double_quant):
+ """Pinned against `_quantize_nf4` (bitsandbytes on CPU), the sharder's own call."""
+ pytest.importorskip("bitsandbytes")
+ torch = pytest.importorskip("torch")
+ from soup_cli.utils.layer_shard import (
+ _nf4_sidecar_suffixes,
+ _quantize_nf4,
+ nf4_weight_bytes,
+ )
+
+ weight = torch.randn(shape, generator=torch.Generator().manual_seed(5)).to(
+ torch.bfloat16
+ )
+ sidecars, _spec, _code, _nested = _quantize_nf4(
+ weight, double_quant=double_quant, device="cpu"
+ )
+ stored = sum(value.numel() * value.element_size() for value in sidecars.values())
+ assert nf4_weight_bytes(weight.numel(), double_quant=double_quant) == stored
+ # the header allowance names the same stored keys the sharder writes
+ assert sorted(_nf4_sidecar_suffixes(double_quant)) == sorted(sidecars)
+
+ def test_an_empty_weight_is_refused(self):
+ from soup_cli.utils.layer_shard import nf4_weight_bytes
+
+ with pytest.raises(ValueError, match="positive"):
+ nf4_weight_bytes(0, double_quant=True)
+
+
+# --------------------------------------------------------------------------
+# the estimate, from headers
+# --------------------------------------------------------------------------
+class TestEstimateFromHeaders:
+ def test_fused_nf4_keeps_the_routed_experts_at_the_stream_dtype(self, tmp_path):
+ path = _write_checkpoint(tmp_path / "m", _moe_tensors())
+ got = _estimate([path], layout="")
+ assert (got.layer_bytes, got.other_bytes) == _expected("fused", nf4=True)
+
+ def test_per_expert_nf4_quantises_each_expert_matrix(self, tmp_path):
+ path = _write_checkpoint(tmp_path / "m", _moe_tensors())
+ got = _estimate([path], layout="per_expert")
+ assert (got.layer_bytes, got.other_bytes) == _expected("per_expert", nf4=True)
+
+ @pytest.mark.parametrize("layout", ["", "per_expert"], ids=["fused", "per_expert"])
+ def test_single_quant_uses_float32_absmax(self, tmp_path, layout):
+ path = _write_checkpoint(tmp_path / "m", _moe_tensors())
+ got = _estimate([path], layout=layout, double_quant=False)
+ expected = _expected(layout or "fused", nf4=True, double_quant=False)
+ assert (got.layer_bytes, got.other_bytes) == expected
+
+ @pytest.mark.parametrize("layout", ["", "per_expert"], ids=["fused", "per_expert"])
+ def test_unquantised_charges_every_tensor_at_the_stream_dtype(self, tmp_path, layout):
+ path = _write_checkpoint(tmp_path / "m", _moe_tensors())
+ got = _estimate([path], layout=layout, quant="none")
+ assert (got.layer_bytes, got.other_bytes) == _expected("fused", nf4=False)
+ # a bf16 source at the bf16 stream dtype: the payload is the source payload
+ source_payload = sum(
+ math.prod(shape) * _ITEMSIZE[dtype] for dtype, shape in _moe_tensors().values()
+ )
+ assert sum(got.layer_bytes) + got.other_bytes == source_payload
+
+ def test_a_float32_source_is_charged_at_the_stream_dtype(self, tmp_path):
+ path = _write_checkpoint(tmp_path / "m", _moe_tensors(source_dtype="F32"))
+ got = _estimate([path], layout="")
+ assert (got.layer_bytes, got.other_bytes) == _expected("fused", nf4=True)
+
+ def test_a_float32_stream_dtype_doubles_the_unquantised_part(self, tmp_path):
+ path = _write_checkpoint(tmp_path / "m", _moe_tensors())
+ got = _estimate([path], layout="", dtype="float32")
+ assert (got.layer_bytes, got.other_bytes) == _expected("fused", nf4=True, itemsize=4)
+
+ def test_the_fused_cache_is_far_above_the_old_nf4_rate(self, tmp_path):
+ """The defect itself: the routed experts are most of an MoE base."""
+ path = _write_checkpoint(tmp_path / "m", _moe_tensors())
+ fused = _estimate([path], layout="")
+ per_expert = _estimate([path], layout="per_expert")
+ assert fused.total_bytes > 2 * _coarse(os.path.getsize(path))
+ # an MoE layer: stacked experts at bf16 against one NF4 matrix per expert
+ assert fused.layer_bytes[1] > 2 * per_expert.layer_bytes[1]
+
+ def test_layers_past_num_hidden_layers_are_not_charged(self, tmp_path):
+ """DeepSeek-V3 / Kimi K2 MTP layers: the sharder drops them, so does the estimate."""
+ path = _write_checkpoint(tmp_path / "m", _moe_tensors(extra_layers=1))
+ got = _estimate([path], layout="", num_hidden_layers=N_LAYERS)
+ assert (got.layer_bytes, got.other_bytes) == _expected("fused", nf4=True)
+ kept = _estimate([path], layout="")
+ assert len(kept.layer_bytes) == N_LAYERS + 1
+
+ def test_the_tensors_may_span_several_files(self, tmp_path):
+ tensors = list(_moe_tensors().items())
+ half = len(tensors) // 2
+ first = _write_checkpoint(tmp_path / "m", dict(tensors[:half]), "a.safetensors")
+ second = _write_checkpoint(tmp_path / "m", dict(tensors[half:]), "b.safetensors")
+ got = _estimate([first, second], layout="")
+ assert (got.layer_bytes, got.other_bytes) == _expected("fused", nf4=True)
+
+ def test_a_dense_unquantised_base_is_charged_its_source_payload(self, tmp_path):
+ """The pre-fix estimate for quant none was the source size; that does not move."""
+ path = _write_checkpoint(tmp_path / "m", _dense_tensors())
+ got = _estimate([path], arch="llama", quant="none")
+ _header, source_payload = _header_and_payload(path)
+ assert sum(got.layer_bytes) + got.other_bytes == source_payload
+
+ def test_a_dense_nf4_base_keeps_embeddings_and_norms_at_the_stream_dtype(self, tmp_path):
+ path = _write_checkpoint(tmp_path / "m", _dense_tensors())
+ got = _estimate([path], arch="llama")
+ layers, other = _expected("fused", nf4=True, n_layers=1)
+ assert (got.layer_bytes, got.other_bytes) == (layers, other)
+ # the old rate charged the embeddings at NF4 too, so it sat below this
+ assert got.total_bytes > _coarse(os.path.getsize(path))
+
+ def test_headers_and_the_index_are_counted_on_top_of_the_payload(self, tmp_path):
+ path = _write_checkpoint(tmp_path / "m", _moe_tensors())
+ got = _estimate([path], layout="per_expert")
+ assert got.header_bytes > 0 and got.index_bytes > 0
+ payload = sum(got.layer_bytes) + got.other_bytes
+ assert got.total_bytes == payload + got.header_bytes + got.index_bytes
+
+ def test_one_tensor_spelled_twice_is_refused_like_the_sharder(self, tmp_path):
+ tensors = _moe_tensors()
+ first = _write_checkpoint(tmp_path / "m", tensors, "a.safetensors")
+ twin = {"model.norm.weight": tensors["model.norm.weight"]}
+ second = _write_checkpoint(tmp_path / "m", twin, "b.safetensors")
+ with pytest.raises(ValueError, match="twice"):
+ _estimate([first, second])
+
+ def test_a_missing_decoder_layer_is_refused_like_the_sharder(self, tmp_path):
+ tensors = {
+ key: value
+ for key, value in _moe_tensors().items()
+ if not key.startswith("model.layers.1.")
+ }
+ path = _write_checkpoint(tmp_path / "m", tensors)
+ with pytest.raises(ValueError, match="not contiguous"):
+ _estimate([path])
+
+ def test_a_checkpoint_without_decoder_layers_is_refused(self, tmp_path):
+ tensors = {"model.embed_tokens.weight": ("BF16", (VOCAB, HIDDEN))}
+ path = _write_checkpoint(tmp_path / "m", tensors)
+ with pytest.raises(ValueError, match="no decoder layer weights"):
+ _estimate([path], quant="none")
+
+ def test_qwen4_exp_is_left_to_its_own_estimators(self, tmp_path):
+ path = _write_checkpoint(tmp_path / "m", _moe_tensors())
+ assert _estimate([path], arch="qwen4_exp", quant="none") is None
+
+ def test_nf4_without_quant_suffixes_is_refused_like_the_sharder(self, tmp_path):
+ path = _write_checkpoint(tmp_path / "m", _moe_tensors())
+ with pytest.raises(ValueError, match="quant_suffixes"):
+ _estimate([path], suffixes=())
+
+ @pytest.mark.parametrize("spelling", sorted(_MALFORMED), ids=sorted(_MALFORMED))
+ def test_a_header_that_cannot_be_parsed_is_a_source_header_error(self, tmp_path, spelling):
+ from soup_cli.utils.layer_shard import SourceHeaderError
+
+ bad = _write_raw(tmp_path / "bad.safetensors", _MALFORMED[spelling])
+ with pytest.raises(SourceHeaderError, match="bad.safetensors"):
+ _estimate([bad])
+
+ def test_a_missing_source_file_is_a_source_header_error(self, tmp_path):
+ from soup_cli.utils.layer_shard import SourceHeaderError
+
+ with pytest.raises(SourceHeaderError):
+ _estimate([str(tmp_path / "gone.safetensors")])
+
+ def test_arguments_are_checked_before_any_header_is_read(self, tmp_path):
+ """A bad request is a bug to raise, never a header problem to fall back on."""
+ from soup_cli.utils.layer_shard import SourceHeaderError
+
+ missing = str(tmp_path / "gone.safetensors")
+ for kwargs, needle in (
+ ({"dtype": "int8"}, "unsupported dtype"),
+ ({"layout": "experts"}, "unsupported expert_layout"),
+ ({"suffixes": ()}, "quant_suffixes"),
+ ):
+ with pytest.raises(ValueError, match=needle) as exc:
+ _estimate([missing], **kwargs)
+ assert not isinstance(exc.value, SourceHeaderError)
+
+ def test_a_layer_index_past_the_sharder_bound_is_refused_cheaply(self, tmp_path):
+ """The sharder refuses more than 512 layers; sizing anything by the index first
+ would allocate per index (~780 MB at 8,000,000, ~190 MB here) before saying so."""
+ import tracemalloc
+
+ tensors = _moe_tensors()
+ tensors["model.layers.2000000.input_layernorm.weight"] = ("BF16", (HIDDEN,))
+ path = _write_checkpoint(tmp_path / "m", tensors)
+ tracemalloc.start()
+ try:
+ with pytest.raises(ValueError, match=r"too many decoder layers \(2000001 > 512\)"):
+ _estimate([path])
+ _current, peak = tracemalloc.get_traced_memory()
+ finally:
+ tracemalloc.stop()
+ assert peak < 8 * 2**20, peak
+
+ @pytest.mark.parametrize("n_layers", [512, 513])
+ def test_the_layer_cap_counts_layers_like_the_sharder(self, tmp_path, n_layers):
+ """The sharder takes max index + 1 and refuses above 512: 512 layers (indices
+ 0..511) shard, 513 do not. The estimate draws the line in the same place."""
+ pytest.importorskip("torch")
+ pytest.importorskip("safetensors")
+ from soup_cli.utils.layer_shard import shard_checkpoint
+
+ weights = tmp_path / "m"
+ path = _write_checkpoint(weights, _layer_stack(n_layers))
+ if n_layers == 512:
+ assert len(_estimate([path], arch="llama", quant="none").layer_bytes) == 512
+ index = shard_checkpoint(str(weights), str(tmp_path / "out"), arch="llama")
+ assert index.n_layers == 512
+ return
+ message = r"too many decoder layers \(513 > 512\)"
+ with pytest.raises(ValueError, match=message):
+ _estimate([path], arch="llama", quant="none")
+ with pytest.raises(ValueError, match=message):
+ shard_checkpoint(str(weights), str(tmp_path / "out"), arch="llama")
+
+ @pytest.mark.parametrize("n_tensors", [10, 11])
+ def test_the_tensor_cap_matches_the_sharder(self, tmp_path, monkeypatch, n_tensors):
+ """At most _MAX_TOTAL_TENSORS tensors, the sharder's own constant and words.
+ The cap is lowered to 10 here so the test stays a few KB."""
+ pytest.importorskip("torch")
+ pytest.importorskip("safetensors")
+ import soup_cli.utils.layer_shard as layer_shard
+
+ monkeypatch.setattr(layer_shard, "_MAX_TOTAL_TENSORS", 10)
+ weights = tmp_path / "m"
+ path = _write_checkpoint(weights, _layer_stack(n_tensors - 1))
+ if n_tensors == 10:
+ assert len(_estimate([path], arch="llama", quant="none").layer_bytes) == 9
+ return
+ message = "checkpoint declares more than 10 tensors"
+ with pytest.raises(ValueError, match=message):
+ _estimate([path], arch="llama", quant="none")
+ with pytest.raises(ValueError, match=message):
+ layer_shard.shard_checkpoint(str(weights), str(tmp_path / "out"), arch="llama")
+
+ def test_the_tensor_cap_counts_across_files(self, tmp_path, monkeypatch):
+ import soup_cli.utils.layer_shard as layer_shard
+
+ monkeypatch.setattr(layer_shard, "_MAX_TOTAL_TENSORS", 10)
+ items = list(_layer_stack(10).items()) # 11 tensors, six and five per file
+ first = _write_checkpoint(tmp_path / "m", dict(items[:6]), "a.safetensors")
+ second = _write_checkpoint(tmp_path / "m", dict(items[6:]), "b.safetensors")
+ with pytest.raises(ValueError, match="checkpoint declares more than 10 tensors"):
+ _estimate([first, second], arch="llama", quant="none")
+
+ def test_an_incomplete_expert_is_refused_like_the_sharder(self, tmp_path):
+ tensors = _moe_tensors()
+ del tensors["model.layers.1.mlp.experts.2.up_proj.weight"]
+ path = _write_checkpoint(tmp_path / "m", tensors)
+ with pytest.raises(ValueError, match="expert"):
+ _estimate([path], layout="per_expert")
+
+
+# --------------------------------------------------------------------------
+# striping: the per-root shares come from the same estimate
+# --------------------------------------------------------------------------
+class TestStripeSharesUseTheEstimate:
+ def test_shares_follow_the_estimated_layer_bytes(self, tmp_path):
+ from soup_cli.trainer.stream_setup import estimate_stripe_write_shares
+
+ path = _write_checkpoint(tmp_path / "m", _moe_tensors())
+ est = _estimate([path], layout="")
+ shares, approximate = estimate_stripe_write_shares(
+ str(tmp_path / "m"), total_bytes=est.total_bytes, n_roots=2,
+ dtype="bfloat16", quant="nf4", arch="deepseek_v3", estimate=est,
+ )
+ assert approximate is False
+ assert sum(shares) == est.total_bytes
+ # layers 0 and 2 plus everything outside the layers on root 0, layer 1 on root 1
+ payload = sum(est.layer_bytes) + est.other_bytes
+ root1 = est.layer_bytes[1]
+ assert shares[1] == pytest.approx(est.total_bytes * root1 / payload, abs=1)
+
+ def test_without_an_estimate_the_header_heuristic_is_unchanged(self, tmp_path):
+ from soup_cli.trainer.stream_setup import estimate_stripe_write_shares
+
+ path = _write_checkpoint(tmp_path / "m", _moe_tensors())
+ est = _estimate([path], layout="")
+ heuristic, _ = estimate_stripe_write_shares(
+ str(tmp_path / "m"), total_bytes=est.total_bytes, n_roots=2,
+ dtype="bfloat16", quant="nf4", arch="deepseek_v3",
+ )
+ exact, _ = estimate_stripe_write_shares(
+ str(tmp_path / "m"), total_bytes=est.total_bytes, n_roots=2,
+ dtype="bfloat16", quant="nf4", arch="deepseek_v3", estimate=est,
+ )
+ assert heuristic != exact # else the test above proves nothing
+
+
+# --------------------------------------------------------------------------
+# which files the pre-flight reads
+# --------------------------------------------------------------------------
+_REVISION = "a" * 40
+
+
+def _snapshot(tmp_path):
+ repo = tmp_path / "hub" / "models--org--moe"
+ snapshot = repo / "snapshots" / _REVISION
+ (repo / "blobs").mkdir(parents=True)
+ snapshot.mkdir(parents=True)
+ return repo, snapshot
+
+
+class TestPlannedSourceShards:
+ def test_a_ready_weight_dir_is_listed_like_the_sharder_lists_it(self, tmp_path):
+ from soup_cli.trainer.stream_setup import _planned_source_shards
+
+ path = _write_checkpoint(tmp_path / "m", _moe_tensors())
+ plan = types.SimpleNamespace(weights_dir=str(tmp_path / "m"), needs_materialization=False)
+ assert _planned_source_shards(plan) == [os.path.realpath(path)]
+
+ def test_a_copy_not_made_yet_is_read_from_its_snapshot(self, tmp_path):
+ from soup_cli.trainer.stream_setup import _planned_source_shards
+
+ _repo, snapshot = _snapshot(tmp_path)
+ path = _write_checkpoint(snapshot, _moe_tensors())
+ plan = types.SimpleNamespace(
+ weights_dir=str(tmp_path / "copy-not-made-yet"),
+ source_dir=str(snapshot),
+ source_revision=_REVISION,
+ needs_materialization=True,
+ )
+ assert [os.path.realpath(p) for p in _planned_source_shards(plan)] == [
+ os.path.realpath(path)
+ ]
+
+ def test_a_snapshot_without_its_revision_is_not_read(self, tmp_path):
+ """The copy step refuses it; the pre-flight falls back instead of guessing."""
+ from soup_cli.trainer.stream_setup import _planned_source_shards
+
+ _repo, snapshot = _snapshot(tmp_path)
+ _write_checkpoint(snapshot, _moe_tensors())
+ plan = types.SimpleNamespace(
+ weights_dir=str(tmp_path / "copy"),
+ source_dir=str(snapshot),
+ source_revision=None,
+ needs_materialization=True,
+ )
+ with pytest.raises(ValueError, match="revision"):
+ _planned_source_shards(plan)
+
+ def test_only_top_level_weight_files_are_read(self, tmp_path):
+ """The sharder lists the copy's top level; a nested file is copied, never sharded."""
+ from soup_cli.trainer.stream_setup import _planned_source_shards
+
+ _repo, snapshot = _snapshot(tmp_path)
+ path = _write_checkpoint(snapshot, _moe_tensors())
+ _write_checkpoint(snapshot / "onnx", _moe_tensors())
+ plan = types.SimpleNamespace(
+ weights_dir=str(tmp_path / "copy"),
+ source_dir=str(snapshot),
+ source_revision=_REVISION,
+ needs_materialization=True,
+ )
+ assert [os.path.realpath(p) for p in _planned_source_shards(plan)] == [
+ os.path.realpath(path)
+ ]
+
+ @pytest.mark.requires_symlink
+ def test_a_symlinked_snapshot_is_read_through_its_blob(self, tmp_path):
+ from soup_cli.trainer.stream_setup import _planned_source_shards
+
+ repo, snapshot = _snapshot(tmp_path)
+ blob = _write_checkpoint(repo / "blobs", _moe_tensors(), name="etag123")
+ (snapshot / "model.safetensors").symlink_to(os.path.join("..", "..", "blobs", "etag123"))
+ plan = types.SimpleNamespace(
+ weights_dir=str(tmp_path / "copy"),
+ source_dir=str(snapshot),
+ source_revision=_REVISION,
+ needs_materialization=True,
+ )
+ assert [os.path.realpath(p) for p in _planned_source_shards(plan)] == [
+ os.path.realpath(blob)
+ ]
+
+ @pytest.mark.requires_symlink
+ def test_a_link_out_of_the_blob_store_is_refused(self, tmp_path):
+ from soup_cli.trainer.stream_setup import _planned_source_shards
+
+ _repo, snapshot = _snapshot(tmp_path)
+ outside = _write_checkpoint(tmp_path / "elsewhere", _moe_tensors())
+ (snapshot / "model.safetensors").symlink_to(outside)
+ plan = types.SimpleNamespace(
+ weights_dir=str(tmp_path / "copy"),
+ source_dir=str(snapshot),
+ source_revision=_REVISION,
+ needs_materialization=True,
+ )
+ with pytest.raises(ValueError, match="outside the Hugging Face blob store"):
+ _planned_source_shards(plan)
+
+
+# --------------------------------------------------------------------------
+# what falls back to the approximate figure, and what does not
+# --------------------------------------------------------------------------
+def _ready_plan(directory):
+ return types.SimpleNamespace(weights_dir=str(directory), needs_materialization=False)
+
+
+def _preflight(plan, **kwargs):
+ from soup_cli.trainer.stream_setup import _preflight_cache_estimate
+
+ kwargs.setdefault("dtype", "bfloat16")
+ kwargs.setdefault("arch", "deepseek_v3")
+ kwargs.setdefault("quant", "nf4")
+ kwargs.setdefault("quant_suffixes", SUFFIXES)
+ kwargs.setdefault("double_quant", True)
+ kwargs.setdefault("expert_layout", "")
+ kwargs.setdefault("num_hidden_layers", N_LAYERS)
+ return _preflight_cache_estimate(plan, **kwargs)
+
+
+class TestTheFallbackIsOnlyForUnreadableSources:
+ @pytest.mark.parametrize("spelling", sorted(_MALFORMED), ids=sorted(_MALFORMED))
+ def test_a_malformed_header_falls_back(self, tmp_path, spelling):
+ _write_raw(tmp_path / "m" / "model.safetensors", _MALFORMED[spelling])
+ assert _preflight(_ready_plan(tmp_path / "m")) is None
+
+ def test_a_source_that_cannot_be_listed_falls_back(self, tmp_path):
+ plan = types.SimpleNamespace(
+ weights_dir=str(tmp_path / "copy"), source_dir=str(tmp_path),
+ source_revision=None, needs_materialization=True,
+ )
+ assert _preflight(plan) is None
+
+ def test_a_readable_source_is_estimated(self, tmp_path):
+ _write_checkpoint(tmp_path / "m", _moe_tensors())
+ got = _preflight(_ready_plan(tmp_path / "m"))
+ assert (got.layer_bytes, got.other_bytes) == _expected("fused", nf4=True)
+
+ @pytest.mark.parametrize(
+ ("kwargs", "needle"),
+ [
+ ({"dtype": "int8"}, "unsupported dtype"),
+ ({"expert_layout": "experts"}, "unsupported expert_layout"),
+ ({"quant_suffixes": ()}, "quant_suffixes"),
+ ],
+ ids=["dtype", "layout", "suffixes"],
+ )
+ def test_a_bad_request_is_raised_not_approximated(self, tmp_path, kwargs, needle):
+ _write_checkpoint(tmp_path / "m", _moe_tensors())
+ with pytest.raises(ValueError, match=needle):
+ _preflight(_ready_plan(tmp_path / "m"), **kwargs)
+
+ def test_a_checkpoint_the_sharder_refuses_is_refused_here(self, tmp_path):
+ """Same words, before any copy or shard is written."""
+ tensors = _moe_tensors()
+ tensors["model.layers.600.input_layernorm.weight"] = ("BF16", (HIDDEN,))
+ _write_checkpoint(tmp_path / "m", tensors)
+ with pytest.raises(ValueError, match=r"too many decoder layers \(601 > 512\)"):
+ _preflight(_ready_plan(tmp_path / "m"), num_hidden_layers=None)
+
+ def test_too_many_tensors_is_refused_not_approximated(self, tmp_path, monkeypatch):
+ import soup_cli.utils.layer_shard as layer_shard
+
+ monkeypatch.setattr(layer_shard, "_MAX_TOTAL_TENSORS", 10)
+ _write_checkpoint(tmp_path / "m", _layer_stack(10))
+ with pytest.raises(ValueError, match="checkpoint declares more than 10 tensors"):
+ _preflight(
+ _ready_plan(tmp_path / "m"), arch="llama", quant="none", quant_suffixes=(),
+ num_hidden_layers=None,
+ )
+
+ def test_qwen4_exp_never_lists_its_source(self, tmp_path, monkeypatch):
+ """Its own estimators size it; a snapshot walk would be wasted work."""
+ import soup_cli.trainer.stream_setup as stream_setup
+
+ def _must_not_list(_plan):
+ raise AssertionError("qwen4_exp source listed")
+
+ monkeypatch.setattr(stream_setup, "_planned_source_shards", _must_not_list)
+ plan = _ready_plan(tmp_path)
+ assert _preflight(plan, arch="qwen4_exp", quant="none", quant_suffixes=()) is None
+
+
+# --------------------------------------------------------------------------
+# the setup charges it (the shared driver in tests/test_issue602_qwen4_ple_streaming.py)
+# --------------------------------------------------------------------------
+def _deepseek_cfg():
+ return types.SimpleNamespace(
+ model_type="deepseek_v3", hidden_size=HIDDEN, num_hidden_layers=N_LAYERS,
+ vocab_size=VOCAB, intermediate_size=DENSE_INTER,
+ )
+
+
+def _drive_preflight(tmp_path, monkeypatch, *, layout, tensors=None, free=10**15,
+ plan_overrides=None, quantization="4bit", double_quant=True,
+ suffixes=SUFFIXES, header_text=None):
+ """Run the real setup up to the sharder; return the pre-flight's keyword arguments.
+
+ The resolver hands the real `_disk_preflight` a plan over a synthetic checkpoint
+ (or, with `header_text`, a file with that header), the meta probe reports
+ `suffixes`, and the volume reports `free` bytes.
+ """
+ import soup_cli.trainer.stream_setup as stream_setup
+ import soup_cli.utils.layer_stream_runtime as layer_stream_runtime
+ import soup_cli.utils.moe as moe
+ from tests.test_issue602_qwen4_ple_streaming import _drive_qwen4_streaming_setup
+
+ weights = tmp_path / "weights"
+ if header_text is None:
+ path = _write_checkpoint(weights, tensors or _moe_tensors())
+ else:
+ path = _write_raw(weights / "model.safetensors", header_text)
+ (weights / "config.json").write_text('{"model_type": "deepseek_v3"}', encoding="utf-8")
+ size = os.path.getsize(path)
+ plan = types.SimpleNamespace(
+ weights_dir=str(weights), source_dir=str(weights), source_bytes=size,
+ materialized_copy_bytes=0, materialize_bytes=0, needs_materialization=False,
+ source_files=(("model.safetensors", size, 0),), source_revision=None,
+ )
+ for name, value in (plan_overrides or {}).items():
+ setattr(plan, name, value)
+
+ def _resolve(_base, *, before_materialize=None):
+ if before_materialize is not None:
+ before_materialize(plan)
+ return str(weights)
+
+ probes = []
+ monkeypatch.setattr(
+ stream_setup.StreamingSetupMixin, "_stream_meta_skeleton",
+ classmethod(lambda cls, *a, **k: probes.append(k) or object()),
+ )
+ monkeypatch.setattr(layer_stream_runtime, "quantised_layer_suffixes", lambda _probe: suffixes)
+ monkeypatch.setattr(moe, "resolve_moe_lora_targets", lambda *a, **k: None)
+ monkeypatch.setattr(stream_setup, "_disk_volume", lambda _path: (1, free))
+ seen = []
+ real = stream_setup._render_stream_disk_preflight
+
+ def _spy(**kwargs):
+ seen.append(kwargs)
+ return real(**kwargs)
+
+ monkeypatch.setattr(stream_setup, "_render_stream_disk_preflight", _spy)
+ real_shares = stream_setup.estimate_stripe_write_shares
+
+ def _shares_spy(*args, **kwargs):
+ seen.append({"shares_call": kwargs})
+ return real_shares(*args, **kwargs)
+
+ monkeypatch.setattr(stream_setup, "estimate_stripe_write_shares", _shares_spy)
+ _drive_qwen4_streaming_setup(
+ tmp_path, monkeypatch, resolve_weights=_resolve, arch="deepseek_v3",
+ model_cfg=_deepseek_cfg(),
+ tcfg_overrides={
+ "stream_expert_layout": layout,
+ "quantization": quantization,
+ "double_quant_on": double_quant,
+ },
+ )
+ shares_calls =[entry["shares_call"] for entry in seen if "shares_call" in entry]
+ panels = [entry for entry in seen if "shares_call" not in entry]
+ return panels, path, shares_calls
+
+
+def _stream_dtype():
+ from soup_cli.utils.layer_stream import resolve_stream_dtype
+
+ return resolve_stream_dtype("cpu")
+
+
+class TestTheSetupChargesTheEstimate:
+ @pytest.mark.parametrize("layout", ["fused", "per_expert"])
+ def test_the_preflight_charges_the_header_estimate(self, tmp_path, monkeypatch, layout):
+ panels, path, shares_calls = _drive_preflight(tmp_path, monkeypatch, layout=layout)
+ expected = _estimate(
+ [path], layout="" if layout == "fused" else layout, dtype=_stream_dtype(),
+ num_hidden_layers=N_LAYERS,
+ )
+ assert len(panels) == 1
+ assert panels[0]["shard_bytes"] == expected.total_bytes
+ assert panels[0]["shard_write_bytes"] == expected.total_bytes
+ assert panels[0]["approximate"] is False
+ # a striped cache splits that same estimate over its roots
+ assert [call["estimate"] for call in shares_calls] == [expected]
+
+ def test_a_disk_that_fits_the_old_rate_but_not_the_fused_cache_is_refused(
+ self, tmp_path, monkeypatch
+ ):
+ path = _write_checkpoint(tmp_path / "probe", _moe_tensors())
+ old = _coarse(os.path.getsize(path))
+ new = _estimate([path], layout="", dtype=_stream_dtype()).total_bytes
+ assert old < new
+ with pytest.raises(ValueError) as exc:
+ _drive_preflight(tmp_path, monkeypatch, layout="fused", free=(old + new) // 2)
+ text = str(exc.value)
+ assert "layer-shard cache" in text
+ assert "Refusing before copying or sharding" in text
+
+ def test_a_disk_that_fits_the_fused_cache_passes(self, tmp_path, monkeypatch):
+ path = _write_checkpoint(tmp_path / "probe", _moe_tensors())
+ new = _estimate([path], layout="", dtype=_stream_dtype()).total_bytes
+ panels, _path, _calls = _drive_preflight(
+ tmp_path, monkeypatch, layout="fused", free=new
+ )
+ assert panels[0]["shard_bytes"] == new
+
+ @pytest.mark.parametrize("spelling", sorted(_MALFORMED), ids=sorted(_MALFORMED))
+ def test_unreadable_headers_fall_back_to_the_old_rate_and_say_approximately(
+ self, tmp_path, monkeypatch, spelling
+ ):
+ from soup_cli.utils.layer_stream import estimate_stream_store_bytes
+
+ panels, path, _calls = _drive_preflight(
+ tmp_path, monkeypatch, layout="fused", header_text=_MALFORMED[spelling]
+ )
+ assert panels[0]["shard_bytes"] == estimate_stream_store_bytes(
+ os.path.getsize(path), dtype=_stream_dtype(), quant="nf4"
+ )
+ assert panels[0]["approximate"] is True
+
+ @pytest.mark.parametrize("layout", ["fused", "per_expert"])
+ def test_single_quant_runs_are_charged_float32_absmax(self, tmp_path, monkeypatch, layout):
+ """double_quant: false stores a float32 absmax per block, ~9% more than NF4 with it."""
+ panels, path, _calls = _drive_preflight(
+ tmp_path, monkeypatch, layout=layout, double_quant=False
+ )
+ expected = _estimate(
+ [path], layout="" if layout == "fused" else layout, dtype=_stream_dtype(),
+ double_quant=False, num_hidden_layers=N_LAYERS,
+ )
+ assert panels[0]["shard_bytes"] == expected.total_bytes
+ double = _estimate([path], layout="", dtype=_stream_dtype())
+ assert expected.total_bytes != double.total_bytes # else this pins nothing
+
+ def test_layers_past_the_configs_count_are_not_charged(self, tmp_path, monkeypatch):
+ """DeepSeek-V3 / Kimi K2 MTP layers: the sharder drops them against the config."""
+ panels, path, _calls = _drive_preflight(
+ tmp_path, monkeypatch, layout="fused", tensors=_moe_tensors(extra_layers=1)
+ )
+ dropped = _estimate([path], dtype=_stream_dtype(), num_hidden_layers=N_LAYERS)
+ kept = _estimate([path], dtype=_stream_dtype())
+ assert len(dropped.layer_bytes) == N_LAYERS
+ assert panels[0]["shard_bytes"] == dropped.total_bytes != kept.total_bytes
+
+ def test_a_checkpoint_the_sharder_refuses_is_refused_before_sharding(
+ self, tmp_path, monkeypatch
+ ):
+ tensors = _moe_tensors()
+ del tensors["model.layers.1.mlp.experts.2.up_proj.weight"]
+ with pytest.raises(ValueError, match="incomplete expert projections"):
+ _drive_preflight(tmp_path, monkeypatch, layout="per_expert", tensors=tensors)
+
+ def test_a_probe_that_found_nothing_to_quantise_is_refused(self, tmp_path, monkeypatch):
+ """quant='nf4' with no suffixes is a setup bug, never an approximate figure."""
+ with pytest.raises(ValueError, match="quant_suffixes"):
+ _drive_preflight(tmp_path, monkeypatch, layout="fused", suffixes=frozenset())
+
+ def test_an_unquantised_run_is_charged_its_header_estimate(self, tmp_path, monkeypatch):
+ panels, path, _calls = _drive_preflight(
+ tmp_path, monkeypatch, layout="fused", quantization="none"
+ )
+ expected = _estimate(
+ [path], quant="none", dtype=_stream_dtype(), num_hidden_layers=N_LAYERS
+ )
+ assert panels[0]["shard_bytes"] == expected.total_bytes
+
+
+# --------------------------------------------------------------------------
+# qwen4_exp keeps its own figures; only the source-size one is labelled a guess
+# --------------------------------------------------------------------------
+def _qwen4_panel_text(tmp_path, monkeypatch, *, oq):
+ """The pre-flight panel text of the real setup over a tiny qwen4_exp checkpoint.
+
+ With ``oq`` the checkpoint carries affine companions (``.scales``/``.biases``) and a
+ quantization_config, so ``estimate_oq_stream_cache_bytes`` sizes it from its
+ headers; without, the panel shows the source-size figure.
+ """
+ import io
+ import json
+
+ import torch
+ from rich.console import Console
+ from safetensors.torch import save_file
+
+ import soup_cli.trainer.stream_setup as stream_setup
+ from tests.test_issue602_qwen4_ple_streaming import _drive_qwen4_streaming_setup
+
+ weights = tmp_path / "weights"
+ weights.mkdir()
+ tensors = {"language_model.model.norm.weight": torch.ones(2)}
+ if oq:
+ tensors["language_model.model.layers.0.proj.weight"] = torch.tensor(
+ [[0, 1, 2, 3]], dtype=torch.uint32
+ )
+ tensors["language_model.model.layers.0.proj.scales"] = torch.ones(
+ (1, 1), dtype=torch.bfloat16
+ )
+ tensors["language_model.model.layers.0.proj.biases"] = torch.zeros(
+ (1, 1), dtype=torch.bfloat16
+ )
+ config = {"quantization_config": {"bits": 4, "group_size": 32}}
+ else:
+ tensors["language_model.model.layers.0.proj.weight"] = torch.ones(
+ (2, 2), dtype=torch.bfloat16
+ )
+ config = {}
+ blob = weights / "model.safetensors"
+ save_file(tensors, str(blob))
+ (weights / "config.json").write_text(json.dumps(config), 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)
+
+ buffer = io.StringIO()
+ monkeypatch.setattr(
+ stream_setup, "console", Console(file=buffer, width=400, color_system=None)
+ )
+ monkeypatch.setattr(stream_setup, "_disk_volume", lambda _path: (1, 10**15))
+ _drive_qwen4_streaming_setup(tmp_path, monkeypatch, resolve_weights=_resolve)
+ return " ".join(buffer.getvalue().split())
+
+
+class TestQwen4ExpPanelLabel:
+ def test_an_oq_checkpoint_is_sized_from_its_headers_not_labelled(
+ self, tmp_path, monkeypatch
+ ):
+ text = _qwen4_panel_text(tmp_path, monkeypatch, oq=True)
+ assert "Layer-shard cache:" in text
+ assert "Layer-shard cache: approximately" not in text
+
+ def test_a_non_oq_checkpoint_shows_its_source_size_as_approximate(
+ self, tmp_path, monkeypatch
+ ):
+ text = _qwen4_panel_text(tmp_path, monkeypatch, oq=False)
+ assert "Layer-shard cache: approximately" in text
+
+
+# --------------------------------------------------------------------------
+# the estimate against what the real sharder writes (CPU NF4)
+# --------------------------------------------------------------------------
[email protected](scope="module")
+def tiny_moonlight(tmp_path_factory):
+ """A small `deepseek_v3` base laid out like Moonlight (untied head, q_lora_rank None),
+ saved at bf16 with one 2-D tensor per expert, plus the probe's quant suffixes."""
+ torch = pytest.importorskip("torch")
+ pytest.importorskip("bitsandbytes")
+ transformers = pytest.importorskip("transformers")
+ from soup_cli.utils.layer_stream_runtime import build_meta_skeleton, quantised_layer_suffixes
+
+ torch.manual_seed(3)
+ config = transformers.DeepseekV3Config(
+ vocab_size=256, hidden_size=256, intermediate_size=512, moe_intermediate_size=256,
+ 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=32, q_lora_rank=None,
+ qk_nope_head_dim=32, qk_rope_head_dim=16, v_head_dim=32,
+ max_position_embeddings=64, tie_word_embeddings=False,
+ )
+ model = transformers.DeepseekV3ForCausalLM(config).to(torch.bfloat16)
+ weights = tmp_path_factory.mktemp("tiny-moonlight") / "model"
+ model.save_pretrained(str(weights))
+ del model
+ probe = build_meta_skeleton(str(weights), dtype="bfloat16", quant="nf4")
+ suffixes = quantised_layer_suffixes(probe)
+ del probe
+ return str(weights), suffixes
+
+
[email protected](scope="module")
+def tiny_dense(tmp_path_factory):
+ """A one-layer tied Llama: the smallest cache, where the index's fixed part shows."""
+ torch = pytest.importorskip("torch")
+ pytest.importorskip("bitsandbytes")
+ transformers = pytest.importorskip("transformers")
+ from soup_cli.utils.layer_stream_runtime import build_meta_skeleton, quantised_layer_suffixes
+
+ torch.manual_seed(4)
+ config = transformers.LlamaConfig(
+ vocab_size=128, hidden_size=64, intermediate_size=128, num_hidden_layers=1,
+ num_attention_heads=4, num_key_value_heads=2, tie_word_embeddings=True,
+ max_position_embeddings=64,
+ )
+ model = transformers.LlamaForCausalLM(config).to(torch.bfloat16)
+ weights = tmp_path_factory.mktemp("tiny-dense") / "model"
+ model.save_pretrained(str(weights))
+ del model
+ probe = build_meta_skeleton(str(weights), dtype="bfloat16", quant="nf4")
+ suffixes = quantised_layer_suffixes(probe)
+ del probe
+ return str(weights), suffixes
+
+
+def _against_the_sharder(tmp_path, weights, suffixes, *, arch, layout, quant, double_quant,
+ num_hidden_layers):
+ """Shard for real (CPU NF4) and hold the estimate against the files written.
+
+ Returns ``(estimate, bytes of the cache files)`` after asserting that the payload
+ is exact per decoder layer and outside them, and that the header and index
+ allowances each cover what was written.
+ """
+ from soup_cli.utils.expert_stream import expert_shard_name
+ from soup_cli.utils.layer_shard import (
+ _INDEX_NAME,
+ _discover_safetensors,
+ estimate_shard_cache_bytes,
+ layer_shard_path,
+ shard_cache_disk_bytes,
+ shard_checkpoint,
+ )
+
+ common = dict(
+ dtype="bfloat16", arch=arch, quant=quant,
+ quant_suffixes=suffixes if quant == "nf4" else (), double_quant=double_quant,
+ expert_layout=layout, num_hidden_layers=num_hidden_layers,
+ )
+ estimate = estimate_shard_cache_bytes(_discover_safetensors(weights), **common)
+ out = tmp_path / "cache"
+ index = shard_checkpoint(weights, str(out), quant_device="cpu", **common)
+ actual = shard_cache_disk_bytes(str(out), index)
+
+ headers = 0
+ for idx in range(index.n_layers):
+ header, payload = _header_and_payload(layer_shard_path(str(out), idx))
+ headers += header
+ experts = out / expert_shard_name(idx)
+ if experts.exists():
+ header_x, payload_x = _header_and_payload(str(experts))
+ headers += header_x
+ payload += payload_x
+ assert estimate.layer_bytes[idx] == payload, idx
+ other = 0
+ for name in os.listdir(out):
+ if name == "extras.safetensors" or name.startswith("large_"):
+ header, payload = _header_and_payload(str(out / name))
+ headers += header
+ other += payload
+ assert estimate.other_bytes == other
+ assert estimate.header_bytes >= headers
+ assert estimate.index_bytes >= os.path.getsize(out / _INDEX_NAME)
+ assert estimate.total_bytes >= actual
+ return estimate, actual
+
+
+ ("layout", "quant", "double_quant"),
+ [
+ ("", "nf4", True),
+ ("per_expert", "nf4", True),
+ ("", "nf4", False),
+ ("per_expert", "nf4", False),
+ ("", "none", True),
+ ("per_expert", "none", True),
+ ],
+ ids=["fused-nf4", "per_expert-nf4", "fused-nf4-single", "per_expert-nf4-single",
+ "fused-bf16", "per_expert-bf16"],
+)
+def test_the_moe_estimate_matches_the_cache_the_sharder_writes(
+ tiny_moonlight, tmp_path, layout, quant, double_quant
+):
+ weights, suffixes = tiny_moonlight
+ estimate, actual = _against_the_sharder(
+ tmp_path, weights, suffixes, arch="deepseek_v3", layout=layout, quant=quant,
+ double_quant=double_quant, num_hidden_layers=3,
+ )
+ assert estimate.total_bytes <= actual * 1.05
+
+
+def test_a_minimal_checkpoint_index_is_covered(tmp_path):
+ """Two tensors: the index is mostly its scalar fields, which the fixed part covers."""
+ pytest.importorskip("torch")
+ pytest.importorskip("safetensors")
+ weights = tmp_path / "model"
+ _write_checkpoint(
+ weights,
+ {
+ "model.embed_tokens.weight": ("BF16", (16, 8)),
+ "model.layers.0.input_layernorm.weight": ("BF16", (8,)),
+ },
+ )
+ _against_the_sharder(
+ tmp_path, str(weights), (), arch="llama", layout="", quant="none",
+ double_quant=True, num_hidden_layers=None,
+ )
+
+
[email protected]("quant", ["nf4", "none"])
+def test_the_dense_estimate_matches_the_cache_the_sharder_writes(tiny_dense, tmp_path, quant):
+ weights, suffixes = tiny_dense
+ _against_the_sharder(
+ tmp_path, weights, suffixes, arch="llama", layout="", quant=quant,
+ double_quant=True, num_hidden_layers=None,
+ )