跳到主要内容

数据格式、时钟与脚本组合

当 stdout 不是终端时,每个 xprobe 命令都会输出一个严格 JSON 文档(schema_version 为 "3.0" 或 "2.0")。这一页提供精确的字段查表、真实 JSONL 行样例、时钟数学与零前置假设的脚本组合配方。

各模式 stdout 与产物路径查表​

模式stdout 中的产物文件路径stdout 中的核心内联字段
单边 measureevidence.artifact.path(Event JSONL)measurement.{latency_ns, samples}、quality、evidence.exemplars、evidence.pairs(需 --evidence full)
多边 measure --specartifact.path(及各 edges[].evidence.artifact.path)edges[].{name, measurement, quality, evidence}
--python-sampleartifact.path(Python Sample JSONL)inventory.{gil_hotspots, gil_released_proportion, gil_stack_groups, thread_stack_groups, native_waits}、collection
--trigger-*windows[].artifact.path(每窗口一份 Event JSONL)trigger、observed、windows[].{fired, start_ns, end_ns, truncated, longest}、collection
--aggregate无(仅内联)inventory.groups[]、collection.{cuda_devices, dropped_activities, table_utilization}
--cpu-sample无(仅内联)inventory.{hotspots, stack_groups}、symbolization.python_status、collection
--syscall-aggregate无(仅内联)inventory.groups[]、collection
--triagesources[] 中各数据源独立路径sources[]、not_covered、threads、cgroup、cpu_hotspots、python_hotspots、syscalls、gpu_activity、gpu_devices、findings

出错时命令以非零退出码退出并输出错误 JSON(ok: false、error.{code, message, details, hints}),若已生成产物文件,其路径会保留在 details 中。


Event JSONL(*.jsonl)​

每行一个 JSON 对象(schema_version: "2.0"),三类主要事件的真实结构如下:

{"schema_version":"2.0","session_id":"s1","event_id":"e1","sequence":1,"source":"cupti_activity","event_type":"gpu_kernel_start","pid":4242,"tid":0,"timestamp_raw":1000,"timestamp_ns":1000,"clock_domain":"cupti_normalized_to_host_monotonic","cuda":{"device_id":0,"context_id":1,"stream_id":7,"correlation_id":99,"kernel_name":"flash_fwd","grid":{"x":64,"y":1,"z":1},"block":{"x":128,"y":1,"z":1}},"host":null,"nvtx":null,"attributes":{}}
{"schema_version":"2.0","session_id":"s1","event_id":"e2","sequence":2,"source":"cupti_callback","event_type":"cuda_api_exit","pid":4242,"tid":4242,"timestamp_raw":950,"timestamp_ns":950,"clock_domain":"host_monotonic","cuda":{"correlation_id":99,"callback_domain":2,"callback_id":211},"host":null,"nvtx":null,"attributes":{"cuda_api_name":"cudaLaunchKernel","cuda_api_domain":"runtime_api"}}
{"schema_version":"2.0","session_id":"s1","event_id":"e3","sequence":3,"source":"ebpf","event_type":"syscall_exit","pid":4242,"tid":4242,"timestamp_raw":900,"timestamp_ns":900,"clock_domain":"host_monotonic","cuda":null,"host":{"probe_kind":"syscall","symbol":"futex","return_value":0,"arguments":[]},"nvtx":null,"attributes":{}}

