#!/usr/bin/env python3
"""Parse model.safetensors headers directly to compute short-context weight-only active bytes per decode step (R=1, no drafting)."""
import json
import os
import struct
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
MODEL_DIR = Path(
    sys.argv[1]
    if len(sys.argv) > 1
    else os.environ.get("OQ25E_MODEL_DIR", str(Path.home() / "models/apetersson/DeepSeek-V4.1-Flash-1017-Abliterated-MLX"))
)
OUT_JSON = Path(sys.argv[2] if len(sys.argv) > 2 else str(HERE / "roofline_oq25e.json"))

index = json.loads((MODEL_DIR / "model.safetensors.index.json").read_text())
wmap = index["weight_map"]
cfg = json.loads((MODEL_DIR / "config.json").read_text())

shard_headers = {}
for shard in sorted(set(wmap.values())):
    p = MODEL_DIR / shard
    with open(p, "rb") as f:
        hlen = struct.unpack("<Q", f.read(8))[0]
        hdr = json.loads(f.read(hlen))
    shard_headers[shard] = hdr

def tensor_bytes(name: str) -> int:
    shard = wmap[name]
    s, e = shard_headers[shard][name]["data_offsets"]
    return e - s

cats = {
    "wq_b": 0,
    "wo_b": 0,
    "shared_experts": 0,
    "wo_a_disk_bf16": 0,
    "lm_head_disk_bf16": 0,
    "wq_a_plus_wkv": 0,
    "engram_wkv": 0,
    "hc_and_norms": 0,
    "router_gate": 0,
    "indexer": 0,
    "compressor": 0,
    "routed_w1_all384": 0,
    "routed_w3_all384": 0,
    "routed_w2_all384": 0,
    "engram_tables_ssd": 0,
    "mtp_head": 0,
    "embed_tokens": 0,
    "vision_and_aligner": 0,
    "other": 0,
}

for name in wmap:
    b = tensor_bytes(name)
    if name.startswith("vision.") or name.startswith("aligner.") or name in ("image_start", "image_end", "image_newline"):
        cats["vision_and_aligner"] += b
    elif name.startswith("language_model.mtp."):
        cats["mtp_head"] += b
    elif name == "language_model.embed.weight":
        cats["embed_tokens"] += b
    elif name == "language_model.head.weight":
        cats["lm_head_disk_bf16"] += b
    elif ".engram.embed." in name:
        cats["engram_tables_ssd"] += b
    elif ".engram." in name:
        cats["engram_wkv"] += b
    elif ".attn.wq_b." in name:
        cats["wq_b"] += b
    elif ".attn.wo_b." in name:
        cats["wo_b"] += b
    elif ".attn.wo_a." in name:
        cats["wo_a_disk_bf16"] += b
    elif ".attn.wq_a." in name or ".attn.wkv." in name:
        cats["wq_a_plus_wkv"] += b
    elif ".attn.indexer." in name:
        cats["indexer"] += b
    elif ".attn.compressor." in name:
        cats["compressor"] += b
    elif ".ffn.shared_experts." in name:
        cats["shared_experts"] += b
    elif ".ffn.gate." in name:
        cats["router_gate"] += b
    elif ".ffn.experts.w1." in name:
        cats["routed_w1_all384"] += b
    elif ".ffn.experts.w3." in name:
        cats["routed_w3_all384"] += b
    elif ".ffn.experts.w2." in name:
        cats["routed_w2_all384"] += b
    elif "norm" in name or ".hc_" in name or ".attn.attn_sink" in name:
        cats["hc_and_norms"] += b
    else:
        cats["other"] += b

# Runtime conversions performed by oMLX Wave 43 at load time:
# wo_a BF16 (2 B/param) -> runtime MXFP8 (33 bytes per 32 elements = 1.03125 B/param)
# lm_head BF16 (2 B/param) -> runtime Q8 affine gs=64 (68 bytes per 64 elements = 1.0625 B/param)
wo_a_runtime_mxfp8 = int(cats["wo_a_disk_bf16"] * (33.0 / 64.0))
lm_head_runtime_q8 = int(cats["lm_head_disk_bf16"] * (68.0 / 128.0))

