The ImageNet revolution: AlexNet, VGG and Inception
Compare AlexNet, VGG and Inception in the context of their ImageNet evaluation protocols, and count parameters and operations while distinguishing compute from latency.
After this lesson you can
- Interpret ImageNet top-5 results in their original evaluation protocols.
- Describe the architectural and training choices of AlexNet and VGG.
- Explain pointwise convolutions and Inception branches.
- Calculate parameters and MACs of direct and bottleneck convolutions.
- Compare small CNN variants under matched experimental conditions.
Before you start
One benchmark, many choices
A network can improve because architecture, data, training recipe, preprocessing or the way predictions are combined changes. ImageNet’s history is more useful when these choices are separated. AlexNet, VGG and Inception are not merely three positions in a table: they raise different questions about depth, computation and feature reuse.
What ImageNet measures
The ImageNet benchmark and ILSVRC organized images into categories related to WordNet synonym sets and used human annotations. ILSVRC included different tasks, including classification, localization and detection: do not mix their metrics. In classification, top-5 error counts an image as a failure when its label is absent from the five highest-scoring predictions. It is the complement of top-5 accuracy, not top-1 error.
The organizers’ 2017 overview plots rounded annual results from 2010 to 2017. The preceding graph retains those roundings, so it does not replace each paper’s detailed tables. Some entries also combine models, crops or external data. Directly comparing that number with one network and one crop confuses architecture and protocol.
A test reused to decide designs ceases to be completely independent of accumulated decisions. But observing a drop on another dataset is not enough to identify one cause. Recht and colleagues built a new ImageNet test and observed an 11 to 14 point accuracy drop; their analysis pointed to a difference in image difficulty and found no evidence attributing the drop mainly to adaptive overfitting. These are limits of the dataset and evaluation procedure, not a denial of the benchmark’s usefulness. Prospective evaluation and possible biases recur in research methodology and adaptive data analysis.
AlexNet: training and compute as design
The AlexNet architecture combines five convolutions and three dense layers, with approximately 60 million parameters in one network. Krizhevsky, Sutskever and Hinton describe training on two GPUs and choices including ReLU, dropout, augmentation and local response normalization, LRN. ReLU avoids saturation in its positive region but has zero slope in the negative region: it does not automatically remove all optimization problems. Dropout changes training and should not remain active as though it were a deterministic evaluation layer.
The paper’s table 2 distinguishes protocols: one CNN obtains validation top-1 error 40.7% and top-5 18.2%; five CNNs obtain 38.1% and 16.4%. The 15.3% top-5 test entry combines seven CNNs, two pretrained with additional data. Do not attribute that figure to the cost or predictions of one model. The 17.0% result also appearing in the abstract corresponds to ILSVRC-2010, not the same 2012 experiment.
LRN normalizes an activation using neighbors across channels; in the paper it was a specific architectural choice. It is not BatchNorm or a mandatory part of a modern CNN. Evaluating activations also requires controlling rate, initialization and recipe: saturation is a mechanism, not an automatic explanation for every observed difference.
VGG: regular depth, expensive head
The VGG family explores depth with blocks of small convolutions. Simonyan and Zisserman compare configurations A through E; D is known as VGG-16. Its blocks mainly use 3×3 kernels, although configuration C also contains 1×1 layers. Two 3×3 layers without intermediate dilation or reduction have the same potential box as one 5×5, as derived in small-kernel stacking; introducing nonlinearity changes the function class, so equal field does not imply functional equivalence.
The same paper’s table 3 reports, for one network with variable training scale and evaluation scale , 25.6% top-1 and 8.1% top-5 validation error for configuration D. Table 7 distinguishes other scale and model combinations: each figure cannot validly be presented as the same evaluation. Parameter count also depends on the specific implementation and head.
A dense layer with input and output has parameters with bias, regardless of how many examples it processes. Convolution shares weights across positions but performs multiplications at each. Layers with the most parameters therefore need not concentrate the most compute. The figure counts convolution and dense MACs on one image; it ignores other operations and does not measure real time. Changing to global averaging and a new classifier alters architecture and requires training it: it is not a prediction-preserving substitution.
1×1: mix channels without mixing positions
The 1×1 convolution receives and, with stride one, no padding and no groups, produces
At each position it is the same affine mapping from to . It shares parameters across positions and sees no new spatial neighbors; nonlinearity added afterward is another operation. A bottleneck with channels can reduce spatial-branch cost: a 1×1 followed by costs MACs, versus without reduction. The counter omits bias additions in both. Smaller also restricts the intermediate representation, so saving compute does not guarantee retaining the same function.
Global average pooling reduces each spatial map to a mean before the classifier. It removes the need for a dense head depending on all positions but discards some spatial information. Connect this to global average pooling and the receptive field: summarizing one local position and aggregating all positions are different operations.
Inception: allocating channels and paths
An Inception module processes the same input in parallel branches and concatenates their results by channel. In GoogLeNet, branches use 1×1, 3×3, 5×5 and pooling; 1×1 reductions precede more expensive convolutions. All outputs concatenated must match in height and width. Their local fields differ and resulting channel counts add, rather than being averaged.
GoogLeNet has 22 layers with weights; the paper describes a budget of approximately 1.5 billion multiply-accumulates per inference. One network and one crop obtain 10.07% top-5 validation error; the table with seven models and 144 crops reports 6.67%. The competition value is not the cost or accuracy of one forward pass. Auxiliary classifiers added training signals at intermediate stages; do not count them as necessarily the final classifier used by a simplified implementation.
In Inception v2/v3, an convolution can be factorized into and , with an intermediate representation and possible nonlinearity. With fixed channel widths, spatial count changes from terms per channel pair to two factors of length if intermediate width matches; if widths differ, count each layer separately. Factorization introduces constraints and is not equivalent to every large kernel. The work also studies label smoothing: its tables of cumulative modifications do not prove one technique explains all model differences.
Cost is not latency
A MAC counts a multiply-accumulate. Under two FLOPs per MAC, the figure doubles, but some tools call one MAC one FLOP. Also state whether biases, activations, pooling, backward and auxiliary heads are included. A 1×1 with fewer operations may use hardware differently from a 3×3, and parallel branches may require memory and synchronization: fewer FLOPs do not ensure lower latency. As in the CIFAR recipe, measure throughput with warmup, synchronization and the same protocol, and keep accuracy and time conclusions separate.
Labs
The following cells define a shape, parameter and MAC counter, apply it to VGG-16 and torchvision’s particular AlexNet implementation, and check 1×1 equivalence. Counting a MAC as two FLOPs is a convention: torchvision documentation presents its operation figure under a different name. Torchvision’s AlexNet follows a later variant and does not exactly reproduce the 2012 paper’s two-GPU split.
# Cuentas por imagen. Un MAC es un producto acumulado; dos FLOP por MAC
# es una convención, no cuenta bias, pooling, ReLU, memoria ni backward.
import math
def nonnegative_int(value, name, minimum=0):
if isinstance(value, bool) or not isinstance(value, int) or value < minimum:
raise ValueError(f'{name} debe ser un entero >= {minimum}')
return value
def pair(value, name, minimum):
if isinstance(value, int) and not isinstance(value, bool):
value = (value, value)
if not isinstance(value, (tuple, list)) or len(value) != 2:
raise ValueError(f'{name} debe ser un entero o una pareja')
return tuple(nonnegative_int(x, name, minimum) for x in value)
def count_network(input_shape, layers):
"""Conv, maxpool, flatten, GAP y linear; salida por imagen y por capa.
Formas CHW o vector; conv/pool usan padding simétrico, floor y sin ceil.
Conv admite stride, dilatación y grupos. Maxpool no cuenta operaciones.
GAP solo cambia la forma: tampoco se incluyen sus sumas en MAC.
"""
if not isinstance(input_shape, (list, tuple)) or len(input_shape) != 3:
raise ValueError('Se espera una entrada CHW')
shape = tuple(nonnegative_int(v, 'dimensión', 1) for v in input_shape)
if not isinstance(layers, (list, tuple)):
raise ValueError('Se requiere una lista de capas')
rows = []
for spec in layers:
if not isinstance(spec, dict) or not isinstance(spec.get('name'), str):
raise ValueError('Capa sin nombre')
kind = spec.get('kind')
before = shape
params = macs = 0
if kind in ('conv', 'pool'):
if len(shape) != 3:
raise ValueError('La capa espacial requiere CHW')
cin, height, width = shape
kh, kw = pair(spec.get('kernel'), 'kernel', 1)
sh, sw = pair(spec.get('stride', 1), 'stride', 1)
ph, pw = pair(spec.get('padding', 0), 'padding', 0)
dh, dw = pair(spec.get('dilation', 1), 'dilation', 1)
oh = (height + 2*ph - dh*(kh-1) - 1)//sh + 1
ow = (width + 2*pw - dw*(kw-1) - 1)//sw + 1
if min(oh, ow) < 1:
raise ValueError('La ventana no produce salida')
if kind == 'conv':
cout = nonnegative_int(spec.get('out_channels'), 'canales de salida', 1)
groups = nonnegative_int(spec.get('groups', 1), 'grupos', 1)
bias = spec.get('bias', True)
if type(bias) is not bool or cin % groups or cout % groups:
raise ValueError('Grupos o sesgo incompatibles')
weights = cout*(cin//groups)*kh*kw
params = weights + (cout if bias else 0)
macs = weights*oh*ow
else:
cout = cin
shape = (cout, oh, ow)
elif kind == 'flatten':
if len(shape) != 3:
raise ValueError('flatten requiere CHW')
shape = (math.prod(shape),)
elif kind == 'gap':
if len(shape) != 3:
raise ValueError('GAP requiere CHW')
shape = (shape[0],)
elif kind == 'linear':
if len(shape) != 1:
raise ValueError('La capa lineal requiere un vector')
output = nonnegative_int(spec.get('out_features'), 'salidas', 1)
bias = spec.get('bias', True)
if type(bias) is not bool:
raise ValueError('El sesgo debe ser bool')
macs = shape[0]*output
params = macs + (output if bias else 0)
shape = (output,)
else:
raise ValueError('Tipo de capa no soportado')
rows.append({'name':spec['name'], 'kind':kind, 'input':before, 'output':shape,
'parameters':params, 'mac':macs, 'flop_2permac':2*macs})
return rows
def totals(rows):
return {'parameters':sum(r['parameters'] for r in rows),
'mac':sum(r['mac'] for r in rows),
'flop_2permac':sum(r['flop_2permac'] for r in rows)}def vgg16_spec():
layers=[]
for block, (channels, count) in enumerate(((64,2),(128,2),(256,3),(512,3),(512,3)), 1):
for layer in range(1, count+1):
layers.append({'name':f'conv{block}_{layer}', 'kind':'conv',
'out_channels':channels, 'kernel':3, 'padding':1})
layers.append({'name':f'pool{block}', 'kind':'pool', 'kernel':2, 'stride':2})
layers += [{'name':'flatten', 'kind':'flatten'},
{'name':'fc6', 'kind':'linear', 'out_features':4096},
{'name':'fc7', 'kind':'linear', 'out_features':4096},
{'name':'fc8', 'kind':'linear', 'out_features':1000}]
return layers
vgg_rows = count_network((3,224,224), vgg16_spec())
vgg_total = totals(vgg_rows)
conv_parameters = sum(r['parameters'] for r in vgg_rows if r['kind']=='conv')
dense_parameters = sum(r['parameters'] for r in vgg_rows if r['kind']=='linear')
print('VGG-16 por capa:')
for row in vgg_rows:
print(row['name'], row['output'], 'parámetros', row['parameters'], 'MAC', row['mac'])
print('Total:',vgg_total)
print('Convolucionales, densos y porcentaje denso:',conv_parameters,dense_parameters,100*dense_parameters/vgg_total['parameters'])
assert vgg_total['parameters']==138357544
assert sum(row['kind']=='conv' for row in vgg_rows)==13
assert abs(vgg_total['mac']/1e9-15.47)<.01# La arquitectura anterior de la lección m16-l06 es un control independiente.
lenet_spec=[{'name':'conv1','kind':'conv','out_channels':6,'kernel':5,'padding':2},
{'name':'pool1','kind':'pool','kernel':2,'stride':2},
{'name':'conv2','kind':'conv','out_channels':16,'kernel':5},
{'name':'pool2','kind':'pool','kernel':2,'stride':2},
{'name':'flatten','kind':'flatten'},
{'name':'fc1','kind':'linear','out_features':120},
{'name':'fc2','kind':'linear','out_features':84},
{'name':'fc3','kind':'linear','out_features':10}]
lenet=count_network((1,28,28),lenet_spec)
print('LeNet de m16-l06:',totals(lenet))
assert totals(lenet)['parameters']==61706
assert totals(lenet)['mac']==416520
# Rama 5x5: MAC y FLOP con y sin reducción; ambas usan 32 canales de salida.
direct=count_network((192,28,28),[{'name':'5x5','kind':'conv','kernel':5,'padding':2,'out_channels':32}])
reduced=count_network((192,28,28),[{'name':'1x1','kind':'conv','kernel':1,'out_channels':16},
{'name':'5x5','kind':'conv','kernel':5,'padding':2,'out_channels':32}])
print('Rama directa y con reducción:',totals(direct),totals(reduced))
# Rechazos y grupo: 4 salidas, dos grupos de dos entradas, kernel 3×3.
grouped=count_network((4,8,8),[{'name':'grupo','kind':'conv','kernel':3,'groups':2,'out_channels':4}])[0]
assert grouped['output']==(4,6,6) and grouped['parameters']==76 and grouped['mac']==2592
for shape, layers in [((3,2,2),[{'name':'conv','kind':'conv','out_channels':4,'kernel':5}]),
((3,8,8),[{'name':'conv','kind':'conv','out_channels':4,'kernel':3,'groups':2}]),
((3,8,8),[{'name':'fc','kind':'linear','out_features':5}])]:
try:
count_network(shape,layers)
except ValueError:
pass
else:
raise AssertionError('Entrada inválida aceptada')import numpy as np
generator=np.random.default_rng(1608)
x=generator.normal(size=(2,3,4,5))
w=generator.normal(size=(7,3))
b=generator.normal(size=7)
# Referencia por índices, sin operaciones que mezclen ubicaciones.
by_loop=np.empty((2,7,4,5))
for n in range(2):
for o in range(7):
for h in range(4):
for col in range(5):
by_loop[n,o,h,col]=sum(w[o,c]*x[n,c,h,col] for c in range(3))+b[o]
by_matrix=(x.transpose(0,2,3,1) @ w.T + b).transpose(0,3,1,2)
error=float(np.max(np.abs(by_loop-by_matrix)))
print('1x1: forma',by_matrix.shape,'diferencia máxima por índices:',error)
assert error<1e-12# Variante AlexNet de torchvision para 224×224. No es la topología original
# en dos GPU de 2012: aquí todas las convoluciones se calculan sin grupos.
alex_spec=[
{'name':'conv1','kind':'conv','out_channels':64,'kernel':11,'stride':4,'padding':2},
{'name':'pool1','kind':'pool','kernel':3,'stride':2},
{'name':'conv2','kind':'conv','out_channels':192,'kernel':5,'padding':2},
{'name':'pool2','kind':'pool','kernel':3,'stride':2},
{'name':'conv3','kind':'conv','out_channels':384,'kernel':3,'padding':1},
{'name':'conv4','kind':'conv','out_channels':256,'kernel':3,'padding':1},
{'name':'conv5','kind':'conv','out_channels':256,'kernel':3,'padding':1},
{'name':'pool3','kind':'pool','kernel':3,'stride':2},
{'name':'flatten','kind':'flatten'},
{'name':'fc1','kind':'linear','out_features':4096},
{'name':'fc2','kind':'linear','out_features':4096},
{'name':'fc3','kind':'linear','out_features':1000}]
alex=count_network((3,224,224),alex_spec)
print('AlexNet torchvision por capa:')
for row in alex:
print(row['name'],row['output'],'parámetros',row['parameters'],'MAC',row['mac'])
print('Total:',totals(alex))
assert totals(alex)['parameters']==61100840
assert abs(totals(alex)['mac']/1e9-.71)<.01The local cell compares miniatures for CIFAR; it does not reproduce ImageNet networks. It uses stated splits and augmentations, the same recipe and three seeds; each best checkpoint is chosen on validation. Short mode runs 120 steps per combination and reader mode proposes longer training. It includes two activation and initialization controls for mini AlexNet. Cost counts only convolutions and dense layers and compares that part with torch.profiler; throughput measures inference with resident batches and synchronization, without data loading. Accuracy metrics use float32, while training and throughput measurement use bfloat16 autocast when available. A short trial on shared hardware does not establish a universal winner.
In the recorded short run, best validation accuracies of mini AlexNet with ReLU and default initialization were 10%, 10% and 13% across three seeds. With He weights and zero-initialized biases they were 25%, 20% and 22.5%; with tanh and default initialization, 26.5%, 28.5% and 27%. The experiment shows this recipe did not train the first variant well under that budget and changing weight and bias initialization changed the observed result. It does not prove tanh superior to ReLU or identify one cause: initial scale, saturation and rate interact, and three seeds and 200 validation examples are limited exploration. Short test is another stratified block, disjoint from that consulted during previous exploration.
"""Tres CNN reducidas comparadas en CIFAR-10 con una receta común.
Requiere torch, numpy, pillow, pyarrow y huggingface_hub. ORYON_VERIFY_SHORT=1
verifica con subconjuntos estratificados y un presupuesto corto; el modo normal
es para el entrenamiento del lector. ORYON_ARCH_OUTPUT elige el JSON de salida.
Se trata de variantes para CIFAR, no de reproducciones de ImageNet.
"""
import io
import json
import os
import statistics
import time
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)
torch.backends.cudnn.benchmark = False
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 comparación está configurada para CUDA')
amp = torch.cuda.is_bf16_supported()
revision = '0b27149'
seeds = [16081, 16082, 16083]
steps = 120 if short else 12000
batch_size = 64 if short else 128
train_per_class = 100 if short else 4500
valid_per_class = 20 if short else 500
test_per_class = 20 if short else 1000
def choose_indices(split, count, seed):
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)
labels = np.concatenate([b.column(0).to_numpy() for b in parquet.iter_batches(batch_size=1024, columns=['label'])]).astype(np.int64)
generator = np.random.default_rng(seed)
groups = [generator.permutation(np.flatnonzero(labels == k)) for k in range(10)]
if any(len(group) < count for group in groups):
raise ValueError('Insuficientes imágenes de una clase')
return path, labels, groups
def read_selected(path, labels, indices):
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):
target = position.get(offset + local)
if target 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 de forma inesperada')
images[target] = array.transpose(2, 0, 1)
seen[target] = 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)
def make_splits():
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])
# La selección corta usa el bloque siguiente al test visto en una primera
# exploración. El modo lector evalúa el test completo del conjunto.
offset = test_per_class if short else 0
test_path, test_labels, test_groups = choose_indices('test', test_per_class + offset, 16074)
test_ids = np.concatenate([g[offset:offset + test_per_class] for g in test_groups])
assert not set(train_ids) & set(valid_ids)
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)
return (train_x, train_y, valid_x, valid_y, test_x, test_y,
train_ids.tolist(), valid_ids.tolist(), test_ids.tolist())
def channel_stats(images):
totals = torch.zeros(3, device=device, dtype=torch.float64)
squares = torch.zeros_like(totals)
count = 0
for start in range(0, len(images), 256):
batch = images[start:start + 256].to(torch.float64) / 255
totals += batch.sum((0, 2, 3))
squares += (batch * batch).sum((0, 2, 3))
count += batch.shape[0] * 32 * 32
mean = totals / count
std = (squares / count - mean ** 2).clamp_min(0).sqrt()
if not bool(torch.isfinite(std).all() and (std > 0).all()):
raise ValueError('Estadísticas inválidas')
return mean, std
def preprocess(images, mean, std, generator=None):
x = images.float() / 255
if generator is not None:
padded = F.pad(x, (4, 4, 4, 4), mode='reflect')
n = len(x)
dy = torch.randint(0, 9, (n,), generator=generator, device=device)
dx = torch.randint(0, 9, (n,), generator=generator, device=device)
rows = dy[:, None] + torch.arange(32, device=device)[None, :]
cols = dx[:, None] + torch.arange(32, device=device)[None, :]
x = padded[torch.arange(n, device=device)[:, None, None, None],
torch.arange(3, device=device)[None, :, None, None],
rows[:, None, :, None], cols[:, None, None, :]]
flips = torch.rand(n, generator=generator, device=device) < .5
x = torch.where(flips[:, None, None, None], x.flip(-1), x)
return ((x - mean.float()[None, :, None, None]) / std.float()[None, :, None, None]).contiguous(memory_format=torch.channels_last)
class ChannelLRN(nn.Module):
"""LRN con ventana impar y padding de canal cero, sin avg_pool3d CUDA."""
def __init__(self, size=5, alpha=1e-4, beta=.75, k=1.):
super().__init__()
if size < 1 or size % 2 == 0:
raise ValueError('La ventana debe ser impar y positiva')
self.size, self.alpha, self.beta, self.k = size, alpha, beta, k
def forward(self, x):
squares = x * x
channels = x.shape[1]
radius = self.size // 2
total = torch.zeros_like(x)
for shift in range(-radius, radius + 1):
if abs(shift) >= channels:
continue
if shift < 0:
gap = torch.zeros_like(squares[:, :-shift])
shifted = torch.cat((gap, squares[:, :shift]), dim=1)
elif shift > 0:
gap = torch.zeros_like(squares[:, :shift])
shifted = torch.cat((squares[:, shift:], gap), dim=1)
else:
shifted = squares
total = total + shifted
return x / (self.k + (self.alpha / self.size) * total).pow(self.beta)
def verify_lrn():
generator = torch.Generator().manual_seed(16089)
x = torch.randn((2, 7, 3, 4), generator=generator, dtype=torch.float64, requires_grad=True)
y = x.detach().clone().requires_grad_(True)
seed = torch.randn(x.shape, generator=generator, dtype=x.dtype)
actual, expected = ChannelLRN()(x), nn.LocalResponseNorm(5)(y)
(actual * seed).sum().backward()
(expected * seed).sum().backward()
value_error = float((actual - expected).detach().abs().max())
gradient_error = float((x.grad - y.grad).abs().max())
assert max(value_error, gradient_error) < 1e-12, (value_error, gradient_error)
print('LRN frente a PyTorch CPU: errores máximo forward y backward', value_error, gradient_error, flush=True)
class MiniAlexNet(nn.Module):
"""Cinco convoluciones, LRN, pooling y dropout; adaptación, no AlexNet original."""
def __init__(self, activation='relu', kaiming=False):
super().__init__()
def act():
if activation == 'relu':
return nn.ReLU()
if activation == 'tanh':
return nn.Tanh()
raise ValueError('Activación desconocida')
self.features = nn.Sequential(
nn.Conv2d(3, 32, 5, padding=2), act(), ChannelLRN(), nn.MaxPool2d(2),
nn.Conv2d(32, 64, 3, padding=1), act(), ChannelLRN(), nn.MaxPool2d(2),
nn.Conv2d(64, 128, 3, padding=1), act(),
nn.Conv2d(128, 128, 3, padding=1), act(),
nn.Conv2d(128, 128, 3, padding=1), act())
self.classifier = nn.Sequential(nn.Dropout(.5), nn.Linear(128, 128), act(),
nn.Dropout(.5), nn.Linear(128, 10))
if kaiming:
for module in self.modules():
if isinstance(module, (nn.Conv2d, nn.Linear)):
nn.init.kaiming_normal_(module.weight, mode='fan_in', nonlinearity='relu')
if module.bias is not None:
nn.init.zeros_(module.bias)
def forward(self, x):
return self.classifier(self.features(x).mean(dim=(2, 3)))
class MiniVGG11(nn.Module):
"""Patrón 1,1,2,2,2 convoluciones, BN y cinco max pooling."""
def __init__(self):
super().__init__()
widths = [(16, 1), (32, 1), (64, 2), (96, 2), (128, 2)]
layers, channels = [], 3
for width, count in widths:
for _ in range(count):
layers.extend([nn.Conv2d(channels, width, 3, padding=1, bias=False),
nn.BatchNorm2d(width), nn.ReLU()])
channels = width
layers.append(nn.MaxPool2d(2))
self.features = nn.Sequential(*layers)
self.classifier = nn.Sequential(nn.Linear(128, 128), nn.ReLU(),
nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 10))
def forward(self, x):
return self.classifier(self.features(x).flatten(1))
class InceptionBlock(nn.Module):
def __init__(self, cin, c1, c3r, c3, c5r, c5, pool_proj):
super().__init__()
def conv(a, b, k, p):
return nn.Sequential(nn.Conv2d(a, b, k, padding=p, bias=False), nn.BatchNorm2d(b), nn.ReLU())
self.one = conv(cin, c1, 1, 0)
self.three = nn.Sequential(conv(cin, c3r, 1, 0), conv(c3r, c3, 3, 1))
self.five = nn.Sequential(conv(cin, c5r, 1, 0), conv(c5r, c5, 5, 2))
self.pool = nn.Sequential(nn.MaxPool2d(3, stride=1, padding=1), conv(cin, pool_proj, 1, 0))
def forward(self, x):
return torch.cat((self.one(x), self.three(x), self.five(x), self.pool(x)), dim=1)
class MiniInception(nn.Module):
"""Tres módulos Inception, sin los clasificadores auxiliares de GoogLeNet."""
def __init__(self):
super().__init__()
self.features = nn.Sequential(nn.Conv2d(3, 32, 3, padding=1, bias=False), nn.BatchNorm2d(32), nn.ReLU(),
InceptionBlock(32, 16, 12, 16, 4, 8, 8), nn.MaxPool2d(2),
InceptionBlock(48, 24, 16, 24, 8, 12, 12), nn.MaxPool2d(2),
InceptionBlock(72, 32, 24, 32, 8, 16, 16))
self.classifier = nn.Linear(96, 10)
def forward(self, x):
return self.classifier(self.features(x).mean(dim=(2, 3)))
def parameter_groups(model):
norm_ids = {id(p) for m in model.modules() if isinstance(m, nn.modules.batchnorm._BatchNorm)
for p in m.parameters(recurse=False)}
decay, clean = [], []
for name, parameter in model.named_parameters():
if parameter.requires_grad:
(clean if name.endswith('.bias') or id(parameter) in norm_ids else decay).append(parameter)
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.0}]
def evaluate(model, x, y, mean, std):
model.eval()
predictions = []
with torch.inference_mode():
for start in range(0, len(x), 128):
sample = preprocess(x[start:start + 128], mean, std)
predictions.append(model(sample).float().cpu())
logits = torch.cat(predictions)
labels = y.cpu()
order = logits.argsort(dim=1, descending=True)
top1 = float(order[:, 0].eq(labels).float().mean())
top5 = float(order[:, :5].eq(labels[:, None]).any(1).float().mean())
return {'top1': top1, 'top5': top5, 'loss': float(F.cross_entropy(logits, labels))}
def count_compute(model, sample):
"""Cuenta MAC conv/densas por hooks y los contrasta con profiler CPU."""
handles, macs = [], []
def hook(module, inputs, output):
if isinstance(module, nn.Conv2d):
macs.append(output.numel() * (module.in_channels // module.groups) * module.kernel_size[0] * module.kernel_size[1])
elif isinstance(module, nn.Linear):
macs.append(output.numel() * module.in_features)
for module in model.modules():
if isinstance(module, (nn.Conv2d, nn.Linear)):
handles.append(module.register_forward_hook(hook))
model.eval()
try:
with torch.inference_mode(), torch.profiler.profile(activities=[torch.profiler.ProfilerActivity.CPU], with_flops=True) as prof:
model(sample)
torch.cuda.synchronize()
finally:
for handle in handles:
handle.remove()
events = prof.key_averages()
operations = {event.key: int(event.flops) for event in events if event.flops}
profiled = sum(operations.get(key, 0) for key in ('aten::conv2d', 'aten::mm', 'aten::addmm'))
expected = int(2 * sum(macs))
if profiled != expected:
raise AssertionError(f'Profiler conv/densas {profiled} no coincide con 2×MAC {expected}; operaciones {operations}')
return {'parameters': sum(p.numel() for p in model.parameters()), 'mac_conv_linear': int(sum(macs)),
'flops_conv_linear_2_per_mac': expected, 'profiler_flops_conv_linear': int(profiled),
'profiler_all_supported_flops': sum(operations.values()), 'profiler_by_operation': operations,
'convention': 'solo convoluciones y densas, sin sumas de sesgo; 2 FLOPs por MAC'}
def inference_throughput(model, sample):
model.eval()
warmup, measured, repeats = (3, 5, 2) if short else (10, 30, 5)
with torch.inference_mode(), torch.autocast('cuda', dtype=torch.bfloat16, enabled=amp):
for _ in range(warmup):
model(sample)
torch.cuda.synchronize()
durations = []
for _ in range(repeats):
torch.cuda.synchronize()
start = time.perf_counter()
for _ in range(measured):
model(sample)
torch.cuda.synchronize()
durations.append(time.perf_counter() - start)
return {'batch': len(sample), 'warmup': warmup, 'steps_per_repeat': measured,
'seconds_per_repeat': durations, 'images_per_second': len(sample) * measured / statistics.median(durations)}
def run_experiment():
verify_lrn()
train_x, train_y, valid_x, valid_y, test_x, test_y, train_ids, valid_ids, test_ids = make_splits()
mean, std = channel_stats(train_x)
variants = [('alexnet_relu', lambda: MiniAlexNet('relu')),
('alexnet_tanh', lambda: MiniAlexNet('tanh')),
('alexnet_relu_he', lambda: MiniAlexNet('relu', kaiming=True)),
('vgg11_bn', MiniVGG11), ('inception', MiniInception)]
results, costs = [], {}
for name, make_model in variants:
for seed in seeds:
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
generator = torch.Generator(device=device).manual_seed(seed + 1000)
model = make_model().to(device=device, memory_format=torch.channels_last)
opt = torch.optim.SGD(parameter_groups(model), lr=.05, momentum=.9, nesterov=True)
scheduler = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=.05, total_steps=steps,
pct_start=.3, div_factor=5., final_div_factor=100., cycle_momentum=False)
history, best_state, best_accuracy, best_step = [], None, -1., 0
if name not in costs:
sample = preprocess(train_x[:1], mean, std)
costs[name] = count_compute(model, sample)
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], mean, std, generator)
opt.zero_grad(set_to_none=True)
with torch.autocast('cuda', dtype=torch.bfloat16, enabled=amp):
logits = model(x)
loss = F.cross_entropy(logits, train_y[idx], label_smoothing=.05)
if not bool(torch.isfinite(loss)):
raise FloatingPointError('Pérdida no finita')
loss.backward()
report = step == 0 or (step + 1) % max(1, steps // 4) == 0
if report:
grad_norms = {name: float(parameter.grad.detach().norm().cpu())
for name, parameter in model.named_parameters() if parameter.grad is not None}
opt.step()
scheduler.step()
if report:
metrics = evaluate(model, valid_x, valid_y, mean, std)
if metrics['top1'] > best_accuracy:
best_accuracy, best_step = metrics['top1'], step + 1
best_state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
history.append({'step': step + 1, 'train_loss_batch': float(loss.detach()),
'gradient_norms': grad_norms, 'validation': metrics})
model.load_state_dict(best_state)
final = evaluate(model, test_x, test_y, mean, std)
sample = preprocess(train_x[:batch_size], mean, std)
throughput = inference_throughput(model, sample)
results.append({'architecture': name, 'seed': seed, 'best_step': best_step,
'history': history, 'test': final, 'inference_throughput': throughput})
print(name, 'semilla', seed, 'mejor paso', best_step, 'validación', best_accuracy,
'test top1', final['top1'], flush=True)
del opt, scheduler, model, best_state, sample
torch.cuda.empty_cache()
print('Variante | semilla | parámetros | FLOP conv/densas | top1 test | imágenes/s en inferencia residente')
for row in results:
cost = costs[row['architecture']]
print(row['architecture'], row['seed'], cost['parameters'], cost['flops_conv_linear_2_per_mac'],
row['test']['top1'], row['inference_throughput']['images_per_second'])
result = {'dataset': 'uoft-cs/cifar10', 'revision': revision, 'short': short,
'device': torch.cuda.get_device_name(), 'torch_version': torch.__version__,
'seeds': seeds, 'steps': steps, 'batch_size': batch_size,
'train_indices': train_ids, 'valid_indices': valid_ids, 'test_indices': test_ids,
'mean_train': mean.cpu().tolist(), 'std_train': std.cpu().tolist(),
'recipe': 'SGD Nesterov 0.9, weight decay 0.0005 excepto BN y sesgos, OneCycleLR, label smoothing 0.05',
'augmentation': 'reflect pad 4, crop aleatorio 32 y flip horizontal 0.5',
'short_test_selection': 'siguiente bloque estratificado, disjunto de una ejecución exploratoria previa' if short else 'test completo',
'precision': 'bfloat16 autocast' if amp else 'float32',
'selection': 'primer máximo top1 en validación de cada ejecución; test al finalizar',
'throughput': 'inferencia eval con lote residente, warmup y sincronización CUDA; no incluye datos',
'costs': costs, 'runs': results}
output = Path(os.environ.get('ORYON_ARCH_OUTPUT', 'm16-l08-arquitecturas.json'))
output.write_text(json.dumps(result, ensure_ascii=False, allow_nan=False, indent=2), encoding='utf-8')
print('Resultado:', output, flush=True)
if __name__ == '__main__':
try:
run_experiment()
finally:
torch.cuda.empty_cache()npm run lab and open the connection link.Exercises
Step 1 of 3. Which spatial values does output at (h,w) use?
import torch
from torch import nn
class InceptionBlock(nn.Module):
def __init__(self,in_ch,c1,c3r,c3,c5r,c5,pool_proj):
super().__init__()
def forward(self,x):
passThe competition number belongs to a complete protocol. To understand an architecture, count paths, parameters and operations; to compare it with another, control the recipe and measure latency.
References
- Krizhevsky, Sutskever and Hinton, ImageNet Classification with Deep Convolutional Neural Networks.
- Simonyan and Zisserman, Very Deep Convolutional Networks.
- Szegedy and colleagues, Going Deeper with Convolutions.
- Szegedy and colleagues, Rethinking the Inception Architecture.
- Russakovsky and colleagues, ImageNet Large Scale Visual Recognition Challenge.
- Recht and colleagues, Do ImageNet Classifiers Generalize to ImageNet?.
- Torchvision, VGG-16 and AlexNet.