#!/usr/bin/env python3 """ Purpose-channel measurements for the instrumented multi-node case. Computes, from the raw collector NDJSON of one labelled run, the four structural measurements the paper reports on top of the per-window table: 1. fabric step cadence autocorrelation of the per-node fabric-rate series, reported as the peak over a lag range and as the coefficient at a stated step period 2. participant synchrony pairwise Pearson correlation of the per-node fabric-rate series on a shared time grid 3. storage bursts write-burst events on each node's busiest block device: count, peak rate, size, inter-burst interval 4. operation estimate integral of the DCGM tensor-pipe active fraction over the participants, and what it becomes under a declared per-board operation rate plus the per-window collector-gap record used to characterise the coverage dropout. Standard library only. python3 purpose_channels.py --run-dir --out-dir Every estimator parameter is a command line argument, and the values used are written into the output alongside the results. The cadence coefficient depends on the bin width, so `--cadence-bins` takes a list and the output carries one row per bin width. The operation estimate is linear in the per-board rate given by `--board-rate`, which is a registry input rather than a measured quantity. """ from __future__ import annotations import argparse import bisect import json import math import re import sys from pathlib import Path from typing import Any, Iterable BYTES_PER_SECTOR = 512 MB = 1.0e6 GIB = float(1 << 30) 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]]: 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 = { 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")), } for record in read_ndjson(windows_path) } nodes.append({"node": node_dir.name, "rank": rank, "dir": node_dir, "windows": windows}) return sorted(nodes, key=lambda n: n["rank"]) def load_ground_truth(run_dir: Path) -> dict[str, dict[int, dict[str, Any]]]: """run_id -> rank -> the runner's own ground-truth record.""" truth: dict[str, dict[int, dict[str, Any]]] = {} for path in sorted(run_dir.glob("*/ground_truth/*.json")): record = json.loads(path.read_text(encoding="utf-8")) run_id = record.get("run_id") rank = record.get("rank") if run_id is None or rank is None: continue truth.setdefault(run_id, {})[int(rank)] = record return truth # ------------------------------------------------------------------- series def window_locator(windows: dict[str, dict[str, float]]): """Map a timestamp to a window id, over non-overlapping ordered windows.""" bounds = sorted((w["t_start"], w["t_end"], wid) for wid, w in windows.items()) starts = [b[0] for b in bounds] def locate(ts: float) -> str | None: index = bisect.bisect_right(starts, ts) - 1 if index < 0: return None start, end, wid = bounds[index] return wid if ts <= end else None return locate def collect_node(node: dict[str, Any], interface: str) -> dict[str, dict[str, Any]]: """One streaming pass per stream, filling every window of one node at once. Returns, per window id: fabric [(interval start, interval end, bytes)] on `interface` disk {block device: [(interval start, interval end, bytes)]} gpu_ts sample times gpu_tensor tensor-pipe active fraction at those times, None where absent A step is one non-negative successive difference of a monotonic counter, kept with the interval it covers rather than collapsed to a single instant. A negative difference is a counter reset and contributes nothing. Both samples behind a step must fall in the same window, so no step straddles a window boundary. """ locate = window_locator(node["windows"]) per_window: dict[str, dict[str, Any]] = { wid: {"fabric": [], "disk": {}, "gpu_ts": [], "gpu_tensor": []} for wid in node["windows"] } last_fabric: tuple[float, float] | None = None for path in sorted(node["dir"].glob("fabric.*.ndjson")): for record in read_ndjson(path): if record.get("class") != "eth" or record.get("dev") != interface: continue ts, value = record.get("ts"), None if ts is None: continue if isinstance(record.get("tx_bytes"), (int, float)) and \ isinstance(record.get("rx_bytes"), (int, float)): value = float(record["tx_bytes"]) + float(record["rx_bytes"]) if value is None: continue ts /= 1000.0 previous, last_fabric = last_fabric, (ts, value) if previous is None: continue delta = value - previous[1] if delta < 0: continue wid = locate(ts) if wid is not None and locate(previous[0]) == wid: per_window[wid]["fabric"].append((previous[0], ts, delta)) last_disk: dict[str, tuple[float, float]] = {} for path in sorted(node["dir"].glob("disk.*.ndjson")): for record in read_ndjson(path): ts, dev = record.get("ts"), record.get("dev") sectors = record.get("sectors_written") if ts is None or dev is None or not isinstance(sectors, (int, float)): continue ts /= 1000.0 value = float(sectors) * BYTES_PER_SECTOR previous = last_disk.get(dev) last_disk[dev] = (ts, value) if previous is None: continue delta = value - previous[1] if delta < 0: continue wid = locate(ts) if wid is not None and locate(previous[0]) == wid: per_window[wid]["disk"].setdefault(dev, []).append( (previous[0], ts, delta) ) for path in sorted(node["dir"].glob("gpu.*.ndjson")): for record in read_ndjson(path): ts = record.get("ts") if ts is None: continue ts /= 1000.0 wid = locate(ts) if wid is None: continue value = record.get("tensor_active") per_window[wid]["gpu_ts"].append(ts) per_window[wid]["gpu_tensor"].append( float(value) if isinstance(value, (int, float)) else None ) for bucket in per_window.values(): order = sorted(range(len(bucket["gpu_ts"])), key=lambda i: bucket["gpu_ts"][i]) bucket["gpu_ts"] = [bucket["gpu_ts"][i] for i in order] bucket["gpu_tensor"] = [bucket["gpu_tensor"][i] for i in order] return per_window def bin_rate(steps: list[tuple[float, float, float]], bin_s: float, t0: float, t1: float, mode: str = "midpoint") -> list[float]: """Bytes per second on a fixed grid, from interval-stamped byte steps. Two placements of a counter delta are supported: midpoint the whole delta lands in the bin holding the middle of its interval. This keeps a burst inside one bin, and the bin a delta lands in depends on the sampling phase, so two nodes sampling the same traffic out of phase differ by about one sample per bin. spread the delta is distributed across the bins its interval overlaps, in proportion to the overlap. This is insensitive to sampling phase and smears a burst across the bin boundary it straddles. Comparing two nodes requires passing both the same `t0`, otherwise the two grids are offset from each other and a periodic signal can be driven to a negative correlation by the offset alone. """ if bin_s <= 0 or t1 <= t0: return [] n = int((t1 - t0) / bin_s) if n <= 1: return [] grid = [0.0] * n if mode == "midpoint": for start, end, delta in steps: index = int(((start + end) / 2.0 - t0) / bin_s) if 0 <= index < n: grid[index] += delta elif mode == "spread": for start, end, delta in steps: if end <= start: continue rate = delta / (end - start) first = max(0, int((start - t0) / bin_s)) last = min(n - 1, int((end - t0) / bin_s)) for index in range(first, last + 1): lo = max(start, t0 + index * bin_s) hi = min(end, t0 + (index + 1) * bin_s) if hi > lo: grid[index] += rate * (hi - lo) else: raise ValueError(f"unknown binning mode {mode!r}") return [value / bin_s for value in grid] def native_rate(steps: list[tuple[float, float, float]]) -> tuple[list[float], float]: """The rate series at the collector's own cadence, with no resampling. Returns the per-step byte rates in sample order and the median interval between the samples behind them, so a lag in samples can be read as a lag in seconds. `bin_rate` is the fixed-grid alternative; both are computed and both appear in the output. """ rates: list[float] = [] intervals: list[float] = [] for start, end, delta in steps: interval = end - start if interval <= 0: continue rates.append(delta / interval) intervals.append(interval) if not intervals: return [], 0.0 ordered = sorted(intervals) return rates, ordered[len(ordered) // 2] # --------------------------------------------------------------- estimators def autocorrelation(series: list[float], lag: int) -> float | None: n = len(series) if lag <= 0 or lag >= n: return None mean = sum(series) / n centred = [value - mean for value in series] denominator = sum(value * value for value in centred) if denominator <= 0: return None numerator = sum(centred[i] * centred[i + lag] for i in range(n - lag)) return numerator / denominator def pearson(a: list[float], b: list[float]) -> float | None: n = min(len(a), len(b)) if n < 2: return None a, b = a[:n], b[:n] mean_a, mean_b = sum(a) / n, sum(b) / n ca = [value - mean_a for value in a] cb = [value - mean_b for value in b] denominator = math.sqrt(sum(v * v for v in ca) * sum(v * v for v in cb)) if denominator <= 0: return None return sum(x * y for x, y in zip(ca, cb)) / denominator def cadence(series: list[float], sample_s: float, estimator: str, min_lag_s: float, max_lag_s: float, step_time_s: float | None) -> dict[str, Any]: """Peak autocorrelation over a lag band, and the value at a step period. `sample_s` is the spacing one lag step represents: the bin width for a resampled series, the median sample interval for a native one. """ lo = max(1, int(round(min_lag_s / sample_s))) hi = min(len(series) - 1, int(round(max_lag_s / sample_s))) curve = [] for lag in range(lo, hi + 1): value = autocorrelation(series, lag) if value is not None: curve.append((lag, value)) peak_lag, peak_value = (max(curve, key=lambda item: item[1]) if curve else (None, None)) result = { "estimator": estimator, "sample_s": round(sample_s, 6), "samples": len(series), "lag_band_s": [min_lag_s, max_lag_s], "peak_lag_s": round(peak_lag * sample_s, 6) if peak_lag else None, "peak_autocorrelation": peak_value, } result.update(_recurrence(curve, sample_s)) if step_time_s: lag = int(round(step_time_s / sample_s)) result["step_time_s"] = step_time_s result["autocorrelation_at_step_period"] = autocorrelation(series, lag) return result def _recurrence(curve: list[tuple[int, float]], sample_s: float) -> dict[str, Any]: """Does the autocorrelation come back up after it first falls? A step-periodic series recurs at multiples of its step period, so it has a local maximum after its first local minimum. A series that only decays does not. The lag and value of that maximum are returned; no threshold is applied to them. """ if len(curve) < 3: return {"first_local_min_lag_s": None, "peak_after_first_local_min": None, "peak_after_first_local_min_lag_s": None} minimum_index = None for i in range(1, len(curve) - 1): if curve[i][1] <= curve[i - 1][1] and curve[i][1] < curve[i + 1][1]: minimum_index = i break if minimum_index is None: return {"first_local_min_lag_s": None, "peak_after_first_local_min": None, "peak_after_first_local_min_lag_s": None} tail = curve[minimum_index:] lag, value = max(tail, key=lambda item: item[1]) return { "first_local_min_lag_s": round(curve[minimum_index][0] * sample_s, 6), "peak_after_first_local_min": value, "peak_after_first_local_min_lag_s": round(lag * sample_s, 6), } def find_bursts(steps: list[tuple[float, float]], threshold_mb_s: float, merge_gap_s: float) -> list[dict[str, Any]]: """Maximal runs of samples above a write-rate threshold, merged over gaps. The rate of one step is its bytes divided by the interval it covers, which the collector's 1 Hz disk cadence makes about one second. """ if len(steps) < 2: return [] spans = [] for start, end, delta in steps: interval = end - start if interval <= 0: continue spans.append((end, delta, delta / interval)) bursts: list[dict[str, Any]] = [] current: dict[str, Any] | None = None for ts, delta, rate in spans: if rate >= threshold_mb_s * MB: if current and ts - current["end_ts"] <= merge_gap_s: current["end_ts"] = ts current["bytes"] += delta current["peak_bytes_per_s"] = max(current["peak_bytes_per_s"], rate) else: if current: bursts.append(current) current = {"start_ts": ts, "end_ts": ts, "bytes": delta, "peak_bytes_per_s": rate} if current: bursts.append(current) out = [] for index, burst in enumerate(bursts): record = { "start_ts": burst["start_ts"], "duration_s": round(burst["end_ts"] - burst["start_ts"], 3), "bytes": burst["bytes"], "gib": burst["bytes"] / GIB, "peak_mb_per_s": burst["peak_bytes_per_s"] / MB, } if index: record["interval_since_previous_start_s"] = round( burst["start_ts"] - bursts[index - 1]["start_ts"], 3 ) out.append(record) return out def sample_gaps(times: list[float], min_gap_s: float) -> list[dict[str, float]]: gaps = [] for index in range(1, len(times)): gap = times[index] - times[index - 1] if gap >= min_gap_s: gaps.append({"start_ts": times[index - 1], "gap_s": round(gap, 3)}) return gaps # ------------------------------------------------------------------- passes def node_window_record(node, window_id, bucket, step_time_s, args) -> dict[str, Any]: """Everything measurable for one node inside one window.""" window = node["windows"][window_id] steps = bucket["fabric"] record: dict[str, Any] = { "node_rank": node["rank"], "participant": window["participant"], "fabric_bytes": sum(delta for _, _, delta in steps), "fabric_steps": len(steps), "cadence": [], } if steps: native, sample_s = native_rate(steps) if native and sample_s > 0: record["cadence"].append( cadence(native, sample_s, "native_sample_cadence", args.min_lag_s, args.max_lag_s, step_time_s) ) for bin_s in args.cadence_bins: record["cadence"].append( cadence(bin_rate(steps, bin_s, window["t_start"], window["t_end"]), bin_s, f"fixed_grid_{bin_s}s", args.min_lag_s, args.max_lag_s, step_time_s) ) totals = {dev: sum(d for _, _, d in series) for dev, series in bucket["disk"].items()} if totals: busiest = max(totals, key=totals.get) record["disk_busiest_device"] = busiest record["disk_write_bytes"] = totals[busiest] record["disk_write_gb"] = totals[busiest] / 1e9 record["disk_bursts"] = find_bursts( bucket["disk"][busiest], args.burst_threshold_mb_s, args.burst_merge_gap_s ) record["disk_peak_mb_per_s"] = _peak_rate(bucket["disk"][busiest]) / MB times = bucket["gpu_ts"] record["gpu_samples"] = len(times) record["gpu_gaps"] = sample_gaps(times, args.min_gap_s) record["gpu_window_fraction_before_first_gap"] = ( round((record["gpu_gaps"][0]["start_ts"] - window["t_start"]) / (window["t_end"] - window["t_start"]), 4) if record["gpu_gaps"] and window["t_end"] > window["t_start"] else None ) record["tensor_active_device_seconds"] = _integrate(times, bucket["gpu_tensor"]) return record def assemble_window(window_id, nodes, node_records, binned, truth, args) -> dict[str, Any]: present = [n for n in nodes if window_id in n["windows"]] participant_ranks = sorted( n["rank"] for n in present if n["windows"][window_id]["participant"] ) truth_by_rank = truth.get(window_id, {}) writer_rank = min(truth_by_rank) if truth_by_rank else ( participant_ranks[0] if participant_ranks else None ) result: dict[str, Any] = { "window": window_id, "participant_ranks": participant_ranks, "writer_rank": writer_rank, "fabric_interface": args.interface, "shared_grid": { "t_start": max(n["windows"][window_id]["t_start"] for n in present), "t_end": min(n["windows"][window_id]["t_end"] for n in present), "bin_s": args.sync_bin_s, }, "nodes": {n["node"]: node_records[n["node"]] for n in present}, } # Participant synchrony on the shared grid, under both placements of a # counter delta. Both are computed and both are written to the output. result["participant_synchrony"] = {"bin_s": args.sync_bin_s} for mode, series in binned.items(): ranks = sorted(series) all_pairs = {} for i, rank_a in enumerate(ranks): for rank_b in ranks[i + 1:]: value = pearson(series[rank_a], series[rank_b]) if value is not None: all_pairs[f"{rank_a}-{rank_b}"] = value result["participant_synchrony"][mode] = { "participant_pairs": { key: value for key, value in all_pairs.items() if all(int(r) in participant_ranks for r in key.split("-")) }, "all_pairs": all_pairs, } pipe_seconds = sum( record.get("tensor_active_device_seconds") or 0.0 for node, record in result["nodes"].items() if record["node_rank"] in participant_ranks ) logged = [ record.get("stats", {}).get("flop_6nd_estimate") for record in truth_by_rank.values() ] logged = [value for value in logged if isinstance(value, (int, float))] result["operation_estimate"] = { "tensor_pipe_device_seconds": pipe_seconds, "logged_6nd_operations": max(logged) if logged else None, "by_board_rate": [ { "board_rate_ops_per_s": board_rate, "estimated_operations": pipe_seconds * board_rate, "ratio_to_logged_6nd": (pipe_seconds * board_rate / max(logged)) if logged and max(logged) else None, } for board_rate in args.board_rate ], "note": "occupancy integral against a declared board rate; the DCGM " "profiling fields report occupancy, not counted operations", } if writer_rank in truth_by_rank: source = truth_by_rank[writer_rank] result["ground_truth"] = { "kind": source.get("kind"), "strategy": source.get("params", {}).get("strategy"), "ckpt_interval_s": source.get("params", {}).get("ckpt_interval_s"), "stats": { key: source.get("stats", {}).get(key) for key in ("param_count", "steps", "tokens_global", "flop_6nd_estimate", "step_time_s_mean", "comm_fraction_est") }, "checkpoints": source.get("stats", {}).get("checkpoints"), } return result def _integrate(times: list[float], values: list[float | None]) -> float: """Rectangle-rule integral of a fraction over the sample spacing.""" total = 0.0 for index in range(1, len(times)): value = values[index] interval = times[index] - times[index - 1] if value is None or interval <= 0: continue total += value * interval return total def _peak_rate(steps: list[tuple[float, float, float]]) -> float: peak = 0.0 for start, end, delta in steps: if end > start: peak = max(peak, delta / (end - start)) return peak # --------------------------------------------------------------------- main def main() -> None: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--run-dir", type=Path, required=True) parser.add_argument("--out-dir", type=Path, required=True) parser.add_argument("--window", action="append", default=None, help="window id; repeatable; default every window in the run") parser.add_argument("--interface", default="bond0") parser.add_argument("--cadence-bins", type=float, nargs="+", default=[0.05, 0.1, 0.2], help="bin widths in seconds for the cadence autocorrelation") parser.add_argument("--min-lag-s", type=float, default=0.3) parser.add_argument("--max-lag-s", type=float, default=30.0) parser.add_argument("--sync-bin-s", type=float, default=0.5, help="bin width for the participant-synchrony correlation") parser.add_argument("--burst-threshold-mb-s", type=float, default=100.0) parser.add_argument("--burst-merge-gap-s", type=float, default=5.0) parser.add_argument("--min-gap-s", type=float, default=5.0, help="smallest inter-sample gap reported as a delivery gap") parser.add_argument("--board-rate", type=float, nargs="+", default=[8.35e14, 1.0e15], help="declared per-board operation rates for the estimate") 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}") truth = load_ground_truth(args.run_dir) ordered: list[str] = [] for node in nodes: for window_id in node["windows"]: if window_id not in ordered: ordered.append(window_id) selected = [w for w in (args.window or ordered) if w in ordered] shared = { window_id: ( max(n["windows"][window_id]["t_start"] for n in nodes if window_id in n["windows"]), min(n["windows"][window_id]["t_end"] for n in nodes if window_id in n["windows"]), ) for window_id in selected } step_times = { window_id: {rank: record.get("stats", {}).get("step_time_s_mean") for rank, record in truth.get(window_id, {}).items()} for window_id in selected } records: dict[str, dict[str, Any]] = {w: {} for w in selected} binned: dict[str, dict[str, dict[int, list[float]]]] = { w: {"midpoint": {}, "spread": {}} for w in selected } for node in nodes: print(f" reading {node['node']} (rank {node['rank']})", file=sys.stderr) buckets = collect_node(node, args.interface) for window_id in selected: if window_id not in node["windows"]: continue bucket = buckets[window_id] per_window_steps = step_times[window_id] step_time = per_window_steps.get(node["rank"]) or ( per_window_steps.get(min(per_window_steps)) if per_window_steps else None ) records[window_id][node["node"]] = node_window_record( node, window_id, bucket, step_time, args ) if bucket["fabric"]: t0, t1 = shared[window_id] for mode in ("midpoint", "spread"): binned[window_id][mode][node["rank"]] = bin_rate( bucket["fabric"], args.sync_bin_s, t0, t1, mode ) results = [ assemble_window(window_id, nodes, records[window_id], binned[window_id], truth, args) for window_id in selected ] args.out_dir.mkdir(parents=True, exist_ok=True) payload = { "schema": "trace-purpose-channels/1", "parameters": { "fabric_interface": args.interface, "cadence_bins_s": args.cadence_bins, "cadence_lag_band_s": [args.min_lag_s, args.max_lag_s], "synchrony_bin_s": args.sync_bin_s, "burst_threshold_mb_per_s": args.burst_threshold_mb_s, "burst_merge_gap_s": args.burst_merge_gap_s, "delivery_gap_min_s": args.min_gap_s, "board_rates_ops_per_s": args.board_rate, }, "windows": results, } out = args.out_dir / "purpose_channels.json" out.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") print(f"wrote {out}", file=sys.stderr) if __name__ == "__main__": main()