Tag: llm

Anthropic: Activations to Interpretable features with Monosemanticity

The Anthropic papers “Towards monosemanticity” and “Scaling Monosemanticity: Extracting Interpretable Features from Claude 3 Sonnet” demonstrate how sparse autoencoders can extract interpretable features from large language models, converting polysemantic neuron activations into monosemantic representations that directly map to identifiable concepts and behaviors.​ In this writeup I try to and explain the core concepts in this research.

A sparse autoencoder is a neural network designed to learn a compact, interpretablerepresentation of input data by enforcing sparsity on its hidden layer activations.  A sparse autoencoder is “sparse” because it applies a constraint during training so that, for any given input, only a small subset of the hidden (latent) units is active (nonzero). This is achieved by adding a sparsity penalty to the loss function, commonly L1 regularization or a KL-divergence term, which discourages most activations from deviating much from zero. This ensures the encoded representation is sparse—meaning only a few features are used to reconstruct the input—resulting in greater interpretability and the extraction of meaningful features.​ It is an “autoencoder” because the full model is trained end-to-end to reconstruct its own input. The encoder maps the input data to a latent code, and the decoder maps it back to the reconstruction. The central training objective is to minimize reconstruction error, making the network learn to reproduce its input as closely as possible. The difference from other autoencoder types (e.g., vanilla, denoising, variational) is specifically the addition of the sparsity constraint on the hidden code.

An activation is the output value of a neuron or unit in a neural network layer after applying an activation function to a weighted sum of inputs. Mathematically, for a neuron receiving inputs x1,x2,…,xnx1,x2,…,xn with weights w1,w2,…,wnw1,w2,…,wn, the activation is a=f(w1x1+w2x2+⋯+wnxn+b)a=f(w1x1+w2x2+⋯+wnxn+b), where ff is the activation function (such as ReLU, sigmoid, or tanh) and bb is a bias term.

The idea is to view activations as superpositions of underlying features and to use a neural network to reverse the mapping from the activations to the features. This is peering into the workings of an LLM with another neural network to see what the activations mean.

So in the monosemanticity quest, the activations are seen as a superposition of underlying features. A sparse autoencoder decomposes model activations into interpretable features by expressing each activation vector as a sparse linear combination of learned feature directions. Given an activation vector xjxj, the decomposition is:xj≈b+∑ifi(xj)dixjb+ifi(xj)di where fi(xj)fi(xj) is the activation (magnitude) of feature ii, didi is a unit vector representing the direction of feature ii in activation space, and bb is a bias term. The feature activations are computed by the encoder as fi(x)=ReLU(We(x−bd)+be)ifi(x)=ReLU(We(xbd)+be)i, where WeWe is the encoder weight matrix and bdbd, bebe are pre-encoder and encoder biases. The feature directions are the columns of the decoder weight matrix WdWd. This formulation is dictionary learning: each activation is reconstructed from a sparse set of learned basis vectors scaled by their respective feature activations.

Acts is short for activations in the above figure of a sparse auto encoder functioning from Anthropic. .

Does the SAE look at all the activations or only certain layers ?

Sparse autoencoders are typically trained on activations from specific layers rather than all layers simultaneously. In practice, a separate SAE is trained for each layer or location in the model where one wishes to analyze or intervene on activations.​ In Anthropic’s “Scaling Monosemanticity” paper specifically, the SAE was trained only on activations from the residual stream at the middle layer (halfway through Claude 3 Sonnet). This choice was made for several reasons: the residual stream is smaller than the MLP layer, making training and inference computationally cheaper; focusing on the residual stream mitigates “cross-layer superposition,” which refers to neurons whose activations depend on combinations of information across multiple layers; and the middle layer likely contains more interesting and abstract features compared to early layers (which capture basic patterns) or final layers (which may be too task-specific).

Motivation and Definitions

  • Large language models (LLMs) typically exhibit polysemantic neurons, which activate in response to numerous, often unrelated, concepts, impeding interpretability and safe control.
  • Monosemanticity refers to representations where each learned feature corresponds to a single, easily identifiable concept, thus improving transparency in model operations.
  • Sparse autoencoders (SAEs) are employed to learn dictionary-like decompositions of hidden activations, aiming for each basis vector (feature) to align with a distinct semantic unit rather than mixed signals.

