Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
fix(stream): size the early RAM check from the header estimate (#2068)
Alpamys Makazhanebee004b25e1
diff --git a/changelog.d/0.76.0/2068.fixed.md b/changelog.d/0.76.0/2068.fixed.mdnew file mode 100644index 00000000..007c9195--- /dev/null+++ b/changelog.d/0.76.0/2068.fixed.md@@ -0,0 +1 @@+- **The layer-streaming RAM check that runs before sharding (`stream_source: ram`) now charges what the RAM tier will hold.** It charged the flat NF4 rate on the source files' size on disk. That under-counted a fused MoE base under `quantization: 4bit` (Moonlight-16B-A3B: about 8.2 GB against a 30.6 GB cache, whose stacked routed experts stay at the stream dtype) and an FP8 block source about 2x (one byte per weight on disk, dequantised in the cache). Such a base was refused only by the exact check after sharding, after minutes of work and about 30 GB of disk writes. The check now reuses the disk pre-flight's estimate from the source safetensors headers, so the headers are read once. It charges what the check after sharding measures: the decoder-layer files, the embedding and head and the resident extras (not the `per_expert` experts files, which stay on disk on every tier). It refuses by that check's rule, 70% of free RAM or 55% of physical RAM, so a base the exact check would refuse is refused before anything is sharded. When the headers cannot be listed or read, it charges the old rate and the refusal says "approximately". `stream_source: auto` is unchanged: nothing before sharding decides or warns on a RAM figure. (#2068)diff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.mdindex 05de1f77..aa64421f 100644--- a/docs/performance-and-quantization.md+++ b/docs/performance-and-quantization.md@@ -526,7 +526,7 @@ What the sharder does:Measured:- **Numerics.** On a tiny DeepSeek-V3, the model streamed from the FP8 checkpoint matches a resident model holding the same dequantised weights bit for bit, in its logits, loss and LoRA gradients, in both expert layouts. Its layer cache holds the same tensors, bit for bit, as the one sharded from those dequantised weights, NF4 included ([gate](../benchmarks/gate-fp8-shard.md)).-- **Disk.** The pre-flight charges each FP8 weight at the rate its dequantised tensor is stored at, and nothing for the scales.+- **Disk and RAM.** The disk pre-flight charges each FP8 weight at the rate its dequantised tensor is stored at, and nothing for the scales. So does the RAM check that runs before sharding under `stream_source: ram`, so a base whose dequantised weights do not fit in RAM is refused before anything is written.- **A real checkpoint, CPU only.** Moonlight-16B-A3B, converted to this format, sharded in 93 s (27 layers, NF4, `fused`). The 30.60 GB cache came within 0.0002% of the pre-flight's figure (0.000115%: 35,336 bytes), and every FP8-derived tensor checked in three layers equals an independent dequantisation of the source. No GPU run is recorded yet.Limits and refusals:@@ -534,7 +534,6 @@ Limits and refusals:- **Other FP8 formats.** Each of these is refused, and the message names the supported format: per-tensor scales, `e5m2` weights, `compressed-tensors`, ue8m0 (power-of-two) scales, static activation scales, a missing or misshapen scale, an FP8 tensor without a scale, and a scale without its tensor. A `weight_block_size` axis outside [1, 1048576] is refused too. A spelling the config already gives away is refused at setup, before any weight is resolved or downloaded; the rest before the first byte of the cache is written.- **Damaged values.** A weight that is NaN after dequantisation (the e4m3fn bytes 0x7F and 0xFF), a negative scale, a non-finite scale, and a weight past float16's range under a float16 stream (pre-Ampere cards; stream it in bfloat16) are refused, naming the tensor, when that tensor is read: before the cache index is written, though files of earlier layers may already be on disk (no index names them, so they are never used, and the next run shards again). A zero scale, as an all-zero block has, is kept.- **Cache identity.** For `deepseek_v3`, `config.json` is part of the cache's source identity, as are the weight files, so a cache sharded from the bf16 checkpoint is never reused for its FP8 copy at the same path, nor the reverse.-- **The early RAM check.** The check that runs before sharding still charges the FP8 files at their size on disk, about half the dequantised weights. A base that cannot fit in RAM may therefore be refused after sharding, by the exact check, rather than before it.- **After training.** The adapter is trained against the dequantised weights. Merging it or serving it loads the base through transformers' own FP8 path, which is a different numerical path from the one the adapter was trained on.**`stream_nf4_scale_cache` (opt-in).** On the dequantise + `F.linear` path, a@@ -960,8 +959,14 @@ an untied head and the norms stay at the stream dtype rather than NF4: Llama-3.1Mistral-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 oldfigure 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.+(`stream_source: ram`, before sharding) charges the same estimate, read once: the decoder-layer+files, the embedding and head and the resident extras, which is what the check after sharding+measures on the real store (the `per_expert` experts files stay on disk on every tier and are+not charged). It refuses by that check's rule, 70% of free RAM or 55% of physical RAM, so a+base the exact check would refuse is refused before anything is sharded. When the headers+cannot be listed or read, it charges the flat NF4 rate on the size on disk and its refusal+says approximately. `stream_source: auto` is not checked before sharding: it picks its tier+after sharding, from the real store.**Two or more NVMe drives.** On a cold store larger than RAM the disk-tier step can wait on theread (measured for a 70B-shaped store), and then one drive is the ceiling. Setdiff --git a/src/soup_cli/trainer/stream_setup.py b/src/soup_cli/trainer/stream_setup.pyindex 187b7971..ef475b4d 100644--- a/src/soup_cli/trainer/stream_setup.py+++ b/src/soup_cli/trainer/stream_setup.py@@ -213,6 +213,66 @@ def _validate_qwen4_ngram_ram_fit()+def _validate_early_ram_fit(+ *,+ base: str,+ source_bytes: int,+ ram_bytes: int,+ approximate: bool,+ quantised: bool,+ free_ram: Optional[int],+ total_ram: Optional[int],+) -> None:+ """Refuse a ``stream_source: ram`` run BEFORE sharding when the RAM tier cannot hold it.++ ``ram_bytes`` is what the check after sharding (:func:`_validate_qwen4_ngram_ram_fit`)+ charges, sized from the source headers (``ShardCacheEstimate.ram_tier_bytes``): the+ decoder-layer files, the embedding/head shards and the resident extras. The rule is+ that check's rule (70% of free RAM, 55% of physical RAM, either reached refuses), so+ a base the exact check would refuse is refused here, before minutes of disk writes.++ ``approximate`` marks the fallback for source headers that cannot be listed or read:+ the flat NF4 rate on the size on disk, which errs low (far low for a fused MoE base)+ and is labelled as a guess, the way the disk pre-flight panel labels it.++ A figure psutil cannot report (``None``) is not checked. That mirrors the check+ after sharding, which replaces an unknown free RAM by ten times the store and so+ can still refuse only by the physical ceiling, when the total is known.+ """+ from soup_cli.utils.layer_stream import (+ PHYSICAL_RAM_TIER_HEADROOM,+ PHYSICAL_RAM_TIER_HEADROOM_PERCENT,+ RAM_TIER_HEADROOM,+ )++ if total_ram is not None and ram_bytes >= total_ram * PHYSICAL_RAM_TIER_HEADROOM:+ limit = (+ f"more than {PHYSICAL_RAM_TIER_HEADROOM_PERCENT}% of physical RAM "+ f"({total_ram / 1e9:.1f} GB)"+ )+ elif free_ram is not None and ram_bytes >= free_ram * RAM_TIER_HEADROOM:+ limit = f"and only {free_ram / 1e9:.1f} GB of RAM is free"+ else:+ return+ if approximate:+ streamed = "once quantised to NF4" if quantised else "in RAM"+ need = (+ f"is {source_bytes / 1e9:.1f} GB on disk, approximately "+ f"{ram_bytes / 1e9:.1f} GB {streamed} (its safetensors headers could not "+ "be listed or read),"+ )+ else:+ need = (+ f"needs {ram_bytes / 1e9:.1f} GB of RAM once sharded (sized from its "+ f"safetensors headers; {source_bytes / 1e9:.1f} GB on disk),"+ )+ raise ValueError(+ f"training.stream_source='ram' but {base} {need} {limit}. Refusing before "+ "sharding. Set stream_source='auto' to fall back to the NVMe disk tier, free "+ "RAM, or pick a smaller base."+ )++def _validate_stream_staging_ram_fit(*,staging_bytes: int,@@ -540,6 +600,18 @@ def _planned_source_shards(weights_plan: Any) -> list[str]:)+@dataclass(frozen=True)+class _ResolvedWeights:+ """A weight directory already resolved to regular files, as a pre-flight plan.++ No copy is pending, so :func:`_planned_source_shards` lists it the way the sharder+ lists it.+ """++ weights_dir: str+ needs_materialization: bool = False++#: 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)@@ -992,21 +1064,27 @@ class StreamingSetupMixin:moe_targets = resolve_moe_lora_targets(probe, tcfg, None, console=console)del probe+ # One set of arguments for every header estimate of this run's cache.+ estimate_kwargs = dict(+ 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,+ quantization_config=source_quantization,+ )+ # The disk pre-flight's estimate, kept for the early RAM check below so the+ # source headers are read once. Present (possibly None) once it has run.+ preflight_estimate: dict = {}+def _disk_preflight(weights_plan) -> None:# 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,- quantization_config=source_quantization,- )+ cache_estimate = _preflight_cache_estimate(weights_plan, **estimate_kwargs)+ preflight_estimate["cache"] = cache_estimateif cache_estimate is not None:shard_estimate = cache_estimate.total_byteselse:@@ -1079,38 +1157,44 @@ class StreamingSetupMixin:before_materialize=_disk_preflight,)- # Cheap size probe BEFORE sharding: re-writing a checkpoint we are- # about to refuse for not fitting in RAM costs minutes of disk I/O.- # Charged at the STREAMED rate, not the on-disk one — an 8B bf16- # checkpoint is 16 GB on disk but only ~4.2 GB of NF4 store, and- # comparing the raw file size would refuse exactly the runs NF4 enables.- early_free_ram = free_ram_bytes()- if early_free_ram is not None:- source_bytes = source_weight_bytes(weights_dir)- store_estimate = estimate_stream_store_bytes(- source_bytes, dtype=dtype, quant=quant, double_quant=double_quant- )- # Qwen4's source size includes the PLE table, which the sharder- # leaves external. Its exact RAM/disk decision is made from the- # safetensors header below; counting it here would reject the very- # `stream_ngram_source: disk` run this path enables.- if (- arch != "qwen4_exp"- and store_estimate >= early_free_ram * RAM_TIER_HEADROOM- and tcfg.stream_source == "ram"- ):- as_streamed = (- ""- if quant == QUANT_NONE- else f" ({store_estimate / 1e9:.1f} GB once quantised to NF4)"+ # RAM check BEFORE sharding: re-writing a checkpoint we are about to refuse+ # for not fitting in RAM costs minutes of disk I/O. Only `stream_source: ram`+ # insists on the RAM tier; `auto` falls back to disk after sharding, from the+ # real store. Charged what the check after sharding charges, from the disk+ # pre-flight's header estimate (fused MoE experts at the stream dtype, FP8+ # weights dequantised, embeddings and norms unquantised), not the on-disk+ # size at a flat NF4 rate, which errs low. That rate is the fallback only+ # when the headers cannot be listed or read, and says approximately.+ # Qwen4's source size includes the PLE table, which the sharder leaves+ # external. Its exact RAM/disk decision is made from the safetensors header+ # below; counting it here would reject the very `stream_ngram_source: disk`+ # run this path enables. A RAM figure psutil cannot report is not checked,+ # as after sharding (see `_validate_early_ram_fit`).+ if arch != "qwen4_exp" and tcfg.stream_source == "ram":+ if "cache" in preflight_estimate:+ cache_estimate = preflight_estimate["cache"]+ else:+ # A resolver that did not call the pre-flight back: the resolved+ # directory holds regular files, so it is sized where it lies.+ cache_estimate = _preflight_cache_estimate(+ _ResolvedWeights(weights_dir), **estimate_kwargs)- raise ValueError(- f"training.stream_source='ram' but {cfg.base} is "- f"{source_bytes / 1e9:.1f} GB on disk{as_streamed} and only "- f"{early_free_ram / 1e9:.1f} GB of RAM is free. Set "- f"stream_source='auto' to fall back to the NVMe disk tier, "- f"free RAM, or pick a smaller base."+ source_bytes = source_weight_bytes(weights_dir)+ if cache_estimate is not None:+ ram_bytes = cache_estimate.ram_tier_bytes+ else:+ ram_bytes = estimate_stream_store_bytes(+ source_bytes, dtype=dtype, quant=quant, double_quant=double_quant)+ _validate_early_ram_fit(+ base=cfg.base,+ source_bytes=source_bytes,+ ram_bytes=ram_bytes,+ approximate=cache_estimate is None,+ quantised=quant != QUANT_NONE,+ free_ram=free_ram_bytes(),+ total_ram=total_ram_bytes(),+ )console.print(f"[dim]Preparing layer shards -> {shard_dir}[/]")index = shard_checkpoint(diff --git a/src/soup_cli/utils/layer_shard.py b/src/soup_cli/utils/layer_shard.pyindex b53d441e..bb5841df 100644--- a/src/soup_cli/utils/layer_shard.py+++ b/src/soup_cli/utils/layer_shard.py@@ -1052,17 +1052,40 @@ class ShardCacheEstimate:to the same root). ``other_bytes`` is the payload of the extras shard and thelarge embed/head shards, all on root 0. Both are exact. ``header_bytes`` and``index_bytes`` bound the safetensors headers and ``index.json`` from above.++ ``expert_file_bytes`` is the part of ``layer_bytes`` that lives in the+ per_expert experts files (0 for the fused layout), and ``code_table_bytes``+ the part of ``other_bytes`` that is the shared NF4 code tables (0 without+ NF4). Neither is held by the RAM tier; see :attr:`ram_tier_bytes`."""layer_bytes: Tuple[int, ...]other_bytes: intheader_bytes: intindex_bytes: int+ expert_file_bytes: int = 0+ code_table_bytes: int = 0@propertydef total_bytes(self) -> int:return sum(self.layer_bytes) + self.other_bytes + self.header_bytes + self.index_bytes+ @property+ def ram_tier_bytes(self) -> int:+ """Host RAM the RAM tier holds for this cache: what the post-shard check charges.++ The decoder-layer files plus the large embed/head shards (the store), plus+ the resident extras. The per_expert experts files are read from the cache+ volume on every tier, and the NF4 code tables are machinery that+ ``extras_resident_bytes`` leaves out, so neither is counted.+ """+ return (+ sum(self.layer_bytes)+ - self.expert_file_bytes+ + self.other_bytes+ - self.code_table_bytes+ )+def estimate_shard_cache_bytes(shard_paths: Sequence[str],@@ -1134,6 +1157,8 @@ def estimate_shard_cache_bytes(routed: Dict[int, Dict[int, Dict[str, int]]] = {}other_bytes = 0header_bytes = 0+ expert_file_bytes = 0+ code_table_bytes = 0stored_names: set = set()any_nf4 = False@@ -1189,14 +1214,17 @@ def estimate_shard_cache_bytes(]if experts_nf4:any_nf4 = True- layer_bytes[idx] += sum(+ experts_payload = 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+ experts_payload = sum(gate_up + down for gate_up, down in pairs) * itemsize+ layer_bytes[idx] += experts_payloadif expert_layout == EXPERT_LAYOUT_PER_EXPERT:+ # In the experts file, not the layer file: never held by the RAM tier.+ expert_file_bytes += experts_payload# experts_NNN.safetensors, whose keys index.json does not list.parts = sidecars if experts_nf4 else ("",)names = [@@ -1229,7 +1257,8 @@ def estimate_shard_cache_bytes(tables = {NF4_CODE_KEY: 16 * 4}if double_quant:tables[NF4_NESTED_CODE_KEY] = 256 * 4- other_bytes += sum(tables.values())+ code_table_bytes = sum(tables.values())+ other_bytes += code_table_bytesheader_bytes += _charge_names(tables)index_entries = len(shard_paths) + len(stored_names) + len(suffixes) + n_layersreturn ShardCacheEstimate(@@ -1237,6 +1266,8 @@ def estimate_shard_cache_bytes(other_bytes=other_bytes,header_bytes=header_bytes,index_bytes=_INDEX_BYTES_FIXED + _INDEX_BYTES_PER_ENTRY * index_entries,+ expert_file_bytes=expert_file_bytes,+ code_table_bytes=code_table_bytes,)diff --git a/src/soup_cli/utils/layer_stream.py b/src/soup_cli/utils/layer_stream.pyindex 8fecaaba..5d2cb9c3 100644--- a/src/soup_cli/utils/layer_stream.py+++ b/src/soup_cli/utils/layer_stream.py@@ -1014,13 +1014,13 @@ def estimate_stream_store_bytes(Deliberately coarse: it assumes the source is stored at ``dtype`` andcharges the NF4 rate to every parameter, while layernorms and (in the shard- 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.+ set) the embeddings actually stay unquantised. That errs LOW — 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``, and+ for an FP8 block source, whose files hold one byte per weight. So the disk+ pre-flight and the early RAM check both size the cache from the source headers+ instead (``layer_shard.estimate_shard_cache_bytes``) and fall back to this+ ratio only when those headers cannot be listed or read."""if quant not in SUPPORTED_STREAM_QUANTS:raise ValueError(diff --git a/tests/test_issue602_qwen4_ple_streaming.py b/tests/test_issue602_qwen4_ple_streaming.pyindex 5ea4f9aa..fde40f4b 100644--- a/tests/test_issue602_qwen4_ple_streaming.py+++ b/tests/test_issue602_qwen4_ple_streaming.py@@ -704,6 +704,8 @@ def _drive_qwen4_streaming_setup(tcfg_overrides=None,disk_kind="ssd",disk_calls=None,+ free_ram=1_000_000,+ total_ram=2_000_000,resolve_targets=None,):"""Drive the real `_setup_streaming_transformers()` for a qwen4_exp base.@@ -725,7 +727,8 @@ def _drive_qwen4_streaming_setup(`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;+ when a list, receives the (path, override) of every call to it; `free_ram` and+ `total_ram` are what the stubbed `free_ram_bytes` / `total_ram_bytes` report;`resolve_targets` replaces the `resolve_lora_target_modules` stub (whichanswers `["q_proj"]` whatever it is given), so a test about targetresolution can hand the setup the real resolver@@ -736,7 +739,7 @@ def _drive_qwen4_streaming_setup(import soup_cli.trainer.stream_setup as stream_setup- harness_total_ram = 2_000_000+ harness_total_ram = total_ramharness_resident_ram = 4_096class _Wrapper(stream_setup.StreamingSetupMixin):@@ -860,7 +863,7 @@ def _drive_qwen4_streaming_setup(or (lambda *_a, **_k: str(tmp_path / "weights")),)monkeypatch.setattr(- "soup_cli.utils.layer_stream.free_ram_bytes", lambda: 1_000_000+ "soup_cli.utils.layer_stream.free_ram_bytes", lambda: free_ram)monkeypatch.setattr("soup_cli.utils.layer_stream.total_ram_bytes", lambda: harness_total_ramdiff --git a/tests/test_stream_ram_preflight_estimate.py b/tests/test_stream_ram_preflight_estimate.pynew file mode 100644index 00000000..9d152c0d--- /dev/null+++ b/tests/test_stream_ram_preflight_estimate.py@@ -0,0 +1,841 @@+"""Layer streaming's early RAM check charges what the RAM tier will hold, from the headers.++`soup train` with `training.stream_layers: true` and `training.stream_source: ram` refuses a+base the RAM tier cannot hold. One check runs BEFORE sharding, so that such a base is refused+before minutes of disk writes; the exact one runs after, on the shard headers. The early one+charged the flat NF4 rate to the source files' size on disk. A fused MoE base under+`quantization: 4bit` was under-counted (Moonlight-16B-A3B: ~8.2 GB against a 30.6 GB cache,+whose stacked routed experts stay at the stream dtype), and an FP8 block source about 2x (one+byte per weight on disk, the dequantised weight in the cache). Such a run was refused only by+the exact check, after the sharder had written ~30 GB.++The early check now charges the disk pre-flight's header estimate+(`layer_shard.estimate_shard_cache_bytes`, read once per setup) for exactly what the exact+check counts: the decoder-layer files, the embedding/head shards and the resident extras, not+the per_expert experts files and not the NF4 code tables. The flat rate is the fallback only+when the headers cannot be listed or read, and its refusal says approximately.++Every setup-level case drives the real `_setup_streaming_transformers` through the shared+harness in `tests/test_issue602_qwen4_ple_streaming.py`, the way+`tests/test_stream_disk_preflight_moe.py` drives the disk pre-flight. The harness stubs the+sharder, so an empty list of sharder calls means no shard was written.+"""++import json+import math+import os+import types++import pytest++from tests.test_stream_disk_preflight_moe import (+ _MALFORMED,+ DENSE_INTER,+ HIDDEN,+ N_LAYERS,+ SUFFIXES,+ VOCAB,+ _deepseek_cfg,+ _dense_tensors,+ _moe_tensors,+ _write_checkpoint,+ _write_raw,+)++#: The meta probe's suffixes for the dense (Llama-shaped) base: every decoder nn.Linear.+DENSE_SUFFIXES = frozenset(+ {+ "self_attn.q_proj.weight",+ "self_attn.o_proj.weight",+ "mlp.gate_proj.weight",+ "mlp.up_proj.weight",+ "mlp.down_proj.weight",+ }+)+_BASE = "qwen4-test" # the harness's cfg.base+++def _stream_dtype():+ from soup_cli.utils.layer_stream import resolve_stream_dtype++ return resolve_stream_dtype("cpu")+++def _llama_cfg():+ return types.SimpleNamespace(+ model_type="llama", hidden_size=HIDDEN, num_hidden_layers=1, vocab_size=VOCAB,+ intermediate_size=DENSE_INTER,+ )+++def _with_config(directory, model_type, num_hidden_layers):+ (directory / "config.json").write_text(+ json.dumps({"model_type": model_type, "num_hidden_layers": num_hidden_layers}),+ encoding="utf-8",+ )+ return directory+++def _moe_dir(tmp_path, tensors=None):+ weights = tmp_path / "weights"+ _write_checkpoint(weights, tensors or _moe_tensors())+ return _with_config(weights, "deepseek_v3", N_LAYERS)+++def _dense_dir(tmp_path):+ weights = tmp_path / "weights"+ _write_checkpoint(weights, _dense_tensors())+ return _with_config(weights, "llama", 1)+++def _source_bytes(weights):+ return sum(+ os.path.getsize(os.path.join(weights, name))+ for name in os.listdir(weights)+ if name.endswith(".safetensors")+ )+++def _estimate(weights, *, arch="deepseek_v3", quant="nf4", suffixes=SUFFIXES, layout="",+ num_hidden_layers=N_LAYERS, double_quant=True, quantization_config=None):+ """The header estimate the setup computes for this run, called directly."""+ from soup_cli.utils.layer_shard import _discover_safetensors, estimate_shard_cache_bytes++ return estimate_shard_cache_bytes(+ _discover_safetensors(str(weights)), dtype=_stream_dtype(), arch=arch, quant=quant,+ quant_suffixes=suffixes if quant == "nf4" else (), double_quant=double_quant,+ expert_layout=layout, num_hidden_layers=num_hidden_layers,+ quantization_config=quantization_config,+ )+++def _flat(source_bytes, quant="nf4"):+ """The old early charge: the NF4 rate to every byte on disk."""+ from soup_cli.utils.layer_stream import estimate_stream_store_bytes++ return estimate_stream_store_bytes(source_bytes, dtype=_stream_dtype(), quant=quant)+++def _free_for_budget(budget):+ """Free RAM whose 70% RAM-tier headroom is ``budget`` (to within a byte)."""+ from soup_cli.utils.layer_stream import RAM_TIER_HEADROOM++ return int(budget / RAM_TIER_HEADROOM)+++def _drive(tmp_path, monkeypatch, *, weights, arch="deepseek_v3", model_cfg=None,+ layout="fused", quantization="4bit", double_quant=True, suffixes=SUFFIXES,+ stream_source="ram", free_ram=10**15, total_ram=10**15, run_preflight=True,+ plan_overrides=None):+ """Run the real setup through the shared harness; return what it saw.++ ``early``: the keyword arguments of every early-check call; ``shards``: every sharder+ call (stubbed, so empty means nothing was written); ``reads``: how many times the source+ headers were read for an estimate; ``error``: the ValueError the setup raised, if any.+ ``run_preflight=False`` is a resolver that does not call the disk pre-flight back.+ """+ import soup_cli.trainer.stream_setup as stream_setup+ import soup_cli.utils.layer_shard as layer_shard+ 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++ monkeypatch.delenv("SOUP_LAYER_STREAM_STRIPE_DIRS", raising=False)+ weights = str(weights)+ size = _source_bytes(weights)+ plan = types.SimpleNamespace(+ weights_dir=weights, source_dir=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 run_preflight and before_materialize is not None:+ before_materialize(plan)+ return weights++ seen = {"early": [], "shards": [], "reads": 0}+ real_early = stream_setup._validate_early_ram_fit++ def _early_spy(**kwargs):+ seen["early"].append(kwargs)+ return real_early(**kwargs)++ real_read = layer_shard._read_source_tensors++ def _read_spy(paths):+ seen["reads"] += 1+ return real_read(paths)++ monkeypatch.setattr(stream_setup, "_validate_early_ram_fit", _early_spy)+ monkeypatch.setattr(layer_shard, "_read_source_tensors", _read_spy)+ monkeypatch.setattr(+ stream_setup.StreamingSetupMixin, "_stream_meta_skeleton",+ classmethod(lambda cls, *a, **k: 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, 10**15))+ try:+ _drive_qwen4_streaming_setup(+ tmp_path, monkeypatch, resolve_weights=_resolve, arch=arch,+ model_cfg=model_cfg or _deepseek_cfg(), shard_calls=seen["shards"],+ free_ram=free_ram, total_ram=total_ram,+ tcfg_overrides={+ "stream_expert_layout": layout,+ "quantization": quantization,+ "double_quant_on": double_quant,+ "stream_source": stream_source,+ },+ )+ except ValueError as exc:+ seen["error"] = exc+ return seen+++def _text(seen):+ assert "error" in seen, "the setup was not refused"+ return " ".join(str(seen["error"]).split())+++def _passed(seen):+ assert "error" not in seen, seen.get("error")+ return seen+++# --------------------------------------------------------------------------+# 1-2. a fused MoE base: refused early by the header estimate, passes when it fits+# --------------------------------------------------------------------------+class TestAFusedMoeBase:+ def test_over_free_ram_by_the_estimate_but_not_the_flat_rate_is_refused_before_sharding(+ self, tmp_path, monkeypatch+ ):+ weights = _moe_dir(tmp_path)+ need = _estimate(weights).ram_tier_bytes+ flat = _flat(_source_bytes(weights))+ assert flat < need # the fused experts stay at the stream dtype+ free = _free_for_budget((flat + need) // 2)+ seen = _drive(tmp_path, monkeypatch, weights=weights, free_ram=free)+ text = _text(seen)+ assert "training.stream_source='ram'" in text+ assert "needs" in text and "of RAM once sharded" in text+ assert "sized from its safetensors headers" in text+ assert "Refusing before sharding" in text+ assert "stream_source='auto' to fall back to the NVMe disk tier" in text+ assert "approximately" not in text+ assert seen["shards"] == [] # nothing was sharded+ assert [call["ram_bytes"] for call in seen["early"]] == [need]+ assert seen["early"][0]["approximate"] is False+ # the on-disk figure is the source size (the harness reports 1,024 bytes)+ assert seen["early"][0]["source_bytes"] == 1_024++ def test_the_old_flat_rate_would_have_let_it_through(self, tmp_path):+ """The control: at that free RAM the flat figure is under the headroom."""+ from soup_cli.trainer.stream_setup import _validate_early_ram_fit++ weights = _moe_dir(tmp_path)+ need = _estimate(weights).ram_tier_bytes+ flat = _flat(_source_bytes(weights))+ free = _free_for_budget((flat + need) // 2)+ _validate_early_ram_fit(+ base=_BASE, source_bytes=_source_bytes(weights), ram_bytes=flat,+ approximate=True, quantised=True, free_ram=free, total_ram=None,+ )++ @pytest.mark.parametrize("layout", ["fused", "per_expert"])+ def test_a_base_that_fits_passes_and_is_sharded(self, tmp_path, monkeypatch, layout):+ weights = _moe_dir(tmp_path)+ need = _estimate(weights, layout="" if layout == "fused" else layout).ram_tier_bytes+ free = math.ceil(need / 0.7) + 2+ seen = _passed(+ _drive(tmp_path, monkeypatch, weights=weights, layout=layout, free_ram=free)+ )+ assert [call["ram_bytes"] for call in seen["early"]] == [need]+ assert len(seen["shards"]) == 1++ def test_the_per_expert_experts_files_are_not_charged(self, tmp_path, monkeypatch):+ """They are read from the cache volume on every tier; the RAM tier never holds them."""+ weights = _moe_dir(tmp_path)+ per_expert = _estimate(weights, layout="per_expert")+ assert per_expert.expert_file_bytes > 0+ seen = _passed(_drive(tmp_path, monkeypatch, weights=weights, layout="per_expert"))+ charged = seen["early"][0]["ram_bytes"]+ assert charged == sum(per_expert.layer_bytes) - per_expert.expert_file_bytes + (+ per_expert.other_bytes - per_expert.code_table_bytes+ )+ assert charged < sum(per_expert.layer_bytes) + per_expert.other_bytes++ def test_over_physical_ram_is_refused_before_sharding(self, tmp_path, monkeypatch):+ """The exact check's second rule, 55% of physical RAM, applies early too."""+ weights = _moe_dir(tmp_path)+ need = _estimate(weights).ram_tier_bytes+ seen = _drive(+ tmp_path, monkeypatch, weights=weights, free_ram=10**15, total_ram=need+ )+ text = _text(seen)+ assert "more than 55% of physical RAM" in text+ assert "Refusing before sharding" in text+ assert seen["shards"] == []+++# --------------------------------------------------------------------------+# the estimate is read once: reused from the disk pre-flight+# --------------------------------------------------------------------------+class TestTheHeadersAreReadOnce:+ def test_the_early_check_reuses_the_disk_preflights_estimate(self, tmp_path, monkeypatch):+ weights = _moe_dir(tmp_path)+ seen = _passed(_drive(tmp_path, monkeypatch, weights=weights))+ assert seen["reads"] == 1+ assert seen["early"][0]["approximate"] is False++ def test_without_a_disk_preflight_the_resolved_directory_is_sized(+ self, tmp_path, monkeypatch+ ):+ """A resolver that never called the pre-flight back: the flat rate is not a fallback+ for readable headers, so the resolved directory is sized instead, once."""+ weights = _moe_dir(tmp_path)+ need = _estimate(weights).ram_tier_bytes+ seen = _passed(_drive(tmp_path, monkeypatch, weights=weights, run_preflight=False))+ assert seen["reads"] == 1+ assert [call["ram_bytes"] for call in seen["early"]] == [need]+ assert seen["early"][0]["approximate"] is False++ def test_auto_is_not_checked_early_and_reads_nothing_more(self, tmp_path, monkeypatch):+ """Only `ram` insists on the RAM tier. `auto` takes the disk tier when RAM is short,+ which is decided after sharding from the real store, so nothing before sharding+ refuses or warns on any RAM figure, even with no RAM free at all."""+ weights = _moe_dir(tmp_path)+ seen = _passed(+ _drive(+ tmp_path, monkeypatch, weights=weights, stream_source="auto",+ free_ram=1, run_preflight=False,+ )+ )+ assert seen["early"] == []+ assert seen["reads"] == 0+ assert len(seen["shards"]) == 1++ def test_a_qwen4_exp_base_is_left_to_its_exact_check(self, tmp_path, monkeypatch):+ """Its source size includes the external PLE table: charging it early would refuse+ the `stream_ngram_source: disk` run that path exists for."""+ import soup_cli.trainer.stream_setup as stream_setup+ from tests.test_issue602_qwen4_ple_streaming import _drive_qwen4_streaming_setup++ calls = []+ monkeypatch.setattr(+ stream_setup, "_validate_early_ram_fit", lambda **kwargs: calls.append(kwargs)+ )+ shards = []+ _drive_qwen4_streaming_setup(+ tmp_path, monkeypatch, shard_calls=shards, free_ram=100,+ tcfg_overrides={"stream_source": "ram"},+ )+ assert calls == []+ assert len(shards) == 1+++# --------------------------------------------------------------------------+# 3. an FP8 block source is charged its dequantised size+# --------------------------------------------------------------------------+#: Large enough that the weights, not the safetensors header, dominate the file size.+_FP8_HIDDEN, _FP8_INTER, _FP8_VOCAB, _FP8_EXPERTS, _FP8_LAYERS = 256, 128, 64, 2, 2+_FP8_BLOCK = (128, 128) # DeepSeek-V3's own block size+_FP8_SUFFIXES = frozenset({"self_attn.o_proj.weight"})+++def _fp8_pair(tmp_path):+ """(FP8 block checkpoint, the same weights dequantised, its quantization_config).++ Built with `tests/test_fp8_block_streaming.py`'s quantiser and writer: a DeepSeek-V3+ layout whose attention output and routed experts are FP8 with a scale per block, the+ embeddings, head, norms and router bf16.+ """+ torch = pytest.importorskip("torch")+ pytest.importorskip("safetensors")+ from tests.test_fp8_block_streaming import _dequantised, _to_fp8, _write++ generator = torch.Generator().manual_seed(5)++ def normal(*shape):+ return torch.randn(*shape, generator=generator).to(torch.bfloat16)++ hidden, inter = _FP8_HIDDEN, _FP8_INTER+ state = {+ "model.embed_tokens.weight": normal(_FP8_VOCAB, hidden),+ "model.norm.weight": normal(hidden),+ "lm_head.weight": normal(_FP8_VOCAB, hidden),+ }+ linears = []+ for layer in range(_FP8_LAYERS):+ prefix = f"model.layers.{layer}."+ state[prefix + "input_layernorm.weight"] = normal(hidden)+ linears.append(prefix + "self_attn.o_proj.weight")+ state[linears[-1]] = normal(hidden, hidden)+ state[prefix + "mlp.gate.weight"] = normal(_FP8_EXPERTS, hidden)+ state[prefix + "mlp.gate.e_score_correction_bias"] = torch.randn(+ _FP8_EXPERTS, generator=generator+ )+ for expert in range(_FP8_EXPERTS):+ for name, shape in (+ ("gate_proj", (inter, hidden)),+ ("up_proj", (inter, hidden)),+ ("down_proj", (hidden, inter)),+ ):+ linears.append(prefix + f"mlp.experts.{expert}.{name}.weight")+ state[linears[-1]] = normal(*shape)+ fp8_state = _to_fp8(state, linears, _FP8_BLOCK)+ fp8 = _write(tmp_path / "fp8", fp8_state, block=_FP8_BLOCK, layers=_FP8_LAYERS)+ ref = _write(+ tmp_path / "ref", _dequantised(fp8_state, _FP8_BLOCK), quant=None, layers=_FP8_LAYERS+ )+ with open(os.path.join(fp8, "config.json"), encoding="utf-8") as handle:+ quantization_config = json.load(handle)["quantization_config"]+ return fp8, ref, quantization_config+++def _fp8_cfg(quantization_config):+ return types.SimpleNamespace(+ model_type="deepseek_v3", hidden_size=_FP8_HIDDEN, num_hidden_layers=_FP8_LAYERS,+ vocab_size=_FP8_VOCAB, intermediate_size=_FP8_INTER,+ quantization_config=quantization_config,+ )+++class TestAnFp8BlockSource:+ @pytest.mark.parametrize("quantization", ["none", "4bit"])+ def test_it_is_charged_its_dequantised_size(self, tmp_path, monkeypatch, quantization):+ fp8, ref, quantization_config = _fp8_pair(tmp_path)+ quant = "nf4" if quantization == "4bit" else "none"+ dequantised = _estimate(+ ref, quant=quant, suffixes=_FP8_SUFFIXES, num_hidden_layers=_FP8_LAYERS+ )+ seen = _passed(+ _drive(+ tmp_path, monkeypatch, weights=fp8, model_cfg=_fp8_cfg(quantization_config),+ quantization=quantization, suffixes=_FP8_SUFFIXES,+ )+ )+ assert [call["ram_bytes"] for call in seen["early"]] == [dequantised.ram_tier_bytes]+ assert seen["early"][0]["approximate"] is False+ # one byte per FP8 weight on disk: the old charge was well under the dequantised one+ assert 2 * _flat(_source_bytes(fp8), quant=quant) < dequantised.ram_tier_bytes++ def test_one_that_fits_its_files_but_not_its_dequantised_weights_is_refused_early(+ self, tmp_path, monkeypatch+ ):+ fp8, ref, quantization_config = _fp8_pair(tmp_path)+ need = _estimate(ref, quant="none", num_hidden_layers=_FP8_LAYERS).ram_tier_bytes+ flat = _flat(_source_bytes(fp8), quant="none")+ assert flat < need+ seen = _drive(+ tmp_path, monkeypatch, weights=fp8, model_cfg=_fp8_cfg(quantization_config),+ quantization="none", free_ram=_free_for_budget((flat + need) // 2),+ )+ text = _text(seen)+ assert "sized from its safetensors headers" in text+ assert "Refusing before sharding" in text+ assert seen["shards"] == []+++# --------------------------------------------------------------------------+# 4. the early and the late check agree for the same base+# --------------------------------------------------------------------------+def _random_checkpoint(directory, tensors, *, model_type, num_hidden_layers, seed=0):+ """Real values (NF4 of an all-zero block is degenerate), the same headers as ``tensors``."""+ torch = pytest.importorskip("torch")+ from safetensors.torch import save_file++ dtypes = {"BF16": torch.bfloat16, "F16": torch.float16, "F32": torch.float32}+ generator = torch.Generator().manual_seed(seed)+ state = {+ key: torch.randn(*shape, generator=generator).to(dtypes[dtype])+ for key, (dtype, shape) in tensors.items()+ }+ directory.mkdir(parents=True, exist_ok=True)+ save_file(state, str(directory / "model.safetensors"))+ return _with_config(directory, model_type, num_hidden_layers)+++def _late_charge(weights, out, shard_kwargs):+ """Shard for real with the setup's own arguments; return what the exact check charges.++ The same calls the setup makes after sharding: the decoder-layer files' tensors, the+ embed/head shards and the resident extras (``store_total + embed_bytes``).+ """+ from soup_cli.utils.layer_shard import layer_paths, shard_checkpoint+ from soup_cli.utils.layer_stream import dtype_bytes+ from soup_cli.utils.layer_stream_runtime import (+ RamSource,+ extras_resident_bytes,+ large_layer_store_bytes,+ )++ index = shard_checkpoint(str(weights), str(out), **shard_kwargs)+ layer_specs = RamSource.layer_specs_from_paths(layer_paths(str(out), index))+ layer_store = sum(+ math.prod(shape) * dtype_bytes(stored)+ for per_layer in layer_specs+ for shape, stored in per_layer.values()+ )+ return layer_store + large_layer_store_bytes(str(out), index) + extras_resident_bytes(str(out))+++_AGREEMENT_CASES = [+ ("deepseek_v3", "fused", "4bit", True),+ ("deepseek_v3", "per_expert", "4bit", True),+ ("deepseek_v3", "fused", "4bit", False),+ ("deepseek_v3", "fused", "none", True),+ ("deepseek_v3", "per_expert", "none", True),+ ("llama", "fused", "4bit", True),+ ("llama", "fused", "none", True),+]+++ ("arch", "layout", "quantization", "double_quant"), _AGREEMENT_CASES,+ ids=["moe-fused-nf4", "moe-per_expert-nf4", "moe-fused-nf4-single", "moe-fused-plain",+ "moe-per_expert-plain", "dense-nf4", "dense-plain"],+)+def test_the_early_charge_is_what_the_check_after_sharding_charges(+ tmp_path, monkeypatch, arch, layout, quantization, double_quant+):+ if quantization == "4bit":+ pytest.importorskip("bitsandbytes")+ moe_base = arch == "deepseek_v3"+ weights = _random_checkpoint(+ tmp_path / "weights", _moe_tensors() if moe_base else _dense_tensors(),+ model_type=arch, num_hidden_layers=N_LAYERS if moe_base else 1,+ )+ seen = _passed(+ _drive(+ tmp_path, monkeypatch, weights=weights, arch=arch,+ model_cfg=_deepseek_cfg() if moe_base else _llama_cfg(), layout=layout,+ quantization=quantization, double_quant=double_quant,+ suffixes=SUFFIXES if moe_base else DENSE_SUFFIXES,+ )+ )+ (early,) = seen["early"]+ (shard_kwargs,) = seen["shards"]+ monkeypatch.undo() # the harness's stubs off: shard and measure for real+ late = _late_charge(weights, tmp_path / "cache", shard_kwargs)+ assert early["approximate"] is False+ assert early["ram_bytes"] == late++[email protected]("quantization", ["none", "4bit"])+def test_an_fp8_sources_early_charge_is_what_the_check_after_sharding_charges(+ tmp_path, monkeypatch, quantization+):+ if quantization == "4bit":+ pytest.importorskip("bitsandbytes")+ fp8, _ref, quantization_config = _fp8_pair(tmp_path)+ seen = _passed(+ _drive(+ tmp_path, monkeypatch, weights=fp8, model_cfg=_fp8_cfg(quantization_config),+ quantization=quantization, suffixes=_FP8_SUFFIXES,+ )+ )+ (early,) = seen["early"]+ (shard_kwargs,) = seen["shards"]+ monkeypatch.undo()+ assert early["ram_bytes"] == _late_charge(fp8, tmp_path / "cache", shard_kwargs)+++def _refused(check):+ try:+ check()+ except ValueError:+ return True+ return False+++ ("ram", "free", "total", "refused"),+ [+ (6_999, 10_000, None, False),+ (7_000, 10_000, None, True), # 70% of free RAM reached: strict, like the late check+ (5_499, 10**9, 10_000, False),+ (5_500, 10**9, 10_000, True), # 55% of physical RAM reached+ (10**12, 10**9, None, True), # psutil without a physical total: free RAM alone+ ],+ ids=["under-free", "at-free", "under-physical", "at-physical", "no-total"],+)+def test_the_early_rule_is_the_late_rule(ram, free, total, refused):+ """The two decide alike on the same bytes: one budget, so the early check is never the+ stricter or the looser of the two."""+ from soup_cli.trainer.stream_setup import (+ _validate_early_ram_fit,+ _validate_qwen4_ngram_ram_fit,+ )++ early = _refused(+ lambda: _validate_early_ram_fit(+ base=_BASE, source_bytes=0, ram_bytes=ram, approximate=False, quantised=True,+ free_ram=free, total_ram=total,+ )+ )+ late = _refused(+ lambda: _validate_qwen4_ngram_ram_fit(+ stream_source="ram", ngram_source="disk", required_ram=ram, free_ram=free,+ resident_ram=0, total_ram=total,+ )+ )+ assert early is late is refused+++# --------------------------------------------------------------------------+# 5. headers that cannot be read or listed: the old rate, labelled approximately+# --------------------------------------------------------------------------+class TestTheFallback:+ @pytest.mark.parametrize("spelling", sorted(_MALFORMED), ids=sorted(_MALFORMED))+ def test_unreadable_headers_fall_back_to_the_flat_rate_and_say_approximately(+ self, tmp_path, monkeypatch, spelling+ ):+ weights = tmp_path / "weights"+ _write_raw(weights / "model.safetensors", _MALFORMED[spelling])+ _with_config(weights, "deepseek_v3", N_LAYERS)+ seen = _drive(tmp_path, monkeypatch, weights=weights, free_ram=1)+ text = _text(seen)+ assert "approximately" in text+ assert "once quantised to NF4" in text+ assert "safetensors headers could not be listed or read" in text+ assert "Refusing before sharding" in text+ assert seen["shards"] == []+ assert seen["reads"] == 1 # the disk pre-flight's; the early check did not retry+ # the harness reports 1,024 bytes on disk: the flat rate of that is the charge+ assert [call["ram_bytes"] for call in seen["early"]] == [_flat(1_024)]+ assert seen["early"][0]["approximate"] is True++ def test_a_source_that_cannot_be_listed_falls_back(self, tmp_path, monkeypatch):+ """A symlinked snapshot without its revision: the copy step refuses it later."""+ weights = _moe_dir(tmp_path)+ seen = _passed(+ _drive(+ tmp_path, monkeypatch, weights=weights,+ plan_overrides={"needs_materialization": True, "source_revision": None},+ )+ )+ assert seen["early"][0]["approximate"] is True+ assert seen["early"][0]["ram_bytes"] == _flat(1_024)++ def test_an_unquantised_fallback_says_approximately_in_ram(self, tmp_path, monkeypatch):+ weights = tmp_path / "weights"+ _write_raw(weights / "model.safetensors", _MALFORMED["not-json"])+ _with_config(weights, "deepseek_v3", N_LAYERS)+ seen = _drive(tmp_path, monkeypatch, weights=weights, quantization="none", free_ram=1)+ text = _text(seen)+ assert "approximately" in text and "GB in RAM" in text+ assert "once quantised to NF4" not in text++ def test_a_fallback_that_fits_passes(self, tmp_path, monkeypatch):+ weights = tmp_path / "weights"+ _write_raw(weights / "model.safetensors", _MALFORMED["not-json"])+ _with_config(weights, "deepseek_v3", N_LAYERS)+ seen = _passed(_drive(tmp_path, monkeypatch, weights=weights))+ assert seen["early"][0]["approximate"] is True+ assert len(seen["shards"]) == 1+++# --------------------------------------------------------------------------+# 6. dense bases+# --------------------------------------------------------------------------+class TestADenseBase:+ def test_an_nf4_dense_base_is_charged_its_unquantised_embeddings_and_norms(+ self, tmp_path, monkeypatch+ ):+ """Embeddings, the head and the norms stay at the stream dtype, which the flat NF4+ rate charged at 4 bits: refused early once the real figure is over the headroom."""+ weights = _dense_dir(tmp_path)+ need = _estimate(+ weights, arch="llama", suffixes=DENSE_SUFFIXES, num_hidden_layers=None+ ).ram_tier_bytes+ flat = _flat(_source_bytes(weights))+ assert flat < need+ seen = _drive(+ tmp_path, monkeypatch, weights=weights, arch="llama", model_cfg=_llama_cfg(),+ suffixes=DENSE_SUFFIXES, free_ram=_free_for_budget((flat + need) // 2),+ )+ text = _text(seen)+ assert "sized from its safetensors headers" in text+ assert "Refusing before sharding" in text+ assert seen["shards"] == []+ assert [call["ram_bytes"] for call in seen["early"]] == [need]++ @pytest.mark.parametrize("quantization", ["4bit", "none"])+ def test_a_dense_base_that_fits_passes(self, tmp_path, monkeypatch, quantization):+ weights = _dense_dir(tmp_path)+ quant = "nf4" if quantization == "4bit" else "none"+ need = _estimate(+ weights, arch="llama", quant=quant, suffixes=DENSE_SUFFIXES, num_hidden_layers=None+ ).ram_tier_bytes+ seen = _passed(+ _drive(+ tmp_path, monkeypatch, weights=weights, arch="llama", model_cfg=_llama_cfg(),+ quantization=quantization, suffixes=DENSE_SUFFIXES,+ free_ram=math.ceil(need / 0.7) + 2,+ )+ )+ assert [call["ram_bytes"] for call in seen["early"]] == [need]+ assert len(seen["shards"]) == 1++ def test_a_dense_unquantised_base_is_charged_what_it_streams_at(+ self, tmp_path, monkeypatch+ ):+ """No NF4, so no code tables; every tensor at the stream dtype (float32 on CPU)."""+ weights = _dense_dir(tmp_path)+ estimate = _estimate(+ weights, arch="llama", quant="none", suffixes=(), num_hidden_layers=None+ )+ assert estimate.code_table_bytes == 0 and estimate.expert_file_bytes == 0+ seen = _passed(+ _drive(+ tmp_path, monkeypatch, weights=weights, arch="llama", model_cfg=_llama_cfg(),+ quantization="none", suffixes=DENSE_SUFFIXES,+ )+ )+ assert seen["early"][0]["ram_bytes"] == sum(estimate.layer_bytes) + estimate.other_bytes+++# --------------------------------------------------------------------------+# review round: psutil without figures, both ceilings, the printed figures, a bad checkpoint+# --------------------------------------------------------------------------+def _message(check):+ with pytest.raises(ValueError) as excinfo:+ check()+ return " ".join(str(excinfo.value).split())+++def _early(**overrides):+ from soup_cli.trainer.stream_setup import _validate_early_ram_fit++ kwargs = dict(+ base=_BASE, source_bytes=0, ram_bytes=0, approximate=False, quantised=True,+ free_ram=10**15, total_ram=None,+ )+ kwargs.update(overrides)+ return _validate_early_ram_fit(**kwargs)+++def _late(*, ram, free, total):+ from soup_cli.trainer.stream_setup import _validate_qwen4_ngram_ram_fit++ return _validate_qwen4_ngram_ram_fit(+ stream_source="ram", ngram_source="disk", required_ram=ram, free_ram=free,+ resident_ram=0, total_ram=total,+ )+++class TestWhenPsutilCannotReportRam:+ """After sharding, an unknown free RAM is replaced by ten times the store (with a+ notice), so only the 55% physical ceiling can still refuse, and only when the total is+ known. The early check does the same: no free-RAM rule, the physical one if it can."""++ def test_no_figures_at_all_proceed_to_sharding_with_the_notice(self, tmp_path, monkeypatch):+ import io++ from rich.console import Console++ import soup_cli.trainer.stream_setup as stream_setup++ buffer = io.StringIO()+ monkeypatch.setattr(+ stream_setup, "console", Console(file=buffer, width=400, color_system=None)+ )+ seen = _passed(+ _drive(+ tmp_path, monkeypatch, weights=_moe_dir(tmp_path), free_ram=None,+ total_ram=None,+ )+ )+ assert len(seen["shards"]) == 1+ text = " ".join(buffer.getvalue().split())+ assert "psutil unavailable" in text and "cannot size the RAM tier" in text+ assert text.count("psutil unavailable") == 1 # said once, by the check after sharding++ def test_unknown_free_ram_still_meets_the_physical_ceiling(self, tmp_path, monkeypatch):+ weights = _moe_dir(tmp_path)+ need = _estimate(weights).ram_tier_bytes+ seen = _drive(tmp_path, monkeypatch, weights=weights, free_ram=None, total_ram=need)+ text = _text(seen)+ assert "more than 55% of physical RAM" in text+ assert "Refusing before sharding" in text+ assert seen["shards"] == []++ def test_unknown_free_ram_under_the_physical_ceiling_passes(self, tmp_path, monkeypatch):+ weights = _moe_dir(tmp_path)+ need = _estimate(weights).ram_tier_bytes+ seen = _passed(+ _drive(tmp_path, monkeypatch, weights=weights, free_ram=None, total_ram=need * 2)+ )+ assert [call["ram_bytes"] for call in seen["early"]] == [need]+ assert len(seen["shards"]) == 1++ @pytest.mark.parametrize(("free", "total"), [(None, None), (None, 10**15), (10**15, None)])+ def test_an_unknown_figure_never_refuses_on_its_own(self, free, total):+ _early(ram_bytes=10**12, free_ram=free, total_ram=total)+++def test_over_both_ceilings_the_physical_one_is_named_as_after_sharding():+ """The late check tests 55% of physical RAM first; the early refusal names it too."""+ early = _message(lambda: _early(ram_bytes=8_000, free_ram=10_000, total_ram=10_000))+ late = _message(lambda: _late(ram=8_000, free=10_000, total=10_000))+ for text in (early, late):+ assert "55% of physical RAM (0.0 GB)" in text, text+ assert "of RAM is free" not in text, text+++class TestTheRefusalPrintsTheFiguresItCompared:+ def test_the_header_estimate(self):+ text = _message(+ lambda: _early(+ base="org/model", source_bytes=16_000_000_000, ram_bytes=30_600_000_000,+ free_ram=20_000_000_000,+ )+ )+ assert (+ "training.stream_source='ram' but org/model needs 30.6 GB of RAM once sharded"+ in text+ )+ assert "(sized from its safetensors headers; 16.0 GB on disk)" in text+ assert "and only 20.0 GB of RAM is free" in text++ def test_the_fallback(self):+ text = _message(+ lambda: _early(+ base="org/model", source_bytes=16_000_000_000, ram_bytes=4_100_000_000,+ approximate=True, free_ram=5_000_000_000,+ )+ )+ assert (+ "org/model is 16.0 GB on disk, approximately 4.1 GB once quantised to NF4" in text+ )+ assert "and only 5.0 GB of RAM is free" in text++ def test_the_physical_ceiling(self):+ text = _message(+ lambda: _early(+ source_bytes=16_000_000_000, ram_bytes=30_600_000_000,+ total_ram=40_000_000_000,+ )+ )+ assert "needs 30.6 GB of RAM once sharded" in text+ assert "16.0 GB on disk" in text+ assert "more than 55% of physical RAM (40.0 GB)" in text++[email protected]("run_preflight", [True, False], ids=["after-preflight", "own-estimate"])+def test_a_checkpoint_the_sharder_refuses_is_refused_not_approximated(+ tmp_path, monkeypatch, run_preflight+):+ """Only an unreadable header falls back; a checkpoint the sharder would refuse is+ refused in its words, before any shard, whichever check sizes it first."""+ tensors = _moe_tensors()+ del tensors["model.layers.1.mlp.experts.2.up_proj.weight"]+ seen = _drive(+ tmp_path, monkeypatch, weights=_moe_dir(tmp_path, tensors), run_preflight=run_preflight+ )+ assert "incomplete expert projections" in _text(seen)+ assert seen["early"] == []+ assert seen["shards"] == []diff --git a/tests/test_v07202.py b/tests/test_v07202.pyindex 2a155e73..52c27620 100644--- a/tests/test_v07202.py+++ b/tests/test_v07202.py@@ -1512,7 +1512,13 @@ class TestNF4StoreEstimate:class TestPreflightUsesTheStreamedSize:"""The estimate exists to stop the pre-flight refusing an 8B run becauseits bf16 files are 16 GB on disk. Unit-testing the arithmetic alone would- not catch a regression that simply stops passing ``quant=`` through."""+ not catch a regression that simply stops passing ``quant=`` through.++ The early RAM check now charges the source headers' estimate+ (tests/test_stream_ram_preflight_estimate.py); this flat rate on the size on+ disk is its fallback for headers that cannot be read. So `_run` makes the+ estimator's header read fail (the sharder reads the tensors its own way), and+ the faked on-disk size drives the check as it did before."""def _run(self, tmp_path, monkeypatch, *, quantization, free_ram, on_disk,@@ -1534,6 +1540,13 @@ class TestPreflightUsesTheStreamedSize:monkeypatch.setattr("soup_cli.utils.layer_shard.source_weight_bytes", lambda *_a, **_k: on_disk)++ def _unreadable(_paths):+ from soup_cli.utils.layer_shard import SourceHeaderError++ raise SourceHeaderError("header unreadable (test)")++ monkeypatch.setattr("soup_cli.utils.layer_shard._read_source_tensors", _unreadable)# Pinned, not probed: the real media type differs between the dev box# (NVMe) and a CI runner (often "unknown"), and an environment-dependent# tier decision would make these assertions flaky rather than wrong.