Cheap Defense Against Attention Hijacking in Vision Transformers

Vision Transformers (ViTs), image models that cut a picture into small square patches and let every patch "look at" every other through attention, can be broken by corrupting a single patch. The corrupted patch pulls the attention of the whole image toward itself. Patch-Fool shows that this drops DeiT-S on ImageNet to 6.25% accuracy with one attacked patch, while a ResNet-50 holds 24.00%. The same work reports that standard adversarial training, which retrains the model on worst-case perturbed images, helps but leaves ViTs weaker than CNNs. Adversarial training is also very expensive at high resolution and large model size, because each training step runs an inner attack loop of many forward and backward passes through the full network.

This note proposes a defense that exploits where the hijacking happens. Patch-Fool picks its patch using attention in an intermediate block (layer 5 of DeiT). That suggests hijacking is settled early in the network, so the attack used during training only needs to run through those first blocks. We freeze the pretrained backbone. We train only a few hundred to a few thousand parameters: a handful of learnable input tokens, plus learnable per-head limits on how large any single attention score can grow. The training signal asks attention in the early blocks to stay the same on clean and patch-attacked images. The inner attack then costs a fraction of a full pass, and the outer update touches almost nothing. The claim is that this restores patch robustness on high-resolution ViTs and foundation backbones at a small fraction of the cost of adversarial training. A second claim is that the learned attention limits, not the tokens, carry most of the benefit, for a structural reason given below.

Core Claim

The closest existing work is Robustness Tokens. It appends about 10 learnable tokens to a frozen ViT and trains them for 200 steps so that features of attacked images match clean features. On DINOv2-G this lifts white-box accuracy from 0.3% to 63.1% with clean accuracy essentially unchanged (85.2% vs 85.6%). It was evaluated against dense whole-image noise, not localized attention hijacking.

There is a simple reason to expect appended tokens alone to struggle against hijacking. In the block where they are added, extra tokens only add terms to the softmax denominator. The ratio of attention a query gives the attacked patch versus any other image patch is therefore unchanged. Tokens can change routing only indirectly, by altering the representations that later blocks compute queries from. Hijacking, however, is decided in exactly those early blocks.

We therefore add a direct routing control: a learned, per-head soft cap on pre-softmax attention scores in the first $\ell$ blocks. With $s_{ij}$ the score from query $i$ to key $j$ in a given head, and $\mu_i, \sigma_i$ the mean and standard deviation of that query's scores, the capped score is

$$\tilde s_{ij} = \mu_i + \kappa \,\sigma_i \tanh\!\left(\frac{s_{ij}-\mu_i}{\kappa\,\sigma_i}\right),$$

where $\kappa > 0$ is learned separately for each head and block. Normal scores pass nearly unchanged. Outliers saturate at about $\kappa$ standard deviations above the mean. This makes the fixed cap of Max Attention Suppression in RAM learnable and differentiable, and trains it adversarially.

The training loss has three terms. An attention-preservation term is the KL divergence between clean and attacked attention rows in blocks $1..\ell$, restricted to image tokens. It adapts the attention-preservation idea of Attention, Please!, which used it with full CNN adversarial training, to frozen ViTs. The other two are the invariance and feature-correction terms of Robustness Tokens.

The inner attack maximizes attention captured by the chosen patch at block $\ell$, computed on the network truncated at $\ell$. With $k$ attack steps on an $L$-block model, the cost per example is roughly $k\ell/L$ plus one full pass, versus $k$ plus one for full-depth adversarial training. For a 40-block giant model with hijacking settled by block 8, that is about a five-fold cut in attack cost, on top of not updating the backbone.

This approach differs from YOPO (You Only Propagate Once) in which part of the network it uses. YOPO confines the attack to layer 1, which cannot simulate the intermediate-block attention exploits identified by Patch-Fool and by Attacking Attention of Foundation Models. We truncate at the depth where the attack actually operates. That depth is measured, not assumed.

Research Program

Measuring the hijack depth. For DeiT-S, DeiT-III-B and DINOv2-B/G, we sweep the truncation layer $\ell$ and run attention-only Patch-Fool attacks against each truncated network. We then measure how much each attack degrades the full model. This gives a transfer curve, full-model accuracy drop against $\ell$, at 224 and 518 pixels. It tells us whether the truncation idea holds at all.

Training the defense. On a frozen backbone, we train tokens and caps on ImageNet-1k with 1-patch and 2-patch Patch-Fool examples crafted at the measured $\ell$. Training budgets range from 200 to 2,000 steps. Linear heads come from the published checkpoints. For dense prediction, we train with a DINOv2 segmentation head on ADE20K.

