Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
fix(stream): refuse CCE absent from streamed setup (#2023)
Nurkhan Esenbek90ca760b96c7
diff --git a/changelog.d/0.76.0/2023.fixed.md b/changelog.d/0.76.0/2023.fixed.mdnew file mode 100644index 00000000..dd04d131--- /dev/null+++ b/changelog.d/0.76.0/2023.fixed.md@@ -0,0 +1 @@+- Refuse `training.stream_layers` with `training.use_cut_ce` because streamed setup never installs the resident CCE patch; preserve the conservative full-logits budget. (#1206 by @kok-o in #2023)diff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.mdindex 5fc5b928..7dcf7545 100644--- a/docs/performance-and-quantization.md+++ b/docs/performance-and-quantization.md@@ -285,7 +285,7 @@ training:use_cut_ce: true # Patches the CE kernel before model load```-Architecture detection reads `config.model_type` first, so a local checkpoint directory (`soup merge`/`soup shrink`/`soup draft distill` output) is patched the same as a hub id; a name-based match on the last path component (`meta-llama/Llama-3.1-8B` → llama patcher) is the fallback when config resolution is unavailable. Saves 8-24 GB VRAM at common batch × seq shapes. Not compatible with unsloth (own CE kernel) or mlx. Wired across every transformer-backend trainer (SFT, DPO, GRPO, KTO, ORPO, SimPO, IPO, PPO, Reward-Model, Embedding, Pretrain) — note that PPO has its own forward loop so cut_ce no-ops gracefully there.+Architecture detection reads `config.model_type` first, so a local checkpoint directory (`soup merge`/`soup shrink`/`soup draft distill` output) is patched the same as a hub id; a name-based match on the last path component (`meta-llama/Llama-3.1-8B` → llama patcher) is the fallback when config resolution is unavailable. Saves 8-24 GB VRAM at common batch × seq shapes. Not compatible with unsloth (own CE kernel), mlx or layer streaming. Wired across every transformer-backend trainer (SFT, DPO, GRPO, KTO, ORPO, SimPO, IPO, PPO, Reward-Model, Embedding, Pretrain) — note that PPO has its own forward loop so cut_ce no-ops gracefully there.## Gradient Checkpointing Tiers@@ -736,6 +736,7 @@ prints this advice when it sees you accumulating.- `lora.use_dora` / `lora.use_vera` / `lora.init_strategy` other than `random` → these initialise from the real base weight, which is on the meta device under streaming- `moe_expert_quant` → expert quantization runs only in the resident model-construction path and would otherwise be silently ignored- `unfrozen_parameters`, `lisa_enabled`, `packing`, `multipack`, `use_fsdp2_compile`, `train_router_only`, `expand_layers` → each independently rewrites or re-freezes the same layers+- `use_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_disk_kind` / `stream_pin` set while `stream_layers: false` → a footgun, refused- `stream_nf4_scale_cache` without `quantization: 4bit` and double quantization → refused: there are no nested NF4 scales to cachediff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.pyindex d7abfac0..c353733d 100644--- a/src/soup_cli/config/schema.py+++ b/src/soup_cli/config/schema.py@@ -6951,6 +6951,13 @@ class SoupConfig(BaseModel):f"initialise the adapter from an SVD of the base weight, which "f"is on the meta device under streaming.")+ if tcfg.use_cut_ce:+ raise ValueError(+ "training.stream_layers cannot be combined with training.use_cut_ce: "+ "the streamed setup never installs the resident Cut Cross-Entropy patch. "+ "Set use_cut_ce=false to stream with the conservative logits budget, "+ "or disable stream_layers to use resident CCE."+ )conflicts = []if tcfg.unfrozen_parameters:conflicts.append("unfrozen_parameters")@@ -6984,8 +6991,8 @@ class SoupConfig(BaseModel):# set there either, so `use_liger_kernel` misses `TrainingArguments` as# well. These are the switches a user reaches for when a streamed run will# not fit, so silently dropping them is the worst outcome: refuse until- # each is wired and shown to engage on a streamed model. (`use_cut_ce` has- # the same shape and is #1206.)+ # each is wired and shown to engage on a streamed model.+ # CCE is refused separately above (#1206).if tcfg.use_liger:conflicts.append("use_liger")if tcfg.use_flash_attn:diff --git a/tests/test_issue1692_stream_layers_kernel_flags.py b/tests/test_issue1692_stream_layers_kernel_flags.pyindex f519361d..da1ba332 100644--- a/tests/test_issue1692_stream_layers_kernel_flags.py+++ b/tests/test_issue1692_stream_layers_kernel_flags.py@@ -23,8 +23,8 @@ the claim itself, so a reader moving is caught where it matters.These are the switches a user reaches for when a streamed run will not fit, so droppingthem silently is the worst outcome: the refusal is the small step until each is wired-and shown to engage on a streamed model. ``use_cut_ce`` has the same shape and is #1206,-deliberately left loading here.+and shown to engage on a streamed model. ``use_cut_ce`` is separately refused by+#1206 after a real streamed-model probe."""from __future__ import annotations@@ -163,9 +163,9 @@ class TestWhatMustKeepLoading:def test_the_switch_alone_on_a_resident_stream_free_config_loads(self, field: str) -> None:assert getattr(_cfg(**{field: True}).training, field) is True- def test_use_cut_ce_still_loads_under_streaming(self) -> None:- """SCOPE. #1206 owns `use_cut_ce`; this PR must not quietly widen into it."""- assert _cfg(stream_layers=True, use_cut_ce=True).training.use_cut_ce is True+ def test_disabled_cut_ce_still_loads_under_streaming(self) -> None:+ """A streamed run with CCE disabled still reaches its supported setup."""+ assert _cfg(stream_layers=True, use_cut_ce=False).training.use_cut_ce is Falseclass TestTheStreamedPreferencePathsAreAlreadyCovered:diff --git a/tests/test_stream_cut_ce.py b/tests/test_stream_cut_ce.pynew file mode 100644index 00000000..0b9070e0--- /dev/null+++ b/tests/test_stream_cut_ce.py@@ -0,0 +1,120 @@+"""Streaming does not install the resident CCE patch; refuse the dead switch."""++from __future__ import annotations++from types import SimpleNamespace++import pytest++from soup_cli.config.loader import load_config_from_string+from soup_cli.config.schema import SoupConfig+++def _config(**training) -> SoupConfig:+ return SoupConfig(+ base="local/model", data={"train": "train.jsonl"},+ training={"batch_size": 1, "quantization": "none", **training},+ )++[email protected]("task", ["sft", "dpo", "kto", "orpo", "simpo"])+def test_streamed_cce_refused(task):+ with pytest.raises(ValueError, match="stream_layers.*use_cut_ce"):+ SoupConfig(+ base="local/model", task=task, data={"train": "train.jsonl"},+ training={"batch_size": 2, "stream_layers": True, "use_cut_ce": True},+ )+++def test_public_yaml_refuses_streamed_cce():+ with pytest.raises(ValueError, match="stream_layers.*use_cut_ce"):+ load_config_from_string(+ "base: local/model\ndata:\n train: train.jsonl\ntraining:\n"+ " batch_size: 1\n stream_layers: true\n use_cut_ce: true\n"+ )+++def test_config_file_diagnostic(tmp_path, capsys):+ from soup_cli.config.loader import load_config+ from tests.conftest import strip_ansi++ path = tmp_path / "soup.yaml"+ path.write_text(+ "base: local/model\ndata:\n train: train.jsonl\ntraining:\n"+ " batch_size: 1\n stream_layers: true\n use_cut_ce: true\n",+ encoding="utf-8",+ )+ with pytest.raises(SystemExit) as exc:+ load_config(path)+ assert exc.value.code == 1+ output = strip_ansi(capsys.readouterr().out)+ assert "stream_layers" in output and "use_cut_ce" in output+ assert "resident" in output+++def test_supported_controls():+ assert _config(stream_layers=True).training.stream_layers+ assert not _config(stream_layers=True, use_cut_ce=False).training.use_cut_ce+ assert _config(use_cut_ce=True).training.use_cut_ce+++def test_real_streamed_setup_uses_ordinary_ce(tmp_path, monkeypatch):+ """CPU model, real sharding/setup/forward/backward, no CCE or model download.++ Bypass the new schema gate deliberately to inspect the formerly accepted+ implementation. Only tokenizer loading and the cache destination are isolated;+ model construction, shards, streaming and the loss are real.+ """+ import torch+ import torch.nn.functional as functional+ from transformers import LlamaConfig, LlamaForCausalLM++ from soup_cli.trainer.stream_setup import StreamingSetupMixin++ torch.manual_seed(7)+ model_config = LlamaConfig(+ vocab_size=32, hidden_size=16, intermediate_size=32, num_hidden_layers=2,+ num_attention_heads=2, num_key_value_heads=2, max_position_embeddings=64,+ )+ weights = tmp_path / "model"+ LlamaForCausalLM(model_config).save_pretrained(weights)+ monkeypatch.setattr(+ "transformers.AutoTokenizer.from_pretrained",+ lambda *args, **kwargs: SimpleNamespace(pad_token=None, eos_token="</s>"),+ )+ monkeypatch.setattr(+ "soup_cli.utils.layer_shard.resolve_shard_dir", lambda *_: str(tmp_path / "shards"),+ )++ def unexpected_patch(*args, **kwargs):+ pytest.fail("streamed setup now reaches CCE: reassess the refusal and VRAM budget")++ monkeypatch.setattr("soup_cli.utils.cut_ce.apply_cut_ce", unexpected_patch)++ class Wrapper(StreamingSetupMixin):+ device = "cpu"+ _trust_remote_code = False++ cfg = _config(stream_layers=True)+ cfg.base = str(weights)+ cfg.training = cfg.training.model_copy(update={"use_cut_ce": True})+ wrapper = Wrapper()+ try:+ wrapper._setup_streaming_transformers(cfg, cfg.training)+ assert wrapper._stream_runtime.stats()["n_layers"] == 2+ inputs = torch.tensor([[1, 2, 3, 4, 5]])+ output = wrapper.model(input_ids=inputs, labels=inputs)+ assert output.logits.shape == (1, 5, 32)+ oracle = functional.cross_entropy(+ output.logits[:, :-1].float().reshape(-1, 32), inputs[:, 1:].reshape(-1),+ )+ torch.testing.assert_close(output.loss, oracle)+ output.loss.backward()+ gradients = [+ parameter.grad for name, parameter in wrapper.model.named_parameters()+ if "lora_" in name and parameter.grad is not None+ ]+ assert gradients and all(torch.isfinite(gradient).all() for gradient in gradients)+ assert any(gradient.abs().sum() > 0 for gradient in gradients)+ finally:+ wrapper._close_stream_runtime()