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(monitoring): persist and cap spike recovery attempts across launches (Refs #808) (#1971)

Nariman Abdikarim243bccbfb048
diff --git a/changelog.d/0.76.0/1971.fixed.md b/changelog.d/0.76.0/1971.fixed.md
new file mode 100644
index 00000000..491f5141
--- /dev/null
+++ b/changelog.d/0.76.0/1971.fixed.md
@@ -0,0 +1 @@
+- `training.loss_spike_recovery_max_attempts`: persist and enforce attempt counts across re-launches via `spike_recovery.json`, capping recovery when the budget is reached (Refs #808, #1971 by @Nari-Ab).
diff --git a/docs/peft-and-efficiency.md b/docs/peft-and-efficiency.md
index 54ccabdd..45ecd727 100644
--- a/docs/peft-and-efficiency.md
+++ b/docs/peft-and-efficiency.md
@@ -702,7 +702,7 @@ config load because its evidence covers BF16, not FP16; see the
### Loss Spike Auto-Recovery
-Extends the watchdog: instead of stopping on a spike, writes `<output>/spike_recovery.json` with decayed LR and attempt count for re-launch. Capped at 3 attempts by default.
+Extends the watchdog: when the watchdog halts training on a loss spike, writes `<output>/spike_recovery.json` with decayed LR and attempt count for re-launch (e.g. `soup train --resume`). Capped at `loss_spike_recovery_max_attempts` (default 3); each launch hitting a spike evaluates prior completed attempts against the cap (`attempts < max_attempts`), writes the incremented count, and sets `should_recover: false` once the recovery budget is exhausted.
```yaml
training:
diff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.py
index 113c6a42..7ae86426 100644
--- a/src/soup_cli/config/schema.py
+++ b/src/soup_cli/config/schema.py
@@ -3292,7 +3292,7 @@ class TrainingConfig(BaseModel):
default=False,
description=(
"On watchdog trigger: write <output>/spike_recovery.json with "
- "decayed LR and attempt count for re-launch (instead of bare stop). "
+ "decayed LR and attempt count for re-launch (tracks attempts and caps recovery). "
"Requires loss_watchdog=true."
),
)
diff --git a/src/soup_cli/monitoring/callback.py b/src/soup_cli/monitoring/callback.py
index 0dc5282e..9b8b83ef 100644
--- a/src/soup_cli/monitoring/callback.py
+++ b/src/soup_cli/monitoring/callback.py
@@ -632,16 +632,15 @@ class _SoupTrainerCallback_body: # noqa: N801
Best-effort: errors are logged but never crash training.
"""
import json
+ import math
from pathlib import Path
if self._spike_strategy is None:
return
- attempts = self._spike_recovery_attempts
try:
new_lr = self._spike_strategy.compute_new_lr(args.learning_rate)
except ValueError:
return
- recover = self._spike_strategy.should_recover(attempts)
out_dir = Path(self.output_dir or args.output_dir or ".")
# Containment: never write outside cwd (matches v0.32.0 lr-finder /
# autopilot / cans policy). Caller's output_dir is already validated
@@ -657,6 +656,24 @@ class _SoupTrainerCallback_body: # noqa: N801
try:
out_dir.mkdir(parents=True, exist_ok=True)
hint_path = out_dir / "spike_recovery.json"
+ attempts = self._spike_recovery_attempts
+ if hint_path.exists() and attempts == 0:
+ try:
+ data = json.loads(hint_path.read_text(encoding="utf-8"))
+ if isinstance(data, dict) and "attempts" in data:
+ raw = data["attempts"]
+ if isinstance(raw, bool):
+ pass
+ elif isinstance(raw, float):
+ if math.isfinite(raw):
+ attempts = max(0, int(raw))
+ elif isinstance(raw, int):
+ attempts = max(0, raw)
+ elif isinstance(raw, str):
+ attempts = max(0, int(raw))
+ except (json.JSONDecodeError, ValueError, TypeError, OverflowError, OSError):
+ pass
+ recover = self._spike_strategy.should_recover(attempts)
hint_path.write_text(json.dumps({
"attempts": attempts + 1,
"max_attempts": self._spike_strategy.max_attempts,
@@ -666,10 +683,17 @@ class _SoupTrainerCallback_body: # noqa: N801
"should_recover": recover,
}, indent=2), encoding="utf-8")
self._spike_recovery_attempts = attempts + 1
- console.print(
- f"[yellow]Spike recovery hint written:[/] {hint_path} "
- f"(recommended_lr={new_lr:.2e}, should_recover={recover})"
- )
+ if recover:
+ console.print(
+ f"[yellow]Spike recovery hint written:[/] {hint_path} "
+ f"(recommended_lr={new_lr:.2e}, should_recover={recover})"
+ )
+ else:
+ console.print(
+ f"[yellow]Spike recovery hint written:[/] {hint_path} "
+ f"(recommended_lr={new_lr:.2e}, should_recover=False, "
+ f"max attempts {self._spike_strategy.max_attempts} reached)"
+ )
except OSError as exc:
logger.warning("Failed to write spike recovery hint: %s", exc)
diff --git a/tests/test_part_e.py b/tests/test_part_e.py
index 194c9b67..4e8506ab 100644
--- a/tests/test_part_e.py
+++ b/tests/test_part_e.py
@@ -284,32 +284,249 @@ class TestSpikeRecoveryHint:
data = json.loads((tmp_path / "spike_recovery.json").read_text())
assert data["attempts"] == 2
- def test_disabled_when_strategy_not_set(self, tmp_path):
- cb = _make_callback(tmp_path, spike_recovery=False)
- args = SimpleNamespace(
- learning_rate=1e-3, output_dir=str(tmp_path),
+ def test_fresh_cap_1_allows_one_recovery_and_refuses_second(self, tmp_path, monkeypatch):
+ """Cap 1 permits exactly one recovery (prior attempts=0), refusing the second."""
+ monkeypatch.chdir(tmp_path)
+ args = SimpleNamespace(learning_rate=1e-3, output_dir=str(tmp_path))
+
+ # Launch 1: fresh instance, prior count = 0 -> recovery permitted, attempts incremented to 1
+ cb1 = _make_callback(
+ tmp_path,
+ spike_recovery=True,
+ spike_recovery_max_attempts=1,
+ spike_recovery_lr_decay=0.5,
+ )
+ cb1._write_spike_recovery_hint(args, loss=10.0)
+ data1 = json.loads((tmp_path / "spike_recovery.json").read_text(encoding="utf-8"))
+ assert data1["attempts"] == 1
+ assert data1["should_recover"] is True, "First launch under cap 1 must permit recovery"
+
+ # Launch 2 (re-launch): new instance reads persisted count 1 -> budget exhausted
+ cb2 = _make_callback(
+ tmp_path,
+ spike_recovery=True,
+ spike_recovery_max_attempts=1,
+ spike_recovery_lr_decay=0.5,
+ )
+ cb2._write_spike_recovery_hint(args, loss=12.0)
+ data2 = json.loads((tmp_path / "spike_recovery.json").read_text(encoding="utf-8"))
+ assert data2["attempts"] == 2
+ assert data2["should_recover"] is False, "Second launch under cap 1 must refuse recovery"
+
+ def test_cap_2_two_allowed_attempts_across_new_instances(self, tmp_path, monkeypatch):
+ """Under cap 2, both attempt 1 and attempt 2 are permitted; attempt 3 is refused."""
+ monkeypatch.chdir(tmp_path)
+ args = SimpleNamespace(learning_rate=1e-3, output_dir=str(tmp_path))
+
+ # Launch 1: prior count = 0 -> permitted, persisted 1
+ cb1 = _make_callback(
+ tmp_path,
+ spike_recovery=True,
+ spike_recovery_max_attempts=2,
+ spike_recovery_lr_decay=0.5,
+ )
+ cb1._write_spike_recovery_hint(args, loss=10.0)
+ data1 = json.loads((tmp_path / "spike_recovery.json").read_text(encoding="utf-8"))
+ assert data1["attempts"] == 1
+ assert data1["should_recover"] is True, "First attempt under cap 2 must be permitted"
+
+ # Launch 2: new instance reads persisted count 1 -> second attempt is permitted
+ cb2 = _make_callback(
+ tmp_path,
+ spike_recovery=True,
+ spike_recovery_max_attempts=2,
+ spike_recovery_lr_decay=0.5,
+ )
+ cb2._write_spike_recovery_hint(args, loss=12.0)
+ data2 = json.loads((tmp_path / "spike_recovery.json").read_text(encoding="utf-8"))
+ assert data2["attempts"] == 2
+ assert data2["should_recover"] is True, "Second attempt under cap 2 must be permitted"
+
+ # Launch 3: new instance reads persisted count 2 -> budget exhausted, recovery refused
+ cb3 = _make_callback(
+ tmp_path,
+ spike_recovery=True,
+ spike_recovery_max_attempts=2,
+ spike_recovery_lr_decay=0.5,
+ )
+ cb3._write_spike_recovery_hint(args, loss=14.0)
+ data3 = json.loads((tmp_path / "spike_recovery.json").read_text(encoding="utf-8"))
+ assert data3["attempts"] == 3
+ assert data3["should_recover"] is False, "Third attempt under cap 2 must be refused"
+
+ @pytest.mark.parametrize(
+ "bad_payload",
+ [
+ "corrupted non-json",
+ '{"attempts": null}',
+ '{"attempts": []}',
+ '{"attempts": {}}',
+ '{"attempts": "not_an_int"}',
+ '{"attempts": true}',
+ '{"attempts": 1e999}',
+ '{"attempts": -1e999}',
+ '{"attempts": Infinity}',
+ '{"attempts": -Infinity}',
+ '{"attempts": NaN}',
+ ],
+ )
+ def test_corrupt_and_malformed_hint_files_fall_back_gracefully(
+ self, tmp_path, monkeypatch, bad_payload
+ ):
+ """Malformed JSON or invalid attempt types fall back safely to 0 without crashing."""
+ monkeypatch.chdir(tmp_path)
+ args = SimpleNamespace(learning_rate=1e-3, output_dir=str(tmp_path))
+ (tmp_path / "spike_recovery.json").write_text(bad_payload, encoding="utf-8")
+
+ cb = _make_callback(
+ tmp_path,
+ spike_recovery=True,
+ spike_recovery_max_attempts=2,
+ spike_recovery_lr_decay=0.5,
)
cb._write_spike_recovery_hint(args, loss=10.0)
- # No hint file written.
- assert not (tmp_path / "spike_recovery.json").exists()
+ data = json.loads((tmp_path / "spike_recovery.json").read_text(encoding="utf-8"))
+ assert data["attempts"] == 1
+ assert data["should_recover"] is True
+
+ def test_preserves_valid_positive_persisted_count(self, tmp_path, monkeypatch):
+ """Valid persisted count from prior launch is safely parsed and incremented."""
+ monkeypatch.chdir(tmp_path)
+ args = SimpleNamespace(learning_rate=1e-3, output_dir=str(tmp_path))
+ hint_path = tmp_path / "spike_recovery.json"
+ hint_path.write_text(json.dumps({"attempts": 2, "max_attempts": 3}), encoding="utf-8")
+
+ cb1 = _make_callback(
+ tmp_path,
+ spike_recovery=True,
+ spike_recovery_max_attempts=3,
+ spike_recovery_lr_decay=0.5,
+ )
+ cb1._write_spike_recovery_hint(args, loss=10.0)
+ data1 = json.loads(hint_path.read_text(encoding="utf-8"))
+ assert data1["attempts"] == 3
+ assert data1["should_recover"] is True, "Prior count 2 with cap 3 must allow 3rd attempt"
+
+ # Subsequent re-launch with prior count 3
+ cb2 = _make_callback(
+ tmp_path,
+ spike_recovery=True,
+ spike_recovery_max_attempts=3,
+ spike_recovery_lr_decay=0.5,
+ )
+ cb2._write_spike_recovery_hint(args, loss=12.0)
+ data2 = json.loads(hint_path.read_text(encoding="utf-8"))
+ assert data2["attempts"] == 4
+ assert data2["should_recover"] is False, "Prior count 3 with cap 3 must refuse recovery"
+
+ def test_preserves_large_positive_integer_count_and_exhausts_cap(
+ self, tmp_path, monkeypatch
+ ):
+ """Large integer count (10**309) is preserved without float conversion and exhausts cap."""
+ monkeypatch.chdir(tmp_path)
+ args = SimpleNamespace(learning_rate=1e-3, output_dir=str(tmp_path))
+ hint_path = tmp_path / "spike_recovery.json"
+ huge_attempts = 10**309
+ hint_path.write_text(
+ json.dumps({"attempts": huge_attempts, "max_attempts": 2}),
+ encoding="utf-8",
+ )
+
+ cb = _make_callback(
+ tmp_path,
+ spike_recovery=True,
+ spike_recovery_max_attempts=2,
+ spike_recovery_lr_decay=0.5,
+ )
+ cb._write_spike_recovery_hint(args, loss=10.0)
+ data = json.loads(hint_path.read_text(encoding="utf-8"))
+ assert data["attempts"] == huge_attempts + 1
+ assert data["should_recover"] is False, (
+ "Prior large count must exhaust cap and refuse recovery"
+ )
- def test_should_recover_false_at_max_attempts(self, tmp_path, monkeypatch):
- """When attempts have hit max_attempts, should_recover must be False."""
+ @pytest.mark.parametrize(
+ "bad_payload",
+ [
+ '{"attempts": null}',
+ '{"attempts": 1e999}',
+ '{"attempts": -1e999}',
+ '{"attempts": Infinity}',
+ '{"attempts": -Infinity}',
+ '{"attempts": NaN}',
+ '{"attempts": "not_an_int"}',
+ ],
+ )
+ def test_watchdog_path_stops_training_with_bad_hints(
+ self, tmp_path, monkeypatch, bad_payload
+ ):
+ """Watchdog path stops training safely when hint file is malformed or non-finite."""
+ monkeypatch.chdir(tmp_path)
+ hint_path = tmp_path / "spike_recovery.json"
+ hint_path.write_text(bad_payload, encoding="utf-8")
+
+ cb = _make_callback(
+ tmp_path,
+ loss_watchdog=True,
+ loss_watchdog_threshold=5.0,
+ loss_watchdog_patience=1,
+ spike_recovery=True,
+ spike_recovery_max_attempts=2,
+ spike_recovery_lr_decay=0.5,
+ )
+ args = SimpleNamespace(learning_rate=1e-3, output_dir=str(tmp_path))
+ state = SimpleNamespace(global_step=1, epoch=1.0)
+ control = SimpleNamespace(should_training_stop=False)
+
+ cb.on_log(args, state, control, logs={"loss": 10.0})
+
+ assert control.should_training_stop is True, "Watchdog must stop training on loss spike"
+ assert cb._watchdog_fired is True
+ data = json.loads(hint_path.read_text(encoding="utf-8"))
+ assert data["attempts"] == 1
+ assert data["should_recover"] is True
+
+ def test_watchdog_path_preserves_large_integer_count_and_exhausts_cap(
+ self, tmp_path, monkeypatch
+ ):
+ """Watchdog path preserves large positive integer and exhausts recovery budget."""
monkeypatch.chdir(tmp_path)
+ hint_path = tmp_path / "spike_recovery.json"
+ huge_attempts = 10**309
+ hint_path.write_text(
+ json.dumps({"attempts": huge_attempts, "max_attempts": 2}),
+ encoding="utf-8",
+ )
+
cb = _make_callback(
tmp_path,
+ loss_watchdog=True,
+ loss_watchdog_threshold=5.0,
+ loss_watchdog_patience=1,
spike_recovery=True,
spike_recovery_max_attempts=2,
spike_recovery_lr_decay=0.5,
)
+ args = SimpleNamespace(learning_rate=1e-3, output_dir=str(tmp_path))
+ state = SimpleNamespace(global_step=1, epoch=1.0)
+ control = SimpleNamespace(should_training_stop=False)
+
+ cb.on_log(args, state, control, logs={"loss": 10.0})
+
+ assert control.should_training_stop is True, "Watchdog must stop training on loss spike"
+ assert cb._watchdog_fired is True
+ data = json.loads(hint_path.read_text(encoding="utf-8"))
+ assert data["attempts"] == huge_attempts + 1
+ assert data["should_recover"] is False, "Exhausted count must keep recovery disabled"
+
+ def test_disabled_when_strategy_not_set(self, tmp_path):
+ cb = _make_callback(tmp_path, spike_recovery=False)
args = SimpleNamespace(
learning_rate=1e-3, output_dir=str(tmp_path),
)
- # Bump internal counter to budget cap
- cb._spike_recovery_attempts = 2
cb._write_spike_recovery_hint(args, loss=10.0)
- data = json.loads((tmp_path / "spike_recovery.json").read_text())
- assert data["should_recover"] is False
+ # No hint file written.
+ assert not (tmp_path / "spike_recovery.json").exists()
def test_outside_cwd_skipped(self, tmp_path):
"""Containment guard: when output_dir is outside cwd, skip silently."""