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(grpo): skip non-finite optimizer steps via gradient watchdog (Refs #342) (#1084)
Harshit Sharma6c2d1fa2329b
diff --git a/changelog.d/0.75.1/1084.fixed.md b/changelog.d/0.75.1/1084.fixed.mdnew file mode 100644index 00000000..d7a5a6c2--- /dev/null+++ b/changelog.d/0.75.1/1084.fixed.md@@ -0,0 +1,5 @@+- **GRPO training now skips non-finite optimizer steps instead of corrupting adapter weights.**+ A pre-step gradient watchdog detects NaN or Inf gradients and zeros them before+ `optimizer.step()`, so the update is skipped and the adapter is preserved. The+ skipped-step count and fraction are persisted in `trainer_state.json` and reported+ by `soup adapters audit`. (#342 by @harshitthek in #1084)diff --git a/docs/adapters-and-governance.md b/docs/adapters-and-governance.mdindex 06744cd8..4f8d8167 100644--- a/docs/adapters-and-governance.md+++ b/docs/adapters-and-governance.md@@ -586,7 +586,9 @@ config asked" from "the path was wrong" -- a missing `adapter_config.json`, amissing `--config` and a path outside the working directory all exit `1`.This follows `soup ship` / `soup shrink` (0 pass / 2 failed gate / 1 error)rather than the older `adapters scan`, which predates that convention.-`unknown` rows exit `0`.+`unknown` rows exit `0`. For GRPO runs, any non-zero `nan_skip_fraction`+reads as `DIVERGED` (exit 2); even a single skipped step out of thousands is+surfaced so the user can decide whether it matters.Strings in `adapter_config.json` are untrusted -- an adapter can be downloaded-- so record-derived text is stripped of ANSI/OSC control bytes and escapeddiff --git a/docs/training.md b/docs/training.mdindex 6686dc70..1bf584e2 100644--- a/docs/training.md+++ b/docs/training.md@@ -1280,6 +1280,13 @@ soup init --template reasoningsoup train --config soup.yaml```+**Gradient watchdog (#342).** If non-finite gradients (NaN or Inf) appear during+a GRPO run, the optimizer step is skipped: weights and optimizer state are+unchanged, and the step still counts toward the step total and the LR schedule.+The skipped-step count is logged at the end of the run (as a console warning+when the fraction exceeds 5%) and persisted in `trainer_state.json` so+`soup adapters audit` can see it.+**Built-in reward functions:**- `accuracy` — 1.0 when the completion's final answer matches the gold's, else 0.0 (no partial credit)- `format` — checks for structured `<think>...</think>` reasoning blocksdiff --git a/src/soup_cli/commands/adapters.py b/src/soup_cli/commands/adapters.pyindex f4db81df..2ddd2d02 100644--- a/src/soup_cli/commands/adapters.py+++ b/src/soup_cli/commands/adapters.py@@ -1809,6 +1809,30 @@ def audit(raise typer.Exit(1) from exccfg = soup_config.model_dump()+ # #342 — read the sibling trainer_state.json for nan_skip data.+ # The audit module is deliberately filesystem-free, so the command+ # reads the file and passes the relevant keys into the record.+ trainer_state_file = adapter_path / "trainer_state.json"+ if trainer_state_file.is_file():+ try:+ state_data = _json.loads(+ trainer_state_file.read_text(encoding="utf-8")+ )+ except (OSError, ValueError):+ state_data = None # unreadable or not JSON: the row stays unknown+ history = (+ state_data.get("log_history")+ if isinstance(state_data, dict)+ else None+ )+ for entry in reversed(history if isinstance(history, list) else []):+ if isinstance(entry, dict) and "nan_skip_count" in entry:+ record["nan_skip_count"] = entry["nan_skip_count"]+ record["nan_skip_fraction"] = entry.get(+ "nan_skip_fraction", 0.0+ )+ break+result = audit_adapter(cfg, record)if json_out:diff --git a/src/soup_cli/monitoring/grpo_stability_callback.py b/src/soup_cli/monitoring/grpo_stability_callback.pyindex f38e58db..661376ae 100644--- a/src/soup_cli/monitoring/grpo_stability_callback.py+++ b/src/soup_cli/monitoring/grpo_stability_callback.py@@ -226,6 +226,9 @@ class _GRPOStabilityCallback_body: # type: ignore[misc, valid-type] # noqa: N8# before the first event fires).self._policy_model: Any = Noneself._ref_model: Any = None+ # #342 — gradient watchdog state.+ self._nan_skip_count: int = 0+ self._nan_model_ref: Any = Nonedef push_rollout(self, rollout: Any) -> None:"""Append a rollout to the bounded replay buffer (no-op if disabled)."""@@ -269,6 +272,8 @@ class _GRPOStabilityCallback_body: # type: ignore[misc, valid-type] # noqa: N8if trainer is not None:ref = getattr(trainer, "ref_model", None)self._ref_model = ref+ # #342 — capture model reference for gradient watchdog.+ self._nan_model_ref = modelreturn controldef on_step_end(self, args, state, control, model=None, **kwargs):@@ -318,6 +323,101 @@ class _GRPOStabilityCallback_body: # type: ignore[misc, valid-type] # noqa: N8log_history.append(entry)return control+ # --- #342 gradient watchdog ---++ def on_pre_optimizer_step(+ self, args, state, control, model=None, **kwargs+ ):+ """Zero non-finite gradients before ``optimizer.step()``.++ #342 — HF Trainer has no ``TrainerControl.should_skip_optimizer_step``+ flag, so there is no way for a callback to skip the optimizer step.+ Zeroing gradients is the pragmatic substitute: the step still runs+ but updates nothing meaningful.++ With ``set_to_none=True`` (the default), ``zero_grad()`` makes the+ gradients ``None``, so AdamW skips those parameters entirely: the+ optimizer update is skipped; weights and optimizer state are+ unchanged; the step still counts toward the step total and the+ LR schedule.++ This hook fires once per optimizer step, AFTER all gradient+ accumulation. Placing this check in ``training_step`` (per-+ microbatch) would call ``zero_grad()`` mid-accumulation, wiping+ valid gradients from earlier microbatches and producing asymmetric+ partial updates.+ """+ import torch++ target = model if model is not None else self._nan_model_ref+ if target is None:+ return control+ has_nan = False+ for p in target.parameters():+ if p.grad is not None and not torch.isfinite(p.grad).all():+ has_nan = True+ break+ if has_nan:+ self._nan_skip_count += 1+ target.zero_grad()+ logger.warning(+ "step %d: non-finite gradients detected, zeroing "+ "gradients so optimizer.step() is a no-op "+ "(%d total skipped)",+ state.global_step + 1,+ self._nan_skip_count,+ )+ return control++ def on_train_end(self, args, state, control, **kwargs):+ """Report cumulative NaN skip count at end of run.++ #342 — the count is always reported at any fraction above zero+ so a run that skipped steps does not end looking identical to a+ clean one. Loud warning at >= 5%. The fraction is surfaced in+ ``state.log_history`` so ``soup adapters audit`` can see it.+ """+ total = max(state.global_step, 1)+ fraction = self._nan_skip_count / total++ # Always surface in run record for ``soup adapters audit``.+ # A missing record means "trained before the watchdog existed";+ # a zero record means "the watchdog ran and saw no NaN".+ log_history = getattr(state, "log_history", None)+ if log_history is not None:+ log_history.append(+ {+ "nan_skip_count": self._nan_skip_count,+ "nan_skip_fraction": round(fraction, 4),+ }+ )++ # Console / log messages are conditional.+ if self._nan_skip_count > 0:+ msg = (+ "%d of %d optimizer steps were skipped due to "+ "non-finite gradients (%.1f%%)"+ )+ # Always report (logger.info at minimum).+ if fraction >= 0.05:+ logger.warning(+ msg, self._nan_skip_count, total, fraction * 100+ )+ from rich.console import Console++ Console().print(+ f"[bold yellow]Gradient watchdog:[/] "+ f"{self._nan_skip_count} of {total} steps skipped "+ f"({fraction:.1%}) — this may indicate a systematic "+ f"numerical issue"+ )+ else:+ logger.info(+ msg, self._nan_skip_count, total, fraction * 100+ )+ return control++_LAZY_CALLBACKS = {"GRPOStabilityCallback": _GRPOStabilityCallback_body,diff --git a/src/soup_cli/trainer/grpo.py b/src/soup_cli/trainer/grpo.pyindex d0f8dfe6..ad1aec9e 100644--- a/src/soup_cli/trainer/grpo.py+++ b/src/soup_cli/trainer/grpo.py@@ -591,6 +591,16 @@ class GRPOTrainerWrapper:attach_grpo_stability_callback(self.trainer, tcfg)+ # #342 — gradient watchdog (on_pre_optimizer_step) must be always-on.+ # attach_grpo_stability_callback only fires when stability knobs+ # are set. ensure_grpo_stability_callback is a no-op if already+ # attached, otherwise attaches with defaults (only watchdog fires).+ from soup_cli.utils.peft_wiring import (+ ensure_grpo_stability_callback,+ )++ ensure_grpo_stability_callback(self.trainer)+# v0.71.11 #235/#238/#240 — wire the live RL callbacks (reward-hack,# echo-trap, mid-epoch RL checkpoint).from soup_cli.utils.peft_wiring import attach_rl_callbacks@@ -795,6 +805,10 @@ class GRPOTrainerWrapper:self.trainer, self._output_dir, self.config.training.relora_steps)self.tokenizer.save_pretrained(self._output_dir)+ # #342 — persist trainer_state.json (including nan_skip_count+ # from the stability callback) next to adapter_config.json so+ # ``soup adapters audit`` can read the skipped-step fraction.+ self.trainer.save_state()# Extract metricslogs = self.trainer.state.log_historydiff --git a/src/soup_cli/utils/adapter_audit.py b/src/soup_cli/utils/adapter_audit.pyindex 4e615e46..3c27117f 100644--- a/src/soup_cli/utils/adapter_audit.py+++ b/src/soup_cli/utils/adapter_audit.py@@ -515,6 +515,18 @@ def audit_adapter(config: Dict[str, Any], record: Dict[str, Any]) -> AuditResultif "alpha" in lora:rows.append(_cmp("lora.alpha", lora["alpha"], _ran_alpha(record)))+ # #342 — gradient watchdog skip fraction. Only GRPO runs carry the+ # watchdog; elsewhere the row could never be known.+ if config.get("task") == "grpo":+ nan_skip = record.get("nan_skip_count")+ if nan_skip is None:+ rows.append(AuditRow("nan_skip_fraction", 0, None, UNKNOWN, "not in the record"))+ else:+ nan_frac = record.get("nan_skip_fraction", 0.0)+ rows.append(+ AuditRow("nan_skip_fraction", 0, nan_frac, OK if nan_frac == 0 else DIVERGED)+ )+return AuditResult(rows=rows, record_kind=kind)diff --git a/src/soup_cli/utils/peft_wiring.py b/src/soup_cli/utils/peft_wiring.pyindex 3473ea6b..8a3c2dde 100644--- a/src/soup_cli/utils/peft_wiring.py+++ b/src/soup_cli/utils/peft_wiring.py@@ -1147,6 +1147,49 @@ def attach_grpo_stability_callback(trainer: Any, tcfg: Any) -> bool:return True+def ensure_grpo_stability_callback(trainer: Any) -> bool:+ """Ensure the stability callback is attached for the gradient watchdog.++ #342 — ``on_pre_optimizer_step`` in ``GRPOStabilityCallback`` must run+ unconditionally. ``attach_grpo_stability_callback`` only attaches when+ stability knobs are set. This function is a no-op if the callback is+ already attached; otherwise it attaches with all stability knobs at+ their defaults (inactive) so only the gradient watchdog hooks fire.++ The public ``add_callback`` API is the primary capability gate.+ ``callback_handler`` is treated as optional because it is an internal+ ``Trainer`` implementation detail and may be absent on test doubles or+ future TRL versions.+ """+ from soup_cli.monitoring.grpo_stability_callback import (+ GRPOStabilityCallback,+ )++ add_callback = getattr(trainer, "add_callback", None)+ if not callable(add_callback):+ return False++ # Optional duplicate-detection via the private callback list.+ handler = getattr(trainer, "callback_handler", None)+ callbacks = getattr(handler, "callbacks", None) if handler is not None else None+ if callbacks is not None:+ try:+ for cb in callbacks:+ if isinstance(cb, GRPOStabilityCallback):+ return False # already wired — watchdog will fire+ except TypeError:+ pass++ # Attach with defaults: all stability knobs inactive, watchdog active.+ callback = GRPOStabilityCallback()+ try:+ add_callback(callback)+ except Exception as exc: # noqa: BLE001 — best-effort callback attachment+ logger.debug("ensure_grpo_stability_callback add_callback failed: %s", exc)+ return False+ return True++def rl_callbacks_need_buffer(tcfg: Any) -> bool:"""True when a reward-fn capture buffer is needed (v0.71.11 #235/#240).diff --git a/tests/test_grpo.py b/tests/test_grpo.pyindex 8041bc15..fd863d66 100644--- a/tests/test_grpo.py+++ b/tests/test_grpo.py@@ -467,3 +467,250 @@ class TestGRPOSweepParams:config = {"training": {"reward_fn": "accuracy"}}_set_nested_param(config, "reward_fn", "format")assert config["training"]["reward_fn"] == "format"+++# ─── #342 Gradient watchdog — real-trainer smoke tests ───────────────────────+# These download a model and run a real GRPOTrainer on CPU.+# Marked @pytest.mark.smoke — deselected by the 3x3 matrix, run by pytorch-smoke.+++class TestGRPOStabilityWiring:+ """Assert exactly one GRPOStabilityCallback after a real GRPOTrainer setup."""++ def test_exactly_one_callback_attached(self, tmp_path):+ """After GRPOTrainerWrapper.setup(), exactly one GRPOStabilityCallback+ is in the trainer's callback list. On main without this PR there are+ none. Deleting the ensure_grpo_stability_callback call fails this.+ """+ from soup_cli.monitoring.grpo_stability_callback import (+ GRPOStabilityCallback,+ )+ from soup_cli.trainer.grpo import GRPOTrainerWrapper++ config = SoupConfig(+ base="hf-internal-testing/tiny-random-LlamaForCausalLM",+ task="grpo",+ data={"train": str(tmp_path / "train.jsonl"), "max_length": 64},+ training={+ "epochs": 1,+ "lr": 1e-4,+ "batch_size": 2,+ "num_generations": 2,+ "gradient_accumulation_steps": 2,+ "grpo_beta": 0.04,+ "lora": {"r": 8, "alpha": 16},+ "quantization": "none",+ },+ )+ # Write minimal training data+ import json+ train_file = tmp_path / "train.jsonl"+ for i in range(4):+ train_file.open("a").write(+ json.dumps({"prompt": f"What is {i}+{i}?", "answer": str(i * 2)}) + "\n"+ )++ wrapper = GRPOTrainerWrapper(config, device="cpu")+ dataset = {"train": [json.loads(line) for line in train_file.read_text().splitlines()]}+ wrapper.setup(dataset)++ cbs = [+ cb for cb in wrapper.trainer.callback_handler.callbacks+ if isinstance(cb, GRPOStabilityCallback)+ ]+ assert len(cbs) == 1, f"Expected exactly 1 GRPOStabilityCallback, got {len(cbs)}"+++class TestGRPOWatchdogE2E:+ """End-to-end: NaN injection on a real GRPOTrainer, watchdog skips the step."""++ def test_nan_step_leaves_weights_unchanged(self, tmp_path):+ """Inject NaN into one lora_B gradient on microbatch 1 of optimizer+ step 2. Assert every trainable weight is bit-identical before and+ after step 2, and all weights are finite.++ This test kills four mutations:+ - Moving the check into training_step (microbatch 2 gets applied)+ - Deleting ensure_grpo_stability_callback (weights go NaN)+ - Changing zero_grad(set_to_none=False) (weights move)+ - Removing the watchdog's zero_grad (weights go NaN)+ """+ import json++ import torch+ from trl import GRPOConfig, GRPOTrainer++ from soup_cli.utils.peft_wiring import ensure_grpo_stability_callback++ model_name = "hf-internal-testing/tiny-random-LlamaForCausalLM"++ # Write minimal training data — 4 prompts+ train_file = tmp_path / "train.jsonl"+ for i in range(4):+ train_file.open("a").write(+ json.dumps({"prompt": f"What is {i}+{i}?", "answer": str(i * 2)}) + "\n"+ )++ # Load model + tokenizer + LoRA+ from peft import LoraConfig, get_peft_model+ from transformers import AutoModelForCausalLM, AutoTokenizer++ tokenizer = AutoTokenizer.from_pretrained(model_name)+ if tokenizer.pad_token is None:+ tokenizer.pad_token = tokenizer.eos_token+ model = AutoModelForCausalLM.from_pretrained(model_name)+ lora_config = LoraConfig(r=8, lora_alpha=16, task_type="CAUSAL_LM")+ model = get_peft_model(model, lora_config)++ from datasets import Dataset++ ds = Dataset.from_list([+ {"prompt": f"What is {i}+{i}?"}+ for i in range(4)+ ])++ def reward_fn(completions, **kwargs):+ return [1.0] * len(completions)++ grpo_config = GRPOConfig(+ output_dir=str(tmp_path / "output"),+ num_train_epochs=1,+ per_device_train_batch_size=2,+ gradient_accumulation_steps=2,+ learning_rate=1e-4,+ # With a constant reward and lora_B initialised to zero, every+ # gradient but the injected NaN is exactly zero, so an applied+ # step moves nothing unless weight decay is on.+ weight_decay=0.01,+ max_completion_length=32,+ num_generations=2,+ beta=0.04,+ logging_steps=1,+ save_strategy="no",+ report_to="none",+ use_cpu=True,+ bf16=False,+ )++ trainer = GRPOTrainer(+ model=model,+ args=grpo_config,+ train_dataset=ds,+ processing_class=tokenizer,+ reward_funcs=reward_fn,+ )++ # Wire the watchdog+ ensure_grpo_stability_callback(trainer)++ # Find a lora_B parameter and register a NaN-injecting hook+ # that fires on the second optimizer step's first microbatch+ target_param = None+ for name, param in model.named_parameters():+ if "lora_B" in name and param.requires_grad:+ target_param = param+ break+ assert target_param is not None, "No lora_B parameter found"++ step_counter = {"count": 0}++ def poison_hook(grad):+ step_counter["count"] += 1+ # Poison on the 3rd backward call = microbatch 1 of step 2+ # (step 1 has 2 microbatches, step 2 starts at call 3)+ if step_counter["count"] == 3:+ return torch.full_like(grad, float("nan"))+ return grad++ handle = target_param.register_hook(poison_hook)++ # Callback to snapshot weights after step 1 (before poisoned step 2)+ from transformers import TrainerCallback++ class _SnapshotCallback(TrainerCallback):+ def __init__(self):+ self.snapshot = {}++ def on_step_end(self, args, state, control, model=None, **kwargs):+ if state.global_step == 1 and model is not None:+ for n, p in model.named_parameters():+ if p.requires_grad:+ self.snapshot[n] = p.data.clone()++ snap_cb = _SnapshotCallback()+ trainer.add_callback(snap_cb)++ try:+ trainer.train()++ # Assert all weights are finite+ for name, param in model.named_parameters():+ if param.requires_grad:+ assert torch.isfinite(param.data).all(), (+ f"Parameter {name} has non-finite values after training"+ )++ # Assert weights are bit-identical to the step-1 snapshot+ # (step 2 was poisoned, so the watchdog should have skipped it)+ assert snap_cb.snapshot, "Snapshot callback did not fire"+ for name, pre in snap_cb.snapshot.items():+ post = dict(model.named_parameters())[name].data+ assert torch.equal(pre, post), (+ f"Parameter {name} changed during poisoned step 2 "+ f"(watchdog failed to skip)"+ )+ finally:+ handle.remove()+++class TestGRPORunRecordReachesTheAudit:+ def test_a_real_run_writes_the_record_and_the_audit_reads_it(self, tmp_path, monkeypatch):+ """save_state() puts trainer_state.json next to the adapter; the audit reads it."""+ import json+ import os+ import pathlib++ import yaml+ from typer.testing import CliRunner++ from soup_cli.commands.adapters import app as adapters_app+ from soup_cli.trainer.grpo import GRPOTrainerWrapper++ monkeypatch.chdir(tmp_path)+ raw = {+ "base": "hf-internal-testing/tiny-random-LlamaForCausalLM",+ "task": "grpo",+ "data": {"train": "train.jsonl", "max_length": 64},+ "output": "out",+ "training": {+ "epochs": 1,+ "lr": 1e-4,+ "batch_size": 2,+ "num_generations": 2,+ "gradient_accumulation_steps": 2,+ "grpo_beta": 0.04,+ "reward_fn": "format",+ "lora": {"r": 8, "alpha": 16},+ "quantization": "none",+ },+ }+ (tmp_path / "soup.yaml").write_text(yaml.safe_dump(raw))+ rows = [{"prompt": f"What is {i}+{i}?", "answer": str(i * 2)} for i in range(4)]+ wrapper = GRPOTrainerWrapper(SoupConfig(**raw), device="cpu")+ wrapper.setup({"train": rows})+ wrapper.train()++ out = pathlib.Path(wrapper._output_dir)+ state = json.loads((out / "trainer_state.json").read_text())+ assert state["log_history"][-1] == {"nan_skip_count": 0, "nan_skip_fraction": 0.0}++ rel = os.path.relpath(out, tmp_path)+ res = CliRunner().invoke(adapters_app, ["audit", rel, "--config", "soup.yaml", "--json"])+ assert res.exit_code in (0, 2), (res.output, repr(res.exception))+ row = next(+ r for r in json.loads(res.stdout)["rows"] if r["setting"] == "nan_skip_fraction"+ )+ assert (row["status"], row["ran"]) == ("ok", 0.0)diff --git a/tests/test_issue342_grpo_nan.py b/tests/test_issue342_grpo_nan.pynew file mode 100644index 00000000..865238c7--- /dev/null+++ b/tests/test_issue342_grpo_nan.py@@ -0,0 +1,497 @@+"""Tests for #342 — GRPO numerical stability (gradient watchdog).++CPU-only, no model, no GPU. Four test groups:++1. Watchdog behavior — detect NaN, zero grads, track count+2. Run record — skip count always persisted (including zero)+3. Microbatch placement — on_pre_optimizer_step vs training_step+4. Defensive callback wiring — ensure_grpo_stability_callback contract+"""++from __future__ import annotations++import logging+from types import SimpleNamespace+from unittest.mock import MagicMock++import pytest+import torch++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _make_mock_state(global_step: int = 100) -> SimpleNamespace:+ """Mock HF TrainerState with log_history."""+ return SimpleNamespace(global_step=global_step, log_history=[])+++def _make_mock_control() -> MagicMock:+ """Mock HF TrainerControl."""+ return MagicMock()+++def _make_mock_model_with_grads(*grad_tensors: torch.Tensor) -> MagicMock:+ """Create a mock model whose parameters() yields params with the given grads."""+ params = []+ for g in grad_tensors:+ p = MagicMock()+ p.grad = g+ params.append(p)+ model = MagicMock()+ model.parameters.return_value = params+ return model+++def _get_callback_instance():+ """Get a fresh GRPOStabilityCallback instance with defaults."""+ from soup_cli.monitoring.grpo_stability_callback import (+ GRPOStabilityCallback,+ )++ return GRPOStabilityCallback()+++# ===========================================================================+# Group 1 — Watchdog behavior [C7.5-C7.9]+# ===========================================================================+++class TestGradWatchdog:+ """Pre-step gradient watchdog: detect NaN, zero grads, track count."""++ def test_nan_grad_detected_and_zeroed(self):+ """Watchdog zeros all gradients when any param has NaN grad."""+ cb = _get_callback_instance()+ nan_grad = torch.tensor([float("nan"), 1.0])+ model = _make_mock_model_with_grads(nan_grad)+ state = _make_mock_state()+ control = _make_mock_control()++ cb.on_pre_optimizer_step(None, state, control, model=model)+ model.zero_grad.assert_called_once()+ assert cb._nan_skip_count == 1++ def test_finite_grad_untouched(self):+ """Watchdog does nothing when all gradients are finite."""+ cb = _get_callback_instance()+ ok_grad = torch.tensor([1.0, 2.0])+ model = _make_mock_model_with_grads(ok_grad)+ state = _make_mock_state()+ control = _make_mock_control()++ cb.on_pre_optimizer_step(None, state, control, model=model)+ model.zero_grad.assert_not_called()+ assert cb._nan_skip_count == 0++ def test_inf_grad_detected(self):+ """Watchdog catches inf (not just NaN)."""+ cb = _get_callback_instance()+ inf_grad = torch.tensor([float("inf"), 1.0])+ model = _make_mock_model_with_grads(inf_grad)+ state = _make_mock_state()+ control = _make_mock_control()++ cb.on_pre_optimizer_step(None, state, control, model=model)+ model.zero_grad.assert_called_once()+ assert cb._nan_skip_count == 1++ def test_multiple_nans_counted(self):+ """Cumulative counter increments on each NaN step."""+ cb = _get_callback_instance()+ nan_grad = torch.tensor([float("nan")])+ model = _make_mock_model_with_grads(nan_grad)+ state = _make_mock_state()+ control = _make_mock_control()++ for _ in range(3):+ cb.on_pre_optimizer_step(None, state, control, model=model)+ assert cb._nan_skip_count == 3++ def test_warning_logged(self, caplog):+ """Watchdog emits a WARNING-level log on NaN detection."""+ cb = _get_callback_instance()+ nan_grad = torch.tensor([float("nan")])+ model = _make_mock_model_with_grads(nan_grad)+ state = _make_mock_state()+ control = _make_mock_control()++ with caplog.at_level(logging.WARNING):+ cb.on_pre_optimizer_step(None, state, control, model=model)+ assert any("non-finite" in r.message for r in caplog.records)+++# ===========================================================================+# Group 2 — Run record (always persisted, including zero)+# ===========================================================================+++class TestRunRecord:+ """Skip fraction persisted in log_history for audit."""++ def test_nonzero_count_surfaced(self):+ """Non-zero skip count appears in state.log_history."""+ cb = _get_callback_instance()+ cb._nan_skip_count = 3+ state = _make_mock_state(global_step=100)+ control = _make_mock_control()++ cb.on_train_end(None, state, control)+ record = state.log_history[-1]+ assert record["nan_skip_count"] == 3+ assert record["nan_skip_fraction"] == 0.03++ def test_zero_count_surfaced(self):+ """Zero skip count must still appear in log_history.++ A missing record means 'trained before the watchdog existed';+ a zero record means 'the watchdog ran and saw no NaN'.+ """+ cb = _get_callback_instance()+ state = _make_mock_state(global_step=50)+ control = _make_mock_control()++ cb.on_train_end(None, state, control)+ record = state.log_history[-1]+ assert record["nan_skip_count"] == 0+ assert record["nan_skip_fraction"] == 0.0++ def test_loud_threshold_at_5_percent(self, caplog):+ """>=5% triggers WARNING; <5% triggers INFO."""+ cb = _get_callback_instance()+ cb._nan_skip_count = 5+ state = _make_mock_state(global_step=100)+ control = _make_mock_control()++ with caplog.at_level(logging.WARNING):+ cb.on_train_end(None, state, control)+ assert any(+ r.levelno >= logging.WARNING for r in caplog.records+ ), "5% fraction must trigger WARNING"+++# ===========================================================================+# Group 3 — Microbatch placement+# ===========================================================================+++class TestMicrobatchPlacement:+ """Unit-level check that on_pre_optimizer_step handles accumulated gradients.++ These tests verify the watchdog's behavior on pre-accumulated gradient+ buffers. The e2e smoke test (TestGRPOWatchdogE2E) proves the actual+ placement in the trainer lifecycle.+ """++ def test_first_microbatch_survives_second_nan(self):+ """Accumulated gradient from microbatch 1 must survive.++ Simulate gradient accumulation: microbatch 1 is finite,+ microbatch 2 is NaN. After on_pre_optimizer_step, the grads+ should be zeroed (or None), NOT the finite microbatch 1 grads.+ The watchdog sees the accumulated result, which includes NaN.+ """+ cb = _get_callback_instance()++ # After accumulation: mixed finite + NaN in the gradient buffer.+ mixed_grad = torch.tensor([1.0, float("nan")])+ model = _make_mock_model_with_grads(mixed_grad)+ state = _make_mock_state()+ control = _make_mock_control()++ cb.on_pre_optimizer_step(None, state, control, model=model)++ # The watchdog zeroes because NaN is present.+ model.zero_grad.assert_called_once()+ assert cb._nan_skip_count == 1++ def test_clean_accumulation_untouched(self):+ """When both microbatches are finite, no zeroing occurs."""+ cb = _get_callback_instance()++ # After accumulation: all finite.+ finite_grad = torch.tensor([1.0, 2.0])+ model = _make_mock_model_with_grads(finite_grad)+ state = _make_mock_state()+ control = _make_mock_control()++ cb.on_pre_optimizer_step(None, state, control, model=model)++ model.zero_grad.assert_not_called()+ assert cb._nan_skip_count == 0+++# ---------------------------------------------------------------------------+# Group 4 — ensure_grpo_stability_callback defensive contract+# ---------------------------------------------------------------------------+# Concrete test doubles (NOT MagicMock) so missing attributes surface as+# AttributeError rather than silently auto-generating child mocks.+# ---------------------------------------------------------------------------++class _CallbackHandler:+ """Minimal callback_handler stand-in with a mutable callbacks list."""++ def __init__(self):+ self.callbacks: list = []+++class _TrainerWithCallbacks:+ """Has both add_callback and callback_handler (normal HF Trainer)."""++ def __init__(self):+ self.callback_handler = _CallbackHandler()++ def add_callback(self, cb):+ self.callback_handler.callbacks.append(cb)+++class _TrainerWithoutCallbackHandler:+ """Has add_callback but NO callback_handler (future TRL / slim mock)."""++ def __init__(self):+ self._attached: list = []++ def add_callback(self, cb):+ self._attached.append(cb)+++class _BareTrainer:+ """Has neither add_callback nor callback_handler (FakeGRPOTrainer)."""++ def __init__(self, **kwargs):+ pass+++class TestEnsureGRPOStabilityCallback:+ """Group 4 — defensive callback wiring for issue #342."""++ def test_attaches_when_callback_handler_present(self):+ """Normal path: trainer with both add_callback and handler."""+ from soup_cli.monitoring.grpo_stability_callback import (+ GRPOStabilityCallback,+ )+ from soup_cli.utils.peft_wiring import (+ ensure_grpo_stability_callback,+ )++ trainer = _TrainerWithCallbacks()+ result = ensure_grpo_stability_callback(trainer)++ assert result is True, "Must attach on first call"+ assert any(+ isinstance(cb, GRPOStabilityCallback)+ for cb in trainer.callback_handler.callbacks+ ), "Callback must be in the handler's list"++ def test_skips_duplicate_when_already_attached(self):+ """Duplicate detection via callback_handler.callbacks."""+ from soup_cli.monitoring.grpo_stability_callback import (+ GRPOStabilityCallback,+ )+ from soup_cli.utils.peft_wiring import (+ ensure_grpo_stability_callback,+ )++ trainer = _TrainerWithCallbacks()+ ensure_grpo_stability_callback(trainer)+ result = ensure_grpo_stability_callback(trainer)++ assert result is False, "Second call must be no-op"+ count = sum(+ 1+ for cb in trainer.callback_handler.callbacks+ if isinstance(cb, GRPOStabilityCallback)+ )+ assert count == 1, f"Expected exactly 1 callback, got {count}"++ def test_attaches_without_callback_handler(self):+ """Trainer with add_callback but no callback_handler."""+ from soup_cli.monitoring.grpo_stability_callback import (+ GRPOStabilityCallback,+ )+ from soup_cli.utils.peft_wiring import (+ ensure_grpo_stability_callback,+ )++ trainer = _TrainerWithoutCallbackHandler()+ result = ensure_grpo_stability_callback(trainer)++ assert result is True, (+ "Must attach even without callback_handler"+ )+ assert any(+ isinstance(cb, GRPOStabilityCallback)+ for cb in trainer._attached+ ), "Callback must be in the trainer's internal list"++ def test_returns_false_for_bare_trainer(self):+ """Bare trainer without add_callback must not crash."""+ from soup_cli.utils.peft_wiring import (+ ensure_grpo_stability_callback,+ )++ trainer = _BareTrainer()+ result = ensure_grpo_stability_callback(trainer)++ assert result is False, (+ "Must return False for trainers without add_callback"+ )++ def test_returns_false_for_none_and_non_trainer(self):+ """Degenerate inputs (None, string, int) must degrade safely."""+ from soup_cli.utils.peft_wiring import (+ ensure_grpo_stability_callback,+ )++ for degenerate in (None, "trainer", 42, [], object()):+ result = ensure_grpo_stability_callback(degenerate)+ assert result is False, f"Expected False for {degenerate!r}, got {result!r}"++ def test_attaches_when_callbacks_attribute_is_non_iterable(self):+ """Non-iterable callback_handler.callbacks must not crash."""+ from soup_cli.monitoring.grpo_stability_callback import (+ GRPOStabilityCallback,+ )+ from soup_cli.utils.peft_wiring import (+ ensure_grpo_stability_callback,+ )++ class _BrokenHandlerTrainer:+ def __init__(self):+ self.callback_handler = type("Handler", (), {"callbacks": 123})()+ self._attached = []++ def add_callback(self, cb):+ self._attached.append(cb)++ trainer = _BrokenHandlerTrainer()+ result = ensure_grpo_stability_callback(trainer)+ assert result is True+ assert any(isinstance(cb, GRPOStabilityCallback) for cb in trainer._attached)++ def test_returns_false_when_add_callback_raises(self):+ """Failing add_callback degrades to False without crashing."""+ from soup_cli.utils.peft_wiring import (+ ensure_grpo_stability_callback,+ )++ class _FailingTrainer:+ def add_callback(self, cb):+ raise RuntimeError("Trainer rejects callback")++ trainer = _FailingTrainer()+ result = ensure_grpo_stability_callback(trainer)+ assert result is False+++# ---------------------------------------------------------------------------+# Group 5 — `soup adapters audit` reads the skip record (#342 item 3)+# ---------------------------------------------------------------------------++_PEFT_RECORD = {+ "peft_type": "LORA",+ "base_model_name_or_path": "hf-internal-testing/tiny-random-LlamaForCausalLM",+ "r": 8,+ "lora_alpha": 16,+ "lora_dropout": 0.0,+ "target_modules": ["q_proj", "v_proj"],+}+++def _audit_config(task: str = "grpo") -> dict:+ return {+ "base": "hf-internal-testing/tiny-random-LlamaForCausalLM",+ "task": task,+ "data": {"train": "./d.jsonl"},+ "training": {"lora": {"r": 8, "alpha": 16}},+ }+++class TestTheAuditRow:+ @pytest.mark.parametrize(+ ("extra", "status", "ran"),+ [+ ({}, "unknown", None),+ ({"nan_skip_count": 0, "nan_skip_fraction": 0.0}, "ok", 0.0),+ ({"nan_skip_count": 1, "nan_skip_fraction": 0.5}, "diverged", 0.5),+ ],+ )+ def test_the_row_reads_the_record(self, extra, status, ran):+ from soup_cli.utils.adapter_audit import audit_adapter++ result = audit_adapter(_audit_config(), {**_PEFT_RECORD, **extra})+ row = next(r for r in result.rows if r.setting == "nan_skip_fraction")+ assert (row.status, row.ran) == (status, ran)++ def test_a_non_grpo_adapter_gets_no_row(self):+ """Only GRPO runs carry the watchdog; elsewhere the row could never be known."""+ from soup_cli.utils.adapter_audit import audit_adapter++ result = audit_adapter(_audit_config(task="sft"), dict(_PEFT_RECORD))+ assert all(r.setting != "nan_skip_fraction" for r in result.rows)+++class TestTheAuditCommandReadsTrainerState:+ def _row(self, tmp_path, monkeypatch, trainer_state):+ import json++ import yaml+ from typer.testing import CliRunner++ from soup_cli.commands.adapters import app++ monkeypatch.chdir(tmp_path)+ (tmp_path / "adapter_config.json").write_text(json.dumps(_PEFT_RECORD))+ (tmp_path / "soup.yaml").write_text(yaml.safe_dump(_audit_config()))+ if trainer_state is not None:+ (tmp_path / "trainer_state.json").write_text(trainer_state)+ res = CliRunner().invoke(app, ["audit", ".", "--config", "soup.yaml", "--json"])+ assert res.exit_code in (0, 2), (res.output, repr(res.exception))+ rows = json.loads(res.stdout)["rows"]+ return next(r for r in rows if r["setting"] == "nan_skip_fraction")++ def test_the_last_record_in_trainer_state_is_reported(self, tmp_path, monkeypatch):+ import json++ state = {+ "log_history": [+ {"loss": 1.0, "step": 1},+ {"nan_skip_count": 1, "nan_skip_fraction": 0.5},+ ]+ }+ row = self._row(tmp_path, monkeypatch, json.dumps(state))+ assert (row["status"], row["ran"]) == ("diverged", 0.5)++ def test_no_trainer_state_reads_unknown(self, tmp_path, monkeypatch):+ assert self._row(tmp_path, monkeypatch, None)["status"] == "unknown"++ @pytest.mark.parametrize(+ "bad", ["[]", '{"log_history": 5}', '{"log_history": [3]}', "not json"]+ )+ def test_a_malformed_trainer_state_reads_unknown(self, tmp_path, monkeypatch, bad):+ assert self._row(tmp_path, monkeypatch, bad)["status"] == "unknown"+++# ---------------------------------------------------------------------------+# Group 6 — Message text pinning (#342 review round 2)+# ---------------------------------------------------------------------------+++class TestTheMessagesPeopleSee:+ def test_a_skip_below_five_percent_is_still_reported(self, caplog):+ cb = _get_callback_instance()+ cb._nan_skip_count = 1+ with caplog.at_level(logging.INFO):+ cb.on_train_end(None, _make_mock_state(global_step=100), _make_mock_control())+ assert "1 of 100 optimizer steps were skipped" in caplog.text++ def test_the_warning_names_the_step_the_trainer_logs(self, caplog):+ """global_step is incremented after on_pre_optimizer_step, so step 5 is 4 + 1."""+ cb = _get_callback_instance()+ model = _make_mock_model_with_grads(torch.tensor([float("nan")]))+ with caplog.at_level(logging.WARNING):+ cb.on_pre_optimizer_step(+ None, _make_mock_state(global_step=4), _make_mock_control(), model=model+ )+ assert "step 5:" in caplog.text