# Include DSA sparse indexer + KV compressor weights in always-read dense weights
dense_always_read_bytes = (
    cats["wq_b"]
    + cats["wo_b"]
    + cats["shared_experts"]
    + wo_a_runtime_mxfp8
    + lm_head_runtime_q8
    + cats["wq_a_plus_wkv"]
    + cats["engram_wkv"]
    + cats["hc_and_norms"]
    + cats["router_gate"]
    + cats["indexer"]
    + cats["compressor"]
)
routed_total_384 = cats["routed_w1_all384"] + cats["routed_w3_all384"] + cats["routed_w2_all384"]
text_cfg = cfg.get("text_config", cfg)
n_routed_experts = text_cfg.get("n_routed_experts", 384)
top_k = text_cfg.get("num_experts_per_tok", 6)
routed_per_unique_expert_bytes = routed_total_384 / n_routed_experts

# Modeling bandwidth constants (M5 Ultra 1,024 GB/s theoretical peak; 950 GB/s assumed sustained ceiling)
sustained_bw_gbs = 950.0
theoretical_bw_gbs = 1024.0

# Weight-only (zero-KV-read) roofline rows.
# Both uniform i.i.d. routing E_uniform = N*(1 - ((N-k)/N)^B) and skewed-routing estimates are reported.
# Prior internal R=1 no-draft reference points (from separate Wave 23/43 kernel profiling, NOT inside full_matrix_18199.json)
# are clearly labeled as external reference figures; logged dspark_off ablations arrive in V2 oQ4e.
roofline_rows = []
for b, e_skewed, prior_r1_ms, note in [
    (1, 6.0, 21.3, "Exact E_unique=6 at B=1; prior internal R=1 profiling ref (not in full_matrix_18199.json)"),
    (4, 21.0, 31.6, "E_unique skewed assumption vs 23.4 uniform; prior internal R=1 profiling ref (not in full_matrix_18199.json)"),
    (8, 37.0, 42.0, "E_unique skewed assumption vs 45.5 uniform; prior internal R=1 profiling ref (not in full_matrix_18199.json)"),
    (16, 65.0, None, "Analytical weight-only ceiling (R=1, zero drafting); E_unique skewed 65 vs 85.5 uniform"),
    (32, 110.0, None, "Analytical weight-only ceiling (R=1, zero drafting); E_unique skewed 110 vs 152.0 uniform"),
]:
    e_uniform = n_routed_experts * (1.0 - ((n_routed_experts - top_k) / n_routed_experts) ** b)
    active_gb_skew = (dense_always_read_bytes + e_skewed * routed_per_unique_expert_bytes) / 1e9
    active_gb_unif = (dense_always_read_bytes + e_uniform * routed_per_unique_expert_bytes) / 1e9
    sol_ms_950 = (active_gb_skew / sustained_bw_gbs) * 1000.0
    sol_tps_950 = (b * 1000.0) / sol_ms_950
    sol_tps_950_unif = (b * sustained_bw_gbs) / active_gb_unif
    sol_tps_1024 = (b * theoretical_bw_gbs) / active_gb_skew
    prior_r1_tps = round((b * 1000.0) / prior_r1_ms, 1) if prior_r1_ms else None
    pct_sol = round(100.0 * (sol_ms_950 / prior_r1_ms), 1) if prior_r1_ms else None
    headroom_ms = round(prior_r1_ms - sol_ms_950, 1) if prior_r1_ms else None
    roofline_rows.append({
        "batch_size": b,
        "assumed_e_unique_skewed": e_skewed,
        "uniform_iid_e_unique": round(e_uniform, 1),
        "active_bytes_gb_skewed": round(active_gb_skew, 2),
        "active_bytes_gb_uniform": round(active_gb_unif, 2),
        "sol_ms_at_950gbs": round(sol_ms_950, 1),
        "sol_tps_at_950gbs_skewed": round(sol_tps_950, 1),
        "sol_tps_at_950gbs_uniform": round(sol_tps_950_unif, 1),
        "sol_tps_at_1024gbs_skewed": round(sol_tps_1024, 1),
        "prior_internal_r1_no_draft_ms": prior_r1_ms,
        "prior_internal_r1_no_draft_tps": prior_r1_tps,
        "pct_of_950gbs_sol_skewed": pct_sol,
        "headroom_ms": headroom_ms,
        "provenance_note": note,
    })

