Skip to main content

Reverse Attention Beam Search for tracing attention paths in transformer models

Project description

Reverse Attention Tracer (RAT)

A Python package for tracing attention paths backward through transformer models, with interactive D3.js Sankey visualization.

Features

  • Reverse attention tracing: Trace which tokens most influence a target token by following attention paths backward
  • Beam search: Efficiently explore multiple high-probability paths through the attention matrix
  • Interactive visualization: D3.js-powered Sankey diagrams with zoom, pan, and click-to-highlight
  • Qwen2 support: Optimized for Qwen2 family models (works with other HuggingFace transformers)

Installation

pip install reverse-attention

Or install from source:

git clone https://github.com/ovshake/reverse-attention
cd reverse-attention
pip install -e .

Quick Start

from transformers import AutoModelForCausalLM, AutoTokenizer
from reverse_attention import ReverseAttentionTracer

# Load model and tokenizer
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B")
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B")

# Create tracer
tracer = ReverseAttentionTracer(model, tokenizer)

# Trace attention from the last token
result = tracer.trace_text("The quick brown fox jumps over the lazy dog.")

# Print top attention paths
for i, path in enumerate(result.paths_text):
    print(f"Beam {i+1}: {path}")

# Generate interactive visualization
tracer.render_html(result, "output/", open_browser=True)

API Reference

ReverseAttentionTracer

The main class for tracing attention paths.

tracer = ReverseAttentionTracer(model, tokenizer, device=None, dtype=None)

Parameters

  • model: HuggingFace transformer model
  • tokenizer: Corresponding tokenizer
  • device: Device to run on (defaults to model's device)
  • dtype: Data type for computation (defaults to model's dtype)

trace()

Trace attention paths backward from a target position.

result = tracer.trace(
    input_ids,              # Input token IDs [1, seq_len]
    target_pos=-1,          # Position to trace from (supports negative indexing)
    attention_mask=None,    # Optional attention mask
    layer=-1,               # Layer index (supports negative indexing)
    top_beam=5,             # Number of beams to keep
    top_k=5,                # Top-k predecessors per step
    min_attn=0.0,           # Minimum attention threshold
    agg_heads="mean",       # Head aggregation: "mean", "max", "none"
    length_norm="avg_logprob",  # Score normalization
    stop_at_bos=True,       # Stop at BOS tokens
    bos_token_id=None,      # Override BOS token ID
)

trace_text()

Convenience method that tokenizes text before tracing.

result = tracer.trace_text(
    "Your text here",
    target_pos=-1,
    **kwargs  # Same as trace()
)

render_html()

Generate interactive HTML visualization.

html_path = tracer.render_html(
    result,                 # TraceResult from trace()
    out_dir="output/",      # Output directory
    open_browser=False,     # Open in browser after generation
)

TraceResult

The result object returned by trace():

  • seq_len: Sequence length
  • target_pos: Target position (resolved to positive index)
  • layer: Layer index (resolved to positive index)
  • top_beam: Number of beams used
  • top_k: Top-k value used
  • tokens: List of all tokens in sequence
  • beams: List of BeamPath objects
  • sankey: SankeyData for visualization
  • paths_text: Human-readable path descriptions

BeamPath

A single attention path:

  • positions: Token positions in sequence
  • tokens: Token strings
  • token_ids: Token IDs
  • edge_attns: Attention weights along edges
  • score_raw: Raw cumulative log score
  • score_norm: Length-normalized score

Score Normalization

The length_norm parameter controls how path scores are normalized:

  • "none": No normalization (raw cumulative log probability)
  • "avg_logprob": Divide by path length (geometric mean, default)
  • "sqrt": Divide by sqrt(path length)
  • "pow:α": Divide by path_length^α (e.g., "pow:0.7")

Head Aggregation

The agg_heads parameter controls how attention heads are combined:

  • "mean": Average attention across all heads (default)
  • "max": Maximum attention across heads
  • "none": Keep all heads separate (returns 3D attention tensor)

Example Script

Run the demo script:

python examples/demo_qwen2.py --text "Your text here" --open-browser

Options:

  • --model: Model name or path (default: Qwen/Qwen2-0.5B)
  • --text: Text to trace
  • --target-pos: Target position (default: -1)
  • --layer: Layer index (default: -1)
  • --top-beam: Number of beams (default: 5)
  • --top-k: Top-k predecessors (default: 5)
  • --output: Output directory (default: output)
  • --open-browser: Open visualization in browser
  • --device: Device to use (default: auto)

Visualization Features

The generated HTML visualization includes:

  • Zoom/Pan: Scroll to zoom, drag to pan
  • Click to highlight: Click nodes to highlight connected paths
  • Beam filter: Dropdown to filter by specific beam
  • Info panel: Click elements to see details (position, token, attention weights)
  • Color coding: Beams are color-coded for easy identification

Development

Install dev dependencies:

pip install -e ".[dev]"

Run tests:

pytest tests/ -v

License

MIT License

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

reverse_attention-0.1.0.tar.gz (30.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

reverse_attention-0.1.0-py3-none-any.whl (26.2 kB view details)

Uploaded Python 3

File details

Details for the file reverse_attention-0.1.0.tar.gz.

File metadata

  • Download URL: reverse_attention-0.1.0.tar.gz
  • Upload date:
  • Size: 30.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.12

File hashes

Hashes for reverse_attention-0.1.0.tar.gz
Algorithm Hash digest
SHA256 6ba9ac9dee063d6d27d310146af3a0ed23dd5ae87d2de2414b875762277b0655
MD5 4184b991ea8a5d3a913cd0083b2074e3
BLAKE2b-256 6c0132134e86a46bb3972f10dd8647d4e8be017f355f7387d8786b017a7d7702

See more details on using hashes here.

File details

Details for the file reverse_attention-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for reverse_attention-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 c66186944efe090e8538c1d264445b518eb68098fc4edec4985cd4cb9ea8c04b
MD5 d07794e42e42c291afb7855e41efce9d
BLAKE2b-256 7d71367ac3bd6806edf4613db3e410b54598d6c42aaeec36b728346e61dbf0e8

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page