源文件:chapter2/attentionvisualization/README.md 注意力可视化 一个交互式可视化工具,用于探索语言模型中的注意力机制。每次 Agent 运行都会生成一条独特的轨迹,可在前端查看与对比。 概览 本项目提供了一种交互方式,帮助理解语言模型在处理不同类型查询时如何分配注意力。Agent 每次运行都会生成一个新的轨迹文件,记录: 输入查询与模型响应 逐 token 的注意力权重 跨层、跨注意力头的注意力模式 注意力分布的统计分析 架构 系统采用简单的架构: Agent 生成轨迹:运行 或 生成新轨迹 JSON 存储:每条轨迹保存为 下的独立 JSON 文件 前端可视化:React 应用加载并通过标签页导航展示所有轨迹 快速开始(独立 CLI) 复现第 2
源文件:chapter2/attention_visualization/README.md
一个交互式可视化工具,用于探索语言模型中的注意力机制。每次 Agent 运行都会生成一条独特的轨迹,可在前端查看与对比。
本项目提供了一种交互方式,帮助理解语言模型在处理不同类型查询时如何分配注意力。Agent 每次运行都会生成一个新的轨迹文件,记录:
系统采用简单的架构:
agent.py 或 main.py 生成新轨迹frontend/public/trajectories/ 下的独立 JSON 文件复现第 2 章中描述的注意力模式(实验 2-2)最快的办法是使用独立命令行工具 attention_cli.py。它会运行真实模型、捕获其自注意力,并直接输出一张热力图 PNG——无需前端。
# Single heatmap for the default prompt (last layer, heads averaged) python attention_cli.py # Custom prompt, inspect a specific layer/head, choose the output path python attention_cli.py --prompt "北京 的 天气 怎么样" \ --layer 0 --head 3 --output layer0_head3.png # Generate a short continuation first, then visualize the whole sequence python attention_cli.py --prompt "Explain attention in one sentence." \ --max-new-tokens 40 # Compare how the attention sink emerges across layers, side by side python attention_cli.py --compare-layers 0 13 -1 --output layer_compare.png
运行 python attention_cli.py --help 查看完整参数列表。关键参数:
| 参数 | 含义 | 默认值 |
|---|---|---|
-p, --prompt |
要可视化的文本 | 北京 的 天气 怎么样 |
-o, --output |
输出 PNG 路径 | attention_heatmap.png |
-m, --model |
HF 模型名或本地路径 | Qwen/Qwen3-0.6B |
--device |
cuda / mps / cpu |
自动检测 |
-l, --layer |
层索引(-1 = 最后一层) |
-1 |
--head |
头索引(-1 = 对各头取平均) |
-1 |
--compare-layers |
多层并排渲染 | 关闭 |
--max-new-tokens |
捕获注意力前先生成 N 个 token | 0 |
--no-chat-template |
直接喂原始 prompt(不加 `< | im_start |
--cmap |
matplotlib 配色 | viridis |
热力图怎么看。 行是 Query 位置(发起注意力的 token),列是 Key 位置(被注意的 token)。该工具会直接基于模型自身的权重测量并打印注意力池占比(attention-sink share)——即每行注意力落到第一个 token 上的比例。在Qwen3-0.6B 上,最后一层的注意力池通常吸收每行约 75–85% 的注意力(即第 2 章"注意力储存池 / Attention Sink"现象),而第 0 层则接近局部的对角线模式。被掩码的上三角让因果"三角形"结构一目了然:每个 token 只能注意到自己及其之前的 token。
首次运行会下载模型权重(约 1–2 GB)。推荐使用 GPU/MPS,但这些短 prompt 在 CPU 上也能跑。
可视化过程也可以拆分为两个手动步骤:生成轨迹,再在前端查看。
选择以下任一方式生成轨迹数据:
# Option A: Run basic attention tracking demo python agent.py # Option B: Run ReAct agent with tool calling (demonstrates multi-step reasoning) python main.py
每次运行都会在 frontend/public/trajectories/ 下生成一个带唯一时间戳的轨迹文件。
在另一个终端启动前端服务:
cd frontend npm install # First time only npm run dev
打开浏览器访问 http://localhost:3000
前端可以一直保持运行,同时在第一个终端生成新轨迹——它们会自动出现在界面中。
attention_visualization/ ├── attention_cli.py # Standalone CLI: prompt -> attention heatmap PNG ├── agent.py # Core attention tracking agent ├── main.py # ReAct agent with tool calling ├── tools.py # Tool implementations ├── visualization.py # Visualization utilities (heatmap / comparison) ├── config.py # Configuration settings ├── requirements.txt # Python dependencies ├── env.example # Environment variable template ├── frontend/ # Next.js frontend │ ├── pages/ # React pages │ ├── components/ # Visualization components │ └── public/ │ └── trajectories/ # Stored trajectory JSONs │ ├── trajectory_YYYYMMDD_HHMMSS.json │ └── manifest.json # Index of all trajectories └── attention_data/ # Additional trajectory storage
agent.pymain.py两个脚本都会:
frontend/public/trajectories/每条轨迹 JSON 包含:
{ "id": "20250914_123456", "timestamp": "2025-09-14 12:34:56", "test_case": { "category": "Math", "query": "What is 25 * 37?", "description": "Agent trajectory from..." }, "response": "The answer is...", "tokens": ["What", "is", "25", ...], "attention_data": { "tokens": [...], "attention_matrix": [[...]], "num_layers": 1, "num_heads": 16 }, "metadata": {...} }
React 前端:
编辑 demonstrate_attention_tracking() 函数以添加自定义查询:
test_prompts = [ ("Your custom query here", "Category"), # Add more queries... ]
ReAct Agent 演示了工具使用与多步推理。请在 demonstrate_react_agent() 中编辑测试查询。
你也可以通过编程方式使用 Agent:
from agent import AttentionVisualizationAgent agent = AttentionVisualizationAgent() result = agent.generate_with_attention( "Your query here", max_new_tokens=100, temperature=0.3, save_trajectory=True, category="Custom" )
requirements.txtfrontend/package.json克隆仓库
设置环境变量(可选):
cp env.example .env # Edit .env to customize model, device, and visualization settings
pip install -r requirements.txt
cd frontend npm install
agent.py 和 main.py 以查看不同的注意力模式main.py(带工具)和 agent.py(不带工具),看工具使用如何影响注意力agent.py 或 main.pyfrontend/public/trajectories/ 下是否存在轨迹文件manifest.json 存在且包含轨迹条目npm installmax_new_tokens 以加快演示agent.py 和 main.py 都可多次运行以生成不同的轨迹