Methods and Techniques

  • The approach uses SAEs to project model activations into higher-dimensional, sparse spaces where individual features become interpretable.
  • Dictionary learning is central: activations from a given layer are encoded by the SAE so that each dictionary element ideally corresponds to a unique concept or pattern.
  • Anthropic scales this method from small, shallow models to large networks by training SAEs on billions of activations from state-of-the-art LLMs (e.g., Claude 3 Sonnet).
  • Modifying feature coefficients within the SAE’s learned space causes proportional, causal shifts in the model’s reconstructed activation, allowing direct steering of outputs at runtime.
  • Feature steering leverages these interpretable directions to alter specific model behaviors (e.g., changing model goals, tone, biases, or inducing controlled errors) by adjusting activation values during inference.

Results and Empirical Findings

  • The method yields dictionaries where a substantial portion of features (by human evaluation, approximately 70%) are monosemantic—associated with singular, nameable concepts such as DNA motifs or language script.
  • Quantitative validation includes human raters agreeing with feature names, decoder-row alignment (cosine similarity > 0.86 between encoder and decoder vectors), and strong compositionality in steering outcomes.
  • Scaling up the size of the SAE dictionary increases the proportion of monosemantic features and the precision of behavioral interventions.
  • Interventions using these features show robust control over model outputs, evidenced by targeted behavioral scores and ability to suppress or augment specific behaviors with tunable steering coefficients.

Conceptual Advances

  • The work empirically supports the superposition hypothesis: raw neurons entangle multiple meanings, but sparse dictionary learning untangles these into separately addressable features.
  • The method demonstrates that high-dimensional, sparsely coded representations can be extracted at scale without significant algorithmic changes, opening new paths for mechanistic interpretability and control tools in LLMs.
  • These advances suggest dictionary learning could, in future, replace large fine-tuning campaigns for behavioral adjustments, increase safety monitoring, and allow new forms of user-customized steering.

Activation Steering and Implications

  • Steering methods operate by selecting, amplifying, or suppressing identified sparse features using signed, tunable coefficients (λλ), with each adjustment reflected directly and causally in output behavior.
  • The process is mathematically tractable because the SAE remains linear; interventions can be analyzed for causal effects and compositional interactions, which is not feasible in the dense activation spaces of standard LLMs.
  • This enables multifaceted interventions and targeted control: steering vectors can increase or decrease model propensities for specific behaviors, factuality, style, or compliance in a transparent manner.

Summary Table: Key Terms

TermDefinition
Polysemantic neuronNeural unit that activates for multiple, unrelated concepts
Monosemantic featureBasis vector representing a single interpretable concept
Sparse autoencoderNeural model learning an overcomplete, interpretable dictionary
Dictionary learningDecomposition of activations into a set of sparse, meaningful vectors
ActivationOutput value of a neuron or unit in a neural network layer after applying an activation function to a weighted sum of inputs
Activation steeringModifying activations using interpretable features to control outputs

This research establishes scalable techniques for extracting and manipulating interpretable features in large LLMs, enabling precise behavioral steering and laying groundwork for safer, more controllable AI deployments.

The sparse autoencoder (SAE) in Anthropic’s “Scaling Monosemanticity” paper was trained at three different scales on activations from Claude 3 Sonnet: approximately 1 million (1,048,576), 4 million (4,194,304), and 34 million (33,554,432) features. For the largest run, the 34M-feature SAE, the number of active (nonzero) features for any given token was typically fewer than 300, showing high sparsity.

The paper emphasizes that many extracted features are relevant to AI safety, such as features for security vulnerabilities, code backdoors, bias (overt and subtle), deception (including power-seeking and treacherous turns), sycophancy, and the generation of dangerous or criminal content. However, the authors note that the detection of such features is preliminary and should not be over-interpreted: knowing about harmful behaviors is distinct from enacting them. The presence of potentially dangerous features suggests the model could represent these concepts internally, warranting deeper investigation. The interpretability gained through the SAE allows for the identification and possible intervention on such features but does not automatically ensure safe model behavior without further work and robust evaluation.

