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): measure grad-accum pressure against the card, not a fixed 24 GB (#1620) (#1625)

vaputa437b7a6595ca
diff --git a/changelog.d/0.75.1/1625.fixed.md b/changelog.d/0.75.1/1625.fixed.md
new file mode 100644
index 00000000..b051d427
--- /dev/null
+++ b/changelog.d/0.75.1/1625.fixed.md
@@ -0,0 +1 @@
+- **The grad-accum advisory measures VRAM pressure against the card the run uses, not a fixed 24 GB (#1620).** `training.grad_accum_auto_tune` built its monitor with a hard-coded `total_vram_gb=24.0`, so on every card smaller than about 24 GB (all common 4, 8, 12, 16 and 20 GB cards) the advisory could never fire, while a 40-80 GB card fired at ~22 GB of peak use (about 28% of an H100). The callback now reads the CUDA device's real total memory on the first advisory call (an explicit `grad_accum_total_vram_gb` still overrides it), reads the peak from the same device, prints the measured numbers in the advisory (`peak 7.8 of 8.0 GB (97%)`), and the live memory panel reads its total from the same device instead of always device 0 (#1620 by @vaputa in #1625).
diff --git a/docs/peft-and-efficiency.md b/docs/peft-and-efficiency.md
index 391d0cda..9c46374c 100644
--- a/docs/peft-and-efficiency.md
+++ b/docs/peft-and-efficiency.md
@@ -721,7 +721,7 @@ training:
grad_accum_pressure_threshold: 0.92
```
-Records peak memory each step. When pressure crosses the threshold, recommends a new `(batch, accum)` pair preserving effective batch (capped at `accum=1024`).
+Records peak memory each step. Pressure is peak allocated memory divided by the total memory of the CUDA device the run uses (#1620), so the threshold means the same thing on a 4 GB laptop card and on an 80 GB accelerator. When pressure crosses the threshold, recommends a new `(batch, accum)` pair preserving effective batch (capped at `accum=1024`), together with the measured peak and total.
> **Backend Note:** Setting `grad_accum_auto_tune: true` is refused on `backend: mlx` at config validation (there is no VRAM total to measure pressure against on unified memory).
diff --git a/src/soup_cli/monitoring/callback.py b/src/soup_cli/monitoring/callback.py
index f4ed73c5..579088cd 100644
--- a/src/soup_cli/monitoring/callback.py
+++ b/src/soup_cli/monitoring/callback.py
@@ -146,7 +146,7 @@ class _SoupTrainerCallback_body: # noqa: N801
spike_recovery_lr_decay: float = 0.5,
grad_accum_auto_tune: bool = False,
grad_accum_pressure_threshold: float = 0.9,
- grad_accum_total_vram_gb: float = 24.0,
+ grad_accum_total_vram_gb: Optional[float] = None,
grad_accum_current_steps: int = 1,
grad_accum_current_batch: int = 1,
):
@@ -194,14 +194,13 @@ class _SoupTrainerCallback_body: # noqa: N801
self._grad_accum_current = max(1, int(grad_accum_current_steps))
self._grad_accum_batch = max(1, int(grad_accum_current_batch))
self._grad_accum_advised = False
- if grad_accum_auto_tune:
- from soup_cli.utils.grad_accum import GradAccumMonitor
- self._grad_accum_monitor = GradAccumMonitor(
- total_vram_gb=grad_accum_total_vram_gb,
- threshold=grad_accum_pressure_threshold,
- )
- else:
- self._grad_accum_monitor = None
+ self._grad_accum_threshold = grad_accum_pressure_threshold
+ #: None = measure the total memory of the CUDA device the run uses on
+ #: the first advisory call (#1620); an explicit value overrides that.
+ self._grad_accum_total_vram_gb = grad_accum_total_vram_gb
+ #: Built lazily on the first advisory call: construction must not
+ #: probe torch, and the card total is only known once CUDA is up.
+ self._grad_accum_monitor = None
# Eval gate state (Part B of v0.26.0)
self.eval_gate_config = eval_gate_config
# Tests inject these; prod wiring sets them at on_train_begin time.
@@ -289,8 +288,9 @@ class _SoupTrainerCallback_body: # noqa: N801
import torch
if torch.cuda.is_available():
- used = torch.cuda.max_memory_allocated() / (1024**3)
- total = torch.cuda.get_device_properties(0).total_memory / (1024**3)
+ device = torch.cuda.current_device()
+ used = torch.cuda.max_memory_allocated(device) / (1024**3)
+ total = torch.cuda.get_device_properties(device).total_memory / (1024**3)
gpu_mem = f"{used:.1f}/{total:.1f} GB"
except Exception:
pass
@@ -435,12 +435,9 @@ class _SoupTrainerCallback_body: # noqa: N801
else:
self._watchdog_counter = 0
- # v0.33.0 #59 — grad-accum advisory (one-shot per run)
- if (
- self._grad_accum_enabled
- and not self._grad_accum_advised
- and self._grad_accum_monitor is not None
- ):
+ # v0.33.0 #59 — grad-accum advisory (one-shot per run). The monitor
+ # is built lazily inside the method on its first call (#1620).
+ if self._grad_accum_enabled and not self._grad_accum_advised:
self._maybe_advise_grad_accum()
# Log to experiment tracker
@@ -661,18 +658,38 @@ class _SoupTrainerCallback_body: # noqa: N801
Phase 1 is advisory-only. Phase 2 (live DataLoader rebuild) requires
a small upstream TRL change tracked as a known limitation.
"""
- if self._grad_accum_advised:
+ if self._grad_accum_advised or not self._grad_accum_enabled:
return
try:
import torch
if not torch.cuda.is_available():
return
- used_gb = torch.cuda.max_memory_allocated() / (1024**3)
+ # The advisory must measure against the card the run actually
+ # uses (#1620): against the old fixed 24 GB total it could never
+ # fire on a smaller card and fired early on larger ones. The peak
+ # and the total are read from the same device.
+ device = torch.cuda.current_device()
+ used_gb = torch.cuda.max_memory_allocated(device) / (1024**3)
except Exception: # noqa: BLE001 — VRAM probe is best-effort
return
if self._grad_accum_monitor is None:
- return
+ try:
+ if self._grad_accum_total_vram_gb is None:
+ total_gb = (
+ torch.cuda.get_device_properties(device).total_memory
+ / (1024**3)
+ )
+ else:
+ total_gb = float(self._grad_accum_total_vram_gb)
+ from soup_cli.utils.grad_accum import GradAccumMonitor
+ self._grad_accum_monitor = GradAccumMonitor(
+ total_vram_gb=total_gb,
+ threshold=self._grad_accum_threshold,
+ )
+ except Exception: # noqa: BLE001 — card probe is best-effort
+ return
+
self._grad_accum_monitor.observe(used_gb)
if not self._grad_accum_monitor.should_adjust(used_gb):
return
@@ -682,11 +699,13 @@ class _SoupTrainerCallback_body: # noqa: N801
if new_accum == self._grad_accum_current:
return
self._grad_accum_advised = True
+ monitor_gb = self._grad_accum_monitor.total_vram_gb
console.print(
- f"[yellow]Grad-accum advisory:[/] VRAM pressure crossed "
- f"threshold; recommend (batch_size, grad_accum_steps) "
- f"({self._grad_accum_batch}, {self._grad_accum_current}) -> "
- f"({new_batch}, {new_accum}). "
+ f"[yellow]Grad-accum advisory:[/] peak {used_gb:.1f} of "
+ f"{monitor_gb:.1f} GB ({used_gb / monitor_gb:.0%}) crossed "
+ f"the pressure threshold; recommend (batch_size, "
+ f"grad_accum_steps) ({self._grad_accum_batch}, "
+ f"{self._grad_accum_current}) -> ({new_batch}, {new_accum}). "
f"Restart training with the new pair to take effect."
)
diff --git a/tests/test_issue802_callback_kwargs_in_trainers.py b/tests/test_issue802_callback_kwargs_in_trainers.py
index 06f5e1f0..cc9e460f 100644
--- a/tests/test_issue802_callback_kwargs_in_trainers.py
+++ b/tests/test_issue802_callback_kwargs_in_trainers.py
@@ -322,7 +322,10 @@ class TestCallbackIntegrationWithKwargs:
assert cb._spike_strategy.max_attempts == 4
assert cb._spike_strategy.lr_decay == pytest.approx(0.35)
assert cb._grad_accum_enabled is True
- assert cb._grad_accum_monitor.threshold == pytest.approx(0.88)
+ # #1620: the monitor is built lazily on the first advisory call, so
+ # construction stores the threshold instead of a GradAccumMonitor.
+ assert cb._grad_accum_monitor is None
+ assert cb._grad_accum_threshold == pytest.approx(0.88)
assert cb._grad_accum_current == 2
assert cb._grad_accum_batch == 4
diff --git a/tests/test_part_e.py b/tests/test_part_e.py
index 705063e4..194c9b67 100644
--- a/tests/test_part_e.py
+++ b/tests/test_part_e.py
@@ -14,11 +14,19 @@ Covers:
from __future__ import annotations
import json
+import re
from types import SimpleNamespace
from unittest.mock import MagicMock
import pytest
+_ANSI_RE = re.compile(r"\x1b\[[0-9;]*m")
+
+
+def _plain(text: str) -> str:
+ """ANSI-stripped, whitespace-collapsed CLI output (#1068: Rich colours numbers)."""
+ return " ".join(_ANSI_RE.sub("", text).split())
+
# ---------------------------------------------------------------------------
# #56 — run_lr_sweep
# ---------------------------------------------------------------------------
@@ -386,3 +394,158 @@ class TestGradAccumAdvisory:
cb._maybe_advise_grad_accum()
assert cb._grad_accum_advised is False
+
+ # -- #1620: pressure is measured against the card, not a fixed total ----
+
+ def test_advises_on_small_card_using_measured_total(self, tmp_path, monkeypatch, capsys):
+ """An 8 GB card at 97.5% pressure with no explicit total advises.
+
+ Against the old fixed 24 GB default this peak could never fire.
+ """
+ cb = _make_callback(
+ tmp_path,
+ grad_accum_auto_tune=True,
+ grad_accum_pressure_threshold=0.92,
+ grad_accum_current_steps=1,
+ grad_accum_current_batch=8,
+ )
+ fake_torch = MagicMock()
+ fake_torch.cuda.is_available.return_value = True
+ fake_torch.cuda.current_device.return_value = 0
+ fake_torch.cuda.max_memory_allocated.return_value = int(7.8 * (1024**3))
+ fake_torch.cuda.get_device_properties.return_value.total_memory = 8 * (1024**3)
+ monkeypatch.setitem(__import__("sys").modules, "torch", fake_torch)
+
+ cb._maybe_advise_grad_accum()
+ assert cb._grad_accum_advised is True
+ assert cb._grad_accum_monitor.total_vram_gb == pytest.approx(8.0)
+ # The advisory carries the measured numbers, not just the pair
+ # (#1068: strip ANSI before reading numbers out of Rich output).
+ assert "peak 7.8 of 8.0 GB (97%)" in _plain(capsys.readouterr().out)
+
+ def test_no_advice_on_large_card_using_measured_total(self, tmp_path, monkeypatch):
+ """An 80 GB card at 28.7% pressure with no explicit total stays quiet."""
+ cb = _make_callback(
+ tmp_path,
+ grad_accum_auto_tune=True,
+ grad_accum_pressure_threshold=0.92,
+ grad_accum_current_steps=1,
+ grad_accum_current_batch=8,
+ )
+ fake_torch = MagicMock()
+ fake_torch.cuda.is_available.return_value = True
+ fake_torch.cuda.current_device.return_value = 0
+ fake_torch.cuda.max_memory_allocated.return_value = 23 * (1024**3)
+ fake_torch.cuda.get_device_properties.return_value.total_memory = 80 * (1024**3)
+ monkeypatch.setitem(__import__("sys").modules, "torch", fake_torch)
+
+ cb._maybe_advise_grad_accum()
+ assert cb._grad_accum_advised is False
+ assert cb._grad_accum_monitor.total_vram_gb == pytest.approx(80.0)
+
+ def test_trainer_built_callback_measures_the_card(self, tmp_path, monkeypatch):
+ """Built exactly as the trainers build it (#802 kwargs), the advisory
+ uses the card's total, not the old 24 GB default."""
+ from soup_cli.monitoring.callback import (
+ SoupTrainerCallback,
+ soup_callback_kwargs,
+ )
+
+ tcfg = SimpleNamespace(
+ grad_accum_auto_tune=True,
+ gradient_accumulation_steps=1,
+ batch_size=8,
+ )
+ cb = SoupTrainerCallback(
+ display=MagicMock(), **soup_callback_kwargs(tcfg)
+ )
+ fake_torch = MagicMock()
+ fake_torch.cuda.is_available.return_value = True
+ fake_torch.cuda.current_device.return_value = 0
+ fake_torch.cuda.max_memory_allocated.return_value = int(7.8 * (1024**3))
+ fake_torch.cuda.get_device_properties.return_value.total_memory = 8 * (1024**3)
+ monkeypatch.setitem(__import__("sys").modules, "torch", fake_torch)
+
+ cb._maybe_advise_grad_accum()
+ assert cb._grad_accum_advised is True
+ assert cb._grad_accum_monitor.total_vram_gb == pytest.approx(8.0)
+
+ def test_no_advice_when_device_properties_raise(self, tmp_path, monkeypatch):
+ """An unreadable card total means no advice and no exception."""
+ cb = _make_callback(
+ tmp_path,
+ grad_accum_auto_tune=True,
+ grad_accum_pressure_threshold=0.92,
+ grad_accum_current_steps=1,
+ grad_accum_current_batch=8,
+ )
+ fake_torch = MagicMock()
+ fake_torch.cuda.is_available.return_value = True
+ fake_torch.cuda.current_device.return_value = 0
+ fake_torch.cuda.max_memory_allocated.return_value = int(7.8 * (1024**3))
+ fake_torch.cuda.get_device_properties.side_effect = RuntimeError("no props")
+ monkeypatch.setitem(__import__("sys").modules, "torch", fake_torch)
+
+ cb._maybe_advise_grad_accum()
+ assert cb._grad_accum_advised is False
+ assert cb._grad_accum_monitor is None
+
+ # -- review follow-ups: the gate, the enabled guard, the device identity ----
+
+ def _fake_cuda(self, current=0, peaks=None, totals=None):
+ peaks, totals = peaks or {0: 7.8}, totals or {0: 8}
+ fake_torch = MagicMock()
+ fake_torch.cuda.is_available.return_value = True
+ fake_torch.cuda.current_device.return_value = current
+ fake_torch.cuda.max_memory_allocated.side_effect = (
+ lambda device=0: int(peaks.get(device, 0.0) * (1024**3))
+ )
+ fake_torch.cuda.get_device_properties.side_effect = (
+ lambda device: SimpleNamespace(total_memory=int(totals[device] * (1024**3)))
+ )
+ return fake_torch
+
+ def test_on_log_drives_the_advisory(self, tmp_path, monkeypatch):
+ """The advisory must fire through on_log, not only via a direct call:
+ the on_log gate is what makes a real run advise at all."""
+ cb = _make_callback(tmp_path, grad_accum_auto_tune=True,
+ grad_accum_pressure_threshold=0.92,
+ grad_accum_current_steps=1, grad_accum_current_batch=8)
+ monkeypatch.setitem(__import__("sys").modules, "torch", self._fake_cuda())
+ state = SimpleNamespace(global_step=1, epoch=0.1, max_steps=10, log_history=[])
+ cb.on_log(SimpleNamespace(output_dir=str(tmp_path)), state, SimpleNamespace(),
+ logs={"loss": 1.0, "learning_rate": 1e-4})
+ assert cb._grad_accum_advised is True
+ assert cb._grad_accum_monitor.total_vram_gb == pytest.approx(8.0)
+
+ def test_disabled_callback_stays_quiet_under_pressure(self, tmp_path, monkeypatch):
+ """The enabled guard keeps a callback built with auto_tune off silent
+ even when pressure is over the threshold."""
+ cb = _make_callback(tmp_path, grad_accum_auto_tune=False,
+ grad_accum_current_batch=8)
+ monkeypatch.setitem(__import__("sys").modules, "torch", self._fake_cuda())
+ cb._maybe_advise_grad_accum()
+ assert cb._grad_accum_advised is False
+ assert cb._grad_accum_monitor is None
+
+ def test_peak_and_total_come_from_the_current_device(self, tmp_path, monkeypatch):
+ """The peak and the total must both come from the device the run uses:
+ device 1 holds the 7.8 GB peak and the 8 GB card, device 0 is idle."""
+ cb = _make_callback(tmp_path, grad_accum_auto_tune=True,
+ grad_accum_pressure_threshold=0.92,
+ grad_accum_current_steps=1, grad_accum_current_batch=8)
+ monkeypatch.setitem(__import__("sys").modules, "torch", self._fake_cuda(
+ current=1, peaks={0: 0.0, 1: 7.8}, totals={0: 80, 1: 8}))
+ cb._maybe_advise_grad_accum()
+ assert cb._grad_accum_advised is True
+ assert cb._grad_accum_monitor.total_vram_gb == pytest.approx(8.0)
+
+ def test_live_panel_reads_the_current_device(self, tmp_path, monkeypatch):
+ """The live memory panel reports the device the run uses, not device 0."""
+ cb = _make_callback(tmp_path)
+ monkeypatch.setitem(__import__("sys").modules, "torch", self._fake_cuda(
+ current=1, peaks={0: 0.0, 1: 7.8}, totals={0: 80, 1: 8}))
+ state = SimpleNamespace(global_step=1, epoch=0.1, max_steps=10, log_history=[])
+ cb.on_log(SimpleNamespace(output_dir=str(tmp_path)), state, SimpleNamespace(),
+ logs={"loss": 1.0, "learning_rate": 1e-4})
+ assert cb.display.update.call_args.kwargs["gpu_mem"] == "7.8/8.0 GB"