AI Wiki中文/EN

AlexNet: architecture, compute and evaluation

AlexNet 架构

Reconstruct grouped convolution, LRN and overlapping pooling, then keep implementation and benchmark conventions explicit.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Start with an experiment

The 2012 network did not fit comfortably on a single 3 GB GPU, so its authors divided computation across two GPUs and limited communication between them. That hardware choice appears in the connectivity: some convolutional layers see only half the preceding maps, while another layer mixes information from both halves.

AlexNet is useful to study as a complete experimental design: a large labeled dataset, learned convolutional features, ReLU activations, regularization, data augmentation and substantial computation. A layer list alone does not reproduce its result. This chapter reconstructs the grouped architecture and several operations in a small CPU program, then separates the program’s explicit conventions from the paper and other teaching versions. Krizhevsky et al., 2012

The model and its assumptions

The paper describes five convolutional layers followed by two 4096-unit hidden fully connected layers and a 1000-class output. Convolutional output widths are 96,256,384,384,256. Layers 2,4 and 5 use two groups; layer 3 connects to all preceding maps. ReLU is max⁡(0,a)\max(0,a), allowing a nonzero derivative for positive inputs while still permitting inactive units on the negative side.

For an input side L, kernel side K, stride s and symmetric padding p, our floor-based output convention is:

Lout=⌊L+2p−Ks⌋+1.L_{\mathrm{out}}=\left\lfloor\frac{L+2p-K}{s}\right\rfloor+1.

The paper states a 224-pixel input and an 11-pixel first kernel with stride 4. Without a padding convention, those numbers alone do not specify a 55-pixel result: p=0 gives 54, whereas p=2 gives 55. Our program chooses p=2 explicitly. It does not claim to recover every detail of the original GPU implementation. D 2 L’s inspected PyTorch teaching class instead uses padding 1 and omits explicit grouping and local response normalization; its framework variants are not all identical either. Krizhevsky et al., 2012 D2L: AlexNet

With g groups dividing both channel counts, a biased convolution has:

P=Cout(K2Cing+1).P=C_{\mathrm{out}}\left(K^2\frac{C_{\mathrm{in}}}{g}+1\right).

The spatial multiplication count is HoutWoutCoutK2Cin/gH_{\mathrm{out}}W_{\mathrm{out}}C_{\mathrm{out}}K^2C_{\mathrm{in}}/g multiply-accumulates, excluding bias, activation and pooling work. Groups change which inputs a filter can use, not just the implementation speed.

The original local response normalization operates across neighbouring channels at the same pixel, after ReLU:

bc=ac(2+10−4∑j∈Ncaj2)0.75.b_c=\frac{a_c}{\left(2+10^{-4}\sum_{j\in\mathcal N_c}a_j^2\right)^{0.75}}.

The neighbourhood contains up to five channels, clipped at the ends. This is a sum; inserting a division by five while keeping the same coefficient changes the operation. It also differs from batch normalization and does not subtract a batch mean. Three-by-three max pooling with stride two follows the first two normalization layers and the fifth convolution, so adjacent pooling windows overlap. Krizhevsky et al., 2012

The first two hidden fully connected layers use dropout. The paper’s non-inverted convention drops units with probability 0.5 during training and multiplies their outputs by 0.5 at test time. An inverted-dropout implementation scales surviving training activations instead. The mean-activation conventions can be reconciled, but the deterministic test network is not the exact average of every nonlinear masked network. Our program uses the paper-style deterministic factor and performs no training dropout. Krizhevsky et al., 2012

A complete small program

The full-size plan allocates no full-size weights: it traces shapes and counts parameters. The forward demonstration retains all eight weighted stages, grouping, LRN, overlapping pooling and hidden-layer scaling, but uses 64-by-64 RGB input, narrower channels,16-unit hidden layers and ten outputs. It uses sampled weights, not pretrained recognition features. Run with Python 3.12 and NumPy 1.26.4.

import numpy as np

