Module contents
Lesson 5 of 25Core 85 min

Receptive fields and the feature hierarchy

Calculate receptive-field size, jump and center; distinguish structural support from measured gradient sensitivity; compare small kernels, dilation and feature hierarchies.

After this lesson you can

  • Calculate receptive-field size, jump and center through a local layer stack.
  • Compare stacked small kernels and dilated kernels by reach and parameters.
  • Distinguish a bounding box, exact reachable support and an effective gradient map.
  • Explain the normalized path-count analogy and its limitations.
  • Inspect filters and activation patches without assuming causal explanations.

Before you start

One output, many paths

Choose a spatial unit in a CNN and ask which pixels could influence it. Each layer connects that unit to a window in the previous layer, and each of those positions opens further windows. The box grows, but actual influence may concentrate in a small part or even disappear for a particular input.

If a spatial prediction must distinguish an object by the joint arrangement of its parts, it needs some path integrating the relevant regions. A unit with too small a window cannot solve that case alone; a final classifier aggregating many local units is another architecture and can integrate information from farther away.

Build a stack and follow its connections backward. Distinguish the box containing paths from positions actually reachable and the number of paths reaching each pixel: none of these quantities is yet a gradient measurement of a trained network.

InteractiveBuild a stack and follow its paths

31×31 input. Edit each layer or add up to four; blue indicates connected positions and its intensity the number of potential paths. The orange frame is the structural box, which can extend outside the image.

1: conv 3×3, s=1, d=1, symmetric padding · 2: conv 3×3, s=1, d=1, symmetric padding · 3: conv 3×3, s=1, d=1, symmetric padding

The orange frame is the intersection of the potential box with the image; sides at its boundary may not be edges of the original box. Paths are counted backward respecting each layer’s boundaries. These are potential connections: they omit weights, signs and cancellations; in max pooling the path participating in the gradient depends on input maxima.

Operation
Square kernel
Stride
Dilation
Padding
15
15
Output shape31×31
Theoretical box7×7
Jump1
Selected center15.5, 15.5
Reachable pixels49
Valid potential paths729
Select a unit and compare the structural box with reachable support and calculated paths.

Size, jump and center

For a chain of local layers, a unit’s structural receptive field is the set of input positions connected by some path, regardless of weight values. We track a potential geometric box per axis, calculated before discarding paths outside each layer. Dilation may leave holes inside; near margins part of the box may correspond to constant padding outside the image. Even cropped to the image, the box can overapproximate actual support because intermediate-layer padding removes paths. To know it exactly, propagate connections and respect boundaries at every level.

Use input pixel centers 0.5,1.5,…0.5,1.5,\ldots. Initially the box has size r=1r=1, the jump between neighboring units is j=1j=1 and the first center is c=0.5c=0.5. For kernel length kk, stride ss, dilation dd and padding pizqp_{\mathrm{izq}} at the start of the axis, a layer updates

r′=r+(k−1)d j,c′=c+((k−1)d2−pizq)j,j′=s j.\begin{aligned} r'&=r+(k-1)d\,j,\\ c'&=c+\left(\frac{(k-1)d}{2}-p_{\mathrm{izq}}\right)j,\\ j'&=s\,j. \end{aligned}

r′r' and c′c' use the previous jump. Output unit ii has center c′+ij′c'+ij'. Padding at the far end affects available shape but does not shift the first unit’s center. Apply the recurrence separately to height and width and also calculate whether output fits using shape arithmetic. An even kernel can place the center between pixels: rounding too early shifts the box.

To derive the three expressions, take output ii: it connects to preceding positions is−pizq+udis-p_{\mathrm{izq}}+ud for u=0,…,k−1u=0,\ldots,k-1. Their centers in the original input range from c+(is−pizq)jc+(is-p_{\mathrm{izq}})j to c+(is−pizq+(k−1)d)jc+(is-p_{\mathrm{izq}}+(k-1)d)j. Each position carries a box of size rr, so the envelope increases by (k−1)dj(k-1)dj and its center is the mean of those endpoints. Increasing ii by one shifts the center by sjsj. This derivation counts the envelope before removing padding; exact support requires following valid paths. The same geometry works for local pooling, although max pooling’s active derivative path depends on input.

