"""CUDA 版 TP 行并行：跨卡共享激活量化 scale。

问题：TP 行并行把 out_proj/fc2 的 K 轴切半，每卡只看到一半激活，
per-row 动态量化各自算 amax → 两个不同的量化点 → 与单卡全宽不一致
（ROCm 实测 0.88%/层）。

做法：旋转后把 amax 跨卡 all_reduce(MAX)，两卡用同一个 scale 量化自己那半，
再用 ck.mm_int8(cuBLASLt) 做 GEMM、手动反量化。数值上等价于"整行一起量化"。

只对注册过 install_row_parallel() 的行并行层生效；其余层原样走 fused kernel。
"""
import os

import torch
import torch.distributed as dist

import comfy_kitchen as ck
from comfy_kitchen.tensor.int8_utils import _build_hadamard, _rotate_activation

APP_VERSION = "0.2.0-cuda-sharedscale"

_ROW = set()          # 行并行层的 int8 权重 data_ptr
_WT = {}              # weight.T 缓存（data_ptr -> tensor）
_H = {}               # Hadamard 缓存
_ACTIVE = {"on": False}
_PATCHED = {"ok": False}
_STATS = {"calls": 0, "fallback": 0}
_DBG = {"n": 0}


def _qdata_of(layer):
    w = getattr(layer, "weight", None)
    if w is None:
        return None
    try:
        from comfy_kitchen.tensor.int8 import TensorWiseINT8Layout
        qd, _ = TensorWiseINT8Layout.get_plain_tensors(w)
        return qd
    except Exception:
        d = getattr(w, "data", None)
        if isinstance(d, torch.Tensor) and d.dtype == torch.int8:
            return d
    return None


def install_row_parallel(layer, *a, **k):
    """注册行并行层（core.finalize_tp / patch_refiner 调用）。"""
    qd = _qdata_of(layer)
    if isinstance(qd, torch.Tensor) and qd.dtype == torch.int8:
        _ROW.add(int(qd.data_ptr()))
    return None


def _wt(weight):
    key = int(weight.data_ptr())
    t = _WT.get(key)
    if t is None or t.shape != (weight.shape[1], weight.shape[0]):
        t = weight.t().contiguous()
        if len(_WT) > 256:
            _WT.clear()
        _WT[key] = t
    return t


def _h(gs, dev, dt):
    key = (gs, str(dev), dt)
    h = _H.get(key)
    if h is None:
        h = _build_hadamard(gs, device=dev, dtype=dt)
        _H[key] = h
    return h


def _shared_int8_linear(x, weight, weight_scale, bias, out_dtype, gs,
                        input_act=None, input_act_weight=None, input_act_eps=0.0):
    """共享 scale 的 convrot int8 linear（分块做，避免 1GB 级临时张量撞 ComfyUI 预留）。"""
    orig_shape = x.shape
    x2 = x.reshape(-1, x.shape[-1])
    if input_act in ("swiglu", "gelu_tanh", "rms_norm"):
        from comfy_kitchen.backends.cuda import _apply_input_act
        x2 = _apply_input_act(x2, input_act, input_act_weight, input_act_eps)
        orig_shape = tuple(orig_shape[:-1]) + (x2.shape[-1],)
    if not x2.is_contiguous():
        x2 = x2.contiguous()
    dt = out_dtype or x.dtype
    h = _h(gs, x2.device, x2.dtype)
    m, k = x2.shape
    CH = 4096

    # 1) 分块旋转一次并缓存，per-row amax 顺带算
    xrs = []
    amax = torch.empty((m, 1), dtype=torch.float32, device=x2.device)
    for i in range(0, m, CH):
        xr = _rotate_activation(x2[i:i + CH], h, gs)
        amax[i:i + CH] = xr.abs().amax(dim=-1, keepdim=True).float()
        xrs.append(xr)
    dist.all_reduce(amax, op=dist.ReduceOp.MAX)      # 两卡共用同一 scale
    s = (amax / 127.0).clamp_min(1e-12)

    # 2) 用共享 scale 原地量化 + int8 GEMM + 反量化
    wt = _wt(weight)
    ws = weight_scale.reshape(1, -1).float()
    outs = []
    for j, xr in enumerate(xrs):
        sc = s[j * CH:(j + 1) * CH]
        q = xr.div_(sc.to(xr.dtype)).round_().clamp_(-127, 127).to(torch.int8)
        mm = ck.mm_int8(q, wt)
        outs.append(mm.float().mul_(sc).mul_(ws).to(dt))
        xrs[j] = None
        del xr, q, mm
    out = outs[0] if len(outs) == 1 else torch.cat(outs, dim=0)
    if bias is not None:
        out = out + bias.to(out.dtype)
    return out.reshape(*orig_shape[:-1], out.shape[-1])


def _patch_once():
    if _PATCHED["ok"]:
        return
    orig = ck.int8_linear

    def patched(x, weight, weight_scale, bias=None, out_dtype=None, convrot=False,
                convrot_groupsize=256, input_act=None, input_act_weight=None,
                input_act_eps=0.0, residual=None, residual_scale=None):
        _DBG["n"] += 1
        if _DBG["n"] <= 4:
            try:
                print(f"[tp-dbg] call#{_DBG['n']} w={tuple(weight.shape)} dtype={weight.dtype} "
                      f"ptr_in_ROW={int(weight.data_ptr()) in _ROW} convrot={convrot} "
                      f"act={input_act} res={residual is not None} ROW_n={len(_ROW)}", flush=True)
            except Exception:
                pass
        row_par = False
        if (isinstance(weight, torch.Tensor) and weight.dtype == torch.int8
                and weight.dim() == 2):
            row_par = int(weight.data_ptr()) in _ROW
            if not row_par and weight.shape[0] == 5376 and weight.shape[1] in (3584, 7168):
                row_par = True   # H3 行并行层形状（LoRA 重新量化后 data_ptr 会变）
        if (_ACTIVE["on"] and convrot and input_act in (None, "none", "swiglu")
                and residual is None and row_par):
            try:
                _STATS["calls"] += 1
                if _STATS["calls"] == 1:
                    print(f"[tp-scale] 共享 scale 首次生效：weight={tuple(weight.shape)} "
                          f"x={tuple(x.shape)} gs={convrot_groupsize}", flush=True)
                return _shared_int8_linear(x, weight, weight_scale, bias, out_dtype,
                                           convrot_groupsize, input_act,
                                           input_act_weight, input_act_eps)
            except Exception as e:
                _STATS["fallback"] += 1
                print(f"[tp-scale] 共享 scale 失败，回退 fused: {type(e).__name__}: {e}", flush=True)
        return orig(x, weight, weight_scale, bias, out_dtype, convrot,
                    convrot_groupsize, input_act, input_act_weight, input_act_eps,
                    residual, residual_scale)

    ck.int8_linear = patched
    _PATCHED["ok"] = True


def enable():
    """在模型加载/采样前打开共享 scale 路径（TP_SHARED_SCALE=0 可关闭做对照）。"""
    _patch_once()
    _ACTIVE["on"] = os.environ.get("TP_SHARED_SCALE", "1") != "0"
    print(f"[tp-scale] 共享激活 scale: {'ON' if _ACTIVE['on'] else 'OFF(对照)'}", flush=True)


def stats():
    return dict(_STATS)
