%%capture
from pathlib import Path
import matplotlib.pyplot as plt
import torch
from torch.utils.data import DataLoader, Subset
from torchvision import datasets, models, transforms
style = Path("../figure_style.mplstyle")
plt.style.use(str(style) if style.exists() else
"https://csci145.rtealwitter.com/topics/figure_style.mplstyle")
weights = models.AlexNet_Weights.DEFAULT
model = models.alexnet(weights=weights, progress=False).eval()
model.requires_grad_(False)
preprocess = weights.transforms()
normalize = transforms.Normalize(preprocess.mean, preprocess.std)
class_names = weights.meta["categories"]Demo: Can a Tiny Change Fool AlexNet?
The reading built convolutions from shared filters. Let’s see those same filters inside a trained image classifier, use it to recognize a dog, and then change its prediction by optimizing a tiny change to the image.
AlexNet
AlexNet (2012) stacks five convolutional layers before its fully connected classifier. The input has three channels: red, green, and blue. Convolutions produce new channels of learned features, while stride and pooling reduce the spatial dimensions.
C1–C5 number the convolutional layers, and the orange stacks show their output feature maps. A convolutional block usually groups a convolution with its activation and sometimes pooling. This overview omits the ReLU and pooling operations that appear in the model printout below.
Let’s load TorchVision’s pretrained AlexNet. TorchVision uses a later AlexNet variant with different channel counts, so its first convolution has 64 output channels rather than the diagram’s 96. Its weights were trained on ImageNet-1K, which has 1,000 labels. eval() turns off dropout, and requires_grad_(False) freezes the learned weights.
A CPU is sufficient. The first run downloads about 233 MiB of weights and 94 MiB of images. Later runs reuse the cached files. %%capture hides the download messages.
Inspect the Convolutions
Print the actual network. In each Conv2d line, the first two numbers are the input and output channel counts. The kernel size, stride, and padding are the same parameters we used in the reading. features contains the convolutions and pooling. classifier contains the fully connected layers.
print(model)AlexNet(
(features): Sequential(
(0): Conv2d(3, 64, kernel_size=(11, 11), stride=(4, 4), padding=(2, 2))
(1): ReLU(inplace=True)
(2): MaxPool2d(kernel_size=3, stride=2, padding=0, dilation=1, ceil_mode=False)
(3): Conv2d(64, 192, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))
(4): ReLU(inplace=True)
(5): MaxPool2d(kernel_size=3, stride=2, padding=0, dilation=1, ceil_mode=False)
(6): Conv2d(192, 384, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(7): ReLU(inplace=True)
(8): Conv2d(384, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(9): ReLU(inplace=True)
(10): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(11): ReLU(inplace=True)
(12): MaxPool2d(kernel_size=3, stride=2, padding=0, dilation=1, ceil_mode=False)
)
(avgpool): AdaptiveAvgPool2d(output_size=(6, 6))
(classifier): Sequential(
(0): Dropout(p=0.5, inplace=False)
(1): Linear(in_features=9216, out_features=4096, bias=True)
(2): ReLU(inplace=True)
(3): Dropout(p=0.5, inplace=False)
(4): Linear(in_features=4096, out_features=4096, bias=True)
(5): ReLU(inplace=True)
(6): Linear(in_features=4096, out_features=1000, bias=True)
)
)
The first convolution maps 3 input channels to 64 output channels using 11 × 11 kernels, stride 4, and padding 2. One output channel combines a local patch from all three input channels. The same weights are reused at every spatial position.
Predict: What shape should its weight tensor have? What changes in later convolutions?
PyTorch stores convolution weights as output channels × input channels × kernel height × kernel width. Let’s inspect all five.
for layer in model.features:
if isinstance(layer, torch.nn.Conv2d):
print(tuple(layer.weight.shape))(64, 3, 11, 11)
(192, 64, 5, 5)
(384, 192, 3, 3)
(256, 384, 3, 3)
(256, 256, 3, 3)
The first shape, (64, 3, 11, 11), means 64 filters, each spanning all three color channels. Later filters combine the feature channels produced by earlier layers. These are the reading’s 2D convolutions applied repeatedly, with learned kernels.
Load Some Images
We use Imagenette, a ten-class ImageNet subset available through TorchVision. Our examples include two dogs, a truck, and a parachute. AlexNet still chooses among all 1,000 ImageNet labels.
We resize and take a 224 × 224 center crop using the settings supplied with the weights. ToTensor() gives RGB values in \([0,1]\), and DataLoader stacks the images into a batch. We keep those RGB values for display and perturbation. Before each network call, normalize(images) applies the pretrained model’s channel means and standard deviations using TorchVision’s Normalize transform.
%%capture
image_transform = transforms.Compose([
transforms.Resize(preprocess.resize_size, interpolation=preprocess.interpolation),
transforms.CenterCrop(preprocess.crop_size),
transforms.ToTensor(),
])
dataset = datasets.Imagenette(
root="data", split="val", size="160px", download=True, transform=image_transform,
)
indices = [409, 404, 2328, 3535] # Two dogs, a truck, and a parachute.
loader = DataLoader(Subset(dataset, indices), batch_size=4, shuffle=False)
images, dataset_labels = next(iter(loader))Here are the input crops and their dataset labels. Predict: Which labels will AlexNet choose?
fig, axes = plt.subplots(1, 4, figsize=(9, 2.7), layout="constrained")
for i, ax in enumerate(axes):
ax.imshow(images[i].permute(1, 2, 0))
ax.set_xlabel(dataset.classes[dataset_labels[i].item()][0])
ax.set_xticks([])
ax.set_yticks([])
plt.show()
Predict the Labels
The network returns one score, or logit, per ImageNet class. Softmax converts these scores into probabilities. We display the top prediction for every image and the five largest probabilities for the first image.
with torch.no_grad():
logits = model(normalize(images))
probabilities = logits.softmax(dim=1)
predicted_labels = probabilities.argmax(dim=1)
for i, predicted in enumerate(predicted_labels.tolist()):
actual = dataset.classes[dataset_labels[i].item()][0]
print(f"Image {i}: dataset = {actual}, prediction = {class_names[predicted]} "
f"({probabilities[i, predicted]:.1%})")
values, labels = probabilities[0].topk(5)
fig, ax = plt.subplots(figsize=(7, 2.8), layout="constrained")
ax.barh([class_names[label] for label in labels.tolist()], values.tolist())
ax.invert_yaxis()
ax.set_xlim(0, 1)
ax.set_xlabel("Predicted Probability")
plt.show()Image 0: dataset = English springer, prediction = English springer (77.1%)
Image 1: dataset = English springer, prediction = English springer (74.2%)
Image 2: dataset = garbage truck, prediction = trailer truck (28.6%)
Image 3: dataset = parachute, prediction = parachute (98.3%)

Adversarial Input
Let’s change the English springer image so AlexNet gives the correct label a low probability. We hold the network weights fixed and treat an additive perturbation \(\boldsymbol{\delta}\) as the parameter. Backpropagation differentiates through the network and normalization to tell us how to change the pixels.
Let \(\mathbf x\) be the original RGB image and \(y\) its correct label. We minimize
\[ \log p_y(\mathbf x+\boldsymbol{\delta}). \]
Lower log probability means lower probability. We do not choose which wrong label should replace English springer. This is an untargeted attack.
Adam updates only the perturbation. After each step, we rescale it to keep \(\|\boldsymbol{\delta}\|_\infty=\varepsilon\): the largest absolute RGB change is always \(\varepsilon\). With \(\varepsilon=8/255\), that is eight levels on the usual 0–255 scale. We leave RGB values within \(\varepsilon\) of 0 or 1 unchanged so the image stays valid without clipping changing this norm. This uses the input gradients described in PyTorch’s adversarial example tutorial.
We draw 128 random perturbations with this same fixed norm. Both attacks start from the first draw, so their initial probabilities match. The other draws will give us a comparison in the final plot.
The attack function records the probabilities after each update. We will reuse it for a chosen label in the next section. Predict: Will the dog still look like a dog when AlexNet changes its prediction?
image_index = 0
original = images[image_index:image_index + 1].clone()
actual_name = dataset.classes[dataset_labels[image_index].item()][0]
correct_class = class_names.index(actual_name)
assert probabilities[image_index].argmax().item() == correct_class
epsilon = 8 / 255
steps = 40
learning_rate = 0.25 / 255
editable = (original >= epsilon) & (original <= 1 - epsilon)
def fixed_norm(change):
change = change * editable
norm = change.abs().amax(dim=(-3, -2, -1), keepdim=True)
return epsilon * change / norm.clamp_min(1e-12)
torch.manual_seed(7)
random_changes = fixed_norm(2 * torch.rand(128, *original.shape[1:]) - 1)
def attack(label, targeted=False):
delta = random_changes[:1].clone().requires_grad_()
optimizer = torch.optim.Adam([delta], lr=learning_rate)
with torch.no_grad():
history = [model(normalize(original + delta)).softmax(dim=1)[0]]
for step in range(steps):
optimizer.zero_grad()
scores = model(normalize(original + delta))
log_probability = scores.log_softmax(dim=1)[0, label]
loss = -log_probability if targeted else log_probability
loss.backward()
optimizer.step()
with torch.no_grad():
delta.copy_(fixed_norm(delta))
history.append(model(normalize(original + delta)).softmax(dim=1)[0])
return (original + delta).detach(), torch.stack(history)
away_image, away_history = attack(correct_class)Here is the original dog beside the result. The middle panel amplifies the perturbation: gray means no change, and the allowed range \([-\varepsilon,\varepsilon]\) fills the display range. The original and perturbed images use the same RGB scale.
def show_attack(perturbed, history):
predicted = history[-1].argmax().item()
visible_change = (0.5 + (perturbed - original) / (2 * max(epsilon, 1e-12))).clamp(0, 1)
fig, axes = plt.subplots(1, 3, figsize=(9, 3), layout="constrained")
labels = [f"Original: {actual_name}", "Perturbation (Amplified)",
f"Prediction: {class_names[predicted]}\n({history[-1, predicted]:.1%})"]
for ax, pixels, label in zip(axes, [original, visible_change, perturbed], labels):
ax.imshow(pixels[0].permute(1, 2, 0))
ax.set_xlabel(label)
ax.set_xticks([])
ax.set_yticks([])
plt.show()
print(f"English springer probability (original → final): {probabilities[image_index, correct_class]:.1%} "
f"→ {history[-1, correct_class]:.1%}")
show_attack(away_image, away_history)
English springer probability (original → final): 77.1% → 0.0%
Adversarial Input with a Chosen Label
Now let’s ask for a particular wrong answer: tabby, a kind of cat. This is a targeted attack. Starting again from the same randomly perturbed dog, we minimize the negative log probability of our chosen label \(t\):
\[ -\log p_t(\mathbf x+\boldsymbol{\delta}). \]
The minus sign makes gradient descent increase the chosen label’s probability. In attack, targeted=True changes that sign. We use the same starting perturbation, fixed norm, learning rate, and number of steps. Adam starts fresh. Each update changes the perturbation while preserving its norm.
Predict: Will pushing away from English springer and pushing toward tabby produce the same perturbation?
target_name = "tabby" # Try "Persian cat" or "Siamese cat" next.
target_class = class_names.index(target_name)
toward_image, toward_history = attack(target_class, targeted=True)
show_attack(toward_image, toward_history)
print(f"{target_name.capitalize()} probability: {toward_history[0, target_class]:.1%} "
f"→ {toward_history[-1, target_class]:.1%}")
English springer probability (original → final): 77.1% → 0.0%
Tabby probability: 0.0% → 95.3%
Probabilities by Step
Does any small change have this effect? Evaluate each of our 128 fixed random perturbations once. Every random perturbation and every attack step has the same maximum absolute RGB change, \(\|\boldsymbol{\delta}\|_\infty=\varepsilon\). This fixes the maximum change per RGB value, not the sum of squared changes over the image.
Every line below tracks the probability of the correct label, English springer, including the attack aimed at tabby. Each faint horizontal line is one fixed random perturbation. Its probability stays constant because it is never optimized. Both attacks begin at the first random perturbation, then change its pattern while keeping its norm fixed. These are comparisons on one dog, not accuracy estimates over a dataset.
with torch.no_grad():
random_probabilities = model(normalize(original + random_changes)).softmax(dim=1)[:, correct_class]
fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
ax.hlines(random_probabilities, 0, steps, color="0.75", linewidth=0.7, alpha=0.35,
label="128 Fixed Random Perturbations")
ax.plot(away_history[:, correct_class], label="Away from English Springer",
marker="o", markersize=3, markevery=4)
ax.plot(toward_history[:, correct_class], label=f"Toward {target_name.capitalize()}",
linestyle="--", linewidth=2)
ax.set_xlabel("Optimization Step")
ax.set_ylabel("English Springer Probability")
ax.set_xlim(0, steps)
ax.set_ylim(0, 1)
ax.legend(loc="lower left", bbox_to_anchor=(0, 1), fontsize=10)
plt.show()
Both attacks use the network’s derivatives to choose the changes. The untargeted attack lowers the correct label’s probability directly. The targeted attack raises the chosen label’s probability, making the other labels compete for less probability. The displayed images let us compare those changes with what we can see. The network’s weights never changed.
Try it: Change target_name to another ImageNet label and rerun the targeted attack and final comparison. Then change epsilon and rerun both attacks. How much change is needed to get the chosen label? Failure to find a perturbation in a fixed number of steps does not establish robustness.