Download scripts/manage_dataset.py from nvidia/aisimulate-fpm-dataset: direct link, hf CLI and curl.
- Browser
- Download file 161 kB
-
https://huggingface.co/datasets/nvidia/aisimulate-fpm-dataset/resolve/main/scripts/manage_dataset.py
- Command line
-
hf download hf://datasets/nvidia/aisimulate-fpm-dataset/scripts/manage_dataset.py
-
curl -L -o manage_dataset.py https://huggingface.co/datasets/nvidia/aisimulate-fpm-dataset/resolve/main/scripts/manage_dataset.py
161 kB
#!/usr/bin/env python3
"""Import and validate the AISimPlayground-backed FPM dataset.
The importer copies reviewed FPM libraries and their measurement evidence from
one pinned AISimPlayground checkout. Predictions, normalized comparisons, and
metrics are deliberately left to FPM Gym. The validator is source-independent
so a published Hugging Face snapshot can be checked without internal access.
"""
from __future__ import annotations
import migrate_measurements
import argparse
import array
import bisect
import csv
import gzip
import hashlib
import io
import json
import math
import os
import re
import shutil
import statistics
import subprocess
import tempfile
from collections import Counter
from collections.abc import Callable, Iterable, Mapping, Sequence
from dataclasses import dataclass
from dataclasses import field as dataclass_field
from decimal import Decimal
from pathlib import Path, PurePosixPath
from typing import Any
import jsonschema
import pyarrow as pa
import pyarrow.compute as pc
import pyarrow.parquet as pq
from pre_grouped import REPRESENTATION as PRE_GROUPED_REPRESENTATION
from pre_grouped import validate_file as validate_pre_grouped_file
from self_benchmark import CAMPAIGN as SELF_BENCHMARK_CAMPAIGN
from self_benchmark import validate_catalog_record as validate_self_benchmark_catalog_record
from self_benchmark import validate_snapshot as validate_self_benchmark_snapshot
from inkling_six_run import CAMPAIGNS as INKLING_CAMPAIGNS
from inkling_six_run import validate_snapshot as validate_inkling_snapshot
from inkling_six_run import validate_catalog_record as validate_inkling_catalog_record
from dsv41 import CAMPAIGNS as DSV41_CAMPAIGNS
from dsv41 import validate_snapshot as validate_dsv41_snapshot
from dsv41 import validate_catalog_record as validate_dsv41_catalog_record
DATASET_ID = "nvidia/aisimulate-fpm-dataset"
SOURCE_REPOSITORY = "https://gitlab-master.nvidia.com/dl/ai-dynamo/AISimPlayground"
SOURCE_REVISION = "731947aabdcb5ae8658fd16744022ca94e407cd3"
MEASUREMENT_MANIFEST_VERSION = 4
CONFIGURATION_MANIFEST_VERSION = 3
CATALOG_VERSION = 5
CANONICAL_BUNDLE_VERSION = 4
FPM_CATALOG_VERSION = 4
MEASUREMENT_CATALOG_VERSION = 4
MEASUREMENT_TRUTH_ROLES = frozenset({"truth", "derived_truth"})
DOCUMENT_SCHEMAS = {
"catalog_index": "schemas/history/catalog-index-v5.schema.json",
"configuration_manifest": "schemas/history/configuration-manifest-v3.schema.json",
"measurement_manifest": "schemas/history/measurement-manifest-v4.schema.json",
}
MEASUREMENT_PROTOCOL_SCHEMAS = {
"forward-pass-measurement-v1": "schemas/forward-pass-measurement-v1.schema.json",
"forward-pass-record-v1": "schemas/forward-pass-record-v1.schema.json",
}
MEASUREMENT_PROTOCOL_IDS = frozenset(MEASUREMENT_PROTOCOL_SCHEMAS)
EVIDENCE_FORMAT_IDS = frozenset({"wave-summary-v1", "bucket-summary-v1"})
DSV4PRO_DERIVED_TRUTH_SOURCES = 25
# DSV4-Pro benchmark-lane configs published as FPM provenance: (paths, distinct sources).
DSV4PRO_FPM_PROVENANCE_COUNTS = (15, 14)
# Snapshot generations whose evidence postdates their campaign's evidence_date.
GENERATION_EVIDENCE_DATES = {"dsv4pro-gb300-fpm:r6pin": "2026-09-04"}
DERIVED_TRUTH_FIELDS = (
"measurement_id",
"phase",
"batch_size",
"total_prefill_tokens",
"total_kv_read_tokens",
"truth_latency_ms",
"source_file",
"source_row",
)
REQUIRED_FPM_COLUMNS = {
"model_path",
"system",
"backend",
"backend_version",
"weight_quantization",
"gemm_quant_mode",
"moe_quant_mode",
"fmha_quant_mode",
"fmha_resolution",
"comm_quant_mode",
"kv_cache_dtype",
"parallel_strategy",
"tp",
"pp",
"dp",
"moe_tp",
"moe_ep",
"cp",
"workload_kind",
"batch_size",
"total_prefill_tokens",
"total_kv_read_tokens",
"latency_ms",
}
@dataclass(frozen=True)
class Campaign:
model_id: str
model_revision: str | None
gpu_family: str
evidence_date: str
measurement_protocol_id: str | None
caveats: tuple[str, ...] = ()
evidence_format_id: str | None = None
@dataclass(frozen=True)
class Collector:
name: str
email: str
attribution: str
@dataclass(frozen=True)
class FPMIdentityCorrection:
model_path: str
gemm_quant_mode: str
changes: tuple[tuple[str, str, str], ...]
@dataclass
class Snapshot:
configuration_path: str
generation_id: str
campaign_id: str
identity: dict[str, object]
evidence_date: str
fpm_assets: dict[str, dict[str, object]] = dataclass_field(default_factory=dict)
fpm_provenance: list[dict[str, object]] = dataclass_field(default_factory=list)
measurements: list[dict[str, object]] = dataclass_field(default_factory=list)
snapshot_id: str = ""
snapshot_status: str = ""
output_root: str = ""
aisim_commit: str | None = None
aisim_commit_status: str = "unknown"
producer_revisions: tuple[str, ...] = ()
published_fpm: dict[str, dict[str, object]] = dataclass_field(default_factory=dict)
published_measurement_manifest: dict[str, object] = dataclass_field(
default_factory=dict
)
CAMPAIGNS: dict[str, Campaign] = {
"dsv4flash-b200-static-baseline-fpm": Campaign(
"deepseek-ai/DeepSeek-V4-Flash-0731",
None,
"B200",
"2026-09-02",
"forward-pass-measurement-v1",
),
"dsv4pro-gb300-fpm": Campaign(
"deepseek-ai/DeepSeek-V4-Pro",
None,
"GB300",
"2026-09-03",
"forward-pass-record-v1",
(
"Raw serving truth streams are external; truth values are normalized from the upstream score evidence.",
"DEP8 r6pin re-measured the prefill lanes with worker pinning; its decode rows are identical to the r4 library.",
),
),
"glm52-gb200-dep16-disagg-fpm-fidelity": Campaign(
"nvidia/GLM-5.2-NVFP4",
"aec724e8",
"GB200",
"2026-09-10",
"forward-pass-measurement-v1",
(
"Lockstep self-benchmark on GB200 DEP16: decode 3.6% and prefill 24.0% step-level MAPE against the 16/16 disaggregated truth run (17.2% when all 16 ranks prefill).",
"The decode cell joins two collection attempts (Slurm 7024594 rows 1-121, 7025934 rows 128-256); 38 of 1,025 decode points are fake_fallback at the deepest KV rung.",
"Truth is reconstructed at import from one rank-event stream per engine role (16 DP ranks) with the campaign's clock correction (estimated for prefill; declared zero for decode, where no shared step exceeds 150 ms) and an 8 ms window; the dataset default is the maximum rank wall time, while the campaign's published fidelity used the median over busy ranks (about 1% apart at the median on complete decode steps, 1.7% at p90, 8% at p99).",
"vLLM 0.28.0 is not a curated aisimulate version slot; loading the library requires AIC_ALLOW_UNLISTED_VERSIONS=1.",
),
),
"glm52-b200-static-baseline-fpm": Campaign(
"nvidia/GLM-5.2-NVFP4",
None,
"B200",
"2026-08-28",
"forward-pass-measurement-v1",
(
"The original FPM anchor-collection JSON is unavailable; the released Parquet is the surviving form.",
),
),
"kimi-k3-gb300-fpm": Campaign(
"moonshotai/Kimi-K3",
None,
"GB300",
"2026-09-01",
"forward-pass-measurement-v1",
),
"minimax-e9-b200-ragged-commonmode": Campaign(
"MiniMaxAI/MiniMax-M2.7",
"d494266a",
"B200",
"2026-08-27",
"forward-pass-measurement-v1",
(
"Decode-only evidence; ragged serving truth contains an exam-side latency component.",
),
),
"minimax-m27-h200-generational-verify-dep4-tp4-fpm": Campaign(
"MiniMaxAI/MiniMax-M2.7",
"d494266a",
"H200",
"2026-08-20",
"forward-pass-measurement-v1",
(
"Only dep4 and pure_tp4 have retained measurement evidence; tep4 and the 2-GPU forms do not.",
),
),
"minimax-m27-h200-static-baseline-fpm": Campaign(
"MiniMaxAI/MiniMax-M2.7",
"d494266a",
"H200",
"2026-08-28",
"forward-pass-measurement-v1",
(
"The original FPM metadata sidecars are unavailable and are reconstructed during import.",
),
),
"minimax2.7-b200-fpm": Campaign(
"MiniMaxAI/MiniMax-M2.7",
"d494266a",
"B200",
"2026-08-31",
"forward-pass-measurement-v1",
("dep4/c4 is quarantined and dep4 prefill is unavailable.",),
),
}
FPM_IDENTITY_CORRECTION_POLICY_ID = "runtime-dtype-annotation-v1"
FPM_IDENTITY_CORRECTION_FIELD = "fpm_identity_correction"
FPM_IDENTITY_PRESERVED_COLUMNS = (
"weight_quantization",
"gemm_quant_mode",
"workload_kind",
"batch_size",
"total_prefill_tokens",
"total_kv_read_tokens",
"latency_ms",
)
FPM_IDENTITY_CORRECTIONS = {
"dsv4flash-b200-static-baseline-fpm": FPMIdentityCorrection(
model_path="deepseek-ai/DeepSeek-V4-Flash-0731",
gemm_quant_mode="fp8",
changes=(
("moe_quant_mode", "fp8", "w4a8_mxfp4_mxfp8"),
("fmha_quant_mode", "fp8", "bfloat16"),
(
"fmha_resolution",
"checkpoint_native",
"aic_data_fallback_from_fp8",
),
),
),
"dsv4pro-gb300-fpm": FPMIdentityCorrection(
model_path="deepseek-ai/DeepSeek-V4-Pro",
gemm_quant_mode="fp8_block",
changes=(("moe_quant_mode", "fp8_block", "w4a8_mxfp4_mxfp8"),),
),
"kimi-k3-gb300-fpm": FPMIdentityCorrection(
model_path="moonshotai/Kimi-K3",
gemm_quant_mode="fp8_block",
changes=(("moe_quant_mode", "fp8_block", "w4a16_mxfp4"),),
),
"glm52-b200-static-baseline-fpm": FPMIdentityCorrection(
model_path="nvidia/GLM-5.2-NVFP4",
gemm_quant_mode="nvfp4",
changes=(
("fmha_quant_mode", "fp8", "bfloat16"),
(
"fmha_resolution",
"checkpoint_native",
"aic_data_fallback_from_fp8",
),
),
),
}
COLLECTORS: dict[str, Collector] = {
"dsv4flash-b200-static-baseline-fpm": Collector(
"Yuan Li", "yuanli@nvidia.com", "source campaign author and path owner"
),
"dsv4pro-gb300-fpm": Collector(
"Kimi Zhao", "kimiz@nvidia.com", "source campaign author and path owner"
),
"glm52-gb200-dep16-disagg-fpm-fidelity": Collector(
"Yiming Liu", "yimingl@nvidia.com", "source campaign author and path owner"
),
"glm52-b200-static-baseline-fpm": Collector(
"Yuan Li", "yuanli@nvidia.com", "source campaign author"
),
"kimi-k3-gb300-fpm": Collector(
"Kimi Zhao", "kimiz@nvidia.com", "source campaign author and path owner"
),
"minimax-e9-b200-ragged-commonmode": Collector(
"Yuan Li", "yuanli@nvidia.com", "source campaign author"
),
"minimax-m27-h200-generational-verify-dep4-tp4-fpm": Collector(
"Yuan Li", "yuanli@nvidia.com", "source campaign author"
),
"minimax-m27-h200-static-baseline-fpm": Collector(
"Yuan Li", "yuanli@nvidia.com", "source campaign author and path owner"
),
"minimax2.7-b200-fpm": Collector(
"Kimi Zhao", "kimiz@nvidia.com", "source campaign author and path owner"
),
}
LEGACY_MODEL_DIRECTORIES = tuple(
sorted(
{
re.sub(
r"[^a-z0-9._-]+", "-", campaign.model_id.rsplit("/", 1)[-1].lower()
).strip("-")
for campaign in CAMPAIGNS.values()
}
)
)
PRIMARY_FPM_SOURCE_PATHS = {
"dsv4flash-b200-static-baseline-fpm/fpm/fpm_forward_perf.dsv4flash_kvwarm_db_dep4.parquet",
"dsv4flash-b200-static-baseline-fpm/fpm/fpm_forward_perf.dsv4flash_kvwarm_db_tep4.parquet",
"dsv4pro-gb300-fpm/fpm/dep8-kvon-full4096-j3521395-3545915/data/gb300/vllm/0.26.0/fpm_forward_perf.parquet",
"dsv4pro-gb300-fpm/fpm/tep8-kvon-full4096-j3521393-3529760/data/gb300/vllm/0.26.0/fpm_forward_perf.parquet",
"glm52-gb200-dep16-disagg-fpm-fidelity/fpm/dep16-kvon-pairs-realseed-dg-chunks-j7024594-7025934-7052366/data/gb200/vllm/0.28.0/fpm_forward_perf.parquet",
"glm52-b200-static-baseline-fpm/fpm/fpm_forward_perf.glm52_kvwarm_db.parquet",
"glm52-b200-static-baseline-fpm/fpm/fpm_forward_perf.glm52_kvwarm_db_dep8.parquet",
"glm52-b200-static-baseline-fpm/fpm/fpm_forward_perf.glm52_realseed_db_dep8.parquet",
"glm52-b200-static-baseline-fpm/fpm/fpm_forward_perf.glm52_realseed_db_tep8.parquet",
"kimi-k3-gb300-fpm/fpm/fpm_forward_perf.kvoff_cap4096_gb300_vllmdev19262.parquet",
"kimi-k3-gb300-fpm/fpm/fpm_forward_perf.kvon_cap4096_gb300_vllmdev19262.parquet",
"minimax-e9-b200-ragged-commonmode/fpm/fpm_forward_perf.e9v2_b200_tep4.parquet",
"minimax-m27-h200-generational-verify-dep4-tp4-fpm/fpm/fpm_forward_perf.mm27_h200_r17_release.parquet",
"minimax-m27-h200-static-baseline-fpm/fpm/fpm_forward_perf.mm27_h200_tep4_kvwarm.parquet",
"minimax2.7-b200-fpm/fpm/fpm_forward_perf.warm_repaired_b200_vllm0251.parquet",
}
DISCARDED_FPM_SOURCE_PATHS: dict[str, str] = {
"glm52-gb200-dep16-disagg-fpm-fidelity/fpm/dep16-kvon-realseed-dg-j6838798-6971217/data/gb200/vllm/0.28.0/fpm_forward_perf.parquet": (
"Superseded by the paired-rows decode cell; its 12-row decode grid has no (x, x+1) capture-rung pairs, so aisimulate cannot bracket off-lattice batches. Kept in the source as the fidelity-report reference."
),
}
HISTORICAL_FPM_SOURCE_PATHS = {
"dsv4pro-gb300-fpm/fpm/dep8-kvon-full4096-j3521395/data/gb300/vllm/0.26.0/fpm_forward_perf.parquet": (
"Historical r4 library; superseded by the worker-pinned prefill-lane library (j3545915) with identical decode rows, and its r4 score evidence remains published."
),
"dsv4pro-gb300-fpm/fpm/tep8-kvoff-full4096-j3521394-3522180/data/gb300/vllm/0.26.0/fpm_forward_perf.parquet": (
"Historical r3 library; retained because its prefill rows differ from the shipped r9 library and its score evidence remains published."
),
"dsv4pro-gb300-fpm/fpm/tep8-kvon-full4096-j3521393/data/gb300/vllm/0.26.0/fpm_forward_perf.parquet": (
"Historical r3 library; retained because its prefill rows differ from the shipped r9 library and its score evidence remains published."
),
}
MEASUREMENT_EVIDENCE_PATHS = {
"dsv4flash-b200-static-baseline-fpm": (
"measurements/dep4/benchmark_dep4_decode_warmon_unitruth.json.gz",
"measurements/dep4/benchmark_dep4_decode_warmon_unitruthx4.json.gz",
"measurements/dep4/benchmark_dep4_prefill_warmon_ptruthx6.json.gz",
"measurements/dep4/benchmark_dep4_prefill_warmon_ptruthx6c.json.gz",
"measurements/tep4/benchmark_tep4_decode_warmon_unitruth.json.gz",
"measurements/tep4/benchmark_tep4_decode_warmon_unitruthx4.json.gz",
"measurements/tep4/benchmark_tep4_prefill_warmon_ptruthx6.json.gz",
"measurements/tep4/benchmark_tep4_prefill_warmon_ptruthx6c.json.gz",
),
"dsv4pro-gb300-fpm": (),
"glm52-gb200-dep16-disagg-fpm-fidelity": (),
"glm52-b200-static-baseline-fpm": (
"measurements/glm_b200_dep8/benchmark_results_glm_dep8_decode_base_merged.json.gz",
"measurements/glm_b200_dep8/benchmark_results_glm_dep8_prefill_base_merged.json",
"measurements/glm_b200_tep8/benchmark_results_glm_tep8_decode_base_merged.json",
"measurements/glm_b200_tep8/benchmark_results_glm_tep8_prefill_base_merged.json",
),
"kimi-k3-gb300-fpm": (
"measurements/r4/fpm_stream_decode.jsonl.gz",
"measurements/r4/fpm_stream_prefill.jsonl.gz",
),
"minimax-e9-b200-ragged-commonmode": (
"measurements/truth/fpm_stream_decode.jsonl.gz",
"measurements/v2/benchmark_results_70102041_merged.json.gz",
),
"minimax-m27-h200-generational-verify-dep4-tp4-fpm": (
"measurements/trace_truth_dep4/fpm_stream.jsonl.gz",
"measurements/trace_truth_tp4/fpm_stream.jsonl.gz",
),
"minimax-m27-h200-static-baseline-fpm": (
"measurements/benchmark_results_mm_tep4_decode_base_merged.json",
"measurements/benchmark_results_mm_tep4_prefill_base_merged.json",
),
"minimax2.7-b200-fpm": (
"measurements/dep4/c16/fpm_stream_decode.jsonl.gz",
"measurements/dep4/c32/fpm_stream_decode.jsonl.gz",
"measurements/dep4/c64/fpm_stream_decode.jsonl.gz",
"measurements/tep4/c4/fpm_stream_decode.jsonl.gz",
"measurements/tep4/c4/fpm_stream_prefill.jsonl.gz",
"measurements/tep4/c16/fpm_stream_decode.jsonl.gz",
"measurements/tep4/c16/fpm_stream_prefill.jsonl.gz",
"measurements/tep4/c32/fpm_stream_decode.jsonl.gz",
"measurements/tep4/c32/fpm_stream_prefill.jsonl.gz",
"measurements/tep4/c64/fpm_stream_decode.jsonl.gz",
"measurements/tep4/c64/fpm_stream_prefill.jsonl.gz",
),
}
# Reviewed non-truth evidence published beside a protocol bundle (role supporting_evidence,
# stored under measurements/provenance/): summaries, client exports, and raw streams.
SUPPORTING_EVIDENCE_PATHS = {
"glm52-gb200-dep16-disagg-fpm-fidelity": (
"measurements/truth/disagg16-truth-v2-j6924441/truth_table_decode.csv.gz",
"measurements/truth/disagg16-truth-v2-j6924441/truth_table_prefill.csv.gz",
"measurements/truth/disagg16-truth-v2-j6924441/truth_report_decode.txt",
"measurements/truth/disagg16-truth-v2-j6924441/truth_report_prefill.txt",
"measurements/truth/disagg16-truth-v2-j6924441/aiperf_c16.json",
"measurements/truth/disagg16-truth-v2-j6924441/aiperf_c32.json",
"measurements/truth/disagg16-truth-v2-j6924441/aiperf_c64.json",
"measurements/truth/disagg16-truth-v2-j6924441/aiperf_c128.json",
"measurements/truth/disagg16-truth-v2-j6924441/fpm_summary_node0.json",
"measurements/truth/disagg16-truth-v2-j6924441/fpm_summary_node1.json",
"measurements/truth/disagg16-truth-v2-j6924441/fpm_summary_node2.json",
"measurements/truth/disagg16-truth-v2-j6924441/fpm_summary_node3.json",
"measurements/truth/disagg16-truth-v2-j6924441/fpm_summary_node4.json",
"measurements/truth/disagg16-truth-v2-j6924441/fpm_summary_node5.json",
"measurements/truth/disagg16-truth-v2-j6924441/fpm_summary_node6.json",
"measurements/truth/disagg16-truth-v2-j6924441/fpm_summary_node7.json",
"measurements/truth/disagg16-truth-v2-j6924441/fpm_streams_provenance.json",
"measurements/truth/disagg16-truth-v2-j6924441/fpm_stream_prefill.jsonl.gz",
"measurements/truth/disagg16-truth-v2-j6924441/fpm_stream_decode.jsonl.gz",
),
}
@dataclass(frozen=True)
class ListenerWindowNormalization:
"""Reconstruct forward-pass-measurement-v1 iterations from rank-event streams.
Ports the campaign's documented step join (``truth_table.py`` v3): ranks are grouped
into clock groups (one per node), each non-reference group's clock offset is the
median receive-time delta of long busy steps matched against the reference group,
and records are then clustered on the corrected timeline into half-open windows
that hold at most one record per DP rank.
"""
engine_roles: Mapping[str, str]
expected_dp_ranks: tuple[int, ...]
ranks_per_clock: int
window_ms: float
long_step_ms: float
match_tolerance_s: float
wall_tolerance: float
min_matches: int
tight_window_s: float
producer: Mapping[str, str]
collector_path: str
CLOCK_CORRECTION_METHOD = "shared-long-step-offset-median-v3"
LISTENER_WINDOW_NORMALIZATIONS = {
"glm52-gb200-dep16-disagg-fpm-fidelity": ListenerWindowNormalization(
engine_roles={
"prefill": "measurements/truth/disagg16-truth-v2-j6924441/fpm_stream_prefill.jsonl.gz",
"decode": "measurements/truth/disagg16-truth-v2-j6924441/fpm_stream_decode.jsonl.gz",
},
expected_dp_ranks=tuple(range(16)),
ranks_per_clock=4,
window_ms=8.0,
long_step_ms=150.0,
match_tolerance_s=1.5,
wall_tolerance=0.15,
min_matches=30,
tight_window_s=0.05,
producer={
"component": "dynamo.vllm InstrumentedScheduler forward-pass-metrics publisher",
"version": "ai-dynamo 1.5.0, vLLM 0.28.0 (dynamo-ci ed5a4e6466bec188def5b5f24b67e8b775a5d279-65755723-vllm-arm64)",
"source_revision": "ed5a4e6466bec188def5b5f24b67e8b775a5d279",
},
collector_path="harness/jet/payloads/fpm_listener.py",
),
}
# Per-role normalization summaries collected during import for the audit report.
LISTENER_WINDOW_SUMMARIES: list[dict[str, object]] = []
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as stream:
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def stable_json(value: object) -> str:
return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
def write_json(path: Path, value: object) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
payload = (
json.dumps(value, indent=2, sort_keys=True, ensure_ascii=False, allow_nan=False)
+ "\n"
)
atomic_write_text(path, payload)
def atomic_write_text(path: Path, payload: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
descriptor, temporary_name = tempfile.mkstemp(
prefix=f".{path.name}.", dir=path.parent
)
try:
with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
stream.write(payload)
os.replace(temporary_name, path)
path.chmod(0o644)
except BaseException:
Path(temporary_name).unlink(missing_ok=True)
raise
def write_gzip_csv(
path: Path, fieldnames: Sequence[str], rows: Iterable[Mapping[str, object]]
) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
descriptor, temporary_name = tempfile.mkstemp(
prefix=f".{path.name}.", dir=path.parent
)
try:
with (
os.fdopen(descriptor, "wb") as raw_stream,
gzip.GzipFile(
filename="", mode="wb", fileobj=raw_stream, mtime=0
) as gzip_stream,
io.TextIOWrapper(gzip_stream, encoding="utf-8", newline="") as text_stream,
):
writer = csv.DictWriter(
text_stream, fieldnames=fieldnames, lineterminator="\n"
)
writer.writeheader()
writer.writerows(rows)
os.replace(temporary_name, path)
path.chmod(0o644)
except BaseException:
Path(temporary_name).unlink(missing_ok=True)
raise
def read_csv(path: Path) -> list[dict[str, str]]:
opener: Callable[..., Any] = gzip.open if path.suffix == ".gz" else open
with opener(path, "rt", encoding="utf-8", newline="") as stream:
return list(csv.DictReader(stream))
def git_output(repository: Path, *arguments: str) -> str:
return subprocess.run(
["git", "-C", str(repository), *arguments],
check=True,
capture_output=True,
text=True,
).stdout.strip()
def source_repository_root(source_root: Path) -> Path:
result = git_output(source_root, "rev-parse", "--show-toplevel")
return Path(result).resolve()
def validate_source(source_root: Path) -> tuple[Path, str, str]:
if not source_root.is_dir():
raise FileNotFoundError(f"source root does not exist: {source_root}")
repository = source_repository_root(source_root)
revision = git_output(repository, "rev-parse", "HEAD")
if revision != SOURCE_REVISION:
raise ValueError(
f"expected AISimPlayground {SOURCE_REVISION}, found {revision}"
)
commit_time = git_output(repository, "show", "-s", "--format=%cI", revision)
missing = sorted(
campaign for campaign in CAMPAIGNS if not (source_root / campaign).is_dir()
)
if missing:
raise FileNotFoundError(f"missing source campaigns: {', '.join(missing)}")
return repository, revision, commit_time
def safe_relative(path: str) -> PurePosixPath:
relative = PurePosixPath(path)
if relative.is_absolute() or ".." in relative.parts or not relative.parts:
raise ValueError(f"unsafe repository path: {path!r}")
return relative
def destination_path(root: Path, relative: str) -> Path:
safe = safe_relative(relative)
destination = (root / Path(*safe.parts)).resolve()
if root.resolve() not in destination.parents:
raise ValueError(f"path escapes dataset root: {relative!r}")
return destination
def prepare_destination(root: Path, replace: bool) -> None:
resolved = root.resolve()
if resolved == Path(resolved.anchor) or resolved == Path.home().resolve():
raise ValueError(f"refusing broad destination: {resolved}")
if not (resolved / "README.md").is_file():
raise ValueError(f"destination is not the dataset checkout: {resolved}")
generated = (
"catalog",
"data",
"fpm",
"measurements",
"pairs",
"history",
"audit",
*LEGACY_MODEL_DIRECTORIES,
)
existing = [resolved / name for name in generated if (resolved / name).exists()]
if existing and not replace:
raise FileExistsError(
"generated dataset paths exist; pass --replace to rebuild them"
)
for path in existing:
shutil.rmtree(path)
def source_to_destination_path(campaign: str, source_relative: str) -> str:
source = PurePosixPath(source_relative)
if source.parts[0] == "fpm":
return str(PurePosixPath("fpm", campaign, *source.parts[1:]))
if source.parts[0] == "measurements":
return str(PurePosixPath("measurements", campaign, *source.parts[1:]))
raise ValueError(f"unsupported source namespace: {source_relative}")
def copy_source_file(source: Path, destination: Path) -> None:
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source, destination)
def parquet_row_count(path: Path) -> int:
return pq.ParquetFile(path).metadata.num_rows
def schema_fingerprint(path: Path) -> str:
schema = pq.read_schema(path).remove_metadata()
return hashlib.sha256(str(schema).encode("utf-8")).hexdigest()
def distinct_column_strings(table: pa.Table, column: str) -> list[str]:
return sorted(
{str(value) for value in table[column].to_pylist() if value is not None}
)
def fpm_identity_correction_record(campaign_id: str) -> dict[str, object] | None:
policy = FPM_IDENTITY_CORRECTIONS.get(campaign_id)
if policy is None:
return None
return {
"policy_id": FPM_IDENTITY_CORRECTION_POLICY_ID,
"source_revision": SOURCE_REVISION,
"scope": "all_rows",
"model_path": policy.model_path,
"reason": (
"The source Parquet recorded planned dtype labels instead of the "
"effective runtime identity."
),
"changes": [
{
"column": column,
"source_value": source_value,
"published_value": published_value,
}
for column, source_value, published_value in policy.changes
],
"preserved_columns": list(FPM_IDENTITY_PRESERVED_COLUMNS),
}
def require_fpm_column_value(
table: pa.Table, column: str, expected: str, *, context: str
) -> None:
if column not in table.column_names:
raise ValueError(f"{context} has no {column!r} column")
actual = set(table[column].to_pylist())
if actual != {expected}:
rendered = sorted(repr(value) for value in actual)
raise ValueError(
f"{context} has unexpected {column}: expected {expected!r}, "
f"found {rendered}"
)
def apply_fpm_identity_correction(
table: pa.Table, campaign_id: str
) -> tuple[pa.Table, dict[str, object] | None]:
policy = FPM_IDENTITY_CORRECTIONS.get(campaign_id)
correction_record = fpm_identity_correction_record(campaign_id)
if policy is None:
return table, correction_record
context = f"source FPM for campaign {campaign_id!r}"
require_fpm_column_value(table, "model_path", policy.model_path, context=context)
require_fpm_column_value(
table,
"gemm_quant_mode",
policy.gemm_quant_mode,
context=context,
)
changed_columns = {column for column, _, _ in policy.changes}
preserved_overlap = changed_columns & set(FPM_IDENTITY_PRESERVED_COLUMNS)
if preserved_overlap:
raise RuntimeError(
f"FPM correction policy changes preserved columns: {sorted(preserved_overlap)}"
)
for column, source_value, _ in policy.changes:
require_fpm_column_value(table, column, source_value, context=context)
missing_preserved = sorted(
set(FPM_IDENTITY_PRESERVED_COLUMNS) - set(table.column_names)
)
if missing_preserved:
raise ValueError(
f"{context} lacks preserved columns: {', '.join(missing_preserved)}"
)
preserved = {column: table[column] for column in FPM_IDENTITY_PRESERVED_COLUMNS}
corrected = table
for column, _, published_value in policy.changes:
index = corrected.schema.get_field_index(column)
field = corrected.schema.field(index)
values = pa.array([published_value] * corrected.num_rows, type=field.type)
corrected = corrected.set_column(index, field, values)
for column, values in preserved.items():
if not corrected[column].equals(values):
raise RuntimeError(f"FPM correction unexpectedly changed {column!r}")
return corrected, correction_record
def validate_fpm_identity_correction(
table: pa.Table,
metadata: Mapping[str, object],
campaign_id: str,
*,
context: str,
) -> None:
policy = FPM_IDENTITY_CORRECTIONS.get(campaign_id)
expected_record = fpm_identity_correction_record(campaign_id)
actual_record = metadata.get(FPM_IDENTITY_CORRECTION_FIELD)
if policy is None:
if actual_record is not None:
raise ValueError(f"{context} has an unapproved FPM identity correction")
return
require_fpm_column_value(table, "model_path", policy.model_path, context=context)
require_fpm_column_value(
table,
"gemm_quant_mode",
policy.gemm_quant_mode,
context=context,
)
for column, _, published_value in policy.changes:
require_fpm_column_value(table, column, published_value, context=context)
if actual_record != expected_record:
raise ValueError(f"{context} has a missing or invalid FPM identity correction")
def topology_label(
strategy_value: object, tp_value: object, dp_value: object, moe_ep_value: object
) -> str:
strategy = str(strategy_value)
if strategy == "single" or re.search(r"\d$", strategy):
return strategy
if strategy == "dep":
return f"dep{int(dp_value)}"
if strategy == "tep":
return f"tep{int(moe_ep_value)}"
if strategy == "pure_tp":
return f"pure_tp{int(tp_value)}"
return strategy
def topology_phase_configurations(table: pa.Table) -> list[str]:
rows = zip(
table["parallel_strategy"].to_pylist(),
table["tp"].to_pylist(),
table["dp"].to_pylist(),
table["moe_ep"].to_pylist(),
table["workload_kind"].to_pylist(),
)
return sorted(
{
f"{topology_label(strategy, tp, dp, moe_ep)}/{phase}"
for strategy, tp, dp, moe_ep, phase in rows
}
)
def classify_fpm(source_relative: str) -> tuple[str, str | None]:
name = PurePosixPath(source_relative).name
if source_relative in PRIMARY_FPM_SOURCE_PATHS:
return "primary", None
historical_reason = HISTORICAL_FPM_SOURCE_PATHS.get(source_relative)
if historical_reason:
return "historical", historical_reason
if "r16_release" in name:
return "historical", "Historical FPM release."
return "comparator", None
def read_sidecar(
path: Path, expected_sha: str, expected_rows: int
) -> dict[str, object]:
value = json.loads(path.read_text(encoding="utf-8"))
if value.get("parquet_sha256") != expected_sha:
raise ValueError(f"sidecar hash mismatch: {path}")
if value.get("row_count") != expected_rows:
raise ValueError(f"sidecar row-count mismatch: {path}")
if value.get("schema_version") != 6:
raise ValueError(f"unsupported FPM schema version in {path}")
return value
def reconstruct_sidecar(
destination: Path, source_relative: str, digest: str, rows: int
) -> None:
write_json(
destination,
{
"backend": "vllm",
"metadata_provenance": "reconstructed_from_parquet",
"notes": "The upstream metadata sidecar is unavailable; identity fields are read from the Parquet payload.",
"parquet_sha256": digest,
"row_count": rows,
"schema_name": "aic_fpm_forward_perf",
"schema_version": 6,
"source_path": f"playground/{source_relative}",
"source_repository": SOURCE_REPOSITORY,
"source_revision": SOURCE_REVISION,
},
)
def copy_fpm_assets(
source_root: Path, destination_root: Path
) -> tuple[list[dict[str, object]], list[dict[str, str]]]:
records: list[dict[str, object]] = []
dispositions: list[dict[str, str]] = []
for campaign in sorted(CAMPAIGNS):
campaign_root = source_root / campaign
for source in sorted((campaign_root / "fpm").rglob("*.parquet")):
source_relative = (
f"{campaign}/{source.relative_to(campaign_root).as_posix()}"
)
discarded_reason = DISCARDED_FPM_SOURCE_PATHS.get(source_relative)
if discarded_reason:
dispositions.append(
{
"source_path": f"playground/{source_relative}",
"disposition": "discarded",
"reason": discarded_reason,
}
)
continue
relative_within_campaign = source.relative_to(campaign_root).as_posix()
destination_relative = source_to_destination_path(
campaign, relative_within_campaign
)
destination = destination_path(destination_root, destination_relative)
copy_source_file(source, destination)
digest = sha256_file(destination)
rows = parquet_row_count(destination)
schema = pq.read_schema(destination)
missing_columns = sorted(REQUIRED_FPM_COLUMNS - set(schema.names))
if missing_columns:
raise ValueError(
f"{source} lacks FPM columns: {', '.join(missing_columns)}"
)
identity_table = pq.read_table(
destination,
columns=[
"system",
"backend",
"backend_version",
"parallel_strategy",
"workload_kind",
"tp",
"dp",
"moe_ep",
],
)
source_sidecar = source.with_suffix(".metadata.json")
destination_sidecar = destination.with_suffix(".metadata.json")
if source_sidecar.is_file():
read_sidecar(source_sidecar, digest, rows)
copy_source_file(source_sidecar, destination_sidecar)
sidecar_provenance = "source"
else:
reconstruct_sidecar(destination_sidecar, source_relative, digest, rows)
sidecar_provenance = "reconstructed"
role, reason = classify_fpm(source_relative)
artifact_id = (
f"fpm-{hashlib.sha256(destination_relative.encode()).hexdigest()[:16]}"
)
records.append(
{
"fpm_artifact_id": artifact_id,
"campaign_id": campaign,
"model_id": CAMPAIGNS[campaign].model_id,
"gpu_family": CAMPAIGNS[campaign].gpu_family,
"path": destination_relative,
"sha256": digest,
"bytes": destination.stat().st_size,
"row_count": rows,
"schema_name": "aic_fpm_forward_perf",
"schema_version": 6,
"schema_fingerprint": schema_fingerprint(destination),
"metadata_path": destination_sidecar.relative_to(
destination_root.resolve()
).as_posix(),
"metadata_provenance": sidecar_provenance,
"role": role,
"status_reason": reason,
"systems": distinct_column_strings(identity_table, "system"),
"backends": distinct_column_strings(identity_table, "backend"),
"backend_versions": distinct_column_strings(
identity_table, "backend_version"
),
"topologies": sorted(
{
configuration.split("/", 1)[0]
for configuration in topology_phase_configurations(
identity_table
)
}
),
"configurations": topology_phase_configurations(identity_table),
"phases": distinct_column_strings(identity_table, "workload_kind"),
"source_path": f"playground/{source_relative}",
"source_revision": SOURCE_REVISION,
}
)
dispositions.append(
{
"source_path": f"playground/{source_relative}",
"disposition": "copied",
"reason": role,
}
)
return records, dispositions
def measurement_role(path: Path, campaign_id: str, source_relative: str) -> str:
name = path.name.lower()
if "window" in name:
return "window"
if "config" in name or path.suffix in {".yaml", ".yml"}:
return "configuration"
if "manifest" in name:
return "manifest"
if CAMPAIGNS[campaign_id].measurement_protocol_id is None:
return "supporting_evidence"
if source_relative in SUPPORTING_EVIDENCE_PATHS.get(campaign_id, ()):
return "supporting_evidence"
return "truth"
def is_fpm_producer_configuration(record: Mapping[str, object]) -> bool:
return (
record["campaign_id"] == "dsv4pro-gb300-fpm"
and "/measurements/lanes/" in f"/{record['source_path']}"
)
def job_ids(value: object) -> set[str]:
return set(re.findall(r"(?<!\d)\d{7}(?!\d)", str(value)))
def selected_evidence_sources(campaign_root: Path, campaign: str) -> list[Path]:
selected: set[Path] = set()
supporting = SUPPORTING_EVIDENCE_PATHS.get(campaign, ())
overlap = set(MEASUREMENT_EVIDENCE_PATHS[campaign]) & set(supporting)
if overlap:
raise ValueError(
f"{campaign}: paths listed as both truth and supporting evidence: {sorted(overlap)}"
)
for relative in (*MEASUREMENT_EVIDENCE_PATHS[campaign], *supporting):
path = campaign_root / relative
if not path.is_file():
raise FileNotFoundError(f"missing reviewed measurement evidence: {path}")
selected.add(path)
measurements = campaign_root / "measurements"
for pattern in (
"**/*windows*.tsv",
"**/*resolved-config*.json",
"**/*.yaml",
"**/*.yml",
"**/*manifest*.jsonl",
):
selected.update(path for path in measurements.glob(pattern) if path.is_file())
if campaign == "dsv4flash-b200-static-baseline-fpm":
selected.update(
path for path in measurements.glob("points/*truth*.json") if path.is_file()
)
return sorted(selected)
def create_dsv4pro_derived_truth(
campaign_root: Path,
destination_root: Path,
campaign: str,
) -> list[dict[str, object]]:
records: list[dict[str, object]] = []
patterns = (
"predictions/dep8/scores_decode_kvon_all.csv.gz",
"predictions/dep8/scores_prefill_kvon_all.csv",
"predictions/dep8/scores_decode_kvon_c1.csv",
"predictions/dep8/scores_prefill_kvon_c1.csv",
"predictions/dep8-r6pin/scores_decode_kvon_c*.csv.gz",
"predictions/dep8-r6pin/scores_prefill_kvon_all.csv",
"predictions/tep8-r3/scores_decode_kvon_all.csv.gz",
"predictions/tep8-r3/scores_prefill_kvon_all.csv",
"predictions/tep8-r8/scores_decode_kvon_c*.csv.gz",
"predictions/tep8-r8/scores_prefill_kvon_all.csv",
"predictions/tep8-r9/scores_decode_kvon_c*.csv.gz",
"predictions/tep8-r9/scores_prefill_kvon_all.csv",
)
sources = sorted(
{
source
for pattern in patterns
for source in campaign_root.glob(pattern)
if source.is_file()
}
)
if len(sources) != DSV4PRO_DERIVED_TRUTH_SOURCES:
raise ValueError(
f"expected {DSV4PRO_DERIVED_TRUTH_SOURCES} reviewed DSV4-Pro truth sources, found {len(sources)}"
)
for source in sources:
relative = source.relative_to(campaign_root).as_posix()
source_rows = read_csv(source)
output_rows: list[dict[str, object]] = []
seen: set[tuple[object, ...]] = set()
for index, row in enumerate(source_rows):
if row.get("side") != "new":
continue
phase = source_phase(source)
batch_size = optional_int(row, "b", "bp")
total_prefill_tokens = (
optional_int(row, "tot") if phase == "prefill" else None
)
total_kv_read_tokens = optional_int(row, "kv")
truth = finite_positive(row.get("truth"))
if truth is None:
continue
key = (phase, batch_size, total_prefill_tokens, total_kv_read_tokens, truth)
if key in seen:
continue
seen.add(key)
source_path = f"playground/{campaign}/{relative}"
output_rows.append(
{
"measurement_id": hashlib.sha256(
f"{source_path}|{index + 2}".encode()
).hexdigest()[:24],
"phase": phase,
"batch_size": batch_size or "",
"total_prefill_tokens": total_prefill_tokens or "",
"total_kv_read_tokens": total_kv_read_tokens or "",
"truth_latency_ms": repr(truth),
"source_file": source_path,
"source_row": index + 2,
}
)
topology = topology_from_name(source)
series = source.parent.name
output_prefix = "tep8" if series == "tep8-r3" else series
slice_match = re.search(r"_(c\d+)\.csv(?:\.gz)?$", source.name)
slice_suffix = f"-{slice_match.group(1)}" if slice_match else ""
output_relative = (
f"measurements/{campaign}/derived-truth/"
f"{output_prefix or topology}-{source_phase(source)}{slice_suffix}.csv.gz"
)
output = destination_path(destination_root, output_relative)
write_gzip_csv(output, DERIVED_TRUTH_FIELDS, output_rows)
records.append(
{
"measurement_file_id": f"measurement-{hashlib.sha256(output_relative.encode()).hexdigest()[:16]}",
"campaign_id": campaign,
"path": output_relative,
"sha256": sha256_file(output),
"bytes": output.stat().st_size,
"role": "derived_truth",
"source_path": f"playground/{campaign}/{relative}",
"source_sha256": sha256_file(source),
"source_revision": SOURCE_REVISION,
"derived": True,
}
)
return records
def estimate_clock_offsets(
spec: ListenerWindowNormalization,
times: array.array,
ranks: array.array,
walls_ms: array.array,
busy: array.array,
) -> tuple[dict[int, float], list[dict[str, object]]]:
"""Cross-clock offsets from long busy steps shared in lockstep (truth_table.py v3).
The first rank of each clock group represents its clock; the lowest clock is the
reference. Every long step of another clock is matched to the nearest reference
long step within ``match_tolerance_s`` whose wall time agrees within
``wall_tolerance``; the offset is the median of the tight cluster of deltas.
"""
per_clock_long: dict[int, list[tuple[float, float]]] = {}
for index in range(len(times)):
rank = ranks[index]
if rank % spec.ranks_per_clock != 0:
continue
if not busy[index] or walls_ms[index] <= spec.long_step_ms:
continue
per_clock_long.setdefault(rank // spec.ranks_per_clock, []).append(
(times[index], walls_ms[index])
)
clocks = sorted({rank // spec.ranks_per_clock for rank in spec.expected_dp_ranks})
reference = clocks[0]
ref_long = sorted(per_clock_long.get(reference, ()))
ref_times = [item[0] for item in ref_long]
offsets = {reference: 0.0}
groups: list[dict[str, object]] = []
for clock in clocks:
group: dict[str, object] = {
"clock_id": f"node{clock}",
"dp_ranks": [
rank
for rank in spec.expected_dp_ranks
if rank // spec.ranks_per_clock == clock
],
"offset": 0.0,
}
if clock != reference:
deltas: list[float] = []
for time_value, wall in sorted(per_clock_long.get(clock, ())):
low = bisect.bisect_left(ref_times, time_value - spec.match_tolerance_s)
high = bisect.bisect_right(
ref_times, time_value + spec.match_tolerance_s
)
best: float | None = None
for position in range(low, high):
if abs(ref_long[position][1] - wall) <= spec.wall_tolerance * wall:
delta = ref_long[position][0] - time_value
if best is None or abs(delta) < abs(best):
best = delta
if best is not None:
deltas.append(best)
deltas.sort()
if len(deltas) >= spec.min_matches:
median = deltas[len(deltas) // 2]
tight = [d for d in deltas if abs(d - median) < spec.tight_window_s]
offsets[clock] = statistics.median(tight) if tight else median
group["offset"] = offsets[clock]
group["matches"] = len(deltas)
group["tight_matches"] = len(tight)
group["status"] = "estimated"
else:
offsets[clock] = 0.0
group["matches"] = len(deltas)
group["tight_matches"] = 0
group["status"] = "insufficient_matches_assumed_zero"
else:
group["status"] = "reference"
groups.append(group)
return offsets, groups
def normalize_listener_window_streams(
campaign_root: Path, destination_root: Path, campaign: str
) -> list[dict[str, object]]:
spec = LISTENER_WINDOW_NORMALIZATIONS[campaign]
expected = list(spec.expected_dp_ranks)
expected_set = set(expected)
records: list[dict[str, object]] = []
scratch = destination_root / ".normalize" / campaign
scratch.mkdir(parents=True, exist_ok=True)
for role, relative in sorted(spec.engine_roles.items()):
source = campaign_root / relative
if not source.is_file():
raise FileNotFoundError(f"missing rank-event stream: {source}")
raw_path = scratch / f"{role}.jsonl"
opener: Callable[..., Any] = gzip.open if source.suffix == ".gz" else open
with opener(source, "rb") as stream, raw_path.open("wb") as raw:
shutil.copyfileobj(stream, raw, 1024 * 1024)
times = array.array("d")
walls_s = array.array("d")
walls_ms = array.array("d")
ranks = array.array("i")
busy = array.array("b")
offsets_in_file = array.array("q")
lengths = array.array("i")
position = 0
with raw_path.open("rb") as raw:
for line in raw:
length = len(line)
record = json.loads(line)
receive = record.get("_recv_ts")
if not isinstance(receive, (int, float)) or isinstance(receive, bool):
raise TypeError(f"{source}: record without numeric _recv_ts")
wall = record.get("wall_time")
if not isinstance(wall, (int, float)) or isinstance(wall, bool):
raise TypeError(f"{source}: record without numeric wall_time")
rank = int(record["dp_rank"])
if rank not in expected_set:
raise ValueError(f"{source}: unexpected dp_rank {rank}")
scheduled = record.get("scheduled_requests") or {}
requests = int(scheduled.get("num_prefill_requests") or 0) + int(
scheduled.get("num_decode_requests") or 0
)
times.append(float(receive))
walls_s.append(float(wall))
walls_ms.append(float(wall) * 1000.0)
ranks.append(rank)
busy.append(1 if requests > 0 else 0)
offsets_in_file.append(position)
lengths.append(length)
position += length
total = len(times)
if total == 0:
raise ValueError(f"{source}: empty rank-event stream")
clock_offsets, groups = estimate_clock_offsets(
spec, times, ranks, walls_ms, busy
)
decimal_clock_offsets = {
clock: Decimal(str(offset)) for clock, offset in clock_offsets.items()
}
def exact_corrected_time(
index: int,
*,
rank_values: array.array = ranks,
receive_times: array.array = times,
offset_values: Mapping[int, Decimal] = decimal_clock_offsets,
) -> Decimal:
clock = rank_values[index] // spec.ranks_per_clock
return Decimal(str(receive_times[index])) + offset_values[clock]
corrected = array.array(
"d",
(
times[index] + clock_offsets[ranks[index] // spec.ranks_per_clock]
for index in range(total)
),
)
order = pc.sort_indices(
pa.table(
{
"t": pa.array(corrected, pa.float64()),
"rank": pa.array(ranks, pa.int32()),
}
),
sort_keys=[("t", "ascending"), ("rank", "ascending")],
).to_pylist()
# Binary-float sorting is memory efficient for the multi-million-record raw
# streams. Resolve ties using the exact JSON-number semantics consumed by the
# protocol adapter so the first member remains the declared window anchor.
tie_start = 0
while tie_start < len(order):
tie_end = tie_start + 1
tie_value = corrected[order[tie_start]]
while tie_end < len(order) and corrected[order[tie_end]] == tie_value:
tie_end += 1
if tie_end - tie_start > 1:
order[tie_start:tie_end] = sorted(
order[tie_start:tie_end],
key=lambda index: (exact_corrected_time(index), ranks[index]),
)
tie_start = tie_end
clock_correction = {
"method": CLOCK_CORRECTION_METHOD,
"reference_clock_id": groups[0]["clock_id"],
"offset_unit": "s",
"groups": groups,
}
window = {
"size": spec.window_ms,
"unit": "ms",
"anchor": "earliest_corrected_receive_timestamp",
"boundary": "half_open",
"distinct_by": "dp_rank",
}
producer = dict(spec.producer)
collector = {
"kind": "custom_script",
"component": PurePosixPath(spec.collector_path).name,
"path": f"playground/{campaign}/{spec.collector_path}",
"source_revision": SOURCE_REVISION,
}
output_relative = (
f"measurements/{campaign}/canonical/fpm_iterations_{role}.jsonl.gz"
)
output = destination_path(destination_root, output_relative)
output.parent.mkdir(parents=True, exist_ok=True)
iterations = 0
complete_count = 0
emitted_records = 0
window_size_s = Decimal(str(spec.window_ms)) / Decimal(1000)
def emit(
members: list[int],
start: Decimal,
sequence: int,
*,
rank_values: array.array = ranks,
wall_values: array.array = walls_s,
role_value: str = role,
producer_value: Mapping[str, str] = producer,
collector_value: Mapping[str, str] = collector,
correction_value: Mapping[str, object] = clock_correction,
window_value: Mapping[str, object] = window,
file_offsets: array.array = offsets_in_file,
line_lengths: array.array = lengths,
) -> None:
nonlocal iterations, complete_count, emitted_records
members = sorted(members, key=lambda index: rank_values[index])
member_ranks = [rank_values[index] for index in members]
complete = member_ranks == expected
max_wall = (
max(wall_values[index] for index in members) if complete else None
)
window_start = str(start)
head = {
"version": 1,
"source_kind": "rank_event_stream",
"iteration_id": f"{role_value}-{sequence:07d}-{window_start}",
"producer": producer_value,
"collector": collector_value,
"grouping": {
"method": "listener_receive_time_window",
"authority": "derived",
"performed_by": f"{DATASET_ID} scripts/manage_dataset.py import",
"key": f"{role_value}:{window_start}:s:{spec.window_ms:g}ms:half_open:dp_rank",
"engine_role": role_value,
"source_field": "_recv_ts",
"source_unit": "s",
"clock_correction": correction_value,
"window": window_value,
"window_start": window_start,
},
"expected_dp_ranks": expected,
"complete": complete,
"max_rank_wall_time": max_wall,
}
payload = json.dumps(head, separators=(",", ":"), allow_nan=False)
parts = []
for index in members:
raw.seek(file_offsets[index])
parts.append(raw.read(line_lengths[index]).rstrip(b"\r\n"))
gz.write(
payload[:-1].encode("utf-8")
+ b',"rank_measurements":['
+ b",".join(parts)
+ b"]}\n"
)
iterations += 1
complete_count += 1 if complete else 0
emitted_records += len(members)
descriptor, temporary_name = tempfile.mkstemp(
prefix=f".{output.name}.", dir=output.parent
)
try:
with (
raw_path.open("rb") as raw,
os.fdopen(descriptor, "wb") as raw_out,
gzip.GzipFile(filename="", mode="wb", fileobj=raw_out, mtime=0) as gz,
):
current: list[int] = []
current_ranks: set[int] = set()
current_start: Decimal | None = None
sequence = 0
for index in order:
time_value = exact_corrected_time(index)
rank = ranks[index]
if (
current
and current_start is not None
and time_value - current_start < window_size_s
and rank not in current_ranks
):
current.append(index)
current_ranks.add(rank)
continue
if current:
assert current_start is not None
emit(current, current_start, sequence)
sequence += 1
current, current_ranks, current_start = [index], {rank}, time_value
if current:
assert current_start is not None
emit(current, current_start, sequence)
os.replace(temporary_name, output)
output.chmod(0o644)
except BaseException:
Path(temporary_name).unlink(missing_ok=True)
raise
if emitted_records != total:
raise RuntimeError(
f"{source}: normalized {emitted_records} records, expected {total}"
)
raw_path.unlink()
LISTENER_WINDOW_SUMMARIES.append(
{
"campaign_id": campaign,
"engine_role": role,
"records": total,
"iterations": iterations,
"complete_iterations": complete_count,
"clock_groups": groups,
"window_ms": spec.window_ms,
}
)
records.append(
{
"measurement_file_id": f"measurement-{hashlib.sha256(output_relative.encode()).hexdigest()[:16]}",
"campaign_id": campaign,
"path": output_relative,
"sha256": sha256_file(output),
"bytes": output.stat().st_size,
"role": "truth",
"source_path": f"playground/{campaign}/{relative}",
"source_sha256": sha256_file(source),
"source_revision": SOURCE_REVISION,
"derived": True,
}
)
shutil.rmtree(destination_root / ".normalize", ignore_errors=True)
return records
def copy_measurements(
source_root: Path, destination_root: Path
) -> tuple[list[dict[str, object]], list[dict[str, object]]]:
records: list[dict[str, object]] = []
fpm_provenance: list[dict[str, object]] = []
for campaign in sorted(CAMPAIGNS):
campaign_root = source_root / campaign
for source in selected_evidence_sources(campaign_root, campaign):
relative_within_campaign = source.relative_to(campaign_root).as_posix()
destination_relative = source_to_destination_path(
campaign, relative_within_campaign
)
destination = destination_path(destination_root, destination_relative)
copy_source_file(source, destination)
record = {
"measurement_file_id": f"measurement-{hashlib.sha256(destination_relative.encode()).hexdigest()[:16]}",
"campaign_id": campaign,
"path": destination_relative,
"sha256": sha256_file(destination),
"bytes": destination.stat().st_size,
"role": measurement_role(
destination, campaign, relative_within_campaign
),
"source_path": f"playground/{campaign}/{relative_within_campaign}",
"source_sha256": sha256_file(source),
"source_revision": SOURCE_REVISION,
"derived": False,
}
if is_fpm_producer_configuration(record):
fpm_provenance.append(record)
else:
records.append(record)
if campaign == "dsv4pro-gb300-fpm":
derived_records = create_dsv4pro_derived_truth(
campaign_root, destination_root, campaign
)
records.extend(derived_records)
if campaign in LISTENER_WINDOW_NORMALIZATIONS:
records.extend(
normalize_listener_window_streams(
campaign_root, destination_root, campaign
)
)
return records, fpm_provenance
def source_phase(path: Path) -> str:
if "prefill" in path.name:
return "prefill"
if "decode" in path.name:
return "decode"
if path.name.startswith(
("r16base_", "r17_", "scores_e9v2_", "aic_q8b_", "scores_dep4_", "scores_tep4_")
):
return "decode"
return "mixed"
def topology_from_name(path: Path) -> str:
for topology in ("dep8", "tep8", "dep4", "tep4", "pure_tp4"):
if topology in path.as_posix():
return topology
return "single"
def finite_positive(value: object) -> float | None:
try:
number = float(value)
except (TypeError, ValueError):
return None
return number if math.isfinite(number) and number > 0.0 else None
def optional_int(record: Mapping[str, str], *names: str) -> int | None:
for name in names:
value = record.get(name)
if value not in {None, ""}:
try:
return int(float(value))
except ValueError:
return None
return None
def write_parquet(path: Path, records: Sequence[Mapping[str, object]]) -> None:
if not records:
raise ValueError(f"cannot write empty catalog: {path}")
path.parent.mkdir(parents=True, exist_ok=True)
# Arrow infers top-level keys from the first row. Preserve optional fields
# that occur only on later externally contributed measurement rows.
fields = sorted({key for record in records for key in record})
table = pa.Table.from_pylist([{key: record.get(key) for key in fields} for record in records])
if path.exists() and table.to_pylist() == pq.read_table(path).to_pylist():
return # Preserve byte identity for unchanged catalogs.
pq.write_table(table, path, compression="zstd", version="2.6")
FPM_CONFIGURATION_FIELDS = (
"model_path",
"system",
"backend",
"backend_version",
"weight_quantization",
"kv_cache_dtype",
"parallel_strategy",
"tp",
"pp",
"dp",
"moe_tp",
"moe_ep",
"cp",
)
def path_component(value: object) -> str:
component = re.sub(r"[^a-z0-9.-]+", "-", str(value).lower()).strip("-")
if not component:
raise ValueError(f"cannot create a path component from {value!r}")
return component
def hf_model_component(model_id: object) -> str:
parts = str(model_id).split("/")
if len(parts) != 2 or any(
not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", part) for part in parts
):
raise ValueError(f"invalid Hugging Face model ID: {model_id!r}")
return "--".join(parts)
def configuration_path(identity: Mapping[str, object]) -> str:
model = hf_model_component(identity["model_id"])
system = path_component(identity["system"])
framework = path_component(identity["framework"])
framework_version = path_component(identity["framework_version"])
parallelism = path_component(identity["parallelism"])
return str(
PurePosixPath("data", model, system, framework, framework_version, parallelism)
)
def history_snapshot_path(configuration: str, snapshot_id: str) -> str:
relative = safe_relative(configuration)
if relative.parts[0] != "data" or len(relative.parts) != 6:
raise ValueError(f"invalid configuration path: {configuration}")
return str(PurePosixPath("data", "history", *relative.parts[1:], snapshot_id))
def configuration_groups(
path: Path, campaign: Campaign
) -> list[tuple[dict[str, object], dict[str, object]]]:
table = pq.read_table(path)
rows = table.select(FPM_CONFIGURATION_FIELDS).to_pylist()
unique = {stable_json(row): row for row in rows}
groups: list[tuple[dict[str, object], dict[str, object]]] = []
for row in sorted(unique.values(), key=stable_json):
topology = topology_label(
row["parallel_strategy"], row["tp"], row["dp"], row["moe_ep"]
)
identity = {
"model_id": campaign.model_id,
"model_revision": campaign.model_revision,
"system": row["system"],
"gpu_family": campaign.gpu_family,
"framework": row["backend"],
"framework_version": row["backend_version"],
"parallelism": topology,
"parallel_strategy": row["parallel_strategy"],
"tp": row["tp"],
"pp": row["pp"],
"dp": row["dp"],
"moe_tp": row["moe_tp"],
"moe_ep": row["moe_ep"],
"cp": row["cp"],
"weight_quantization": row["weight_quantization"],
"kv_cache_dtype": row["kv_cache_dtype"],
}
groups.append((identity, row))
return groups
def filter_configuration(table: pa.Table, selector: Mapping[str, object]) -> pa.Table:
mask: pa.Array | None = None
for name, expected in selector.items():
column = table[name]
comparison = (
pa.compute.is_null(column)
if expected is None
else pa.compute.equal(column, pa.scalar(expected, type=column.type))
)
mask = comparison if mask is None else pa.compute.and_(mask, comparison)
selected = table if mask is None else table.filter(mask)
if selected.num_rows == 0:
raise ValueError(f"configuration selector matched no rows: {selector}")
return selected
def fpm_generation(record: Mapping[str, object], parallelism: str) -> str:
campaign = str(record["campaign_id"])
source = str(record["source_path"])
if campaign == "dsv4pro-gb300-fpm" and parallelism == "tep8":
return f"{campaign}:r3" if record["role"] == "historical" else f"{campaign}:r9"
# DEP8 rounds are told apart by their prefill-lane job ids; extend per round.
if (
campaign == "dsv4pro-gb300-fpm"
and parallelism == "dep8"
and ("-3545915" in source or "-3545916" in source)
):
return f"{campaign}:r6pin"
if campaign == "minimax-m27-h200-generational-verify-dep4-tp4-fpm":
return f"{campaign}:r16" if "r16_release" in source else f"{campaign}:r17"
return campaign
def generation_priority(generation: str) -> int:
suffix = generation.rsplit(":", 1)[-1]
return {"r3": 0, "r6pin": 2, "r8": 1, "r9": 2, "r16": 0, "r17": 1}.get(suffix, 1)
def ensure_snapshot(
snapshots: dict[tuple[str, str], Snapshot],
configuration: str,
generation: str,
campaign_id: str,
identity: Mapping[str, object],
) -> Snapshot:
key = (configuration, generation)
existing = snapshots.get(key)
if existing is not None:
return existing
snapshot = Snapshot(
configuration_path=configuration,
generation_id=generation,
campaign_id=campaign_id,
identity=dict(identity),
evidence_date=GENERATION_EVIDENCE_DATES.get(
generation, CAMPAIGNS[campaign_id].evidence_date
),
)
snapshots[key] = snapshot
return snapshot
def add_dsv4pro_r8_snapshot(
snapshots: dict[tuple[str, str], Snapshot],
) -> None:
campaign_id = "dsv4pro-gb300-fpm"
generation = f"{campaign_id}:r9"
candidates = [
snapshot
for snapshot in snapshots.values()
if snapshot.campaign_id == campaign_id
and snapshot.generation_id == generation
and snapshot.identity["parallelism"] == "tep8"
]
if len(candidates) != 1:
raise ValueError(
f"expected one DSV4-Pro TEP8 r9 snapshot, found {len(candidates)}"
)
r9 = candidates[0]
shared_assets = [
(path, asset)
for path, asset in r9.fpm_assets.items()
if "tep8-kvon-full4096-j3521393-3529760" in path
]
if len(shared_assets) != 1:
raise ValueError(
f"expected one DSV4-Pro r8/r9 shared FPM, found {len(shared_assets)}"
)
r8 = ensure_snapshot(
snapshots,
r9.configuration_path,
f"{campaign_id}:r8",
campaign_id,
r9.identity,
)
path, asset = shared_assets[0]
r8.fpm_assets[path] = {**asset, "base_occurrence": False}
def normalized_aisim_commit(value: object) -> tuple[str | None, bool]:
if not isinstance(value, str):
return None, False
match = re.fullmatch(r"([0-9a-f]{40})(?:-dirty-[0-9a-f]+)?", value.lower())
return (match.group(1), "-dirty-" in value) if match else (None, False)
def assign_snapshot_identity(snapshot: Snapshot, staging_root: Path) -> None:
revisions: set[str] = set()
commits: set[str] = set()
dirty = False
for asset in snapshot.fpm_assets.values():
source_record = asset["source_record"]
assert isinstance(source_record, Mapping)
metadata = load_json(
destination_path(staging_root, str(source_record["metadata_path"]))
)
if not isinstance(metadata, Mapping):
raise TypeError("malformed source FPM metadata")
revision = metadata.get("aisim_commit", metadata.get("aic_revision"))
if isinstance(revision, str):
revisions.add(revision)
commit, is_dirty = normalized_aisim_commit(revision)
if commit:
commits.add(commit)
dirty = dirty or is_dirty
snapshot.producer_revisions = tuple(sorted(revisions))
if len(commits) == 1:
snapshot.aisim_commit = next(iter(commits))
snapshot.aisim_commit_status = "dirty" if dirty else "recorded"
snapshot.snapshot_id = f"aisim-commit-{snapshot.aisim_commit[:8]}"
return
if len(commits) > 1:
snapshot.aisim_commit_status = "mixed"
digest_seed = stable_json(
{
"configuration": snapshot.configuration_path,
"generation": snapshot.generation_id,
"fpm": sorted(snapshot.fpm_assets),
"measurements": sorted(
str(record["path"])
for record in (*snapshot.measurements, *snapshot.fpm_provenance)
),
}
)
digest = hashlib.sha256(digest_seed.encode("utf-8")).hexdigest()[:8]
snapshot.snapshot_id = f"aisim-commit-unknown-{digest}"
def measurement_topology(path: str) -> str | None:
normalized = path.lower().replace("-", "_")
if "trace_truth_tp4" in normalized or "pure_tp4" in normalized:
return "pure_tp4"
for topology in ("dep8", "tep8", "dep4", "tep4"):
if topology in normalized:
return topology
return None
def measurement_matches_snapshot(
record: Mapping[str, object], snapshot: Snapshot
) -> bool:
if record["campaign_id"] != snapshot.campaign_id:
return False
topology = measurement_topology(str(record["path"]))
if topology is not None and topology != snapshot.identity["parallelism"]:
return False
if snapshot.campaign_id != "dsv4pro-gb300-fpm" or topology not in {"tep8", "dep8"}:
return True
path = str(record["path"]).lower()
release = snapshot.generation_id.rsplit(":", 1)[-1]
if topology == "dep8":
# r6pin evidence: its truth run and the two pinned prefill lanes; extend per round.
pinned = "r6pin" in path or "j3545915" in path or "j3545916" in path
return pinned if release == "r6pin" else not pinned
if release == "r9":
return "r9" in path or "j3529760" in path or "j3530507" in path
if release == "r8":
return "r8" in path or "j3529760" in path
if release == "r3":
return not (
"r8" in path or "r9" in path or "j3529760" in path or "j3530507" in path
)
return False
def fpm_output_name(source_path: str, single_asset: bool) -> str:
if single_asset:
return "fpm_forward_perf.parquet"
lowered = source_path.lower()
variants = (
(("realseed", "real-seed"), "real-seeded"),
(("nokvwarm", "nowarm", "kvoff"), "kv-off"),
(("kvwarm", ".warm", "kvon"), "kv-on"),
)
for needles, label in variants:
if any(needle in lowered for needle in needles):
return f"fpm_forward_perf.{label}.parquet"
relative = PurePosixPath(source_path)
name = relative.name
if name != "fpm_forward_perf.parquet":
return name
try:
fpm_index = relative.parts.index("fpm")
variant = relative.parts[fpm_index + 1]
except (ValueError, IndexError):
variant = hashlib.sha256(source_path.encode("utf-8")).hexdigest()[:8]
return f"fpm_forward_perf.{path_component(variant)}.parquet"
def collector_fields(campaign_id: str) -> dict[str, object]:
collector = COLLECTORS[campaign_id]
return {
"collected_by": {"name": collector.name, "email": collector.email},
"collector_attribution": collector.attribution,
}
def snapshot_identity_fields(snapshot: Snapshot) -> dict[str, object]:
return {
**snapshot.identity,
"configuration_path": snapshot.configuration_path,
"snapshot_id": snapshot.snapshot_id,
"snapshot_status": snapshot.snapshot_status,
"evidence_date": snapshot.evidence_date,
"aisim_commit": snapshot.aisim_commit,
"aisim_commit_status": snapshot.aisim_commit_status,
"producer_revisions": list(snapshot.producer_revisions),
**collector_fields(snapshot.campaign_id),
}
def publish_fpm_provenance_files(
snapshot: Snapshot,
source_record: Mapping[str, object],
staging_root: Path,
destination_root: Path,
) -> tuple[list[dict[str, object]], set[str]]:
source_jobs = job_ids(source_record["source_path"])
matches = [
record
for record in snapshot.fpm_provenance
if source_jobs & job_ids(record["source_path"])
]
published: list[dict[str, object]] = []
consumed: set[str] = set()
campaign_prefix = PurePosixPath("measurements", snapshot.campaign_id, "lanes")
for record in sorted(matches, key=lambda item: str(item["path"])):
old_relative = PurePosixPath(str(record["path"]))
try:
payload_relative = old_relative.relative_to(campaign_prefix)
except ValueError as error:
raise ValueError(
f"unexpected FPM producer configuration path: {old_relative}"
) from error
relative = str(
PurePosixPath(snapshot.output_root, "fpm", "provenance", payload_relative)
)
source = destination_path(staging_root, str(old_relative))
destination = destination_path(destination_root, relative)
copy_source_file(source, destination)
copied_sha = sha256_file(destination)
if copied_sha != record["sha256"]:
raise ValueError(
f"FPM producer configuration copy changed content: {old_relative}"
)
published.append(
{
"path": relative,
"sha256": copied_sha,
"role": "producer_configuration",
"source_path": record["source_path"],
"source_sha256": record["source_sha256"],
}
)
consumed.add(str(record["path"]))
return published, consumed
def publish_fpm_assets(
snapshot: Snapshot, staging_root: Path, destination_root: Path
) -> list[dict[str, object]]:
records: list[dict[str, object]] = []
used_names: set[str] = set()
consumed_provenance: set[str] = set()
for old_path, asset in sorted(snapshot.fpm_assets.items()):
source_record = asset["source_record"]
selector = asset["configuration_selector"]
assert isinstance(source_record, Mapping)
assert isinstance(selector, Mapping)
source_data = destination_path(staging_root, old_path)
table = filter_configuration(pq.read_table(source_data), selector)
table, identity_correction = apply_fpm_identity_correction(
table, snapshot.campaign_id
)
output_name = fpm_output_name(
str(source_record["source_path"]), len(snapshot.fpm_assets) == 1
)
if output_name in used_names:
stem = PurePosixPath(output_name).stem
suffix = hashlib.sha256(old_path.encode("utf-8")).hexdigest()[:8]
output_name = f"{stem}.{suffix}.parquet"
used_names.add(output_name)
relative = str(PurePosixPath(snapshot.output_root, "fpm", output_name))
destination = destination_path(destination_root, relative)
destination.parent.mkdir(parents=True, exist_ok=True)
pq.write_table(table, destination, compression="zstd", version="2.6")
digest = sha256_file(destination)
source_metadata_path = destination_path(
staging_root, str(source_record["metadata_path"])
)
source_metadata = load_json(source_metadata_path)
if not isinstance(source_metadata, Mapping):
raise TypeError(f"malformed FPM metadata: {source_metadata_path}")
producer_revision = source_metadata.get(
"aisim_commit", source_metadata.get("aic_revision")
)
metadata = {
key: value
for key, value in source_metadata.items()
if key
not in {
"aic_revision",
"aisim_commit",
"parquet_sha256",
"producer_configuration_files",
"row_count",
"source_path",
"source_revision",
FPM_IDENTITY_CORRECTION_FIELD,
}
}
metadata.update(
{
"aisim_commit": snapshot.aisim_commit,
"aisim_commit_status": snapshot.aisim_commit_status,
"producer_revision": producer_revision,
"parquet_sha256": digest,
"row_count": table.num_rows,
"source_parquet_path": source_record["source_path"],
"source_parquet_sha256": source_record["sha256"],
"source_parquet_row_count": source_record["row_count"],
"source_metadata_sha256": sha256_file(source_metadata_path),
"source_repository": SOURCE_REPOSITORY,
"source_revision": SOURCE_REVISION,
"configuration_selector": dict(selector),
**collector_fields(snapshot.campaign_id),
}
)
if identity_correction is not None:
metadata[FPM_IDENTITY_CORRECTION_FIELD] = identity_correction
producer_configuration_files, consumed = publish_fpm_provenance_files(
snapshot, source_record, staging_root, destination_root
)
if producer_configuration_files:
metadata["producer_configuration_files"] = producer_configuration_files
overlap = consumed_provenance & consumed
if overlap:
raise ValueError(
f"FPM producer configurations match multiple artifacts: {sorted(overlap)}"
)
consumed_provenance.update(consumed)
metadata_relative = str(PurePosixPath(relative).with_suffix(".metadata.json"))
write_json(destination_path(destination_root, metadata_relative), metadata)
partition_seed = f"{source_record['source_path']}|{stable_json(selector)}"
partition_id = hashlib.sha256(partition_seed.encode("utf-8")).hexdigest()[:24]
artifact_id = f"fpm-{hashlib.sha256(relative.encode()).hexdigest()[:16]}"
phases = distinct_column_strings(table, "workload_kind")
record = {
"fpm_artifact_id": artifact_id,
**snapshot_identity_fields(snapshot),
"path": relative,
"sha256": digest,
"bytes": destination.stat().st_size,
"row_count": table.num_rows,
"schema_name": "aic_fpm_forward_perf",
"schema_version": 6,
"schema_fingerprint": schema_fingerprint(destination),
"metadata_path": metadata_relative,
"role": source_record["role"],
"status_reason": source_record["status_reason"],
"phases": phases,
"source_partition_id": partition_id,
"base_occurrence": bool(asset["base_occurrence"]),
"source_path": source_record["source_path"],
"source_sha256": source_record["sha256"],
"source_row_count": source_record["row_count"],
"source_revision": SOURCE_REVISION,
"source_campaign_id": snapshot.campaign_id,
}
snapshot.published_fpm[old_path] = record
records.append(record)
expected_provenance = {str(record["path"]) for record in snapshot.fpm_provenance}
if consumed_provenance != expected_provenance:
missing = sorted(expected_provenance - consumed_provenance)
raise ValueError(
f"FPM producer configurations do not match an artifact: {missing}"
)
return records
def measurement_payload_path(
snapshot: Snapshot,
source_record: Mapping[str, object],
payload_relative: PurePosixPath,
duplicate_truth_names: set[str],
) -> PurePosixPath:
role = str(source_record["role"])
if role not in MEASUREMENT_TRUTH_ROLES:
parts = payload_relative.parts
if parts[0] == "provenance":
return payload_relative
if parts[0] in {"derived-truth", "truth"}:
parts = parts[1:]
if not parts:
raise ValueError(
f"measurement provenance has no payload path: {payload_relative}"
)
return PurePosixPath("provenance", *parts)
name = payload_relative.name
if name not in duplicate_truth_names:
return PurePosixPath(name)
parents = list(payload_relative.parts[:-1])
parallelism = str(snapshot.identity["parallelism"]).replace("_", "-")
if parents and parents[0].replace("_", "-") == parallelism:
parents.pop(0)
if not parents:
raise ValueError(
f"cannot disambiguate measurement truth path: {payload_relative}"
)
prefix = "-".join(parents)
return PurePosixPath(f"{prefix}-{name}")
def publish_measurements(
snapshot: Snapshot, staging_root: Path, destination_root: Path
) -> tuple[list[dict[str, object]], dict[str, object]]:
records: list[dict[str, object]] = []
campaign_prefix = PurePosixPath("measurements", snapshot.campaign_id)
truth_names = Counter(
PurePosixPath(str(record["path"])).name
for record in snapshot.measurements
if record["role"] in MEASUREMENT_TRUTH_ROLES
)
duplicate_truth_names = {name for name, count in truth_names.items() if count > 1}
published_paths: set[str] = set()
for source_record in sorted(
snapshot.measurements, key=lambda item: str(item["path"])
):
old_relative = PurePosixPath(str(source_record["path"]))
try:
payload_relative = old_relative.relative_to(campaign_prefix)
except ValueError as error:
raise ValueError(f"unexpected measurement path: {old_relative}") from error
legacy_relative = str(
PurePosixPath(snapshot.output_root, "measurements", payload_relative)
)
relative = str(
PurePosixPath(
snapshot.output_root,
"measurements",
measurement_payload_path(
snapshot,
source_record,
payload_relative,
duplicate_truth_names,
),
)
)
if relative in published_paths:
raise ValueError(f"duplicate published measurement path: {relative}")
published_paths.add(relative)
source = destination_path(staging_root, str(old_relative))
destination = destination_path(destination_root, relative)
copy_source_file(source, destination)
copied_sha = sha256_file(destination)
if copied_sha != source_record["sha256"]:
raise ValueError(f"measurement copy changed content: {old_relative}")
record = {
"measurement_file_id": f"measurement-{hashlib.sha256(legacy_relative.encode()).hexdigest()[:16]}",
**snapshot_identity_fields(snapshot),
"path": relative,
"sha256": copied_sha,
"bytes": destination.stat().st_size,
"role": source_record["role"],
"source_path": source_record["source_path"],
"source_sha256": source_record["source_sha256"],
"source_revision": SOURCE_REVISION,
"source_campaign_id": snapshot.campaign_id,
"derived": source_record["derived"],
}
records.append(record)
manifest_relative = str(
PurePosixPath(snapshot.output_root, "measurements", "manifest.json")
)
artifact_id = (
f"measurements-{hashlib.sha256(manifest_relative.encode()).hexdigest()[:16]}"
)
campaign = CAMPAIGNS[snapshot.campaign_id]
evidence_format_id = campaign.evidence_format_id if records else None
manifest = {
"manifest_version": MEASUREMENT_MANIFEST_VERSION,
"measurement_artifact_id": artifact_id,
**snapshot_identity_fields(snapshot),
"measurement_protocol_id": campaign.measurement_protocol_id,
"files": records,
"provenance": {
"source_repository": SOURCE_REPOSITORY,
"source_revision": SOURCE_REVISION,
"source_campaign_id": snapshot.campaign_id,
"source_campaign_path": f"playground/{snapshot.campaign_id}",
},
}
if evidence_format_id is not None:
manifest["evidence_format_id"] = evidence_format_id
write_json(destination_path(destination_root, manifest_relative), manifest)
published = {
"artifact_id": artifact_id,
"protocol_id": campaign.measurement_protocol_id,
"manifest_path": manifest_relative,
"manifest_sha256": sha256_file(
destination_path(destination_root, manifest_relative)
),
"file_count": len(records),
}
if evidence_format_id is not None:
published["evidence_format_id"] = evidence_format_id
snapshot.published_measurement_manifest = published
return records, published
def write_snapshot_manifest(
snapshot: Snapshot,
destination_root: Path,
history: Sequence[Mapping[str, object]] = (),
) -> tuple[str, dict[str, object]]:
manifest_relative = str(PurePosixPath(snapshot.output_root, "manifest.json"))
payload: dict[str, object] = {
"manifest_version": CONFIGURATION_MANIFEST_VERSION,
**snapshot_identity_fields(snapshot),
"fpm": [
{
"artifact_id": record["fpm_artifact_id"],
"path": record["path"],
"sha256": record["sha256"],
"row_count": record["row_count"],
"metadata_path": record["metadata_path"],
"role": record["role"],
"phases": record["phases"],
}
for record in snapshot.published_fpm.values()
],
"measurements": snapshot.published_measurement_manifest,
"provenance": {
"source_repository": SOURCE_REPOSITORY,
"source_revision": SOURCE_REVISION,
"source_campaign_id": snapshot.campaign_id,
"source_campaign_path": f"playground/{snapshot.campaign_id}",
},
}
if history:
payload["history"] = list(history)
write_json(destination_path(destination_root, manifest_relative), payload)
return manifest_relative, payload
def build_snapshots(
staging_root: Path,
fpm_records: Sequence[Mapping[str, object]],
measurement_records: Sequence[Mapping[str, object]],
fpm_provenance_records: Sequence[Mapping[str, object]],
) -> list[Snapshot]:
snapshots: dict[tuple[str, str], Snapshot] = {}
for source_record in fpm_records:
old_path = str(source_record["path"])
campaign_id = str(source_record["campaign_id"])
campaign = CAMPAIGNS[campaign_id]
for identity, selector in configuration_groups(
destination_path(staging_root, old_path), campaign
):
config = configuration_path(identity)
generation = fpm_generation(source_record, str(identity["parallelism"]))
snapshot = ensure_snapshot(
snapshots, config, generation, campaign_id, identity
)
asset = {
"source_record": source_record,
"configuration_selector": selector,
"base_occurrence": True,
}
snapshot.fpm_assets[old_path] = asset
add_dsv4pro_r8_snapshot(snapshots)
for snapshot in snapshots.values():
snapshot.measurements = [
dict(record)
for record in measurement_records
if measurement_matches_snapshot(record, snapshot)
]
snapshot.fpm_provenance = [
dict(record)
for record in fpm_provenance_records
if measurement_matches_snapshot(record, snapshot)
]
assign_snapshot_identity(snapshot, staging_root)
by_configuration: dict[str, list[Snapshot]] = {}
for snapshot in snapshots.values():
by_configuration.setdefault(snapshot.configuration_path, []).append(snapshot)
for config, candidates in by_configuration.items():
ranked = sorted(
candidates,
key=lambda item: (
item.evidence_date,
generation_priority(item.generation_id),
),
reverse=True,
)
best_rank = (
ranked[0].evidence_date,
generation_priority(ranked[0].generation_id),
)
if (
sum(
(item.evidence_date, generation_priority(item.generation_id))
== best_rank
for item in ranked
)
!= 1
):
raise ValueError(f"ambiguous current snapshot for {config}")
for index, snapshot in enumerate(ranked):
snapshot.snapshot_status = "current" if index == 0 else "historical"
snapshot.output_root = (
snapshot.configuration_path
if index == 0
else history_snapshot_path(
snapshot.configuration_path, snapshot.snapshot_id
)
)
return sorted(
snapshots.values(),
key=lambda item: (
item.configuration_path,
item.snapshot_status,
item.snapshot_id,
),
)
def publish_configuration_layout(
staging_root: Path,
destination_root: Path,
fpm_records: Sequence[Mapping[str, object]],
measurement_records: Sequence[Mapping[str, object]],
fpm_provenance_records: Sequence[Mapping[str, object]],
) -> tuple[
list[dict[str, object]],
list[dict[str, object]],
list[str],
list[str],
]:
snapshots = build_snapshots(
staging_root,
fpm_records,
measurement_records,
fpm_provenance_records,
)
published_fpm: list[dict[str, object]] = []
published_measurements: list[dict[str, object]] = []
for snapshot in snapshots:
published_fpm.extend(
publish_fpm_assets(snapshot, staging_root, destination_root)
)
measurement_output, _ = publish_measurements(
snapshot, staging_root, destination_root
)
published_measurements.extend(measurement_output)
manifest_paths: dict[tuple[str, str], str] = {}
for snapshot in snapshots:
manifest_path, _ = write_snapshot_manifest(snapshot, destination_root)
manifest_paths[(snapshot.configuration_path, snapshot.snapshot_id)] = (
manifest_path
)
current_manifests: list[str] = []
history_manifests: list[str] = []
for snapshot in snapshots:
manifest_path = manifest_paths[
(snapshot.configuration_path, snapshot.snapshot_id)
]
if snapshot.snapshot_status == "historical":
history_manifests.append(manifest_path)
continue
history = []
older_snapshots = sorted(
(
older
for older in snapshots
if older.configuration_path == snapshot.configuration_path
and older.snapshot_status == "historical"
),
key=lambda item: (
item.evidence_date,
generation_priority(item.generation_id),
),
reverse=True,
)
for older in older_snapshots:
older_path = manifest_paths[(older.configuration_path, older.snapshot_id)]
history.append(
{
"snapshot_id": older.snapshot_id,
"snapshot_status": "historical",
"evidence_date": older.evidence_date,
"aisim_commit": older.aisim_commit,
"manifest_path": older_path,
"manifest_sha256": sha256_file(
destination_path(destination_root, older_path)
),
}
)
write_snapshot_manifest(snapshot, destination_root, history=history)
current_manifests.append(manifest_path)
return (
published_fpm,
published_measurements,
sorted(current_manifests),
sorted(history_manifests),
)
def configuration_catalog_records(
root: Path,
current_manifests: Sequence[str],
history_manifests: Sequence[str],
) -> list[dict[str, object]]:
records: list[dict[str, object]] = []
for manifest_relative in [*current_manifests, *history_manifests]:
manifest = load_json(destination_path(root, manifest_relative))
if not isinstance(manifest, Mapping):
raise TypeError(f"malformed configuration manifest: {manifest_relative}")
fpm = manifest["fpm"]
measurements = manifest["measurements"]
provenance = manifest["provenance"]
assert isinstance(fpm, Sequence)
assert isinstance(measurements, Mapping)
assert isinstance(provenance, Mapping)
records.append(
{
"manifest_path": manifest_relative,
"manifest_sha256": sha256_file(
destination_path(root, manifest_relative)
),
**{
field: manifest[field]
for field in (
"model_id",
"model_revision",
"system",
"gpu_family",
"framework",
"framework_version",
"parallelism",
"parallel_strategy",
"tp",
"pp",
"dp",
"moe_tp",
"moe_ep",
"cp",
"weight_quantization",
"kv_cache_dtype",
"configuration_path",
"snapshot_id",
"snapshot_status",
"evidence_date",
"aisim_commit",
"aisim_commit_status",
)
},
**{
field: manifest[field]
for field in ("dcp", "physical_gpu_count", "collection_method")
if field in manifest
},
"fpm_file_count": len(fpm),
"measurement_file_count": measurements["file_count"],
"measurement_manifest_path": measurements["manifest_path"],
"measurement_manifest_sha256": measurements["manifest_sha256"],
"source_campaign_id": provenance.get("source_campaign_id"),
"source_revision": provenance["source_revision"],
}
)
return sorted(records, key=lambda record: str(record["manifest_path"]))
def write_catalogs(
root: Path,
fpm_records: Sequence[Mapping[str, object]],
measurement_records: Sequence[Mapping[str, object]],
current_manifests: Sequence[str],
history_manifests: Sequence[str],
commit_time: str,
*,
playground: Path | None = None,
catalog_version: int = CATALOG_VERSION,
) -> None:
if catalog_version not in (CATALOG_VERSION, 6):
raise ValueError(f"unsupported catalog version: {catalog_version}")
configuration_records = configuration_catalog_records(
root, current_manifests, history_manifests
)
if catalog_version == 6:
# Already-normalized importers must not rerun the historical migration.
for record in configuration_records:
record.pop("source_campaign_id", None)
write_parquet(root / "catalog" / "index.parquet", configuration_records)
write_parquet(root / "catalog" / "fpm.parquet", fpm_records)
flat_measurements = (
[
{k: v for k, v in record.items() if k != "grouping"}
for record in measurement_records
]
if catalog_version == 6
else measurement_records
)
if catalog_version == 6 and not flat_measurements:
pq.write_table(
pa.table({}), root / "catalog" / "measurements.parquet", compression="zstd"
)
else:
write_parquet(root / "catalog" / "measurements.parquet", flat_measurements)
write_json(
root / "catalog" / "fpm.json",
{"schema_version": FPM_CATALOG_VERSION, "records": list(fpm_records)},
)
write_json(
root / "catalog" / "measurements.json",
{
"schema_version": (
5 if catalog_version == 6 else MEASUREMENT_CATALOG_VERSION
),
"records": list(measurement_records),
},
)
catalog_files = {
"index_json": "catalog/index.json",
"configurations": "catalog/index.parquet",
"fpm": "catalog/fpm.parquet",
"fpm_json": "catalog/fpm.json",
"measurements": "catalog/measurements.parquet",
"measurements_json": "catalog/measurements.json",
}
index = {
"catalog_version": catalog_version,
"dataset_id": DATASET_ID,
"source": {
"repository": SOURCE_REPOSITORY,
"revision": SOURCE_REVISION,
"commit_time": commit_time,
},
"counts": {
"source_campaigns": len(set(CAMPAIGNS) | {
str(record.get("source_campaign_id")) for record in configuration_records
}),
"configurations": len(current_manifests),
"history_snapshots": len(history_manifests),
"configuration_snapshots": len(configuration_records),
"fpm_files": len(fpm_records),
"current_fpm_files": sum(
record["snapshot_status"] == "current" for record in fpm_records
),
"history_fpm_files": sum(
record["snapshot_status"] == "historical" for record in fpm_records
),
"source_fpm_files": len(
{
record["source_path"]
for record in fpm_records
if record["base_occurrence"]
}
),
"source_fpm_rows": sum(
int(record["row_count"])
for record in fpm_records
if record["base_occurrence"]
),
"measurement_bundles": len(configuration_records),
"measurement_files": len(measurement_records),
"source_measurement_files": len(
{record["source_path"] for record in measurement_records}
),
"truth_files": sum(
record["role"] in {"truth", "derived_truth"}
for record in measurement_records
),
"derived_truth_files": sum(
record["role"] == "derived_truth" for record in measurement_records
),
},
"configuration_manifests": list(current_manifests),
"history_manifests": list(history_manifests),
"catalog_files": catalog_files,
}
if catalog_version == 6:
index["counts"].pop("source_campaigns")
additional_sources = sorted({
(str(load_json(root / path)["provenance"]["source_repository"]),
str(load_json(root / path)["provenance"]["source_revision"]))
for path in [*current_manifests, *history_manifests]
} - {(SOURCE_REPOSITORY, SOURCE_REVISION)})
if additional_sources:
index["source"]["additional_sources"] = [
{"repository": repository, "revision": revision}
for repository, revision in additional_sources
]
write_json(root / "catalog" / "index.json", index)
canonical_bundle = {
"bundle_version": CANONICAL_BUNDLE_VERSION,
"dataset_id": DATASET_ID,
"source_revision": SOURCE_REVISION,
"catalog_path": "catalog/index.parquet",
"catalog_sha256": sha256_file(root / "catalog" / "index.parquet"),
"discovery_index_path": "catalog/index.json",
"discovery_index_sha256": sha256_file(root / "catalog" / "index.json"),
"catalog_files": [
{"path": path, "sha256": sha256_file(root / path)}
for path in catalog_files.values()
],
"configuration_manifests": [
{"path": path, "sha256": sha256_file(root / path)}
for path in current_manifests
],
"history_manifests": [
{"path": path, "sha256": sha256_file(root / path)}
for path in history_manifests
],
}
if additional_sources:
canonical_bundle["additional_sources"] = index["source"]["additional_sources"]
write_json(root / "catalog" / "canonical-bundle.json", canonical_bundle)
if catalog_version != 6:
migrate_measurements.migrate(root, playground)
def write_audit_reports(
root: Path,
fpm_records: Sequence[Mapping[str, object]],
measurement_records: Sequence[Mapping[str, object]],
current_manifests: Sequence[str],
history_manifests: Sequence[str],
dispositions: Sequence[Mapping[str, str]],
) -> None:
source_mapping = [
"# Source mapping",
"",
f"Source: `{SOURCE_REPOSITORY}` at `{SOURCE_REVISION}`.",
"",
"| Source campaign | Model | GPU | FPM occurrences | Measurement occurrences |",
"|---|---|---|---:|---:|",
]
for campaign, spec in sorted(CAMPAIGNS.items()):
source_mapping.append(
"| {campaign} | `{model}` | {gpu} | {fpm} | {measurements} |".format(
campaign=campaign,
model=spec.model_id,
gpu=spec.gpu_family,
fpm=sum(
record["source_campaign_id"] == campaign for record in fpm_records
),
measurements=sum(
record["source_campaign_id"] == campaign
for record in measurement_records
),
)
)
source_mapping.extend(
[
"",
"Data paths map as follows:",
"",
"- Active data → `data/<org>--<model>/<system>/<framework>/<version>/<parallelism>/{fpm,measurements}`.",
"- Superseded snapshots → `data/history/<org>--<model>/<system>/<framework>/<version>/<parallelism>/aisim-commit-*/...`.",
"- Campaign names are retained only as source provenance in manifests and catalogs.",
"- Multi-configuration FPM Parquets are split while preserving row order. A strict publish-time policy corrects declared dtype identity for DSV4-Flash, DSV4-Pro, Kimi-K3, and GLM-5.2-NVFP4.",
"- Identity correction never changes GEMM, latency, workload kind, batch size, or token coordinates. Each affected sidecar records the source and published labels.",
"- Usable measurement truth is flat under `measurements/`; summaries and helper evidence are under `measurements/provenance/`.",
"- FPM benchmark-lane configs are stored with the matching artifact under `fpm/provenance/`.",
"- Predictions, normalized comparisons, and accuracy metrics are computed by FPM Gym and are not published here.",
"",
]
)
atomic_write_text(root / "audit" / "source-mapping.md", "\n".join(source_mapping))
derived_truth = [
record for record in measurement_records if record["role"] == "derived_truth"
]
corrected_fpm = sum(
record["source_campaign_id"] in FPM_IDENTITY_CORRECTIONS
for record in fpm_records
)
fpm_provenance = [
path for path in root.glob("data/**/fpm/provenance/**/*") if path.is_file()
]
reconciliation = [
"# Reconciliation report",
"",
f"- Audited FPM Parquets: {len(dispositions)}.",
f"- Reviewed source FPM Parquets: {sum(item['disposition'] == 'copied' for item in dispositions)}.",
f"- Discarded superseded FPM Parquets: {sum(item['disposition'] == 'discarded' for item in dispositions)}.",
f"- Published configuration leaves: {len(current_manifests)}.",
f"- Published history snapshots: {len(history_manifests)}.",
f"- Published split FPM occurrences: {len(fpm_records)}.",
f"- Reconciled source FPM rows: {sum(int(record['row_count']) for record in fpm_records if record['base_occurrence'])}.",
f"- Published measurement occurrences: {len(measurement_records)}.",
f"- Reconciled source measurement files: {len({record['source_path'] for record in measurement_records})}.",
f"- Published FPM producer configuration occurrences: {len(fpm_provenance)}.",
f"- Published DSV4-Pro truth-only derivatives: {len(derived_truth)}.",
"- Stored predictions, comparison rows, pair manifests, and derived accuracy metrics: 0.",
"- Unreviewed logs, scripts, reports, per-rank duplicates, and source prediction tables are not mirrored.",
"",
"## Truth evidence",
"",
"- Reviewed raw measurement artifacts are retained for every campaign where they are available.",
f"- DSV4-Pro raw serving streams are external. Each of its {DSV4PRO_DERIVED_TRUTH_SOURCES} reviewed score sources is converted to a truth-only derivative with source path, source row, and content hash.",
"- Summary artifacts, serving-run configs, window maps, and helper manifests are measurement provenance.",
"- DSV4-Pro benchmark-lane configs are FPM provenance because they are explicitly linked to producer artifacts.",
"- FPM Gym owns source-specific parsing, exclusions, live AISim evaluation, and metrics.",
"- Measurement and prediction state rules are documented in `docs/evaluation-state-policy.md`.",
"",
"## FPM identity annotations",
"",
f"- Publish-time dtype correction applies to {corrected_fpm} FPM occurrences from DSV4-Flash, DSV4-Pro, Kimi-K3, and GLM-5.2-NVFP4.",
"- The pinned source mislabeled planned dtype identity. The importer changes only the declared MoE, FMHA, and FMHA-resolution fields listed by policy.",
"- GEMM, weight quantization, latency, workload kind, batch size, token coordinates, row order, and row count are preserved.",
"- Each affected FPM sidecar records the policy ID and exact source-to-published labels.",
"",
"## Listener-window normalization",
"",
*(
[
"- Canonical iterations reconstructed from rank-event streams with declared clock offsets and an 8 ms half-open window; every source record appears in exactly one iteration.",
*[
"- {campaign} {role}: {records:,} records -> {iterations:,} iterations ({complete:,} complete); clock offsets (s): {offsets}.".format(
campaign=summary["campaign_id"],
role=summary["engine_role"],
records=summary["records"],
iterations=summary["iterations"],
complete=summary["complete_iterations"],
offsets=", ".join(
f"{group['clock_id']}={group['offset']:+.4f} ({group.get('status')}"
+ (
f", {group['matches']} matches)"
if "matches" in group
else ")"
)
for group in summary["clock_groups"]
),
)
for summary in LISTENER_WINDOW_SUMMARIES
],
]
if LISTENER_WINDOW_SUMMARIES
else ["- No campaign requires listener-window normalization."]
),
"",
"## FPM dispositions",
"",
"| Source path | Disposition | Reason |",
"|---|---|---|",
]
reconciliation.extend(
f"| `{item['source_path']}` | {item['disposition']} | {item['reason']} |"
for item in dispositions
)
reconciliation.extend(
[
"",
"## Known gaps",
"",
"- DSV4-Pro raw serving streams are external; normalized upstream score truth is retained.",
"- DSV4-Pro TEP8 r9 is active; r8 diagnostic and r3 superseded evidence are in history.",
"- DSV4-Pro DEP8 r6pin (worker-pinned prefill lanes, decode rows identical to r4) is active; the r4 library and its evidence are in history.",
"- DSV4-Pro worker pinning remains a mitigation rather than a proven root-cause fix for the historical bimodal prefill regime.",
"- DSV4-Pro DEP8 prefill lacks the required global-active-token axis.",
"- MiniMax H200 R17 is active except at tep4, where the later static snapshot is active; R16 is history.",
"- MiniMax B200 dep4/c4 is quarantined and dep4 prefill has no retained measurement.",
"- MiniMax E9 is decode-only.",
"- GLM and MiniMax H200 static FPM anchor provenance is incomplete because original collection JSONs are lost.",
"- GLM-5.2 GB200 DEP16 truth is reconstructed at import: canonical forward-pass-measurement-v1 iterations per engine role (listener_receive_time_window join with the campaign's per-node clock correction, estimated for prefill and declared zero for decode where no shared step exceeds 150 ms, and an 8 ms half-open window; exact decimal timestamp arithmetic, every rank record retained, max_rank_wall_time cached). The campaign's published fidelity figures used the median wall over busy ranks; on complete decode steps the maximum exceeds the median by about 1% at the median (1.7% at p90, 8% at p99). Raw streams, bucketed tables, reports and aiperf exports are supporting evidence.",
"- GLM-5.2 GB200 DEP16 self-benchmark is lockstep-only: decode 3.6% and prefill 24.0% step-level MAPE against the 16/16 disaggregated truth (17.2% when all 16 ranks prefill).",
"- The GLM-5.2 GB200 DEP16 source also holds the superseded 12-row decode pair (discarded) and comparison-arm cells as point tables only; they are not imported.",
"- The snapshot contains internal provenance and has no approved redistribution license; it must remain private.",
"",
]
)
atomic_write_text(
root / "audit" / "reconciliation-report.md", "\n".join(reconciliation)
)
def load_json(path: Path) -> object:
return json.loads(path.read_text(encoding="utf-8"))
def require_hash(root: Path, relative: str, expected: str) -> Path:
path = destination_path(root, relative)
if not path.is_file():
raise FileNotFoundError(f"missing cataloged file: {relative}")
actual = sha256_file(path)
if actual != expected:
raise ValueError(
f"SHA-256 mismatch for {relative}: expected {expected}, found {actual}"
)
return path
def schema_violations(root: Path, kind: str, document: object) -> list[str]:
schema_path = DOCUMENT_SCHEMAS[kind]
if isinstance(document, Mapping):
if kind == "configuration_manifest" and document.get("manifest_version") == 4:
schema_path = "schemas/configuration-manifest-v4.schema.json"
elif kind == "measurement_manifest" and document.get("manifest_version") == 5:
schema_path = "schemas/measurement-manifest-v5.schema.json"
elif kind == "catalog_index" and document.get("catalog_version") == 6:
schema_path = "schemas/catalog-index-v6.schema.json"
validator = jsonschema.Draft202012Validator(
load_json(root / schema_path),
format_checker=jsonschema.FormatChecker(),
)
return [
"/" + "/".join(str(part) for part in error.absolute_path) + ": " + error.message
for error in sorted(
validator.iter_errors(document), key=lambda error: list(error.absolute_path)
)
]
def validate_document_schemas(
root: Path, current_manifests: Sequence[str], history_manifests: Sequence[str]
) -> None:
documents = [("catalog_index", "catalog/index.json")]
for relative in [*current_manifests, *history_manifests]:
manifest = load_json(destination_path(root, relative))
documents.append(("configuration_manifest", relative))
if isinstance(manifest, Mapping) and isinstance(
manifest.get("measurements"), Mapping
):
documents.append(
("measurement_manifest", str(manifest["measurements"]["manifest_path"]))
)
for kind, relative in documents:
violations = schema_violations(
root, kind, load_json(destination_path(root, relative))
)
if violations:
raise ValueError(
f"{relative} violates {DOCUMENT_SCHEMAS[kind]}: "
+ "; ".join(violations)
)
def validate_derived_truth_file(path: Path) -> tuple[int, set[str]]:
rows = read_csv(path)
if not rows:
raise ValueError(f"empty derived-truth file: {path}")
if tuple(rows[0]) != DERIVED_TRUTH_FIELDS:
raise ValueError(f"derived-truth schema mismatch: {path}")
measurement_ids = [row["measurement_id"] for row in rows]
if len(measurement_ids) != len(set(measurement_ids)):
raise ValueError(f"duplicate derived-truth measurement IDs: {path}")
invalid_phases = sorted({row["phase"] for row in rows} - {"decode", "prefill"})
if invalid_phases:
raise ValueError(f"invalid derived-truth phases in {path}: {invalid_phases}")
if any(finite_positive(row["truth_latency_ms"]) is None for row in rows):
raise ValueError(f"invalid derived-truth latency in {path}")
source_files = {row["source_file"] for row in rows}
if any(
not source.startswith("playground/dsv4pro-gb300-fpm/predictions/")
for source in source_files
):
raise ValueError(f"invalid derived-truth source in {path}")
return len(rows), source_files
def count_jsonl_records(path: Path) -> int:
opener: Callable[..., Any] = gzip.open if path.suffix == ".gz" else open
with opener(path, "rb") as stream:
return sum(1 for line in stream if line.strip())
def validate_canonical_iteration_file(
path: Path, spec: ListenerWindowNormalization, *, context: str
) -> tuple[int, int, str]:
"""Structural validation of a canonical forward-pass-measurement-v1 iteration stream.
Returns (iterations, rank records, engine_role). Every constraint here mirrors the
schema's x-semantic-constraints for listener_receive_time_window groupings.
"""
expected = list(spec.expected_dp_ranks)
iterations = 0
rank_records = 0
roles: set[str] = set()
window_size_s = Decimal(str(spec.window_ms)) / Decimal(1000)
with gzip.open(path, "rt", encoding="utf-8") as stream:
for line in stream:
iteration = json.loads(line)
iterations += 1
grouping = iteration.get("grouping")
if (
iteration.get("version") != 1
or iteration.get("source_kind") != "rank_event_stream"
or not isinstance(grouping, Mapping)
or grouping.get("method") != "listener_receive_time_window"
or grouping.get("authority") != "derived"
or grouping.get("source_field") != "_recv_ts"
or grouping.get("source_unit") != "s"
or not isinstance(iteration.get("collector"), Mapping)
or not isinstance(iteration.get("producer"), Mapping)
or not isinstance(iteration.get("iteration_id"), str)
):
raise ValueError(
f"{context}: iteration {iterations} is not a listener-window iteration"
)
role = str(grouping.get("engine_role"))
if role not in spec.engine_roles:
raise ValueError(f"{context}: unknown engine role {role!r}")
roles.add(role)
if iteration.get("expected_dp_ranks") != expected:
raise ValueError(
f"{context}: unexpected expected_dp_ranks in iteration {iterations}"
)
measurements = iteration.get("rank_measurements")
if not isinstance(measurements, list) or not measurements:
raise ValueError(
f"{context}: iteration {iterations} has no rank measurements"
)
ranks = [int(record["dp_rank"]) for record in measurements]
if ranks != sorted(set(ranks)) or any(
rank not in spec.expected_dp_ranks for rank in ranks
):
raise ValueError(
f"{context}: iteration {iterations} ranks are not sorted and distinct"
)
complete = ranks == expected
if iteration.get("complete") != complete:
raise ValueError(
f"{context}: iteration {iterations} has a wrong complete flag"
)
walls = [record["wall_time"] for record in measurements]
if complete:
if iteration.get("max_rank_wall_time") != max(walls):
raise ValueError(
f"{context}: iteration {iterations} max_rank_wall_time mismatch"
)
elif iteration.get("max_rank_wall_time") is not None:
raise ValueError(
f"{context}: incomplete iteration {iterations} carries a latency"
)
correction = grouping.get("clock_correction")
if (
not isinstance(correction, Mapping)
or correction.get("offset_unit") != "s"
):
raise ValueError(
f"{context}: iteration {iterations} lacks a clock correction"
)
offset_of: dict[int, Decimal] = {}
reference_offset = None
for group in correction["groups"]:
for rank in group["dp_ranks"]:
offset_of[rank] = Decimal(str(group["offset"]))
if group["clock_id"] == correction.get("reference_clock_id"):
reference_offset = Decimal(str(group["offset"]))
if sorted(offset_of) != expected or reference_offset != Decimal(0):
raise ValueError(
f"{context}: iteration {iterations} clock groups do not partition the ranks"
)
corrected = []
for record in measurements:
receive = record.get("_recv_ts")
if not isinstance(receive, (int, float)) or isinstance(receive, bool):
raise TypeError(
f"{context}: iteration {iterations} lost a raw _recv_ts"
)
corrected.append(
Decimal(str(receive)) + offset_of[int(record["dp_rank"])]
)
window_start = Decimal(str(grouping["window_start"]))
window = grouping.get("window")
if (
not isinstance(window, Mapping)
or window.get("unit") != "ms"
or float(window.get("size", 0)) != spec.window_ms
or window.get("boundary") != "half_open"
or window.get("distinct_by") != "dp_rank"
):
raise ValueError(
f"{context}: iteration {iterations} declares a different window"
)
if (
min(corrected) != window_start
or max(corrected) - window_start >= window_size_s
):
raise ValueError(
f"{context}: iteration {iterations} violates its own window"
)
rank_records += len(measurements)
if len(roles) != 1:
raise ValueError(
f"{context}: canonical file mixes engine roles {sorted(roles)}"
)
return iterations, rank_records, roles.pop()
def validate_dataset(root: Path, write_report: bool = True) -> dict[str, int]:
if load_json(root / "catalog/index.json").get("catalog_version") == 6:
return migrate_measurements.validate(root)
for protocol_id, relative in MEASUREMENT_PROTOCOL_SCHEMAS.items():
schema = load_json(root / relative)
if (
not isinstance(schema, Mapping)
or schema.get("x-protocol-id") != protocol_id
or schema.get("$id")
!= f"https://huggingface.co/datasets/{DATASET_ID}/raw/main/{relative}"
):
raise ValueError(f"invalid measurement protocol schema: {relative}")
index = load_json(root / "catalog" / "index.json")
if (
not isinstance(index, Mapping)
or index.get("catalog_version") != CATALOG_VERSION
):
raise ValueError("unsupported or malformed catalog/index.json")
if "metric_policy" in index or "pair_manifests" in index:
raise ValueError("pair-era fields remain in catalog/index.json")
current_manifests = index.get("configuration_manifests")
history_manifests = index.get("history_manifests")
if not isinstance(current_manifests, list) or not current_manifests:
raise ValueError("catalog contains no configuration manifests")
if not isinstance(history_manifests, list):
raise TypeError("catalog history manifest list is malformed")
for paths in (current_manifests, history_manifests):
if len(paths) != len(set(paths)):
raise ValueError("catalog contains duplicate manifest paths")
if set(current_manifests) & set(history_manifests):
raise ValueError("current and history manifest lists overlap")
validate_document_schemas(root, current_manifests, history_manifests)
catalog_files = index.get("catalog_files")
expected_catalog_keys = {
"index_json",
"configurations",
"fpm",
"fpm_json",
"measurements",
"measurements_json",
}
if (
not isinstance(catalog_files, Mapping)
or set(catalog_files) != expected_catalog_keys
):
raise ValueError("catalog file map is incomplete")
canonical_bundle = load_json(root / "catalog" / "canonical-bundle.json")
if not isinstance(canonical_bundle, Mapping):
raise TypeError("malformed canonical bundle")
if (
canonical_bundle.get("bundle_version") != CANONICAL_BUNDLE_VERSION
or canonical_bundle.get("dataset_id") != DATASET_ID
or canonical_bundle.get("source_revision") != SOURCE_REVISION
or "pair_manifests" in canonical_bundle
):
raise ValueError("canonical bundle identity is invalid")
require_hash(
root,
str(canonical_bundle.get("catalog_path")),
str(canonical_bundle.get("catalog_sha256")),
)
require_hash(
root,
str(canonical_bundle.get("discovery_index_path")),
str(canonical_bundle.get("discovery_index_sha256")),
)
bundled_catalogs = canonical_bundle.get("catalog_files")
if not isinstance(bundled_catalogs, list):
raise TypeError("canonical bundle has no catalog file hashes")
bundled_paths: set[str] = set()
for file_record in bundled_catalogs:
if not isinstance(file_record, Mapping):
raise TypeError("malformed canonical catalog file record")
relative = str(file_record["path"])
require_hash(root, relative, str(file_record["sha256"]))
bundled_paths.add(relative)
if bundled_paths != {str(path) for path in catalog_files.values()}:
raise ValueError("canonical bundle catalog files do not match index")
for key, expected_paths in (
("configuration_manifests", current_manifests),
("history_manifests", history_manifests),
):
bundled = canonical_bundle.get(key)
if not isinstance(bundled, list):
raise TypeError(f"canonical bundle has no {key}")
actual_paths: set[str] = set()
for record in bundled:
if not isinstance(record, Mapping):
raise TypeError(f"canonical bundle has malformed {key}")
path = str(record["path"])
require_hash(root, path, str(record["sha256"]))
actual_paths.add(path)
if actual_paths != set(expected_paths):
raise ValueError(f"canonical bundle {key} do not match index")
snapshot_manifests: dict[str, Mapping[str, object]] = {}
grouped_measurement_files = 0
grouped_iterations = 0
grouped_rank_records = 0
bundled_measurement_records: dict[str, Mapping[str, object]] = {}
measurement_manifests: set[str] = set()
fpm_provenance_paths: set[str] = set()
external_fpm_provenance_paths: set[str] = set()
fpm_provenance_sources: set[str] = set()
expected_history_by_configuration: dict[str, set[str]] = {}
for manifest_relative in [*current_manifests, *history_manifests]:
manifest = load_json(destination_path(root, str(manifest_relative)))
if (
not isinstance(manifest, Mapping)
or manifest.get("manifest_version") != CONFIGURATION_MANIFEST_VERSION
):
raise ValueError(f"unsupported configuration manifest: {manifest_relative}")
if any(field in manifest for field in ("identity", "current", "pairs")):
raise ValueError(f"legacy field remains in manifest: {manifest_relative}")
expected_status = (
"current" if manifest_relative in current_manifests else "historical"
)
if manifest.get("snapshot_status") != expected_status:
raise ValueError(f"snapshot status mismatch: {manifest_relative}")
expected_configuration = configuration_path(manifest)
if manifest.get("configuration_path") != expected_configuration:
raise ValueError(
f"configuration identity/path mismatch: {manifest_relative}"
)
parent = PurePosixPath(str(manifest_relative)).parent.as_posix()
if expected_status == "current":
if parent != expected_configuration:
raise ValueError(
f"current manifest is outside its leaf: {manifest_relative}"
)
else:
expected_parent = history_snapshot_path(
expected_configuration, str(manifest["snapshot_id"])
)
if parent != expected_parent:
raise ValueError(
f"history manifest is outside its snapshot: {manifest_relative}"
)
expected_history_by_configuration.setdefault(
expected_configuration, set()
).add(str(manifest_relative))
provenance = manifest.get("provenance")
if not isinstance(provenance, Mapping):
raise TypeError(f"malformed snapshot provenance: {manifest_relative}")
campaign_id = provenance.get("source_campaign_id")
if not isinstance(campaign_id, str) or not campaign_id:
raise ValueError(f"invalid source campaign: {manifest_relative}")
external_campaign = campaign_id not in CAMPAIGNS
external_self_benchmark = campaign_id == SELF_BENCHMARK_CAMPAIGN
if external_self_benchmark:
external_fpm_provenance_paths.update(
validate_self_benchmark_snapshot(root, manifest)
)
if campaign_id in DSV41_CAMPAIGNS:
external_fpm_provenance_paths.update(validate_dsv41_snapshot(root, manifest))
if campaign_id in INKLING_CAMPAIGNS:
external_fpm_provenance_paths.update(validate_inkling_snapshot(root, manifest))
fpm_entries = manifest.get("fpm")
if not isinstance(fpm_entries, list):
raise ValueError(f"snapshot fpm must be an array: {manifest_relative}")
if external_campaign and fpm_entries and not external_self_benchmark and campaign_id not in DSV41_CAMPAIGNS and campaign_id not in INKLING_CAMPAIGNS:
raise ValueError("External campaign FPM libraries need a reviewed import policy")
for record in fpm_entries:
if not isinstance(record, Mapping):
raise TypeError(f"malformed FPM entry: {manifest_relative}")
data = require_hash(root, str(record["path"]), str(record["sha256"]))
if parquet_row_count(data) != record["row_count"]:
raise ValueError(f"FPM row-count mismatch: {record['path']}")
metadata = load_json(destination_path(root, str(record["metadata_path"])))
if not isinstance(metadata, Mapping) or "aic_revision" in metadata:
raise ValueError(
f"malformed or legacy FPM metadata: {record['metadata_path']}"
)
if (
metadata.get("parquet_sha256") != record["sha256"]
or metadata.get("row_count") != record["row_count"]
):
raise ValueError(f"FPM metadata mismatch: {record['path']}")
validate_fpm_identity_correction(
pq.read_table(data),
metadata,
campaign_id,
context=f"published FPM {record['path']}",
)
producer_files = metadata.get("producer_configuration_files", [])
if not isinstance(producer_files, list):
raise TypeError(
f"malformed FPM producer configuration list: {record['metadata_path']}"
)
fpm_jobs = job_ids(metadata.get("source_parquet_path", ""))
for producer_file in producer_files:
if not isinstance(producer_file, Mapping):
raise TypeError(
f"malformed FPM producer configuration: {record['metadata_path']}"
)
relative = str(producer_file.get("path"))
if "/fpm/provenance/" not in relative:
raise ValueError(
f"FPM producer configuration is outside provenance: {relative}"
)
if producer_file.get("role") != "producer_configuration":
raise ValueError(
f"invalid FPM producer configuration role: {relative}"
)
require_hash(root, relative, str(producer_file.get("sha256")))
source_path = str(producer_file.get("source_path"))
source_sha = str(producer_file.get("source_sha256"))
if (
"/measurements/lanes/" not in source_path
or not re.fullmatch(r"[0-9a-f]{64}", source_sha)
or source_sha != producer_file.get("sha256")
):
raise ValueError(
f"invalid FPM producer configuration provenance: {relative}"
)
producer_jobs = job_ids(source_path)
if not fpm_jobs & producer_jobs:
raise ValueError(
f"FPM producer configuration does not match its artifact: {relative}"
)
if relative in fpm_provenance_paths:
raise ValueError(
f"duplicate FPM producer configuration path: {relative}"
)
fpm_provenance_paths.add(relative)
fpm_provenance_sources.add(source_path)
measurements = manifest.get("measurements")
if not isinstance(measurements, Mapping):
raise TypeError(f"malformed measurements entry: {manifest_relative}")
measurement_manifest_path = str(measurements["manifest_path"])
bundle_path = require_hash(
root, measurement_manifest_path, str(measurements["manifest_sha256"])
)
measurement_manifests.add(measurement_manifest_path)
bundle = load_json(bundle_path)
if (
not isinstance(bundle, Mapping)
or bundle.get("manifest_version") != MEASUREMENT_MANIFEST_VERSION
or any(field in bundle for field in ("identity", "current", "pairs"))
):
raise ValueError(f"malformed measurement manifest: {bundle_path}")
for field in (
"configuration_path",
"snapshot_id",
"snapshot_status",
"model_id",
"system",
"framework",
"framework_version",
"parallelism",
):
if bundle.get(field) != manifest.get(field):
raise ValueError(
f"measurement identity mismatch for {field}: {bundle_path}"
)
files = bundle.get("files")
if not isinstance(files, list):
raise TypeError(f"measurement file list is malformed: {bundle_path}")
if len(files) != measurements["file_count"]:
raise ValueError(f"measurement file-count mismatch: {bundle_path}")
protocol_id = measurements.get("protocol_id")
evidence_format_id = measurements.get("evidence_format_id")
if protocol_id != bundle.get("measurement_protocol_id"):
raise ValueError(f"measurement protocol mismatch: {bundle_path}")
if evidence_format_id != bundle.get("evidence_format_id"):
raise ValueError(f"measurement evidence format mismatch: {bundle_path}")
if protocol_id is not None and protocol_id not in MEASUREMENT_PROTOCOL_IDS:
raise ValueError(f"unknown measurement protocol: {protocol_id}")
if (
evidence_format_id is not None
and evidence_format_id not in EVIDENCE_FORMAT_IDS
):
raise ValueError(
f"unknown measurement evidence format: {evidence_format_id}"
)
if protocol_id is not None and evidence_format_id is not None:
raise ValueError(
f"measurement bundle mixes protocol and evidence format: {bundle_path}"
)
if files and protocol_id is None and evidence_format_id is None:
raise ValueError(
f"measurement bundle has unclassified evidence: {bundle_path}"
)
truth_roles = {
str(record.get("role"))
for record in files
if isinstance(record, Mapping)
and record.get("role") in MEASUREMENT_TRUTH_ROLES
}
if evidence_format_id is not None and truth_roles:
raise ValueError(
f"supporting evidence is mislabeled as truth: {bundle_path}"
)
if not fpm_entries and not truth_roles:
raise ValueError("Measurement-only configuration requires usable truth")
if not fpm_entries and protocol_id is None:
raise ValueError("Measurement-only configuration requires a protocol")
expected_ranks = list(range(int(manifest["dp"])))
external_truth_files = 0
for record in files:
require_hash(root, str(record["path"]), str(record["sha256"]))
record_path = str(record["path"])
if record_path in bundled_measurement_records:
raise ValueError("Measurement payload appears in multiple bundles")
bundled_measurement_records[record_path] = record
if record.get("role") in MEASUREMENT_TRUTH_ROLES:
if record.get("representation") == PRE_GROUPED_REPRESENTATION:
if protocol_id != "forward-pass-measurement-v1":
raise ValueError("Pre-grouped records require forward-pass-measurement-v1")
iterations, ranks = validate_pre_grouped_file(root, record, expected_ranks)
grouped_measurement_files += 1
grouped_iterations += iterations
grouped_rank_records += ranks
external_truth_files += 1
elif external_campaign:
raise ValueError("External truth needs a supported, validated representation")
if external_campaign and not external_truth_files and not external_self_benchmark and campaign_id not in DSV41_CAMPAIGNS and campaign_id not in INKLING_CAMPAIGNS:
raise ValueError("External campaign has no validated truth")
snapshot_manifests[str(manifest_relative)] = manifest
for current_relative in current_manifests:
current = snapshot_manifests[str(current_relative)]
configuration = str(current["configuration_path"])
history = current.get("history", [])
if not isinstance(history, list):
raise TypeError(f"history list is malformed: {current_relative}")
referenced: set[str] = set()
for pointer in history:
if not isinstance(pointer, Mapping):
raise TypeError(f"history pointer is malformed: {current_relative}")
path = str(pointer["manifest_path"])
require_hash(root, path, str(pointer["manifest_sha256"]))
referenced.add(path)
if referenced != expected_history_by_configuration.get(configuration, set()):
raise ValueError(f"history pointers are incomplete: {current_relative}")
discovered_fpm_provenance = {
path.relative_to(root).as_posix()
for path in root.glob("data/**/fpm/provenance/**/*")
if path.is_file()
}
if discovered_fpm_provenance != fpm_provenance_paths | external_fpm_provenance_paths:
raise ValueError("FPM producer configuration provenance is not fully cataloged")
if (
len(fpm_provenance_paths),
len(fpm_provenance_sources),
) != DSV4PRO_FPM_PROVENANCE_COUNTS:
raise ValueError(
"DSV4-Pro FPM provenance does not cover all producer configurations"
)
expected_counts = index.get("counts")
if not isinstance(expected_counts, Mapping):
raise TypeError("catalog counts are malformed")
configuration_catalog = pq.read_table(root / "catalog" / "index.parquet")
expected_snapshot_paths = set(current_manifests) | set(history_manifests)
if configuration_catalog.num_rows != len(expected_snapshot_paths):
raise ValueError("configuration catalog row count mismatch")
catalog_snapshot_paths = set(configuration_catalog["manifest_path"].to_pylist())
if catalog_snapshot_paths != expected_snapshot_paths:
raise ValueError("configuration catalog manifest paths differ from index")
for record in configuration_catalog.to_pylist():
require_hash(root, str(record["manifest_path"]), str(record["manifest_sha256"]))
# Sparse identity extensions become null columns for older Parquet rows.
optional_identity = {"dcp", "physical_gpu_count", "collection_method"}
normalized_configurations = [
{key: value for key, value in row.items() if key not in optional_identity or value is not None}
for row in configuration_catalog.to_pylist()
]
if sorted(normalized_configurations, key=lambda r: r["manifest_path"]) != configuration_catalog_records(
root, current_manifests, history_manifests
):
raise ValueError("Configuration catalog metadata disagrees with manifests")
fpm_catalog = pq.read_table(root / "catalog" / "fpm.parquet")
measurement_catalog = pq.read_table(root / "catalog" / "measurements.parquet")
if fpm_catalog.num_rows != expected_counts["fpm_files"]:
raise ValueError("catalog/fpm.parquet row count mismatch")
if measurement_catalog.num_rows != expected_counts["measurement_files"]:
raise ValueError("catalog/measurements.parquet row count mismatch")
fpm_json = load_json(root / "catalog" / "fpm.json")
if (
not isinstance(fpm_json, Mapping)
or fpm_json.get("schema_version") != FPM_CATALOG_VERSION
or not isinstance(fpm_json.get("records"), list)
or len(fpm_json["records"]) != expected_counts["fpm_files"]
):
raise ValueError("catalog/fpm.json does not match the FPM catalog")
fpm_artifact_ids: set[str] = set()
fpm_catalog_paths: set[str] = set()
base_partitions: set[str] = set()
source_paths: set[str] = set()
source_rows = 0
source_row_totals: dict[str, int] = {}
source_expected_rows: dict[str, int] = {}
source_expected_hashes: dict[str, str] = {}
current_fpm_count = 0
history_fpm_count = 0
for record in fpm_json["records"]:
if not isinstance(record, Mapping):
raise TypeError("catalog/fpm.json contains a non-object record")
if any(
field in record
for field in (
"paired_pair_count",
"paired_phases",
"missing_phases",
"pairing_status",
)
):
raise ValueError("pair-era fields remain in the FPM catalog")
artifact_id = str(record["fpm_artifact_id"])
if artifact_id in fpm_artifact_ids:
raise ValueError(f"duplicate FPM artifact ID: {artifact_id}")
fpm_artifact_ids.add(artifact_id)
if record["snapshot_status"] == "current":
current_fpm_count += 1
else:
history_fpm_count += 1
data_relative = str(record["path"])
if data_relative in fpm_catalog_paths:
raise ValueError(f"duplicate FPM catalog path: {data_relative}")
fpm_catalog_paths.add(data_relative)
data_path = require_hash(root, data_relative, str(record["sha256"]))
if parquet_row_count(data_path) != record["row_count"]:
raise ValueError(f"FPM catalog row-count mismatch: {data_relative}")
campaign_id = str(record["source_campaign_id"])
if campaign_id in DSV41_CAMPAIGNS:
expected_schema_version = validate_dsv41_catalog_record(root, record)
elif campaign_id == SELF_BENCHMARK_CAMPAIGN:
expected_schema_version = validate_self_benchmark_catalog_record(root, record)
elif campaign_id in INKLING_CAMPAIGNS:
expected_schema_version = validate_inkling_catalog_record(root, record)
else:
expected_schema_version = 6
if record["schema_name"] != "aic_fpm_forward_perf" or record["schema_version"] != 6:
raise ValueError(f"unsupported FPM schema: {data_relative}")
groups = configuration_groups(data_path, CAMPAIGNS[campaign_id])
if len(groups) != 1:
raise ValueError(f"split FPM contains multiple configurations: {data_relative}")
table_identity, _ = groups[0]
if configuration_path(table_identity) != record["configuration_path"] or any(
table_identity[field] != record[field] for field in table_identity
):
raise ValueError(f"split FPM identity mismatch: {data_relative}")
metadata = load_json(destination_path(root, str(record["metadata_path"])))
if not isinstance(metadata, Mapping):
raise TypeError(f"malformed FPM metadata: {data_relative}")
if (
metadata.get("parquet_sha256") != record["sha256"]
or metadata.get("row_count") != record["row_count"]
or metadata.get("schema_version") != expected_schema_version
):
raise ValueError(f"FPM metadata mismatch: {data_relative}")
if record["base_occurrence"]:
partition = str(record["source_partition_id"])
if partition in base_partitions:
raise ValueError(f"duplicate base FPM partition: {partition}")
base_partitions.add(partition)
source_path = str(record["source_path"])
source_paths.add(source_path)
source_rows += int(record["row_count"])
source_row_totals[source_path] = source_row_totals.get(
source_path, 0
) + int(record["row_count"])
expected_rows = int(record["source_row_count"])
expected_hash = str(record["source_sha256"])
if source_path in source_expected_rows and (
source_expected_rows[source_path] != expected_rows
or source_expected_hashes[source_path] != expected_hash
):
raise ValueError(f"inconsistent source FPM identity: {source_path}")
source_expected_rows[source_path] = expected_rows
source_expected_hashes[source_path] = expected_hash
if set(fpm_catalog["fpm_artifact_id"].to_pylist()) != fpm_artifact_ids:
raise ValueError("catalog/fpm Parquet and JSON artifact IDs differ")
if set(fpm_catalog["path"].to_pylist()) != fpm_catalog_paths:
raise ValueError("catalog/fpm Parquet and JSON paths differ")
if len(source_paths) != expected_counts["source_fpm_files"]:
raise ValueError("source FPM file count does not reconcile")
if source_rows != expected_counts["source_fpm_rows"]:
raise ValueError("source FPM row count does not reconcile")
if source_row_totals != source_expected_rows:
raise ValueError("split FPM rows do not reconcile per source file")
measurement_json = load_json(root / "catalog" / "measurements.json")
if (
not isinstance(measurement_json, Mapping)
or measurement_json.get("schema_version") != MEASUREMENT_CATALOG_VERSION
or not isinstance(measurement_json.get("records"), list)
or len(measurement_json["records"]) != expected_counts["measurement_files"]
):
raise ValueError("catalog/measurements.json does not match its Parquet catalog")
measurement_ids: set[str] = set()
measurement_paths: set[str] = set()
source_measurement_hashes: dict[str, str] = {}
derived_truth_sources: set[str] = set()
derived_truth_files = 0
truth_files = 0
canonical_iteration_files: list[tuple[Path, str, str]] = []
raw_stream_paths: dict[tuple[str, str], Path] = {}
for record in measurement_json["records"]:
if not isinstance(record, Mapping):
raise TypeError("catalog/measurements.json contains a non-object record")
measurement_id = str(record["measurement_file_id"])
if measurement_id in measurement_ids:
raise ValueError(f"duplicate measurement artifact ID: {measurement_id}")
measurement_ids.add(measurement_id)
relative = str(record["path"])
if relative in measurement_paths:
raise ValueError(f"duplicate measurement catalog path: {relative}")
measurement_paths.add(relative)
path = require_hash(root, relative, str(record["sha256"]))
source_path = str(record["source_path"])
source_digest = str(record["source_sha256"])
if not re.fullmatch(r"[0-9a-f]{64}", source_digest):
raise ValueError(f"invalid measurement source hash: {relative}")
if (
source_path in source_measurement_hashes
and source_measurement_hashes[source_path] != source_digest
):
raise ValueError(
f"measurement source hash changed across copies: {source_path}"
)
source_measurement_hashes[source_path] = source_digest
if not record["derived"] and source_digest != record["sha256"]:
raise ValueError(f"raw measurement source hash mismatch: {relative}")
role = str(record["role"])
if role in MEASUREMENT_TRUTH_ROLES:
truth_files += 1
if role == "derived_truth":
derived_truth_files += 1
_, row_sources = validate_derived_truth_file(path)
if row_sources != {source_path}:
raise ValueError(f"derived-truth provenance mismatch: {relative}")
derived_truth_sources.add(source_path)
campaign_id = str(record["source_campaign_id"])
if campaign_id in LISTENER_WINDOW_NORMALIZATIONS:
if role == "truth":
if not record["derived"]:
raise ValueError(
f"listener-window campaign publishes raw truth: {relative}"
)
canonical_iteration_files.append((path, campaign_id, source_path))
elif role == "supporting_evidence" and relative.endswith(".jsonl.gz"):
raw_stream_paths[(campaign_id, source_path)] = path
relative_parts = PurePosixPath(relative).parts
measurement_indexes = [
index for index, part in enumerate(relative_parts) if part == "measurements"
]
if len(measurement_indexes) != 1:
raise ValueError(f"invalid published measurement path: {relative}")
payload_parts = relative_parts[measurement_indexes[0] + 1 :]
if not payload_parts:
raise ValueError(f"measurement path has no payload: {relative}")
if role in MEASUREMENT_TRUTH_ROLES:
if len(payload_parts) != 1:
raise ValueError(f"measurement truth is not flattened: {relative}")
elif payload_parts[0] != "provenance" or len(payload_parts) == 1:
raise ValueError(f"measurement helper is outside provenance: {relative}")
discovered_measurement_paths = {
path.relative_to(root).as_posix()
for path in root.glob("data/**/measurements/**/*")
if path.is_file()
and not (path.name == "manifest.json" and path.parent.name == "measurements")
}
if discovered_measurement_paths != measurement_paths:
raise ValueError("measurement payloads are not fully cataloged")
for path, campaign_id, source_path in canonical_iteration_files:
spec = LISTENER_WINDOW_NORMALIZATIONS[campaign_id]
context = f"canonical iterations {path.relative_to(root).as_posix()}"
iterations, rank_records, role = validate_canonical_iteration_file(
path, spec, context=context
)
if f"playground/{campaign_id}/{spec.engine_roles[role]}" != source_path:
raise ValueError(
f"{context}: source stream does not match engine role {role}"
)
raw_stream = raw_stream_paths.get((campaign_id, source_path))
if raw_stream is None:
raise ValueError(
f"{context}: raw rank-event stream is not retained as supporting evidence"
)
raw_records = count_jsonl_records(raw_stream)
if rank_records != raw_records:
raise ValueError(
f"{context}: {rank_records} rank records across {iterations} iterations, "
f"raw stream has {raw_records}"
)
expected_canonical = sum(
len(spec.engine_roles) for spec in LISTENER_WINDOW_NORMALIZATIONS.values()
)
if len(canonical_iteration_files) != expected_canonical:
raise ValueError(
f"expected {expected_canonical} canonical iteration files, found {len(canonical_iteration_files)}"
)
if set(measurement_catalog["measurement_file_id"].to_pylist()) != measurement_ids:
raise ValueError("measurement Parquet and JSON artifact IDs differ")
if set(measurement_catalog["path"].to_pylist()) != measurement_paths:
raise ValueError("measurement Parquet and JSON paths differ")
json_measurements = {str(r["path"]): r for r in measurement_json["records"]}
if json_measurements != bundled_measurement_records:
raise ValueError("Measurement catalog metadata disagrees with bundle manifests")
def without_nulls(value: object) -> object:
if isinstance(value, Mapping):
return {k: without_nulls(v) for k, v in value.items() if v is not None}
if isinstance(value, list):
return [without_nulls(v) for v in value]
return value
for record in measurement_catalog.to_pylist():
if without_nulls(record) != without_nulls(json_measurements[str(record["path"])]):
raise ValueError("Measurement Parquet lost or changed catalog metadata")
if (
derived_truth_files != DSV4PRO_DERIVED_TRUTH_SOURCES
or len(derived_truth_sources) != DSV4PRO_DERIVED_TRUTH_SOURCES
):
raise ValueError(
"DSV4-Pro truth-only derivatives do not cover all "
f"{DSV4PRO_DERIVED_TRUTH_SOURCES} reviewed sources"
)
computed_counts = {
"source_campaigns": len(set(CAMPAIGNS) | {
str(m["provenance"]["source_campaign_id"]) for m in snapshot_manifests.values()
}),
"configurations": len(current_manifests),
"history_snapshots": len(history_manifests),
"configuration_snapshots": len(snapshot_manifests),
"fpm_files": len(fpm_json["records"]),
"current_fpm_files": current_fpm_count,
"history_fpm_files": history_fpm_count,
"source_fpm_files": len(source_paths),
"source_fpm_rows": source_rows,
"measurement_bundles": len(measurement_manifests),
"measurement_files": len(measurement_json["records"]),
"source_measurement_files": len(source_measurement_hashes),
"truth_files": truth_files,
"derived_truth_files": derived_truth_files,
}
if dict(expected_counts) != computed_counts:
raise ValueError(
f"catalog counts do not reconcile: expected {expected_counts}, "
f"computed {computed_counts}"
)
forbidden_directories = [
path
for path in root.rglob("pairs")
if path.is_dir() and ".git" not in path.parts
]
if forbidden_directories:
raise ValueError(f"pair directories remain: {forbidden_directories}")
for obsolete_schema in (
"schemas/comparison-v1.schema.json",
"schemas/pair-manifest-v2.schema.json",
):
if (root / obsolete_schema).exists():
raise ValueError(f"obsolete pair schema remains: {obsolete_schema}")
legacy_data_paths = [
root / name
for name in ("fpm", "measurements", "history", *LEGACY_MODEL_DIRECTORIES)
if (root / name).exists()
]
if legacy_data_paths:
raise ValueError(f"legacy top-level data paths remain: {legacy_data_paths}")
counts = {
"configurations": len(current_manifests),
"history_snapshots": len(history_manifests),
"fpm_files": len(fpm_json["records"]),
"source_fpm_files": len(source_paths),
"source_fpm_rows": source_rows,
"source_measurement_files": len(source_measurement_hashes),
"measurement_bundles": len(measurement_manifests),
"derived_truth_files": derived_truth_files,
"fpm_provenance_files": len(fpm_provenance_paths | external_fpm_provenance_paths),
"pre_grouped_measurement_files": grouped_measurement_files,
"pre_grouped_iterations": grouped_iterations,
"pre_grouped_rank_records": grouped_rank_records,
}
if write_report:
report = [
"VALID",
f"dataset_id={DATASET_ID}",
f"source_revision={SOURCE_REVISION}",
*(f"{key}={value}" for key, value in counts.items()),
f"catalog_sha256={sha256_file(root / 'catalog' / 'index.parquet')}",
]
atomic_write_text(
root / "audit" / "validation-report.txt", "\n".join(report) + "\n"
)
return counts
def import_dataset(
source_root: Path, destination_root: Path, replace: bool
) -> dict[str, int]:
# The audited Playground rebuild does not own externally contributed data.
for path in destination_root.glob("data/**/manifest.json"):
candidate = load_json(path)
if (isinstance(candidate, Mapping)
and candidate.get("manifest_version") in (CONFIGURATION_MANIFEST_VERSION, 4)
and candidate.get("provenance", {}).get("source_campaign_id") not in CAMPAIGNS):
raise ValueError("Base import cannot replace external measurements; rebuild into a fresh destination")
_, _, commit_time = validate_source(source_root)
prepare_destination(destination_root, replace)
with tempfile.TemporaryDirectory(prefix="aisim-fpm-import-") as temporary:
staging_root = Path(temporary)
source_fpm_records, dispositions = copy_fpm_assets(source_root, staging_root)
source_measurement_records, source_fpm_provenance_records = copy_measurements(
source_root, staging_root
)
(
fpm_records,
measurement_records,
current_manifests,
history_manifests,
) = publish_configuration_layout(
staging_root,
destination_root,
source_fpm_records,
source_measurement_records,
source_fpm_provenance_records,
)
write_catalogs(
destination_root,
fpm_records,
measurement_records,
current_manifests,
history_manifests,
commit_time,
playground=source_repository_root(source_root),
)
write_audit_reports(
destination_root,
fpm_records,
measurement_records,
current_manifests,
history_manifests,
dispositions,
)
return validate_dataset(destination_root)
def main() -> None:
repository = Path(__file__).resolve().parents[1]
parser = argparse.ArgumentParser(description=__doc__)
subparsers = parser.add_subparsers(dest="command", required=True)
import_parser = subparsers.add_parser(
"import", help="rebuild the dataset from the pinned source checkout"
)
import_parser.add_argument("--source-root", type=Path, required=True)
import_parser.add_argument("--destination", type=Path, default=repository)
import_parser.add_argument("--replace", action="store_true")
validate_parser = subparsers.add_parser(
"validate", help="validate a local or downloaded dataset snapshot"
)
validate_parser.add_argument("--dataset-root", type=Path, default=repository)
validate_parser.add_argument("--no-write-report", action="store_true")
args = parser.parse_args()
if args.command == "import":
counts = import_dataset(
args.source_root.resolve(), args.destination.resolve(), args.replace
)
else:
counts = validate_dataset(
args.dataset_root.resolve(), write_report=not args.no_write_report
)
print("validated " + ", ".join(f"{key}={value}" for key, value in counts.items()))
if __name__ == "__main__":
main()
#!/usr/bin/env python3
"""Import and validate the AISimPlayground-backed FPM dataset.
The importer copies reviewed FPM libraries and their measurement evidence from
one pinned AISimPlayground checkout. Predictions, normalized comparisons, and
metrics are deliberately left to FPM Gym. The validator is source-independent
so a published Hugging Face snapshot can be checked without internal access.
"""
from __future__ import annotations
import migrate_measurements
import argparse
import array
import bisect
import csv
import gzip
import hashlib
import io
import json
import math
import os
import re
import shutil
import statistics
import subprocess
import tempfile
from collections import Counter
from collections.abc import Callable, Iterable, Mapping, Sequence
from dataclasses import dataclass
from dataclasses import field as dataclass_field
from decimal import Decimal
from pathlib import Path, PurePosixPath
from typing import Any
import jsonschema
import pyarrow as pa
import pyarrow.compute as pc
import pyarrow.parquet as pq
from pre_grouped import REPRESENTATION as PRE_GROUPED_REPRESENTATION
from pre_grouped import validate_file as validate_pre_grouped_file
from self_benchmark import CAMPAIGN as SELF_BENCHMARK_CAMPAIGN
from self_benchmark import validate_catalog_record as validate_self_benchmark_catalog_record
from self_benchmark import validate_snapshot as validate_self_benchmark_snapshot
from inkling_six_run import CAMPAIGNS as INKLING_CAMPAIGNS
from inkling_six_run import validate_snapshot as validate_inkling_snapshot
from inkling_six_run import validate_catalog_record as validate_inkling_catalog_record
from dsv41 import CAMPAIGNS as DSV41_CAMPAIGNS
from dsv41 import validate_snapshot as validate_dsv41_snapshot
from dsv41 import validate_catalog_record as validate_dsv41_catalog_record
DATASET_ID = "nvidia/aisimulate-fpm-dataset"
SOURCE_REPOSITORY = "https://gitlab-master.nvidia.com/dl/ai-dynamo/AISimPlayground"
SOURCE_REVISION = "731947aabdcb5ae8658fd16744022ca94e407cd3"
MEASUREMENT_MANIFEST_VERSION = 4
CONFIGURATION_MANIFEST_VERSION = 3
CATALOG_VERSION = 5
CANONICAL_BUNDLE_VERSION = 4
FPM_CATALOG_VERSION = 4
MEASUREMENT_CATALOG_VERSION = 4
MEASUREMENT_TRUTH_ROLES = frozenset({"truth", "derived_truth"})
DOCUMENT_SCHEMAS = {
"catalog_index": "schemas/history/catalog-index-v5.schema.json",
"configuration_manifest": "schemas/history/configuration-manifest-v3.schema.json",
"measurement_manifest": "schemas/history/measurement-manifest-v4.schema.json",
}
MEASUREMENT_PROTOCOL_SCHEMAS = {
"forward-pass-measurement-v1": "schemas/forward-pass-measurement-v1.schema.json",
"forward-pass-record-v1": "schemas/forward-pass-record-v1.schema.json",
}
MEASUREMENT_PROTOCOL_IDS = frozenset(MEASUREMENT_PROTOCOL_SCHEMAS)
EVIDENCE_FORMAT_IDS = frozenset({"wave-summary-v1", "bucket-summary-v1"})
DSV4PRO_DERIVED_TRUTH_SOURCES = 25
# DSV4-Pro benchmark-lane configs published as FPM provenance: (paths, distinct sources).
DSV4PRO_FPM_PROVENANCE_COUNTS = (15, 14)
# Snapshot generations whose evidence postdates their campaign's evidence_date.
GENERATION_EVIDENCE_DATES = {"dsv4pro-gb300-fpm:r6pin": "2026-09-04"}
DERIVED_TRUTH_FIELDS = (
"measurement_id",
"phase",
"batch_size",
"total_prefill_tokens",
"total_kv_read_tokens",
"truth_latency_ms",
"source_file",
"source_row",
)
REQUIRED_FPM_COLUMNS = {
"model_path",
"system",
"backend",
"backend_version",
"weight_quantization",
"gemm_quant_mode",