写解析脚本时最容易踩坑的 5 个细节:

  1. event_type 完整枚举:gpu_kernel_start|end、gpu_memcpy_start|end、gpu_memset_start|end、cuda_api_entry|exit、nvtx_range_start|end、host_function_entry|exit、kernel_function_entry|exit、syscall_entry|exit、tracepoint、python_gc_start|end、marker。
  2. 名称字段所在位置:
    • Kernel:cuda.kernel_name
    • Memcpy:cuda.memcpy_kind(HtoD|DtoH|DtoD|HtoH|PtoP|unknown)、cuda.bytes
    • CUDA API:attributes.cuda_api_name(注意不在 cuda 对象内!)
    • NVTX:nvtx.name(附 nvtx.range_kind、nvtx.range_id、nvtx.start_tid)
    • Host:host.symbol_demangled / host.symbol / host.binary_path / host.return_value
  3. GPU activity 由两行组成:一条 *_start 与一条 *_end,按 (kind, pid, cuda.device_id, cuda.context_id, cuda.stream_id, cuda.correlation_id, name) 配对。
  4. start_unknown 记录:带有 attributes.get("start_unknown") 的记录表示在 STOP 时仍在运行的活动。它的时间戳被设为该 stream 上一次活动结束时刻(或窗口起点),用于标记 stream 仍处于忙碌状态,不可用于计算 duration、gap 或 latency。
  5. 时钟域比较规则:host_monotonic 与 cupti_normalized_to_host_monotonic 均属于主机 CLOCK_MONOTONIC,可直接互相比对、与 --python-sample 拼表、以及在同一主机跨进程拼表。原始 cupti 时间戳只能与同一次采集内的原始 cupti 比对。时间戳相同时按 sequence 排序。

采集清单(<artifact>.manifest.json)​

每份 Event JSONL 旁都会生成对应的 manifest(schema_version: "1.0")。请将其与 .jsonl 保持同目录,供 measure --input 和 analyze_trace.py 校验完整性与映射设备/时钟:

{
"schema_version": "1.0",
"target": {"pid": 4242, "process_start_time": 987654},
"window": {"start_ns": 1000000, "end_ns": 3000000},
"selectors": ["cuda:kernel_end", "cuda:kernel_start"],
"all_gpu_activity": true,
"peer_copies": true,
"dropped_records": 0,
"unknown_records": 0,
"record_limit_reached": null,
"capture_failed": false,
"cuda_devices": [{"device_id": 0, "uuid": "GPU-xxxx", "gpu_uuid": null}],
"wall_clock": {
"start": {"monotonic_ns": 1000000, "realtime_ns": 1730000000000000000, "uncertainty_ns": 500},
"end": {"monotonic_ns": 3000000, "realtime_ns": 1730000000002000000, "uncertainty_ns": 500}
},
"artifact": {"format": "jsonl", "events": 5000, "bytes": 1234567, "sha256": "..."}
}
  • 只有在 all_gpu_activity: true 时,算出来的 GPU 空闲时间才可信(否则被过滤掉的 kernel 会被误判为空闲)。
  • cuda_devices 将进程局部 device_id(受 CUDA_VISIBLE_DEVICES 影响)映射到物理 uuid(或 MIG uuid + 所属物理 gpu_uuid)。跨进程归并 GPU 时始终按 UUID 分组。

Python Sample JSONL(--python-sample)​

位于 stdout 的 result["artifact"]["path"],每行一条样本:

{"timestamp_ns":1001234,"pid":4242,"tid":4242,"gil":true,"truncated":false,"frames":[{"function":"step","file":"train.py","first_line":40},{"function":"main","file":"train.py","first_line":10}],"native":null}
{"timestamp_ns":1005000,"pid":4242,"tid":4248,"gil":false,"truncated":false,"frames":[{"function":"recv","file":"comm.py","first_line":12}],"native":{"syscall":"futex","module":"libc.so.6","symbol":"__futex_abstimed_wait_common"}}
  • timestamp_ns 为 CLOCK_MONOTONIC,可直接与 Event JSONL 拼表。
  • frames[0] 是最内层栈帧;first_line 是函数定义起始行,不是当前执行行号。
  • gil: true 表示高频 GIL 持有者采样(默认 2000 Hz);gil: false 表示全线程扫描采样(默认 100 Hz),当线程阻塞在系统调用/原生函数时会填充 native。
  • stdout 中的 collection 报告 gil_hz_achieved、inconsistent_reads、tid_source 与 wall_clock。

