SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2108.12777 · EMNLP · 2021

Searching for an Effective Defender: Benchmarking Defense against Adversarial Word Substitution

Cho-Jui Hsieh, Kai-Wei Chang, Qi Zhang, Zongyi Li, Jianhan Xu, Xiaoqing Zheng, Linyang Li, Jiehang Zeng

arXiv · PDF · Open in the Atlas

Code that ran

4 of 9 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (1 of them constructed an object rather than computing a result; 0 honoured the contract we drafted, 0 violated it and 3 have no contract verdict; 1 failure of our instrument; 5 no recorded run), measured 2026-11-23; repository links from the Papers with Code archive attributed under CC BY-SA, no affiliation; bodies inline only under a permissive licence as GitHub detects it. Not a reproduction of the paper's results.

"Ran" means the function executed on a synthesized input and returned a value. It is not a reproduction of the paper's results. This record, dated, as JSON: /api/ran/2108.12777.json · badge: /api/ran/2108.12777.svg

Each repository's role is a label: a classifier's output recorded on the link, or, where no role is recorded, what the Papers with Code archive marked. The line under it names its basis. Neither says who wrote the code.

RepositoryRoleRan
rockylzy/textdefender canonical (classifier label)
classifier basis: census
2 ran · 0 no recorded run
RockyLzy/TextDefender community
Papers with Code archive
2 ran · 5 no recorded run
FunctionStatusWhere it lives
BaseTrainer Ran
ran on a synthesized input · constructed an object; no result was computed
RockyLzy/TextDefender/trainer/ascc.py
code served (permissive licence) · get_code("875a0b28ba40c0a5")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned an instance of its own class, BaseTrainer: the run constructed the object and did not call it, so no result was computed. The image it ran in was not recorded. The code mentions cuda, and the harness aliases cuda to the CPU for every sample; whether this run needed that is not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn
from torch.optim import Adam
from torch.optim.lr_scheduler import StepLR
from torch.utils.data import DataLoader, TensorDataset
from torch.nn.modules.loss import CrossEntropyLoss
from torch.utils.tensorboard import SummaryWriter
import tempfile

torch.manual_seed(0)

# Create a minimal BERT-like model
class MinimalBertModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(4, 3)
        self.device_attr = 'cpu'
    
    @property
    def device(self):
        return self.device_attr
    
    def forward(self, input_ids=None, inputs_embeds=None, attention_mask=None, token_type_ids=None):
        if inputs_embeds is not None:
            logits = self.linear(inputs_embeds.mean(dim=1))
        else:
            # Embed input_ids to 4 dimensions
            embedded = nn.functional.embedding(input_ids, torch.randn(10, 4))
            logits = self.linear(embedded.mean(dim=1))
        return (logits,)

# Create minimal batch data
# Each batch contains: (input_ids, attention_mask, token_type_ids, labels)
batch_size = 2
seq_length = 5
num_classes = 3

input_ids = torch.randint(0, 10, (batch_size, seq_length))
attention_mask = torch.ones(batch_size, seq_length)
token_type_ids = torch.zeros(batch_size, seq_length)
labels = torch.randint(0, num_classes, (batch_size,))

dataset = TensorDataset(input_ids, attention_mask, token_type_ids, labels)
data_loader = DataLoader(dataset, batch_size=batch_size)

# Create model
model = MinimalBertModel()

# Create loss function
loss_function = CrossEntropyLoss(reduction='none')

# Create optimizer
optimizer = Adam(model.parameters(), lr=2e-5)

# Create learning rate scheduler
lr_scheduler = StepLR(optimizer, step_size=1)

# Create tensorboard writer (optional)
temp_dir = tempfile.mkdtemp()
writer = SummaryWriter(temp_dir)

# Create args namespace with required attributes
import argparse
args = argparse.Namespace(
    max_grad_norm=1.0,
    model_type='bert',
    gradient_accumulation_steps=1
)

