Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
feat(stream): the output head and the loss in token chunks (#1693) (#1880)
Yang Bai5170471bd9e8
diff --git a/changelog.d/0.76.0/1880.added.md b/changelog.d/0.76.0/1880.added.mdnew file mode 100644index 00000000..cd3554a7--- /dev/null+++ b/changelog.d/0.76.0/1880.added.md@@ -0,0 +1,15 @@+- **`training.stream_loss_chunk: N` runs the output head and the loss `N` tokens at a time under+ layer streaming, so the logits no longer grow with the context length.** Unset, the head builds+ the full `[batch, seq, vocab]` logits and the loss works on all of them, which is what ran a+ 4 GB card out of memory from about 1024 tokens. Set, each chunk runs the head, takes its+ cross-entropy and the gradient on its own hidden states, and drops its logits; one+ `[batch, seq, hidden]` tensor carries the gradient to the backward pass. The loss and the+ gradients match the unchunked step within `1e-5` of the largest value, not bit for bit. The+ `entropy`, `mean_token_accuracy` and `num_tokens` columns and `rewind.jsonl` are written as+ before; a labelled forward returns no logits. `task: sft` only; refused without+ `stream_layers`, beside `use_cut_ce`, with `data.format: raft`, with a trainable output head,+ and for a model that changes its logits after the head (Gemma 2's soft-capping). The pre-flight+ charges the logits on `min(seq, N)` tokens plus two hidden-sized tensors. **Not measured on a+ GPU**: the peak-VRAM table #1693 asks for is still open. Try: `soup train --config soup.yaml`+ with `training.stream_layers: true` and `training.stream_loss_chunk: 128` (#1693 by @ybai08 in+ #1880).diff --git a/docs/config-reference.md b/docs/config-reference.mdindex 034c3ed5..0c72fa2e 100644--- a/docs/config-reference.md+++ b/docs/config-reference.md@@ -317,6 +317,7 @@ Sections:| `training.stream_vram_probe` | `bool` | `false` | | Decide the layer-streaming VRAM pre-flight on a MEASUREMENT instead of the fitted formula. One real forward+backward runs at the configured shape after the streamed model is built, and its peak decides whether the run proceeds; the prediction is printed beside it so a divergence is visible. The formula under-predicts past seq 4352 (measured 0.934x the real peak at seq 5120 and 0.787x at 6144), which is the direction that does not announce itself — an OOM on Linux, a silent spill to host memory on Windows. Against the probe the same formula reads 0.992x at seq 4096 and 0.830x at 5120, because the probe itself runs 12.5-14.3% above the real training step — the direction that makes it safe as a gate. Off by default: it costs one step (1-5 s measured) and it can refuse a run the formula accepts. task='sft' only: the probe runs a plain causal-LM forward+backward, which IS the SFT step but not a preference loss. At the one preference shape measured it reads +13.5% high (probe 6.021 GB against a real DPO step's 5.304 GB) — the same safe direction it shows for SFT — but one shape is not a validation, so the restriction stands until it is measured across shapes. || `training.stream_nf4_scale_cache` | `bool` | `false` | | Keep each streamed NF4 weight's expanded fp32 block scales on the compute device after its first use. A double-quantised weight stores its scales as 8-bit codes plus a nested scale and offset, and bitsandbytes' dequantise + linear path expands them on every visit (forward and checkpoint recompute): two extra kernels and a temporary per projection. The base is frozen, so the expansion is done once per (layer, weight) and reused; results are bit-identical. Costs 4 bytes per 64-element block of VRAM for the whole run (416 MiB on Mistral-7B), which the pre-flight charges up front. bitsandbytes' fused 4-bit GEMM path expands the scales inside its kernel and is left unchanged. Needs quantization='4bit' with double quantization (the default). Off by default. || `training.stream_expert_layout` | `str` | `"fused"` | one of `"fused"`, `"per_expert"` | How a MoE base's routed experts are streamed. 'fused' (the default) keeps each MoE layer's experts inside its layer file, so the largest layer bounds the card. 'per_expert' writes them to their own file, one pair of matrices per expert (NF4 per matrix under quantization='4bit'), and reads an expert only when the router picks it, again in the backward: the decoder-layer buffers hold the dense part alone, so the VRAM bound no longer grows with the expert count. Each routed expert is read about three times per step from the cache volume, so expect slower steps (an NVMe volume is recommended). Under quantization='4bit' the routed experts are NF4 here but stay at the stream dtype with 'fused', so the two layouts train against numerically different bases. Admitted for DeepSeek-V3-family bases (model_type deepseek_v3); adapters on the routed experts (moe_lora) are refused with it. |+| `training.stream_loss_chunk` | `int \| null` | `null` | `>= 16`, `<= 8192` | Tokens per chunk for the output head and the loss under layer streaming (#1693). Unset, the head builds the full \[batch, seq, vocab] logits and the loss works on all of them, which is what caps the context length on a small card. Set, each chunk runs the head, takes its cross-entropy and the gradient on its hidden states, and drops its logits, so the logits term is vocab x chunk x batch whatever data.max_length is. It costs one more \[batch, seq, hidden] tensor and a loop over the head. It gives up outputs.logits on a labelled forward, and equality to the last bit with an unchunked step: the per-token terms are the same, the order of the final sum is not. task='sft' only; refused beside use_cut_ce. || `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 d12ff276..05de1f77 100644--- a/docs/performance-and-quantization.md+++ b/docs/performance-and-quantization.md@@ -450,6 +450,7 @@ training:# 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_loss_chunk: 128 # Output head and loss N tokens at a time, for long contexts (sft only)# stream_disk_kind: nvme # Override auto disk-kind detection: nvme/ssd/hdd; see below```@@ -784,7 +785,7 @@ prints this advice when it sees you accumulating.- `unfrozen_parameters`, `lisa_enabled`, `packing`, `multipack`, `use_fsdp2_compile`, `train_router_only`, `expand_layers` → each independently rewrites or re-freezes the same layers- `use_cut_ce` is refused with `stream_layers` (#1206): streamed setup does not install the resident CCE patch. Disable CCE to stream with the conservative full-logits budget, or disable streaming to use resident CCE. A tiny local streamed Llama was exercised through sharding, forward/loss and backward on CPU; this is no CUDA memory measurement.- `use_liger` / `use_flash_attn` → **not reached at all** under streaming (#1692). Both are read by the *resident* setup: Liger patches the MLP forward there, and flash-attn is handed to `from_pretrained` as `attn_implementation`. A streamed model is built by `from_config` with no attention argument and no Liger patch, and `_liger_applied` is never set, so `use_liger_kernel` misses `TrainingArguments` too. These are the switches you reach for when a streamed run will not fit, so they are refused rather than dropped; each is offered again once it is wired and shown to engage on a streamed model. On every task outside `{sft, tts}` they are already refused at config load (#806)-- `stream_source` / `stream_ngram_source` / `stream_buffers` / `stream_read_ahead` / `stream_vram_override` / `stream_vram_probe` / `stream_nf4_scale_cache` / `stream_expert_layout` / `stream_disk_kind` / `stream_pin` set while `stream_layers: false` → a footgun, refused+- `stream_source` / `stream_ngram_source` / `stream_buffers` / `stream_read_ahead` / `stream_vram_override` / `stream_vram_probe` / `stream_nf4_scale_cache` / `stream_expert_layout` / `stream_disk_kind` / `stream_pin` / `stream_loss_chunk` set while `stream_layers: false` → a footgun, refused- `stream_expert_layout: per_expert` with `moe_lora` → refused: a routed expert streamed one at a time has nowhere to keep an adapter. On a base that is not `model_type: deepseek_v3` → refused at setup, before the weights are resolved- an FP8 checkpoint in any format other than DeepSeek-V3's block FP8, or an FP8 base that is not `model_type: deepseek_v3` → refused naming the supported format: at setup when `config.json` gives it away, otherwise before the cache is written. The block format itself is dequantised at shard time (see "FP8 block-quantised bases" above)- `stream_nf4_scale_cache` without `quantization: 4bit` and double quantization → refused: there are no nested NF4 scales to cache@@ -792,6 +793,8 @@ prints this advice when it sees you accumulating.- a disk-tier run whose host staging (`stream_read_ahead` layers, plus one slot each for the embedding and an untied `lm_head`) plus the resident extras will not fit the free-RAM headroom → refused by name, naming the depth to lower. Refused rather than clamped: a depth you set is a decision, and silently lowering it would hand back a slower run than the one you configured- more than 8 distinct layer shapes in one shard index → refused. Staging is allocated per shape and a shape with one member takes a full slot at any depth, so an index whose every layer differed would hold most of the model in staging at once — page-locked when the box allows it and `stream_pin` is not false, a loud pageable fallback otherwise, and a refusal only under `stream_pin: true` on a CUDA target — which is what the disk tier exists to avoid. A real model has one to three- `stream_vram_probe` on any task other than `sft` → the probe runs a plain causal-LM step, which *is* the SFT step but is not a preference loss. Measured at one matching shape it is conservative there too (6.02 GB against a real DPO step's 5.30 GB, +13.5%), but one shape is not a validation, so it is not offered for `dpo`/`orpo`/`simpo`/`kto` yet+- `stream_loss_chunk` on any task other than `sft`, or with `data.format: raft` → the chunked step rebuilds the causal-LM cross-entropy and returns no logits. A preference loss reduces the logits to per-token log-probs instead, and RAFT's weighted loss reads all of them (#1693)+- `stream_loss_chunk` beside `use_cut_ce` → each replaces how the loss over the logits is computed. Refused before the `use_cut_ce` refusal above, with a message that names both fields (#1693)- an architecture outside the supported list (llama / qwen2 / qwen3, including qwen3_5_moe text aliases / qwen4_exp text / mistral / gemma / gemma2 / gemma3_text / phi / phi3 / deepseek_v3) → named explicitly. `deepseek_v3` is the DeepSeek-V3 family (MLA attention, routed experts plus a shared expert); a Kimi K2 checkpoint uses the same decoder but declares `model_type: kimi_k2`, which transformers does not register, so it is refused under that name. Under `quantization: 4bit` its attention, shared-expert and dense-MLP projections are NF4 while the routed experts stay at the stream dtype: they are 3-D parameters, not `nn.Linear` modules, so a DeepSeek-V3 layer streams most of its bytes unquantised**Config example:**diff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.pyindex 479c7e5a..9ee8dcfe 100644--- a/src/soup_cli/config/schema.py+++ b/src/soup_cli/config/schema.py@@ -15,9 +15,11 @@ from soup_cli.utils.config_bounds import (DEFAULT_STREAM_READ_AHEAD,MAX_NOISE_FLOOR_RUNS,MAX_STREAM_BUFFERS,+ MAX_STREAM_LOSS_CHUNK,MAX_STREAM_READ_AHEAD,MIN_NOISE_FLOOR_RUNS,MIN_STREAM_BUFFERS,+ MIN_STREAM_LOSS_CHUNK,MIN_STREAM_READ_AHEAD,)from soup_cli.utils.config_bounds import (@@ -3734,6 +3736,35 @@ class TrainingConfig(BaseModel):"with it."),)++ stream_loss_chunk: Optional[int] = Field(+ default=None,+ ge=MIN_STREAM_LOSS_CHUNK,+ le=MAX_STREAM_LOSS_CHUNK,+ description=(+ "Tokens per chunk for the output head and the loss under layer "+ "streaming (#1693). Unset, the head builds the full [batch, seq, "+ "vocab] logits and the loss works on all of them, which is what "+ "caps the context length on a small card. Set, each chunk runs the "+ "head, takes its cross-entropy and the gradient on its hidden "+ "states, and drops its logits, so the logits term is vocab x chunk "+ "x batch whatever data.max_length is. It costs one more [batch, "+ "seq, hidden] tensor and a loop over the head. It gives up "+ "outputs.logits on a labelled forward, and equality to the last "+ "bit with an unchunked step: the per-token terms are the same, the "+ "order of the final sum is not. task='sft' only; refused beside "+ "use_cut_ce."+ ),+ )++ @field_validator("stream_loss_chunk", mode="before")+ @classmethod+ def _validate_stream_loss_chunk_int(cls, v: Any) -> Any:+ """Reject bool-as-int (bool subclasses int), mirrors stream_buffers."""+ if isinstance(v, bool):+ raise ValueError("training.stream_loss_chunk must be an int (tokens), not bool")+ return v+stream_disk_kind: Optional[Literal["nvme", "ssd", "hdd"]] = Field(default=None,description=(@@ -6806,14 +6837,15 @@ class SoupConfig(BaseModel):or tcfg.stream_expert_layout != "fused"or tcfg.stream_disk_kind is not Noneor tcfg.stream_pin is not None+ or tcfg.stream_loss_chunk is not None):raise ValueError("training.stream_source / training.stream_ngram_source / ""training.stream_buffers / training.stream_read_ahead / ""training.stream_vram_override / training.stream_vram_probe ""/ training.stream_nf4_scale_cache / training.stream_expert_layout "- "/ training.stream_disk_kind / training.stream_pin set but "- "stream_layers is false; set "+ "/ training.stream_disk_kind / training.stream_pin "+ "/ training.stream_loss_chunk set but stream_layers is false; set ""stream_layers=true to stream the base layer-by-layer.")return self@@ -6895,6 +6927,32 @@ class SoupConfig(BaseModel):f"training.stream_vram_override if you have measured this "f"configuration yourself.")+ if tcfg.stream_loss_chunk is not None and self.task != "sft":+ # #1693 — the chunked step rebuilds `ForCausalLMLoss`, the sft loss.+ raise ValueError(+ f"training.stream_loss_chunk supports task='sft' only; got "+ f"task={self.task!r}. It computes the causal-LM cross-entropy "+ f"chunk by chunk; a preference loss reduces the logits to "+ f"per-token log-probs of chosen and rejected instead, and that "+ f"reduction is not chunked. Remove training.stream_loss_chunk."+ )+ if tcfg.stream_loss_chunk is not None and self.data.format == "raft":+ raise ValueError(+ "training.stream_loss_chunk cannot be combined with data.format="+ "'raft': the RAFT loss weights every token and is computed from "+ "the full logits, which a chunked step does not return. Remove "+ "training.stream_loss_chunk."+ )+ if tcfg.stream_loss_chunk is not None and tcfg.use_cut_ce:+ # #1693 — two mechanisms over the same loss. Checked before the+ # refusal of use_cut_ce under streaming (#2023), so that the+ # message names both fields.+ raise ValueError(+ "training.stream_loss_chunk and training.use_cut_ce cannot be "+ "combined: each replaces how the loss over the logits is "+ "computed. Keep stream_loss_chunk and set use_cut_ce=false; "+ "streaming refuses use_cut_ce on its own."+ )if self.backend != "transformers":raise ValueError(f"training.stream_layers requires backend='transformers'; got "diff --git a/src/soup_cli/trainer/rewind_hf.py b/src/soup_cli/trainer/rewind_hf.pyindex bf3ef85e..1725c18e 100644--- a/src/soup_cli/trainer/rewind_hf.py+++ b/src/soup_cli/trainer/rewind_hf.py@@ -51,6 +51,9 @@ from typing import Any, Optional, Protocol, Sequencefrom rich.console import Consolefrom rich.markup import escape+# Where a chunked step (#1693) leaves what its trainer collected.+from soup_cli.utils.stream_loss_chunk import STEP_ATTR as _CHUNKED_STEP_ATTR+console = Console()# Hidden attr on the trainer instance -- read by the overrides below.@@ -162,6 +165,21 @@ class RewindState:return f"rewind: {self.dropped} {noun} dropped (FIFO underflow)"+def row_losses_from_token_losses(token_loss: Any, labels: Any) -> tuple[list[float], list[int]]:+ """:func:`row_losses` for a step that has no logits (#1693).++ ``token_loss`` is ``(B, T)``: position ``t`` holds the cross-entropy of+ ``labels[:, t + 1]``, and 0.0 where that label is ``-100`` or there is none.+ """+ import torch++ with torch.no_grad():+ tokens = (labels[:, 1:] != -100).sum(dim=1)+ totals = token_loss.float().sum(dim=1).to(tokens.device)+ means = totals / tokens.clamp(min=1).to(totals.dtype)+ return [float(mean) for mean in means], [int(count) for count in tokens]++def row_losses(logits: Any, labels: Any) -> tuple[list[float], list[int]]:"""Per-row mean supervised-token cross-entropy, and the token counts.@@ -325,12 +343,20 @@ def make_rewind_trainer_class(base_cls: type) -> type:)try:logits = getattr(outputs, "logits", None)- if logits is None:+ # #1693 -- a chunked step returns no logits and leaves each+ # token's loss here instead.+ chunked = getattr(self, _CHUNKED_STEP_ATTR, None)+ if logits is not None:+ row_loss, row_tokens = row_losses(logits, labels)+ elif chunked is not None:+ row_loss, row_tokens = row_losses_from_token_losses(+ chunked.token_loss, labels+ )+ else:raise RuntimeError("the model returned no logits (use_liger_kernel skips them ""during training), so per-row losses cannot be computed")- row_loss, row_tokens = row_losses(logits, labels)# ``state.global_step`` is the number of COMPLETED optimizer# steps, so +1 is the 1-based step this micro-batch belongs to.state.on_micro_batch(diff --git a/src/soup_cli/trainer/sft.py b/src/soup_cli/trainer/sft.pyindex 49017388..99335cae 100644--- a/src/soup_cli/trainer/sft.py+++ b/src/soup_cli/trainer/sft.py@@ -1109,6 +1109,18 @@ class SFTTrainerWrapper(StreamingSetupMixin):# so two ``multipack: true`` runs against the same base class share# the same subclass.use_multipack = bool(getattr(tcfg, "multipack", False))+ # #1693 -- with `stream_loss_chunk` the model returns no logits, which+ # TRL's `compute_loss` reads for its metrics. The schema keeps the+ # option to the two branches below that build `sft_cls`.+ sft_cls = SFTTrainer+ chunk_hook = getattr(self, "_stream_loss_chunk_hook", None)+ if chunk_hook is not None:+ from soup_cli.utils.stream_loss_chunk import (+ HOOK_ATTR,+ make_chunked_loss_trainer_class,+ )++ sft_cls = make_chunked_loss_trainer_class(SFTTrainer)if self._is_raft:# v0.71.10 #199 — RAFT uses a plain Trainer + weighted-CE loss# (answer-only mask via loss_weights; citation-span boost when@@ -1212,7 +1224,7 @@ class SFTTrainerWrapper(StreamingSetupMixin):and not use_audio):self.trainer = self._build_rewind_trainer(- SFTTrainer,+ sft_cls,trainer_kwargs,rows=dataset["train"],output_dir=output_dir,@@ -1220,7 +1232,9 @@ class SFTTrainerWrapper(StreamingSetupMixin):grad_accum=int(tcfg.gradient_accumulation_steps),)else:- self.trainer = SFTTrainer(**trainer_kwargs)+ self.trainer = sft_cls(**trainer_kwargs)+ if chunk_hook is not None:+ setattr(self.trainer, HOOK_ATTR, chunk_hook)# The recording trainer is the last branch above, so RAFT, multipack,# vision, audio and a pre-tokenised dataset all skip it -- silently,@@ -2393,6 +2407,8 @@ class SFTTrainerWrapper(StreamingSetupMixin):with self._training_context(offload_context(tcfg.activation_offloading, save_dir=offload_save_dir)) as train_ctx:+ # #1693: also when training raises.+ train_ctx.callback(self._remove_stream_loss_chunk_hook)# LongLoRA S² shifted-sparse attention (v0.49.0 schema). The override# monkeypatches attention.forward for the duration of training and# was previously never installed (use_longlora validated but shippeddiff --git a/src/soup_cli/trainer/stream_setup.py b/src/soup_cli/trainer/stream_setup.pyindex 41813996..187b7971 100644--- a/src/soup_cli/trainer/stream_setup.py+++ b/src/soup_cli/trainer/stream_setup.py@@ -722,6 +722,8 @@ class StreamingSetupMixin:#: Set by :meth:`_setup_streaming_transformers`; absent on a resident run._stream_runtime = None+ # #1693 -- the head-and-loss hook of a run with `stream_loss_chunk` set.+ _stream_loss_chunk_hook = None#: ``trust_remote_code`` for the streamed MODEL (config, meta skeleton,#: install): always False. Every entry of ``SUPPORTED_STREAM_ARCHS`` passed@@ -1425,6 +1427,18 @@ class StreamingSetupMixin:raiseif fast_lora_counts is not None:console.print(f"[green]{fast_lora_summary(fast_lora_counts)}[/]")+ loss_chunk = getattr(tcfg, "stream_loss_chunk", None)+ if loss_chunk is not None:+ # #1693 -- before the probe, so that it measures the step that runs.+ from soup_cli.utils.stream_loss_chunk import ChunkedHeadLoss, causal_lm_of++ try:+ self._stream_loss_chunk_hook = ChunkedHeadLoss(causal_lm_of(model), loss_chunk)+ except Exception:+ # As for #792's patch above: training's cleanup context has+ # not started yet, so release the runtime here.+ self._close_stream_runtime()+ raiseif probe_plan is not None:self._run_stream_vram_probe(model, probe_plan)stats = runtime.stats()@@ -1485,6 +1499,24 @@ class StreamingSetupMixin:if runtime is not None:runtime.close()+ def _remove_stream_loss_chunk_hook(self) -> None:+ """Take the chunked head and loss off the model when training ends (#1693).++ A labelled forward later in the same process (an eval gate, ``infer``)+ then gets the full logits again, and the trainer's ``compute_loss``+ takes TRL's own path.+ """+ hook = self._stream_loss_chunk_hook+ if hook is None:+ return+ from soup_cli.utils.stream_loss_chunk import HOOK_ATTR++ hook.remove()+ trainer = getattr(self, "trainer", None)+ if trainer is not None and getattr(trainer, HOOK_ATTR, None) is hook:+ setattr(trainer, HOOK_ATTR, None)+ self._stream_loss_chunk_hook = None+def _estimate_adapter_params(self, tcfg, model_config) -> int:"""Trainable adapter parameters, before the model exists.@@ -1577,6 +1609,10 @@ class StreamingSetupMixin:hidden = int(getattr(shape_cfg, "hidden_size", 0) or 0)inter = self._stream_intermediate_size(shape_cfg)seq_len = int(cfg.data.max_length)+ # #1693 -- with the head and the loss in chunks, the logits term stops+ # at one chunk. (`getattr`: the stand-in configs of #348 and #349 name+ # only the fields this method read when they were written.)+ loss_chunk = getattr(tcfg, "stream_loss_chunk", None)batch = tcfg.batch_size if isinstance(tcfg.batch_size, int) else 1# v0.72.4 — a paired loss concatenates chosen and rejected into ONE# tensor, so twice the rows reach the model per configured batch. The@@ -1615,16 +1651,21 @@ class StreamingSetupMixin:logits_bytes_per_element=calibrated,large_layer_bytes=large_layer_bytes,persistent_bytes=scale_cache_bytes + expert_bytes,+ loss_chunk=loss_chunk,)logits = estimate_logits_bytes(- vocab_size=vocab, seq_len=seq_len, batch_size=rows, bytes_per_element=calibrated+ vocab_size=vocab,+ seq_len=seq_len if loss_chunk is None else min(seq_len, loss_chunk),+ batch_size=rows,+ bytes_per_element=calibrated,)paired = ("" if rows == batch else f" ({rows} rows — chosen+rejected are one concatenated tensor)")+ chunked = "" if loss_chunk is None else f" in chunks of {loss_chunk} tokens"lines = [f" peak VRAM ~{predicted / 1e9:.2f} GB at batch {batch} x seq "- f"{seq_len}{paired} (logits {logits / 1e9:.2f} GB)"+ f"{seq_len}{paired} (logits {logits / 1e9:.2f} GB{chunked})"]if scale_cache_bytes:lines.append(diff --git a/src/soup_cli/utils/config_bounds.py b/src/soup_cli/utils/config_bounds.pyindex e509b879..fa591ce1 100644--- a/src/soup_cli/utils/config_bounds.py+++ b/src/soup_cli/utils/config_bounds.py@@ -16,6 +16,12 @@ MIN_STREAM_READ_AHEAD = 1MAX_STREAM_READ_AHEAD = 8DEFAULT_STREAM_READ_AHEAD = 2+# --- layer streaming: head + loss chunk (utils/stream_loss_chunk.py) --------+#: Below this the loop over the head costs more than the logits it saves: 16+#: tokens of a 128 256-token vocabulary are 29 MB at the shipped 14 B/element.+MIN_STREAM_LOSS_CHUNK = 16+MAX_STREAM_LOSS_CHUNK = 8192+# --- layer streaming: tasks ------------------------------------------------#: Tasks whose trainers can run against a streamed base (v0.72.4).#:diff --git a/src/soup_cli/utils/layer_stream.py b/src/soup_cli/utils/layer_stream.pyindex a595243c..8fecaaba 100644--- a/src/soup_cli/utils/layer_stream.py+++ b/src/soup_cli/utils/layer_stream.py@@ -1225,6 +1225,21 @@ def nf4_scale_cache_bytes(quant_specs: Mapping[str, Any], n_layers: int) -> int:return per_layer * n_layers+def estimate_loss_chunk_bytes(+ *, hidden_size: int, seq_len: int, batch_size: int = 1, dtype: str = "bfloat16"+) -> int:+ """What ``training.stream_loss_chunk`` keeps that an unchunked step does not (#1693).++ Two ``[batch, seq, hidden]`` tensors in the stream dtype: the gradient on+ the hidden states that the forward fills chunk by chunk, and its product+ with the incoming gradient in the backward. They are not live together with+ a chunk's logits, so charging both next to the logits term errs high.+ """+ if hidden_size <= 0 or seq_len <= 0 or batch_size <= 0:+ raise ValueError("hidden_size, seq_len and batch_size must all be positive")+ return 2 * hidden_size * seq_len * batch_size * dtype_bytes(dtype)++def estimate_stream_peak_vram(*,layer_bytes: int,@@ -1241,6 +1256,7 @@ def estimate_stream_peak_vram(logits_bytes_per_element: Optional[float] = None,large_layer_bytes: int = 0,persistent_bytes: int = 0,+ loss_chunk: Optional[int] = None,) -> int:"""Predicted ``torch.cuda.max_memory_allocated()`` for a streaming step.@@ -1269,7 +1285,21 @@ def estimate_stream_peak_vram(``persistent_bytes`` is device memory the runtime holds for the whole run ontop of the pool, such as :func:`nf4_scale_cache_bytes`.++ ``loss_chunk`` is ``training.stream_loss_chunk`` (#1693): the logits term is+ charged on ``min(seq_len, loss_chunk)`` tokens, at the same bytes per+ element, and :func:`estimate_loss_chunk_bytes` is added. None of the runs+ this formula was fitted to used it."""+ logits_tokens = seq_len+ chunk_bytes = 0+ if loss_chunk is not None:+ if isinstance(loss_chunk, bool) or not isinstance(loss_chunk, int) or loss_chunk < 1:+ raise ValueError(f"loss_chunk must be a positive integer, got {loss_chunk!r}")+ logits_tokens = min(seq_len, loss_chunk)+ chunk_bytes = estimate_loss_chunk_bytes(+ hidden_size=hidden_size, seq_len=seq_len, batch_size=batch_size, dtype=dtype+ )return (layer_bytes * buffers+ large_layer_bytes@@ -1287,10 +1317,11 @@ def estimate_stream_peak_vram()+ estimate_logits_bytes(vocab_size=vocab_size,- seq_len=seq_len,+ seq_len=logits_tokens,batch_size=batch_size,bytes_per_element=logits_bytes_per_element,)+ + chunk_bytes)diff --git a/src/soup_cli/utils/stream_loss_chunk.py b/src/soup_cli/utils/stream_loss_chunk.pynew file mode 100644index 00000000..a58b41cc--- /dev/null+++ b/src/soup_cli/utils/stream_loss_chunk.py@@ -0,0 +1,370 @@+"""The output head and the causal-LM loss in token chunks (#1693).++Layer streaming bounds the weights. What still grows with ``batch x seq`` is+the output head plus the loss: the head builds a ``[batch, seq, vocab]`` logits+tensor and ``ForCausalLMLoss`` upcasts it to fp32 and keeps two more buffers of+that shape at the backward peak. With a 128 256-token vocabulary that is+0.92 GB at 512 tokens and 3.68 GB at 2048, whatever the model's size.++Here the head and the loss run ``chunk`` positions at a time. Each chunk runs+the head, takes the cross-entropy sum, takes the gradient on its own slice of+the hidden states and drops its logits; the slices fill one ``[batch, seq,+hidden]`` tensor that the backward pass hands on. No graph over the logits+outlives its chunk, so the logits term is ``vocab x chunk x batch`` and no+longer depends on the sequence length.++The per-token terms are the ones ``ForCausalLMLoss`` computes. What differs is+the order of the final sum and the shape of each matmul, so the loss and the+gradients agree with the unchunked step to rounding, not bit for bit.+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Any, Callable, Optional++IGNORE_INDEX = -100+++@dataclass(frozen=True)+class ChunkedStep:+ """What a labelled forward leaves for the trainer's metrics.++ TRL's ``SFTTrainer`` reads ``outputs.logits`` for its ``entropy`` and+ ``mean_token_accuracy`` columns, and the rewind log for its per-row+ losses; a chunked step has no logits to give them.+ """++ token_entropy: Any # [batch, seq], the entropy of each position's distribution+ token_loss: Any # [batch, seq] float32, each labelled position's cross-entropy+ correct: Any # labelled positions whose argmax is the label+ labelled: Any # positions with a label+++def shift_for_next_token(labels: Any, ignore_index: int = IGNORE_INDEX) -> Any:+ """``labels`` moved one position left, as ``ForCausalLMLoss`` does: position+ ``t`` is scored against token ``t + 1`` and the last position against+ nothing."""+ from torch.nn import functional++ return functional.pad(labels, (0, 1), value=ignore_index)[..., 1:]+++def _chunk_terms(head: Callable[[Any], Any], piece: Any, target: Any, ignore_index: int):+ """One chunk: the cross-entropy sum, and what the metrics need, the latter+ without gradients."""+ import torch+ from torch.nn import functional++ logits = head(piece)+ with torch.no_grad():+ # In the head's own dtype, as TRL's `entropy_from_logits` reads them.+ log_probs = functional.log_softmax(logits, dim=-1)+ entropy = -(torch.exp(log_probs) * log_probs).sum(-1)+ labelled = target != ignore_index+ correct = ((logits.argmax(dim=-1) == target) & labelled).sum()+ # Also in the head's dtype and only then cast, as `row_losses` does.+ at_label = log_probs.gather(-1, target.clamp(min=0).unsqueeze(-1)).squeeze(-1)+ token_loss = (-at_label).float() * labelled+ # Gone before the fp32 copy below is made, so the two do not add up.+ del log_probs+ # `ForCausalLMLoss` upcasts before the loss; so does each chunk.+ wide = logits.float()+ total = functional.cross_entropy(+ wide.view(-1, wide.shape[-1]),+ target.reshape(-1),+ ignore_index=ignore_index,+ reduction="sum",+ )+ return total, entropy, token_loss, correct+++def _chunked_function():+ import torch++ class _ChunkedHeadLoss(torch.autograd.Function):+ """The loss, with the gradient on the hidden states taken in ``forward``."""++ @staticmethod+ def forward(ctx, hidden, head, target, chunk, denominator, ignore_index, with_grad):+ grad = torch.zeros_like(hidden) if with_grad else None+ total = torch.zeros((), dtype=torch.float32, device=hidden.device)+ entropies, losses = [], []+ correct = torch.zeros((), dtype=torch.long, device=hidden.device)+ for start in range(0, hidden.shape[1], chunk):+ stop = start + chunk+ piece = hidden[:, start:stop].detach()+ labels = target[:, start:stop]+ if with_grad:+ piece.requires_grad_(True)+ with torch.enable_grad():+ part, entropy, token_loss, hits = _chunk_terms(+ head, piece, labels, ignore_index+ )+ # Scaled BEFORE the gradient is taken, so each token's+ # gradient is rounded to the head's dtype at the scale+ # the unchunked step rounds it at. Scaling the summed+ # gradient afterwards moved bf16 gradients by up to+ # 9e-3 of the largest one.+ (piece_grad,) = torch.autograd.grad(part / denominator, piece)+ grad[:, start:stop] = piece_grad+ else:+ part, entropy, token_loss, hits = _chunk_terms(+ head, piece, labels, ignore_index+ )+ total = total + part.detach()+ entropies.append(entropy)+ losses.append(token_loss)+ correct = correct + hits+ token_entropy = torch.cat(entropies, dim=1)+ token_loss = torch.cat(losses, dim=1)+ ctx.with_grad = with_grad+ if with_grad:+ ctx.save_for_backward(grad)+ ctx.mark_non_differentiable(token_entropy, token_loss, correct)+ return total / denominator, token_entropy, token_loss, correct++ @staticmethod+ def backward(ctx, grad_loss, _grad_entropy, _grad_token_loss, _grad_correct):+ if not ctx.with_grad: # pragma: no cover — nothing asked for a gradient+ return (None,) * 7+ (grad,) = ctx.saved_tensors+ return (grad * grad_loss, None, None, None, None, None, None)++ return _ChunkedHeadLoss+++def chunked_causal_lm_loss(+ hidden: Any,+ head: Callable[[Any], Any],+ labels: Any,+ chunk: int,+ *,+ num_items_in_batch: Any = None,+ shift_labels: Any = None,+ ignore_index: int = IGNORE_INDEX,+) -> tuple[Any, ChunkedStep]:+ """``ForCausalLMLoss(head(hidden), labels)`` without the full logits.++ ``head`` maps ``[batch, n, hidden]`` to ``[batch, n, vocab]`` and must be+ frozen: the gradient is taken on the hidden states only. ``labels``,+ ``shift_labels`` and ``num_items_in_batch`` mean what they mean to+ ``ForCausalLMLoss``: the mean over the labelled positions, or the sum over+ ``num_items_in_batch`` when the trainer passes one.+ """+ import torch++ if isinstance(chunk, bool) or not isinstance(chunk, int) or chunk < 1:+ raise ValueError(f"chunk must be a positive integer, got {chunk!r}")+ target = shift_labels if shift_labels is not None else shift_for_next_token(+ labels, ignore_index+ )+ target = target.to(hidden.device)+ if target.shape != hidden.shape[:2]:+ raise ValueError(+ f"labels of shape {tuple(target.shape)} do not match hidden states of "+ f"shape {tuple(hidden.shape)}"+ )+ labelled = (target != ignore_index).sum()+ if num_items_in_batch is None:+ denominator = labelled+ elif torch.is_tensor(num_items_in_batch):+ denominator = num_items_in_batch.to(hidden.device)+ else:+ denominator = num_items_in_batch+ with_grad = torch.is_grad_enabled() and hidden.requires_grad+ loss, token_entropy, token_loss, correct = _chunked_function().apply(+ hidden, head, target, chunk, denominator, ignore_index, with_grad+ )+ step = ChunkedStep(+ token_entropy=token_entropy, token_loss=token_loss, correct=correct, labelled=labelled+ )+ return loss, step+++class ChunkedHeadLoss:+ """A causal LM whose labelled forward runs its head and loss in chunks.++ The head wrapper of a streamed model never sees the labels, and a tied+ checkpoint has no streamed head at all, so the hook is on the causal-LM+ forward: with labels, the decoder runs as it always does, the head is held+ back, and the loss is built from the hidden states the head would have+ received. The output then carries the loss and no logits. A forward without+ labels (generation, ``predict``) is untouched.+ """++ def __init__(self, causal_lm: Any, chunk: int) -> None:+ if isinstance(chunk, bool) or not isinstance(chunk, int) or chunk < 1:+ raise ValueError(f"chunk must be a positive integer, got {chunk!r}")+ head = causal_lm.get_output_embeddings()+ if head is None:+ raise ValueError(+ "training.stream_loss_chunk needs a model with an output head "+ f"(get_output_embeddings); {type(causal_lm).__name__} has none."+ )+ cap = getattr(getattr(causal_lm, "config", None), "final_logit_softcapping", None)+ if cap is not None:+ # Known before the first step; `_chunked_forward` checks any model.+ raise ValueError(+ "training.stream_loss_chunk cannot be used with "+ f"{type(causal_lm).__name__}: it soft-caps its logits after the "+ f"output head (final_logit_softcapping={cap}), so the loss cannot be "+ "rebuilt chunk by chunk from the head alone. Remove "+ "training.stream_loss_chunk."+ )+ trainable = [name for name, param in head.named_parameters() if param.requires_grad]+ if trainable:+ raise ValueError(+ "training.stream_loss_chunk takes the gradient on the hidden states "+ "only, so the output head must be frozen; trainable: "+ f"{', '.join(sorted(trainable))}."+ )+ self.chunk = chunk+ self.last_step: Optional[ChunkedStep] = None+ self._causal_lm = causal_lm+ self._head = head+ self._head_forward = head.forward+ self._forward = causal_lm.forward+ self._held: Optional[tuple[Any, Any]] = None+ self._holding = False+ # A forward already set on the instance (accelerate's hooks do that)+ # is put back as it was found; a class's own is uncovered again.+ self._before = [(module, module.__dict__.get("forward")) for module in (head, causal_lm)]+ head.forward = self._head_or_hold+ causal_lm.forward = self._chunked_forward++ def remove(self) -> None:+ """Put both forwards back."""+ for module, forward in self._before:+ if forward is None:+ module.__dict__.pop("forward", None)+ else:+ module.forward = forward++ def take_step(self) -> Optional[ChunkedStep]:+ """The metrics of the last labelled forward, once."""+ step, self.last_step = self.last_step, None+ return step++ def _head_or_hold(self, hidden: Any, *args: Any, **kwargs: Any) -> Any:+ if not self._holding:+ return self._head_forward(hidden, *args, **kwargs)+ # Stands for the logits until the forward returns: no vocabulary axis,+ # so it costs nothing, and its identity says whether the model did+ # anything to "the logits" after the head.+ placeholder = hidden.new_empty((*hidden.shape[:-1], 0))+ self._held = (hidden, placeholder)+ return placeholder++ def _chunked_forward(self, *args: Any, **kwargs: Any) -> Any:+ labels = kwargs.pop("labels", None)+ if labels is None:+ return self._forward(*args, **kwargs)+ self._holding, self._held = True, None+ try:+ outputs = self._forward(*args, **kwargs)+ finally:+ self._holding = False+ held, self._held = self._held, None+ if held is None or getattr(outputs, "logits", None) is not held[1]:+ raise ValueError(+ "training.stream_loss_chunk cannot be used with "+ f"{type(self._causal_lm).__name__}: its forward does not hand the "+ "output head's result back unchanged (for example a final logit "+ "soft-cap), so the loss cannot be rebuilt chunk by chunk. Remove "+ "training.stream_loss_chunk."+ )+ loss, self.last_step = chunked_causal_lm_loss(+ held[0],+ self._head_forward,+ labels,+ self.chunk,+ num_items_in_batch=kwargs.get("num_items_in_batch"),+ shift_labels=kwargs.get("shift_labels"),+ )+ rest = {key: value for key, value in outputs.items() if key not in ("loss", "logits")}+ return type(outputs)(loss=loss, **rest)+++def causal_lm_of(model: Any) -> Any:+ """The causal LM under a PEFT wrapper, or ``model`` itself."""+ get_base_model = getattr(model, "get_base_model", None)+ return get_base_model() if callable(get_base_model) else model+++# The trainer holds the hook under this name, and leaves the last labelled+# forward's `ChunkedStep` under the other for the rewind recorder above it.+HOOK_ATTR = "_soup_chunked_head_loss"+STEP_ATTR = "_soup_chunked_step"+++def make_chunked_loss_trainer_class(base_cls: type) -> type:+ """``base_cls`` (TRL's ``SFTTrainer``) for a model that returns no logits.++ ``SFTTrainer.compute_loss`` computes ``entropy`` and+ ``mean_token_accuracy`` from ``outputs.logits`` and raises without them.+ This goes to transformers' own ``compute_loss`` instead and logs the same+ columns, by TRL's formulas, from what the chunk loop collected. A step that+ is not chunked (no hook, or no labels) takes ``base_cls``'s path untouched.+ """+ from transformers import Trainer++ class ChunkedLossTrainer(base_cls): # type: ignore[misc, valid-type]+ def compute_loss( # type: ignore[override]+ self,+ model: Any,+ inputs: Any,+ return_outputs: bool = False,+ num_items_in_batch: Any = None,+ ) -> Any:+ hook = getattr(self, HOOK_ATTR, None)+ if hook is None or "labels" not in inputs:+ return super().compute_loss(+ model,+ inputs,+ return_outputs=return_outputs,+ num_items_in_batch=num_items_in_batch,+ )+ mode = "train" if self.model.training else "eval"+ # As TRL's `compute_loss` does before it delegates.+ inputs.pop("_prediction_loss_only", None)+ inputs["use_cache"] = False+ loss, outputs = Trainer.compute_loss(+ self, model, inputs, return_outputs=True, num_items_in_batch=num_items_in_batch+ )+ step = hook.take_step()+ setattr(self, STEP_ATTR, step)+ if step is not None:+ _log_trl_metrics(self, mode, inputs, step)+ return (loss, outputs) if return_outputs else loss++ ChunkedLossTrainer.__name__ = f"ChunkedLoss{base_cls.__name__}"+ ChunkedLossTrainer.__qualname__ = ChunkedLossTrainer.__name__+ return ChunkedLossTrainer+++def _log_trl_metrics(trainer: Any, mode: str, inputs: Any, step: ChunkedStep) -> None:+ """``entropy``, ``num_tokens`` and ``mean_token_accuracy`` as TRL logs them.++ A trl without the ``_metrics`` store logs none of the three; the run does+ not depend on them.+ """+ metrics = getattr(trainer, "_metrics", None)+ gather = getattr(getattr(trainer, "accelerator", None), "gather_for_metrics", None)+ if metrics is None or gather is None:+ return+ attention_mask = inputs.get("attention_mask")+ if attention_mask is not None:+ entropy = (step.token_entropy * attention_mask).sum() / attention_mask.sum()+ tokens = gather(attention_mask.sum()).sum().item()+ else:+ entropy = step.token_entropy.mean()+ tokens = None+ metrics[mode]["entropy"].append(gather(entropy).mean().item())+ if mode == "train" and tokens is not None and hasattr(trainer, "_total_train_tokens"):+ trainer._total_train_tokens += tokens+ if hasattr(trainer, "_total_train_tokens"):+ metrics[mode]["num_tokens"] = [trainer._total_train_tokens]+ labelled = gather(step.labelled).sum()+ accuracy = (gather(step.correct).sum() / labelled).item() if labelled > 0 else 0.0+ metrics[mode]["mean_token_accuracy"].append(accuracy)diff --git a/tests/fixtures/recipe_config_snapshots.json b/tests/fixtures/recipe_config_snapshots.jsonindex 15d277ea..5d9183a3 100644--- a/tests/fixtures/recipe_config_snapshots.json+++ b/tests/fixtures/recipe_config_snapshots.json@@ -270,6 +270,7 @@"training.stream_expert_layout": "fused","training.stream_layers": false,"training.stream_nf4_scale_cache": false,+ "training.stream_loss_chunk": null,"training.stream_ngram_source": "auto","training.stream_pin": null,"training.stream_read_ahead": 2,diff --git a/tests/test_stream_loss_chunk.py b/tests/test_stream_loss_chunk.pynew file mode 100644index 00000000..91fea73c--- /dev/null+++ b/tests/test_stream_loss_chunk.py@@ -0,0 +1,1336 @@+"""#1693: the output head and the causal-LM loss in token chunks.++The reference throughout is what a step does today: the head over the whole+sequence, then transformers' ``ForCausalLMLoss`` over the full logits. The+chunked form computes the same per-token terms; the order of the final sum and+the shape of each matmul differ, so the comparisons carry a tolerance. It is+``_RTOL`` of the largest value compared, and the tests that can be exact say so.+"""++from __future__ import annotations++import pytest++torch = pytest.importorskip("torch")+pytest.importorskip("transformers")++# Largest difference seen on CPU, relative to the largest gradient: 7.2e-08 in+# float32 (2 x 67 x 101, chunk 16) and 0 in bfloat16 over the same shapes.+_RTOL = 1e-5+++def _full(head, hidden, labels, **kwargs):+ from transformers.loss.loss_utils import ForCausalLMLoss++ return ForCausalLMLoss(head(hidden), labels, head.out_features, **kwargs)+++def _case(dtype=torch.float32, batch=2, seq=67, hidden_size=32, vocab=101, seed=0):+ """A frozen head, the leaf the hidden states are computed from, and labels+ with a masked prompt in the first row and padding at the end of the last."""+ torch.manual_seed(seed)+ head = torch.nn.Linear(hidden_size, vocab, bias=False).to(dtype)+ head.weight.requires_grad_(False)+ leaf = torch.randn(batch, seq, hidden_size)+ labels = torch.randint(0, vocab, (batch, seq))+ labels[0, : seq // 3] = -100+ labels[-1, -5:] = -100+ return head, leaf, labels+++def _both(dtype, chunk, loss_kwargs=None, **shape):+ """(loss, gradient on the leaf) of the full step and of the chunked one."""+ from soup_cli.utils.stream_loss_chunk import chunked_causal_lm_loss++ head, source, labels = _case(dtype, **shape)+ results = []+ for chunked in (False, True):+ leaf = source.clone().requires_grad_(True)+ hidden = (leaf * 1.5).to(dtype) # stands for the decoder+ if chunked:+ loss, _ = chunked_causal_lm_loss(hidden, head, labels, chunk, **(loss_kwargs or {}))+ else:+ loss = _full(head, hidden, labels, **(loss_kwargs or {}))+ loss.backward()+ results.append((loss.detach(), leaf.grad))+ return results+++def biased_module(head, bias):+ """``head`` plus a constant, with the ``out_features`` ``_full`` reads."""++ def forward(hidden):+ return head(hidden) + bias++ forward.out_features = head.out_features+ return forward+++def _close(got, want):+ got, want = got.cpu().double(), want.cpu().double() # MPS has no float64+ return float((got - want).abs().max()) <= _RTOL * float(want.abs().max())+++class TestTheLossAndItsGradient:+ @pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16])+ @pytest.mark.parametrize(+ ("chunk", "shape"),+ [+ (16, {}), # 67 is not a multiple of 16+ (1, {}),+ (67, {}), # one chunk: the whole sequence+ (1000, {}), # a chunk longer than the sequence+ (128, {"batch": 1, "seq": 513, "hidden_size": 64, "vocab": 4099}),+ ],+ )+ def test_they_equal_the_full_logits_step_within_the_tolerance(self, dtype, chunk, shape):+ (full_loss, full_grad), (loss, grad) = _both(dtype, chunk, **shape)++ assert loss.dtype == torch.float32 and loss.shape == ()+ assert _close(loss, full_loss), (float(loss), float(full_loss))+ assert float(full_grad.abs().max()) > 0 # the premise: there is a gradient+ assert _close(grad, full_grad), float((grad - full_grad).abs().max())++ @pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16])+ def test_one_chunk_is_the_full_step_exactly(self, dtype):+ """With nothing to reorder, there is nothing to round differently."""+ (full_loss, full_grad), (loss, grad) = _both(dtype, 67)++ assert torch.equal(loss, full_loss)+ assert torch.equal(grad, full_grad)++ @pytest.mark.parametrize("items", [torch.tensor(431), 431])+ def test_num_items_in_batch_replaces_the_mean(self, items):+ """Under gradient accumulation the trainer passes the token count of+ the whole accumulated batch, and the loss is a sum over it."""+ kwargs = {"num_items_in_batch": items}+ shape = {"batch": 3, "seq": 200, "hidden_size": 64, "vocab": 499}+ (full_loss, full_grad), (loss, grad) = _both(torch.float32, 64, kwargs, **shape)+ (mean_loss, _), _ = _both(torch.float32, 64, **shape)++ assert _close(loss, full_loss) and _close(grad, full_grad)+ assert not _close(loss, mean_loss) # and it is not the mean++ def test_shift_labels_are_used_as_given(self):+ from soup_cli.utils.stream_loss_chunk import chunked_causal_lm_loss++ head, hidden, labels = _case()+ given = torch.roll(labels, 3, dims=1)++ loss, step = chunked_causal_lm_loss(hidden, head, labels, 16, shift_labels=given)++ assert _close(loss, _full(head, hidden, labels, shift_labels=given))+ assert not _close(loss, _full(head, hidden, labels))+ assert int(step.labelled) == int((given != -100).sum())++ def test_the_last_position_is_scored_against_nothing(self):+ """``ForCausalLMLoss`` shifts: position t predicts token t + 1."""+ from soup_cli.utils.stream_loss_chunk import shift_for_next_token++ labels = torch.tensor([[5, 6, -100, 7]])++ assert shift_for_next_token(labels).tolist() == [[6, -100, 7, -100]]++ def test_a_batch_with_no_label_is_nan_as_it_is_today(self):+ from soup_cli.utils.stream_loss_chunk import chunked_causal_lm_loss++ head, hidden, labels = _case()+ labels = torch.full_like(labels, -100)++ loss, step = chunked_causal_lm_loss(hidden, head, labels, 16)++ assert torch.isnan(_full(head, hidden, labels)) and torch.isnan(loss)+ assert int(step.labelled) == 0++ def test_the_gradient_scales_with_what_is_done_to_the_loss(self):+ """The stored gradient is multiplied by the incoming one, not returned+ as it is: a loss scaled by gradient accumulation scales its gradient."""+ from soup_cli.utils.stream_loss_chunk import chunked_causal_lm_loss++ head, source, labels = _case()+ grads = []+ for factor in (1.0, 0.25):+ leaf = source.clone().requires_grad_(True)+ loss, _ = chunked_causal_lm_loss(leaf * 1.5, head, labels, 16)+ (loss * factor).backward()+ grads.append(leaf.grad)++ assert torch.allclose(grads[1], grads[0] * 0.25, rtol=1e-6, atol=0)+++class TestNoFullLogits:+ def _spied(self, head):+ seen = []++ def spy(piece):+ seen.append((tuple(piece.shape), piece.requires_grad, torch.is_grad_enabled()))+ return head(piece)++ return spy, seen++ def test_the_head_never_sees_more_than_a_chunk(self):+ from soup_cli.utils.stream_loss_chunk import chunked_causal_lm_loss++ head, leaf, labels = _case()+ spy, seen = self._spied(head)++ chunked_causal_lm_loss(leaf.requires_grad_(True), spy, labels, 16)++ assert [shape for shape, _, _ in seen] == [(2, 16, 32)] * 4 + [(2, 3, 32)]++ def test_without_gradients_no_graph_is_built(self):+ """The eval loss: the same chunks, and nothing to differentiate."""+ from soup_cli.utils.stream_loss_chunk import chunked_causal_lm_loss++ head, leaf, labels = _case()+ spy, seen = self._spied(head)++ with torch.no_grad():+ loss, _ = chunked_causal_lm_loss(leaf.requires_grad_(True), spy, labels, 16)++ assert loss.grad_fn is None and not loss.requires_grad+ assert _close(loss, _full(head, leaf, labels).detach())+ assert all(not needs_grad and not enabled for _, needs_grad, enabled in seen)++ def test_hidden_states_nothing_trains_through_build_no_graph_either(self):+ from soup_cli.utils.stream_loss_chunk import chunked_causal_lm_loss++ head, leaf, labels = _case()+ spy, seen = self._spied(head)++ loss, _ = chunked_causal_lm_loss(leaf, spy, labels, 16)++ assert not loss.requires_grad+ assert all(not needs_grad for _, needs_grad, _ in seen)++ def test_with_gradients_each_chunk_is_its_own_leaf(self):+ """What keeps a chunk's logits from outliving it: the chunk is cut+ from the graph, and its gradient is taken before the next one runs."""+ from soup_cli.utils.stream_loss_chunk import chunked_causal_lm_loss++ head, leaf, labels = _case()+ pieces = []++ def spy(piece):+ pieces.append(piece)+ return head(piece)++ loss, _ = chunked_causal_lm_loss(leaf.requires_grad_(True) * 1.5, spy, labels, 16)++ assert all(piece.is_leaf and piece.requires_grad for piece in pieces)+ assert type(loss.grad_fn).__name__ == "_ChunkedHeadLossBackward"+++class TestTheMetrics:+ """TRL's ``SFTTrainer.compute_loss`` logs two numbers it reads from+ ``outputs.logits``. These are its formulas, on the full logits."""++ def test_the_token_entropy_is_trls(self):+ from trl.trainer.utils import entropy_from_logits++ from soup_cli.utils.stream_loss_chunk import chunked_causal_lm_loss++ head, hidden, labels = _case()++ _, step = chunked_causal_lm_loss(hidden, head, labels, 16)++ want = entropy_from_logits(head(hidden))+ assert step.token_entropy.shape == (2, 67)+ assert torch.allclose(step.token_entropy, want, rtol=1e-5, atol=1e-6)++ def test_the_accuracy_counts_are_trls(self):+ from soup_cli.utils.stream_loss_chunk import chunked_causal_lm_loss++ head, hidden, labels = _case(vocab=7) # few words, so some are right++ _, step = chunked_causal_lm_loss(hidden, head, labels, 16)++ predictions = head(hidden)[..., :-1, :].argmax(dim=-1)+ shifted = labels[..., 1:]+ mask = shifted != -100+ assert int(step.labelled) == int(mask.sum())+ assert int(step.correct) == int(((predictions == shifted) & mask).sum())+ assert 0 < int(step.correct) < int(step.labelled) # the premise++ @pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16])+ def test_the_token_losses_give_the_rewind_logs_row_losses(self, dtype):+ """``row_losses`` is what the rewind log computes from the logits: the+ mean token cross-entropy of each row, in the logits' own dtype."""+ from soup_cli.trainer.rewind_hf import row_losses+ from soup_cli.utils.stream_loss_chunk import chunked_causal_lm_loss++ head, hidden, labels = _case(dtype)+ hidden = hidden.to(dtype)++ _, step = chunked_causal_lm_loss(hidden, head, labels, 16)++ want_loss, want_tokens = row_losses(head(hidden), labels)+ counts = (labels[:, 1:] != -100).sum(dim=1)+ assert step.token_loss.shape == (2, 67) and step.token_loss.dtype == torch.float32+ assert counts.tolist() == want_tokens+ assert (step.token_loss.sum(dim=1) / counts).tolist() == pytest.approx(want_loss, rel=1e-5)+ assert float(step.token_loss[0, : 67 // 3 - 1].abs().max()) == 0.0 # the masked prompt+ assert float(step.token_loss[:, -1].abs().max()) == 0.0 # the last position++ def test_another_ignore_index_is_ignored_by_the_loss_and_the_accuracy(self):+ """With an ignore index that is also a token id, the head can predict+ it: such a position is neither a loss term nor a correct answer."""+ from soup_cli.utils.stream_loss_chunk import chunked_causal_lm_loss++ head, hidden, labels = _case(vocab=7)+ labels[labels == -100] = 3+ always_three = torch.zeros(7)+ always_three[3] = 50.0++ def biased(piece):+ return head(piece) + always_three++ loss, step = chunked_causal_lm_loss(hidden, biased, labels, 16, ignore_index=3)++ shifted = labels[..., 1:]+ assert int((shifted == 3).sum()) > 0 # the premise+ assert int(step.labelled) == int((shifted != 3).sum())+ assert int(step.correct) == 0+ want = _full(biased_module(head, always_three), hidden, labels, ignore_index=3)+ assert _close(loss, want)+ # And with the head as it is, where a position labelled 3 would cost+ # something if it were scored:+ plain, _ = chunked_causal_lm_loss(hidden, head, labels, 16, ignore_index=3)+ assert _close(plain, _full(head, hidden, labels, ignore_index=3))+ assert not _close(plain, _full(head, hidden, labels))++ def test_the_metrics_carry_no_gradient(self):+ from soup_cli.utils.stream_loss_chunk import chunked_causal_lm_loss++ head, leaf, labels = _case()++ _, step = chunked_causal_lm_loss(leaf.requires_grad_(True), head, labels, 16)++ for value in (step.token_entropy, step.token_loss, step.correct):+ assert not value.requires_grad+++class TestWhatIsRefused:+ @pytest.mark.parametrize("chunk", [0, -4, True, 16.0, "16", None])+ def test_a_chunk_that_is_not_a_positive_integer(self, chunk):+ from soup_cli.utils.stream_loss_chunk import chunked_causal_lm_loss++ head, hidden, labels = _case()++ with pytest.raises(ValueError, match="chunk must be a positive integer"):+ chunked_causal_lm_loss(hidden, head, labels, chunk)++ def test_labels_of_another_length(self):+ from soup_cli.utils.stream_loss_chunk import chunked_causal_lm_loss++ head, hidden, labels = _case()++ with pytest.raises(ValueError, match="do not match hidden states"):+ chunked_causal_lm_loss(hidden, head, labels[:, :-1], 16)+++# ─── The hook on the causal-LM forward ───────────────────────────────────────+++def _tiny_causal_lm(tie=False):+ from transformers import LlamaConfig, LlamaForCausalLM++ torch.manual_seed(7)+ config = LlamaConfig(+ vocab_size=64,+ hidden_size=32,+ intermediate_size=64,+ num_hidden_layers=2,+ num_attention_heads=4,+ num_key_value_heads=2,+ tie_word_embeddings=tie,+ max_position_embeddings=128,+ )+ model = LlamaForCausalLM(config)+ model.get_output_embeddings().weight.requires_grad_(False)+ return model+++def _ids(seq=37):+ generator = torch.Generator().manual_seed(17)+ ids = torch.randint(0, 64, (2, seq), generator=generator)+ labels = ids.clone()+ labels[0, :9] = -100+ labels[1, -4:] = -100+ return ids, labels+++def _step(model, **kwargs):+ """(loss, gradients of the decoder's trainable weights) of one labelled step."""+ ids, labels = _ids()+ model.zero_grad(set_to_none=True)+ outputs = model(input_ids=ids, labels=labels, **kwargs)+ outputs.loss.backward()+ grads = {+ name: param.grad.clone()+ for name, param in model.named_parameters()+ if param.grad is not None+ }+ return outputs, grads+++class TestTheHook:+ @pytest.mark.parametrize("tie", [False, True])+ @pytest.mark.parametrize("kwargs", [{}, {"num_items_in_batch": torch.tensor(50)}])+ def test_a_labelled_forward_gives_the_loss_and_no_logits(self, tie, kwargs):+ from soup_cli.utils.stream_loss_chunk import ChunkedHeadLoss++ model = _tiny_causal_lm(tie)+ plain, plain_grads = _step(model, **kwargs)+ ChunkedHeadLoss(model, 8)++ outputs, grads = _step(model, **kwargs)++ assert outputs.logits is None and "logits" not in outputs.keys()+ assert plain.logits.shape == (2, 37, 64) # the premise+ assert _close(outputs.loss.detach(), plain.loss.detach())+ assert grads.keys() == plain_grads.keys() and grads+ for name, want in plain_grads.items():+ assert _close(grads[name], want), name++ def test_num_items_in_batch_reaches_the_loss(self):+ from soup_cli.utils.stream_loss_chunk import ChunkedHeadLoss++ model = _tiny_causal_lm()+ ChunkedHeadLoss(model, 8)++ mean, _ = _step(model)+ summed, _ = _step(model, num_items_in_batch=torch.tensor(50))++ assert not _close(summed.loss.detach(), mean.loss.detach())++ def test_shift_labels_given_to_the_forward_reach_the_loss(self):+ """Context parallelism hands the model labels it has already shifted."""+ from soup_cli.utils.stream_loss_chunk import ChunkedHeadLoss++ model = _tiny_causal_lm()+ ids, labels = _ids()+ given = torch.roll(labels, 3, dims=1)+ with torch.no_grad():+ want = model(input_ids=ids, labels=labels, shift_labels=given).loss+ unshifted = model(input_ids=ids, labels=labels).loss+ ChunkedHeadLoss(model, 8)+ got = model(input_ids=ids, labels=labels, shift_labels=given).loss++ assert _close(got, want) and not _close(got, unshifted)++ def test_a_forward_without_labels_is_untouched(self):+ from soup_cli.utils.stream_loss_chunk import ChunkedHeadLoss++ model = _tiny_causal_lm()+ ids, _ = _ids()+ with torch.no_grad():+ want = model(input_ids=ids).logits+ hook = ChunkedHeadLoss(model, 8)+ got = model(input_ids=ids)++ assert torch.equal(got.logits, want)+ assert hook.take_step() is None++ def test_the_eval_loss_is_chunked_without_a_graph(self):+ from soup_cli.utils.stream_loss_chunk import ChunkedHeadLoss++ model = _tiny_causal_lm()+ ids, labels = _ids()+ with torch.no_grad():+ want = model(input_ids=ids, labels=labels).loss+ ChunkedHeadLoss(model, 8)+ outputs = model(input_ids=ids, labels=labels)++ assert outputs.logits is None and outputs.loss.grad_fn is None+ assert _close(outputs.loss, want)++ def test_the_step_is_handed_over_once(self):+ from soup_cli.utils.stream_loss_chunk import ChunkedHeadLoss++ model = _tiny_causal_lm()+ hook = ChunkedHeadLoss(model, 8)+ _step(model)++ step = hook.take_step()++ assert step.token_entropy.shape == (2, 37) and int(step.labelled) == 60+ assert hook.take_step() is None++ def test_under_peft_the_hook_sits_on_the_causal_lm(self):+ from peft import LoraConfig, get_peft_model++ from soup_cli.utils.stream_loss_chunk import ChunkedHeadLoss, causal_lm_of++ base = _tiny_causal_lm()+ model = get_peft_model(base, LoraConfig(r=4, target_modules=["q_proj", "v_proj"]))+ ids, labels = _ids()+ plain = model(input_ids=ids, labels=labels).loss.detach()++ assert causal_lm_of(model) is base and causal_lm_of(base) is base+ ChunkedHeadLoss(causal_lm_of(model), 8)+ outputs = model(input_ids=ids, labels=labels)++ assert outputs.logits is None and _close(outputs.loss.detach(), plain)++ def test_remove_puts_both_forwards_back(self):+ from soup_cli.utils.stream_loss_chunk import ChunkedHeadLoss++ model = _tiny_causal_lm()+ head = model.get_output_embeddings()+ ids, labels = _ids()+ hook = ChunkedHeadLoss(model, 8)+ assert "forward" in model.__dict__ and "forward" in head.__dict__ # the premise++ hook.remove()++ assert "forward" not in model.__dict__ and "forward" not in head.__dict__+ assert model(input_ids=ids, labels=labels).logits.shape == (2, 37, 64)++ def test_remove_restores_a_forward_that_was_already_set_on_the_instance(self):+ """accelerate's hooks set ``module.forward`` on the instance; removing+ ours must leave theirs."""+ from soup_cli.utils.stream_loss_chunk import ChunkedHeadLoss++ model = _tiny_causal_lm()+ original = model.forward+ calls = []++ def theirs(*args, **kwargs):+ calls.append(1)+ return original(*args, **kwargs)++ model.forward = theirs+ hook = ChunkedHeadLoss(model, 8)+ _step(model)+ assert calls == [1] # ours wraps theirs++ hook.remove()++ assert model.__dict__["forward"] is theirs++ def test_a_failed_forward_does_not_leave_the_head_held(self):+ from soup_cli.utils.stream_loss_chunk import ChunkedHeadLoss++ model = _tiny_causal_lm()+ ids, labels = _ids()+ ChunkedHeadLoss(model, 8)++ with pytest.raises(Exception): # noqa: B017 -- whatever the model raises+ model(input_ids=ids, labels=labels, attention_mask="not a mask")++ with torch.no_grad():+ assert model(input_ids=ids).logits.shape == (2, 37, 64)++ def test_a_trainable_head_is_refused_with_the_reason(self):+ from soup_cli.utils.stream_loss_chunk import ChunkedHeadLoss++ model = _tiny_causal_lm()+ model.get_output_embeddings().weight.requires_grad_(True)++ with pytest.raises(ValueError, match="the output head must be frozen; trainable: weight"):+ ChunkedHeadLoss(model, 8)+ assert "forward" not in model.__dict__++ def test_a_soft_capped_architecture_is_refused_when_the_hook_is_built(self):+ """Gemma 2's config says so, so the refusal need not wait for a step."""+ from soup_cli.utils.stream_loss_chunk import ChunkedHeadLoss++ model = _tiny_causal_lm()+ model.config.final_logit_softcapping = 30.0++ with pytest.raises(ValueError, match=r"soft-caps its logits.*final_logit_softcapping=30.0"):+ ChunkedHeadLoss(model, 8)+ assert "forward" not in model.__dict__++ def test_a_model_without_an_output_head_is_refused(self):+ from soup_cli.utils.stream_loss_chunk import ChunkedHeadLoss++ class _Headless(torch.nn.Module):+ def get_output_embeddings(self):+ return None++ with pytest.raises(ValueError, match="needs a model with an output head"):+ ChunkedHeadLoss(_Headless(), 8)++ @pytest.mark.parametrize("chunk", [0, True, 8.0])+ def test_a_chunk_that_is_not_a_positive_integer_is_refused(self, chunk):+ from soup_cli.utils.stream_loss_chunk import ChunkedHeadLoss++ with pytest.raises(ValueError, match="chunk must be a positive integer"):+ ChunkedHeadLoss(_tiny_causal_lm(), chunk)++ @pytest.mark.parametrize("after_the_head", ["soft-capped", "head not called"])+ def test_a_forward_that_does_not_return_the_heads_result_is_refused(self, after_the_head):+ """Gemma soft-caps its logits after the head. The loss rebuilt from the+ hidden states would then be the loss of another model, so say no."""+ from transformers.modeling_outputs import CausalLMOutput++ from soup_cli.utils.stream_loss_chunk import ChunkedHeadLoss++ class _Model(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.body = torch.nn.Linear(8, 8)+ self.head = torch.nn.Linear(8, 11, bias=False)+ self.head.weight.requires_grad_(False)++ def get_output_embeddings(self):+ return self.head++ def forward(self, hidden, labels=None):+ if after_the_head == "soft-capped":+ logits = torch.tanh(self.head(self.body(hidden)) / 30.0) * 30.0+ else:+ logits = torch.nn.functional.linear(self.body(hidden), self.head.weight)+ return CausalLMOutput(logits=logits)++ model = _Model()+ ChunkedHeadLoss(model, 4)+ hidden = torch.randn(2, 6, 8)++ with pytest.raises(ValueError, match="does not hand the output head's result back"):+ model(hidden, labels=torch.randint(0, 11, (2, 6)))+ assert model(hidden).logits.shape == (2, 6, 11) # and without labels it still runs+++# ─── What the trainer logs, and the rewind log ───────────────────────────────+++def _fake_trainer(**without):+ from collections import defaultdict+ from types import SimpleNamespace++ trainer = SimpleNamespace(+ _metrics={"train": defaultdict(list), "eval": defaultdict(list)},+ _total_train_tokens=10,+ accelerator=SimpleNamespace(gather_for_metrics=lambda value: value),+ )+ for name in without:+ delattr(trainer, name)+ return trainer+++def _a_step(correct=3, labelled=4):+ from soup_cli.utils.stream_loss_chunk import ChunkedStep++ return ChunkedStep(+ token_entropy=torch.tensor([[1.0, 3.0], [5.0, 7.0]]),+ token_loss=torch.zeros(2, 2),+ correct=torch.tensor(correct),+ labelled=torch.tensor(labelled),+ )+++class TestTheLoggedColumns:+ """``_log_trl_metrics`` by hand, with TRL's formulas: the entropy is the+ mean over the attended positions, the accuracy over the labelled ones."""++ _MASK = {"attention_mask": torch.tensor([[1, 1], [1, 0]])}++ def test_a_training_step(self):+ from soup_cli.utils.stream_loss_chunk import _log_trl_metrics++ trainer = _fake_trainer()++ _log_trl_metrics(trainer, "train", self._MASK, _a_step())++ assert dict(trainer._metrics["train"]) == {+ "entropy": [3.0], # (1 + 3 + 5) / 3: the padded position is left out+ "num_tokens": [13],+ "mean_token_accuracy": [0.75],+ }+ assert trainer._total_train_tokens == 13 and not trainer._metrics["eval"]++ def test_an_eval_step_counts_no_training_tokens(self):+ from soup_cli.utils.stream_loss_chunk import _log_trl_metrics++ trainer = _fake_trainer()++ _log_trl_metrics(trainer, "eval", self._MASK, _a_step())++ assert trainer._total_train_tokens == 10+ assert trainer._metrics["eval"]["num_tokens"] == [10]+ assert trainer._metrics["eval"]["entropy"] == [3.0]++ def test_without_an_attention_mask_the_entropy_is_the_plain_mean(self):+ """Padding-free batches carry ``position_ids`` instead."""+ from soup_cli.utils.stream_loss_chunk import _log_trl_metrics++ trainer = _fake_trainer()++ _log_trl_metrics(trainer, "train", {"position_ids": torch.zeros(2, 2)}, _a_step())++ assert trainer._metrics["train"]["entropy"] == [4.0]+ assert trainer._total_train_tokens == 10++ def test_a_batch_with_no_label_has_accuracy_zero_not_nan(self):+ from soup_cli.utils.stream_loss_chunk import _log_trl_metrics++ trainer = _fake_trainer()++ _log_trl_metrics(trainer, "train", self._MASK, _a_step(correct=0, labelled=0))++ assert trainer._metrics["train"]["mean_token_accuracy"] == [0.0]++ @pytest.mark.parametrize("missing", ["_metrics", "accelerator"])+ def test_a_trl_without_the_metrics_store_logs_nothing(self, missing):+ from soup_cli.utils.stream_loss_chunk import _log_trl_metrics++ trainer = _fake_trainer(**{missing: True})++ _log_trl_metrics(trainer, "train", self._MASK, _a_step())++ assert not getattr(trainer, "_metrics", {"train": {}})["train"]+ assert trainer._total_train_tokens == 10++ def test_the_logged_columns_are_gathered_across_ranks_as_trl_gathers_them(self):+ from soup_cli.utils.stream_loss_chunk import _log_trl_metrics++ trainer = _fake_trainer()+ # Two ranks: this one's value, and a second rank that saw twice as much.+ trainer.accelerator.gather_for_metrics = lambda value: torch.stack([value, value * 2])++ _log_trl_metrics(trainer, "train", self._MASK, _a_step())++ assert trainer._metrics["train"]["entropy"] == [4.5] # mean(3.0, 6.0)+ assert trainer._metrics["train"]["num_tokens"] == [19] # 10 + (3 + 6) attended tokens+ assert trainer._metrics["train"]["mean_token_accuracy"] == [0.75] # (3 + 6) / (4 + 8)+++def test_the_chunked_trainer_class_leaves_other_steps_to_its_base():+ """No hook on the trainer, or a batch without labels: the base class's own+ ``compute_loss`` runs, untouched."""+ from soup_cli.utils.stream_loss_chunk import HOOK_ATTR, make_chunked_loss_trainer_class++ class _Base:+ def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):+ return ("base", return_outputs, num_items_in_batch)++ trainer = make_chunked_loss_trainer_class(_Base)()++ assert type(trainer).__name__ == "ChunkedLoss_Base"+ assert trainer.compute_loss(None, {"labels": 1}, True, 5) == ("base", True, 5)+ setattr(trainer, HOOK_ATTR, object())+ assert trainer.compute_loss(None, {"input_ids": 1}) == ("base", False, None)+++def test_the_rewind_logs_row_losses_from_token_losses():+ """A row's mean over its labelled tokens; a row with none is (0.0, 0)."""+ from soup_cli.trainer.rewind_hf import row_losses_from_token_losses++ token_loss = torch.tensor([[1.0, 2.0, 0.0], [0.0, 0.0, 0.0]])+ # The first label has no position that predicts it, so it is not counted.+ labels = torch.tensor([[7, 5, 6], [-100, -100, -100]])++ assert row_losses_from_token_losses(token_loss, labels) == ([1.5, 0.0], [2, 0])+++# ─── The option ──────────────────────────────────────────────────────────────+++def _cfg(task="sft", **training):+ from soup_cli.config.schema import SoupConfig++ data = {"train": "tests/fixtures/sample_train.jsonl"}+ if task != "sft":+ data["format"] = "dpo"+ return SoupConfig(+ base="test/model", task=task, data=data, training={"batch_size": 1, **training}+ )+++def _refusal(task="sft", **training):+ from pydantic import ValidationError++ with pytest.raises(ValidationError) as excinfo:+ _cfg(task, **training)+ return excinfo.value.errors()[0]["msg"]+++class TestTheOption:+ def test_it_is_off_by_default(self):+ assert _cfg().training.stream_loss_chunk is None+ assert _cfg(stream_layers=True).training.stream_loss_chunk is None++ def test_it_loads_with_layer_streaming_on_sft(self):+ assert _cfg(stream_layers=True, stream_loss_chunk=128).training.stream_loss_chunk == 128++ def test_without_stream_layers_it_is_refused(self):+ message = _refusal(stream_loss_chunk=128)++ assert "training.stream_loss_chunk" in message+ assert "stream_layers is false" in message++ @pytest.mark.parametrize("task", ["dpo", "orpo", "simpo", "kto"])+ def test_a_preference_task_is_refused_with_the_reason(self, task):+ # kto refuses a batch of one before anything else is looked at.+ message = _refusal(task, batch_size=2, stream_layers=True, stream_loss_chunk=128)++ assert f"training.stream_loss_chunk supports task='sft' only; got task='{task}'" in message+ assert "per-token log-probs" in message++ def test_the_raft_loss_is_refused_with_the_reason(self):+ from pydantic import ValidationError++ from soup_cli.config.schema import SoupConfig++ kwargs = {+ "base": "test/model",+ "task": "sft",+ "data": {"train": "tests/fixtures/sample_train.jsonl", "format": "raft"},+ }+ SoupConfig(**kwargs, training={"batch_size": 1, "stream_layers": True}) # the premise+ with pytest.raises(ValidationError) as excinfo:+ SoupConfig(+ **kwargs,+ training={"batch_size": 1, "stream_layers": True, "stream_loss_chunk": 128},+ )+ message = excinfo.value.errors()[0]["msg"]+ assert "cannot be combined with data.format='raft'" in message+ assert "full logits" in message++ def test_use_cut_ce_and_the_chunk_refuse_each_other(self):+ """Two mechanisms over the same loss: refused, with both fields named."""+ from pydantic import ValidationError++ # use_cut_ce alone is refused under streaming (#2023); the pair is+ # refused first, with both fields named.+ with pytest.raises(ValidationError, match="cannot be combined with training.use_cut_ce"):+ _cfg(stream_layers=True, use_cut_ce=True)+ _cfg(stream_layers=True, stream_loss_chunk=128)+ with pytest.raises(ValidationError) as excinfo:+ _cfg(stream_layers=True, stream_loss_chunk=128, use_cut_ce=True)+ message = excinfo.value.errors()[0]["msg"]+ assert "training.stream_loss_chunk and training.use_cut_ce cannot be combined" in message+ assert "Keep stream_loss_chunk and set use_cut_ce=false" in message++ def test_the_rewind_log_stays_on_beside_it(self):+ """``rewind_log`` is on by default: refusing the pair would switch the+ flight recorder off for everyone who sets a chunk."""+ training = _cfg(stream_layers=True, stream_loss_chunk=128).training++ assert training.rewind_log is True++ @pytest.mark.parametrize("chunk", [0, -1, 15, 8193])+ def test_a_chunk_outside_the_bounds_is_refused(self, chunk):+ from pydantic import ValidationError++ with pytest.raises(ValidationError, match="stream_loss_chunk"):+ _cfg(stream_layers=True, stream_loss_chunk=chunk)++ @pytest.mark.parametrize("chunk", [16, 8192])+ def test_the_bounds_themselves_load(self, chunk):+ assert _cfg(stream_layers=True, stream_loss_chunk=chunk).training.stream_loss_chunk == chunk++ @pytest.mark.parametrize("chunk", [True, False])+ def test_a_bool_is_not_a_chunk(self, chunk):+ """``true`` would otherwise load as a chunk of one token."""+ from pydantic import ValidationError++ with pytest.raises(ValidationError, match="must be an int .tokens., not bool"):+ _cfg(stream_layers=True, stream_loss_chunk=chunk)+++# ─── Through the real streamed trainer ───────────────────────────────────────+++def _train(tmp_path, monkeypatch, *, chunk, tie=False, steps=2, **training):+ """``steps`` real sft steps on the tiny streamed Llama, on the device the+ trainer picks (forcing CPU beside an accelerator is a mismatch no user+ has): float32 on CPU, which is what CI runs."""+ import json++ from tests.test_v07204 import _build_streamed_wrapper, _randomise_lora_b++ torch.manual_seed(1234)+ tmp_path.mkdir(parents=True, exist_ok=True)+ if chunk is not None:+ training["stream_loss_chunk"] = chunk+ wrapper, _, _ = _build_streamed_wrapper(+ tmp_path, monkeypatch, task="sft", n_layers=2, tie=tie, **training+ )+ # PEFT starts `lora_B` at zero, which leaves most gradients zero.+ _randomise_lora_b(wrapper.model)+ hook = wrapper._stream_loss_chunk_hook+ head_inputs, forward_kwargs = [], set()+ if hook is not None:+ head, forward = hook._head_forward, hook._forward++ def spy(hidden, *args, **kwargs):+ head_inputs.append(tuple(hidden.shape))+ return head(hidden, *args, **kwargs)++ def forward_spy(*args, **kwargs):+ forward_kwargs.update(key for key in kwargs if key.startswith("_"))+ forward_kwargs.add(("use_cache", kwargs.get("use_cache")))+ return forward(*args, **kwargs)++ hook._head_forward, hook._forward = spy, forward_spy++ from transformers import TrainerCallback++ grads = []++ class _Grads(TrainerCallback):+ def on_pre_optimizer_step(self, args, state, control, model=None, **kwargs):+ grads.append(+ [p.grad.detach().clone() for p in model.parameters() if p.requires_grad]+ )++ wrapper.trainer.add_callback(_Grads())+ wrapper.trainer.args.max_steps = steps+ try:+ wrapper.trainer.train()+ weights = {+ name: param.detach().clone()+ for name, param in wrapper.model.named_parameters()+ if param.requires_grad+ }+ # The rows it trained on, as an evaluation set: `prediction_step` goes+ # through `compute_loss` with the model in eval mode and no gradients.+ evaluation = wrapper.trainer.evaluate(eval_dataset=wrapper.trainer.train_dataset)+ finally:+ wrapper._close_stream_runtime()+ rewind = tmp_path / "out" / "rewind.jsonl"+ history = wrapper.trainer.state.log_history+ return {+ "eval_loss": evaluation["eval_loss"],+ "eval_log": next(entry for entry in history if "eval_loss" in entry),+ "train_tokens": wrapper.trainer._total_train_tokens,+ "forward_kwargs": forward_kwargs,+ "trainer": type(wrapper.trainer).__name__,+ "grads": grads,+ "weights": weights,+ "logs": [entry for entry in wrapper.trainer.state.log_history if "loss" in entry],+ "rewind": [json.loads(line) for line in rewind.read_text().splitlines()]+ if rewind.exists()+ else None,+ "head_inputs": head_inputs,+ }+++class TestThroughTheRealTrainer:+ """Two runs from the same seed, one of them chunked. The sequences here are+ 17 tokens long, so a chunk of 16 splits each of them in two."""++ @pytest.fixture(params=[False, True], ids=["untied", "tied"])+ def arms(self, request, tmp_path, monkeypatch):+ plain = _train(tmp_path / "plain", monkeypatch, chunk=None, tie=request.param)+ chunked = _train(tmp_path / "chunked", monkeypatch, chunk=16, tie=request.param)+ return plain, chunked++ def test_the_head_only_ever_runs_on_a_chunk(self, arms):+ plain, chunked = arms++ assert plain["head_inputs"] == [] # no hook, nothing to spy on+ lengths = [shape[1] for shape in chunked["head_inputs"]]+ assert lengths and max(lengths) == 16+ assert min(lengths) < 16 # the premise: a sequence was really split++ def test_the_gradients_and_the_trained_weights_agree(self, arms):+ plain, chunked = arms++ assert len(plain["grads"]) == len(chunked["grads"]) == 2+ seen_nonzero = False+ for step, (want, got) in enumerate(zip(plain["grads"], chunked["grads"])):+ assert len(want) == len(got)+ for index, (a, b) in enumerate(zip(want, got)):+ if float(a.abs().max()) == 0.0:+ assert float(b.abs().max()) == 0.0, (step, index)+ continue+ seen_nonzero = True+ assert _close(b, a), (step, index)+ assert seen_nonzero, "vacuous: every gradient was zero"+ assert plain["weights"].keys() == chunked["weights"].keys()+ for name, want in plain["weights"].items():+ assert _close(chunked["weights"][name], want), name++ def test_the_log_keeps_trls_columns_with_trls_numbers(self, arms):+ """``entropy``, ``num_tokens`` and ``mean_token_accuracy`` come from+ TRL's own ``compute_loss`` in the plain run and from the chunk loop in+ the other."""+ plain, chunked = arms++ assert len(plain["logs"]) == len(chunked["logs"]) == 2+ for want, got in zip(plain["logs"], chunked["logs"]):+ assert got.keys() == want.keys()+ assert {"entropy", "num_tokens", "mean_token_accuracy"} <= got.keys()+ assert got["num_tokens"] == want["num_tokens"] > 0+ for column in ("loss", "grad_norm", "entropy", "mean_token_accuracy"):+ assert got[column] == pytest.approx(want[column], rel=_RTOL, abs=1e-7), column++ def test_the_rewind_log_records_the_same_rows(self, arms):+ plain, chunked = arms++ want = [entry for entry in plain["rewind"] if entry["kind"] == "batch"]+ got = [entry for entry in chunked["rewind"] if entry["kind"] == "batch"]+ assert len(want) == len(got) == 2+ for a, b in zip(want, got):+ for field in ("step", "rows", "row_tokens"):+ assert b[field] == a[field], field+ assert b["row_loss"] == pytest.approx(a["row_loss"], rel=_RTOL)+ assert b["row_loss"][0] > 0++ def test_the_eval_loss_agrees(self, arms):+ """With no logits in the outputs, the evaluation loop still returns."""+ plain, chunked = arms++ assert chunked["eval_loss"] == pytest.approx(plain["eval_loss"], rel=_RTOL)+ assert plain["eval_loss"] > 0++ def test_evaluation_is_booked_as_evaluation(self, arms):+ """TRL keeps eval metrics apart and counts training tokens only."""+ plain, chunked = arms++ assert chunked["train_tokens"] == plain["train_tokens"] > 0+ assert chunked["eval_log"].keys() == plain["eval_log"].keys()+ for column in ("eval_entropy", "eval_mean_token_accuracy", "eval_num_tokens"):+ assert chunked["eval_log"][column] == pytest.approx(+ plain["eval_log"][column], rel=_RTOL, abs=1e-7+ ), column++ def test_the_model_is_called_as_trl_calls_it(self, arms):+ """``_prediction_loss_only`` is the trainer's own note and is taken out+ before the model is called; the cache is off, as in TRL's step."""+ _, chunked = arms++ assert chunked["forward_kwargs"] == {("use_cache", False)}++ def test_under_gradient_accumulation_with_a_batch_of_two(self, tmp_path, monkeypatch):+ """The trainer then passes ``num_items_in_batch``: the loss is a sum+ over the tokens of the whole accumulated batch, not a mean per call."""+ training = {"batch_size": 2, "gradient_accumulation_steps": 2}+ plain = _train(tmp_path / "plain", monkeypatch, chunk=None, **training)+ chunked = _train(tmp_path / "chunked", monkeypatch, chunk=16, **training)++ assert {shape[0] for shape in chunked["head_inputs"]} == {2}+ assert len(plain["grads"]) == len(chunked["grads"]) == 2+ for want, got in zip(plain["grads"], chunked["grads"]):+ for a, b in zip(want, got):+ assert _close(b, a) or float(a.abs().max()) == 0.0+ for want, got in zip(plain["logs"], chunked["logs"]):+ assert got["num_tokens"] == want["num_tokens"]+ for column in ("loss", "grad_norm", "entropy", "mean_token_accuracy"):+ assert got[column] == pytest.approx(want[column], rel=_RTOL, abs=1e-7), column+ batches = [entry for entry in chunked["rewind"] if entry["kind"] == "batch"]+ assert [len(entry["rows"]) for entry in batches] == [2, 2, 2, 2]++ def test_with_the_rewind_log_off_the_plain_trainer_is_chunked_too(+ self, tmp_path, monkeypatch+ ):+ plain = _train(tmp_path / "plain", monkeypatch, chunk=None, rewind_log=False)+ chunked = _train(tmp_path / "chunked", monkeypatch, chunk=16, rewind_log=False)++ assert plain["trainer"] == "SFTTrainer"+ assert chunked["trainer"] == "ChunkedLossSFTTrainer"+ assert plain["rewind"] is None and chunked["rewind"] is None+ assert max(shape[1] for shape in chunked["head_inputs"]) == 16+ for want, got in zip(plain["grads"], chunked["grads"]):+ for a, b in zip(want, got):+ assert _close(b, a) or float(a.abs().max()) == 0.0+ for want, got in zip(plain["logs"], chunked["logs"]):+ for column in ("loss", "entropy", "mean_token_accuracy", "num_tokens"):+ assert got[column] == pytest.approx(want[column], rel=_RTOL, abs=1e-7), column++ def test_the_trainer_classes(self, arms):+ plain, chunked = arms++ assert plain["trainer"] == "RewindSFTTrainer"+ assert chunked["trainer"] == "RewindChunkedLossSFTTrainer"+++class TestTheHookComesOffAfterTraining:+ """``train()`` takes the hook off when it ends, also when training raised,+ so a labelled forward later in the same process (an eval gate, ``infer``)+ gets the full logits and the trainer takes TRL's own ``compute_loss``."""++ @pytest.mark.parametrize("raises", [False, True])+ def test_train_removes_the_hook(self, tmp_path, monkeypatch, raises):+ from soup_cli.utils.stream_loss_chunk import HOOK_ATTR, causal_lm_of+ from tests.test_v07204 import _build_streamed_wrapper++ wrapper, _, _ = _build_streamed_wrapper(+ tmp_path, monkeypatch, task="sft", n_layers=2, stream_loss_chunk=16+ )+ hook = wrapper._stream_loss_chunk_hook+ causal_lm = causal_lm_of(wrapper.model)+ assert getattr(wrapper.trainer, HOOK_ATTR) is hook # the premise+ assert "forward" in causal_lm.__dict__++ def fake_train(**_kwargs):+ if raises:+ raise RuntimeError("CUDA out of memory")++ wrapper.trainer.train = fake_train+ if raises:+ with pytest.raises(RuntimeError, match="out of memory"):+ wrapper.train()+ else:+ monkeypatch.setattr(wrapper.trainer, "save_model", lambda *_a, **_k: None)+ monkeypatch.setattr(wrapper, "_assert_streamed_adapter_saved", lambda *_a: None)+ wrapper.train()++ assert "forward" not in causal_lm.__dict__+ assert getattr(wrapper.trainer, HOOK_ATTR) is None+ assert wrapper._stream_loss_chunk_hook is None++ def test_a_run_without_the_option_is_untouched(self, tmp_path, monkeypatch):+ from tests.test_v07204 import _build_streamed_wrapper++ wrapper, _, _ = _build_streamed_wrapper(tmp_path, monkeypatch, task="sft", n_layers=2)+ wrapper._remove_stream_loss_chunk_hook() # nothing to remove++ assert wrapper._stream_loss_chunk_hook is None+ wrapper._close_stream_runtime()+++# ─── The pre-flight ──────────────────────────────────────────────────────────++_GB = 1e9+++def _peak(**overrides):+ from soup_cli.utils.layer_stream import estimate_stream_peak_vram++ shape = {+ "layer_bytes": 300_000_000,+ "buffers": 2,+ "extras_bytes": 0,+ "adapter_params": 10_000_000,+ "vocab_size": 128_256,+ "hidden_size": 4096,+ "intermediate_size": 14_336,+ "n_layers": 32,+ "seq_len": 2048,+ "batch_size": 1,+ }+ return estimate_stream_peak_vram(**{**shape, **overrides})+++class TestThePreFlight:+ def test_the_chunk_bytes_are_two_hidden_sized_tensors(self):+ """The gradient the forward fills, and its product with the incoming+ gradient in the backward. bf16 is 2 bytes."""+ from soup_cli.utils.layer_stream import estimate_loss_chunk_bytes++ got = estimate_loss_chunk_bytes(hidden_size=4096, seq_len=2048, batch_size=3)++ assert got == 2 * 4096 * 2048 * 3 * 2+ assert estimate_loss_chunk_bytes(+ hidden_size=4096, seq_len=2048, batch_size=3, dtype="float32"+ ) == 2 * got++ @pytest.mark.parametrize("bad", [{"hidden_size": 0}, {"seq_len": 0}, {"batch_size": -1}])+ def test_the_chunk_bytes_refuse_a_shape_that_is_not_positive(self, bad):+ from soup_cli.utils.layer_stream import estimate_loss_chunk_bytes++ shape = {"hidden_size": 8, "seq_len": 8, "batch_size": 1, **bad}+ with pytest.raises(ValueError, match="must all be positive"):+ estimate_loss_chunk_bytes(**shape)++ def test_the_logits_term_is_charged_on_the_chunk(self):+ """The issue's arithmetic: 14 x vocab x C x batch is 0.23 GB at C = 128+ whatever the sequence length, against 3.68 GB at 2048 tokens."""+ from soup_cli.utils.layer_stream import estimate_logits_bytes, estimate_loss_chunk_bytes++ full = estimate_logits_bytes(vocab_size=128_256, seq_len=2048)+ chunk = estimate_logits_bytes(vocab_size=128_256, seq_len=128)+ kept = estimate_loss_chunk_bytes(hidden_size=4096, seq_len=2048, batch_size=1)++ assert full / _GB == pytest.approx(3.68, abs=0.005)+ assert chunk / _GB == pytest.approx(0.23, abs=0.005)+ assert _peak() - _peak(loss_chunk=128) == full - chunk - kept++ def test_the_saving_no_longer_grows_with_the_sequence(self):+ short = _peak(seq_len=1024) - _peak(seq_len=1024, loss_chunk=128)+ long = _peak(seq_len=2048) - _peak(seq_len=2048, loss_chunk=128)++ assert long > 2 * short > 0++ def test_a_chunk_at_or_above_the_sequence_saves_nothing(self):+ """One chunk is the whole sequence: the full logits are built, and the+ gradient tensor is paid on top. The prediction must not go down."""+ from soup_cli.utils.layer_stream import estimate_loss_chunk_bytes++ kept = estimate_loss_chunk_bytes(hidden_size=4096, seq_len=2048, batch_size=1)++ assert _peak(loss_chunk=2048) == _peak() + kept+ assert _peak(loss_chunk=8192) == _peak() + kept++ def test_unset_it_is_the_prediction_it_was(self):+ assert _peak(loss_chunk=None) == _peak()++ def test_a_calibrated_constant_still_only_raises_it(self):+ base = _peak(loss_chunk=128)++ assert _peak(loss_chunk=128, logits_bytes_per_element=20.0) > base+ assert _peak(loss_chunk=128, logits_bytes_per_element=1.0) == base++ @pytest.mark.parametrize("chunk", [0, -8, True, 12.5])+ def test_a_chunk_that_is_not_a_positive_integer_is_refused(self, chunk):+ with pytest.raises(ValueError, match="loss_chunk must be a positive integer"):+ _peak(loss_chunk=chunk)+++def test_the_pre_flight_of_a_real_setup_charges_the_chunk(tmp_path, monkeypatch):+ """The charge has to reach the pre-flight, not only exist. The tiny model+ (vocabulary 64, hidden 64) is budgeted at ``data.max_length`` = 64 tokens:+ the logits term is 14 x 64 x 64 bytes unchunked and a quarter of that at a+ chunk of 16, where two 64 x 64 bf16 tensors are added."""+ from soup_cli.utils import layer_stream+ from tests.test_v07204 import _build_streamed_wrapper++ estimate = layer_stream.estimate_stream_peak_vram+ seen = {}++ def recording(**kwargs):+ seen["chunk"], seen["bytes"] = kwargs["loss_chunk"], estimate(**kwargs)+ return seen["bytes"]++ monkeypatch.setattr(layer_stream, "estimate_stream_peak_vram", recording)++ def predicted(chunk):+ root = tmp_path / str(chunk)+ root.mkdir()+ training = {} if chunk is None else {"stream_loss_chunk": chunk}+ wrapper, _, _ = _build_streamed_wrapper(root, monkeypatch, task="sft", **training)+ wrapper._close_stream_runtime()+ assert seen.pop("chunk") == chunk+ return seen.pop("bytes")++ saved = predicted(None) - predicted(16)++ assert saved == 14 * 64 * (64 - 16) - 2 * 64 * 64 * 2+++def test_the_pre_flight_panel_says_the_logits_are_chunked(tmp_path, monkeypatch):+ from soup_cli.trainer.stream_setup import StreamingSetupMixin+ from tests.test_v07204 import _build_streamed_wrapper++ budget_lines = StreamingSetupMixin._stream_budget_lines+ seen = []++ def recording(self, *args, **kwargs):+ lines, plan = budget_lines(self, *args, **kwargs)+ seen.append(lines[0])+ return lines, plan++ monkeypatch.setattr(StreamingSetupMixin, "_stream_budget_lines", recording)+ for chunk in (None, 16):+ root = tmp_path / str(chunk)+ root.mkdir()+ training = {} if chunk is None else {"stream_loss_chunk": chunk}+ wrapper, _, _ = _build_streamed_wrapper(root, monkeypatch, task="sft", **training)+ wrapper._close_stream_runtime()++ plain, chunked = seen+ assert plain.endswith("GB)") and "in chunks of" not in plain+ assert chunked.endswith("GB in chunks of 16 tokens)")+++def _panel_line(loss_chunk, seq=2048):+ from soup_cli.trainer.stream_setup import StreamingSetupMixin++ class _Lora:+ r = 8+ target_modules = ["q_proj", "v_proj"]++ class _Train:+ batch_size = 1+ stream_buffers = 2+ stream_vram_probe = False+ stream_vram_override = int(64 * _GB)+ gradient_accumulation_steps = 1+ lora = _Lora()++ _Train.stream_loss_chunk = loss_chunk++ class _Model:+ vocab_size = 128_256+ hidden_size = 4096+ intermediate_size = 14_336++ class _Index:+ n_layers = 32+ total_params = 0++ class _Data:+ max_length = seq++ class _Cfg:+ data = _Data()++ mixin = StreamingSetupMixin()+ mixin.device = "cpu"+ lines, _ = mixin._stream_budget_lines(+ _Cfg(), _Train(), model_config=_Model(), layer_bytes=300_000_000,+ embed_bytes=0, index=_Index(), on_cuda=False,+ )+ return lines[0]+++def test_the_panel_shows_the_logits_of_one_chunk():+ assert _panel_line(None).endswith("(logits 3.68 GB)")+ assert _panel_line(128).endswith("(logits 0.23 GB in chunks of 128 tokens)")+ assert _panel_line(8192).endswith("(logits 3.68 GB in chunks of 8192 tokens)")+++def test_the_chunk_bytes_are_charged_for_every_row_of_the_batch():+ from soup_cli.utils.layer_stream import estimate_logits_bytes, estimate_loss_chunk_bytes++ full = estimate_logits_bytes(vocab_size=128_256, seq_len=2048, batch_size=4)+ chunk = estimate_logits_bytes(vocab_size=128_256, seq_len=128, batch_size=4)+ kept = estimate_loss_chunk_bytes(hidden_size=4096, seq_len=2048, batch_size=4)++ assert _peak(batch_size=4) - _peak(batch_size=4, loss_chunk=128) == full - chunk - kept+++def test_the_hook_is_on_the_model_before_the_vram_probe_measures_a_step(tmp_path, monkeypatch):+ from soup_cli.trainer.stream_setup import StreamingSetupMixin+ from tests.test_v07204 import _build_streamed_wrapper++ seen = []++ def probe(self, model, plan):+ seen.append(self._stream_loss_chunk_hook is not None)++ budget = StreamingSetupMixin._stream_budget_lines+ # Off CUDA the budget returns no probe plan; hand it one so the probe step is reached.+ monkeypatch.setattr(+ StreamingSetupMixin,+ "_stream_budget_lines",+ lambda self, *args, **kwargs: (budget(self, *args, **kwargs)[0], object()),+ )+ monkeypatch.setattr(StreamingSetupMixin, "_run_stream_vram_probe", probe)++ wrapper, _, _ = _build_streamed_wrapper(tmp_path, monkeypatch, task="sft", stream_loss_chunk=16)+ wrapper._close_stream_runtime()++ assert seen == [True]+++def test_a_hook_that_cannot_be_built_releases_the_streamed_runtime(tmp_path, monkeypatch):+ """The hook is built after the runtime and before training's cleanup+ context starts, so a refusal there closes the runtime itself."""+ from soup_cli.trainer.stream_setup import StreamingSetupMixin+ from soup_cli.utils import stream_loss_chunk+ from tests.test_v07204 import _build_streamed_wrapper++ closes = []+ real_close = StreamingSetupMixin._close_stream_runtime++ def counting_close(self):+ closes.append(getattr(self, "_stream_runtime", None) is not None)+ return real_close(self)++ def refuse(*_args, **_kwargs):+ raise ValueError("no output head to chunk")++ monkeypatch.setattr(StreamingSetupMixin, "_close_stream_runtime", counting_close)+ monkeypatch.setattr(stream_loss_chunk, "ChunkedHeadLoss", refuse)++ with pytest.raises(ValueError, match="no output head to chunk"):+ _build_streamed_wrapper(tmp_path, monkeypatch, task="sft", stream_loss_chunk=16)++ assert closes == [True]