Spaces:
Sleeping
Sleeping
File size: 3,812 Bytes
6cc8ae1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 | """
Training engine: train_one_epoch and validate functions.
Core training loop logic separated from orchestration.
"""
import time
from typing import Optional
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
def train_one_epoch(
model: nn.Module,
dataloader: DataLoader,
criterion: nn.Module,
optimizer: torch.optim.Optimizer,
device: torch.device,
gradient_clip_max_norm: Optional[float] = 1.0,
) -> dict:
"""
Train for one epoch.
Returns dict with: loss, accuracy, num_samples, time_seconds.
"""
model.train()
total_loss = 0.0
correct = 0
total = 0
start_time = time.time()
for batch_idx, (inputs, labels) in enumerate(dataloader):
inputs = inputs.to(device)
labels = labels.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
if gradient_clip_max_norm is not None and gradient_clip_max_norm > 0:
nn.utils.clip_grad_norm_(model.parameters(), gradient_clip_max_norm)
optimizer.step()
total_loss += loss.item() * inputs.size(0)
_, predicted = torch.max(outputs, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
elapsed = time.time() - start_time
return {
'loss': total_loss / total,
'accuracy': correct / total,
'num_samples': total,
'time_seconds': round(elapsed, 2),
}
@torch.no_grad()
def validate(
model: nn.Module,
dataloader: DataLoader,
criterion: nn.Module,
device: torch.device,
) -> dict:
"""
Evaluate model on validation/test set.
Returns dict with: loss, accuracy, num_samples, predictions, labels.
"""
model.eval()
total_loss = 0.0
correct = 0
total = 0
all_preds = []
all_labels = []
all_probs = []
start_time = time.time()
for inputs, labels in dataloader:
inputs = inputs.to(device)
labels = labels.to(device)
outputs = model(inputs)
loss = criterion(outputs, labels)
total_loss += loss.item() * inputs.size(0)
probs = torch.softmax(outputs, dim=1)
_, predicted = torch.max(outputs, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
all_preds.extend(predicted.cpu().tolist())
all_labels.extend(labels.cpu().tolist())
all_probs.extend(probs.cpu().tolist())
elapsed = time.time() - start_time
return {
'loss': total_loss / total,
'accuracy': correct / total,
'num_samples': total,
'time_seconds': round(elapsed, 2),
'predictions': all_preds,
'labels': all_labels,
'probabilities': all_probs,
}
@torch.no_grad()
def measure_inference_latency(
model: nn.Module,
device: torch.device,
img_size: int = 224,
num_runs: int = 50,
warmup_runs: int = 10,
) -> dict:
"""
Measure single-image inference latency on given device.
Returns dict with avg/min/max latency in milliseconds.
"""
model.eval()
dummy_input = torch.randn(1, 3, img_size, img_size).to(device)
# Warmup
for _ in range(warmup_runs):
_ = model(dummy_input)
# Measure
latencies = []
for _ in range(num_runs):
if device.type == 'cuda':
torch.cuda.synchronize()
start = time.time()
_ = model(dummy_input)
if device.type == 'cuda':
torch.cuda.synchronize()
latencies.append((time.time() - start) * 1000) # ms
return {
'avg_ms': round(sum(latencies) / len(latencies), 2),
'min_ms': round(min(latencies), 2),
'max_ms': round(max(latencies), 2),
'device': str(device),
}
|