SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2310.17230 · 2023

Codebook Features: Sparse and Discrete Interpretability for Neural Networks

arXiv · PDF · Open in the Atlas

Code that ran

9 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; 2 honoured the contract we drafted, 0 violated it and 0 have no contract verdict; 7 failures of our instrument; 2 no recorded run), measured 2026-11-23; repository links from the Papers with Code archive attributed under CC BY-SA, no affiliation; bodies inline only under a permissive licence as GitHub detects it. Not a reproduction of the paper's results.

"Ran" means the function executed on a synthesized input and returned a value. It is not a reproduction of the paper's results. This record, dated, as JSON: /api/ran/2310.17230.json · badge: /api/ran/2310.17230.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
taufeeque9/codebook-features canonical (classifier label)
classifier basis: census
9 ran · 2 no recorded run
FunctionStatusWhere it lives
color_str Ran
ran; our contract draft was wrong, not the code
taufeeque9/codebook-features/codebook_features/utils.py
code served (permissive licence) · get_code("315c612a7005019a")
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
from termcolor import colored

ARGS = {
    's': 'Hello World',
    'html': False,
    'color': 'green'
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
termcolor, 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_tokenizer Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
taufeeque9/codebook-features/codebook_features/train_fsm_model.py
code served (permissive licence) · get_code("e7a3a433b5807b51")
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 GPT2TokenizerFast. 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 json
import pathlib
import tempfile
import torch

# Create a temporary directory for the tokenizer files
temp_dir = tempfile.mkdtemp()

ARGS = {
    'path': temp_dir,
    'vocab_size': 100
}
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 GPT2TokenizerFast — a GPT2TokenizerFast output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a GPT2TokenizerFast 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
features_to_tokens Ran
ran; our contract draft was wrong, not the code
taufeeque9/codebook-features/codebook_features/utils.py
code served (permissive licence) · get_code("e883b9a34464b3db")
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. 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 numpy as np
import torch

torch.manual_seed(0)

# Build cb_acts - a dictionary with codebook activations
# The function indexes it as cb_acts[cb_key], which should be a 3D array
# with shape (batch, spatial_dim, topk_or_codes)
cb_key = "codebook_0"
codebook_ids = np.random.randint(0, 5, size=(2, 3, 4))  # (batch=2, spatial=3, codes=4)
cb_acts = {cb_key: codebook_ids}

# num_codes: the total number of codes in the codebook
num_codes = 5

# code: optional specific code to filter for (None for first branch, int for second)
code = None

# topk: used in the second branch with np.where
topk = 1

ARGS = {
    "cb_key": cb_key,
    "cb_acts": cb_acts,
    "num_codes": num_codes,
    "code": code,
    "topk": topk,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy, torch, tqdm — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type list — a list 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_next_state_probs Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
taufeeque9/codebook-features/codebook_features/fsm_utils.py
code served (permissive licence) · get_code("bc3765261beb68f8")
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 3, 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
import torch.nn.functional as F

torch.manual_seed(0)

# Build a minimal model that satisfies the function's usage
class SimpleModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(4, 8)  # input: 4, output: 8 (vocab_size)
    
    def to_tokens(self, text, prepend_bos=True):
        # Return a simple tensor of token ids
        # batch_size=1, seq_len=3
        tokens = torch.tensor([[1, 2, 3]], dtype=torch.long)
        return tokens
    
    def forward(self, x):
        # x shape: (batch, seq_len) with token ids
        # Return logits of shape (batch, seq_len, vocab_size)
        batch_size = x.shape[0]
        seq_len = x.shape[1]
        logits = torch.randn(batch_size, seq_len, 8)
        return logits
    
    def run_with_hooks(self, x, fwd_hooks=None):
        return self.forward(x)

# Build a minimal FSM
class SimpleFSM:
    def __init__(self):
        self.N = 16  # num_edges * base = 4 * 4
        self.num_edges = 4
        self.representation_base = 4
    
    def traj_to_str(self, traj):
        # Convert trajectory to string representation
        return "state_" + str(traj[0])

# Create instances
model = SimpleModel()
fsm = SimpleFSM()

# Prepare arguments
ARGS = {
    'state': 0,  # single int state
    'model': model,
    'fsm': fsm,
    'fwd_hooks': None,
    'prepend_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 tuple, ndim 3, 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
get_optimizer Ran
ran; our contract draft was wrong, not the code
taufeeque9/codebook-features/codebook_features/train_codebook.py
code served (permissive licence) · get_code("ca5c4697a5c093ec")
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 AdamW. 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)

class MockModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.codebook = nn.Parameter(torch.randn(4, 3))
        self.model_weights = nn.Parameter(torch.randn(5, 2))
    
    def get_codebook_params(self):
        return [self.codebook]
    
    def get_model_params(self):
        return [self.model_weights]

class TrainingArgs:
    def __init__(self, train_model_params=True, learning_rate=0.001, model_lr_factor=0.1, weight_decay=0.01):
        self.train_model_params = train_model_params
        self.learning_rate = learning_rate
        self.model_lr_factor = model_lr_factor
        self.weight_decay = weight_decay

model = MockModel()
training_args = TrainingArgs(train_model_params=True, learning_rate=0.001, model_lr_factor=0.1, weight_decay=0.01)

ARGS = {
    'training_args': training_args,
    'model': model
}
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 AdamW — a AdamW output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a AdamW 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_code_search_cache Ran
ran; our contract draft was wrong, not the code
taufeeque9/codebook-features/codebook_features/code_search_utils.py
code served (permissive licence) · get_code("0baf689e42d326b6")
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 pickle
import numpy as np
import tempfile
import os

# Create a temporary directory for cache files
temp_dir = tempfile.mkdtemp()
cache_base_path = temp_dir + '/'

# Create metrics.npy
metrics_dict = {
    'accuracy': 0.95,
    'precision': 0.92,
    'recall': 0.88,
    'f1': 0.90
}
np.save(cache_base_path + 'metrics.npy', metrics_dict)

# Create cb_acts.pkl
cb_acts = {
    'layer_0': np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]),
    'layer_1': np.array([[0.5, 1.5], [2.5, 3.5], [4.5, 5.5]]),
}
with open(cache_base_path + 'cb_acts.pkl', 'wb') as f:
    pickle.dump(cb_acts, f)

