"""TP2 共用：int8 权重切分 + 块级 all_reduce 补丁。

所属：tp2-comfy v1.1.0-dev（双卡张量并行，ComfyUI + MiniMax-H3 int8_convrot）
环境变量：
  COMFY_ROOT  ComfyUI 根目录（默认 /home/ly/02-Engines/04-ComfyUI/ComfyUI）
  TP_UNET     仅 build_model() 独立探针用；生产路径从工作流里读模型

v1.1.0-dev 起的插桩（默认全关，TP_PROFILE=1 才测量）：
  seq_len          每步 packed 序列行数（与帖主 payload 反推的 15663/39770/80014 对比）
  attn_fwd/mlp_fwd 主块 attention / MLP 全程
  sum_ar_attn/sum_ar_mlp 两个 partial-sum all_reduce 的墙钟（含等对端）
  refiner_fwd      token_refiner 全程；TP_PROFILE_REFINER=1 时打输出指纹
"""
import os
import sys
import importlib
import time

import torch
import torch.distributed as dist

APP_VERSION = "1.2.0"
TP_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, TP_DIR)
import tp_linear
import tp_prof

ROC = os.environ.get("COMFY_ROOT", "/home/ly/02-Engines/04-ComfyUI/ComfyUI")
UNET = os.environ.get(
    "TP_UNET",
    "/home/ly/01-Models/05-ComfyUI模型库/models/diffusion_models/"
    "Minimax-h3_Singularity_ref2va_v2_int8.safetensors")


def build_model():
    """独立探针：不起 ComfyUI，直接加载模型看结构（可选调试入口）。"""
    os.chdir(ROC)
    sys.path.insert(0, ROC)
    sys.path.insert(0, os.path.join(ROC, "custom_nodes"))
    import comfy.sd
    import comfy.model_management as mm
    q = importlib.import_module("ComfyUI-INT8-Fast-ROCM.int8_quant")
    mp = comfy.sd.load_diffusion_model(UNET, model_options={"custom_operations": q.Int8TensorwiseOps})
    mm.load_models_gpu([mp])
    return mp.model.diffusion_model


def _slice_rows(lin, idx):
    """沿输出轴（行）取分片；tensorwise scale 不变，per-row scale 同步切。"""
    w = lin.weight.data
    lin.weight.data = w[idx].contiguous()
    lin.out_features = lin.weight.data.shape[0]
    sc = getattr(lin, "weight_scale", None)
    if sc is not None and torch.is_tensor(sc) and sc.numel() == w.shape[0]:
        lin.weight_scale = sc[idx].contiguous()
    return lin


def _slice_cols(lin, idx):
    w = lin.weight.data
    lin.weight.data = w[:, idx].contiguous()
    lin.in_features = lin.weight.data.shape[1]
    return lin


def apply_tp(net, rank, world=2, which="both", slice_weights=True):
    """按 head 切 attention、按 ffn 切 MLP；返回每层的切分信息供反向检查。

    只支持 world=2：heads=56 → 每卡 28；ffn=14336 → 每卡 7168。
    """
    assert world == 2, "本实现只支持 2 卡（半宽切分）"
    info = []
    for bi, blk in enumerate(net.blocks):
        attn, mlp = blk.attn, blk.mlp
        heads, hd = attn.heads, attn.head_dim
        inner = heads * hd
        half = heads // world
        lo, hi = rank * half, (rank + 1) * half
        hsel = torch.arange(lo * hd, hi * hd)

        if which in ("both", "attn", "ref"):
            # qkv：q/k/v 三段各取本 rank 的 head 行
            idx = torch.cat([hsel, inner + hsel, 2 * inner + hsel])
            attn.heads = half
            if which != "ref" and slice_weights:
                _slice_rows(attn.qkv_proj, idx)
                _slice_cols(attn.out_proj, hsel)
            tp_linear.install_row_parallel(attn.out_proj)   # 行并行：全局行 scale + 由调用方 all_reduce
        else:
            attn.heads = heads

        # MLP：fc1 输出是 [gate(ffn) | up(ffn)]，两半各取 ffn/2
        ffn = mlp.fc1.out_features // 2
        fh = ffn // world
        f_lo, f_hi = rank * fh, (rank + 1) * fh
        if which in ("both", "mlp", "ref"):
            gidx = torch.cat([torch.arange(f_lo, f_hi), torch.arange(ffn + f_lo, ffn + f_hi)])
            if which != "ref" and slice_weights:
                _slice_rows(mlp.fc1, gidx)
                _slice_cols(mlp.fc2, torch.arange(f_lo, f_hi))
            tp_linear.install_row_parallel(mlp.fc2)          # 行并行
        info.append((bi, half, (f_lo, f_hi)))
    patch_refiner(net, rank)
    instrument_refiner(net, rank)
    return info


