一个CLI工具和MCP(模型上下文协议)服务器,用于查询和分析TensorBoard事件文件,无需运行TensorBoard服务器。
tb-query 允许您直接与 TensorBoard 的 events.out.tfevents.* 文件交互,以提取标量数据、计算统计信息、查找相关性等。它特别适用于:
pip install tb-query
git clone https://github.com/Alir3z4/tb-query.git
cd tb-query
pip install -e .
从TensorBoard事件文件中提取标量数据:
# 查询所有可用标签
tb-query query path/to/events.out.tfevents.12345
# 查询特定标签
tb-query query path/to/events.out.tfevents.12345 --tags loss --tags accuracy
# 使用步数范围过滤查询
tb-query query path/to/events.out.tfevents.12345 --start_step 100 --end_step 120
# 组合过滤器
tb-query query path/to/events.out.tfevents.12345 --tags loss --start_step 100 --end_step 200
输出格式(JSON):
{
"loss": [
{"step": 100, "value": 0.5},
{"step": 101, "value": 0.48}
],
"accuracy": [
{"step": 100, "value": 0.85},
{"step": 101, "value": 0.86}
]
}
列出事件文件中的所有可用标量标签:
# 列出所有标签
tb-query tags path/to/events.out.tfevents.12345
# 过滤包含特定字符串的标签
tb-query tags path/to/events.out.tfevents.12345 --filter loss
tb-query tags path/to/events.out.tfevents.12345 --filter loss --filter accuracy
输出格式(JSON):
{
"tags": ["train/loss", "train/accuracy", "eval/loss", "eval/accuracy"]
}
在目录中查找所有TensorBoard事件文件:
tb-query find path/to/logs
输出格式(JSON):
{
"event_files": [
{
"path": "path/to/logs/run1/events.out.tfevents.12345",
"created_at": "2025-11-04T10:30:00.123456"
},
{
"path": "path/to/logs/run2/events.out.tfevents.67890",
"created_at": "2025-11-03T15:20:00.654321"
}
]
}
文件按创建时间排序(最新优先)。
获取特定标签的步数:
tb-query steps path/to/events.out.tfevents.12345 --tags loss --tags accuracy
输出格式(JSON):
{
"loss": [0, 10, 20, 30, 40, 50],
"accuracy": [0, 10, 20, 30, 40, 50]
}
计算标签值的统计措施:
tb-query stats path/to/events.out.tfevents.12345 --tags loss --tags accuracy
输出格式(JSON):
{
"loss": {
"min": 0.15,
"max": 2.34,
"mean": 0.85,
"std": 0.42,
"count": 1000
},
"accuracy": {
"min": 0.65,
"max": 0.98,
"mean": 0.87,
"std": 0.08,
"count": 1000
}
}
计算标量标签之间的皮尔逊相关性:
# 基本相关性
tb-query correlation path/to/events.out.tfevents.12345 --tags "loss,accuracy"
# 使用步数范围
tb-query correlation path/to/events.out.tfevents.12345 --tags "loss,accuracy" --start_step 100 --end_step 200
# 显示解释
tb-query correlation path/to/events.out.tfevents.12345 --tags "loss,accuracy" --display-interpretation true
# 自定义舍入
tb-query correlation path/to/events.out.tfevents.12345 --tags "loss,accuracy" --rounding 6
无解释输出格式(JSON):
{
"loss": {
"accuracy": -0.9234,
"learning_rate": 0.1234
}
}
有解释输出格式(JSON):
{
"loss": {
"accuracy": {
"correlation": -0.9234,
"interpretation": "强负相关"
}
}
}
tb-query 提供了一个MCP(模型上下文协议)服务器,使AI编码助手能够与TensorBoard事件文件交互。这允许代理分析训练运行,提取指标并提供见解。
tb-query-mcp
服务器将启动并监听兼容客户端的MCP连接。
您可以设置 TB_QUERY_EVENTS_PATH 环境变量来指定事件文件的默认目录:
export TB_QUERY_EVENTS_PATH=/path/to/tensorboard/logs
tb-query-mcp
这会启用 event_files 资源,该资源会自动列出指定目录中的可用事件文件。
向您的Claude Desktop配置文件添加以下配置:
macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
Windows: %APPDATA%\Claude\claude_desktop_config.json
{
"mcpServers": {
"tb-query": {
"command": "tb-query-mcp",
"env": {
"TB_QUERY_EVENTS_PATH": "/path/to/your/tensorboard/logs"
}
}
}
}
添加配置后,请重启Claude Desktop。tb-query工具将可用于Claude分析您的训练运行。
向您的Cline MCP设置文件(工作区中的 .cline/mcp_settings.json)添加以下内容:
{
"mcpServers": {
"tb-query": {
"command": "tb-query-mcp",
"env": {
"TB_QUERY_EVENTS_PATH": "/path/to/your/tensorboard/logs"
}
}
}
}
向您的Zed设置(~/.config/zed/settings.json)添加以下内容:
{
"context_servers": {
"tb-query": {
"command": "tb-query-mcp",
"env": {
"TB_QUERY_EVENTS_PATH": "/path/to/your/tensorboard/logs"
}
}
}
}
向您的Continue配置文件(~/.continue/config.json)添加以下内容:
{
"mcpServers": [
{
"name": "tb-query",
"command": "tb-query-mcp",
"env": {
"TB_QUERY_EVENTS_PATH": "/path/to/your/tensorboard/logs"
}
}
]
}
您还可以使用MCP协议将tb-query集成到自己的Python脚本中:
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
server_params = StdioServerParameters(
command="tb-query-mcp",
env={"TB_QUERY_EVENTS_PATH": "/path/to/logs"}
)
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
# 调用工具
result = await session.call_tool("list_tags", {
"event_file": "/path/to/events.out.tfevents.12345"
})
print(result)
当作为MCP服务器运行时,tb-query提供了以下工具:
从TensorBoard事件文件查询标量数据。
参数:
event_file (字符串,必需):事件文件路径tags (字符串列表,可选):要查询的标签列表(默认:所有标签)start_step (整数,可选):起始步数(包括)end_step (整数,可选):结束步数(包括)获取所有可用的标量标签,并可选地进行过滤。
参数:
event_file (字符串,必需):事件文件路径filters (字符串列表,可选):过滤包含这些字符串的标签在目录及其子目录中查找所有TensorBoard事件文件。
参数:
directory (字符串,必需):搜索的目录路径获取指定标签的步数。
参数:
event_file (字符串,必需):事件文件路径tags (字符串列表,必需):标签列表获取指定标签的统计信息。
参数:
event_file (字符串,必需):事件文件路径tags (字符串列表,必需):标签列表计算标量标签之间的相关性。
参数:
event_file (字符串,必需):事件文件路径tags (字符串列表,必需):要计算相关性的标签start_step (整数,可选):起始步数end_step (整数,可选):结束步数当设置了 TB_QUERY_EVENTS_PATH 时,此资源会提供从配置目录中获取的所有可用事件文件列表。
URI: resource://event-files
# 检查最新的损失值
tb-query query events.out.tfevents.12345 --tags train/loss --start_step 990
# 比较训练和验证指标
tb-query query events.out.tfevents.12345 --tags train/loss --tags val/loss
# 获取关键指标的统计信息
tb-query stats events.out.tfevents.12345 --tags train/accuracy --tags val/accuracy
# 查找指标之间的相关性
tb-query correlation events.out.tfevents.12345 --tags "loss,learning_rate" --display-interpretation true
当通过MCP与AI编码助手集成时,您可以简单地询问:
AI代理将自动使用适当的tb-query工具来获取和分析数据。
您也可以直接在Python代码中使用tb-query:
from tb_query.core import (
query_tensorboard,
get_all_tags,
find_event_files,
get_tag_statistics,
calculate_correlation
)
# 查询数据
data = query_tensorboard(
"events.out.tfevents.12345",
tags=["loss", "accuracy"],
start_step=100,
end_step=200
)
# 获取标签
tags = get_all_tags("events.out.tfevents.12345", filters=["loss"])
# 获取统计信息
stats = get_tag_statistics("events.out.tfevents.12345", tags=["loss"])
# 计算相关性
correlation = calculate_correlation(
data,
tags={"loss"},
rounding=4,
display_interpretation=True
)
import json
import subprocess
# 查找所有事件文件
result = subprocess.run(
["tb-query", "find", "logs/"],
capture_output=True,
text=True
)
event_files = json.loads(result.stdout)
# 查询最近的文件
latest_file = event_files["event_files"][0]["path"]
result = subprocess.run(
["tb-query", "query", latest_file, "--tags", "loss"],
capture_output=True,
text=True
)
data = json.loads(result.stdout)
# 处理数据
print(f"最终损失: {data['loss'][-1]['value']}")
tb-query的主要目的是提供一个Python库,以便程序化访问TensorBoard数据。所有功能都可通过 tb_query.core 模块获得:
from tb_query.core import (
query_tensorboard,
get_all_tags,
find_event_files,
get_tag_steps,
get_tag_statistics,
calculate_correlation,
ValidationError
)
# 在目录中查找所有事件文件
try:
result = find_event_files("logs/")
event_files = result["event_files"]
print(f"找到 {len(event_files)} 个事件文件")
# 使用最近的文件
latest_file = event_files[0]["path"]
print(f"分析: {latest_file}")
except ValidationError as e:
print(f"错误: {e.message}")
# 获取所有可用标签
try:
tags_result = get_all_tags(latest_file)
all_tags = tags_result["tags"]
print(f"可用标签: {all_tags}")
# 过滤包含“loss”的标签
loss_tags = get_all_tags(latest_file, filters=["loss"])
print(f"与损失相关的标签: {loss_tags['tags']}")
except ValidationError as e:
print(f"错误: {e.message}")
# 使用步数过滤查询特定标签
try:
data = query_tensorboard(
event_file=latest_file,
tags=["train/loss", "val/loss"],
start_step=100,
end_step=500
)
for tag, values in data.items():
print(f"\n{tag}:")
print(f" 第一个值: step={values[0]['step']}, value={values[0]['value']}")
print(f" 最后一个值: step={values[-1]['step']}, value={values[-1]['value']}")
print(f" 总点数: {len(values)}")
except ValidationError as e:
print(f"错误: {e.message}")
# 获取标签的统计信息
try:
stats = get_tag_statistics(latest_file, tags=["train/loss", "train/accuracy"])
for tag, stat in stats.items():
if "error" in stat:
print(f"{tag}: {stat['error']}")
else:
print(f"\n{tag} 统计信息:")
print(f" 最小值: {stat['min']:.4f}")
print(f" 最大值: {stat['max']:.4f}")
print(f" 平均值: {stat['mean']:.4f}")
print(f" 标准差: {stat['std']:.4f}")
print(f" 数量: {stat['count']}")
except ValidationError as e:
print(f"错误: {e.message}")
# 获取特定标签的可用步数
try:
steps = get_tag_steps(latest_file, tags=["train/loss", "val/loss"])
for tag, step_list in steps.items():
print(f"{tag}: {len(step_list)} 步")
print(f" 范围: {step_list[0]} 至 {step_list[-1]}")
except ValidationError as e:
print(f"错误: {e.message}")
# 计算相关性
try:
# 首先查询数据
data = query_tensorboard(
event_file=latest_file,
tags=None, # 获取所有标签
start_step=0,
end_step=1000
)
# 计算特定标签的相关性
correlation = calculate_correlation(
data=data,
tags={"train/loss"}, # 对比其他标签的主要标签
rounding=4,
display_interpretation=False
)
print("\n与train/loss的相关性:")
for other_tag, corr_value in correlation["train/loss"].items():
print(f" {other_tag}: {corr_value}")
# 带解释
correlation_interpreted = calculate_correlation(
data=data,
tags={"train/loss"},
rounding=4,
display_interpretation=True
)
print("\n带解释的相关性:")
for other_tag, corr_data in correlation_interpreted["train/loss"].items():
print(f" {other_tag}:")
print(f" 相关性: {corr_data['correlation']}")