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.

fix(train): honor gradient checkpointing in TRL/HF args (#797) (#1778)

AmixDigital5d57c1f2aee3
diff --git a/changelog.d/0.76.0/1778.fixed.md b/changelog.d/0.76.0/1778.fixed.md
new file mode 100644
index 00000000..f19ab5fd
--- /dev/null
+++ b/changelog.d/0.76.0/1778.fixed.md
@@ -0,0 +1 @@
+- Honor `training.gradient_checkpointing` in the TRL/HF arguments for GRPO, IPO, BCO, reward-model, online-DPO, pretrain and embedding, including unquantized runs. Preserve the full-checkpointing fallback for enabled tiers. (#797 by @Amix29 in #1778)
diff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.md
index 35d683e5..cc184790 100644
--- a/docs/performance-and-quantization.md
+++ b/docs/performance-and-quantization.md
@@ -311,6 +311,11 @@ fallback instead of claiming an inactive selective tier. Other task wrappers
currently treat any enabled tier as full checkpointing. Legacy boolean configs
continue to work unchanged.
+GRPO, IPO, BCO, reward-model, online-DPO, pretrain and embedding explicitly
+forward this setting to their TRL/HF training arguments: `false` disables it
+and `true` enables it, including unquantized runs (`quantization: none`). These
+wrappers use full checkpointing for any enabled tier.
+
## Kernel Auto-Composition
diff --git a/src/soup_cli/trainer/bco.py b/src/soup_cli/trainer/bco.py
index e37910bb..3aa967c5 100644
--- a/src/soup_cli/trainer/bco.py
+++ b/src/soup_cli/trainer/bco.py
@@ -186,6 +186,7 @@ class BCOTrainerWrapper:
output_dir.mkdir(parents=True, exist_ok=True)
# --- Calculate warmup steps from ratio (#1431) ---
+ from soup_cli.utils.layer_stream import should_enable_hf_gradient_checkpointing
from soup_cli.utils.warmup import resolve_trainer_warmup_steps
warmup_steps = resolve_trainer_warmup_steps(tcfg.warmup_ratio)
@@ -199,6 +200,9 @@ class BCOTrainerWrapper:
gradient_accumulation_steps=tcfg.gradient_accumulation_steps,
learning_rate=tcfg.lr,
warmup_steps=warmup_steps,
+ gradient_checkpointing=should_enable_hf_gradient_checkpointing(
+ tcfg.gradient_checkpointing, stream_layers=tcfg.stream_layers
+ ),
weight_decay=tcfg.weight_decay,
max_grad_norm=tcfg.max_grad_norm,
optim=tcfg.optimizer,
diff --git a/src/soup_cli/trainer/embedding.py b/src/soup_cli/trainer/embedding.py
index 6217144b..88a6e5ba 100644
--- a/src/soup_cli/trainer/embedding.py
+++ b/src/soup_cli/trainer/embedding.py
@@ -168,6 +168,7 @@ class EmbeddingTrainerWrapper:
)
# --- Calculate warmup steps from ratio (#1431) ---
+ from soup_cli.utils.layer_stream import should_enable_hf_gradient_checkpointing
from soup_cli.utils.warmup import resolve_trainer_warmup_steps
warmup_steps = resolve_trainer_warmup_steps(tcfg.warmup_ratio)
@@ -181,6 +182,9 @@ class EmbeddingTrainerWrapper:
"gradient_accumulation_steps": tcfg.gradient_accumulation_steps,
"learning_rate": tcfg.lr,
"warmup_steps": warmup_steps,
+ "gradient_checkpointing": should_enable_hf_gradient_checkpointing(
+ tcfg.gradient_checkpointing, stream_layers=tcfg.stream_layers
+ ),
"weight_decay": tcfg.weight_decay,
"max_grad_norm": tcfg.max_grad_norm,
"optim": tcfg.optimizer,
diff --git a/src/soup_cli/trainer/grpo.py b/src/soup_cli/trainer/grpo.py
index 94db1606..f4b281e8 100644
--- a/src/soup_cli/trainer/grpo.py
+++ b/src/soup_cli/trainer/grpo.py
@@ -466,6 +466,7 @@ class GRPOTrainerWrapper:
output_dir.mkdir(parents=True, exist_ok=True)
# --- Calculate warmup steps from ratio (#1431) ---
+ from soup_cli.utils.layer_stream import should_enable_hf_gradient_checkpointing
from soup_cli.utils.warmup import resolve_trainer_warmup_steps
warmup_steps = resolve_trainer_warmup_steps(tcfg.warmup_ratio)
@@ -505,6 +506,9 @@ class GRPOTrainerWrapper:
"gradient_accumulation_steps": tcfg.gradient_accumulation_steps,
"learning_rate": tcfg.lr,
"warmup_steps": warmup_steps,
+ "gradient_checkpointing": should_enable_hf_gradient_checkpointing(
+ tcfg.gradient_checkpointing, stream_layers=tcfg.stream_layers
+ ),
"weight_decay": tcfg.weight_decay,
"max_grad_norm": tcfg.max_grad_norm,
"optim": tcfg.optimizer,
diff --git a/src/soup_cli/trainer/ipo.py b/src/soup_cli/trainer/ipo.py
index 936f0ecf..a5b83e7d 100644
--- a/src/soup_cli/trainer/ipo.py
+++ b/src/soup_cli/trainer/ipo.py
@@ -137,6 +137,7 @@ class IPOTrainerWrapper:
output_dir.mkdir(parents=True, exist_ok=True)
# --- Calculate warmup steps from ratio (#1431) ---
+ from soup_cli.utils.layer_stream import should_enable_hf_gradient_checkpointing
from soup_cli.utils.warmup import resolve_trainer_warmup_steps
warmup_steps = resolve_trainer_warmup_steps(tcfg.warmup_ratio)
@@ -151,6 +152,9 @@ class IPOTrainerWrapper:
gradient_accumulation_steps=tcfg.gradient_accumulation_steps,
learning_rate=tcfg.lr,
warmup_steps=warmup_steps,
+ gradient_checkpointing=should_enable_hf_gradient_checkpointing(
+ tcfg.gradient_checkpointing, stream_layers=tcfg.stream_layers
+ ),
weight_decay=tcfg.weight_decay,
max_grad_norm=tcfg.max_grad_norm,
optim=tcfg.optimizer,
diff --git a/src/soup_cli/trainer/online_dpo.py b/src/soup_cli/trainer/online_dpo.py
index c4ade074..70ce6173 100644
--- a/src/soup_cli/trainer/online_dpo.py
+++ b/src/soup_cli/trainer/online_dpo.py
@@ -281,6 +281,7 @@ class OnlineDPOTrainerWrapper:
output_dir.mkdir(parents=True, exist_ok=True)
# --- Warmup from ratio (#1431) ---
+ from soup_cli.utils.layer_stream import should_enable_hf_gradient_checkpointing
from soup_cli.utils.warmup import resolve_trainer_warmup_steps
warmup_steps = resolve_trainer_warmup_steps(tcfg.warmup_ratio)
@@ -293,6 +294,9 @@ class OnlineDPOTrainerWrapper:
gradient_accumulation_steps=tcfg.gradient_accumulation_steps,
learning_rate=tcfg.lr,
warmup_steps=warmup_steps,
+ gradient_checkpointing=should_enable_hf_gradient_checkpointing(
+ tcfg.gradient_checkpointing, stream_layers=tcfg.stream_layers
+ ),
weight_decay=tcfg.weight_decay,
max_grad_norm=tcfg.max_grad_norm,
optim=tcfg.optimizer,
diff --git a/src/soup_cli/trainer/pretrain.py b/src/soup_cli/trainer/pretrain.py
index 1c90f91f..00fc089c 100644
--- a/src/soup_cli/trainer/pretrain.py
+++ b/src/soup_cli/trainer/pretrain.py
@@ -155,6 +155,7 @@ class PretrainTrainerWrapper:
output_dir.mkdir(parents=True, exist_ok=True)
# --- Calculate warmup steps from ratio (#1431) ---
+ from soup_cli.utils.layer_stream import should_enable_hf_gradient_checkpointing
from soup_cli.utils.warmup import resolve_trainer_warmup_steps
warmup_steps = resolve_trainer_warmup_steps(tcfg.warmup_ratio)
@@ -168,6 +169,9 @@ class PretrainTrainerWrapper:
"gradient_accumulation_steps": tcfg.gradient_accumulation_steps,
"learning_rate": tcfg.lr,
"warmup_steps": warmup_steps,
+ "gradient_checkpointing": should_enable_hf_gradient_checkpointing(
+ tcfg.gradient_checkpointing, stream_layers=tcfg.stream_layers
+ ),
"weight_decay": tcfg.weight_decay,
"max_grad_norm": tcfg.max_grad_norm,
"optim": tcfg.optimizer,
diff --git a/src/soup_cli/trainer/reward_model.py b/src/soup_cli/trainer/reward_model.py
index bb43af88..b36f06b3 100644
--- a/src/soup_cli/trainer/reward_model.py
+++ b/src/soup_cli/trainer/reward_model.py
@@ -137,6 +137,7 @@ class RewardModelTrainerWrapper:
output_dir.mkdir(parents=True, exist_ok=True)
# --- Calculate warmup steps from ratio (#1431) ---
+ from soup_cli.utils.layer_stream import should_enable_hf_gradient_checkpointing
from soup_cli.utils.warmup import resolve_trainer_warmup_steps
warmup_steps = resolve_trainer_warmup_steps(tcfg.warmup_ratio)
@@ -150,6 +151,9 @@ class RewardModelTrainerWrapper:
gradient_accumulation_steps=tcfg.gradient_accumulation_steps,
learning_rate=tcfg.lr,
warmup_steps=warmup_steps,
+ gradient_checkpointing=should_enable_hf_gradient_checkpointing(
+ tcfg.gradient_checkpointing, stream_layers=tcfg.stream_layers
+ ),
weight_decay=tcfg.weight_decay,
max_grad_norm=tcfg.max_grad_norm,
optim=tcfg.optimizer,
diff --git a/tests/test_issue797_trainer_checkpointing.py b/tests/test_issue797_trainer_checkpointing.py
new file mode 100644
index 00000000..f5c31041
--- /dev/null
+++ b/tests/test_issue797_trainer_checkpointing.py
@@ -0,0 +1,150 @@
+"""#797, item 2: the real TRL/HF trainer must receive the YAML setting.
+
+Local random Llama weights and a real tokenizer keep this offline. Model loads,
+PEFT, config construction and trainer construction are real. Tests pin HF's
+device choice to CPU; the online judge is a deterministic local evaluator.
+"""
+
+from __future__ import annotations
+
+import importlib
+from collections.abc import Iterator
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+
+import pytest
+
+from soup_cli.config.loader import load_config_from_string
+from tests._tiny_hf_models import tiny_model_dir
+
+if TYPE_CHECKING:
+ from soup_cli.eval.judge import JudgeScore
+
+_WRAPPERS = {
+ "grpo": "GRPOTrainerWrapper",
+ "ipo": "IPOTrainerWrapper",
+ "bco": "BCOTrainerWrapper",
+ "reward_model": "RewardModelTrainerWrapper",
+ "online_dpo": "OnlineDPOTrainerWrapper",
+ "pretrain": "PretrainTrainerWrapper",
+ "embedding": "EmbeddingTrainerWrapper",
+}
+
+
[email protected](autouse=True)
+def train_stack(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
+ for name in ("torch", "transformers", "peft", "trl", "datasets"):
+ pytest.importorskip(name, reason=f"{name} requires the train extra")
+ import torch
+ from transformers import TrainingArguments
+
+ threads = torch.get_num_threads()
+ torch.set_num_threads(1)
+ # ACCELERATE_USE_CPU alone still lets HF choose MPS on a Mac. Set the public
+ # flag before real HF initialization, without changing the checkpointing value.
+ real_post_init = TrainingArguments.__post_init__
+
+ def cpu_post_init(args: TrainingArguments) -> None:
+ args.use_cpu = True
+ real_post_init(args)
+
+ monkeypatch.setattr(TrainingArguments, "__post_init__", cpu_post_init)
+ yield
+ torch.set_num_threads(threads)
+
+
+class _LocalJudge:
+ def compare_pair(self, prompt: str, resp_a: str, resp_b: str) -> int:
+ return 0
+
+ def evaluate(
+ self, prompt: str, response: str, category: str = "default"
+ ) -> JudgeScore:
+ from soup_cli.eval.judge import JudgeScore
+
+ return JudgeScore(prompt=prompt, response=response, weighted_score=1.0)
+
+
+def _build(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, task: str, checkpointing: bool | str
+) -> tuple[Any, Any]:
+ import yaml
+
+ monkeypatch.chdir(tmp_path)
+ training = {
+ "quantization": "none",
+ "gradient_checkpointing": checkpointing,
+ "batch_size": 2,
+ "gradient_accumulation_steps": 1,
+ "epochs": 1,
+ "warmup_ratio": 0.0,
+ "save_steps": 1000,
+ "seed": 7,
+ "lora": {"r": 4, "alpha": 8, "target_modules": ["q_proj", "v_proj"]},
+ }
+ if task == "grpo":
+ training.update(num_generations=2, reward_fn="format")
+ elif task == "online_dpo":
+ training.update(online_dpo_judge="ollama://local-test", online_dpo_max_new_tokens=8)
+ import soup_cli.trainer.online_dpo as online_dpo
+
+ monkeypatch.setattr(online_dpo, "_ONLINE_DPO_JUDGE_OVERRIDE", _LocalJudge())
+ data = {"train": "unused.jsonl", "max_length": 64}
+ if task not in {"pretrain", "embedding"}:
+ data["chat_template"] = "chatml"
+ cfg = load_config_from_string(yaml.safe_dump({
+ "base": tiny_model_dir("llama"),
+ "task": task,
+ "backend": "transformers",
+ "data": data,
+ "training": training,
+ "output": str(tmp_path / "out"),
+ }))
+ if task in {"grpo", "online_dpo"}:
+ rows = [{"prompt": "hello world"}] * 4
+ elif task == "pretrain":
+ rows = [{"text": "hello world hi there friend"}] * 4
+ elif task == "embedding":
+ rows = [{"anchor": "hello world", "positive": "hi there friend"}] * 4
+ else:
+ rows = [{"prompt": "hello", "chosen": " world", "rejected": " friend"}] * 4
+ cls = getattr(importlib.import_module(f"soup_cli.trainer.{task}"), _WRAPPERS[task])
+ wrapper = cls(cfg, device="cpu")
+ wrapper.setup({"train": rows})
+ trainer = getattr(wrapper.trainer, "_trainer", wrapper.trainer)
+ assert trainer.args.device.type == "cpu"
+ assert next(trainer.model.parameters()).device.type == "cpu"
+ return wrapper, trainer
+
+
[email protected]("task", _WRAPPERS)
[email protected]("checkpointing", [False, True], ids=["disabled", "enabled"])
+def test_yaml_checkpointing_reaches_real_trainer(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, task: str, checkpointing: bool
+) -> None:
+ _, trainer = _build(tmp_path, monkeypatch, task, checkpointing)
+ assert trainer.args.gradient_checkpointing is checkpointing, task
+
+
[email protected]("task", _WRAPPERS)
[email protected]("checkpointing", [False, True], ids=["disabled", "enabled"])
+def test_checkpointing_state_after_cpu_training(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, task: str, checkpointing: bool
+) -> None:
+ _, trainer = _build(tmp_path, monkeypatch, task, checkpointing)
+ trainer.args.max_steps = 1
+ trainer.args.save_strategy = "no"
+ trainer.args.disable_tqdm = True
+ trainer.train()
+ assert trainer.state.global_step == 1
+ assert trainer.model.is_gradient_checkpointing is checkpointing, task
+
+
[email protected]("task", _WRAPPERS)
[email protected]("tier", ["full", "medium", "selective", "auto"])
+def test_enabled_tiers_keep_non_sft_full_checkpointing(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, task: str, tier: str
+) -> None:
+ # These wrappers have no selective hooks: retain the documented full fallback.
+ _, trainer = _build(tmp_path, monkeypatch, task, tier)
+ assert trainer.args.gradient_checkpointing is True, (task, tier)