_SEQ_LOGGED = {"done": False}
# TP_NOAR=1：只跳过两个 partial-sum all_reduce，用来量"零通信下限"（结果必然不正確，仅计时用）
_SKIP_AR = os.environ.get("TP_NOAR", "") == "1"
# TP_MLP_CHUNKS=N：MLP 沿序列切 N 块，块间 all_reduce 异步重叠（0/1 = 关，默认关）
def _mlp_chunks():
    try:
        v = int(os.environ.get("TP_MLP_CHUNKS", "4"))   # v1.2.0 起默认 4 块；设 0/1 关闭
    except ValueError:
        v = 0
    return v if v > 1 else 0


_MLP_CHUNKS = _mlp_chunks()


def patch_blocks(net, which="both"):
    """在 attn/mlp 输出后插入 all_reduce（Megatron 行并行语义：部分和相加）。

    which="" 时只装计时、不做归约（单卡参考跑用）。
    """
    import comfy.ldm.minimax.model as M

    def make_forward(bi):
        def block_forward(self, x, t_emb, mod_segments, rope_freqs, transformer_options={}, attention=None):
            attention = self.attn if attention is None else attention
            if bi == 0 and not _SEQ_LOGGED["done"]:
                _SEQ_LOGGED["done"] = True
                print("[tp-prof] packed seq_len=%d（主块输入行数，含文本/首帧/参考/音频 token）"
                      % int(x.shape[0]), flush=True)
                # 文本区（layout 里 text 段在最前）指纹：两卡若不同，说明 refiner 行并行确实没归约
                with torch.no_grad():
                    t = x[:256].float()
                    print("[tp-prof] packed 前256行 sum=%.6f absmean=%.9f（文本区指纹）"
                          % (float(t.sum()), float(t.abs().mean())), flush=True)
            shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaln_proj(t_emb)
            h = M._mod_scale_shift(self.norm1(x), shift_msa, scale_msa, mod_segments)
            t0 = tp_prof.mark()
            a = attention(h, rope_freqs=rope_freqs, transformer_options=transformer_options)
            t1 = tp_prof.mark()
            tp_prof.add("attn_fwd", t0, t1)
            if which in ("both", "attn") and not _SKIP_AR:
                t0 = time.perf_counter()
                dist.all_reduce(a)
                tp_prof.wall("sum_ar_attn", time.perf_counter() - t0)
                if a.dtype != x.dtype:
                    a = a.to(x.dtype)
            x = M._mod_gate(x, gate_msa, a, mod_segments)
            h = M._mod_scale_shift(self.norm2(x), shift_mlp, scale_mlp, mod_segments)
            t0 = tp_prof.mark()
            if _MLP_CHUNKS > 1 and which in ("both", "mlp") and not _SKIP_AR:
                # 序列分块 + 异步归约：MLP 逐 token 运算，沿序列切块数学等价；
                # 块 i 的 partial-sum all_reduce 投到通信流上，与块 i+1 的 GEMM 并行，
                # 全部投递完再统一 wait 汇合（思路来自帖 2697 的 COMFY_TP_MLP_CHUNKS）。
                n = int(x.shape[0])
                step = (n + _MLP_CHUNKS - 1) // _MLP_CHUNKS
                outs, works = [], []
                for a0 in range(0, n, step):
                    a1 = min(a0 + step, n)
                    o = self.mlp(h[a0:a1])
                    works.append(dist.all_reduce(o, async_op=True))
                    outs.append(o)
                t1 = tp_prof.mark()
                tp_prof.add("mlp_fwd", t0, t1)
                tw = time.perf_counter()
                for w in works:
                    w.wait()
                tp_prof.wall("mlp_ar_wait", time.perf_counter() - tw)
                m = outs[0] if len(outs) == 1 else torch.cat(outs, dim=0)
                if m.dtype != x.dtype:
                    m = m.to(x.dtype)
            else:
                m = self.mlp(h)
                t1 = tp_prof.mark()
                tp_prof.add("mlp_fwd", t0, t1)
                if which in ("both", "mlp") and not _SKIP_AR:
                    t0 = time.perf_counter()
                    dist.all_reduce(m)
                    tp_prof.wall("sum_ar_mlp", time.perf_counter() - t0)
                    if m.dtype != x.dtype:
                        m = m.to(x.dtype)
            return M._mod_gate(x, gate_mlp, m, mod_segments)

        return block_forward

    for i, b in enumerate(net.blocks):
        b.forward = make_forward(i).__get__(b, type(b))
    if _SKIP_AR:
        print("[tp] ⚠ TP_NOAR=1：跳过 all_reduce，只用于量零通信下限（产物无效）", flush=True)
    if _MLP_CHUNKS:
        print(f"[tp] MLP 分块重叠已启用：{_MLP_CHUNKS} 块/层（异步 all_reduce）", flush=True)


