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

mechanistic-interpretability-nnsight

Skill này làm gì

Skill này hướng dẫn AI của bạn tìm hiểu điều gì xảy ra bên trong mạng nơ-ron bằng thư viện nnsight. Dành cho nhà nghiên cứu và kỹ sư muốn xem hoặc chỉnh sửa các giá trị bên trong của mô hình.

Khi nào nên dùng

  • ✓Khi bạn muốn xem các giá trị bên trong của mạng nơ-ron trong lúc nó xử lý một đầu vào.
  • ✓Khi bạn muốn thử nghiệm mô hình trên một hệ thống quá lớn để chạy trên máy tính của bạn.
  • ✓Khi bạn muốn thay đổi giá trị bên trong trong lúc mô hình chạy để xem đầu ra thay đổi thế nào.

Liên kết skill

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

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

Cách dùng

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

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

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

Ví dụ cách nhờ AI

“Bạn có thể giúp tôi nhìn vào bên trong một mô hình ngôn ngữ và xem điều gì xảy ra ở một lớp giữa không?”

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

Cách hoạt động

Skill cho thấy cách bọc một mô hình PyTorch, chạy một đầu vào qua nó và lưu các giá trị bên trong đã chọn. Cùng một đoạn code có thể chạy cục bộ hoặc trên dịch vụ từ xa cho các mô hình lớn.

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

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

nnsight: Transparent Access to Neural Network Internals

nnsight (/ɛn.saɪt/) 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.

GitHub: ndif-team/nnsight (730+ stars) Paper: NNsight and NDIF: Democratizing Access to Foundation Model Internals (ICLR 2025)

Key Value Proposition

Write once, run anywhere: The same interpretability code works on GPT-2 locally or Llama-3.1-405B remotely. Just toggle remote=True.

# Local execution (small model)
with model.trace("Hello world"):
    hidden = model.transformer.h[5].output[0].save()

# Remote execution (massive model) - same code!
with model.trace("Hello world", remote=True):
    hidden = model.model.layers[40].output[0].save()

When to Use nnsight

Use nnsight when you need to:

  • Run interpretability experiments on models too large for local GPUs (70B, 405B)
  • Work with any PyTorch architecture (transformers, Mamba, custom models)
  • Perform multi-token generation interventions
  • Share activations between different prompts
  • Access full model internals without reimplementation

Consider alternatives when:

  • You want consistent API across models → Use TransformerLens
  • You need declarative, shareable interventions → Use pyvene
  • You're training SAEs → Use SAELens
  • You only work with small models locally → TransformerLens may be simpler

Installation

# Basic installation
pip install nnsight

# For vLLM support
pip install "nnsight[vllm]"

For remote NDIF execution, sign up at login.ndif.us for an API key.

Core Concepts

LanguageModel Wrapper

from nnsight import LanguageModel

# Load model (uses HuggingFace under the hood)
model = LanguageModel("openai-community/gpt2", device_map="auto")

# For larger models
model = LanguageModel("meta-llama/Llama-3.1-8B", device_map="auto")

Tracing Context

The trace context manager enables deferred execution - operations are collected into a computation graph:

from nnsight import LanguageModel

model = LanguageModel("gpt2", device_map="auto")

with model.trace("The Eiffel Tower is in") as tracer:
    # Access any module's output
    hidden_states = model.transformer.h[5].output[0].save()

    # Access attention patterns
    attn = model.transformer.h[5].attn.attn_dropout.input[0][0].save()

    # Modify activations
    model.transformer.h[8].output[0][:] = 0  # Zero out layer 8

    # Get final output
    logits = model.output.save()

# After context exits, access saved values
print(hidden_states.shape)  # [batch, seq, hidden]

Proxy Objects

Inside trace, module accesses return Proxy objects that record operations:

with model.trace("Hello"):
    # These are all Proxy objects - operations are deferred
    h5_out = model.transformer.h[5].output[0]  # Proxy
    h5_mean = h5_out.mean(dim=-1)              # Proxy
    h5_saved = h5_mean.save()                   # Save for later access

Workflow 1: Activation Analysis

Step-by-Step

from nnsight import LanguageModel
import torch

model = LanguageModel("gpt2", device_map="auto")

prompt = "The capital of France is"

with model.trace(prompt) as tracer:
    # 1. Collect activations from multiple layers
    layer_outputs = []
    for i in range(12):  # GPT-2 has 12 layers
        layer_out = model.transformer.h[i].output[0].save()
        layer_outputs.append(layer_out)

    # 2. Get attention patterns
    attn_patterns = []
    for i in range(12):
        # Access attention weights (after softmax)
        attn = model.transformer.h[i].attn.attn_dropout.input[0][0].save()
        attn_patterns.append(attn)

    # 3. Get final logits
    logits = model.output.save()

# 4. Analyze outside context
for i, layer_out in enumerate(layer_outputs):
    print(f"Layer {i} output shape: {layer_out.shape}")
    print(f"Layer {i} norm: {layer_out.norm().item():.3f}")

# 5. Find top predictions
probs = torch.softmax(logits[0, -1], dim=-1)
top_tokens = probs.topk(5)
for token, prob in zip(top_tokens.indices, top_tokens.values):
    print(f"{model.tokenizer.decode(token)}: {prob.item():.3f}")

Checklist

  • Load model with LanguageModel wrapper
  • Use trace context for operations
  • Call `.sav
Câu hỏi thường gặp

Tôi có cần máy tính mạnh không?

Với mô hình lớn thì không cần. Tùy chọn từ xa cho phép bạn chạy cùng đoạn code trên dịch vụ dùng chung có sẵn phần cứng cần thiết.

Nó hỗ trợ những mô hình nào?

Nó hoạt động với mọi mô hình PyTorch, kể cả các mô hình transformer phổ biến.

Nó có dễ cho người mới không?

Skill giả định bạn biết một chút Python và kiến thức cơ bản về học máy, nhưng hướng dẫn đi qua từng bước.

Chi tiết

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

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.

repo: davila7/claude-code-templates

Độ phổ biến

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

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

0

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

Bình luận

  • …

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

Skill tương tự