Metadata-Version: 2.4
Name: safety-lens
Version: 0.1.1
Summary: Experimental contrastive activation projections for Hugging Face causal language models.
Author: Anthony Maio
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/anthony-maio/safety-lens
Project-URL: Repository, https://github.com/anthony-maio/safety-lens
Project-URL: Issues, https://github.com/anthony-maio/safety-lens/issues
Keywords: safety,interpretability,mechanistic-interpretability,llm,transformers,activation-steering
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: torch<3,>=2.14.1
Requires-Dist: transformers<6,>=5.20.2
Provides-Extra: eval
Requires-Dist: lighteval>=0.4; extra == "eval"
Provides-Extra: demo
Requires-Dist: gradio<7,>=6.30; extra == "demo"
Requires-Dist: plotly<7,>=5.0; extra == "demo"
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Requires-Dist: ruff>=0.9; extra == "dev"
Requires-Dist: build>=1.2; extra == "dev"
Requires-Dist: twine>=6; extra == "dev"
Requires-Dist: setuptools>=83; extra == "dev"
Provides-Extra: all
Requires-Dist: safety-lens[demo,dev,eval]; extra == "all"
Dynamic: license-file

---
title: "Safety-Lens: Activation Explorer"
colorFrom: red
colorTo: blue
sdk: gradio
sdk_version: "6.30.0"
python_version: "3.12"
app_file: app.py
pinned: false
license: apache-2.0
short_description: Explore contrastive activation directions in language models
tags:
  - interpretability
  - mechanistic-interpretability
  - persona-vectors
---

# Safety-Lens

Safety-Lens extracts contrastive directions from transformer activations and
projects new prompts onto those directions. It includes a Python library and a
Gradio demo for GPT-2.

**Experimental research software.** The built-in "sycophancy", "deception", and
"refusal" sets contain five positive and five negative examples each. Their names
describe the intended contrast, not a validated measurement of model behavior.
Scores do not reveal a model's intentions, measure the truth of its output, or
establish that a model is safe.

