sae-feature-activation-state

sae-feature-activation-state is a skill for Claude Code from zjunlp/Mechanist. It costs 67 tokens per session (7,735 once invoked), scanned A, original, MIT.

A research toolkit for studying Sparse Autoencoders, models that represent complex neural activity using a small number of active features. It focuses on finding, removing, and testing these features in language models such as Gemma-2.

In plain words
What is it for?
Use it to run feature-ablation experiments, probe language-model features, study feature splitting and absorption, and measure how individual features change generated text.
Why use it?
It helps investigate which internal features affect a model's output instead of treating the model as a black box. Feature ablation, meaning deliberately removing a feature, can show whether that feature matters.

Skill for Claude Code

Written for Claude Code: shipped in a Claude Code plugin.

Part of the mechanist plugin — 85 skills, 4 agents shipped together

Good fit Use it to run feature-ablation experiments, probe language-model features, study feature splitting and absorption, and measure how individual features change generated text.

Compare 6 skills from other repositories ↓
Install with agentmods
npx agentmods add skills/zjunlp/mechanist/sae-feature-activation-state
Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

Any agent
npx skills add zjunlp/Mechanist --skill sae-feature-activation-state
Clone the repo
git clone --depth 1 https://github.com/zjunlp/Mechanist

Made for: Claude Code.

Or install mechanist, the plugin that ships this one along with the rest of its 85 skills, 4 agents.

Wrote this? Show the measurements

A badge with what this costs and how it scanned, read live from this page, so it follows the numbers instead of freezing them. Markdown for a README, HTML for a documentation site or a project page.

agentmods badge for sae-feature-activation-state

