#!/usr/bin/env python3
"""Parse oQ4e 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("OQ4E_MODEL_DIR", str(Path.home() / "models/niyazirsaliev/DeepSeek-V4.1-Flash-1017-oQ4e-mtp-uncensored"))
)
OUT_JSON = Path(sys.argv[2] if len(sys.argv) > 2 else str(HERE / "roofline_oq4e.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

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))

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

sustained_bw_gbs = 950.0
theoretical_bw_gbs = 1024.0

# Attach actual logged dspark_off (R=1) measurements from v2_bulletproof_oq4e.json when present
v2_path = HERE / "v2_bulletproof_oq4e.json"
v2_ab_off = json.loads(v2_path.read_text()).get("ablations", {}).get("dspark_off", {}) if v2_path.exists() else {}

roofline_rows = []
for b, e_skewed in [(1, 6.0), (4, 21.0), (8, 37.0), (16, 65.0)]:
    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
    row = {
        "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),
    }
    rec = v2_ab_off.get(f"5K_prose_B{b}")
    if rec and rec.get("overlap_agg_tps"):
        meas_tps = float(rec["overlap_agg_tps"])
        meas_ms = round((b * 1000.0) / meas_tps, 1)
        row["logged_dspark_off_5k_prose_ov_tps"] = meas_tps
        row["logged_dspark_off_5k_prose_ms"] = meas_ms
        row["pct_of_950gbs_sol_skewed"] = round(100.0 * (meas_tps / row["sol_tps_at_950gbs_skewed"]), 1)
        row["pct_of_950gbs_sol_uniform"] = round(100.0 * (meas_tps / row["sol_tps_at_950gbs_uniform"]), 1)
        row["headroom_ms_vs_skewed_sol"] = round(meas_ms - row["sol_ms_at_950gbs"], 1)
        row["provenance_key"] = f"v2_bulletproof_oq4e.json -> ablations.dspark_off.5K_prose_B{b}.overlap_agg_tps"
    roofline_rows.append(row)

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": "oQ4e-mtp-uncensored (niyazirsaliev/DeepSeek-V4.1-Flash-1017-oQ4e-mtp-uncensored, 4.529 bpw native MXFP4/MXFP8)",
    "scope_note": (
        "Weight-only (zero-KV-read) DRAM-bandwidth lower bound for R=1 (no drafting) on oQ4e-mtp-uncensored. "
        "Excludes per-step KV-cache reads, sparse indexer-K scan across context L, intermediate activations, "
        "Engram SSD lookups, and the 8.05 GB MTP head read when DSpark drafting is active. "
        "Unlike V1 oQ2.5e, all R=1 no-draft measurements below are logged directly in data/v2_bulletproof_oq4e.json "
        "(ablations.dspark_off at 5K prose, real Python source code)."
    ),
    "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_mxfp8": round(cats["wq_b"] / 1e6, 1),
        "wo_b_mxfp8": round(cats["wo_b"] / 1e6, 1),
        "shared_experts_mxfp8": 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_mxfp8": 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_mxfp4": round((cats["routed_w1_all384"] / n_routed_experts) / 1e6, 2),
        "w3_mxfp4": round((cats["routed_w3_all384"] / n_routed_experts) / 1e6, 2),
        "w2_mxfp4": 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(json.dumps(out, indent=2))
