#!/usr/bin/env python3 """500-epoch FP32 Pipe experiment. Run inside an allocated compute node.""" import copy import csv import json import os from pathlib import Path import random import socket import time import numpy as np import torch import yaml from common import (parser, load_config, paths, save_json, seed_all, get_device, PipeDataset, make_loader, relative_l2, make_model, make_optimizer, evaluate, load_checkpoint, config_digest) def snapshot(model, optimizer, scheduler, cfg, epoch, global_step, best, best_epoch, metrics): return {'model_state_dict': model.state_dict(), 'optimizer_state_dict': optimizer.state_dict(), 'scheduler_state_dict': scheduler.state_dict(), 'config': cfg, 'config_digest': config_digest(cfg), 'epoch': epoch, 'global_step': global_step, 'best_test_relative_l2': best, 'best_epoch': best_epoch, 'test_metrics': metrics, 'selection_metric': 'test_relative_l2', 'torch_rng': torch.get_rng_state(), 'cuda_rng': torch.cuda.get_rng_state_all() if torch.cuda.is_available() else [], 'numpy_rng': np.random.get_state(), 'python_rng': random.getstate()} def atomic_checkpoint(path, payload): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_suffix('.pth.tmp') torch.save(payload, temporary) os.replace(temporary, path) def train(cfg, resume=None): seed_all(cfg['training']['seed']) device = get_device(cfg) output, results = paths(cfg) best_path = output / cfg['output']['best_checkpoint'] last_path = output / cfg['output']['last_checkpoint'] train_data = PipeDataset(cfg, 'train') test_data = PipeDataset(cfg, 'test') train_loader = make_loader(train_data, cfg, shuffle=True) test_loader = make_loader(test_data, cfg) model = make_model(cfg, device) optimizer, scheduler = make_optimizer(model, cfg, len(train_loader)) count = sum(p.numel() for p in model.parameters()) start_epoch, global_step, best, best_epoch = 0, 0, float('inf'), 0 history_file = results / 'history.csv' if resume: checkpoint = load_checkpoint(resume) if checkpoint['config_digest'] != config_digest(cfg): raise ValueError('Resume configuration differs from checkpoint; refusing a protocol change') model.load_state_dict(checkpoint['model_state_dict']) optimizer.load_state_dict(checkpoint['optimizer_state_dict']) scheduler.load_state_dict(checkpoint['scheduler_state_dict']) start_epoch, global_step = checkpoint['epoch'], checkpoint['global_step'] best, best_epoch = checkpoint['best_test_relative_l2'], checkpoint['best_epoch'] torch.set_rng_state(checkpoint['torch_rng']) if torch.cuda.is_available(): torch.cuda.set_rng_state_all(checkpoint['cuda_rng']) metrics = checkpoint['test_metrics'] np.random.set_state(checkpoint['numpy_rng']) random.setstate(checkpoint['python_rng']) # Remove a row written after the last durable epoch checkpoint, if interrupted. if history_file.exists(): with history_file.open() as stream: reader = csv.DictReader(stream) columns = reader.fieldnames rows = [row for row in reader if int(row['epoch']) <= start_epoch] with history_file.open('w', newline='') as stream: writer = csv.DictWriter(stream, fieldnames=columns) writer.writeheader() writer.writerows(rows) elif history_file.exists() or last_path.exists(): raise FileExistsError('Existing training outputs: use --resume or a different --output-dir') (results / 'config_used.yaml').write_text(yaml.safe_dump(cfg, sort_keys=False)) metadata = {'host': socket.gethostname(), 'slurm_job_id': os.environ.get('SLURM_JOB_ID'), 'torch': torch.__version__, 'hip': torch.version.hip, 'cuda': torch.version.cuda, 'device': torch.cuda.get_device_name(device) if device.type == 'cuda' else 'cpu', 'parameters': count, 'precision': 'float32', 'train_samples': len(train_data), 'test_samples': len(test_data), 'points_per_sample': 16641, 'steps_per_epoch': len(train_loader), 'total_epochs': cfg['training']['epochs'], 'config_digest': config_digest(cfg), 'selection_metric': 'test_relative_l2', 'start_epoch': start_epoch} save_json(results / 'run_metadata.json', metadata) print(json.dumps(metadata), flush=True) columns = ['epoch', 'global_step', 'train_relative_l2', 'test_relative_l2', 'test_mse', 'test_rmse', 'test_mae', 'learning_rate', 'epoch_seconds', 'best_test_relative_l2'] began = time.perf_counter() with history_file.open('a', newline='', buffering=1) as stream: writer = csv.DictWriter(stream, fieldnames=columns) if stream.tell() == 0: writer.writeheader() for epoch in range(start_epoch + 1, cfg['training']['epochs'] + 1): tick = time.perf_counter() model.train() accumulated = torch.zeros((), device=device) samples = 0 lr_used = optimizer.param_groups[0]['lr'] for batch_index, (x, target, _) in enumerate(train_loader, 1): x = x.to(device, non_blocking=True) target = target.to(device, non_blocking=True) optimizer.zero_grad(set_to_none=True) predicted = model(x) losses = relative_l2(predicted, target) loss = losses.mean() if not torch.isfinite(loss): raise FloatingPointError(f'Nonfinite loss at epoch {epoch}, batch {batch_index}') loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), cfg['training']['grad_clip'], error_if_nonfinite=True) optimizer.step() lr_used = optimizer.param_groups[0]['lr'] scheduler.step() global_step += 1 accumulated += losses.detach().sum() samples += len(x) if batch_index == 1 or batch_index % cfg['training']['print_every'] == 0: print(f'epoch={epoch:03d}/{cfg["training"]["epochs"]} batch={batch_index:03d}/{len(train_loader)} ' f'loss={loss.item():.8f} train_running_rel_l2={accumulated.item()/samples:.8f} ' f'lr={lr_used:.8g} global_step={global_step}', flush=True) metrics, _, _ = evaluate(model, test_loader, device) train_loss = accumulated.item() / samples improved = metrics['relative_l2'] < best if improved: best, best_epoch = metrics['relative_l2'], epoch payload = snapshot(model, optimizer, scheduler, cfg, epoch, global_step, best, best_epoch, metrics) if improved: atomic_checkpoint(best_path, payload) atomic_checkpoint(last_path, payload) elapsed = time.perf_counter() - tick row = {'epoch': epoch, 'global_step': global_step, 'train_relative_l2': train_loss, 'test_relative_l2': metrics['relative_l2'], 'test_mse': metrics['mse'], 'test_rmse': metrics['rmse'], 'test_mae': metrics['mae'], 'learning_rate': lr_used, 'epoch_seconds': elapsed, 'best_test_relative_l2': best} writer.writerow(row) stream.flush() os.fsync(stream.fileno()) progress = {'status': 'training', **row, 'best_epoch': best_epoch, 'total_epochs': cfg['training']['epochs'], 'slurm_job_id': os.environ.get('SLURM_JOB_ID')} save_json(results / 'progress.json', progress) print(f'EPOCH {epoch:03d} train_loss={train_loss:.8f} test_rel_l2={metrics["relative_l2"]:.8f} ' f'test_rmse={metrics["rmse"]:.8f} test_mae={metrics["mae"]:.8f} best={best:.8f} ' f'best_epoch={best_epoch} seconds={elapsed:.2f} checkpoint_saved={improved}', flush=True) summary = {'status': 'completed', 'completed_epochs': cfg['training']['epochs'], 'global_step': global_step, 'expected_total_steps': len(train_loader) * cfg['training']['epochs'], 'best_epoch': best_epoch, 'best_test_relative_l2': best, 'final_epoch_test_metrics': metrics, 'training_seconds_this_allocation': time.perf_counter()-began, 'best_checkpoint': str(best_path), 'last_checkpoint': str(last_path), 'selection_metric': 'test_relative_l2', 'config_digest': config_digest(cfg)} if global_step != summary['expected_total_steps']: raise AssertionError('Incomplete optimizer steps') save_json(results / 'training_summary.json', summary) save_json(results / 'progress.json', summary) print('TRAINING_COMPLETE ' + json.dumps(summary), flush=True) return summary def main(): cli = parser(__doc__) cli.add_argument('--resume', type=Path, help='Restore complete epoch-boundary training state') cli.add_argument('--smoke', action='store_true', help='Separate 8/4-sample, one-epoch compute-node smoke run') args = cli.parse_args() cfg = load_config(args) if args.smoke: cfg = copy.deepcopy(cfg) cfg['data']['train_count'], cfg['data']['test_count'] = 8, 4 cfg['training']['epochs'] = 1 cfg['training']['print_every'] = 1 cfg['output']['directory'] = str(Path(cfg['output']['directory']) / 'results' / 'smoke' / 'train_loop') train(cfg, args.resume) if __name__ == '__main__': main()