In a network with residual branches, follow each path, check grids align and union their supports. Taking only the largest box does not count holes or paths. Global attention and operations mixing positions, such as spatial statistics calculated during training, require analyzing additional dependencies. The recurrence above describes a chain of local operators, not every graph.

Designing reach without confusing functions

Stacking small kernels can increase the box and reuse parameters. Two stride-one 3×3 layers reach a 5×5 box, like one 5×5 layer. If all have CC input and output channels, without groups and with bias, they have 18C2+2C18C^2+2C parameters versus 25C2+C25C^2+C. Three 3×3 layers reach 7×7 and have 27C2+3C27C^2+3C versus 49C2+C49C^2+C for one 7×7 layer. Without biases the linear terms in CC disappear.

The same box does not mean the same operator: two linear filters compose a factorized filter, which need not represent every large kernel. With a nonlinearity between layers the function ceases to be linear and generally cannot be replaced by a single filter either. Simonyan and Zisserman study deep networks with small filters; the choice also affects cost, memory, depth and training.

Stride grows the jump and hence later layers’ reach, at the cost of resolution. Dilation separates samples without adding weights. Repeating the same factor can leave a grid of holes: with three 3×3 kernels and dilations 2, 2, 2 only even offsets are reached. Changing dilations can fill holes, as the figure and cell show. Reach alone does not say how much each position contributes or whether values cancel.

In a chain of nn size-3 kernels without dilation and with stride one, the potential box has side 1+2n1+2n. With dilations dℓ=2ℓ−1d_\ell=2^{\ell-1} and stride one, its side is 1+2(2n−1)1+2(2^n-1); the same nominal growth occurs with size-3 kernels and stride two at each layer because the jump doubles. In both cases check shapes, boundaries and effective connectivity. In causal sequence convolutions the box points into the past and determines which history an output can reach.

Another option is mixing positions with global attention: without a mask, each query can receive information from every available position in one layer. Resulting support is the union of its keys’ and values’ supports, not a box from the local recurrence. With NN positions, the explicit score matrix has N2N^2 entries per head; windows or masks reduce connections but also change reach. Global attention does not itself remove dependence on boundaries, resolution or previous map content.

The effective field is a measurement

Define a map for scalar unit yy and input xx as g[p]=∑c∣∂y/∂xc,p∣g[p]=\sum_c |\partial y/\partial x_{c,p}|, using the input gradient. If the sum of gg is positive, normalize the map to mass one. One way to summarize the effective receptive field is the radius containing 90% of that mass around the chosen center. This definition is a convention: squared gradient, another unit or a different region produce another reading. If mass is zero, radius is undefined; a nonfinite value should not be presented as a valid measurement.

The gradient is a local sensitivity for that input and parameters. An inactive ReLU, opposing signs or cancellations can reduce it even inside the structural box. A box covering the whole image does not prove the output uses all of it. Unit position, sample, network mode and normalization must be held fixed when comparing maps.

InteractiveStructural box and measured sensitivity

Absolute gradient summed over channels and averaged over eight CIFAR-10 test images; the map is normalized to sum to one. Color scale is shared by both stage checkpoints. The orange box marks the intersection of the potential box with the 32×32 image; its sides at the image boundary need not be sides of the original box.

Autograd data from the local cell: same initialized ResNet18, 100 training steps and same probe, eval mode and fixed channel. The box can be much larger than the image. Radius depends on the selected definition and one run does not establish a universal trend.

Checkpoint
Structural box11×11
Jump1
Fixed channel28
90% mass radius4.472
Other checkpoint radius4.472
Compare maps and radii calculated with their mass definition; a box larger than the image is cropped to the visible domain.

