Spaces:
Running
Running
Download lpu/training/training_optimizer.py from iparaco/Virtual-LPU: direct link, hf CLI and curl.
- Browser
- Download file 72.4 kB
-
https://huggingface.co/spaces/iparaco/Virtual-LPU/resolve/main/lpu/training/training_optimizer.py
- Command line
-
hf download hf://spaces/iparaco/Virtual-LPU/lpu/training/training_optimizer.py
-
curl -L -o training_optimizer.py https://huggingface.co/spaces/iparaco/Virtual-LPU/resolve/main/lpu/training/training_optimizer.py
72.4 kB
"""LPU V4 Training Engine: the session-owned training loop.
This module is the V4 answer to audit finding 3.1 ("no single coherent
training API"). There is now exactly ONE recommended way to train with LPU,
and it puts the SESSION in charge of the loop:
import lpu
with lpu.training_session(model, train_loader,
criterion=criterion, optimizer=opt,
batch_size=16) as sess:
for epoch in range(epochs):
summary = sess.train_epoch() # session runs the loop
print(summary["loss_last"], summary["images_per_second"])
Because the session runs fetch -> transfer -> forward(strategy) -> loss ->
backward -> accumulation -> step, the selected multi-GPU strategy, the
measured precision policy, the micro-batch sizing and the OOM recovery are
ALL exercised BY CONSTRUCTION - there is no way for user code to accidentally
bypass them (the V3 failure mode: the example called the raw model and the
whole optimization stack never ran).
A step-level manual API still exists for advanced users (iterate/forward/
backward/step/should_step) - see the ManualMode notes at the bottom of this
docstring for its EXACT guarantees.
Engineering contracts implemented here (V4):
- COHERENT API (3.1): start() probes with the REAL requested batch size;
the strategy wrapper is the only model view ever called; should_step() is
a pure query; step() is the only place the optimizer steps.
- ZERO-SAMPLE-LOSS OOM RECOVERY (3.2): the engine keeps the CPU micro-batches
of the current gradient-accumulation window in a replay buffer. On OOM:
record -> release LPU-owned temporaries -> halve the micro-batch (effective
batch preserved) -> restart the window's gradients (LOGGED, never silent) ->
re-slice the buffer -> replay every sample exactly once. If recovery cannot
be guaranteed, an LPUTrainingIntegrityError stops training with the full
audit context instead of silently dropping samples.
- PRECISION FALLBACK WITH PROVEN RESTORE (3.4): while fp16 is active, a CPU
snapshot of the weights is refreshed after every consistent optimizer step;
a non-finite-gradient event restores the last consistent weights, replays
the window in fp32, and records the whole event.
- PRECISE CUDA TIMING (3.7): forward/backward/optimizer phases are timed with
CUDA events (elapsed_time between recorded events), not wall-clock
perf_counter of async launches (which measured ~0). CPU sessions keep
perf_counter.
- ASYNC DATA PATH: micro-batches cross host->device on a dedicated CUDA
stream with event hand-off + record_stream allocator safety.
Manual-mode notes (iterate/forward/backward/step):
The manual API is explicit about what it CANNOT guarantee: on OOM it records
the event, halves future micro-batches, restarts gradients and RE-RAISES the
OOM with guidance, because replaying user-loop-owned iterations is
impossible from inside backward(). Zero-loss recovery is a session-owned-loop
guarantee. Manual mode exists for users who must own their loop; the price is
owning OOM handling too.
"""
from __future__ import annotations
import contextlib
import time
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple
from ..compat import require_torch
from ..core.engine import LPUEngine, ExecutionPlan
from ..core.workload_analyzer import WorkloadProfile, analyze_model
from ..hardware.multi_gpu import SingleGPU, DataParallel, ModelParallel
from ..memory.memory_manager import MemoryManager
from ..monitoring.performance_monitor import PerformanceMonitor, IterationTimings
from ..ipc import SessionChannel
from .batch_optimizer import BatchOptimizer, BatchState, is_cuda_oom
from .precision_manager import PrecisionManager, PrecisionDecision
from . import dataloader_optimizer as dlo
class LPUTrainingIntegrityError(RuntimeError):
"""Raised when LPU cannot GUARANTEE the zero-sample-loss contract.
Training stops with this error instead of continuing in an unverified
state. The message carries the full recovery context (what was tried,
buffer sizes, effective-batch math) so the failure is auditable.
"""
# ----------------------------------------------------------------------------
# helpers shared by engine and manual mode
# ----------------------------------------------------------------------------
def _record_stream(batch, stream) -> None:
"""Mark every CUDA tensor in a (possibly nested) batch as used by `stream`."""
torch = require_torch()
def rec(t):
if isinstance(t, torch.Tensor) and t.is_cuda:
try:
t.record_stream(stream)
except Exception: # noqa: BLE001 - best effort allocator hint
pass
elif isinstance(t, dict):
for v in t.values():
rec(v)
elif isinstance(t, (list, tuple)):
for v in t:
rec(v)
rec(batch)
def _to_device(batch, device):
torch = require_torch()
T = torch.Tensor
if isinstance(batch, T):
return batch.to(device, non_blocking=True)
if isinstance(batch, dict):
return {k: _to_device(v, device) for k, v in batch.items()}
if isinstance(batch, (list, tuple)):
conv = [_to_device(v, device) for v in batch]
return type(batch)(conv) if isinstance(batch, tuple) else conv
return batch
def n_samples(batch) -> Optional[int]:
"""Number of samples (dim 0) in a tensor / dict / tuple batch, else None."""
torch = require_torch()
if isinstance(batch, torch.Tensor) and batch.dim() >= 1:
return int(batch.shape[0])
if isinstance(batch, dict):
for v in batch.values():
n = n_samples(v)
if n is not None:
return n
if isinstance(batch, (list, tuple)) and batch:
return n_samples(batch[0])
return None
def slice_batch(batch, micro: int):
"""Slice a tensor/dict/list batch along dim 0 into chunks of `micro`.
Chunks may be smaller than `micro` at the tail; the concatenation of all
chunks is always EXACTLY the original batch (zero sample loss by
construction, asserted by callers).
"""
if micro is None or micro <= 1:
return [batch]
torch = require_torch()
def tens(t):
n = t.shape[0]
return [t[i:i + micro] for i in range(0, n, micro)]
if isinstance(batch, torch.Tensor):
return tens(batch)
if isinstance(batch, dict):
per_key = {k: tens(v) for k, v in batch.items() if isinstance(v, torch.Tensor)}
n_chunks = max((len(v) for v in per_key.values()), default=1)
out = []
for i in range(n_chunks):
mb = {}
for k, v in batch.items():
mb[k] = per_key[k][min(i, len(per_key[k]) - 1)] if k in per_key else v
out.append(mb)
return out
if isinstance(batch, (list, tuple)):
per_pos = [tens(v) if isinstance(v, torch.Tensor) else [v] for v in batch]
n_chunks = max(len(v) for v in per_pos)
out = []
for i in range(n_chunks):
mb = [v[min(i, len(v) - 1)] for v in per_pos]
out.append(type(batch)(mb) if isinstance(batch, tuple) else mb)
return out
return [batch]
# (input_key, target_key) conventions for dict batches, in priority order.
_INPUT_TARGET_CONVENTIONS: List[Tuple[str, str]] = [
("lr", "hr"), ("lq", "gt"), ("input", "target"), ("input", "gt"),
("x", "y"), ("x", "label"), ("image", "label"), ("img", "label"),
("img", "gt"), ("image", "target"), ("data", "target"), ("query", "target"),
]
def split_input_target(batch, forward_fn=None,
log=None) -> Tuple[Any, Any]:
"""Split a batch into (model_input, target) for criterion(out, target).
Resolution order:
1. forward_fn(batch) -> (model_input, target) [user adapter, explicit]
2. tuple/list with >= 2 items -> (batch[0], batch[1])
3. dict: known SR convention pairs (lr/hr, lq/gt, input/target, ...)
4. dict with exactly 2 keys -> insertion order (ASSUMPTION LOGGED)
Anything else -> ValueError with the exact remedy (pass forward_fn).
"""
if forward_fn is not None:
model_input, target = forward_fn(batch)
return model_input, target
torch = require_torch()
if isinstance(batch, (tuple, list)) and len(batch) >= 2:
return batch[0], batch[1]
if isinstance(batch, dict):
for ik, tk in _INPUT_TARGET_CONVENTIONS:
if ik in batch and tk in batch:
return batch[ik], batch[tk]
keys = list(batch.keys())
if len(keys) == 2:
if log is not None:
log.warning(
"batch dict keys %r not in known conventions; assuming "
"('%s' = input, '%s' = target) by insertion order. Pass "
"forward_fn= to make this explicit.",
keys, keys[0], keys[1])
return batch[keys[0]], batch[keys[1]]
raise ValueError(
f"cannot split dict batch with keys {keys!r} into "
f"(input, target). Known conventions: {_INPUT_TARGET_CONVENTIONS}. "
"Pass forward_fn=lambda batch: (model_input, target) to "
"train_epoch()."
)
raise ValueError(
f"cannot split batch of type {type(batch).__name__} into "
"(input, target); pass forward_fn= to train_epoch()"
)
class _PhaseTimer:
"""CUDA-event phase timing (V4 audit fix 3.7).
V3 timed forward/backward with time.perf_counter() around ASYNC kernel
launches - measuring approximately zero. V4 records real elapsed GPU
time via event pairs on the current stream (one synchronize per phase,
at the phase boundary only). Falls back to perf_counter on CPU / when
disabled by config (training.cuda_event_timing=false).
"""
def __init__(self, session: "TrainingSession", phase: str):
self.sess = session
self.phase = phase
self._ev0 = None
self._ev1 = None
self._t0 = None
def __enter__(self):
torch = self.sess._torch
self.sess._phase_now = self.phase
if (
self.sess._use_cuda_events
and torch is not None
and torch.cuda.is_available()
and self.sess._primary_device is not None
and self.sess._primary_device.type == "cuda"
):
try:
self._ev0 = torch.cuda.Event(enable_timing=True)
self._ev1 = torch.cuda.Event(enable_timing=True)
self._ev0.record()
return self
except Exception: # noqa: BLE001
self._ev0 = self._ev1 = None
self._t0 = time.perf_counter()
return self
def __exit__(self, exc_type, exc, tb):
if self._ev0 is not None and self._ev1 is not None:
try:
self._ev1.record()
self._ev1.synchronize()
dt = self._ev0.elapsed_time(self._ev1) / 1000.0
except Exception: # noqa: BLE001
dt = time.perf_counter() - self._t0
else:
dt = time.perf_counter() - (self._t0 or time.perf_counter())
setattr(self.sess, f"_t_{self.phase}", dt)
return False
class _Prefetcher:
"""One-ahead host->device prefetch on a side stream (manual-mode iterate).
Correctness pattern: each fetched batch records its OWN event on the side
stream; the consumer stream waits only for the batch it is about to use
(never for the NEXT copy). Returned tensors get `record_stream(consumer)`
so the caching allocator will not hand their storage to a later side-stream
copy while consumer kernels still read them.
"""
def __init__(self, loader, device, enabled: bool = True):
torch = require_torch()
self.loader = loader
self.device = device
self.enabled = enabled and device.type == "cuda"
self._stream = torch.cuda.Stream(device=device) if self.enabled else None
self._iter = None
self._next = None # (dev_batch, event) tuple
def _to_device(self, batch):
return _to_device(batch, self.device)
def __iter__(self):
self._iter = iter(self.loader)
if self.enabled:
try:
self._next = self._fetch(next(self._iter))
except StopIteration:
self._next = None
return self
def _fetch(self, batch):
if not self.enabled:
return self._to_device(batch), None
torch = require_torch()
with torch.cuda.device(self.device):
with torch.cuda.stream(self._stream):
dev_batch = self._to_device(batch)
ev = torch.cuda.Event()
ev.record(self._stream)
return dev_batch, ev
def __next__(self):
if not self.enabled:
return next(self._iter)
if self._next is None:
raise StopIteration
batch, ev = self._next
torch = require_torch()
cur = torch.cuda.current_stream(self.device)
if ev is not None:
cur.wait_event(ev) # wait ONLY for this batch's copy, not the next
try:
nxt = next(self._iter)
self._next = self._fetch(nxt)
except StopIteration:
self._next = None
_record_stream(batch, cur) # allocator safety for side-stream storage
return batch
@dataclass
class EpochSummary:
"""Result of one train_epoch() call (all numbers measured, none estimated)."""
epoch: int
iterations: int # micro-batches processed
optimizer_steps: int
samples: int
loss_first: Optional[float] = None
loss_last: Optional[float] = None
loss_mean: Optional[float] = None
elapsed_s: Optional[float] = None
images_per_second: Optional[float] = None
partial_window_flushed: bool = False
oom_recoveries: int = 0
warnings: List[str] = field(default_factory=list)
def summary(self) -> dict:
return {
"epoch": self.epoch,
"iterations": self.iterations,
"optimizer_steps": self.optimizer_steps,
"samples": self.samples,
"loss_first": self.loss_first,
"loss_last": self.loss_last,
"loss_mean": self.loss_mean,
"elapsed_s": round(self.elapsed_s, 4) if self.elapsed_s else None,
"images_per_second": round(self.images_per_second, 2)
if self.images_per_second else None,
"partial_window_flushed": self.partial_window_flushed,
"oom_recoveries": self.oom_recoveries,
"warnings": self.warnings,
}
@dataclass
class SessionReport:
session_id: str
plan: Dict[str, Any]
perf: Dict[str, Any]
memory: Dict[str, Any]
precision: Dict[str, Any]
batch: Dict[str, Any]
dataloader: Dict[str, Any]
@dataclass
class _OOMRecoveryEvent:
ts: float
iteration: int
phase: str
old_micro: int
new_micro: int
old_accum: int
new_accum: int
effective_batch: int
window_micros_before: int
window_micros_after: int
window_samples: int # MUST be equal before/after (invariant)
grads_restarted: bool
retries_left: int
def summary(self) -> dict:
return {
"ts": round(self.ts, 3),
"iteration": self.iteration,
"phase": self.phase,
"micro_batch": [self.old_micro, self.new_micro],
"accum_steps": [self.old_accum, self.new_accum],
"effective_batch": self.effective_batch,
"window_micro_batches": [self.window_micros_before,
self.window_micros_after],
"window_samples": self.window_samples,
"grads_restarted": self.grads_restarted,
"retries_left": self.retries_left,
}
class TrainingSession:
"""V4 training engine - see the module docstring for the full contract."""
STATUS_EVERY = 10 # IPC status write throttle (micro-iterations)
def __init__(self, model, train_loader=None, config=None, name: str = "train",
criterion=None, optimizer=None, batch_size: Optional[int] = None,
report_to_ipc: bool = True, log_dir=None):
torch = require_torch()
self._torch = torch
self.config = config or __import__("lpu.config", fromlist=["load_config"]).load_config()
self._original_model = model # untouched reference (strategies re-home)
self.train_loader = train_loader
self.name = name
self.criterion = criterion
self.optimizer = optimizer
self.requested_batch = batch_size
self._log = __import__("lpu.monitoring.logger", fromlist=["get_logger"]).get_logger(
"session", log_dir=log_dir, console=False
)
self.channel = SessionChannel() if report_to_ipc else None
self.perf = PerformanceMonitor(warmup=5, log_dir=log_dir)
# environment settings (reversible, recorded)
self._prev_settings = {}
if torch.cuda.is_available():
self._prev_settings["cudnn_benchmark"] = torch.backends.cudnn.benchmark
torch.backends.cudnn.benchmark = self.config.get("training.cudnn_benchmark", True)
try:
# pin fp32 matmul to full precision; TF32 is Ampere+ anyway
torch.set_float32_matmul_precision("highest")
except Exception: # noqa: BLE001
pass
self.engine = LPUEngine(self.config, log_dir=log_dir)
self.memory: MemoryManager = self.engine.memory
self.batch_opt = BatchOptimizer(self.config, log_dir=log_dir)
self.precision = PrecisionManager(self.config, log_dir=log_dir)
self.plan: Optional[ExecutionPlan] = None
self.batch_state: Optional[BatchState] = None
self._decision: Optional[PrecisionDecision] = None
self._scaler = None
self._runner = None # the ACTIVE strategy view (never bypassed)
self._primary_device = None
self._side_stream = None
self._channels_last = self.config.get("training.channels_last", False)
self._use_cuda_events = self.config.get("training.cuda_event_timing", True)
self._replay_enabled = self.config.get("training.oom_replay_buffer", True)
self._max_oom_retries = self.config.get("training.max_oom_retries", 3)
self._snapshot_enabled = self.config.get("precision.snapshot_for_fallback", True)
self._loss_norm = self.config.get("training.loss_normalization", "effective")
self._started_ts = None
self._loss_history: List[float] = []
# engine-mode state (the zero-loss bookkeeping) ----------------------
self._window_buf: List[Any] = [] # CPU micro-batches of current window
self._window_pos: int = 0 # micros already back-propagated
self._weights_snapshot: Optional[dict] = None
self._oom_events: List[_OOMRecoveryEvent] = []
self._oom_retries_left: int = self._max_oom_retries
self._samples_seen: int = 0 # from the loader (CPU side)
self._windows_completed: int = 0
self._partial_flushes: int = 0
self._precision_fallbacks: int = 0
self._micro_iteration: int = 0
self._batch_split_assumption: Optional[str] = None
self._active_optimizer = None # current loop's optimizer (recovery)
self._engine_used = False # True once train_epoch/train ran
self._strategy_actual = "cpu"
self._phase_now = "unknown" # set by _PhaseTimer for OOM context
self._carry_data_t = 0.0 # data-time carried across replays
self._last_manual_n = 1 # manual-mode sample count (forward)
if self.channel:
self.channel.write_descriptor({
"kind": "training_session",
"name": name,
"model": type(model).__name__,
"pid": __import__("os").getpid(),
})
# ------------------------------------------------------------------ start
def start(self, example_input=None, batch_size: Optional[int] = None):
"""Run all probes and build the execution plan. Call before training.
V4 (audit 3.1 fix): the probe batch size is the REAL requested batch
(arg > constructor > loader.batch_size > 1) - V3 hardcoded 1, which
crippled the batch probe AND forced the scheduler's tiny-batch gate.
"""
torch = self._torch
self._started_ts = time.time()
self._oom_retries_left = self._max_oom_retries
requested = batch_size or self.requested_batch
if requested is None and self.train_loader is not None:
requested = getattr(self.train_loader, "batch_size", None)
requested = int(requested or 1)
example = example_input
if example is None and self._original_model is not None:
params = list(self._original_model.parameters())
if params:
example = self._probe_example_for(requested)
self.plan = self.engine.analyze(
self._original_model, dataloader=self.train_loader,
example_input=example, batch_size=requested,
)
hw = self.plan.hardware
if hw.get("gpu_count", 0) == 0:
self._log.info("no CUDA: session runs CPU-advisory (no GPU acceleration claimed)")
self._runner = self._original_model
self._primary_device = None
self._decision = PrecisionDecision("fp32", False, False, False, None, None,
"no CUDA device")
self.batch_state = BatchState(requested, requested)
return self
# channels_last must be applied to the RAW model before any wrapping
if self._channels_last:
try:
self._original_model = self._original_model.to(
memory_format=torch.channels_last)
if example is not None and hasattr(example, "contiguous"):
example = example.contiguous(memory_format=torch.channels_last)
except Exception as exc: # noqa: BLE001
self._log.warning("channels_last unavailable: %s", exc)
# place model on the chosen strategy (wrappers move the raw model)
sched = self.plan.scheduler
strategy = sched.get("strategy", "single")
ids = sched.get("device_ids") or [0]
try:
if strategy == "data_parallel":
self._runner = DataParallel(self._original_model, ids)
elif strategy == "model_parallel":
self._runner = ModelParallel(self._original_model, ids)
else:
self._runner = SingleGPU(self._original_model, ids[0])
except Exception as exc: # noqa: BLE001
self._log.warning("strategy %s failed (%s); falling back to single", strategy, exc)
strategy = "single(fallback)"
ids = ids[:1]
self._runner = SingleGPU(self._original_model, ids[0])
self._strategy_actual = strategy
# primary device + side stream for the async data path
try:
dev = next(self._original_model.parameters()).device
self._primary_device = dev if dev.type == "cuda" else torch.device("cuda:0")
except StopIteration:
self._primary_device = torch.device("cuda:0")
try:
self._side_stream = torch.cuda.Stream(device=self._primary_device)
except Exception: # noqa: BLE001
self._side_stream = None
# probes need the RAW module + an ON-DEVICE example (never wrappers)
probe_model = self._runner.underlying if isinstance(self._runner, DataParallel) \
else self._original_model
try:
dev = next(probe_model.parameters()).device
if example is not None and hasattr(example, "to") and example.device != dev:
example = example.to(dev)
except StopIteration:
pass
# precision (measured when validate_numerics)
caps = None
gpus = hw.get("gpus") or []
if gpus:
g0 = gpus[0]
caps = __import__("lpu.hardware.capabilities", fromlist=["GPUCapabilities"]).GPUCapabilities(
index=g0.get("index", 0), name=g0.get("name", "?"),
compute_capability=tuple(int(x) for x in str(g0.get("compute_capability", "6.0")).split(".")),
total_vram_mb=g0.get("total_vram_mb", 0.0),
)
self.precision.caps = caps
self._decision = self.precision.decide(probe_model, example)
self._scaler = self.precision.make_scaler() if (
self._decision.grad_scaler) else None
# weight snapshot contract (audit 3.4): refreshed after every
# consistent fp16 step; restored on runtime fallback
if self._decision.mode == "fp16" and self._snapshot_enabled:
try:
self._weights_snapshot = self.precision.snapshot(probe_model)
self._log.info("fp16 accepted: weight snapshot taken for "
"guaranteed fallback restore")
except Exception as exc: # noqa: BLE001
self._weights_snapshot = None
self._log.warning("weight snapshot failed (%s); fallback will "
"continue WITHOUT restore (honest limitation)", exc)
# batch sizing (V4: per-GPU probe, replicas-aware)
replicas = len(ids) if strategy == "data_parallel" else 1
probe_indices = list(ids) if strategy == "data_parallel" else [
(self._primary_device.index or 0)]
self.batch_state = self.batch_opt.initial_state(
probe_model, example, requested_batch=requested,
device_indices=probe_indices, replicas=replicas,
)
self._log.info("session started: strategy=%s precision=%s micro=%d accum=%d",
strategy, self._decision.mode,
self.batch_state.micro_batch, self.batch_state.accum_steps)
return self
def __enter__(self):
return self.start()
def close(self, error: Optional[str] = None):
"""Tear down: restore settings, free LPU resources, write report."""
torch = self._torch
for k, v in self._prev_settings.items():
try:
if k == "cudnn_benchmark":
torch.backends.cudnn.benchmark = v
except Exception: # noqa: BLE001
pass
report = self.build_report(error=error)
if self.channel:
try:
self.channel.append_metrics({"kind": "session_report", **report})
self.channel.write_status({"state": "finished",
"images_per_second": report["perf"].get("images_per_second")})
self.channel.archive()
except Exception: # noqa: BLE001
pass
return report
def __exit__(self, exc_type, exc, tb):
self.close(error=str(exc) if exc else None)
return False
# ================================================================ THE ENGINE
# session-owned loop - the V4 recommended API
# ================================================================
@property
def model(self):
"""The ACTIVE strategy view. The engine only ever calls this - which
is why the selected strategy is exercised by construction (audit 3.1:
V3's example ignored it)."""
return self._runner if self._runner is not None else self._original_model
@property
def strategy_actual(self) -> str:
"""The strategy ACTUALLY running (vs. planned) - appears in reports."""
return getattr(self, "_strategy_actual", "cpu")
def train(self, epochs: int = 1, loader=None, criterion=None, optimizer=None,
forward_fn: Optional[Callable] = None,
on_epoch_end: Optional[Callable] = None,
on_step: Optional[Callable] = None) -> List[EpochSummary]:
"""Run `epochs` full epochs through the session-owned loop.
Windows CARRY ACROSS epoch boundaries (the effective batch stays
exact); the final partial window is flushed with one real, logged
optimizer step at the end of the LAST epoch.
"""
summaries = []
for ep in range(epochs):
s = self.train_epoch(loader=loader, criterion=criterion,
optimizer=optimizer, epoch=ep,
forward_fn=forward_fn, on_step=on_step)
summaries.append(s)
if on_epoch_end is not None:
try:
on_epoch_end(ep, s)
except Exception: # noqa: BLE001 - user callback must not kill training
self._log.exception("on_epoch_end callback failed")
# final flush: any carried partial window becomes one logged step
if self.batch_state is not None and self.batch_state.samples_in_window > 0:
n_partial = self.batch_state.samples_in_window
self.flush(optimizer=optimizer, criterion=criterion)
if summaries:
last = summaries[-1]
last.partial_window_flushed = True
last.optimizer_steps += 1
last.warnings.append(
f"final partial window flushed after last epoch: "
f"{n_partial} samples stepped with a smaller effective "
"batch (counted and reported, not silent)")
return summaries
def train_epoch(self, loader=None, criterion=None, optimizer=None,
epoch: int = 0, forward_fn: Optional[Callable] = None,
on_step: Optional[Callable] = None) -> EpochSummary:
"""ONE epoch, run BY THE SESSION (fetch->transfer->fwd->loss->bwd->step).
Guarantees (see module docstring):
- every sample of every loader batch is back-propagated EXACTLY once
per optimizer step, across any number of OOM recoveries;
- the active strategy wrapper is the only model view called;
- effective batch = micro * accum is preserved through recoveries;
- windows CARRY ACROSS epoch boundaries (a partial window at the end
of this call stays accumulated for the next call / final flush) -
use train() for automatic end-of-training flushing, or call
sess.flush() yourself.
forward_fn(batch) -> (model_input, target) adapts exotic batches;
without it, (input, target) follows the documented conventions.
"""
loader = loader if loader is not None else self.train_loader
criterion = criterion if criterion is not None else self.criterion
optimizer = optimizer if optimizer is not None else self.optimizer
if loader is None:
raise ValueError("no loader (pass loader= or construct with train_loader)")
if criterion is None:
raise ValueError("no criterion (pass criterion= or construct with criterion)")
if optimizer is None:
raise ValueError("no optimizer (pass optimizer= or construct with optimizer)")
if self.batch_state is None:
self.start()
# dataloader measurement (advisory, once)
try:
stats = dlo.measure(loader)
recs = dlo.recommend(
stats,
self._primary_device.type == "cuda" if self._primary_device else False,
self.config.get("training.dataloader_max_workers", 8))
self._dataloader_report = {
"measured": stats.summary(),
"recommended": recs,
"diff": dlo.diff(stats, recs),
}
except Exception: # noqa: BLE001
self._dataloader_report = {}
s = EpochSummary(epoch=epoch, iterations=0, optimizer_steps=0, samples=0)
t_start = time.perf_counter()
losses: List[float] = []
# fresh window per epoch call (partial windows from a previous call
# are the caller's business; train() avoids this by never leaving one)
if self.batch_state is not None and self.batch_state.samples_in_window > 0:
s.warnings.append(
f"epoch started with a carried-over partial window of "
f"{self.batch_state.samples_in_window} sample(s) from a "
"previous train_epoch call; it will be flushed at the "
"end of THIS epoch")
ooms_at_start = len(self._oom_events)
for raw in loader:
t_data0 = time.perf_counter()
micros = slice_batch(raw, self.batch_state.micro_batch)
n_in = n_samples(raw)
if n_in is None and self.batch_state.micro_batch > 1:
# non-slicable batch: cannot micro-batch; honest treatment
micros = [raw]
s.warnings.append(
"non-slicable batch type "
f"{type(raw).__name__}: micro-batching disabled for it; "
"OOM recovery cannot re-slice and the effective batch "
"cannot be split exactly (will hard-stop if it OOMs)")
self._samples_seen += n_in or 1
data_t = time.perf_counter() - t_data0
for mi, micro in enumerate(micros):
loss, stepped = self._window_step(
micro, criterion, optimizer, forward_fn,
data_t if mi == 0 else 0.0)
s.iterations += 1
self._micro_iteration += 1
if loss is not None and loss == loss: # not NaN
losses.append(loss)
s.samples += (n_samples(micro) or 1)
if stepped:
s.optimizer_steps += 1
if on_step is not None:
try:
on_step(s.optimizer_steps, loss)
except Exception: # noqa: BLE001
self._log.exception("on_step callback failed")
self._maybe_write_status()
# partial window at epoch end CARRIES (exact effective batch wins;
# train()/flush() handles the end-of-training flush)
if self.batch_state is not None and self.batch_state.samples_in_window > 0:
s.warnings.append(
f"{self.batch_state.samples_in_window} sample(s) remain in a "
"partial accumulation window at epoch end (carried to the "
"next epoch; flush via train() or sess.flush())")
# ---- integrity invariant: every seen sample was back-propagated ----
seen = self._samples_seen
done = self.batch_state.samples_done_epoch
if seen != done:
raise LPUTrainingIntegrityError(
f"sample accounting mismatch after epoch: loader yielded "
f"{seen} samples, {done} were back-propagated. This is a bug "
"in LPU - training stopped rather than continue unverified.")
if losses:
s.loss_first, s.loss_last = losses[0], losses[-1]
s.loss_mean = sum(losses) / len(losses)
self._loss_history.extend(losses)
s.elapsed_s = time.perf_counter() - t_start
if s.elapsed_s and s.samples:
s.images_per_second = s.samples / s.elapsed_s
s.oom_recoveries = len(self._oom_events) - ooms_at_start
return s
def evaluate(self, loader=None, criterion=None, forward_fn: Optional[Callable] = None,
max_batches: Optional[int] = None) -> dict:
"""Evaluation loop (no_grad, same strategy view + precision policy)."""
torch = self._torch
loader = loader if loader is not None else self.train_loader
criterion = criterion if criterion is not None else self.criterion
if loader is None or criterion is None:
raise ValueError("evaluate() needs a loader and a criterion")
if self._runner is None:
self.start()
total_loss, total_images = 0.0, 0
n_eval = 0
was_training = self.model.training if hasattr(self.model, "training") else False
try:
self.model.eval()
t0 = time.perf_counter()
with torch.no_grad():
for bi, batch in enumerate(loader):
if max_batches is not None and bi >= max_batches:
break
model_input, target = split_input_target(
batch, forward_fn, log=self._log)
dev_in = self._transfer(model_input)
dev_tg = self._transfer(target)
if self._decision and self._decision.autocast and \
self._primary_device is not None:
with self.precision.autocast_context(True):
out = self.model(dev_in)
else:
out = self.model(dev_in)
loss = criterion(out, dev_tg)
n_img = n_samples(batch) or 1
total_loss += float(loss.detach()) * n_img
total_images += n_img
n_eval += 1
elapsed = time.perf_counter() - t0
return {
"batches": n_eval,
"images": total_images,
"loss_mean": (total_loss / total_images) if total_images else None,
"elapsed_s": round(elapsed, 4),
"images_per_second": round(total_images / elapsed, 2)
if elapsed > 0 and total_images else None,
}
finally:
if was_training and hasattr(self.model, "train"):
self.model.train()
# ------------------------------------------------------- window machinery
def _window_step(self, micro, criterion, optimizer, forward_fn,
data_t: float) -> Tuple[Optional[float], bool]:
"""Add ONE micro-batch to the window and drive the window forward.
This is the zero-sample-loss heart (audit 3.2):
- the CPU micro-batch is retained in the replay buffer;
- forward/backward run through the ACTIVE strategy view;
- on OOM: halve micro, restart grads (logged), re-slice the buffer,
and REPLAY the window - every sample processed exactly once;
- when the window completes: optimizer step (AMP-gated), window
closed, weights snapshot refreshed (fp16 mode).
Returns (loss, stepped); `stepped` is True when the optimizer
stepped while consuming this micro-batch.
"""
self._active_optimizer = optimizer
self._engine_used = True
self._window_buf.append(micro)
self._carry_data_t = max(self._carry_data_t, data_t)
while True:
try:
return self._process_window(criterion, optimizer, forward_fn)
except _WindowReplaySignal:
# recovery already re-sliced the buffer / fell back to fp32;
# loop again to replay (budget enforced inside recovery)
continue
def _process_window(self, criterion, optimizer, forward_fn
) -> Tuple[Optional[float], bool]:
"""Back-propagate buffered micros from _window_pos; step when full.
Exact-window semantics: a micro-batch that would overshoot the
effective batch is SPLIT - the needed part closes the window, the
remainder opens the next one. The effective batch is therefore
EXACT in samples, not approximate in micro counts (audit 3.2:
"precise preservation of samples and Effective Batch").
Raises _WindowReplaySignal on OOM / precision fallback so the outer
loop can retry after the recovery procedure ran.
"""
loss_val: Optional[float] = None
stepped_any = False
while self._window_pos < len(self._window_buf):
micro = self._window_buf[self._window_pos]
n = n_samples(micro)
if n is None:
n = 1 # non-slicable batch: exactness degraded (warned)
elif n > 1:
# exact-window split: never overshoot the effective batch
need = self.batch_state.effective_batch \
- self.batch_state.samples_in_window
if 0 < need < n:
parts = slice_batch(micro, need)
if len(parts) > 1 and (n_samples(parts[0]) or 0) == need:
self._window_buf[self._window_pos] = parts[0]
self._window_buf[self._window_pos + 1:self._window_pos + 1] = parts[1:]
micro = parts[0]
n = need
try:
with _PhaseTimer(self, "data"):
model_input, target = split_input_target(
micro, forward_fn, log=self._log)
dev_in = self._transfer(model_input)
dev_tg = self._transfer(target)
with _PhaseTimer(self, "forward"):
out = self._forward_dev(dev_in)
loss = criterion(out, dev_tg)
with _PhaseTimer(self, "backward"):
self._backward_scaled(loss * self._accum_factor(n))
except _OOMDuring as oom:
self._recover_from_oom(oom.phase)
raise _WindowReplaySignal("oom", str(oom)) from oom.exc
except Exception as exc: # noqa: BLE001
if is_cuda_oom(exc):
self._recover_from_oom(self._phase_now)
raise _WindowReplaySignal("oom", str(exc)) from exc
raise
self.batch_state.advance(n)
self._window_pos += 1
loss_val = float(loss.detach())
if self.batch_state.should_step():
stepped = self._step_optimizer(optimizer)
if not stepped:
# non-finite grads: weights restored / fallback already
# done; replay the window in fp32 (never drop samples)
raise _WindowReplaySignal(
"precision-fallback", "window replay in fp32")
self._windows_completed += 1
stepped_any = True
# keep only the unprocessed remainder (split leftovers)
self._window_buf = self._window_buf[self._window_pos:]
self._window_pos = 0
self.batch_state.close_window()
self._record_iteration(self._carry_data_t, n, loss_val)
self._carry_data_t = 0.0
return loss_val, stepped_any
def flush(self, optimizer=None, criterion=None) -> bool:
"""Explicitly step a carried partial window (logged, counted).
Call after train_epoch() loops you drive yourself; train() already
flushes at its end. Returns True when a partial step was executed.
"""
if self.batch_state is None or self.batch_state.samples_in_window <= 0:
return False
opt = optimizer or self.optimizer
if opt is None:
raise ValueError("flush() needs the training optimizer "
"(pass optimizer= or construct with optimizer)")
self._flush_partial_window(criterion or self.criterion, opt, None)
return True
def _flush_partial_window(self, criterion, optimizer, forward_fn) -> None:
"""Force-step the partial window at epoch end (counted, logged).
All buffered micros were already back-propagated (their gradients
sit in .grad); the window just never reached the effective batch.
We step on what exists - recorded as a partial flush - instead of
dropping the samples' gradients (audit 3.2: never silently drop).
"""
self._partial_flushes += 1
n = self.batch_state.samples_in_window
self._log.warning(
"flushing partial accumulation window: %d sample(s) will be "
"stepped with a smaller effective batch (recorded in report)", n)
# any never-processed micros (defensive; normally none at epoch end)
while self._window_pos < len(self._window_buf):
try:
self._process_window(criterion, optimizer, forward_fn)
break
except _WindowReplaySignal:
continue
stepped = self._step_optimizer(optimizer)
if stepped:
self._windows_completed += 1
self._window_buf = self._window_buf[self._window_pos:]
self._window_pos = 0
self.batch_state.close_window()
# ------------------------------------------------------------- primitives
def _forward_dev(self, dev_input):
"""Forward through the ACTIVE strategy view under the precision policy."""
if self._decision and self._decision.autocast and \
self._primary_device is not None:
with self.precision.autocast_context(True):
return self.model(dev_input)
return self.model(dev_input)
def _accum_factor(self, n: int) -> float:
"""Loss scale factor making accumulated grads EQUAL full-batch grads.
With exact windows (samples sum to effective_batch), the factors of
all micros in a window sum to exactly 1.0, so
sum_k factor_k * dloss_k == d(mean loss over the window) - the
gradient a full effective-batch step would have produced. Without
this, K equal micros would multiply the gradient by K (silent
effective-batch corruption - the V3 audit's core accumulation bug).
Set training.loss_normalization=none to disable (users who scale
losses themselves).
"""
if self._loss_norm == "none" or self.batch_state is None:
return 1.0
eff = self.batch_state.effective_batch
if eff <= 0:
return 1.0
return n / eff
def _backward_scaled(self, loss) -> None:
"""Scaled backward. Raises _OOMDuring('backward') on CUDA OOM."""
try:
scaled = self._scaler.scale(loss) if self._scaler is not None else loss
scaled.backward()
except Exception as exc: # noqa: BLE001
if is_cuda_oom(exc):
raise _OOMDuring("backward", exc) from exc
raise
def _transfer(self, obj):
"""Async H2D on the side stream (event hand-off + record_stream).
CPU sessions: no-op (data stays as-is; the model is CPU too).
"""
torch = self._torch
if (self._primary_device is None or obj is None
or not torch.cuda.is_available()):
return obj
try:
with torch.cuda.device(self._primary_device):
with torch.cuda.stream(self._side_stream):
dev = _to_device(obj, self._primary_device)
ev = torch.cuda.Event()
ev.record(self._side_stream)
cur = torch.cuda.current_stream(self._primary_device)
cur.wait_event(ev)
_record_stream(dev, cur)
return dev
except RuntimeError as exc:
if is_cuda_oom(exc):
raise _OOMDuring("transfer", exc) from exc
raise
def _step_optimizer(self, optimizer) -> bool:
"""Execute ONE optimizer step (AMP unscale + finite gate + step).
Returns True when the step executed. On non-finite gradients under
fp16: restores the last consistent weights (audit 3.4), falls back
to fp32 permanently, and asks for a window replay in fp32 - the
samples are re-processed, never dropped.
Non-finite gradients under FP32 are a user-level training fault:
hard stop with full context.
"""
with _PhaseTimer(self, "optimizer"):
torch = self._torch
if self._scaler is not None:
self._scaler.unscale_(optimizer)
finite = True
for group in optimizer.param_groups:
for p in group["params"]:
if p.grad is not None and not bool(
torch.isfinite(p.grad).all()):
finite = False
break
if not finite:
break
if not finite:
self._handle_nonfinite_grads(optimizer)
return False
self._scaler.step(optimizer)
self._scaler.update()
else:
optimizer.step()
optimizer.zero_grad(set_to_none=True)
# refresh the fp16 weight snapshot AFTER a consistent step (3.4)
if self._decision is not None and self._decision.mode == "fp16" \
and self._snapshot_enabled:
try:
raw = self._runner.underlying if isinstance(self._runner,
DataParallel) \
else self._original_model
self._weights_snapshot = self.precision.snapshot(raw)
except Exception: # noqa: BLE001
pass
return True
def _handle_nonfinite_grads(self, optimizer) -> None:
"""Non-finite gradients: restore weights, fall back, request replay."""
optimizer.zero_grad(set_to_none=True)
if self._decision is not None and self._decision.mode != "fp16":
raise LPUTrainingIntegrityError(
"non-finite gradients under FP32: this is a training-level "
"fault (data/loss/optimizer), not an LPU recoverable "
"condition. Training stopped rather than continue unverified.")
self._precision_fallbacks += 1
self.perf.note_precision_fallback()
restored = False
if self._weights_snapshot is not None:
raw = self._runner.underlying if isinstance(self._runner, DataParallel) \
else self._original_model
restored = self.precision.restore(raw, self._weights_snapshot)
if restored:
self._log.warning(
"fp16 runtime fallback: non-finite gradients; weights "
"RESTORED from the last consistent step snapshot; the "
"window will be replayed in fp32 (no samples lost)")
else:
self._log.error(
"fp16 runtime fallback: snapshot RESTORE FAILED - "
"continuing with current weights (honest disclosure; "
"scaler skipped the corrupt step, weights are the last "
"stepped ones)")
else:
self._log.warning(
"fp16 runtime fallback: no weight snapshot available "
"(snapshot_for_fallback=false or snapshot failed earlier); "
"the skipped step protects the weights, restore not needed")
self.precision.note_fallback("non-finite gradients under fp16")
self._decision = PrecisionDecision(
"fp32", False, False, True, None, None,
"runtime fallback: non-finite gradients; "
+ ("weights restored from snapshot" if restored
else "weights kept (no snapshot)"))
self._scaler = None
# restart the window so the replay re-processes its samples in fp32
self.batch_state.restart_window()
self._window_pos = 0
# ---------------------------------------------------------- OOM recovery
def _recover_from_oom(self, phase: str) -> None:
"""The V4 zero-loss OOM recovery procedure (audit 3.2).
1. record the event (memory manager + perf counter)
2. release LPU-owned temporaries ONLY (cache evict + one gated
empty_cache on the affected device - never user tensors)
3. halve the micro-batch, keeping effective batch EXACTLY equal
4. restart the window's gradients (LOGGED window_restart - the
replay re-processes those samples; nothing is silently dropped)
5. re-slice the retained CPU window buffer at the new micro size,
asserting the sample count is IDENTICAL before/after
6. if any guarantee cannot be upheld: LPUTrainingIntegrityError
"""
torch = self._torch
if self._oom_retries_left <= 0:
raise LPUTrainingIntegrityError(
f"CUDA OOM in {phase}: recovery budget exhausted "
f"({self._max_oom_retries} recoveries allowed per session "
"run). Training stopped rather than risk silent sample "
f"loss. Context: micro={self.batch_state.micro_batch}, "
f"accum={self.batch_state.accum_steps}, "
f"effective={self.batch_state.effective_batch}, "
f"window_micros={len(self._window_buf)}")
self._oom_retries_left -= 1
dev_idx = (self._primary_device.index or 0) \
if self._primary_device is not None else 0
self.memory.record_oom(dev_idx, {"detail": f"training {phase}",
"phase": phase})
self.memory.controlled_cleanup(dev_idx, reason="training OOM")
self.perf.note_oom()
old = self.batch_state
samples_before = sum((n_samples(m) or 0) for m in self._window_buf)
micros_before = len(self._window_buf)
new = self.batch_opt.on_oom(old, phase)
if new is None:
raise LPUTrainingIntegrityError(
f"CUDA OOM in {phase} with micro_batch={old.micro_batch}: "
"no further reduction possible. Training stopped rather "
"than drop samples. The loader batch size must be reduced "
"or the model shrunk - LPU will not silently continue.")
# transfer the accounting so samples_done_epoch stays exact across
# the replay (restart_window subtracts the window's samples below)
new.samples_done_epoch = old.samples_done_epoch
new.samples_in_window = old.samples_in_window
new.step_in_accum = old.step_in_accum
new.restart_window()
optimizer = self._active_optimizer
try:
if optimizer is not None:
optimizer.zero_grad(set_to_none=True) # window restart (logged)
except Exception: # noqa: BLE001
pass
self._log.warning(
"OOM recovery (phase=%s): window gradients RESTARTED for replay "
"(logged, not silent); micro %d -> %d, accum %d -> %d, effective "
"batch preserved at %d",
phase, old.micro_batch, new.micro_batch, old.accum_steps, new.accum_steps,
new.effective_batch)
# re-slice the retained buffer at the new micro size
try:
resliced: List[Any] = []
for m in self._window_buf:
resliced.extend(slice_batch(m, new.micro_batch))
except Exception as exc: # noqa: BLE001
raise LPUTrainingIntegrityError(
f"OOM recovery could not re-slice the window buffer "
f"({exc}); training stopped rather than risk sample loss") from exc
samples_after = sum((n_samples(m) or 0) for m in resliced)
if samples_after != samples_before:
raise LPUTrainingIntegrityError(
f"OOM re-slice changed the window sample count "
f"({samples_before} -> {samples_after}); training stopped - "
"this is an LPU bug")
self.batch_state = new
self._window_buf = resliced
self._window_pos = 0
self._oom_events.append(_OOMRecoveryEvent(
ts=time.time(),
iteration=self._micro_iteration,
phase=phase,
old_micro=old.micro_batch, new_micro=new.micro_batch,
old_accum=old.accum_steps, new_accum=new.accum_steps,
effective_batch=new.effective_batch,
window_micros_before=micros_before,
window_micros_after=len(resliced),
window_samples=samples_after,
grads_restarted=True,
retries_left=self._oom_retries_left,
))
def _record_iteration(self, data_t: float, images: int, loss: float) -> None:
rec = IterationTimings(
data=data_t,
forward=getattr(self, "_t_forward", None),
backward=getattr(self, "_t_backward", None),
optimizer=getattr(self, "_t_optimizer", None),
total=None,
images=images,
loss=loss,
)
rec.total = data_t + (rec.forward or 0.0) + (rec.backward or 0.0) \
+ (rec.optimizer or 0.0)
self.perf.record(rec)
self._pending_loss = loss
def _maybe_write_status(self) -> None:
if self.channel and (self._micro_iteration % self.STATUS_EVERY == 0):
try:
self.channel.write_status({
"state": "training",
"iterations": self._micro_iteration,
})
except Exception: # noqa: BLE001
pass
# ==================================================== manual step-level API
# explicit, honest about its limits (see module docstring)
# ================================================================
def iterate(self, loader, requested_batch: Optional[int] = None):
"""Manual-mode iteration (prefetch + micro-slicing + timing).
Yields DEVICE-side micro-batches. Pair with forward()/backward()/
step(). NOTE: manual mode cannot replay user-owned iterations, so
its OOM contract is: record + halve future micros + grad restart +
RE-RAISE with guidance. Use train_epoch() for zero-loss recovery.
"""
if requested_batch and self.batch_state and self._torch.cuda.is_available():
self.batch_state.requested_batch = requested_batch
device = self._primary_device or _cpu_device()
try:
device = next(self._original_model.parameters()).device
except StopIteration:
pass
return _IterContext(self, loader, device)
def slice_batch(self, batch):
"""Public helper: slice a batch at the CURRENT micro size."""
return slice_batch(batch, self.batch_state.micro_batch
if self.batch_state else 1)
def forward(self, batch_input, model=None):
"""Timed forward under the session's precision policy.
Always forwards through the session's ACTIVE strategy view. The
optional `model` argument is accepted for V3 call-compatibility and
IGNORED (passing it was never safe: strategy wrappers re-home
modules; the session view is the only correct one).
"""
if model is not None and not hasattr(batch_input, "shape") \
and not isinstance(batch_input, (dict, tuple, list)):
# legacy positional call forward(model, x): swap gracefully
batch_input, model = model, batch_input
self._last_manual_n = n_samples(batch_input) or 1
with _PhaseTimer(self, "forward"):
out = self._forward_dev(batch_input)
self._pending_optimizer = None
return out
def backward(self, loss, optimizer) -> bool:
"""Timed backward with AMP scaling. Returns True on success.
Manual-mode OOM contract (differs from the engine - documented):
on CUDA OOM this records the event, halves FUTURE micro-batches,
restarts gradients, and RE-RAISES with guidance, because the failed
micro-batch cannot be replayed from inside backward() when the
caller owns the loop. The zero-sample-loss guarantee is available in
session-owned mode (train_epoch), where the replay buffer exists.
"""
with _PhaseTimer(self, "backward"):
try:
factor = self._accum_factor(self._last_manual_n)
self._backward_scaled(loss * factor if factor != 1.0 else loss)
except _OOMDuring as oom:
# manual-mode OOM: record, halve future micros, restart
# grads, then RE-RAISE the ORIGINAL OOM with guidance
# (replay is impossible when the caller owns the loop)
self._manual_oom_recovery(optimizer, oom.exc)
raise oom.exc from None
except Exception as exc: # noqa: BLE001
if not is_cuda_oom(exc):
raise
self._manual_oom_recovery(optimizer, exc)
raise
self._pending_optimizer = optimizer
self._pending_loss = float(loss.detach()) if loss.dim() == 0 else None
# the window counter advances ONLY on a successful backward
if self.batch_state is not None:
self.batch_state.advance(self._last_manual_n)
return True
def _manual_oom_recovery(self, optimizer, exc) -> None:
dev_idx = (self._primary_device.index or 0) \
if self._primary_device is not None else 0
self.memory.record_oom(dev_idx, {"detail": "manual backward",
"phase": "backward"})
self.memory.controlled_cleanup(dev_idx, reason="training OOM")
self.perf.note_oom()
if self.batch_state is not None:
new_state = self.batch_opt.on_oom(self.batch_state, "manual backward")
if new_state is not None:
new_state.samples_done_epoch = self.batch_state.samples_done_epoch
new_state.samples_in_window = self.batch_state.samples_in_window
new_state.restart_window()
self.batch_state = new_state
try:
optimizer.zero_grad(set_to_none=True)
except Exception: # noqa: BLE001
pass
self._log.warning(
"manual-mode OOM: micro-batch halved to %d for FUTURE "
"batches and window gradients restarted; RE-RAISING the "
"OOM to the caller - re-run YOUR micro-batch (or switch "
"to sess.train_epoch() for automatic zero-loss replay). "
"Original error: %s",
new_state.micro_batch, exc)
return
raise LPUTrainingIntegrityError(
f"manual-mode OOM at micro_batch="
f"{self.batch_state.micro_batch if self.batch_state else '?'}: "
"no further reduction possible. Original error: "
f"{exc}. Reduce the loader batch size or use train_epoch()."
) from exc
def should_step(self) -> bool:
"""PURE QUERY (V4): would step() now execute the optimizer step?
No side effects - safe to call for logging/branching. The window
counter advances only via the session's backward() completion.
"""
if self.batch_state is None:
return True
# manual mode: advance happens inside backward() success path
return self.batch_state.should_step()
def step(self, optimizer) -> bool:
"""Execute the optimizer step IF the accumulation window is complete.
Returns True when a step ran. Handles AMP unscale/step/update, the
finite-gradient gate, fp32 fallback with weight restore, and
zero_grad. This is the ONLY place a manual-mode loop should step.
"""
if not self.should_step():
return False
stepped = self._step_optimizer(optimizer)
if stepped and self.batch_state is not None:
self.batch_state.close_window()
return stepped
# -- misc ----------------------------------------------------------------
def _probe_example_for(self, batch: int):
"""A real on-device example tensor for the batch probe (never None)."""
try:
p = next(self._original_model.parameters())
if p.dim() == 4: # conv weight (out,in,kh,kw) -> N,C,H,W probe
c = min(3, p.shape[1])
return p.new_zeros((batch, c, 64, 64))
return p.new_zeros((batch, p.shape[0] if p.dim() > 1 else 1))
except StopIteration:
return None
def build_report(self, error: Optional[str] = None) -> dict:
bs = self.batch_state
seen, done = self._samples_seen, (bs.samples_done_epoch if bs else 0)
return {
"session_id": self.channel.session_id if self.channel else "in-memory",
"version": 4,
"plan": self.plan.summary() if self.plan else {},
"perf": self.perf.summary(),
"memory": self.memory.snapshot(),
"precision": (self._decision.summary() if self._decision else {}),
"batch": {
"requested": bs.requested_batch if bs else None,
"micro": bs.micro_batch if bs else None,
"accum_steps": bs.accum_steps if bs else None,
"effective": bs.effective_batch if bs else None,
"adjustments": [a.summary() for a in bs.adjustments] if bs else [],
},
"engine": {
"mode": "session_loop" if getattr(self, "_engine_used", False)
else "manual_or_idle",
"strategy_actual": self.strategy_actual,
"timing_method": ("cuda_events"
if self._use_cuda_events and self._torch.cuda.is_available()
else "perf_counter"),
"criterion": type(self.criterion).__name__
if self.criterion else None,
"weights_snapshot_active": self._weights_snapshot is not None,
},
"integrity": {
"samples_seen": seen,
"samples_backpropagated": done,
# the seen==backpropagated invariant is an ENGINE-mode
# guarantee; manual mode reports None (honest: the user's
# loop owns the sample flow, LPU only counts backward calls)
"invariant_ok": (seen == done) if self._engine_used else None,
"windows_completed": self._windows_completed,
"partial_window_flushes": self._partial_flushes,
"oom_recoveries": [e.summary() for e in self._oom_events],
"oom_retries_left": self._oom_retries_left,
"precision_fallbacks": self._precision_fallbacks,
},
"dataloader": getattr(self, "_dataloader_report", {}),
"error": error,
}
class _OOMDuring(Exception):
"""Internal: a CUDA OOM happened during `phase` (carries the original)."""
def __init__(self, phase: str, exc: BaseException):
super().__init__(f"CUDA OOM during {phase}: {exc}")
self.phase = phase
self.exc = exc
class _WindowReplaySignal(Exception):
"""Internal: recovery ran; the window should be re-processed."""
def __init__(self, reason: str, message: str = ""):
super().__init__(message or reason)
self.reason = reason
self.message = message
self.exc = None
def _cpu_device():
torch = require_torch()
return torch.device("cpu")
class _IterContext:
"""Manual-mode iterator: data timing, micro-batching, iteration records.
Timing contract (primary metrics are images/sec + iteration time):
- rec.total = data + forward + backward + optimizer for ONE iteration
- the previous record is finalized when the NEXT data fetch starts (so
data time belongs to the iteration that consumed it, and the final
record is flushed at StopIteration - nothing is dropped)
- status writes are throttled (every 10 iterations) so monitor overhead
never distorts the measured loop
"""
STATUS_EVERY = 10
def __init__(self, session: TrainingSession, loader, device):
self.session = session
self.loader = loader
self.device = device
self.stats = dlo.measure(loader) if loader is not None else None
self.recs = dlo.recommend(self.stats, device.type == "cuda",
session.config.get("training.dataloader_max_workers", 8)) if self.stats else {}
session._dataloader_report = {
"measured": self.stats.summary() if self.stats else {},
"recommended": self.recs,
"diff": dlo.diff(self.stats, self.recs) if self.stats else {},
"applied": ({"note": "apply_recommendations applies only through the "
"guarded DataLoader wrapper in hooks, not via iterate()"}
if session.config.get("training.dataloader_apply_recommendations", False) else False),
}
prefetch_on = session.config.get("training.prefetch", True)
self._prefetcher = _Prefetcher(loader, device, enabled=prefetch_on).__iter__() \
if loader is not None else None
self._iter_count = 0
self._micro_queue = [] # micro-batches sliced from the current loader batch
def __iter__(self):
return self
def __next__(self):
s = self.session
t0 = time.perf_counter()
# micro-batches from the current loader batch first
if self._micro_queue:
batch = self._micro_queue.pop(0)
data_t = 0.0 # already fetched as part of the parent batch
else:
try:
raw = next(self._prefetcher) if self._prefetcher is not None else next(self.loader)
except StopIteration:
self._flush_pending(final=True)
raise
data_t = time.perf_counter() - t0
micro = s.batch_state.micro_batch if s.batch_state else 1
if micro and micro > 1:
chunks = slice_batch(raw, micro)
self._micro_queue = chunks[1:]
batch = chunks[0]
else:
batch = raw
# finalize the PREVIOUS record now that the loop wants a new batch
self._flush_pending(final=False, next_data_t=data_t)
rec = IterationTimings(
forward=getattr(s, "_t_forward", None),
backward=getattr(s, "_t_backward", None),
optimizer=getattr(s, "_t_optimizer", None),
total=None,
images=(s.batch_state.micro_batch if s.batch_state else 1),
loss=getattr(s, "_pending_loss", None),
)
s._pending_iter = rec
self._iter_count += 1
return batch
def _flush_pending(self, final: bool, next_data_t: float = 0.0) -> None:
s = self.session
rec = getattr(s, "_pending_iter", None)
if rec is None:
return
rec.data = next_data_t
# FULL iteration time = data + all phases
rec.total = next_data_t + (rec.forward or 0.0) + (rec.backward or 0.0) \
+ (rec.optimizer or 0.0)
s.perf.record(rec)
s._pending_iter = None
if s.channel and (final or self._iter_count % self.STATUS_EVERY == 0):
try:
s.channel.write_status({
"state": "training",
"iterations": self._iter_count,
})
except Exception: # noqa: BLE001
pass
def training_session(model, train_loader=None, config=None, name="train",
criterion=None, optimizer=None, batch_size=None):
"""Factory for the V4 session (all-in-one: pass criterion/optimizer once)."""
return TrainingSession(model, train_loader=train_loader, config=config,
name=name, criterion=criterion, optimizer=optimizer,
batch_size=batch_size)
"""LPU V4 Training Engine: the session-owned training loop.
This module is the V4 answer to audit finding 3.1 ("no single coherent
training API"). There is now exactly ONE recommended way to train with LPU,
and it puts the SESSION in charge of the loop:
import lpu
with lpu.training_session(model, train_loader,
criterion=criterion, optimizer=opt,
batch_size=16) as sess:
for epoch in range(epochs):
summary = sess.train_epoch() # session runs the loop
print(summary["loss_last"], summary["images_per_second"])
Because the session runs fetch -> transfer -> forward(strategy) -> loss ->
backward -> accumulation -> step, the selected multi-GPU strategy, the
measured precision policy, the micro-batch sizing and the OOM recovery are
ALL exercised BY CONSTRUCTION - there is no way for user code to accidentally
bypass them (the V3 failure mode: the example called the raw model and the
whole optimization stack never ran).
A step-level manual API still exists for advanced users (iterate/forward/
backward/step/should_step) - see the ManualMode notes at the bottom of this
docstring for its EXACT guarantees.
Engineering contracts implemented here (V4):
- COHERENT API (3.1): start() probes with the REAL requested batch size;
the strategy wrapper is the only model view ever called; should_step() is
a pure query; step() is the only place the optimizer steps.
- ZERO-SAMPLE-LOSS OOM RECOVERY (3.2): the engine keeps the CPU micro-batches
of the current gradient-accumulation window in a replay buffer. On OOM:
record -> release LPU-owned temporaries -> halve the micro-batch (effective
batch preserved) -> restart the window's gradients (LOGGED, never silent) ->
re-slice the buffer -> replay every sample exactly once. If recovery cannot
be guaranteed, an LPUTrainingIntegrityError stops training with the full
audit context instead of silently dropping samples.
- PRECISION FALLBACK WITH PROVEN RESTORE (3.4): while fp16 is active, a CPU
snapshot of the weights is refreshed after every consistent optimizer step;
a non-finite-gradient event restores the last consistent weights, replays
the window in fp32, and records the whole event.
- PRECISE CUDA TIMING (3.7): forward/backward/optimizer phases are timed with
CUDA events (elapsed_time between recorded events), not wall-clock
perf_counter of async launches (which measured ~0). CPU sessions keep
perf_counter.
- ASYNC DATA PATH: micro-batches cross host->device on a dedicated CUDA
stream with event hand-off + record_stream allocator safety.
Manual-mode notes (iterate/forward/backward/step):
The manual API is explicit about what it CANNOT guarantee: on OOM it records
the event, halves future micro-batches, restarts gradients and RE-RAISES the
OOM with guidance, because replaying user-loop-owned iterations is
impossible from inside backward(). Zero-loss recovery is a session-owned-loop
guarantee. Manual mode exists for users who must own their loop; the price is
owning OOM handling too.
"""
from __future__ import annotations
import contextlib
import time
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple
from ..compat import require_torch
from ..core.engine import LPUEngine, ExecutionPlan
from ..core.workload_analyzer import WorkloadProfile, analyze_model
from ..hardware.multi_gpu import SingleGPU, DataParallel, ModelParallel
from ..memory.memory_manager import MemoryManager
from ..monitoring.performance_monitor import PerformanceMonitor, IterationTimings
from ..ipc import SessionChannel
from .batch_optimizer import BatchOptimizer, BatchState, is_cuda_oom
from .precision_manager import PrecisionManager, PrecisionDecision
from . import dataloader_optimizer as dlo
class LPUTrainingIntegrityError(RuntimeError):
"""Raised when LPU cannot GUARANTEE the zero-sample-loss contract.
Training stops with this error instead of continuing in an unverified
state. The message carries the full recovery context (what was tried,
buffer sizes, effective-batch math) so the failure is auditable.
"""
# ----------------------------------------------------------------------------
# helpers shared by engine and manual mode
# ----------------------------------------------------------------------------
def _record_stream(batch, stream) -> None:
"""Mark every CUDA tensor in a (possibly nested) batch as used by `stream`."""
torch = require_torch()
def rec(t):
if isinstance(t, torch.Tensor) and t.is_cuda:
try:
t.record_stream(stream)
except Exception: # noqa: BLE001 - best effort allocator hint
pass
elif isinstance(t, dict):
for v in t.values():