def plan(side=224,channels=(96,256,384,384,256),hidden=4096,classes=1000):
    if type(side) is not int or side<1 or len(channels)!=5 or any(type(n) is not int or n<1 for n in (*channels,hidden,classes)):
        raise ValueError('positive integer dimensions required')
    # Explicit teaching convention: first convolution uses symmetric padding 2.
    specs=zip(channels,(11,5,3,3,3),(4,1,1,1,1),(2,2,1,1,1),(1,2,1,2,2))
    n,cin=side,3;layers=[]
    for i,(cout,k,stride,padding,groups) in enumerate(specs,1):
        if cin%groups or cout%groups:raise ValueError('channel counts must divide into groups')
        n=(n+2*padding-k)//stride+1
        if n<1:raise ValueError('spatial extent collapsed')
        layers.append(dict(kind='conv',name=f'conv{i}',cin=cin,cout=cout,k=k,stride=stride,padding=padding,groups=groups,
                           shape=(n,n,cout),parameters=cout*(cin//groups*k*k+1)))
        cin=cout
        if i in (1,2):layers.append(dict(kind='lrn',name=f'lrn{i}',parameters=0))
        if i in (1,2,5):
            n=(n-3)//2+1
            if n<1:raise ValueError('pooling extent collapsed')
            layers.append(dict(kind='pool',name=f'pool{i}',shape=(n,n,cout),parameters=0))
    cin=n*n*cin
    for i,cout in enumerate((hidden,hidden,classes),1):
        layers.append(dict(kind='fc',name=f'fc{i}',cin=cin,cout=cout,parameters=cin*cout+cout));cin=cout
    return layers

def grouped_conv(image,weights,bias,stride=1,padding=0,groups=1):
    a,w,b=np.asarray(image,dtype=float),np.asarray(weights,dtype=float),np.asarray(bias,dtype=float)
    if any(type(n) is not int or n<1 for n in (stride,groups)) or type(padding) is not int or padding<0:
        raise ValueError('invalid stride, padding or group count')
    if a.ndim!=3 or w.ndim!=4 or w.shape[2]!=w.shape[3] or a.shape[2]%groups or w.shape[0]%groups or w.shape[1]!=a.shape[2]//groups or b.shape!=(w.shape[0],):
        raise ValueError('incompatible grouped-convolution shapes')
    if min(a.shape)<1 or min(w.shape)<1 or not all(np.isfinite(v).all() for v in (a,w,b)):
        raise ValueError('finite nonempty arrays required')
    padded=np.pad(a,((padding,padding),(padding,padding),(0,0)));k=w.shape[2]
    if min(padded.shape[:2])<k:raise ValueError('kernel larger than padded input')
    windows=np.lib.stride_tricks.sliding_window_view(padded,(k,k),axis=(0,1))[::stride,::stride]
    ci,co=a.shape[2]//groups,w.shape[0]//groups
    return np.concatenate([np.einsum('hwcij,ocij->hwo',windows[:,:,g*ci:(g+1)*ci],w[g*co:(g+1)*co])+b[g*co:(g+1)*co] for g in range(groups)],axis=2)

def lrn(image):
    a=np.asarray(image,dtype=float)
    if a.ndim!=3 or min(a.shape)<1 or not np.isfinite(a).all():raise ValueError('finite HWC array required')
    # The paper uses alpha times a sum; no division by the window size.
    return np.stack([a[:,:,c]/(2+1e-4*(a[:,:,max(0,c-2):c+3]**2).sum(axis=2))**.75 for c in range(a.shape[2])],axis=2)

def max_pool(image):
    a=np.asarray(image,dtype=float)
    if a.ndim!=3 or min(a.shape[:2])<3 or a.shape[2]<1 or not np.isfinite(a).all():raise ValueError('finite HWC input at least 3x3 required')
    return np.lib.stride_tricks.sliding_window_view(a,(3,3),axis=(0,1))[::2,::2].max(axis=(-1,-2))

def tiny_forward(image,seed=13):
    a=np.asarray(image,dtype=float)
    if a.shape!=(64,64,3) or not np.isfinite(a).all():raise ValueError('tiny model expects finite 64x64 RGB input')
    rng=np.random.default_rng(seed);trace=[]
    for l in plan(64,(4,8,12,12,8),16,10):
        if l['kind']=='conv':
            w=rng.normal(scale=.01,size=(l['cout'],l['cin']//l['groups'],l['k'],l['k']))
            b=np.full(l['cout'],1. if l['name'] in ('conv2','conv4','conv5') else 0.)
            a=np.maximum(grouped_conv(a,w,b,l['stride'],l['padding'],l['groups']),0)
        elif l['kind']=='lrn':a=lrn(a)
        elif l['kind']=='pool':a=max_pool(a)
        else:
            w=rng.normal(scale=.01,size=(l['cin'],l['cout']));a=a.ravel()@w
            # Original non-inverted dropout convention: deterministic test-time factor.
            if l['name']!='fc3':a=.5*np.maximum(a+1,0)
        trace.append((l['name'],a.shape))
    probabilities=np.exp(a-a.max());probabilities/=probabilities.sum()
    return probabilities,trace

if __name__=='__main__':
    full=plan()
    print('weight layers:',sum(l['kind'] in ('conv','fc') for l in full))
    print('parameters with stated padding/groups:',sum(l['parameters'] for l in full))
    print('full convolution shapes:',[l['shape'] for l in full if l['kind']=='conv'])
    print('224, k11, stride4, padding0 versus2:',(224-11)//4+1,(224+4-11)//4+1)
    p,trace=tiny_forward(np.random.default_rng(9).normal(size=(64,64,3)))
    print('untrained tiny probabilities:',p.round(5).tolist());print('sum:',round(float(p.sum()),12))
weight layers: 8
parameters with stated padding/groups: 60965224
full convolution shapes: [(55, 55, 96), (27, 27, 256), (13, 13, 384), (13, 13, 384), (13, 13, 256)]
224, k11, stride4, padding0 versus2: 54 55
untrained tiny probabilities: [0.10117, 0.09986, 0.09909, 0.10199, 0.09972, 0.10444, 0.10064, 0.09667, 0.10044, 0.09596]
sum: 1.0

The 60965224 count follows from the stated channels, groups, biases and resulting six-by-six final pooled map. It should not be attached to another implementation merely because that implementation is named AlexNet. Likewise, the small output probabilities sum to one but provide no evidence of recognition accuracy.

Tests use a literal multichannel/group/stride reference, prove that changing one group’s input leaves the other group’s output unchanged, check LRN’s boundary sums, verify overlapping pooling and execute the complete narrow forward graph. Invalid groups and collapsed spatial dimensions are rejected.

Limits and comparisons

The paper reports training with batch size 128, momentum 0.9 and weight decay 0.0005, along with random crops, horizontal reflections and color perturbations. It describes roughly 90 passes through 1.2 million training images, taking five to six days on two NVIDIA GTX 580 GPUs with 3 GB of memory each. These are historical experimental conditions, not an estimate for current hardware or this program. The small example does not reproduce training, augmentation, optimizer state or GPU communication. Krizhevsky et al., 2012

Keep evaluation conditions attached to numbers. The proceedings PDF’s Table 2 distinguishes a single CNN’s 18.2% top-five validation error from the pretrained seven-model ensemble’s 15.3% test error. The latter is not the performance of every single AlexNet instance. The authors discuss validation and test rates together in prose, but their table labels should be preserved when explaining the result. Krizhevsky et al., 2012

LRN, grouping and pooling can be changed in later implementations, and trained weights depend on those conventions. A checkpoint with matching layer names but different connectivity or preprocessing is not automatically compatible. Compare tensor shapes and operations before importing weights. Image classification gives a small example of why an impressive familiar-distribution score also needs a meaningful test design.

Exercises with answers

1. Compute the first-layer side for L=224,K=11,s=4,p=0 and p=2.

Answer. The floor formula gives 54 and 55 respectively. Padding must be explicit; the network name cannot supply it.

2. How many parameters does the grouped second convolution have?

Answer. There are 256 outputs, each using 48 input channels with 25 weights per channel plus one bias:256×(48×25+1)=307456.

3. Is alpha times the average of five squared responses identical to alpha times their sum?

Answer. No. With the same alpha it is smaller by five for a full five-channel window. Match the formula and boundary rule when transferring hyperparameters.

4. Can 15.3% test error be quoted as the error of the single model used in the 18.2% row?

Answer. No. Those rows differ in model count, pretraining and evaluation split. Preserve the single-model validation versus ensemble-test distinction.

Sources and next steps

The source is the 2012 proceedings PDF; the bounded architecture, regularization, training and comparison passages were checked. D 2 L supplies a concrete teaching variant to compare, not a substitute specification for the paper. No upstream model code or weights are redistributed. Krizhevsky et al., 2012 D2L: AlexNet

Continue with VGG to study repeated small-filter blocks, and Inception for parallel branches that allocate computation differently. AlexNet history covers the historical setting separately.

Make a prediction, then check

Which first-layer convention does this teaching program use for 224-pixel input?

Choose one answer

Learning objectives

  • Calculate grouped parameter counts and spatial dimensions with explicit conventions.
  • Distinguish architectural changes and single-model versus ensemble evidence.

Prerequisites & connections

Explore related knowledge →

References

  1. ImageNet Classification with Deep Convolutional Neural Networks — architecture and training passages
    Alex Krizhevsky; Ilya Sutskever; Geoffrey E. Hinton · 2012
  2. Dive into Deep Learning 1.0.3 — alexnet
    Aston Zhang; Zachary C. Lipton; Mu Li; Alexander J. Smola

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-07 · Codex single-AI-author technical check: bounded primary-source passages, explicit image classification experiments and CNN architecture models, executed programs, independent mathematical references, input boundaries and bilingual alignment. Not independent human or second-agent review; no full-system research reproduction claimed.

  • Single-agent authored technical review; runnable example, exact or literal reference checks, explicit assumptions and matching bilingual equations/exercises. Automated execution and rendering results recorded separately.
  • 6 tests: explicit-padding/group parameter totals, literal grouped strided convolution and group isolation, channel-sum LRN, overlapping pooling, complete narrow forward pass and invalid groups. Added original non-inverted dropout test-time 0.5 factors after rereading section 4.2. Not an original GPU/training reproduction.
  • Single AI author compared both locales across six sections, assumptions, definitions, equations, executed code and output, four exercise/answer pairs and scoped citations.43 checks across six draft articles; not independent human review or full historical training reproduction.
  • Complete bilingual prose and corresponding exercises promoted with formal status and SHA binding. Algorithm tests read formal MDX; historical essays claim no executable program or computational tests.
  • After visual reading review, shortened/localized inline citation labels. Verified ordered link targets and every protected code/math/tag span unchanged; full source identities remain in metadata. Frozen drafts preserved and final article SHA rebound.
  • Final copy review separated the GPU model number GTX580 from the3GB per-GPU memory specification in both languages, matching the inspected paper. This removes an ambiguous joined numeric string; no program or benchmark values changed.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.