def patch_refiner(net, rank):
    """TokenRefiner 的 RefinerBlock 也是行并行（out_proj / fc2 已切半）→ 两份 partial sum
    必须在 add_(x) 之前 SUM 归约，否则两个 rank 的文本区输入不同，主 DiT 从第一层就分叉。
    （CUDA 版新增：ROCm 版只对主 blocks 插桩，refiner 输出未归约）"""
    ref = getattr(net, "token_refiner", None)
    if ref is None or getattr(ref, "_tp_ar_patched", False):
        return 0
    n = 0
    for blk in ref.blocks:
        tp_linear.install_row_parallel(blk.attn.out_proj)
        tp_linear.install_row_parallel(blk.mlp.fc2)

        def fwd(self, x, transformer_options={}):
            a = self.attn(self.norm1(x), transformer_options=transformer_options)
            dist.all_reduce(a)
            if a.dtype != x.dtype:
                a = a.to(x.dtype)
            x2 = a.add_(x)
            m = self.mlp(self.norm2(x2))
            dist.all_reduce(m)
            if m.dtype != x2.dtype:
                m = m.to(x2.dtype)
            return m.add_(x2)
        blk.forward = fwd.__get__(blk, type(blk))
        n += 1
    ref._tp_ar_patched = True
    print(f"[tp] rank{rank} refiner 已挂 {n} 层 all_reduce（RefinerBlock 行并行）", flush=True)
    return n


def instrument_refiner(net, rank):
    """统计 token_refiner 耗时；TP_PROFILE_REFINER=1 时打输出指纹。

    为什么要有指纹：帖主说公开代码把 token_refiner 的权重也切了，但前向补丁只覆盖
    主 DiT，行并行的 refiner 输出必须再补一次 SUM + 残差。我们的 slice_state_dict 是
    后缀匹配，同样会命中 refiner（日志 308 = 主 50×6 + refiner 8），而 patch_blocks
    只遍历 net.blocks → 需要实测两个 rank 的 refiner 输出是否相同来定性。
    """
    ref = getattr(net, "token_refiner", None)
    if ref is None or getattr(ref, "_tp_prof", False):
        return
    orig = ref.forward
    want = os.environ.get("TP_PROFILE_REFINER", "") not in ("", "0", "false", "False")

    def rfwd(x, transformer_options={}):
        t0 = tp_prof.mark()
        out = orig(x, transformer_options=transformer_options)
        t1 = tp_prof.mark()
        tp_prof.add("refiner_fwd", t0, t1)
        if want:
            o = out.detach().float()
            print("[tp-prof] refiner rank%s in=%s out=%s sum=%.6f absmean=%.9f"
                  % (rank, tuple(x.shape), tuple(o.shape), float(o.sum()), float(o.abs().mean())),
                  flush=True)
        return out

    ref.forward = rfwd
    ref._tp_prof = True


