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
docs: drop past-release promises and state the untied DPO/KTO head copy (#1353) (#1402)
Maxidff53101a754
diff --git a/changelog.d/0.75.1/1402.fixed.md b/changelog.d/0.75.1/1402.fixed.mdnew file mode 100644index 00000000..3ef15d64--- /dev/null+++ b/changelog.d/0.75.1/1402.fixed.md@@ -0,0 +1 @@+- The refusal for `training.citation_faithful` on a task other than `sft`/`pretrain` no longer says its span-mask runtime "ships in v0.62.1"; that runtime has run in the SFT trainer since v0.71.10. The streaming docs now state that `dpo` and `kto` hold a copy of an untied output head per step, which the VRAM pre-flight already charges (#1353 by @maximilianfeix in #1402).diff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.mdindex a50c9b3b..b483c9e1 100644--- a/docs/performance-and-quantization.md+++ b/docs/performance-and-quantization.md@@ -509,7 +509,7 @@ Correctness is not a tradeoff here either: a streamed NF4 run is **bit-exact** aThe 3B NF4-vs-bf16 rows differ by 1.85×, but attribute that to **pinning, not arithmetic** — see point 2 above. The two rows also come from different sessions, and this card's boost clock varies ~13% between sessions, so treat the factor as indicative and the mechanism as the claim.-The 3.32 GB 8B row above predates large-layer streaming: its untied, unquantised `embed_tokens` + `lm_head` both stayed resident and occupied 2.10 GB. Current code writes them as separate large-layer shards and reuses one device slot sized to the larger matrix, so an equally shaped untied pair should reclaim one matrix while a tied model keeps the same one-matrix requirement. CPU CI pins bit-exact logits for both controls. The updated CUDA peak remains to be measured on the reference RTX 3050; the historical 3.32 GB figure is not relabelled as a new measurement.+The 3.32 GB 8B row above predates large-layer streaming: its untied, unquantised `embed_tokens` + `lm_head` both stayed resident and occupied 2.10 GB. Current code writes them as separate large-layer shards and reuses one device slot sized to the larger matrix, so an equally shaped untied pair should reclaim one matrix while a tied model keeps the same one-matrix requirement. Under `dpo` and `kto` that saving is spent again: the output head's forward keeps a private copy of the matrix for its backward every step (about 1.05 GB for Llama-3.1-8B in bf16, charged by the pre-flight, #1049). CPU CI pins bit-exact logits for both controls. The updated CUDA peak remains to be measured on the reference RTX 3050; the historical 3.32 GB figure is not relabelled as a new measurement.**Honest scope:**- **RAM tier + disk overflow (v0.72.3).** `stream_source: auto` picks RAM when the store fits both dynamic free-RAM headroom and a physical-host ceiling, falls back to NVMe disk when not; SATA/HDD rejected. Correctness verified. **The read is off the compute thread**: a background reader parses each shard's header itself (no memory map) and stages `training.stream_read_ahead` layers in host RAM (page-locked where the box allows — see `stream_pin` below), so the GPU is fed while the next layer is still arriving. **Measured cold and warm against a same-day control of the source it replaces** (RTX 5070 Laptop, 2026-09-14, [record](../benchmarks/gate-971-async-nvme-source.md)).@@ -741,7 +741,10 @@ pre-flight, same refusals. The interesting part is DPO's reference model.**DPO compares the model being trained against a frozen reference.** Implemented as asecond model instance that doubles memory and there is no point streaming at all. Soupinstead uses *the same streamed base with its LoRA adapters switched off*, so the-reference costs no extra weights. Measured on an RTX 3050 4 GB with a 730 MB model:+reference costs no extra weights. On an untied checkpoint, `dpo` and `kto` also hold+one copy of the output head per step (about 1.05 GB for Llama-3.1-8B in bf16), which+the VRAM pre-flight charges (#1049); tied checkpoints and `sft`/`orpo`/`simpo` pay+nothing. Measured on an RTX 3050 4 GB with a 730 MB model:| arm | peak VRAM | vs SFT ||---|---|---|@@ -756,12 +759,14 @@ byte-identical between the SFT and DPO arms.**KTO is not reference-free**, however it is usually described — it selects a referencethe same way DPO does, so it gets the same treatment. ORPO and SimPO genuinely arereference-free. All four are verified **bit-exact** against a resident run of the same-loss.+loss on a tied checkpoint; on an untied one, that check covers `dpo`+(`tests/test_issue1049_untied_streamed_preference.py`).**The cost is time, not memory.** DPO runs the layer stack three times per step (policyforward, reference forward, checkpoint recompute) against SFT's two — measured **1.52×**-the layer reads on a 24-layer model. Streaming makes the reference free in memory; it-does not make it free.+the layer reads on a 24-layer model. Streaming adds no second copy of the weights for the+reference (on an untied checkpoint `dpo` and `kto` still hold one output-head copy, see+above); it does not make the reference free.**Two things to know before you configure it:**diff --git a/docs/training.md b/docs/training.mdindex 6156e040..93b33a54 100644--- a/docs/training.md+++ b/docs/training.md@@ -9,7 +9,8 @@> VRAM is bounded by one layer instead of the whole model. Add `quantization: 4bit` and an> 8B base fits a 4 GB card. Works for `sft` and, from v0.72.4, for `dpo` / `orpo` /> `simpo` / `kto` — DPO's reference model is the same streamed base with its adapters-> switched off, so it costs no extra weights — see+> switched off, so it needs no second copy of the model (on an untied checkpoint `dpo` and+> `kto` still hold one copy of the output head per step) — see> [Layer Streaming](performance-and-quantization.md#layer-streaming-beta-v0720-nf4-v0722-disk--wider-archs-v0723-preference-losses-v0724).**Contents:**diff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.pyindex 1568de14..a2eb86b9 100644--- a/src/soup_cli/config/schema.py+++ b/src/soup_cli/config/schema.py@@ -1603,7 +1603,7 @@ class TrainingConfig(BaseModel):return value# v0.50.0 Part A — GRPO objective variants (unsloth + axolotl parity).- # Schema-only in v0.50.0; live loss kernels wired in v0.50.1.+ # The trainer applies the variant losses (trainer/grpo.py).grpo_variant: Optional[Literal["standard", "gspo", "dapo", "dr_grpo", "bnpo", "two_sided", "rft"]] = Field(@@ -1686,7 +1686,7 @@ class TrainingConfig(BaseModel):return validate_rollout_func(value)# v0.50.0 Part D — GRPO stability / efficiency knobs (axolotl + unsloth).- # All schema-only in v0.50.0; live trainer callbacks wired in v0.50.1.+ # The trainer wires these as callbacks (trainer/grpo.py).ref_model_ema_alpha: Optional[float] = Field(default=None,gt=0.0,@@ -2578,9 +2578,9 @@ class TrainingConfig(BaseModel):@field_validator("minillm_pretrain_anchor_path")@classmethoddef _validate_minillm_anchor_path(cls, v):- """v0.70.0 Part C — shape-only path validation. Cwd containment- deferred to v0.70.1 runtime hook (matches v0.69.0 build_dag /- magpie base_model policy).+ """v0.70.0 Part C — shape-only path validation. Cwd containment is+ checked when the trainer loads the anchor (``utils/minillm.py``,+ matching the build_dag / magpie base_model policy)."""if v is None:return None@@ -4216,10 +4216,8 @@ class TrainingConfig(BaseModel):return validate_unlearn_alpha(v)# ---- v0.62.0 Part B — RA-DIT (Retrieval-Augmented Dual Instruction- # Tuning, Meta 2023). Schema-only: a YAML can declare ``ra_dit_stage``- # so a recipe locks the right pairing; live two-stage orchestration- # ships in v0.62.1 (mirrors the v0.50.0 / v0.61.0 stub-then-live- # pattern).+ # Tuning, Meta 2023). A YAML declares ``ra_dit_stage`` so a recipe locks+ # the right pairing; ``soup ra-dit`` runs the two stages.ra_dit_stage: Optional[Literal["retriever", "generator"]] = Field(default=None,description=(@@ -5211,10 +5209,8 @@ class SoupConfig(BaseModel):transformers/unsloth backends. MLX rejected with distinct message(matches v0.34.0 review-fix policy of distinct error reasons).- Live loss kernels for non-standard variants are deferred to v0.50.1;- a yellow advisory at trainer construction time will name the- deferred wiring (mirrors v0.40.0 Part D ``NotImplementedError``- stub-then-live pattern).+ The trainer applies the non-standard variant losses+ (``trainer/grpo.py``)."""if self.training.grpo_variant is None:return self@@ -5259,8 +5255,8 @@ class SoupConfig(BaseModel):"""v0.50.0 Part E — ``task='prm'`` schema gate.Delegates to :func:`prm.validate_prm_compat` so the rules are- single-source-of-truth. Live PRM trainer wrapper is deferred to- v0.50.1.+ single-source-of-truth. Training runs through+ ``trainer/prm.py``'s ``PRMTrainerWrapper``."""if self.task != "prm":return self@@ -5642,8 +5638,8 @@ class SoupConfig(BaseModel):Mirrors v0.50.0 ``_validate_grpo_stability_task_gate`` policy.``reasoning_effort`` only makes sense on SFT-family training- (sft / pretrain / distill / classifier-family) because the live- formatter (v0.52.1) will inject a system-prefix token. The other+ (sft / pretrain / distill / classifier-family) because the SFT+ formatter injects it as a system-prefix token. The othertasks (DPO / GRPO / KTO / ORPO / SimPO / IPO / BCO / preference /PPO / reward_model / embedding / prm / tts) do not consume it.@@ -7028,7 +7024,7 @@ class SoupConfig(BaseModel):- ``unlearn_method`` is rejected on any other task (silent no-opfootgun — mirrors v0.52.0 distill / classifier task-gate).- ``data.forget_set`` is present when ``task='unlearn'``.- - Backend != mlx (live wiring deferred to v0.61.1).+ - Backend != mlx (there is no MLX unlearning path).- ``loraplus_lr_ratio`` is refused (#745): unlearn drives its own``torch.optim.AdamW`` loop, not a ``Trainer``, so there is nothingfor ``attach_loraplus_optimizer`` to attach to and LoRA+ would be@@ -7203,8 +7199,8 @@ class SoupConfig(BaseModel):RAFT row carries the doc references; other formats can't supplyground-truth citation IDs).* ``citation_faithful=True`` requires ``task in {sft, pretrain}``- (the span-mask runtime that v0.62.1 will ship only makes sense- for the SFT family; mirrors v0.52.0 distill / classifier+ (the span-mask runtime only makes sense for the SFT family;+ mirrors v0.52.0 distill / classifiertask-gate policy — review M3 fix).* ``citation_style`` set without ``citation_faithful=True`` is asilent-no-op footgun — rejected (mirrors v0.61.0 unlearn_alpha /@@ -7238,8 +7234,8 @@ class SoupConfig(BaseModel):raise ValueError("training.citation_faithful=true requires "f"task in {{sft, pretrain}}; got task={self.task!r}. "- "Citation-faithful FT is an SFT-family feature; the "- "live span-mask runtime ships in v0.62.1."+ "Citation-faithful FT is an SFT-family feature: its "+ "span-mask runtime runs in the SFT trainer.")return self@@ -7716,8 +7712,8 @@ class SoupConfig(BaseModel):# DEPRECATED (v0.39.0 Part E) — these inline templates are kept for back-compat.# The canonical source is `soup_cli/templates/*.yaml` with `manifest.json`.# Both sources are asserted equal in tests/test_templates_yaml.py — when editing-# a template, update both. Planned removal: v0.41.0+ once external consumers-# have migrated to the YAML registry.+# a template, update both. It is kept until external consumers have migrated+# to the YAML registry.TEMPLATES: dict[str, str] = {"chat": """# Soup template: Chat Assistant# Fine-tune a model for conversational chatdiff --git a/src/soup_cli/data/loss_mask.py b/src/soup_cli/data/loss_mask.pyindex 1655b66f..e4843709 100644--- a/src/soup_cli/data/loss_mask.py+++ b/src/soup_cli/data/loss_mask.py@@ -502,6 +502,11 @@ def post_processor_leading_bos_count(tokenizer: Any) -> Optional[int]:BOS is the post-processor's, independent of anything a chat template renders.``None`` means it could not be measured, and the caller falls back to:func:`strip_doubled_leading_bos`.++ That measures a ``TemplateProcessing``-style post-processor, which adds the+ same specials to every input; a content-conditional post-processor could+ mis-measure it, and the ``None`` fallback covers the probe failing, not the+ probe lying."""bos_id = _resolve_bos_token_id(tokenizer)if bos_id is None:diff --git a/src/soup_cli/utils/layer_stream_runtime.py b/src/soup_cli/utils/layer_stream_runtime.pyindex db7f4fc3..b1bbc159 100644--- a/src/soup_cli/utils/layer_stream_runtime.py+++ b/src/soup_cli/utils/layer_stream_runtime.py@@ -1591,7 +1591,7 @@ def _build_streamed_large_layer_class():loss. SFT, ORPO and SimPO run one forward per step, and nothingrefills the slot between it and its backward, so they never need thecopy (``refill_before_backward``, set by the trainer). The slot must- be SHARED: a tied checkpoint streams one key, so its buffer is never+ be SHARED: a tied checkpoint streams no large key, so its buffer is neverrefilled within a step. And the weight must be one autograd can save,which an embedding's is not -- ``embedding_backward`` works from theindices and the vocabulary size, never from the weight values, sodiff --git a/src/soup_cli/utils/ra_dit.py b/src/soup_cli/utils/ra_dit.pyindex 6782621d..e7685600 100644--- a/src/soup_cli/utils/ra_dit.py+++ b/src/soup_cli/utils/ra_dit.py@@ -8,12 +8,9 @@ Meta 2023 recipe. Two-stage:* ``generator`` — RAFT-style SFT on the query + golden_doc + distractorbundle (uses v0.62.0 Part A ``data.format='raft'``).-Schema-only release. Both stages share the existing trainer wrappers;-v0.62.0 ships the ``ra_dit_stage`` schema field + cross-validator so a-``soup.yaml`` can lock both stages in a hub-shareable recipe. Live-orchestration that chains the two stages in a single ``soup train`` call-is deferred to v0.62.1 (mirrors the v0.50.0 / v0.52.0 / v0.61.0-stub-then-live pattern).+Both stages share the existing trainer wrappers. The ``ra_dit_stage``+schema field + cross-validator let a ``soup.yaml`` lock both stages in a+hub-shareable recipe, and ``soup ra-dit`` chains the two stages."""from __future__ import annotationsdiff --git a/src/soup_cli/utils/unlearning.py b/src/soup_cli/utils/unlearning.pyindex fa086f85..1e565cce 100644--- a/src/soup_cli/utils/unlearning.py+++ b/src/soup_cli/utils/unlearning.py@@ -173,8 +173,8 @@ def validate_unlearn_compat(*, task: str, backend: str) -> None:)if backend == "mlx":raise ValueError(- "task='unlearn' is not supported on backend=mlx in v0.61.0 "- "(deferred to v0.61.1)"+ "task='unlearn' is not supported on backend=mlx: there is no MLX "+ "unlearning path. Use backend: transformers.")diff --git a/tests/test_issue1049_untied_streamed_preference.py b/tests/test_issue1049_untied_streamed_preference.pyindex 4e60f96d..83488ba0 100644--- a/tests/test_issue1049_untied_streamed_preference.py+++ b/tests/test_issue1049_untied_streamed_preference.py@@ -8,7 +8,7 @@ loss refilled those bytes in place and the policy backward died withinplace operation``.The streaming preference tests all used TIED fixtures, and a tied checkpoint-streams one key, so nothing here was covered. Llama-3-8B-class checkpoints are+streams no large key, so nothing here was covered. Llama-3-8B-class checkpoints areuntied, which is the common real-world shape."""@@ -170,7 +170,7 @@ def test_the_private_copy_is_taken_only_when_it_is_needed():)assert torch.equal(projection, untied.buffer), "the copy must be the same bytes"assert projection_tied.data_ptr() == tied.buffer.data_ptr(), (- "a tied checkpoint streams one key, so its slot is never refilled: no copy"+ "a tied checkpoint streams no large key, so its slot is never refilled: no copy")assert projection_nograd.data_ptr() == untied.buffer.data_ptr(), ("no backward can follow under no_grad, so no copy"diff --git a/tests/test_issue823_stale_feature_descriptions.py b/tests/test_issue823_stale_feature_descriptions.pyindex 329d4b04..3cda5d8e 100644--- a/tests/test_issue823_stale_feature_descriptions.py+++ b/tests/test_issue823_stale_feature_descriptions.py@@ -100,6 +100,34 @@ def _schema_descriptions(path: Path = SCHEMA_PATH) -> list[tuple[str, int, str]]return descriptions+def _constant_text(node: ast.AST) -> str | None:+ """The literal text of a string, f-string included (its constant parts)."""+ if isinstance(node, ast.Constant) and isinstance(node.value, str):+ return node.value+ if isinstance(node, ast.JoinedStr):+ return "".join(+ part.value+ for part in node.values+ if isinstance(part, ast.Constant) and isinstance(part.value, str)+ )+ return None+++def _schema_raise_messages(path: Path = SCHEMA_PATH) -> list[tuple[int, str]]:+ """Every string handed to an exception raised in ``schema.py`` (#1353):+ these reach the user when a config is refused, same as a description."""+ tree = ast.parse(path.read_text(encoding="utf-8"))+ messages: list[tuple[int, str]] = []+ for node in ast.walk(tree):+ if not isinstance(node, ast.Raise) or not isinstance(node.exc, ast.Call):+ continue+ for arg in node.exc.args:+ text = _constant_text(arg)+ if text:+ messages.append((node.lineno, text))+ return messages++def _cli_help_strings() -> list[tuple[Path, int, str]]:strings: list[tuple[Path, int, str]] = []for path in COMMAND_PATHS:@@ -135,6 +163,31 @@ def test_schema_descriptions_have_no_expired_release_promises() -> None:assert offenders == []+def test_schema_raise_messages_have_no_expired_release_promises() -> None:+ messages = _schema_raise_messages()+ assert len(messages) >= 300+ offenders = [+ f"schema.py:{line}: {text}"+ for line, text in messages+ if _has_expired_version_promise(text)+ ]+ assert offenders == []+++def test_the_raise_scanner_reads_f_strings(tmp_path: Path) -> None:+ sample = tmp_path / "schema.py"+ sample.write_text(+ 'def check(task):\n'+ ' raise ValueError(f"got {task!r}; " "the runtime ships in v0.62.1.")\n',+ encoding="utf-8",+ )++ ((line, text),) = _schema_raise_messages(sample)++ assert line == 2+ assert _has_expired_version_promise(text)++def test_cli_help_has_no_expired_promises_or_internal_phase_labels() -> None:help_strings = _cli_help_strings()assert len(help_strings) >= 1_000diff --git a/tests/test_issue975_backward_tail_embed_prefetch.py b/tests/test_issue975_backward_tail_embed_prefetch.pyindex db06077e..ac1d4ec1 100644--- a/tests/test_issue975_backward_tail_embed_prefetch.py+++ b/tests/test_issue975_backward_tail_embed_prefetch.py@@ -17,8 +17,8 @@ unconditionally at the next step's start as a fallback for step 0 and for anybackward that never reaches layer 0; on the hot path that call now finds theslot already holding what it asked for and is a same-owner no-op.-This only matters for an UNTIED checkpoint: a tied model streams one key for-both `embed_tokens` and `lm_head`, so `LargeLayerBufferPool.owner` never+This only matters for an UNTIED checkpoint: a tied model streams no large key+for `embed_tokens` / `lm_head`, so `LargeLayerBufferPool.owner` neverchanges across a whole run and the ping-pong this fix targets does not exist.`_build_streamed_wrapper` in `test_v07204.py` has taken `tie` since #1061; thisfile predates that and keeps its own small helper below rather than switching.