Elamur Research

Towards Building a Robust Toxicity Predictor

Paper · 2023 · Dmitriy Bespalov, Sourav Bhabesh, Yi Xiang et al.

Summary

A toxicity detector can correctly flag a comment and then accept a slightly edited version that conveys the same abuse. For a system used to moderate online discussions, that inconsistency matters. People can change how a message is written while keeping the part that harms its target. The authors investigate this problem with ToxicTrap, a family of tests that starts from toxic text a detector already handles correctly. The tests look for small changes that cause the detector to classify the edited text as benign.

A successful test depends on what the detector predicts. A binary detector decides whether a text is toxic. A multiclass detector chooses among mutually exclusive categories, such as benign, offensive, and hateful. A multilabel detector can flag several forms of toxicity in the same message. ToxicTrap gives that last setting its own success condition. The edited text must activate the benign label and clear every toxicity label. The authors compare several ways to find edits, including replacing a word with a plausible alternative and changing its spelling. They use linguistic checks to limit how far the edited text can move from the original.

In the experiments, a recommended ToxicTrap configuration succeeds on 99.27% of attacks against the binary Jigsaw detector and 98.75% against the multilabel Jigsaw detector. It succeeds on 72.23% against the multiclass Offensive Tweet detector, HTweet-MC. Each rate is conditional on the toxic examples eligible for the attack. The authors also find that a broader search can succeed more often while requiring considerably more calls to the detector. Their preferred configuration balances these costs instead of pursuing the highest success rate in every comparison.

Adversarial training gives the detectors practice on edited text alongside their original training examples. On HTweet-MC, the success rate of the same ToxicTrap test falls from 72.23% to 11.17% after training with examples from that variant. It falls to 6.08% after training with a mixture of other variants that excludes the test recipe. The mixed training also reduces macro F1 on the ordinary HTweet-MC evaluation, from 0.73 to 0.685. The paper therefore documents both a gain in resistance to the tested edits and a cost on ordinary text. The extent of that tradeoff depends on the detector, the training mixture, and the test used to measure robustness.

Deep dive: Towards Building a Robust Toxicity Predictor

ToxicTrap tests whether small text edits hide toxicity from classifiers and measures how adversarial training improves detection on edited text. · about 34 minutes to read

The problem and its context

A correct decision can be fragile

Toxicity detection is an application of supervised text classification. A detector learns from texts paired with human-assigned labels and then predicts labels for new texts. In the settings considered by the paper, the labels describe content such as insults, threats, obscenity, or hate speech. The practical purpose is to flag material for moderation. The paper places that purpose in settings such as gaming and social networks, where people can choose how they write and may deliberately change a message to avoid being flagged.

Ordinary held-out evaluation asks how well a detector classifies a collection of examples it did not train on. The robustness question starts from an individual prediction. Given a message the detector gets right, how stable is its decision when the text changes in ways that leave its toxicity in place? A detector can do well at the first task and make inconsistent decisions on the paired examples used in the second. Those evaluation procedures put different demands on the detector. One samples ordinary inputs from a dataset. The other deliberately looks for an input variation that exposes a failure.

Keeping the toxicity in place is crucial. A benign decision might be correct if an edit removes an insult, changes the person being discussed, or turns a threat into a description of one. A robustness test therefore needs both a change in the detector’s judgment and a reason to expect the human judgment to stay the same. Looking only at the detector’s output would leave those cases indistinguishable. A considerable part of the paper concerns what linguistic checks can contribute to that distinction, and where the checks leave uncertainty.

The decision that matters to the authors is whether the text will still be flagged. In a classifier that distinguishes offensive language from hate speech, an offensive message predicted as hateful is a classification error. It still receives a label under which a moderation system could flag it. ToxicTrap focuses on the failure in which a correctly recognized toxic input ends up on the benign side of the decision. That choice connects the test to a particular use of toxicity detection as a filtering service.

The meaning of benign depends on the task

A binary detector returns one decision about toxicity. If the initial text was recognized as toxic, a switch to benign is enough to meet the test’s prediction condition. The original text and its edited counterpart can then be compared on the same question. This is the most direct version of the paper’s experiment because there is only one toxic class to leave.

A multiclass detector still returns one class per text, but it has more categories to choose from. Offensive Tweet separates hateful language, offensive language without the hate label, and material in neither category. In that setting, a score moving away from the original class can mean several things. It could move towards the other harmful category or towards benign. The authors choose the latter outcome in advance. The task itself comes from earlier work on the distinction between hate speech and other offensive language. Automated Hate Speech Detection and the Problem of Offensive Language

A multilabel detector allows several labels to apply to one input. The same comment can, for instance, receive a threat label and an insult label. The prediction is a collection of individual decisions. This structure changes the robustness question because lowering one score can leave other grounds for flagging the comment. A test that looks only at the label with the largest score would discard information about the remaining labels. Similarly, the appearance of a benign prediction does not settle the outcome if the detector simultaneously retains a toxicity flag. ToxicTrap’s multilabel condition treats the whole pattern of decisions as relevant.

These distinctions matter whenever the paper compares results across tasks. A multilabel failure has a stricter output condition in the sense that every toxic flag must clear. That observation alone cannot rank the difficulty of the experimental tasks. The datasets, the detectors, and the examples that qualify as starting points also differ. The paper tests each detector against a failure condition that fits its output, so the rates describe the behavior of particular systems under particular tests.

Where earlier work left the question