# Create act_count_ft_tkns.pkl
act_count_ft_tkns = {
    'token_counts': np.array([10, 20, 30, 40]),
    'feature_activation': np.array([0.1, 0.2, 0.3, 0.4, 0.5]),
}
with open(cache_base_path + 'act_count_ft_tkns.pkl', 'wb') as f:
    pickle.dump(act_count_ft_tkns, f)

ARGS = {
    'cache_base_path': cache_base_path
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type 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
prepare_logging Ran
ran; our contract draft was wrong, not the code
taufeeque9/codebook-features/codebook_features/train_codebook.py
code served (permissive licence) · get_code("dbc3ad84e8a2ddd9")
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 omegaconf
import pandas as pd
import torch

# Create a minimal config object that omegaconf can work with
cfg_dict = {
    'model_name_or_path': 'bert-base',
    'learning_rate': 0.001,
    'per_device_train_batch_size': 32,
    'codebook_type': 'product',
    'num_codes': 256,
    'num_codebooks': 4,
    'layers_to_snap': [10, 11, 12],
    'similarity_metric': 'cosine',
    'codebook_at': 'encoder',
    'loss': 'mse',
    'train_model_params': True,
    'model_lr_factor': 0.1,
    'k_codebook': 1,
    'dataset_name': 'wikipedia',
    'tags': ['experiment', 'v1'],
    'tag_keys': ['model_name_or_path', 'learning_rate', 'per_device_train_batch_size', 'codebook_type', 'num_codes', 'num_codebooks', 'layers_to_snap', 'similarity_metric', 'codebook_at', 'loss', 'train_model_params', 'model_lr_factor', 'k_codebook', 'dataset_name'],
    'training_args': {
        'run_name': 'initial_run'
    }
}

cfg = omegaconf.OmegaConf.create(cfg_dict)

ARGS = {
    'cfg': cfg
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
omegaconf, pandas, 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
preprocess_logits_for_metrics Ran
ran, honoured the contract we drafted
taufeeque9/codebook-features/codebook_features/run_clm.py
code served (permissive licence) · get_code("d2895bdf14e8f94f")
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 1, dtype family int, shape (2,) 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 checks if logits is a tuple, and if so, extracts the first element
# Then it calls argmax(dim=-1) on the logits tensor
# So we need:
# - logits: either a tensor or a tuple containing a tensor
# - labels: used in function signature but not in the function body

# Create a small logits tensor with shape (batch=2, num_classes=4)
logits_tensor = torch.randn(2, 4)

# Create labels (not used in function but required as parameter)
labels = torch.tensor([0, 1])

# Test with logits as a tensor
ARGS = {
    "logits": logits_tensor,
    "labels": labels
}
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 1, dtype family int, shape (2,) — shape (2,) 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
search_re Ran
ran, honoured the contract we drafted
taufeeque9/codebook-features/codebook_features/code_search_utils.py
code served (permissive licence) · get_code("605b9653cd77b330")
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 2, dtype family int; 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 re

# Construct valid arguments for search_re function
ARGS = {
    're_pattern': r'\b[a-z]+\b',  # Simple regex pattern to search for lowercase words
    'tokens_text': [
        'hello world test example',
        'foo bar baz qux',
        'one two three four five'
    ],
    'at_odd_even': -1  # Default: no limitation on positions
}
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 2, dtype family int — 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
load_dataset_cache Not yet run
unverified (harvested, no recorded run)
taufeeque9/codebook-features/codebook_features/code_search_utils.py
code served (permissive licence) · get_code("4471d92715bb6e40")
How it ran

no invocation recorded.

logits_to_pred Not yet run
unverified (harvested, no recorded run)
taufeeque9/codebook-features/codebook_features/utils.py
code served (permissive licence) · get_code("1c6d09ac6435d64a")
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, 1 are also present in other papers whose code we hold (1 with at least one paper dated earlier, 1 the same month, 1 later) and 10 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
preprocess_logits_for_metrics 7 other papers
2 dated earlier, 1 the same month, 4 later
2010.11934 (2020-10)
mT5: A massively multilingual pre-trained text-to-text transformer
2304.08177 (2023-04)
Efficient and Effective Text Encoding for Chinese LLaMA and Alpaca
2310.09089 (2023-10)
Qilin-Med: Multi-stage Knowledge Injection Advanced Medical Large Language Model
and 4 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

Understanding neural networks is challenging in part because of the dense, continuous nature of their hidden states. We explore whether we can train neural networks to have hidden states that are sparse, discrete, and more interpretable by quantizing their continuous features into what we call codebook features. Codebook features are produced by finetuning neural networks with vector quantization bottlenecks at each layer, producing a network whose hidden features are the sum of a small number of discrete vector codes chosen from a larger codebook. Surprisingly, we find that neural networks can operate under this extreme bottleneck with only modest degradation in performance. This sparse, discrete bottleneck also provides an intuitive way of controlling neural network behavior: first, find codes that activate when the desired behavior is present, then activate those same codes during generation to elicit that behavior. We validate our approach by training codebook Transformers on several different datasets. First, we explore a finite state machine dataset with far more hidden states than neurons. In this setting, our approach overcomes the superposition problem by assigning states to distinct codes, and we find that we can make the neural network behave as if it is in a different state by activating the code for that state. Second, we train Transformer language models with up to 410M parameters on two natural language datasets. We identify codes in these models representing diverse, disentangled concepts (ranging from negative emotions to months of the year) and find that we can guide the model to generate different topics by activating the appropriate codes during inference. Overall, codebook features appear to be a promising unit of analysis and control for neural networks and interpretability. Our codebase and models are open-sourced at https://github.com/taufeeque9/codebook-features.

For agents

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

get_harvested_code_for_paper("2310.17230")
get_code_for_paper("2310.17230")
have("2310.17230")

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

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

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

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

Connect an agent — have() is free.