aisimulate-fpm-dataset / scripts /self_benchmark.py
nv-simonec's picture nvzhouhk's picture
Add Kimi K3 GB300 TP8+DCP8 self-benchmark calibration data (#10)
6fad3f9
Raw History Blame Contribute Delete
17.2 kB
"""Reviewed Kimi K3 native self-benchmark import contract.
DCP overlaps the TP group and is recorded explicitly in the v6 identity.
The reviewed original and sanitized source hashes bind every imported point.
"""
from __future__ import annotations
import hashlib
import json
import math
from pathlib import Path
import pyarrow as pa
import pyarrow.parquet as pq
POLICY = "dynamo-selfbench-kimi-k3-20260916-v1"
CAMPAIGN = "kimi-k3-selfbench-20260916"
SCHEMA_NAME = "aic_fpm_forward_perf"
SCHEMA_VERSION = 6
METHOD = "dynamo_native_self_benchmark"
LEAF = "data/moonshotai--Kimi-K3/gb300/vllm/0.29.0/tp8-dcp8"
# Original SHA-256, Dynamo revision, row count, reviewed sanitized SHA-256.
SOURCES = {
"2201004": (
"9e902768fc79f03aaa78554baf05a9ef3a7a47eae08ca2460a0109dec81bb010",
"54174204af65eec5661fb1ba451c19012dac9306",
451,
"b1d5ba27b6b6a643cdfe1f8c052d249707722077b9d75d1a0767141da19b90a3",
),
"2209472": (
"da7a7611d9ee166c1f16dde5610e42cfa2f94f4284078ac28d0418899223c2e9",
"e8382179d91636626e7844b2da9f99066af2f639",
288,
"38e875570738119c8f6b13d5ed76c2b960d85341e7e36d6d04e7afbdc0dbe1ae",
),
}
IDENTITY = {
"model_id": "moonshotai/Kimi-K3",
"model_revision": None,
"system": "gb300",
"gpu_family": "GB300",
"framework": "vllm",
"framework_version": "0.29.0",
"parallelism": "tp8-dcp8",
"parallel_strategy": "pure_tp",
"tp": 8,
"pp": 1,
"dp": 1,
"moe_tp": 8,
"moe_ep": 1,
"cp": 1,
"dcp": 8,
"physical_gpu_count": 8,
"weight_quantization": "mxfp4",
"kv_cache_dtype": "fp8",
"collection_method": METHOD,
}
# The sidecar uses canonical FPM fields, not the richer manifest identity.
FPM_SELECTOR = {
"model_path": IDENTITY["model_id"],
"system": IDENTITY["system"],
"backend": IDENTITY["framework"],
"backend_version": IDENTITY["framework_version"],
**{
key: IDENTITY[key]
for key in (
"weight_quantization",
"kv_cache_dtype",
"parallel_strategy",
"tp",
"pp",
"dp",
"moe_tp",
"moe_ep",
"cp",
"dcp",
)
},
}
def read(path: Path):
return json.loads(path.read_text())
def sha(path: Path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def require(condition, message):
if not condition:
raise ValueError(message)
def checked_file(root: Path, record):
path = root / record["path"]
require(
path.resolve().is_relative_to(root.resolve()), "provenance path escapes dataset"
)
require(sha(path) == record["sha256"], f"source hash mismatch: {path}")
return path
def arrow_schema(root):
spec = read(root / "schemas/aisim-fpm-forward-v6.schema.json")
types = {
"string": pa.string(),
"int64": pa.int64(),
"float64": pa.float64(),
"bool": pa.bool_(),
}
return pa.schema(
[
pa.field(f["name"], types[f["arrow_type"]], nullable=f["nullable"])
for f in spec["fields"]
]
)
def classify(point, regime):
rows = point.get("rows")
balanced = not point.get("partition") and (
not rows or len({tuple(r) for r in rows}) == 1
)
if regime == "fake_attention_kv_random_kda":
return "synthetic_attention_boundary"
return "primary" if balanced else "nonuniform_prefill"
def canonical_row(source, entry):
point = entry["point"]
fpm = entry["fpms"][0]
repeats = fpm.get("kvwarm_giant_median_of", 1)
return {
"cell_id": "kimi-k3-gb300-vllm-0.29.0-tp8-dcp8",
"model_path": IDENTITY["model_id"],
"system": "gb300",
"backend": "vllm",
"backend_version": "0.29.0",
"weight_quantization": "mxfp4",
"gemm_quant_mode": "bfloat16",
"moe_quant_mode": "w4a16_mxfp4",
"fmha_quant_mode": None,
"fmha_resolution": "runtime_not_resolved",
"comm_quant_mode": None,
"kv_cache_dtype": "fp8",
"parallel_strategy": "pure_tp",
"tp": 8,
"pp": 1,
"dp": 1,
"moe_tp": 8,
"moe_ep": 1,
"cp": 1,
"dcp": 8,
"moe_backend": "auto",
"attention_backend": "FLASHINFER_MLA",
"enable_wideep": False,
"enable_eplb": False,
"workload_kind": point["point_type"],
"batch_size": point["batch_size"],
"total_prefill_tokens": point["total_prefill_tokens"],
"total_kv_read_tokens": point["total_kv_read_tokens"],
"partition_policy": "balanced_v1",
"kv_seed_regime": entry["kv_seed_regime"],
"latency_ms": fpm["wall_time"] * 1000,
"global_warmup_iterations": source["config"]["warmup_iterations"],
"warmup_repeats": None,
"measurement_repeats": repeats,
"measurement_policy": "kvwarm_median_of_3"
if repeats == 3
else "dynamo_native_single_sample_v1",
"model_support_level": None,
"model_template_id": None,
"model_template_version": None,
"aic_database_version": None,
"source_plan_sha256": None,
"collector_attempt_id": None,
"runtime_run_id": source["run_id"],
"runtime_grid_digest": source["grid_digest"],
}
def validate_sources(root: Path, provenance):
require(
provenance["policy_id"] == POLICY, "unreviewed self-benchmark import policy"
)
require(
provenance["source_kind"] == "self_benchmark", "wrong collection source kind"
)
require(provenance["collection_method"] == METHOD, "wrong collection method")
require(provenance["timing_scope"] == "scheduler_wall_time", "wrong latency scope")
require(
provenance["independent_evaluation_truth"] is False,
"calibration is not independent truth",
)
require(
{s["job_id"] for s in provenance["sources"]} == set(SOURCES),
"unexpected source set",
)
outputs = {
"primary": [],
"synthetic_attention_boundary": [],
"nonuniform_prefill": [],
}
seen = set()
for record in provenance["sources"]:
original_hash, commit, count, sanitized_hash = SOURCES[record["job_id"]]
require(
record["original_sha256"] == original_hash
and record["dynamo_commit"] == commit,
"unreviewed source revision",
)
source_path = checked_file(root, record)
require(
sha(source_path) == sanitized_hash,
f"source differs from reviewed sanitized bytes: {record['job_id']}",
)
data = read(source_path)
require(
data["status"] == "complete"
and data["valid"]
and data["usable"]
and data["timing_valid"],
"incomplete source",
)
require(
not data["error"] and not data["skipped_points"],
"source has skipped/failed points",
)
require(
len(data["results"]) == len(data["iteration_groups"]) == count,
"source count mismatch",
)
require(
data["coverage"]["completed_points"] == count, "source coverage mismatch"
)
require(
data["limits"]["max_num_running_reqs"] == 32
and data["limits"]["max_model_len"] == 1048576,
"engine limit mismatch",
)
require(
data["recurrent_state"]
== {
"initialization": "random",
"policy": "uniform-request-layer-rank-v1",
"uniform_bound": 0.01,
},
"unknown KDA state policy",
)
for entry, group in zip(data["results"], data["iteration_groups"]):
point = entry["point"]
require(
group["benchmark_id"] == point["benchmark_id"], "benchmark ID mismatch"
)
require(len(entry["fpms"]) == 1, "expected one attention-DP observation")
fpm = entry["fpms"][0]
phase, batch = point["point_type"], point["batch_size"]
require(fpm["dp_rank"] == 0, "unexpected attention-DP rank")
require(
phase in ("prefill", "decode") and 0 < batch <= 32,
"invalid phase or batch",
)
require(
math.isfinite(fpm["wall_time"]) and fpm["wall_time"] > 0,
"invalid latency",
)
require(
fpm.get("kvwarm_giant_median_of", 1) in (1, 3),
"unexpected repeat policy",
)
metrics = fpm["scheduled_requests"]
require(
metrics[f"num_{phase}_requests"] == batch, "scheduled batch mismatch"
)
require(
metrics["sum_prefill_tokens"] == point["total_prefill_tokens"],
"scheduled prefill mismatch",
)
kv_field = (
"sum_decode_kv_tokens" if phase == "decode" else "sum_prefill_kv_tokens"
)
require(
metrics[kv_field] == point["total_kv_read_tokens"],
"scheduled KV mismatch",
)
require(
group["point"] == point
and group["complete"]
and group["expected_dp_ranks"] == [0],
"invalid synchronization",
)
require(
group["rank_results"] == [{"dp_rank": 0, "fpms": entry["fpms"]}]
and group["wall_time"] == fpm["wall_time"],
"rank timing mismatch",
)
if phase == "decode":
require(
entry["kv_seed_regime"]
in ("real_attention_kv_random_kda", "fake_attention_kv_random_kda"),
"unknown decode KV regime",
)
else:
require(
entry["kv_seed_regime"] in ("not_applicable", "real_prefix"),
"unknown prefill KV regime",
)
key = (data["run_id"], point["benchmark_id"])
require(key not in seen, "duplicate source point")
seen.add(key)
classification = classify(point, entry["kv_seed_regime"])
if classification == "nonuniform_prefill":
require(
phase == "prefill" and point["rows"],
"nonuniform point needs explicit prefill rows",
)
require(
len(point["rows"]) == batch
and sum(r[0] for r in point["rows"])
== point["total_prefill_tokens"]
and sum(r[1] for r in point["rows"])
== point["total_kv_read_tokens"],
"nonuniform rows disagree with totals",
)
outputs[classification].append(
{
"runtime_run_id": data["run_id"],
"source_job_id": record["job_id"],
"result": entry,
}
)
else:
outputs[classification].append(canonical_row(data, entry))
require(
{k: len(v) for k, v in outputs.items()}
== {
"primary": 669,
"synthetic_attention_boundary": 14,
"nonuniform_prefill": 56,
},
"classification count mismatch",
)
for key in ("primary", "synthetic_attention_boundary"):
coords = [
tuple(
r[k]
for k in (
"workload_kind",
"batch_size",
"total_prefill_tokens",
"total_kv_read_tokens",
)
)
for r in outputs[key]
]
require(len(set(coords)) == len(coords), "duplicate canonical coordinates")
return outputs
def validate_snapshot(root: Path, manifest):
require(manifest["configuration_path"] == LEAF, "unreviewed self-benchmark leaf")
require(
all(manifest.get(k) == v for k, v in IDENTITY.items()),
"DCP configuration identity mismatch",
)
require(
manifest["tp"] * manifest["pp"] * manifest["dp"] * manifest["cp"]
== manifest["physical_gpu_count"],
"DCP must not multiply GPU count",
)
require(manifest["tp"] % manifest["dcp"] == 0, "DCP must divide TP")
require(
manifest["measurements"]["file_count"] == 0
and manifest["measurements"]["protocol_id"] is None,
"self-calibration cannot be independent measurement truth",
)
provenance_path = root / LEAF / "fpm/provenance/import.json"
provenance = read(provenance_path)
expected = validate_sources(root, provenance)
engine = read(root / LEAF / "fpm/provenance/engine-config.json")
require(
engine["physical_gpu_count"] == 8 and engine["model_runner"] == "V1",
"engine topology/runner mismatch",
)
require(
engine["enable_expert_parallel"] is False
and engine["speculative_decoding"] is False,
"unexpected EP or speculation",
)
for key, value in {
"tensor-parallel-size": "8",
"pipeline-parallel-size": "1",
"decode-context-parallel-size": "8",
"max-num-seqs": "32",
"max-model-len": "1048576",
"kv-cache-dtype": "fp8",
}.items():
require(engine["flags"][key] == value, f"engine flag mismatch: {key}")
require(
len(manifest["fpm"]) == 2, "expected primary and synthetic-boundary libraries"
)
claimed = {provenance_path.relative_to(root).as_posix()}
claimed.update(s["path"] for s in provenance["sources"])
for source in provenance["supporting_files"]:
checked_file(root, source)
claimed.add(source["path"])
found_roles = set()
for record in manifest["fpm"]:
data_path = checked_file(root, record)
metadata = read(root / record["metadata_path"])
category = metadata["sample_classification"]
require(
category in ("primary", "synthetic_attention_boundary"),
"invalid library class",
)
require(category not in found_roles, "duplicate library class")
found_roles.add(category)
require(
metadata["schema_name"] == SCHEMA_NAME
and metadata["schema_version"] == SCHEMA_VERSION,
"wrong DCP schema",
)
require(
metadata["import_policy"] == POLICY
and metadata["collection_method"] == METHOD
and metadata["source_kind"] == "self_benchmark",
"missing collection policy",
)
require(
metadata["provenance_sha256"] == sha(provenance_path),
"import provenance hash mismatch",
)
require(
record["role"] == ("primary" if category == "primary" else "comparator"),
"synthetic data promoted to primary",
)
table = pq.read_table(data_path)
require(
table.schema.remove_metadata().equals(arrow_schema(root)),
"physical DCP schema mismatch",
)
require(
table.to_pylist() == expected[category], "published rows differ from source"
)
require(
metadata["configuration_selector"] == FPM_SELECTOR,
"metadata identity mismatch",
)
nonuniform = read(root / LEAF / "fpm/provenance/nonuniform-prefill.json")
require(
nonuniform == expected["nonuniform_prefill"],
"nonuniform request layouts were changed",
)
return claimed
def validate_catalog_record(root: Path, record):
metadata = read(root / record["metadata_path"])
require(
record["schema_name"] == SCHEMA_NAME
and record["schema_version"] == SCHEMA_VERSION,
"unreviewed external FPM schema",
)
require(
record["configuration_path"] == LEAF
and all(record.get(k) == v for k, v in IDENTITY.items()),
"catalog DCP identity mismatch",
)
require(metadata["import_policy"] == POLICY, "catalog import policy mismatch")
require(
record.get("source_kind") == "self_benchmark"
and record.get("timing_scope") == "scheduler_wall_time",
"catalog method/timing mismatch",
)
manifest = read(root / LEAF / "manifest.json")
entry = next(item for item in manifest["fpm"] if item["path"] == record["path"])
for field in ("path", "metadata_path", "sha256", "row_count", "role", "phases"):
require(record[field] == entry[field], f"catalog/manifest mismatch: {field}")
catalog_row = next(
row
for row in pq.read_table(root / "catalog/fpm.parquet").to_pylist()
if row["path"] == record["path"]
)
require(
{k: v for k, v in catalog_row.items() if v is not None}
== {k: v for k, v in record.items() if v is not None},
"DCP catalog Parquet/JSON mismatch",
)
return SCHEMA_VERSION