trace-artifact / instrumented_case /analysis /window_telemetry.py
idacy's picture
TRACE artifact: framework, corpus, instrumented case, provider case, evaluators, figures
2955ecc verified
Raw
History Blame Contribute Delete
19.4 kB
#!/usr/bin/env python3
"""
Per-window telemetry aggregation for the instrumented multi-node case.
Reduces the raw collector NDJSON of one labelled run to the per-window,
per-node and participant-averaged aggregates. Standard library only.
python3 window_telemetry.py --run-dir <run> --out-dir <derived>
<run> holds one directory per node, each carrying what `collect.py` and the
orchestrator wrote for that node:
<run>/<node>/manifest.json
<run>/<node>/windows_rank<R>.ndjson window bounds and return codes
<run>/<node>/gpu.<UTCDATE>.ndjson DCGM samples
<run>/<node>/fabric.<UTCDATE>.ndjson interface counters
<run>/<node>/disk.<UTCDATE>.ndjson block-device counters
<run>/<node>/ground_truth/*.json per-window workload ground truth
Conventions:
* The rank of a node is taken from the name of its windows file. A node's
samples are attributed to a window using that node's own window bounds,
never another node's.
* The participant set of a window is the ranks whose window record carries a
non-empty `return_codes` list. Non-participants idle through the window and
are excluded from the participant average.
* Activity and power are arithmetic means of the DCGM `sm_active`,
`tensor_active` and `power_w` fields over the samples inside the window.
Missing fields are skipped, never read as zero, and the number of samples
behind every mean is reported alongside it.
* Fabric volume is the sum of the non-negative successive differences of
`tx_bytes + rx_bytes` on one named Ethernet interface (default `bond0`),
over the samples inside the window. The rate divides that volume by the
span between the first and last sample used, not by the nominal window
duration, so a collector gap lowers the volume instead of raising the
rate.
* Disk write volume is computed per block device from `sectors_written`
(512 bytes per sector) by the same successive-difference rule, and the
window keeps the single busiest device rather than summing devices,
because partitions and device-mapper targets double-count the same writes.
* Counters are monotonic, so a negative successive difference means a
counter reset or a device reappearing; such a step contributes zero rather
than a negative volume, and the number of resets seen is reported.
"""
from __future__ import annotations
import argparse
import csv
import json
import re
import sys
from pathlib import Path
from typing import Any, Iterable
BYTES_PER_SECTOR = 512
MB = 1.0e6
GPU_MEAN_FIELDS = (
"sm_active",
"tensor_active",
"gr_engine_active",
"dram_active",
"power_w",
"gpu_util",
"fb_used_mib",
"temp_c",
)
WINDOWS_RE = re.compile(r"^windows_rank(\d+)\.ndjson$")
# --------------------------------------------------------------------- input
def read_ndjson(path: Path) -> Iterable[dict[str, Any]]:
with path.open(encoding="utf-8") as handle:
for line in handle:
line = line.strip()
if not line:
continue
try:
yield json.loads(line)
except json.JSONDecodeError:
continue
def discover_nodes(run_dir: Path) -> list[dict[str, Any]]:
"""One entry per node directory, with its rank and its window records."""
nodes = []
for node_dir in sorted(p for p in run_dir.iterdir() if p.is_dir()):
windows_files = [p for p in node_dir.iterdir() if WINDOWS_RE.match(p.name)]
if not windows_files:
continue
windows_path = sorted(windows_files)[0]
rank = int(WINDOWS_RE.match(windows_path.name).group(1))
windows = []
for record in read_ndjson(windows_path):
windows.append(
{
"id": record["id"],
"t_start": float(record["t_start"]),
"t_end": float(record["t_end"]),
"duration_s": float(record.get("duration_s", 0.0)),
"participant": bool(record.get("return_codes")),
"return_codes": record.get("return_codes", []),
"error": record.get("error"),
}
)
manifest = {}
manifest_path = node_dir / "manifest.json"
if manifest_path.exists():
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
nodes.append(
{
"node": node_dir.name,
"rank": rank,
"dir": node_dir,
"windows": windows,
"hardware": manifest.get("driver_and_gpus"),
"sampling": manifest.get("sampling"),
}
)
return sorted(nodes, key=lambda n: n["rank"])
def window_index(windows: list[dict[str, Any]]):
"""Return a lookup from a timestamp in seconds to a window position."""
bounds = [(w["t_start"], w["t_end"], i) for i, w in enumerate(windows)]
bounds.sort()
def locate(ts: float) -> int | None:
for start, end, position in bounds:
if start <= ts <= end:
return position
if ts < start:
return None
return None
return locate
# ------------------------------------------------------------ per-node passes
def gpu_pass(node: dict[str, Any], locate) -> list[dict[str, Any]]:
"""Means of the DCGM fields over the samples inside each window."""
acc = [
{"sums": {f: 0.0 for f in GPU_MEAN_FIELDS},
"counts": {f: 0 for f in GPU_MEAN_FIELDS},
"samples": 0,
"fallback_samples": 0,
"first_ts": None,
"last_ts": None}
for _ in node["windows"]
]
for path in sorted(node["dir"].glob("gpu.*.ndjson")):
for record in read_ndjson(path):
ts = record.get("ts")
if ts is None:
continue
position = locate(ts / 1000.0)
if position is None:
continue
bucket = acc[position]
bucket["samples"] += 1
if record.get("src") != "dcgm":
bucket["fallback_samples"] += 1
if bucket["first_ts"] is None:
bucket["first_ts"] = ts / 1000.0
bucket["last_ts"] = ts / 1000.0
for field in GPU_MEAN_FIELDS:
value = record.get(field)
if isinstance(value, (int, float)):
bucket["sums"][field] += float(value)
bucket["counts"][field] += 1
return acc
def counter_pass(
node: dict[str, Any],
locate,
glob_pattern: str,
key_of,
value_of,
) -> list[dict[str, dict[str, float]]]:
"""Successive-difference volumes per counter key, per window.
`key_of` names the series a record belongs to (an interface or a block
device) and `value_of` extracts its monotonic counter value.
"""
acc: list[dict[str, dict[str, float]]] = [dict() for _ in node["windows"]]
last: dict[str, tuple[float, float]] = {}
for path in sorted(node["dir"].glob(glob_pattern)):
for record in read_ndjson(path):
ts = record.get("ts")
if ts is None:
continue
key = key_of(record)
if key is None:
continue
value = value_of(record)
if value is None:
continue
ts = ts / 1000.0
previous = last.get(key)
last[key] = (ts, value)
if previous is None:
continue
position = locate(ts)
if position is None:
continue
# Only pair up samples that both fall inside the same window.
if not (node["windows"][position]["t_start"] <= previous[0]
<= node["windows"][position]["t_end"]):
continue
series = acc[position].setdefault(
key, {"volume": 0.0, "resets": 0, "samples": 0,
"first_ts": previous[0], "last_ts": ts},
)
delta = value - previous[1]
if delta < 0:
series["resets"] += 1
else:
series["volume"] += delta
series["samples"] += 1
series["last_ts"] = ts
return acc
def fabric_pass(node, locate, interface: str):
return counter_pass(
node,
locate,
"fabric.*.ndjson",
key_of=lambda r: r.get("dev") if r.get("class") == "eth" else None,
value_of=lambda r: (
float(r["tx_bytes"]) + float(r["rx_bytes"])
if isinstance(r.get("tx_bytes"), (int, float))
and isinstance(r.get("rx_bytes"), (int, float))
else None
),
)
def disk_pass(node, locate):
return counter_pass(
node,
locate,
"disk.*.ndjson",
key_of=lambda r: r.get("dev"),
value_of=lambda r: (
float(r["sectors_written"]) * BYTES_PER_SECTOR
if isinstance(r.get("sectors_written"), (int, float))
else None
),
)
def clock_pass(node, locate) -> list[dict[str, Any]]:
"""Clock-channel delivery, kept as a three-state coverage record."""
acc = [
{"samples": 0, "offset_samples": 0, "sources": set()}
for _ in node["windows"]
]
for path in sorted(node["dir"].glob("clock.*.ndjson")):
for record in read_ndjson(path):
ts = record.get("ts")
if ts is None:
continue
position = locate(ts / 1000.0)
if position is None:
continue
acc[position]["samples"] += 1
acc[position]["sources"].add(record.get("src"))
if isinstance(record.get("system_time_offset_s"), (int, float)):
acc[position]["offset_samples"] += 1
return [
{
"samples": a["samples"],
"offset_samples": a["offset_samples"],
"sources": sorted(s for s in a["sources"] if s),
# No offset value at all is a delivery gap, not a zero offset.
"offset_state": "observed" if a["offset_samples"] else
("synchronization_flag_only" if a["samples"] else "missing"),
}
for a in acc
]
# --------------------------------------------------------------- aggregation
def rate(volume: float, first_ts: float | None, last_ts: float | None) -> float | None:
if first_ts is None or last_ts is None:
return None
span = last_ts - first_ts
if span <= 0:
return None
return volume / span
def mean(total: float, count: int) -> float | None:
return total / count if count else None
def per_node_rows(node, gpu, fabric, disk, clock, interface: str):
rows = []
for position, window in enumerate(node["windows"]):
gpu_acc = gpu[position]
fabric_series = fabric[position].get(interface, {})
disk_series = disk[position]
busiest = max(
disk_series.items(), key=lambda item: item[1]["volume"], default=None
)
row = {
"window": window["id"],
"node": node["node"],
"rank": node["rank"],
"participant": window["participant"],
"return_codes": window["return_codes"],
"error": window["error"],
"t_start": window["t_start"],
"t_end": window["t_end"],
"duration_s": window["duration_s"],
"gpu_samples": gpu_acc["samples"],
"gpu_fallback_samples": gpu_acc["fallback_samples"],
"gpu_sample_hz": rate(
max(gpu_acc["samples"] - 1, 0), gpu_acc["first_ts"], gpu_acc["last_ts"]
),
"fabric_interface": interface,
"fabric_bytes": fabric_series.get("volume"),
"fabric_samples": fabric_series.get("samples"),
"fabric_counter_resets": fabric_series.get("resets"),
"fabric_mb_per_s": None,
"disk_busiest_device": busiest[0] if busiest else None,
"disk_write_bytes": busiest[1]["volume"] if busiest else None,
"disk_write_mb_per_s": None,
"clock": clock[position],
}
if fabric_series:
row["fabric_mb_per_s"] = (
rate(fabric_series["volume"], fabric_series["first_ts"],
fabric_series["last_ts"]) or 0.0
) / MB
if busiest:
row["disk_write_mb_per_s"] = (
rate(busiest[1]["volume"], busiest[1]["first_ts"],
busiest[1]["last_ts"]) or 0.0
) / MB
for field in GPU_MEAN_FIELDS:
row[field] = mean(gpu_acc["sums"][field], gpu_acc["counts"][field])
row[f"{field}_samples"] = gpu_acc["counts"][field]
rows.append(row)
return rows
AVERAGED_FIELDS = (
"sm_active",
"tensor_active",
"gr_engine_active",
"dram_active",
"power_w",
"fabric_mb_per_s",
"disk_write_mb_per_s",
)
def participant_average(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Unweighted mean over the participant nodes of each window."""
order: list[str] = []
grouped: dict[str, list[dict[str, Any]]] = {}
for row in rows:
if row["window"] not in grouped:
grouped[row["window"]] = []
order.append(row["window"])
grouped[row["window"]].append(row)
out = []
for window in order:
members = grouped[window]
participants = [r for r in members if r["participant"]] or members
record = {
"window": window,
"participant_ranks": sorted(r["rank"] for r in members if r["participant"]),
"participant_nodes": sorted(r["node"] for r in members if r["participant"]),
"nodes_reporting": len(members),
"duration_s": members[0]["duration_s"],
"return_codes": sorted(
{code for r in members for code in (r["return_codes"] or [])}
),
}
for field in AVERAGED_FIELDS:
values = [r[field] for r in participants if r[field] is not None]
record[field] = sum(values) / len(values) if values else None
out.append(record)
return out
# ------------------------------------------------------------------ ground truth
def load_ground_truth(run_dir: Path) -> dict[str, list[dict[str, Any]]]:
truth: dict[str, list[dict[str, Any]]] = {}
for path in sorted(run_dir.glob("*/ground_truth/*.json")):
record = json.loads(path.read_text(encoding="utf-8"))
truth.setdefault(record.get("run_id", path.stem), []).append(record)
return truth
# ------------------------------------------------------------------------ main
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--run-dir", type=Path, required=True,
help="directory holding one subdirectory per node")
parser.add_argument("--out-dir", type=Path, required=True,
help="where window_telemetry.json and the CSVs are written")
parser.add_argument("--interface", default="bond0",
help="Ethernet interface used as the fabric counter (default bond0)")
args = parser.parse_args()
nodes = discover_nodes(args.run_dir)
if not nodes:
raise SystemExit(f"no node directories with a windows_rank*.ndjson under {args.run_dir}")
rows: list[dict[str, Any]] = []
for node in nodes:
locate = window_index(node["windows"])
print(f" node {node['node']} (rank {node['rank']}): "
f"{len(node['windows'])} windows", file=sys.stderr)
gpu = gpu_pass(node, locate)
fabric = fabric_pass(node, locate, args.interface)
disk = disk_pass(node, locate)
clock = clock_pass(node, locate)
rows.extend(per_node_rows(node, gpu, fabric, disk, clock, args.interface))
averaged = participant_average(rows)
truth = load_ground_truth(args.run_dir)
args.out_dir.mkdir(parents=True, exist_ok=True)
payload = {
"schema": "trace-window-telemetry/1",
"conventions": {
"participant_set": "ranks whose window record has a non-empty return_codes list",
"activity_and_power": "arithmetic mean of the DCGM field over samples inside the node's own window bounds",
"fabric": f"sum of non-negative successive differences of tx_bytes+rx_bytes on {args.interface}, divided by the span of the samples used",
"disk": "single busiest block device by sectors_written x 512, never a sum over devices",
"participant_average": "unweighted mean across participant nodes",
"missing": "a field absent from a sample is skipped, never read as zero",
},
"nodes": [
{"node": n["node"], "rank": n["rank"], "hardware": n["hardware"],
"sampling": n["sampling"]}
for n in nodes
],
"windows_participant_averaged": averaged,
"windows_per_node": rows,
"ground_truth_runs": sorted(truth),
}
(args.out_dir / "window_telemetry.json").write_text(
json.dumps(payload, indent=2, sort_keys=False) + "\n", encoding="utf-8"
)
with (args.out_dir / "window_table.csv").open("w", newline="", encoding="utf-8") as fh:
writer = csv.writer(fh)
writer.writerow(["window", "participant_ranks", "sm_active", "tensor_active",
"fabric_mb_per_s", "disk_write_mb_per_s", "power_w"])
for record in averaged:
writer.writerow([
record["window"],
" ".join(str(r) for r in record["participant_ranks"]),
_fmt(record["sm_active"], 2),
_fmt(record["tensor_active"], 2),
_fmt(record["fabric_mb_per_s"], 0),
_fmt(record["disk_write_mb_per_s"], 1),
_fmt(record["power_w"], 0),
])
with (args.out_dir / "window_table_per_node.csv").open("w", newline="", encoding="utf-8") as fh:
writer = csv.writer(fh)
writer.writerow(["window", "node", "rank", "participant", "sm_active",
"tensor_active", "power_w", "fabric_mb_per_s",
"disk_busiest_device", "disk_write_mb_per_s",
"gpu_samples", "gpu_sample_hz", "clock_offset_state"])
for row in rows:
writer.writerow([
row["window"], row["node"], row["rank"], int(row["participant"]),
_fmt(row["sm_active"], 4), _fmt(row["tensor_active"], 4),
_fmt(row["power_w"], 2), _fmt(row["fabric_mb_per_s"], 2),
row["disk_busiest_device"], _fmt(row["disk_write_mb_per_s"], 3),
row["gpu_samples"], _fmt(row["gpu_sample_hz"], 3),
row["clock"]["offset_state"],
])
print(f"wrote {args.out_dir/'window_telemetry.json'}", file=sys.stderr)
def _fmt(value: float | None, digits: int) -> str:
if value is None:
return ""
return f"{value:.{digits}f}"
if __name__ == "__main__":
main()