There is a probabilistic intuition under precise assumptions. In a linear 1D chain without boundaries, with nn kernels [1,1,1][1,1,1] and stride one, a pixel’s coefficient counts paths. Normalized, these coefficients form the distribution of a sum of nn independent uniform steps in {−1,0,1}\{-1,0,1\}; its mean is zero and variance 2n/32n/3. The central limit theorem approximates a Gaussian as depth grows, with deviation 2n/3\sqrt{2n/3}, while the box has width 2n+12n+1. The separable 2D case multiplies both axis distributions. Signed weights, nonlinearities and boundaries break this probability interpretation and can change the shape.

The count can be made with generating function (z−1+1+z)n(z^{-1}+1+z)^n: the coefficient of zqz^q counts step sequences ending at qq. There are 3n3^n equally likely sequences, so dividing that coefficient by 3n3^n gives the corresponding probability. Each step has zero mean and second moment 2/32/3; independence adds variances. The central limit theorem applies to the sum centered and divided by its deviation; it does not claim an arbitrary network has an exactly Gaussian map.

Luo and colleagues, section 3 and figure 2, report slopes 0.56 for effective size and −0.43 for its proportion relative to theoretical size on a logarithmic scale; they average 20 runs and define size with a threshold associated with two deviations, not our 90% radius. In their CamVid segmentation experiment they describe a theoretical box of 505 and approximate effective diameter of 100 initially and 150 after training. These are that study’s results and metrics, not a guarantee for an individual network or sample.

In our short trial we train a CIFAR-10-adapted ResNet18 for 100 steps on 2048 training images. Before and after, we measure the same unit and channel per stage on the same eight test images; the channel is chosen by mean activation on that probe before training and kept fixed. The average map’s 90% radius changed from 4.472 to 4.472 in layer1, 8.246 to 8.544 in layer2, 14.318 to 14.866 in layer3 and 16.155 to 16.279 in layer4. The first stage does not change under this metric and other changes are small: one initialization, small probe and limited budget. They do not prove universal growth or equal Luo’s metric.

Looking at filters, maps and patches

Early filters may show oriented patterns; later layers compose more complex responses. That feature hierarchy is an interpretation to test, not a label each channel has by definition. To explore it, select a layer and channel, observe its map on several images and locate spatial maxima. Ranking images by their maximum is not the same as choosing the most active pixels within one image.

InteractiveExplore filters and activations

Pretrained ImageNet ResNet18 and six validation images. The frame shows the structural box of the spatial maximum, clipped to the image; it does not prove which pixels caused the response. The map shows block averages, independently scaled by image and channel.

Image and maximum box
Activation map
Blue positive, orange negative.
Filter weights: R, G, B

Patches from the three images with the highest spatial maxima among the six probe images. Deep-layer boxes may span the whole image:

Each layer’s four channels were chosen by mean maximum on these same six images; top 3 ranks images, not pixels. Responses do not receive automatic semantic labels and are not causal attributions by themselves.

Spatial maximum16.7926
Maximum position18, 79
Theoretical box7×7
Box clipped by boundaryNo
Top-1 / label741 / 741
Images, channels and crops come from a pretrained ResNet18; inspect the structural box and possible boundary cropping.

The browser uses another network: ResNet18 with torchvision ImageNet weights and six validation images selected in the short run. Channels are chosen by mean spatial maxima on those same images; these are selected examples, not independent estimates of a semantic class. Boxes show the structural region corresponding to the unit, cropped to the image when necessary. We do not automatically interpret a channel as “face” or as a causal explanation. Zeiler and Fergus combined visualization with ablations, and Olah and colleagues distinguish visualizing a feature from attributing a prediction to specific parts of an input. That distinction is developed in the interpretability taxonomy; sparse coding offers another way to learn filters from patches.

Try a concrete reading: in conv1, compare each filter RGB plane’s sign pattern with the locations of its maxima; a spatial transition in weights suggests contrast sensitivity, but its orientation and sign depend on all three channels. Then switch to a later stage and compare the three most activating patches. Do they share texture, color, an object part or only background? The displayed map is block-averaged and may hide a point maximum; numerical position comes from the original map. Form a hypothesis and check it on additional images and with controlled interventions before assigning meaning to the channel.

