from __future__ import annotations import json from dataclasses import dataclass from pathlib import Path from typing import Dict, List, Tuple import matplotlib.pyplot as plt import torch import torch.nn as nn from tqdm import tqdm from .data import make_mnist_loaders @dataclass class History: train_loss: List[float] train_acc: List[float] val_loss: List[float] val_acc: List[float] def _set_seed(seed: int) -> None: torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) @torch.no_grad() def evaluate(model: torch.nn.Module, loader, device: torch.device) -> Tuple[float, float]: model.eval() criterion = nn.CrossEntropyLoss() total_loss = 0.0 correct = 0 total = 0 for x, y in loader: x = x.to(device) y = y.to(device) logits = model(x) loss = criterion(logits, y) total_loss += float(loss.item()) * x.size(0) pred = logits.argmax(dim=1) correct += int((pred == y).sum().item()) total += int(x.size(0)) return total_loss / max(total, 1), correct / max(total, 1) def train_one_epoch( model: torch.nn.Module, loader, optimizer: torch.optim.Optimizer, device: torch.device, ) -> Tuple[float, float]: model.train() criterion = nn.CrossEntropyLoss() total_loss = 0.0 correct = 0 total = 0 for x, y in tqdm(loader, desc="train", leave=False): x = x.to(device) y = y.to(device) optimizer.zero_grad(set_to_none=True) logits = model(x) loss = criterion(logits, y) loss.backward() optimizer.step() total_loss += float(loss.item()) * x.size(0) pred = logits.argmax(dim=1) correct += int((pred == y).sum().item()) total += int(x.size(0)) return total_loss / max(total, 1), correct / max(total, 1) def _plot_history(history: History, out_path: Path) -> None: epochs = list(range(1, len(history.train_loss) + 1)) fig, axes = plt.subplots(1, 2, figsize=(10, 4)) axes[0].plot(epochs, history.train_loss, label="train") axes[0].plot(epochs, history.val_loss, label="val") axes[0].set_title("Loss") axes[0].set_xlabel("epoch") axes[0].grid(True) axes[0].legend() axes[1].plot(epochs, history.train_acc, label="train") axes[1].plot(epochs, history.val_acc, label="val") axes[1].set_title("Accuracy") axes[1].set_xlabel("epoch") axes[1].set_ylim(0.9, 1.0) axes[1].grid(True) axes[1].legend() fig.tight_layout() out_path.parent.mkdir(parents=True, exist_ok=True) fig.savefig(out_path, dpi=160) plt.close(fig) def train_and_evaluate( model: torch.nn.Module, device: torch.device, data_root: Path, artifacts_dir: Path, epochs: int, batch_size: int, lr: float, weight_decay: float, seed: int, num_workers: int, use_augmentation: bool, ) -> Dict[str, float]: _set_seed(seed) artifacts_dir.mkdir(parents=True, exist_ok=True) loaders = make_mnist_loaders( data_root=data_root, batch_size=batch_size, seed=seed, num_workers=num_workers, use_augmentation=use_augmentation, normalize=True, ) model = model.to(device) optimizer = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay) history = History(train_loss=[], train_acc=[], val_loss=[], val_acc=[]) best_val_acc = -1.0 best_path = artifacts_dir / "cnn_mnist.pt" for epoch in range(1, epochs + 1): tr_loss, tr_acc = train_one_epoch(model, loaders.train, optimizer, device) va_loss, va_acc = evaluate(model, loaders.val, device) history.train_loss.append(tr_loss) history.train_acc.append(tr_acc) history.val_loss.append(va_loss) history.val_acc.append(va_acc) print( f"epoch={epoch}/{epochs} train_loss={tr_loss:.4f} train_acc={tr_acc:.4f} " f"val_loss={va_loss:.4f} val_acc={va_acc:.4f}" ) if va_acc > best_val_acc: best_val_acc = va_acc torch.save({"state_dict": model.state_dict()}, best_path) _plot_history(history, artifacts_dir / "curves.png") test_loss, test_acc = evaluate(model, loaders.test, device) metrics = { "best_val_acc": float(best_val_acc), "test_acc": float(test_acc), "test_loss": float(test_loss), "epochs": int(epochs), "batch_size": int(batch_size), "lr": float(lr), "weight_decay": float(weight_decay), "seed": int(seed), "device": str(device), "use_augmentation": bool(use_augmentation), } (artifacts_dir / "metrics.json").write_text(json.dumps(metrics, indent=2), encoding="utf-8") print(f"test_acc={test_acc:.4f} saved={best_path}") return metrics