SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2604.14602 · 2026

CausalDetox: Causal Head Selection and Intervention for Language Model Detoxification

Yian Wang, Yuen Chen, Hari Sundaram, Agam Goyal

arXiv · PDF · Open in the Atlas

Code that ran

6 of 9 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; 2 honoured the contract we drafted, 0 violated it and 0 have no contract verdict; 4 failures of our instrument; 3 no recorded run), measured 2026-11-23; 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/2604.14602.json · badge: /api/ran/2604.14602.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
unitaryai/detoxify canonical (classifier label)
classifier basis: census
6 ran · 3 no recorded run
FunctionStatusWhere it lives
compute_auc Ran
ran, honoured the contract we drafted
unitaryai/detoxify/model_eval/utils.py
code served (permissive licence) · get_code("2e7535087b00d38f")
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 numpy as np

# Set seed for reproducibility
np.random.seed(0)

# Create binary classification ground truth labels
y_true = np.array([0, 1, 1, 0, 1])

# Create predicted probabilities (scores between 0 and 1)
y_pred = np.array([0.1, 0.9, 0.8, 0.2, 0.7])

ARGS = {
    "y_true": y_true,
    "y_pred": y_pred,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy, sklearn — 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
compute_subgroup_auc Ran
ran, honoured the contract we drafted
unitaryai/detoxify/model_eval/utils.py
code served (permissive licence) · get_code("1049dc1056dad3ff")
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 numpy as np
import pandas as pd
from sklearn.metrics import roc_auc_score

def compute_auc(y_true, y_pred):
    try:
        return roc_auc_score(y_true, y_pred)
    except ValueError:
        return np.nan

def compute_subgroup_auc(df, subgroup, label, model_name):
    subgroup_examples = df[df[subgroup]]
    return compute_auc(subgroup_examples[label], subgroup_examples[model_name])

# Create a small dataframe with the required structure
np.random.seed(0)
df = pd.DataFrame({
    'subgroup_col': [True, False, True, False, True],
    'label_col': [1, 0, 1, 0, 1],
    'model_predictions': [0.9, 0.2, 0.8, 0.3, 0.7]
})

ARGS = {
    'df': df,
    'subgroup': 'subgroup_col',
    'label': 'label_col',
    'model_name': 'model_predictions'
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy, pandas, sklearn — 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
get_model_and_tokenizer Ran
ran; our contract draft was wrong, not the code
unitaryai/detoxify/detoxify/detoxify.py
code served (permissive licence) · get_code("12904fe5b793594c")
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 tuple, 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 transformers
from unittest.mock import MagicMock, patch
import sys

torch.manual_seed(0)

# Create a minimal state_dict (what would be model weights)
state_dict = {
    'embeddings.word_embeddings.weight': torch.randn(100, 64),
    'encoder.layer.0.attention.self.query.weight': torch.randn(64, 64),
}

# Create a mock config class that has the necessary methods
class MockConfig:
    def __init__(self, num_labels=None):
        self.num_labels = num_labels
        self.hidden_size = 64
        self.vocab_size = 100
    
    @classmethod
    def from_pretrained(cls, model_type, num_labels=None):
        return cls(num_labels=num_labels)

# Create a mock model class
class MockModel(torch.nn.Module):
    config_class = MockConfig
    
    def __init__(self, config=None):
        super().__init__()
        self.config = config
        self.embeddings = torch.nn.Embedding(100, 64)
    
    @classmethod
    def from_pretrained(cls, pretrained_model_name_or_path=None, config=None, state_dict=None, local_files_only=False):
        model = cls(config=config)
        if state_dict:
            # Load only compatible keys
            model_dict = model.state_dict()
            compatible_dict = {k: v for k, v in state_dict.items() if k in model_dict}
            model.load_state_dict(compatible_dict, strict=False)
        return model

# Create a mock tokenizer class
class MockTokenizer:
    def __init__(self):
        self.vocab_size = 100
    
    @classmethod
    def from_pretrained(cls, model_name_or_path, local_files_only=False):
        return cls()

# Patch the transformers module to return our mocks
with patch.object(transformers, 'AutoModel', MockModel):
    with patch.object(transformers, 'AutoTokenizer', MockTokenizer):
        # These patches ensure getattr works correctly
        transformers.MockModel = MockModel
        transformers.MockTokenizer = MockTokenizer

ARGS = {
    'model_type': 'bert-base-uncased',
    'model_name': 'MockModel',
    'tokenizer_name': 'MockTokenizer',
    'num_classes': 2,
    'state_dict': state_dict,
    'huggingface_config_path': None,
}
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 tuple, ndim 1, dtype family float — a tuple 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
load_input_text Ran
ran; our contract draft was wrong, not the code
unitaryai/detoxify/run_prediction.py
code served (permissive licence) · get_code("0ca28293fa42b301")
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 os
import tempfile

# Create a temporary txt file for testing
temp_dir = tempfile.mkdtemp()
temp_file = os.path.join(temp_dir, "test_input.txt")
with open(temp_file, 'w') as f:
    f.write("line 1\nline 2\nline 3")

# Test case 1: File path
ARGS = {
    "input_obj": temp_file
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
none outside the standard library — 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
move_to Ran
ran; our contract draft was wrong, not the code
unitaryai/detoxify/src/utils.py
code served (permissive licence) · get_code("f1ef1b0e36849908")
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)

# Test with a nested structure containing tensors, dicts, and lists
tensor_obj = torch.randn(2, 4)
dict_obj = {
    "tensor": torch.randn(2, 3),
    "nested_dict": {
        "another_tensor": torch.randn(2, 5)
    }
}
list_obj = [
    torch.randn(2, 4),
    {"tensor": torch.randn(2, 3)},
    [torch.randn(2, 2), torch.randn(2, 1)]
]

device = "cpu"

ARGS = {
    "obj": dict_obj,
    "device": device
}
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
update_test Ran
ran; our contract draft was wrong, not the code
unitaryai/detoxify/preprocessing_utils.py
code served (permissive licence) · get_code("db2dc7de4cb95bc5")
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 DataFrame. 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 tempfile
import pandas as pd
from pathlib import Path

# Create temporary directory for test files
temp_dir = tempfile.mkdtemp()

# Create a test CSV file
test_data = pd.DataFrame({
    'id': [1, 2, 3],
    'content': ['text one', 'text two', 'text three']
})
test_csv_path = Path(temp_dir) / 'test.csv'
test_data.to_csv(test_csv_path, index=False)

# Create corresponding labels CSV file
labels_data = pd.DataFrame({
    'id': [1, 2, 3],
    'toxic': [0, 1, 0],
    'severe_toxic': [0, 0, 1]
})
labels_csv_path = Path(temp_dir) / 'test_labels.csv'
labels_data.to_csv(labels_csv_path, index=False)

ARGS = {
    'test_csv_file': str(test_csv_path)
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
pandas — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type DataFrame — a DataFrame output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a DataFrame output the recorded ndim 2 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_dataframe_to_bool Not yet run
unverified (harvested, no recorded run)
unitaryai/detoxify/model_eval/compute_language_breakdown.py
code served (permissive licence) · get_code("5bb0e0f2124550a8")
How it ran

no invocation recorded.

load_checkpoint Not yet run
unverified (harvested, no recorded run)
unitaryai/detoxify/detoxify/detoxify.py
code served (permissive licence) · get_code("3ad447f54f3563db")
How it ran

no invocation recorded.

load_model Not yet run
unverified (harvested, no recorded run)
unitaryai/detoxify/detoxify/detoxify.py
code served (permissive licence) · get_code("784c42a453ac5e68")
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 (2 with at least one paper dated earlier, 0 the same month, 0 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
move_to 2 other papers
2 dated earlier
2210.07228 (2022-10)
Language Model Decoding as Likelihood-Utility Alignment
aaai_25418 (2023 (year only))
Video Event Extraction via Tracking Visual States of Arguments
load_input_text 1 other paper
1 dated earlier
2306.14870 (2023-06)
Composing Parameter-Efficient Modules with Arithmetic Operations

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

Large language models (LLMs) frequently generate toxic content, posing significant risks for safe deployment. Current mitigation strategies often degrade generation quality or require costly human annotation. We propose CAUSALDETOX, a framework that identifies and intervenes on the specific attention heads causally responsible for toxic generation. Using the Probability of Necessity and Sufficiency (PNS), we isolate a minimal set of heads that are necessary and sufficient for toxicity. We utilize these components via two complementary strategies: (1) Local Inference-Time Intervention, which constructs dynamic, input-specific steering vectors for context-aware detoxification, and (2) PNS-Guided Fine-Tuning, which permanently unlearns toxic representations. We also introduce PARATOX, a novel benchmark of aligned toxic/non-toxic sentence pairs enabling controlled counterfactual evaluation. Experiments on ToxiGen, ImplicitHate, and Pa-raDetox show that CAUSALDETOX achieves up to 5.34% greater toxicity reduction compared to baselines while preserving linguistic fluency, and offers a 7× speedup in head selection.

For agents

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

get_harvested_code_for_paper("2604.14602")
get_code_for_paper("2604.14602")
have("2604.14602")

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

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

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

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

Connect an agent — have() is free.