ARGS = {
    'data_loader': data_loader,
    'model': model,
    'loss_function': loss_function,
    'optimizer': optimizer,
    'lr_scheduler': lr_scheduler,
    'writer': writer
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch, tqdm — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type BaseTrainer — the run constructed an instance of its own class and did not call it; no shape is stated — the instrument coerces any output to an array; for a BaseTrainer output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
convert_batch_to_bert_input_dict Ran
ran; our contract draft was wrong, not the code
RockyLzy/TextDefender/trainer/ascc.py
code served (permissive licence) · get_code("950d3cda566f3244")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned dict. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch

torch.manual_seed(0)

# Create batch components
# batch[0]: input embeddings or input_ids
# batch[1]: attention_mask
# batch[2]: token_type_ids

# Create embeddings tensor (3D: batch_size=2, seq_length=4, embedding_dim=5)
input_embeds = torch.randn(2, 4, 5)

# Create attention mask (2D: batch_size=2, seq_length=4)
attention_mask = torch.ones(2, 4, dtype=torch.long)

# Create token_type_ids (2D: batch_size=2, seq_length=4)
token_type_ids = torch.zeros(2, 4, dtype=torch.long)

# Construct the batch tuple
batch = (input_embeds, attention_mask, token_type_ids)

# Model type
model_type = 'bert'

ARGS = {
    'batch': batch,
    'model_type': model_type,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type dict — a dict output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a dict output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
normalize Ran
ran on a synthesized input
rockylzy/textdefender/textattack/search_methods/particle_swarm_optimization.py
code served (permissive licence) · get_code("f353cbc87c6b9b65")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned ndarray, ndim 1, dtype family float, shape (5,) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import numpy as np

# The function normalize takes a single parameter 'n' which should be:
# - convertible to a numpy array
# - contain numeric values (some potentially negative)
# - have a length (len(n) works)
# - support sum operation

# Create a small test array with mixed positive and negative values
n_value = np.array([1.5, -2.0, 3.0, 0.5, -1.0])

ARGS = {
    "n": n_value
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type ndarray, ndim 1, dtype family float, shape (5,) — shape (5,) as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
string_to_bool Ran
ran on a synthesized input
rockylzy/textdefender/args.py
code served (permissive licence) · get_code("dba58334f3386aef")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned bool, ndim 0, dtype family float, shape () as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch

ARGS = {
    'string_val': 'true'
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type bool, ndim 0, dtype family float, shape () — shape () as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
ASCCTrainer Not yet run
unverified (harvested, no recorded run)
RockyLzy/TextDefender/trainer/ascc.py
code served (permissive licence) · get_code("dc62e1e5a832d72a")
How it ran

no invocation recorded.

EmbeddingHook Not yet run
unverified (harvested, no recorded run)
RockyLzy/TextDefender/trainer/ascc.py
code served (permissive licence) · get_code("54c850220fd6baa3")
How it ran

no invocation recorded.

EmbeddingLevelGradientTrainer Not yet run
unverified (harvested, no recorded run)
RockyLzy/TextDefender/trainer/ascc.py
code served (permissive licence) · get_code("780fac80a9c9ce61")
How it ran

no invocation recorded.

GradientTrainer Not yet run
unverified (harvested, no recorded run)
RockyLzy/TextDefender/trainer/ascc.py
code served (permissive licence) · get_code("4b67e8745a8f54ab")
How it ran

no invocation recorded.

register_trainer Not yet run
unverified (harvested, no recorded run)
RockyLzy/TextDefender/trainer/ascc.py
code served (permissive licence) · get_code("a125d92bded563ec")
How it ran

no invocation recorded.

Also present in other papers' code

Of 9 samples lifted from this paper's linked repositories, 9 carry a function identity and 0 do not. Of the 9 distinct functions with an identity, 2 are also present in other papers whose code we hold (0 with at least one paper dated earlier, 0 the same month, 2 later) and 7 are only here among the 52,977 papers whose code Syntology holds (as of 2026-09-26).

Only here means: among the 52,977 papers whose code Syntology holds (51,887 with lifted samples, 1,090 through their assemblies only), as of 2026-09-26, no other paper's lifted samples or current assembly bricks contain an identical function body after normalisation.

FunctionAlso present inEarliest-datedOthers named
normalize 1 other paper
1 later
2305.17444 (2023-05)
Query-Efficient Black-Box Red Teaming via Bayesian Optimization
string_to_bool 1 other paper
1 later
2211.02878 (2022-11)
Textual Manifold-based Defense Against Natural Language Adversarial Examples

Presence, not direction: an identical function body in two papers' repositories does not say who wrote it, which came from which, or that either paper's method rests on it. Matching is exact after normalisation, so a renamed or edited function is not matched. Dates are when papers appeared, not when code was written. Only .py files the harvester lifted are covered; notebooks are not read. A new-style arXiv id YYMM.NNNN dates a paper to the month 20YY-MM; otherwise Paper.year dates it to the year; otherwise it is undated. Dates are when the paper appeared, not when the code was written. Read 2026-11-23.

Repositories linked to this paper

Some links come from the archived Papers with Code dataset (CC BY-SA 4.0): attribution and licence.

Abstract

Recent studies have shown that deep neural network-based models are vulnerable to intentionally crafted adversarial examples, and various methods have been proposed to defend against adversarial word-substitution attacks for neural NLP models. However, there is a lack of systematic study on comparing different defense approaches under the same attacking setting. In this paper, we seek to fill the gap through comprehensive studies on the behavior of neural text classifiers trained with various defense methods against representative adversarial attacks. In addition, we propose an effective method to further improve the robustness of neural text classifiers against such attacks, and achieved the highest accuracy on both clean and adversarial examples on AGNEWS and IMDB datasets, outperforming existing methods by a significant margin. We hope this study could provide useful clues for future research on text adversarial defense. Codes are available at https:// github.com/RockyLzy/TextDefender.

For agents

The same record, over MCP at https://syntology.ai/mcp:

get_harvested_code_for_paper("2108.12777")
get_code_for_paper("2108.12777")
have("2108.12777")

The run record, dated, one paper per request, free:

curl https://syntology.ai/api/ran/2108.12777.json

A badge for a README (the split and the date, never a ratio):

[![Syntology run record](https://syntology.ai/api/ran/2108.12777.svg)](https://syntology.ai/paper/2108.12777)

Connect an agent — have() is free.