"""TP2 启动引导：在 ComfyUI 外面套一层，挂 NCCL + 模型加载钩子。

教训（照抄会炸）：不能在 ComfyUI 之前 import torch / comfy.sd —— 会破坏 AIMDO 初始化
（报 'NoneType' object has no attribute 'hostbuf_allocate'）。
做法：只提前打开参数解析（comfy.options 很轻），其余工作交给后台线程，
等 main.py 自己把 comfy.sd 导入完之后再 init NCCL 并挂载模型加载钩子。

用法（每个 rank 一个进程，各只暴露一张卡）：
  TP_RANK=1 CUDA_VISIBLE_DEVICES=<GPU1> python tp_boot.py --port 8191 ...
  TP_RANK=0 CUDA_VISIBLE_DEVICES=<GPU0> python tp_boot.py --port 8190 ...
环境变量：
  COMFY_ROOT     ComfyUI 根目录（默认 /home/ly/02-Engines/04-ComfyUI/ComfyUI）
  TP_RANK        0 / 1
  MASTER_ADDR    NCCL 地址（默认 127.0.0.1）
  MASTER_PORT    NCCL 端口（默认 29670）
"""
import os
import sys
import threading
import time
import faulthandler as _fh
import signal as _sig
_fh.register(_sig.SIGUSR1, all_threads=True)

APP_VERSION = "1.2.1-lora"
TP_DIR = os.path.dirname(os.path.abspath(__file__))
ROC = os.environ.get("COMFY_ROOT", "/home/ly/02-Engines/04-ComfyUI/ComfyUI")
sys.path.insert(0, ROC)
sys.path.insert(0, TP_DIR)

import comfy.options as _co  # 只定义开关，不拉 torch/cli_args
_co.enable_args_parsing()

rank = int(os.environ["TP_RANK"])
SOLO = os.environ.get("TP_SOLO", "") == "1"      # 只插桩、不切权重、不建 NCCL（取单卡参考值）
os.environ.setdefault("MASTER_ADDR", "127.0.0.1")
os.environ.setdefault("MASTER_PORT", "29670")
READY = threading.Event()


def _lora_slice(up, down, key, rank, world=2):
    """把全宽 LoRA 的 up/down 按 TP 的半宽切法切出本 rank 的那一半。

    H3 固定配置：hidden=5376、56 头 × head_dim 128 → inner=7168、qkv=21504、ffn=14336。
    切法必须与 core.slice_state_dict 完全一致，否则 LoRA delta 会错位。
    """
    import torch as _t
    HEAD_DIM, HEADS = 128, 56
    inner = HEADS * HEAD_DIM          # 7168
    half = HEADS // world
    hsel = _t.arange(rank * half * HEAD_DIM, (rank + 1) * half * HEAD_DIM)
    if key.endswith(".attn.qkv_proj.weight") and up.shape[0] == 3 * inner:
        idx = _t.cat([hsel, inner + hsel, 2 * inner + hsel])
        return up[idx].contiguous(), down
    if key.endswith(".attn.out_proj.weight") and down.shape[1] == inner:
        return up, down[:, hsel].contiguous()
    if key.endswith(".mlp.fc1.weight") and up.shape[0] % 2 == 0:
        ffn = up.shape[0] // 2
        fh = ffn // world
        gidx = _t.cat([_t.arange(rank * fh, (rank + 1) * fh),
                       _t.arange(ffn + rank * fh, ffn + (rank + 1) * fh)])
        return up[gidx].contiguous(), down
    if key.endswith(".mlp.fc2.weight") and down.shape[1] % 2 == 0:
        ffn = down.shape[1]
        fh = ffn // world
        return up, down[:, rank * fh:(rank + 1) * fh].contiguous()
    return None, None


def _patch_lora():
    """LoRA 在 TP 模型上默认打不上（全宽 delta vs 半宽层）→ 加载时按 rank 切分。"""
    import comfy.lora as _lora
    orig = _lora.load_lora

    def wrapped(lora, to_load, log_missing=True):
        pd = orig(lora, to_load, log_missing)
        if SOLO:
            return pd
        n = 0
        for key, ad in list(pd.items()):
            if not isinstance(key, str):
                continue
            v = getattr(ad, "weights", None)
            if not (isinstance(v, tuple) and len(v) >= 6):
                continue
            mat1, mat2, alpha, mid, dora_scale, reshape = v[0], v[1], v[2], v[3], v[4], v[5]
            if mid is not None:
                continue
            nu, nd = _lora_slice(mat1, mat2, key, rank)
            if nu is None:
                continue
            ad.weights = (nu, nd, alpha, mid, dora_scale, reshape)
            n += 1
        print(f"[tp] rank{rank} LoRA 已按 TP 半宽切分 {n} 个张量", flush=True)
        return pd

    _lora.load_lora = wrapped
    print(f"[tp] rank{rank} 已挂载 LoRA 切分钩子", flush=True)




