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
perf(stream): opt-in training.stream_nf4_scale_cache keeps expanded NF4 scales resident (#1892)
Alpamys Makazhan9801e4f59d9e
diff --git a/benchmarks/harness/issue361_nf4_throughput.py b/benchmarks/harness/issue361_nf4_throughput.pyindex ec3ef011..bb29bb40 100644--- a/benchmarks/harness/issue361_nf4_throughput.py+++ b/benchmarks/harness/issue361_nf4_throughput.py@@ -153,6 +153,18 @@ def parse_args() -> argparse.Namespace:action="store_true",help="skip the same-session GEMM ceiling (not the published protocol)",)+ parser.add_argument(+ "--nf4-scale-cache",+ action="store_true",+ help="build with training.stream_nf4_scale_cache on (#1892); not the published protocol",+ )+ parser.add_argument(+ "--train-threads",+ type=int,+ default=None,+ help="torch.set_num_threads(N) for the warm-up and measured steps only; "+ "a measurement knob, not a Soup setting",+ )parser.add_argument("--json",dest="json_path",@@ -416,6 +428,7 @@ def main() -> int: # noqa: C901 — a protocol is a sequence, not a branch treetier="ram",quant=args.quant,weights_dir=weights_dir,+ nf4_scale_cache=args.nf4_scale_cache,)build_secs = time.time() - t0assert runtime.source.pinned, "require_pin=True but the source is not pinned"@@ -437,6 +450,8 @@ def main() -> int: # noqa: C901 — a protocol is a sequence, not a branch treelabels = input_ids.clone()model.train()+ if args.train_threads is not None:+ torch.set_num_threads(args.train_threads)torch.cuda.synchronize()torch.cuda.reset_peak_memory_stats()@@ -544,6 +559,10 @@ def main() -> int: # noqa: C901 — a protocol is a sequence, not a branch tree"targets": args.targets,"pin_required": True,"store_gb_pinned": round(store_gb, 3),+ "nf4_scale_cache": args.nf4_scale_cache,+ "nf4_scale_cache_bytes": runtime.stats()["nf4_scale_cache_bytes"],+ "train_threads": args.train_threads,+ "step_times_s": [round(t, 4) for t in step_times],"param_split": {"decoder": split["decoder"],"embed": split["embed"],diff --git a/changelog.d/0.76.0/1892.added.md b/changelog.d/0.76.0/1892.added.mdnew file mode 100644index 00000000..4eaf2601--- /dev/null+++ b/changelog.d/0.76.0/1892.added.md@@ -0,0 +1 @@+- Layer streaming: new opt-in `training.stream_nf4_scale_cache` keeps each streamed double-quantised NF4 weight's expanded fp32 block scales on the compute device after its first use, so bitsandbytes' dequantise + linear path stops re-expanding them on every forward and checkpoint recompute (about 0.38 ms per Mistral-7B layer visit in an isolated RTX 5070 measurement). Results are bit-identical; the fused 4-bit GEMM path is unchanged. Costs 4 bytes per 64-element block of VRAM for the run (416 MiB on Mistral-7B), charged by the pre-flight. Off by default; needs `quantization: 4bit` with double quantization (#1892).diff --git a/docs/config-reference.md b/docs/config-reference.mdindex 8ea9b186..60270e45 100644--- a/docs/config-reference.md+++ b/docs/config-reference.md@@ -314,6 +314,7 @@ Sections:| `training.stream_pin` | `bool \| null` | `null` | | Force the page-locked (pinned) host memory on or off — the RAM tier's base store, or the disk tier's async-reader host staging (#971). None (the default) lets the box decide: it attempts to page-lock that memory and falls back to pageable — announcing the cost — when the host cannot page-lock it. 'false' forces the pageable store, the only known escape hatch when a pinning path is suspect (it was the sole mitigation while #331 was live). 'true' forces pinning and REFUSES the run rather than silently degrading if the box cannot page-lock it: on the RAM tier naming the store size, on the disk tier naming training.stream_read_ahead as the depth that decides how much staging gets locked — page-locking is worth up to 6.56x measured throughput, so a silent fallback spends the whole margin the feature exists to provide. Non-CUDA targets (CPU or MPS) are the one case pinning stays INAPPLICABLE: 'true' is announced there and the run proceeds with a pageable CPU source, so the key stays committable to a config shared between CUDA and non-CUDA boxes. || `training.stream_vram_override` | `int \| null` | `null` | `>= 0` | Bytes to assume free instead of measuring torch.cuda.mem_get_info(). mem_get_info() is a device-level driver query, so it cannot see a per-process cap (set_per_process_memory_fraction, a MIG slice, a card another process is also using), so on that hardware the pre-flight sees the whole device's free VRAM regardless of what this process can actually use. Set this to replace the measured figure in either direction: raise it to let a known-safe over-prediction through, or lower it to make the pre-flight enforce a cap the driver itself cannot report. || `training.stream_vram_probe` | `bool` | `false` | | Decide the layer-streaming VRAM pre-flight on a MEASUREMENT instead of the fitted formula. One real forward+backward runs at the configured shape after the streamed model is built, and its peak decides whether the run proceeds; the prediction is printed beside it so a divergence is visible. The formula under-predicts past seq 4352 (measured 0.934x the real peak at seq 5120 and 0.787x at 6144), which is the direction that does not announce itself — an OOM on Linux, a silent spill to host memory on Windows. Against the probe the same formula reads 0.992x at seq 4096 and 0.830x at 5120, because the probe itself runs 12.5-14.3% above the real training step — the direction that makes it safe as a gate. Off by default: it costs one step (1-5 s measured) and it can refuse a run the formula accepts. task='sft' only: the probe runs a plain causal-LM forward+backward, which IS the SFT step but not a preference loss. At the one preference shape measured it reads +13.5% high (probe 6.021 GB against a real DPO step's 5.304 GB) — the same safe direction it shows for SFT — but one shape is not a validation, so the restriction stands until it is measured across shapes. |+| `training.stream_nf4_scale_cache` | `bool` | `false` | | Keep each streamed NF4 weight's expanded fp32 block scales on the compute device after its first use. A double-quantised weight stores its scales as 8-bit codes plus a nested scale and offset, and bitsandbytes' dequantise + linear path expands them on every visit (forward and checkpoint recompute): two extra kernels and a temporary per projection. The base is frozen, so the expansion is done once per (layer, weight) and reused; results are bit-identical. Costs 4 bytes per 64-element block of VRAM for the whole run (416 MiB on Mistral-7B), which the pre-flight charges up front. bitsandbytes' fused 4-bit GEMM path expands the scales inside its kernel and is left unchanged. Needs quantization='4bit' with double quantization (the default). Off by default. || `training.stream_disk_kind` | `str \| null` | `null` | one of `"nvme"`, `"ssd"`, `"hdd"` | Override the auto-detected disk media type for the streaming disk overflow tier. Detection classifies a device by a measured sequential read when the kernel's rotational flag is unreliable — virtio and other paravirtual disks report spinning with no media hint, so a fast cloud disk is otherwise refused (#365). Set this for the case where even that is wrong: 'nvme' forces the disk tier on, 'ssd'/'hdd' force it off. The resolved value is printed beside what was detected. || `training.packing` | `bool` | `false` | | Pack multiple short samples into one sequence for faster training || `training.multipack` | `bool` | `false` | | Use FFD bin-packing sampler to maximise tokens-per-batch on uneven-length data. Mutually exclusive with packing. Only supported for sft / pretrain tasks (transformers backend). (v0.37.0). |diff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.mdindex 1b264d23..d2cf60cd 100644--- a/docs/performance-and-quantization.md+++ b/docs/performance-and-quantization.md@@ -449,6 +449,7 @@ training:# stream_pin: false # Force the pinned RAM store off (escape hatch) or on; unset = automatic. See below# stream_vram_override: 4_000_000_000 # Bytes to assume free (v0.73.x); see below# stream_vram_probe: true # Decide the fit by MEASURING one step (sft only); see below+ # stream_nf4_scale_cache: true # Keep expanded NF4 scales resident (4bit + double quant); see below# stream_disk_kind: nvme # Override auto disk-kind detection: nvme/ssd/hdd; see below```@@ -468,6 +469,19 @@ checkpointed step. The fused arm reduces saved-weight VRAM but its backward stildequantises because bitsandbytes exposes no transposed 4-bit GEMM; it is therefore abounded memory/time trade, not a claim that #842's full kernel ceiling is complete.+**`stream_nf4_scale_cache` (opt-in).** On the dequantise + `F.linear` path, a+double-quantised NF4 weight expands its 8-bit block scales to fp32 on every visit,+forward and recompute alike: two small kernels and a temporary per projection.+The base is frozen, so with `training.stream_nf4_scale_cache: true` each+(layer, weight) is expanded once and kept on the compute device; results are+bit-identical. It costs 4 bytes per 64-element block for the whole run (416 MiB on+Mistral-7B, one eighth of the packed 4-bit weights), which the pre-flight charges+up front and prints as a `scale cache` line. The fused GEMM arm expands the scales+inside its kernel and is unchanged, so on a shape bitsandbytes sends there the+cache stays empty. Needs `quantization: 4bit` with double quantization (the+default). It trades VRAM for time, and the time saved has not been measured+across machines yet, so it is off by default.+**Qwen3.8-Flash-Next / Qwen4-Exp PLE.** The frozen PLE N-gram table is not adecoder-layer weight for storage purposes: putting it in the PLE layer's shardwould make the shared layer buffer as large as the whole table. Soup keeps the@@ -702,7 +716,8 @@ prints this advice when it sees you accumulating.- `moe_expert_quant` → expert quantization runs only in the resident model-construction path and would otherwise be silently ignored- `unfrozen_parameters`, `lisa_enabled`, `packing`, `multipack`, `use_fsdp2_compile`, `train_router_only`, `expand_layers` → each independently rewrites or re-freezes the same layers- `use_liger` / `use_flash_attn` → **not reached at all** under streaming (#1692). Both are read by the *resident* setup: Liger patches the MLP forward there, and flash-attn is handed to `from_pretrained` as `attn_implementation`. A streamed model is built by `from_config` with no attention argument and no Liger patch, and `_liger_applied` is never set, so `use_liger_kernel` misses `TrainingArguments` too. These are the switches you reach for when a streamed run will not fit, so they are refused rather than dropped; each is offered again once it is wired and shown to engage on a streamed model. On every task outside `{sft, tts}` they are already refused at config load (#806)-- `stream_source` / `stream_ngram_source` / `stream_buffers` / `stream_read_ahead` / `stream_vram_override` / `stream_vram_probe` / `stream_disk_kind` / `stream_pin` set while `stream_layers: false` → a footgun, refused+- `stream_source` / `stream_ngram_source` / `stream_buffers` / `stream_read_ahead` / `stream_vram_override` / `stream_vram_probe` / `stream_nf4_scale_cache` / `stream_disk_kind` / `stream_pin` set while `stream_layers: false` → a footgun, refused+- `stream_nf4_scale_cache` without `quantization: 4bit` and double quantization → refused: there are no nested NF4 scales to cache- a non-default `stream_read_ahead` beside `stream_source: ram` → refused. The read-ahead reader belongs to the NVMe disk tier and `ram` never falls back to it, so the setting would validate, be documented, and reach nothing. The default is accepted, because a default is not a decision- a disk-tier run whose host staging (`stream_read_ahead` layers, plus one slot each for the embedding and an untied `lm_head`) plus the resident extras will not fit the free-RAM headroom → refused by name, naming the depth to lower. Refused rather than clamped: a depth you set is a decision, and silently lowering it would hand back a slower run than the one you configured- more than 8 distinct layer shapes in one shard index → refused. Staging is allocated per shape and a shape with one member takes a full slot at any depth, so an index whose every layer differed would hold most of the model in staging at once — page-locked when the box allows it and `stream_pin` is not false, a loud pageable fallback otherwise, and a refusal only under `stream_pin: true` on a CUDA target — which is what the disk tier exists to avoid. A real model has one to threediff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.pyindex 995e5a99..a5662be0 100644--- a/src/soup_cli/config/schema.py+++ b/src/soup_cli/config/schema.py@@ -3656,6 +3656,23 @@ class TrainingConfig(BaseModel):"until it is measured across shapes."),)+ stream_nf4_scale_cache: bool = Field(+ default=False,+ description=(+ "Keep each streamed NF4 weight's expanded fp32 block scales on the "+ "compute device after its first use. A double-quantised weight stores "+ "its scales as 8-bit codes plus a nested scale and offset, and "+ "bitsandbytes' dequantise + linear path expands them on every visit "+ "(forward and checkpoint recompute): two extra kernels and a "+ "temporary per projection. The base is frozen, so the expansion is "+ "done once per (layer, weight) and reused; results are bit-identical. "+ "Costs 4 bytes per 64-element block of VRAM for the whole run (416 "+ "MiB on Mistral-7B), which the pre-flight charges up front. "+ "bitsandbytes' fused 4-bit GEMM path expands the scales inside its "+ "kernel and is left unchanged. Needs quantization='4bit' with "+ "double quantization (the default). Off by default."+ ),+ )stream_disk_kind: Optional[Literal["nvme", "ssd", "hdd"]] = Field(default=None,description=(@@ -6561,6 +6578,7 @@ class SoupConfig(BaseModel):or tcfg.stream_read_ahead != DEFAULT_STREAM_READ_AHEADor tcfg.stream_vram_override is not Noneor tcfg.stream_vram_probe+ or tcfg.stream_nf4_scale_cacheor tcfg.stream_disk_kind is not Noneor tcfg.stream_pin is not None):@@ -6568,11 +6586,24 @@ class SoupConfig(BaseModel):"training.stream_source / training.stream_ngram_source / ""training.stream_buffers / training.stream_read_ahead / ""training.stream_vram_override / training.stream_vram_probe "- "/ training.stream_disk_kind / training.stream_pin set but "- "stream_layers is false; set stream_layers=true to stream the "- "base layer-by-layer."+ "/ training.stream_nf4_scale_cache / training.stream_disk_kind "+ "/ training.stream_pin set but stream_layers is false; set "+ "stream_layers=true to stream the base layer-by-layer.")return self+ if tcfg.stream_nf4_scale_cache and (+ tcfg.quantization != "4bit" or not tcfg.double_quant_on+ ):+ # The cache holds the EXPANDED nested scales. Without 4-bit there is+ # no NF4 weight, and without double quantisation the stored scales+ # are already fp32, so the setting would reach nothing.+ raise ValueError(+ "training.stream_nf4_scale_cache needs quantization='4bit' with "+ "double quantization (training.bnb_4bit_use_double_quant unset or "+ f"true); got quantization={tcfg.quantization!r}, "+ f"bnb_4bit_use_double_quant={tcfg.bnb_4bit_use_double_quant!r}. "+ "Without them there are no nested NF4 scales to cache."+ )# #971 — `stream_source: 'ram'` INSISTS on the RAM tier: 'ram' insists,# 'disk' forces, 'auto' falls back (trainer/stream_setup.py). The# read-ahead reader belongs to the NVMe disk tier, so a non-defaultdiff --git a/src/soup_cli/trainer/stream_setup.py b/src/soup_cli/trainer/stream_setup.pyindex 6001f508..0d72f198 100644--- a/src/soup_cli/trainer/stream_setup.py+++ b/src/soup_cli/trainer/stream_setup.py@@ -1211,6 +1211,7 @@ class StreamingSetupMixin:weights_dir=weights_dir,ngram_source=ngram_source,refill_before_backward=self._STREAM_REFILL_BEFORE_BACKWARD,+ nf4_scale_cache=bool(getattr(tcfg, "stream_nf4_scale_cache", False)),)self.model = modelself._stream_runtime = runtime@@ -1332,10 +1333,19 @@ class StreamingSetupMixin:estimate_logits_bytes,estimate_stream_peak_vram,forecast_stream_throughput,+ nf4_scale_cache_bytes,resolve_available_vram_bytes,)from soup_cli.utils.layer_stream_runtime import measure_gemm_tflops+ # Charged whole even though it fills lazily: the cache is complete after+ # the first step and stays resident for the run.+ scale_cache_bytes = (+ nf4_scale_cache_bytes(getattr(index, "quant_specs", None) or {}, index.n_layers)+ if getattr(tcfg, "stream_nf4_scale_cache", False)+ else 0+ )+shape_cfg = self._stream_shape_config(model_config)vocab = int(getattr(shape_cfg, "vocab_size", 0) or 0)hidden = int(getattr(shape_cfg, "hidden_size", 0) or 0)@@ -1378,6 +1388,7 @@ class StreamingSetupMixin:batch_size=rows,logits_bytes_per_element=calibrated,large_layer_bytes=large_layer_bytes,+ persistent_bytes=scale_cache_bytes,)logits = estimate_logits_bytes(vocab_size=vocab, seq_len=seq_len, batch_size=rows, bytes_per_element=calibrated@@ -1389,6 +1400,11 @@ class StreamingSetupMixin:f" peak VRAM ~{predicted / 1e9:.2f} GB at batch {batch} x seq "f"{seq_len}{paired} (logits {logits / 1e9:.2f} GB)"]+ if scale_cache_bytes:+ lines.append(+ f" scale cache {scale_cache_bytes / 1e9:.2f} GB resident "+ "(training.stream_nf4_scale_cache), included above"+ )if calibrated > LOGITS_BYTES_PER_ELEMENT:lines.append(f" logits calibrated {calibrated:.3f} B/element on this stack, "diff --git a/src/soup_cli/utils/layer_stream.py b/src/soup_cli/utils/layer_stream.pyindex 3bfbb0ea..84efee7f 100644--- a/src/soup_cli/utils/layer_stream.py+++ b/src/soup_cli/utils/layer_stream.py@@ -19,7 +19,7 @@ stay resident.import mathfrom dataclasses import dataclass-from typing import Any, Callable, Dict, Optional, Sequence, Tuple, Union+from typing import Any, Callable, Dict, Mapping, Optional, Sequence, Tuple, Unionfrom rich.panel import Panel@@ -1199,6 +1199,22 @@ def estimate_optimizer_bytes(return adapter_params * bytes_per_param+def nf4_scale_cache_bytes(quant_specs: Mapping[str, Any], n_layers: int) -> int:+ """Device bytes ``training.stream_nf4_scale_cache`` holds once every layer ran.++ One fp32 scale per block of every double-quantised decoder weight, in every+ layer. ``quant_specs`` is keyed by the layer-relative name shared across+ layers, so a model whose layers do not all carry a weight is over-counted,+ which is the safe direction for a number that can refuse a run.+ """+ per_layer = sum(+ 4 * -(-math.prod(spec.shape) // spec.blocksize)+ for spec in quant_specs.values()+ if spec.nested+ )+ return per_layer * n_layers++def estimate_stream_peak_vram(*,layer_bytes: int,@@ -1214,6 +1230,7 @@ def estimate_stream_peak_vram(dtype: str = "bfloat16",logits_bytes_per_element: Optional[float] = None,large_layer_bytes: int = 0,+ persistent_bytes: int = 0,) -> int:"""Predicted ``torch.cuda.max_memory_allocated()`` for a streaming step.@@ -1239,10 +1256,14 @@ def estimate_stream_peak_vram(``logits_bytes_per_element`` forwards a stack measurement from:func:`calibrated_logits_bytes_per_element`; it is floored at the shippedconstant, so passing it can only raise the prediction.++ ``persistent_bytes`` is device memory the runtime holds for the whole run on+ top of the pool, such as :func:`nf4_scale_cache_bytes`."""return (layer_bytes * buffers+ large_layer_bytes+ + persistent_bytes+ extras_bytes+ estimate_optimizer_bytes(adapter_params)+ STREAM_FIXED_SLACK_BYTESdiff --git a/src/soup_cli/utils/layer_stream_runtime.py b/src/soup_cli/utils/layer_stream_runtime.pyindex bbf98a86..1079cc93 100644--- a/src/soup_cli/utils/layer_stream_runtime.py+++ b/src/soup_cli/utils/layer_stream_runtime.py@@ -175,6 +175,69 @@ def rebuild_params4bit(key: str, buffers: Mapping[str, Any], spec: Any, codes: M)+class NF4ScaleCache:+ """Expanded fp32 block scales of streamed nested-NF4 weights (opt-in).++ bitsandbytes' dequantise + linear path expands a double-quantised weight's+ scales on every call: ``dequantize_blockwise`` of the 8-bit codes, then+ ``+= offset``. The base is frozen, so the result for a (layer, weight) never+ changes; this keeps it on the compute device after the first visit and hands+ later visits a non-nested ``QuantState`` over it. The expansion below is the+ one in ``bitsandbytes.functional.dequantize_4bit``, so the 4-bit dequantise+ that follows reads identical scales.++ Keyed by layer index and shard key, never by pool slot: several layers take+ turns in one slot. Only the dense path may use it; the fused custom GEMM+ expands the nested scales inside its kernel.+ """++ def __init__(self) -> None:+ self._states: Dict[Tuple[int, str], Any] = {}++ def __len__(self) -> int:+ return len(self._states)++ @property+ def nbytes(self) -> int:+ return sum(+ state.absmax.numel() * state.absmax.element_size() for state in self._states.values()+ )++ def dense_state(self, key: Tuple[int, str], quant_state: Any) -> Any:+ state = self._states.get(key)+ if state is None:+ state = self._expand(quant_state)+ self._states[key] = state+ elif state.shape != quant_state.shape or state.blocksize != quant_state.blocksize:+ raise RuntimeError(+ f"NF4 scale cache entry {key} was built for shape {tuple(state.shape)} "+ f"/ block {state.blocksize}, but the weight now has shape "+ f"{tuple(quant_state.shape)} / block {quant_state.blocksize}"+ )+ return state++ @staticmethod+ def _expand(quant_state: Any) -> Any:+ import torch+ from bitsandbytes import functional as bnb_functional++ absmax = bnb_functional.dequantize_blockwise(quant_state.absmax, quant_state.state2)+ absmax += quant_state.offset+ if absmax.dtype != torch.float32:+ absmax = absmax.float()+ return bnb_functional.QuantState(+ absmax=absmax,+ shape=quant_state.shape,+ code=quant_state.code,+ blocksize=quant_state.blocksize,+ quant_type=quant_state.quant_type,+ dtype=quant_state.dtype,+ )++ def clear(self) -> None:+ self._states.clear()++_CHECKPOINT_VISIBLE_NF4_FUNCTION = None@@ -440,7 +503,11 @@ def install_dequant_forward(module: Any) -> int:).to(inp_dtype)# Compatibility path: dequantise inside the checkpointed region and let- # F.linear save the dense weight properly.+ # F.linear save the dense weight properly. The fused arm above keeps the+ # nested state: its kernel expands the scales itself.+ scale_cache = getattr(self.weight, "_soup_scale_cache", None)+ if scale_cache is not None:+ quant_state = scale_cache.dense_state(self.weight._soup_scale_cache_key, quant_state)weight = dequantize_4bit(self.weight, quant_state).to(x.dtype)return functional.linear(x, weight, bias).to(inp_dtype)@@ -1415,6 +1482,7 @@ def _build_streamed_layer_class():use_checkpoint=True,quant_specs=None,codes=None,+ scale_cache=None,):super().__init__()self.inner = inner@@ -1425,6 +1493,9 @@ def _build_streamed_layer_class():self.use_checkpoint = bool(use_checkpoint)self.quant_specs = dict(quant_specs or {})self.codes = dict(codes or {})+ # training.stream_nf4_scale_cache — an NF4ScaleCache owned by the+ # runtime, or None.+ self.scale_cache = scale_cache# #841 — each wrapper returns to the same pool slot on every visit.# Cache the tensor/Params4bit substitution views for that slot rather# than reconstructing Python wrappers and QuantState objects on every@@ -1682,6 +1753,9 @@ def _build_streamed_layer_class():else:weight = rebuild_params4bit(ckpt, buffers, spec, self.codes)weight._soup_stream_owner_check = self._assert_nf4_slot_owner+ if self.scale_cache is not None:+ weight._soup_scale_cache = self.scale_cache+ weight._soup_scale_cache_key = (self.idx, ckpt)weights[meta] = weightself._cached_substitution_buffers = buffersself._cached_substitution_weights = weights@@ -2794,6 +2868,8 @@ class StreamRuntime:total_params: int = 0#: Read-only Qwen4 PLE mappings, if the N-gram table is SSD-backed.external_sources: Tuple[Any, ...] = ()+ #: training.stream_nf4_scale_cache — the layers' shared NF4ScaleCache, or None.+ scale_cache: Any = Nonedef close(self) -> None:"""Release the weight source and detach the prefetch hook.@@ -2815,6 +2891,10 @@ class StreamRuntime:if self.hook is not None:self.hook.remove()self.hook = None+ if self.scale_cache is not None:+ # The layers' substituted weights still reference the cache object;+ # emptying it is what returns the device memory.+ self.scale_cache.clear()def stats(self) -> Dict[str, Any]:return {@@ -2839,6 +2919,7 @@ class StreamRuntime:"large_loads": getattr(self.large_pool, "loads", 0),"device": self.device,"total_params": self.total_params,+ "nf4_scale_cache_bytes": getattr(self.scale_cache, "nbytes", 0),}@@ -2886,6 +2967,7 @@ def install_streaming(read_ahead: int = DEFAULT_STREAM_READ_AHEAD,refill_before_backward: bool = False,read_ahead_decision: Any = None,+ nf4_scale_cache: bool = False,) -> StreamRuntime:"""Wrap every decoder layer and wire the buffer pool + prefetch scheduler.@@ -2893,6 +2975,9 @@ def install_streaming(step's backward; an untied output head then hands autograd a private copyof its weight (#1049).+ ``nf4_scale_cache`` gives the layers one shared :class:`NF4ScaleCache`+ (``training.stream_nf4_scale_cache``); it needs double-quantised NF4 shards.+``read_ahead_decision`` (a ``stripe_roots.ReadAheadDecision``, R4) says how``read_ahead`` came about, so the page-lock messages advise a depth that isnot raised straight back up on a striped cache.@@ -2936,6 +3021,14 @@ def install_streaming(f"shard index is inconsistent: quant={getattr(index, 'quant', None)!r} "f"but {len(quant_specs)} quant_specs — reshard the checkpoint")+ scale_cache = None+ if nf4_scale_cache:+ if not any(spec.nested for spec in quant_specs.values()):+ raise ValueError(+ "nf4_scale_cache=True needs double-quantised NF4 shards, but this "+ "index has no nested NF4 weights; there are no scales to cache"+ )+ scale_cache = NF4ScaleCache()owner = decoder_owner(model)layers = owner.layers@@ -3058,6 +3151,7 @@ def install_streaming(layer_name_maps[idx],quant_specs=quant_specs,codes=codes,+ scale_cache=scale_cache,)if large_pool is not None:@@ -3137,6 +3231,7 @@ def install_streaming(hook=handle,total_params=int(getattr(index, "total_params", 0) or 0),tier=tier,+ scale_cache=scale_cache,)@@ -3504,6 +3599,7 @@ def build_streamed_model(ngram_source: str = "disk",refill_before_backward: bool = False,read_ahead_decision: Any = None,+ nf4_scale_cache: bool = False,) -> Tuple[Any, StreamRuntime]:"""Meta skeleton -> extras -> LoRA -> streaming. No resident base load.@@ -3556,6 +3652,7 @@ def build_streamed_model(read_ahead=read_ahead,refill_before_backward=refill_before_backward,read_ahead_decision=read_ahead_decision,+ nf4_scale_cache=nf4_scale_cache,)except BaseException:for external in external_sources:diff --git a/tests/fixtures/recipe_config_snapshots.json b/tests/fixtures/recipe_config_snapshots.jsonindex 0a4c10c5..5952be22 100644--- a/tests/fixtures/recipe_config_snapshots.json+++ b/tests/fixtures/recipe_config_snapshots.json@@ -267,6 +267,7 @@"training.stream_buffers": 2,"training.stream_disk_kind": null,"training.stream_layers": false,+ "training.stream_nf4_scale_cache": false,"training.stream_ngram_source": "auto","training.stream_pin": null,"training.stream_read_ahead": 2,diff --git a/tests/test_stream_nf4_scale_cache.py b/tests/test_stream_nf4_scale_cache.pynew file mode 100644index 00000000..bb084603--- /dev/null+++ b/tests/test_stream_nf4_scale_cache.py@@ -0,0 +1,556 @@+"""Layer streaming: ``training.stream_nf4_scale_cache`` keeps expanded NF4 scales resident.++A double-quantised NF4 weight stores its per-block absmax as uint8 codes plus a+nested absmax and offset. On bitsandbytes' dequantise + linear path every visit+first expands those to fp32 (``dequantize_blockwise`` + ``+= offset``) and only+then dequantises the 4-bit weight: two extra kernels and a temporary per projection,+on the forward and again on the checkpoint recompute. The base is frozen, so the+fp32 scales of a (layer, weight) never change. With the opt-in on, the streamed+layer expands them once and keeps them on the compute device, at a persistent+cost of 4 bytes per 64-element block (416 MiB for Mistral-7B) that the VRAM+pre-flight charges up front.++The fused custom-GEMM path is left alone: it dequantises the nested scales inside+its kernel, and feeding it pre-expanded scales changes the arithmetic.+"""++import pytest++from soup_cli.config.loader import load_config_from_string+++def _cfg(**training):+ body = "\n".join(f" {k}: {v}" for k, v in training.items())+ return (+ "base: HuggingFaceTB/SmolLM2-135M\n"+ "task: sft\n"+ "data:\n"+ " train: d.jsonl\n"+ " max_length: 512\n"+ "training:\n"+ " batch_size: 1\n"+ " lora:\n"+ " r: 8\n" + body + "\n"+ )+++class TestSchema:+ def test_defaults_off(self):+ cfg = load_config_from_string(_cfg(stream_layers="true", quantization="4bit"))+ assert cfg.training.stream_nf4_scale_cache is False++ def test_parses_with_streamed_nf4(self):+ cfg = load_config_from_string(+ _cfg(stream_layers="true", quantization="4bit", stream_nf4_scale_cache="true")+ )+ assert cfg.training.stream_nf4_scale_cache is True++ def test_refused_while_streaming_is_off(self):+ with pytest.raises(Exception) as exc:+ load_config_from_string(_cfg(stream_layers="false", stream_nf4_scale_cache="true"))+ assert "stream_nf4_scale_cache" in str(exc.value)+ assert "stream_layers" in str(exc.value)++ def test_refused_without_4bit(self):+ with pytest.raises(Exception) as exc:+ load_config_from_string(+ _cfg(stream_layers="true", quantization="none", stream_nf4_scale_cache="true")+ )+ message = str(exc.value)+ assert "stream_nf4_scale_cache" in message+ assert "quantization='4bit'" in message++ def test_refused_without_double_quant(self):+ with pytest.raises(Exception) as exc:+ load_config_from_string(+ _cfg(+ stream_layers="true",+ quantization="4bit",+ bnb_4bit_use_double_quant="false",+ stream_nf4_scale_cache="true",+ )+ )+ message = str(exc.value)+ assert "stream_nf4_scale_cache" in message+ assert "bnb_4bit_use_double_quant" in message+++def _spec(shape, nested=True, blocksize=64):+ from soup_cli.utils.layer_shard import NF4WeightSpec++ return NF4WeightSpec(+ shape=tuple(shape),+ dtype="bfloat16",+ blocksize=blocksize,+ quant_type="nf4",+ nested=nested,+ nested_blocksize=256,+ )+++class TestCacheBytes:+ def test_mistral_7b_is_416_mib(self):+ from soup_cli.utils.layer_stream import nf4_scale_cache_bytes++ hidden, kv, inter = 4096, 1024, 14336+ specs = {+ "self_attn.q_proj.weight": _spec((hidden, hidden)),+ "self_attn.k_proj.weight": _spec((kv, hidden)),+ "self_attn.v_proj.weight": _spec((kv, hidden)),+ "self_attn.o_proj.weight": _spec((hidden, hidden)),+ "mlp.gate_proj.weight": _spec((inter, hidden)),+ "mlp.up_proj.weight": _spec((inter, hidden)),+ "mlp.down_proj.weight": _spec((hidden, inter)),+ }+ assert nf4_scale_cache_bytes(specs, n_layers=32) == 436_207_616++ def test_a_partial_block_rounds_up(self):+ from soup_cli.utils.layer_stream import nf4_scale_cache_bytes++ # 65 elements -> 2 blocks of 64 -> 8 bytes per layer.+ assert nf4_scale_cache_bytes({"w": _spec((5, 13))}, n_layers=3) == 24++ def test_non_nested_weights_cost_nothing(self):+ from soup_cli.utils.layer_stream import nf4_scale_cache_bytes++ specs = {"a": _spec((64, 64), nested=False), "b": _spec((64, 64))}+ assert nf4_scale_cache_bytes(specs, n_layers=2) == 2 * 64 * 4++ def test_the_block_size_is_read_from_the_spec(self):+ from soup_cli.utils.layer_stream import nf4_scale_cache_bytes++ assert nf4_scale_cache_bytes({"w": _spec((128, 128), blocksize=128)}, n_layers=1) == 512+++class TestPeakEstimate:+ def _estimate(self, **extra):+ from soup_cli.utils.layer_stream import estimate_stream_peak_vram++ return estimate_stream_peak_vram(+ layer_bytes=1000,+ buffers=2,+ extras_bytes=0,+ adapter_params=10,+ vocab_size=64,+ hidden_size=8,+ intermediate_size=16,+ n_layers=4,+ seq_len=4,+ **extra,+ )++ def test_persistent_bytes_add_exactly(self):+ assert self._estimate(persistent_bytes=12_345) == self._estimate() + 12_345++ def test_default_adds_nothing(self):+ assert self._estimate(persistent_bytes=0) == self._estimate()+++class _Lora:+ r = 8+ target_modules = ["q_proj", "v_proj"]+++class _ModelConfig:+ vocab_size = 64+ hidden_size = 8+ intermediate_size = 16+ num_hidden_layers = 4+++class _Data:+ max_length = 4+++class _Config:+ data = _Data()+++class _TrainConfig:+ batch_size = 1+ stream_buffers = 2+ stream_vram_probe = False+ lora = _Lora()++ def __init__(self, cache):+ self.stream_nf4_scale_cache = cache+++class _Index:+ n_layers = 4++ def __init__(self):+ self.quant_specs = {"self_attn.q_proj.weight": _spec((64, 64))}+++class TestPreflightCharge:+ def _captured_persistent_bytes(self, monkeypatch, cache):+ from soup_cli.trainer.stream_setup import StreamingSetupMixin+ from soup_cli.utils import layer_stream++ real = layer_stream.estimate_stream_peak_vram+ seen = {}++ def capture(**kwargs):+ seen.update(kwargs)+ return real(**kwargs)++ monkeypatch.setattr(layer_stream, "estimate_stream_peak_vram", capture)+ lines, _plan = StreamingSetupMixin()._stream_budget_lines(+ _Config(),+ _TrainConfig(cache),+ model_config=_ModelConfig(),+ layer_bytes=1000,+ embed_bytes=0,+ index=_Index(),+ on_cuda=False,+ )+ return seen.get("persistent_bytes", 0), "\n".join(lines)++ def test_the_cache_is_charged_when_on(self, monkeypatch):+ charged, text = self._captured_persistent_bytes(monkeypatch, cache=True)+ # 4 layers x 64 blocks x 4 bytes.+ assert charged == 4 * 64 * 4+ assert "stream_nf4_scale_cache" in text++ def test_nothing_is_charged_when_off(self, monkeypatch):+ charged, text = self._captured_persistent_bytes(monkeypatch, cache=False)+ assert charged == 0+ assert "stream_nf4_scale_cache" not in text+++def _nf4_stream(tmp_path, *, cache, n_layers=2, double_quant=True, device="cpu", dtype="float32"):+ pytest.importorskip("torch")+ pytest.importorskip("bitsandbytes")+ pytest.importorskip("peft")+ from soup_cli.utils.layer_shard import QUANT_NF4, shard_checkpoint+ from soup_cli.utils.layer_stream_runtime import (+ build_meta_skeleton,+ build_streamed_model,+ quantised_layer_suffixes,+ )+ from tests.test_v07202 import _tiny_llama_dir, _tiny_lora++ weights, _resident, _ = _tiny_llama_dir(tmp_path, n_layers=n_layers)+ probe = build_meta_skeleton(weights, dtype=dtype, quant=QUANT_NF4)+ suffixes = quantised_layer_suffixes(probe)+ del probe+ shards = str(tmp_path / "shards")+ index = shard_checkpoint(+ weights,+ shards,+ dtype=dtype,+ arch="llama",+ quant=QUANT_NF4,+ quant_suffixes=suffixes,+ quant_device=device,+ double_quant=double_quant,+ )+ model, runtime = build_streamed_model(+ model_id=weights,+ shard_dir=shards,+ index=index,+ lora_config=_tiny_lora(),+ device=device,+ dtype=dtype,+ buffers=2,+ pin=False,+ seed=3,+ quant=QUANT_NF4,+ double_quant=double_quant,+ nf4_scale_cache=cache,+ )+ return model, runtime, index+++def _count_blockwise_dequant(monkeypatch):+ import bitsandbytes.functional as bnb_functional++ real = bnb_functional.dequantize_blockwise+ calls = {"n": 0}++ def counting(*args, **kwargs):+ calls["n"] += 1+ return real(*args, **kwargs)++ monkeypatch.setattr(bnb_functional, "dequantize_blockwise", counting)+ return calls+++def _step(model, optimizer, ids):+ optimizer.zero_grad(set_to_none=True)+ out = model(input_ids=ids, labels=ids)+ out.loss.backward()+ grads = [p.grad.detach().clone() for p in model.parameters() if p.requires_grad]+ optimizer.step()+ return out.logits.detach().clone(), out.loss.detach().clone(), grads+++class TestRuntime:+ def test_off_builds_no_cache(self, tmp_path):+ _model, runtime, _index = _nf4_stream(tmp_path, cache=False)+ assert runtime.scale_cache is None+ assert runtime.stats()["nf4_scale_cache_bytes"] == 0++ def test_one_step_fills_every_nested_weight_once(self, tmp_path):+ import torch++ from soup_cli.utils.layer_stream import nf4_scale_cache_bytes++ model, runtime, index = _nf4_stream(tmp_path, cache=True)+ nested = sum(1 for spec in index.quant_specs.values() if spec.nested)+ assert nested > 0+ assert len(runtime.scale_cache) == 0++ ids = torch.randint(0, 64, (1, 8), generator=torch.Generator().manual_seed(0))+ model(input_ids=ids, labels=ids).loss.backward()++ assert len(runtime.scale_cache) == index.n_layers * nested+ # Every layer is filled, so the planned bytes are exactly what is held.+ assert runtime.scale_cache.nbytes == nf4_scale_cache_bytes(+ index.quant_specs, n_layers=index.n_layers+ )+ assert runtime.stats()["nf4_scale_cache_bytes"] == runtime.scale_cache.nbytes++ def test_a_filled_cache_skips_the_nested_expansion(self, tmp_path, monkeypatch):+ import torch++ model, runtime, _index = _nf4_stream(tmp_path, cache=True)+ ids = torch.randint(0, 64, (1, 8), generator=torch.Generator().manual_seed(0))+ model(input_ids=ids, labels=ids).loss.backward()+ filled = len(runtime.scale_cache)++ calls = _count_blockwise_dequant(monkeypatch)+ model(input_ids=ids, labels=ids).loss.backward()+ assert calls["n"] == 0+ assert len(runtime.scale_cache) == filled++ def test_without_the_cache_every_visit_expands(self, tmp_path, monkeypatch):+ """The control for the test above: the counter does see the expansion."""+ import torch++ model, _runtime, _index = _nf4_stream(tmp_path, cache=False)+ ids = torch.randint(0, 64, (1, 8), generator=torch.Generator().manual_seed(0))+ calls = _count_blockwise_dequant(monkeypatch)+ model(input_ids=ids, labels=ids).loss.backward()+ assert calls["n"] > 0++ def test_training_is_bit_identical_with_and_without_the_cache(self, tmp_path):+ import torch++ runs = {}+ for cache in (False, True):+ torch.manual_seed(0)+ model, _runtime, _index = _nf4_stream(tmp_path / str(cache), cache=cache)+ optimizer = torch.optim.AdamW(+ [p for p in model.parameters() if p.requires_grad], lr=1e-2+ )+ generator = torch.Generator().manual_seed(1)+ steps = []+ for _ in range(3):+ ids = torch.randint(0, 64, (1, 8), generator=generator)+ steps.append(_step(model, optimizer, ids))+ runs[cache] = steps++ nonzero = False+ for (logits_a, loss_a, grads_a), (logits_b, loss_b, grads_b) in zip(+ runs[False], runs[True]+ ):+ assert torch.equal(logits_a, logits_b)+ assert torch.equal(loss_a, loss_b)+ assert len(grads_a) == len(grads_b)+ for grad_a, grad_b in zip(grads_a, grads_b):+ assert torch.equal(grad_a, grad_b)+ nonzero = nonzero or bool(grad_a.abs().sum() > 0)+ assert nonzero, "vacuous: every gradient was zero"++ def test_close_releases_the_cache(self, tmp_path):+ import torch++ model, runtime, _index = _nf4_stream(tmp_path, cache=True)+ ids = torch.randint(0, 64, (1, 8), generator=torch.Generator().manual_seed(0))+ model(input_ids=ids, labels=ids).loss.backward()+ assert len(runtime.scale_cache) > 0++ runtime.close()+ assert len(runtime.scale_cache) == 0+ assert runtime.scale_cache.nbytes == 0++ def test_the_fused_path_keeps_the_nested_state(self, tmp_path, monkeypatch):+ """The custom GEMM folds the nested dequantisation into its kernel; giving+ it pre-expanded scales changed the loss in the study this ports. The fused+ arm must receive the original nested state and must not fill the cache."""+ import torch+ from bitsandbytes.functional import dequantize_4bit++ import soup_cli.utils.layer_stream_runtime as runtime_module++ model, runtime, _index = _nf4_stream(tmp_path, cache=True)+ seen = []++ def fake_fused(x, packed, quant_state, bias=None):+ seen.append(bool(quant_state.nested))+ weight = dequantize_4bit(packed, quant_state)+ return torch.nn.functional.linear(x, weight.to(x.dtype), bias)++ monkeypatch.setattr(+ runtime_module, "_can_use_checkpoint_visible_nf4_gemm", lambda *_a, **_k: True+ )+ monkeypatch.setattr(runtime_module, "checkpoint_visible_nf4_linear", fake_fused)++ ids = torch.randint(0, 64, (1, 8), generator=torch.Generator().manual_seed(0))+ with torch.no_grad():+ model(input_ids=ids)+ assert seen and all(seen)+ assert len(runtime.scale_cache) == 0+++class TestEdges:+ def test_shards_without_double_quant_are_refused(self, tmp_path):+ with pytest.raises(ValueError, match="no nested NF4 weights"):+ _nf4_stream(tmp_path, cache=True, double_quant=False)++ def test_a_key_reused_for_another_shape_is_refused(self):+ torch = pytest.importorskip("torch")+ pytest.importorskip("bitsandbytes")+ from bitsandbytes.functional import quantize_4bit++ from soup_cli.utils.layer_stream_runtime import NF4ScaleCache++ cache = NF4ScaleCache()+ _packed, first = quantize_4bit(+ torch.randn(64, 64), compress_statistics=True, quant_type="nf4"+ )+ _packed, second = quantize_4bit(+ torch.randn(32, 128), compress_statistics=True, quant_type="nf4"+ )+ cache.dense_state((0, "w"), first)+ with pytest.raises(RuntimeError, match="was built for shape"):+ cache.dense_state((0, "w"), second)++ def test_filled_under_inference_mode_then_trained(self, tmp_path):+ """An eval or generation pass may be the first to visit a layer; the+ scales it leaves behind must serve training unchanged."""+ import torch++ runs = {}+ for cache in (False, True):+ torch.manual_seed(0)+ model, _runtime, _index = _nf4_stream(tmp_path / str(cache), cache=cache)+ ids = torch.randint(0, 64, (1, 8), generator=torch.Generator().manual_seed(2))+ with torch.inference_mode():+ model(input_ids=ids)+ optimizer = torch.optim.AdamW(+ [p for p in model.parameters() if p.requires_grad], lr=1e-2+ )+ runs[cache] = [_step(model, optimizer, ids) for _ in range(2)]++ for (logits_a, loss_a, grads_a), (logits_b, loss_b, grads_b) in zip(+ runs[False], runs[True]+ ):+ assert torch.equal(logits_a, logits_b)+ assert torch.equal(loss_a, loss_b)+ for grad_a, grad_b in zip(grads_a, grads_b):+ assert torch.equal(grad_a, grad_b)+++class TestSetupWiring:+ """The real setup path, from YAML to the runtime builder (spied), on CPU."""++ @pytest.mark.parametrize("flag", [True, False])+ def test_the_setting_reaches_the_runtime_builder(self, tmp_path, monkeypatch, flag):+ pytest.importorskip("torch")+ pytest.importorskip("bitsandbytes")+ from unittest.mock import MagicMock++ import soup_cli.utils.layer_stream as ls+ import soup_cli.utils.layer_stream_runtime as rt+ from soup_cli.trainer.sft import SFTTrainerWrapper+ from tests.test_issue623_stream_pin_allocation import (+ _FREE_BYTES,+ _cfg_yaml,+ _tiny_checkpoint,+ )++ weights = _tiny_checkpoint(tmp_path)+ monkeypatch.chdir(tmp_path)+ monkeypatch.setenv("SOUP_LAYER_STREAM_CACHE_DIR", str(tmp_path / "cache"))+ monkeypatch.setattr(+ "soup_cli.utils.spectrum_scan.resolve_model_weights", lambda *_a, **_k: weights+ )+ monkeypatch.setattr(ls, "free_ram_bytes", lambda: _FREE_BYTES)+ monkeypatch.setattr(+ ls, "classify_disk_kind", lambda *_a, **_k: ls.DiskClassification("nvme")+ )+ captured = {}++ def spy_build(**kwargs):+ captured.update(kwargs)+ runtime = MagicMock()+ runtime.tier = "ram"+ runtime.stats.return_value = {+ "tier": "ram",+ "store_bytes": 1_000_000,+ "disk_bytes": 0,+ "pinned": False,+ "read_ahead": None,+ "buffers": 2,+ "buffer_bytes": 4_000,+ "n_layers": 3,+ }+ return MagicMock(), runtime++ monkeypatch.setattr(rt, "build_streamed_model", spy_build)+ text = _cfg_yaml(+ weights, "", extra_training_yaml=f" stream_nf4_scale_cache: {str(flag).lower()}\n"+ ).replace("quantization: none", "quantization: 4bit")+ cfg = load_config_from_string(text)+ wrapper = SFTTrainerWrapper(cfg)+ wrapper.device = "cpu"+ wrapper._setup_streaming_transformers(cfg, cfg.training)++ assert captured["nf4_scale_cache"] is flag+++class TestCuda:+ """bitsandbytes' CUDA kernels on the dense path, with and without the cache."""++ @pytest.mark.gpu+ @pytest.mark.parametrize("force_dense", [True, False])+ def test_bit_identical_on_cuda(self, tmp_path, monkeypatch, force_dense):+ torch = pytest.importorskip("torch")+ import soup_cli.utils.layer_stream_runtime as runtime_module++ if force_dense:+ # Tiny shapes would otherwise go to the fused GEMM, which the cache+ # never touches; forcing the dense arm is what puts the cache to work.+ monkeypatch.setattr(+ runtime_module, "_can_use_checkpoint_visible_nf4_gemm", lambda *_a, **_k: False+ )+ runs = {}+ for cache in (False, True):+ torch.manual_seed(0)+ model, runtime, _index = _nf4_stream(+ tmp_path / str(cache), cache=cache, device="cuda", dtype="bfloat16"+ )+ optimizer = torch.optim.AdamW(+ [p for p in model.parameters() if p.requires_grad], lr=1e-2+ )+ generator = torch.Generator().manual_seed(1)+ steps = []+ for _ in range(3):+ ids = torch.randint(0, 64, (1, 8), generator=generator).cuda()+ steps.append(_step(model, optimizer, ids))+ runs[cache] = steps+ if cache:+ filled = len(runtime.scale_cache)+ runtime.close()++ assert (filled > 0) is force_dense+ for (logits_a, loss_a, grads_a), (logits_b, loss_b, grads_b) in zip(+ runs[False], runs[True]+ ):+ assert torch.equal(logits_a, logits_b)+ assert torch.equal(loss_a, loss_b)+ for grad_a, grad_b in zip(grads_a, grads_b):+ assert torch.equal(grad_a, grad_b)