The paper describes toxicity research as having concentrated mainly on improving ordinary classification. Earlier approaches used engineered features, learned representations, and fine-tuning from pretrained systems. In fine-tuning, a network that has already learned from other text is adjusted using labeled examples for the task at hand. The authors describe pretrained transformer encoders as a common starting point. They give earlier work on interpretability and fairness a place in that history as well. Those directions concern, among other things, the evidence behind a prediction and the behavior of detectors across different kinds of content. BERT · RoBERTa · ToxiGen

The authors place ToxicTrap within a broader study of adversarial examples. An adversarial example is an input chosen because its effect on the system differs from the effect one would expect from the change itself. In the paper’s text setting, the intended change is small enough to leave the label applicable. Prior research had explored this question in text classification and other language tasks. Some of those studies investigated substitutions at the word level. Others investigated character changes or formalized the problem as a search over many possible combinations of edits. Generating Natural Language Adversarial Examples · HotFlip · Word-level Textual Adversarial Attacking as Combinatorial Optimization

For toxicity detection specifically, the authors describe the earlier evidence as sparse. They point to a study of Google’s Perspective API that examined misspelled abusive words and punctuation inserted within words. Its relevance is that the target judgment, toxicity, is intended to survive ordinary variation in how a reader encounters the word. ToxicTrap broadens the study to additional forms of editing and to several ways of representing toxicity labels. The authors regard the treatment of multilabel attacks as new to their knowledge. Their priority claim is qualified by that account of the literature.

The paper adopts an existing way of describing adversarial text generation in terms of an objective, admissible edits, rules for rejecting candidates, and a search procedure. That organization is useful here because much of what changes between toxicity tasks is the objective. A technique that proposes related words can still supply candidates whether the detector returns a class or a set of flags. The definition of a benign decision, and the information needed to recognize progress towards it, have to reflect the output of the detector being tested. TextAttack · Reevaluating Adversarial Examples in Natural Language

The method, step by step

Start with text the detector already recognizes

ToxicTrap begins with a toxic example whose recorded label agrees with the detector’s original decision. The starting example is called a seed. Using seeds whose initial predictions are correct makes the original and edited texts a pair with a known change in detector behavior. If a detector already accepts a toxic seed as benign, that is an ordinary classification failure. It offers no observation of a toxic decision turning benign after an edit. This selection step is also why the final success rates have a narrower denominator than the set of all toxic texts.

From that seed, the method constructs candidate texts. A transformation specifies the possible edits. Linguistic constraints determine which candidates are eligible to go forward. A search procedure decides which candidates to examine and uses the detector’s scores to decide which promising edits to carry forward. The goal function checks for the particular outcome the authors are studying. In the training experiments, the authors use selected edited examples from the training data to teach a detector to preserve the original label under variation.

From correctly detected toxic text to robustness evaluation

The steps in order.

From correctly detected toxic text to robustness evaluationStep 1: Select correctly classified toxic seeds1. Select correctly classified toxic seedsStep 2: Generate candidate edits under linguistic constraints2. Generate candidate edits under linguistic constraintsStep 3: Evaluate eligible candidates against the benign goal3. Evaluate eligible candidates against the benign goalStep 4: Collect edited training examples with their original labels4. Collect edited training examples with their original labelsStep 5: Retrain on original and edited examples5. Retrain on original and edited examplesStep 6: Evaluate ordinary predictions and resistance to edits6. Evaluate ordinary predictions and resistance to edits

The process supports two connected experiments. One asks how easily an existing detector can be made to change its decision. The other asks whether examples of those failures can improve a detector through retraining. The first can be run on the original detector on its own. In the second, a test is run again after retraining, so the authors can compare how the original and retrained detectors behave.

Formalize the edit and the desired decision

The paper expresses candidate generation as finding a perturbed input that lies in the input space, passes the constraints, and achieves the goal.

x′ = T(x, Δx),  x′ ∈ X,  subject to G(F, x′) and {Cᵢ(x, x′)}

Here x is the original text and x′ is the candidate produced from it. T is the transformation and Δx represents the edits it applies. X is the space of possible text inputs, and ∈ means that the edited text belongs to that space. F is the detector and G is the goal condition evaluated using that detector. Each Cᵢ is a constraint applied to the pair of original and edited texts. The index i identifies a constraint, and the braces collect the constraints. The equal sign defines how the candidate is obtained.

In this formulation F maps inputs in X to outputs in a space the paper calls Y. For an annotated example, y is the recorded output in that space. The form of Y depends on the classification task. Some outputs represent a single discrete decision, while others are vectors whose entries indicate whether individual labels are active. That difference carries through to the definition of G.

G(F, x′) := {F(x′) = b ∧ F(x) ≠ b}

G is the success condition. The symbol := introduces its definition, and ∧ requires both statements inside the braces to hold. F(x′) and F(x) are the detector’s class decisions for the edited and original texts. b stands for the benign class. The equal sign requires the edited text to receive that class, and ≠ requires the original prediction to be different from it. Eligibility screening supplies the further condition that the original prediction was correct for a toxic example. The displayed goal is shared by the binary and multiclass cases.

In multilabel classification, the paper represents the output as a vector of binary decisions. L denotes the number of labels. An entry yᵢ denotes the decision for the label at index i, and its possible values are 0 for inactive and 1 for active. If the decision for benign is considered by itself, it is possible to overlook another active label. The goal therefore has an additional clause.

G(F, x′) := {F_b(x′) = 1 ∧ F_b(x) = 0 ∧ F_t(x′) = 0 for every t ∈ T}

