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(trainer): honor training settings across PRM, MoLE, PPO and unlearning (#1564)

Alpamys Makazhan2d742ab94195
diff --git a/changelog.d/0.75.1/868.fixed.md b/changelog.d/0.75.1/868.fixed.md
new file mode 100644
index 00000000..8a178667
--- /dev/null
+++ b/changelog.d/0.75.1/868.fixed.md
@@ -0,0 +1,6 @@
+- Honor configured optimizer, schedule, warmup, weight decay, clipping and effective batch settings across PRM, MoLE, PPO and unlearning; keep unlearn loss and sample counts on their original scale.
+ Unlearn now tokenizes forget and retain rows to `data.max_length` (default 2048) instead of
+ a hard-coded 256, so existing unlearn configs use more memory and run longer; set
+ `data.max_length: 256` to keep the old limit. On unlearn, `batch_size: auto` now resolves
+ to 1 rather than to a memory estimate, so the same config makes the same number of
+ optimizer updates on any card. (#805 by @Oxygen56 in #868)
diff --git a/docs/training.md b/docs/training.md
index 44e01a58..0947b423 100644
--- a/docs/training.md
+++ b/docs/training.md
@@ -547,6 +547,21 @@ soup eval unlearning <run-id> --benchmark tofu --evidence evidence.json --output
`task: unlearn` is live (v0.71.9): it loads a LoRA-wrapped policy, a frozen reference copy (NPO / RMU), and the forget / retain JSONL sets, then optimises the per-method loss — NPO's `(2/β)·mean(-logσ(-β·(π_logp − ref_logp)))` drives the policy's forget-set log-prob below the reference (= forgetting), while the retain set anchors capability. Run NPO/SimNPO **with** a `retain_set` — without one the policy has no utility anchor and Soup warns loudly.
+Unlearning honors `training.optimizer`, `scheduler`, `warmup_ratio`, `weight_decay`,
+`max_grad_norm`, `batch_size` and `gradient_accumulation_steps`. The default
+`batch_size: auto` resolves to 1 for unlearning rather than to the memory estimate
+the other trainers use, so a config makes the same number of updates on any card. This
+memory-constrained loop processes one example at a time and accumulates gradients
+for `batch_size * gradient_accumulation_steps` examples per optimizer update;
+a final partial group is averaged by its actual size. `initial_loss` and
+`final_loss` remain unscaled per-example losses, and `total_steps` and the 2,000-step
+budget continue to count examples rather than optimizer updates.
+
+`data.max_length` now controls forget and retain tokenization instead of the old
+256-token cap. Its default is 2,048, so existing configurations can use more memory
+and take longer. Set `data.max_length: 256` to retain the old sequence-length limit,
+or explicitly choose a value that fits the model and device.
+
Three orthogonal axes: **Forget Quality** (pre/post forget-loss delta), **Model Utility** (retain-accuracy preserved), **PrivLeak** (membership-inference AUC distance from 0.5). Bundled mini-fixtures for all three benchmarks ship in the box (v0.71.1 added MUSE + WMDP alongside the existing TOFU set), so `--benchmark muse|wmdp` runs without supplying evidence. The WMDP forget-set probes ship **redacted** (placeholder prompts + `REFUSED` responses) — Soup never bundles verbatim hazardous-knowledge content.
diff --git a/src/soup_cli/trainer/mole_routing.py b/src/soup_cli/trainer/mole_routing.py
index 42493375..33e4be51 100644
--- a/src/soup_cli/trainer/mole_routing.py
+++ b/src/soup_cli/trainer/mole_routing.py
@@ -17,6 +17,7 @@ project policy — ``python -m soup_cli.cli --help`` must not pull torch.
from __future__ import annotations
import logging
+import math
from functools import lru_cache
from pathlib import Path
from typing import Any, Optional
@@ -26,6 +27,12 @@ from rich.console import Console
from soup_cli.config.schema import SoupConfig
from soup_cli.trainer.loss_summary import summarize_training_loss
from soup_cli.utils.eval_schedule import training_eval_kwargs
+from soup_cli.utils.gpu import (
+ bf16_fp16_flags,
+ estimate_batch_size,
+ get_gpu_info,
+ model_size_from_name,
+)
from soup_cli.utils.mixed_precision import align_trainable_dtype_for_fp16
from soup_cli.utils.seeding import apply_training_seed, training_seed_kwargs
@@ -408,20 +415,44 @@ class MoleRoutingTrainerWrapper:
self._dataset["val"], self.tokenizer, cfg.data.max_length
)
- # bool is subclass of int — explicit reject before isinstance(int).
- if isinstance(tcfg.batch_size, bool) or not isinstance(tcfg.batch_size, int):
- bs = 1
- else:
- bs = tcfg.batch_size
+ batch_size = tcfg.batch_size
+ if batch_size == "auto":
+ gpu_info = get_gpu_info()
+ batch_size = estimate_batch_size(
+ model_params_b=model_size_from_name(cfg.base),
+ seq_length=cfg.data.max_length,
+ gpu_memory_bytes=gpu_info["memory_total_bytes"],
+ quantization=tcfg.quantization,
+ lora_r=tcfg.lora.r,
+ )
+ console.print(f"[green]Auto batch size (MoLE):[/] {batch_size}")
+ bs = int(batch_size)
+ total_steps = math.ceil(
+ len(train_rows) / bs / tcfg.gradient_accumulation_steps
+ ) * tcfg.epochs
+ warmup_steps = int(total_steps * tcfg.warmup_ratio)
+ use_bf16, use_fp16 = bf16_fp16_flags(self.device)
+ from soup_cli.utils.layer_stream import should_enable_hf_gradient_checkpointing
+
args = TrainingArguments(
output_dir=str(output_dir),
num_train_epochs=tcfg.epochs,
per_device_train_batch_size=bs,
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,
+ lr_scheduler_type=tcfg.scheduler,
logging_steps=tcfg.logging_steps,
save_steps=tcfg.save_steps,
save_total_limit=3,
+ bf16=use_bf16,
+ fp16=use_fp16,
report_to=self.report_to,
remove_unused_columns=False,
deepspeed=self.deepspeed_config,
diff --git a/src/soup_cli/trainer/ppo.py b/src/soup_cli/trainer/ppo.py
index dc2dd6c9..28b1e85d 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 math
import os
import time
from pathlib import Path
@@ -19,6 +20,7 @@ from soup_cli.config.schema import SoupConfig
from soup_cli.data.chat_templates import apply_chat_template_override
from soup_cli.trainer.loss_summary import summarize_training_loss
from soup_cli.utils.gpu import (
+ bf16_fp16_flags,
estimate_batch_size,
model_size_from_name,
resolve_device_map,
@@ -34,6 +36,9 @@ def _set_ppo_training_kwargs(
ppo_kwargs: dict[str, object],
ppo_config_cls: type,
tcfg: Any,
+ *,
+ total_steps: int | None = None,
+ device: str = "cpu",
) -> dict[str, str]:
"""Forward Soup's three PPO schedules across TRL parameter renames."""
from soup_cli.trainer._trl_compat import config_accepts, kl_penalty_kwargs
@@ -56,6 +61,28 @@ def _set_ppo_training_kwargs(
for name in kl_kwargs:
applied["kl_coef"] = name
+ if total_steps is not None:
+ from soup_cli.utils.layer_stream import should_enable_hf_gradient_checkpointing
+
+ use_bf16, use_fp16 = bf16_fp16_flags(device)
+ training_kwargs = {
+ "warmup_steps": int(total_steps * tcfg.warmup_ratio),
+ "weight_decay": tcfg.weight_decay,
+ "max_grad_norm": tcfg.max_grad_norm,
+ "optim": tcfg.optimizer,
+ "lr_scheduler_type": tcfg.scheduler,
+ "logging_steps": tcfg.logging_steps,
+ "save_steps": tcfg.save_steps,
+ "bf16": use_bf16,
+ "fp16": use_fp16,
+ "gradient_checkpointing": should_enable_hf_gradient_checkpointing(
+ tcfg.gradient_checkpointing, stream_layers=tcfg.stream_layers
+ ),
+ }
+ for name, value in training_kwargs.items():
+ if config_accepts(ppo_config_cls, name):
+ ppo_kwargs[name] = value
+
return applied
@@ -275,8 +302,12 @@ class PPOTrainerWrapper:
ppo_params = inspect.signature(ppo_config_cls).parameters
+ total_steps = math.ceil(
+ len(train_ds) / batch_size / tcfg.gradient_accumulation_steps
+ ) * tcfg.epochs
applied_ppo_fields = _set_ppo_training_kwargs(
- ppo_kwargs, ppo_config_cls, tcfg
+ ppo_kwargs, ppo_config_cls, tcfg,
+ total_steps=total_steps, device=self.device,
)
if "cliprange" in ppo_params:
diff --git a/src/soup_cli/trainer/prm.py b/src/soup_cli/trainer/prm.py
index 0f36701c..8831738b 100644
--- a/src/soup_cli/trainer/prm.py
+++ b/src/soup_cli/trainer/prm.py
@@ -17,6 +17,7 @@ per project policy — ``python -m soup_cli.cli --help`` must not pull torch.
from __future__ import annotations
import logging
+import math
import time
from functools import lru_cache
from pathlib import Path
@@ -27,7 +28,13 @@ from rich.console import Console
from soup_cli.config.schema import SoupConfig
from soup_cli.trainer.loss_summary import summarize_training_loss
from soup_cli.utils.eval_schedule import training_eval_kwargs
-from soup_cli.utils.gpu import bf16_fp16_flags, resolve_base_load_dtype
+from soup_cli.utils.gpu import (
+ bf16_fp16_flags,
+ estimate_batch_size,
+ get_gpu_info,
+ model_size_from_name,
+ resolve_base_load_dtype,
+)
from soup_cli.utils.mixed_precision import align_trainable_dtype_for_fp16
from soup_cli.utils.seeding import apply_training_seed, training_seed_kwargs
@@ -323,19 +330,39 @@ class PRMTrainerWrapper:
self._dataset["val"], self.tokenizer, cfg.data.max_length
)
- # v0.53.11 review fix (python-review HIGH) — bool is subclass of int,
- # so explicit bool reject before isinstance(int).
- if isinstance(tcfg.batch_size, bool) or not isinstance(tcfg.batch_size, int):
- bs = 1
- else:
- bs = tcfg.batch_size
+ batch_size = tcfg.batch_size
+ if batch_size == "auto":
+ gpu_info = get_gpu_info()
+ batch_size = estimate_batch_size(
+ model_params_b=model_size_from_name(cfg.base),
+ seq_length=cfg.data.max_length,
+ gpu_memory_bytes=gpu_info["memory_total_bytes"],
+ quantization=tcfg.quantization,
+ lora_r=tcfg.lora.r,
+ )
+ console.print(f"[green]Auto batch size (PRM):[/] {batch_size}")
+ bs = int(batch_size)
+ total_steps = math.ceil(
+ len(train_rows) / bs / tcfg.gradient_accumulation_steps
+ ) * tcfg.epochs
+ warmup_steps = int(total_steps * tcfg.warmup_ratio)
use_bf16, use_fp16 = bf16_fp16_flags(self.device, allow_mps_bf16=True)
+ from soup_cli.utils.layer_stream import should_enable_hf_gradient_checkpointing
+
args = TrainingArguments(
output_dir=str(output_dir),
num_train_epochs=tcfg.epochs,
per_device_train_batch_size=bs,
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,
+ lr_scheduler_type=tcfg.scheduler,
logging_steps=tcfg.logging_steps,
save_steps=tcfg.save_steps,
save_total_limit=3,
diff --git a/src/soup_cli/trainer/unlearn.py b/src/soup_cli/trainer/unlearn.py
index 130b4999..f2999ad3 100644
--- a/src/soup_cli/trainer/unlearn.py
+++ b/src/soup_cli/trainer/unlearn.py
@@ -22,6 +22,7 @@ Validated on SmolLM2-135M (RTX 3050 4 GB). Heavy imports (torch / transformers
from __future__ import annotations
import json
+import math
import os
import stat
import time
@@ -38,7 +39,6 @@ _MAX_STEPS_CAP = 2000
_MAX_ROWS = 5000
_MAX_ROW_BYTES = 1 * 1024 * 1024 # per-line cap (defends against multi-GB row)
_MAX_FILE_BYTES = 1 * 1024 * 1024 * 1024 # 1 GiB dataset-file cap
-_MAX_LENGTH = 256
_RMU_CONTROL_SCALE = 6.0
_DEFAULT_BETA = 0.1
@@ -157,6 +157,10 @@ class UnlearnTrainerWrapper:
self._forget: List[Tuple[str, str]] = []
self._retain: List[Tuple[str, str]] = []
self._optimizer: Any = None
+ self._scheduler: Any = None
+ self._max_updates = 0
+ self._batch_size = 1
+ self._max_examples = 0
# Kept None — this wrapper has no HF Trainer object (the push-callback
# path in commands/train.py gracefully skips when .trainer is None).
self.trainer: Any = None
@@ -168,7 +172,6 @@ class UnlearnTrainerWrapper:
# in ``train()`` stays as the TOCTOU guard after the run.
_validated_output_dir(self.config.output)
- import torch
from peft import get_peft_model
from soup_cli.utils.live_eval import load_model_and_tokenizer
@@ -186,7 +189,9 @@ class UnlearnTrainerWrapper:
self.method = method
self.model, self.tokenizer, self._dev = load_model_and_tokenizer(
- cfg.base, device=self.device, trust_remote_code=self.trust_remote_code,
+ cfg.base,
+ device=self.device,
+ trust_remote_code=self.trust_remote_code,
)
from soup_cli.utils.peft_wiring import (
build_lora_config,
@@ -211,7 +216,9 @@ class UnlearnTrainerWrapper:
# NPO + RMU need a frozen reference copy of the base.
if method in ("npo", "rmu"):
ref, _, _ = load_model_and_tokenizer(
- cfg.base, device=self.device, trust_remote_code=self.trust_remote_code,
+ cfg.base,
+ device=self.device,
+ trust_remote_code=self.trust_remote_code,
)
for p in ref.parameters():
p.requires_grad_(False)
@@ -235,9 +242,57 @@ class UnlearnTrainerWrapper:
"data.retain_set to preserve utility."
)
+ batch_size = tcfg.batch_size
+ if batch_size == "auto":
+ # This loop processes one example per forward/backward pass. The
+ # configured batch size only controls gradient accumulation, so
+ # the memory estimator used by the Trainer-based paths would
+ # silently change the number of updates for the unlearn task.
+ batch_size = 1
+ console.print("[green]Auto batch size (unlearn):[/] 1")
+ self._batch_size = int(batch_size)
+ effective_batch = self._batch_size * int(tcfg.gradient_accumulation_steps)
+ # Keep the pre-existing sample budget and reported total_steps scale.
+ self._max_examples = min(_MAX_STEPS_CAP, len(self._forget) * int(tcfg.epochs))
+ full_epochs, remainder = divmod(self._max_examples, len(self._forget))
+ self._max_updates = (
+ full_epochs * math.ceil(len(self._forget) / effective_batch)
+ + math.ceil(remainder / effective_batch)
+ )
lr = float(tcfg.lr)
- self._optimizer = torch.optim.AdamW(
- (p for p in self.model.parameters() if p.requires_grad), lr=lr,
+ # Reuse Transformers' optimizer resolution so the hand-rolled loop
+ # honors the same optimizer allowlist and optional backends as the
+ # Trainer-based wrappers. A small TrainingArguments instance keeps
+ # this path aligned with the configured optimizer without creating a
+ # second Trainer or silently falling back to AdamW.
+ from transformers import Trainer, TrainingArguments, get_scheduler
+
+ optimizer_args = TrainingArguments(
+ output_dir=str(cfg.output),
+ optim=tcfg.optimizer,
+ learning_rate=lr,
+ weight_decay=float(tcfg.weight_decay),
+ )
+ optimizer_cls, optimizer_kwargs = Trainer.get_optimizer_cls_and_kwargs(
+ optimizer_args
+ )
+ optimizer_kwargs = dict(optimizer_kwargs)
+ optimizer_kwargs.setdefault("lr", lr)
+ optimizer_params = [
+ {
+ "params": [
+ p for p in self.model.parameters() if p.requires_grad
+ ],
+ "weight_decay": float(tcfg.weight_decay),
+ }
+ ]
+ self._optimizer = optimizer_cls(optimizer_params, **optimizer_kwargs)
+
+ self._scheduler = get_scheduler(
+ name=tcfg.scheduler,
+ optimizer=self._optimizer,
+ num_warmup_steps=int(self._max_updates * tcfg.warmup_ratio),
+ num_training_steps=max(1, self._max_updates),
)
self._setup_called = True
console.print(
@@ -262,8 +317,8 @@ class UnlearnTrainerWrapper:
cfg = self.config
tcfg = cfg.training
- epochs = max(1, int(tcfg.epochs))
- n_steps = min(_MAX_STEPS_CAP, epochs * len(self._forget))
+ batch_size = self._batch_size
+ accumulation = int(tcfg.gradient_accumulation_steps)
started = time.monotonic()
dev = self._dev
method = self.method
@@ -292,11 +347,12 @@ class UnlearnTrainerWrapper:
final_loss = None
step = 0
retain_idx = 0
- while step < n_steps:
+ accumulated = 0
+ self._optimizer.zero_grad(set_to_none=True)
+ for _epoch in range(int(tcfg.epochs)):
for f_prompt, f_target in self._forget:
- if step >= n_steps:
+ if step >= self._max_examples:
break
- self._optimizer.zero_grad(set_to_none=True)
if method in ("npo", "simnpo"):
loss = self._step_preference(
_tokenize_pair, f_prompt, f_target, method, dev,
@@ -314,14 +370,39 @@ class UnlearnTrainerWrapper:
)
if loss is None:
continue
- loss.backward()
- self._optimizer.step()
+ # Accumulate unscaled gradients, then average by the actual
+ # number of contributing examples (including a partial batch).
lval = float(loss.item())
+ loss.backward()
+ accumulated += 1
+ step += 1
if initial_loss is None:
initial_loss = lval
final_loss = lval
- step += 1
- if step == 0:
+ if accumulated < batch_size * accumulation:
+ continue
+ for parameter in self.model.parameters():
+ if parameter.grad is not None:
+ parameter.grad.div_(accumulated)
+ torch.nn.utils.clip_grad_norm_(
+ self.model.parameters(), float(tcfg.max_grad_norm)
+ )
+ self._optimizer.step()
+ self._scheduler.step()
+ self._optimizer.zero_grad(set_to_none=True)
+ accumulated = 0
+ if accumulated:
+ for parameter in self.model.parameters():
+ if parameter.grad is not None:
+ parameter.grad.div_(accumulated)
+ torch.nn.utils.clip_grad_norm_(
+ self.model.parameters(), float(tcfg.max_grad_norm)
+ )
+ self._optimizer.step()
+ self._scheduler.step()
+ self._optimizer.zero_grad(set_to_none=True)
+ accumulated = 0
+ if step >= self._max_examples:
break
output_dir = _validated_output_dir(cfg.output)
@@ -357,7 +438,7 @@ class UnlearnTrainerWrapper:
)
input_ids, labels = tokenize_pair(
- self.tokenizer, prompt, target, max_length=_MAX_LENGTH
+ self.tokenizer, prompt, target, max_length=self.config.data.max_length
)
if (labels != -100).sum().item() == 0:
return None
@@ -391,7 +472,7 @@ class UnlearnTrainerWrapper:
self._retain_ce_idx = idx + 1
prompt, target = self._retain[idx % len(self._retain)]
input_ids, labels = tokenize_pair(
- self.tokenizer, prompt, target, max_length=_MAX_LENGTH
+ self.tokenizer, prompt, target, max_length=self.config.data.max_length
)
if (labels != -100).sum().item() == 0:
return None
@@ -422,7 +503,7 @@ class UnlearnTrainerWrapper:
captured.append(hidden)
f_ids, f_labels = tokenize_pair(
- self.tokenizer, f_prompt, f_target, max_length=_MAX_LENGTH
+ self.tokenizer, f_prompt, f_target, max_length=self.config.data.max_length
)
f_ids = f_ids.to(dev)
@@ -438,7 +519,7 @@ class UnlearnTrainerWrapper:
retain_frozen = None
if r_pair is not None and self._retain:
r_ids, _ = tokenize_pair(
- self.tokenizer, r_pair[0], r_pair[1], max_length=_MAX_LENGTH
+ self.tokenizer, r_pair[0], r_pair[1], max_length=self.config.data.max_length
)
r_ids = r_ids.to(dev)
captured.clear()
diff --git a/tests/test_issue805_optimizer_settings.py b/tests/test_issue805_optimizer_settings.py
new file mode 100644
index 00000000..5c7bd5c6
--- /dev/null
+++ b/tests/test_issue805_optimizer_settings.py
@@ -0,0 +1,286 @@
+"""Exercise #805's configuration values at real trainer/optimizer boundaries."""
+
+from __future__ import annotations
+
+import json
+import math
+from unittest.mock import patch
+
+import pytest
+
+
+def tiny_model(tmp_path, monkeypatch):
+ """An offline CPU model and tokenizer, including loadable task adapters."""
+ import torch
+ from tokenizers import Tokenizer
+ from tokenizers.models import WordLevel
+ from tokenizers.pre_tokenizers import Whitespace
+ from transformers import LlamaConfig, LlamaForCausalLM, PreTrainedTokenizerFast
+
+ monkeypatch.chdir(tmp_path)
+ previous_threads = torch.get_num_threads()
+ torch.set_num_threads(1)
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: False)
+ monkeypatch.setattr(torch.backends.mps, "is_available", lambda: False)
+ # Transformers caches MPS availability across tests. Override the Trainer's
+ # lookup too, so a prior MPS probe cannot move this CPU fixture's model.
+ monkeypatch.setattr("transformers.training_args.is_torch_mps_available", lambda: False)
+ torch.manual_seed(42)
+ tokenizer = Tokenizer(WordLevel(
+ {"<pad>": 0, "<unk>": 1, "<eos>": 2, "one": 3, "two": 4, "three": 5},
+ unk_token="<unk>",
+ ))
+ tokenizer.pre_tokenizer = Whitespace()
+ tokenizer = PreTrainedTokenizerFast(
+ tokenizer_object=tokenizer, pad_token="<pad>", unk_token="<unk>", eos_token="<eos>"
+ )
+ model = LlamaForCausalLM(LlamaConfig(
+ vocab_size=6, hidden_size=16, intermediate_size=32, num_hidden_layers=1,
+ num_attention_heads=2, num_key_value_heads=2, max_position_embeddings=64,
+ pad_token_id=0, eos_token_id=2,
+ ))
+ path = tmp_path / "tiny-model"
+ model.save_pretrained(path)
+ tokenizer.save_pretrained(path)
+ yield path
+ torch.set_num_threads(previous_threads)
+
+
+def _config(tiny_model, task, **training):
+ from soup_cli.config.schema import SoupConfig
+
+ return SoupConfig(
+ base=str(tiny_model), task=task, output="output-" + task,
+ data={"train": "train.jsonl", "forget_set": "forget.jsonl", "max_length": 64},
+ training={
+ "epochs": 2, "batch_size": 2, "gradient_accumulation_steps": 2,
+ "scheduler": "cosine", "warmup_ratio": 0.25, "weight_decay": 0.1,
+ "max_grad_norm": 0.3, "optimizer": "adafactor", "lr": 0.001,
+ "quantization": "none", "gradient_checkpointing": False,
+ "logging_steps": 1, "save_steps": 100,
+ "lora": {
+ "r": 0 if task == "prm" else 2,
+ "alpha": 4, "dropout": 0.0, "target_modules": ["q_proj"],
+ },
+ **training,
+ },
+ )
+
+
[email protected]("kind", ["prm", "moe_lora_routing"])
+def test_prm_and_mole_train_with_configured_optimizer(tiny_model, monkeypatch, kind):
+ from peft import LoraConfig, get_peft_model
+ from transformers import Adafactor, AutoModelForCausalLM
+
+ from soup_cli.trainer import mole_routing, prm
+
+ training = {"batch_size": "auto"}
+ if kind == "moe_lora_routing":
+ adapters = []
+ for index in range(2):
+ model = get_peft_model(
+ AutoModelForCausalLM.from_pretrained(tiny_model),
+ LoraConfig(r=2, target_modules=["q_proj"], task_type="CAUSAL_LM"),
+ )
+ path = tiny_model.parent / f"adapter-{index}"
+ model.save_pretrained(path)
+ adapters.append(str(path))
+ training["mole_task_adapters"] = adapters
+ module = mole_routing
+ wrapper_class = mole_routing.MoleRoutingTrainerWrapper
+ rows = [{"text": "one two three"}] * 8
+ else:
+ module = prm
+ wrapper_class = prm.PRMTrainerWrapper
+ rows = [{"prompt": "one", "completions": [" two", " three"], "labels": [0.0, 1.0]}] * 8
+ monkeypatch.setattr(module, "estimate_batch_size", lambda **kwargs: 2)
+ config = _config(tiny_model, kind, **training)
+ wrapper = wrapper_class(config, device="cpu")
+ wrapper.setup({"train": rows})
+ result = wrapper.train()
+ args = wrapper.trainer.args
+ assert args.per_device_train_batch_size == 2
+ assert args.warmup_steps == 1
+ assert args.weight_decay == 0.1
+ assert args.max_grad_norm == 0.3
+ assert args.optim.value == "adafactor"
+ assert args.lr_scheduler_type.value == "cosine"
+ assert not args.gradient_checkpointing
+ optimizer = wrapper.trainer.optimizer
+ optimizer = getattr(optimizer, "optimizer", optimizer)
+ assert isinstance(optimizer, Adafactor)
+ assert any(group["weight_decay"] == 0.1 for group in optimizer.param_groups)
+ assert result["total_steps"] == 4
+
+
+def test_ppo_constructs_real_config_with_nondefault_training_values(tiny_model):
+ from trl.experimental.ppo import PPOConfig
+
+ from soup_cli.trainer.ppo import PPOTrainerWrapper
+
+ class ConfigCapture:
+ def __init__(self, *, args, **kwargs):
+ self.args = args
+
+ def add_callback(self, callback):
+ pass
+
+ config = _config(tiny_model, "ppo", reward_fn="accuracy")
+ wrapper = PPOTrainerWrapper(config, device="cpu")
+ # Preserve actual model loading, dataset preparation and PPOConfig creation.
+ # Only stop before PPO's separate rollout-training loop, which #805 does not alter.
+ with (
+ patch(
+ "soup_cli.trainer.ppo._import_ppo_classes",
+ return_value=(ConfigCapture, PPOConfig, True),
+ ),
+ patch.object(wrapper, "_get_or_create_reward_model", return_value=None),
+ patch.object(wrapper, "_create_value_model", return_value=None),
+ ):
+ wrapper.setup({"train": [{"prompt": "one two", "answer": "three"}] * 8})
+ args = wrapper.trainer.args
+ assert isinstance(args, PPOConfig)
+ assert args.warmup_steps == 1
+ assert args.weight_decay == 0.1
+ assert args.max_grad_norm == 0.3
+ assert args.optim.value == "adafactor"
+ assert args.lr_scheduler_type.value == "cosine"
+ assert args.num_train_epochs == 2
+ assert args.logging_steps == 1
+ assert args.save_steps == 100
+ assert not args.gradient_checkpointing
+
+
+def _unlearn_wrapper(tiny_model, **training):
+ from soup_cli.trainer.unlearn import UnlearnTrainerWrapper
+
+ (tiny_model.parent / "forget.jsonl").write_text(
+ (json.dumps({"prompt": "one ", "completion": "two three"}) + "\n") * 5
+ )
+ training = {"epochs": 1, "unlearn_method": "simnpo", **training}
+ config = _config(tiny_model, "unlearn", **training)
+ wrapper = UnlearnTrainerWrapper(config, device="cpu")
+ wrapper.setup()
+ return wrapper
+
+
[email protected](("method", "model_loads"), [("simnpo", 1), ("npo", 2)])
+def test_unlearn_default_auto_reaches_real_training(tiny_model, monkeypatch, method, model_loads):
+ from soup_cli.utils import live_eval
+
+ with patch.object(
+ live_eval, "load_model_and_tokenizer", wraps=live_eval.load_model_and_tokenizer
+ ) as load_model:
+ wrapper = _unlearn_wrapper(tiny_model, batch_size="auto", unlearn_method=method)
+ assert load_model.call_count == model_loads
+ assert all("quantization" not in call.kwargs for call in load_model.call_args_list)
+ assert wrapper._batch_size == 1
+ assert wrapper.train()["total_steps"] == 5
+
+
+def test_unlearn_auto_stays_one_on_a_large_card(tiny_model, monkeypatch):
+ """``batch_size: auto`` means 1 on unlearn whatever the card reports.
+
+ Without a GPU (CPU boxes, every CI runner) the memory estimator itself
+ answers 1, so the test above cannot tell the ruling from a revert to
+ ``estimate_batch_size``. Report an 80 GB card, check that the estimator
+ then answers more than 1, and only then assert the ruling.
+ """
+ from soup_cli.trainer import unlearn
+ from soup_cli.utils import gpu
+
+ def large_card(*args, **kwargs):
+ return {"memory_total": "80.0 GB", "memory_total_bytes": 80 * 1024**3, "gpu_count": 1}
+
+ monkeypatch.setattr(gpu, "get_gpu_info", large_card)
+ # A revert that imported the helper at module level would bind its own name.
+ monkeypatch.setattr(unlearn, "get_gpu_info", large_card, raising=False)
+ estimate = gpu.estimate_batch_size(
+ model_params_b=gpu.model_size_from_name(str(tiny_model)),
+ seq_length=64,
+ gpu_memory_bytes=gpu.get_gpu_info()["memory_total_bytes"],
+ quantization="none",
+ lora_r=2,
+ )
+ assert estimate > 1, "the mocked card no longer separates the ruling from the estimator"
+
+ wrapper = _unlearn_wrapper(tiny_model, batch_size="auto")
+ assert wrapper._batch_size == 1
+ # 5 forget rows, one epoch, accumulation 2: three updates, not one.
+ assert wrapper._max_updates == 3
+
+
[email protected](("batch_size", "accumulation"), [(1, 1), (1, 4), (2, 4)])
+def test_unlearn_reports_unscaled_loss_and_example_count(tiny_model, batch_size, accumulation):
+ import torch
+ from transformers import Adafactor
+
+ from soup_cli.utils.live_eval import _tokenize_pair
+
+ wrapper = _unlearn_wrapper(
+ tiny_model, batch_size=batch_size, gradient_accumulation_steps=accumulation
+ )
+ expected = wrapper._step_preference(
+ _tokenize_pair, "one ", "two three", "simnpo", "cpu"
+ ).item()
+ assert isinstance(wrapper._optimizer, Adafactor)
+ assert wrapper._optimizer.param_groups[0]["weight_decay"] == 0.1
+ updates = math.ceil(5 / (batch_size * accumulation))
+ with patch("torch.nn.utils.clip_grad_norm_", wraps=torch.nn.utils.clip_grad_norm_) as clip:
+ result = wrapper.train()
+ assert result["initial_loss"] == pytest.approx(expected)
+ assert result["total_steps"] == 5
+ assert clip.call_count == updates
+ assert all(call.args[1] == 0.3 for call in clip.call_args_list)
+ assert wrapper._scheduler.last_epoch == updates
+ warmup = int(updates * wrapper.config.training.warmup_ratio)
+ probe_step = warmup + 0.25 * (updates - warmup)
+ assert wrapper._scheduler.lr_lambdas[0](probe_step) == pytest.approx(
+ 0.5 * (1.0 + math.cos(math.pi * 0.25))
+ )
+
+
+def test_unlearn_uses_configured_sequence_length(tiny_model):
+ from soup_cli.utils.live_eval import _tokenize_pair
+
+ wrapper = _unlearn_wrapper(tiny_model)
+ lengths = []
+
+ def capture(*args, **kwargs):
+ lengths.append(kwargs["max_length"])
+ return _tokenize_pair(*args, **kwargs)
+
+ wrapper._step_preference(capture, "one ", "two three " * 20, "simnpo", "cpu")
+ assert lengths == [64]
+
+
+def test_unlearn_partial_group_averages_actual_gradients(tiny_model):
+ import torch
+
+ wrapper = _unlearn_wrapper(tiny_model, batch_size=2, gradient_accumulation_steps=2)
+ parameter = next(p for p in wrapper.model.parameters() if p.requires_grad)
+ gradients = []
+ real_clip = torch.nn.utils.clip_grad_norm_
+
+ def capture_clip(parameters, max_norm):
+ gradients.append(parameter.grad.detach().clone())
+ return real_clip(parameters, max_norm)
+
+ with (
+ patch.object(wrapper, "_step_preference", side_effect=lambda *args: 2 * parameter.sum()),
+ patch("torch.nn.utils.clip_grad_norm_", side_effect=capture_clip),
+ ):
+ result = wrapper.train()
+ assert result["total_steps"] == 5
+ assert len(gradients) == 2
+ for gradient in gradients:
+ torch.testing.assert_close(gradient, torch.full_like(gradient, 2.0))
+
+
+def test_unlearn_cap_still_counts_examples(tiny_model, monkeypatch):
+ from soup_cli.trainer import unlearn
+
+ monkeypatch.setattr(unlearn, "_MAX_STEPS_CAP", 3)
+ wrapper = _unlearn_wrapper(tiny_model, batch_size=2, gradient_accumulation_steps=4)
+ assert wrapper.train()["total_steps"] == 3
diff --git a/tests/test_issue899_loss_summary.py b/tests/test_issue899_loss_summary.py
index acc0b537..ad8798b9 100644
--- a/tests/test_issue899_loss_summary.py
+++ b/tests/test_issue899_loss_summary.py
@@ -229,6 +229,9 @@ class _StubSavedObject:
def save_pretrained(self, output_dir):
pass
+ def parameters(self):
+ return []
+
class _StubLoss:
def __init__(self, value):
@@ -242,7 +245,11 @@ class _StubLoss:
def _run_unlearn_loss_result(tmp_path, monkeypatch, losses):
- monkeypatch.setitem(sys.modules, "torch", types.ModuleType("torch"))
+ torch = types.ModuleType("torch")
+ torch.nn = types.SimpleNamespace(
+ utils=types.SimpleNamespace(clip_grad_norm_=lambda *args: None)
+ )
+ monkeypatch.setitem(sys.modules, "torch", torch)
from soup_cli.config.schema import SoupConfig
from soup_cli.trainer.unlearn import UnlearnTrainerWrapper
@@ -261,7 +268,9 @@ def _run_unlearn_loss_result(tmp_path, monkeypatch, losses):
wrapper.tokenizer = _StubSavedObject()
wrapper._dev = "cpu"
wrapper._optimizer = _StubOptimizer()
+ wrapper._scheduler = types.SimpleNamespace(step=lambda: None)
wrapper._forget = [("prompt", "target")] * max(1, len(losses))
+ wrapper._max_examples = len(wrapper._forget)
wrapper._retain = []
remaining = iter(losses)
monkeypatch.setattr(