SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2406.14144 · NeurIPS · 2025

Towards Understanding Safety Alignment: A Mechanistic Perspective from Safety Neurons

Yushi Bai, Juanzi Li, Lei Hou, Xiaozhi Wang, Zijun Yao, Jianhui Chen, Multi-Layer Perceptron

arXiv · PDF · Open in the Atlas

Code that ran

14 of 14 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 1 has no contract verdict; 12 failures of our instrument; 0 no recorded run); 1 of them was also run on the host, not in the jail, by the peer-agreement lane that set its level, 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/2406.14144.json · badge: /api/ran/2406.14144.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
THU-KEG/SafetyNeuron canonical (classifier label)
classifier basis: census
14 ran · 0 no recorded run
FunctionStatusWhere it lives
repeat_kv Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
THU-KEG/SafetyNeuron/src/models/HookedGemma.py
code served (permissive licence) · get_code("30d7eec482ebf6b1")
How it ran

Ran in Syntology's jail on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1) and returned Tensor, ndim 4, dtype family float, shape (2, 6, 5, 4) as a later run recorded it. The image it ran in was not recorded. The comparison behind this sample's level is a different run: the peer-agreement lane ran it again on the host, not in the jail (report dated 2026-09-04T23:09:20Z). 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 a tensor with shape (batch, num_key_value_heads, seqlen, head_dim)
# Using distinct sizes: batch=2, num_key_value_heads=3, seqlen=5, head_dim=4
hidden_states = torch.randn(2, 3, 5, 4)

# n_rep is the repetition factor
n_rep = 2

ARGS = {
    "hidden_states": hidden_states,
    "n_rep": n_rep,
}
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 Tensor, ndim 4, dtype family float, shape (2, 6, 5, 4) — shape (2, 6, 5, 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
apply_rotary_pos_emb Ran
ran; our contract draft was wrong, not the code
THU-KEG/SafetyNeuron/src/models/HookedGemma.py
code served (permissive licence) · get_code("bac65c3dafaec040")
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 tuple, ndim 5, 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

torch.manual_seed(0)

# Create small tensors for query and key
# Shape: [batch_size, heads, seq_len, head_dim]
batch_size = 2
heads = 3
seq_len = 4
head_dim = 8

q = torch.randn(batch_size, heads, seq_len, head_dim)
k = torch.randn(batch_size, heads, seq_len, head_dim)

# Create cos and sin tensors
# Shape: [batch_size, seq_len, head_dim]
cos = torch.randn(batch_size, seq_len, head_dim)
sin = torch.randn(batch_size, seq_len, head_dim)

# position_ids is optional and unused according to docstring
position_ids = None

# unsqueeze_dim defaults to 1
unsqueeze_dim = 1

ARGS = {
    "q": q,
    "k": k,
    "cos": cos,
    "sin": sin,
    "position_ids": position_ids,
    "unsqueeze_dim": unsqueeze_dim,
}
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 tuple, ndim 5, 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
create_prompt_with_llama2_chat_format Ran
ran; our contract draft was wrong, not the code
THU-KEG/SafetyNeuron/src/eval/templates.py
code served (permissive licence) · get_code("e51c9713fadad16f")
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

# Define the arguments for create_prompt_with_llama2_chat_format
ARGS = {
    'messages': [
        {'role': 'system', 'content': 'You are a helpful assistant.'},
        {'role': 'user', 'content': 'Hello, how are you?'},
        {'role': 'assistant', 'content': 'I am doing well, thank you for asking.'},
        {'role': 'user', 'content': 'What is your name?'},
        {'role': 'assistant', 'content': 'I am Claude, an AI assistant.'}
    ],
    'bos': '<s>',
    'eos': '</s>',
    'add_bos': 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 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
create_prompt_with_tulu_chat_format Ran
ran; our contract draft was wrong, not the code
THU-KEG/SafetyNeuron/src/eval/templates.py
pointer only (licence: MIT); the stored copy get_code serves, from thu-keg/crab, is pointer only (licence: NONE) · get_code("697d92a5d51eff3e")
How it ran

The body of this sample is withheld: this paper's link allows the body inline (MIT), but get_code serves the stored copy, first harvested from thu-keg/crab, and GitHub detected no licence in that repository when it was checked. The setup block that called it is withheld with it, because it is written against that body. source_path and origin say where the code lives, to read under the repository's own terms. A run is recorded.

dispatch_openai_chat_requesets Ran
ran on a synthesized input
THU-KEG/SafetyNeuron/src/eval/dispatch_openai_requests.py
code served (permissive licence) · get_code("233355240185dc1a")
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 coroutine. 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 os
from unittest.mock import AsyncMock, MagicMock, patch

# Set up environment variable for OpenAI API key
os.environ['OPENAI_API_KEY'] = 'sk-test-key-12345'

# Create sample messages for the function
messages_list = [
    [
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "What is 2+2?"}
    ],
    [
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "What is the capital of France?"}
    ]
]

