SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2404.13752 · NeurIPS · 2024

Adversarial Representation Engineering: A General Model Editing Framework for Large Language Models

Zeming Wei, Yihao Zhang, Jun Sun, Meng Sun

arXiv · PDF · Open in the Atlas

Code that ran

8 of 11 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, 0 violated it and 0 have no contract verdict; 8 failures of our instrument; 3 no recorded run), measured 2026-11-22; 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/2404.13752.json · badge: /api/ran/2404.13752.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
zhang-yihao/adversarial-representation-engineering canonical (classifier label)
classifier basis: census
8 ran · 3 no recorded run
FunctionStatusWhere it lives
get_combined_model Ran
ran; our contract draft was wrong, not the code
zhang-yihao/adversarial-representation-engineering/model.py
code served (permissive licence) · get_code("9569cb800cd81f57")
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 CombinedModel. 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

torch.manual_seed(0)

# Build a minimal generator model that returns hidden_states
class MinimalGenerator(nn.Module):
    def __init__(self, hidden_size=4, num_layers=3):
        super().__init__()
        self.hidden_size = hidden_size
        self.num_layers = num_layers
        self.embedding = nn.Embedding(100, hidden_size)
        self.linear = nn.Linear(hidden_size, hidden_size)
    
    def forward(self, prompts, output_hidden_states=0):
        # prompts is a list of strings or token ids
        # Return a mock output with hidden_states attribute
        batch_size = len(prompts) if isinstance(prompts, list) else 2
        seq_len = 5
        
        # Create mock hidden states for each layer
        hidden_states = []
        for layer_idx in range(self.num_layers):
            hidden_state = torch.randn(batch_size, seq_len, self.hidden_size)
            hidden_states.append(hidden_state)
        
        # Return object with hidden_states attribute
        class GeneratorOutput:
            pass
        
        output = GeneratorOutput()
        output.hidden_states = hidden_states
        return output

# Build a minimal classifier model
class MinimalClassifier(nn.Module):
    def __init__(self, input_size=48):
        super().__init__()
        self.linear = nn.Linear(input_size, 2)
    
    def forward(self, x):
        return self.linear(x)

# Create instances
generator_model = MinimalGenerator(hidden_size=4, num_layers=3)
classifier_model = MinimalClassifier(input_size=48)
layer_range = [0, 1, 2]

ARGS = {
    "generator_model": generator_model,
    "classifier_model": classifier_model,
    "layer_range": layer_range,
}
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 CombinedModel — a CombinedModel output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a CombinedModel 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_ft_dataloader Ran
ran; our contract draft was wrong, not the code
zhang-yihao/adversarial-representation-engineering/data.py
code served (permissive licence) · get_code("511192e4d3421c30")
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. 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)

class MockTokenizer:
    def encode(self, text, return_tensors=None):
        # Return a small tensor encoding of the text
        # Shape: (1, sequence_length) for return_tensors='pt'
        if return_tensors == 'pt':
            return torch.tensor([[1, 2, 3, 4]], dtype=torch.long)
        return [1, 2, 3, 4]

train_data = ["hello world", "foo bar"]
test_data = ["test one", "test two", "test three"]
tokenizer = MockTokenizer()
label = 0

ARGS = {
    "train_data": train_data,
    "test_data": test_data,
    "tokenizer": tokenizer,
    "label": label,
}
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 tuple — a tuple output has no array shape of its own; none is 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_linear_classifier Ran
ran; our contract draft was wrong, not the code
zhang-yihao/adversarial-representation-engineering/model.py
code served (permissive licence) · get_code("2ec267f3e9a013fc")
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 LinearClassifier. 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

torch.manual_seed(0)

