[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6KQBGCY5JRW0FCW0YSWP2EQ":3,"skill-same:01M6KQBGCY5JRW0FCW0YSWP2EQ":86},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":40,"linkOnly":41,"markdownContent":42,"markdownBody":43,"frontMatter":44,"refName":52,"commitSha":53,"skillDirectory":54,"forksCount":13,"repositoryHtmlUrl":55,"repositoryHomepageUrl":6,"ownerHtmlUrl":56,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":57,"install":58,"resources":71},"01M6KQBGCY5JRW0FCW0YSWP2EQ","pyvene-interventions",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.","endman100\u002Fskill-router-nexus","endman100","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F31997019?v=4","01M6KPDX17BYDWW4RRB0TNGGMX","01M6KPDX64Y2QBEWVFG5W5PWPF",0,"MIT","https:\u002F\u002Fgithub.com\u002Fendman100\u002Fskill-router-nexus\u002Fblob\u002Fmain\u002FAI-Research\u002Fpyvene\u002FSKILL.md",[],[18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39],"pyvene interventions","pyvene","activation","when","declarative","for","orchestra","Interpretability","Causal Tracing","Activation Patching","Causal Intervention","testing","models","use","model","patching","Transformers","tracing","framework","training","pytorch","research","2026-11-10 10:12:30",false,"---\nname: pyvene-interventions\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.\nversion: 1.0.0\nauthor: Orchestra Research\nlicense: MIT\ntags: [Causal Intervention, pyvene, Activation Patching, Causal Tracing, Interpretability]\ndependencies: [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,"tags":45,"author":46,"license":14,"version":47,"description":7,"dependencies":48},[28,19,27,26,25],"Orchestra Research","1.0.0",[49,50,51],"pyvene>=0.1.8","torch>=2.0.0","transformers>=4.30.0","main","f19b254e8975d0bfddb394686706106930d7964d","AI-Research\u002Fpyvene","https:\u002F\u002Fgithub.com\u002Fendman100\u002Fskill-router-nexus","https:\u002F\u002Fgithub.com\u002Fendman100","2026-11-11 18:19:10",{"source":8,"skillName":5,"commands":59,"prompt":69,"zipAvailable":70},[60,63,66],{"tool":61,"command":62},"npx","npx skills add endman100\u002Fskill-router-nexus --skill pyvene-interventions",{"tool":64,"command":65},"bunx","bunx skills add endman100\u002Fskill-router-nexus --skill pyvene-interventions",{"tool":67,"command":68},"pnpm","pnpm dlx skills add endman100\u002Fskill-router-nexus --skill pyvene-interventions","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fendman100\u002Fskill-router-nexus\u002Fblob\u002Fmain\u002FAI-Research\u002Fpyvene\u002FSKILL.md",true,[72,78,82],{"path":73,"resourceType":74,"resourceTypeDesc":75,"sizeBytes":76,"sourceHtmlUrl":77},"references\u002Fapi.md","REFERENCE","参考文档",7871,"https:\u002F\u002Fgithub.com\u002Fendman100\u002Fskill-router-nexus\u002Fblob\u002Fmain\u002FAI-Research\u002Fpyvene\u002Freferences\u002Fapi.md",{"path":79,"resourceType":74,"resourceTypeDesc":75,"sizeBytes":80,"sourceHtmlUrl":81},"references\u002FREADME.md",2105,"https:\u002F\u002Fgithub.com\u002Fendman100\u002Fskill-router-nexus\u002Fblob\u002Fmain\u002FAI-Research\u002Fpyvene\u002Freferences\u002FREADME.md",{"path":83,"resourceType":74,"resourceTypeDesc":75,"sizeBytes":84,"sourceHtmlUrl":85},"references\u002Ftutorials.md",10111,"https:\u002F\u002Fgithub.com\u002Fendman100\u002Fskill-router-nexus\u002Fblob\u002Fmain\u002FAI-Research\u002Fpyvene\u002Freferences\u002Ftutorials.md",[87,111,147,169,178,202],{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":91,"sourceHtmlUrl":92,"categories":93,"keywords":99,"publishedAt":40},"01M6MPCT5BXVER8HQZTW3QE9AS","create-master","基于佛教经典文献，生成特定高僧大德的 AI 教学角色","https:\u002F\u002Fgithub.com\u002Fendman100\u002Fskill-router-nexus\u002Fblob\u002Fmain\u002FMetaphysics-and-Spirituality\u002FMaster-skill\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fendman100\u002Fskill-router-nexus\u002Fblob\u002Fmain\u002FMetaphysics-and-Spirituality\u002FMaster-skill\u002FSKILL.md",[94],{"categoryNo":95,"categoryName":96,"taxonomyType":97,"taxonomyTypeDesc":98},"01JBSEEDCAT000000000000039","教师与教育","PROFESSION","适用职业",[100,101,102,103,104,105,106,107,108,109,110],"create master","master","create","生成","true","webfetch","edit","write","read","grep","Bash",{"skillNo":112,"name":113,"nameZh":6,"description":114,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":115,"sourceHtmlUrl":116,"categories":117,"keywords":129,"publishedAt":40},"01M6M43AKE95Y64E1JRXEF5QQ3","writing-dna-skill","从至少 20 篇完整文章中蒸馏可复用的写作 DNA，分析语言、文章结构、选题逻辑、素材策略、认知框架和视觉风格，并生成 Writing-DNA.md；按该 DNA 写作时会读取全部蒸馏产物和 5 篇相关原文。用于中英文作者、账号、品牌或出版物的风格分析与一致性写作。 Distill reusable Writing DNA from at least 20 complete articles for Chinese or English authors, publications, brands, and accounts; use for language, structure, topic logic, source strategy, cognitive-frame, and visual-style analysis.","https:\u002F\u002Fgithub.com\u002Fendman100\u002Fskill-router-nexus\u002Fblob\u002Fmain\u002FWriting-and-Content\u002Fwriting-dna-skill\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fendman100\u002Fskill-router-nexus\u002Fblob\u002Fmain\u002FWriting-and-Content\u002Fwriting-dna-skill\u002FSKILL.md",[118,123,126],{"categoryNo":119,"categoryName":120,"taxonomyType":121,"taxonomyTypeDesc":122},"01JBSEEDCAT000000000000018","写作与文案","SCENARIO","使用场景",{"categoryNo":124,"categoryName":125,"taxonomyType":121,"taxonomyTypeDesc":122},"01JBSEEDCAT000000000000023","Skill与智能体开发",{"categoryNo":127,"categoryName":128,"taxonomyType":97,"taxonomyTypeDesc":98},"01JBSEEDCAT000000000000036","内容创作者",[130,131,132,133,134,135,136,137,138,139,31,140,141,103,142,143,144,23,145,146],"writing dna skill","DNA","writing","strategy","english","logic","visual","structure","chinese","reusable","style","distill","analysis","frame","source","at","complete",{"skillNo":148,"name":149,"nameZh":6,"description":150,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":151,"sourceHtmlUrl":152,"categories":153,"keywords":156,"publishedAt":40},"01M6M428TTCGQ4ME3KY99VN037","stop-slop","Remove AI writing patterns from prose. Use when drafting, editing, or reviewing text to eliminate predictable AI tells.","https:\u002F\u002Fgithub.com\u002Fendman100\u002Fskill-router-nexus\u002Fblob\u002Fmain\u002FWriting-and-Content\u002Fstop-slop\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fendman100\u002Fskill-router-nexus\u002Fblob\u002Fmain\u002FWriting-and-Content\u002Fstop-slop\u002FSKILL.md",[154,155],{"categoryNo":119,"categoryName":120,"taxonomyType":121,"taxonomyTypeDesc":122},{"categoryNo":127,"categoryName":128,"taxonomyType":97,"taxonomyTypeDesc":98},[157,158,159,160,21,161,162,163,164,31,165,166,167,23,168,132],"slop","stop slop","stop","drafting","drafts","https","patterns","prose","remove","editing","text","content",{"skillNo":170,"name":171,"nameZh":6,"description":172,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":173,"sourceHtmlUrl":174,"categories":175,"keywords":176,"publishedAt":40},"01M6M41X0B7EBX42TK435DMGGR","shuorenhua","检查和清理中英文文本里的 AI 套路，适用于“去 AI 味”“说人话”“自然一点”“别像模板”“先标问题”这类改写和审稿需求；按场景控制力度，同时保留事实、术语、语域和责任主体。","https:\u002F\u002Fgithub.com\u002Fendman100\u002Fskill-router-nexus\u002Fblob\u002Fmain\u002FWriting-and-Content\u002Fshuorenhua\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fendman100\u002Fskill-router-nexus\u002Fblob\u002Fmain\u002FWriting-and-Content\u002Fshuorenhua\u002FSKILL.md",[],[171,177],"文本",{"skillNo":179,"name":180,"nameZh":6,"description":181,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":182,"sourceHtmlUrl":183,"categories":184,"keywords":185,"publishedAt":40},"01M6M3ZD12WBEW5KXKDM4N6DFG","naming","Name products, SaaS, brands, open source projects, bots, and apps. Use when the user needs to name something, find a brand name, or pick a product name. Metaphor-driven process that produces memorable, meaningful names and avoids AI slop.","https:\u002F\u002Fgithub.com\u002Fendman100\u002Fskill-router-nexus\u002Fblob\u002Fmain\u002FWriting-and-Content\u002Fnaming-main\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fendman100\u002Fskill-router-nexus\u002Fblob\u002Fmain\u002FWriting-and-Content\u002Fnaming-main\u002FSKILL.md",[],[180,186,187,188,189,190,31,191,108,144,192,193,194,195,110,196,197,198,199,21,200,201,157],"repo","websearch","product name","apps","bots","view","brand","pick","gh","projects","open","saas","open source","product","describe","ai slop",{"skillNo":203,"name":204,"nameZh":6,"description":205,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":206,"sourceHtmlUrl":207,"categories":208,"keywords":210,"publishedAt":40},"01M6M3YVXAFAAWJ7F6JMPFREYE","humanizer-zh","去除文本中的 AI 生成痕迹。适用于编辑或审阅文本，使其听起来更自然、更像人类书写。\n基于维基百科的\"AI 写作特征\"综合指南。检测并修复以下模式：夸大的象征意义、\n宣传性语言、以 -ing 结尾的肤浅分析、模糊的归因、破折号过度使用、三段式法则、\nAI 词汇、否定式排比、过多的连接性短语。","https:\u002F\u002Fgithub.com\u002Fendman100\u002Fskill-router-nexus\u002Fblob\u002Fmain\u002FWriting-and-Content\u002Fhumanizer-zh\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fendman100\u002Fskill-router-nexus\u002Fblob\u002Fmain\u002FWriting-and-Content\u002Fhumanizer-zh\u002FSKILL.md",[209],{"categoryNo":119,"categoryName":120,"taxonomyType":121,"taxonomyTypeDesc":122},[211,212,213,108,107,106,132,103,177,214,157,159],"humanizer","zh","humanizer zh","翻译"]