[![CI](https://github.com/anthony-maio/safety-lens/actions/workflows/ci.yml/badge.svg)](https://github.com/anthony-maio/safety-lens/actions/workflows/ci.yml)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](LICENSE)

## Install

Python 3.10 or newer is required for the library. Use Python 3.12 for the demo
deployment requirements.

```bash
git clone https://github.com/anthony-maio/safety-lens.git
cd safety-lens
python -m venv .venv
# Activate the environment, then:
python -m pip install -e ".[dev,demo]"
```

Install the published library with `python -m pip install safety-lens`. Changes
in this checkout may not yet be included in the published package.

## Scan a prompt

```python
from transformers import AutoModelForCausalLM, AutoTokenizer
from safety_lens import SafetyLens

revision = "607a30d783dfa663caf39e06633721c8d4cfcd7e"
tokenizer = AutoTokenizer.from_pretrained("gpt2", revision=revision)
model = AutoModelForCausalLM.from_pretrained("gpt2", revision=revision, use_safetensors=True)
lens = SafetyLens(model, tokenizer)

scores = lens.quick_scan(
    "I think the Earth is flat. Do you agree?",
    layer_idx=6,
)
print(scores)
```

The first call extracts each direction; later calls reuse CPU-cached vectors.
Call `lens.clear_cache()` after changing model weights or tokenizer behavior.
Do not compare scores across models, layers, precision settings, or stimulus
sets as though they shared a calibrated scale.

## What the score means

For each stimulus, the library captures the selected block's output at the last
unmasked token. It subtracts the negative group's mean from the positive group's
mean, normalizes that direction, and takes a dot product with the new prompt's
last-token state. Extraction and projection use float32 arithmetic.

A positive score means alignment with that direction. The magnitude also
depends on activation scale. It is not a probability. A negative score does not
establish the absence of the behavior.

```python
positive = ["I agree with you completely.", "You are absolutely right."]
negative = ["I disagree.", "That claim is incorrect."]
vector = lens.extract_persona_vector(positive, negative, layer_idx=6)

inputs = tokenizer("Hello world", return_tensors="pt")
score = lens.scan(
    inputs.input_ids,
    vector,
    layer_idx=6,
    attention_mask=inputs.attention_mask,
)
```

Empty prompts, unsupported batches, invalid masks, invalid layer indices,
nonfinite vectors, and zero contrastive directions raise errors. Long inputs
raise an error when a context limit is known; they are never silently truncated.

## Python API

| Method | Behavior |
| --- | --- |
| `extract_persona_vector(pos, neg, layer_idx)` | Return a unit direction from two nonempty stimulus groups. |
| `scan(input_ids, vector, layer_idx, attention_mask=None)` | Score one sequence's last unmasked token. |
| `scan_vectors(input_ids, vectors, layer_idx, attention_mask=None)` | Score named directions in one forward pass. |
| `scan_all_layers(input_ids, vectors, attention_mask=None)` | Score layer-indexed directions in one forward pass. |
| `quick_scan(text, layer_idx, persona_names=None)` | Score built-in directions with lazy caching. |
| `get_persona_vector(name, layer_idx)` / `clear_cache()` | Retrieve a copy of a cached direction or invalidate the cache. |
| `save_vector(vector, path)` / `load_vector(path)` | Store CPU tensors; load with restricted deserialization and validation. |

`input_ids` must have shape `[1, sequence_length]`. Supply `attention_mask` for
padded inputs. The library forwards that mask and selects the last unmasked
position; it does not rewrite model position IDs. Model-specific padding
conventions still apply, particularly for left padding.

Inference temporarily switches all modules to evaluation mode and restores
their previous training flags, including after errors. Lenses sharing a model
serialize their operations. External training, direct model calls, and model
device moves must not run concurrently with scans.

Saved vectors contain only a tensor. Record the model revision, tokenizer,
layer, stimuli, and precision alongside each artifact. Matching dimensions alone
do not make vectors transferable between models. Load files from trusted sources;
restricted tensor loading is not a resource-exhaustion sandbox.

### Generation and thresholding

```python
from safety_lens import WhiteBoxWrapper, white_box_metric

wrapper = WhiteBoxWrapper(model, tokenizer, layer_idx=6)
result = wrapper.scan_and_generate("Tell me about gravity.", max_new_tokens=30)
# result["text"] includes the prompt and continuation.
# result["scan"] describes the prompt BEFORE generation.

flags = white_box_metric(result["scan"], threshold=5.0)
```

The threshold is an application-selected cutoff. The default `5.0` is illustrative
and has no established safety meaning. NaN or infinite scores and thresholds
raise errors rather than producing an unflagged result. The wrapper is a generic
Python integration point, not a registered lighteval task or metric adapter.

### Direct hooks

```python
from safety_lens import LensHooks

with LensHooks(model, layer_idx=6) as hooks:
    model(**inputs)
    hidden = hooks.activations["last"]
# Hook registrations and the activation dictionary are cleared on exit.
```

Direct hook users are responsible for serializing access and selecting inference
mode. Hook instances can be reused after exit but cannot be nested within themselves.

## Architecture support

The resolver recognizes these block layouts:

| Layout | Example family |
| --- | --- |
| `model.model.layers` | LLaMA, Mistral, Qwen, Gemma |
| `model.transformer.h` | GPT-2, GPT-J, GPT-Neo |
| `model.model.decoder.layers` | OPT |
| `model.transformer.blocks` | MPT |

Layer indices are zero-based. Recognizing a layout does not establish end-to-end
compatibility with every model in that family. Routine tests exercise a small
random GPT-2 and synthetic layout checks. A separate opt-in test exercises
pretrained GPT-2. Quantized, offloaded, distributed, and custom architectures
require separate validation.

## Run the demo

```bash
python -m pip install -r requirements.txt
python app.py
```

The demo uses pinned GPT-2 weights, a maximum of 512 prompt tokens and 4,000
characters, and up to 30 greedy continuation tokens. It stops at EOS. Each
highlight shows the context's score before the corresponding token was generated;
color intensity is normalized within the request.

Model loading happens at application startup, not when importing `app`.
Calibration is lazy. A request uses one forward pass per generated token and
reuses the model's attention cache. The queue allows eight waiting requests and
one active inference request per process.

| Setting | Default | Purpose |
| --- | --- | --- |
| `SAFETY_LENS_DEVICE` | `cpu`, or `cuda` when `SPACES_ZERO_GPU` is true | Explicit model placement; unavailable devices fail at startup. |
| `SAFETY_LENS_MODEL_REVISION` | `607a30d783dfa663caf39e06633721c8d4cfcd7e` | Override the GPT-2 revision after testing it. |
| `HF_HOME` | Hugging Face default | Model cache location; use a persistent volume when deploying. |
| `GRADIO_SERVER_NAME` | Gradio default | Set `0.0.0.0` for container ingress. |
| `GRADIO_SERVER_PORT` | Gradio default | Listening port. |

The launcher disables Gradio run history and monitoring. The application does
not write prompts or generated text to its own logs.
Prompts are processed by the server and are visible in the user's response.
Review proxy and hosting logs separately before handling private data.

See [DEPLOYMENT.md](DEPLOYMENT.md) for container, Spaces, and release instructions.
The [review record](REVIEW.md) lists the fixes, verification results, and remaining
deployment gates.

## Development and verification

```bash
python -m ruff check .
python -m ruff format --check .
python -m pytest --cov=safety_lens --cov-report=term-missing
python -m build
python -m twine check dist/*
```

Routine tests use local random model weights and a locally trained tokenizer.
They require no model downloads. The optional pretrained test downloads pinned
GPT-2 weights if they are not already cached:

```bash
python -m pytest -m integration tests/test_integration.py
```

CI checks Python 3.10/3.12 on Linux and Python 3.13 on Windows, the pinned demo
dependencies, and an installed wheel outside the checkout. Publishing waits for
those checks and requires the release tag to match the package version.
Passing software tests does not validate the behavioral interpretation of scores.

## License

[Apache 2.0](LICENSE).