F_b is the component of F that makes the benign decision, and F_t is its component for a toxicity label t. In this formula T is the set of toxicity labels. The paper reuses the same letter it uses for the transformation in the general formulation. The equality checks require benign to be active for x′ and inactive for x, and every t in the toxicity set to be inactive for x′. The conjunction symbol joins the requirements, and the braces group them as the definition of G. The practical consequence is that a candidate with a remaining toxicity flag fails the test even if the benign flag has turned on.

Use scores to recognize progress before success

The class decisions tell the search when it has reached the goal. To decide which intermediate candidates to keep, the search also needs scores. For the binary case, the paper gives the output score for benign as its example of a search heuristic. In the multilabel case, a score for benign alone could favor a candidate that retains strong evidence for several types of toxicity. The authors instead use a combined score that rewards movement in the desired direction across the label set.

g = Σₗ∈Lₘₐₓ scores[l] + Σₗ∈Lₘᵢₙ (1 − scores[l])

g is the heuristic value for a candidate. l is a label index and scores[l] is the score assigned to that label after the algorithm applies a sigmoid to the detector’s output. The sigmoid maps the output for each label to a value between 0 and 1. Lₘₐₓ contains the labels to promote and Lₘᵢₙ contains the labels to suppress. Each Σ adds the terms for all indices in the relevant set. 1 − scores[l] grows as the score for a label to suppress falls. The plus sign combines the contributions from both sets. For the paper’s benign goal, the promoted label is benign and the suppressed labels are the toxicity categories.

This aggregate guides the search, while the final decision still depends on each label individually. A candidate can improve the aggregate when several scores move in the desired direction. It only qualifies as a success when every required threshold test passes. In the paper’s pseudocode, scores for labels to promote must exceed the maximization threshold, and scores for labels to suppress must fall below the minimization threshold.

ϵₘᵢₙᵢₘᵢ𝓏ₑ = 1 − ϵₘₐₓᵢₘᵢ𝓏ₑ

ϵₘₐₓᵢₘᵢ𝓏ₑ is the cutoff for labels the algorithm wants to activate. The algorithm gives it the value 0.5. ϵₘᵢₙᵢₘᵢ𝓏ₑ is the cutoff for labels it wants to deactivate. The equal sign defines the latter as the complement of the former, using subtraction from 1. The strict comparisons in the pseudocode mean that a label score at the relevant cutoff does not satisfy its condition. The implementation uses TextAttack, which the authors extend with a goal-function component for multilabel classification.

Propose edits, then check what they preserve

The paper evaluates two broad kinds of transformation. Word substitutions change a word to another candidate that is intended to be close in meaning or plausible in the surrounding sentence. The sources are counter-fitted GloVe word vectors, WordNet neighbors, and predictions from BERT’s masked-word task. The vector approach uses proximity between word embeddings to supply a list. The BERT approach proposes a word given its sentence context. WordNet supplies alternatives from a lexical resource. Each approach produces candidates that can still be wrong for the particular use of the word.

The other family changes characters within a word. The paper considers inserting or deleting characters, swapping neighbors, and substituting visually similar characters. The premise is that some altered spellings remain intelligible to a reader and leave the force of the message intact. A composite transformation pools candidates from the word and character families. It gives the search more ways to express approximately the same content and makes it possible to test robustness to both classes of changes in one run.

The baseline set of linguistic checks looks at edit size, sentence similarity, and grammatical category. The authors state a word modification limit of 10%. The recommended settings table expresses the ratio condition as less than 0.1. To check sentence similarity, they use the Universal Sentence Encoder, or USE, to represent the texts and compare them with an angular similarity measure. The recommended table requires similarity greater than 0.84. A part-of-speech check asks a replacement to preserve the grammatical category of the word it changes. Each criterion addresses a different way that an edited text might become unsuitable. An edit can be small and still change the meaning, and an alternative that is close in meaning can still fit the sentence poorly.

The preferred composite setup in the paper combines the character transformations with GloVe candidates drawn from a list of 20 neighbors. The authors also evaluate synonym-only settings, with neighbor lists of 5, 20, or 50 for GloVe. Those settings let them study the effects of the lexical source and candidate list size without character edits contributing to the result. The constraints are filters over candidates. Passing them is evidence that certain features of the text were preserved, with semantic and label preservation remaining separate questions.

Give the search an order for examining words

A sentence typically offers several editable positions, and each position can have several possible replacements. Trying every combination would quickly become impractical. ToxicTrap primarily uses greedy search with word importance ranking. The ranking gives the search an order in which to consider the positions. Greedy search uses the score for the current candidates to decide what to keep at each step. Earlier choices can shape the remaining possibilities, so a change that looks promising immediately can affect which later edits the procedure ever examines.

The paper compares several ways to produce the ranking. The unknown-token method, labeled unk, measures how the heuristic responds when a word is temporarily replaced by an unknown token. Deletion ranking measures the effect of temporarily removing the word. Weighted saliency uses the score change from unknown-token replacement together with the best score gain available from actually editing that position. Gradient ranking uses the magnitude of the loss gradient associated with a word, summarized by its L1 norm, the sum of the absolute values of the gradient’s components. The first tests look at how outputs respond to input changes. The gradient variant additionally relies on information from inside the detector.

The ranking step and the eventual edit serve different purposes. The unknown token is a probe used to determine which positions affect the detector’s decision. The candidate that is evaluated as a possible final result comes from a permitted transformation. Once the ranking is available, the greedy procedure considers substitutions at the ranked positions and tests their effects under the constraints. It terminates when it reaches the goal or exhausts the relevant search allowance. The paper also evaluates beam search, which can carry several candidate sequences forward, and genetic search, which works with a population of candidates. These comparisons examine the cost of considering a wider set of possibilities.

