Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

Never hand TRL a KTO per-device batch of 1 (#1476)

Kratos0cc3c13267f8
diff --git a/changelog.d/0.75.1/1476.fixed.md b/changelog.d/0.75.1/1476.fixed.md
new file mode 100644
index 00000000..0a18d782
--- /dev/null
+++ b/changelog.d/0.75.1/1476.fixed.md
@@ -0,0 +1 @@
+- Fixed KTO reaching TRL with a per-device batch of 1: the `batch_size >= 2` parse-time refusal now covers every `task='kto'` config (not only `stream_layers`), `batch_size: auto` floors its estimate at 2 instead of 1, and `soup local-rl train --train-method kto` writes `batch_size: 2` (#1420 by @wanjinhao1 in #1476).
diff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.md
index 3cb579cf..20b2b931 100644
--- a/docs/performance-and-quantization.md
+++ b/docs/performance-and-quantization.md
@@ -654,7 +654,7 @@ prints this advice when it sees you accumulating.
- `quantization` other than `none` or `4bit` → other formats cannot be streamed into a pooled buffer
- `backend: unsloth` / `backend: mlx` → streaming replaces the model-load path those backends own
- `task` other than `sft` / `dpo` / `orpo` / `simpo` / `kto` → named explicitly. `grpo` and `ppo` are refused **permanently**, not pending: generation rollouts re-read every layer once per generated token, which destroys the amortisation streaming depends on
-- `task: kto` with `batch_size: 1` → TRL's KL term is degenerate at batch 1; refused when the config is read rather than minutes later after sharding
+- `task: kto` with `batch_size: 1` → TRL's KL term is degenerate at batch 1; refused when the config is read (this applies to every KTO run, not only to streaming) rather than minutes later after sharding
- `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
diff --git a/docs/training.md b/docs/training.md
index 0947b423..76a63b34 100644
--- a/docs/training.md
+++ b/docs/training.md
@@ -1622,6 +1622,8 @@ training:
quantization: 4bit
```
+**Batch size.** KTO needs a per-device `batch_size` of at least 2: TRL's KL term is degenerate at batch 1, so `batch_size: 1` is refused when the config is loaded. `batch_size: auto` never resolves below 2, and `soup local-rl train --train-method kto` writes `batch_size: 2`. Raise `gradient_accumulation_steps` for a larger effective batch.
+
**KTO data format:**
```json
{"prompt": "What is 2+2?", "completion": "4", "label": true}
diff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.py
index 1042b137..6b3b61cd 100644
--- a/src/soup_cli/config/schema.py
+++ b/src/soup_cli/config/schema.py
@@ -6246,6 +6246,35 @@ class SoupConfig(BaseModel):
)
return self
+ @model_validator(mode="after")
+ def _validate_kto_batch_compat(self) -> "SoupConfig":
+ """#1420 — a per-device KTO batch of 1 is invalid, streaming or not.
+
+ TRL's ``KTOTrainer`` refuses ``per_device_train_batch_size=1``
+ ("Actual (not effective) batch size must be > 1") because the KL
+ term degenerates. Soup used to catch this at parse time only for
+ ``stream_layers`` runs (see the note kept in
+ ``_validate_stream_layers_compat``), so a resident KTO config loaded,
+ loaded its model, and only then died inside TRL — after minutes of
+ I/O on a real base. The same refusal now applies to every
+ ``task='kto'`` config, resident or streamed, before anything loads.
+ """
+ if self.backend == "mlx":
+ return self # _validate_mlx_task_support gives the more basic answer
+ tcfg = self.training
+ if (
+ self.task == "kto"
+ and isinstance(tcfg.batch_size, int)
+ and tcfg.batch_size < 2
+ ):
+ raise ValueError(
+ "task='kto' requires training.batch_size >= 2: TRL's KL term is "
+ "degenerate at a per-device batch of 1. Set batch_size to 2 or "
+ "more and raise gradient_accumulation_steps to keep the "
+ "effective batch size."
+ )
+ return self
+
@model_validator(mode="after")
def _validate_stream_layers_compat(self) -> "SoupConfig":
"""v0.72.0 BETA — layer-streaming compatibility gates.
@@ -6378,21 +6407,10 @@ class SoupConfig(BaseModel):
# budget is exhausted (peak moved 0.842 -> 0.846 GB across accum 1->4).
# v0.72.4 — KTO's KL term is degenerate at a per-device batch of 1, so
# TRL refuses it outright ("Actual (not effective) batch size must be
- # > 1"). Under streaming that ValueError arrives only AFTER the RAM
- # pre-flight, the checkpoint sharding and — at quantization='4bit' —
- # the NF4 quantisation pass: minutes of disk I/O on a real base, to
- # fail on a config that was already invalid. Refuse it at parse time.
- if (
- self.task == "kto"
- and isinstance(tcfg.batch_size, int)
- and tcfg.batch_size < 2
- ):
- raise ValueError(
- "task='kto' requires training.batch_size >= 2 (TRL's KL term is "
- "degenerate at batch 1). Checked here rather than in the "
- "trainer so a streaming run fails before sharding the "
- "checkpoint, not minutes into it."
- )
+ # > 1"). Refused at parse time for EVERY task='kto'
+ # config — streaming or resident — by ``_validate_kto_batch_compat``
+ # (#1420); a streaming run therefore still fails before sharding the
+ # checkpoint, not minutes into it.
if tcfg.lora.r < 1:
raise ValueError(
"training.stream_layers requires LoRA (training.lora.r >= 1) — "
diff --git a/src/soup_cli/trainer/kto.py b/src/soup_cli/trainer/kto.py
index b9ab6b07..d0902011 100644
--- a/src/soup_cli/trainer/kto.py
+++ b/src/soup_cli/trainer/kto.py
@@ -137,8 +137,11 @@ class KTOTrainerWrapper(StreamingSetupMixin):
quantization=tcfg.quantization,
lora_r=tcfg.lora.r,
)
- # KTO processes unpaired samples — similar memory to DPO
- batch_size = max(1, batch_size // 2)
+ # KTO processes unpaired samples — similar memory to DPO. The
+ # floor is 2, not 1: TRL's KTOTrainer refuses a per-device batch
+ # of 1 (degenerate KL term), so handing it 1 just moves the
+ # failure after the model has loaded (#1420).
+ batch_size = max(2, batch_size // 2)
console.print(f"[green]Auto batch size (KTO):[/] {batch_size}")
# --- Dataset ---
diff --git a/src/soup_cli/utils/local_rl.py b/src/soup_cli/utils/local_rl.py
index 71a64e8e..e1518d1f 100644
--- a/src/soup_cli/utils/local_rl.py
+++ b/src/soup_cli/utils/local_rl.py
@@ -458,12 +458,15 @@ def _default_train_fn(
import yaml
data_format = _METHOD_FORMAT[train_method]
+ # KTO needs a per-device batch >= 2 (TRL refuses batch 1: degenerate KL
+ # term, #1420); batch 1 stays for dpo/orpo, which accept it.
+ batch_size = 2 if train_method == "kto" else 1
yaml_text = yaml.safe_dump(
{
"base": base_model,
"task": train_method,
"data": {"train": pairs_path, "format": data_format, "max_length": 256},
- "training": {"epochs": 1, "batch_size": 1},
+ "training": {"epochs": 1, "batch_size": batch_size},
"output": output_dir,
},
default_flow_style=False,
diff --git a/tests/test_part_c.py b/tests/test_part_c.py
index 128a0f10..59d44d50 100644
--- a/tests/test_part_c.py
+++ b/tests/test_part_c.py
@@ -110,7 +110,14 @@ class TestSchemaGateExpanded:
"data": {"train": "data.jsonl", "format": "alpaca"}
if task != "pretrain"
else {"train": "data.jsonl", "format": "plaintext"},
- "training": {"epochs": 1, "lr": 1e-4, "batch_size": 1, **training_extra},
+ "training": {
+ "epochs": 1,
+ "lr": 1e-4,
+ # #1420: KTO refuses batch 1 at parse time (TRL's KL term);
+ # these tests exercise unrelated training knobs.
+ "batch_size": 2 if task == "kto" else 1,
+ **training_extra,
+ },
}
if task in ("dpo", "kto", "orpo", "simpo", "ipo", "grpo"):
body["data"]["format"] = "dpo"
diff --git a/tests/test_trainer_coverage_v035.py b/tests/test_trainer_coverage_v035.py
index 2ecc4b51..8b6df828 100644
--- a/tests/test_trainer_coverage_v035.py
+++ b/tests/test_trainer_coverage_v035.py
@@ -225,7 +225,8 @@ def test_activation_offloading_context_missing_attr_safe(tmp_path) -> None:
def _build_yaml_config(task: str, **training_extra) -> dict:
"""Helper: build a minimal config dict accepted by load_config_from_string."""
- default_bs = 2 if task == "embedding" else 1
+ # #1420: KTO refuses batch 1 (TRL KL term)
+ default_bs = 2 if task in ("embedding", "kto") else 1
body = {
"base": "meta-llama/Llama-3.2-1B",
"task": task,
diff --git a/tests/test_v07204.py b/tests/test_v07204.py
index 2603fd56..e8ba59a2 100644
--- a/tests/test_v07204.py
+++ b/tests/test_v07204.py
@@ -1092,10 +1092,55 @@ class TestKtoBatchIsRefusedEarly:
cfg = _stream_cfg(str(tmp_path / "m"), tmp_path / "o", task=task, batch_size=1)
assert cfg.training.batch_size == 1
- def test_non_streaming_kto_is_left_alone(self, tmp_path):
- """Scoped to streaming deliberately: resident KTO at batch 1 fails the
- same way, but that is pre-existing behaviour outside this slot, and
- widening the gate here could reject configs that parse today."""
+ def test_non_streaming_kto_batch_one_is_refused(self, tmp_path):
+ """#1420 widened this gate to resident runs: TRL's KTOTrainer refuses
+ a per-device batch of 1 with the same error, but only AFTER the model
+ has loaded. Refusing at parse time everywhere (streaming or not)
+ fails fast with Soup's own message instead. This test used to assert
+ the opposite — that resident KTO at batch 1 was left alone —
+ which just relocated the crash to `KTOTrainer.__init__`."""
+ import yaml
+
+ from soup_cli.config.loader import load_config_from_string
+
+ with pytest.raises(ValueError) as excinfo:
+ load_config_from_string(
+ yaml.safe_dump(
+ {
+ "base": "sshleifer/tiny-gpt2",
+ "task": "kto",
+ "data": {"train": "t.jsonl"},
+ "training": {"batch_size": 1, "quantization": "none"},
+ "output": str(tmp_path / "o"),
+ }
+ )
+ )
+ message = str(excinfo.value)
+ assert "kto" in message.lower()
+ assert "batch_size" in message
+ assert "KL term" in message and "gradient_accumulation_steps" in message
+ assert "streaming" not in message
+
+ def test_mlx_kto_reports_the_backend_refusal_first(self):
+ import yaml
+
+ from soup_cli.config.loader import load_config_from_string
+
+ with pytest.raises(ValueError, match="MLX backend only ships SFT"):
+ load_config_from_string(
+ yaml.safe_dump(
+ {
+ "base": "org/model",
+ "task": "kto",
+ "backend": "mlx",
+ "data": {"train": "t.jsonl", "format": "kto"},
+ "training": {"batch_size": 1, "quantization": "none"},
+ }
+ )
+ )
+
+ def test_non_streaming_kto_batch_two_still_parses(self, tmp_path):
+ """Control: the #1420 gate refuses only batch 1, not KTO outright."""
import yaml
from soup_cli.config.loader import load_config_from_string
@@ -1106,12 +1151,33 @@ class TestKtoBatchIsRefusedEarly:
"base": "sshleifer/tiny-gpt2",
"task": "kto",
"data": {"train": "t.jsonl"},
- "training": {"batch_size": 1, "quantization": "none"},
+ "training": {"batch_size": 2, "quantization": "none"},
"output": str(tmp_path / "o"),
}
)
)
- assert cfg.training.batch_size == 1
+ assert cfg.training.batch_size == 2
+
+ def test_non_streaming_other_tasks_still_accept_batch_one(self, tmp_path):
+ """The #1420 widening is KTO-only: batch 1 stays valid for dpo/orpo
+ resident runs, which TRL accepts."""
+ import yaml
+
+ from soup_cli.config.loader import load_config_from_string
+
+ for task in ("dpo", "orpo"):
+ cfg = load_config_from_string(
+ yaml.safe_dump(
+ {
+ "base": "sshleifer/tiny-gpt2",
+ "task": task,
+ "data": {"train": "t.jsonl", "format": "dpo"},
+ "training": {"batch_size": 1, "quantization": "none"},
+ "output": str(tmp_path / "o"),
+ }
+ )
+ )
+ assert cfg.training.batch_size == 1
def test_trl_itself_still_refuses_batch_one(self, tmp_path):
"""Pins the UPSTREAM behaviour our schema gate mirrors.
@@ -1241,3 +1307,162 @@ class TestNf4CombinesWithEveryPreferenceLoss:
message = str(excinfo.value)
assert "auto" in message
assert "RESIDENT" in message or "probe" in message
+
+
+class TestIssue1420KtoBatchAutoAndLocalRl:
+ """#1420 — two more ways KTO reached TRL with a per-device batch of 1:
+
+ `batch_size: auto` floored its estimate at 1, and `soup local-rl train
+ --train-method kto` hard-wrote `batch_size: 1`. Both must now land at >= 2
+ (or refuse), so TRL never sees batch 1 for KTO at all."""
+
+ @pytest.mark.parametrize("estimate", [1, 2, 3])
+ def test_auto_floors_at_two(self, tmp_path, monkeypatch, estimate):
+ """The estimator's result is halved (unpaired samples), but the floor
+ is 2, not 1 — TRL refuses 1 outright. A real wrapper.setup() on a tiny
+ random-init CPU model with a patched estimator; mutation check:
+ restoring `max(1, batch_size // 2)` fails this at estimate 1."""
+ from tokenizers import Tokenizer, models, pre_tokenizers
+ from transformers import LlamaConfig, LlamaForCausalLM, PreTrainedTokenizerFast
+
+ words = ["<unk>", "<s>", "</s>", "<pad>", "hi", "good", "bad", "answer"]
+ raw = Tokenizer(
+ models.WordLevel(vocab={w: i for i, w in enumerate(words)}, unk_token="<unk>")
+ )
+ raw.pre_tokenizer = pre_tokenizers.Whitespace()
+ PreTrainedTokenizerFast(
+ tokenizer_object=raw, unk_token="<unk>", bos_token="<s>",
+ eos_token="</s>", pad_token="<pad>",
+ ).save_pretrained(str(tmp_path / "tiny"))
+ LlamaForCausalLM(
+ LlamaConfig(
+ vocab_size=len(words), hidden_size=32, intermediate_size=64,
+ num_hidden_layers=2, num_attention_heads=2, num_key_value_heads=2,
+ pad_token_id=3,
+ )
+ ).save_pretrained(str(tmp_path / "tiny"))
+
+ import yaml
+
+ from soup_cli.config.loader import load_config_from_string
+ from soup_cli.trainer import kto as kto_mod
+ from soup_cli.trainer.kto import KTOTrainerWrapper
+
+ monkeypatch.setattr(kto_mod, "estimate_batch_size", lambda **kwargs: estimate)
+ import soup_cli.utils.gpu as gpu_mod
+
+ monkeypatch.setattr(
+ gpu_mod, "get_gpu_info", lambda: {"memory_total_bytes": 24 * 1024**3}
+ )
+
+ cfg = load_config_from_string(
+ yaml.safe_dump(
+ {
+ "base": str(tmp_path / "tiny"),
+ "task": "kto",
+ "data": {"train": "unused.jsonl", "format": "kto", "max_length": 64},
+ "training": {
+ "batch_size": "auto", "quantization": "none", "epochs": 1,
+ "lora": {"r": 4, "alpha": 8},
+ },
+ "output": str(tmp_path / "out"),
+ }
+ )
+ )
+ wrapper = KTOTrainerWrapper(cfg, device="cpu")
+ wrapper.setup(
+ {"train": [
+ {"prompt": "hi", "completion": " good answer", "label": i % 2 == 0}
+ for i in range(8)
+ ]}
+ )
+ assert wrapper.trainer.args.per_device_train_batch_size >= 2
+
+ def test_local_rl_default_yaml_builds_a_kto_trainer(self, tmp_path, monkeypatch):
+ """The YAML `_default_train_fn` renders for `train_method='kto'` must
+ itself clear the widened schema gate: batch 2, loads, and (on a tiny
+ random-init model) builds a real KTOTrainer on CPU."""
+ import os
+
+ from tokenizers import Tokenizer, models, pre_tokenizers
+ from transformers import LlamaConfig, LlamaForCausalLM, PreTrainedTokenizerFast
+
+ words = ["<unk>", "<s>", "</s>", "<pad>", "hi", "good", "bad", "answer"]
+ raw = Tokenizer(
+ models.WordLevel(vocab={w: i for i, w in enumerate(words)}, unk_token="<unk>")
+ )
+ raw.pre_tokenizer = pre_tokenizers.Whitespace()
+ PreTrainedTokenizerFast(
+ tokenizer_object=raw, unk_token="<unk>", bos_token="<s>",
+ eos_token="</s>", pad_token="<pad>",
+ ).save_pretrained(str(tmp_path / "tiny"))
+ LlamaForCausalLM(
+ LlamaConfig(
+ vocab_size=len(words), hidden_size=32, intermediate_size=64,
+ num_hidden_layers=2, num_attention_heads=2, num_key_value_heads=2,
+ pad_token_id=3,
+ )
+ ).save_pretrained(str(tmp_path / "tiny"))
+
+ import yaml
+
+ from soup_cli.utils.local_rl import _default_train_fn
+
+ pairs_path = str(tmp_path / "pairs.jsonl")
+ with open(pairs_path, "w") as fh:
+ for i in range(8):
+ label = "true" if i % 2 == 0 else "false"
+ fh.write('{"prompt": "hi", "completion": " good answer", "label": %s}\n' % label)
+ out_dir = str(tmp_path / "out")
+
+ # Capture the rendered YAML instead of spawning `soup train`.
+ rendered = {}
+
+ def fake_run(argv, *a, **k):
+ rendered["yaml"] = open(argv[argv.index("--config") + 1]).read()
+
+ class _R:
+ returncode = 0
+
+ return _R()
+
+ import subprocess as _sp
+
+ monkeypatch.setattr(_sp, "run", fake_run)
+ cwd = os.getcwd()
+ os.chdir(tmp_path)
+ try:
+ _default_train_fn(
+ base_model=str(tmp_path / "tiny"),
+ pairs_path=pairs_path,
+ output_dir=out_dir,
+ train_method="kto",
+ )
+ finally:
+ os.chdir(cwd)
+
+ cfg_dict = yaml.safe_load(rendered["yaml"])
+ assert cfg_dict["task"] == "kto"
+ assert cfg_dict["training"]["batch_size"] == 2, rendered["yaml"]
+
+ from soup_cli.config.loader import load_config_from_string
+ from soup_cli.trainer.kto import KTOTrainerWrapper
+
+ cfg = load_config_from_string(rendered["yaml"])
+ assert cfg.training.batch_size == 2
+ # The rendered YAML defaults quantization to 4bit; the point here is
+ # the batch size, so run the tiny CPU model unquantised.
+ cfg = cfg.model_copy(
+ update={"training": cfg.training.model_copy(update={"quantization": "none"})}
+ )
+
+ wrapper = KTOTrainerWrapper(cfg, device="cpu")
+ wrapper.setup(
+ {
+ "train": [
+ {"prompt": "hi", "completion": " good answer", "label": i % 2 == 0}
+ for i in range(8)
+ ]
+ }
+ )
+ assert wrapper.trainer.args.per_device_train_batch_size == 2