Image classification with CNNs in PyTorch on the local GPU
Train a PyTorch CNN on CIFAR-10 with separate data splits, interpret top-k and confusion matrices, and measure the GPU input pipeline, training schedules and throughput.
After this lesson you can
- Compute top-k accuracy and per-class metrics with explicit tie handling.
- Build a reproducible CNN training and data pipeline.
- Explain BatchNorm evaluation behavior and optimizer parameter groups.
- Compare learning-rate schedules under matched conditions.
- Measure GPU throughput and identify input or compute bottlenecks.
Before you start
- 16Convolutional block patternMultichannel convolutional layerDigital image representationGlobal average pooling
- 00Map-style and iterable datasetsWorker processes, pinned memory and prefetchInput pipeline bottleneck diagnosisAutomatic mixed precision in PyTorchTraining memory budgettorch.profiler tracesBottleneck classification
- 15Batch normalizationBatch norm running statisticsLearning rate warmup
- 06Weight decay versus L2 regularizationNesterov accelerated gradient
From digits to natural images
The previous LeNet let you trace each derivative in NumPy. Now the problem changes: small RGB images of natural objects and a CNN trained with PyTorch. Success involves two distinct questions: what does the model learn on data unseen during its updates, and which part of the system limits example-processing rate? More images per second does not demonstrate better generalization, and high accuracy does not show that the GPU is well fed.
The task and its metrics
An image classification task assigns a label to each image . A network produces logits . Top-1 accuracy counts when the highest-logit index matches the label; top- counts whether the label appears among the largest. Softmax preserves the order of finite logits, so it is unnecessary for these metrics. Set a tie-breaking policy for equal logits: top- can depend on it.
For true labels and predictions , define as the number of examples with that pair. The diagonal sum divided by the total is overall accuracy; is accuracy for class if that row is nonempty. For an absent class the ratio is undefined: do not silently turn it into zero. Mean accuracy can hide failure concentrated in one class or image type.
Their relationship follows directly: if and , then, summing only present classes, . Overall accuracy weights each class by frequency; the unweighted mean of gives equal weight to each present class. They agree when frequencies are equal, but generally answer different questions. High top-5 also does not say the first prediction is correct: only that the true label is among five candidates.
The figure uses 200 test images from the short trial, 20 per class, and saved logits from each model. It is an exploratory probe: after inspecting examples and comparing configurations, do not treat those images as a new blind test. The matrix always counts top-1; selector changes membership among the top . Select a confusion and see whether examples share a visual difficulty before proposing a cause.
CIFAR-10 contains 60,000 32×32 RGB images, ten classes, 50,000 official training and 10,000 test images. Official test has 1000 examples per class. We reserve validation from official training and calculate normalization statistics only on the training portion. Do not confuse this task with the previous lesson’s digits: their accuracies measure different problems.
In Ho-Phuoc’s study, table 1 reports human accuracy of 93.91 ± 1.52%. A total of 60 students participated, each classified 1000 images and each image received six annotations, without a time limit. This measures that protocol, not a universal limit or ImageNet human top-5 error.
The data path to the GPU
The input pipeline reads examples, applies transforms, forms batches and delivers them to the device. Per-channel normalization of as requires setting mean and deviation from training and reusing them for validation and test. Mixing test data into their calculation already lets evaluation information influence the procedure. Keep split protocols separate and transform labels alongside their images.
A small dataset can remain as 8-bit integers on GPU and be converted and normalized per batch. This reduces repeated transfers but does not guarantee room for model, gradients, optimizer state and activations: make a memory budget. If data do not fit, the DataLoader and its workers, pinned memory and asynchronous transfers offer another path that must be measured. An excessively large batch can also exhaust memory or change optimization.
As a raw-storage reference, the 50,000 official training images occupy bytes in uint8; float32 needs four times that amount. The following count excludes labels and all training memory. CUDA allocator reservation can exceed memory occupied by live tensors; neither measure alone describes all memory used by other processes.
raw=50000*3*32*32
print('Bytes de imágenes uint8:',raw,'; float32:',4*raw)The figure is a scheduling model, not an RTX 4060 trace. It helps distinguish a GPU waiting for data from a busy GPU. In a real system, increasing workers can help or introduce contention; do not assume more workers, a bigger batch or moving augmentations to GPU always improves performance. An input bottleneck is confirmed by measurement separating loading, transfer and computation.
A reproducible recipe
A CNN training recipe combines architecture, initialization, optimizer, rates, regularization and data. We use a VGG-like network with convolution, BatchNorm, ReLU and reduction blocks, followed by global averaging and a classifier. Averaging removes explicit position from the final map; this can suit global classification while losing information needed to localize objects.
With track_running_stats=True, the usual configuration, BatchNorm uses batch statistics during training and updates running statistics; in evaluation, model.eval() makes it use stored statistics. With track_running_stats=False it also uses batch statistics during evaluation. Mode switching differs from torch.no_grad() or torch.inference_mode(), which control gradient recording. Forgetting evaluation mode can make predictions depend on batch size and composition and update running statistics using evaluation itself.
We use SGD with momentum and Nesterov, separating decayed parameters from biases and normalization parameters. The group list must cover each trainable parameter exactly once, even when parameters are shared. Distinguish weight decay and L2 penalty: equivalence depends on the particular update and does not automatically transfer to every optimizer.
With PyTorch’s SGD convention, momentum , zero dampening and zero initial velocity, let be the batch gradient with decay added only to the group receiving it. For Nesterov, and the update uses . State that convention when comparing implementations: calling two loops “Nesterov” does not guarantee the same initial state or operation order.
The lab also applies label smoothing: instead of target one for the true class and zero elsewhere, it mixes the point label with a uniform distribution over classes. This is a training choice, not a transformation of test labels. To measure validation loss, code uses ordinary unsmoothed cross-entropy and records that choice alongside accuracy. Cropping and flipping are used only in training; their usefulness is a hypothesis about label-preserving transformations, not a theorem for every image dataset.
A schedule controls the rate per step. Warmup gradually increases the initial rate; cosine or cyclic schedules can also reduce it afterward. In PyTorch, OneCycleLR updates after each batch and by default also changes momentum when enabled, as its documentation states. When comparing schedules, fix architecture, data, initialization, budget and momentum options; otherwise a difference cannot be attributed solely to rate shape.
The figure compares short 100-step runs, with 1000 training and 200 validation examples distributed by class. Split, augmentation sequence and initialization are paired by seed; the cycle uses cycle_momentum=False to keep momentum fixed across schedules. First choose a pattern and observe its rate, then compare validation curves with others and another seed. There are eleven recorded points per run, not continuous curves measured every step or a guarantee that the same pattern wins in long training.
Measure before optimizing
CNN GPU performance depends on tensor size and shape, precision, memory format and chosen implementation. channels_last changes physical strides of four-dimensional tensors, not logical NCHW shape. cudnn.benchmark can test algorithms for repeated shapes; if shapes change, search cost and memory can alter comparison. Autocast chooses types by operation: it is not equivalent to blindly converting all tensors to half precision. With float16, loss scaling can protect small gradients; consult the AMP flow and check finiteness.
CUDA executes many operations asynchronously. For reliable wall time, warm up each configuration and synchronize before and after the measured region. Count examples actually processed and divide by elapsed time; state whether transfer, augmentation, forward, backward and update are included. One measurement on a shared GPU can vary greatly. Compare distributions or trends under equal conditions; do not turn a ratio observed here into a speed promise for another machine.
The sweep records AMP scale before and after each interval. A drop suggests the scaler detected a nonfinite gradient and skipped an update; a final value that is not lower does not prove it never dropped during the interval, since it can grow afterward. If seeking training equivalence between configurations, also record effective steps and check losses and gradients. Images per second alone does not establish that equivalence.
With torch.profiler, inspect CPU and CUDA operations, memory and the full interval, not only a kernel table. A row with more self GPU time does not necessarily include all its CPU or child-kernel costs. For bottleneck classification, test hypotheses: if loading synthetic batches removes gaps, study input; if the GPU remains busy and rate does not change, study compute and memory. The profiler adds overhead and its trace is a diagnostic, not the final benchmark.
Local labs
The first cell trains four schedules with three seeds and evaluates a separate probe. With ORYON_VERIFY_SHORT=1 it uses 100 steps and stratified subsets; the reader’s run uses a larger budget. Data are read in batches from the Hugging Face cache and selected images remain as uint8 on GPU. It saves checkpoints and results in the directory chosen by ORYON_CIFAR_OUTPUT; this lesson’s figures use output from the short run and do not depend on that directory.
"""CNN pequeña en CIFAR-10: comparación reproducible de cuatro schedules.
Requisitos: torch, numpy, pillow, pyarrow, huggingface_hub. El conjunto se lee
de la caché compartida de Hugging Face, por lotes. ORYON_VERIFY_SHORT=1 usa
un presupuesto corto para comprobar el bucle; el modo normal entrega al lector
un entrenamiento mayor. ORYON_CIFAR_OUTPUT elige el directorio de salida.
"""
import base64
import copy
import io
import json
import os
from pathlib import Path
os.environ.setdefault('CUBLAS_WORKSPACE_CONFIG', ':4096:8')
import numpy as np
import pyarrow.parquet as pq
from huggingface_hub import hf_hub_download
from PIL import Image
import torch
from torch import nn
from torch.nn import functional as F
torch.set_num_threads(1)
torch.use_deterministic_algorithms(True)
short = os.environ.get('ORYON_VERIFY_SHORT') == '1'
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
if device.type != 'cuda':
raise RuntimeError('Esta receta requiere CUDA; para CPU reduce el presupuesto explícitamente.')
revision = '0b27149'
classes = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog',
'frog', 'horse', 'ship', 'truck']
seeds = [16071, 16072, 16073]
schedules = ['constante', 'escalones', 'coseno', 'un_ciclo']
batch_size = 64 if short else 128
steps = 100 if short else 18000
train_per_class = 100 if short else 4500
valid_per_class = 20 if short else 500
test_per_class = 20 if short else 1000
out_dir = Path(os.environ.get('ORYON_CIFAR_OUTPUT', 'm16-l07-resultados'))
out_dir.mkdir(parents=True, exist_ok=True)
def choose_indices(split, n_each, seed):
"""Selecciona por clase antes de leer imágenes; orden fijado por semilla."""
path = hf_hub_download(repo_id='uoft-cs/cifar10', repo_type='dataset',
filename=f'plain_text/{split}-00000-of-00001.parquet', revision=revision)
parquet = pq.ParquetFile(path)
label_parts = [part.column(0).to_numpy() for part in parquet.iter_batches(batch_size=1024, columns=['label'])]
labels = np.concatenate(label_parts).astype(np.int64)
generator = np.random.default_rng(seed)
by_class = [generator.permutation(np.flatnonzero(labels == k)) for k in range(10)]
if any(len(group) < n_each for group in by_class):
raise ValueError('No hay suficientes imágenes para la partición')
return path, labels, by_class
def read_selected(path, labels, indices):
"""Lee solo las imágenes elegidas; nunca construye una tabla del parquet entero."""
indices = np.asarray(indices, dtype=np.int64)
position = {int(source): i for i, source in enumerate(indices)}
images = np.empty((len(indices), 3, 32, 32), dtype=np.uint8)
seen = np.zeros(len(indices), dtype=bool)
offset = 0
for batch in pq.ParquetFile(path).iter_batches(batch_size=256, columns=['img']):
for local in range(batch.num_rows):
index = position.get(offset + local)
if index is None:
continue
row = batch.column(0)[local].as_py()
with Image.open(io.BytesIO(row['bytes'])) as image:
array = np.asarray(image.convert('RGB'), dtype=np.uint8)
if array.shape != (32, 32, 3):
raise ValueError('Imagen CIFAR con forma inesperada')
images[index] = array.transpose(2, 0, 1)
seen[index] = True
offset += batch.num_rows
if not seen.all():
raise RuntimeError('Faltan imágenes seleccionadas')
return torch.from_numpy(images).to(device), torch.from_numpy(labels[indices].copy()).to(device)
train_path, train_labels, groups = choose_indices('train', train_per_class + valid_per_class, 16070)
train_ids = np.concatenate([g[:train_per_class] for g in groups])
valid_ids = np.concatenate([g[train_per_class:train_per_class+valid_per_class] for g in groups])
test_path, test_labels, test_groups = choose_indices('test', test_per_class, 16074)
test_ids = np.concatenate([g[:test_per_class] for g in test_groups])
assert len(set(train_ids) & set(valid_ids)) == 0
train_x, train_y = read_selected(train_path, train_labels, train_ids)
valid_x, valid_y = read_selected(train_path, train_labels, valid_ids)
test_x, test_y = read_selected(test_path, test_labels, test_ids)
# Estadísticas solo de entrenamiento, sin aumentar; acumulación por tandas.
totals = torch.zeros(3, device=device, dtype=torch.float64)
squares = torch.zeros_like(totals)
pixels = 0
for start in range(0, len(train_x), 256):
batch = train_x[start:start+256].to(torch.float64) / 255
totals += batch.sum(dim=(0, 2, 3))
squares += (batch * batch).sum(dim=(0, 2, 3))
pixels += batch.shape[0] * 32 * 32
mean = totals / pixels
std = (squares / pixels - mean**2).clamp_min(0).sqrt()
assert torch.isfinite(std).all() and bool((std > 0).all())
normal_mean = mean.float()[None, :, None, None]
normal_std = std.float()[None, :, None, None]
def preprocess(batch, generator=None):
batch = batch.float() / 255
if generator is not None:
# Recorte 32×32 de una imagen con padding reflectante de 4 y flip.
padded = F.pad(batch, (4, 4, 4, 4), mode='reflect')
n = len(batch)
dy = torch.randint(0, 9, (n,), generator=generator, device=device)
dx = torch.randint(0, 9, (n,), generator=generator, device=device)
row = dy[:, None] + torch.arange(32, device=device)[None, :]
col = dx[:, None] + torch.arange(32, device=device)[None, :]
batch = padded[torch.arange(n, device=device)[:, None, None, None],
torch.arange(3, device=device)[None, :, None, None],
row[:, None, :, None], col[:, None, None, :]]
flip = torch.rand(n, generator=generator, device=device) < .5
batch = torch.where(flip[:, None, None, None], batch.flip(-1), batch)
return ((batch - normal_mean) / normal_std).contiguous(memory_format=torch.channels_last)
class SmallVGG(nn.Module):
def __init__(self):
super().__init__()
def block(cin, cout):
return nn.Sequential(nn.Conv2d(cin, cout, 3, padding=1, bias=False),
nn.BatchNorm2d(cout), nn.ReLU(),
nn.Conv2d(cout, cout, 3, padding=1, bias=False),
nn.BatchNorm2d(cout), nn.ReLU(), nn.MaxPool2d(2))
self.features = nn.Sequential(block(3, 32), block(32, 64), block(64, 128))
self.classifier = nn.Linear(128, 10)
def forward(self, x):
return self.classifier(self.features(x).mean(dim=(2, 3)))
def parameter_groups(model, weight_decay):
no_decay, decay = [], []
norm_ids = {id(p) for m in model.modules() if isinstance(m, nn.modules.batchnorm._BatchNorm)
for p in m.parameters(recurse=False)}
for name, parameter in model.named_parameters():
if parameter.requires_grad:
(no_decay if name.endswith('.bias') or id(parameter) in norm_ids else decay).append(parameter)
assert not ({id(p) for p in decay} & {id(p) for p in no_decay})
assert len(decay) + len(no_decay) == sum(p.requires_grad for p in model.parameters())
return [{'params': decay, 'weight_decay': weight_decay},
{'params': no_decay, 'weight_decay': 0.0}]
def scheduler_for(optimizer, name):
if name == 'constante':
return torch.optim.lr_scheduler.ConstantLR(optimizer, factor=1., total_iters=steps)
if name == 'escalones':
return torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[steps//2, 3*steps//4], gamma=.2)
if name == 'coseno':
return torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=steps, eta_min=.0001)
return torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr=.05, total_steps=steps,
pct_start=.3, div_factor=5., final_div_factor=100., cycle_momentum=False)
def evaluate(model, x, labels):
model.eval()
pieces = []
with torch.inference_mode():
for start in range(0, len(x), 128):
z = model(preprocess(x[start:start+128]))
pieces.append(z.float().cpu())
logits = torch.cat(pieces)
y = labels.cpu()
order = logits.argsort(dim=1, descending=True)
correct = order.eq(y[:, None])
confusion = torch.bincount(y * 10 + order[:, 0], minlength=100).reshape(10, 10)
counts = confusion.sum(1)
per_class = torch.where(counts > 0, confusion.diag() / counts, float('nan'))
return {'loss': float(F.cross_entropy(logits, y)), 'top1': float(correct[:, :1].any(1).float().mean()),
'top5': float(correct[:, :5].any(1).float().mean()), 'confusion': confusion.tolist(),
'per_class': per_class.tolist(), 'logits': logits.tolist()}
all_runs = []
torch.backends.cudnn.benchmark = False
for seed in seeds:
for schedule in schedules:
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
generator = torch.Generator(device=device).manual_seed(seed + 1000)
model = SmallVGG().to(device=device, memory_format=torch.channels_last)
opt = torch.optim.SGD(parameter_groups(model, .0005), lr=.05, momentum=.9, nesterov=True)
scheduler = scheduler_for(opt, schedule)
history = []
best_accuracy, best_state, best_step = -1., None, 0
for step in range(steps):
model.train()
idx = torch.randint(0, len(train_x), (batch_size,), generator=generator, device=device)
x = preprocess(train_x[idx], generator)
y = train_y[idx]
opt.zero_grad(set_to_none=True)
with torch.autocast(device_type='cuda', dtype=torch.bfloat16):
logits = model(x)
loss = F.cross_entropy(logits, y, label_smoothing=.05)
if not bool(torch.isfinite(loss)):
raise FloatingPointError('Pérdida no finita')
loss.backward()
opt.step()
used_lr = float(opt.param_groups[0]['lr'])
scheduler.step()
if (step + 1) % max(1, steps // 10) == 0 or step == 0:
val = evaluate(model, valid_x, valid_y)
if val['top1'] > best_accuracy:
best_accuracy, best_step = val['top1'], step + 1
best_state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
history.append({'step': step+1, 'lr': used_lr, 'train_loss_batch': float(loss.detach()),
'valid_loss': val['loss'], 'valid_top1': val['top1'], 'valid_top5': val['top5']})
model.load_state_dict(best_state)
final = evaluate(model, test_x, test_y)
checkpoint = out_dir / f'{schedule}-{seed}.pt'
torch.save({'model': best_state, 'seed': seed, 'schedule': schedule, 'best_step': best_step,
'mean': mean.cpu(), 'std': std.cpu()}, checkpoint)
all_runs.append({'seed': seed, 'schedule': schedule, 'best_step': best_step,
'history': history, 'test': final, 'checkpoint': checkpoint.name})
print('semilla', seed, schedule, 'mejor paso', best_step,
'validación', best_accuracy, 'test top1', final['top1'], flush=True)
del opt, scheduler, model, best_state, final
torch.cuda.empty_cache()
# Las imágenes son de test, no ejemplos inventados. El índice en la lista
# enlaza cada imagen con su etiqueta y sus logits para todas las ejecuciones.
examples = []
for i in range(len(test_ids)):
data = test_x[i].cpu().permute(1, 2, 0).numpy()
buffer = io.BytesIO()
Image.fromarray(data).save(buffer, format='PNG')
examples.append({'source_index': int(test_ids[i]), 'target': int(test_labels[test_ids[i]]),
'image_base64': base64.b64encode(buffer.getvalue()).decode('ascii')})
result = {'dataset': 'uoft-cs/cifar10', 'dataset_revision': revision, 'short': short,
'seeds': seeds, 'schedules': schedules, 'steps': steps, 'batch_size': batch_size,
'train_indices': train_ids.tolist(), 'valid_indices': valid_ids.tolist(),
'test_indices': test_ids.tolist(), 'classes': classes,
'channel_mean_train': mean.cpu().tolist(), 'channel_std_train': std.cpu().tolist(),
'augmentation': 'padding reflect 4, recorte uniforme 32, flip horizontal 0.5',
'optimizer': 'SGD momentum 0.9 Nesterov, weight decay 0.0005 excepto BN y sesgos',
'amp': 'bfloat16', 'device': str(device), 'torch_version': torch.__version__,
'selection': 'primer máximo top1 en validación dentro de cada ejecución',
'runs': all_runs, 'examples': examples}
output = out_dir / 'resultados.json'
output.write_text(json.dumps(result, ensure_ascii=False, allow_nan=False), encoding='utf-8')
print('Resultados:', output, flush=True)
del train_x, valid_x, test_x
torch.cuda.empty_cache()npm run lab and open the connection link.The second cell measures full training steps on synthetic inputs already resident on GPU, with the same architecture. It compares memory and rate across batch, format, autocast and algorithm-selection configurations; the trace corresponds to one step of that trial, not the real CIFAR pipeline. Short mode uses small batches and few repetitions. ORYON_BENCH_COMPILE=1 adds an optional torch.compile test: it may require additional memory and compilation and was not included in this lesson’s short check. Throughput varies with shared load; measure again in your own environment.
"""Barrido corto de throughput y traza de una CNN tipo VGG sobre datos sintéticos.
Se miden pasos completos de entrenamiento con el lote ya residente en GPU;
no mide carga ni augmentación ni representa un entrenamiento CIFAR real.
ORYON_VERIFY_SHORT=1 reduce repeticiones. ORYON_BENCH_COMPILE=1 prueba
torch.compile, cuya primera compilación puede consumir bastante RAM y tiempo.
ORYON_THROUGHPUT_OUTPUT fija el JSON de salida. ORYON_PROFILE_TRACE fija la
ruta opcional de la traza Chrome del paso perfilado.
"""
import itertools
import json
import os
import platform
import statistics
import time
from pathlib import Path
os.environ.setdefault('CUBLAS_WORKSPACE_CONFIG', ':4096:8')
import torch
from torch import nn
torch.set_num_threads(1)
short = os.environ.get('ORYON_VERIFY_SHORT') == '1'
do_compile = os.environ.get('ORYON_BENCH_COMPILE') == '1'
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
if device.type != 'cuda':
raise RuntimeError('Este barrido de throughput y el profiler requieren CUDA')
class SmallVGG(nn.Module):
def __init__(self):
super().__init__()
def block(cin, cout):
return nn.Sequential(nn.Conv2d(cin, cout, 3, padding=1, bias=False),
nn.BatchNorm2d(cout), nn.ReLU(),
nn.Conv2d(cout, cout, 3, padding=1, bias=False),
nn.BatchNorm2d(cout), nn.ReLU(), nn.MaxPool2d(2))
self.features = nn.Sequential(block(3, 32), block(32, 64), block(64, 128))
self.classifier = nn.Linear(128, 10)
def forward(self, x):
return self.classifier(self.features(x).mean(dim=(2, 3)))
def group_parameters(model):
"""No regularizar sesgos ni parámetros de BatchNorm de este modelo."""
norms = {id(p) for layer in model.modules() if isinstance(layer, nn.modules.batchnorm._BatchNorm)
for p in layer.parameters(recurse=False)}
decay, clean = [], []
for name, p in model.named_parameters():
if not p.requires_grad:
continue
(clean if name.endswith('.bias') or id(p) in norms else decay).append(p)
assert len({id(p) for p in decay + clean}) == len(decay) + len(clean)
return [{'params': decay, 'weight_decay': 5e-4}, {'params': clean, 'weight_decay': 0.}]
def make_case(batch, channels_last, amp, cudnn_benchmark, compiled=False):
torch.manual_seed(16070)
torch.backends.cudnn.benchmark = cudnn_benchmark
model = SmallVGG().to(device)
if channels_last:
model = model.to(memory_format=torch.channels_last)
torch.manual_seed(16071)
x = torch.randn(batch, 3, 32, 32, device=device)
y = torch.arange(batch, device=device) % 10
if channels_last:
x = x.contiguous(memory_format=torch.channels_last)
optimizer = torch.optim.SGD(group_parameters(model), lr=.05, momentum=.9, nesterov=True)
scaler = torch.amp.GradScaler('cuda', enabled=amp)
forward = torch.compile(model) if compiled else model
def step():
optimizer.zero_grad(set_to_none=True)
with torch.autocast(device_type='cuda', dtype=torch.float16, enabled=amp):
logits = forward(x)
loss = nn.functional.cross_entropy(logits, y, label_smoothing=.05)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
return loss
return model, optimizer, scaler, x, y, step
def measure(batch, channels_last, amp, cudnn_benchmark, compiled=False):
# Semilla, tensores, arquitectura y optimizador se reinician en cada configuración.
model, optimizer, scaler, x, y, step = make_case(batch, channels_last, amp, cudnn_benchmark, compiled)
warmup, steps, repeats = (3, 3, 2) if short else (10, 20, 5)
for _ in range(warmup):
loss = step()
torch.cuda.synchronize()
if not bool(torch.isfinite(loss)):
raise FloatingPointError('La pérdida del calentamiento no es finita')
torch.cuda.reset_peak_memory_stats()
durations, losses = [], []
scale_before = float(scaler.get_scale()) if amp else None
for _ in range(repeats):
torch.cuda.synchronize()
start = time.perf_counter()
for _ in range(steps):
loss = step()
torch.cuda.synchronize()
durations.append(time.perf_counter() - start)
losses.append(float(loss.detach().cpu()))
scale_after = float(scaler.get_scale()) if amp else None
if not all(torch.isfinite(torch.tensor(losses))):
raise FloatingPointError('La pérdida medida no es finita')
median_seconds = statistics.median(durations)
result = {'batch': batch, 'channels_last': channels_last, 'amp_float16': amp,
'cudnn_benchmark': cudnn_benchmark, 'compiled': compiled,
'warmup': warmup, 'steps_per_repeat': steps, 'repeats': repeats,
'images_per_second': batch * steps / median_seconds,
'seconds_per_repeat': durations, 'peak_allocated_bytes': torch.cuda.max_memory_allocated(),
'peak_reserved_bytes': torch.cuda.max_memory_reserved(),
'loss_scale_before': scale_before, 'loss_scale_after': scale_after,
'possible_skipped_steps': bool(amp and scale_after < scale_before),
'losses': losses}
del step, x, y, optimizer, scaler, model
torch.cuda.empty_cache()
return result
def profile_case():
model, optimizer, scaler, x, y, step = make_case(32, False, False, False)
for _ in range(2):
step()
torch.cuda.synchronize()
with torch.profiler.profile(activities=[torch.profiler.ProfilerActivity.CPU, torch.profiler.ProfilerActivity.CUDA],
record_shapes=True) as prof:
with torch.profiler.record_function('paso_entrenamiento'):
step()
torch.cuda.synchronize()
trace = os.environ.get('ORYON_PROFILE_TRACE')
if trace:
prof.export_chrome_trace(trace)
print('Traza CPU y CUDA:', trace)
rows = prof.key_averages(group_by_input_shape=True)
# No mezclar anotaciones ni kernels en el mismo ranking que los operadores aten.
# Los operadores pueden abarcar varios kernels o estar anidados; no sumar sus tiempos.
operators = [item for item in rows if item.key.startswith('aten::')]
top = [{'key': item.key, 'input_shapes': str(item.input_shapes),
'self_device_time_us': float(item.self_device_time_total),
'self_cpu_time_us': float(item.self_cpu_time_total), 'calls': int(item.count)}
for item in sorted(operators, key=lambda item: item.self_device_time_total, reverse=True)[:12]]
print('Profiler: operadores aten ordenados por tiempo de dispositivo propio; no sumar tiempos anidados:')
for row in top:
print(row['key'], round(row['self_device_time_us'], 1), 'µs, llamadas', row['calls'], row['input_shapes'])
del step, x, y, optimizer, scaler, model, prof
torch.cuda.empty_cache()
return top
def main():
before_free, total = torch.cuda.mem_get_info()
# Conservar margen para otros procesos, sin probar tamaños hasta agotar memoria.
if before_free < 1_500_000_000:
raise RuntimeError('Menos de 1,5 GB libres en GPU: no se ejecuta el barrido')
sizes = [16, 64] if short else [32, 64, 128, 256]
choices = list(itertools.product(sizes, (False, True), (False, True), (False, True)))
rows = []
for batch, channels_last, amp, bench in choices:
row = measure(batch, channels_last, amp, bench)
rows.append(row)
print('batch', batch, 'channels_last', channels_last, 'amp', amp, 'cudnn benchmark', bench,
'imágenes/s', round(row['images_per_second'], 1), flush=True)
compiled = {'requested': do_compile, 'result': None, 'error': None}
if do_compile:
try:
compiled['result'] = measure(sizes[0], True, False, False, compiled=True)
except Exception as exc:
compiled['error'] = f'{type(exc).__name__}: {exc}'[:500]
print('torch.compile no disponible en esta configuración:', compiled['error'])
finally:
torch.cuda.empty_cache()
try:
profile = {'rows': profile_case(), 'error': None}
except Exception as exc:
profile = {'rows': [], 'error': f'{type(exc).__name__}: {exc}'[:500]}
print('Profiler no disponible en esta configuración:', profile['error'])
result = {'device': torch.cuda.get_device_name(), 'torch_version': torch.__version__,
'cuda_version': torch.version.cuda, 'cudnn_version': torch.backends.cudnn.version(),
'platform': platform.platform(), 'short': short, 'torch_threads': torch.get_num_threads(),
'tf32_matmul': torch.backends.cuda.matmul.allow_tf32,
'tf32_cudnn': torch.backends.cudnn.allow_tf32,
'deterministic_algorithms': torch.are_deterministic_algorithms_enabled(),
'parameter_count': sum(p.numel() for p in SmallVGG().parameters()),
'workload': 'SmallVGG: 3 bloques con dos conv-bn-relu y maxpool, GAP y lineal; forward, CE con smoothing 0.05, backward y SGD Nesterov',
'input': 'ruido sintético fijo 3x32x32 y etiquetas deterministas, ya residentes en GPU',
'timing': 'warmup, sincronización CUDA, mediana de imágenes por repetición / segundos',
'gpu_free_before_bytes': before_free, 'gpu_total_bytes': total,
'results': rows, 'compile': compiled, 'profiler': profile}
output = Path(os.environ.get('ORYON_THROUGHPUT_OUTPUT', 'm16-l07-throughput.json'))
output.write_text(json.dumps(result, ensure_ascii=False, allow_nan=False, indent=2), encoding='utf-8')
print('Resultado:', output)
if __name__ == '__main__':
try:
main()
finally:
torch.cuda.empty_cache()npm run lab and open the connection link.Exercises
def metrics(logits, targets, ks):
passdef param_groups(model, wd):
passelements=512*(64*32*32+128*16*16+256*8*8)
print('Bytes y MiB de las tres activaciones float16:',elements*2,elements*2/2**20)Model, data protocol and measurement form an experiment. Keep test separate, change one condition at a time and synchronize the GPU when timing.