def _head_rows(attn_heads, head_dim, inner, rank, world=2):
    half = attn_heads // world
    lo, hi = rank * half, (rank + 1) * half
    hsel = torch.arange(lo * head_dim, hi * head_dim)
    return hsel, torch.cat([hsel, inner + hsel, 2 * inner + hsel]), half


def slice_state_dict(sd, rank, world=2):
    """在模型构造前从 state_dict 切分，避免"先装全量再切"的显存峰值。

    H3 配置固定：hidden=5376、56 头 × head_dim 128 → inner=7168、qkv 行数 21504。
    形状守卫：qkv 行数不是 21504 就认为已切过（PDD 节点会二次加载，不能切两遍）。
    """
    HIDDEN, QKV_ROWS, HEAD_DIM, HEADS = 5376, 21504, 128, 56
    k0 = "blocks.0.attn.qkv_proj.weight"
    if k0 not in sd or sd[k0].shape != (QKV_ROWS, HIDDEN):
        return sd
    inner = HEADS * HEAD_DIM
    half = HEADS // world
    hsel = torch.arange(rank * half * HEAD_DIM, (rank + 1) * half * HEAD_DIM)
    qkv_idx = torch.cat([hsel, inner + hsel, 2 * inner + hsel])
    n = 0
    for k in list(sd.keys()):
        t = sd[k]
        if k.endswith(".attn.qkv_proj.weight") and t.shape[0] == QKV_ROWS:
            sd[k] = t[qkv_idx].contiguous(); n += 1
        elif k.endswith(".attn.qkv_proj.weight_scale") and t.shape[0] == QKV_ROWS:
            sd[k] = t[qkv_idx].contiguous(); n += 1
        elif k.endswith(".attn.out_proj.weight") and t.shape[1] == inner:
            sd[k] = t[:, hsel].contiguous(); n += 1
        elif k.endswith(".mlp.fc1.weight") and t.shape[1] == HIDDEN:
            ffn = t.shape[0] // 2
            fh = ffn // world
            gidx = torch.cat([torch.arange(rank * fh, (rank + 1) * fh),
                              torch.arange(ffn + rank * fh, ffn + (rank + 1) * fh)])
            sd[k] = t[gidx].contiguous(); n += 1
            ks = k[:-len("weight")] + "weight_scale"
            if ks in sd and sd[ks].shape[0] == 2 * ffn:
                sd[ks] = sd[ks][gidx].contiguous(); n += 1
        elif k.endswith(".mlp.fc2.weight") and t.shape[0] == HIDDEN:
            ffn = t.shape[1]
            fh = ffn // world
            sd[k] = t[:, rank * fh:(rank + 1) * fh].contiguous(); n += 1
    print(f"[tp] state_dict 已切分 {n} 个张量（rank{rank}）", flush=True)
    return sd


def finalize_tp(net, rank):
    """模型已按半宽构造（state_dict 预切）时调用：只装行并行前向、不切权重。"""
    tp_linear.enable()
    n = 0
    for blk in net.blocks:
        tp_linear.install_row_parallel(blk.attn.out_proj)
        tp_linear.install_row_parallel(blk.mlp.fc2)
        n += 1
    patch_refiner(net, rank)
    instrument_refiner(net, rank)
    b0 = net.blocks[0]
    print(f"[tp] rank{rank} 半宽模型已确认：heads={b0.attn.heads} qkv_out={b0.attn.qkv_proj.weight.shape[0]} "
          f"fc1_out={b0.mlp.fc1.out_features} 行并行层={n}", flush=True)
    return n
