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.