[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7FCCN60JBJY9QF8TV998Z4M":3,"skill-same:01M7FCCN60JBJY9QF8TV998Z4M":71},{"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":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":35,"commitSha":36,"skillDirectory":37,"forksCount":38,"repositoryHtmlUrl":39,"repositoryHomepageUrl":6,"ownerHtmlUrl":40,"ownerBlogUrl":6,"ownerDescription":41,"updatedAt":42,"install":43,"resources":56},"01M7FCCN60JBJY9QF8TV998Z4M","nnsight-remote-interpretability",null,"Provides guidance for interpreting and manipulating neural network internals using nnsight with optional NDIF remote execution. Use when needing to run interpretability experiments on massive models (70B+) without local GPU resources, or when working with any PyTorch architecture.","CZX-LBJ\u002Fdeepseek-science","CZX-LBJ","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F204594689?v=4","01M7FC59WQ9PFXT04MKGJDCFFT","czx","01M7FC59XB2GW0BKWN9JTDBQS7",1,"MIT","https:\u002F\u002Fgithub.com\u002FCZX-LBJ\u002Fdeepseek-science\u002Fblob\u002Fmain\u002Fpackages\u002Fskill\u002Fskill-science\u002Fassets\u002Fsources\u002Fai-research-skills\u002F04-mechanistic-interpretability\u002Fnnsight\u002FSKILL.md",[],[],"2026-11-16 10:05:34",false,"---\nname: nnsight-remote-interpretability\ndescription: Provides guidance for interpreting and manipulating neural network internals using nnsight with optional NDIF remote execution. Use when needing to run interpretability experiments on massive models (70B+) without local GPU resources, or when working with any PyTorch architecture.\nversion: 1.0.0\nauthor: Orchestra Research\nlicense: MIT\ntags: [nnsight, NDIF, Remote Execution, Mechanistic Interpretability, Model Internals]\ndependencies: [nnsight>=0.5.0, torch>=2.0.0]\n---\n\n# nnsight: Transparent Access to Neural Network Internals\n\nnnsight (\u002Fɛn.saɪt\u002F) enables researchers to interpret and manipulate the internals of any PyTorch model, with the unique capability of running the same code locally on small models or remotely on massive models (70B+) via NDIF.\n\n**GitHub**: [ndif-team\u002Fnnsight](https:\u002F\u002Fgithub.com\u002Fndif-team\u002Fnnsight) (730+ stars)\n**Paper**: [NNsight and NDIF: Democratizing Access to Foundation Model Internals](https:\u002F\u002Farxiv.org\u002Fabs\u002F2407.14561) (ICLR 2025)\n\n## Key Value Proposition\n\n**Write once, run anywhere**: The same interpretability code works on GPT-2 locally or Llama-3.1-405B remotely. Just toggle `remote=True`.\n\n```python\n# Local execution (small model)\nwith model.trace(\"Hello world\"):\n    hidden = model.transformer.h[5].output[0].save()\n\n# Remote execution (massive model) - same code!\nwith model.trace(\"Hello world\", remote=True):\n    hidden = model.model.layers[40].output[0].save()\n```\n\n## When to Use nnsight\n\n**Use nnsight when you need to:**\n- Run interpretability experiments on models too large for local GPUs (70B, 405B)\n- Work with any PyTorch architecture (transformers, Mamba, custom models)\n- Perform multi-token generation interventions\n- Share activations between different prompts\n- Access full model internals without reimplementation\n\n**Consider alternatives when:**\n- You want consistent API across models → Use **TransformerLens**\n- You need declarative, shareable interventions → Use **pyvene**\n- You're training SAEs → Use **SAELens**\n- You only work with small models locally → **TransformerLens** may be simpler\n\n## Installation\n\n```bash\n# Basic installation\npip install nnsight\n\n# For vLLM support\npip install \"nnsight[vllm]\"\n```\n\nFor remote NDIF execution, sign up at [login.ndif.us](https:\u002F\u002Flogin.ndif.us) for an API key.\n\n## Core Concepts\n\n### LanguageModel Wrapper\n\n```python\nfrom nnsight import LanguageModel\n\n# Load model (uses HuggingFace under the hood)\nmodel = LanguageModel(\"openai-community\u002Fgpt2\", device_map=\"auto\")\n\n# For larger models\nmodel = LanguageModel(\"meta-llama\u002FLlama-3.1-8B\", device_map=\"auto\")\n```\n\n### Tracing Context\n\nThe `trace` context manager enables deferred execution - operations are collected into a computation graph:\n\n```python\nfrom nnsight import LanguageModel\n\nmodel = LanguageModel(\"gpt2\", device_map=\"auto\")\n\nwith model.trace(\"The Eiffel Tower is in\") as tracer:\n    # Access any module's output\n    hidden_states = model.transformer.h[5].output[0].save()\n\n    # Access attention patterns\n    attn = model.transformer.h[5].attn.attn_dropout.input[0][0].save()\n\n    # Modify activations\n    model.transformer.h[8].output[0][:] = 0  # Zero out layer 8\n\n    # Get final output\n    logits = model.output.save()\n\n# After context exits, access saved values\nprint(hidden_states.shape)  # [batch, seq, hidden]\n```\n\n### Proxy Objects\n\nInside `trace`, module accesses return Proxy objects that record operations:\n\n```python\nwith model.trace(\"Hello\"):\n    # These are all Proxy objects - operations are deferred\n    h5_out = model.transformer.h[5].output[0]  # Proxy\n    h5_mean = h5_out.mean(dim=-1)              # Proxy\n    h5_saved = h5_mean.save()                   # Save for later access\n```\n\n## Workflow 1: Activation Analysis\n\n### Step-by-Step\n\n```python\nfrom nnsight import LanguageModel\nimport torch\n\nmodel = LanguageModel(\"gpt2\", device_map=\"auto\")\n\nprompt = \"The capital of France is\"\n\nwith model.trace(prompt) as tracer:\n    # 1. Collect activations from multiple layers\n    layer_outputs = []\n    for i in range(12):  # GPT-2 has 12 layers\n        layer_out = model.transformer.h[i].output[0].save()\n        layer_outputs.append(layer_out)\n\n    # 2. Get attention patterns\n    attn_patterns = []\n    for i in range(12):\n        # Access attention weights (after softmax)\n        attn = model.transformer.h[i].attn.attn_dropout.input[0][0].save()\n        attn_patterns.append(attn)\n\n    # 3. Get final logits\n    logits = model.output.save()\n\n# 4. Analyze outside context\nfor i, layer_out in enumerate(layer_outputs):\n    print(f\"Layer {i} output shape: {layer_out.shape}\")\n    print(f\"Layer {i} norm: {layer_out.norm().item():.3f}\")\n\n# 5. Find top predictions\nprobs = torch.softmax(logits[0, -1], dim=-1)\ntop_tokens = probs.topk(5)\nfor token, prob in zip(top_tokens.indices, top_tokens.values):\n    print(f\"{model.tokenizer.decode(token)}: {prob.item():.3f}\")\n```\n\n### Checklist\n- [ ] Load model with LanguageModel wrapper\n- [ ] Use trace context for operations\n- [ ] Call `.save()` on values you need after context\n- [ ] Access saved values outside context\n- [ ] Use `.shape`, `.norm()`, etc. for analysis\n\n## Workflow 2: Activation Patching\n\n### Step-by-Step\n\n```python\nfrom nnsight import LanguageModel\nimport torch\n\nmodel = LanguageModel(\"gpt2\", device_map=\"auto\")\n\nclean_prompt = \"The Eiffel Tower is in\"\ncorrupted_prompt = \"The Colosseum is in\"\n\n# 1. Get clean activations\nwith model.trace(clean_prompt) as tracer:\n    clean_hidden = model.transformer.h[8].output[0].save()\n\n# 2. Patch clean into corrupted run\nwith model.trace(corrupted_prompt) as tracer:\n    # Replace layer 8 output with clean activations\n    model.transformer.h[8].output[0][:] = clean_hidden\n\n    patched_logits = model.output.save()\n\n# 3. Compare predictions\nparis_token = model.tokenizer.encode(\" Paris\")[0]\nrome_token = model.tokenizer.encode(\" Rome\")[0]\n\npatched_probs = torch.softmax(patched_logits[0, -1], dim=-1)\nprint(f\"Paris prob: {patched_probs[paris_token].item():.3f}\")\nprint(f\"Rome prob: {patched_probs[rome_token].item():.3f}\")\n```\n\n### Systematic Patching Sweep\n\n```python\ndef patch_layer_position(layer, position, clean_cache, corrupted_prompt):\n    \"\"\"Patch single layer\u002Fposition from clean to corrupted.\"\"\"\n    with model.trace(corrupted_prompt) as tracer:\n        # Get current activation\n        current = model.transformer.h[layer].output[0]\n\n        # Patch only specific position\n        current[:, position, :] = clean_cache[layer][:, position, :]\n\n        logits = model.output.save()\n\n    return logits\n\n# Sweep over all layers and positions\nresults = torch.zeros(12, seq_len)\nfor layer in range(12):\n    for pos in range(seq_len):\n        logits = patch_layer_position(layer, pos, clean_hidden, corrupted)\n        results[layer, pos] = compute_metric(logits)\n```\n\n## Workflow 3: Remote Execution with NDIF\n\nRun the same experiments on massive models without local GPUs.\n\n### Step-by-Step\n\n```python\nfrom nnsight import LanguageModel\n\n# 1. Load large model (will run remotely)\nmodel = LanguageModel(\"meta-llama\u002FLlama-3.1-70B\")\n\n# 2. Same code, just add remote=True\nwith model.trace(\"The meaning of life is\", remote=True) as tracer:\n    # Access internals of 70B model!\n    layer_40_out = model.model.layers[40].output[0].save()\n    logits = model.output.save()\n\n# 3. Results returned from NDIF\nprint(f\"Layer 40 shape: {layer_40_out.shape}\")\n\n# 4. Generation with interventions\nwith model.trace(remote=True) as tracer:\n    with tracer.invoke(\"What is 2+2?\"):\n        # Intervene during generation\n        model.model.layers[20].output[0][:, -1, :] *= 1.5\n\n    output = model.generate(max_new_tokens=50)\n```\n\n### NDIF Setup\n\n1. Sign up at [login.ndif.us](https:\u002F\u002Flogin.ndif.us)\n2. Get API key\n3. Set environment variable or pass to nnsight:\n\n```python\nimport os\nos.environ[\"NDIF_API_KEY\"] = \"your_key\"\n\n# Or configure directly\nfrom nnsight import CONFIG\nCONFIG.API_KEY = \"your_key\"\n```\n\n### Available Models on NDIF\n\n- Llama-3.1-8B, 70B, 405B\n- DeepSeek-R1 models\n- Various open-weight models (check [ndif.us](https:\u002F\u002Fndif.us) for current list)\n\n## Workflow 4: Cross-Prompt Activation Sharing\n\nShare activations between different inputs in a single trace.\n\n```python\nfrom nnsight import LanguageModel\n\nmodel = LanguageModel(\"gpt2\", device_map=\"auto\")\n\nwith model.trace() as tracer:\n    # First prompt\n    with tracer.invoke(\"The cat sat on the\"):\n        cat_hidden = model.transformer.h[6].output[0].save()\n\n    # Second prompt - inject cat's activations\n    with tracer.invoke(\"The dog ran through the\"):\n        # Replace with cat's activations at layer 6\n        model.transformer.h[6].output[0][:] = cat_hidden\n        dog_with_cat = model.output.save()\n\n# The dog prompt now has cat's internal representations\n```\n\n## Workflow 5: Gradient-Based Analysis\n\nAccess gradients during backward pass.\n\n```python\nfrom nnsight import LanguageModel\nimport torch\n\nmodel = LanguageModel(\"gpt2\", device_map=\"auto\")\n\nwith model.trace(\"The quick brown fox\") as tracer:\n    # Save activations and enable gradient\n    hidden = model.transformer.h[5].output[0].save()\n    hidden.retain_grad()\n\n    logits = model.output\n\n    # Compute loss on specific token\n    target_token = model.tokenizer.encode(\" jumps\")[0]\n    loss = -logits[0, -1, target_token]\n\n    # Backward pass\n    loss.backward()\n\n# Access gradients\ngrad = hidden.grad\nprint(f\"Gradient shape: {grad.shape}\")\nprint(f\"Gradient norm: {grad.norm().item():.3f}\")\n```\n\n**Note**: Gradient access not supported for vLLM or remote execution.\n\n## Common Issues & Solutions\n\n### Issue: Module path differs between models\n```python\n# GPT-2 structure\nmodel.transformer.h[5].output[0]\n\n# LLaMA structure\nmodel.model.layers[5].output[0]\n\n# Solution: Check model structure\nprint(model._model)  # See actual module names\n```\n\n### Issue: Forgetting to save\n```python\n# WRONG: Value not accessible outside trace\nwith model.trace(\"Hello\"):\n    hidden = model.transformer.h[5].output[0]  # Not saved!\n\nprint(hidden)  # Error or wrong value\n\n# RIGHT: Call .save()\nwith model.trace(\"Hello\"):\n    hidden = model.transformer.h[5].output[0].save()\n\nprint(hidden)  # Works!\n```\n\n### Issue: Remote timeout\n```python\n# For long operations, increase timeout\nwith model.trace(\"prompt\", remote=True, timeout=300) as tracer:\n    # Long operation...\n```\n\n### Issue: Memory with many saved activations\n```python\n# Only save what you need\nwith model.trace(\"prompt\"):\n    # Don't save everything\n    for i in range(100):\n        model.transformer.h[i].output[0].save()  # Memory heavy!\n\n    # Better: save specific layers\n    key_layers = [0, 5, 11]\n    for i in key_layers:\n        model.transformer.h[i].output[0].save()\n```\n\n### Issue: vLLM gradient limitation\n```python\n# vLLM doesn't support gradients\n# Use standard execution for gradient analysis\nmodel = LanguageModel(\"gpt2\", device_map=\"auto\")  # Not vLLM\n```\n\n## Key API Reference\n\n| Method\u002FProperty | Purpose |\n|-----------------|---------|\n| `model.trace(prompt, remote=False)` | Start tracing context |\n| `proxy.save()` | Save value for access after trace |\n| `proxy[:]` | Slice\u002Findex proxy (assignment patches) |\n| `tracer.invoke(prompt)` | Add prompt within trace |\n| `model.generate(...)` | Generate with interventions |\n| `model.output` | Final model output logits |\n| `model._model` | Underlying HuggingFace model |\n\n## Comparison with Other Tools\n\n| Feature | nnsight | TransformerLens | pyvene |\n|---------|---------|-----------------|--------|\n| Any architecture | Yes | Transformers only | Yes |\n| Remote execution | Yes (NDIF) | No | No |\n| Consistent API | No | Yes | Yes |\n| Deferred execution | Yes | No | No |\n| HuggingFace native | Yes | Reimplemented | Yes |\n| Shareable configs | No | No | Yes |\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 LanguageModel, tracing, proxy objects |\n| [references\u002Ftutorials.md](references\u002Ftutorials.md) | Step-by-step tutorials for local and remote interpretability |\n\n## External Resources\n\n### Tutorials\n- [Getting Started](https:\u002F\u002Fnnsight.net\u002Fstart\u002F)\n- [Features Overview](https:\u002F\u002Fnnsight.net\u002Ffeatures\u002F)\n- [Remote Execution](https:\u002F\u002Fnnsight.net\u002Fnotebooks\u002Ffeatures\u002Fremote_execution\u002F)\n- [Applied Tutorials](https:\u002F\u002Fnnsight.net\u002Fapplied_tutorials\u002F)\n\n### Official Documentation\n- [Official Docs](https:\u002F\u002Fnnsight.net\u002Fdocumentation\u002F)\n- [NDIF Info](https:\u002F\u002Fndif.us\u002F)\n- [Community Forum](https:\u002F\u002Fdiscuss.ndif.us\u002F)\n\n### Papers\n- [NNsight and NDIF Paper](https:\u002F\u002Farxiv.org\u002Fabs\u002F2407.14561) - Fiotto-Kaufman et al. (ICLR 2025)\n\n## Architecture Support\n\nnnsight works with any PyTorch model:\n- **Transformers**: GPT-2, LLaMA, Mistral, etc.\n- **State Space Models**: Mamba\n- **Vision Models**: ViT, CLIP\n- **Custom architectures**: Any nn.Module\n\nThe key is knowing the module structure to access the right components.\n","# nnsight: Transparent Access to Neural Network Internals\n\nnnsight (\u002Fɛn.saɪt\u002F) enables researchers to interpret and manipulate the internals of any PyTorch model, with the unique capability of running the same code locally on small models or remotely on massive models (70B+) via NDIF.\n\n**GitHub**: [ndif-team\u002Fnnsight](https:\u002F\u002Fgithub.com\u002Fndif-team\u002Fnnsight) (730+ stars)\n**Paper**: [NNsight and NDIF: Democratizing Access to Foundation Model Internals](https:\u002F\u002Farxiv.org\u002Fabs\u002F2407.14561) (ICLR 2025)\n\n## Key Value Proposition\n\n**Write once, run anywhere**: The same interpretability code works on GPT-2 locally or Llama-3.1-405B remotely. Just toggle `remote=True`.\n\n```python\n# Local execution (small model)\nwith model.trace(\"Hello world\"):\n    hidden = model.transformer.h[5].output[0].save()\n\n# Remote execution (massive model) - same code!\nwith model.trace(\"Hello world\", remote=True):\n    hidden = model.model.layers[40].output[0].save()\n```\n\n## When to Use nnsight\n\n**Use nnsight when you need to:**\n- Run interpretability experiments on models too large for local GPUs (70B, 405B)\n- Work with any PyTorch architecture (transformers, Mamba, custom models)\n- Perform multi-token generation interventions\n- Share activations between different prompts\n- Access full model internals without reimplementation\n\n**Consider alternatives when:**\n- You want consistent API across models → Use **TransformerLens**\n- You need declarative, shareable interventions → Use **pyvene**\n- You're training SAEs → Use **SAELens**\n- You only work with small models locally → **TransformerLens** may be simpler\n\n## Installation\n\n```bash\n# Basic installation\npip install nnsight\n\n# For vLLM support\npip install \"nnsight[vllm]\"\n```\n\nFor remote NDIF execution, sign up at [login.ndif.us](https:\u002F\u002Flogin.ndif.us) for an API key.\n\n## Core Concepts\n\n### LanguageModel Wrapper\n\n```python\nfrom nnsight import LanguageModel\n\n# Load model (uses HuggingFace under the hood)\nmodel = LanguageModel(\"openai-community\u002Fgpt2\", device_map=\"auto\")\n\n# For larger models\nmodel = LanguageModel(\"meta-llama\u002FLlama-3.1-8B\", device_map=\"auto\")\n```\n\n### Tracing Context\n\nThe `trace` context manager enables deferred execution - operations are collected into a computation graph:\n\n```python\nfrom nnsight import LanguageModel\n\nmodel = LanguageModel(\"gpt2\", device_map=\"auto\")\n\nwith model.trace(\"The Eiffel Tower is in\") as tracer:\n    # Access any module's output\n    hidden_states = model.transformer.h[5].output[0].save()\n\n    # Access attention patterns\n    attn = model.transformer.h[5].attn.attn_dropout.input[0][0].save()\n\n    # Modify activations\n    model.transformer.h[8].output[0][:] = 0  # Zero out layer 8\n\n    # Get final output\n    logits = model.output.save()\n\n# After context exits, access saved values\nprint(hidden_states.shape)  # [batch, seq, hidden]\n```\n\n### Proxy Objects\n\nInside `trace`, module accesses return Proxy objects that record operations:\n\n```python\nwith model.trace(\"Hello\"):\n    # These are all Proxy objects - operations are deferred\n    h5_out = model.transformer.h[5].output[0]  # Proxy\n    h5_mean = h5_out.mean(dim=-1)              # Proxy\n    h5_saved = h5_mean.save()                   # Save for later access\n```\n\n## Workflow 1: Activation Analysis\n\n### Step-by-Step\n\n```python\nfrom nnsight import LanguageModel\nimport torch\n\nmodel = LanguageModel(\"gpt2\", device_map=\"auto\")\n\nprompt = \"The capital of France is\"\n\nwith model.trace(prompt) as tracer:\n    # 1. Collect activations from multiple layers\n    layer_outputs = []\n    for i in range(12):  # GPT-2 has 12 layers\n        layer_out = model.transformer.h[i].output[0].save()\n        layer_outputs.append(layer_out)\n\n    # 2. Get attention patterns\n    attn_patterns = []\n    for i in range(12):\n        # Access attention weights (after softmax)\n        attn = model.transformer.h[i].attn.attn_dropout.input[0][0].save()\n        attn_patterns.append(attn)\n\n    # 3. Get final logits\n    logits = model.output.save()\n\n# 4. Analyze outside context\nfor i, layer_out in enumerate(layer_outputs):\n    print(f\"Layer {i} output shape: {layer_out.shape}\")\n    print(f\"Layer {i} norm: {layer_out.norm().item():.3f}\")\n\n# 5. Find top predictions\nprobs = torch.softmax(logits[0, -1], dim=-1)\ntop_tokens = probs.topk(5)\nfor token, prob in zip(top_tokens.indices, top_tokens.values):\n    print(f\"{model.tokenizer.decode(token)}: {prob.item():.3f}\")\n```\n\n### Checklist\n- [ ] Load model with LanguageModel wrapper\n- [ ] Use trace context for operations\n- [ ] Call `.save()` on values you need after context\n- [ ] Access saved values outside context\n- [ ] Use `.shape`, `.norm()`, etc. for analysis\n\n## Workflow 2: Activation Patching\n\n### Step-by-Step\n\n```python\nfrom nnsight import LanguageModel\nimport torch\n\nmodel = LanguageModel(\"gpt2\", device_map=\"auto\")\n\nclean_prompt = \"The Eiffel Tower is in\"\ncorrupted_prompt = \"The Colosseum is in\"\n\n# 1. Get clean activations\nwith model.trace(clean_prompt) as tracer:\n    clean_hidden = model.transformer.h[8].output[0].save()\n\n# 2. Patch clean into corrupted run\nwith model.trace(corrupted_prompt) as tracer:\n    # Replace layer 8 output with clean activations\n    model.transformer.h[8].output[0][:] = clean_hidden\n\n    patched_logits = model.output.save()\n\n# 3. Compare predictions\nparis_token = model.tokenizer.encode(\" Paris\")[0]\nrome_token = model.tokenizer.encode(\" Rome\")[0]\n\npatched_probs = torch.softmax(patched_logits[0, -1], dim=-1)\nprint(f\"Paris prob: {patched_probs[paris_token].item():.3f}\")\nprint(f\"Rome prob: {patched_probs[rome_token].item():.3f}\")\n```\n\n### Systematic Patching Sweep\n\n```python\ndef patch_layer_position(layer, position, clean_cache, corrupted_prompt):\n    \"\"\"Patch single layer\u002Fposition from clean to corrupted.\"\"\"\n    with model.trace(corrupted_prompt) as tracer:\n        # Get current activation\n        current = model.transformer.h[layer].output[0]\n\n        # Patch only specific position\n        current[:, position, :] = clean_cache[layer][:, position, :]\n\n        logits = model.output.save()\n\n    return logits\n\n# Sweep over all layers and positions\nresults = torch.zeros(12, seq_len)\nfor layer in range(12):\n    for pos in range(seq_len):\n        logits = patch_layer_position(layer, pos, clean_hidden, corrupted)\n        results[layer, pos] = compute_metric(logits)\n```\n\n## Workflow 3: Remote Execution with NDIF\n\nRun the same experiments on massive models without local GPUs.\n\n### Step-by-Step\n\n```python\nfrom nnsight import LanguageModel\n\n# 1. Load large model (will run remotely)\nmodel = LanguageModel(\"meta-llama\u002FLlama-3.1-70B\")\n\n# 2. Same code, just add remote=True\nwith model.trace(\"The meaning of life is\", remote=True) as tracer:\n    # Access internals of 70B model!\n    layer_40_out = model.model.layers[40].output[0].save()\n    logits = model.output.save()\n\n# 3. Results returned from NDIF\nprint(f\"Layer 40 shape: {layer_40_out.shape}\")\n\n# 4. Generation with interventions\nwith model.trace(remote=True) as tracer:\n    with tracer.invoke(\"What is 2+2?\"):\n        # Intervene during generation\n        model.model.layers[20].output[0][:, -1, :] *= 1.5\n\n    output = model.generate(max_new_tokens=50)\n```\n\n### NDIF Setup\n\n1. Sign up at [login.ndif.us](https:\u002F\u002Flogin.ndif.us)\n2. Get API key\n3. Set environment variable or pass to nnsight:\n\n```python\nimport os\nos.environ[\"NDIF_API_KEY\"] = \"your_key\"\n\n# Or configure directly\nfrom nnsight import CONFIG\nCONFIG.API_KEY = \"your_key\"\n```\n\n### Available Models on NDIF\n\n- Llama-3.1-8B, 70B, 405B\n- DeepSeek-R1 models\n- Various open-weight models (check [ndif.us](https:\u002F\u002Fndif.us) for current list)\n\n## Workflow 4: Cross-Prompt Activation Sharing\n\nShare activations between different inputs in a single trace.\n\n```python\nfrom nnsight import LanguageModel\n\nmodel = LanguageModel(\"gpt2\", device_map=\"auto\")\n\nwith model.trace() as tracer:\n    # First prompt\n    with tracer.invoke(\"The cat sat on the\"):\n        cat_hidden = model.transformer.h[6].output[0].save()\n\n    # Second prompt - inject cat's activations\n    with tracer.invoke(\"The dog ran through the\"):\n        # Replace with cat's activations at layer 6\n        model.transformer.h[6].output[0][:] = cat_hidden\n        dog_with_cat = model.output.save()\n\n# The dog prompt now has cat's internal representations\n```\n\n## Workflow 5: Gradient-Based Analysis\n\nAccess gradients during backward pass.\n\n```python\nfrom nnsight import LanguageModel\nimport torch\n\nmodel = LanguageModel(\"gpt2\", device_map=\"auto\")\n\nwith model.trace(\"The quick brown fox\") as tracer:\n    # Save activations and enable gradient\n    hidden = model.transformer.h[5].output[0].save()\n    hidden.retain_grad()\n\n    logits = model.output\n\n    # Compute loss on specific token\n    target_token = model.tokenizer.encode(\" jumps\")[0]\n    loss = -logits[0, -1, target_token]\n\n    # Backward pass\n    loss.backward()\n\n# Access gradients\ngrad = hidden.grad\nprint(f\"Gradient shape: {grad.shape}\")\nprint(f\"Gradient norm: {grad.norm().item():.3f}\")\n```\n\n**Note**: Gradient access not supported for vLLM or remote execution.\n\n## Common Issues & Solutions\n\n### Issue: Module path differs between models\n```python\n# GPT-2 structure\nmodel.transformer.h[5].output[0]\n\n# LLaMA structure\nmodel.model.layers[5].output[0]\n\n# Solution: Check model structure\nprint(model._model)  # See actual module names\n```\n\n### Issue: Forgetting to save\n```python\n# WRONG: Value not accessible outside trace\nwith model.trace(\"Hello\"):\n    hidden = model.transformer.h[5].output[0]  # Not saved!\n\nprint(hidden)  # Error or wrong value\n\n# RIGHT: Call .save()\nwith model.trace(\"Hello\"):\n    hidden = model.transformer.h[5].output[0].save()\n\nprint(hidden)  # Works!\n```\n\n### Issue: Remote timeout\n```python\n# For long operations, increase timeout\nwith model.trace(\"prompt\", remote=True, timeout=300) as tracer:\n    # Long operation...\n```\n\n### Issue: Memory with many saved activations\n```python\n# Only save what you need\nwith model.trace(\"prompt\"):\n    # Don't save everything\n    for i in range(100):\n        model.transformer.h[i].output[0].save()  # Memory heavy!\n\n    # Better: save specific layers\n    key_layers = [0, 5, 11]\n    for i in key_layers:\n        model.transformer.h[i].output[0].save()\n```\n\n### Issue: vLLM gradient limitation\n```python\n# vLLM doesn't support gradients\n# Use standard execution for gradient analysis\nmodel = LanguageModel(\"gpt2\", device_map=\"auto\")  # Not vLLM\n```\n\n## Key API Reference\n\n| Method\u002FProperty | Purpose |\n|-----------------|---------|\n| `model.trace(prompt, remote=False)` | Start tracing context |\n| `proxy.save()` | Save value for access after trace |\n| `proxy[:]` | Slice\u002Findex proxy (assignment patches) |\n| `tracer.invoke(prompt)` | Add prompt within trace |\n| `model.generate(...)` | Generate with interventions |\n| `model.output` | Final model output logits |\n| `model._model` | Underlying HuggingFace model |\n\n## Comparison with Other Tools\n\n| Feature | nnsight | TransformerLens | pyvene |\n|---------|---------|-----------------|--------|\n| Any architecture | Yes | Transformers only | Yes |\n| Remote execution | Yes (NDIF) | No | No |\n| Consistent API | No | Yes | Yes |\n| Deferred execution | Yes | No | No |\n| HuggingFace native | Yes | Reimplemented | Yes |\n| Shareable configs | No | No | Yes |\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 LanguageModel, tracing, proxy objects |\n| [references\u002Ftutorials.md](references\u002Ftutorials.md) | Step-by-step tutorials for local and remote interpretability |\n\n## External Resources\n\n### Tutorials\n- [Getting Started](https:\u002F\u002Fnnsight.net\u002Fstart\u002F)\n- [Features Overview](https:\u002F\u002Fnnsight.net\u002Ffeatures\u002F)\n- [Remote Execution](https:\u002F\u002Fnnsight.net\u002Fnotebooks\u002Ffeatures\u002Fremote_execution\u002F)\n- [Applied Tutorials](https:\u002F\u002Fnnsight.net\u002Fapplied_tutorials\u002F)\n\n### Official Documentation\n- [Official Docs](https:\u002F\u002Fnnsight.net\u002Fdocumentation\u002F)\n- [NDIF Info](https:\u002F\u002Fndif.us\u002F)\n- [Community Forum](https:\u002F\u002Fdiscuss.ndif.us\u002F)\n\n### Papers\n- [NNsight and NDIF Paper](https:\u002F\u002Farxiv.org\u002Fabs\u002F2407.14561) - Fiotto-Kaufman et al. (ICLR 2025)\n\n## Architecture Support\n\nnnsight works with any PyTorch model:\n- **Transformers**: GPT-2, LLaMA, Mistral, etc.\n- **State Space Models**: Mamba\n- **Vision Models**: ViT, CLIP\n- **Custom architectures**: Any nn.Module\n\nThe key is knowing the module structure to access the right components.\n",{"name":5,"tags":24,"author":30,"license":15,"version":31,"description":7,"dependencies":32},[25,26,27,28,29],"nnsight","NDIF","Remote Execution","Mechanistic Interpretability","Model Internals","Orchestra Research","1.0.0",[33,34],"nnsight>=0.5.0","torch>=2.0.0","main","18193d71ea3441d7c033dbf195b8a7c75ac96f75","packages\u002Fskill\u002Fskill-science\u002Fassets\u002Fsources\u002Fai-research-skills\u002F04-mechanistic-interpretability\u002Fnnsight",0,"https:\u002F\u002Fgithub.com\u002FCZX-LBJ\u002Fdeepseek-science","https:\u002F\u002Fgithub.com\u002FCZX-LBJ","一个没事喜欢随便写点代码的小菜鸡\r\n","2026-10-22 09:48:04",{"source":8,"skillName":5,"commands":44,"prompt":54,"zipAvailable":55},[45,48,51],{"tool":46,"command":47},"npx","npx skills add CZX-LBJ\u002Fdeepseek-science --skill nnsight-remote-interpretability",{"tool":49,"command":50},"bunx","bunx skills add CZX-LBJ\u002Fdeepseek-science --skill nnsight-remote-interpretability",{"tool":52,"command":53},"pnpm","pnpm dlx skills add CZX-LBJ\u002Fdeepseek-science --skill nnsight-remote-interpretability","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FCZX-LBJ\u002Fdeepseek-science\u002Fblob\u002Fmain\u002Fpackages\u002Fskill\u002Fskill-science\u002Fassets\u002Fsources\u002Fai-research-skills\u002F04-mechanistic-interpretability\u002Fnnsight\u002FSKILL.md",true,[57,63,67],{"path":58,"resourceType":59,"resourceTypeDesc":60,"sizeBytes":61,"sourceHtmlUrl":62},"references\u002Fapi.md","REFERENCE","参考文档",7160,"https:\u002F\u002Fgithub.com\u002FCZX-LBJ\u002Fdeepseek-science\u002Fblob\u002Fmain\u002Fpackages\u002Fskill\u002Fskill-science\u002Fassets\u002Fsources\u002Fai-research-skills\u002F04-mechanistic-interpretability\u002Fnnsight\u002Freferences\u002Fapi.md",{"path":64,"resourceType":59,"resourceTypeDesc":60,"sizeBytes":65,"sourceHtmlUrl":66},"references\u002FREADME.md",1913,"https:\u002F\u002Fgithub.com\u002FCZX-LBJ\u002Fdeepseek-science\u002Fblob\u002Fmain\u002Fpackages\u002Fskill\u002Fskill-science\u002Fassets\u002Fsources\u002Fai-research-skills\u002F04-mechanistic-interpretability\u002Fnnsight\u002Freferences\u002FREADME.md",{"path":68,"resourceType":59,"resourceTypeDesc":60,"sizeBytes":69,"sourceHtmlUrl":70},"references\u002Ftutorials.md",7970,"https:\u002F\u002Fgithub.com\u002FCZX-LBJ\u002Fdeepseek-science\u002Fblob\u002Fmain\u002Fpackages\u002Fskill\u002Fskill-science\u002Fassets\u002Fsources\u002Fai-research-skills\u002F04-mechanistic-interpretability\u002Fnnsight\u002Freferences\u002Ftutorials.md",[72,79,86,93,100,107],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":19},"01M7FEEKSNMRMKW6JEK93PFDFY","bio-free-energy-calculations","Performs alchemical free-energy calculations including relative binding free energy (RBFE \u002F FEP+) and absolute binding free energy (ABFE) via OpenFE, FEP+, GROMACS, AMBER pmemd, and OpenMM with explicit lambda scheduling, soft-core potentials, MBAR\u002FBAR analysis, cycle-closure validation, and protocol-appropriate enhanced sampling. Compares ML alternatives (Boltz-2 affinity, DeepDock). Use when ranking analogs by binding affinity beyond docking accuracy, performing prospective lead optimization, or validating SAR predictions.","https:\u002F\u002Fgithub.com\u002FCZX-LBJ\u002Fdeepseek-science\u002Fblob\u002Fmain\u002Fpackages\u002Fskill\u002Fskill-science\u002Fassets\u002Fsources\u002Fbioskills\u002Fchemoinformatics\u002Ffree-energy-calculations\u002FSKILL.md",[],[],{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":19},"01M7FEE5CTE5QK55CEMXNNVWY9","bio-conformer-generation","Generates 3D conformer ensembles using RDKit ETKDGv3 with knowledge-enhanced distance geometry, MMFF94\u002FUFF force-field optimization, CREST + GFN2-xTB semi-empirical refinement, and macrocycle-aware torsion preferences. Provides explicit decision rules for single vs ensemble conformer use, RMSD pruning, energy windows, conformer count, and force-field choice. Use when preparing 3D ligands for docking, generating descriptor input for 3D QSAR, or sampling macrocycle\u002Fpeptide conformational ensembles.","https:\u002F\u002Fgithub.com\u002FCZX-LBJ\u002Fdeepseek-science\u002Fblob\u002Fmain\u002Fpackages\u002Fskill\u002Fskill-science\u002Fassets\u002Fsources\u002Fbioskills\u002Fchemoinformatics\u002Fconformer-generation\u002FSKILL.md",[],[],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":19},"01M7FEDNGFEMFWD1MSEDR5H7CY","bio-admet-prediction","Predicts ADMET properties using ADMETlab 3.0 (119 platform features, including 77 prediction models with modeled-endpoint uncertainty), ADMET-AI, DeepChem MolNet, and chemprop D-MPNN with explicit handling of OECD QSAR principles, applicability domain assessment, calibration, hERG\u002FCYP\u002FAMES endpoints, and PAINS \u002F Lipinski \u002F Ro5 \u002F Veber \u002F BBB druglikeness filters. Use when filtering compounds for drug-likeness, prioritizing leads by predicted safety, or building an in-house ADMET QSAR model.","https:\u002F\u002Fgithub.com\u002FCZX-LBJ\u002Fdeepseek-science\u002Fblob\u002Fmain\u002Fpackages\u002Fskill\u002Fskill-science\u002Fassets\u002Fsources\u002Fbioskills\u002Fchemoinformatics\u002Fadmet-prediction\u002FSKILL.md",[],[],{"skillNo":94,"name":95,"nameZh":6,"description":96,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":97,"categories":98,"keywords":99,"publishedAt":19},"01M7FED69GFB54FRF7AV5066DN","writing-systems-papers","Paragraph-level structural blueprint for 10-12 page systems papers targeting OSDI, SOSP, ASPLOS, NSDI, and EuroSys. Provides page allocation, paragraph templates, and writing patterns. Use when user says \"写系统论文\", \"systems paper structure\", \"OSDI paper\", \"SOSP paper\", or wants fine-grained structural guidance for a systems conference submission.","https:\u002F\u002Fgithub.com\u002FCZX-LBJ\u002Fdeepseek-science\u002Fblob\u002Fmain\u002Fpackages\u002Fskill\u002Fskill-science\u002Fassets\u002Fsources\u002Faris\u002Fskills\u002Fwriting-systems-papers\u002FSKILL.md",[],[],{"skillNo":101,"name":102,"nameZh":6,"description":103,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":104,"categories":105,"keywords":106,"publishedAt":19},"01M7FECVVDWZ0X0VEDTCE4B4DZ","wiki-enrich","Fill in the per-paper TODO sections of research-wiki\u002Fpapers\u002F\u003Cslug>.md pages that literature-ingest skills leave as bare scaffolds. Use when user says 'enrich wiki', 'fill paper TODOs', 'wiki body 補完', '把 paper 摘要寫進 wiki', 'research-wiki 自動填', or after a batch ingest that left papers\u002F as TODO scaffolds.","https:\u002F\u002Fgithub.com\u002FCZX-LBJ\u002Fdeepseek-science\u002Fblob\u002Fmain\u002Fpackages\u002Fskill\u002Fskill-science\u002Fassets\u002Fsources\u002Faris\u002Fskills\u002Fwiki-enrich\u002FSKILL.md",[],[],{"skillNo":108,"name":109,"nameZh":6,"description":110,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":111,"categories":112,"keywords":113,"publishedAt":19},"01M7FECD4BCJ2MTSBDDSE3ZAJ5","web-debug-search","Search GitHub, Stack Exchange, Chinese technical communities, official documentation, and general developer web sources for software errors, compatibility problems, API usage questions, and real-world workarounds. Use for debugging and discovery only; results are not paper-citation evidence.","https:\u002F\u002Fgithub.com\u002FCZX-LBJ\u002Fdeepseek-science\u002Fblob\u002Fmain\u002Fpackages\u002Fskill\u002Fskill-science\u002Fassets\u002Fsources\u002Faris\u002Fskills\u002Fweb-debug-search\u002FSKILL.md",[],[]]