其它模式核心 stdout 字段速查​

  • 单边 / Graph:measurement.latency_ns.{min, mean, p50, p90, p95, p99, max}、measurement.samples.{matched, unmatched_start, unmatched_end, ambiguous, dropped}、quality.{verdict, issues}、correlation.{method, confidence}、clock.{alignment, estimated_error_ns}、collection.{coverage, cupti, cuda_devices, wall_clock}。status == "timed_out" 时的统计为部分样本。
  • GPU --aggregate:inventory.groups[] 含 activity(kernel|memcpy|memset)、name、name_complete、memcpy_kind、src_memory、dst_memory(pageable 意味着经由临时缓冲的同步拷贝)、device_id、count、total_bytes、duration_ns.{min, mean, max, total}、start_selector_hint、end_selector_hint。
  • CPU --cpu-sample:inventory.hotspots[](frame.{symbol, module_path, language}、exclusive_proportion、inclusive_proportion、entry_selector_hint、return_selector_hint)、inventory.stack_groups[]、symbolization.python_status、collection.{lost_samples, truncated_stacks, threads_attached, threads_observed}。
  • Syscall --syscall-aggregate:inventory.groups[](syscall_name、syscall_number、count、errors、duration_ns.{min, mean, max, total}、entry_selector_hint、exit_selector_hint)。注意阻塞时间包含正常空闲等待。
  • Trigger --trigger-*:trigger.{kind, threshold_ns}、observed.{spans, over_threshold, longest}、windows[](fired、start_ns、end_ns、truncated、longest、artifact)、collection.{overwritten_records, dropped_records, lost_windows, revoked_windows}。

内置确定性分析器(analyze_trace.py)​

随 Skill 一并分发的 scripts/analyze_trace.py 已实现区间并集、跨流预算与垂直切片,避免重复手写易错的区间合并逻辑:

# 单份 trace:按 GPU 统计 busy/idle/compute/comm/transfer、kernel、memcpy 带宽与 stream gap
analyze_trace.py trace.jsonl --comm-kernel 'nccl|custom_allreduce'

# 对最大 GPU 空闲气泡做垂直切片,并叠加并发 Python 采样栈
analyze_trace.py trace.jsonl --slice-gap 1 --window-ms 2 --python-samples py.jsonl

# 对最慢测量对或指定 CLOCK_MONOTONIC 区间切片
analyze_trace.py trace.jsonl --measurement res.json --slice-outlier 1
analyze_trace.py trace.jsonl --around 1000000:2000000 --python-samples py.jsonl

# 同主机多 rank / 多进程对比(在共享时间窗内计算各卡预算占比)
analyze_trace.py rank0.jsonl rank1.jsonl rank2.jsonl rank3.jsonl

核心输出字段:devices[](uuid、span、busy_ns、idle_ns、compute_ns、communication_ns、communication_only_ns、transfer_ns、top_idle_gaps、top_compute_gaps)、kernels.by_name[](含 selector_hint 与 launch_variants)、memcpy(bandwidth_gbps)、streams[].top_gaps、gpu.top_idle_gaps、slice(含 python)、warnings(WALL_CLOCK_DRIFT、GPU_ACTIVITY_COVERAGE_UNKNOWN、CAPTURE_INCOMPLETE)。多 trace 模式额外输出 devices[].shares 与 spread(compute_share、most_compute、most_communication_only、most_idle)。--comm-kernel 默认正则为 nccl(非锚定,可匹配 _Z40ncclDevKernel_AllReduce...),自定义集合通信(vLLM、TRT-LLM、FlashInfer、NVSHMEM/DeepEP)时可按需扩展。


可组合脚本配方​

1. 配对 GPU 区间并计算真实设备 busy/idle(避免并发重叠重复累加)​

import collections, json

