Chuyển đến nội dung
Skillpedia
Học máy33k · #8574

mechanistic-interpretability-pyvene

Skill này làm gì

Skill này giúp AI của bạn thiết kế và chạy các thí nghiệm can thiệp trên mô hình PyTorch bằng thư viện pyvene. Dành cho nhà nghiên cứu muốn kiểm tra phần nào của mô hình gây ra một hành vi nhất định.

Khi nào nên dùng

  • ✓Khi bạn muốn tìm lớp nào của mô hình chịu trách nhiệm cho một câu trả lời cụ thể.
  • ✓Khi bạn muốn chạy activation patching để kiểm tra một giả thuyết nhân quả về mô hình.
  • ✓Khi bạn muốn chia sẻ một thí nghiệm can thiệp có thể tái lập với người khác.

Liên kết skill

https://github.com/davila7/claude-code-templates/blob/main/cli-tool/components/skills/ai-research/mechanistic-interpretability-pyvene/SKILL.md

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/davila7/claude-code-templates/blob/main/cli-tool/components/skills/ai-research/mechanistic-interpretability-pyvene/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Bạn có thể giúp tôi kiểm tra xem lớp nào của mô hình ngôn ngữ này khiến nó trả lời sai không?”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Skill mô tả các phần mô hình bạn muốn thay đổi và các đầu vào cần so sánh. pyvene sau đó áp dụng thay đổi trong lúc chạy và ghi lại đầu ra khác đi như thế nào.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

pyvene: Causal Interventions for Neural Networks

pyvene is Stanford NLP's library for performing causal interventions on PyTorch models. It provides a declarative, dict-based framework for activation patching, causal tracing, and interchange intervention training - making intervention experiments reproducible and shareable.

GitHub: stanfordnlp/pyvene (840+ stars) Paper: pyvene: A Library for Understanding and Improving PyTorch Models via Interventions (NAACL 2024)

When to Use pyvene

Use pyvene when you need to:

  • Perform causal tracing (ROME-style localization)
  • Run activation patching experiments
  • Conduct interchange intervention training (IIT)
  • Test causal hypotheses about model components
  • Share/reproduce intervention experiments via HuggingFace
  • Work with any PyTorch architecture (not just transformers)

Consider alternatives when:

  • You need exploratory activation analysis → Use TransformerLens
  • You want to train/analyze SAEs → Use SAELens
  • You need remote execution on massive models → Use nnsight
  • You want lower-level control → Use nnsight

Installation

pip install pyvene

Standard import:

import pyvene as pv

Core Concepts

IntervenableModel

The main class that wraps any PyTorch model with intervention capabilities:

import pyvene as pv
from transformers import AutoModelForCausalLM, AutoTokenizer

# Load base model
model = AutoModelForCausalLM.from_pretrained("gpt2")
tokenizer = AutoTokenizer.from_pretrained("gpt2")

# Define intervention configuration
config = pv.IntervenableConfig(
    representations=[
        pv.RepresentationConfig(
            layer=8,
            component="block_output",
            intervention_type=pv.VanillaIntervention,
        )
    ]
)

# Create intervenable model
intervenable = pv.IntervenableModel(config, model)

Intervention Types

Type Description Use Case
VanillaIntervention Swap activations between runs Activation patching
AdditionIntervention Add activations to base run Steering, ablation
SubtractionIntervention Subtract activations Ablation
ZeroIntervention Zero out activations Component knockout
RotatedSpaceIntervention DAS trainable intervention Causal discovery
CollectIntervention Collect activations Probing, analysis

Component Targets

# Available components to intervene on
components = [
    "block_input",      # Input to transformer block
    "block_output",     # Output of transformer block
    "mlp_input",        # Input to MLP
    "mlp_output",       # Output of MLP
    "mlp_activation",   # MLP hidden activations
    "attention_input",  # Input to attention
    "attention_output", # Output of attention
    "attention_value_output",  # Attention value vectors
    "query_output",     # Query vectors
    "key_output",       # Key vectors
    "value_output",     # Value vectors
    "head_attention_value_output",  # Per-head values
]

Workflow 1: Causal Tracing (ROME-style)

Locate where factual associations are stored by corrupting inputs and restoring activations.

Step-by-Step

import pyvene as pv
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

model = AutoModelForCausalLM.from_pretrained("gpt2-xl")
tokenizer = AutoTokenizer.from_pretrained("gpt2-xl")

# 1. Define clean and corrupted inputs
clean_prompt = "The Space Needle is in downtown"
corrupted_prompt = "The ##### ###### ## ## ########"  # Noise

clean_tokens = tokenizer(clean_prompt, return_tensors="pt")
corrupted_tokens = tokenizer(corrupted_prompt, return_tensors="pt")

# 2. Get clean activations (source)
with torch.no_grad():
    clean_outputs = model(**clean_tokens, output_hidden_states=True)
    clean_states = clean_outputs.hidden_states

# 3. Define restoration intervention
def run_causal_trace(layer, position):
    """Restore clean activation at specific layer and position."""
    config = pv.IntervenableConfig(
        representations=[
            pv.RepresentationConfig(
                layer=layer,
                component="block_output",
                intervention_type=pv.VanillaIntervention,
                unit="pos",
                max_number_of_units=1,
            )
        ]
    )

    intervenable = pv.IntervenableModel(config, model)
Câu hỏi thường gặp

Thí nghiệm can thiệp là gì?

Đó là việc thay đổi một phần bên trong mô hình trong lúc chạy, rồi kiểm tra xem đầu ra có thay đổi không. Nhờ vậy bạn biết phần nào thực sự quan trọng.

Tôi có chia sẻ được cấu hình thí nghiệm không?

Có. Cấu hình pyvene có thể được lưu và chia sẻ, kể cả qua Hugging Face hub.

Nó có chạy được với mô hình không phải ngôn ngữ không?

Có. Nó hoạt động với mọi kiến trúc PyTorch, không chỉ transformer.

Chi tiết

Mô tả gốc của tác giả

Provides guidance for performing causal interventions on PyTorch models using pyvene's declarative intervention framework. Use when conducting causal tracing, activation patching, interchange intervention training, or testing causal hypotheses about model behavior.

repo: davila7/claude-code-templates

Độ phổ biến

Sao GitHub
33k
Vị trí xếp hạng
#8574
Giấy phép
MIT
Cập nhật
2/11/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự