본문으로 건너뛰기
Skillpedia
머신러닝33k · #8573

mechanistic-interpretability-nnsight

하는 일

이 스킬은 nnsight 라이브러리를 사용해 신경망 내부에서 무슨 일이 일어나는지 연구하도록 AI를 안내합니다. 모델의 내부 값을 살펴보거나 고치려는 연구자와 엔지니어를 위한 스킬입니다.

사용하는 경우

  • ✓신경망이 입력을 처리하는 동안 내부 값을 보고 싶을 때.
  • ✓내 컴퓨터에서는 돌릴 수 없는 매우 큰 시스템에서 모델을 테스트하고 싶을 때.
  • ✓모델 실행 중 내부 값을 바꿔서 출력이 어떻게 달라지는지 보고 싶은 경우.

스킬 링크

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

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/davila7/claude-code-templates/blob/main/cli-tool/components/skills/ai-research/mechanistic-interpretability-nnsight/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“언어 모델 내부를 들여다보고 중간 레이어에서 무슨 일이 일어나는지 확인하도록 도와주시겠어요?”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

스킬은 PyTorch 모델을 감싸고, 입력을 통과시키고, 선택한 내부 값을 저장하는 방법을 보여 줍니다. 같은 코드를 로컬에서 실행하거나 대형 모델용 원격 서비스에서 실행할 수 있습니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

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
자주 묻는 질문

강력한 컴퓨터가 필요한가요?

대형 모델의 경우에는 필요하지 않습니다. 원격 옵션을 쓰면 필요한 하드웨어를 갖춘 공용 서비스에서 같은 코드를 실행할 수 있습니다.

어떤 모델을 쓸 수 있나요?

일반적인 트랜스포머 모델을 포함해 PyTorch 모델이라면 모두 쓸 수 있습니다.

초보자도 쓸 수 있나요?

Python과 머신러닝 기초를 안다고 가정하지만, 가이드가 단계별로 안내합니다.

상세 정보

작성자의 원본 설명

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

인기도

GitHub 스타
33k
순위
#8573
라이선스
MIT
업데이트
2026. 11. 2.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