ARGS = {
    "input_size": 4,
    "num_classes": 3,
    "half": 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 LinearClassifier — a LinearClassifier output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a LinearClassifier 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_logprobs Ran
ran; our contract draft was wrong, not the code
zhang-yihao/adversarial-representation-engineering/tqa_utils.py
code served (permissive licence) · get_code("7ca617e63b68d16f")
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
import torch.nn.functional as F

torch.manual_seed(0)

# Construct arguments for get_logprobs
batch_size = 2
seq_length = 5
vocab_size = 4

# logits: shape (batch_size, seq_length, vocab_size)
# The function does [:, :-1] so we keep full sequence
logits = torch.randn(batch_size, seq_length, vocab_size)

# input_ids: shape (batch_size, seq_length)
# The function indexes with [:, 1:] and uses it with gather on dim=-1
input_ids = torch.randint(0, vocab_size, (batch_size, seq_length))

# masks: shape (batch_size, seq_length)
# The function uses [:, 1:, None] to multiply, so any shape works
# Use values 0 and 1 for masking
masks = torch.ones(batch_size, seq_length)

ARGS = {
    "logits": logits,
    "input_ids": input_ids,
    "masks": masks,
}
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
get_response_from_sentence Ran
ran; our contract draft was wrong, not the code
zhang-yihao/adversarial-representation-engineering/utils.py
code served (permissive licence) · get_code("8755580d111f919d")
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 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

torch.manual_seed(0)

# Stand-in tokenizer class that mimics HuggingFace tokenizer behavior
class MockTokenizer:
    def __init__(self):
        self.vocab_size = 100
        self.pad_token_id = 0
    
    def encode(self, sentence, return_tensors=None):
        # Simple mock: convert sentence to token ids
        tokens = [1, 2, 3, 4]  # Fixed mock tokens
        if return_tensors == 'pt':
            return torch.tensor([tokens], dtype=torch.long)
        return tokens
    
    def decode(self, token_ids):
        # Mock decode: convert tokens back to string
        return "mock response text"

# Minimal generative model that satisfies the function's needs
class MockGenerativeModel(nn.Module):
    def __init__(self, vocab_size=100):
        super().__init__()
        self.vocab_size = vocab_size
        self.embedding = nn.Embedding(vocab_size, 8)
        self.linear = nn.Linear(8, vocab_size)
        self.device_val = torch.device('cpu')
    
    @property
    def device(self):
        return self.device_val
    
    def generate(self, input_ids, max_length=250):
        # Mock generation: create a sequence of tokens up to max_length
        batch_size = input_ids.shape[0]
        seq_len = input_ids.shape[1]
        
        # Generate additional tokens beyond input
        generated_seq = torch.cat([
            input_ids,
            torch.randint(1, self.vocab_size, (batch_size, max_length - seq_len))
        ], dim=1)
        
        return generated_seq

# Construct arguments
model = MockGenerativeModel(vocab_size=100)
tokenizer = MockTokenizer()
sentence = "Hello, how are you?"
max_length = 250

ARGS = {
    "model": model,
    "tokenizer": tokenizer,
    "sentence": sentence,
    "max_length": max_length
}
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 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
get_simple_classifier Ran
ran; our contract draft was wrong, not the code
zhang-yihao/adversarial-representation-engineering/model.py
code served (permissive licence) · get_code("92549591cfee0bc1")
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 SimpleClassifier. 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.cuda.amp import autocast

torch.manual_seed(0)

ARGS = {
    "input_size": 10,
    "num_classes": 5,
    "half": 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 SimpleClassifier — a SimpleClassifier output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a SimpleClassifier 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
load_function_dataset Ran
ran; our contract draft was wrong, not the code
zhang-yihao/adversarial-representation-engineering/data.py
code served (permissive licence) · get_code("4552bfcbbb33d545")
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 function. 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 numpy as np
from unittest.mock import Mock, MagicMock

torch.manual_seed(0)

# Create a mock dataset that mimics the structure returned by load_dataset
mock_train_dataset = {
    'sentence': ['This is a test sentence.', 'Another test sentence here.'],
    'label': [0, 1]
}

mock_test_dataset = {
    'sentence': ['Test sentence one.', 'Test sentence two.'],
    'label': [1, 0]
}

mock_dataset_obj = {
    'train': mock_train_dataset,
    'test': mock_test_dataset
}

# Create a mock for load_dataset that returns our mock dataset
def mock_load_dataset(path):
    return mock_dataset_obj

# Patch load_dataset in the module
import sys
from unittest.mock import patch

# Create template string
template_str = "You are an AI assistant. {instruction}"

ARGS = {
    'func_name': 'jailbreak'
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
datasets, numpy, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type function — a function output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a function 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
prepare_decoder_only_inputs Ran
ran; our contract draft was wrong, not the code
zhang-yihao/adversarial-representation-engineering/tqa_utils.py
code served (permissive licence) · get_code("57208ac8398b92a4")
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. 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)

class MockTokenizer:
    def __init__(self):
        self.padding_side = 'left'
    
    def __call__(self, texts, return_tensors=None, padding=False, truncation=False, add_special_tokens=True):
        # Simple mock: assign each text a fixed sequence of token ids
        batch_size = len(texts)
        seq_len = 5
        
        input_ids = torch.randint(0, 1000, (batch_size, seq_len))
        attention_mask = torch.ones(batch_size, seq_len)
        
        # Simulate padding to same length within batch
        result = {
            'input_ids': input_ids,
            'attention_mask': attention_mask
        }
        
        return result

prompts = ["Hello world", "How are you"]
targets = ["response one", "response two"]
tokenizer = MockTokenizer()
device = 'cpu'

ARGS = {
    'prompts': prompts,
    'targets': targets,
    'tokenizer': tokenizer,
    '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 tuple — a tuple output has no array shape of its own; none is 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_logits_from_sentence Not yet run
unverified (harvested, no recorded run)
zhang-yihao/adversarial-representation-engineering/utils.py
code served (permissive licence) · get_code("10fbd09fe2900ed0")
How it ran

no invocation recorded.

jailbreak_dataset Not yet run
unverified (harvested, no recorded run)
zhang-yihao/adversarial-representation-engineering/data.py
code served (permissive licence) · get_code("08a7082fc03e045c")
How it ran

no invocation recorded.

load_tqa_sentences Not yet run
unverified (harvested, no recorded run)
zhang-yihao/adversarial-representation-engineering/tqa_utils.py
code served (permissive licence) · get_code("67739638a15cdc16")
How it ran

no invocation recorded.

Also present in other papers' code

Of 11 samples lifted from this paper's linked repositories, 11 carry a function identity and 0 do not. Of the 11 distinct functions with an identity, 0 are also present in other papers whose code we hold (0 with at least one paper dated earlier, 0 the same month, 0 later) and 11 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.

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

Since the rapid development of Large Language Models (LLMs) has achieved remarkable success, understanding and rectifying their internal complex mechanisms has become an urgent issue. Recent research has attempted to interpret their behaviors through the lens of inner representation. However, developing practical and efficient methods for applying these representations for general and flexible model editing remains challenging. In this work, we explore how to leverage insights from representation engineering to guide the editing of LLMs by deploying a representation sensor as an editing oracle. We first identify the importance of a robust and reliable sensor during editing, then propose an Adversarial Representation Engineering (ARE) framework to provide a unified and interpretable approach for conceptual model editing without compromising baseline performance. Experiments on multiple tasks demonstrate the effectiveness of ARE in various model editing scenarios. Our code and data are available at https://github.com/ Zhang-Yihao/Adversarial-Representation-Engineering.

For agents

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

get_harvested_code_for_paper("2404.13752")
get_code_for_paper("2404.13752")
have("2404.13752")

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

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

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

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

Connect an agent — have() is free.