SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2405.18540 · ICLR · 2025

Learning diverse attacks on large language models for robust red-teaming and safety tuning

Yoshua Bengio, Moksh Jain, Sung Hwang, Gauthier Gidel, Juho Lee, Kenji Kawaguchi, Seanie Lee, Minsu Kim, Nikolay Malkin, David Dobre, Lynn Cherif

arXiv · PDF · Open in the Atlas

Code that ran

7 of 8 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (0 of them constructed an object rather than computing a result; 0 honoured the contract we drafted, 1 violated it and 0 have no contract verdict; 6 failures of our instrument; 1 no recorded run), measured 2026-11-22; 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/2405.18540.json · badge: /api/ran/2405.18540.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
GFNOrg/red-teaming canonical (classifier label)
classifier basis: census
6 ran · 1 no recorded run
gfnorg/red-teaming canonical (classifier label)
classifier basis: classifier_2025
1 ran · 0 no recorded run
FunctionStatusWhere it lives
avg_pooling Ran
ran; our contract draft was wrong, not the code
GFNOrg/red-teaming/trainers/gfn_trainer.py
code served (permissive licence) · get_code("9e3fca8886c2c85e")
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 Tensor, ndim 2, dtype family float, shape (2, 4) 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

torch.manual_seed(0)

# Create tiny tensors for the function
batch_size = 2
seq_length = 3
hidden_dim = 4

# last_hidden: shape (batch_size, seq_length, hidden_dim)
last_hidden = torch.randn(batch_size, seq_length, hidden_dim)

# attention_mask: shape (batch_size, seq_length)
# Values should be 0 or 1 to indicate valid/invalid tokens
attention_mask = torch.tensor([
    [1, 1, 0],
    [1, 1, 1]
], dtype=torch.long)

ARGS = {
    "last_hidden": last_hidden,
    "attention_mask": attention_mask,
}
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 Tensor, ndim 2, dtype family float, shape (2, 4) — shape (2, 4) 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
batch_cosine_similarity_kernel Ran
ran; our contract draft was wrong, not the code
GFNOrg/red-teaming/utils.py
code served (permissive licence) · get_code("0c83713b19aeca88")
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 float, 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
import torch.nn.functional as F

torch.manual_seed(0)

# Create a small embeddings tensor
# Shape: (num_samples, embedding_dim)
# num_samples=2, embedding_dim=4
embeddings = torch.randn(2, 4)

ARGS = {
    "embeddings": embeddings,
    "batch_size": 16,
}
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 float, 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
check_filename Ran
ran, violated the contract we drafted
GFNOrg/red-teaming/collect_samples.py
code served (permissive licence) · get_code("9fa453cce5ebc8e9")
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
import numpy as np

# Based on the function, we need:
# - exp_name: a string (experiment name)
# - file_name: a string (filename to check)

