Module contents
Lesson 12 of 25Advanced 100 min

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.

InteractiveAdd or concatenate

All three variants start with 16 channels and apply one 3×3 convolution per layer. In the dense network, each function receives the concatenation of all previous features and adds 8 new channels.

F1F2F3F40x01h12h23h34h4
  • New feature
LayerInputF outputWeights
11681152
22481728
33282304
44082880

F is one convolution without bias, with stride 1 and padding that preserves resolution. We do not count BN, activation, projection or classifier. Plain and residual use an output of 16 channels; the residual adds it to the state. In the dense case, x0 is the input and h1 through h4 are only the new features: they are concatenated, not added.

Memory is a model, not a measured peak: batch 1, float32, storing the input and each displayed output once, without gradients or temporaries. If all concatenated inputs are also materialized and retained separately, they would add 112 KiB extra. An implementation can share memory or recompute and change that cost.

Connectivity
4
8
Spatial side length
Input channels to the last layer40
Output state channels48
Accumulated convolution weights8064
Retained outputs, illustrative model48.0 KiB
Compare four layers under the stated size and memory assumptions. Figures model retained tensors, not measured CUDA peak.

DenseNet: retain and reuse

In a residual network with compatible shapes, xℓ=xℓ−1+Fℓ(xℓ−1)x_\ell=x_{\ell-1}+F_\ell(x_{\ell-1}): addition mixes two tensors coordinate by coordinate. In a DenseNet, instead,

xℓ=Hℓ([x0,x1,…,xℓ−1]),x_\ell=H_\ell([x_0,x_1,\ldots,x_{\ell-1}]),

where brackets concatenate channels and each xℓx_\ell contributes kk new channels. If x0x_0 has c0c_0 channels, layer ℓ\ell‘s input, numbering from one, has c0+(ℓ−1)kc_0+(\ell-1)k and accumulated output after LL layers has c0+Lkc_0+Lk. Earlier maps remain separately available; they are not summed. The original paper counts L(L+1)/2L(L+1)/2 direct connections from input and earlier layers to the LL transforms under that indexing convention (Huang and colleagues).

In DenseNet-BC, each transform uses a 1×1 bottleneck before the 3×3 convolution producing kk channels. Between blocks a transition projects mm channels to approximately θm\theta m and reduces resolution with pooling; 0<θ≤10<\theta\leq1. Keeping resolution uniform within each block makes concatenation possible. Reducing kk 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 4k4k channels and biases and normalizations are omitted, a transform receiving cc channels has 4kc+36k24kc+36k^2 weights: 4kc4kc in the 1×1 projection and 9(4k)k9(4k)k in the 3×3. Without a bottleneck, a direct 3×3 from cc to kk has 9ck9ck. The bottleneck is not automatically smaller for all cc and kk: it is cheaper only when 4kc+36k2<9ck4kc+36k^2<9ck, or c>36k/5c>36k/5. 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 ∑ℓ=1L[c0+(ℓ−1)k]=Lc0+kL(L−1)/2\sum_{\ell=1}^L[c_0+(\ell-1)k]=Lc_0+kL(L-1)/2 spatial channels, in addition to original features, weights, gradients and temporary memory. The sum contains a quadratic term in LL even though new maps total only LkLk 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 CinC_{\rm in} input and CoutC_{\rm out} output channels into GG equal groups. Each output receives input only from its group, so both channel counts must be divisible by GG. Weights of correlation with a kh×kwk_h\times k_w kernel have shape (Cout,Cin/G,kh,kw)(C_{\rm out},C_{\rm in}/G,k_h,k_w) and, without bias, number

P=CinCoutkhkwG.P=\frac{C_{\rm in}C_{\rm out}k_hk_w}{G}.

Nominal direct work for batch NN and spatial output Ho×WoH_o\times W_o is NHoWoPNH_oW_oP multiply-accumulates, excluding biases. Multichannel convolution with G=1G=1 is fully connected across channels. If G=CinG=C_{\rm in} and Cout=mCinC_{\rm out}=mC_{\rm in}, each input has mm filters of its own: depthwise with multiplier mm.

InteractiveGroup wiring

Each row is an output channel and each column an input channel. A colored cell indicates a learned kernel for that pair; the highlighted row is the selected output. Indices start at zero.

0481204812Input channelsOutput channels
  • An allowed connection
  • Next contiguous group

There are 4 inputs and 4 outputs per group. Each output combines only inputs in its group. Empty cells represent absent connections, not learned weights equal to zero.

Without bias, the weights are k²·Cin·Cout/g and MACs per image are that number multiplied by output area. Multiply-accumulates are counted for one image; bias, activations and other operations are excluded. Compared with dense convolution of the same shapes, there remain 25.0 % of the weights and MACs.

With g = Cᵢₙ we obtain depthwise convolution; outputs can have a multiplier per channel. Fewer MACs do not guarantee lower latency: hardware, memory access and kernels also matter.