README.md
[![agentmods](https://agentmods.dev/badge/skills/zjunlp/mechanist/sae-feature-activation-state/github.svg)](https://agentmods.dev/skills/zjunlp/mechanist/sae-feature-activation-state)
Your own site
<a href="https://agentmods.dev/skills/zjunlp/mechanist/sae-feature-activation-state"><img src="https://agentmods.dev/badge/skills/zjunlp/mechanist/sae-feature-activation-state/github.svg" alt="Measured on agentmods" height="20"></a>

Or the 80×15 button, for a site that already has a row of RSS and ATOM ones. Only the verdict fits; the numbers stay here.

agentmods 80×15 button for sae-feature-activation-state

Your own site · 80×15
<a href="https://agentmods.dev/skills/zjunlp/mechanist/sae-feature-activation-state"><img src="https://agentmods.dev/badge/skills/zjunlp/mechanist/sae-feature-activation-state.svg" alt="Reviewed on agentmods" width="80" height="20"></a>
Per session 67 Skills are progressive disclosure: only the name and description are preloaded; the body loads when the skill is used.
When invoked 7,735 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. A grade says what 26 rules found in the file — not that it is safe.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5.1 $0.00067 $0.07735
Opus 5.5 $0.00027 $0.03094
Sonnet 5.5 $0.00013 $0.01547
Haiku 4.5 $0.00007 $0.00773

Measured 2mo ago against content hash bca20ce14c1c, method: parsed. Prices are Anthropic first-party input rates as of 2026-10-07, from the pricing page.

Security

Grade A, and why

sae-feature-activation-state scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 2mo ago.

The scan reads SKILL.md. This mod also ships 3 executable files (scripts/feature_ablation_example.py, scripts/feature_attribution_example.py, scripts/k_sparse_probing_example.py), listed below but not scanned — reading those needs a real analyzer, not pattern matching.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

skills/mechanism-skills/probing/sae-feature-activation-state/SKILL.md · 1,076 lines

How it starts

The opening of the file, as written. The whole thing — 1,076 lines — stays where its author put it; the contents beside it link to each section on GitHub.

Demo Scripts

scripts/feature_ablation_example.py

#!/usr/bin/env python3
"""
Feature Ablation Example for SAE Analysis

This script demonstrates how to use the sae_spelling library to perform
feature ablation experiments on Sparse Autoencoders (SAEs). It shows how
to ablate individual SAE features and measure their impact on model outputs.

Requires: poetry install (or pip install sae-spelling)
"""

import torch
from typing import List, Dict, Any
from pathlib import Path

# Mock imports - replace with actual imports when available
# from sae_spelling.feature_ablation import calculate_individual_feature_ablations
# from sae_spelling.experiments.common import load_gemma2_model, load_gemmascope_sae
# from sae_spelling.prompting import create_icl_prompt, first_letter_formatter
# from sae_spelling.vocab import get_alpha_tokens

def setup_model_and_sae(layer: int = 12, sae_width: int = 16384, sae_l0: int = 128):
    """
    Load a Gemma-2 model and corresponding SAE.
    
    Args:
        layer: Which transformer layer to analyze
        sae_width: Width of the SAE (number of features)
        sae_l0: L0 target for SAE sparsity
    
    Returns:
        Tuple of (model, sae, tokenizer)
    """
    print(f"Loading Gemma-2 model...")
    # model, tokenizer = load_gemma2_model(dtype=torch.float32, device="cuda")
    
    print(f"Loading GemmaScope SAE for layer {layer}...")
    # sae = load_gemmascope_sae(layer=layer, width=sae_width, l0=sae_l0)
    
    # Mock implementation for demonstration
    model = None
    sae = None
    tokenizer = None
    
    return model, sae, tokenizer

def prepare_spelling_prompts(tokenizer, num_examples: int = 10):
    """
    Create prompts for first-letter spelling tasks.
    
    Args:
        tokenizer: The model's tokenizer
        num_examples: Number of example prompts to generate
    
    Returns:
        List of formatted prompts
    """
    # Get alphabetic tokens from vocabulary
    # alpha_tokens = get_alpha_tokens(tokenizer)
    
    # Create ICL prompts for first-letter task
    prompts = []
    
    # Mock implementation
    example_tokens = ["cat", "dog", "house", "tree", "book"]
    
    for token in example_tokens[:num_examples]:
        # prompt = create_icl_prompt(
        #     tokens=[token],
        #     formatter=first_letter_formatter(),
        #     num_shots=5
        # )
        prompt = f"The first letter of '{token}' is"
        prompts.append(prompt)
    
    return prompts

def run_feature_ablation_analysis(
    model,
    sae,
    tokenizer,
    prompts: List[str],
    metric_fn=None
):
    """
    Perform feature ablation analysis on given prompts.
    
    Args:
        model: The language model
        sae: The Sparse Autoencoder
        tokenizer: Model tokenizer
        prompts: List of evaluation prompts
        metric_fn: Function to evaluate model output quality
    
    Returns:
        Dict containing ablation results for each feature
    """
    results = {}
    
    print("Running feature ablation experiments...")
    
    for prompt_idx, prompt in enumerate(prompts):
        print(f"Processing prompt {prompt_idx + 1}/{len(prompts)}: {prompt[:50]}...")
        
        # Tokenize the prompt
        # tokens = tokenizer(prompt, return_tensors="pt")
        
        # Get baseline model output
        # with torch.no_grad():
        #     baseline_output = model(tokens)
        
        # Calculate individual feature ablations
        # ablation_effects = calculate_individual_feature_ablations(
        #     model=model,
        #     sae=sae,
        #     prompt=prompt,
        #     metric_fn=metric_fn or default_metric
        # )
        
        # Mock results for demonstration
        ablation_effects = {
            f"feature_{i}": {
                "effect_size": torch.randn(1).item(),
                "firing_rate": torch.rand(1).item(),
                "importance_score": torch.rand(1).item()
            }
            for i in range(5)  # Mock 5 features
        }
        
        results[f"prompt_{prompt_idx}"] = {
            "prompt": prompt,
            "ablation_effects": ablation_effects
        }
    
    return results

def analyze_feature_importance(ablation_results: Dict[str, Any]):
    """
    Analyze and summarize feature importance from ablation results.
    
    Args:
        ablation_results: Results from feature ablation analysis
    
    Returns:
        Summary statistics of feature importance
    """
    print("\nAnalyzing feature importance...")
    
    # Aggregate feature effects across prompts
    feature_scores = {}
    
    for prompt_key, prompt_results in ablation_results.items():
        for feature_name, effects in prompt_results["ablation_effects"].items():
            if feature_name not in feature_scores:
                feature_scores[feature_name] = []
            
            feature_scores[feature_name].append(effects["importance_score"])
    
    # Calculate average importance for each feature
    feature_importance = {}
    for feature_name, scores in feature_scores.items():
        feature_importance[feature_name] = {
            "mean_importance": sum(scores) / len(scores),
            "max_importance": max(scores),
            "frequency": len([s for s in scores if s > 0.5]) / len(scores)
        }
    
    # Sort features by mean importance
    sorted_features = sorted(
        feature_importance.items(),
        key=lambda x: x[1]["mean_importance"],
        reverse=True
    )
    
    print("\nTop 5 Most Important Features:")
    for feature_name, stats in sorted_features[:5]:
        print(f"  {feature_name}:")
        print(f"    Mean importance: {stats['mean_importance']:.4f}")
        print(f"    Max importance: {stats['max_importance']:.4f}")
        print(f"    Active frequency: {stats['frequency']:.2%}")
    
    return feature_importance

def save_results(results: Dict[str, Any], output_path: Path):
    """
    Save ablation results to disk for further analysis.
    
    Args:
        results: Ablation analysis results
        output_path: Path to save results
    """
    import json
    
    output_path = Path(output_path)
    output_path.parent.mkdir(parents=True, exist_ok=True)
    
    # Convert torch tensors to regular Python types for JSON serialization
    serializable_results = {}
    for key, value in results.items():
        if isinstance(value, torch.Tensor):
            serializable_results[key] = value.tolist()
        elif isinstance(value, dict):
            serializable_results[key] = {
                k: v.tolist() if isinstance(v, torch.Tensor) else v
                for k, v in value.items()
            }
        else:
            serializable_results[key] = value
    
    with open(output_path, 'w') as f:
        json.dump(serializable_results, f, indent=2)
    
    print(f"\nResults saved to {output_path}")

def main():
    """
    Main function to run the feature ablation example.
    """
    print("SAE Feature Ablation Analysis Example")
    print("=" * 50)
    
    # Configuration
    layer = 12
    sae_width = 16384
    sae_l0 = 128
    num_prompts = 5
    output_path = Path("ablation_results.json")
    
    # Step 1: Load model and SAE
    model, sae, tokenizer = setup_model_and_sae(
        layer=layer,
        sae_width=sae_width,
        sae_l0=sae_l0
    )
    
    # Step 2: Prepare evaluation prompts
    prompts = prepare_spelling_prompts(tokenizer, num_examples=num_prompts)
    
    # Step 3: Run ablation analysis
    ablation_results = run_feature_ablation_analysis(
        model=model,
        sae=sae,
        tokenizer=tokenizer,
        prompts=prompts
    )
    
    # Step 4: Analyze feature importance
    feature_importance = analyze_feature_importance(ablation_results)
    
    # Step 5: Save results
    save_results(
        {
            "ablation_results": ablation_results,
            "feature_importance": feature_importance
        },
        output_path
    )
    
    print("\nAnalysis complete!")

if __name__ == "__main__":
    main()

Read the full file on GitHub · 1,076 lines

Files

What ships with it

4 files beside SKILL.md in the same directory: the scripts, references and assets a skill reads on demand. Not counted in the per-session cost; read them before you install if any of them is executable.

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 2mo ago First seen · 1,076 lines · 67 tokens per session scan A bca20ce14c1c

Subscribe to this mod's changes

sae-feature-activation-state is a skill published in the GitHub repository zjunlp/Mechanist (82 stars, last pushed 2d ago), licensed MIT. It adds 67 tokens to every session and 7,735 once invoked, about $0.0003 per session on Opus 5.5. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-09-16.

Related

sae-feature-activation-state compared with skills from other repositories

sae-feature-activation-state next to 6 skills from other repositories
ModTypeStarsLast pushLicenceScanTokensWorks with
sae-feature-activation-statezjunlp/MechanistSkill822d agoMITA67Claude Code
nanoresearch-writingOpenRaiser/NanoResearchSkill1.3k1mo agoMITA17Claude Code, Codex
nanoresearch-experimentOpenRaiser/NanoResearchSkill1.3k1mo agoMITA15Claude Code, Codex
nanoresearch-ideationOpenRaiser/NanoResearchSkill1.3k1mo agoMITA14Claude Code, Codex
nnsight-remote-interpretabilityOpenLAIR/dr-clawSkill1.2k19d agononeA59Claude Code, Codex
sparse-autoencoder-trainingOpenLAIR/dr-clawSkill1.2k19d agononeA58Claude Code, Codex
transformer-lens-interpretabilityOpenLAIR/dr-clawSkill1.2k19d agononeA52Claude Code, Codex