ResNet: residual learning and hundred-layer networks
Study degradation in deep networks, residual and preactivation blocks, ResNet architectures and path expansions, with controlled gradient, parity and ablation experiments.
After this lesson you can
- Explain the degradation problem and distinguish training error from overfitting.
- Derive the direct gradient term of identity residual blocks and its limitations.
- Implement basic and bottleneck blocks with shape-safe shortcuts.
- Compare ImageNet and CIFAR ResNet families and their computational cost.
- Interpret residual path counts and evaluate block removal cautiously.
Before you start
When adding layers worsens the fit
Imagine a trained network and a deeper one built by inserting identity layers. The second contains, at least in principle, a solution as good as the first. That does not force the optimizer to find it. He and colleagues observed that under their recipe a 56-layer plain network had higher training error than a 20-layer one on CIFAR-10. Since it fails even on fitting examples, that observation is not explained simply by saying the deeper network overfits. The paper calls this optimization behavior the degradation problem.
The following comparison uses another experiment from the same paper: ImageNet validation evaluation with ten crops. Select a depth and compare both families. A validation difference alone does not diagnose degradation; training curves are also needed, as shown in figures 1 and 4 of the original work.
In table 2, going from 18 to 34 layers increases plain-network top-1 validation error from 27.94% to 28.54%, whereas residual error goes from 27.88% to 25.03%. These figures belong to that experiment, not a universal law for all deep networks. The original networks use batch normalization; the authors also observed healthy gradient norms in their plain network. Therefore do not automatically equate degradation with vanishing gradients.
Learning a correction
An identity residual block computes . Instead of requiring the branch to learn a full transform , parameterize and approximate identity by making small. Addition requires both tensors to have exactly the same shape. A channel or resolution change needs explicit shortcut adaptation; allowing accidental broadcasting does not implement the intended block.
For differentiable blocks of equal dimension and no operations after addition, telescoping gives
Each summand’s total derivative includes dependence of on . If loss depends on only through in this segment, column gradients and the chain rule give
There is a direct identity term, but it does not guarantee a nonzero gradient: if , its Jacobian exactly cancels that term. Amplification or ill-conditioned directions can also arise. An auxiliary loss connected to an intermediate state adds its own gradient term. Interpretation depends on the Jacobian product’s spectrum, not just a plus sign; connect this with signal propagation and variance. At nondifferentiable ReLU points the library’s derivative convention is used.
More precisely, for one block with , the Jacobian is . If the spectral norm of is strictly less than one, the reverse triangle inequality gives for every vector : that block nulls no direction. However, chaining many blocks can make the product of those bounds approach zero. Looking only at eigenvalues is also insufficient: non-normal matrices can stretch and contract vectors in ways separate eigenvalues do not reveal. Norm guarantees depend on singular values of the full product.
The following cell calculates a two-dimensional case. The first branch makes the Jacobian singular and erases a direction; in the second every factor is invertible, but repetition attenuates a direction. This constructed example checks the derivation; it is not a ResNet measurement.
import numpy as np
identidad = np.eye(2)
cancelacion = identidad + np.diag([-1.0, 0.2])
factor = identidad + np.diag([-0.1, 0.2])
producto = np.linalg.matrix_power(factor, 10)
print('jacobiano singular:', cancelacion)
print('valores singulares de diez bloques:', np.linalg.svd(producto, compute_uv=False))
print('producto exacto esperado:', 1.2**10, 0.9**10)The preceding model supports reasoning but is not a CNN measurement. In the next local cell’s short trial, choose depth, seed and step to observe real errors and gradient norms. Recorded norms are for weights of one convolution in each block, not the gradient with respect to the scalar model’s state. Step 1 measures gradients before the first update and errors after it. Test was consulted at every point and is therefore exploratory; checkpoints were selected using validation only.
Shapes, blocks and shortcuts
A ResNet v1 basic block uses two 3×3 convolutions with BN and ReLU between them; after the second BN it adds the shortcut and applies ReLU. The bottleneck uses 1×1 to reduce channels, 3×3 in the reduced space and another 1×1 to expand them. This reuses 1×1 convolutional channel mixing. Savings depend on widths and resolution: calculate operations rather than assuming them.
When shape changes, the paper studies shortcuts that subsample and zero-pad channels, and learned 1×1 projections with appropriate stride. These are different choices: a projection is not a mathematical identity and adds parameters. ResNet v1 applies ReLU after addition, so its derivative can mask the shortcut path. A preactivation block instead places BN and ReLU before convolutions and no activation after addition. Between dimension changes it thus offers a clean identity path. The preactivation paper reports CIFAR-10 errors of 6.61% and 6.37% for ResNet-110 v1 and preactivated respectively under its protocols; do not attribute that difference to one detail without controlling the recipe.
For example, if input is and the next stage produces , the unchanged identity cannot be added to the residual. Shortcut A takes positions with stride 2 and adds 16 zero channels; the learned projection uses a stride-two 1×1 convolution. Both outputs have compatible shape, but their values, parameters and derivatives differ. Check the complete shape before addition: a size-one dimension could allow broadcasting without an error and hide a design flaw.
BN also changes behavior between training and evaluation. In training it uses batch statistics; in evaluation it normally uses accumulated statistics. Since an example’s training result depends on other batch examples, in the derivation above you can regard as the entire batch tensor and use the full Jacobian with cross-dependencies. To compare weights and predictions, put both models in evaluation mode and feed exactly the same tensors. To compare training, control batch size, augmentation, optimizer, seed, budget and checkpoint selection. An error curve on a small training subset is a probe, not exact error across all fitting data.
He initialization and BN influence the initial signal. Another option is to zero the final BN factor in each residual branch. If its bias is also zero, the branch begins with zero output; in the v1 block output is still ReLU of the shortcut, not necessarily identity. This does not automatically turn a projection into identity either. Torchvision documents the option, which also changes initial gradient flow into the branch. Compare it in a controlled way with He initialization, not as a universal requirement.
Two ResNet families
The ImageNet ResNet architecture has a stride-two 7×7 stem and max pooling, four stages, global spatial averaging and a classifier. ResNet-18 and 34 use basic blocks; 50, 101 and 152 use bottlenecks. On 32×32 images that stem reduces resolution early. The paper’s CIFAR family uses a 3×3 stem and three stages of 16, 32 and 64 channels. With two-convolution blocks per stage, depth is : 20 layers corresponds to and 56 to .
On ImageNet, ResNet-18’s four stages contain 2, 2, 2 and 2 blocks; each contributes two convolutions, plus the stem convolution and classifier. ResNet-50 uses 3, 4, 6 and 3 bottlenecks of three convolutions each, plus stem and classifier. Shortcut projection convolutions are not included in that depth name. The count is a family convention, not the number of all executed modules.
Do not confuse depth counted by convolutions and classifier with block count. Torchvision’s ResNet-50 variant places reduction stride in the bottleneck’s 3×3 convolution, while the original description places it in the first 1×1. Shapes and parameter count may match even when functions differ. To load weights and obtain the same prediction, also copy operation order and stride position. Official implementations report 11,689,512 parameters for ResNet-18 and 25,557,032 for ResNet-50, with 1000 classes.
The following counter uses an explicit convention: bias-free convolutions, excluding BN and activations, and two FLOPs per MAC. Compare parameters with work for one image. Real time also depends on memory and kernels, as seen in CNN performance.
from math import comb
spatial, channels, inner = 14, 256, 64
basic = 2 * 9 * channels * channels
bottle = channels * inner + 9 * inner * inner + inner * channels
for name, weights in [('básico', basic), ('bottleneck', bottle)]:
print(name, 'pesos', weights, 'MAC', weights * spatial**2,
'FLOP', 2 * weights * spatial**2)
print('rutas centrales en 54 bloques:', comb(54, 27))
print('longitud media uniforme:', 54 / 2)A sum of paths, carefully
The path-ensemble view arises by expanding the Jacobian product , where is evaluated at on a particular trajectory. For blocks there are selections of residual branches. This counts algebraic terms, not independent models: they share weights, Jacobians depend on the trajectory and magnitudes and signs can differ. In general a nonlinear function also cannot be distributed over a sum.
Veit, Wilber and Belongie studied a 110-layer CIFAR ResNet and estimated gradient contributions by sampling. In their analysis, paths of 5 to 17 modules concentrate almost all estimated magnitude and represent only 0.45% of combinations. Their deletion experiment retains shortcuts; when deleting a branch with projection, it is essential to define what happens to the shape transform. A gradual drop in one experiment does not prove any block or set can be removed without consequence.
With input and trajectory fixed, each matrix is concrete and matrix distributivity justifies expanding while preserving multiplication order. A term’s length counts how many factors appear. The terms of one length can have very different norms or cancel. The binomial histogram is therefore a combinatorial count. Measuring importance requires specifying the observed quantity, how terms are sampled and what is held fixed when a branch is removed.
Residual addition has conceptual relatives in the transformer residual stream and the additive path of an LSTM cell, though their gates and operations differ. Writing resembles an Euler step; interpreting it as an ODE also requires specifying the limit, scale and how varies. Algebraic similarity alone does not prove a trained ResNet precisely discretizes continuous dynamics.
Local lab: depth, parity and deletion
The following lab implements CIFAR models and compares plain and residual networks under the same recipe, records training and gradients, and separates training, validation and test. Set the full budget for your GPU; the short verification via ORYON_VERIFY_SHORT=1 checks the procedure works but does not itself reproduce the paper’s full-training curves. To test architecture parity, compare shapes, parameters and predictions of custom implementations with torchvision using the same weights. Deletion analysis evaluates without retraining and must retain shape adaptations; do not extrapolate a short measurement to all depths.
Custom ResNet and torchvision parity
The test loads the same state into both models, compares each stage and evaluation logits and reports whether it used official or initialized weights. If ResNet-50 is not in the common cache, enable ORYON_DOWNLOAD_RESNET50=1 to download official weights. Random tensors check numerical parity, not classification accuracy.
"""ResNet propia compatible con ResNet18 y ResNet50 de torchvision.
Comprueba claves, parámetros y salidas con pesos idénticos; carga pesos oficiales
si están en la caché. ORYON_DOWNLOAD_RESNET50=1 permite descargar el checkpoint
de 50 capas si falta. ORYON_VERIFY_SHORT=1 usa una imagen más pequeña.
ORYON_RESNET_PARITY_OUTPUT elige el JSON de salida.
"""
import json
import os
from pathlib import Path
from urllib.parse import urlparse
import torch
from torch import nn
from torchvision.models import ResNet18_Weights, ResNet50_Weights, resnet18, resnet50
torch.set_num_threads(1)
short = os.environ.get('ORYON_VERIFY_SHORT') == '1'
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def conv3(cin, cout, stride=1):
return nn.Conv2d(cin, cout, 3, stride=stride, padding=1, bias=False)
def conv1(cin, cout, stride=1):
return nn.Conv2d(cin, cout, 1, stride=stride, bias=False)
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None):
super().__init__()
self.conv1 = conv3(inplanes, planes, stride)
self.bn1 = nn.BatchNorm2d(planes)
self.relu = nn.ReLU(inplace=True)
self.conv2 = conv3(planes, planes)
self.bn2 = nn.BatchNorm2d(planes)
self.downsample = downsample
self.stride = stride
def forward(self, x):
identity = x if self.downsample is None else self.downsample(x)
out = self.relu(self.bn1(self.conv1(x)))
out = self.bn2(self.conv2(out))
if out.shape != identity.shape:
raise ValueError('El atajo no coincide en forma con el residuo')
return self.relu(out + identity)
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super().__init__()
self.conv1 = conv1(inplanes, planes)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = conv3(planes, planes, stride)
self.bn2 = nn.BatchNorm2d(planes)
self.conv3 = conv1(planes, planes * self.expansion)
self.bn3 = nn.BatchNorm2d(planes * self.expansion)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
def forward(self, x):
identity = x if self.downsample is None else self.downsample(x)
out = self.relu(self.bn1(self.conv1(x)))
out = self.relu(self.bn2(self.conv2(out)))
out = self.bn3(self.conv3(out))
if out.shape != identity.shape:
raise ValueError('El atajo no coincide en forma con el residuo')
return self.relu(out + identity)
class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000, zero_init_residual=False):
super().__init__()
if len(layers) != 4 or any(not isinstance(n, int) or n < 1 for n in layers):
raise ValueError('Se requieren cuatro etapas no vacías')
self.inplanes = 64
self.conv1 = nn.Conv2d(3, 64, 7, stride=2, padding=3, bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(3, stride=2, padding=1)
self.layer1 = self._make_layer(block, 64, layers[0])
self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.fc = nn.Linear(512 * block.expansion, num_classes)
for module in self.modules():
if isinstance(module, nn.Conv2d):
nn.init.kaiming_normal_(module.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(module, nn.BatchNorm2d):
nn.init.ones_(module.weight)
nn.init.zeros_(module.bias)
if zero_init_residual:
for module in self.modules():
if isinstance(module, Bottleneck):
nn.init.zeros_(module.bn3.weight)
elif isinstance(module, BasicBlock):
nn.init.zeros_(module.bn2.weight)
def _make_layer(self, block, planes, count, stride=1):
outplanes = planes * block.expansion
projection = None
if stride != 1 or self.inplanes != outplanes:
projection = nn.Sequential(conv1(self.inplanes, outplanes, stride), nn.BatchNorm2d(outplanes))
layers = [block(self.inplanes, planes, stride, projection)]
self.inplanes = outplanes
layers.extend(block(self.inplanes, planes) for _ in range(1, count))
return nn.Sequential(*layers)
def forward(self, x):
x = self.maxpool(self.relu(self.bn1(self.conv1(x))))
for stage in (self.layer1, self.layer2, self.layer3, self.layer4):
x = stage(x)
return self.fc(self.avgpool(x).flatten(1))
def compare(name, block, layers, builder, weights):
torch.manual_seed(16091)
reference = builder(weights=None).to(device).eval()
checkpoint = Path(torch.hub.get_dir()) / 'checkpoints' / Path(urlparse(weights.url).path).name
available = checkpoint.is_file()
if available:
state = torch.load(checkpoint, map_location='cpu', weights_only=True)
reference.load_state_dict(state, strict=True)
provenance = 'pesos oficiales desde caché local'
elif name == 'resnet50' and os.environ.get('ORYON_DOWNLOAD_RESNET50') == '1':
state = weights.get_state_dict(progress=True, check_hash=True)
reference.load_state_dict(state, strict=True)
provenance = 'pesos oficiales descargados a caché común'
else:
provenance = 'inicialización de torchvision sin pesos preentrenados'
own = ResNet(block, layers).to(device).eval()
own.load_state_dict(reference.state_dict(), strict=True)
assert list(own.state_dict()) == list(reference.state_dict())
count = sum(p.numel() for p in own.parameters())
assert count == sum(p.numel() for p in reference.parameters())
captures = {'own': {}, 'reference': {}}
hooks = []
for key, model in [('own', own), ('reference', reference)]:
for stage in ('layer1', 'layer2', 'layer3', 'layer4'):
def collect(_module, _inputs, output, key=key, stage=stage):
captures[key][stage] = output.detach().clone()
hooks.append(getattr(model, stage).register_forward_hook(collect))
side = 64 if short else 224
generator = torch.Generator(device=device).manual_seed(16910)
x = torch.randn(1, 3, side, side, device=device, generator=generator)
try:
with torch.inference_mode():
a, b = own(x), reference(x)
finally:
for hook in hooks:
hook.remove()
output_error = float((a - b).abs().max().cpu())
stage_errors = {stage: float((captures['own'][stage] - captures['reference'][stage]).abs().max().cpu())
for stage in ('layer1', 'layer2', 'layer3', 'layer4')}
shapes = {stage: list(captures['own'][stage].shape) for stage in stage_errors}
assert max([output_error, *stage_errors.values()]) < 1e-5
print(name, 'parámetros', count, 'origen', provenance, 'error máximo', output_error, 'formas', shapes, flush=True)
del own, reference, captures, x, a, b
if device.type == 'cuda':
torch.cuda.empty_cache()
return {'model': name, 'parameters': count, 'weight_source': provenance, 'input_side': side,
'logit_max_abs_error': output_error, 'stage_max_abs_errors': stage_errors, 'stage_shapes': shapes}
def main():
rows = [compare('resnet18', BasicBlock, [2, 2, 2, 2], resnet18, ResNet18_Weights.IMAGENET1K_V1),
compare('resnet50', Bottleneck, [3, 4, 6, 3], resnet50, ResNet50_Weights.IMAGENET1K_V1)]
result = {'short': short, 'device': str(device), 'torch_version': torch.__version__, 'comparisons': rows,
'bottleneck_stride': '3x3, igual a torchvision ResNet v1.5',
'input': 'tensor aleatorio compartido, no una evaluación de precisión'}
output = Path(os.environ.get('ORYON_RESNET_PARITY_OUTPUT', 'm16-l09-resnet-paridad.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:
main()
finally:
if device.type == 'cuda':
torch.cuda.empty_cache()npm run lab and open the connection link.A preactivation block
This block applies BN and ReLU before each convolution. When there is a projection, it applies it to the preactivated state; when shape is unchanged, the shortcut preserves x exactly. The test zeros the second convolution to isolate the identity path, without claiming a trained network will always have zero residual.
import torch
from torch import nn
class PreActBlock(nn.Module):
def __init__(self, cin, cout, stride=1):
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.projection = (None if stride == 1 and cin == cout else
nn.Conv2d(cin, cout, 1, stride=stride, bias=False))
def forward(self, x):
activated = torch.relu(self.bn1(x))
shortcut = x if self.projection is None else self.projection(activated)
residual = self.conv2(torch.relu(self.bn2(self.conv1(activated))))
if shortcut.shape != residual.shape:
raise ValueError('Atajo y residuo tienen formas incompatibles')
return shortcut + residual
torch.manual_seed(1609)
x = torch.randn(2, 8, 8, 8)
block = PreActBlock(8, 8).eval()
with torch.no_grad():
block.conv2.weight.zero_()
error = (block(x) - x).abs().max().item()
changed = PreActBlock(8, 16, 2).eval()(x)
assert error == 0.0 and changed.shape == (2, 16, 4, 4)
print('error identidad', error, 'forma con proyección', tuple(changed.shape))npm run lab and open the connection link.Depth and deletion on CIFAR-10
Normal mode trains 20- and 56-layer plain and residual networks; ORYON_EXTRA_DEPTHS=1 separately runs 32, 44 and 110. To train CIFAR-adapted ResNet-18, instead enable ORYON_RESNET18_CIFAR=1: it uses a 3×3 stem, no initial max pooling and transition projections. The two extra modes are mutually exclusive and by default write different files. To reproduce figure data use ORYON_VERIFY_SHORT=1 in CIFAR-depth runs. The short test records three seeds for 20 and 56, and one for the others; ResNet-18 is also checked with one seed. In that 100-step test, ResNet-18 remains near chance: 11.5% validation accuracy and 10% exploratory test. It verifies the program works but does not demonstrate convergence. Nonfinite metrics remain missing and the run reports the failure: they are not 100% classification error. Test is repeatedly evaluated, used in another lesson and also used for exploratory deletion; reserve another set if independent final evaluation is needed. Deletion replaces shape-compatible blocks with identity without retraining and leaves transitions intact. It selects three positions among shape-preserving blocks and evaluates each separately and all three together; this is not an exhaustive sweep of all blocks.
"""CIFAR-10: redes 6n+2 planas y residuales, gradientes y borrado.
Requiere torch, numpy, pillow, pyarrow y huggingface_hub. La lectura por tandas
reutiliza el protocolo de la lección anterior. ORYON_VERIFY_SHORT=1 reduce los
datos y pasos para comprobar el programa de principio a fin; el modo normal es
el experimento del lector. ORYON_CIFAR_RESNET_OUTPUT selecciona el JSON.
ORYON_EXTRA_DEPTHS=1 estudia 32, 44 y 110 capas en un archivo independiente.
ORYON_RESNET18_CIFAR=1 entrena por separado ResNet-18 adaptada a 32×32.
"""
import io
import json
import math
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)
torch.backends.cudnn.benchmark = False
short = os.environ.get('ORYON_VERIFY_SHORT') == '1'
extra_depths = os.environ.get('ORYON_EXTRA_DEPTHS') == '1'
resnet18_cifar = os.environ.get('ORYON_RESNET18_CIFAR') == '1'
if extra_depths and resnet18_cifar:
raise ValueError('Selecciona solo uno de los modos adicionales')
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
if device.type != 'cuda':
raise RuntimeError('Este laboratorio está configurado para CUDA')
amp = torch.cuda.is_bf16_supported()
revision = '0b27149'
seeds = [16091] if short and (extra_depths or resnet18_cifar) else [16091, 16092, 16093]
depths = [18] if resnet18_cifar else [32, 44, 110] if extra_depths else [20, 56]
batch_size = 64 if short else 128
steps = 100 if short else 64000
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(g) < count for g in groups):
raise ValueError('Insuficientes imágenes para la partición')
return path, labels, groups
def read_selected(path, labels, indices):
indices = np.asarray(indices, dtype=np.int64)
positions = {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 = positions.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('Forma CIFAR incorrecta')
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 dataset():
path, 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])
path_test, labels_test, test_groups = choose_indices('test', test_per_class, 16074)
test_ids = np.concatenate([g[:test_per_class] for g in test_groups])
assert not set(train_ids) & set(valid_ids)
return (read_selected(path, labels, train_ids), read_selected(path, labels, valid_ids),
read_selected(path_test, labels_test, test_ids), train_ids.tolist(), valid_ids.tolist(), test_ids.tolist())
def stats(images):
total = torch.zeros(3, dtype=torch.float64, device=device)
squares = torch.zeros_like(total)
count = 0
for i in range(0, len(images), 256):
batch = images[i:i + 256].to(torch.float64) / 255
total += batch.sum((0, 2, 3))
squares += batch.square().sum((0, 2, 3))
count += batch.shape[0] * 32 * 32
mean = total / count
std = (squares / count - mean.square()).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, :]]
flip = torch.rand(n, generator=generator, device=device) < .5
x = torch.where(flip[:, 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 PadShortcut(nn.Module):
"""Atajo CIFAR opción A: submuestreo y canales añadidos con ceros."""
def __init__(self, cin, cout, stride):
super().__init__()
if stride not in (1, 2) or cout < cin:
raise ValueError('Cambio de forma no admitido')
self.cin, self.cout, self.stride = cin, cout, stride
def forward(self, x):
x = x[:, :, ::self.stride, ::self.stride]
delta = self.cout - self.cin
left, right = delta // 2, delta - delta // 2
return torch.cat((x.new_zeros((len(x), left, *x.shape[2:])), x,
x.new_zeros((len(x), right, *x.shape[2:]))), dim=1)
class CIFARBlock(nn.Module):
def __init__(self, cin, cout, stride, residual):
super().__init__()
self.conv1 = nn.Conv2d(cin, cout, 3, stride=stride, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(cout)
self.conv2 = nn.Conv2d(cout, cout, 3, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(cout)
self.shortcut = PadShortcut(cin, cout, stride) if stride != 1 or cin != cout else nn.Identity()
self.residual = residual
self.can_delete = stride == 1 and cin == cout
self.deleted = False
def forward(self, x):
if self.deleted:
if not self.can_delete:
raise ValueError('No se puede borrar un bloque que cambia la forma')
return x
out = F.relu(self.bn1(self.conv1(x)))
out = self.bn2(self.conv2(out))
if self.residual:
identity = self.shortcut(x)
if identity.shape != out.shape:
raise ValueError('El atajo y el residuo deben tener la misma forma')
out = out + identity
return F.relu(out)
class PreActBlock(nn.Module):
"""Identidad limpia cuando no cambia la forma, sin ReLU tras la suma."""
def __init__(self, cin, cout, stride=1):
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.projection = nn.Conv2d(cin, cout, 1, stride=stride, bias=False) if cin != cout or stride != 1 else None
def forward(self, x):
activated = F.relu(self.bn1(x))
shortcut = x if self.projection is None else self.projection(activated)
out = self.conv2(F.relu(self.bn2(self.conv1(activated))))
if shortcut.shape != out.shape:
raise ValueError('El atajo y el residuo deben tener la misma forma')
return shortcut + out
class CIFAR18Block(nn.Module):
"""Bloque básico con proyección 1×1 cuando cambia la forma."""
def __init__(self, cin, cout, stride=1):
super().__init__()
self.conv1 = nn.Conv2d(cin, cout, 3, stride=stride, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(cout)
self.conv2 = nn.Conv2d(cout, cout, 3, padding=1, bias=False)
self.bn2 = 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())
self.can_delete = stride == 1 and cin == cout
self.deleted = False
def forward(self, x):
if self.deleted:
if not self.can_delete:
raise ValueError('No se puede borrar un bloque que cambia la forma')
return x
out = self.bn2(self.conv2(F.relu(self.bn1(self.conv1(x)))))
identity = self.shortcut(x)
if identity.shape != out.shape:
raise ValueError('El atajo y el residuo deben tener la misma forma')
return F.relu(out + identity)
class CIFARResNet18(nn.Module):
"""Tallo 3×3 y cuatro etapas [2,2,2,2], sin max pooling inicial."""
def __init__(self, zero_init=False):
super().__init__()
self.stem = nn.Sequential(nn.Conv2d(3, 64, 3, padding=1, bias=False), nn.BatchNorm2d(64), nn.ReLU())
self.blocks = nn.ModuleList()
channels = 64
for stage, width in enumerate((64, 128, 256, 512)):
for i in range(2):
stride = 2 if stage > 0 and i == 0 else 1
self.blocks.append(CIFAR18Block(channels, width, stride))
channels = width
self.fc = nn.Linear(512, 10)
for module in self.modules():
if isinstance(module, nn.Conv2d):
nn.init.kaiming_normal_(module.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(module, nn.BatchNorm2d):
nn.init.ones_(module.weight)
nn.init.zeros_(module.bias)
if zero_init:
for block in self.blocks:
nn.init.zeros_(block.bn2.weight)
def forward(self, x):
x = self.stem(x)
for block in self.blocks:
x = block(x)
return self.fc(x.mean(dim=(2, 3)))
class CIFARNet(nn.Module):
def __init__(self, depth, residual=True, zero_init=False):
super().__init__()
if depth < 8 or (depth - 2) % 6:
raise ValueError('La profundidad debe ser 6n+2 con n positivo')
n = (depth - 2) // 6
self.stem = nn.Sequential(nn.Conv2d(3, 16, 3, padding=1, bias=False), nn.BatchNorm2d(16), nn.ReLU())
self.blocks = nn.ModuleList()
channels = 16
for stage, width in enumerate((16, 32, 64)):
for i in range(n):
stride = 2 if stage > 0 and i == 0 else 1
self.blocks.append(CIFARBlock(channels, width, stride, residual))
channels = width
self.fc = nn.Linear(64, 10)
for module in self.modules():
if isinstance(module, nn.Conv2d):
nn.init.kaiming_normal_(module.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(module, nn.BatchNorm2d):
nn.init.ones_(module.weight)
nn.init.zeros_(module.bias)
if zero_init and residual:
for block in self.blocks:
nn.init.zeros_(block.bn2.weight)
def forward(self, x):
x = self.stem(x)
for block in self.blocks:
x = block(x)
return self.fc(x.mean(dim=(2, 3)))
def verify_blocks():
x = torch.randn(2, 16, 8, 8, device=device)
for residual in (False, True):
model = CIFARBlock(16, 32, 2, residual).to(device).eval()
assert model(x).shape == (2, 32, 4, 4)
identity = PreActBlock(16, 16).to(device).eval()
projection = PreActBlock(16, 32, 2).to(device).eval()
assert identity(x).shape == x.shape and projection(x).shape == (2, 32, 4, 4)
with torch.no_grad():
identity.conv2.weight.zero_()
assert torch.equal(identity(x), x)
for depth in (20, 56):
net = CIFARNet(depth).to(device).eval()
assert len(net.blocks) == 3 * ((depth - 2) // 6)
assert net(torch.zeros(1, 3, 32, 32, device=device)).shape == (1, 10)
if resnet18_cifar:
from torchvision.models import resnet18
net18 = CIFARResNet18().to(device).eval()
assert len(net18.blocks) == 8 and net18(torch.zeros(1, 3, 32, 32, device=device)).shape == (1, 10)
reference = resnet18(weights=None, num_classes=10)
reference.conv1 = nn.Conv2d(3, 64, 3, padding=1, bias=False)
reference.maxpool = nn.Identity()
renamed = {}
for name, value in net18.state_dict().items():
if name.startswith('stem.0.'):
target = 'conv1.' + name[len('stem.0.'):]
elif name.startswith('stem.1.'):
target = 'bn1.' + name[len('stem.1.'):]
elif name.startswith('blocks.'):
_, index, tail = name.split('.', 2)
index = int(index)
if tail.startswith('shortcut.'):
tail = 'downsample.' + tail[len('shortcut.'):]
target = f'layer{index // 2 + 1}.{index % 2}.{tail}'
else:
target = name
renamed[target] = value
reference.load_state_dict(renamed, strict=True)
reference = reference.to(device).eval()
x18 = torch.randn(1, 3, 32, 32, device=device)
with torch.inference_mode():
error = float((net18(x18) - reference(x18)).abs().max().cpu())
assert error < 1e-5
print('ResNet-18 CIFAR frente a torchvision adaptada, error máximo:', error, flush=True)
del net18, reference, renamed, x18
torch.cuda.empty_cache()
print('Formas, proyección, identidad preactivada y profundidad: comprobadas', flush=True)
def evaluate(model, images, labels, mean, std):
model.eval()
correct, loss_sum = 0, 0.
with torch.inference_mode():
for i in range(0, len(images), 128):
z = model(preprocess(images[i:i + 128], mean, std))
target = labels[i:i + 128]
if not bool(torch.isfinite(z).all()):
return {'accuracy': None, 'error': None, 'loss': None, 'status': 'logits no finitos'}
correct += int(z.argmax(1).eq(target).sum().item())
batch_loss = float(F.cross_entropy(z, target, reduction='sum').item())
if not math.isfinite(batch_loss):
return {'accuracy': None, 'error': None, 'loss': None, 'status': 'pérdida no finita'}
loss_sum += batch_loss
return {'accuracy': correct / len(labels), 'error': 1 - correct / len(labels), 'loss': loss_sum / len(labels), 'status': 'ok'}
def delete_test(model, images, labels, mean, std):
eligible = [i for i, b in enumerate(model.blocks) if b.can_delete]
chosen = [eligible[0], eligible[len(eligible) // 2], eligible[-1]]
masks = [[], *[[i] for i in chosen], chosen]
result = []
try:
for mask in masks:
for i, block in enumerate(model.blocks):
block.deleted = i in mask
result.append({'deleted_blocks': mask, **evaluate(model, images, labels, mean, std)})
finally:
for block in model.blocks:
block.deleted = False
return result
def experiment():
verify_blocks()
(train_x, train_y), (valid_x, valid_y), (test_x, test_y), train_ids, valid_ids, test_ids = dataset()
mean, std = stats(train_x)
# La sonda es fija y estratificada porque las particiones se concatenan por clase.
sample_per_class = min(20, train_per_class)
train_probe = torch.tensor(np.concatenate([np.arange(k * train_per_class, k * train_per_class + sample_per_class)
for k in range(10)]), device=device)
runs = []
for depth in depths:
for residual in ((True,) if resnet18_cifar else (False, True)):
for seed in seeds:
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
generator = torch.Generator(device=device).manual_seed(seed + 1000)
model = (CIFARResNet18() if resnet18_cifar else CIFARNet(depth, residual=residual)).to(
device=device, memory_format=torch.channels_last)
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)
history, best_accuracy, best_step, best_state, failure = [], -1., 0, None, None
for step in range(steps):
model.train()
ids = torch.randint(0, len(train_x), (batch_size,), generator=generator, device=device)
x = preprocess(train_x[ids], 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[ids])
if not bool(torch.isfinite(loss)):
failure = {'step': step + 1, 'reason': 'pérdida de entrenamiento no finita'}
break
loss.backward()
gradients = [(name, parameter.grad) for name, parameter in model.named_parameters()
if parameter.requires_grad]
missing = [name for name, gradient in gradients if gradient is None]
if missing:
failure = {'step': step + 1, 'reason': 'gradientes ausentes', 'parameters': missing}
break
finite = torch.stack([torch.isfinite(gradient).all() for _, gradient in gradients])
if not bool(finite.all()):
flags = finite.cpu().tolist()
failure = {'step': step + 1, 'reason': 'gradientes no finitos',
'parameters': [name for (name, _), ok in zip(gradients, flags) if not ok]}
break
report = step == 0 or (step + 1) % max(1, steps // 4) == 0
if report:
grad = [float(b.conv1.weight.grad.detach().double().norm().cpu()) for b in model.blocks]
invalid = [i for i, value in enumerate(grad) if not math.isfinite(value)]
if invalid:
failure = {'step': step + 1, 'reason': 'gradientes no finitos', 'blocks': invalid}
break
opt.step()
scheduler.step()
if report:
train = evaluate(model, train_x[train_probe], train_y[train_probe], mean, std)
valid = evaluate(model, valid_x, valid_y, mean, std)
test = evaluate(model, test_x, test_y, mean, std)
history.append({'step': step + 1, 'train_probe': train, 'validation': valid,
'test_exploratory': test, 'batch_loss': float(loss.detach()),
'block_conv1_gradient_norms': grad})
if train['accuracy'] is None or valid['accuracy'] is None:
failure = {'step': step + 1, 'reason': 'evaluación de entrenamiento o validación no finita',
'statuses': [train['status'], valid['status']]}
break
if valid['accuracy'] > best_accuracy:
best_accuracy, best_step = valid['accuracy'], step + 1
best_state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
if best_state is not None:
model.load_state_dict(best_state, strict=True)
deletion = delete_test(model, test_x, test_y, mean, std)
else:
deletion = []
runs.append({'depth': depth, 'residual': residual, 'seed': seed,
'parameters': sum(p.numel() for p in model.parameters()),
'best_step': best_step, 'history': history, 'test_and_deletion': deletion,
'failure': failure})
print('profundidad', depth, 'residual', residual, 'semilla', seed,
'validación', best_accuracy if best_state is not None else None,
'test', deletion[0]['accuracy'] if deletion else None, 'fallo', failure, flush=True)
del model, opt, scheduler, best_state
torch.cuda.empty_cache()
default_output = ('m16-l09-resnet18-cifar.json' if resnet18_cifar else
'm16-l09-cifar-extra.json' if extra_depths else 'm16-l09-cifar-residual.json')
output = Path(os.environ.get('ORYON_CIFAR_RESNET_OUTPUT', default_output))
result = {'dataset': 'uoft-cs/cifar10', 'revision': revision, 'short': short,
'device': torch.cuda.get_device_name(), 'torch_version': torch.__version__,
'seeds': seeds, 'depths': depths, 'steps': steps, 'batch_size': batch_size,
'train_indices': train_ids, 'valid_indices': valid_ids, 'test_indices': test_ids,
'train_mean': mean.cpu().tolist(), 'train_std': std.cpu().tolist(),
'train_probe_count': len(train_probe), 'precision': 'bfloat16 autocast' if amp else 'float32',
'recipe': 'SGD momentum 0.9, weight decay 0.0001, LR 0.1 con dos caídas de 10, crop y flip',
'shortcut': 'proyección 1x1 y BN en transiciones' if resnet18_cifar else 'opción A: submuestreo y padding de canales cero',
'gradients': 'normas de conv1.weight por bloque en el último lote del checkpoint, antes de actualizar',
'selection': 'primer máximo de precisión de validación; test exploratorio en cada checkpoint y borrado al final',
'deletion': 'borrado total de bloque con forma igual; no se borran transiciones', 'runs': runs}
output.write_text(json.dumps(result, ensure_ascii=False, allow_nan=False, indent=2), encoding='utf-8')
print('Resultado:', output, flush=True)
print('Resumen: error de sonda de entrenamiento, validación y test exploratorio, gradientes por bloque y borrado.')
print('Las normas proceden del minibatch anterior a la actualización; las métricas, de después.')
for run in runs:
print('Modelo:', run['depth'], 'residual:', run['residual'], 'semilla:', run['seed'],
'parámetros:', run['parameters'], 'mejor paso:', run['best_step'])
for row in run['history']:
gradients = ','.join(f'{value:.6g}' for value in row['block_conv1_gradient_norms'])
print('paso', row['step'], 'error_train', row['train_probe']['error'],
'error_valid', row['validation']['error'], 'error_test_exploratorio', row['test_exploratory']['error'],
'normas_gradiente', gradients)
if run['failure']:
print('Fallo:', run['failure'])
for row in run['test_and_deletion']:
print('borrados', row['deleted_blocks'], 'error_test', row['error'])
if __name__ == '__main__':
try:
experiment()
finally:
torch.cuda.empty_cache()npm run lab and open the connection link.Exercises
Step 1 of 3. What results from summing increments between l and L?
import torch
from torch import nn
class BasicBlock(nn.Module):
def __init__(self, cin, cout, stride=1):
super().__init__()
def forward(self, x):
pass
class Bottleneck(nn.Module):
def __init__(self, cin, width, stride=1):
super().__init__()
def forward(self, x):
passResNet changes the problem’s parameterization. The shortcut offers a direct path and makes a small correction easier to represent, but its effect depends on architecture, initialization and optimization. Always compare training and evaluation with identified protocols.