Browser lab

The first cell calculates size, jump, center and shape for a 1D chain; it uses separate left and right padding and Fraction to retain the exact center. The second compares backward paths with forward-propagated impulse responses. This control’s all-ones kernels count paths; they are not intended as gradients of a trained CNN.

[ ]Receptive field calculatorBrowser
from fractions import Fraction

def receptive_field(layers, input_size):
    """Cadena 1D: centros 0.5, 1.5, ...; padding (izquierda, derecha)."""
    if isinstance(input_size,bool) or not isinstance(input_size,int) or input_size<1:
        raise ValueError('tamaño de entrada inválido')
    size=input_size
    rf,jump,center=1,1,Fraction(1,2)
    trace=[{'size':size,'rf':rf,'jump':jump,'center':center}]
    for layer in layers:
        k=layer['kernel']; s=layer.get('stride',1); d=layer.get('dilation',1)
        padding=layer.get('padding',(0,0))
        if (any(isinstance(v,bool) or not isinstance(v,int) or v<1 for v in (k,s,d))
            or not isinstance(padding,(tuple,list)) or len(padding)!=2
            or any(isinstance(v,bool) or not isinstance(v,int) or v<0 for v in padding)):
            raise ValueError('parámetros inválidos')
        left,right=padding
        size=(size+left+right-d*(k-1)-1)//s+1
        if size<1: raise ValueError('la capa no produce salidas')
        center += (Fraction((k-1)*d,2)-left)*jump
        rf += (k-1)*d*jump
        jump *= s
        trace.append({'size':size,'rf':rf,'jump':jump,'center':center})
    return trace

example=[{'kernel':3,'stride':2,'padding':(1,1)},
         {'kernel':2,'stride':2,'padding':(0,1)},
         {'kernel':3,'dilation':2,'padding':(2,2)}]
for i,row in enumerate(receptive_field(example,101)):
    print('nivel',i,row)
large = 10**400
assert receptive_field([{'kernel':large,'padding':(large,large)}],5)[-1]['center'] == Fraction(-large,2)
[ ]Paths and impulse controlBrowser
import numpy as np

def structural_paths(layers, size, chosen):
    """Retropropagación lineal con todos los pesos uno; padding constante."""
    trace=receptive_field(layers,size)
    if not 0<=chosen<trace[-1]['size']: raise ValueError('índice inválido')
    delta=np.zeros(trace[-1]['size'],dtype=np.int64); delta[chosen]=1
    for level in range(len(layers)-1,-1,-1):
        l=layers[level]; k=l['kernel']; s=l.get('stride',1); d=l.get('dilation',1); p=l.get('padding',(0,0))[0]
        prev=np.zeros(trace[level]['size'],dtype=np.int64)
        for i in range(len(delta)):
            for u in range(k):
                t=i*s-p+u*d
                if 0<=t<len(prev): prev[t]+=delta[i]
        delta=prev
    return delta

def impulse_forward(layers, size, chosen):
    """Un impulso por fila; calcula la salida con kernels de unos."""
    signals=np.eye(size,dtype=np.int64)
    trace=receptive_field(layers,size)
    for level,layer in enumerate(layers):
        k=layer['kernel']; s=layer.get('stride',1); d=layer.get('dilation',1); left=layer.get('padding',(0,0))[0]
        outputs=np.zeros((size,trace[level+1]['size']),dtype=np.int64)
        for i in range(outputs.shape[1]):
            for u in range(k):
                source=i*s-left+u*d
                if 0<=source<signals.shape[1]: outputs[:,i]+=signals[:,source]
        signals=outputs
    return signals[:,chosen]