# Model name
model = "gpt-3.5-turbo"

# Completion kwargs with common parameters for OpenAI API
completion_kwargs = {
    "temperature": 0.7,
    "max_tokens": 100,
    "top_p": 0.9
}

# Define the ARGS dict with all required parameters
ARGS = {
    "messages_list": messages_list,
    "model": model,
    **completion_kwargs
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
openai — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type coroutine — a coroutine output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a coroutine 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
dispatch_openai_prompt_requesets Ran
ran; our contract draft was wrong, not the code
THU-KEG/SafetyNeuron/src/eval/dispatch_openai_requests.py
code served (permissive licence) · get_code("0979c8368e7c6a08")
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 coroutine. 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 asyncio
from typing import Any, List, Dict
from unittest.mock import AsyncMock, MagicMock, patch

# Mock openai module since we can't make real API calls
class MockCompletion:
    @staticmethod
    async def acreate(**kwargs):
        # Return a mock response object
        return MagicMock(
            choices=[MagicMock(text="Mock response text")],
            usage=MagicMock(total_tokens=10)
        )

# Create mock openai module
mock_openai = MagicMock()
mock_openai.Completion = MockCompletion()

# Patch openai in the function's namespace
import sys
sys.modules['openai'] = mock_openai

# Now define the arguments
ARGS = {
    "prompt_list": [
        "What is the meaning of life?",
        "Explain quantum computing"
    ],
    "model": "text-davinci-003",
    "completion_kwargs": {
        "max_tokens": 100,
        "temperature": 0.7,
        "top_p": 0.9
    }
}
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 coroutine — a coroutine output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a coroutine 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_completions Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
THU-KEG/SafetyNeuron/src/eval/utils.py
code served (permissive licence) · get_code("4b7fca0051f25274")
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. 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 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 import PreTrainedModel, PreTrainedTokenizer

torch.manual_seed(0)

# Create a minimal mock tokenizer
class MockTokenizer:
    def __init__(self):
        self.pad_token_id = 0
        self.eos_token_id = 2
        
    def __call__(self, prompts, padding=None, return_tensors=None, add_special_tokens=True):
        # Return a mock tokenized output
        batch_size = len(prompts)
        seq_len = 5
        input_ids = torch.randint(1, 10, (batch_size, seq_len))
        attention_mask = torch.ones(batch_size, seq_len)
        return type('TokenizerOutput', (), {
            'input_ids': input_ids,
            'attention_mask': attention_mask
        })()
    
    def batch_decode(self, token_ids, skip_special_tokens=False):
        # Return dummy text for each sequence
        return [f"decoded_text_{i}" for i in range(token_ids.shape[0])]

# Create a minimal mock model
class MockModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.device_obj = type('Device', (), {'type': 'cpu'})()
        
    @property
    def device(self):
        return self.device_obj
    
    def generate(self, input_ids, attention_mask=None, stopping_criteria=None, **kwargs):
        batch_size = input_ids.shape[0]
        max_new_tokens = kwargs.get('max_new_tokens', 10)
        num_return_sequences = kwargs.get('num_return_sequences', 1)
        
        # Generate output tokens
        new_tokens = torch.randint(1, 10, (batch_size, max_new_tokens))
        output_ids = torch.cat([input_ids, new_tokens], dim=1)
        return output_ids

# Create instances
model = MockModel()
tokenizer = MockTokenizer()

prompts = ["Hello world", "How are you"]
batch_size = 2
stop_id_sequences = [[2], [3]]
add_special_tokens = True
disable_tqdm = True
num_return_sequences = 1

# Define all arguments
ARGS = {
    'model': model,
    'tokenizer': tokenizer,
    'prompts': prompts,
    'batch_size': batch_size,
    'stop_id_sequences': stop_id_sequences,
    'add_special_tokens': add_special_tokens,
    'disable_tqdm': disable_tqdm,
    'num_return_sequences': num_return_sequences,
    'max_new_tokens': 10
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch, tqdm, 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
generate_completions_and_masks Ran
ran; our contract draft was wrong, not the code
THU-KEG/SafetyNeuron/src/eval/utils.py
code served (permissive licence) · get_code("b4722271cba47572")
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. 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)

class SimpleTokenizer:
    def __init__(self):
        self.pad_token_id = 0
    
    def __call__(self, text, padding=None, return_tensors=None, add_special_tokens=True):
        # Simulate tokenization
        if isinstance(text, list):
            # Batch of texts
            token_lists = [[1, 2, 3, 4] for _ in text]
        else:
            # Single text
            token_lists = [[1, 2, 3, 4]]
        
        max_len = max(len(tl) for tl in token_lists)
        
        if padding == 'longest':
            padded = [[self.pad_token_id] * (max_len - len(tl)) + tl for tl in token_lists]
        else:
            padded = token_lists
        
        class TokenizerOutput:
            def __init__(self, input_ids, attention_mask):
                self.input_ids = input_ids
                self.attention_mask = attention_mask
        
        input_ids_tensor = torch.tensor(padded, dtype=torch.long)
        attention_mask_tensor = torch.tensor([[1 if x != self.pad_token_id else 0 for x in row] for row in padded], dtype=torch.long)
        
        if return_tensors == 'pt':
            return TokenizerOutput(input_ids_tensor, attention_mask_tensor)
        else:
            return TokenizerOutput(padded, [[1 if x != self.pad_token_id else 0 for x in row] for row in padded])
    
    def batch_decode(self, token_ids, skip_special_tokens=False):
        # Simple mock decode
        if isinstance(token_ids, torch.Tensor):
            token_ids = token_ids.tolist()
        return [f"text_{i}" for i in range(len(token_ids))]


class SimpleModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(4, 4)
        self.device_obj = torch.device('cpu')
    
    @property
    def device(self):
        return self.device_obj
    
    def generate(self, input_ids, attention_mask, **kwargs):
        # Mock generation: return input_ids repeated
        batch_size = input_ids.shape[0]
        num_return_sequences = kwargs.get('num_return_sequences', 1)
        
        # Expand batch for num_return_sequences
        output_ids = input_ids.repeat_interleave(num_return_sequences, dim=0)
        
        # Append some tokens to simulate generation
        extra_tokens = torch.full((output_ids.shape[0], 2), 5, dtype=torch.long)
        output_ids = torch.cat([output_ids, extra_tokens], dim=1)
        
        return output_ids


tokenizer = SimpleTokenizer()
model = SimpleModel()
prompts = ["hello world", "test prompt"]

ARGS = {
    'model': model,
    'tokenizer': tokenizer,
    'prompts': prompts,
    'batch_size': 1,
    'add_special_tokens': True,
    'disable_tqdm': True,
    'num_return_sequences': 1,
    'max_length': 10
}
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 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_act_name Ran
ran; our contract draft was wrong, not the code
THU-KEG/SafetyNeuron/src/utils.py
code served (permissive licence) · get_code("0d845b84c5219607")
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 re
from typing import Optional, Union

# Analyze the function to understand what parameters it needs
# The function takes:
# - name: str (required)
# - layer: Optional[Union[int, str]] (optional)
# - layer_type: Optional[str] (optional)

# Looking at the function body, it:
# 1. Takes a string `name` and parses it
# 2. Optionally uses `layer` as an int or str
# 3. Optionally uses `layer_type` as a string
# The function doesn't actually use these values to construct objects,
# it just processes strings and returns a string.

# Test with various examples from the docstring
ARGS = {
    "name": "k",
    "layer": 6,
    "layer_type": "a"
}

# This should produce: 'model.layers.6.self_attn.hook_k'
# based on the logic in the function
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 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_clf Ran
ran; our contract draft was wrong, not the code
THU-KEG/SafetyNeuron/src/predict_before_gen.py
code served (permissive licence) · get_code("0f88e41d70d1279d")
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 LogisticRegression. 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 tempfile
import os
from sklearn.linear_model import LogisticRegression

torch.manual_seed(0)

# Create temporary directory and mock data file
temp_dir = tempfile.mkdtemp()
mock_data_dir = os.path.join(temp_dir, 'data1', 'cjh', 'Alignment', 'output', 'activations', 'harmless_prediction')
os.makedirs(mock_data_dir, exist_ok=True)

# Create small mock training data
X_train = torch.randn(2, 4)  # 2 samples, 4 features
y_train = torch.tensor([0, 1])  # 2 labels
mock_data_path = os.path.join(mock_data_dir, 'test_dataset_5000_peft_top1500.pt')
torch.save((X_train, y_train), mock_data_path)

# Patch torch.load to return our mock data
_original_load = torch.load
def mock_load(path, *args, **kwargs):
    if 'harmless_prediction' in path:
        return (X_train.numpy(), y_train.numpy())
    return _original_load(path, *args, **kwargs)

torch.load = mock_load

ARGS = {
    'peft': 'peft',
    'dataset': 'test_dataset',
    'topk': 1500
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
sklearn, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type LogisticRegression — a LogisticRegression output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a LogisticRegression 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
layer_patch_hook Ran
ran, violated the contract we drafted
THU-KEG/SafetyNeuron/src/ppl.py
code served (permissive licence) · get_code("508cbcd9d0571483")
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 3, dtype family float, shape (2, 4, 6) 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)

# Construct the arguments for layer_patch_hook

# value: A tensor that will be modified in-place
# The function indexes into it with [..., neurons], so it needs to be at least 2D
value = torch.randn(2, 4, 6)  # batch=2, some_dim=4, feature_dim=6

# hook: A string identifier for the hook
hook = "test_hook_0"

# neurons: Indices to select from the last dimension of value
# Should be indexable (list, tensor, or array of indices)
neurons = [0, 2]  # Select neurons at indices 0 and 2

# patched_values: Values to assign to value[..., neurons]
# Should be compatible with the shape of value[..., neurons]
# value[..., neurons] has shape (2, 4, 2) since neurons has 2 elements
patched_values = torch.randn(2, 4, 2)

ARGS = {
    "value": value,
    "hook": hook,
    "neurons": neurons,
    "patched_values": patched_values,
}
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 3, dtype family float, shape (2, 4, 6) — shape (2, 4, 6) 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
load_adapter_weights Ran
ran; our contract draft was wrong, not the code
THU-KEG/SafetyNeuron/src/utils.py
code served (permissive licence) · get_code("34cedc62fcf7195b")
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 os
import torch
import tempfile
from safetensors.torch import save_file

torch.manual_seed(0)

# Create a temporary directory to serve as the path
temp_dir = tempfile.mkdtemp()

# Create sample adapter weights
adapter_weights = {
    'layer1.weight': torch.randn(4, 3),
    'layer1.bias': torch.randn(4),
    'layer2.weight': torch.randn(5, 4),
}

# Save as safetensors file
save_file(adapter_weights, os.path.join(temp_dir, 'adapter_model.safetensors'))

ARGS = {
    'path': temp_dir
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
safetensors, 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
rotate_half Ran
ran; our contract draft was wrong, not the code
THU-KEG/SafetyNeuron/src/models/HookedGemma.py
code served (permissive licence) · get_code("b99eea6376d1e212")
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 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)

# The function rotate_half takes a single parameter 'x' which is a tensor
# It accesses x.shape[-1] to get the last dimension
# It uses indexing with [..., :] slicing notation
# It calls torch.cat() to concatenate tensors

# Create a small tensor with shape (2, 4) - batch size 2, hidden dim 4
x = torch.randn(2, 4)

ARGS = {
    "x": x
}
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 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
topk_index Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
THU-KEG/SafetyNeuron/src/utils.py
code served (permissive licence) · get_code("8ae41f0bacbff51f")
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 zip. 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 a small test tensor with distinct dimensions
tensor = torch.randn(2, 4)

# k should be a positive integer smaller than the total number of elements
# or negative to select all elements
k = 3

ARGS = {
    "tensor": tensor,
    "k": k,
}
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 zip — a zip output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a zip 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

Also present in other papers' code

Of 14 samples lifted from this paper's linked repositories, 14 carry a function identity and 0 do not. Of the 14 distinct functions with an identity, 7 are also present in other papers whose code we hold (7 with at least one paper dated earlier, 3 the same month, 7 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
rotate_half 360 other papers
135 dated earlier, 21 the same month, 195 later, 6 same year, order not determinable, 3 undated · 30 only as an assembly brick
1901.02860 (2019-01)
Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context
2203.08913 (2022-03)
Memorizing Transformers
2302.13971 (2023-02)
LLaMA: Open and Efficient Foundation Language Models
and 357 more not named here
repeat_kv 243 other papers
79 dated earlier, 16 the same month, 144 later, 2 same year, order not determinable, 2 undated · 22 only as an assembly brick
1901.02860 (2019-01)
Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context
2203.08913 (2022-03)
Memorizing Transformers
2305.17888 (2023-05)
LLM-QAT: Data-Free Quantization Aware Training for Large Language Models
and 240 more not named here
apply_rotary_pos_emb 94 other papers
14 dated earlier, 6 the same month, 70 later, 1 same year, order not determinable, 3 undated · 6 only as an assembly brick
1901.02860 (2019-01)
Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context
2305.17888 (2023-05)
LLM-QAT: Data-Free Quantization Aware Training for Large Language Models
2309.11674 (2023-09)
A Paradigm Shift in Machine Translation: Boosting Translation Performance of Large Language Models
and 91 more not named here
create_prompt_with_tulu_chat_format 8 other papers
5 dated earlier, 3 later
2401.10768 (2024-01)
Knowledge Verification to Nip Hallucination in the Bud
2401.16405 (2024-01)
Scaling Sparse Fine-Tuning to Large Language Models
2403.03870 (2024-03)
Learning to Decode Collaboratively with Multiple Language Models
and 5 more not named here
dispatch_openai_prompt_requesets 8 other papers
6 dated earlier, 2 later
2310.06830 (2023-10)
Lemur: Harmonizing Natural Language and Code for Language Agents
2401.10768 (2024-01)
Knowledge Verification to Nip Hallucination in the Bud
2401.15006 (2024-01)
Airavata: Introducing Hindi Instruction-tuned LLM
and 5 more not named here
create_prompt_with_llama2_chat_format 6 other papers
4 dated earlier, 2 later
2401.08565 (2024-01)
Tuning Language Models by Proxy
2401.10768 (2024-01)
Knowledge Verification to Nip Hallucination in the Bud
2401.16405 (2024-01)
Scaling Sparse Fine-Tuning to Large Language Models
and 3 more not named here
generate_completions 6 other papers
4 dated earlier, 2 later
2310.08491 (2023-10)
Prometheus: Inducing Fine-grained Evaluation Capability in Language Models
2401.10768 (2024-01)
Knowledge Verification to Nip Hallucination in the Bud
2401.15006 (2024-01)
Airavata: Introducing Hindi Instruction-tuned LLM
and 3 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-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) excel in various capabilities but pose safety risks such as generating harmful content and misinformation, even after safety alignment. In this paper, we explore the inner mechanisms of safety alignment through the lens of mechanistic interpretability, focusing on identifying and analyzing safety neurons within LLMs that are responsible for safety behaviors. We propose inference-time activation contrasting to locate these neurons and dynamic activation patching to evaluate their causal effects on model safety. Experiments on multiple prevalent LLMs demonstrate that we can consistently identify about 5% safety neurons, and by only patching their activations we can restore over 90% of the safety performance across various red-teaming benchmarks without influencing general ability. The finding of safety neurons also helps explain the "alignment tax" phenomenon by revealing that the key neurons for model safety and helpfulness significantly overlap, yet they require different activation patterns for the same neurons. Furthermore, we demonstrate an application of our findings in safeguarding LLMs by detecting unsafe outputs before generation. The source code is available at https://github.com/THU-KEG/SafetyNeuron. * indicates equal contribution.

For agents

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

get_harvested_code_for_paper("2406.14144")
get_code_for_paper("2406.14144")
have("2406.14144")

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

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

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

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

Connect an agent — have() is free.