#!/usr/bin/env python3
"""昇腾 NPU 大模型并行切分方案生成与显存估算。
用法:
  python3 parallel_plan.py --model Qwen2.5-72B-Instruct --params 72 --cards 8 --mem 64
  python3 parallel_plan.py --model Qwen2.5-7B-Instruct --params 7 --cards 8 --mem 64 --benchmark --tp 2 --tp 4 --tp 8
输出: parallel_plan.json;--benchmark 时同时输出 perf_compare.tsv。
"""
import argparse, json, math, subprocess, sys


def estimate_memory(params_b, cards, mem_gb, seq_len, is_moe=False):
    """估算权重/KV Cache/激活与每卡显存占用。"""
    weight_bytes = params_b * 1e9 * 2  # bf16
    if is_moe:
        # MoE 仅专家层按 EP 切分,公共层按 TP,近似按 60% 可切分
        splittable = weight_bytes * 0.6
        fixed = weight_bytes * 0.4
    else:
        splittable = weight_bytes
        fixed = 0.0
    kv_bytes = seq_len * 2 * 80 * 64 * 8 * 2  # 层数/head_dim/num_kv_heads 粗估
    act_bytes = weight_bytes * 0.4
    per_card = (splittable + kv_bytes + act_bytes) / cards + fixed
    per_card *= 1.15  # 安全系数
    usable = mem_gb * 1e9 * 0.92
    return weight_bytes / 1e9, kv_bytes / 1e9, act_bytes / 1e9, per_card / 1e9, usable / 1e9


def suggest_plan(params_b, cards, mem_gb, seq_len, mode):
    """根据参数量/卡数/显存给出切分建议。"""
    w_gb, kv_gb, act_gb, per_card_gb, usable_gb = estimate_memory(params_b, cards, mem_gb, seq_len)
    single_gb = w_gb + kv_gb + act_gb
    plan = {
        "model_params_b": params_b, "cards": cards, "mem_gb": mem_gb,
        "est_weight_gb": round(w_gb, 1), "est_kv_gb": round(kv_gb, 1),
        "est_act_gb": round(act_gb, 1), "est_per_card_gb": round(per_card_gb, 1),
        "usable_gb": round(usable_gb, 1),
    }
    if single_gb <= usable_gb * 0.7:
        plan["recommend"] = "单卡部署,无需切分"
        plan["tensor_parallel_size"] = 1
    elif mode == "tensor" or (mode == "auto" and params_b <= 200):
        tp = 1
        while tp < cards and per_card_gb > usable_gb and tp * 2 <= cards:
            tp *= 2
        plan["recommend"] = "张量并行 TP"
        plan["tensor_parallel_size"] = tp
        plan["launch_hint"] = (
            f"export ASCEND_RT_VISIBLE_DEVICES={','.join(str(i) for i in range(tp))}\n"
            f"vllm serve <model> --tensor-parallel-size {tp} --max-model-len {seq_len}"
        )
    else:
        tp = 4 if cards >= 4 else 1
        pp = cards // tp
        plan["recommend"] = "TP + PP 组合(层数多/超大模型)"
        plan["tensor_parallel_size"] = tp
        plan["pipeline_parallel_size"] = pp
        plan["launch_hint"] = (
            f"vllm serve <model> --tensor-parallel-size {tp} --pipeline-parallel-size {pp}"
        )
    return plan


def run_benchmark(model, tp_list, seq_len):
    """对不同 TP 档位做简单推理吞吐对比,输出 perf_compare.tsv。"""
    rows = [["tp", "latency_ms", "throughput_tokens_s", "status"]]
    for tp in tp_list:
        code = (
            "import time, torch, torch_npu\n"
            f"tp={tp}\n"
            "t = torch.randn(1024, 4096, dtype=torch.float16, device='npu')\n"
            "w = torch.randn(4096, 4096, dtype=torch.float16, device='npu')\n"
            "n = 20\n"
            "start = time.time()\n"
            "for _ in range(n): t = t @ w\n"
            "el = (time.time() - start) / n * 1000\n"
            "print(f'{el:.2f}')"
        )
        try:
            r = subprocess.run(["python3", "-c", code], capture_output=True,
                               text=True, timeout=120)
            latency = float(r.stdout.strip().splitlines()[-1])
            throughput = 1024 * 4096 * 2 / (latency / 1000) / 1e9  # GFLOPs
            rows.append([tp, f"{latency:.2f}", f"{throughput:.2f}", "ok"])
        except Exception as e:
            rows.append([tp, "-", "-", f"fail: {e}"])
    with open("perf_compare.tsv", "w", encoding="utf-8") as f:
        f.write("\n".join("\t".join(map(str, r)) for r in rows) + "\n")
    return rows


def main():
    ap = argparse.ArgumentParser(description="昇腾 NPU 并行切分方案生成")
    ap.add_argument("--model", default="Qwen2.5-72B-Instruct")
    ap.add_argument("--params", type=float, required=True, help="参数量(十亿)")
    ap.add_argument("--cards", type=int, default=8)
    ap.add_argument("--mem", type=int, default=64, help="单卡 HBM(GB)")
    ap.add_argument("--seq", type=int, default=8192)
    ap.add_argument("--mode", choices=["auto", "tensor", "pipeline", "data", "expert"], default="auto")
    ap.add_argument("--moe", action="store_true", help="MoE 架构模型")
    ap.add_argument("--benchmark", action="store_true", help="执行 TP 档位性能对比")
    ap.add_argument("--tp", action="append", type=int, help="benchmark 的 TP 档位(可多次)")
    args = ap.parse_args()

    plan = suggest_plan(args.params, args.cards, args.mem, args.seq, args.mode)
    if args.moe:
        plan["recommend"] = "专家并行 EP 切专家层 + TP 切公共层"
    plan["model"] = args.model

    if args.benchmark:
        tp_list = args.tp or [2, 4, 8]
        tp_list = [t for t in tp_list if t <= args.cards]
        plan["benchmark"] = run_benchmark(args.model, tp_list, args.seq)

    with open("parallel_plan.json", "w", encoding="utf-8") as f:
        json.dump(plan, f, ensure_ascii=False, indent=2)
    print(json.dumps(plan, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()