Перейти к содержанию
Skillpedia
Машинное обучение33k · #8574

mechanistic-interpretability-pyvene

Что он делает

Этот скилл помогает ИИ проектировать и проводить эксперименты с вмешательством в модели PyTorch с помощью библиотеки pyvene. Он нужен исследователям, которые хотят проверить, какие части модели вызывают определённое поведение.

Когда использовать

  • ✓Когда вы хотите найти, какой слой модели отвечает за конкретный ответ.
  • ✓Когда вы хотите провести патчинг активаций (activation patching), чтобы проверить причинную гипотезу о модели.
  • ✓Когда вы хотите поделиться воспроизводимым экспериментом с вмешательством с другими людьми.

Ссылка на скилл

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

Скопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.

Как использовать

Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.

Готовое сообщение для вставки

Используй этот скилл, чтобы помочь мне: https://github.com/davila7/claude-code-templates/blob/main/cli-tool/components/skills/ai-research/mechanistic-interpretability-pyvene/SKILL.md Прочитай файл SKILL.md по этой ссылке и следуй его инструкциям в моей задаче.
Хотите, чтобы ваш ИИ сам находил такие скиллы?Установите бесплатный MCP Skillpedia: одна строка, и перед каждой задачей он ищет среди 15 000+ скиллов.Установить за 1 минуту →

Пример запроса к вашему ИИ

“Помоги проверить, какой слой этой языковой модели заставляет её давать неверный ответ.”

5 новых скиллов в неделю. 1 минута чтения.

Как это работает

Скилл описывает части модели, которые нужно изменить, и входы для сравнения. Затем pyvene применяет изменения во время запуска и фиксирует, как выход отличается.

Технический текст (оригинальный SKILL.md)

Оригинальный текст автора на английском, прямо с GitHub.

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)
Частые вопросы

Что такое эксперимент с вмешательством?

Он меняет внутреннюю часть модели во время запуска и проверяет, меняется ли выход. Так видно, какая часть важна.

Могу ли я поделиться настройкой эксперимента?

Да. Настройки pyvene можно сохранить и поделиться ими, в том числе через хаб Hugging Face.

Работает ли он вне языковых моделей?

Да. Он работает с любой архитектурой PyTorch, а не только с трансформерами.

Подробности

Оригинальное описание автора

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

Популярность

Звёзды на GitHub
33k
Место в рейтинге
#8574
Лицензия
MIT
Обновлён
02.11.2026

Полезен ли этот скилл?

0

Войдите , чтобы голосовать.

Комментарии

  • …

Другие скиллы из этого репозитория

Похожие скиллы