def _on_model(mp):
    # 注意：PDD 加速节点会重建一次模型（adaln rebase），每次加载都要切，不能只切一次
    if mp is None:
        return mp
    try:
        net = getattr(mp.model, "diffusion_model", None)
        if net is None or not hasattr(net, "blocks"):
            return mp
    except Exception:
        return mp
    if getattr(net, "_tp_done", False):
        return mp
    import core
    if SOLO:
        core.instrument_refiner(net, rank)
        core.patch_blocks(net, which="")      # 只计时、不归约（没有 NCCL）
        net._tp_done = True
        print(f"[tp] rank{rank} SOLO：不切权重、不挂 all_reduce（插桩参考跑）", flush=True)
        return mp
    try:
        rows = int(net.blocks[0].attn.qkv_proj.weight.shape[0])
    except Exception:
        rows = 0
    if rows == 10752:      # 已经是半宽模型（预切路径）
        core.finalize_tp(net, rank)
    elif rows == 21504:    # 全宽模型：现场切
        core.apply_tp(net, rank)
    else:
        # 非 H3 模型（如出图用的 Krea2）走单卡路径，不切、不挂 all_reduce
        print(f"[tp] rank{rank} 跳过 TP：qkv 行数 {rows} 不是 H3（21504/10752），按单卡模型处理", flush=True)
        return mp
    core.patch_blocks(net)
    net._tp_done = True
    b0 = net.blocks[0]
    print(f"[tp] rank{rank} 已切分 DiT：heads={b0.attn.heads} "
          f"qkv_out={b0.attn.qkv_proj.weight.shape[0]} out_proj_in={b0.attn.out_proj.weight.shape[1]} "
          f"fc1_out={b0.mlp.fc1.out_features} fc2_in={b0.mlp.fc2.weight.shape[1]}", flush=True)
    return mp


def _boot():
    # 等 main.py 把 comfy.sd 导入完，保证 torch 的导入顺序由 ComfyUI 自己决定
    for _ in range(12000):
        if "comfy.sd" in sys.modules:
            break
        time.sleep(0.05)
    import torch
    import torch.distributed as dist
    # 每个进程只暴露自己那张卡（CUDA_VISIBLE_DEVICES 单卡）→ 本地 index 恒为 0，
    # 这样 ComfyUI 主线程怎么设 current device 都不会和别的 rank 撞同一张卡。
    torch.cuda.set_device(0)
    if not SOLO:
        dist.init_process_group("nccl", rank=rank, world_size=2)
        bus = getattr(torch.cuda.get_device_properties(0), "pci_bus_id", "?")
        print(f"[tp] rank{rank} 已加入 NCCL，device={torch.cuda.current_device()} bus={bus}", flush=True)
    else:
        print(f"[tp] rank{rank} SOLO：跳过 NCCL", flush=True)
    READY.set()

    import comfy.sd as sd
    orig = sd.load_diffusion_model_state_dict

    def wrapped(sd=None, *a, **k):
        READY.wait()
        import core
        presliced = False
        if not SOLO and isinstance(sd, dict):
            n0 = sd.get("blocks.0.attn.qkv_proj.weight")
            if n0 is not None and tuple(n0.shape) == (21504, 5376):
                sd = core.slice_state_dict(sd, rank)   # 预切：模型按半宽构造
                presliced = True
        try:
            import comfy.model_management as _mm
            _mm.unload_all_models()                    # 先腾出 26G 文本编码器
            import torch as _t
            _t.cuda.empty_cache()
        except Exception as e:
            print(f"[tp] 预卸载失败: {e}", flush=True)
        mp = orig(sd, *a, **k)
        if presliced and mp is not None:
            net = getattr(getattr(mp, "model", None), "diffusion_model", None)
            if net is not None:
                net._tp_presliced = True
        return _on_model(mp)

    _patch_lora()
    sd.load_diffusion_model_state_dict = wrapped
    print(f"[tp] rank{rank} 已挂载模型加载钩子", flush=True)


print(f"[tp] tp2-comfy v{APP_VERSION} rank{rank} 启动（COMFY_ROOT={ROC}）", flush=True)
threading.Thread(target=_boot, daemon=True).start()
import runpy
runpy.run_path(os.path.join(ROC, "main.py"), run_name="__main__")
