Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

fix(train): give unlearn runs a formatted duration and fall back in the completion panel (#1529) (#1537)

vaputa1d150a7bb669
diff --git a/changelog.d/0.75.1/1537.fixed.md b/changelog.d/0.75.1/1537.fixed.md
new file mode 100644
index 00000000..c288c6c2
--- /dev/null
+++ b/changelog.d/0.75.1/1537.fixed.md
@@ -0,0 +1,8 @@
+- Fix `soup train --task unlearn` crashing with `KeyError: 'duration'` in the
+ "Training Complete!" panel after the run had already finished: the adapter was
+ saved and the tracker row written, but the unlearn wrapper was the one
+ transformers-backend trainer that returned only `duration_secs` without the
+ pre-formatted `duration` string. The wrapper now formats `duration` like every
+ other wrapper, and the completion panel falls back to formatting
+ `duration_secs` itself so no future wrapper can lose a finished run's summary
+ (#1529 by @vaputa in #1537).
diff --git a/src/soup_cli/commands/train.py b/src/soup_cli/commands/train.py
index 3eb23645..dfddad34 100644
--- a/src/soup_cli/commands/train.py
+++ b/src/soup_cli/commands/train.py
@@ -89,6 +89,29 @@ def _format_training_complete_loss(result: dict) -> str:
return f"Loss: [bold]{result['initial_loss']:.4f} -> {result['final_loss']:.4f}[/]{label}"
+def _format_duration_display(result: dict) -> str:
+ """Duration line for the completion panel (#1529).
+
+ Every trainer wrapper returns both a pre-formatted ``duration`` string and
+ the raw ``duration_secs`` — except unlearn, which until #1529 returned only
+ the seconds, so the panel's ``result['duration']`` raised ``KeyError``
+ AFTER the adapter was saved and the run was otherwise complete. Read the
+ string when present and fall back to formatting the seconds (``unknown``
+ when both are missing — a measured ``0m`` stays ``0m``, but an absent
+ measurement should not read as a zero) so no wrapper can lose a finished
+ run's summary.
+ """
+ duration = result.get("duration")
+ if duration:
+ return duration
+ duration_secs = result.get("duration_secs")
+ if duration_secs is None:
+ return "unknown"
+ hours = int(duration_secs // 3600)
+ minutes = int((duration_secs % 3600) // 60)
+ return f"{hours}h {minutes}m" if hours > 0 else f"{minutes}m"
+
+
def _run_auto_eval_after_training(eval_config, output_dir: str, run_id: str) -> None:
"""Run configured evaluation once after the trained model is saved."""
if not eval_config or not getattr(eval_config, "auto_eval", False):
@@ -1875,7 +1898,7 @@ def train(
console.print(
Panel(
f"{_format_training_complete_loss(result)}\n"
- f"Duration: [bold]{result['duration']}[/]\n"
+ f"Duration: [bold]{_format_duration_display(result)}[/]\n"
f"Output: [bold]{result['output_dir']}[/]\n"
f"Run ID: [bold]{run_id}[/]\n\n"
f"Quick test: [bold]soup chat --model {result['output_dir']}[/]\n"
diff --git a/src/soup_cli/trainer/unlearn.py b/src/soup_cli/trainer/unlearn.py
index f2999ad3..610b4568 100644
--- a/src/soup_cli/trainer/unlearn.py
+++ b/src/soup_cli/trainer/unlearn.py
@@ -420,9 +420,13 @@ class UnlearnTrainerWrapper:
else [loss for loss in (initial_loss, final_loss) if loss is not None]
)
loss_summary = summarize_training_loss([{"loss": loss} for loss in losses])
+ hours = int(duration // 3600)
+ minutes = int((duration % 3600) // 60)
+ duration_str = f"{hours}h {minutes}m" if hours > 0 else f"{minutes}m"
return {
**loss_summary,
"total_steps": step,
+ "duration": duration_str,
"duration_secs": duration,
"output_dir": output_dir,
}
diff --git a/tests/test_issue1529_unlearn_duration.py b/tests/test_issue1529_unlearn_duration.py
new file mode 100644
index 00000000..a0898f12
--- /dev/null
+++ b/tests/test_issue1529_unlearn_duration.py
@@ -0,0 +1,123 @@
+"""#1529 — unlearn's trainer result must carry the panel's 'duration' key.
+
+``soup train --task unlearn`` crashed with ``KeyError: 'duration'`` in the
+"Training Complete!" panel — AFTER the adapter was saved and the tracker row
+was written — because ``UnlearnTrainerWrapper`` was the one transformers-backend
+wrapper that returned only ``duration_secs``. These tests pin both halves of
+the fix: the wrapper now formats the string like every other wrapper, and the
+panel tolerates a result dict that lacks the key anyway.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from unittest.mock import MagicMock
+from unittest.mock import patch as mock_patch
+
+import pytest
+
+from soup_cli.commands.train import _format_duration_display
+from soup_cli.trainer.unlearn import UnlearnTrainerWrapper
+
+TRAINER_DIR = Path(__file__).parent.parent / "src" / "soup_cli" / "trainer"
+
+
+def _run_ready_unlearn_wrapper(tmp_path, monkeypatch) -> UnlearnTrainerWrapper:
+ """A wrapper past setup() with an empty forget set (a zero-step run).
+
+ setup() itself refuses an empty forget set, so this bypasses it and
+ arranges exactly what a real call leaves behind: ``_setup_called`` set,
+ mock model/tokenizer, and an output dir under the (tmp) cwd that the
+ ``_validated_output_dir`` gate accepts. ``train()`` then clears the
+ optimizer's gradients, finds no forget row to step over, and exercises
+ the save + result path.
+ """
+ monkeypatch.chdir(tmp_path)
+ cfg = MagicMock()
+ cfg.training.epochs = 1
+ cfg.output = "unlearn-out"
+ wrapper = UnlearnTrainerWrapper(cfg)
+ wrapper._setup_called = True
+ wrapper.model = MagicMock()
+ wrapper.tokenizer = MagicMock()
+ wrapper._optimizer = MagicMock() # #1564: train() touches it even at zero steps
+ return wrapper
+
+
[email protected](("elapsed", "expected"), [(90, "1m"), (3720, "1h 2m")])
+def test_unlearn_train_returns_formatted_duration(
+ tmp_path, monkeypatch, elapsed, expected
+):
+ """train() returns the pre-formatted 'duration' alongside duration_secs."""
+ wrapper = _run_ready_unlearn_wrapper(tmp_path, monkeypatch)
+ ticks = iter([0, elapsed])
+
+ with mock_patch(
+ "soup_cli.trainer.unlearn.time.monotonic", side_effect=lambda: next(ticks)
+ ):
+ result = wrapper.train()
+
+ assert result["duration"] == expected
+ assert result["duration_secs"] == elapsed
+
+
+ ("result", "expected"),
+ [
+ ({"duration": "3m", "duration_secs": 185.0}, "3m"),
+ # The #1529 shape: seconds only, no pre-formatted string.
+ ({"duration_secs": 90.0}, "1m"),
+ ({"duration_secs": 3720.0}, "1h 2m"),
+ # A measured zero stays 0m; an absent measurement is not a zero.
+ ({"duration_secs": 0.0}, "0m"),
+ # Neither key: a finished run still gets its summary panel.
+ ({}, "unknown"),
+ ],
+)
+def test_completion_panel_duration_falls_back_to_seconds(result, expected):
+ """The panel reads 'duration' when present, else formats duration_secs."""
+ assert _format_duration_display(result) == expected
+
+
+def test_completion_panel_never_indexes_result_duration_directly():
+ """#1529 surfaced in the completion panel, after finish_run() had already run.
+
+ The helper tests above never reach that call site, so reverting the panel
+ line to ``result['duration']`` would leave them green. Pin the site itself.
+ """
+ import ast
+
+ train_py = TRAINER_DIR.parent / "commands" / "train.py"
+ tree = ast.parse(train_py.read_text(encoding="utf-8"))
+ offenders = [
+ node.lineno
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Subscript)
+ and isinstance(node.value, ast.Name)
+ and node.value.id == "result"
+ and isinstance(node.slice, ast.Constant)
+ and node.slice.value == "duration"
+ ]
+ assert not offenders, (
+ f"commands/train.py indexes result['duration'] at line(s) {offenders}; "
+ "go through _format_duration_display(result) so a wrapper that omits the key "
+ "cannot crash a finished run"
+ )
+
+
+def test_every_trainer_reporting_duration_secs_also_formats_duration():
+ """Guard the whole wrapper family, not just unlearn (#1529).
+
+ Any trainer module that reports ``duration_secs`` but never emits the
+ ``"duration"`` string key crashes the train completion panel after the
+ run is otherwise done. unlearn.py was the original offender; this scan
+ catches the next wrapper that repeats the mistake.
+ """
+ offenders = []
+ for path in sorted(TRAINER_DIR.glob("*.py")):
+ src = path.read_text(encoding="utf-8")
+ if "duration_secs" not in src:
+ continue
+ if '"duration"' not in src and "'duration'" not in src:
+ offenders.append(path.name)
+ assert not offenders, f"trainer module(s) missing the duration key: {offenders}"