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(ppo): hand trl only the token columns, refuse a train set smaller than one rollout batch (#1391) (#1410)
Maxiea8ea71fadf5
diff --git a/changelog.d/0.75.1/1410.fixed.md b/changelog.d/0.75.1/1410.fixed.mdnew file mode 100644index 00000000..4ecb2b0a--- /dev/null+++ b/changelog.d/0.75.1/1410.fixed.md@@ -0,0 +1 @@+- `task: ppo` runs again on trl 0.29: the dataset handed to trl's `PPOTrainer` carries only `input_ids` / `attention_mask`, so its padding collator no longer crashes on the `prompt_text` strings before the first step. A train set with fewer than `batch_size` x `gradient_accumulation_steps` x the number of processes rows is refused before any model loads, instead of hanging (#1391 by @maximilianfeix in #1410).diff --git a/docs/training.md b/docs/training.mdindex 93b33a54..6686dc70 100644--- a/docs/training.md+++ b/docs/training.md@@ -1555,6 +1555,12 @@ controls optimization passes within each PPO update. Soup forwards both values,plus `ppo_kl_penalty`, to the active TRL `PPOConfig` names and prints theeffective schedule during setup.+One PPO rollout batch is `batch_size` x `gradient_accumulation_steps` prompts on+every process, and TRL drops a partial batch, so the train set needs at least+`batch_size` x `gradient_accumulation_steps` x the number of processes rows.+A smaller one would never reach a step, so `soup train` refuses it before loading+any model and names the row count and both settings.+PPO supports two reward sources:- **Reward model** (`reward_model`): pre-trained reward model (from step 2)- **Reward function** (`reward_fn`): callable function (same as GRPO — `accuracy`, `format`, or custom `.py`)diff --git a/src/soup_cli/trainer/ppo.py b/src/soup_cli/trainer/ppo.pyindex 7a660a79..567fd246 100644--- a/src/soup_cli/trainer/ppo.py+++ b/src/soup_cli/trainer/ppo.py@@ -7,6 +7,7 @@ clipped surrogate objectives with a KL penalty against a frozen reference model.Full RLHF pipeline: SFT → Reward Model → PPO"""+import osimport timefrom pathlib import Pathfrom typing import Any, Mapping, Optional@@ -137,6 +138,32 @@ class PPOTrainerWrapper:use_unsloth = cfg.backend == "unsloth"+ # --- Batch size ---+ batch_size = tcfg.batch_size+ if batch_size == "auto":+ from soup_cli.utils.gpu import get_gpu_info++ gpu_info = get_gpu_info()+ model_size = model_size_from_name(cfg.base)+ batch_size = estimate_batch_size(+ model_params_b=model_size,+ seq_length=cfg.data.max_length,+ gpu_memory_bytes=gpu_info["memory_total_bytes"],+ quantization=tcfg.quantization,+ lora_r=tcfg.lora.r,+ )+ # PPO needs memory for policy + ref model + reward model → conservative+ batch_size = max(1, batch_size // 4)+ console.print(f"[green]Auto batch size (PPO):[/] {batch_size}")++ # #1391: a train set smaller than one rollout batch never reaches a+ # step. _prepare_ppo_dataset turns every row into exactly one prompt,+ # so the count is known before any model is loaded.+ if is_experimental:+ _check_one_rollout_batch(+ len(dataset["train"]), batch_size, tcfg.gradient_accumulation_steps+ )+# --- Load reward source ---self._setup_reward(cfg, tcfg)@@ -156,24 +183,6 @@ class PPOTrainerWrapper:f" / {total:,} total ({pct:.2f}%)")- # --- Batch size ---- batch_size = tcfg.batch_size- if batch_size == "auto":- from soup_cli.utils.gpu import get_gpu_info-- gpu_info = get_gpu_info()- model_size = model_size_from_name(cfg.base)- batch_size = estimate_batch_size(- model_params_b=model_size,- seq_length=cfg.data.max_length,- gpu_memory_bytes=gpu_info["memory_total_bytes"],- quantization=tcfg.quantization,- lora_r=tcfg.lora.r,- )- # PPO needs memory for policy + ref model + reward model → conservative- batch_size = max(1, batch_size // 4)- console.print(f"[green]Auto batch size (PPO):[/] {batch_size}")-# --- Dataset ---train_data = _prepare_ppo_dataset(dataset["train"], tokenizer=self.tokenizer)train_ds = Dataset.from_list(train_data)@@ -191,6 +200,10 @@ class PPOTrainerWrapper:)train_ds = train_ds.map(_tokenize_ppo, batched=True)+ # #1391: trl's PPOTrainer pads every column with DataCollatorWithPadding and+ # never drops unused ones, so the prompt_text strings crash the collator.+ # The manual (trl<0.28) loop below still reads prompt_text from _train_ds.+ trl_train_ds = train_ds.select_columns(["input_ids", "attention_mask"])# --- Output dir ---output_dir = Path(cfg.output)@@ -360,7 +373,7 @@ class PPOTrainerWrapper:"model": self.model,"ref_model": None,"reward_model": reward_model_obj,- "train_dataset": train_ds,+ "train_dataset": trl_train_ds,"value_model": value_model_obj,}# LoRA+ (#724/#745): inject so the eagerly-built scheduler binds to it.@@ -380,9 +393,9 @@ class PPOTrainerWrapper:"processing_class": self.tokenizer,}if "train_dataset" in ppo_trainer_params:- trainer_kwargs["train_dataset"] = train_ds+ trainer_kwargs["train_dataset"] = trl_train_dselif "dataset" in ppo_trainer_params:- trainer_kwargs["dataset"] = train_ds+ trainer_kwargs["dataset"] = trl_train_dsif reward_funcs and "reward_funcs" in ppo_trainer_params:trainer_kwargs["reward_funcs"] = reward_funcs# Pass ref/reward/value models if required positionally@@ -466,6 +479,7 @@ class PPOTrainerWrapper:self._output_dir = str(output_dir)self._train_ds = train_ds+ self._trl_train_ds = trl_train_dsself._batch_size = batch_sizeself._num_epochs = tcfg.epochsself._max_length = cfg.data.max_length@@ -718,9 +732,9 @@ class PPOTrainerWrapper:# If dataset wasn't accepted by constructor, set it on the trainerif not self._dataset_in_constructor:if hasattr(self.trainer, "train_dataset"):- self.trainer.train_dataset = self._train_ds+ self.trainer.train_dataset = self._trl_train_dselif hasattr(self.trainer, "dataset"):- self.trainer.dataset = self._train_ds+ self.trainer.dataset = self._trl_train_dsif display:from soup_cli.monitoring.callback import (@@ -926,6 +940,29 @@ class PPOTrainerWrapper:return rewards+def _world_size() -> int:+ try:+ return max(1, int(os.environ.get("WORLD_SIZE", "1") or "1"))+ except (TypeError, ValueError):+ return 1+++def _check_one_rollout_batch(rows: int, batch_size: int, grad_accum: int) -> None:+ """#1391: trl's PPO DataLoader uses ``drop_last=True`` with one rollout batch+ (``batch_size * gradient_accumulation_steps`` rows per process) and repeats it+ with ``while True``, so a smaller train set spins forever without a step."""+ processes = _world_size()+ needed = batch_size * grad_accum * processes+ if rows < needed:+ per_process = f" x {processes} processes" if processes > 1 else ""+ raise ValueError(+ f"PPO needs at least one rollout batch of training prompts: the train set "+ f"has {rows} rows, but batch_size={batch_size} x "+ f"gradient_accumulation_steps={grad_accum}{per_process} = {needed}. "+ f"Add prompts, or lower batch_size / gradient_accumulation_steps."+ )++def _import_ppo_classes():"""Import PPOTrainer and PPOConfig, handling trl version differences.diff --git a/tests/test_bugfixes.py b/tests/test_bugfixes.pyindex 06bb17b0..af894d46 100644--- a/tests/test_bugfixes.py+++ b/tests/test_bugfixes.py@@ -471,6 +471,21 @@ class TestPPODatasetCompat:# doesn't accept it (uses "args" path but no train_dataset param)assert wrapper._dataset_in_constructor is False+ # #1391: the late assignment in _train_builtin hands over token columns only+ class _StopError(Exception):+ pass++ def _stop(*args, **kwargs):+ raise _StopError++ wrapper.trainer.train_dataset = None+ wrapper.trainer.model = MagicMock()+ wrapper.trainer.args = MagicMock(fp16=False, bf16=False)+ wrapper.trainer.train = _stop+ with pytest.raises(_StopError):+ wrapper._train_builtin(None, None, None, None)+ assert wrapper.trainer.train_dataset.column_names == ["input_ids", "attention_mask"]+def test_ppo_dataset_in_constructor_when_accepted(self):"""_dataset_in_constructor should be True when train_dataset is accepted."""from unittest.mock import MagicMock@@ -486,11 +501,13 @@ class TestPPODatasetCompat:wrapper = PPOTrainerWrapper(cfg, device="cpu")# Real class whose __init__ DOES accept train_dataset+ captured = {}+class FakePPOTrainer:def __init__(self, *, model=None, args=None,processing_class=None, train_dataset=None,reward_funcs=None):- pass+ captured["train_dataset"] = train_datasetclass FakePPOConfig:def __init__(self, **kwargs):@@ -522,6 +539,8 @@ class TestPPODatasetCompat:wrapper.setup(dataset)assert wrapper._dataset_in_constructor is True+ # #1391: trl pads every column it is given, so only token columns go in+ assert captured["train_dataset"].column_names == ["input_ids", "attention_mask"]# --- BUG-007: PPO trl >=0.28 experimental API missing positional args (v0.10.6) ---@@ -570,7 +589,8 @@ class TestPPOExperimentalSetup:)wrapper = PPOTrainerWrapper(cfg, device="cpu")- dataset = {"train": [{"prompt": "What is 2+2?", "answer": "4"}]}+ # #1391: one rollout batch is batch_size (1 here) x gradient_accumulation_steps (4)+ dataset = {"train": [{"prompt": "What is 2+2?", "answer": "4"}] * 4}# Track what args PPOTrainer receivescaptured_kwargs = {}@@ -945,7 +965,8 @@ class TestPPOResumeCheckpoint:def __init__(self, **kwargs):pass- dataset = {"train": [{"prompt": "Q?", "answer": "A"}]}+ # #1391: one rollout batch is batch_size (1 here) x gradient_accumulation_steps (4)+ dataset = {"train": [{"prompt": "Q?", "answer": "A"}] * 4}with mock_patch("soup_cli.trainer.ppo.PPOTrainerWrapper._setup_reward"), \mock_patch("soup_cli.trainer.ppo.PPOTrainerWrapper._setup_transformers"), \diff --git a/tests/test_issue1391_ppo_real_step.py b/tests/test_issue1391_ppo_real_step.pynew file mode 100644index 00000000..c89fcef7--- /dev/null+++ b/tests/test_issue1391_ppo_real_step.py@@ -0,0 +1,137 @@+"""#1391 — ``task: ppo`` never completed a step on trl 0.29.++``setup()`` handed trl's ``PPOTrainer`` a dataset that still carried the+``prompt_text`` strings, and trl's ``DataCollatorWithPadding`` tried to turn+them into a tensor before the first rollout. A train set smaller than one+rollout batch hung instead, because trl's DataLoader drops the ragged batch and+repeats itself forever.++These tests drive the real trl trainer on CPU with a tiny on-disk Llama policy+and a tiny reward model. Nothing about the trainer is mocked.+"""++from __future__ import annotations++import pytest++for _mod in ("torch", "transformers", "peft", "trl", "datasets"):+ pytest.importorskip(_mod)+++def _tiny_models(root):+ import torch+ from tokenizers import Tokenizer, models, pre_tokenizers+ from transformers import (+ LlamaConfig,+ LlamaForCausalLM,+ LlamaForSequenceClassification,+ PreTrainedTokenizerFast,+ )++ def config(**extra):+ return LlamaConfig(+ vocab_size=64, hidden_size=64, intermediate_size=128, num_hidden_layers=2,+ num_attention_heads=4, num_key_value_heads=2, tie_word_embeddings=True,+ max_position_embeddings=128, pad_token_id=3, bos_token_id=1, eos_token_id=2,+ **extra,+ )++ torch.manual_seed(7)+ names = ["<unk>", "<s>", "</s>", "<pad>", "say", "hi", "hello", "world"]+ tok = Tokenizer(models.WordLevel(vocab={w: i for i, w in enumerate(names)}, unk_token="<unk>"))+ tok.pre_tokenizer = pre_tokenizers.Whitespace()+ base, rm = root / "base", root / "rm"+ LlamaForCausalLM(config()).save_pretrained(base)+ PreTrainedTokenizerFast(+ tokenizer_object=tok, unk_token="<unk>", bos_token="<s>",+ eos_token="</s>", pad_token="<pad>",+ ).save_pretrained(base)+ LlamaForSequenceClassification(config(num_labels=1)).save_pretrained(rm)+ return base.as_posix(), rm.as_posix()+++_PROMPTS = ("say hi", "say hello world", "hi", "hello")+++def _wrapper(tmp_path, monkeypatch, grad_accum=1):+ from soup_cli.config.loader import load_config_from_string+ from soup_cli.trainer.ppo import PPOTrainerWrapper++ monkeypatch.setenv("WANDB_DISABLED", "true")+ monkeypatch.delenv("WORLD_SIZE", raising=False)+ monkeypatch.chdir(tmp_path)+ base, rm = _tiny_models(tmp_path)+ cfg = load_config_from_string(+ f"base: {base}\ntask: ppo\nbackend: transformers\n"+ "data:\n train: train.jsonl\n max_length: 64\n"+ # One rollout batch is batch_size * gradient_accumulation_steps rows, so+ # these 4 rows fill exactly one batch at batch_size 2, accumulation 1.+ f"training:\n epochs: 1\n batch_size: 2\n gradient_accumulation_steps: {grad_accum}\n"+ f" quantization: none\n ppo_epochs: 1\n reward_model: {rm}\n"+ " lora:\n r: 4\n alpha: 8\n target_modules: [q_proj, v_proj]\n"+ f"output: {(tmp_path / 'out').as_posix()}\n"+ )+ wrapper = PPOTrainerWrapper(cfg, device="cpu")+ wrapper.setup({"train": [{"messages": [{"role": "user", "content": p}]} for p in _PROMPTS]})+ return wrapper+++def test_ppo_hands_trl_only_token_columns(tmp_path, monkeypatch):+ wrapper = _wrapper(tmp_path, monkeypatch)+ columns = set(wrapper.trainer.train_dataset.column_names)+ assert columns <= {"input_ids", "attention_mask"}, columns+ # the manual loop's copy keeps the prompt text+ assert "prompt_text" in wrapper._train_ds.column_names+++def test_ppo_runs_a_real_step(tmp_path, monkeypatch):+ wrapper = _wrapper(tmp_path, monkeypatch)+ result = wrapper.train()+ assert result["total_steps"] >= 1, result+ assert (tmp_path / "out" / "adapter_config.json").is_file()+ assert any("loss/policy_avg" in e for e in wrapper.trainer.state.log_history)+++def test_a_train_set_smaller_than_one_rollout_batch_is_refused(tmp_path, monkeypatch):+ # 4 rows, batch_size 2 x accumulation 4 = 8: trl would spin without a step+ with pytest.raises(ValueError) as exc:+ _wrapper(tmp_path, monkeypatch, grad_accum=4)+ msg = str(exc.value)+ assert "4 rows" in msg+ assert "batch_size=2" in msg+ assert "gradient_accumulation_steps=4" in msg+++def test_the_rollout_batch_counts_every_process(monkeypatch):+ from soup_cli.trainer.ppo import _check_one_rollout_batch++ monkeypatch.setenv("WORLD_SIZE", "2")+ _check_one_rollout_batch(8, 2, 2)+ with pytest.raises(ValueError, match=r"x 2 processes = 8"):+ _check_one_rollout_batch(7, 2, 2)+ monkeypatch.setenv("WORLD_SIZE", "nonsense")+ _check_one_rollout_batch(4, 2, 2)+++def test_the_refusal_comes_before_any_model_is_loaded(tmp_path, monkeypatch):+ """The refusal needs only the row count and two settings, so it must not+ wait for the reward model and the policy to load."""+ from soup_cli.trainer import ppo++ loaded = []+ real_reward = ppo.PPOTrainerWrapper._setup_reward+ real_policy = ppo.PPOTrainerWrapper._setup_transformers++ def reward(self, *args):+ loaded.append("reward model")+ return real_reward(self, *args)++ def policy(self, *args):+ loaded.append("policy")+ return real_policy(self, *args)++ monkeypatch.setattr(ppo.PPOTrainerWrapper, "_setup_reward", reward)+ monkeypatch.setattr(ppo.PPOTrainerWrapper, "_setup_transformers", policy)+ with pytest.raises(ValueError, match="4 rows"):+ _wrapper(tmp_path, monkeypatch, grad_accum=4)+ assert loaded == [], f"refused only after loading: {loaded}"diff --git a/tests/test_issue721_ppo_config_forwarding.py b/tests/test_issue721_ppo_config_forwarding.pyindex 444f4bb9..03166449 100644--- a/tests/test_issue721_ppo_config_forwarding.py+++ b/tests/test_issue721_ppo_config_forwarding.py@@ -200,7 +200,8 @@ def test_setup_passes_current_schedule_to_trainer(tmp_path, capsys) -> None:patch.object(wrapper, "_get_or_create_reward_model", return_value=MagicMock()),patch.object(wrapper, "_create_value_model", return_value=MagicMock()),):- wrapper.setup({"train": [{"prompt": "Q?", "answer": "A"}]})+ # #1391: one rollout batch is batch_size (1 here) x gradient_accumulation_steps (4)+ wrapper.setup({"train": [{"prompt": "Q?", "answer": "A"}] * 4})assert wrapper.trainer.args.num_train_epochs == 7assert wrapper.trainer.args.num_ppo_epochs == 2diff --git a/tests/test_issue745_ppo_loraplus_scheduler.py b/tests/test_issue745_ppo_loraplus_scheduler.pyindex 28b92f82..bd7fe84e 100644--- a/tests/test_issue745_ppo_loraplus_scheduler.py+++ b/tests/test_issue745_ppo_loraplus_scheduler.py@@ -314,7 +314,8 @@ def _run_ppo_setup(training=training,)wrapper = PPOTrainerWrapper(cfg, device="cpu", deepspeed_config=deepspeed_config)- dataset = {"train": [{"prompt": "What is 2+2?", "answer": "4"}]}+ # #1391: one rollout batch is batch_size (1 here) x gradient_accumulation_steps (4)+ dataset = {"train": [{"prompt": "What is 2+2?", "answer": "4"}] * 4}with mock_patch("soup_cli.trainer.ppo.PPOTrainerWrapper._setup_reward"), \mock_patch("soup_cli.trainer.ppo.PPOTrainerWrapper._setup_transformers"), \@@ -531,6 +532,8 @@ def test_real_ppo_trainer_trains_the_value_model_with_loraplus(tmp_path, monkeypf" reward_model: {reward_dir.as_posix()}\n"" epochs: 1\n"" batch_size: 2\n"+ # #1391: two prompts have to fill one rollout batch (2 x 1)+ " gradient_accumulation_steps: 1\n"" lr: 1e-4\n"f" loraplus_lr_ratio: {RATIO}\n""output: ./out\n"diff --git a/tests/test_issue804_chat_template_trainers.py b/tests/test_issue804_chat_template_trainers.pyindex 02f0366c..8c405782 100644--- a/tests/test_issue804_chat_template_trainers.py+++ b/tests/test_issue804_chat_template_trainers.py@@ -285,8 +285,11 @@ class TestEveryConversationalTrainerIsWired:monkeypatch.setattr(wrapper_class, "_setup_transformers", fake_setup)wrapper = wrapper_class(cfg, device="cpu")+ # #1391: PPO refuses a train set smaller than one rollout batch+ # (batch_size 2 x gradient_accumulation_steps 4) before loading anything.+ rows = [{"prompt": "hi"}] * 8 if task == "ppo" else []with pytest.raises(StopAfterTemplateError):- wrapper.setup({"train": []})+ wrapper.setup({"train": rows})assert wrapper.tokenizer.chat_template == marker, taskdef test_online_dpo_override_beats_fallback_on_a_loaded_tokenizer(self, tmp_path):