Efficient CNNs: separable convolutions, MobileNet and EfficientNet
Derive depthwise-separable convolution cost, implement MobileNetV2 inverted residuals, study compound scaling and distinguish nominal compute from measured efficiency.
After this lesson you can
- Calculate depthwise-separable convolution cost and representational constraints.
- Implement inverted residual blocks with shape-safe shortcuts.
- Explain EfficientNet compound scaling and its approximations.
- Compare architecture-search objectives using compute and measured latency.
- Interpret roofline estimates and benchmark efficiency on actual hardware.
Before you start
Cheap operations, costly decisions
A robot camera produces image after image. If prediction takes too long, the robot acts on an old scene; if the processor consumes too much energy, battery budget limits its use. Counting operations can rule out expensive designs before building them, but does not replace measuring actual implementation and device latency.
Grouped convolution separated channels into groups. Now we take that constraint to one convolution per channel and add 1×1 mixing. Then we examine how MobileNetV2 organizes these steps, how EfficientNet scales a base architecture and what a roofline model can and cannot conclude.
A depthwise convolution and projection
With input channels, output channels, a kernel and spatial output of positions, a bias-free dense convolution has weights. A depthwise-separable convolution first applies one spatial filter per channel and then a 1×1 projection mixing channels. With depthwise multiplier one, its weights number . If both stages produce the same resolution, the nominal multiply-accumulate ratio is
The ratio does not depend on under these assumptions. The same value results if both alternatives count two FLOPs per multiply-accumulate; it excludes biases, activations, normalization, memory access and launch cost. For factorization adds a stage and saves no work. The MobileNet analysis gives the same ratio and studies models with 3×3 spatial filters.
The reduction constrains the function. Without intermediate nonlinearity, for each input channel the effective kernel is . Placing outputs in rows and spatial positions in columns, that matrix has rank at most one. An arbitrary dense convolution can have higher rank and is not always represented by one spatial filter per channel. With depthwise multiplier , the sum of outer products raises maximum rank to . Inserting an activation between stages changes the function and no longer allows describing the whole block with one linear kernel.
MobileNet v1 offers two global controls. A width multiplier reduces channels and a resolution multiplier reduces input spatial dimensions. In an idealized internal layer, the 1×1 part scales approximately with width squared, whereas depthwise filtering scales linearly with width; both depend on output spatial area. Rounding to integer channels and initial and final layers prevent applying this approximation as exact equality to the full network.
MobileNetV2: expand, filter and project
The inverted residual receives a narrow representation, expands it with 1×1, applies depthwise convolution and projects it with another 1×1 to a narrow representation. Expansion and filtering have activations; the final projection adds no activation clipping the bottleneck. If stride is one and input and output shapes match, an identity shortcut is added. Otherwise that shortcut is not added: broadcasting must not be used to make shapes appear compatible.
Why leave the bottleneck linear? ReLU sends all negative values to zero: distinct values such as and become indistinguishable. A narrow representation has fewer alternative coordinates to preserve discarded information. This is intuition about possible local loss, not proof that every nonlinear activation worsens any network or that a linear projection guarantees invertibility. Sandler and colleagues formulate their argument under a low-dimensional manifold assumption and empirically test the design; an identity shortcut also changes what information can traverse the block.
With expansion and stride one, ignoring biases, normalization and activations, the three convolutions total weights. To obtain MACs per image multiply by spatial area, provided all three stages have the same resolution; with stride two expansion operates at input resolution and later stages at output resolution, so they must be counted separately.
Scaling with an explicit budget
Depth , width and resolution jointly affect cost. As an approximation for internal dense layers, FLOPs scale as . EfficientNet’s compound scaling rule takes , , and seeks so each unit of approximately doubles cost. The paper chose , and around its base model; this empirical choice does not require other problems to share the optimum (Tan and Le, section 4). The commas denote decimal points.
Depthwise layers, stages with differing channel counts, the classifier, rounding and implementation constraints mean actual cost does not exactly follow that power. Comparing one network at native resolution with another at lower resolution also mixes architecture and input. Fix the protocol or show both resolutions. In the same paper’s table 7, under its compute convention, EfficientNet-B0 scaled only in depth, width or resolution achieves 79.0%, 78.9% and 79.1% top-1 with roughly 1.8 to 1.9 billion operations; the compound version achieves 81.1% with 1.8 billion. These are published results of that experiment, not a law guaranteeing balanced scaling always wins.
Searching for an architecture
Neural architecture search needs a candidate space, a strategy proposing configurations and a way to estimate quality. The space may choose kernels, channels, connections and block count; the strategy may use reinforcement learning, evolution or differentiable search; estimation may train candidates, use surrogates or share weights. A cheap estimate can rank networks incorrectly: finally measure chosen candidates with a full recipe and held-out split.
The objective also matters. Searching for accuracy under a FLOP constraint differs from including latency measured on a particular phone. MnasNet includes observed phone latency in its search objective; MobileNetV3 combines hardware-aware search, NetAdapt and mobile CPU design decisions. The cost of finding a network can far exceed one inference: report search budget alongside final training budget when comparing methods.
From nominal compute to the device
Efficiency metrics describe different resources. Parameters count learned values; nominal MACs or FLOPs count work under a convention; peak memory counts reservations in a particular run; latency measures one request’s time and throughput measures requests per unit time. A larger batch can improve throughput and increase request latency. Numerical precision, memory formats, compilation, warmup and size affect measurements.
The roofline model compares arithmetic intensity against two ceilings: compute performance and bandwidth . The idealized bound is , provided describes relevant memory-hierarchy traffic and ceilings suit operation type and precision. The sum of input, weight and output sizes does not itself measure bytes transferred: caches, reuse, temporaries and fusion change traffic. A point calculated from those sizes is therefore an intensity estimate, not proof the kernel is memory-bound. Attributing a bottleneck requires traffic and utilization measurements with appropriate tools, plus comparison with sustained device ceilings.
Later designs return hardware to the center. EfficientNetV2 includes Fused-MBConv in its search space and also optimizes training speed: a dense convolution can be more favorable than several separate stages for certain shapes and devices. RegNet studies populations of regular networks rather than designing one instance and compares GPU performance. These results depend on their protocols and do not prove one family is always faster on your machine.
Labs
The first cell compares CIFAR-adapted MobileNetV2 with lesson 9’s ResNet-18 and trains a compact base with depth, width, resolution and combined scaling. The ORYON_VERIFY_SHORT=1 check uses one seed, 40 steps and reduced subsets to verify the flow; full mode uses three seeds and the 64,000-step recipe. Selection uses validation and test is reported as exploratory. FLOPs are nominal counts of convolutions and linear layers; interpolating images adds no new detail.
The short check produced unstable validation losses: in ResNet-18, 74,718 at step 10 and approximately 5.29 at step 40, with step 1 selected; in MobileNetV2, approximately 76.95 at step 20. The four scale variants had close nominal budgets, but this run demonstrates neither convergence nor a compound-scaling advantage. Keep curves and review the recipe using validation if full training is also unstable; do not choose settings by looking at test.
"""MobileNetV2, ResNet-18 y escalado de una base compacta sobre CIFAR-10.
Requiere torch, numpy, pillow, pyarrow y huggingface_hub, y una GPU CUDA.
ORYON_VERIFY_SHORT=1 usa 40 pasos, lote 32, una semilla y menos imágenes; es
una verificación del circuito, no una reproducción ni un ranking de precisión.
Modo completo: tres semillas, 64000 pasos y lote 128, como la receta de l09.
MobileNetV2 adapta el tallo y los strides a CIFAR; la red de escala es una
base propia, no EfficientNet ni sus cifras de entrenamiento. El reescalado de
32 píxeles no añade información nueva. Resultados en ORYON_MOBILE_OUTPUT.
"""
import gc
import io
import json
import math
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')
seeds = [16131] if short else [16131, 16132, 16133]
steps = 40 if short else 64000
batch_size = 32 if short else 128
train_per_class, valid_per_class, test_per_class = (50, 10, 20) if short else (4500, 500, 1000)
revision = '0b27149'
amp = device.type == 'cuda' and torch.cuda.is_bf16_supported()
def choose_indices(split, 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)]
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 not None:
row = batch.column(0)[local].as_py()
with Image.open(io.BytesIO(row['bytes'])) as image:
images[target] = np.asarray(image.convert('RGB'), dtype=np.uint8).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', 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', 16074)
start = 80 if short else 0
test_ids = np.concatenate([g[start:start+test_per_class] for g in test_groups])
assert not set(train_ids) & set(valid_ids)
if short:
assert not set(test_ids) & set(np.concatenate([g[:80] for g in test_groups]))
return (read_selected(path, labels, train_ids), read_selected(path, labels, valid_ids),
read_selected(path_test, labels_test, test_ids), train_ids, valid_ids, test_ids)
def stats(images):
total = torch.zeros(3, dtype=torch.float64, device=device)
squares = torch.zeros_like(total)
count = 0
for batch in images.split(256):
x = batch.to(torch.float64)/255
total += x.sum((0, 2, 3))
squares += x.square().sum((0, 2, 3))
count += len(x)*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 de entrenamiento inválidas')
return mean.float()[None, :, None, None], std.float()[None, :, None, None]
def preprocess(images, mean, std, resolution, 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)
if resolution != 32:
x = F.interpolate(x, size=(resolution, resolution), mode='bilinear', align_corners=False)
return ((x-mean)/std).contiguous(memory_format=torch.channels_last)
class CIFAR18Block(nn.Module):
"""Bloque básico y proyección de l09, sin borrado para esta comparación."""
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())
def forward(self, x):
out = self.bn2(self.conv2(F.relu(self.bn1(self.conv1(x)))))
return F.relu(out + self.shortcut(x))
class CIFARResNet18(nn.Module):
def __init__(self):
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)
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 InvertedResidual(nn.Module):
"""Expansión y depthwise no lineales, proyección sin ReLU y atajo condicionado."""
def __init__(self, cin, cout, stride, expand):
super().__init__()
if stride not in (1, 2) or expand < 1:
raise ValueError('Stride o expansión inválidos')
hidden = cin*expand
layers = []
if expand != 1:
layers.extend((nn.Conv2d(cin, hidden, 1, bias=False), nn.BatchNorm2d(hidden), nn.ReLU6()))
layers.extend((nn.Conv2d(hidden, hidden, 3, stride=stride, padding=1, groups=hidden, bias=False),
nn.BatchNorm2d(hidden), nn.ReLU6(),
nn.Conv2d(hidden, cout, 1, bias=False), nn.BatchNorm2d(cout)))
self.body = nn.Sequential(*layers)
self.use_skip = stride == 1 and cin == cout
def forward(self, x):
result = self.body(x)
return x+result if self.use_skip else result
class MobileNetV2CIFAR(nn.Module):
"""Tabla MobileNetV2 adaptada a 32×32: tallo de stride uno."""
def __init__(self):
super().__init__()
self.stem = nn.Sequential(nn.Conv2d(3, 32, 3, padding=1, bias=False), nn.BatchNorm2d(32), nn.ReLU6())
settings = [(1, 16, 1, 1), (6, 24, 2, 1), (6, 32, 3, 2), (6, 64, 4, 2),
(6, 96, 3, 1), (6, 160, 3, 2), (6, 320, 1, 1)]
cin, blocks = 32, []
for expand, cout, repeats, stride in settings:
for j in range(repeats):
blocks.append(InvertedResidual(cin, cout, stride if j == 0 else 1, expand))
cin = cout
self.blocks = nn.Sequential(*blocks)
self.head = nn.Sequential(nn.Conv2d(cin, 1280, 1, bias=False), nn.BatchNorm2d(1280), nn.ReLU6())
self.fc = nn.Linear(1280, 10)
def forward(self, x):
x = self.head(self.blocks(self.stem(x)))
return self.fc(x.mean((2, 3)))
def round_channels(value):
return max(4, int(math.floor(value/4+.5))*4)
class ScaleNet(nn.Module):
"""Base compacta, creada para estudiar profundidad, anchura y resolución."""
def __init__(self, repeats, width):
super().__init__()
channels = round_channels(16*width)
self.stem = nn.Sequential(nn.Conv2d(3, channels, 3, padding=1, bias=False), nn.BatchNorm2d(channels), nn.ReLU6())
blocks = []
for stage, base in enumerate((16, 24, 32)):
cout = round_channels(base*width)
for i in range(repeats[stage]):
stride = 2 if stage > 0 and i == 0 else 1
blocks.append(InvertedResidual(channels, cout, stride, 3))
channels = cout
self.blocks = nn.Sequential(*blocks)
head = round_channels(64*width)
self.head = nn.Sequential(nn.Conv2d(channels, head, 1, bias=False), nn.BatchNorm2d(head), nn.ReLU6())
self.fc = nn.Linear(head, 10)
def forward(self, x):
x = self.head(self.blocks(self.stem(x)))
return self.fc(x.mean((2, 3)))
# Cuatro variantes cercanas en coste teórico; ninguna accuracy está prefijada.
CONFIGS = {
'base': {'repeats': [2, 2, 2], 'width': 1., 'resolution': 32},
'profundidad': {'repeats': [6, 5, 5], 'width': 1., 'resolution': 32},
'anchura': {'repeats': [2, 2, 2], 'width': 1.625, 'resolution': 32},
'resolucion': {'repeats': [2, 2, 2], 'width': 1., 'resolution': 52},
'compuesto': {'repeats': [3, 3, 3], 'width': 1.125, 'resolution': 36},
}
def build(name):
if name == 'resnet18':
return CIFARResNet18(), 32
if name == 'mobilenetv2':
return MobileNetV2CIFAR(), 32
config = CONFIGS[name]
return ScaleNet(config['repeats'], config['width']), config['resolution']
def conv_linear_flops(model, resolution):
"""Dos FLOPs por multiplicación-acumulación; excluye BN, ReLU, pooling y sumas."""
macs = 0
hooks = []
def conv_hook(layer, inputs, output):
nonlocal macs
n, cout, height, width = output.shape
kh, kw = layer.kernel_size
macs += n*height*width*cout*(layer.in_channels//layer.groups)*kh*kw
def linear_hook(layer, inputs, output):
nonlocal macs
macs += inputs[0].numel()//layer.in_features*layer.in_features*layer.out_features
for module in model.modules():
if isinstance(module, nn.Conv2d):
hooks.append(module.register_forward_hook(conv_hook))
elif isinstance(module, nn.Linear):
hooks.append(module.register_forward_hook(linear_hook))
try:
model.eval()
with torch.no_grad():
model(torch.zeros((1, 3, resolution, resolution), device=device).contiguous(memory_format=torch.channels_last))
finally:
for hook in hooks:
hook.remove()
return 2*macs
def evaluate(model, images, labels, mean, std, resolution):
model.eval()
logits = []
with torch.no_grad():
for chunk in images.split(128):
x = preprocess(chunk, mean, std, resolution)
with torch.autocast('cuda', dtype=torch.bfloat16, enabled=amp):
logits.append(model(x).float().cpu())
logits = torch.cat(logits)
if not bool(torch.isfinite(logits).all()):
return {'status': 'no finito', 'accuracy': None, 'loss': None}
target = labels.cpu()
loss = F.cross_entropy(logits, target)
if not bool(torch.isfinite(loss)):
return {'status': 'no finito', 'accuracy': None, 'loss': None}
return {'status': 'ok', 'accuracy': float((logits.argmax(1)==target).float().mean()),
'loss': float(loss)}
def bench(model, images, mean, std, resolution):
"""Latencia de una imagen y throughput por lote, sin preprocesado."""
model.eval()
batch = preprocess(images[:batch_size], mean, std, resolution)
single = batch[:1].contiguous(memory_format=torch.channels_last)
def measure_batch(x, warm=5, repeat=20):
with torch.no_grad(), torch.autocast('cuda', dtype=torch.bfloat16, enabled=amp):
for _ in range(warm):
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_seconds = measure_batch(batch)
# El tiempo de petición individual incluye lanzamiento y sincronización.
with torch.no_grad(), torch.autocast('cuda', dtype=torch.bfloat16, enabled=amp):
for _ in range(5):
model(single)
torch.cuda.synchronize()
samples = []
for _ in range(20):
start = time.perf_counter()
model(single)
torch.cuda.synchronize()
samples.append(time.perf_counter()-start)
single_seconds = statistics.median(samples)
return {'batch': len(batch), 'batch_seconds': batch_seconds,
'images_per_second': len(batch)/batch_seconds, 'single_image_seconds': single_seconds,
'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, resolution = build(name)
model = model.to(device=device, memory_format=torch.channels_last)
flops = conv_linear_flops(model, resolution)
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_generator = torch.Generator(device=device).manual_seed(seed+1000)
aug_generator = torch.Generator(device=device).manual_seed(seed+2000)
history, best_acc, best_state, best_step, failure = [], -1., None, None, None
points = {1, steps//4, steps//2, 3*steps//4, steps}
for step in range(1, steps+1):
model.train()
ids = torch.randint(0, len(train_x), (batch_size,), generator=batch_generator, device=device)
x = preprocess(train_x[ids], mean, std, resolution, aug_generator)
opt.zero_grad(set_to_none=True)
with torch.autocast('cuda', dtype=torch.bfloat16, enabled=amp):
output = model(x)
loss = F.cross_entropy(output, train_y[ids])
if not bool(torch.isfinite(loss)):
failure = {'step': step, 'reason': 'pérdida no finita'}
break
loss.backward()
gradients = [p.grad for p in model.parameters() if p.requires_grad]
if any(g is None for g in gradients):
failure = {'step': step, 'reason': 'gradiente ausente'}
break
if not bool(torch.stack([torch.isfinite(g).all() for g in gradients]).all()):
failure = {'step': step, 'reason': 'gradiente no finito'}
break
opt.step()
scheduler.step()
if step in points:
valid = evaluate(model, valid_x, valid_y, mean, std, resolution)
if valid['accuracy'] is None:
failure = {'step': step, 'reason': 'validación no finita'}
break
history.append({'step': step, 'batch_loss': float(loss.detach()), 'validation': valid})
if valid['accuracy'] > best_acc:
best_acc, best_step = valid['accuracy'], step
best_state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
result = {'name': name, 'seed': seed, 'resolution': resolution, 'parameters': params,
'conv_linear_flops': flops, 'history': history, 'best_step': best_step, 'failure': failure}
if best_state is not None and failure is None:
model.load_state_dict(best_state, strict=True)
result['test_exploratory'] = evaluate(model, test_x, test_y, mean, std, resolution)
result['inference'] = bench(model, valid_x, mean, std, resolution)
opt.zero_grad(set_to_none=True)
opt.state.clear()
del model, opt, scheduler, best_state
gc.collect()
torch.cuda.empty_cache()
return result
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)
output = {'protocol': {'short': short, 'steps': steps, 'batch_size': batch_size, 'seeds': seeds,
'train_per_class': train_per_class, 'valid_per_class': valid_per_class, 'test_per_class': test_per_class,
'train_seed': 16070, 'test_seed': 16074, 'test_slice': [80, 100] if short else [0, 1000],
'mean': mean.flatten().cpu().tolist(), 'std': std.flatten().cpu().tolist(),
'recipe': 'SGD lr 0.1, momentum 0.9, wd 0.0001, hitos a mitad y tres cuartos, crop reflect y flip',
'l09_difference': 'corto reducido y test distinto; la validación corta incluye imágenes usadas por l09 al entrenar, pero aquí se entrena un modelo nuevo; semillas de inicialización diferentes y generadores separados',
'selection': 'mejor exactitud de validación entre cinco puntos, primer empate',
'flops': 'dos por MAC de convolución directa nominal, incluidos ceros de padding; solo conv y lineales; excluye BN, ReLU, pooling, interpolación y sumas',
'timing': 'eval tras warmup; latencia individual sincronizada en cada muestra y throughput por lote; preprocesado excluido',
'test': 'exploratorio, no usar para seleccionar variantes; test completo compartido con lecciones anteriores',
'scale_note': 'arquitectura propia con tamaños discretos; interpolar CIFAR no añade detalle nuevo',
'gpu': torch.cuda.get_device_name(device), 'torch': str(torch.__version__),
'cuda': str(torch.version.cuda), 'cudnn': torch.backends.cudnn.version(), 'amp_bfloat16': amp},
'scale_configurations': CONFIGS, 'runs': []}
path = Path(os.environ.get('ORYON_MOBILE_OUTPUT', 'm16-l13-mobile-scaling.json'))
for name in ['resnet18', 'mobilenetv2', 'base', 'profundidad', 'anchura', 'resolucion', 'compuesto']:
for seed in seeds:
run = train_one(name, seed, train_x, train_y, valid_x, valid_y, test_x, test_y, mean, std)
output['runs'].append(run)
path.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)
scales = [run['conv_linear_flops'] for run in output['runs'] if run['name'] in ('profundidad','anchura','resolucion','compuesto')]
assert max(scales)/min(scales) < 1.06
print('Presupuestos de las cuatro variantes, máximo/mínimo:', max(scales)/min(scales), flush=True)
if __name__ == '__main__':
main()npm run lab and open the connection link.The second cell warms up and times CUDA operators, a copy and a matrix product. Block bytes are the sum of input, parameter and output sizes, not measured memory traffic. The copy uses logical bytes and copy and GEMM references describe those particular kernels, not universal ceilings; without traffic counters they cannot classify the bottleneck.
"""Operadores reales, FLOPs analíticos y latencia CUDA, sin tráfico ficticio.
El tamaño input + parámetros + output es solo una suma de tensores, NO una
medición de bytes de DRAM ni una cota universal del tráfico. Para un roofline
real por nivel de memoria hacen falta contadores de hardware, por ejemplo
Nsight Compute con --section SpeedOfLight_RooflineChart. No se puede decidir
si un operador está limitado por memoria solo con estas magnitudes.
"""
import json
import os
import statistics
import time
from pathlib import Path
import torch
from torch import nn
from torch.nn import functional as F
torch.set_num_threads(1)
torch.backends.cudnn.benchmark = False
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
if device.type != 'cuda':
raise RuntimeError('Este laboratorio requiere CUDA')
short = os.environ.get('ORYON_VERIFY_SHORT') == '1'
repeats = 20 if short else 100
rounds = 3 if short else 10
class SE(nn.Module):
def __init__(self, channels, reduction=16):
super().__init__()
hidden = max(1, channels//reduction)
self.fc1, self.fc2 = nn.Linear(channels, hidden), nn.Linear(hidden, channels)
def forward(self, x):
weights = torch.sigmoid(self.fc2(F.relu(self.fc1(x.mean((2, 3))))))
return x*weights[:, :, None, None]
def operations(name, channels, height, width):
n = height*width
if name == 'dense3':
return 2*n*channels*channels*9
if name == 'depthwise3':
return 2*n*channels*9
if name == 'pointwise1':
return 2*n*channels*channels
hidden = max(1, channels//16)
# Suma espacial, dos productos matriciales y multiplicación por compuertas.
# No incluye la división de la media, bias, ReLU ni sigmoid.
return channels*(n-1) + 2*(channels*hidden+hidden*channels) + channels*n
def measure_kernel(fn):
"""Tiempo medio por iteración de rondas repetidas, no latencia fría."""
with torch.no_grad():
for _ in range(10):
fn()
torch.cuda.synchronize()
gpu_samples, host_samples = [], []
for _ in range(rounds):
torch.cuda.synchronize()
begin, end = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
start = time.perf_counter()
begin.record()
for _ in range(repeats):
fn()
end.record()
torch.cuda.synchronize()
host_samples.append((time.perf_counter()-start)/repeats)
gpu_samples.append(begin.elapsed_time(end)/(1000*repeats))
return {'gpu_seconds_median': statistics.median(gpu_samples),
'host_seconds_median': statistics.median(host_samples),
'gpu_seconds_samples': gpu_samples, 'host_seconds_samples': host_samples}
def measured_references():
"""Copia y GEMM concretos; no miden techos físicos universales."""
elements = 16*1024*1024
source = torch.empty(elements, device=device, dtype=torch.float32).uniform_()
destination = torch.empty_like(source)
copying = measure_kernel(lambda: destination.copy_(source))
logical_bytes = 2*elements*source.element_size()
copying.update({'operation': 'copy_', 'shape': [elements], 'dtype': 'float32',
'logical_bytes': logical_bytes,
'logical_bytes_per_second': logical_bytes/copying['gpu_seconds_median'],
'note': 'Un acceso lógico de lectura y uno de escritura por elemento; tráfico DRAM no medido.'})
del source, destination
torch.cuda.empty_cache()
size = 1024
a = torch.randn((size, size), device=device)
b = torch.randn((size, size), device=device)
c = torch.empty_like(a)
gemm = measure_kernel(lambda: torch.mm(a, b, out=c))
flops = 2*size**3
gemm.update({'operation': 'torch.mm', 'shape': [size, size, size], 'dtype': 'float32',
'nominal_flops': flops, 'nominal_tensor_bytes': 3*size*size*a.element_size(),
'effective_flops_per_second': flops/gemm['gpu_seconds_median'],
'matmul_allow_tf32': torch.backends.cuda.matmul.allow_tf32,
'note': '2n³ FLOPs convencionales; el algoritmo y las transacciones reales pueden diferir.'})
del a, b, c
torch.cuda.empty_cache()
return {'copy': copying, 'gemm': gemm}
def main():
torch.manual_seed(16130)
torch.cuda.manual_seed_all(16130)
channels, height, width = 64, 56, 56
x = torch.randn(1, channels, height, width, device=device).contiguous(memory_format=torch.channels_last)
models = {'dense3': nn.Conv2d(channels, channels, 3, padding=1, bias=False),
'depthwise3': nn.Conv2d(channels, channels, 3, padding=1, groups=channels, bias=False),
'pointwise1': nn.Conv2d(channels, channels, 1, bias=False), 'se': SE(channels)}
output = {'protocol': {'seed': 16130, 'input_shape': list(x.shape), 'dtype': str(x.dtype), 'memory_format': 'channels_last',
'repeats': repeats, 'rounds': rounds, 'device': torch.cuda.get_device_name(device),
'torch': str(torch.__version__), 'cuda': str(torch.version.cuda),
'cudnn': torch.backends.cudnn.version(), 'cudnn_allow_tf32': torch.backends.cudnn.allow_tf32,
'operation_convention': 'dos FLOPs por MAC nominal de convolución directa, incluidos ceros de padding; SE excluye división de media, bias, ReLU y sigmoid; el backend puede usar otro algoritmo',
'bytes_note': 'suma input + parámetros + output en fp32; no es tráfico DRAM medido ni cota universal',
'timing': 'modelos eval, warmup, eventos CUDA y reloj host sincronizados; resultados orientativos',
'classification': 'No se deduce estar limitado por memoria sin contadores de tráfico y techos medidos.',
'reference_note': 'Copia y GEMM concretos; las referencias no son techos universales y los bytes de copia son lógicos.'},
'operators': []}
for name, model in models.items():
model = model.to(device=device, memory_format=torch.channels_last).eval()
with torch.no_grad():
for _ in range(10):
y = model(x)
torch.cuda.synchronize()
params = sum(p.numel() for p in model.parameters())
bytes_proxy = (x.numel()+params+y.numel())*x.element_size()
flops = operations(name, channels, height, width)
gpu_samples, host_samples = [], []
for _ in range(rounds):
torch.cuda.synchronize()
begin, end = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
start = time.perf_counter()
begin.record()
for _ in range(repeats):
y = model(x)
end.record()
torch.cuda.synchronize()
host_samples.append((time.perf_counter()-start)/repeats)
gpu_samples.append(begin.elapsed_time(end)/(1000*repeats))
gpu_median = statistics.median(gpu_samples)
host_median = statistics.median(host_samples)
row = {'name': name, 'flops': flops, 'parameters': params, 'tensor_bytes_proxy': bytes_proxy,
'flops_per_proxy_byte': flops/bytes_proxy, 'gpu_seconds_median': gpu_median,
'host_seconds_median': host_median, 'gpu_seconds_samples': gpu_samples,
'host_seconds_samples': host_samples, 'effective_flops_per_second': flops/gpu_median}
output['operators'].append(row)
print(json.dumps(row, ensure_ascii=False), flush=True)
del model, y
torch.cuda.empty_cache()
output['references'] = measured_references()
print(json.dumps(output['references'], ensure_ascii=False), flush=True)
path = Path(os.environ.get('ORYON_ROOFLINE_OUTPUT', 'm16-l13-operator-proxies.json'))
path.write_text(json.dumps(output, ensure_ascii=False, indent=2, allow_nan=False), encoding='utf-8')
print('El cociente FLOPs/tamaño de tensores no clasifica el cuello de botella.', flush=True)
if __name__ == '__main__':
main()npm run lab and open the connection link.Exercises
Step 1 of 3. How many MACs does dense convolution perform per image?
import torch
from torch import nn
class InvertedResidual(nn.Module):
def __init__(self, in_ch, out_ch, stride, expand):
super().__init__()
def forward(self, x):
passcin, cout, expansion, kernel, side = 24, 24, 6, 3, 56
hidden = cin * expansion
mac = side**2 * (cin*hidden + kernel**2*hidden + hidden*cout)
print('FLOPs con dos por MAC:', 2*mac)
print('Factor compuesto:', 1.2 * 1.1**2 * 1.15**2)
print('Cociente depthwise con multiplicador 8:', 8*(1/16 + 1/9))