for ds in ((1,2,4),(2,2,2)):
    layers=[{'kernel':3,'dilation':d,'padding':(d,d)} for d in ds]
    trace=receptive_field(layers,101); idx=trace[-1]['size']//2
    paths=structural_paths(layers,101,idx); support=np.flatnonzero(paths)
    assert np.array_equal(paths,impulse_forward(layers,101,idx))
    lo,hi=int(support[0]),int(support[-1]); state=trace[-1]
    assert hi-lo+1==state['rf']
    assert (lo+hi+1)/2==state['center']+idx*state['jump']
    print('dilataciones:',ds,'caja:',lo,hi,'alcanzables:',len(support),'rutas:',paths.sum())
    assert len(support)==(15 if ds==(1,2,4) else 7)

layers=[{'kernel':3,'stride':2,'padding':(1,1)},
        {'kernel':2,'stride':2,'padding':(0,1)},
        {'kernel':3,'dilation':2,'padding':(2,2)}]
state=receptive_field(layers,101)[-1]; idx=state['size']//2
paths=structural_paths(layers,101,idx); supp=np.flatnonzero(paths)
assert np.array_equal(paths,impulse_forward(layers,101,idx))
assert supp[-1]-supp[0]+1==state['rf']
assert (supp[0]+supp[-1]+1)/2==state['center']+idx*state['jump']
print('cadena mixta: caja',int(supp[0]),int(supp[-1]),'rutas',int(paths.sum()))

Local labs: training and hierarchy

The first program takes two different CIFAR-10 splits: training and a test probe. It retains the same network, channel and images before and after training, uses eval() when measuring and records map and radius rules. Module hooks capture activations without changing architecture. The short check uses 100 steps; the program offers a larger budget for you to run. The probe chooses channels and explores maps, so do not treat it as an independent performance estimate if you consult it to tune decisions.

[ ]CIFAR training and effective fieldLocal GPU
"""ResNet18 CIFAR: mismas unidades e imágenes antes y después de entrenar.

Requisitos: torch, torchvision, numpy, pyarrow, huggingface_hub y pillow.
ORYON_VERIFY_SHORT=1: 100 pasos; modo lector: 5000 pasos. Archivos de datos
se descargan a la caché común de Hugging Face. Salida: ORYON_ERF_OUTPUT.
"""
import io
import json
import os
from pathlib import Path
os.environ.setdefault('CUBLAS_WORKSPACE_CONFIG',':4096:8')
import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
from huggingface_hub import hf_hub_download
from PIL import Image
import torch
from torchvision.models import resnet18

torch.set_num_threads(1)
torch.manual_seed(20261102)
torch.use_deterministic_algorithms(True)
torch.backends.cudnn.benchmark=False
rng=np.random.default_rng(20261102)
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
short=os.environ.get('ORYON_VERIFY_SHORT')=='1'
steps=100 if short else 5000
train_count=2048 if short else 50000
batch_size=32
revision='0b27149'
def load_sample(split,count):
    path=hf_hub_download(repo_id='uoft-cs/cifar10',repo_type='dataset',
        filename=f'plain_text/{split}-00000-of-00001.parquet',revision=revision)
    table=pq.read_table(path)
    indices=rng.choice(len(table),size=count,replace=False)
    rows=table.take(pa.array(indices)).to_pylist()
    images=np.stack([np.asarray(Image.open(io.BytesIO(row['img']['bytes'])).convert('RGB'),dtype=np.uint8) for row in rows])
    labels=np.array([row['label'] for row in rows],dtype=np.int64)
    return torch.from_numpy(images).permute(0,3,1,2),torch.from_numpy(labels),indices.tolist()

train_x,train_y,train_indices=load_sample('train',train_count)
probe_x,probe_y,probe_indices=load_sample('test',8)
def normalized(x): return x.to(device=device,dtype=torch.float32)/127.5-1
net=resnet18(weights=None,num_classes=10)
# Adaptación CIFAR: stem 3x3 stride 1, sin maxpool; capas residuales estándar.
net.conv1=torch.nn.Conv2d(3,64,3,stride=1,padding=1,bias=False)
net.maxpool=torch.nn.Identity()
net=net.to(device)
stages={'layer1':(net.layer1,11,1),'layer2':(net.layer2,25,2),
        'layer3':(net.layer3,53,4),'layer4':(net.layer4,109,8)}
