Backprop to the input: the same gradient, aimed at the image instead of the weights

Training asks: how should each weight change to lower the loss on this example? An attack asks: how should the input change to raise it? Both are answered by the same backward pass through the same network. Training stops it at the weights; the attack carries it one step further, through the first layer, to the input. Below, a small network learns to separate two classes in the plane. Pick a point, run the backward pass, and use the gradient either way.

use the gradient for
The network and the input planeLeft, a diagram of a network with two inputs, six hidden units and two outputs, showing values from the forward pass and gradients from the backward pass. Right, the input plane colored by the network's decision, with the training points and the selected point; in attack mode an arrow shows the gradient with respect to the input.
Click a point in the plane to select it, or click anywhere to place a new one. Its class is the one it was drawn from; a new point takes the class the network gives it.
One backward pass, two stopping places. The forward pass computes a = W1x + b1, h = tanh(a), z = W2h + b2, p = softmax(z), and the loss L = −log py. Backward, the chain rule gives ∂L/∂z = p − onehot(y), then ∂L/∂h = W2T(p − y), then ∂L/∂a = ∂L/∂h ⊙ (1 − h2). Every quantity so far is needed for both uses. Training then takes ∂L/∂W1 = (∂L/∂a) xT and moves the weights downhill, which moves the boundary. The attack takes ∂L/∂x = W1T(∂L/∂a), one more multiplication by the weights, and moves the input instead, while the weights stay frozen. Nothing new is needed: in PyTorch it is x.requires_grad_(True) and loss.backward(), then read x.grad instead of the weights’ .grad.
Which way to step. Training goes downhill on the loss for the true label. An attack can go uphill on the true label’s loss (untargeted), or downhill on the loss for a chosen wrong label (targeted, as in Szegedy et al.). Here the attack is targeted at the other class: x ← x − α ∂L(x, target)/∂x. In two dimensions the point has to travel visibly to cross the boundary. On an MNIST image the input has 784 dimensions, and a step of the same total length, spread over all the pixels in exactly the right pattern, is almost invisible; that is where finding an adversarial example picks up.