on_disk_non_engram = sum(cats.values()) - cats["engram_tables_ssd"]
runtime_non_engram = (
    on_disk_non_engram
    - cats["wo_a_disk_bf16"] + wo_a_runtime_mxfp8
    - cats["lm_head_disk_bf16"] + lm_head_runtime_q8
)

out = {
    "model_id": MODEL_DIR.name,
    "quant_label": "oQ2.5e (apetersson/DeepSeek-V4.1-Flash-1017-Abliterated-MLX)",
    "scope_note": (
        "Weight-only (zero-KV-read) DRAM-bandwidth lower bound for R=1 (no drafting). "
        "Excludes per-step KV-cache reads (128-token local + top-512 sparse global + full-context indexer-K scan), "
        "intermediate activation traffic, Engram SSD lookups, and the 8.05 GB MTP head used when DSpark drafting is enabled. "
        "Weight byte counts are parsed directly from safetensors shard headers; sustained 950 GB/s, B>1 skewed E_unique, "
        "and prior internal R=1 profiling references are modeling/external reference inputs."
    ),
    "total_safetensors_on_disk_gb": round(sum(cats.values()) / 1e9, 2),
    "non_engram_safetensors_on_disk_gb": round(on_disk_non_engram / 1e9, 2),
    "non_engram_runtime_weights_gb": round(runtime_non_engram / 1e9, 2),
    "n_routed_experts": n_routed_experts,
    "num_experts_per_tok": top_k,
    "assumed_sustained_dram_bw_gbs": sustained_bw_gbs,
    "theoretical_dram_bw_gbs": theoretical_bw_gbs,
    "dense_always_read_gb": round(dense_always_read_bytes / 1e9, 2),
    "dense_breakdown_mb": {
        "wq_b_aff8": round(cats["wq_b"] / 1e6, 1),
        "wo_b_aff8": round(cats["wo_b"] / 1e6, 1),
        "shared_experts_aff8": round(cats["shared_experts"] / 1e6, 1),
        "wo_a_runtime_mxfp8": round(wo_a_runtime_mxfp8 / 1e6, 1),
        "wo_a_disk_bf16": round(cats["wo_a_disk_bf16"] / 1e6, 1),
        "lm_head_runtime_q8": round(lm_head_runtime_q8 / 1e6, 1),
        "lm_head_disk_bf16": round(cats["lm_head_disk_bf16"] / 1e6, 1),
        "wq_a_plus_wkv_aff8": round(cats["wq_a_plus_wkv"] / 1e6, 1),
        "engram_wkv_mxfp8": round(cats["engram_wkv"] / 1e6, 1),
        "hc_and_norms": round(cats["hc_and_norms"] / 1e6, 1),
        "router_gate": round(cats["router_gate"] / 1e6, 1),
        "indexer_8l_mb": round(cats["indexer"] / 1e6, 1),
        "compressor_4l_mb": round(cats["compressor"] / 1e6, 1),
        "other_mb": round(cats["other"] / 1e6, 1),
    },
    "routed_moe_per_unique_expert_mb": round(routed_per_unique_expert_bytes / 1e6, 2),
    "routed_breakdown_per_expert_mb": {
        "w1": round((cats["routed_w1_all384"] / n_routed_experts) / 1e6, 2),
        "w3": round((cats["routed_w3_all384"] / n_routed_experts) / 1e6, 2),
        "w2": round((cats["routed_w2_all384"] / n_routed_experts) / 1e6, 2),
    },
    "engram_tables_ssd_offload_gb": round(cats["engram_tables_ssd"] / 1e9, 2),
    "mtp_head_gb": round(cats["mtp_head"] / 1e9, 2),
    "embed_tokens_gb": round(cats["embed_tokens"] / 1e9, 2),
    "vision_and_aligner_gb": round(cats["vision_and_aligner"] / 1e9, 2),
    "roofline_r1_no_draft": roofline_rows,
}
OUT_JSON.write_text(json.dumps(out, indent=2))
print("Wrote", OUT_JSON, "| dense_gb:", out["dense_always_read_gb"], "| B=1 SOL @ 950:", out["roofline_r1_no_draft"][0]["sol_tps_at_950gbs_skewed"])