ARGS = {
    'exp_name': 'my_experiment',
    'file_name': 'my_experiment.csv'
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy, 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
get_dataloader Ran
ran; our contract draft was wrong, not the code
GFNOrg/red-teaming/dataset.py
code served (permissive licence) · get_code("a31a641c4e49e500")
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 DataLoader. 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
import json
import tempfile
import os
from unittest.mock import Mock

torch.manual_seed(0)

# Create temporary files for the datasets
temp_dir = tempfile.mkdtemp()

# Create prompt file (JSONL format)
prompt_file = os.path.join(temp_dir, "prompts.jsonl")
with open(prompt_file, 'w') as f:
    for i in range(5):
        f.write(json.dumps({"attacker_prompt": f"Attack prompt {i}"}) + "\n")

# Create instruction file (JSON format)
sft_file = os.path.join(temp_dir, "instructions.json")
instructions = [
    {"instruction": f"Instruction {i}"} for i in range(20)
]
with open(sft_file, 'w') as f:
    json.dump(instructions, f)

# Create a minimal tokenizer mock
class MockTokenizer:
    def __init__(self):
        self.eos_token_id = 2
        self.pad_token_id = 0
    
    def encode(self, text, padding=False, truncation=False, return_tensors=None):
        # Simple tokenization: split and convert to token ids
        tokens = text.split()
        token_ids = [hash(token) % 1000 + 3 for token in tokens]
        if return_tensors == 'pt':
            return torch.tensor(token_ids, dtype=torch.int64).unsqueeze(0)
        return token_ids
    
    def __call__(self, texts, padding=False, truncation=False, return_tensors=None):
        # Handle batch processing
        if isinstance(texts, list):
            batch = [self.encode(text) for text in texts]
            max_len = max(len(ids) for ids in batch)
            input_ids = []
            attention_masks = []
            for ids in batch:
                padded = ids + [self.pad_token_id] * (max_len - len(ids))
                input_ids.append(padded)
                attention_masks.append([1] * len(ids) + [0] * (max_len - len(ids)))
            if return_tensors == 'pt':
                return {
                    'input_ids': torch.tensor(input_ids, dtype=torch.int64),
                    'attention_mask': torch.tensor(attention_masks, dtype=torch.int64)
                }
            return {'input_ids': input_ids, 'attention_mask': attention_masks}
        return self.encode(texts, padding, truncation, return_tensors)
    
    def apply_chat_template(self, messages, tokenize=False):
        # Simple chat template
        text = messages[0]['content']
        return f"[USER] {text}"

tokenizer = MockTokenizer()

ARGS = {
    'name': 'gfn',
    'tokenizer': tokenizer,
    'prompt_file': prompt_file,
    'sft_file': sft_file,
    'batch_size': 2,
    'shuffle': True
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch, transformers — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type DataLoader — a DataLoader output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a DataLoader 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
get_decay_parameter_names Ran
ran; our contract draft was wrong, not the code
GFNOrg/red-teaming/utils.py
code served (permissive licence) · get_code("38c281ea8977e9ae")
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 list, ndim 1, dtype family float; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim 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 transformers.pytorch_utils import ALL_LAYERNORM_LAYERS

torch.manual_seed(0)

class SimpleModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear1 = nn.Linear(4, 3)
        self.norm = nn.LayerNorm(3)
        self.linear2 = nn.Linear(3, 2)
        self.bias_param = nn.Parameter(torch.randn(2))
    
    def forward(self, x):
        x = self.linear1(x)
        x = self.norm(x)
        x = self.linear2(x)
        return x

model = SimpleModel()

ARGS = {
    "model": model,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch, transformers — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type list, ndim 1, dtype family float — a list output has no array shape of its own; none is stated
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
get_parameter_names Ran
ran; our contract draft was wrong, not the code
GFNOrg/red-teaming/utils.py
code served (permissive licence) · get_code("214442c552c26bab")
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 list, ndim 1, dtype family float; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim 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

torch.manual_seed(0)

# Build a simple model with nested structure
class SimpleChild(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(4, 3)
        self.register_parameter('custom_param', nn.Parameter(torch.randn(2)))

class SimpleModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.child1 = SimpleChild()
        self.child2 = nn.Linear(3, 2)
        self.register_parameter('model_param', nn.Parameter(torch.randn(4)))

model = SimpleModel()

# Define forbidden layer types
forbidden_layer_types = [nn.BatchNorm1d, nn.Dropout]

ARGS = {
    'model': model,
    'forbidden_layer_types': forbidden_layer_types,
}
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 list, ndim 1, dtype family float — a list output has no array shape of its own; none is stated
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
make_chat_prompt Ran
ran; our contract draft was wrong, not the code
gfnorg/red-teaming/safety_dataset/create_safety_response.py
code served (permissive licence) · get_code("5e006375b39e3def")
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) and returned str. 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
import torch.nn as nn

class MockTokenizer:
    def apply_chat_template(self, messages, tokenize=False, add_generation_prompt=False):
        # Simulate a chat template application
        # messages is a list of dicts with 'role' and 'content'
        content = messages[0]['content']
        prompt = f"<|user|>\n{content}\n<|assistant|>\n"
        return prompt

instruction = "What is the capital of France?"
tokenizer = MockTokenizer()

ARGS = {
    'instruction': instruction,
    'tokenizer': tokenizer,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type str — a str output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a str 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
generate_and_return_z_logprob Not yet run
unverified (harvested, no recorded run)
GFNOrg/red-teaming/trainers/gfn_trainer.py
code served (permissive licence) · get_code("1c61f4ae1d677417")
How it ran

no invocation recorded.

Also present in other papers' code

Of 8 samples lifted from this paper's linked repositories, 8 carry a function identity and 0 do not. Of the 8 distinct functions with an identity, 1 are also present in other papers whose code we hold (1 with at least one paper dated earlier, 0 the same month, 1 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
get_parameter_names 4 other papers
1 dated earlier, 3 later
2106.02584 (2021-06)
Self-Attention Between Datapoints: Going Beyond Individual Input-Output Pairs in Deep Learning
2407.09533 (2024-07)
Video Occupancy Models
2408.16090 (2024-08)
EPO: Hierarchical LLM Agents with Environment Preference Optimization
and 1 more not named here

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-22.

Repositories linked to this paper

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

Abstract

Red-teaming, or identifying prompts that elicit harmful responses, is a critical step in ensuring the safe and responsible deployment of large language models (LLMs). Developing effective protection against many modes of attack prompts requires discovering diverse attacks. Automated red-teaming typically uses reinforcement learning to fine-tune an attacker language model to generate prompts that elicit undesirable responses from a target LLM, as measured, for example, by an auxiliary toxicity classifier. We show that even with explicit regularization to favor novelty and diversity, existing approaches suffer from mode collapse or fail to generate effective attacks. As a flexible and probabilistically principled alternative, we propose to use GFlowNet fine-tuning, followed by a secondary smoothing phase, to train the attacker model to generate diverse and effective attack prompts. We find that the attacks generated by our method are effective against a wide range of target LLMs, both with and without safety tuning, and transfer well between target LLMs. Finally, we demonstrate that models safetytuned using a dataset of red-teaming prompts generated by our method are robust to attacks from other RL-based red-teaming approaches. Code is available at https://github.com/GFNOrg/red-teaming. Warning: This paper contains offensive language model outputs.

For agents

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

get_harvested_code_for_paper("2405.18540")
get_code_for_paper("2405.18540")
have("2405.18540")

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

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

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

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

Connect an agent — have() is free.