nv-simonec's picture nvzhouhk's picture
Integrate four AgentX FPM captures into canonical dataset layout (#9)
5487a45
Raw History Blame Contribute Delete
20.2 kB
#!/usr/bin/env python3
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""Prepare sequence-aligned, receipt-window-trimmed FPM data; no network calls."""
import argparse
from collections import Counter
from contextlib import contextmanager
from datetime import datetime, timedelta, timezone
from decimal import Decimal
import gzip
import hashlib
import json
import math
from pathlib import Path
import platform
import shutil
from zoneinfo import ZoneInfo
import zlib
FORMAT = "agentx-fpm-list-of-lists-v1"
HERE = Path(__file__).resolve().parent
def digest(path):
with path.open("rb") as f:
return hashlib.file_digest(f, "sha256").hexdigest()
def dump(path, value):
path.write_text(json.dumps(value, indent=2, allow_nan=False) + "\n")
def epoch_ns(text, zone):
d = datetime.fromisoformat(text)
if d.tzinfo is None:
d = d.replace(tzinfo=ZoneInfo(zone))
delta = d.astimezone(timezone.utc) - datetime(1970, 1, 1, tzinfo=timezone.utc)
return (delta.days * 86400 + delta.seconds) * 1_000_000_000 + delta.microseconds * 1000
def iso_ns(value):
whole, fraction = divmod(value, 1_000_000_000)
base = datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=whole)
return base.strftime("%Y-%m-%dT%H:%M:%S") + f".{fraction:09d}Z"
def measured_window(export, zone):
phases = [p for p in export["input_config"]["phases"] if p["kind"] == "profiling"]
if len(phases) != 1 or Decimal(str(phases[0]["duration"])) != 3600:
raise ValueError("This submission requires exactly one 3600-second profiling phase")
start = epoch_ns(export["start_time"], zone)
end = start + 3600 * 1_000_000_000
if end > epoch_ns(export["end_time"], zone):
raise ValueError("Profiling window extends past the exported end")
return start, end
def check_record(m, expected):
if m["version"] != 1 or m["dp_rank"] not in expected or not isinstance(m["worker_id"], str):
raise ValueError("Invalid FPM identity")
for key in ("dp_rank", "counter_id"):
if type(m[key]) is not int or m[key] < 0:
raise ValueError(f"Invalid {key}")
if not math.isfinite(m["wall_time"]) or m["wall_time"] < 0:
raise ValueError("Invalid wall_time")
for container in ("scheduled_requests", "queued_requests"):
for key, value in m[container].items():
if not isinstance(value, (float, int)) or isinstance(value, bool) or not math.isfinite(value) or value < 0:
raise ValueError(f"Invalid {container}.{key}")
@contextmanager
def gzip_text(path):
with path.open("xb") as raw:
with gzip.GzipFile(filename="", mode="wb", fileobj=raw, compresslevel=6, mtime=0) as stream:
yield stream
def emit_array_item(stream, group, index):
stream.write((",\n" if index else "").encode())
stream.write(json.dumps(group, separators=(",", ":"), allow_nan=False).encode())
def file_info(path):
return {"path": path.name, "bytes": path.stat().st_size, "sha256": digest(path)}
def percentile(values, percent):
ordered = sorted(values)
if not ordered:
return None
position = (len(ordered) - 1) * percent / 100
low, high = math.floor(position), math.ceil(position)
return ordered[low] + (ordered[high] - ordered[low]) * (position - low)
def prepare_case(root, output, case, common):
source, export_path = root / case["source_capture"], root / case["source_export"]
export = json.loads(export_path.read_text())
start, end = measured_window(export, case["export_timezone"])
expected = case["expected_dp_ranks"]
if export["input_config"]["phases"][0]["concurrency"] != case["concurrency"]:
raise ValueError("Client concurrency disagrees with case provenance")
records, counts, per_rank, counters, workers = [], Counter(), Counter(), {}, set()
ordinal_join = case["backend"] == "sglang" and len(expected) > 1
full_timed = {r: [] for r in expected}
ordinals = {}
sha = hashlib.sha256()
with source.open("rb") as f:
for line_number, line in enumerate(f, 1):
sha.update(line)
x = json.loads(line)
m, t = x["metrics"], x["received_at_ns"]
check_record(m, expected)
if type(t) is not int:
raise ValueError("Receive timestamps must be original integer nanoseconds")
r = m["dp_rank"]
workers.add(m["worker_id"])
if r in counters and m["counter_id"] != counters[r] + 1:
raise ValueError(f"Counter discontinuity at source line {line_number}")
counters[r] = m["counter_id"]
full_ordinal = len(full_timed[r])
if ordinal_join and m["wall_time"] > 0:
full_timed[r].append(m["wall_time"])
counts["source_records"] += 1
if t < start:
counts["excluded_before_profiling_start"] += 1
elif t >= end:
counts["excluded_at_or_after_sending_end"] += 1
elif m["wall_time"] == 0:
if any(m["scheduled_requests"].values()) or any(m["queued_requests"].values()):
raise ValueError("Zero timing is not an all-zero heartbeat")
counts["excluded_in_window_zero_time_heartbeats"] += 1
else:
if any(k in m for k in ("received_at_ns", "source_line", "wire_counter")):
raise ValueError("Provenance field collides with native metric")
row = dict(m, received_at_ns=t, source_line=line_number)
if "wire_counter" in x:
row["wire_counter"] = x["wire_counter"]
records.append(row)
if ordinal_join:
ordinals[line_number] = full_ordinal
per_rank[r] += 1
counts["retained_positive_rank_records"] += 1
s = m["scheduled_requests"]
if s["num_prefill_requests"] == 0 and s["num_decode_requests"] == 0:
counts["retained_timed_empty_rank_records"] += 1
if sha.hexdigest() != case["source_sha256"]:
raise ValueError(f"Raw capture hash mismatch: {source}")
if set(counters) != set(expected) or len(workers) != 1 or not records:
raise ValueError("Missing rank, unexpected worker set, or empty selected interval")
assert counts["source_records"] == sum(counts[k] for k in (
"excluded_before_profiling_start", "excluded_at_or_after_sending_end",
"excluded_in_window_zero_time_heartbeats", "retained_positive_rank_records"))
records.sort(key=lambda r: (r["received_at_ns"], r["dp_rank"], r["source_line"]))
from alignment import align_records
groups, alignment_report = align_records(records, case, full_timed, ordinals)
destination = output / "data" / case["case_id"]
destination.mkdir(parents=True, exist_ok=False)
complete_path = destination / "fpm_iterations.json.gz"
incomplete_path = destination / "incomplete_iterations.json.gz"
index_path = destination / "iteration_index.jsonl.gz"
spread, kinds = [], Counter()
with gzip_text(complete_path) as good, gzip_text(incomplete_path) as partial, gzip_text(index_path) as index:
good.write(b"[\n")
partial.write(b"[\n")
for sequence, (group, alignment_support) in enumerate(groups):
complete = [r["dp_rank"] for r in group] == expected
label = "complete" if complete else "incomplete"
path = complete_path if complete else incomplete_path
position = counts[f"{label}_groups"]
emit_array_item(good if complete else partial, group, position)
walls = [r["wall_time"] for r in group]
times = [r["received_at_ns"] for r in group]
p = any(r["scheduled_requests"]["num_prefill_requests"] for r in group)
d = any(r["scheduled_requests"]["num_decode_requests"] for r in group)
kind = "mixed" if p and d else "prefill" if p else "decode" if d else "empty"
delta_ms = (max(walls) - min(walls)) * 1000
entry = dict(iteration_id=f'{case["case_id"]}:derived-group-{sequence}',
data_file=path.name, array_index=position, complete=complete,
available_dp_ranks=[r["dp_rank"] for r in group],
min_received_at_ns=min(times), max_received_at_ns=max(times),
max_rank_wall_time=max(walls) if complete else None,
rank_wall_time_spread_ms=delta_ms,
duration_spread_exceeds_1ms=delta_ms > 1,
alignment_support=alignment_support,
workload_kind=kind)
index.write((json.dumps(entry, separators=(",", ":"), allow_nan=False) + "\n").encode())
counts[f"{label}_groups"] += 1
counts[f"{label}_rank_records"] += len(group)
if complete:
spread.append(delta_ms)
kinds[kind] += 1
good.write(b"\n]\n")
partial.write(b"\n]\n")
assert counts["complete_rank_records"] + counts["incomplete_rank_records"] == len(records)
selected_client = {
"source_export_sha256": digest(export_path),
"benchmark_id": export["benchmark_id"],
"aiperf_version": export.get("aiperf_version"),
"source_start_time": export["start_time"], "source_end_time_including_drain": export["end_time"],
"source_export_timezone": case["export_timezone"],
"input_config": export["input_config"], "run_info": export["run_info"],
"metadata": export.get("metadata"), "error_summary": export.get("error_summary"),
"was_cancelled": export.get("was_cancelled"),
"completed_measured_requests": export["time_to_first_token"]["count"],
}
evidence = destination / "collection_evidence.json"
dump(evidence, selected_client)
audit = destination / "alignment_report.json"
dump(audit, alignment_report)
manifest = {
"format": FORMAT, "status": "proposal_not_in_canonical_catalog",
"case": case,
"source_capture_bytes": source.stat().st_size,
"source_capture_sha256_verified": sha.hexdigest(),
"source_export_sha256": digest(export_path),
"processor_sha256": digest(HERE / "prepare.py"),
"alignment_processor_sha256": digest(HERE / "alignment.py"),
"runtime": {"python": platform.python_version(), "zlib": zlib.ZLIB_RUNTIME_VERSION},
"reproduction_url": f'{common["reproduction_repository"]}/tree/{common["reproduction_revision"]}/{case["reproduction_directory"]}',
"aiperf_revision": common["aiperf_revision"],
"window": {"clock": "recorder time.time_ns()", "start_inclusive_ns": start,
"end_exclusive_ns": end, "start_utc": iso_ns(start), "end_utc": iso_ns(end),
"duration_seconds": 3600, "export_timezone": case["export_timezone"],
"uses_export_end_time_for_cutoff": False,
"limitation": "Receipt-time trimming, not GPU-execution-time or request-phase attribution; publisher latency can move boundary records."},
"grouping": {"method": alignment_report["method"],
"algorithm_version": alignment_report["version"],
"authority": "producer" if len(expected) == 1 else "derived",
"performed_at": "offline upload preparation; readers consume stored membership",
"fixed_receive_time_window": False,
"clock_groups": [{"clock_id": "recorder0", "dp_ranks": expected, "offset_ns": 0}],
"counter_ids_used_for_cross_rank_join": False,
"duration_used_as_alignment_feature": case["backend"] == "vllm" and len(expected) > 1,
"duration_used_for_record_deletion": False,
"native_global_execution_id_available": False,
"report": audit.name,
"warning": "Run-audited sequence inference, not producer-certified global IDs. In vLLM, duration agreement is partly by construction and not independent accuracy evidence."},
"counts": dict(counts), "retained_positive_records_per_rank": dict(sorted(per_rank.items())),
"complete_group_workload_kinds": dict(kinds),
"complete_group_duration_spread_ms": {str(q): percentile(spread, q) for q in (50, 90, 99, 100)},
"complete_group_duration_spread_over_1ms": sum(x > 1 for x in spread),
"files": [file_info(p) for p in (complete_path, incomplete_path, index_path, evidence, audit)],
}
dump(destination / "manifest.json", manifest)
return manifest
def read_groups(path):
"""Stream the pretty outer-array format emitted here, validating separators."""
with gzip.open(path, "rt") as f:
if next(f) != "[\n":
raise ValueError("Missing outer list")
previous = None
for line in f:
stripped = line.strip()
if stripped == "]":
if previous is not None:
if previous.endswith(","):
raise ValueError("Trailing comma")
yield json.loads(previous)
if f.read().strip():
raise ValueError("Trailing content")
return
if not stripped:
continue
if previous is not None:
if not previous.endswith(","):
raise ValueError("Missing comma")
yield json.loads(previous[:-1])
previous = stripped
raise ValueError("Unterminated outer list")
def validate_case(root, manifest, source_root=None):
directory = root / "data" / manifest["case"]["case_id"]
expected = manifest["case"]["expected_dp_ranks"]
start, end = (manifest["window"][k] for k in ("start_inclusive_ns", "end_exclusive_ns"))
for info in manifest["files"]:
if digest(directory / info["path"]) != info["sha256"]:
raise ValueError("Artifact hash mismatch")
seen, counters, fingerprints = set(), set(), {}
group_iterators = {"fpm_iterations.json.gz": iter(read_groups(directory / "fpm_iterations.json.gz")),
"incomplete_iterations.json.gz": iter(read_groups(directory / "incomplete_iterations.json.gz"))}
counts = Counter()
last_matched_counter = {}
with gzip.open(directory / "iteration_index.jsonl.gz", "rt") as f:
for line in f:
meta = json.loads(line)
group = next(group_iterators[meta["data_file"]])
ranks = [r["dp_rank"] for r in group]
if ranks != sorted(set(ranks)) or not set(ranks).issubset(expected):
raise ValueError("Invalid rank list")
complete = ranks == expected
label = "complete" if complete else "incomplete"
if complete != meta["complete"] or counts[f"{label}_groups"] != meta["array_index"]:
raise ValueError("Index/group mismatch")
if meta["max_rank_wall_time"] != (max(r["wall_time"] for r in group) if complete else None):
raise ValueError("Invalid group timing")
times = [r["received_at_ns"] for r in group]
support = meta["alignment_support"]
if support["method"] != manifest["grouping"]["method"]:
raise ValueError("Alignment support method mismatch")
for r in group:
check_record(r, expected)
key = (r["worker_id"], r["dp_rank"], r["counter_id"])
if not start <= r["received_at_ns"] < end or r["wall_time"] <= 0:
raise ValueError("Warmup/drain/heartbeat leaked")
if r["source_line"] in seen or key in counters:
raise ValueError("Record duplicated")
seen.add(r["source_line"])
counters.add(key)
if support.get("assignment") != "unresolved_observation":
rank = r["dp_rank"]
if rank in last_matched_counter and r["counter_id"] <= last_matched_counter[rank]:
raise ValueError("Matched rank sequence is non-monotonic")
last_matched_counter[rank] = r["counter_id"]
if source_root is not None:
fingerprints[r["source_line"]] = hashlib.sha256(
json.dumps(r, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()
).hexdigest()
counts[f"{label}_groups"] += 1
counts[f"{label}_rank_records"] += len(group)
for iterator in group_iterators.values():
if next(iterator, None) is not None:
raise ValueError("Unindexed group")
for key, value in counts.items():
if manifest["counts"].get(key, 0) != value:
raise ValueError(f"Count mismatch: {key}")
if len(seen) != manifest["counts"]["retained_positive_rank_records"]:
raise ValueError("Retained membership count mismatch")
if source_root is not None:
source = source_root / manifest["case"]["source_capture"]
if digest(source) != manifest["source_capture_sha256_verified"]:
raise ValueError("Source capture hash changed")
with source.open() as f:
for number, line in enumerate(f, 1):
original = json.loads(line)
t, m = original["received_at_ns"], original["metrics"]
if not start <= t < end or m["wall_time"] <= 0:
if number in fingerprints:
raise ValueError("Excluded source record retained")
continue
row = dict(m, received_at_ns=t, source_line=number)
if "wire_counter" in original:
row["wire_counter"] = original["wire_counter"]
expected_fingerprint = hashlib.sha256(
json.dumps(row, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()
).hexdigest()
if fingerprints.pop(number, None) != expected_fingerprint:
raise ValueError(f"Retained source record changed or absent: {number}")
if fingerprints:
raise ValueError("Output contains invented source records")
return dict(case_id=manifest["case"]["case_id"], verified_records=len(seen), **counts)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("mode", choices=("build", "validate"))
parser.add_argument("--experiments-root", type=Path)
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
common = json.loads((HERE / "cases.json").read_text())
if args.mode == "build":
if args.experiments_root is None:
parser.error("build requires --experiments-root")
args.output.mkdir(parents=True, exist_ok=False)
for name in ("cases.json", "prepare.py", "alignment.py", "test_prepare.py", "README.md"):
shutil.copyfile(HERE / name, args.output / name)
manifests = []
for case in common["cases"]:
manifest = prepare_case(args.experiments_root, args.output, case, common)
manifests.append(manifest)
print(case["case_id"], json.dumps(manifest["counts"]), flush=True)
dump(args.output / "submission.json", dict(format=FORMAT,
dataset_base_revision=common["dataset_base_revision"], status="proposal_not_in_canonical_catalog",
case_manifests=[f'data/{m["case"]["case_id"]}/manifest.json' for m in manifests]))
else:
submission = json.loads((args.output / "submission.json").read_text())
for relative in submission["case_manifests"]:
manifest = json.loads((args.output / relative).read_text())
print(json.dumps(validate_case(args.output, manifest, args.experiments_root)), flush=True)
if __name__ == "__main__":
main()