The authors create ToxicTraps Extend by adapting five existing text-attack families to the toxicity goal. The extensions reuse different combinations of transformations, constraints, and rankings. Some mainly supply word substitutions, some supply character edits, and TextBugger contributes a mixture. The extensions give the adversarial training experiments a pool of examples with differing sources. They also give the authors a way to hold out a named recipe when evaluating a defense. TextBugger · Probability Weighted Word Saliency · TextFooler

Train on the original and edited text together

Adversarial training uses the original label as a teaching signal for both the original input and a generated counterpart. If an edited example still expresses the same toxicity, the detector is asked to make both predictions consistent with that label. The original examples stay in the training set so the detector also keeps learning from the ordinary data. The idea follows the use of adversarial examples as training inputs in earlier work on robustness. Explaining and Harnessing Adversarial Examples · Towards Deep Learning Models Resistant to Adversarial Attacks

Written with λ standing for the weight on the adversarial term, the paper’s objective is

arg min_F E₍ₓ,ᵧ₎∼D [L(F(x), y) + λ · L(F(x′ = A(F, x, y)), y)]

arg min_F asks for the detector F that minimizes the expression. E₍ₓ,ᵧ₎∼D is the expectation over input and label pairs drawn from the training dataset D. x is the original text and y is its label. L measures the loss of a prediction against that label. The first loss uses the prediction F(x) for the original text. A generates an edited text from the detector, the original text, and its label. The inner equality names that text x′, and the second loss uses the prediction for x′ against the same y. The plus sign adds the losses, and · multiplies the second term by its weight λ.

The authors call training with examples from a single attack recipe AT1. They call training with examples from multiple recipes AT2. The name AT2 refers to combining sources of edited data for one detector. For that procedure, the authors first train on the original examples. They then use selected recipes to generate edited training examples against the resulting detector. The pseudocode gives each recipe a target amount expressed as a fraction of the original dataset size and allows the procedure to stop when it runs out of original examples. The edits keep their seeds’ labels. They are added to the original data, the combined dataset is shuffled, and training continues on it.

The selection of recipes is part of the experimental design. AT2 can reserve a recipe for evaluation while using the others to provide training examples. This creates a distinction between a detector encountering a recipe it was trained on and encountering a held-out recipe. A held-out name can still share some kinds of edits with the training recipes. The authors treat that overlap as a possible explanation for transfer, which they examine by comparing resistance to ToxicTrap after training with the extensions.

Experiments and results

Datasets and the original detectors

The experiments use Jigsaw and Offensive Tweet. Jigsaw comes from Wikipedia Talk Pages, where contributors discuss changes to articles. Its examples are anonymized comments annotated for toxicity. Several kinds of harmful content can occur in the same comment. The paper uses Jigsaw for both the binary decision in Jigsaw-BL and the multilabel decision in Jigsaw-ML. Jigsaw has 1.48MM training examples, 185k development examples, and 185k test examples in the dataset overview. The same overview reports 71,273 toxic examples in training and 8,909 in the test split.

Offensive Tweet comes from a collection of tweets gathered using a crowdsourced hate-speech lexicon. Human annotators assigned examples to hate speech, other offensive language, or neither. This setup provides the multiclass task for HTweet-MC. The paper’s dataset overview lists 20k training examples, 2.2k development examples, and 2.5k test examples. Its toxic test counts are 1897 offensive examples and 145 hateful examples. The categories matter to the experiment because either harmful class can be the correct starting point for a test aimed at benign.

The two Jigsaw detectors use the distilbert-base-uncased checkpoint. The binary detector’s listed learning rate is 2.06e-05 and its training length is 5 epochs. The multilabel detector uses 3.80e-05 and 10 epochs. HTweet-MC starts from GroNLP/hateBERT, with a listed learning rate of 2.66e-05 and 10 epochs. An epoch is a pass through the training data. The authors limit each input to its first 128 tokens after tokenization, which is the division of text into units the detector accepts. They use training batches of 64 examples and the AdamW optimizer with 50 warm-up steps. The appendix also reports early stopping with patience 2, which limits how long training continues without sufficient improvement under the monitored criterion.

The original detectors provide the baselines for retraining. For the attack component comparisons, the same original detector is evaluated under different search or transformation settings. Holding the detector fixed in those comparisons helps attribute differences in success and query counts to changes in the test. Comparing the original and retrained detectors instead holds a test recipe fixed as the training changes. The paper also uses the extensions as sources of training examples, so their role in the main retraining comparison is distinct from that of the ordinary, unaugmented classifier.

How success and effort are measured

Attack success rate, abbreviated ASR, describes the share of attempted attacks that attain the specified goal. The paper’s denominator is the number of attacks attempted. Its seed-screening rule conditions that number on correct initial predictions for toxic examples.

ASR = number of successful attacks ÷ total number of attacks

ASR is attack success rate. The numerator counts attempts that achieve the benign goal while satisfying the applicable rules. The denominator counts the attempted attacks. The division sign yields the fraction of attempts that succeed, which the paper reports on a percentage scale. A large ASR indicates low resistance to the given test. Ordinary errors on seeds screened out before the test are a separate part of the detector’s behavior.

The appendix reports how much of the toxic pool was attacked in the search comparison. The proportions are 59.76% for Jigsaw-BL, 65.46% for Jigsaw-ML, and 96.62% for HTweet-MC. The comparison across tasks therefore has two denominators of interest. The toxic pool is the population from which seeds are drawn. The attack success rate then describes outcomes among attempts on eligible seeds. This matters in interpreting a task whose attack rate is lower but whose eligible share of toxic examples is larger.