def feature(x,module):
    box=[]
    def capture(_m,_a,out): box.append(out)
    hook=module.register_forward_hook(capture)
    try: net(x)
    finally: hook.remove()
    return box[0]

net.eval()
channels={}
with torch.no_grad():
    for name,(module,rf,jump) in stages.items():
        f=feature(normalized(probe_x),module)
        channels[name]=int(f[:,:,f.shape[2]//2,f.shape[3]//2].mean(0).argmax().item())

def measure():
    net.eval()
    result={}
    for name,(module,rf,jump) in stages.items():
        maps=[]
        for sample in probe_x:
            x=normalized(sample[None]).requires_grad_(True)
            f=feature(x,module)
            iy,ix=f.shape[2]//2,f.shape[3]//2
            scalar=f[0,channels[name],iy,ix]
            grad,=torch.autograd.grad(scalar,x)
            maps.append(grad.detach().abs().sum(dim=1)[0].cpu().numpy())
        mass=np.mean(maps,axis=0).astype(np.float64)
        if not np.isfinite(mass).all(): raise FloatingPointError('gradiente no finito')
        total=float(mass.sum())
        norm=mass/total if total>0 else np.zeros_like(mass)
        center=(iy*jump,ix*jump)
        yy,xx=np.indices(mass.shape)
        distance=np.hypot(yy-center[0],xx-center[1]).ravel()
        order=np.argsort(distance,kind='stable')
        radius=float(distance[order[np.searchsorted(np.cumsum(norm.ravel()[order]),.9)]]) if total>0 else None
        result[name]={'channel':channels[name],'unit':[int(iy),int(ix)],'center_pixel':list(center),
                      'theoretical_rf':rf,'jump':jump,'mean_abs_gradient_sum':total,
                      'radius_90':radius,'normalized_mass':norm.tolist()}
    return result

before=measure()
net.train()
optimizer=torch.optim.SGD(net.parameters(),lr=0.005,momentum=0.9,weight_decay=5e-4)
batch_rng=np.random.default_rng(313)
history=[]
for step in range(steps):
    idx=torch.from_numpy(batch_rng.integers(0,train_count,size=batch_size))
    x=normalized(train_x[idx]); y=train_y[idx].to(device)
    optimizer.zero_grad(set_to_none=True)
    logits=net(x); loss=torch.nn.functional.cross_entropy(logits,y)
    if not torch.isfinite(loss): raise FloatingPointError('pérdida no finita')
    loss.backward(); optimizer.step()
    if step in (0,steps-1) or (step+1)%100==0:
        history.append({'step':step+1,'loss':float(loss.detach().cpu())})
after=measure()
result={'seed':20261102,'dataset':'uoft-cs/cifar10 test para sonda, train para entrenamiento',
        'dataset_revision':revision,'model':'torchvision ResNet18, stem CIFAR 3x3 stride 1 sin maxpool',
        'device':str(device),'torch_version':torch.__version__,'deterministic_algorithms':True,
        'short':short,'steps':steps,'batch_size':batch_size,
        'optimizer':{'name':'SGD','lr':0.005,'momentum':0.9,'weight_decay':0.0005},
        'train_count':train_count,'train_indices':train_indices if short else 'muestra aleatoria, semilla 20261102',
        'probe_indices':probe_indices,'probe_labels':probe_y.tolist(),
        'measurement':'media de |gradiente de la unidad| sobre 8 imágenes, suma por canales; radio 90% respecto al centro de la unidad',
        'selection':'canal de máxima media en la sonda antes de entrenar; se mantiene fijo',
        'before':before,'after':after,'history':history}
out=Path(os.environ.get('ORYON_ERF_OUTPUT','m16-l05-erf.json'))
out.write_text(json.dumps(result,ensure_ascii=False,allow_nan=False),encoding='utf-8')
print(json.dumps({'steps':steps,'device':str(device),'history':history,
    'radios':{name:[before[name]['radius_90'],after[name]['radius_90']] for name in stages},
    'channels':channels,'output':str(out)},ensure_ascii=False,indent=2))
del net,optimizer
if device.type=='cuda': 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.

The second program loads ImageNet-pretrained ResNet18, collects filters and activations with hooks removed afterward and calculates boxes per unit. It uses a different dataset and checkpoint: it is not the post-training state of the preceding CIFAR experiment. Images in the short check come from an ImageNet validation mirror resized to 256×256; center crop and preprocessing are stated in code.

[ ]Hierarchy in ImageNet ResNet18Local GPU
"""Filtros y activaciones reales de ResNet18 ImageNet, sin entrenamiento aquí.

Descarga en caché común de HF/Torch; ORYON_VERIFY_SHORT=1 usa 6 imágenes,
modo lector 30. No interpreta los canales como explicaciones causales.
"""
import base64
import hashlib
import io
import json
import os
from pathlib import Path
import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
from huggingface_hub import hf_hub_download
from PIL import Image
import torch
from torchvision.models import ResNet18_Weights,resnet18
from torchvision.transforms import functional as TF

torch.set_num_threads(1)
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
short=os.environ.get('ORYON_VERIFY_SHORT')=='1'
count=6 if short else 30
rng=np.random.default_rng(1701)
revision='1bd0400450249a7fe90c0aece37d0d03e7ea956a'
path=hf_hub_download(repo_id='benjamin-paine/imagenet-1k-256x256',repo_type='dataset',
    filename='data/validation-00000-of-00002.parquet',revision=revision)
table=pq.read_table(path)
names=json.loads(table.schema.metadata[b'huggingface'])['info']['features']['label']['names']
labels=table.column('label').to_numpy()
indices=rng.choice(np.flatnonzero(labels<1000),size=count,replace=False).tolist()
rows=table.take(pa.array(indices)).to_pylist()
images=[]; records=[]
for index,row in zip(indices,rows):
    original=Image.open(io.BytesIO(row['image']['bytes'])).convert('RGB')
    resized=TF.resize(original,256,interpolation=TF.InterpolationMode.BILINEAR,antialias=True)
    image=TF.center_crop(resized,[224,224]); images.append(TF.pil_to_tensor(image))
    buffer=io.BytesIO(); image.save(buffer,format='PNG',optimize=True)
    data=buffer.getvalue(); label=int(row['label'])
    records.append({'index':int(index),'label':names[label],
                    'imagenet_class':label,'image_sha256':hashlib.sha256(data).hexdigest(),
                    'image_mime':'image/png','image_base64':base64.b64encode(data).decode('ascii')})

net=resnet18(weights=ResNet18_Weights.IMAGENET1K_V1).to(device).eval()
stages={'conv1':(net.conv1,7,2),'layer1':(net.layer1,43,4),
        'layer2':(net.layer2,99,8),'layer3':(net.layer3,211,16),'layer4':(net.layer4,435,32)}
captured={}; handles=[]
for name,(module,rf,jump) in stages.items():
    def save(_module,_input,output,name=name): captured[name]=output.detach().cpu()
    handles.append(module.register_forward_hook(save))
batch=torch.stack(images).to(device=device,dtype=torch.float32)/255
mean=torch.tensor([.485,.456,.406],device=device)[None,:,None,None]
std=torch.tensor([.229,.224,.225],device=device)[None,:,None,None]
try:
    with torch.inference_mode(): logits=net((batch-mean)/std).cpu()
finally:
    for h in handles: h.remove()
for row,pred in zip(records,logits.argmax(dim=1).tolist()): row['top1']=pred

features={}
for name,(_module,rf,jump) in stages.items():
    activation=captured[name].numpy()
    scores=np.mean(np.max(activation,axis=(2,3)),axis=0)
    selected=np.argsort(-scores,kind='stable')[:4]
    channels=[]
    for channel in selected:
        items=[]
        for i in range(count):
            m=activation[i,channel]
            y,x=np.unravel_index(np.argmax(m),m.shape)
            yc,xc=int(y)*jump,int(x)*jump
            half=(rf-1)//2
            box=[max(0,yc-half),max(0,xc-half),min(224,yc+half+1),min(224,xc+half+1)]
            items.append({'image':i,'max':float(m[y,x]),'location':[int(y),int(x)],
                          'input_box_yxyx':box,'clipped':yc-half<0 or xc-half<0 or yc+half>=224 or xc+half>=224,
                          'map':m.tolist()})
        channels.append({'channel':int(channel),'mean_spatial_max':float(scores[channel]),
                         'top_images':sorted(range(count),key=lambda i:-items[i]['max'])[:3],
                         'per_image':items})
    features[name]={'rf':rf,'jump':jump,'center_first':0.5,'channels':channels}
result={'dataset':'benjamin-paine/imagenet-1k-256x256 validation',
        'revision':revision,'seed':1701,'device':str(device),'short':short,
        'model':'torchvision ResNet18 IMAGENET1K_V1','selection':'4 canales de mayor media del máximo espacial de las imágenes de sonda',
        'input':'crop central 224x224; normalización ImageNet',
        'first_layer_filters':net.conv1.weight.detach().cpu().numpy().tolist(),
        'records':records,'features':features}
out=Path(os.environ.get('ORYON_FEATURE_OUTPUT','m16-l05-features.json'))
out.write_text(json.dumps(result,ensure_ascii=False,allow_nan=False),encoding='utf-8')
print(json.dumps({'device':str(device),'images':count,'channels':{k:[v['channel'] for v in f['channels']] for k,f in features.items()},'output':str(out)},ensure_ascii=False))
del net
if device.type=='cuda': 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.

Exercises

NumericThrough conv5_3
In VGG-16, count 13 stride-one 3×3 convolutions with padding 1, and four stride-two 2×2 max pools after the first four blocks. Excluding pool5, what is the side length of conv5_3's receptive box?
NumericThree small kernels
With C=16 input and output channels in each layer, no groups and one bias per channel, how many parameters do three 3×3 convolutions have?
NumericOne large kernel
With the same 16 channels, no groups and bias, how many parameters does one 7×7 convolution have?
CodeSize, jump and center
Implement receptive_field(layers,input_size) for a 1D chain. input_size is a positive Python integer excluding bool. layers is a list or tuple of dictionaries with mandatory positive integer kernel and optional positive integer stride and dilation, defaulting to 1. padding is a pair (left,right) of nonnegative integers, defaulting to (0,0); do not accept bool. Return a list of dictionaries with size, rf, jump and center for input and each layer. Initialize (input_size,1,1,0.5), use the previous jump for rf and center and preserve the exact center even for large integers; you may use fractions.Fraction. Reject invalid configuration or empty output with ValueError.
def receptive_field(layers,input_size):
  pass
Shift+Enter to run
ProofFrom paths to a Gaussian
Prove: Justify the scale of the path distribution for n uniform 1D kernels [1,1,1], without boundaries or nonlinearities.
0
Each kernel position choice corresponds to an independent step in {−1,0,1}, with probability 1/3.

Step 1 of 2. What are one step’s mean and variance?

QuizSystematic holes
Three 3×3 kernels with stride one and no boundaries use per-axis dilations (1,2,4) or (2,2,2). What happens to structurally reachable positions?
[ ]Check exercise calculationsBrowser
layers=[]
for block,count in enumerate((2,2,3,3,3)):
    layers += [{'kernel':3,'padding':(1,1)}]*count
    if block<4: layers.append({'kernel':2,'stride':2})
print('VGG conv5_3:',receptive_field(layers,224)[-1])
c=16
print('Tres 3×3 y una 7×7 con sesgo:',3*(9*c*c+c),49*c*c+c)
Key idea

The structural box bounds possible paths; exact support requires respecting each layer’s boundaries, and a gradient map measures local sensitivity for a particular input and network. A large box does not guarantee large influence or causally explain a prediction.

References