Source code for chronoprop.train

"""Training and evaluation, as in the paper.

Each epoch trains on shuffled batches, then evaluates the validation set and the
test set. The paper reports the test accuracy at the epoch of best validation
accuracy (:func:`test_at_best_val`); it never selects anything on the test set.

The loop keeps the paper's order of operations, so a run with the same seed draws
the same random numbers (weight initialisation, shuffling). Two additions are
off by default and do not change a run: ``resume_path`` saves the full training
state every epoch so an interrupted run continues where it stopped, and
``checkpoint_path`` keeps the weights of the best-validation epoch.
"""
import os
import random
import time
from pathlib import Path
from typing import Optional

import numpy as np
import torch
from torch import nn
from torch.utils.data import DataLoader

from .data import PadToWindow


[docs] def evaluate(model: nn.Module, loader: DataLoader, device: torch.device, loss_fn: Optional[nn.Module] = None) -> tuple: """Mean loss and accuracy (%) of ``model`` over ``loader``, without gradients.""" if loss_fn is None: loss_fn = nn.CrossEntropyLoss() model.eval() n_total, loss_sum, correct, n_batches = 0, 0.0, 0, 0 with torch.no_grad(): for X, y in loader: X, y = X.to(device), y.to(device) pred = model(X) loss_sum += loss_fn(pred, y).item() correct += (pred.argmax(dim=1) == y).sum().item() n_total += y.shape[0] n_batches += 1 return loss_sum / max(n_batches, 1), (correct / max(n_total, 1)) * 100
[docs] def test_at_best_val(results: dict) -> tuple: """``(test accuracy, epoch index)`` at the epoch of best validation accuracy.""" va = results['val_acc'] best = max(range(len(va)), key=lambda i: va[i]) return results['test_acc'][best], best
def _loader(data, batch_size, shuffle, window_steps, num_workers, pin_memory): return DataLoader( data, batch_size=batch_size, shuffle=shuffle, pin_memory=pin_memory, num_workers=num_workers, collate_fn=PadToWindow(window_steps=window_steps), multiprocessing_context='fork' if num_workers > 0 else None) def _rng_state(device): state = {'torch': torch.get_rng_state(), 'numpy': np.random.get_state(), 'python': random.getstate()} if torch.device(device).type == 'cuda': state['cuda'] = torch.cuda.get_rng_state(device) return state def _set_rng_state(state, device): torch.set_rng_state(state['torch']) np.random.set_state(state['numpy']) random.setstate(state['python']) if 'cuda' in state and torch.device(device).type == 'cuda': torch.cuda.set_rng_state(state['cuda'], device) def lr_scheduler(optimizer, lr_schedule: str = 'constant', epochs: int = 1, warmup_epochs: int = 10, lr_min: float = 1e-6): """The learning-rate schedule, stepped once per epoch; ``None`` for ``'constant'``. ``'cosine_warmup'`` (Figs 5 and 6) rises linearly from 1/1000 of the learning rate to the full rate over ``warmup_epochs``, then follows a cosine down to ``lr_min`` at the last epoch. """ if lr_schedule == 'constant': return None if lr_schedule != 'cosine_warmup': raise ValueError(f"Unknown lr_schedule={lr_schedule!r}; use 'constant' or 'cosine_warmup'") from torch.optim.lr_scheduler import CosineAnnealingLR, LinearLR, SequentialLR warmup = LinearLR(optimizer, start_factor=1e-3, end_factor=1.0, total_iters=max(1, warmup_epochs)) cosine = CosineAnnealingLR(optimizer, T_max=max(1, epochs - max(1, warmup_epochs)), eta_min=lr_min) return SequentialLR(optimizer, schedulers=[warmup, cosine], milestones=[max(1, warmup_epochs)])
[docs] def train(model: nn.Module, train_data, test_data, *, batch_size: int, epochs: int, lr: float, device, window_steps: int = 1, val_data=None, recurrent: bool = False, optimizer_name: str = 'Adam', grad_clip: Optional[float] = None, weight_decay: float = 0.0, lr_schedule: str = 'constant', warmup_epochs: int = 10, lr_min: float = 1e-6, num_workers: int = 0, pin_memory: bool = False, checkpoint_path: Optional[str] = None, resume_path: Optional[str] = None, print_progress: bool = True, defects=None, stop_after_epoch: Optional[int] = None) -> dict: """Train ``model`` and return per-epoch losses and accuracies. ``window_steps`` pads every batch to whole time windows (ChronoProp); use 1 for BPTT. ``recurrent=True`` re-applies the recurrent mask after each optimizer step. ``stop_after_epoch`` ends training early while keeping the schedule of ``epochs`` (a short look at the first epochs of a long run). ``defects`` (optional, Fig 6) is a :class:`chronoprop.defects.Defects` describing the hardware the network is trained and evaluated on. Returns a dict with lists ``train_loss``, ``train_acc``, ``val_loss``, ``val_acc`` (if ``val_data``), ``test_loss``, ``test_acc`` and the wall-clock seconds per epoch ``epoch_seconds``. """ device = torch.device(device) has_validation = val_data is not None train_loader = _loader(train_data, batch_size, True, window_steps, num_workers, pin_memory) val_loader = (_loader(val_data, batch_size, False, window_steps, num_workers, pin_memory) if has_validation else None) test_loader = _loader(test_data, batch_size, False, window_steps, num_workers, pin_memory) loss_fn = nn.CrossEntropyLoss() optimizer_params = {'params': model.parameters(), 'lr': lr} if optimizer_name == 'SGD': optimizer_params.update({'momentum': 0.9, 'weight_decay': 0.0}) if weight_decay > 0 and optimizer_name == 'Adam': optimizer_name = 'AdamW' optimizer_params['weight_decay'] = weight_decay optimizer = getattr(torch.optim, optimizer_name)(**optimizer_params) scheduler = lr_scheduler(optimizer, lr_schedule, epochs, warmup_epochs, lr_min) if device.type == 'cuda': torch.cuda.reset_peak_memory_stats(device) results = {'train_loss': [], 'train_acc': [], 'test_loss': [], 'test_acc': [], 'epoch_seconds': []} if has_validation: results['val_loss'], results['val_acc'] = [], [] best_val = -1.0 start_epoch = 0 if resume_path is not None and Path(resume_path).exists(): state = torch.load(resume_path, map_location=device, weights_only=False) model.load_state_dict(state['model']) optimizer.load_state_dict(state['optimizer']) if scheduler is not None: scheduler.load_state_dict(state['scheduler']) results, best_val, start_epoch = state['results'], state['best_val'], state['epoch'] + 1 _set_rng_state(state['rng'], device) if print_progress: print(f'Resumed from {resume_path} at epoch {start_epoch + 1}') def run_eval(loader): if defects is None: return evaluate(model, loader, device, loss_fn) with defects.evaluation(model, device): return evaluate(model, loader, device, loss_fn) for epoch in range(start_epoch, epochs): t0 = time.time() model.train() if hasattr(train_data, 'set_epoch'): # addSHD draws new pairs every epoch train_data.set_epoch(epoch) train_loss, train_correct, train_total = 0.0, 0, 0 for X, y in train_loader: X, y = X.to(device), y.to(device) with (defects.training(model) if defects is not None else _null()): y_pred = model(X) loss = loss_fn(y_pred, y) train_loss += loss.item() with torch.no_grad(): train_correct += (y_pred.argmax(-1) == y).sum().item() train_total += y.size(0) optimizer.zero_grad() loss.backward() if grad_clip is not None: torch.nn.utils.clip_grad_norm_(model.parameters(), grad_clip) optimizer.step() if recurrent: model.apply_recurrent_mask() results['train_loss'].append(train_loss / len(train_loader)) results['train_acc'].append(100.0 * train_correct / max(train_total, 1)) if scheduler is not None: scheduler.step() if has_validation: val_loss, val_acc = run_eval(val_loader) results['val_loss'].append(val_loss) results['val_acc'].append(val_acc) if checkpoint_path is not None and val_acc > best_val: best_val = val_acc Path(checkpoint_path).parent.mkdir(parents=True, exist_ok=True) tmp = f'{checkpoint_path}.tmp' torch.save({'state_dict': model.state_dict(), 'best_val_epoch': epoch, 'best_val_acc': best_val}, tmp) os.replace(tmp, checkpoint_path) test_loss, test_acc = run_eval(test_loader) results['test_loss'].append(test_loss) results['test_acc'].append(test_acc) results['epoch_seconds'].append(time.time() - t0) if print_progress: msg = f"Epoch {epoch + 1}/{epochs} | train loss {results['train_loss'][-1]:.4f}" if has_validation: msg += f" | val acc {results['val_acc'][-1]:.2f}%" msg += f" | test acc {test_acc:.2f}% | {results['epoch_seconds'][-1]:.1f} s" print(msg, flush=True) if resume_path is not None: Path(resume_path).parent.mkdir(parents=True, exist_ok=True) tmp = f'{resume_path}.tmp' torch.save({'model': model.state_dict(), 'optimizer': optimizer.state_dict(), 'scheduler': scheduler.state_dict() if scheduler is not None else None, 'results': results, 'best_val': best_val, 'epoch': epoch, 'rng': _rng_state(device)}, tmp) os.replace(tmp, resume_path) if stop_after_epoch is not None and epoch + 1 >= stop_after_epoch: break if device.type == 'cuda': results['peak_memory_mb'] = torch.cuda.max_memory_allocated(device) / 2 ** 20 return results
class _null: def __enter__(self): return self def __exit__(self, *exc): return False