layer-wise-representation

layer-wise-representation is a skill for Claude Code, Codex from zjunlp/Mechanist. It costs 57 tokens per session (6,367 once invoked), scanned A, original, MIT.

A method for changing a language model’s internal representations while it generates an answer, with the aim of making responses more truthful and reducing made-up information. An internal representation is the model’s numeric encoding of what it is processing.

In plain words
What is it for?
Use it to load a TruthX-enabled Llama model and generate answers with inference-time controls intended to improve truthfulness.
Why use it?
It addresses cases where a language model sounds confident but gives false or invented answers.

Skill for Claude CodeCodex

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

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.

agentmods
npx agentmods add skills/zjunlp/mechanist/layer-wise-representation
Any agent
npx skills add zjunlp/Mechanist --skill layer-wise-representation
Clone the repo
git clone --depth 1 https://github.com/zjunlp/Mechanist

Made for: Claude Code, Codex.

Or install mechanist, the plugin that ships this one along with the rest of its 54 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 layer-wise-representation

README.md
[![agentmods](https://agentmods.dev/badge/skills/zjunlp/mechanist/layer-wise-representation.svg)](https://agentmods.dev/skills/zjunlp/mechanist/layer-wise-representation)
Your own site
<a href="https://agentmods.dev/skills/zjunlp/mechanist/layer-wise-representation"><img src="https://agentmods.dev/badge/skills/zjunlp/mechanist/layer-wise-representation.svg" alt="Measured on agentmods" height="20"></a>
Per session 57 Skills are progressive disclosure: only the name and description are preloaded; the body loads when the skill is used.
When invoked 6,367 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. Scan, not verified.
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 $0.00057 $0.06367
Opus 5 $0.00028 $0.03184
Sonnet 5 $0.00011 $0.01273
Haiku 4.5 $0.00006 $0.00637

Measured 5d ago against content hash 7dfd3472162e, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

layer-wise-representation 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 5d ago.

The scan reads SKILL.md. This mod also ships 3 executable files (scripts/basic_inference.py, scripts/truthfulqa_evaluation.py, scripts/truthx_editing.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/magnitude-analysis/layer-wise-representation/SKILL.md · 1,043 lines

How it starts

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

Demo Scripts

scripts/basic_inference.py

#!/usr/bin/env python3
"""
Basic TruthX Inference Example

This script demonstrates how to use the TruthX-enhanced Llama model for
generating truthful responses to questions.

Requirements:
- pip install torch transformers
- Download model from: https://huggingface.co/ICTNLP/Llama-2-7b-chat-TruthX
"""

import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
import argparse
from typing import Optional, List


def load_truthx_model(model_name: str = "ICTNLP/Llama-2-7b-chat-TruthX"):
    """
    Load the TruthX-enhanced model and tokenizer.
    
    Args:
        model_name: Hugging Face model identifier or local path
        
    Returns:
        Tuple of (model, tokenizer)
    """
    print(f"Loading model: {model_name}")
    
    tokenizer = AutoTokenizer.from_pretrained(
        model_name, 
        trust_remote_code=True
    )
    
    model = AutoModelForCausalLM.from_pretrained(
        model_name,
        trust_remote_code=True,
        torch_dtype=torch.float16,
        device_map="auto"
    )
    
    # Move to CUDA if available
    if torch.cuda.is_available():
        model = model.cuda()
        print("Model loaded on CUDA")
    else:
        print("Model loaded on CPU")
    
    return model, tokenizer


def generate_response(
    model,
    tokenizer,
    prompt: str,
    max_length: int = 512,
    temperature: float = 0.7,
    top_p: float = 0.9,
    do_sample: bool = True
) -> str:
    """
    Generate a response using the TruthX model.
    
    Args:
        model: The loaded model
        tokenizer: The loaded tokenizer
        prompt: Input text prompt
        max_length: Maximum length of generated text
        temperature: Sampling temperature
        top_p: Nucleus sampling parameter
        do_sample: Whether to use sampling
        
    Returns:
        Generated text response
    """
    # Encode the input
    encoded_inputs = tokenizer(prompt, return_tensors="pt")["input_ids"]
    
    # Move to same device as model
    if torch.cuda.is_available():
        encoded_inputs = encoded_inputs.cuda()
    
    # Generate response
    with torch.no_grad():
        outputs = model.generate(
            encoded_inputs,
            max_length=max_length,
            temperature=temperature,
            top_p=top_p,
            do_sample=do_sample,
            pad_token_id=tokenizer.eos_token_id
        )
    
    # Decode only the generated portion
    generated_tokens = outputs[0, encoded_inputs.shape[-1]:]
    response = tokenizer.decode(generated_tokens, skip_special_tokens=True).strip()
    
    return response


def batch_generate(
    model,
    tokenizer,
    prompts: List[str],
    **kwargs
) -> List[str]:
    """
    Generate responses for multiple prompts.
    
    Args:
        model: The loaded model
        tokenizer: The loaded tokenizer
        prompts: List of input prompts
        **kwargs: Additional generation parameters
        
    Returns:
        List of generated responses
    """
    responses = []
    
    for i, prompt in enumerate(prompts):
        print(f"Processing prompt {i+1}/{len(prompts)}...")
        response = generate_response(model, tokenizer, prompt, **kwargs)
        responses.append(response)
    
    return responses


def interactive_mode(model, tokenizer):
    """
    Run an interactive chat session with the model.
    """
    print("\n=== Interactive TruthX Chat ===")
    print("Type 'quit' to exit\n")
    
    while True:
        # Get user input
        prompt = input("You: ").strip()
        
        if prompt.lower() in ['quit', 'exit', 'q']:
            print("Goodbye!")
            break
        
        if not prompt:
            continue
        
        # Generate response
        response = generate_response(
            model, 
            tokenizer, 
            prompt,
            temperature=0.7,
            top_p=0.9
        )
        
        print(f"\nTruthX: {response}\n")


def main():
    parser = argparse.ArgumentParser(
        description="TruthX inference script for generating truthful responses"
    )
    parser.add_argument(
        "--model-path",
        type=str,
        default="ICTNLP/Llama-2-7b-chat-TruthX",
        help="Path to TruthX model or Hugging Face identifier"
    )
    parser.add_argument(
        "--prompt",
        type=str,
        help="Single prompt to process"
    )
    parser.add_argument(
        "--interactive",
        action="store_true",
        help="Run in interactive mode"
    )
    parser.add_argument(
        "--temperature",
        type=float,
        default=0.7,
        help="Sampling temperature"
    )
    parser.add_argument(
        "--max-length",
        type=int,
        default=512,
        help="Maximum generation length"
    )
    
    args = parser.parse_args()
    
    # Load model
    model, tokenizer = load_truthx_model(args.model_path)
    
    if args.interactive:
        # Interactive mode
        interactive_mode(model, tokenizer)
    elif args.prompt:
        # Single prompt mode
        response = generate_response(
            model,
            tokenizer,
            args.prompt,
            max_length=args.max_length,
            temperature=args.temperature
        )
        print(f"\nPrompt: {args.prompt}")
        print(f"Response: {response}")
    else:
        # Demo with sample questions
        sample_questions = [
            "What are the benefits of eating an apple a day?",
            "What is the capital of France?",
            "Explain the theory of relativity in simple terms.",
            "What happens if you swallow gum?",
            "Is it true that we only use 10% of our brain?"
        ]
        
        print("\n=== TruthX Demo Responses ===\n")
        
        for question in sample_questions:
            response = generate_response(
                model,
                tokenizer,
                question,
                temperature=args.temperature
            )
            print(f"Q: {question}")
            print(f"A: {response}\n")


if __name__ == "__main__":
    main()

Read the full file on GitHub · 1,043 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. 5d ago First seen · 1,043 lines · 57 tokens per session scan A 7dfd3472162e

Subscribe to this mod's changes

layer-wise-representation is a skill published in the GitHub repository zjunlp/Mechanist (51 stars, last pushed 9d ago), licensed MIT. It adds 57 tokens to every session and 6,367 once invoked, about $0.0003 per session on Opus 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-08-30.

Related

Other skills, from other repositories

create-atomic-tool

Build a BaseTool[InSchema, OutSchema] subclass — input/output schemas, BaseToolConfig, run() (and optional runasync()), env-driven secrets, typed failure outputs. Use when the user asks to "add a tool", "create a tool", "wrap an API as a tool", "build a BaseTool", "make a calculator/search/weather tool", or runs…

Eigenwise/atomic-agents · 99 tokens

framework

Guide for the Atomic Agents Python framework — schemas, agents, tools, context providers, prompts, orchestration, and provider configuration. Use when code imports from atomicagents, defines an AtomicAgent, BaseTool, or BaseIOSchema, or the user asks about multi-agent orchestration or LLM-provider wiring in an…

Eigenwise/atomic-agents · 74 tokens

create-atomic-agent

Build and wire an AtomicAgent[InSchema, OutSchema] — schemas, AgentConfig, SystemPromptGenerator, provider client, history, hooks, optional context providers. Use when the user asks to "create an agent", "add another agent", "build an AtomicAgent", "wire up an agent", "make a planner/router/extractor agent", or runs…

Eigenwise/atomic-agents · 93 tokens

create-atomic-context-provider

Build a BaseDynamicContextProvider that injects a named, titled block into an agent's system prompt at every run() — current time, user identity, retrieved RAG docs, session state, cached DB schema. Use when the user asks to "add a context provider", "inject X into the prompt", "give the agent dynamic context", "wire…

Eigenwise/atomic-agents · 106 tokens

create-atomic-schema

Design and write a BaseIOSchema input/output pair for an Atomic Agents agent or tool — docstrings, field descriptions, validators, error variants. Use when the user asks to "create a schema", "design the input/output schema", "define an IOSchema", "write a BaseIOSchema", "model the agent's output", or runs…

Eigenwise/atomic-agents · 89 tokens

new-app

Scaffold a new Atomic Agents project from scratch — create the directory, pyproject.toml, env file, first agent, and a runnable entry point. Use when the user asks to start a new atomic-agents project from scratch, says "scaffold" / "new project" / "start from zero", or runs /atomic-agents:new-app.

Eigenwise/atomic-agents · 76 tokens