The authors compare their feature-extraction approach to previous interpretability and model-steering methods:

  • Unlike neuron-centric methods, which often yield tangled, polysemantic activations, SAEs learn overcomplete, sparse dictionaries that approximate monosemantic features.
  • Their approach leverages scaling laws to optimize both the number of features and training steps, showing that larger SAEs provide more granular, precise, and interpretable decompositions than smaller or denser models.
  • The SAE-based approach allows for explicit, steerable interventions by clamping or zeroing specific features, something not possible with conventional dense neuron manipulation.
  • The paper positions this technique as extensible, mechanistically transparent, and a foundation for scalable model interpretability—offering capabilities not matched by most prior strategies.

These results highlight that scalable, sparse autoencoders produce directly actionable, interpretable features offering new tools for AI safety and more precise model control compared to traditional neuron or layerwise interpretability approaches.

An argument on the urgency of interpretability: https://www.darioamodei.com/post/the-urgency-of-interpretability

Neel Nanda’s replication of results has a notebook for going deeper. https://www.alignmentforum.org/posts/fKuugaxt2XLTkASkk/open-source-replication-and-commentary-on-anthropic-s

vLLM project – overview, comparisons, PagedAttention mechanism

The vLLM project is an open-source venture designed to enhance the efficiency and scalability of serving Large Language Models (LLMs). Developed by researchers at UC Berkeley, vLLM aims to improve the performance of LLM inference by optimizing memory management and execution. It offers a system that reduces latency and increases throughput for LLMs, making it a valuable tool for deploying these models more effectively in various applications. It supports multiple LLM model types, multiple hardware architectures, and multiple optimization techniques. It is described in this paper, on Efficient LLM serving with PagedAttention.

vLLM achieves its improvements through

  • dynamic batching,
  • efficient memory usage, and
  • parallel execution strategies.

These features allow it to handle multiple requests simultaneously without sacrificing speed or accuracy.

By making LLMs more accessible and efficient, vLLM helps lower the barriers to using advanced AI models, facilitating broader adoption and innovation in the field of natural language processing. For more detailed information or to contribute to the project, you can explore its repository on platforms like GitHub.

vLLM, NVIDIA Triton Inference Server, and NVIDIA NeMo (formerly known as NVIDIA NIM) are all designed to improve the deployment and performance of machine learning models, but they have different focuses and functionalities. Here’s a comparison of each:

vLLM
  • Purpose: Optimizes the serving of Large Language Models (LLMs) with a focus on improving inference efficiency, particularly regarding memory management and execution.
  • Features: Offers dynamic batching, efficient memory usage, and parallel execution strategies specifically for LLMs, enhancing latency and throughput.
  • Use Cases: Best suited for applications requiring fast, efficient LLM inference, such as AI-driven conversational agents.
  • How it reduces memory waste and improves utilization with PagedAttention – https://blog.runpod.io/introduction-to-vllm-and-how-to-run-vllm-on-runpod-serverless/
NVIDIA Triton Inference Server
  • Purpose: A scalable and flexible platform for serving different types of machine learning models across a variety of frameworks and hardware architectures.
  • Features: Supports multiple model frameworks (e.g., TensorFlow, PyTorch, ONNX), dynamic batching, model versioning, and provides both HTTP/REST and gRPC endpoints for inference requests. It is designed to maximize GPU utilization and streamline inference workflows.
  • Use Cases: Ideal for deploying diverse AI models in production environments, allowing for efficient inference at scale across CPUs and GPUs.
NVIDIA NeMo
  • Purpose: A toolkit for building, training, and fine-tuning state-of-the-art conversational AI models, including those for Automatic Speech Recognition (ASR), Natural Language Processing (NLP), and Text-to-Speech (TTS).
  • Features: Provides pre-trained models, model architectures, and training scripts that can be customized and extended for specific tasks. NeMo is designed to facilitate the development of AI models with high accuracy and efficiency.
  • Use Cases: Suitable for developers and researchers focused on building and customizing conversational AI applications, offering extensive support for research and development in speech and language domains.

Comparison summary

  • Optimization Focus: vLLM is specialized for LLM inference optimization, NVIDIA Triton is a general-purpose inference server supporting various models and frameworks, and NVIDIA NeMo is focused on developing and customizing conversational AI models.
  • Hardware and Framework Support: Triton supports a wide range of frameworks and hardware, optimizing inference across diverse environments. NeMo, while capable of leveraging NVIDIA’s hardware optimizations, is more focused on the model training and customization aspect, particularly for conversational AI.
  • Target Audience: vLLM targets developers needing efficient LLM deployment; Triton appeals to teams deploying a variety of models in scalable production settings; NeMo is aimed at researchers and developers building state-of-the-art conversational systems.