The authors also count the average number of detector queries and the average percentage of words perturbed. A query is a request for a prediction or score. Its count gives an indication of how much work the search asks of the detector. The percentage of edited words describes the scale of the changes as reported by the evaluation. The appendix includes elapsed times for several comparisons. Those times give another view of computational expense in the authors’ setup.

On ordinary text, the authors report area under the curve, labeled AUC, average precision, labeled AP, F1, and recall. Recall tracks the fraction of relevant cases found. F1 combines precision, the share of positive predictions that are correct, with recall. Average precision summarizes how precision behaves across levels of recall. The tables give macro averages, which give each category influence in the reported aggregate. These measures describe ordinary prediction and answer a different question from ASR. A retrained detector can become harder to move to benign while also losing performance on regular examples.

The original detectors under ToxicTrap

With the preferred unknown-token greedy ranking, the part-of-speech check, and the composite transformation, ToxicTrap reports 99.27% ASR against Jigsaw-BL. The average query count is 47.62, and the reported average share of perturbed words is 6.76%. Under the corresponding configuration, Jigsaw-ML has an ASR of 98.75%, with 49.38 average queries and 6.96% average perturbed words. The latter case reached the paper’s full multilabel goal. Its high success rate therefore concerns a benign decision with the toxicity flags cleared.

On HTweet-MC, the same configuration has 72.23% ASR and an average of 48.04 queries. Its reported average perturbed-word percentage is 19.43%. The multiclass detector resists this particular setup more often among its eligible examples than either of the Jigsaw detectors. That observation is specific to the tested settings. The comparison changes the source of the text, the detector, and the task together. A difference in success rates can reflect any of those factors, as well as differences in which examples pass the eligibility screen.

The opening figure illustrates what the aggregate rate means for an individual prediction. In the example, the original text is a short insult with a recorded toxicity score of 90.32%, and the original detector outputs 92.83% toxicity. The edit substitutes one insulting word for another. The original detector assigns the edited text a toxicity score of 0.066%. An adversarially trained detector assigns the edited text 86.84%. The figure shows both the collapse in the original detector’s score and the recovery on the edited input after retraining. The paper uses the other experiments to check how broadly that pattern extends.

The highest ASR for every task comes from beam search in the composite search comparison. For Jigsaw-BL the beam result is 99.68%, and for Jigsaw-ML it is 99.54%. On HTweet-MC it is 90.07%. The average query counts are 658.55, 756.05, and 442.18 for those respective tasks. The recommended configuration comes from weighing this success metric against the cost of search. The beam results also show that a lower-cost search leaves some failures undiscovered, with the extent of that gap varying by task.

Retraining the multiclass detector

For HTweet-MC the paper compares ordinary training, AT1 with deletion ranking, AT1 with unknown-token ranking, and AT2 with examples from the five extensions. In the deletion-ranking test, the baseline ASR of 71.46% falls to 21.97% for AT1-delete and to 8.28% for AT2. In the unknown-token test, the corresponding comparisons are among the ordinary detector, AT1-unk, and AT2.

HTweet-MC attack success rate under the unknown-token ToxicTrap test

Training on multiple extensions gives the lowest success rate for the held-out ToxicTrap recipe.

HTweet-MC attack success rate under the unknown-token ToxicTrap testOrdinary training: 72.23Ordinary training72.23Single-recipe adversarial training with unknown-token ranking: 11.17Single-recipe adversarial training withunknown-token ranking11.17Multiple-recipe adversarial training (this paper): 6.08Multiple-recipe adversarial training(this paper)6.08
The numbers
System or settingattack success rate %
Ordinary training72.23
Single-recipe adversarial training with unknown-token ranking11.17
Multiple-recipe adversarial training (this paper)6.08

The reported query counts also rise after retraining. For the unknown-token test they are 48.04 for the original detector, 74.71 for AT1-unk, and 77.91 for AT2. For the deletion test they are 48.17, 69.68, and 75.71 for the original, AT1-delete, and AT2 detectors, respectively. These comparisons show a change in both outcomes and the amount of work the test performs. The reported average percentage of words perturbed in the unknown-token test rises from 19.43% on the original detector to 33.07% for AT1-unk and 33.24% for AT2. The tables report those edit percentages alongside ASR and effort, and their relationship to the stated edit cap requires care.

Ordinary HTweet-MC performance tells a different part of the story. In the main adversarial training table, the original detector records macro AUC of 0.935, macro AP of 0.786, macro F1 of 0.73, and macro recall of 0.71. AT1-delete records 0.936, 0.792, 0.74, and 0.719 on the same metrics, in that order. AT1-unk records 0.938, 0.785, 0.738, and 0.723. The two single-recipe variants stay close to the original detector on ordinary data, with the best metric values spread across the variants.

Macro F1 on ordinary Offensive Tweet data for HTweet-MC training variants

Single-recipe adversarial training preserves ordinary F1 more closely than training with the mixture.

Macro F1 on ordinary Offensive Tweet data for HTweet-MC training variantsOrdinary training: 0.73Ordinary training0.73AT1 with deletion ranking (this paper): 0.74AT1 with deletion ranking (this paper)0.74AT1 with unknown-token ranking: 0.738AT1 with unknown-token ranking0.738AT2 with multiple recipes: 0.685AT2 with multiple recipes0.685
The numbers
System or settingmacro F1
Ordinary training0.73
AT1 with deletion ranking (this paper)0.74
AT1 with unknown-token ranking0.738
AT2 with multiple recipes0.685

