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): dynamically resolve warmup ratio over actual optimizer steps (#1431) (#1507)

Nurkhan Esenbekb717741d0a10
diff --git a/changelog.d/0.75.1/1507.fixed.md b/changelog.d/0.75.1/1507.fixed.md
new file mode 100644
index 00000000..ee246c5a
--- /dev/null
+++ b/changelog.d/0.75.1/1507.fixed.md
@@ -0,0 +1,2 @@
+- **`training.warmup_ratio` dynamically resolves over actual optimizer steps instead of a precomputed estimate (#1431 by @kok-o in #1507).**
+ Trainer wrappers previously turned `warmup_ratio` into fixed `warmup_steps` using raw dataset row counts before constructing the trainer. Under GRPO (where prompts repeat `num_generations` times), SFT with packing or multipack, and pretrain with packing, the trainer executed a different step count, causing warmup to shrink or cover the entire run so peak learning rate was never reached. All wrappers now pass `warmup_ratio` through via `resolve_trainer_warmup_steps` directly to `TrainingArguments(warmup_steps=...)`, letting transformers resolve warmup dynamically as `ceil(real_optimizer_steps * warmup_ratio)`. Runs with fewer than 34 optimizer steps at the default `warmup_ratio: 0.03` now resolve to exactly one warmup step, whose first step trains at learning rate 0.
diff --git a/src/soup_cli/trainer/asr.py b/src/soup_cli/trainer/asr.py
index 1a3b7f21..ec26254f 100644
--- a/src/soup_cli/trainer/asr.py
+++ b/src/soup_cli/trainer/asr.py
@@ -21,7 +21,6 @@ Security / robustness:
from __future__ import annotations
-import math
import os
import time
from pathlib import Path
@@ -316,11 +315,10 @@ class AsrTrainerWrapper:
output_dir.mkdir(parents=True, exist_ok=True)
batch_size = tcfg.batch_size if tcfg.batch_size != "auto" else 8
- total_steps = (
- math.ceil(len(train_ds) / batch_size / tcfg.gradient_accumulation_steps)
- * tcfg.epochs
- )
- warmup_steps = int(total_steps * tcfg.warmup_ratio)
+ # --- Calculate warmup steps from ratio (#1431) ---
+ from soup_cli.utils.warmup import resolve_trainer_warmup_steps
+
+ warmup_steps = resolve_trainer_warmup_steps(tcfg.warmup_ratio)
# Mixed precision by GPU capability — bf16=cuda was hardcoded, which
# crashes on pre-Ampere cards (T4 / GTX 16xx) that lack bf16. Fall back
diff --git a/src/soup_cli/trainer/bco.py b/src/soup_cli/trainer/bco.py
index 005ee0e7..ed436fed 100644
--- a/src/soup_cli/trainer/bco.py
+++ b/src/soup_cli/trainer/bco.py
@@ -10,7 +10,6 @@ Each row is internally split into two rows for TRL's BCOTrainer
from __future__ import annotations
-import math
import time
from pathlib import Path
from typing import TYPE_CHECKING, Optional
@@ -186,12 +185,10 @@ class BCOTrainerWrapper:
output_dir = output_dir / cfg.experiment_name
output_dir.mkdir(parents=True, exist_ok=True)
- # --- Calculate warmup steps from ratio ---
- total_steps = (
- math.ceil(len(train_ds) / batch_size / tcfg.gradient_accumulation_steps)
- * tcfg.epochs
- )
- warmup_steps = int(total_steps * tcfg.warmup_ratio)
+ # --- Calculate warmup steps from ratio (#1431) ---
+ from soup_cli.utils.warmup import resolve_trainer_warmup_steps
+
+ warmup_steps = resolve_trainer_warmup_steps(tcfg.warmup_ratio)
# --- BCO config ---
_bf16, _fp16 = bf16_fp16_flags(self.device)
diff --git a/src/soup_cli/trainer/classifier.py b/src/soup_cli/trainer/classifier.py
index 6f423917..ab192090 100644
--- a/src/soup_cli/trainer/classifier.py
+++ b/src/soup_cli/trainer/classifier.py
@@ -24,7 +24,6 @@ trust_remote_code threaded through the v0.36.0 resolver.
from __future__ import annotations
-import math
import time
from pathlib import Path
from typing import Any, List, Union
@@ -392,11 +391,10 @@ class ClassifierTrainerWrapper:
output_dir.mkdir(parents=True, exist_ok=True)
batch_size = tcfg.batch_size if tcfg.batch_size != "auto" else 8
- total_steps = (
- math.ceil(len(train_ds) / batch_size / tcfg.gradient_accumulation_steps)
- * tcfg.epochs
- )
- warmup_steps = int(total_steps * tcfg.warmup_ratio)
+ # --- Calculate warmup steps from ratio (#1431) ---
+ from soup_cli.utils.warmup import resolve_trainer_warmup_steps
+
+ warmup_steps = resolve_trainer_warmup_steps(tcfg.warmup_ratio)
_bf16, _fp16 = bf16_fp16_flags(self.device)
args = TrainingArguments(
diff --git a/src/soup_cli/trainer/distill.py b/src/soup_cli/trainer/distill.py
index c47ded7d..6194942d 100644
--- a/src/soup_cli/trainer/distill.py
+++ b/src/soup_cli/trainer/distill.py
@@ -803,11 +803,10 @@ class DistillTrainerWrapper:
output_dir.mkdir(parents=True, exist_ok=True)
batch_size = tcfg.batch_size if tcfg.batch_size != "auto" else 4
- total_steps = (
- math.ceil(len(train_ds) / batch_size / tcfg.gradient_accumulation_steps)
- * tcfg.epochs
- )
- warmup_steps = int(total_steps * tcfg.warmup_ratio)
+ # --- Calculate warmup steps from ratio (#1431) ---
+ from soup_cli.utils.warmup import resolve_trainer_warmup_steps
+
+ warmup_steps = resolve_trainer_warmup_steps(tcfg.warmup_ratio)
_bf16, _fp16 = bf16_fp16_flags(self.device)
args = TrainingArguments(
diff --git a/src/soup_cli/trainer/dpo.py b/src/soup_cli/trainer/dpo.py
index a7b4ea0e..62b0e872 100644
--- a/src/soup_cli/trainer/dpo.py
+++ b/src/soup_cli/trainer/dpo.py
@@ -161,14 +161,10 @@ class DPOTrainerWrapper(StreamingSetupMixin):
output_dir = output_dir / cfg.experiment_name
output_dir.mkdir(parents=True, exist_ok=True)
- # --- Calculate warmup steps from ratio ---
- import math
+ # --- Calculate warmup steps from ratio (#1431) ---
+ from soup_cli.utils.warmup import resolve_trainer_warmup_steps
- total_steps = (
- math.ceil(len(train_ds) / batch_size / tcfg.gradient_accumulation_steps)
- * tcfg.epochs
- )
- warmup_steps = int(total_steps * tcfg.warmup_ratio)
+ warmup_steps = resolve_trainer_warmup_steps(tcfg.warmup_ratio)
# --- DPO config ---
from soup_cli.utils.layer_stream import should_enable_hf_gradient_checkpointing
diff --git a/src/soup_cli/trainer/embedding.py b/src/soup_cli/trainer/embedding.py
index b37b088a..845b568a 100644
--- a/src/soup_cli/trainer/embedding.py
+++ b/src/soup_cli/trainer/embedding.py
@@ -1,6 +1,5 @@
"""Embedding model trainer — contrastive/triplet loss for sentence embeddings."""
-import math
import time
from pathlib import Path
from typing import Optional
@@ -168,12 +167,10 @@ class EmbeddingTrainerWrapper:
f"pooling={tcfg.embedding_pooling}"
)
- # --- Calculate warmup steps from ratio ---
- total_steps = (
- math.ceil(len(train_ds) / batch_size / tcfg.gradient_accumulation_steps)
- * tcfg.epochs
- )
- warmup_steps = int(total_steps * tcfg.warmup_ratio)
+ # --- Calculate warmup steps from ratio (#1431) ---
+ from soup_cli.utils.warmup import resolve_trainer_warmup_steps
+
+ warmup_steps = resolve_trainer_warmup_steps(tcfg.warmup_ratio)
# --- Training args ---
_bf16, _fp16 = bf16_fp16_flags(self.device)
diff --git a/src/soup_cli/trainer/grpo.py b/src/soup_cli/trainer/grpo.py
index ad1aec9e..6a62fb63 100644
--- a/src/soup_cli/trainer/grpo.py
+++ b/src/soup_cli/trainer/grpo.py
@@ -460,13 +460,10 @@ class GRPOTrainerWrapper:
output_dir = output_dir / cfg.experiment_name
output_dir.mkdir(parents=True, exist_ok=True)
- # --- Calculate warmup steps from ratio ---
- import math
+ # --- Calculate warmup steps from ratio (#1431) ---
+ from soup_cli.utils.warmup import resolve_trainer_warmup_steps
- total_steps = (
- math.ceil(len(train_ds) / batch_size / tcfg.gradient_accumulation_steps) * tcfg.epochs
- )
- warmup_steps = int(total_steps * tcfg.warmup_ratio)
+ warmup_steps = resolve_trainer_warmup_steps(tcfg.warmup_ratio)
# --- Warn if running on CPU (trl GRPO has known CPU issues) ---
if self.device == "cpu":
diff --git a/src/soup_cli/trainer/ipo.py b/src/soup_cli/trainer/ipo.py
index 092b9f2e..d955ba44 100644
--- a/src/soup_cli/trainer/ipo.py
+++ b/src/soup_cli/trainer/ipo.py
@@ -1,6 +1,5 @@
"""IPO (Identity Preference Optimization) trainer — wraps trl.DPOTrainer with loss_type='ipo'."""
-import math
import time
from pathlib import Path
from typing import Optional
@@ -133,12 +132,10 @@ class IPOTrainerWrapper:
output_dir = output_dir / cfg.experiment_name
output_dir.mkdir(parents=True, exist_ok=True)
- # --- Calculate warmup steps from ratio ---
- total_steps = (
- math.ceil(len(train_ds) / batch_size / tcfg.gradient_accumulation_steps)
- * tcfg.epochs
- )
- warmup_steps = int(total_steps * tcfg.warmup_ratio)
+ # --- Calculate warmup steps from ratio (#1431) ---
+ from soup_cli.utils.warmup import resolve_trainer_warmup_steps
+
+ warmup_steps = resolve_trainer_warmup_steps(tcfg.warmup_ratio)
# --- IPO config (DPO with loss_type='ipo') ---
# In IPO, the beta parameter acts as tau (regularization strength)
diff --git a/src/soup_cli/trainer/kto.py b/src/soup_cli/trainer/kto.py
index d0902011..b4f4acbf 100644
--- a/src/soup_cli/trainer/kto.py
+++ b/src/soup_cli/trainer/kto.py
@@ -1,6 +1,5 @@
"""KTO (Kahneman-Tversky Optimization) trainer — wraps trl.KTOTrainer."""
-import math
import time
from pathlib import Path
from typing import Optional
@@ -157,12 +156,10 @@ class KTOTrainerWrapper(StreamingSetupMixin):
output_dir = output_dir / cfg.experiment_name
output_dir.mkdir(parents=True, exist_ok=True)
- # --- Calculate warmup steps from ratio ---
- total_steps = (
- math.ceil(len(train_ds) / batch_size / tcfg.gradient_accumulation_steps)
- * tcfg.epochs
- )
- warmup_steps = int(total_steps * tcfg.warmup_ratio)
+ # --- Calculate warmup steps from ratio (#1431) ---
+ from soup_cli.utils.warmup import resolve_trainer_warmup_steps
+
+ warmup_steps = resolve_trainer_warmup_steps(tcfg.warmup_ratio)
# --- KTO config ---
from soup_cli.utils.layer_stream import should_enable_hf_gradient_checkpointing
diff --git a/src/soup_cli/trainer/online_dpo.py b/src/soup_cli/trainer/online_dpo.py
index 350c792e..073f76e0 100644
--- a/src/soup_cli/trainer/online_dpo.py
+++ b/src/soup_cli/trainer/online_dpo.py
@@ -280,14 +280,10 @@ class OnlineDPOTrainerWrapper:
output_dir = output_dir / cfg.experiment_name
output_dir.mkdir(parents=True, exist_ok=True)
- # --- Warmup from ratio ---
- import math
+ # --- Warmup from ratio (#1431) ---
+ from soup_cli.utils.warmup import resolve_trainer_warmup_steps
- total_steps = (
- math.ceil(len(train_ds) / batch_size / tcfg.gradient_accumulation_steps)
- * tcfg.epochs
- )
- warmup_steps = int(total_steps * tcfg.warmup_ratio)
+ warmup_steps = resolve_trainer_warmup_steps(tcfg.warmup_ratio)
_bf16, _fp16 = bf16_fp16_flags(self.device)
odpo_config = online_dpo_config_cls(
diff --git a/src/soup_cli/trainer/orpo.py b/src/soup_cli/trainer/orpo.py
index faf8d1a1..891a8b5d 100644
--- a/src/soup_cli/trainer/orpo.py
+++ b/src/soup_cli/trainer/orpo.py
@@ -1,6 +1,5 @@
"""ORPO (Odds Ratio Preference Optimization) trainer — wraps trl.ORPOTrainer."""
-import math
import time
from pathlib import Path
from typing import Optional
@@ -163,12 +162,10 @@ class ORPOTrainerWrapper(StreamingSetupMixin):
output_dir = output_dir / cfg.experiment_name
output_dir.mkdir(parents=True, exist_ok=True)
- # --- Calculate warmup steps from ratio ---
- total_steps = (
- math.ceil(len(train_ds) / batch_size / tcfg.gradient_accumulation_steps)
- * tcfg.epochs
- )
- warmup_steps = int(total_steps * tcfg.warmup_ratio)
+ # --- Calculate warmup steps from ratio (#1431) ---
+ from soup_cli.utils.warmup import resolve_trainer_warmup_steps
+
+ warmup_steps = resolve_trainer_warmup_steps(tcfg.warmup_ratio)
# --- ORPO config ---
from soup_cli.utils.layer_stream import should_enable_hf_gradient_checkpointing
diff --git a/src/soup_cli/trainer/pretrain.py b/src/soup_cli/trainer/pretrain.py
index 4b9599cd..10f7e8cd 100644
--- a/src/soup_cli/trainer/pretrain.py
+++ b/src/soup_cli/trainer/pretrain.py
@@ -1,6 +1,5 @@
"""Pretrain (Continued Pre-training) trainer — wraps HuggingFace SFTTrainer for CLM."""
-import math
import time
from pathlib import Path
from typing import Optional
@@ -155,12 +154,10 @@ class PretrainTrainerWrapper:
output_dir = output_dir / cfg.experiment_name
output_dir.mkdir(parents=True, exist_ok=True)
- # --- Calculate warmup steps from ratio ---
- total_steps = (
- math.ceil(len(train_ds) / batch_size / tcfg.gradient_accumulation_steps)
- * tcfg.epochs
- )
- warmup_steps = int(total_steps * tcfg.warmup_ratio)
+ # --- Calculate warmup steps from ratio (#1431) ---
+ from soup_cli.utils.warmup import resolve_trainer_warmup_steps
+
+ warmup_steps = resolve_trainer_warmup_steps(tcfg.warmup_ratio)
# --- Training args ---
_bf16, _fp16 = bf16_fp16_flags(self.device)
diff --git a/src/soup_cli/trainer/reward_model.py b/src/soup_cli/trainer/reward_model.py
index c97b0cfd..0005f828 100644
--- a/src/soup_cli/trainer/reward_model.py
+++ b/src/soup_cli/trainer/reward_model.py
@@ -133,14 +133,10 @@ class RewardModelTrainerWrapper:
output_dir = output_dir / cfg.experiment_name
output_dir.mkdir(parents=True, exist_ok=True)
- # --- Calculate warmup steps from ratio ---
- import math
+ # --- Calculate warmup steps from ratio (#1431) ---
+ from soup_cli.utils.warmup import resolve_trainer_warmup_steps
- total_steps = (
- math.ceil(len(train_ds) / batch_size / tcfg.gradient_accumulation_steps)
- * tcfg.epochs
- )
- warmup_steps = int(total_steps * tcfg.warmup_ratio)
+ warmup_steps = resolve_trainer_warmup_steps(tcfg.warmup_ratio)
# --- Reward config ---
_bf16, _fp16 = bf16_fp16_flags(self.device, allow_mps_bf16=True)
diff --git a/src/soup_cli/trainer/sft.py b/src/soup_cli/trainer/sft.py
index 1dba5343..cbb3f0dd 100644
--- a/src/soup_cli/trainer/sft.py
+++ b/src/soup_cli/trainer/sft.py
@@ -935,14 +935,10 @@ class SFTTrainerWrapper(StreamingSetupMixin):
if tcfg.quantization_aware == "quest":
self._setup_quest(train_ds)
- # --- Calculate warmup steps from ratio ---
- import math
+ # --- Calculate warmup steps from ratio (#1431) ---
+ from soup_cli.utils.warmup import resolve_trainer_warmup_steps
- total_steps = (
- math.ceil(len(train_ds) / batch_size / tcfg.gradient_accumulation_steps)
- * tcfg.epochs
- )
- warmup_steps = int(total_steps * tcfg.warmup_ratio)
+ warmup_steps = resolve_trainer_warmup_steps(tcfg.warmup_ratio)
# --- Training args ---
# v0.33.0 #58: auto_mixed_precision wires pick_mixed_precision()
diff --git a/src/soup_cli/trainer/simpo.py b/src/soup_cli/trainer/simpo.py
index d1c70380..bec504d7 100644
--- a/src/soup_cli/trainer/simpo.py
+++ b/src/soup_cli/trainer/simpo.py
@@ -1,6 +1,5 @@
"""SimPO (Simple Preference Optimization) trainer — wraps trl.CPOTrainer."""
-import math
import time
from pathlib import Path
from typing import Optional
@@ -161,12 +160,10 @@ class SimPOTrainerWrapper(StreamingSetupMixin):
output_dir = output_dir / cfg.experiment_name
output_dir.mkdir(parents=True, exist_ok=True)
- # --- Calculate warmup steps from ratio ---
- total_steps = (
- math.ceil(len(train_ds) / batch_size / tcfg.gradient_accumulation_steps)
- * tcfg.epochs
- )
- warmup_steps = int(total_steps * tcfg.warmup_ratio)
+ # --- Calculate warmup steps from ratio (#1431) ---
+ from soup_cli.utils.warmup import resolve_trainer_warmup_steps
+
+ warmup_steps = resolve_trainer_warmup_steps(tcfg.warmup_ratio)
# --- SimPO config (via CPOTrainer with loss_type='simpo') ---
from soup_cli.utils.layer_stream import should_enable_hf_gradient_checkpointing
diff --git a/src/soup_cli/utils/warmup.py b/src/soup_cli/utils/warmup.py
index f542d288..78b87c28 100644
--- a/src/soup_cli/utils/warmup.py
+++ b/src/soup_cli/utils/warmup.py
@@ -48,3 +48,18 @@ def compute_warmup_steps(
total_steps = steps_per_epoch * epochs
raw = int(round(total_steps * ratio))
return max(MIN_WARMUP, min(MAX_WARMUP, raw))
+
+
+def resolve_trainer_warmup_steps(warmup_ratio: float | int | None) -> float:
+ """Return the warmup fraction to pass to HF TrainingArguments(warmup_steps=...).
+
+ HuggingFace TrainingArguments interprets a float ``warmup_steps`` in [0, 1) as
+ a warmup ratio over the actual number of optimizer steps executed by the trainer:
+ warmup_steps = math.ceil(num_training_steps * warmup_steps)
+ """
+ if warmup_ratio is None:
+ return 0.0
+ val = float(warmup_ratio)
+ if not (0.0 <= val < 1.0):
+ raise ValueError(f"warmup_ratio must be in [0.0, 1.0), got {val}")
+ return val
diff --git a/tests/test_issue1225_online_dpo_unranked_pairs.py b/tests/test_issue1225_online_dpo_unranked_pairs.py
index c7195eab..b5bb1679 100644
--- a/tests/test_issue1225_online_dpo_unranked_pairs.py
+++ b/tests/test_issue1225_online_dpo_unranked_pairs.py
@@ -147,7 +147,8 @@ def _build(path, monkeypatch, evaluator, *, batch_size=4, n_prompts=4, extra="")
' online_dpo_judge: "ollama://llama3.1"\n'
f" epochs: 1\n batch_size: {batch_size}\n"
" online_dpo_max_new_tokens: 6\n lr: 1e-4\n quantization: none\n"
- " seed: 7\n" + extra + f"output: {(path / 'out').as_posix()}\n"
+ " seed: 7\n"
+ " warmup_ratio: 0.0\n" + extra + f"output: {(path / 'out').as_posix()}\n"
)
rows = [
{"messages": [{"role": "user", "content": text}]} for text in _PROMPTS[:n_prompts]
diff --git a/tests/test_issue1431_warmup_steps.py b/tests/test_issue1431_warmup_steps.py
new file mode 100644
index 00000000..3ad73b81
--- /dev/null
+++ b/tests/test_issue1431_warmup_steps.py
@@ -0,0 +1,291 @@
+"""Tests for dynamic warmup resolution across trainer wrappers (#1431).
+
+Verifies that:
+1. All trainer wrappers pass warmup_ratio directly through as warmup_steps to
+ HuggingFace TrainingArguments, so transformers dynamically resolves warmup
+ over the trainer's actual optimizer steps (ceil(max_steps * warmup_ratio)).
+2. GRPO warmup no longer shrinks by num_generations.
+3. SFT with packing / multipack and pretrain with packing scale warmup to the
+ real packed step count.
+4. Unpacked SFT control matches the expected warmup within one step.
+5. All 15 wrappers resolve warmup_steps as the configured fraction without multiplying
+ warmup_ratio into a step count.
+"""
+
+from __future__ import annotations
+
+import ast
+import math
+from pathlib import Path
+
+import pytest
+import torch
+from tokenizers import AddedToken, Tokenizer, models, pre_tokenizers
+from transformers import LlamaConfig, LlamaForCausalLM, PreTrainedTokenizerFast
+
+from soup_cli.config.loader import load_config_from_string
+from soup_cli.utils.warmup import resolve_trainer_warmup_steps
+from tests import test_trl_preference_config_contract as contract
+
+WORDS = ["<pad>", "<s>", "</s>", "<unk>", "apple", "banana", "cherry", "date"]
+TRAINER_DIR = Path(__file__).resolve().parent.parent / "src" / "soup_cli" / "trainer"
+WARMUP_WRAPPERS = (
+ "asr",
+ "bco",
+ "classifier",
+ "distill",
+ "dpo",
+ "embedding",
+ "grpo",
+ "ipo",
+ "kto",
+ "online_dpo",
+ "orpo",
+ "pretrain",
+ "reward_model",
+ "sft",
+ "simpo",
+)
+
+
[email protected](scope="module")
+def tiny_llama_model(tmp_path_factory: pytest.TempPathFactory) -> str:
+ tmp = tmp_path_factory.mktemp("tiny_llama")
+ raw = Tokenizer(models.BPE())
+ raw.pre_tokenizer = pre_tokenizers.Whitespace()
+ vocab = {w: i for i, w in enumerate(WORDS)}
+ raw.add_tokens([AddedToken(w, special=True) for w in WORDS[:4]])
+ raw.add_tokens([AddedToken(w) for w in WORDS[4:]])
+ tok = PreTrainedTokenizerFast(
+ tokenizer_object=raw,
+ bos_token="<s>",
+ eos_token="</s>",
+ pad_token="<pad>",
+ unk_token="<unk>",
+ )
+ tok.chat_template = (
+ "{% for m in messages %}{{ '<|' + m['role'] + '|> ' }}"
+ "{% if m['role'] == 'assistant' %}{% generation %}{{ m['content'] + ' </s>' }}"
+ "{% endgeneration %}{% else %}{{ m['content'] + ' </s> ' }}{% endif %}{% endfor %}"
+ "{% if add_generation_prompt %}{{ '<|assistant|> ' }}{% endif %}"
+ )
+ torch.manual_seed(0)
+ LlamaForCausalLM(
+ LlamaConfig(
+ vocab_size=len(vocab),
+ hidden_size=32,
+ intermediate_size=64,
+ num_hidden_layers=2,
+ num_attention_heads=2,
+ num_key_value_heads=2,
+ max_position_embeddings=256,
+ pad_token_id=0,
+ bos_token_id=1,
+ eos_token_id=2,
+ )
+ ).save_pretrained(str(tmp))
+ tok.save_pretrained(str(tmp))
+ return str(tmp).replace("\\", "/")
+
+
+class TestWarmupHelper:
+ def test_resolve_trainer_warmup_steps(self) -> None:
+ assert resolve_trainer_warmup_steps(0.0) == 0.0
+ assert resolve_trainer_warmup_steps(0.1) == 0.1
+ assert resolve_trainer_warmup_steps(0.5) == 0.5
+ assert resolve_trainer_warmup_steps(None) == 0.0
+
+ def test_invalid_ratio_rejected(self) -> None:
+ with pytest.raises(ValueError, match="warmup_ratio must be in"):
+ resolve_trainer_warmup_steps(-0.01)
+ with pytest.raises(ValueError, match="warmup_ratio must be in"):
+ resolve_trainer_warmup_steps(1.0)
+ with pytest.raises(ValueError, match="warmup_ratio must be in"):
+ resolve_trainer_warmup_steps(1.5)
+
+
+class TestGRPOWarmup:
+ @pytest.mark.parametrize(
+ ("prompts", "batch", "accum", "gens", "ratio", "epochs"),
+ [
+ (40, 4, 1, 4, 0.5, 1),
+ (40, 8, 1, 8, 0.5, 1),
+ (64, 4, 4, 4, 0.1, 1),
+ (40, 4, 1, 4, 0.25, 2),
+ ],
+ )
+ def test_grpo_warmup_matches_real_steps(
+ self,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ tiny_llama_model: str,
+ prompts: int,
+ batch: int,
+ accum: int,
+ gens: int,
+ ratio: float,
+ epochs: int,
+ ) -> None:
+ from soup_cli.trainer.grpo import GRPOTrainerWrapper
+
+ monkeypatch.chdir(tmp_path)
+ out_dir = str(tmp_path / "out-grpo").replace("\\", "/")
+ cfg = load_config_from_string(
+ f"base: {tiny_llama_model}\ntask: grpo\n"
+ "data: {train: ./unused.jsonl, max_length: 64}\n"
+ f"training:\n epochs: {epochs}\n batch_size: {batch}\n"
+ f" gradient_accumulation_steps: {accum}\n"
+ f" num_generations: {gens}\n warmup_ratio: {ratio}\n reward_fn: accuracy\n"
+ " quantization: none\n lora: {r: 4, alpha: 8, target_modules: [q_proj, v_proj]}\n"
+ f"output: {out_dir}\n"
+ )
+ row = {
+ "messages": [
+ {"role": "user", "content": "what is apple ?"},
+ {"role": "assistant", "content": "apple"},
+ ]
+ }
+ rows = [row] * prompts
+ wrapper = GRPOTrainerWrapper(cfg, device="cpu")
+ wrapper.setup({"train": rows})
+ trainer = wrapper.trainer
+ steps = (len(trainer.get_train_dataloader()) // accum) * epochs
+ expected_warmup = math.ceil(steps * ratio)
+ resolved_warmup = trainer.args.get_warmup_steps(steps)
+ assert resolved_warmup == expected_warmup
+ assert trainer.args.warmup_steps == ratio
+
+ # Mutation check: the old row-count formula would have shrunk warmup by gens
+ old_formula_steps = int(math.ceil(prompts / batch / accum) * epochs * ratio)
+ if gens > 1:
+ assert resolved_warmup > old_formula_steps
+
+
+class TestSFTWarmup:
+ @pytest.mark.parametrize("packing_mode", ["none", "packing", "multipack"])
+ @pytest.mark.parametrize("epochs", [1, 2])
+ def test_sft_warmup_scales_to_packed_optimizer_steps(
+ self,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ tiny_llama_model: str,
+ packing_mode: str,
+ epochs: int,
+ ) -> None:
+ from soup_cli.trainer.sft import SFTTrainerWrapper
+
+ monkeypatch.chdir(tmp_path)
+ out_dir = str(tmp_path / f"out-sft-{packing_mode}-{epochs}").replace("\\", "/")
+ extra = ""
+ if packing_mode == "packing":
+ extra = " packing: true\n"
+ elif packing_mode == "multipack":
+ extra = " multipack: true\n"
+
+ cfg = load_config_from_string(
+ f"base: {tiny_llama_model}\ntask: sft\n"
+ "data: {train: ./unused.jsonl, format: chatml, max_length: 64}\n"
+ f"training:\n epochs: {epochs}\n batch_size: 1\n gradient_accumulation_steps: 1\n"
+ " lr: 1.0e-3\n warmup_ratio: 0.5\n"
+ " scheduler: cosine\n quantization: none\n"
+ f"{extra} lora: {{r: 4, alpha: 8}}\noutput: {out_dir}\n"
+ )
+ rows = [
+ {
+ "messages": [
+ {"role": "user", "content": f"what is {w} ?"},
+ {"role": "assistant", "content": "ok"},
+ ]
+ }
+ for w in WORDS[4:] * 5
+ ]
+ wrapper = SFTTrainerWrapper(cfg, device="cpu")
+ wrapper.setup({"train": rows})
+ trainer = wrapper.trainer
+ steps = len(trainer.get_train_dataloader()) * epochs
+ resolved_warmup = trainer.args.get_warmup_steps(steps)
+ expected_warmup = math.ceil(steps * 0.5)
+ assert resolved_warmup == expected_warmup
+ assert trainer.args.warmup_steps == 0.5
+
+
+class TestPretrainWarmup:
+ def test_pretrain_warmup_ratio_preserved(
+ self,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ tiny_llama_model: str,
+ ) -> None:
+ from soup_cli.trainer.pretrain import PretrainTrainerWrapper
+
+ monkeypatch.chdir(tmp_path)
+ out_dir = str(tmp_path / "out-pretrain").replace("\\", "/")
+ cfg = load_config_from_string(
+ f"base: {tiny_llama_model}\ntask: pretrain\n"
+ "data: {train: ./unused.jsonl, max_length: 64}\n"
+ "training:\n epochs: 1\n batch_size: 2\n gradient_accumulation_steps: 1\n"
+ " lr: 1.0e-3\n warmup_ratio: 0.25\n"
+ f" quantization: none\n lora: {{r: 4, alpha: 8}}\noutput: {out_dir}\n"
+ )
+ rows = [{"text": f"apple {w} banana"} for w in WORDS[4:] * 4]
+ wrapper = PretrainTrainerWrapper(cfg, device="cpu")
+ wrapper.setup({"train": rows})
+ trainer = wrapper.trainer
+ steps = len(trainer.get_train_dataloader())
+ assert trainer.args.warmup_steps == 0.25
+ assert trainer.args.get_warmup_steps(steps) == math.ceil(steps * 0.25)
+
+
[email protected]("task", contract._ALL_SIX)
+def test_live_preference_trainer_carries_the_warmup_fraction(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, task: str
+) -> None:
+ wrapper = contract._build(tmp_path, monkeypatch, task)
+ assert wrapper.trainer.args.warmup_steps == pytest.approx(0.03), (
+ task,
+ wrapper.trainer.args.warmup_steps,
+ )
+
+
[email protected]("name", WARMUP_WRAPPERS)
+def test_wrapper_source_passes_the_ratio_not_a_row_count_estimate(name: str) -> None:
+ tree = ast.parse((TRAINER_DIR / f"{name}.py").read_text(encoding="utf-8"))
+ calls = [
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Call)
+ and getattr(node.func, "id", None) == "resolve_trainer_warmup_steps"
+ ]
+ assert len(calls) == 1, f"{name}: expected one resolve_trainer_warmup_steps call"
+ assert ast.unparse(calls[0].args[0]) == "tcfg.warmup_ratio", name
+ for node in ast.walk(tree):
+ if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mult):
+ assert "warmup_ratio" not in ast.unparse(node), (
+ f"{name}: warmup_ratio is multiplied into a step count again"
+ )
+ has_arg = any(
+ (
+ isinstance(node, ast.keyword)
+ and node.arg == "warmup_steps"
+ and getattr(node.value, "id", None) == "warmup_steps"
+ )
+ or (
+ isinstance(node, ast.Dict)
+ and any(
+ getattr(k, "value", None) == "warmup_steps"
+ and getattr(v, "id", None) == "warmup_steps"
+ for k, v in zip(node.keys, node.values)
+ )
+ )
+ for node in ast.walk(tree)
+ )
+ assert has_arg, f"{name}: warmup_steps argument not passed in source"
+
+
+def test_short_run_at_default_ratio_gets_one_warmup_step(tmp_path: Path) -> None:
+ from transformers import TrainingArguments
+
+ args = TrainingArguments(output_dir=str(tmp_path / "out"), warmup_steps=0.03)
+ assert args.get_warmup_steps(10) == 1
+ assert args.get_warmup_steps(33) == 1
+ assert args.get_warmup_steps(34) == 2
diff --git a/tests/test_issue341_seed_and_fullft.py b/tests/test_issue341_seed_and_fullft.py
index e688f4eb..59a007ec 100644
--- a/tests/test_issue341_seed_and_fullft.py
+++ b/tests/test_issue341_seed_and_fullft.py
@@ -375,6 +375,7 @@ def _wrapper(tmp_path, monkeypatch, base=None, **training_over):
"quantization": "none",
"epochs": 1,
"lr": 1e-3,
+ "warmup_ratio": 0.0,
"logging_steps": 100,
"save_steps": 10_000,
"lora": {"r": 4, "alpha": 8, "dropout": 0.0, "target_modules": ["q_proj", "v_proj"]},
diff --git a/tests/test_issue353_seed_every_task.py b/tests/test_issue353_seed_every_task.py
index 98d17124..f73f56ee 100644
--- a/tests/test_issue353_seed_every_task.py
+++ b/tests/test_issue353_seed_every_task.py
@@ -178,6 +178,7 @@ def _cfg(weights, out_dir, task, **training_over):
"batch_size": _MIN_BATCH.get(task, 1),
"quantization": "none",
"epochs": 1,
+ "warmup_ratio": 0.0,
"logging_steps": 1,
"save_steps": 1000,
"lora": {"r": 4, "alpha": 8, "target_modules": ["q_proj", "v_proj"]},