Beyond ResNet: DenseNet, ResNeXt, Wide ResNet and channel attention
Compare DenseNet connectivity, grouped convolution and ResNeXt cardinality, Wide ResNet and Squeeze-and-Excitation while measuring parameters, activations and latency.
After this lesson you can
- Calculate DenseNet channel growth and discuss activation-memory tradeoffs.
- Derive grouped-convolution parameters and the depthwise special case.
- Explain the equivalence of parallel ResNeXt branches and grouped convolution.
- Compare width and depth with explicit compute and memory budgets.
- Implement Squeeze-and-Excitation and evaluate architecture choices under constraints.
Before you start
Four ways to spend a budget
A network that learns well need not be the deepest or have the fewest weights. Weights are stored once; activations also depend on batch size and resolution, and time depends on how operations execute on hardware. After ResNet, we change connectivity, cardinality, width and channel rescaling. The question is what each change gains and which resource it consumes.
DenseNet: retain and reuse
In a residual network with compatible shapes, : addition mixes two tensors coordinate by coordinate. In a DenseNet, instead,
where brackets concatenate channels and each contributes new channels. If has channels, layer ‘s input, numbering from one, has and accumulated output after layers has . Earlier maps remain separately available; they are not summed. The original paper counts direct connections from input and earlier layers to the transforms under that indexing convention (Huang and colleagues).
In DenseNet-BC, each transform uses a 1×1 bottleneck before the 3×3 convolution producing channels. Between blocks a transition projects channels to approximately and reduces resolution with pooling; . Keeping resolution uniform within each block makes concatenation possible. Reducing saves parameters per transform but also reduces new features it can add. Compression limits accumulated width at the cost of projecting the representation.
For example, if the bottleneck produces channels and biases and normalizations are omitted, a transform receiving channels has weights: in the 1×1 projection and in the 3×3. Without a bottleneck, a direct 3×3 from to has . The bottleneck is not automatically smaller for all and : it is cheaper only when , or . Comparing functions matters too, because interleaving normalization and activation changes the transform family.
To see why memory may grow, suppose each input concatenation is materialized and retained until backward. Those copies contain spatial channels, in addition to original features, weights, gradients and temporary memory. The sum contains a quadratic term in even though new maps total only channels. This counts one storage scheme, not a law for every implementation. Pleiss and colleagues describe memory reuse and recomputation to reduce map storage from quadratic to linear; recomputation costs compute. The choice connects with memory measurement and later checkpointing.
Recomputing part of forward requires preserving semantics: dropout must use the appropriate mask and stateful layers, such as batch-normalization running statistics, need special care to avoid accidentally updating state twice. Even an efficient implementation must retain new features while successors use them. Possible savings depend on which intermediates are recomputed and backend reservations; check actual peak during forward and backward instead of inferring it only from channel sums.
Grouped convolution: which channels can communicate
A grouped convolution divides both input and output channels into equal groups. Each output receives input only from its group, so both channel counts must be divisible by . Weights of correlation with a kernel have shape and, without bias, number
Nominal direct work for batch and spatial output is multiply-accumulates, excluding biases. Multichannel convolution with is fully connected across channels. If and , each input has filters of its own: depthwise with multiplier .
AlexNet split some computation between two GPUs and restricted some channel connections; see AlexNet for context. Modern grouping is also a controllable architectural constraint, not a requirement to use multiple GPUs. Fewer nominal multiplications do not guarantee lower latency: smaller operations may use the device less effectively and pay more for memory access or launches. Measure the specific case, as in CNN performance.
ResNeXt: cardinality as well as width
A ResNeXt block aggregates transforms of identical topology. If branch is , with and 1×1 convolutions and a 3×3, its residual output is . Stack outputs of all by channel: grouped 3×3 applies each to its segment. A final 1×1 whose weight blocks are sums their contributions and exactly reproduces aggregation. The same argument permits independent per-channel activations and normalizations between operations, provided their parameters and state are copied; it does not permit replacing an operation mixing branches with an independent one without changing the function.
Cardinality is branch count, not layer count or each branch’s width. To increase under a similar budget, width must also be adjusted. In Xie and colleagues, table 3, ResNet-101 and ResNeXt-101 are compared at approximately 7.8 billion FLOPs: ImageNet single-center-view top-1 error is 22.0% and 21.2% respectively. This is a result of that recipe and evaluation, not a promise for every or device.
The count helps design a comparison. With input, output, branches of internal width and no biases, the equivalent sequence has weights. Holding fixed, increasing increases all three terms; holding fixed preserves projection size, but the central term decreases as increases. Matching total width alone therefore does not necessarily match block cost. A fixed-budget search must also count shortcuts and normalizations.
Width, depth and real cost
A Wide ResNet increases block channels and uses fewer layers than some deep alternatives. Multiplying input and output widths of an internal convolution by makes weights grow approximately as ; activations at fixed resolution and batch grow as . To keep similar parameters while widening, reduce other dimensions or depth. Zagoruyko and Komodakis study this tradeoff and place dropout between block convolutions. Greater width can improve GPU utilization, but the result depends on shape, precision, batch and kernels: time with warmup and synchronization without confusing batch throughput with single-image latency.
This comparison changes more than operation count: a deep network composes more nonlinear transforms and a wide one has more channels at each stage. Matching weights does not match expressive capacity, memory or optimization difficulty. For single-input latency use batch one; for throughput measure a representative batch and divide image count by total interval. If CUDA operations are asynchronous, synchronize at both ends. State whether data loading, transfer, preprocessing and compilation are included: these are real costs, though sometimes useful to measure separately.
Squeeze-and-Excitation: a conditioned gate
In Squeeze-and-Excitation, a sample first produces . A small network calculates and returns . With intermediate dimension , the two matrices have weights and biases add . If is an integer, the dominant term is . Averaging loses spatial position; the gate is per channel and depends on the whole sample. It resembles multiplicative gating, but does not compute a position-to-position attention matrix like self-attention.
Although final rescaling is diagonal by channel, gates need not be independent: dense matrices let depend on other channel averages. For a fixed sample, the same multiplies every position; changing one pixel can affect gates at other positions through global averaging. Sigmoid produces values between zero and one for finite inputs, without forcing them to sum to one. If the second projection and its bias are zero, all gates equal : the block halves values and is not identity. A residual combination can still have a separate identity path.
This local cell reproduces figure data: it selects 16 CIFAR-100 test images, applies official preprocessing and runs EfficientNet-B0 with official ImageNet weights. It saves gates and checks multiplying them by input reproduces SE output. It needs CUDA, PyTorch, torchvision, pyarrow, Pillow and huggingface_hub; the first run downloads data and weights.
"""Compuertas reales de EfficientNet-B0 oficial sobre imágenes CIFAR-100.
La red está preentrenada en ImageNet-1K, no en CIFAR-100. Se usa el
preprocesado incluido en torchvision. No se entrena ni se seleccionan imágenes
por sus predicciones. El JSON se puede incorporar como datos al interactivo.
"""
import base64
import io
import json
import os
from pathlib import Path
import numpy as np
from PIL import Image
import pyarrow.parquet as pq
from huggingface_hub import hf_hub_download
import torch
from torchvision.models import EfficientNet_B0_Weights, efficientnet_b0
torch.set_num_threads(1)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
if device.type != 'cuda':
raise RuntimeError('La extracción está configurada para CUDA')
revision = 'aadb3af77e9048adbea6b47c21a81e47dd092ae5'
path = hf_hub_download(repo_id='uoft-cs/cifar100', repo_type='dataset',
filename='cifar100/test-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=['fine_label'])]).astype(np.int64)
generator = np.random.default_rng(16124)
groups = [generator.permutation(np.flatnonzero(labels == k)) for k in range(100)]
classes = [0, 14, 28, 42, 56, 70, 84, 98]
class_names = {0: 'apple', 14: 'butterfly', 28: 'cup', 42: 'leopard',
56: 'palm_tree', 70: 'rose', 84: 'table', 98: 'woman'}
ids = np.concatenate([groups[k][:2] for k in classes])
positions = {int(source): i for i, source in enumerate(ids)}
image_array = np.empty((len(ids), 3, 32, 32), dtype=np.uint8)
seen = np.zeros(len(ids), dtype=bool)
offset = 0
for batch in parquet.iter_batches(batch_size=256, columns=['img']):
for j in range(batch.num_rows):
pos = positions.get(offset+j)
if pos is not None:
with Image.open(io.BytesIO(batch.column(0)[j].as_py()['bytes'])) as im:
image_array[pos] = np.asarray(im.convert('RGB'), dtype=np.uint8).transpose(2, 0, 1)
seen[pos] = True
offset += batch.num_rows
if not seen.all():
raise RuntimeError('Faltan imágenes')
images = torch.from_numpy(image_array).to(device)
targets = labels[ids]
weights = EfficientNet_B0_Weights.IMAGENET1K_V1
model = efficientnet_b0(weights=weights).to(device).eval()
transform = weights.transforms()
blocks = {'early': 'features.1.0.block.1', 'deep': 'features.7.0.block.2'}
module_map = dict(model.named_modules())
captures = {}
handles = []
def gate_hook(name):
def capture(module, inputs, output):
captures[name] = output.detach()
return capture
def output_hook(name):
def check(module, inputs, output):
expected = inputs[0] * captures[name]
if not torch.allclose(output, expected, atol=1e-7, rtol=1e-6):
raise AssertionError('La compuerta guardada no reproduce la salida SE')
return check
for key, module_name in blocks.items():
module = module_map[module_name]
handles.append(module.scale_activation.register_forward_hook(gate_hook(key)))
handles.append(module.register_forward_hook(output_hook(key)))
result = {'model': 'torchvision.models.efficientnet_b0',
'weights': {'name': 'EfficientNet_B0_Weights.IMAGENET1K_V1', 'url': weights.url,
'training_dataset': 'ImageNet-1K'},
'source': 'uoft-cs/cifar100 test', 'source_revision': revision,
'class_names_source': 'https://huggingface.co/datasets/uoft-cs/cifar100#dataset-structure',
'preprocess': {'description': 'EfficientNet_B0_Weights.IMAGENET1K_V1.transforms()',
'resize': 256, 'center_crop': 224, 'interpolation': 'bilinear',
'mean': [0.485, 0.456, 0.406], 'std': [0.229, 0.224, 0.225]},
'note': 'No seleccionado por predicción. Imágenes CIFAR-100 evaluadas fuera del dominio de entrenamiento ImageNet.',
'blocks': {key: {'name': name, 'channels': module_map[name].fc2.out_channels}
for key, name in blocks.items()}, 'images': []}
for start in range(0, len(ids), 4):
originals = [Image.fromarray(images[j].permute(1, 2, 0).cpu().numpy(), mode='RGB')
for j in range(start, min(start+4, len(ids)))]
inputs = torch.stack([transform(image) for image in originals]).to(device)
with torch.no_grad():
logits = model(inputs).float().cpu()
probabilities = logits.softmax(1)
gates = {key: value.flatten(1).float().cpu() for key, value in captures.items()}
for j, original in enumerate(originals):
buf = io.BytesIO()
original.save(buf, format='PNG')
predicted = int(probabilities[j].argmax())
result['images'].append({'id': int(ids[start+j]), 'label': int(targets[start+j]),
'label_name': class_names[int(targets[start+j])],
'png_base64': base64.b64encode(buf.getvalue()).decode('ascii'),
'gates': {key: value[j].tolist() for key, value in gates.items()},
'imagenet_prediction': predicted, 'imagenet_label': weights.meta['categories'][predicted],
'imagenet_probability': float(probabilities[j, predicted])})
for handle in handles:
handle.remove()
assert len(result['images']) == 16
for item in result['images']:
for key in blocks:
arr = item['gates'][key]
assert len(arr) == result['blocks'][key]['channels'] and all(0 <= v <= 1 for v in arr)
destination = Path(os.environ.get('ORYON_PRETRAINED_SE_OUTPUT', 'm16-l12-pretrained-se.json'))
destination.write_text(json.dumps(result, ensure_ascii=False), encoding='utf-8')
print('16 imágenes, compuertas sigmoid verificadas antes de multiplicar:', destination, flush=True)
torch.cuda.empty_cache()npm run lab and open the connection link.In Hu and colleagues’ analysis, figure 6, SE-ResNet-50 excitations tend to be more class-specific in deeper stages, with exceptions such as SE_5_2. Figures summarize ImageNet images; one cannot infer that every channel or image pair follows that trend. Spatial reduction, two projections and rescaling also have real cost: adding SE to every block does not guarantee lower latency.
Lab: checking the wiring
The im2col lesson already implemented groups. Here we revisit that idea with a small test against saved PyTorch results and check the depthwise case. Library correlation uses the same group-order convention.
This cell retrieves the previous lesson’s implementation. Expected results were calculated with PyTorch CPU and are included so you can check them in the browser without installing PyTorch.
"""Correlación NCHW agrupada: la implementación actual de m16-l02.
Los arreglos de referencia se generaron con torch.nn.functional.conv2d,
PyTorch 2.11.0 en CPU y float64, mediante la celda local siguiente. Las entradas
usan enteros exactamente representables; esta celda solo requiere NumPy.
"""
import numpy as np
from numpy.lib.stride_tricks import sliding_window_view
def _pair(value, name, minimum):
values = (value, value) if isinstance(value, (int, np.integer)) else tuple(value)
if (len(values) != 2 or any(not isinstance(v, (int, np.integer)) or isinstance(v, (bool, np.bool_))
or v < minimum for v in values)):
raise ValueError(name + ' debe contener dos enteros válidos')
return tuple(int(v) for v in values)
def _validate(x, weights, bias, stride, padding, dilation, groups):
x, weights = np.asarray(x, dtype=float), np.asarray(weights, dtype=float)
if x.ndim != 4 or weights.ndim != 4 or not x.size or not weights.size:
raise ValueError('Se esperan X NCHW y pesos OIHW no vacíos')
if not np.isfinite(x).all() or not np.isfinite(weights).all():
raise ValueError('Datos y pesos deben ser finitos')
if not isinstance(groups, (int, np.integer)) or isinstance(groups, (bool, np.bool_)) or groups < 1:
raise ValueError('groups debe ser un entero positivo')
n, cin, h, w = x.shape
cout, cgroup, kh, kw = weights.shape
if cin % groups or cout % groups or cgroup != cin//groups:
raise ValueError('Canales incompatibles con los grupos')
if bias is None:
bias = np.zeros(cout)
bias = np.asarray(bias, dtype=float)
if bias.shape != (cout,) or not np.isfinite(bias).all():
raise ValueError('Sesgo inválido')
sh, sw = _pair(stride, 'stride', 1)
ph, pw = _pair(padding, 'padding', 0)
dh, dw = _pair(dilation, 'dilation', 1)
effh, effw = dh*(kh-1)+1, dw*(kw-1)+1
oh, ow = (h+2*ph-effh)//sh+1, (w+2*pw-effw)//sw+1
if oh <= 0 or ow <= 0:
raise ValueError('El núcleo efectivo no cabe en la entrada extendida')
return x, weights, bias, (sh,sw), (ph,pw), (dh,dw), (oh,ow), int(groups)
def conv2d_im2col(x, weights, bias=None, stride=1, padding=0, dilation=1, groups=1, details=False):
x, w, b, (sh,sw), (ph,pw), (dh,dw), (oh,ow), groups = _validate(
x,weights,bias,stride,padding,dilation,groups)
n, cin, _, _ = x.shape
cout, cg, kh, kw = w.shape
effh, effw = dh*(kh-1)+1, dw*(kw-1)+1
padded = np.pad(x, ((0,0),(0,0),(ph,ph),(pw,pw)))
view = sliding_window_view(padded, (effh,effw), axis=(2,3))
view = view[:,:,::sh,::sw,::dh,::dw][:,:,:oh,:ow,:kh,:kw]
patches = view.reshape(n,groups,cg,oh,ow,kh,kw).transpose(0,1,3,4,2,5,6)
columns = np.ascontiguousarray(patches).reshape(n,groups,oh*ow,cg*kh*kw)
filters = w.reshape(groups,cout//groups,cg*kh*kw)
out = np.einsum('ngpd,god->ngop', columns, filters, optimize=False).reshape(n,cout,oh,ow)
out += b[None,:,None,None]
if details:
return out, {'shape': columns.shape, 'bytes': columns.nbytes,
'windows_share_padded': bool(np.shares_memory(view,padded)),
'columns_share_padded': bool(np.shares_memory(columns,padded))}
return out
# Los valores esperados son salidas reales de PyTorch CPU, no de esta función.
cases = [
('dos grupos', (1,4,3,3), (4,2,2,2), (1,1), (0,0), (1,1), 2, (1,4,2,2),
[4,1,-5,6,-10,5,0,8,-10,4,11,4,-1,-9,-11,-5]),
('paso y dilatación', (1,4,4,5), (6,2,2,2), (2,1), (1,0), (1,2), 2, (1,6,3,3),
[-5,2,2,-3,8,12,-1,-4,-7,17,0,-3,-7,-13,-12,-3,1,5,-6,-2,2,-1,6,-1,10,6,2,
-8,-5,-2,5,4,17,5,-6,-10,17,6,-5,-6,-3,-7,-4,-4,3,-3,-3,-3,-2,-5,-1,7,18,1]),
('profundidad, multiplicador dos', (1,3,3,3), (6,1,2,2), (1,1), (0,0), (1,1), 3, (1,6,2,2),
[8,6,-5,-7,-2,-3,-5,1,-7,0,14,0,-3,12,0,-6,-8,-6,5,7,-5,-7,10,8]),
]
for name, xs, ws, stride, padding, dilation, groups, shape, reference in cases:
x=(np.arange(np.prod(xs)).reshape(xs)%7-3).astype(float)
w=(np.arange(np.prod(ws)).reshape(ws)%5-2).astype(float)
b=(np.arange(ws[0])%3-1).astype(float)
actual, info = conv2d_im2col(x,w,b,stride,padding,dilation,groups,details=True)
expected=np.asarray(reference,dtype=float).reshape(shape)
assert actual.shape == shape and np.array_equal(actual,expected)
print(name, 'forma', actual.shape, 'error máximo respecto a PyTorch:', np.max(np.abs(actual-expected)))
print('columnas N,G,posiciones,ventana:', info['shape'])
print('salida aplanada:', actual.ravel().astype(int).tolist())
if name == 'dos grupos':
changed=x.copy(); changed[:,0] += 17
shifted=conv2d_im2col(changed,w,b,stride,padding,dilation,groups)
assert np.array_equal(shifted[:,2:],actual[:,2:]) and not np.array_equal(shifted[:,:2],actual[:,:2])
print('Cambiar un canal del primer grupo no altera las salidas del segundo.')
if name == 'profundidad, multiplicador dos':
for c in range(3):
independent=conv2d_im2col(x[:,c:c+1],w[2*c:2*c+2],b[2*c:2*c+2])
assert np.array_equal(independent,actual[:,2*c:2*c+2])
print('Cada entrada produce dos salidas sin mezclar otros canales.')
try:
conv2d_im2col(np.ones((1,4,3,3)),np.ones((4,2,2,2)),groups=3)
raise AssertionError('La división inválida de canales no se detectó')
except ValueError:
print('División de canales incompatible: rechazada.')The next local cell regenerates references with PyTorch. By default it prints results; if ORYON_GROUPED_REFERENCE_OUTPUT is set, it also saves them to the indicated file.
"""Genera referencias CPU de torch.nn.functional.conv2d, con datos explícitos."""
import json
import os
from pathlib import Path
import numpy as np
import torch
from torch.nn import functional as F
torch.set_num_threads(1)
cases = [
{'name':'dos_grupos', 'xshape':(1,4,3,3), 'wshape':(4,2,2,2),
'stride':(1,1), 'padding':(0,0), 'dilation':(1,1), 'groups':2},
{'name':'paso_y_dilatacion', 'xshape':(1,4,4,5), 'wshape':(6,2,2,2),
'stride':(2,1), 'padding':(1,0), 'dilation':(1,2), 'groups':2},
{'name':'profundidad_multiplicador_dos', 'xshape':(1,3,3,3), 'wshape':(6,1,2,2),
'stride':(1,1), 'padding':(0,0), 'dilation':(1,1), 'groups':3},
]
for case in cases:
x=(np.arange(np.prod(case['xshape'])).reshape(case['xshape'])%7-3).astype(np.float64)
w=(np.arange(np.prod(case['wshape'])).reshape(case['wshape'])%5-2).astype(np.float64)
b=(np.arange(case['wshape'][0])%3-1).astype(np.float64)
result=F.conv2d(torch.from_numpy(x),torch.from_numpy(w),torch.from_numpy(b),
stride=case['stride'],padding=case['padding'],dilation=case['dilation'],groups=case['groups'])
case['output']=result.tolist()
print(case['name'], 'forma', list(result.shape), 'salida', result.flatten().tolist(), flush=True)
payload={'torch_version':str(torch.__version__),'device':'cpu','dtype':'float64',
'construction':'x=(arange%7)-3, w=(arange%5)-2, b=(arange%3)-1', 'cases':cases}
output=os.environ.get('ORYON_GROUPED_REFERENCE_OUTPUT')
if output:
path=Path(output)
path.parent.mkdir(parents=True,exist_ok=True)
path.write_text(json.dumps(payload,ensure_ascii=False,indent=2),encoding='utf-8')
print('Referencias:',path,flush=True)
else:
print('Referencias JSON:',json.dumps(payload,ensure_ascii=True),flush=True)npm run lab and open the connection link.Lab: families with comparable budgets
The next experiment builds families at CIFAR-100 scale and keeps recipe and splits comparable. Parameter count is an approximate constraint, not mathematical equality: inspect figures printed by the code. Accuracy, peak memory, throughput and latency answer different questions. Keep test out of architecture and hyperparameter selection, and repeat seeds rather than treating one run as certainty. The short run checks the flow end to end; it is not a converged ranking or proof of architectural superiority.
Before interpreting a row, identify what accuracy represents: a checkpoint is chosen by validation loss and test is evaluated separately. Comparing several families on the same test makes their figures exploratory if you then choose by looking at test; reserve another evaluation to estimate the chosen model without that bias. All families share the experiment’s recipe, facilitating controlled comparison, but a common recipe may favor some architectures over others. A specific search with equal tuning budgets answers another question and must be described separately.
In the short check, ResNeXt reached validation loss of approximately 41.83 at step 20 and the criterion chose step 1; these brief curves do not demonstrate convergence. Output retains those results rather than presenting the table as a reliable ranking. Inspect curves and tune the recipe on validation if the full run is unstable; do not choose settings by looking at test.
"""DenseNet-BC, ResNeXt, Wide ResNet y ResNet-SE para CIFAR-100.
Experimento autocontenido: requiere PyTorch, NumPy, pyarrow, Pillow,
huggingface_hub y CUDA. ORYON_VERIFY_SHORT=1 reduce datos y pasos. Las
arquitecturas se han redimensionado para aproximar, no igualar, parámetros.
Las cifras de una prueba corta no reproducen los resultados de los artículos.
"""
import base64
import copy
import gc
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')
REVISION = 'aadb3af77e9048adbea6b47c21a81e47dd092ae5'
SEEDS = [16121] if SHORT else [16121, 16122, 16123]
BATCH = 64 if SHORT else 128
STEPS = 40 if SHORT else 64000
TRAIN_N, VALID_N, TEST_N = (20, 5, 5) if SHORT else (450, 50, 100)
AMP = DEVICE.type == 'cuda' and torch.cuda.is_bf16_supported()
class DenseLayer(nn.Module):
def __init__(self, cin, growth):
super().__init__()
self.block = nn.Sequential(nn.BatchNorm2d(cin), nn.ReLU(), nn.Conv2d(cin, 4*growth, 1, bias=False),
nn.BatchNorm2d(4*growth), nn.ReLU(), nn.Conv2d(4*growth, growth, 3, padding=1, bias=False))
def forward(self, x):
return torch.cat((x, self.block(x)), dim=1)
class DenseNetBC(nn.Module):
def __init__(self, growth=24, layers=4):
super().__init__()
width = 2*growth
self.stem = nn.Conv2d(3, width, 3, padding=1, bias=False)
self.blocks = nn.ModuleList()
self.transitions = nn.ModuleList()
for stage in range(3):
block = []
for _ in range(layers):
block.append(DenseLayer(width, growth))
width += growth
self.blocks.append(nn.Sequential(*block))
if stage < 2:
target = width//2
self.transitions.append(nn.Sequential(nn.BatchNorm2d(width), nn.ReLU(),
nn.Conv2d(width, target, 1, bias=False), nn.AvgPool2d(2)))
width = target
self.norm, self.fc = nn.BatchNorm2d(width), nn.Linear(width, 100)
def forward(self, x):
x = self.stem(x)
for i, block in enumerate(self.blocks):
x = block(x)
if i < 2:
x = self.transitions[i](x)
return self.fc(F.relu(self.norm(x)).mean((2, 3)))
class ResNeXtBlock(nn.Module):
def __init__(self, cin, cout, hidden, groups, stride):
super().__init__()
self.body = nn.Sequential(nn.Conv2d(cin, hidden, 1, bias=False), nn.BatchNorm2d(hidden), nn.ReLU(),
nn.Conv2d(hidden, hidden, 3, stride=stride, padding=1, groups=groups, bias=False),
nn.BatchNorm2d(hidden), nn.ReLU(), nn.Conv2d(hidden, cout, 1, bias=False), nn.BatchNorm2d(cout))
self.shortcut = nn.Sequential(nn.Conv2d(cin, cout, 1, stride=stride, bias=False), nn.BatchNorm2d(cout)) if stride != 1 or cin != cout else nn.Identity()
def forward(self, x):
return F.relu(self.body(x) + self.shortcut(x))
class ResNeXt(nn.Module):
def __init__(self, base=32, groups=4, blocks=2):
super().__init__()
self.stem = nn.Conv2d(3, 16, 3, padding=1, bias=False)
self.blocks = nn.ModuleList()
cin = 16
for stage in range(3):
hidden = base * 2**stage
cout = 2*hidden
for i in range(blocks):
stride = 2 if stage and i == 0 else 1
self.blocks.append(ResNeXtBlock(cin, cout, hidden, groups, stride))
cin = cout
self.fc = nn.Linear(cin, 100)
def forward(self, x):
x = self.stem(x)
for block in self.blocks:
x = block(x)
return self.fc(x.mean((2, 3)))
class SE(nn.Module):
def __init__(self, channels, reduction=16):
super().__init__()
hidden = max(1, channels//reduction)
self.fc1 = nn.Linear(channels, hidden)
self.fc2 = nn.Linear(hidden, channels)
self.last_gates = None
def forward(self, x):
gates = torch.sigmoid(self.fc2(F.relu(self.fc1(x.mean((2, 3))))))
self.last_gates = gates.detach()
return x * gates[:, :, None, None]
class BasicBlock(nn.Module):
"""Bloque preactivación de dos convoluciones; SE antes de la suma."""
def __init__(self, cin, cout, stride, se=False, dropout=0.):
super().__init__()
self.bn1 = nn.BatchNorm2d(cin)
self.conv1 = nn.Conv2d(cin, cout, 3, stride=stride, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(cout)
self.conv2 = nn.Conv2d(cout, cout, 3, padding=1, bias=False)
self.shortcut = nn.Conv2d(cin, cout, 1, stride=stride, bias=False) if stride != 1 or cin != cout else None
self.se = SE(cout) if se else nn.Identity()
self.dropout = nn.Dropout(dropout) if dropout else nn.Identity()
def forward(self, x):
activated = F.relu(self.bn1(x))
skip = x if self.shortcut is None else self.shortcut(activated)
residual = self.conv2(self.dropout(F.relu(self.bn2(self.conv1(activated)))))
return skip + self.se(residual)
class ResidualNet(nn.Module):
def __init__(self, width=32, blocks=2, se=False, dropout=0.):
super().__init__()
self.stem = nn.Conv2d(3, 16, 3, padding=1, bias=False)
self.blocks = nn.ModuleList()
cin = 16
for stage in range(3):
cout = width*2**stage
for i in range(blocks):
stride = 2 if stage and i == 0 else 1
self.blocks.append(BasicBlock(cin, cout, stride, se=se, dropout=dropout))
cin = cout
self.norm, self.fc = nn.BatchNorm2d(cin), nn.Linear(cin, 100)
def forward(self, x):
x = self.stem(x)
for block in self.blocks:
x = block(x)
return self.fc(F.relu(self.norm(x)).mean((2, 3)))
def make_model(name):
if name == 'densenet_bc':
return DenseNetBC(growth=31, layers=4)
if name == 'resnext':
return ResNeXt(base=48, groups=4, blocks=2)
if name == 'wide_resnet':
return ResidualNet(width=32, blocks=2)
if name == 'resnet_se':
return ResidualNet(width=25, blocks=3, se=True)
if name == 'resnet_deep':
return ResidualNet(width=19, blocks=5)
raise ValueError(name)
NAMES = ['densenet_bc', 'resnext', 'wide_resnet', 'resnet_se', 'resnet_deep']
def dataset_groups(split, seed):
path = hf_hub_download(repo_id='uoft-cs/cifar100', repo_type='dataset',
filename=f'cifar100/{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=['fine_label'])]).astype(np.int64)
generator = np.random.default_rng(seed)
return path, labels, [generator.permutation(np.flatnonzero(labels == k)) for k in range(100)]
def read_images(path, labels, indices):
indices = np.asarray(indices, dtype=np.int64)
positions = {int(idx): pos for pos, idx 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 j in range(batch.num_rows):
pos = positions.get(offset+j)
if pos is not None:
with Image.open(io.BytesIO(batch.column(0)[j].as_py()['bytes'])) as im:
images[pos] = np.asarray(im.convert('RGB'), dtype=np.uint8).transpose(2, 0, 1)
seen[pos] = 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 dataset():
path, labels, groups = dataset_groups('train', 16120)
train_ids = np.concatenate([g[:TRAIN_N] for g in groups])
valid_ids = np.concatenate([g[TRAIN_N:TRAIN_N+VALID_N] for g in groups])
path_t, labels_t, groups_t = dataset_groups('test', 16124)
test_ids = np.concatenate([g[:TEST_N] for g in groups_t])
assert not set(train_ids) & set(valid_ids)
return (read_images(path, labels, train_ids), read_images(path, labels, valid_ids),
read_images(path_t, labels_t, test_ids), train_ids, valid_ids, test_ids)
def stats(images):
total = torch.zeros(3, dtype=torch.float64, device=DEVICE)
square = torch.zeros_like(total)
count = 0
for part in images.split(256):
x = part.double()/255
total += x.sum((0, 2, 3))
square += x.square().sum((0, 2, 3))
count += len(x)*32*32
mu = total/count
std = (square/count-mu.square()).clamp_min(0).sqrt()
assert bool((std > 0).all())
return mu.float()[None, :, None, None], std.float()[None, :, None, None]
def augment(images, mean, std, generator):
x = images.float()/255
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, :]]
flip = torch.rand(n, generator=generator, device=DEVICE) < .5
x = torch.where(flip[:, None, None, None], x.flip(-1), x)
return ((x-mean)/std).contiguous(memory_format=torch.channels_last)
def inference(model, images, mean, std):
model.eval()
output = []
with torch.no_grad():
for batch in images.split(128):
x = ((batch.float()/255-mean)/std).contiguous(memory_format=torch.channels_last)
with torch.autocast(device_type='cuda', dtype=torch.bfloat16, enabled=AMP):
output.append(model(x).float().cpu())
return torch.cat(output)
def bench(model, images, mean, std):
"""Throughput en lote y latencia individual, sin incluir preprocesamiento."""
model.eval()
batch = ((images[:BATCH].float()/255-mean)/std).contiguous(memory_format=torch.channels_last)
single = batch[:1].contiguous(memory_format=torch.channels_last)
def measure(x, warmup, repeat):
with torch.no_grad(), torch.autocast(device_type='cuda', dtype=torch.bfloat16, enabled=AMP):
for _ in range(warmup):
model(x)
torch.cuda.synchronize()
start = time.perf_counter()
for _ in range(repeat):
model(x)
torch.cuda.synchronize()
return (time.perf_counter()-start)/repeat
batch_time = measure(batch, 5, 20)
with torch.no_grad(), torch.autocast(device_type='cuda', dtype=torch.bfloat16, enabled=AMP):
for _ in range(5):
model(single)
torch.cuda.synchronize()
samples = []
for _ in range(30):
start = time.perf_counter()
model(single)
torch.cuda.synchronize()
samples.append(time.perf_counter()-start)
latency = statistics.median(samples)
return {'batch_size': len(batch), 'batch_seconds': batch_time,
'images_per_second': len(batch)/batch_time, 'single_image_seconds': latency,
'single_image_samples': samples}
def train_one(name, seed, train_x, train_y, valid_x, valid_y, test_x, test_y, mean, std):
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
model = make_model(name).to(device=DEVICE, memory_format=torch.channels_last)
params = sum(p.numel() for p in model.parameters())
opt = torch.optim.SGD(model.parameters(), lr=.1, momentum=.9, weight_decay=.0001)
scheduler = torch.optim.lr_scheduler.MultiStepLR(opt, milestones=[STEPS//2, 3*STEPS//4], gamma=.1)
batch_g = torch.Generator(device=DEVICE).manual_seed(seed*100+1)
aug_g = torch.Generator(device=DEVICE).manual_seed(seed*100+2)
checkpoints = {1, STEPS//4, STEPS//2, 3*STEPS//4, STEPS}
history, failure = [], None
best_state, best_loss, best_step = None, float('inf'), None
baseline_alloc = torch.cuda.memory_allocated()
torch.cuda.reset_peak_memory_stats()
torch.cuda.synchronize()
start = time.perf_counter()
for step in range(1, STEPS+1):
model.train()
idx = torch.randint(len(train_x), (BATCH,), generator=batch_g, device=DEVICE)
x = augment(train_x[idx], mean, std, aug_g)
opt.zero_grad(set_to_none=True)
with torch.autocast(device_type='cuda', dtype=torch.bfloat16, enabled=AMP):
out = model(x)
loss = F.cross_entropy(out, train_y[idx])
if not bool(torch.isfinite(loss)):
failure = {'step': step, 'reason': 'pérdida no finita'}
break
loss.backward()
if not all(p.grad is None or bool(torch.isfinite(p.grad).all()) for p in model.parameters()):
failure = {'step': step, 'reason': 'gradiente no finito'}
break
opt.step()
scheduler.step()
if step in checkpoints:
logits = inference(model, valid_x, mean, std)
val_loss = float(F.cross_entropy(logits, valid_y.cpu()))
if not np.isfinite(val_loss):
failure = {'step': step, 'reason': 'validación no finita'}
break
row = {'step': step, 'batch_loss': float(loss.detach()), 'valid_loss': val_loss,
'valid_accuracy': float((logits.argmax(1)==valid_y.cpu()).float().mean())}
history.append(row)
if val_loss < best_loss:
best_loss, best_step = val_loss, step
best_state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
torch.cuda.synchronize()
train_seconds = time.perf_counter()-start
peak = torch.cuda.max_memory_allocated()
run = {'model': name, 'seed': seed, 'params': params, 'history': history, 'failure': failure,
'train_seconds_with_validation': train_seconds, 'cuda_peak_allocated_bytes': peak,
'cuda_baseline_allocated_bytes': baseline_alloc, 'best_step': best_step}
# Tras un fallo no se evalúa ni se presenta un checkpoint parcial.
if best_state is not None and failure is None:
model.load_state_dict(best_state)
logits = inference(model, test_x, mean, std)
if bool(torch.isfinite(logits).all()):
run['test_accuracy_exploratory'] = float((logits.argmax(1)==test_y.cpu()).float().mean())
else:
run['test_accuracy_exploratory'] = None
run['inference'] = bench(model, valid_x, mean, std)
# Evita que gradientes y momentum de una corrida contaminen la siguiente.
opt.zero_grad(set_to_none=True)
opt.state.clear()
return model, run
def save_short_se(model, valid_x, valid_y, valid_ids, mean, std, seed, best_step):
indices = np.linspace(0, len(valid_x)-1, 16, dtype=int)
batch = valid_x[indices]
logits = inference(model, batch, mean, std)
gates = [model.blocks[0].se.last_gates.float().cpu(), model.blocks[-1].se.last_gates.float().cpu()]
output = {'model': 'resnet_se_cifar100', 'seed': seed, 'best_step': best_step,
'description': ('ejecución corta elegida por validación; no se ha comprobado convergencia' if SHORT
else 'modelo entrenado desde cero y elegido por validación; convergencia no garantizada'),
'source': 'uoft-cs/cifar100 train, partición de validación', 'revision': REVISION,
'blocks': {'early': {'channels': gates[0].shape[1]}, 'deep': {'channels': gates[1].shape[1]}},
'images': []}
for i, pos in enumerate(indices):
buf = io.BytesIO()
Image.fromarray(valid_x[pos].permute(1, 2, 0).cpu().numpy(), mode='RGB').save(buf, format='PNG')
output['images'].append({'id': int(valid_ids[pos]), 'label': int(valid_y[pos]),
'png_base64': base64.b64encode(buf.getvalue()).decode('ascii'),
'logits': logits[i].tolist(),
'gates': {'early': gates[0][i].tolist(), 'deep': gates[1][i].tolist()}})
path = Path(os.environ.get('ORYON_CIFAR100_GATES_OUTPUT', 'm16-l12-cifar-se.json'))
path.write_text(json.dumps(output, ensure_ascii=False), encoding='utf-8')
def print_table(runs):
print('\nMedianas por arquitectura (solo corridas completas y finitas):', flush=True)
print('modelo n/fallos parametros val % test % pico MiB imagenes/s latencia ms', flush=True)
for name in NAMES:
selected = [r for r in runs if r['model'] == name]
valid = [r for r in selected if r['failure'] is None and r.get('inference') is not None
and r.get('test_accuracy_exploratory') is not None]
failed = len(selected)-len(valid)
if not valid:
print(f'{name:18s} {len(valid):2d}/{failed:<2d} sin resultados completos', flush=True)
continue
median = np.median
best_accuracy = [next(h['valid_accuracy'] for h in r['history'] if h['step'] == r['best_step']) for r in valid]
print(f"{name:18s} {len(valid):2d}/{failed:<2d} {valid[0]['params']:12d} "
f"{100*median(best_accuracy):8.2f} {100*median([r['test_accuracy_exploratory'] for r in valid]):8.2f} "
f"{median([r['cuda_peak_allocated_bytes'] for r in valid])/1024**2:9.1f} "
f"{median([r['inference']['images_per_second'] for r in valid]):11.1f} "
f"{1000*median([r['inference']['single_image_seconds'] for r in valid]):12.3f}", flush=True)
print('Pico CUDA allocated incluye datos residentes, parámetros, optimizador y activaciones; no es memoria exclusiva del modelo.', flush=True)
print(('La prueba corta verifica el circuito, no compara precisión ni demuestra convergencia; ' if SHORT else 'La convergencia no está garantizada; ')
+ 'el test es exploratorio y el tiempo depende de la carga compartida.', flush=True)
def warmup():
"""Inicializa kernels de cada arquitectura con datos ficticios, antes de medir."""
for name in NAMES:
model = make_model(name).to(device=DEVICE, memory_format=torch.channels_last)
x = torch.zeros((BATCH, 3, 32, 32), device=DEVICE).contiguous(memory_format=torch.channels_last)
y = torch.zeros(BATCH, dtype=torch.long, device=DEVICE)
model.train()
for _ in range(2):
model.zero_grad(set_to_none=True)
with torch.autocast(device_type='cuda', dtype=torch.bfloat16, enabled=AMP):
loss = F.cross_entropy(model(x), y)
loss.backward()
model.eval()
with torch.no_grad(), torch.autocast(device_type='cuda', dtype=torch.bfloat16, enabled=AMP):
model(x)
model(x[:1].contiguous(memory_format=torch.channels_last))
torch.cuda.synchronize()
del model, x, y, loss
gc.collect()
torch.cuda.empty_cache()
def main():
if DEVICE.type != 'cuda':
raise RuntimeError('Este laboratorio requiere CUDA')
(train_x, train_y), (valid_x, valid_y), (test_x, test_y), train_ids, valid_ids, test_ids = dataset()
mean, std = stats(train_x)
counts = {name: sum(p.numel() for p in make_model(name).parameters()) for name in NAMES}
print('Parámetros:', counts, flush=True)
assert max(counts.values())/min(counts.values()) < 1.07
warmup()
output = {'protocol': {'revision': REVISION, 'short': SHORT, 'steps': STEPS, 'batch_size': BATCH,
'seeds': SEEDS, 'train_split_seed': 16120, 'test_split_seed': 16124,
'train_per_class': TRAIN_N, 'valid_per_class': VALID_N, 'test_per_class': TEST_N,
'gpu': torch.cuda.get_device_name(DEVICE), 'torch_version': str(torch.__version__),
'cuda_version': str(torch.version.cuda), 'cudnn_version': torch.backends.cudnn.version(),
'normalization_mean': mean.flatten().cpu().tolist(), 'normalization_std': std.flatten().cpu().tolist(),
'training': 'SGD momentum 0.9, lr 0.1, decay 0.0001, hitos 50% y 75%, crop reflect y flip',
'selection': 'menor pérdida de validación entre cinco puntos',
'memory': 'pico CUDA allocated total: incluye datos residentes, parámetros, optimizador y activaciones',
'latency': 'eval sin preprocesamiento; throughput de lotes amortizado y latencia individual como mediana de 30 peticiones sincronizadas tras warmup; tiempos orientativos bajo carga compartida',
'test': 'test separado, exploratorio por la comparación de arquitecturas', 'amp_bfloat16': AMP,
'parameters': counts, 'dropout_wrn': 0}, 'runs': []}
outpath = Path(os.environ.get('ORYON_CIFAR100_OUTPUT', 'm16-l12-cifar100.json'))
for name in NAMES:
for seed in SEEDS:
model, run = train_one(name, seed, train_x, train_y, valid_x, valid_y, test_x, test_y, mean, std)
if name == 'resnet_se' and seed == SEEDS[0] and run['best_step'] is not None and run['failure'] is None:
save_short_se(model, valid_x, valid_y, valid_ids, mean, std, seed, run['best_step'])
output['runs'].append(run)
outpath.write_text(json.dumps(output, ensure_ascii=False, indent=2, allow_nan=False), encoding='utf-8')
print(json.dumps(run, ensure_ascii=False), flush=True)
del model
gc.collect()
torch.cuda.empty_cache()
print_table(output['runs'])
if __name__ == '__main__':
main()npm run lab and open the connection link.Exercises
Step 1 of 3. What should the first 1×1 produce?
import torch
from torch import nn
class SEBlock(nn.Module):
def __init__(self, channels, reduction):
super().__init__()
def forward(self, x):
passCheck your results with these reproducible calculations:
initial, growth, layer = 64, 32, 12
print('Entrada de la capa 12:', initial + (layer-1)*growth)
for groups in (1, 4, 32, 128):
print('Grupos:', groups, 'pesos sin sesgo:', 128*(128//groups)*3*3)
for c, k in ((32, 12), (96, 12)):
print('c, k, cuello, directo:', c, k, 4*k*c + 36*k*k, 9*c*k)