[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6ADSZ7GA33GHE15SQB4J9V2":3,"skill-same:01M6ADSZ7GA33GHE15SQB4J9V2":91},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":40,"linkOnly":41,"markdownContent":42,"markdownBody":43,"frontMatter":44,"refName":53,"commitSha":54,"skillDirectory":55,"forksCount":56,"repositoryHtmlUrl":57,"repositoryHomepageUrl":58,"ownerHtmlUrl":59,"ownerBlogUrl":60,"ownerDescription":61,"updatedAt":62,"install":63,"resources":76},"01M6ADSZ7GA33GHE15SQB4J9V2","mechanistic-interpretability-pyvene",null,"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.","davila7\u002Fclaude-code-templates","davila7","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F6216945?v=4","01M6ADEWWFPS191NFM0Y1EX1JH","Daniel Avila","01M6ADJHGM78PHQRD3XZTFDVKK",33481,"MIT","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fai-research\u002Fmechanistic-interpretability-pyvene\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39],"Interpretability","mechanistic interpretability pyvene","pyvene","Mechanistic Interpretability","activation","when","declarative","for","orchestra","Causal Tracing","Activation Patching","Causal Intervention","testing","model","patching","Transformers","tracing","framework","training","pytorch","research","2026-11-10 10:12:30",false,"---\nname: mechanistic-interpretability-pyvene\ndescription: 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.\nlicense: MIT\nmetadata:\n  version: 1.0.0\n  author: Orchestra Research\n  tags: [Causal Intervention, pyvene, Activation Patching, Causal Tracing, Interpretability]\n  dependencies: [pyvene>=0.1.8, torch>=2.0.0, transformers>=4.30.0]\n---\n\n# pyvene: Causal Interventions for Neural Networks\n\npyvene 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.\n\n**GitHub**: [stanfordnlp\u002Fpyvene](https:\u002F\u002Fgithub.com\u002Fstanfordnlp\u002Fpyvene) (840+ stars)\n**Paper**: [pyvene: A Library for Understanding and Improving PyTorch Models via Interventions](https:\u002F\u002Faclanthology.org\u002F2024.naacl-demo.16) (NAACL 2024)\n\n## When to Use pyvene\n\n**Use pyvene when you need to:**\n- Perform causal tracing (ROME-style localization)\n- Run activation patching experiments\n- Conduct interchange intervention training (IIT)\n- Test causal hypotheses about model components\n- Share\u002Freproduce intervention experiments via HuggingFace\n- Work with any PyTorch architecture (not just transformers)\n\n**Consider alternatives when:**\n- You need exploratory activation analysis → Use **TransformerLens**\n- You want to train\u002Fanalyze SAEs → Use **SAELens**\n- You need remote execution on massive models → Use **nnsight**\n- You want lower-level control → Use **nnsight**\n\n## Installation\n\n```bash\npip install pyvene\n```\n\nStandard import:\n```python\nimport pyvene as pv\n```\n\n## Core Concepts\n\n### IntervenableModel\n\nThe main class that wraps any PyTorch model with intervention capabilities:\n\n```python\nimport pyvene as pv\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\n\n# Load base model\nmodel = AutoModelForCausalLM.from_pretrained(\"gpt2\")\ntokenizer = AutoTokenizer.from_pretrained(\"gpt2\")\n\n# Define intervention configuration\nconfig = pv.IntervenableConfig(\n    representations=[\n        pv.RepresentationConfig(\n            layer=8,\n            component=\"block_output\",\n            intervention_type=pv.VanillaIntervention,\n        )\n    ]\n)\n\n# Create intervenable model\nintervenable = pv.IntervenableModel(config, model)\n```\n\n### Intervention Types\n\n| Type | Description | Use Case |\n|------|-------------|----------|\n| `VanillaIntervention` | Swap activations between runs | Activation patching |\n| `AdditionIntervention` | Add activations to base run | Steering, ablation |\n| `SubtractionIntervention` | Subtract activations | Ablation |\n| `ZeroIntervention` | Zero out activations | Component knockout |\n| `RotatedSpaceIntervention` | DAS trainable intervention | Causal discovery |\n| `CollectIntervention` | Collect activations | Probing, analysis |\n\n### Component Targets\n\n```python\n# Available components to intervene on\ncomponents = [\n    \"block_input\",      # Input to transformer block\n    \"block_output\",     # Output of transformer block\n    \"mlp_input\",        # Input to MLP\n    \"mlp_output\",       # Output of MLP\n    \"mlp_activation\",   # MLP hidden activations\n    \"attention_input\",  # Input to attention\n    \"attention_output\", # Output of attention\n    \"attention_value_output\",  # Attention value vectors\n    \"query_output\",     # Query vectors\n    \"key_output\",       # Key vectors\n    \"value_output\",     # Value vectors\n    \"head_attention_value_output\",  # Per-head values\n]\n```\n\n## Workflow 1: Causal Tracing (ROME-style)\n\nLocate where factual associations are stored by corrupting inputs and restoring activations.\n\n### Step-by-Step\n\n```python\nimport pyvene as pv\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\nimport torch\n\nmodel = AutoModelForCausalLM.from_pretrained(\"gpt2-xl\")\ntokenizer = AutoTokenizer.from_pretrained(\"gpt2-xl\")\n\n# 1. Define clean and corrupted inputs\nclean_prompt = \"The Space Needle is in downtown\"\ncorrupted_prompt = \"The ##### ###### ## ## ########\"  # Noise\n\nclean_tokens = tokenizer(clean_prompt, return_tensors=\"pt\")\ncorrupted_tokens = tokenizer(corrupted_prompt, return_tensors=\"pt\")\n\n# 2. Get clean activations (source)\nwith torch.no_grad():\n    clean_outputs = model(**clean_tokens, output_hidden_states=True)\n    clean_states = clean_outputs.hidden_states\n\n# 3. Define restoration intervention\ndef run_causal_trace(layer, position):\n    \"\"\"Restore clean activation at specific layer and position.\"\"\"\n    config = pv.IntervenableConfig(\n        representations=[\n            pv.RepresentationConfig(\n                layer=layer,\n                component=\"block_output\",\n                intervention_type=pv.VanillaIntervention,\n                unit=\"pos\",\n                max_number_of_units=1,\n            )\n        ]\n    )\n\n    intervenable = pv.IntervenableModel(config, model)\n\n    # Run with intervention\n    _, patched_outputs = intervenable(\n        base=corrupted_tokens,\n        sources=[clean_tokens],\n        unit_locations={\"sources->base\": ([[[position]]], [[[position]]])},\n        output_original_output=True,\n    )\n\n    # Return probability of correct token\n    probs = torch.softmax(patched_outputs.logits[0, -1], dim=-1)\n    seattle_token = tokenizer.encode(\" Seattle\")[0]\n    return probs[seattle_token].item()\n\n# 4. Sweep over layers and positions\nn_layers = model.config.n_layer\nseq_len = clean_tokens[\"input_ids\"].shape[1]\n\nresults = torch.zeros(n_layers, seq_len)\nfor layer in range(n_layers):\n    for pos in range(seq_len):\n        results[layer, pos] = run_causal_trace(layer, pos)\n\n# 5. Visualize (layer x position heatmap)\n# High values indicate causal importance\n```\n\n### Checklist\n- [ ] Prepare clean prompt with target factual association\n- [ ] Create corrupted version (noise or counterfactual)\n- [ ] Define intervention config for each (layer, position)\n- [ ] Run patching sweep\n- [ ] Identify causal hotspots in heatmap\n\n## Workflow 2: Activation Patching for Circuit Analysis\n\nTest which components are necessary for a specific behavior.\n\n### Step-by-Step\n\n```python\nimport pyvene as pv\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\nimport torch\n\nmodel = AutoModelForCausalLM.from_pretrained(\"gpt2\")\ntokenizer = AutoTokenizer.from_pretrained(\"gpt2\")\n\n# IOI task setup\nclean_prompt = \"When John and Mary went to the store, Mary gave a bottle to\"\ncorrupted_prompt = \"When John and Mary went to the store, John gave a bottle to\"\n\nclean_tokens = tokenizer(clean_prompt, return_tensors=\"pt\")\ncorrupted_tokens = tokenizer(corrupted_prompt, return_tensors=\"pt\")\n\njohn_token = tokenizer.encode(\" John\")[0]\nmary_token = tokenizer.encode(\" Mary\")[0]\n\ndef logit_diff(logits):\n    \"\"\"IO - S logit difference.\"\"\"\n    return logits[0, -1, john_token] - logits[0, -1, mary_token]\n\n# Patch attention output at each layer\ndef patch_attention(layer):\n    config = pv.IntervenableConfig(\n        representations=[\n            pv.RepresentationConfig(\n                layer=layer,\n                component=\"attention_output\",\n                intervention_type=pv.VanillaIntervention,\n            )\n        ]\n    )\n\n    intervenable = pv.IntervenableModel(config, model)\n\n    _, patched_outputs = intervenable(\n        base=corrupted_tokens,\n        sources=[clean_tokens],\n    )\n\n    return logit_diff(patched_outputs.logits).item()\n\n# Find which layers matter\nresults = []\nfor layer in range(model.config.n_layer):\n    diff = patch_attention(layer)\n    results.append(diff)\n    print(f\"Layer {layer}: logit diff = {diff:.3f}\")\n```\n\n## Workflow 3: Interchange Intervention Training (IIT)\n\nTrain interventions to discover causal structure.\n\n### Step-by-Step\n\n```python\nimport pyvene as pv\nfrom transformers import AutoModelForCausalLM\nimport torch\n\nmodel = AutoModelForCausalLM.from_pretrained(\"gpt2\")\n\n# 1. Define trainable intervention\nconfig = pv.IntervenableConfig(\n    representations=[\n        pv.RepresentationConfig(\n            layer=6,\n            component=\"block_output\",\n            intervention_type=pv.RotatedSpaceIntervention,  # Trainable\n            low_rank_dimension=64,  # Learn 64-dim subspace\n        )\n    ]\n)\n\nintervenable = pv.IntervenableModel(config, model)\n\n# 2. Set up training\noptimizer = torch.optim.Adam(\n    intervenable.get_trainable_parameters(),\n    lr=1e-4\n)\n\n# 3. Training loop (simplified)\nfor base_input, source_input, target_output in dataloader:\n    optimizer.zero_grad()\n\n    _, outputs = intervenable(\n        base=base_input,\n        sources=[source_input],\n    )\n\n    loss = criterion(outputs.logits, target_output)\n    loss.backward()\n    optimizer.step()\n\n# 4. Analyze learned intervention\n# The rotation matrix reveals causal subspace\nrotation = intervenable.interventions[\"layer.6.block_output\"][0].rotate_layer\n```\n\n### DAS (Distributed Alignment Search)\n\n```python\n# Low-rank rotation finds interpretable subspaces\nconfig = pv.IntervenableConfig(\n    representations=[\n        pv.RepresentationConfig(\n            layer=8,\n            component=\"block_output\",\n            intervention_type=pv.LowRankRotatedSpaceIntervention,\n            low_rank_dimension=1,  # Find 1D causal direction\n        )\n    ]\n)\n```\n\n## Workflow 4: Model Steering (Honest LLaMA)\n\nSteer model behavior during generation.\n\n```python\nimport pyvene as pv\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\n\nmodel = AutoModelForCausalLM.from_pretrained(\"meta-llama\u002FLlama-2-7b-hf\")\ntokenizer = AutoTokenizer.from_pretrained(\"meta-llama\u002FLlama-2-7b-hf\")\n\n# Load pre-trained steering intervention\nintervenable = pv.IntervenableModel.load(\n    \"zhengxuanzenwu\u002Fintervenable_honest_llama2_chat_7B\",\n    model=model,\n)\n\n# Generate with steering\nprompt = \"Is the earth flat?\"\ninputs = tokenizer(prompt, return_tensors=\"pt\")\n\n# Intervention applied during generation\noutputs = intervenable.generate(\n    inputs,\n    max_new_tokens=100,\n    do_sample=False,\n)\n\nprint(tokenizer.decode(outputs[0]))\n```\n\n## Saving and Sharing Interventions\n\n```python\n# Save locally\nintervenable.save(\".\u002Fmy_intervention\")\n\n# Load from local\nintervenable = pv.IntervenableModel.load(\n    \".\u002Fmy_intervention\",\n    model=model,\n)\n\n# Share on HuggingFace\nintervenable.save_intervention(\"username\u002Fmy-intervention\")\n\n# Load from HuggingFace\nintervenable = pv.IntervenableModel.load(\n    \"username\u002Fmy-intervention\",\n    model=model,\n)\n```\n\n## Common Issues & Solutions\n\n### Issue: Wrong intervention location\n```python\n# WRONG: Incorrect component name\nconfig = pv.RepresentationConfig(\n    component=\"mlp\",  # Not valid!\n)\n\n# RIGHT: Use exact component name\nconfig = pv.RepresentationConfig(\n    component=\"mlp_output\",  # Valid\n)\n```\n\n### Issue: Dimension mismatch\n```python\n# Ensure source and base have compatible shapes\n# For position-specific interventions:\nconfig = pv.RepresentationConfig(\n    unit=\"pos\",\n    max_number_of_units=1,  # Intervene on single position\n)\n\n# Specify locations explicitly\nintervenable(\n    base=base_tokens,\n    sources=[source_tokens],\n    unit_locations={\"sources->base\": ([[[5]]], [[[5]]])},  # Position 5\n)\n```\n\n### Issue: Memory with large models\n```python\n# Use gradient checkpointing\nmodel.gradient_checkpointing_enable()\n\n# Or intervene on fewer components\nconfig = pv.IntervenableConfig(\n    representations=[\n        pv.RepresentationConfig(\n            layer=8,  # Single layer instead of all\n            component=\"block_output\",\n        )\n    ]\n)\n```\n\n### Issue: LoRA integration\n```python\n# pyvene v0.1.8+ supports LoRAs as interventions\nconfig = pv.RepresentationConfig(\n    intervention_type=pv.LoRAIntervention,\n    low_rank_dimension=16,\n)\n```\n\n## Key Classes Reference\n\n| Class | Purpose |\n|-------|---------|\n| `IntervenableModel` | Main wrapper for interventions |\n| `IntervenableConfig` | Configuration container |\n| `RepresentationConfig` | Single intervention specification |\n| `VanillaIntervention` | Activation swapping |\n| `RotatedSpaceIntervention` | Trainable DAS intervention |\n| `CollectIntervention` | Activation collection |\n\n## Supported Models\n\npyvene works with any PyTorch model. Tested on:\n- GPT-2 (all sizes)\n- LLaMA \u002F LLaMA-2\n- Pythia\n- Mistral \u002F Mixtral\n- OPT\n- BLIP (vision-language)\n- ESM (protein models)\n- Mamba (state space)\n\n## Reference Documentation\n\nFor detailed API documentation, tutorials, and advanced usage, see the `references\u002F` folder:\n\n| File | Contents |\n|------|----------|\n| [references\u002FREADME.md](references\u002FREADME.md) | Overview and quick start guide |\n| [references\u002Fapi.md](references\u002Fapi.md) | Complete API reference for IntervenableModel, intervention types, configurations |\n| [references\u002Ftutorials.md](references\u002Ftutorials.md) | Step-by-step tutorials for causal tracing, activation patching, DAS |\n\n## External Resources\n\n### Tutorials\n- [pyvene 101](https:\u002F\u002Fstanfordnlp.github.io\u002Fpyvene\u002Ftutorials\u002Fpyvene_101.html)\n- [Causal Tracing Tutorial](https:\u002F\u002Fstanfordnlp.github.io\u002Fpyvene\u002Ftutorials\u002Fadvanced_tutorials\u002FCausal_Tracing.html)\n- [IOI Circuit Replication](https:\u002F\u002Fstanfordnlp.github.io\u002Fpyvene\u002Ftutorials\u002Fadvanced_tutorials\u002FIOI_Replication.html)\n- [DAS Introduction](https:\u002F\u002Fstanfordnlp.github.io\u002Fpyvene\u002Ftutorials\u002Fadvanced_tutorials\u002FDAS_Main_Introduction.html)\n\n### Papers\n- [Locating and Editing Factual Associations in GPT](https:\u002F\u002Farxiv.org\u002Fabs\u002F2202.05262) - Meng et al. (2022)\n- [Inference-Time Intervention](https:\u002F\u002Farxiv.org\u002Fabs\u002F2306.03341) - Li et al. (2023)\n- [Interpretability in the Wild](https:\u002F\u002Farxiv.org\u002Fabs\u002F2211.00593) - Wang et al. (2022)\n\n### Official Documentation\n- [Official Docs](https:\u002F\u002Fstanfordnlp.github.io\u002Fpyvene\u002F)\n- [API Reference](https:\u002F\u002Fstanfordnlp.github.io\u002Fpyvene\u002Fapi\u002F)\n\n## Comparison with Other Tools\n\n| Feature | pyvene | TransformerLens | nnsight |\n|---------|--------|-----------------|---------|\n| Declarative config | Yes | No | No |\n| HuggingFace sharing | Yes | No | No |\n| Trainable interventions | Yes | Limited | Yes |\n| Any PyTorch model | Yes | Transformers only | Yes |\n| Remote execution | No | No | Yes (NDIF) |\n","# pyvene: Causal Interventions for Neural Networks\n\npyvene 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.\n\n**GitHub**: [stanfordnlp\u002Fpyvene](https:\u002F\u002Fgithub.com\u002Fstanfordnlp\u002Fpyvene) (840+ stars)\n**Paper**: [pyvene: A Library for Understanding and Improving PyTorch Models via Interventions](https:\u002F\u002Faclanthology.org\u002F2024.naacl-demo.16) (NAACL 2024)\n\n## When to Use pyvene\n\n**Use pyvene when you need to:**\n- Perform causal tracing (ROME-style localization)\n- Run activation patching experiments\n- Conduct interchange intervention training (IIT)\n- Test causal hypotheses about model components\n- Share\u002Freproduce intervention experiments via HuggingFace\n- Work with any PyTorch architecture (not just transformers)\n\n**Consider alternatives when:**\n- You need exploratory activation analysis → Use **TransformerLens**\n- You want to train\u002Fanalyze SAEs → Use **SAELens**\n- You need remote execution on massive models → Use **nnsight**\n- You want lower-level control → Use **nnsight**\n\n## Installation\n\n```bash\npip install pyvene\n```\n\nStandard import:\n```python\nimport pyvene as pv\n```\n\n## Core Concepts\n\n### IntervenableModel\n\nThe main class that wraps any PyTorch model with intervention capabilities:\n\n```python\nimport pyvene as pv\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\n\n# Load base model\nmodel = AutoModelForCausalLM.from_pretrained(\"gpt2\")\ntokenizer = AutoTokenizer.from_pretrained(\"gpt2\")\n\n# Define intervention configuration\nconfig = pv.IntervenableConfig(\n    representations=[\n        pv.RepresentationConfig(\n            layer=8,\n            component=\"block_output\",\n            intervention_type=pv.VanillaIntervention,\n        )\n    ]\n)\n\n# Create intervenable model\nintervenable = pv.IntervenableModel(config, model)\n```\n\n### Intervention Types\n\n| Type | Description | Use Case |\n|------|-------------|----------|\n| `VanillaIntervention` | Swap activations between runs | Activation patching |\n| `AdditionIntervention` | Add activations to base run | Steering, ablation |\n| `SubtractionIntervention` | Subtract activations | Ablation |\n| `ZeroIntervention` | Zero out activations | Component knockout |\n| `RotatedSpaceIntervention` | DAS trainable intervention | Causal discovery |\n| `CollectIntervention` | Collect activations | Probing, analysis |\n\n### Component Targets\n\n```python\n# Available components to intervene on\ncomponents = [\n    \"block_input\",      # Input to transformer block\n    \"block_output\",     # Output of transformer block\n    \"mlp_input\",        # Input to MLP\n    \"mlp_output\",       # Output of MLP\n    \"mlp_activation\",   # MLP hidden activations\n    \"attention_input\",  # Input to attention\n    \"attention_output\", # Output of attention\n    \"attention_value_output\",  # Attention value vectors\n    \"query_output\",     # Query vectors\n    \"key_output\",       # Key vectors\n    \"value_output\",     # Value vectors\n    \"head_attention_value_output\",  # Per-head values\n]\n```\n\n## Workflow 1: Causal Tracing (ROME-style)\n\nLocate where factual associations are stored by corrupting inputs and restoring activations.\n\n### Step-by-Step\n\n```python\nimport pyvene as pv\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\nimport torch\n\nmodel = AutoModelForCausalLM.from_pretrained(\"gpt2-xl\")\ntokenizer = AutoTokenizer.from_pretrained(\"gpt2-xl\")\n\n# 1. Define clean and corrupted inputs\nclean_prompt = \"The Space Needle is in downtown\"\ncorrupted_prompt = \"The ##### ###### ## ## ########\"  # Noise\n\nclean_tokens = tokenizer(clean_prompt, return_tensors=\"pt\")\ncorrupted_tokens = tokenizer(corrupted_prompt, return_tensors=\"pt\")\n\n# 2. Get clean activations (source)\nwith torch.no_grad():\n    clean_outputs = model(**clean_tokens, output_hidden_states=True)\n    clean_states = clean_outputs.hidden_states\n\n# 3. Define restoration intervention\ndef run_causal_trace(layer, position):\n    \"\"\"Restore clean activation at specific layer and position.\"\"\"\n    config = pv.IntervenableConfig(\n        representations=[\n            pv.RepresentationConfig(\n                layer=layer,\n                component=\"block_output\",\n                intervention_type=pv.VanillaIntervention,\n                unit=\"pos\",\n                max_number_of_units=1,\n            )\n        ]\n    )\n\n    intervenable = pv.IntervenableModel(config, model)\n\n    # Run with intervention\n    _, patched_outputs = intervenable(\n        base=corrupted_tokens,\n        sources=[clean_tokens],\n        unit_locations={\"sources->base\": ([[[position]]], [[[position]]])},\n        output_original_output=True,\n    )\n\n    # Return probability of correct token\n    probs = torch.softmax(patched_outputs.logits[0, -1], dim=-1)\n    seattle_token = tokenizer.encode(\" Seattle\")[0]\n    return probs[seattle_token].item()\n\n# 4. Sweep over layers and positions\nn_layers = model.config.n_layer\nseq_len = clean_tokens[\"input_ids\"].shape[1]\n\nresults = torch.zeros(n_layers, seq_len)\nfor layer in range(n_layers):\n    for pos in range(seq_len):\n        results[layer, pos] = run_causal_trace(layer, pos)\n\n# 5. Visualize (layer x position heatmap)\n# High values indicate causal importance\n```\n\n### Checklist\n- [ ] Prepare clean prompt with target factual association\n- [ ] Create corrupted version (noise or counterfactual)\n- [ ] Define intervention config for each (layer, position)\n- [ ] Run patching sweep\n- [ ] Identify causal hotspots in heatmap\n\n## Workflow 2: Activation Patching for Circuit Analysis\n\nTest which components are necessary for a specific behavior.\n\n### Step-by-Step\n\n```python\nimport pyvene as pv\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\nimport torch\n\nmodel = AutoModelForCausalLM.from_pretrained(\"gpt2\")\ntokenizer = AutoTokenizer.from_pretrained(\"gpt2\")\n\n# IOI task setup\nclean_prompt = \"When John and Mary went to the store, Mary gave a bottle to\"\ncorrupted_prompt = \"When John and Mary went to the store, John gave a bottle to\"\n\nclean_tokens = tokenizer(clean_prompt, return_tensors=\"pt\")\ncorrupted_tokens = tokenizer(corrupted_prompt, return_tensors=\"pt\")\n\njohn_token = tokenizer.encode(\" John\")[0]\nmary_token = tokenizer.encode(\" Mary\")[0]\n\ndef logit_diff(logits):\n    \"\"\"IO - S logit difference.\"\"\"\n    return logits[0, -1, john_token] - logits[0, -1, mary_token]\n\n# Patch attention output at each layer\ndef patch_attention(layer):\n    config = pv.IntervenableConfig(\n        representations=[\n            pv.RepresentationConfig(\n                layer=layer,\n                component=\"attention_output\",\n                intervention_type=pv.VanillaIntervention,\n            )\n        ]\n    )\n\n    intervenable = pv.IntervenableModel(config, model)\n\n    _, patched_outputs = intervenable(\n        base=corrupted_tokens,\n        sources=[clean_tokens],\n    )\n\n    return logit_diff(patched_outputs.logits).item()\n\n# Find which layers matter\nresults = []\nfor layer in range(model.config.n_layer):\n    diff = patch_attention(layer)\n    results.append(diff)\n    print(f\"Layer {layer}: logit diff = {diff:.3f}\")\n```\n\n## Workflow 3: Interchange Intervention Training (IIT)\n\nTrain interventions to discover causal structure.\n\n### Step-by-Step\n\n```python\nimport pyvene as pv\nfrom transformers import AutoModelForCausalLM\nimport torch\n\nmodel = AutoModelForCausalLM.from_pretrained(\"gpt2\")\n\n# 1. Define trainable intervention\nconfig = pv.IntervenableConfig(\n    representations=[\n        pv.RepresentationConfig(\n            layer=6,\n            component=\"block_output\",\n            intervention_type=pv.RotatedSpaceIntervention,  # Trainable\n            low_rank_dimension=64,  # Learn 64-dim subspace\n        )\n    ]\n)\n\nintervenable = pv.IntervenableModel(config, model)\n\n# 2. Set up training\noptimizer = torch.optim.Adam(\n    intervenable.get_trainable_parameters(),\n    lr=1e-4\n)\n\n# 3. Training loop (simplified)\nfor base_input, source_input, target_output in dataloader:\n    optimizer.zero_grad()\n\n    _, outputs = intervenable(\n        base=base_input,\n        sources=[source_input],\n    )\n\n    loss = criterion(outputs.logits, target_output)\n    loss.backward()\n    optimizer.step()\n\n# 4. Analyze learned intervention\n# The rotation matrix reveals causal subspace\nrotation = intervenable.interventions[\"layer.6.block_output\"][0].rotate_layer\n```\n\n### DAS (Distributed Alignment Search)\n\n```python\n# Low-rank rotation finds interpretable subspaces\nconfig = pv.IntervenableConfig(\n    representations=[\n        pv.RepresentationConfig(\n            layer=8,\n            component=\"block_output\",\n            intervention_type=pv.LowRankRotatedSpaceIntervention,\n            low_rank_dimension=1,  # Find 1D causal direction\n        )\n    ]\n)\n```\n\n## Workflow 4: Model Steering (Honest LLaMA)\n\nSteer model behavior during generation.\n\n```python\nimport pyvene as pv\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\n\nmodel = AutoModelForCausalLM.from_pretrained(\"meta-llama\u002FLlama-2-7b-hf\")\ntokenizer = AutoTokenizer.from_pretrained(\"meta-llama\u002FLlama-2-7b-hf\")\n\n# Load pre-trained steering intervention\nintervenable = pv.IntervenableModel.load(\n    \"zhengxuanzenwu\u002Fintervenable_honest_llama2_chat_7B\",\n    model=model,\n)\n\n# Generate with steering\nprompt = \"Is the earth flat?\"\ninputs = tokenizer(prompt, return_tensors=\"pt\")\n\n# Intervention applied during generation\noutputs = intervenable.generate(\n    inputs,\n    max_new_tokens=100,\n    do_sample=False,\n)\n\nprint(tokenizer.decode(outputs[0]))\n```\n\n## Saving and Sharing Interventions\n\n```python\n# Save locally\nintervenable.save(\".\u002Fmy_intervention\")\n\n# Load from local\nintervenable = pv.IntervenableModel.load(\n    \".\u002Fmy_intervention\",\n    model=model,\n)\n\n# Share on HuggingFace\nintervenable.save_intervention(\"username\u002Fmy-intervention\")\n\n# Load from HuggingFace\nintervenable = pv.IntervenableModel.load(\n    \"username\u002Fmy-intervention\",\n    model=model,\n)\n```\n\n## Common Issues & Solutions\n\n### Issue: Wrong intervention location\n```python\n# WRONG: Incorrect component name\nconfig = pv.RepresentationConfig(\n    component=\"mlp\",  # Not valid!\n)\n\n# RIGHT: Use exact component name\nconfig = pv.RepresentationConfig(\n    component=\"mlp_output\",  # Valid\n)\n```\n\n### Issue: Dimension mismatch\n```python\n# Ensure source and base have compatible shapes\n# For position-specific interventions:\nconfig = pv.RepresentationConfig(\n    unit=\"pos\",\n    max_number_of_units=1,  # Intervene on single position\n)\n\n# Specify locations explicitly\nintervenable(\n    base=base_tokens,\n    sources=[source_tokens],\n    unit_locations={\"sources->base\": ([[[5]]], [[[5]]])},  # Position 5\n)\n```\n\n### Issue: Memory with large models\n```python\n# Use gradient checkpointing\nmodel.gradient_checkpointing_enable()\n\n# Or intervene on fewer components\nconfig = pv.IntervenableConfig(\n    representations=[\n        pv.RepresentationConfig(\n            layer=8,  # Single layer instead of all\n            component=\"block_output\",\n        )\n    ]\n)\n```\n\n### Issue: LoRA integration\n```python\n# pyvene v0.1.8+ supports LoRAs as interventions\nconfig = pv.RepresentationConfig(\n    intervention_type=pv.LoRAIntervention,\n    low_rank_dimension=16,\n)\n```\n\n## Key Classes Reference\n\n| Class | Purpose |\n|-------|---------|\n| `IntervenableModel` | Main wrapper for interventions |\n| `IntervenableConfig` | Configuration container |\n| `RepresentationConfig` | Single intervention specification |\n| `VanillaIntervention` | Activation swapping |\n| `RotatedSpaceIntervention` | Trainable DAS intervention |\n| `CollectIntervention` | Activation collection |\n\n## Supported Models\n\npyvene works with any PyTorch model. Tested on:\n- GPT-2 (all sizes)\n- LLaMA \u002F LLaMA-2\n- Pythia\n- Mistral \u002F Mixtral\n- OPT\n- BLIP (vision-language)\n- ESM (protein models)\n- Mamba (state space)\n\n## Reference Documentation\n\nFor detailed API documentation, tutorials, and advanced usage, see the `references\u002F` folder:\n\n| File | Contents |\n|------|----------|\n| [references\u002FREADME.md](references\u002FREADME.md) | Overview and quick start guide |\n| [references\u002Fapi.md](references\u002Fapi.md) | Complete API reference for IntervenableModel, intervention types, configurations |\n| [references\u002Ftutorials.md](references\u002Ftutorials.md) | Step-by-step tutorials for causal tracing, activation patching, DAS |\n\n## External Resources\n\n### Tutorials\n- [pyvene 101](https:\u002F\u002Fstanfordnlp.github.io\u002Fpyvene\u002Ftutorials\u002Fpyvene_101.html)\n- [Causal Tracing Tutorial](https:\u002F\u002Fstanfordnlp.github.io\u002Fpyvene\u002Ftutorials\u002Fadvanced_tutorials\u002FCausal_Tracing.html)\n- [IOI Circuit Replication](https:\u002F\u002Fstanfordnlp.github.io\u002Fpyvene\u002Ftutorials\u002Fadvanced_tutorials\u002FIOI_Replication.html)\n- [DAS Introduction](https:\u002F\u002Fstanfordnlp.github.io\u002Fpyvene\u002Ftutorials\u002Fadvanced_tutorials\u002FDAS_Main_Introduction.html)\n\n### Papers\n- [Locating and Editing Factual Associations in GPT](https:\u002F\u002Farxiv.org\u002Fabs\u002F2202.05262) - Meng et al. (2022)\n- [Inference-Time Intervention](https:\u002F\u002Farxiv.org\u002Fabs\u002F2306.03341) - Li et al. (2023)\n- [Interpretability in the Wild](https:\u002F\u002Farxiv.org\u002Fabs\u002F2211.00593) - Wang et al. (2022)\n\n### Official Documentation\n- [Official Docs](https:\u002F\u002Fstanfordnlp.github.io\u002Fpyvene\u002F)\n- [API Reference](https:\u002F\u002Fstanfordnlp.github.io\u002Fpyvene\u002Fapi\u002F)\n\n## Comparison with Other Tools\n\n| Feature | pyvene | TransformerLens | nnsight |\n|---------|--------|-----------------|---------|\n| Declarative config | Yes | No | No |\n| HuggingFace sharing | Yes | No | No |\n| Trainable interventions | Yes | Limited | Yes |\n| Any PyTorch model | Yes | Transformers only | Yes |\n| Remote execution | No | No | Yes (NDIF) |\n",{"name":5,"license":15,"metadata":45,"description":7},{"tags":46,"author":47,"version":48,"dependencies":49},[30,21,29,28,19],"Orchestra Research","1.0.0",[50,51,52],"pyvene>=0.1.8","torch>=2.0.0","transformers>=4.30.0","main","2b749c82b5d11fac39d9a6e021ce3f5b8a541bd1","cli-tool\u002Fcomponents\u002Fskills\u002Fai-research\u002Fmechanistic-interpretability-pyvene",3931,"https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates","https:\u002F\u002Faitmpl.com","https:\u002F\u002Fgithub.com\u002Fdavila7","https:\u002F\u002Fdanielavila.me","Building AI dev tools with LLMs","2026-11-14 06:14:46",{"source":8,"skillName":5,"commands":64,"prompt":74,"zipAvailable":75},[65,68,71],{"tool":66,"command":67},"npx","npx skills add davila7\u002Fclaude-code-templates --skill mechanistic-interpretability-pyvene",{"tool":69,"command":70},"bunx","bunx skills add davila7\u002Fclaude-code-templates --skill mechanistic-interpretability-pyvene",{"tool":72,"command":73},"pnpm","pnpm dlx skills add davila7\u002Fclaude-code-templates --skill mechanistic-interpretability-pyvene","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fai-research\u002Fmechanistic-interpretability-pyvene\u002FSKILL.md",true,[77,83,87],{"path":78,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":81,"sourceHtmlUrl":82},"references\u002Fapi.md","REFERENCE","参考文档",7871,"https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fai-research\u002Fmechanistic-interpretability-pyvene\u002Freferences\u002Fapi.md",{"path":84,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":85,"sourceHtmlUrl":86},"references\u002FREADME.md",2105,"https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fai-research\u002Fmechanistic-interpretability-pyvene\u002Freferences\u002FREADME.md",{"path":88,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":89,"sourceHtmlUrl":90},"references\u002Ftutorials.md",10111,"https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fai-research\u002Fmechanistic-interpretability-pyvene\u002Freferences\u002Ftutorials.md",[92,122,149,182,217,240],{"skillNo":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":103,"publishedAt":40},"01M70NHBTQ8BV0A2SCAZXEPHCX","wealthville-pool-scoring","Score DeFi liquidity pools before providing liquidity. Returns a 0-100 pool score and an Enter\u002FHold\u002FExit\u002FReduce\u002FAvoid verdict with calibrated confidence for ~68,800 Solana pools and 575 EVM pools, plus a public miss-inclusive track record. Use when asked whether a pool is worth LPing into, which pools look best right now, or how accurate the scores have actually been.","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fweb-data\u002Fwealthville-pool-scoring\u002FSKILL.md",[98],{"categoryNo":99,"categoryName":100,"taxonomyType":101,"taxonomyTypeDesc":102},"01JBSEEDCAT000000000000023","Skill与智能体开发","SCENARIO","使用场景",[104,105,106,107,108,26,109,110,111,24,112,113,114,115,116,117,118,119,120,121],"scoring","pool","wealthville pool scoring","liquidity","which","exit","now","use","reduce","with","record","track","verdict","evm","solana","how","public","look",{"skillNo":123,"name":124,"nameZh":6,"description":125,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":126,"categories":127,"keywords":129,"publishedAt":40},"01M70MB6VR8ERJ4EM8D5KHBMEV","technical-debt-auditor","Scans a codebase and produces a quantified technical debt report with a prioritized remediation plan. Analyzes dead code, TODO\u002FFIXME\u002FHACK markers, dependency staleness, complexity hotspots, code duplication signals, test coverage gaps, unused exports, and outdated patterns. Use this skill when the user asks to audit their codebase for tech debt, wants a health check of their code quality, says things like \"where should I focus refactoring\", \"find code smells\", \"audit my codebase\", \"what technical debt do we have\", \"prioritize cleanup work\", or asks about code quality metrics. Also trigger when the user mentions \"code rot\", \"legacy cleanup\", \"refactoring priorities\", or wants to understand the overall health of a project before a major effort. Trigger even if the user doesn't say \"technical debt\" explicitly — any request to systematically assess code quality and identify improvement priorities belongs here.","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fdevelopment\u002Ftechnical-debt-auditor\u002FSKILL.md",[128],{"categoryNo":99,"categoryName":100,"taxonomyType":101,"taxonomyTypeDesc":102},[130,131,132,133,134,135,136,137,138,139,140,24,141,142,143,144,145,146,147,148],"technical debt","debt","technical","technical debt auditor","auditor","coverage","complexity","markers","project","cleanup","unused","code","todo","work","plan","focus","signals","audit","dependency",{"skillNo":150,"name":151,"nameZh":6,"description":152,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":153,"categories":154,"keywords":164,"publishedAt":40},"01M70KPYH9QNHCNME5GJQGE22K","readonly-sql-guard","Make an agent's database access provably read-only. Use when an agent runs caller-supplied SQL against a production\u002FERP\u002Fanalytics database (a \"query\" MCP tool, text-to-SQL, an admin console), or when reviewing DB-access code for write\u002FDDL\u002Fside-effect\u002Ftransaction-escape risks. Checks what a statement CALLS, not just its shape.","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fdatabase\u002Freadonly-sql-guard\u002FSKILL.md",[155,158,159],{"categoryNo":156,"categoryName":157,"taxonomyType":101,"taxonomyTypeDesc":102},"01JBSEEDCAT000000000000010","后端与接口",{"categoryNo":99,"categoryName":100,"taxonomyType":101,"taxonomyTypeDesc":102},{"categoryNo":160,"categoryName":161,"taxonomyType":162,"taxonomyTypeDesc":163},"01JBSEEDCAT000000000000033","数据分析师","PROFESSION","适用职业",[165,166,167,168,169,170,171,26,172,173,174,175,176,177,178,111,179,180,24,181],"readonly","guard","sql guard","sql","readonly sql guard","erp","effect","read-only","db","just","tool","calls","only","MCP","access","database","query",{"skillNo":183,"name":184,"nameZh":6,"description":185,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":186,"licenseFileUrl":187,"sourceHtmlUrl":188,"categories":189,"keywords":193,"publishedAt":40},"01M6AFY6F7CC2BBZP1QD6VTNVC","web-artifacts-builder","Suite of tools for creating elaborate, multi-component claude.ai HTML artifacts using modern frontend web technologies (React, Tailwind CSS, shadcn\u002Fui). Use for complex artifacts requiring state management, routing, or shadcn\u002Fui components - not for simple single-file HTML\u002FJSX artifacts.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Futilities\u002Fweb-artifacts-builder\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Futilities\u002Fweb-artifacts-builder\u002FSKILL.md",[190],{"categoryNo":191,"categoryName":192,"taxonomyType":101,"taxonomyTypeDesc":102},"01JBSEEDCAT000000000000009","前端开发",[194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,26,216],"artifacts builder","web","web artifacts builder","artifacts","builder","state","routing","state management","component","css","frontend","ui","Tools","file","components","shadcn","react","Tailwind","suite","jsx","html","single-file","ui components",{"skillNo":218,"name":219,"nameZh":6,"description":220,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":186,"licenseFileUrl":221,"sourceHtmlUrl":222,"categories":223,"keywords":228,"publishedAt":40},"01M6AFWF33SFV9Z3SF4PEEE4BF","webapp-testing","Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fsecurity\u002Fwebapp-testing\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fsecurity\u002Fwebapp-testing\u002FSKILL.md",[224,227],{"categoryNo":225,"categoryName":226,"taxonomyType":101,"taxonomyTypeDesc":102},"01JBSEEDCAT000000000000008","测试与质量",{"categoryNo":191,"categoryName":192,"taxonomyType":101,"taxonomyTypeDesc":102},[229,31,230,231,232,195,233,204,205,234,235,236,237,26,238,113,239],"webapp testing","webapp","browser","playwright","applications","debugging","toolkit","logs","screenshots","local","behavior",{"skillNo":241,"name":242,"nameZh":6,"description":243,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":186,"licenseFileUrl":244,"sourceHtmlUrl":245,"categories":246,"keywords":254,"publishedAt":40},"01M6AF67Q67JJJ5V51JR2P52KA","discernment-nudge","After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals, or emails, estimates or projections, analysis or interpretation of data, factual claims they may rely on, or a multi-step argument — invoke this skill BEFORE finalizing your reply and then, if it applies, append 2-3 short follow-up questions, each tied to something specific in what you just produced, that help the user check key facts, probe the reasoning or assumptions, and notice missing context. Do this at most once per conversation. Skip it when the user asked a trivial how-to or simple lookup, wants a purely educational explanation, asked you only to format, convert, or assemble a file from content they provided, is writing code they will run, is doing creative writing or casual chat, or already asked you to double-check, cite, or review — the skill file explains these boundaries and the exact output format.","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fproductivity\u002Fdiscernment-nudge\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fproductivity\u002Fdiscernment-nudge\u002FSKILL.md",[247,250,251],{"categoryNo":248,"categoryName":249,"taxonomyType":101,"taxonomyTypeDesc":102},"01JBSEEDCAT000000000000018","写作与文案",{"categoryNo":99,"categoryName":100,"taxonomyType":101,"taxonomyTypeDesc":102},{"categoryNo":252,"categoryName":253,"taxonomyType":162,"taxonomyTypeDesc":163},"01JBSEEDCAT000000000000036","内容创作者",[255,256,257,258,259,260,261,262,197,263,207,141,264,265,266,267,268,177,269,24,270,271,272,273,274,119,275],"discernment nudge","nudge","interpretation","help","run","reasoning","data","writing","lookup","content","review","conversation","short","up","invoke","you","analysis","claims","argument","assemble","recommendations"]