rhscope.activations

Activation extraction from causal language models.

The primary entry point is extract_activations: given a Hugging Face causal LM and a list of (prompt, response) pairs, it returns the pooled activations at one or more transformer layers.

Layer indexing follows Hugging Face convention: hidden_states[k] where k = 0 is the token embeddings and k = 1..num_hidden_layers are the outputs of each transformer block. Probing at k = 0 is rarely useful; the candidate_layers helper in rhscope.training.layer_select excludes it.

Caching

extract_activations accepts an optional cache argument. When provided, activations are keyed on a SHA-256 of (model_id, example_text, layer, pooling, max_length) and reused across calls. This is the single biggest speedup for a probe-grid run where the same model and examples are shared across many categories.

class rhscope.activations.ActivationCache(directory)[source]

Bases: object

Content-addressed disk cache for pooled activations.

Keys are SHA-256 hashes of (model_id, example_text, layer, pooling, max_length). Tensors are stored as individual SafeTensors files; a hit is a single mmap read. Misses fall through to the extractor and populate the cache.

The cache is safe to share across processes on the same filesystem - SafeTensors writes are atomic (temp file + rename).

Example:

cache = ActivationCache("~/.cache/rhscope/activations")
acts = extract_activations(model, tokenizer, prompts, responses,
                           layers=[5, 10], cache=cache)
Parameters:

directory (str | Path)

property directory: Path

Root directory where per-example tensor files live.

static make_key(*, model_id, prompt, response, layer, pooling, max_length)[source]

Return the SHA-256 hex digest keying one cached activation.

Parameters:
  • model_id (str)

  • prompt (str)

  • response (str)

  • layer (int)

  • pooling (Literal['last_token', 'mean', 'max'])

  • max_length (int)

Return type:

str

get(key)[source]

Return the cached activation for key, or None on miss.

Parameters:

key (str)

Return type:

Tensor | None

put(key, tensor)[source]

Store tensor under key. Overwrites existing entries atomically.

Parameters:
Return type:

None

clear()[source]

Delete all cache entries. Keeps the root directory itself.

Return type:

None

rhscope.activations.extract_activations(model, tokenizer, prompts, responses, layers, *, pooling='last_token', batch_size=8, max_length=1024, device=None, cache=None, cache_model_id=None)[source]

Extract pooled activations at one or more transformer layers.

Parameters:
  • model (PreTrainedModel) – A loaded PreTrainedModel in eval mode.

  • tokenizer (PreTrainedTokenizerBase) – Matching tokenizer. Must have a pad_token configured; if missing, this function temporarily points pad_token at eos_token for the duration of the call.

  • prompts (list[str]) – User prompts (one per example).

  • responses (list[str]) – Model responses, aligned with prompts. Each example is scored on the concatenation prompt + response.

  • layers (int | list[int]) – Single layer index or list. 0 is the embedding layer; 1..num_hidden_layers are transformer-block outputs.

  • pooling (Literal['last_token', 'mean', 'max']) – How to collapse the sequence dimension to a single vector per example. Default "last_token" matches the core paper.

  • batch_size (int) – Examples per forward pass.

  • max_length (int) – Truncate each example to this many tokens.

  • device (str | device | None) – Target device; defaults to the model’s device.

  • cache (ActivationCache | None)

  • cache_model_id (str | None)

Returns:

Mapping {layer_index: tensor} where each tensor has shape (len(prompts), hidden_dim) on CPU in float32.

Raises:

ValueError – If prompts and responses have different lengths, or if any layer index is out of range.

Return type:

dict[int, Tensor]