AT2’s ordinary macro AUC is 0.932, its macro AP is 0.778, and its macro recall is 0.641. The paper reports lower values for AT2 than for the original detector on these measures and on macro F1. Which training variant appears preferable depends on which outcome is being measured. The mixture gives the lowest reported ASR on both ToxicTrap tests, while the single-recipe variants maintain ordinary prediction measures more closely. Among the single-recipe conditions, the authors favor AT1-unk as a general starting point. The two variants are evaluated against their corresponding search methods in the main robustness table, so that recommendation draws on the pattern across metrics and settings.

Retraining the Jigsaw detectors

The appendix compares ordinary training and AT1-unk for both Jigsaw detectors. Under the unknown-token test with the composite transformation and the part-of-speech check, Jigsaw-BL goes from 99.27% ASR before retraining to 60.28% after it. The average query count rises from 47.62 to 103.54. Jigsaw-ML goes from 98.75% ASR to 71.7%, with average queries rising from 49.38 to 91.08. The trained detectors resist more attempts, but successful attacks remain frequent in these evaluations. The large reductions shown on HTweet-MC therefore do not describe every detector in the study.

On ordinary Jigsaw-BL data, macro AUC is 0.971 and macro F1 is 0.823 for both the original and AT1-unk detectors. Macro AP moves from 0.749 to 0.733, while macro recall goes from 0.794 to 0.811. On Jigsaw-ML, macro AUC is 0.984 for both training settings. Its macro AP moves from 0.636 to 0.633, macro F1 from 0.587 to 0.594, and macro recall from 0.515 to 0.535. These measurements show why the paper reports multiple ordinary metrics along with robustness. A gain in recall or F1 can coincide with a reduction in average precision. The Jigsaw tables cover single-recipe retraining, while the main results with a mixture and a held-out ToxicTrap recipe concern HTweet-MC.

What the ablations show

The grammatical check reduces query counts

The part-of-speech comparison is a controlled change within the search experiments. For the gradient, deletion, and unknown-token rankings, the tables compare runs with and without the grammatical check while keeping the composite transformation. In the Jigsaw-ML unknown-token comparison, the average query count is 57.08 without the check and 49.38 with it. ASR is 98.75% in both rows. This is the cleanest example of the check reducing detector calls in a setting where the rounded success rate shown in the table is unchanged.

The same direction for query count appears for the other detectors. For the unknown-token ranking on Jigsaw-BL, the count is 55.11 without the check and 47.62 with it. Jigsaw-BL’s ASR is 99.32% without the check and 99.27% with it. For HTweet-MC, the average query counts are 58.99 without the check and 48.04 with it. Its ASR moves from 72.38% to 72.23%. The authors report lower query counts across all three detectors for each of the paired ranking comparisons, with success frequently declining slightly. The grammatical check reduces the set of replacements that can survive to the scoring stage, which is consistent with the reduction in calls.

The selected text examples show the kind of error the constraint is meant to address. In one tweet, a candidate produced when the check was absent fit the sentence less naturally than the adjective selected when the check was applied. This illustrates grammatical fit on the particular example. It cannot establish that all checked replacements retain the original meaning. The test asks whether a candidate has the expected grammatical category. Two adjectives can meet that test while expressing quite different attitudes toward their target.

Search breadth helps most where the greedy result is weaker

The search comparison examines methods with the same composite family of edits. Unknown-token ranking is competitive among the lower-cost searches. Beam search attains higher ASR on all three detectors, while the increase in query counts is substantial in every case. The gain in attack success is especially visible on HTweet-MC. The original Jigsaw detectors are already near the upper end of the reported ASR scale under several greedy settings. The HTweet-MC comparison leaves more room for a broader search to find successful edits.

HTweet-MC attack success rate by search strategy with the composite transformation and grammatical check

Beam search finds the most successful edits, while the greedy variants differ in how often they reach the benign goal.

HTweet-MC attack success rate by search strategy with the composite transformation and grammatical checkGradient ranking: 67.56Gradient ranking67.56Deletion ranking: 71.46Deletion ranking71.46Unknown-token ranking: 72.23Unknown-token ranking72.23Weighted saliency: 74.71Weighted saliency74.71Genetic search: 80.49Genetic search80.49Beam search (this paper): 90.07Beam search (this paper)90.07
The numbers
System or settingattack success rate %
Gradient ranking67.56
Deletion ranking71.46
Unknown-token ranking72.23
Weighted saliency74.71
Genetic search80.49
Beam search (this paper)90.07

On HTweet-MC, weighted saliency reaches 74.71% ASR and averages 178.91 queries. The unknown-token ranking reaches 72.23% and averages 48.04 queries. The extra scoring in weighted saliency checks how useful plausible edits to a word can be, in addition to how much the word matters as a temporary probe. That can change which words are tried early. The measured success increase comes with more detector evaluations, which explains why the authors favor the simpler ranking in spite of the higher rate in that row.

Genetic search shows that additional query cost does not guarantee higher success. On Jigsaw-BL, it averages 846.41 queries with 92.67% ASR. On Jigsaw-ML it averages 876.81 queries with 88.91% ASR. Both results fall below the greedy unknown-token results. On HTweet-MC it does improve on that greedy ranking, with 80.49% ASR, while averaging 1025.66 queries. Beam search has the highest reported success on HTweet-MC and needs fewer calls than genetic search on the same detector. The benefit of exploring more candidates depends on how a search allocates its work.