Details of vLLM PagedAttention.

What Are Keys and Values in PagedAttention?

In the context of transformer-based Large Language Models (LLMs), keys (K) and values (V) are components of the attention mechanism used during inference.

  • Keys (K): Represent encoded representations of previous tokens, used to determine how much attention each token should pay to previous tokens.
  • Values (V): Contain the actual information used to generate the next token, weighted based on attention scores.

PagedAttention manages these key-value (KV) caches efficiently to store past token embeddings so the model doesn’t have to recompute them in every step, drastically speeding up inference.


Concrete Example: Key-Value Pairs in Action

Let’s take a simple example where an LLM is generating text based on a prompt.

Example Prompt:

User: "The capital of France is"

Tokenized Version (Using Byte-Pair Encoding or SentencePiece):

["The", "capital", "of", "France", "is"]

Each token gets embedded into a high-dimensional space (e.g., 4096 dimensions for LLaMA-2-70B). Let’s assume we use 4096-dimension embeddings for simplicity.

Step-by-Step Key-Value Storage

  1. The model encodes each token and stores:
    • Key (K): A vector that helps determine how relevant this token is in future attention computations.
    • Value (V): The actual contextual representation of the token.
TokenKey (K) (Simplified)Value (V) (Simplified)
“The”[0.1, 0.2, -0.3, ...][0.5, 0.4, -0.1, ...]
“capital”[0.2, 0.3, 0.1, ...][0.6, 0.2, -0.3, ...]
“of”[-0.1, 0.2, 0.7, ...][0.2, 0.1, 0.9, ...]
“France”[0.5, -0.2, 0.1, ...][0.7, 0.3, -0.2, ...]
“is”[0.3, 0.1, 0.4, ...][0.8, 0.2, -0.5, ...]
  1. When generating the next token (“Paris”), the model:
    • Computes attention scores between “Paris” and all previous tokens using dot product of queries (Q) and keys (K).
    • Uses the weighted sum of values (V) to form the new representation.
  2. Instead of recomputing attention from scratch, PagedAttention retrieves precomputed (K, V) values from memory pages for fast lookup.

How PagedAttention Optimizes Key-Value Caching

  • Without PagedAttention: Each request would store KV pairs in one long, contiguous memory buffer. If a request finishes early, the allocated space is wasted.
  • With PagedAttention: KV pairs are stored in small pages (e.g., chunks of 16 tokens), allowing efficient reuse and minimizing fragmentation.

LLM evolution – Anthropic , AI21, Cohere, GPT-4

https://github.com/Mooler0410/LLMsPracticalGuide

Source paper – Harnessing the Power of LLMs in Practice: A Survey on ChatGPT and Beyond

Pink branch is encoder only. Green branch is encoder-decoder. Blue branch is decoder-only.

This is consistent with the Generative aspect of the blue branch. But it does not explain the emergent properties at the top of the blue tree.

LLM leaderboard – https://chat.lmsys.org/?leaderboard

Stanford HELM (holistic evaluation of LMs) – https://crfm.stanford.edu/helm/latest/?models=1

Constitutional AI paper from Anthropic – https://arxiv.org/abs/2212.08073

More on emergent properties in links below.

https://yaofu.notion.site/How-does-GPT-Obtain-its-Ability-Tracing-Emergent-Abilities-of-Language-Models-to-their-Sources-b9a57ac0fcf74f30a1ab9e3e36fa1dc1

https://openai.com/research/solving-math-word-problems : Autoregressive models, which generate each solution token by token, have no mechanism to correct their own errors. Solutions that veer off-course quickly become unrecoverable, as can be seen in the examples provided. We address this problem by training verifiers to evaluate the correctness of model-generated solutions. Verifiers are given many possible solutions, all written by the model itself, and they are trained to decide which ones, if any, are correct.

Language Models are Few-Shot Learners – https://openai.com/research/language-models-are-few-shot-learners

LLM inferencing tools/techniques were discussed here.