def load_gpu_intervals(jsonl_path):
starts, intervals = collections.defaultdict(collections.deque), []
for line in open(jsonl_path):
e = json.loads(line)
t = e["event_type"]
if not t.startswith("gpu_") or e.get("attributes", {}).get("start_unknown"):
continue
c = e["cuda"]
kind = t.split("_")[1] # kernel | memcpy | memset
name = c.get("kernel_name") or c.get("memcpy_kind") or "memset"
key = (kind, e["pid"], c["device_id"], c["context_id"], c["stream_id"], c["correlation_id"], name)
if t.endswith("_start"):
starts[key].append(e)
elif starts[key]:
s = starts[key].popleft()
intervals.append((s["timestamp_ns"], e["timestamp_ns"], kind, name, c["device_id"], c["stream_id"], s["clock_domain"]))
return intervals

def merge_union(spans): # [(start_ns, end_ns), ...] -> 不重叠的合并区间
merged = []
for s, e in sorted(spans):
if merged and s <= merged[-1][1]:
merged[-1] = (merged[-1][0], max(merged[-1][1], e))
else:
merged.append((s, e))
return merged

2. 跨进程 / 跨数据源时间线拼表(同主机)​

对不同进程并发运行 xprobe measure --pid ...(例如 API 进程 --python-sample + GPU worker Event JSONL,或两张卡的 rank)。host_monotonic、cupti_normalized_to_host_monotonic 与 Python 样本的 timestamp_ns 共享主机 CLOCK_MONOTONIC:

HOST_CLOCKS = {"host_monotonic", "cupti_normalized_to_host_monotonic"}
t0, t1 = gap_start_ns - 2_000_000, gap_end_ns + 2_000_000
py_in_gap = [json.loads(l) for l in open("api_py.jsonl") if t0 <= json.loads(l)["timestamp_ns"] <= t1]
gpu_in_gap = [
e for e in map(json.loads, open("worker_gpu.jsonl"))
if e["clock_domain"] in HOST_CLOCKS and t0 <= e["timestamp_ns"] <= t1
]

跨主机 trace 的 CLOCK_MONOTONIC 互不相关:请比较归一化占比(idle_ns / span_ns),或通过各自 manifest 的 wall_clock 换算到 UTC。

3. 将 CLOCK_MONOTONIC 换算为 UTC 墙钟(对齐业务日志)​

wc = json.load(open("trace.jsonl.manifest.json"))["wall_clock"]
def mono_to_utc_ns(t_ns):
a = min((wc["start"], wc["end"]), key=lambda x: abs(t_ns - x["monotonic_ns"]))
return a["realtime_ns"] + (t_ns - a["monotonic_ns"])

可顺手校验 abs((wc["end"]["realtime_ns"] - wc["end"]["monotonic_ns"]) - (wc["start"]["realtime_ns"] - wc["start"]["monotonic_ns"])):差值过大说明采集期间系统墙钟发生了漂移或跳变。

4. RSI 闭环中的定量前后对比​

优化前后使用完全相同的 --spec(或 CLI 参数与窗口上限):

  • 先校验守卫条件:ok == True、无丢包、检查 quality.verdict(对比 idle_ns 时额外确认 all_gpu_activity == True)。
  • 直接对比机器可读指标:
    • 延迟边:measurement.latency_ns["p50"] 与 ["p95"]
    • GPU 预算(analyze_trace.py):devices[0]["compute_ns"]、["idle_ns"]、["communication_only_ns"] 或 kernels["by_name"]
    • Python GIL(--python-sample):inventory["gil_released_proportion"] 与头部 inventory["gil_hotspots"]
    • 拷贝开销(--aggregate):按 (memcpy_kind, src_memory, dst_memory) 分组的 inventory["groups"]

JSON Schemas 完整索引​

全部 26 个自动生成的 JSON Schema、必填/可选字段与核心枚举值见 JSON 接口规范。