Gradient ranking gives another perspective on the choice. With the grammatical check, it averages 26.78 queries on Jigsaw-BL and attains 98.72% ASR. For Jigsaw-ML those values are 29.78 average queries and 97.72% ASR. Query count makes these rows look economical. The access requirement is different because the ranking depends on derivatives of the loss. The output-probing alternatives can use the scores the detector returns. The paper’s interest in detectors deployed as services makes that distinction important when interpreting the cost comparison.

Candidate choice affects success and cost

To study synonym substitution, the authors hold unknown-token ranking and the grammatical check fixed and remove character changes. On Jigsaw-BL, the GloVe list of 5 candidates gives 86.04% ASR and averages 30.55 queries. With 20 candidates, the table gives 96.75% ASR and 41.87 average queries. With 50 candidates, the values are 98.38% and 64.17. The larger lists find more successful edits, with a corresponding rise in the work needed to search them. The authors favor the intermediate list size as a compromise.

The pattern also appears on Jigsaw-ML. The list of 20 GloVe candidates gives 95.92% ASR and 43.84 average queries. The list of 50 gives 97.91% ASR and 67.09 average queries. On HTweet-MC, the corresponding rates are 66.70% and 69.99%, with query counts of 41.06 and 81.14. The value of extending the list depends on how much effort the evaluator is willing to spend for additional successes. The comparisons keep the other main choices in that experiment fixed, so they directly show how a larger synonym candidate set behaves in those settings.

WordNet and BERT’s masked-word predictions sometimes offer cheaper searches in query terms. For HTweet-MC they yield 56.66% and 65.23% ASR, with 32.08 and 33.66 average queries, respectively. The list of 20 GloVe candidates does better on ASR in that comparison, at 66.70%. A blanket ordering of lexical sources would overlook the weakest GloVe setting on the same task. The list of 5 reaches 33.65% ASR, below both alternatives. The size of the list is therefore part of what makes a particular GloVe setting competitive.

The appendix repeats the synonym-only comparison with deletion ranking and weighted saliency. It preserves the general pattern that expanding the GloVe list from 20 to 50 raises query counts. For example, under weighted saliency on Jigsaw-ML, the table reports 96.09% ASR and 297.63 average queries with the list of 20. With 50 the result is 97.89% ASR and 662.08 average queries. The expense of the larger list is particularly visible when the ranking method itself scores possible edits. The authors’ preference for the intermediate list is thus supported under several ways of ordering the words, within the experiments reported.

The main tables also allow a comparison between using GloVe alone and adding character transformations. For HTweet-MC, with unknown-token ranking and the grammatical check, the synonym-only setting with 20 candidates reaches 66.70% ASR and 41.06 average queries. The corresponding composite setting reaches 72.23% and averages 48.04 queries. For Jigsaw-ML the respective ASRs are 95.92% and 98.75%, with 43.84 and 49.38 queries on average. In the illustrated examples, some character edits leave the intended reading readily recognizable. Some word alternatives generated by the masked-word predictor change the apparent toxicity. Together these analyses show why transformation quality has a linguistic dimension as well as a measurable effect on detector scores.

Transfer depends on what training and testing share

The retraining comparison changes what sorts of edited examples go into training. AT1 uses examples from one recipe. AT2 uses a mixture from the extensions. The low ASR on HTweet-MC after AT2 shows that a detector can gain resistance to a named recipe that did not supply its training examples. The authors suggest that the mixture may cover useful patterns shared by the held-out recipe. The setup makes that explanation plausible because the extensions and ToxicTrap use overlapping families of word and character edits.

The evidence concerns transfer at the recipe level. Holding out a recipe leaves some components in common, and AT2 also alters how many adversarial examples and sources contribute to training. The paper compares these training configurations as packages. It does not vary training volume and recipe diversity independently. The drop in ordinary HTweet-MC performance after AT2 is part of that package comparison. The single-recipe Jigsaw results add another qualification. Their remaining ASRs show that the extent of hardening varies considerably across the tasks tested.

Limitations

Limits identified by the authors

The authors frame the defense as improving empirical robustness against the tested families of edits. Their account of the held-out result explicitly allows for overlap between the training recipes and the unseen recipe. They also emphasize that the choice of recipes for the mixture matters. These qualifications narrow what “unseen” means. The particular recipe was held out, while some of the transformations or other design choices that make it effective may have been represented in the training data.

The paper records a cost to ordinary classification after AT2 on HTweet-MC. The authors associate this drop with using more adversarial examples from multiple attacks, and they present that explanation as an interpretation of the result. Recipe diversity, example count, and the makeup of the augmented data all change together in the main comparison. A reader can verify the reduction in ordinary metrics from the tables. Assigning that reduction to any one of those factors would require an additional controlled comparison.

The authors also leave alternative defense strategies for future study. They name virtual adversarial training, methods that learn disentangled representations, and generative approaches. Those suggestions mark where their evaluation ends. The empirical defense in this paper consists of training on original inputs and generated edits. Its outcomes concern the datasets, learning setups, and attacks actually used.

Limits visible in the experimental setup

The rates are conditional on correctly classified toxic seeds. A moderation system will also encounter toxic inputs that its detector would miss immediately, benign inputs it might wrongly flag, and inputs whose labels are open to disagreement. ASR covers a specific change in prediction among the initially correct cases. The ordinary evaluation reports additional measures, but the attack rates alone cannot characterize the total number of harmful messages a deployment would miss. The paper’s own attacked-share figures show why the eligible populations deserve attention before comparing ASR across tasks.

