tb查询
一个CLI工具和MCP(模型上下文协议)服务器,用于查询和分析TensorBoard事件文件,而不需要运行TensorBoard服务器。
概述
tb查询允许您直接与TensorBoard的 events.out.tfevents.* 用于提取标量数据、计算统计数据、查找相关性等的文件。它特别适用于:
- 通过程序访问培训指标
- 训练运行的自动分析
- 通过MCP与AI编码代理集成
- 无需启动web服务器即可快速检查TensorBoard日志
特性
- 使用步长和标签过滤查询标量数据
- 在目录树中查找所有TensorBoard事件文件
- 列出可用的标量标签,并可选择过滤
- 计算特定标签的统计数据(最小值、最大值、平均值、标准差)
- 计算不同标量度量之间的相关性
- 用于命令行使用的CLI界面
- MCP服务器,用于与AI编码助手集成
安装
来自PyPI
pip install tb-query来源
git clone https://github.com/Alir3z4/tb-query.git
cd tb-query
pip install -e .需求
- Python>=3.11
- 张量板
- fastmcp
- 熊猫
CLI使用情况
Query命令
从TensorBoard事件文件中提取标量数据:
# Query all available tags
tb-query query path/to/events.out.tfevents.12345
# Query specific tags
tb-query query path/to/events.out.tfevents.12345 --tags loss --tags accuracy
# Query with step range filtering
tb-query query path/to/events.out.tfevents.12345 --start_step 100 --end_step 200
# Combine filters
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}
]
}标签命令
列出事件文件中的所有可用标量标记:
# List all tags
tb-query tags path/to/events.out.tfevents.12345
# Filter tags containing specific strings
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"]
}find命令
在目录中找到所有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
}
}关联命令
计算标量标签之间的Pearson相关性:
# Basic correlation
tb-query correlation path/to/events.out.tfevents.12345 --tags "loss,accuracy"
# With step range
tb-query correlation path/to/events.out.tfevents.12345 --tags "loss,accuracy" --start_step 100 --end_step 200
# With interpretation
tb-query correlation path/to/events.out.tfevents.12345 --tags "loss,accuracy" --display-interpretation true
# Custom rounding
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": "Strong negative correlation"
}
}
}MCP服务器使用情况
tb query提供了一个MCP(模型上下文协议)服务器,使AI编码助手能够与TensorBoard事件文件进行交互。这允许代理分析训练运行、提取指标并提供见解。
启动MCP服务器
tb-query-mcp服务器将启动并监听来自兼容客户端的MCP连接。
环境变量
您可以设置 TB_QUERY_EVENTS_PATH 环境变量,用于指定事件文件的默认目录:
export TB_QUERY_EVENTS_PATH=/path/to/tensorboard/logs
tb-query-mcp这使得 event_files 资源,它自动列出指定目录中的可用事件文件。
与AI编码代理集成
克劳德桌面
将以下配置添加到您的Claude Desktop配置文件中:
macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
视窗: %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查询工具将可供Claude在分析您的训练运行时使用。
Cline(VS代码扩展)
添加到Cline MCP设置文件(.cline/mcp_settings.json 在您的工作空间中):
{
"mcpServers": {
"tb-query": {
"command": "tb-query-mcp",
"env": {
"TB_QUERY_EVENTS_PATH": "/path/to/your/tensorboard/logs"
}
}
}
}Zed编辑
添加到Zed设置(~/.config/zed/settings.json):
{
"context_servers": {
"tb-query": {
"command": "tb-query-mcp",
"env": {
"TB_QUERY_EVENTS_PATH": "/path/to/your/tensorboard/logs"
}
}
}
}继续(VS代码扩展)
添加到Continue配置文件(~/.continue/config.json):
{
"mcpServers": [
{
"name": "tb-query",
"command": "tb-query-mcp",
"env": {
"TB_QUERY_EVENTS_PATH": "/path/to/your/tensorboard/logs"
}
}
]
}使用Python客户端
您还可以使用MCP协议将tb查询集成到您自己的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()
# Call tools
result = await session.call_tool("list_tags", {
"event_file": "/path/to/events.out.tfevents.12345"
})
print(result)可用的MCP工具
当作为MCP服务器运行时,tb query提供以下工具:
怎么翻译
从TensorBoard事件文件中查询标量数据。
参数:
event_file(string,必填):事件文件的路径tags(list\[string\],可选):要查询的标签列表(默认:所有标签)start_step(整数,可选):开始步骤(含)end_step(整数,可选):结束步骤(含)
list_tags
通过可选过滤获取所有可用的标量标签。
参数:
event_file(string,必填):事件文件的路径filters(list\[string\],可选):过滤包含这些字符串的标签
find_事件
在目录和子目录中查找所有TensorBoard事件文件。
参数:
directory(字符串,必填):要搜索的目录路径
tag_steps
获取指定标签的步骤编号。
参数:
event_file(string,必填):事件文件的路径tags(list\[string\],必填):标签列表
tag_stats
获取指定标签的统计度量。
参数:
event_file(string,必填):事件文件的路径tags(list\[string\],必填):标签列表
相关性
计算标量标签之间的相关性。
参数:
event_file(string,必填):事件文件的路径tags(list\[string\],必填):用于计算相关性的标签start_step(整数,可选):开始步骤end_step(整数,可选):结束步骤
可用MCP资源
事件文件
当 TB_QUERY_EVENTS_PATH 设置后,此资源将提供配置目录中所有可用事件文件的列表。
URI: resource://event-files
示例用例
监控培训进度
# Check latest loss values
tb-query query events.out.tfevents.12345 --tags train/loss --start_step 990
# Compare train and validation metrics
tb-query query events.out.tfevents.12345 --tags train/loss --tags val/loss分析模型性能
# Get statistics for key metrics
tb-query stats events.out.tfevents.12345 --tags train/accuracy --tags val/accuracy
# Find correlations between metrics
tb-query correlation events.out.tfevents.12345 --tags "loss,learning_rate" --display-interpretation trueAI代理集成
当通过MCP与AI编码助手集成时,您可以简单地问:
- “分析我的日志目录中的最新训练运行”
- “损失和学习率之间有什么关系?”
- “显示准确性指标的统计数据”
- “比较训练和验证丢失的最后100个步骤”
AI代理将自动使用适当的tb查询工具来获取和分析数据。
Python API
你也可以在Python代码中直接使用tb查询:
from tb_query.core import (
query_tensorboard,
get_all_tags,
find_event_files,
get_tag_statistics,
calculate_correlation
)
# Query data
data = query_tensorboard(
"events.out.tfevents.12345",
tags=["loss", "accuracy"],
start_step=100,
end_step=200
)
# Get tags
tags = get_all_tags("events.out.tfevents.12345", filters=["loss"])
# Get statistics
stats = get_tag_statistics("events.out.tfevents.12345", tags=["loss"])
# Calculate correlation
correlation = calculate_correlation(
data,
tags={"loss"},
rounding=4,
display_interpretation=True
)自动分析脚本
import json
import subprocess
# Find all event files
result = subprocess.run(
["tb-query", "find", "logs/"],
capture_output=True,
text=True
)
event_files = json.loads(result.stdout)
# Query the most recent file
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)
# Process the data
print(f"Final loss: {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
)
# Find all event files in a directory
try:
result = find_event_files("logs/")
event_files = result["event_files"]
print(f"Found {len(event_files)} event files")
# Use the most recent file
latest_file = event_files[0]["path"]
print(f"Analyzing: {latest_file}")
except ValidationError as e:
print(f"Error: {e.message}")
# Get all available tags
try:
tags_result = get_all_tags(latest_file)
all_tags = tags_result["tags"]
print(f"Available tags: {all_tags}")
# Filter tags containing "loss"
loss_tags = get_all_tags(latest_file, filters=["loss"])
print(f"Loss-related tags: {loss_tags['tags']}")
except ValidationError as e:
print(f"Error: {e.message}")
# Query specific tags with step filtering
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" First value: step={values[0]['step']}, value={values[0]['value']}")
print(f" Last value: step={values[-1]['step']}, value={values[-1]['value']}")
print(f" Total points: {len(values)}")
except ValidationError as e:
print(f"Error: {e.message}")
# Get statistics for tags
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} statistics:")
print(f" Min: {stat['min']:.4f}")
print(f" Max: {stat['max']:.4f}")
print(f" Mean: {stat['mean']:.4f}")
print(f" Std: {stat['std']:.4f}")
print(f" Count: {stat['count']}")
except ValidationError as e:
print(f"Error: {e.message}")
# Get available steps for specific tags
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)} steps")
print(f" Range: {step_list[0]} to {step_list[-1]}")
except ValidationError as e:
print(f"Error: {e.message}")
# Calculate correlations
try:
# First query the data
data = query_tensorboard(
event_file=latest_file,
tags=None, # Get all tags
start_step=0,
end_step=1000
)
# Calculate correlation for specific tags
correlation = calculate_correlation(
data=data,
tags={"train/loss"}, # Primary tag(s) to correlate against others
rounding=4,
display_interpretation=False
)
print("\nCorrelations with train/loss:")
for other_tag, corr_value in correlation["train/loss"].items():
print(f" {other_tag}: {corr_value}")
# With interpretation
correlation_interpreted = calculate_correlation(
data=data,
tags={"train/loss"},
rounding=4,
display_interpretation=True
)
print("\nCorrelations with interpretation:")
for other_tag, corr_data in correlation_interpreted["train/loss"].items():
print(f" {other_tag}:")
print(f" Correlation: {corr_data['correlation']}")
print(f" Interpretation: {corr_data['interpretation']}")
except ValidationError as e:
print(f"Error: {e.message}")
# Complete analysis workflow
def analyze_training_run(event_file_path: str):
"""Complete analysis of a training run."""
try:
# Get all tags
tags_result = get_all_tags(event_file_path)
all_tags = tags_result["tags"]
# Get statistics for all tags
stats = get_tag_statistics(event_file_path, tags=all_tags)
# Query recent data (last 100 steps)
data = query_tensorboard(event_file_path, tags=all_tags)
# Get the maximum step across all tags
max_step = 0
for tag_data in data.values():
if tag_data:
max_step = max(max_step, tag_data[-1]["step"])
# Query only recent data
recent_data = query_tensorboard(
event_file_path,
tags=all_tags,
start_step=max(0, max_step - 100),
end_step=max_step
)
# Calculate correlations
correlation = calculate_correlation(
data=data,
tags=set(all_tags[:5]), # Limit to first 5 tags to avoid huge output
rounding=4,
display_interpretation=True
)
return {
"tags": all_tags,
"statistics": stats,
"recent_data": recent_data,
"correlations": correlation,
"max_step": max_step
}
except ValidationError as e:
return {"error": e.message}
# Use the analysis function
result = analyze_training_run("events.out.tfevents.12345")
if "error" in result:
print(f"Analysis failed: {result['error']}")
else:
print(f"Analysis complete: {len(result['tags'])} tags analyzed")
print(f"Training ran for {result['max_step']} steps")中的所有功能 tb_query.core 提高 ValidationError 文件访问或解析错误的异常,因此建议将调用包装在try-except块中,以进行稳健的错误处理。
错误处理
tb查询为常见问题提供了清晰的错误消息:
- 文件未找到:当指定的事件文件不存在时引发
- 未能加载事件文件:当文件损坏或无效时引发
- 找不到目录:当指定的目录不存在时引发
- 未找到标签:当请求的标记不存在时,在统计中返回
- 未找到值:当标签存在但没有数据点时返回
发展
设置开发环境
git clone https://github.com/Alir3z4/tb-query.git
cd tb-query
make install运行测试
_目前,代码库不包括测试,我计划稍后添加它们。_
运行测试
make test以覆盖率运行测试
# Run tests with coverage
make coverage
coverage report代码质量
make lint预提交
有一个makefile任务可以运行格式和类型检查。在提交代码之前使用。
make precommit贡献
欢迎投稿!请随时提交拉取请求。对于重大更改,请先打开一个问题来讨论您想要更改的内容。
许可证
此项目根据GPL-3.0或更高版本的许可证进行许可-有关详细信息,请参阅许可证文件。
链接
- 首页: https://github.com/Alir3z4/tb-query
- 仓库: https://github.com/Alir3z4/tb-query.git
- 问题: https://github.com/Alir3z4/tb-query/issues
- 更新日志: https://github.com/Alir3z4/tb-query/blob/master/ChangeLog.md
支持
如果您遇到任何问题或有疑问,请在GitHub存储库上提交问题。