Output channels
Output spatial side length
0
Inputs of the selected output0 to 3
Connections between channels64
Convolution weights576
MACs per image147 k
Each diagonal block contains channel pairs that can connect. Change groups, outputs and kernel to check the count.

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 GG transforms of identical topology. If branch gg is Bg∘Kg∘AgB_g\circ K_g\circ A_g, with AgA_g and BgB_g 1×1 convolutions and KgK_g a 3×3, its residual output is ∑gBg(Kg(Ag(x)))\sum_g B_g(K_g(A_g(x))). Stack outputs of all AgA_g by channel: grouped 3×3 applies each KgK_g to its segment. A final 1×1 whose weight blocks are BgB_g 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 GG 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 GG or device.

The count helps design a comparison. With CinC_{\rm in} input, CoutC_{\rm out} output, GG branches of internal width dd and no biases, the equivalent sequence has GCind+9Gd2+GdCoutGC_{\rm in}d+9Gd^2+GdC_{\rm out} weights. Holding dd fixed, increasing GG increases all three terms; holding GdGd fixed preserves projection size, but the central term decreases as GG 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 aa makes weights grow approximately as a2a^2; activations at fixed resolution and batch grow as aa. 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 U∈RC×H×WU\in\mathbb R^{C\times H\times W} first produces zc=(HW)−1∑i,jUcijz_c=(HW)^{-1}\sum_{i,j}U_{cij}. A small network calculates s=σ(W2 ReLU(W1z+b1)+b2)s=\sigma(W_2\,\mathrm{ReLU}(W_1z+b_1)+b_2) and returns U~cij=scUcij\widetilde U_{cij}=s_c U_{cij}. With intermediate dimension dd, the two matrices have 2Cd2Cd weights and biases add d+Cd+C. If d=C/rd=C/r is an integer, the dominant term is 2C2/r2C^2/r. 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 scs_c depend on other channel averages. For a fixed sample, the same scs_c 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 1/21/2: the block halves values and is not identity. A residual combination can still have a separate identity path.

InteractiveImage-conditioned gates

The gates are real sigmoid outputs from pretrained EfficientNet-B0, before multiplying each channel. Compare two inputs in the same block: a value close to zero attenuates that channel more, while one close to one preserves it more.

Image A: appleA: apple
Image B: appleB: apple
0.00.51.0Channels 0 to 31, in order
  • Image A
  • Image B

To fit the entire block, each point represents one channel; the band marks channel 0. The control and readouts show the individual channel, not the group mean. The mean absolute difference is the mean of |A − B| across all channels in the block; selecting the same image twice gives zero.

Selected block: features.1.0.block.1. Data: EfficientNet-B0 with weights EfficientNet_B0_Weights.IMAGENET1K_V1, images from CIFAR-100 test, revision aadb3af7. The original thumbnail is shown; the model receives the official preprocessing for the weights. The model was trained on ImageNet and these images have a different distribution. These are a few exploratory examples: they do not establish that a layer is specific to a class or allow its channels to be compared with those of another block as if they had the same identity.

0
Gate for A0.8613
Gate for B0.8620
Mean absolute difference between images0.0036
Block channels32
Compare images and layers of a pretrained model. A small sample illustrates individual responses, not a statistical class property by itself.

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.

[ ]Extract real EfficientNet-B0 gatesLocal GPU
"""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()
This cell needs the local lab (PyTorch with your GPU). Start it with 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.

[ ]Grouped convolution with im2colBrowser
"""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.

[ ]Regenerate references with PyTorchLocal GPU
"""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)
This cell needs the local lab (PyTorch with your GPU). Start it with 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.

[ ]CIFAR-100 architectures with comparable budgetsLocal GPU
"""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()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

NumericInput of a dense block
A block starts with 64 channels and each layer adds 32. Numbering the first layer 1, how many channels does layer 12 receive?
NumericThe price of connections
How many weights does a 3×3 convolution from 128 to 128 channels with 32 groups and no bias have?
QuizFour wiring patterns
For that bias-free 3×3 convolution from 128 to 128, what is the weight sequence for 1, 4, 32 and 128 groups, in that order?
ProofFrom branches to groups
Prove: Consider G bias-free parallel branches, each with 1×1, 3×3 and 1×1, and sum their outputs. Branches have equal intermediate width, spatial geometry, stride, padding and dilation. Each final branch projection is linear with no activation before summation; no operations mix branches.
0
Construct one 1×1, grouped 3×3 and 1×1 sequence with the same weights.

Step 1 of 3. What should the first 1×1 produce?

CodeAn SE gate
Implement SEBlock(channels, reduction) with two nn.Linear layers named fc1 and fc2, hidden width max(1, channels//reduction), ReLU, sigmoid and mean over height and width. Return input multiplied by its own sample’s gates.
import torch
from torch import nn

class SEBlock(nn.Module):
  def __init__(self, channels, reduction):
      super().__init__()

  def forward(self, x):
      pass
Shift+Enter to run
QuizChoosing under constraints
Activation memory is very limited and single-image latency strict. What decision is defensible before measuring?
QuizPerformance per parameter
Your goal is highest accuracy under a parameter limit, with no prior latency requirement. Which comparison best supports a choice?

Check your results with these reproducible calculations:

[ ]Check the calculationsBrowser
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)
Key idea
Dense connections reuse features, groups restrict wiring, width changes compute geometry and SE conditions channels on the sample. No parameter count replaces measuring memory, accuracy and latency under an explicit protocol.