The task comparison also changes several factors together. The two Jigsaw classifiers share their source of comments and their underlying encoder family, but differ in output structure and training settings. HTweet-MC uses a different corpus and a different pretrained starting point. Tweets and Talk Page comments also differ in the way they were collected and labeled. The experiments establish that vulnerability appears in all three task settings. They leave open how much of the difference in rates comes from the label structure, the dataset, the architecture, or the training procedure.

An edited sample inherits the original label for training. The defense’s rationale therefore depends on the edit preserving the aspects of the text that warranted the label. Sentence similarity, grammatical agreement, and the edit limit are checks the procedure can apply automatically. They do not guarantee that the target, intent, or severity of the original statement survives. The paper’s examples acknowledge this directly when some plausible substitutions remove toxicity. The reported comparisons supply selected examples of linguistic quality. They leave the population-wide rate of label preservation undetermined.

The Jigsaw label descriptions also need to be read with care. The task discussion gives a multilabel example that includes a benign decision alongside categories such as obscenity, insult, threat, identity attack, and sexually explicit content. The dataset appendix describes source annotations using toxic and severe toxic, with categories such as identity hate among the associated labels. It describes a comment with no toxicity label as non-toxic. The output goal is clear about the benign and toxicity decisions it checks, but the paper’s descriptions do not fully reconcile the label inventory in the illustrative task formulation with the source annotation vocabulary.

The edit percentages deserve similar care. The recommended settings specify a word modification ratio below 0.1, yet the search table records 19.43% average perturbed words for HTweet-MC under the recommended ranking and grammatical check. After AT1-unk, the retraining table reports 33.07% on that detector under the corresponding unknown-token test. The paper does not give a reconciliation that would justify treating the reported averages as demonstrations that the stated cap held per input. This matters especially for short texts, where changing a word can represent a sizeable share of the message. The success rates and edit percentages can be read as reported while the precise relation between the cap and the measured edit size remains unclear.

The training table also needs to be read by test condition. The main HTweet-MC robustness table pairs AT1-delete with the deletion test and AT1-unk with the unknown-token test. Those are good comparisons with the corresponding unaugmented runs. A comparison between the two AT1 outcomes changes the testing search at the same time as the training recipe. The appendix reproduces the AT1-unk outcome but labels its search as deletion in the summary table. The main table and the accompanying discussion consistently pair the outcome with the unknown-token test. The evidence is clearest when read using that pairing. A full cross-test of both AT1 detectors under both searches would answer a different question about which training variant transfers better between them.

Query counts are an operational proxy with a limited scope. They tell how many times the detector is called. Computing lexical candidates, sentence similarities, rankings, and gradients can add work outside those calls. The gradient method also assumes access to information an output-only service may not expose. The appendix’s elapsed-time results add useful context for the authors’ experiments. The measurements leave overall cost dependent on the access available and the implementation in use.

Finally, retraining lowers success under specific tests. The beam comparisons already show that search choice can change the measured vulnerability of the original detectors. The retraining experiments on the composite transformation focus on the greedy tests listed in the results tables. They do not exhaust possible strategies, nor do the ordinary evaluations measure the effect on a live moderation system. The defensible conclusion is bounded by this setup. Edited training examples improve resistance to the tested attacks, can transfer to a related held-out recipe, and can change ordinary prediction quality at the same time.

What came after

One later citation places ToxicTrap in a broader survey of vulnerabilities revealed through adversarial attacks. The survey’s subject extends beyond toxicity classification. For a reader following the connection, ToxicTrap supplies a concrete case of an output failure that broad language-system evaluations can otherwise describe only in general terms. Its case concerns small text changes that move a moderation decision towards benign, with a separate success criterion when the detector can return several labels. The citation establishes the relation to that survey’s subject. The available account leaves the survey’s specific treatment of the ToxicTrap search and training results unspecified. Survey of Vulnerabilities in Large Language Models Revealed by Adversarial Attacks

SMARTER is a later citing work centered on data-efficient toxicity detection with explanations. It describes its approach as self-augmentation. The connection to ToxicTrap is the use of generated training material to improve toxicity detection, with SMARTER’s stated scope also including explanations. ToxicTrap’s augmentation has a particular source and purpose. It generates variants that expose decision failures and trains on them with the original labels. SMARTER’s title identifies a different augmentation approach and goal. The citation alone leaves open whether SMARTER reused ToxicTrap’s goal functions, transformations, or held-out evaluation design. SMARTER

Cite

Cite as Dmitriy Bespalov, Sourav Bhabesh, Yi Xiang, Liutong Zhou and Yanjun Qi. 2023. Towards Building a Robust Toxicity Predictor. Proceedings of the 61st Annual Meeting of the Association for Computational Linguistics (Volume 5: Industry Track).

The paper itself, not this page. BibTeX from the library's record of the work. DOI 10.18653/v1/2023.acl-industry.56

@inproceedings{bespalov2023building,
  title = {{Towards Building a Robust Toxicity Predictor}},
  author = {Dmitriy Bespalov, Sourav Bhabesh, Yi Xiang, Liutong Zhou and Yanjun Qi},
  booktitle = {Proceedings of the 61st Annual Meeting of the Association for Computational Linguistics (Volume 5: Industry Track)},
  year = {2023},
  doi = {10.18653/v1/2023.acl-industry.56},
  url = {https://doi.org/10.18653/v1/2023.acl-industry.56}
}

↑ back to top

This page in Markdown https://md.research.elamur.ai/free/en/papers/bespalov-2023-building-robust-toxicity-predictor/