Input-specific Attention Subnetworks for Adversarial Detection
Paper · 2022 · Emil Biju, Anirudh Sriram, Pratyush Kumar et al.
Summary
A text classifier can give a confident answer after a small edit has led it to the wrong class. The answer alone offers little evidence that the input has been manipulated. Biju and colleagues look for evidence inside the computation. For each input, they switch off selected attention heads, the parallel components that exchange information among token positions, while preserving the class predicted by the full BERT encoder. The retained heads form an input-specific attention subnetwork, or IAS. The paper asks whether the heads selected for a sentence, and the way the sentence responds when that selection changes, can reveal an adversarial input.
The authors build a detector called AdvNet around three kinds of evidence. The first records the scores used to decide which heads to retain. The second records what happens to the prediction when the active and inactive heads in the middle layers exchange roles. The third uses classifiers attached to intermediate layers to see how often their predictions agree with the full encoder and how often they change from layer to layer. For an adversarial input, agreement means reproducing the full encoder’s mistaken class. That reference lets the detector examine a prediction even when the correct task label is unavailable.
The benchmark contains 5,686 successful adversarial examples drawn from 11 attack types across 10 datasets. The tasks include sentiment classification, news categorization, paraphrase recognition and sentence inference. With BERT-Base, AdvNet has higher detection accuracy than the reported comparison systems on every dataset. The main results report an average improvement of 7.45% over the strongest baseline for each task. On the held-out adversarial-detection split of SST-2, AdvNet reaches 90.74% accuracy, compared with 77.60% for FreeLB, the strongest baseline on that dataset.
The attention scores are the strongest feature when each feature is tested alone. The best overall configuration combines all the features and uses CutMix, which creates additional training examples by joining sections of existing feature vectors. Detection also improves when the features come from BERT-Base instead of BERT-Small. In a separate test that withholds attack types during detector training, AdvNet retains some ability to recognize unfamiliar perturbations. The evidence comes from a benchmark where authentic inputs are correctly classified originals and adversarial inputs are successful attacks. Within that setting, the computation behind a prediction carries information about whether to trust it.
Deep dive: Input-specific Attention Subnetworks for Adversarial Detection
How input-specific attention subnetworks expose differences between authentic and adversarial text, and how well AdvNet detects them. · about 40 minutes to read
The problem and its context
The prediction is only the starting point
The paper studies classifiers that turn a text input into a task-specific label. A sentiment classifier might assign a review a positive or negative label. A paraphrase classifier judges whether a pair of texts expresses the same meaning. Each system faces a different language task, but the detection problem has the same form. Given the input and the encoder’s computation, can a separate classifier tell whether the input is an authentic example or a manipulated example that has caused a task error? The underlying tasks are instances of text classification.
The distinction matters because a task classifier is built to choose an answer from its task vocabulary. A sentiment label expresses a decision about sentiment. A paraphrase label expresses a decision about equivalence. Each product of the classifier serves the original language task, so a wrong answer can look just as ordinary as a right answer. A detector has a different output vocabulary. It assigns a label about the status of the input, using evidence that can include the encoder’s behavior under changes to its own computation.
In the paper’s benchmark, an adversarial example is a perturbed input that fools the full, fine-tuned classifier. A small surface change can therefore have a large effect on the decision the classifier returns. The example in the paper’s opening figure is a film review whose altered version contains misspellings. The authors display the attention subnetwork for each version. Both subnetworks reproduce the full network’s decision on their respective inputs, yet the patterns of retained heads look quite different. The diagram poses the question behind the method. Can such changes in computation be measured consistently enough to serve as a detection signal?
That question also changes the reference point for an experiment. To inspect a suspicious prediction, the researchers first take the prediction at face value as a description of what the full network did. They ask which heads can support that decision and how the decision behaves when the head selection changes. A valid target for this experiment can therefore be a wrong task answer. The authors use the full network’s prediction as a reference for comparison, while the detector learns separately which kinds of behavior tend to accompany authentic and adversarial examples.
Why study attention heads?
The work brings together two lines of research described in the paper. The first asks what attention heads do. A head produces a pattern of weights across token positions. These weights can be visualized for a particular sentence to show which other positions contribute to the representation at a given position. Researchers have also examined the information encoded in outputs from different layers. Such work motivates questions about which parts of a network carry linguistic information and how that information changes with depth. This is the paper’s starting point in interpretability.
The authors describe several ways earlier work assigned roles to heads or used their outputs. Studies of particular attention patterns associated heads with linguistic relationships. Probing studies tested whether layer representations contained information associated with stages of language processing. Distillation work treated attention patterns as information that could pass from a larger teacher to a smaller student. These approaches all make the internal computation available for study. They differ in whether the object of interest is an individual pattern, a representation from a layer or behavior transferred between networks.
The second line of research asks how many heads a network needs. The authors discuss earlier experiments in which many heads could be removed while preserving task performance. One study found that a layer configured with 16 heads could be reduced to one in the setting it examined. Other studies used different pruning techniques and likewise found substantial redundancy. Those results made it plausible that there would be room to remove heads while preserving a particular input’s answer. They also left open whether the same heads would be retained for different inputs.
The distinction is one of scope. A shared pruning decision asks which parts of an architecture can be omitted across a collection of inputs. An input-specific decision asks which subset supports the output on a particular example. An attention visualization already varies with the input, but it describes how a head distributes its weights while operating. The IAS procedure varies the set of heads that operate. The authors use that intervention to map each input to a representation indexed by head and layer, which gives them a common format for comparing different sentences and sentence pairs.
The architecture makes this intervention possible because it organizes attention into parallel heads. Each head constructs a different transformation of the same layer input. The outputs are combined before the next stage of the network processes them. The authors can scale each head’s contribution and, when the scale is zero, remove that contribution from the combination. The remainder of the network still processes the example. This is the part of the architecture the method exploits. Transformer and attention
How earlier defenses framed the problem
The paper also describes methods that look for signs of manipulation in the text or train the underlying classifier to tolerate perturbations. Some detectors replace words and measure the change in confidence. They use an altered version of the sentence as a point of comparison, with a rule for deciding whether the resulting confidence shift is large enough to be suspicious. A token-level discriminator takes a different approach by judging which tokens appear perturbed and using those judgments to decide whether the sentence is authentic.
Adversarial training and certified robustness address related questions. Adversarial training exposes the classifier to a form of perturbation during training and makes the resulting loss part of the learning objective. Certified robustness studies what can be guaranteed for a specified class of changes. The IAS approach instead takes a task classifier that has already been trained and uses it to construct features for a separate detector. This distinction helps explain why the paper discusses both detection accuracy and robustness, and why those results need to be read in the context of their respective tests.
Earlier mutation-based detection supplied another motivation. The paper cites work suggesting that adversarial predictions can depend sensitively on the architecture and its particular parameter combinations. That observation makes a change inside the network a plausible diagnostic. Biju and colleagues concentrate the change on attention heads and ask how the result depends on where they intervene. They also retain information from earlier layers, allowing the detector to distinguish a final output that survived the change from a sequence of intermediate outputs that fluctuated along the way.
The method, step by step
From a task prediction to a subnetwork
The procedure starts with a BERT encoder adapted to a particular task. Its ordinary classifier might predict the sentiment of a review or judge the relation between two sentences. The authors also fit auxiliary classifiers to intermediate layers, so those layers can return task labels of their own. The encoder’s trained parameters stay fixed during both the auxiliary training and the later search for an input’s subnetwork. The task-adaptation stage is fine-tuning.
For a new input, the full encoder supplies a reference class. The authors add an adjustable gate to each attention head and search for gate settings that support that class. They then convert the settings to switches, retaining some heads and suppressing others. The search is repeated for each input, so two examples that receive the same reference class can still have different masks. The mask records membership in the subnetwork, while the scores that preceded it preserve information about the search.
Once the authors have an IAS whose prediction agrees with the full encoder, they change the mask in the middle layers. A head retained there is suppressed, and a head suppressed there is retained. The other layers keep their settings. The full task classifier and the intermediate classifiers then provide measurements of the changed computation. AdvNet receives those measurements along with the original gate scores. It returns an authenticity decision, separate from the task label the encoder originally produced.
From a task input to an AdvNet decision
The steps in order.
What the gate controls
Each layer receives a sequence of vectors, with one vector for each token position. An attention head makes query, key and value representations from that sequence. Queries and keys determine which positions contribute to each output. Values carry the information combined using those weights. The paper writes the projections separately for each head. The query projection is as follows.
Qⱼᵢ = Xⱼ Wⱼᵢ^Q
Here Qⱼᵢ is the query matrix for head i at layer j. Xⱼ contains the vectors received by layer j, with T rows for T tokens and dᵥ entries per token vector. Wⱼᵢ^Q is the learned query projection for that head. The superscript Q identifies the query projection.
Kⱼᵢ = Xⱼ Wⱼᵢ^K
Kⱼᵢ is the key matrix for head i at layer j. Xⱼ is the same layer input, and Wⱼᵢ^K is the learned key projection for that head. The superscript K identifies the key projection.
Vⱼᵢ = Xⱼ Wⱼᵢ^V
Vⱼᵢ is the value matrix for head i at layer j. Xⱼ again supplies the input vectors, and Wⱼᵢ^V is the learned value projection. The superscript V identifies the value projection. These projections let different heads transform the same layer input in different ways.
Headⱼᵢ(Xⱼ) = softmax(Qⱼᵢ Kⱼᵢᵀ ∕ √dₖ) Vⱼᵢ
Headⱼᵢ(Xⱼ) is the output of head i in layer j on the input Xⱼ. Qⱼᵢ and Kⱼᵢ are its query and key matrices, and the transpose sign ᵀ lets their product compare positions. The square root √dₖ scales those scores using dₖ, the dimensionality of a key vector. Softmax converts comparison scores to weights over key positions for each query position. Multiplying by Vⱼᵢ combines the value vectors with those weights.
The paper writes the combination of head outputs as a concatenation followed by an output projection. Each head thus contributes its own part of a wider vector at each position. The following expression concerns the attention operation. The encoder layer also has a position-wise feed-forward component, which processes the representation at each position.
Layerⱼ(Xⱼ) = concatᵢ[Headⱼᵢ(Xⱼ)] Wⱼ^O
Layerⱼ(Xⱼ) denotes the projected attention output at layer j. The operation concatᵢ joins the outputs of the heads indexed by i. Headⱼᵢ(Xⱼ) supplies the part from each head, and Wⱼ^O is the learned output projection for the layer. The superscript O identifies that projection.
The intervention changes each head’s contribution before this projection. A single scalar multiplies the whole output of the head for the example. This choice matters because the feature later assigned to that head describes its contribution as a component. It has one entry for the head across the input, regardless of how many token positions the text contains. The attention weights inside an active head can still vary across those positions.
Layerⱼᵍ(Xⱼ) = concatᵢ[gⱼᵢ · Headⱼᵢ(Xⱼ)] Wⱼ^O
Layerⱼᵍ(Xⱼ) denotes the attention output with gates. The superscript g indicates that modification. The scalar gⱼᵢ is the gate for head i at layer j, and · denotes multiplication of every entry in the head output by that scalar. The input Xⱼ, head function Headⱼᵢ, concatenation concatᵢ and output projection Wⱼ^O have the same meanings as in the ungated operation. A gate of 0 suppresses the head, and a gate of 1 gives its output full weight. Values between those endpoints allow a continuous search.
Which answer the search preserves
The authors first train the full network on the language task with cross-entropy. This loss penalizes the network for assigning low probability to the expected class. The target at this training stage comes from the task dataset. Once training finishes, the task classifier and the encoder have parameters that can be held fixed for the rest of the feature pipeline.
Lθ(x) = LCE(f(x, θ), y)
Lθ(x) is the task loss on input x with trainable parameters θ. The function f produces the task prediction scores used by the loss. LCE is cross-entropy, and y is the expected task label for that input. The notation θ refers to the parameters of the ordinary task network, including the components that are subsequently held fixed.
L̄θ = (1 ∕ |𝒳|) ∑ₓ∈𝒳 Lθ(x)
L̄θ is the mean task loss, and 𝒳 denotes the training collection of inputs. The vertical bars in |𝒳| denote its size. The summation visits each x in 𝒳 and adds its loss Lθ(x), using the parameters θ. The factor in front turns the sum into an average. The paper denotes the resulting trained parameters by θ∗.
When computing a subnetwork, the authors use the full, fine-tuned network’s predicted class as the target. In the benchmark an authentic example has been selected because this class is correct. For an adversarial example, the full classifier has already been fooled, so the target is its mistaken prediction. This convention makes the procedure applicable to an input without an accompanying ground-truth task label. The criterion is fidelity to a particular prediction, and the detector learns whether the resulting feature pattern is characteristic of an attack.
The authors optimize the gates for that input with θ∗ fixed. The adjustable quantities are the pre-activation values, which are transformed into the scalar weights applied to the heads. The paper describes the transformation as a version of hard concrete gating. Its purpose in the method is to make the gate values suitable for continuous optimization before a binary mask is constructed.
gⱼᵢ = fHC(pⱼᵢ)
The scalar pⱼᵢ is the pre-activation variable optimized for head i at layer j. The function fHC transforms this variable into the gate gⱼᵢ. The subscript HC denotes the hard concrete variant used by the authors. The collection of pⱼᵢ values will later form the real-valued attention feature.
fHC(pⱼᵢ) = 1 ∕ [1 + e^(α · (log(1 − pⱼᵢ) − log(pⱼᵢ)))]
The input pⱼᵢ is the adjustable pre-activation for layer j and head i. The function log is the logarithm, e is the base of the natural logarithm and the exponent is written after ^. The parameter α controls the shape of the transformation. The paper reports that α = 6 gave the best results in its setting. The expression maps the pre-activation to the scale on which gates multiply head outputs.
Cross-entropy supplies the direction of the search. A change to the gates is favorable if the gated computation better supports the reference class. The authors omit a separate sparsity term from this objective. Instead, they stop the gate search after a fixed number of epochs and choose heads according to their relative gate values at that point. They describe the intended selection as retaining heads whose gates rise quickly toward full inclusion. The implemented test uses the gate values attained at the end of the search.
Turning scores into switches
The threshold is relative to the largest gate for the input across all layers. This makes selection depend on how a gate compares with the strongest gate in that example. The threshold initially uses β = 0.8 after η = 10 epochs of gate optimization. The procedure applies the following binary rule.
ĝⱼᵢ(x) = 1 if gⱼᵢ(x) ≥ β · max(g(x)), and 0 otherwise
The value ĝⱼᵢ(x) indicates whether head i of layer j is retained for input x. The corresponding continuous gate is gⱼᵢ(x), and g(x) collects the continuous gates for x. The function max takes the largest gate in that collection. The parameter β sets the threshold relative to that maximum. The comparison ≥ includes gates equal to the threshold, and · denotes multiplication. The quantity η is the number of optimization epochs before the rule is applied.
There are two checks after thresholding. First, if the rule suppresses every head in a layer, the authors activate the one with the highest gate in that layer. This ensures that each layer has an active attention head. Second, they run the masked network and compare its class with the full network’s class. If the prediction differs, they lower β in steps of 0.2, allowing more heads to enter the mask. The paper reports that for 98% of the inputs the target class was reproduced by the time β reached 0.6.
The check is important because a continuous gate search and a binary subnetwork are different computations. A head with an intermediate weight can contribute during the search and then disappear when the mask is formed. Several changes occur together in the conversion, and subsequent layers process new combinations of head outputs. Checking the class after thresholding verifies that the resulting subnetwork actually has the property the authors want. It also means that some heads can be included because of the safeguards even if their final continuous scores fall below the initial cutoff.
ĝ(x) = {ĝⱼᵢ(x)}ⱼ,ᵢ ∈ {0, 1}ⁿᵐ
Here ĝ(x) is the binary mask for x, built from the individual ĝⱼᵢ(x) for every layer j and head i. The symbol ∈ means that the mask belongs to the set of binary vectors with nm entries. The network has n layers and m attention heads per layer. The active heads are the entries set to 1. BERT-Base has 12 layers and 12 heads per layer, giving the mask 144 entries in the experiments.
There are now several related objects associated with one input. The optimized pre-activations record the real-valued outcome of the search. The continuous gates are the transformed weights used during optimization. The binary mask determines the attention subnetwork evaluated after thresholding. The paper’s discussion sometimes uses attention mask as a broad name for features derived from the search. The distinction between the real-valued values and the hard inclusion decisions becomes important in the ablation experiments.
Recording the original selection and testing a changed one
The first AdvNet feature, F mask, lists the pre-activation values in a fixed order over heads and layers. A head can have useful information in its value even when it receives the same binary decision as another head. For instance, the continuous optimization can assign distinct values to heads that all end up below the threshold. Those distinctions survive in F mask. The authors also consider a binary version, F bmask, whose entries come from the final selection. The two versions have the same length and correspond to the same positions in the encoder.
The second feature comes from reversing the selection in the middle layers. Earlier work cited by the authors associated intermediate layers with syntactic relationships and described heads in those layers as serving several functions. The paper contrasts these roles with the phrase-level information associated with earlier layers and the task-specific behavior associated with the final layers. This gives the authors a reason to try the middle of the network as the place to intervene, with the location tested empirically later.
gᶠⱼᵢ(x) = 1 − ĝⱼᵢ(x) for j ∈ J, and ĝⱼᵢ(x) otherwise
The value gᶠⱼᵢ(x) is the altered gate for head i in layer j on input x. The superscript f marks the flipped selection. The value ĝⱼᵢ(x) comes from the original binary mask. J denotes the middle block of layers, which the paper describes as having size ⌈n ∕ 3⌉ for a network with n layers. The ceiling brackets round the division up to a whole layer. The expression 1 − ĝⱼᵢ(x) turns an active gate off or an inactive gate on. Outside J the original gate is retained.
The final task classifier is evaluated with these altered gates. The resulting F flip vector has 4 entries. It contains the class predicted under the altered mask, the target class from the full encoder, the confidence of the altered prediction and a flag for agreement between the two classes. Including the classes alongside the flag gives the detector access to the identity of the predictions as well as whether they match. The confidence adds information about the strength of the altered decision.
The purpose of the intervention is to see how readily a prediction established under one head selection survives a related change to that selection. An agreement flag provides a coarse measure of stability. A confidence value can vary even when the class remains the same. Together the entries allow AdvNet to distinguish different responses to the same kind of intervention. The authors examine the frequency of disagreements and the distribution of confidence separately in their analysis.
Reading the intermediate layers
The third feature asks how decisions appear as the representation moves through the encoder. The authors train an auxiliary classifier for each layer before the final layer. Each head reads the representation at its own depth and predicts the target class. The standard encoder parameters are frozen and the encoder is fully active during this training. The main classifier stays at the end, while the new classifiers give the experiment a way to ask the same prediction question at earlier points.
LΩₗ(x) = LCE(fₗᵍ(x, θ∗ ∪ Ωₗ, {1}ⁿᵐ), y)
LΩₗ(x) is the loss for the auxiliary classifier at layer l on input x. The parameters Ωₗ belong to that classifier, and θ∗ contains the frozen parameters of the task network. The union symbol ∪ denotes the combined parameter set used to make the prediction. The function fₗᵍ returns the output used by the layer-l loss when the attention gates have the specified setting. The vector {1}ⁿᵐ sets every gate to 1, with n layers and m heads per layer. The function LCE is cross-entropy and y is the target class the auxiliary classifier is trained to predict.
L̄Ω = [1 ∕ ((n − 1)|𝒳|)] ∑ₓ∈𝒳 ∑ₗ₌₁ⁿ⁻¹ LΩₗ(x)
The symbol L̄Ω denotes the mean auxiliary training loss for the collection Ω of auxiliary parameters. The collection 𝒳 contains the training inputs, and |𝒳| is its size. The outer sum runs over inputs x and the inner sum runs over layers l before the final layer of the n-layer encoder. LΩₗ(x) is the loss for each input and layer. The denominator gives equal weight to the individual input and layer terms. The trained parameters for the auxiliary classifier at layer l are denoted by Ωₗ∗.
At feature extraction time, the classifiers are attached to the network with the flipped IAS gates. Training on the full encoder gives each classifier a way of reading its layer under ordinary operation. Evaluating it with modified gates then measures the class read out from a changed representation. Since the earlier layers can be affected by the original IAS mask and the later ones receive representations produced under the middle-layer intervention, the resulting label sequence tracks behavior throughout the modified computation.
ŷₗ(x) = f̂ₗᵍ(x, θ∗ ∪ Ωₗ∗, gᶠ)
The label ŷₗ(x) is the auxiliary prediction for input x at layer l. The function f̂ₗᵍ returns a class from the layer classifier. Its parameters are the frozen θ∗ together with the trained auxiliary parameters Ωₗ∗, as indicated by ∪. The vector gᶠ supplies the flipped gates for the input. The hat indicates a selected class in this expression.
The layer-wise feature, F lw, contains the labels in layer order and two counts. One count gives the number of auxiliary predictions equal to the reference class. The other gives the number of times the prediction changes as the classifiers are visited in order. The labels supply details that both counts discard. Agreement measures how frequently the intermediate readouts support the same decision as the full encoder. Switches measure instability across consecutive readouts and can occur among labels different from the reference class.
This construction answers an important question about the final prediction. The altered network might give the same class as the original network even though its intermediate readouts wander among labels. Conversely, a disagreement at the end could follow a sequence that is comparatively stable. The authors give the detector access to both kinds of information, because the intermediate sequence and the final output describe different aspects of the computation.
Combining features and augmenting detector training
AdvNet takes the concatenated feature vector and produces an authentic or adversarial label. Its convolutions operate along the ordered features, followed by fully connected stages. The encoder and AdvNet solve different prediction tasks. A feature can carry the original task label as one of its entries, while the supervision for AdvNet concerns whether the input is authentic or adversarial.
F(x) = concat[Fmask(x), Fflip(x), Flw(x)] ∈ ℝⁿᵐ⁺ⁿ⁺⁵
The vector F(x) contains all the detector features for input x. The operation concat joins Fmask, the continuous attention feature, Fflip, the final-output feature from the altered mask, and Flw, the layer-wise feature under that mask. The expression ℝⁿᵐ⁺ⁿ⁺⁵ gives the real-valued feature space of dimension nm + n + 5, with n encoder layers and m heads per layer. The symbol ∈ denotes membership in that space. The mask contributes nm entries, the final-output feature contributes 4 and the layer-wise feature has dimension n + 1.
AdvNet uses two one-dimensional convolutional layers with ReLU activations. Both have kernel size 3, with 32 output feature maps in the first layer and 16 in the second. A kernel operates on a short section of the input vector at a time. The fully connected stages have output dimensions of 32 and 16, use sigmoid activations and have dropout rates of 0.1. A final softmax classification layer supplies the detector’s output. The authors report binary cross-entropy as the training loss and Adam as the optimizer, with a learning rate of 0.001. Using an NVIDIA K80 GPU, they train for 100 epochs with early stopping enabled.
The authors describe adversarial data generation as costly, which motivates their use of CutMix during detector training. In this application CutMix joins contiguous pieces of feature vectors. Each piece occupies its usual coordinates, so a region containing gate scores still supplies gate scores in the new vector. The new example can contain contributions from both authentic and adversarial inputs. The resulting mixture has a soft training label that reflects how much of each source vector was used. This takes place after feature extraction and gives the detector additional training vectors without requiring a new sentence for each vector.
F(x̃) = concatᵢ[F(xᵢ)[pᵢ : pᵢ₊₁]]
The object x̃ denotes the augmented example represented by the new vector F(x̃). The inputs xᵢ are sampled from the detector’s training set and i indexes the R selected sources. The vector F(xᵢ) is the feature vector for source i. The start and end positions of its selected patch are pᵢ and pᵢ₊₁, and the colon denotes slicing between those positions. The operation concatᵢ joins the successive patches in order.
0 = p₁ < p₂ < … < pᵣ₊₁ = nm + n + 5
The p values are successive patch boundaries. The subscript r in pᵣ₊₁ denotes the number R of selected sources. The first boundary p₁ starts at 0 and the final boundary ends at the full detector-vector length nm + n + 5. The variables n and m count layers and heads per layer, respectively. The less-than signs require the boundaries to increase, and the ellipsis stands for the intervening boundaries.
ỹ = ∑ᵢ yᵢ (pᵢ₊₁ − pᵢ)
The paper writes the mixed label as ỹ, with yᵢ the authenticity label of source input xᵢ. The sum runs over sources indexed by i. The difference pᵢ₊₁ − pᵢ is the length of the patch contributed by source i. The displayed expression weights labels by patch lengths. The accompanying description calls for each source’s share of the mix to be proportional to the length it contributes. The equation leaves the normalization of those lengths implicit.
The resulting training pipeline has two sources of label information with different purposes. The task label, or the full classifier’s prediction when used as a target, gives the subnetwork search and the auxiliary readouts a class to work with. The authenticity label supervises AdvNet, including the soft labels for CutMix examples. Keeping those roles distinct explains how a detector can learn from a sentence whose task prediction is wrong. The wrong prediction remains a valid reference for the computational measurements.
Experiments and results
How the benchmark was assembled
The authors start with public training and test data for each language task. They train the task classifier on the original training data. From the corresponding test data they select examples that the trained classifier labels correctly, forming the authentic portion of the new benchmark. They also generate perturbed inputs and retain successful attacks against the full, fine-tuned classifier. The resulting adversarial portion therefore measures detection after the original classifier has already been fooled. It is separate from the question of how often a perturbation succeeds in the first place.
The evaluation covers several kinds of language decisions. SST-2, Yelp polarity and IMDb supply binary sentiment tasks. AG News supplies headlines assigned to one of 4 categories. These tasks ask the classifier to assign a label to a single text. In the other tasks, the decision concerns a relationship between two texts. The distinction gives the authors a way to compare detection on direct labeling tasks with detection on tasks that require comparison across the input.
MRPC tests paraphrase judgments for sentence pairs, while QQP asks for equivalent questions in pairs drawn from Quora. RTE, SNLI and MNLI use sentence pairs and concern inference between the sentences. QNLI uses a question and a context sentence, with a binary judgment about whether the sentence contains the answer. These tasks put different demands on the underlying classifier, while AdvNet retains the same binary detection objective throughout.
The benchmark contains word-level and character-level attacks. The word-level group includes deletions, replacements drawn from different lexical relationships, changes in ordering and the named PWWS and TextFooler methods. The character-level group includes replacement, deletion, insertion and reordering. The paper names TextAttack as the framework used to produce the examples. Across the tasks and attack types the authors report 5,686 successful adversarial inputs and make the benchmark publicly available through their Bert-Paths repository.
The combined authentic and adversarial data for each task are assigned to a 70-10-20 split for detector training, validation and testing. This is a new split for studying the authenticity label. The ordinary task training set was used to fit BERT before this stage. Therefore, for instance, an SST-2 detection accuracy in the results measures the binary decision on the held-out portion of the constructed detector benchmark. It answers a different question from SST-2 sentiment accuracy.
Comparison systems and what the metric measures
The main comparison uses adversarial-detection accuracy. A success is an authentic input recognized as authentic or an adversarial input recognized as adversarial. This measure summarizes performance across both types on the test split. Later analyses also examine particular subsets of inputs, where the denominator and the meaning of success can differ. The paper’s attack-specific results, for example, describe performance on adversarial inputs from the named attack family.
FGWS detects manipulation through frequency-guided substitutions. It identifies uncommon words, considers more frequent words with similar meanings and examines the change in prediction confidence after substitution. The detection decision depends on a threshold on that change. NWS, the naive word substitution baseline, instead uses a random choice among related words for out-of-vocabulary items. It then applies the same general confidence-based detection principle. Both use a comparison between two textual inputs as evidence for authenticity.
DISP uses a perturbation discriminator to classify tokens as authentic or altered. It considers the sentence authentic when none of its tokens is flagged. This gives it a decision based on local judgments about the input. AdvNet, by comparison, represents the computation over the whole encoded input using gate scores, a final prediction under modified gates and layer-wise readouts. The comparison therefore includes detectors that take their evidence from different parts of the classification process.
FreeLB enters the comparison as an adversarial training method. It adds perturbations in the word-embedding space during training and minimizes the resulting adversarial loss. This encourages the classifier to be less sensitive to such changes. The paper places FreeLB alongside the other baselines in its detection accuracy table, while describing it as a training approach. The separate comparison with certified robustness concerns explicit bounds for word substitutions and uses a different basis for comparison.
Detection accuracy across tasks
The main table reports higher accuracy for AdvNet with BERT-Base than for the strongest baseline on every dataset. The authors report an average improvement of 7.45% over the best method for each task. The identity of that comparator can vary by dataset. For the sentiment tasks, the paper reports an improvement of 6.53% over the respective best methods. It reports 8.05% for the inference group, which includes QNLI in this analysis, and 6.98% for the paraphrase group.
The SST-2 result shows the size of the comparison on one of the sentiment datasets. FreeLB is the highest-scoring baseline there at 77.60% detection accuracy. AdvNet with BERT-Small reaches 78.57%, and AdvNet with BERT-Base reaches 90.74%. All of these scores concern the held-out authenticity decision. The small encoder and the base encoder also supply an architecture comparison within the same feature design.
Systems compared on SST-2 held-out adversarial-detection accuracy
AdvNet with BERT-Base leads both the baseline defenses and the version using BERT-Small.
The numbers
| System or setting | accuracy % |
|---|---|
| DISP | 68.73 |
| NWS | 70.31 |
| FGWS | 71.93 |
| FreeLB | 77.60 |
| AdvNet with BERT-Small | 78.57 |
| AdvNet with BERT-Base (this paper) | 90.74 |
On the held-out detector split, AdvNet with BERT-Base reaches 87.68% on Yelp and 81.18% on IMDb. It reaches 91.78% on AG News, the news categorization task. This spread matters when reading the paper’s general characterization of detector accuracy. The task affects the absolute level of performance, even for sentiment datasets with the same kind of task label. A gain over baseline and a high absolute accuracy describe related but distinct properties of the results.
On the paraphrase benchmarks, AdvNet with BERT-Base reaches 84.61% on MRPC and 75.27% on QQP. FGWS reaches 73.52% on the QQP detection split. In the inference experiments the BERT-Base version of AdvNet reaches 82.50% on SNLI, 80.43% on RTE and 72.61% on MNLI. QNLI gives an accuracy of 86.07%. Reporting these levels alongside the overall gain makes it possible to see where the detection task remains harder in absolute terms.
QNLI illustrates another feature of the comparison. FGWS has the highest accuracy among the named baselines there, at 78.14%. AdvNet with BERT-Small reaches 74.47%, while the BERT-Base configuration reaches 86.07%. The larger encoder improves the same detector design enough to change its position relative to the baselines. This matters when interpreting the overall result, which is strongest for the BERT-Base feature pipeline.
Systems compared on QNLI held-out adversarial-detection accuracy
AdvNet with BERT-Base has the highest accuracy, with FGWS leading the baseline systems.
The numbers
| System or setting | accuracy % |
|---|---|
| AdvNet with BERT-Small | 74.47 |
| NWS | 74.58 |
| FreeLB | 76.40 |
| DISP | 76.92 |
| FGWS | 78.14 |
| AdvNet with BERT-Base (this paper) | 86.07 |
The paper suggests that the detector performs better on relatively direct labeling tasks such as SST-2 and AG News than on pairwise tasks such as RTE and MRPC. The authors connect this pattern to prior findings that heads differ more clearly in their roles on simpler tasks, with more overlap in head behavior on complex tasks. Their explanation is that a less consistent correspondence between head identity and function could make head-based features vary more across examples of the same authenticity class. The reported accuracy comparisons establish variation across tasks. The role-overlap explanation is an interpretation of that variation.
Performance by attack family
The paper also breaks out performance by perturbation family. For SST-2, it reports adversarial detection accuracy of 0.96 for embedding replacements and 0.95 for synonym replacements, compared with 0.80 for character deletions. On AG News, the embedding-replacement result is 0.96, while the word-order result is 0.82. These figures use the fractional scale of the paper’s attack-specific table. They concern the respective adversarial subsets for those datasets.
The attack breakdown shows that some edits are harder to detect than others, with the relative pattern also depending on the task. For example, among the IMDb adversarial inputs, the reported accuracy for character insertion is 0.96 and the accuracy for character deletion is 0.75. On SNLI, the word-deletion entry is 0.61 and the character-insertion entry is 0.65. Those values give a more detailed picture than a single mixed test accuracy can supply. The test composition affects how much each difficult type contributes to an aggregate result.
The authors identify relatively strong results for embedding and synonym replacements on some of the direct text labeling tasks. They also describe the results for PWWS and TextFooler as fairly consistent across datasets. The per-family analysis reports how the trained detector responds to designated categories in the benchmark. A separate experiment addresses the question of what happens when the detector has never seen a particular family during training.
The comparison with a robustness certificate
For IMDb, the authors also compare their results with a certified robustness approach based on interval bound propagation. In that earlier work, the calculation bounds worst-case loss under a specified class of word substitutions. Biju and colleagues frame correct detection of an adversarial sample as a form of protection in a binary classification task. On IMDb they report 87% for word-substitution attacks and 81% across all 11 attack types under that interpretation. They cite 75% as the best upper bound obtained through the certified training comparison.
Each figure refers to a different experimental condition. The detector percentages describe how many of the studied successful perturbations can be flagged when they are presented to the detector. The certificate concerns a defined perturbation class and a bound obtained under the assumptions of the certified method. The comparison illustrates the paper’s interest in detection as a protective measure. The two approaches provide different kinds of evidence about what will happen under future perturbations.
What the ablations show
How sparse the selected subnetworks are
The authors first examine what the gate search produces. One figure follows the gates for a randomly selected input across optimization epochs. A minority of heads finish high enough to qualify under the threshold, consistent with the idea that the initial prediction can be preserved using a subset of attention heads. Some displayed active heads have final values below the threshold line. The paper relates those cases to the rules that keep a head in every layer and that relax the cutoff when a subnetwork changes the target class.
The authors then plot the number of retained heads across inputs for the datasets they studied. In the BERT-Base figure, most examples have 20-40 active heads out of 144. The distributions have relatively few heads at their most common values and extend farther toward larger counts. That pattern shows considerable room for pruning on many individual examples while retaining the predicted class. It also shows that the selection rule yields subnetworks of different sizes, which is consistent with the method’s treatment of each input as its own optimization problem.
The opening review example illustrates a related distinction. Two closely related texts can produce different head patterns, and each pattern can preserve the relevant prediction of the full encoder. The count of retained heads alone would lose information about which heads differ. The full feature vector preserves their layer and head identities. The figure gives a concrete reason to examine the positions in the mask as well as its overall sparsity.
What the original attention feature captures
The authors visualize the hard masks with t-SNE, which maps the high-dimensional vectors into a plane. In the plots for SST-2 and AG News, authentic inputs with different predicted task classes tend to occupy visibly distinct groups. That outcome fits the construction of the mask. The search is directed towards a reference class, and subnetworks optimized for different classes can have systematically different patterns of activity. The visual grouping is evidence that the mask carries information about the decision the full classifier made.
When the authors add adversarial examples to the visualization, those examples tend to appear near authentic inputs with the same target class. An adversarial prediction has become the reference for the gate search, so this grouping shows why the original task class matters to the feature. Within the task-class groups, the visualization shows a more modest separation by authenticity. The authors then test the complete feature vector directly in AdvNet. That test lets the detector use distinctions that can be lost when a high-dimensional mask is projected into a plane.
The class structure also affects how to read the examples in the first figure. A substantial change in the subnetwork can accompany a perturbation, but a subnetwork can change for reasons related to which task class it was optimized to reproduce. The supervised detector is meant to learn patterns that recur across inputs. The plot of authentic and adversarial examples gives context for that learning problem, while the held-out results measure how well the resulting rule works on new examples within the benchmark.
Which response to flipping is informative
The paper compares the altered subnetwork’s predictions with the full encoder’s target class. In the general pattern the authors describe, altering the middle layers is more likely to produce a different class on an adversarial input. In the SST-2 analysis, where the paper’s plots use BERT-Base by default, a reported 9% of authentic inputs have prediction confidence lower than 0.85, compared with 20% of adversarial inputs. The authors also report that 30% of adversarial inputs with prediction confidence above 0.85 have an altered prediction that disagrees with the target class.
That last observation explains why the detector receives both confidence and agreement. High confidence can accompany an altered decision that has moved away from the reference. Confidence alone would collapse confident agreement and confident disagreement into a similar signal. The predicted class and the agreement flag allow AdvNet to use the difference. The accompanying cumulative plot examines the score associated with the target class and gives another view of how strongly the altered network continues to support the original decision.
The comparison also has exceptions by dataset. On SST-2, the mutated subnetwork gives a non-target label on 12.3% of authentic inputs and 34.2% of adversarial inputs. On SNLI, the corresponding figures are 2.83% and 96.0%. For QQP, the reported fractions are 3.2% for authentic inputs and 1.3% for adversarial inputs. This reversal shows why the same margin of disagreement cannot be assumed across tasks. The feature is part of a detector adapted to each task and is combined with evidence from the original search and the intermediate layers.
The authors also try changing the first or final layers in place of the middle layers. Those interventions produce little change in the prediction for either authenticity group in the comparison described in the paper. The reported contrast supports their choice of the middle layers for the detector. The result concerns where the particular intervention gives a usable signal. It does not assign the same functional role to every head within that region.
What the layer sequence adds
The authors examine the auxiliary classifiers layer by layer. Authentic examples tend to have more intermediate predictions in agreement with the original target, particularly in the later layers. Averaged across datasets, 52.5% of adversarial inputs have more than 2 auxiliary predictions that disagree with the reference. For authentic inputs the reported figure is 23.1%. This supplies a reason to include an agreement count even when the changed subnetwork’s final prediction is already known.
They also examine switches in the auxiliary labels as the layers are visited in order. On SST-2, more than one switch occurs on 37.9% of authentic inputs and 54.8% of adversarial inputs. On AG News, the corresponding figures are 3.2% and 17.0%. The distinction varies by task. On MRPC the paper reports 10.3% for authentic inputs and 8.77% for adversarial inputs. These comparisons support using switches as one measurement among several. They also show why a common threshold on switches would give a different tradeoff on different tasks.
Agreement counts and switch counts summarize different sequences of behavior. A representation may yield several consecutive auxiliary predictions that all disagree with the target, producing substantial disagreement but few switches. Another sequence may alternate between classes, increasing the switch count even if the reference class appears several times. The layer labels retain which classes were involved, and the counts let the detector use these two recurring forms of behavior without having to reconstruct either one from the labels alone.
Which features and training choices matter most
The feature ablations train AdvNet with individual feature families. The attention pre-activations give the strongest single-feature result on every dataset in the reported table. On the SST-2 detector test split, their accuracy is 82.87%, compared with 74.07% using the flipped final-output feature and 64.79% using the layer-wise feature. On AG News, the corresponding held-out accuracies are 83.11%, 76.41% and 57.14%. The ordering is consistent in these examples even though the relative strengths of the latter features vary across tasks.
The authors also combine the final-output and layer-wise features with the binary attention mask in place of the real-valued pre-activations. On SST-2 that combination reaches 85.59% test accuracy. On AG News it reaches 90.47%. The full BERT-Base system, using real-valued pre-activations with the other features and CutMix, gives 90.74% and 91.78%, respectively. These comparisons show that useful information can survive the conversion to a mask and that the real-valued feature can improve on this representation. The amount of improvement varies with the dataset.
Removing CutMix gives 82.23% on SST-2 and 83.11% on AG News in the feature-ablation table. With all features and augmentation, the main results are higher on these tasks. The chart places the rows in the context of the same SST-2 detection metric. The single-feature runs assess standalone value. The binary-mask and augmentation comparisons alter different ingredients of the combined configuration.
AdvNet feature and training variants on SST-2 held-out adversarial-detection accuracy
The full configuration gives the highest accuracy, and attention scores are the strongest feature on their own.
The numbers
| System or setting | accuracy % |
|---|---|
| Layer-wise features alone | 64.79 |
| Flipped output features alone | 74.07 |
| All features without CutMix | 82.23 |
| Real-valued attention features alone | 82.87 |
| Binary mask with flipped and layer-wise features | 85.59 |
| Full AdvNet with CutMix (this paper) | 90.74 |
The single-feature results establish that pre-activations contain a strong detection signal under this training setup. The gains from the combined configuration are consistent with complementary information from the changed final output and the layer sequence. The reported comparisons leave open the separate contribution of each of those families once both the other features and augmentation are present. A feature’s accuracy on its own and its incremental value in a combined detector are different measurements.
The paper also applies Grad-CAM to examine which attention-feature entries have high influence on AdvNet’s decisions. The gradients are taken from the authenticity classifier’s output toward the gate-related inputs. The authors associate influential entries with their corresponding attention heads and compare the patterns across attack families. They report that word replacements involving antonyms, synonyms and embeddings involve more of these heads than character-level changes. They attribute the pattern to a more direct disruption of input representations by character changes. The gradient analysis identifies what the detector is sensitive to, while the account of why those sensitivities differ is the authors’ interpretation.
Encoder size, training volume and unfamiliar attacks
The authors compare features from BERT-Small, with 25M parameters, and BERT-Base, with 108M parameters. AdvNet with BERT-Base has higher detection accuracy on every dataset in the main table. The paper reports an average increase of 10.76% across tasks. On AG News, detection accuracy is 78.63% with BERT-Small and 91.78% with BERT-Base. The authors propose that a deeper network can build up semantic information over more layers and allow individual heads to take on more distinct roles. The comparison changes the encoder as a whole, so that explanation is a hypothesis about the observed performance difference.
A separate experiment varies the amount of detector training data used. The paper reports that even with 40% of the training examples, AdvNet stays above the competing results on most tasks. The fraction here refers to examples available for detector training. This experiment matters because adversarial examples are costly to generate for each task, and the result shows that the method can be competitive with a reduced training sample in this benchmark. The CutMix ablation gives separate evidence about augmentation, while the reduced-data experiment measures the performance of the resulting training approach at different sample sizes.
The transfer experiment varies the share of attack types included in detector training. The authors train with 25%, 50% or 75% of the attack types and report test accuracy for unfamiliar attacks and for the complete test set. At 75% coverage, the reported accuracy for SST-2 is 82.7% on new attack types and 80.7% on all types. For AG News it is 83.6% on new types and 78.4% on all types. The authors find that the results on unfamiliar attacks with this level of coverage surpass earlier comparison systems for most datasets.
Lower attack-family coverage gives lower detection scores. With 25% of attack types in training, SST-2 has 57.8% accuracy on new types and 58.9% on all types. At 50% coverage the corresponding figures are 69.9% and 68.4%. The authors observe that results on unfamiliar attacks and all attacks are often close at a given coverage level. They interpret that pattern as evidence that the training set’s size helps account for the drop at lower coverage. The experiment changes both the variety of attack types and the pool of available training examples, so those contributions remain coupled.
Limitations
Limits the authors acknowledge
The authors identify an additional computational cost at inference. An ordinary task prediction is only the first computation in the pipeline. The per-input search adjusts the gates and evaluates the resulting mask. If the mask changes the predicted class, the selection is revised and checked again. The detector also uses outputs under flipped gates and readouts from multiple layers. The authors discuss this added expense as a tradeoff against the benefit of having more information about a potentially adversarial input.
The paper describes sparse subnetworks as an opportunity for input-specific optimization. That opportunity concerns the computation available after an appropriate mask has been found. End-to-end efficiency depends on the cost of finding the mask, performing the additional feature passes and classifying the features. The paper reports settings for the search and training, while deployed latency and throughput remain unquantified in the detection experiments. The frequency with which a mask preserves the target at a given threshold describes search behavior on the benchmark.
The authors also limit their empirical study to the language understanding tasks considered. They mention vision and speech as directions for future work. These directions follow from their view that input-specific changes to attention could reveal useful information about other Transformer computations. The results reported in the paper establish detection behavior for BERT-style encoders on the selected language tasks.
Limits of the comparison
The benchmark separates correctly classified authentic examples from successful adversarial ones. This makes a clean experimental contrast. It also leaves out ordinary task mistakes from the authentic group and excludes unsuccessful perturbations from the adversarial group. The detector’s behavior on either group remains open. In practice, those cases matter because the decision that a text has been deliberately manipulated would often have to be made among many reasons for a classifier to be uncertain or wrong.
The target-class definition is useful for an input without an available task label. It also determines what the subnetwork search preserves. The search distinguishes computations that reproduce the full classifier’s selected class. Experiments on the mask visualization show substantial organization by that class. Consequently, some structure in the features can reflect the task label and the class mix of the benchmark. Recognition of adversarial behavior beyond the evaluated tasks and distributions requires evidence from a different test.
The paper checks agreement at the class level. Two computations can assign the same top class while assigning it different confidence or producing different intermediate representations. Several subsets of heads may also preserve the class on the same input. IAS gives the subset found by the authors’ gate search and selection procedure. Its success demonstrates that those heads can support a particular prediction in the masked computation. The search provides limited evidence about unique necessity or linguistic function for an individual head.
The text of the method leaves some implementation details to interpretation. In the displayed middle-layer rule, the written ranges for unchanged and flipped gates meet with an overlap at a boundary for some layer counts. The prose identifies the intended intervention as flipping a middle block. In CutMix, the verbal description calls for label contributions proportional to patch length, while the displayed mixed-label expression uses lengths directly. These ambiguities matter for exact reproduction of the intervention and the training labels.
Limits of the generalization evidence
Holding out attack families is a stronger test than evaluating on held-out examples of the same families. The unfamiliar attacks in this experiment still come from the paper’s collection and target the same underlying classification setting. The study provides evidence about transfer within that collection. Detection against a procedure that explicitly accounts for AdvNet’s features, or against adversarial examples from a different deployment setting, remains untested by this comparison.
Varying attack-type coverage also varies the examples available for training. The closeness of accuracy on the unfamiliar subset and on the complete test set is consistent with the authors’ training-volume explanation. A comparison holding the number of training examples fixed while varying type coverage would be needed to isolate the role of diversity. Similarly, the encoder comparison establishes a performance difference between BERT-Small and BERT-Base. The effect of parameter count, depth or head specialization individually remains open.
Aggregate detection accuracy describes performance at the balance of examples in the test split. A deployment with a different prevalence of adversarial inputs can give a different practical meaning to the detector’s errors. The reported accuracy results establish the quality of the binary decision in the constructed benchmark. The attack-specific results contribute detail about successful perturbations, while a deployment-oriented comparison would need to examine authentic errors and adversarial misses under its own input distribution.
The paper’s detailed comparison reports an average improvement of 7.45%, while its abstract describes an improvement of over 7.5%. The experiment section gives the comparison used for the detailed figure, namely the best baseline for each task. Similarly, the earlier robustness certificate and the paper’s empirical flagging rates support different conclusions. High detection accuracy on successful attacks can quantify how often those examples are caught. A guarantee over an entire perturbation set requires the assumptions and analysis of a certification procedure.
The paper makes the strongest case for IAS as a source of empirical detection features. The attention search, controlled intervention and auxiliary readouts all produce measurable signals, and the combined detector improves on the reported baselines. How those measurements translate to the causes of a particular prediction, to inference costs in use or to inputs outside the benchmark remains a matter for separate evaluation.
What came after
Subsequent work extending or evaluating IAS is undocumented in the available research record for this paper. The authors proposed taking the method beyond language understanding to vision and speech. Those extensions remain proposals in the paper’s account.
Cite
Cite as Emil Biju, Anirudh Sriram, Pratyush Kumar and Mitesh Khapra. 2022. Input-specific Attention Subnetworks for Adversarial Detection. Findings of the Association for Computational Linguistics: ACL 2022.
@inproceedings{biju2022input,
title = {{Input-specific Attention Subnetworks for Adversarial Detection}},
author = {Emil Biju, Anirudh Sriram, Pratyush Kumar and Mitesh Khapra},
booktitle = {Findings of the Association for Computational Linguistics: ACL 2022},
year = {2022},
doi = {10.18653/v1/2022.findings-acl.4},
url = {https://doi.org/10.18653/v1/2022.findings-acl.4}
}This page in Markdown https://md.research.elamur.ai/free/en/papers/biju-2022-input-specific-attention-subnetworks-adversarial/