Testing whether the capped attention is robust or only hiding gradients. Saturating functions can starve gradient-based attacks of signal and look robust when they are not, as single-step adversarial training does (Regularizer to Mitigate Gradient Masking). We therefore attack the defended model end to end and with full knowledge of the tokens and caps. Attacks use the full-depth Patch-Fool loss, the classification loss, and an attack that bypasses the cap by treating it as identity during the backward pass. Because attackers know the defense parameters, this also addresses the private-key assumption of Robustness Tokens.

Baselines

The naive reference is the undefended frozen backbone under the same attacks. For DeiT-S this should reproduce the 6.25% one-patch accuracy reported by Patch-Fool on its 2,500-image subset, and we use that same subset.

The strongest existing competitor is Robustness Tokens. Its best reported number is 63.1% white-box accuracy on DINOv2-G against dense attacks, and ADE20K mIoU under attack rising from 4.7 to 23.3. We run it two ways. The first uses the published recipe. The second retrains it on our Patch-Fool examples with the same steps, data and learning-rate sweep. This second version isolates our two additions, the attention cap and the attention-preservation loss, from simply training on patch attacks. Beating it means higher one-patch and two-patch robust accuracy under adaptive attacks at matched clean accuracy (within 0.5 points) and matched training compute.

The second competitor is the fixed cap and random dropout of RAM, applied to the same backbones without training. On segmentation it cut a nonlocal ResNet-50's adversarial target mIoU from 40.42% to 14.59% at about 0.15 mIoU clean cost. No reported result was found on Lacuna for RAM on ViT classifiers. We tune its cap on a held-out split with the same budget as our $\kappa$ search.

The third competitor is full-parameter Patch-Fool adversarial training of DeiT-S. Patch-Fool reports it helps, but no numeric post-training robust accuracy is given in the file. We run it at matched wall-clock time and at a generous three-times budget.

As certified reference points, we cite ScaleCert at 60.4% certified accuracy for a 1% patch on ImageNet and PatchCURE at roughly 44–47%. They are not directly comparable to empirical accuracy, but they bound what a cheap empirical method should aim for.

The ablations are tokens only, caps only, both together, and the attention loss removed. We also compare truncated-depth against full-depth inner attacks at matched compute.

Why not just…?

Why not just retrain Robustness Tokens on patch attacks? This is the most serious threat, so it is a main baseline rather than a footnote. The softmax argument predicts that tokens alone will plateau on hijacking that is settled in early blocks. If tokens-only matches tokens-plus-caps under adaptive patch attacks, the cap contribution is falsified. The result would then be a narrower one: patch attacks crafted on a truncated network are a cheap source of training data for existing token defenses.

Why not just cap attention at inference time with no training? RAM shows fixed caps help, but a single global threshold trades clean accuracy against robustness for every head at once. A learned per-head $\kappa$ can stay loose where heads legitimately attend sharply. The caps-only ablation and the tuned fixed-cap baseline settle whether learning the cap beats a well-chosen constant. If they tie, learning adds nothing.

Why not just run full or LoRA-style adversarial training? Full adversarial training is expensive, and per Patch-Fool it leaves ViTs behind CNNs. A low-rank adapter on the early blocks is a fair middle ground, and we include it at matched step count. Our bet is that its added capacity does not buy more patch robustness than direct routing control. We also expect it to be less portable across downstream heads, which we test by transferring the defense from classification to ADE20K segmentation without retraining.

Why not just use a certified defense? Certified methods give guarantees but assume contiguous square patches of known size, and pay throughput or accuracy costs. We report them as reference points and evaluate sparse, multi-patch Patch-Fool variants, where those assumptions fail.

Proposed Experiments

All experiments use ImageNet-1k validation and the Patch-Fool subset, covering one-patch, two-patch and sparse variants at 224 and 518 pixels. They also use ADE20K mIoU under patch attacks and the attention-divergence attack of Attacking Attention of Foundation Models. Dense ℓ∞ PGD is included to confirm no regression against Robustness Tokens' setting. Cost is reported in GPU-hours and in equivalent full backbone passes.

Three checks decide the proposal.

The first is the transfer curve. If attacks crafted at the truncated depth $\ell$ recover less than about 80% of the full Patch-Fool damage, the efficiency argument fails. In that case we fall back to full-depth attacks and report only the routing result.

The second is the tokens-only versus tokens-plus-caps gap under adaptive, defense-aware attacks at matched clean accuracy.

The third is the gradient-masking audit. Robust accuracy must not rise when attack steps drop from 200 to 10, and the gradient-bypass attack must not recover the undefended error. Either outcome would mean the robustness is an artifact of hidden gradients rather than corrected attention.