Improving Black-box Robustness with In-Context Rewriting
Paper · 2024 · Kyle O'Brien, Nathan Ng, Isha Puri et al.
Summary
A classifier trained to read product reviews may struggle with sentiment expressed in a different setting. The task is still to decide whether the text is positive, neutral, or negative, but the cues it learned from reviews may work less well on unfamiliar writing. Updating the classifier can be expensive or impossible if it is available only through a service. Improving Black-box Robustness with In-Context Rewriting asks how much of that problem can be addressed at the input. The authors study short-form text classification in settings where the classifier stays fixed.
Their approach is a form of test-time augmentation, called LLM-TTA. A separate generator produces alternative versions of an incoming text, the classifier evaluates the original and the alternatives, and the system combines its judgments. One version of the method asks for paraphrases that preserve the input’s meaning. In-context rewriting, or ICR, also shows the generator examples from the classifier’s training domain. Those examples demonstrate what familiar inputs look like. The generator is asked to bring the new text closer to that style while retaining what matters for its label. The original text contributes to the final judgment in either version.
The authors test the approach on sentiment, toxicity, and news topics. For BERT and T5, the highest accuracy on each unfamiliar test task comes from one of the generative rewriting methods. ICR raises BERT’s average accuracy across the out-of-distribution tasks by 4.48 percentage points, with no reported loss in average accuracy on familiar data. The individual results vary. BERT’s largest out-of-distribution gain comes from paraphrasing for toxicity, while ICR works better for BERT on sentiment and news. Falcon gains less consistently. At the class level, some of the changes behind an overall improvement are new mistakes.
Rewriting every example adds work, so the authors also test a rule that rewrites only inputs on which BERT’s initial probabilities show enough uncertainty. With ICR, they report a 57.74% average reduction in the share of unfamiliar inputs sent for rewriting, while accuracy still exceeds the original classifier’s on each task. Rewriting everything yields higher accuracy. A separate analysis of sentiment finds that rewritten texts move only slightly closer to product reviews in an embedding space. The evidence supports a narrower conclusion than full domain adaptation. Alternative phrasings can improve a fixed classifier’s decisions even when the incoming data remain recognizably different from the data it was trained on.
Deep dive: Improving Black-box Robustness with In-Context Rewriting
In-context rewriting tests whether rephrasing incoming text can help frozen classifiers handle unfamiliar data, and when the extra work pays off. · about 32 minutes to read
The problem and its context
The same labels in a different setting
A supervised classifier learns to assign a pre-defined label to a piece of text. For sentiment, the label describes the attitude expressed. For news, it describes the subject. Producing a useful classifier requires more than learning which labels are possible. It requires learning which features of the text count as evidence for each label. Those features can include explicit words, the way a sentence qualifies a judgment, or conventions that writers in a particular setting take for granted.
The paper calls data from the setting used to optimize a classifier in-distribution, abbreviated ID. It calls challenging data from other settings out-of-distribution, or OOD. These terms describe a relationship between a classifier’s training environment and the data it encounters. Amazon reviews, for instance, serve as the familiar environment for the sentiment experiments. A sentiment dataset can ask the same basic question with the same set of labels while giving the classifier texts that express opinions in different ways.
This distinction matters because a classifier can perform well on its familiar evaluation set and still be unreliable when the source of the text changes. A deployment can also receive a mixture of familiar and unfamiliar writing. Changes intended to help on the latter have to be judged in light of what they do to the former. The paper motivates this concern with applications such as content moderation, spam detection, and healthcare. Its experiments focus on short classification tasks where it can measure how final decisions change under a fixed set of labels. It situates that question within earlier work on out-of-distribution generalization.
The term black box describes the practitioner’s relationship to the classifier. Its parameters may be inaccessible through an application interface, or access may exist while the cost of retraining makes updates impractical. The experimental version of this constraint is deliberate. The authors prepare the classifiers themselves and freeze them for evaluation. That design gives them control over how each classifier was prepared while restricting the intervention to submitting text and using the resulting predictions. In the probability-based part of the study, the output interface also needs to expose the classifier’s scores for each class.
Where earlier methods intervene
Several of the approaches reviewed in the paper work by changing training. A practitioner can select different data, change the training procedure, or update the classifier for a new domain. The paper also discusses test-time adaptation, in which the source classifier’s parameters are adjusted as test data arrive. Some adaptation methods use entropy, a measure of how spread out the predicted probabilities are, as a signal for the update. Others try to align distributions or change internal behavior during inference. Under the paper’s black-box constraint, updating the source classifier is unavailable. The related work includes an overview of transfer learning in natural language processing.
Data augmentation offers a different way to intervene. At training time, augmentation creates extra examples from available text, giving a system more forms of the input to learn from. The paper describes uses in settings with limited labeled data and in work on robustness and harmful biases. Text can be modified at the level of characters, words, or whole passages. The same variety of transformations can be used after training, but then the new examples inform the current prediction. They are never added to a training run. The authors draw on a survey of text data augmentation.
Test-time augmentation uses those additional inputs to obtain several judgments about the same case. In the computer vision work reviewed by the paper, researchers had used the technique to study ordinary accuracy, robustness under distribution changes or adversarial perturbations, and uncertainty. Earlier language applications included modifying words in toxicity examples and comparing representations across paraphrases for story classification. Other work tried giving different weight to different augmentations so unreliable rewrites would have less influence. The earlier toxicity study used DistilBERT.
There are two reasons that producing useful textual variants is difficult. An edit has to preserve the evidence for the original label, and it has to change enough of the expression to give the classifier another useful view. In a review, changing a qualifier can alter the strength or even the direction of the opinion. In a comment, a replacement can remove the feature on which a toxicity judgment turns. At the other extreme, a version that changes only an incidental detail may give the classifier almost the same evidence in almost the same form. In both cases the number of predictions grows, but the additional predictions may bring little value. Word substitution and related approaches appear in EDA and work on contextual augmentation.
The authors turn to whole-text generation because earlier work gave them reason to expect more flexible changes in wording. They cite advances in paraphrasing, style transfer, and machine translation. These tasks require some ability to keep the information in a source text while expressing it in another form. The paper asks whether that ability can improve the inputs available to a task classifier. Its extra question is whether examples of familiar text can direct the changes more usefully than a general instruction to paraphrase. That is a use of few-shot learning in the generator’s prompt.
The method, step by step
From one incoming text to one final label
Start with an incoming text and a classifier that already knows the task’s labels. In the unaugmented setting, the classifier reads the text once and returns a decision. With augmentation, a separate procedure produces several versions of the same input. Each version should be capable of receiving the original label under the task’s rules. A restrained complaint should remain a complaint even if a rewrite reorganizes its sentence. For a news topic, changing the register can be harmless so long as the information identifying the subject survives.
The classifier then reads each rewrite independently, using the same task and labels as it uses for the original. The rewrites enter as complete inputs. The classifier has no separate assignment to explain their relationship or determine which one is most faithful. Their predictions are combined outside it. In this way, the final label can reflect how the classifier responds to several formulations, and a shift in the answer can happen without a change to any of its parameters.
For one set of experiments, every input goes through this procedure. The selective version begins by classifying the original and asking how much uncertainty its probability distribution expresses. If uncertainty reaches the chosen threshold, the system generates the variants and combines the resulting predictions with the initial one. If uncertainty is below the threshold, the original prediction is already the final answer. The diagram shows both routes through the same procedure.
How rewriting and selective augmentation produce a label
The steps in order.
The classification problem in notation
The authors assume a supervised task. Inputs belong to a space they denote by X, and the allowed outputs belong to a discrete label space Y with K classes. Their notation places the input space in ℝⁿ, where ℝ denotes real numbers and the exponent indicates the dimension of a numerical representation. The intervention itself acts on natural language text. The authors use n again in the training-set notation to count examples, a separate use from the dimension of the input representation.
D_train = {(xᵢ, yᵢ)}ᵢ₌₁ⁿ
D_train denotes the training dataset. Each pair consists of the input xᵢ and its label yᵢ. The subscript i indexes the pairs and ranges from 1 through n, the number of training examples in this expression. The equals sign defines the dataset, and the braces collect the pairs. The classifier is called f, and the paper treats the pairs used to train it as draws from p_train(X, Y), the joint training distribution over inputs and labels. It writes p_ood(X, Y) for the corresponding unknown test distribution. Calling that distribution unknown allows for an upcoming input, x, to come from the training distribution or from a different one.
x′ ∼ aᵢ(x′ | x)
Here x is the original test input, and x′ is an augmented input. The function aᵢ specifies the distribution of possible rewrites under augmentation i. The tilde indicates a sample from that distribution, and the vertical bar indicates that the rewrite is conditioned on x. This notation lets an augmentation be stochastic, so applying the same procedure again can give a different text.
M = {aᵢ}ᵢ₌₁ᵐ
M collects the transformations used to form the batch of inputs for a decision. Each aᵢ is a transformation, and the index i ranges from 1 to m, where m is the number of entries in the collection. The experiment can use the same rewriting procedure for several entries and draw a fresh result for each. The notation also makes room for a special transformation that supplies the original.
I(x) = x
I is the identity transformation. Applied to the input x, it returns x itself. Including I among the transformations gives the original text a place in the same collection as its rewrites.
M(x) = {xᵢ′ ∼ aᵢ(xᵢ′ | x)}ᵢ₌₁ᵐ
M(x) is the realized batch for one input x. The text xᵢ′ is the sample made with transformation aᵢ at position i. As before, ∼ denotes sampling and the bar expresses conditioning on x. The range through m covers every position, including the identity entry. M therefore describes the transformations, while M(x) describes the texts obtained by applying them.
f(M(x)) = {f(xᵢ′)}ᵢ₌₁ᵐ
The classifier f is evaluated on each member of the batch. The expression f(xᵢ′) is its output for the text at position i, and f(M(x)) collects the outputs for the whole batch. In the experiments, the useful output can be a distribution of probabilities over classes or a class obtained from a generated answer. The collection includes the output for the original text.
ŷ = G(f(M(x)))
The symbol ŷ denotes the final predicted label. G is the aggregation rule, and its argument f(M(x)) is the collection of outputs from the original and rewritten texts. For an aggregation rule based on probabilities, G calculates the mean score for each class and chooses the class with the highest mean. For voting, it counts each available class prediction once and selects the most frequent label.
That difference affects what the aggregation can use. Under probability averaging, a strong preference can contribute more to a class’s mean than a narrow preference. A class can also accumulate support from several versions where it came close to being selected. Under voting, each version contributes its chosen class. When BERT supplies a class probability distribution, the authors use the mean. For T5 and Falcon, they use votes after passing the generated output through a verbalizer, a rule mapping valid answers such as a label word or a numeric identifier to the task’s class. The standard configuration uses the original and four rewrites, so the vote-based procedure operates over the five inputs.
What the generator is asked to do
The authors use Stable Beluga 2-7B, abbreviated SB2, as the rewriting generator. It is an instruction-tuned derivative of Llama 2. Its job is to produce candidate phrasings. The classifier subsequently reads those phrasings and determines their contribution to the label. The paper describes the generation step with a conditional sampling expression.
x′ ∼ LLM(x′ | P, x)
The symbol x′ denotes a generated rewrite. LLM denotes the generator’s distribution over possible output texts. P is the prompt, and x is the input text to be rewritten. The tilde marks a draw from the distribution, the bar separates the output from what it is conditioned on, and the comma separates the two conditions. The prompt must tell the generator what to preserve and what sort of change to make.
In the paraphrasing condition, the prompt asks the generator to re-express the input while keeping its meaning. This is a zero-shot instruction in the sense that it includes no demonstration texts. The rewriting stage can therefore run without access to examples from the classifier’s original domain. A successful result might change the structure of a sentence or express the same judgment using different words. The experiment tests whether these ordinary paraphrases expose useful evidence for a fixed classifier.
ICR adds 16 texts drawn from the ID training split. The authors describe the selection as random and balanced across classes. The examples appear without labels in the rewriting prompt. Their function is to show what texts from the familiar domain are like. For the sentiment classifier trained on Amazon reviews, the prompt can thereby demonstrate the style of reviews without requiring a written description of that style. The instruction still asks the generator to preserve the test input’s meaning. The intended result is an alternative expression of the same example, written in a way that draws on the supplied samples.
The use of unlabeled exemplars in the ICR prompt differs from the use of labeled demonstrations for a classifier such as Falcon. In generation, the in-context material guides how a text is rewritten. In classification, it demonstrates the mapping from a text to a label and the format in which the answer should appear. Falcon’s task prompt is described as 16-shot and balanced across classes. The appendix specifies a seed of 42 for selecting and ordering its training examples. The classifier uses greedy decoding, with a limit of 10 new tokens, and a verbalizer interprets its output.
The output format also mattered during prompt development. The authors report using brackets to delimit generated text and asking for changes to details within the constraint of preserving meaning. At OOD evaluation time they use temperature-based decoding at 0.3 for both the generative rewriting methods and back-translation. The temperature controls the randomness of the choices made during decoding. For ID generation with SB2 they use a beam search with four beams, four groups, and four returned sequences, with a diversity penalty of 0.5. Beam search keeps alternative partial sequences in contention, and the diversity setting encourages the returned variants to differ. The evaluation therefore uses different decoding procedures for the familiar and unfamiliar splits.
How the system decides whether to rewrite
Entropy-based selective augmentation, or ESA, is meant to save the cost of generating variants for inputs that already receive a clear decision. Entropy is high when the probabilities are spread across candidate classes and low when the distribution concentrates on a class. A concentrated distribution gives the authors a reason to consider skipping augmentation. The intuition is that faithful variants may be unlikely to change a confident judgment. The rule uses the probabilities before any rewrite is generated.
ŷ = {
TTA(x; f; M) if H_f(x) ≥ e
arg max_y p_f(y | x) otherwise
}
The predicted label is ŷ. TTA(x; f; M) denotes the label obtained by applying augmentation collection M to input x, running classifier f, and combining its outputs. H_f(x) is the entropy of f’s probability distribution for x, and e is the chosen threshold. The symbol ≥ includes equality in the augmentation branch. The unaugmented branch uses p_f(y | x), the probability that f assigns to class y given x. The expression arg max_y selects the class with the greatest probability. The braces separate the two cases, and the semicolons in the first expression separate the arguments to TTA.
The authors choose the threshold using a labeled ID evaluation set. For a candidate threshold, they examine accuracy and the share of examples that require augmentation. The paper describes its criterion as an adaptation of the F-score, treating accuracy as the quantity playing the precision role and favoring a low augmentation rate. Writing the score as S and the rate as r, its expression combines accuracy with the share of examples left unaugmented.
S = ((1 + (1/500)²) · acc · (1 − r)) / (((1/500)² · acc) + (1 − r))
S denotes the threshold-selection score, acc denotes accuracy, and r denotes the augmentation rate on the distribution used to evaluate a threshold. The term 1 − r is the fraction of inputs that bypass rewriting. The squared factor (1/500)² sets the relative weighting in this F-score expression, the centered dot denotes multiplication, and the slash between the two parenthesized parts divides the numerator by the denominator. The criterion values high accuracy and a large share of skipped inputs. The OOD labels are used to measure performance after applying the threshold selected with the ID data.
What is trained before evaluation
The intervention assumes a working task classifier. For their experiments, the authors prepare an uncased BERT base classifier and T5-Large using supervised training on the appropriate ID task data. They use batches of 32 examples, weight decay of 0.01, and a linear learning-rate schedule that peaks at 2e-5. We choose the checkpoint that achieves the highest mean per-class F1 score on the ID test set. Here F1 is the class-level measure combining precision and recall used for checkpoint selection. The results comparison uses accuracy. This preparation is the study’s use of fine-tuning.
Once prepared, each classifier is held fixed across the comparisons for its task. Rewriting introduces a different input into the same classification procedure. The research question is whether that change alone improves which label emerges from the procedure, including the aggregation step. The authors make their augmentation logs, classifier checkpoints, and code available for reproducing the experiments.
Experiments and results
What counts as a shift in the evaluation
The evaluation covers sentiment, toxicity, and news topics. Each task has a familiar dataset on which the classifier is optimized. Evaluation on the familiar dataset measures how the procedure behaves close to that training setting. Other datasets supply challenging cases. Their training splits are excluded from task optimization, and the test comparisons use their reference labels for measurement.
For sentiment, the authors use the BOSS benchmark’s division between Amazon reviews and the harder evaluation sets. The labels are positive, neutral, and negative. The unfamiliar sets are DynaSent, SST-5, and SemEval. The benchmark chose its shifts using low cosine similarity between each candidate dataset’s centroid and the Amazon centroid. A centroid is an average representation of a collection of examples. Cosine similarity measures how closely two vectors point in the same direction. In this use it compares the aggregate representations of datasets. Two of the evaluation sources are described in papers on SST-5 and SemEval sentiment analysis.
For toxicity, the familiar dataset is Civil Comments, which contains comments posted on news articles. The task assigns either a toxic or a non-toxic label. The BOSS evaluation uses AdvCivil, an adversarial version of Civil Comments, alongside ToxiGen and Implicit Hate. These shifts also come from the benchmark’s low-centroid-similarity selection. From the classifier’s point of view, the experiment asks whether the rule learned for Civil Comments remains effective on these sources. The resulting accuracy for the task averages over the different OOD sets.
The news experiment introduces a paired shift. The familiar input consists of news articles from AG News, with World, Sports, Business, and Sci/Tech as the label options. The AG News test set has 7,600 examples, evenly divided among its categories. The shifted test set contains a generated social-media-style version of each item. Consequently, each paired example starts from the same news story and carries the original topic label. Compared with collecting articles and social posts independently, this procedure gives the authors a more direct way to vary how a story is written. AG News comes from work on character-level text classification.
The shifted news set is a separate generation procedure from the rewrites used during classification. To create it, the authors use GPT-3.5 Turbo and first ask for social-media-style texts that retain the relevant information and sentiment. They use greedy decoding in this pass and lightly process a recurring opening that combined a breaking-news announcement with emoji. They rerun 512 items whose initial outputs they judge unsatisfactory, including some with little rewriting and some composed entirely of emoji. The revised instruction encourages humor, anger, or sarcasm. The examples show what the shift amounts to in concrete terms. A report about Intel delaying a projection television chip becomes a short post with topical hashtags, while a swimming result acquires an unsupported event hashtag. A topic can survive such a change even when individual facts do not.
Baselines, classifiers, and measurement
The first comparison is the original classifier on the unmodified test input. This baseline measures whether augmentation helps at all. The other baselines apply the same overall augmentation-and-aggregation procedure while changing how the alternatives are made. That makes it possible to distinguish gains associated with generating whole-text rewrites from gains that arise whenever the classifier is given several related inputs.
The word insertion and substitution baselines use the nlpaug implementation recommended by earlier work. With its default settings, each word has a 30% chance of being selected for augmentation, subject to a maximum of 10 words. An insertion places a contextually predicted word after a selected position. A substitution instead replaces the selected word using a contextual prediction. Both use BERT to propose words that fit the surrounding text. These proposals can produce locally plausible edits, while the subsequent classification comparison tests whether the resulting texts are helpful as a batch.
Back-translation offers a whole-text baseline. The procedure translates English into German and then back into English with stochastic decoding. The returned English can differ in structure and wording from its source while aiming to carry the same information. Since back-translation can make more extensive changes than word editing, it gives the paper a comparison between different ways of getting a paraphrase, as well as a comparison between local edits and whole-text rewriting. The paper situates the baseline in earlier back-translation work.
The classifiers are BERT, T5-Large, and Falcon-7b. The first uses probability averaging, and the other two use voting over mapped label outputs. Architecture, preparation, and aggregation therefore differ across classifiers. Within a comparison for one classifier, the authors hold the aggregation rule fixed and use a single augmentation function in each run. The accuracy measures how frequently the resulting class agrees with the dataset label. The OOD means and standard deviations summarize four evaluation runs with different random generations. The ID results come from a single run. Where sentiment and toxicity results are grouped by task, the OOD figure also averages across the corresponding shifts. The respective pretrained systems are described in the BERT paper and the T5 paper.
Sentiment on unfamiliar text
For BERT, the observed mean OOD sentiment accuracy is 52.05% on the original input. Back-translation reaches 52.41%, while word insertion and substitution both fall below the unaugmented score. SB2 paraphrases lift the mean to 55.24%, and ICR reaches 57.17%. The paper reports the latter as a gain of 5.12 percentage points. The comparison uses the same fixed classifier and the same three challenging sentiment datasets throughout. The standard deviation reported for ICR’s mean OOD sentiment accuracy is 0.2 percentage points across the generation runs.
BERT augmentation methods on BOSS OOD sentiment accuracy
Exemplar-guided rewriting leads the sentiment comparison, ahead of paraphrasing and the conventional baselines.
The numbers
| System or setting | accuracy % |
|---|---|
| No augmentation | 52.05 |
| Word insertion | 51.66 |
| Word substitution | 51.44 |
| Back-translation | 52.41 |
| LLM-TTA paraphrase | 55.24 |
| LLM-TTA with ICR (this paper) | 57.17 |
T5 begins at 58.09% mean OOD sentiment accuracy and reaches 59.75% with ICR. Its score with the paraphrasing prompt is 59.01%. This is a case where the two classifiers agree on the ordering of the generative approaches, even though their starting accuracies and gains differ. Falcon begins at 46.77% and reaches 43.79% with ICR. Its 45.15% with paraphrasing also trails the unaugmented classifier. A single set of rewritten inputs can therefore lead to different outcomes depending on which classifier reads the text and how its outputs are combined.
Toxicity on unfamiliar comments
In BERT’s toxicity results, the mean OOD accuracy is 53.88% without augmentation. Back-translation gives 62.11%. Exemplar-guided rewriting gives 61.06%, while paraphrasing gives 64.67%. That ordering is important for interpreting the overall comparison. The best generator-guided setting uses no familiar examples in its rewriting prompt, and back-translation also gives a substantial improvement. ICR’s reported improvement of 7.18 percentage points is relative to the original BERT classifier on the OOD toxicity sets.
BERT augmentation methods on BOSS OOD toxicity accuracy
Free paraphrasing leads the toxicity comparison, with back-translation also improving on the original prediction.
The numbers
| System or setting | accuracy % |
|---|---|
| No augmentation | 53.88 |
| Word insertion | 53.11 |
| Word substitution | 52.70 |
| Back-translation | 62.11 |
| LLM-TTA paraphrase (this paper) | 64.67 |
| LLM-TTA with ICR | 61.06 |
T5 shows the same preference for paraphrasing on the OOD toxicity sets. Its mean accuracy is 58.83% with the original input, 63.83% with ICR, and 67.20% with paraphrasing. For Falcon, the original input yields 59.11%, while paraphrasing yields 58.90% and ICR yields 58.11%. The strong improvement for the fine-tuned classifiers and the small declines for Falcon are both part of the result. An augmentation method that suits a task’s text may still fail to yield a gain with a particular classifier.
News written in a social-media style
For the synthetic news shift, BERT already scores 88.57% with the original social-media-style input. ICR brings this mean OOD accuracy to 89.72%, a gain reported as 1.15 percentage points, and paraphrasing gives 88.97%. T5’s mean OOD scores are 88.99% without augmentation and 90.30% with ICR. Falcon, whose unaugmented score on this shift is 25.86%, reaches 27.82% with ICR and 27.50% with paraphrasing. The improvement on news gives a concrete exception to the weaker Falcon results on sentiment and toxicity.
Across the OOD tasks the paper reports average ICR gains of 4.48 percentage points for BERT and 2.66 percentage points for T5. Falcon’s overall LLM-TTA change is reported as –0.67 percentage points. The paper also reports the average change for the conventional BERT comparisons. Back-translation gives a gain of 2.85 percentage points, while the changes for word insertion and substitution are –0.29 and –0.53 points, respectively. These averages summarize several distinct shifts. The news experiment starts much closer to the familiar-domain accuracy for the fine-tuned classifiers than some other comparisons do, and the BERT toxicity comparison gives a stronger showing for a conventional whole-text method than the sentiment comparison does.
Accuracy on the familiar data
For sentiment, BERT’s ID accuracy on Amazon reviews is 90.38% without augmentation and 90.85% with ICR. T5 goes from 90.12% to 90.78% in the same comparison. On Civil Comments, BERT’s ID toxicity accuracy is 88.46% without augmentation and 91.45% with ICR. The paper reports that increase as 2.99 percentage points. For T5 on the same ID toxicity split, the scores are 90.57% and 91.87%. These results show that some inputs from a familiar dataset also benefit from an additional view.
AG News is the less favorable familiar-domain comparison for the fine-tuned classifiers. BERT’s ID accuracy is 94.43% without augmentation, 93.72% with paraphrasing, and 93.53% with ICR. The corresponding T5 scores are 94.87%, 92.05%, and 91.99%. This matters when the incoming stream could contain familiar news alongside the shifted texts. The improvement observed on the shifted set and the decline observed on the familiar set describe different parts of that stream. An overall average across tasks obscures this dependence on the task and split.
Accuracy when only uncertain inputs are rewritten
The selective experiment uses BERT because it supplies the class probabilities needed to calculate entropy and because it gains consistently from augmentation in the main comparisons. The score for the original input determines whether a rewrite is attempted. The augmentation rate measures the fraction of test inputs that enter this branch. Accuracy is still evaluated over the entire test set, including examples that bypass the generator.
BERT OOD sentiment accuracy with default and selective ICR on BOSS
Selective rewriting improves on the original classifier while full rewriting retains an accuracy advantage.
The numbers
| System or setting | accuracy % |
|---|---|
| No augmentation | 52.05 |
| Selective ICR | 56.38 |
| ICR on every input (this paper) | 57.17 |
On OOD sentiment, selective ICR augments 56.53% of inputs and reaches 56.38% mean accuracy. The authors report a gain of 4.33 points for this setting, compared with 5.12 points under full ICR. For paraphrasing, mean OOD sentiment accuracy changes from 55.24% under full augmentation to 54.77% at a selective augmentation rate of 50.51%.
On OOD toxicity, selective ICR reaches 58.33% mean accuracy at an augmentation rate of 66.50%, compared with 61.06% when every input is rewritten. At the same reported rate of 66.50%, selective paraphrasing reaches 61.24%, compared with 64.67% under full paraphrasing. On the news shift, the selective procedure uses the generator on a much smaller fraction of the examples. ICR reaches 89.21% mean OOD accuracy at a rate of 3.76%. Selective paraphrasing gives 88.80% mean OOD accuracy at a rate of 1.62%.
Full augmentation has a rate of 100.00% for each task. The study reports a 57.74% average reduction in the proportion of OOD inputs augmented for BERT with selective ICR. Since the standard procedure generates a batch whenever an input is selected, skipping those inputs reduces the amount of generation. The measured accuracy tradeoff is visible on each task. The selective system remains above the original prediction baseline, and the full system scores higher than the selective one for the same rewriting method.
What the ablations show
Can the rewriter do the classification itself?
SB2 is capable of answering the classification prompts directly. The authors test this because any gain from a system that includes SB2 raises the question of what the separate task classifier contributes. They prompt SB2 with the same classification templates and examples used for Falcon, then compare its direct answers with the outputs from classifiers receiving ICR augmentations.
On OOD sentiment, SB2 directly obtains 50.63% mean accuracy. BERT with ICR obtains 57.17%, and T5 with ICR obtains 59.75%. On the news shift, direct SB2 obtains 80.50%, compared with 89.72% for BERT with ICR and 90.30% for T5 with ICR. Direct SB2 also scores below the corresponding BERT and T5 ICR pipelines on all the familiar datasets. The generator can therefore provide useful formulations for a classifier that is already better at the labeling task than the generator is.
The OOD toxicity comparison goes the other way. SB2 classifies the unfamiliar toxicity data directly with 71.76% mean accuracy. The corresponding ICR scores are 61.06% for BERT and 63.83% for T5. The direct answer also exceeds T5’s paraphrase-based result of 67.20%. The experiment establishes that the division between rewriting and classification is valuable in some settings. It also shows why the generator’s stand-alone accuracy belongs in an evaluation of that division of labor.
How much labeled training data does the classifier need?
The authors train BERT with 5%, 10%, 20%, 40%, and 80% of each task’s ID training set, alongside the full-data comparison. They build the smaller subsets through random sampling stratified by class. The classifier family and training hyper-parameters stay the same. In the resulting comparison, augmentation is evaluated against the no-augmentation baseline appropriate to each training size. That prevents a benefit of having more labeled training examples from being confused with a benefit of rewriting at test time.
The peak reported gain for sentiment occurs at 10% of the training data. For news, it occurs at 20%, and for toxicity it occurs at 100%. The paper describes the differences between the best training size and the full-data case as generally small. The common finding is that improvements occur for classifiers trained with both restricted and full training sets. The different locations of the peaks provide little support for a rule that test-time rewriting becomes steadily more useful as labeled data get scarcer. The experiment changes the amount of downstream training data for BERT. Its conclusions apply to that intervention.
What changes when a batch contains more rewrites?
The main evaluation uses four augmentations with the original. The authors vary the number of augmentations in a separate BERT experiment to see how quickly the accuracy benefit accumulates. They average the OOD improvements across the shifts and compare the methods at different batch sizes. The generative approaches generally level off after two augmentations. Word-level methods can continue to benefit when given a larger batch.
This analysis changes the cost of treating a selected example. The entropy gate changes how often an example is selected in the first place. A larger batch is useful when further variants contribute enough additional evidence to change the decision productively. The plateau suggests diminishing returns for the later generated variants in these comparisons. It remains a pattern across the tested settings, since the useful batch size depends on the task and augmentation function.
Which labels gain and which lose?
For BERT with ICR, the authors inspect cases where the final judgment differs from the original prediction. They group the changes by reference label and distinguish corrections from newly introduced mistakes. An average improvement can result from many corrections accompanied by many mistakes. The class breakdown shows where those two kinds of change occur.
In OOD sentiment, the positive and neutral classes receive more corrections than new mistakes. Negative sentiment has slightly more new mistakes than corrections. In OOD toxicity, the net benefit comes from non-toxic examples. The shifts in news predictions are less frequent than those in sentiment and toxicity. Even for a class that gains overall, the analysis finds cases that were correct before the rewrites entered the decision.
These observations clarify the role of the original prediction in the aggregate. Keeping it in the batch allows it to influence the final answer, but the rewrites can collectively override it. The overrides create both the measured improvements and some of the losses. The class analysis records the direction of those changes. It leaves individual explanations about why a particular text changed class open.
Does ICR make the shifted text look in-distribution?
The authors test part of ICR’s proposed mechanism on the shift from Amazon reviews to SST-5. They use a RoBERTa-based sentence representation to embed the original texts and rewrites as vectors. For each SST-5 example they average the representations of its four augmentations, then compare centroids for the collections. This analysis uses a separate representation from the classifier’s final label scores. It measures aggregate proximity in that representation rather than agreement on the sentiment task.
The cosine similarity between the original SST-5 centroid and the Amazon evaluation centroid is 0.3285. Using the rewrite representations, the corresponding similarity with the Amazon centroid is 0.3445. The visualization in the paper places much of the rewritten material in the broad region occupied by the original SST-5 examples. ICR brings the centroid slightly closer to Amazon reviews in this comparison. The separation visible in the representation remains substantial.
That finding helps narrow the interpretation of the accuracy gain. A rewrite can change the evidence a classifier encounters without turning the test collection into a close match for the training domain. The comparison with zero-shot paraphrasing indicates that the ID demonstrations can improve the final decision for some tasks. The embedding experiment leaves room for changes that matter for classification but are too local or too varied to register as a large movement of the centroid. It tests the proposed domain-bridging explanation through one sentiment pair and one representation.
Does the number of parameters explain the response?
The main BERT, T5, and Falcon comparisons leave several explanations for differences in benefit. The classifiers differ in architecture, training experience, and how they make task predictions, as well as in size. The paper reduces some of these confounders with a comparison within the Pythia family. Its evaluated systems have sizes of 2.8b, 6.9b, and 12b. They share the training corpus and data order and use the same architecture family. The paper uses Pythia runs trained with duplicated examples.
The OOD evaluations use SST-5, ToxiGen, and AG Tweets. On SST-5, the 2.8b system goes from 39.27% accuracy without augmentation to 41.20% with paraphrasing. The 6.9b system gives 51.96% without augmentation and 53.08% with ICR. For the 12b system, the corresponding unaugmented and ICR accuracies are 46.18% and 45.05%. Some comparisons on the other shifts are nearly flat. On ToxiGen, the 6.9b system records 57.63% both without augmentation and with ICR. On AG Tweets, the same system gives 25.05% without augmentation and 25.12% with ICR.
The authors find no clear relationship between parameter count and the accuracy change due to TTA in this controlled comparison. They point to training and architectural factors as possible explanations for the uneven response observed in the main study. They mention that the Pythia training run with duplicates used 300 billion tokens, compared with the cited 3.3 billion tokens for BERT. Those corpus figures motivate a question about pretraining. The within-family experiment isolates size more closely, while leaving the influence of the pretraining objective and corpus size unresolved. The Pythia corpus is The Pile.
Limitations
Limits identified by the authors
The authors use a broad definition of OOD. The sentiment and toxicity datasets were chosen for low centroid similarity to the familiar data, and the news shift was produced by rewriting articles. Those choices give the evaluation a range of challenging inputs. Low similarity at dataset level can coexist with individual examples that resemble the training distribution. Several properties can also change together when the evaluation moves to a different source. A gain under this setup gives evidence for the particular shift. Identifying which feature of the shift caused the difficulty, and which change in a rewrite corrected it, would require a more tightly controlled comparison.
The paired news set offers some of that control because writers on both sides of a pair are expressing a version of the same source story. Its construction nevertheless introduces variation beyond register. The authors point out that they did not impose Twitter’s character limit, so the generated inputs are more broadly social-media-like. They did not manually check every item for preservation of its original class, and some generated stories introduce unsupported details. Their choice of topic classification makes sense because a story can keep its subject when its phrasing changes substantially. It also means that accuracy can stay high in spite of changes that would matter for factual fidelity.
The authors describe the additional computation and latency as a practical cost. Full augmentation has to generate alternatives and classify each one. The entropy rule saves generation on selected examples, but its accuracy is below full augmentation in the reported comparisons. A confident error can bypass rewriting, while an uncertain prediction can consume a batch even if its label is already correct or its rewrites give the same answer. The authors treat entropy as a heuristic for allocating effort. They leave open how much a more direct signal of likely benefit could improve that allocation.
The benefit is generally modest relative to the loss in accuracy associated with the evaluated shifts. A comparison such as BERT’s sentiment results makes the difference visible. Accuracy after ICR on OOD sentiment is 57.17%, while the ICR run on the familiar Amazon evaluation reaches 90.85%. The gain is worth distinguishing from a recovery of familiar-domain performance. Direct use of the generator is also a serious comparator in the setups where it is already better at the task, as demonstrated on OOD toxicity.
The authors discuss two uncertainties concerning pretraining. BERT, T5, and Falcon may have encountered evaluation material during pretraining, and the study does not establish whether such exposure changes how much rewriting helps. More broadly, the paper cannot identify why some classifiers are more receptive to TTA than others. The Pythia analysis weakens an explanation based solely on parameter count. It leaves training objective, corpus, and architecture among the relevant factors that differ in the main comparison.
The scope of the task also matters. All experiments concern assigning a class to short text. An output that refers to a particular span of the source may depend on preserving its structure and exact wording. Rewriting may remove the span or move it to a new position, making it necessary to align a result back to the original. The authors point to extractive question answering as a task where this concern arises. The classification results do not resolve how augmentation would work there.
Limits visible in the experimental setup
Architecture independence describes the form of the intervention. Empirical effectiveness is a separate question, even for an endpoint that accepts the rewritten text. A deployment that returns only a label could support vote aggregation. BERT’s probability averaging and the entropy gate require access to class probabilities. The study demonstrates the gate using BERT, so its efficiency result does not establish the performance of selection with the voting interfaces used for T5 or Falcon. ICR also requires access to representative text from the familiar domain, and the authors’ threshold selection uses labeled ID evaluation data. A practitioner with access only to a classification endpoint would have more of what the paraphrasing condition requires than what the full selective ICR setup requires.
The familiar-domain evaluations deserve particular care. According to the training appendix, average class F1 measured on the ID test set determines which fine-tuned checkpoints are chosen. The selective procedure also chooses thresholds on labeled ID evaluation data. The reported familiar-domain results are consequently tied to this evaluation procedure. The OOD tests address transfer to separate datasets, and the threshold choices use only ID labels. A fresh familiar-domain holdout, kept aside from both checkpoint selection and threshold choice, would answer a different question about how those decisions generalize. The single ID run also provides less direct evidence about generation variability than the repeated OOD runs.
The augmentation rate is a measure of how many inputs require rewriting. It does not contain the length of the texts, the length of the ICR prompt, the time the generator spends processing a batch, or the cost of the extra classifier evaluations. Equal rates can involve different computing work. The reported reduction therefore supports an efficiency claim about avoiding generation on some inputs, while leaving end-to-end timing and resource savings unmeasured by that statistic.
Finally, agreement with the reference label is the principal measure of success. Higher accuracy can coexist with errors in the rewrites, newly incorrect judgments about some examples, or uneven effects between classes. The authors’ analysis of changed labels exposes some of this heterogeneity. It does not by itself measure semantic faithfulness for every generated variant, and the centroid analysis cannot supply that information. The strongest conclusion is about final classification accuracy under the tested conditions. More specific conclusions about which meanings survive, which kinds of mistakes are corrected, or whose texts benefit require measurements matched to those questions.
What came after
The two later works that cite the paper concern robustness in in-context learning itself. In the original study, demonstrations from the familiar domain give the rewriter examples of how an input could be expressed. It is the classifier downstream that is evaluated under distribution shift. The later titles place the different distributions in the problem of obtaining or using demonstrations. This makes the demonstration supply part of the robustness question.
From Fake to Real (2026) frames its problem as mitigating out-of-distribution bias in in-context learning. Its title identifies feedback supervision from large language systems as the proposed means. The connection is that the outcome can depend on the relation between the context seen by the system and the task inputs. O’Brien and colleagues vary whether the rewriter sees familiar examples. The later paper’s stated focus is the use of feedback to address bias when in-context learning encounters a distribution mismatch.
Toward Robust In-Context Learning (2026) focuses on retrieving demonstrations when the target is inaccessible and identifies out-of-distribution proxies as the basis for retrieval. The original ICR experiment draws its demonstrations from an available ID training set. The later work’s title places the constraint at a different step. Its question concerns how to obtain useful demonstrations when direct access to the target is unavailable.
The titles and citations establish these thematic connections. They leave open whether either work incorporates the original rewriting pipeline, its aggregation rules, or the entropy gate. The shared thread is the relationship between the examples supplied in context and the distribution on which a system has to work. The original paper tests that relationship by changing how a fixed classifier’s inputs are expressed. The later works put feedback and demonstration retrieval, respectively, at the center of the problem.
Cite
Cite as Kyle O'Brien, Nathan Ng, Isha Puri, Jorge Mendez, Hamid Palangi, Yoon Kim, Marzyeh Ghassemi and Thomas Hartvigsen. 2024. Improving Black-box Robustness with In-Context Rewriting. arXiv (Cornell University).
@misc{obrien2024improving,
title = {{Improving Black-box Robustness with In-Context Rewriting}},
author = {Kyle O'Brien, Nathan Ng, Isha Puri, Jorge Mendez, Hamid Palangi, Yoon Kim, Marzyeh Ghassemi and Thomas Hartvigsen},
year = {2024},
doi = {10.48550/arxiv.2402.08225},
eprint = {2402.08225},
archivePrefix = {arXiv},
url = {https://doi.org/10.48550/arxiv.2402.08225}
}This page in Markdown https://md.research.elamur.ai/free/en/papers/brien-2024-improving-black-box-robustness-context/