"""Diagnostic: print tma_partition output shapes for K, V tensors only."""
import torch, cutlass, cutlass.cute as cute, cutlass.utils as utils, cutlass.pipeline as pipeline
from cutlass.cute.nvgpu import cpasync, tcgen05
from cutlass import Float32, BFloat16, Int32, Boolean, const_expr
from cutlass.utils import LayoutEnum
from cutlass.utils.tmem_allocator import find_tmem_tensor_col_offset
import cuda.bindings.driver as cuda
import cutlass.torch as ct
import math

HEAD_DIM = 64

class DiagShapes:
    def __init__(self, s_k=256):
        self.s_k = s_k
        self.n_kv_tiles = s_k // 128
        self.qk_acc_dtype = Float32
        self.q_dtype = BFloat16; self.o_dtype = BFloat16; self.c_dtype = BFloat16
        self.use_2cta_instrs = False; self.epilog_sync_bar_id = 1
        self.cluster_shape_mn = (1, 1); self.cta_group = tcgen05.CtaGroup.ONE
        self.epilogue_warp_id = (0,1,2,3); self.mma_warp_id = 4; self.tma_warp_id = 5
        self.threads_per_cta = 192; self.kv_stage = 2; self.q_stage = 1; self.num_c_stage = 2
        self.scale_softmax = 1.0 / math.sqrt(HEAD_DIM)
        self.scale_softmax_log2 = self.scale_softmax * math.log2(math.e)

    def _setup(self, qk_mma, pv_mma):
        qk_ik = cute.size(qk_mma.shape_mnk, mode=[2])
        self.qk_mma_tiler = (128, 128, qk_ik * 4)
        pv_ik = cute.size(pv_mma.shape_mnk, mode=[2])
        self.pv_mma_tiler = (128, HEAD_DIM, pv_ik * (128 // pv_ik))
        self.mma_tiler = self.qk_mma_tiler
        self.cluster_layout_vmnk = cute.tiled_divide(cute.make_layout((1,1,1)), (qk_mma.thr_id.shape,))
        self.cta_tile_shape_mnk = (self.qk_mma_tiler[0]//cute.size(qk_mma.thr_id.shape), HEAD_DIM, self.qk_mma_tiler[2])
        self.c_layout = LayoutEnum.ROW_MAJOR
        self.epi_tile = utils.sm100.compute_epilogue_tile_shape(self.cta_tile_shape_mnk, False, self.c_layout, self.o_dtype)
        self.num_ab_stage = 1; self.num_acc_stage = 1
        self.q_smem_s = utils.sm100.make_smem_layout_a(qk_mma, self.qk_mma_tiler, self.q_dtype, self.q_stage)
        self.k_smem_s = utils.sm100.make_smem_layout_b(qk_mma, self.qk_mma_tiler, self.q_dtype, self.kv_stage)
        self.v_smem_s = utils.sm100.make_smem_layout_b(pv_mma, self.pv_mma_tiler, self.q_dtype, self.kv_stage)
        self.c_smem_s = utils.sm100.make_smem_layout_epi(self.o_dtype, self.c_layout, self.epi_tile, 2)
        self.p_tmem_s = utils.sm100.make_smem_layout_a(pv_mma, self.pv_mma_tiler, self.q_dtype, 1)

    @cute.jit
    def __call__(self, q, k, v, c, stream):
        self.q_dtype = q.element_type; self.o_dtype = c.element_type; self.c_dtype = self.o_dtype
        self.a_major = LayoutEnum.from_tensor(q).mma_major_mode()
        self.b_major = LayoutEnum.from_tensor(k).mma_major_mode()
        v_fmha = cute.make_tensor(
            v.iterator,
            cute.make_layout((HEAD_DIM, self.s_k, 1), stride=(1, HEAD_DIM, HEAD_DIM * self.s_k)),
        )
        self.v_major = LayoutEnum.from_tensor(v_fmha).mma_major_mode()
        self.c_layout = LayoutEnum.from_tensor(c)
        qk_mma = utils.sm100.make_trivial_tiled_mma(self.q_dtype, self.q_dtype, self.a_major, self.b_major, self.qk_acc_dtype, self.cta_group, (128,128), tcgen05.OperandSource.SMEM)
        pv_mma = utils.sm100.make_trivial_tiled_mma(self.q_dtype, self.q_dtype, cute.nvgpu.OperandMajorMode.K, self.v_major, self.qk_acc_dtype, self.cta_group, (128,HEAD_DIM), tcgen05.OperandSource.TMEM)
        self._setup(qk_mma, pv_mma)
        q_s = cute.slice_(self.q_smem_s,(None,None,None,0))
        k_s = cute.slice_(self.k_smem_s,(None,None,None,0))
        v_s = cute.slice_(self.v_smem_s,(None,None,None,0))
        tma_q,mQ = cute.nvgpu.make_tiled_tma_atom_A(utils.sm100.cluster_shape_to_tma_atom_A(self.cluster_shape_mn,qk_mma.thr_id),q,q_s,self.qk_mma_tiler,qk_mma,self.cluster_layout_vmnk.shape)
        tma_k,mK = cute.nvgpu.make_tiled_tma_atom_B(utils.sm100.cluster_shape_to_tma_atom_B(self.cluster_shape_mn,qk_mma.thr_id),k,k_s,self.qk_mma_tiler,qk_mma,self.cluster_layout_vmnk.shape)
        tma_v,mV = cute.nvgpu.make_tiled_tma_atom_B(utils.sm100.cluster_shape_to_tma_atom_B(self.cluster_shape_mn,pv_mma.thr_id),v_fmha,v_s,self.pv_mma_tiler,pv_mma,self.cluster_layout_vmnk.shape)

        gQ = cute.local_tile(mQ,cute.slice_(self.qk_mma_tiler,(None,0,None)),(None,None,None))
        gK = cute.local_tile(mK,cute.slice_(self.qk_mma_tiler,(0,None,None)),(None,None,None))
        gV = cute.local_tile(mV,cute.slice_(self.pv_mma_tiler,(0,None,None)),(None,None,None))

        print(f"gQ shape: {cute.shape(gQ)}")
        print(f"gK shape: {cute.shape(gK)}")
        print(f"gV shape: {cute.shape(gV)}")

        qk_thr = qk_mma.get_slice(0); pv_thr = pv_mma.get_slice(0)
        tCgQ = qk_thr.partition_A(gQ); tCgK = qk_thr.partition_B(gK)
        tCgV = pv_thr.partition_B(gV)

        print(f"tCgQ shape: {cute.shape(tCgQ)}")
        print(f"tCgK shape: {cute.shape(tCgK)}")
        print(f"tCgV shape: {cute.shape(tCgV)}")

        a_lay = cute.make_layout(cute.slice_(self.cluster_layout_vmnk,(0,0,None,0)).shape)
        b_lay = cute.make_layout(cute.slice_(self.cluster_layout_vmnk,(0,None,0,0)).shape)

        # K and V only (Q tma_partition fails in this context)
        tBsK,tBgK = cpasync.tma_partition(tma_k,0,b_lay,cute.group_modes(k_s,0,3),cute.group_modes(tCgK,0,3))
        tVsV,tVgV = cpasync.tma_partition(tma_v,0,b_lay,cute.group_modes(v_s,0,3),cute.group_modes(tCgV,0,3))

        print(f"tBsK shape: {cute.shape(tBsK)}  stride: {tBsK.layout.stride}")
        print(f"tBgK shape: {cute.shape(tBgK)}  stride: {tBgK.layout.stride}")
        print(f"tVsV shape: {cute.shape(tVsV)}  stride: {tVsV.layout.stride}")
        print(f"tVgV shape: {cute.shape(tVgV)}  stride: {tVgV.layout.stride}")

        # Try the (None,0,None,0) pre-slice
        tBgK_sliced = tBgK[(None,0,None,0)]
        tVgV_sliced = tVgV[(None,0,None,0)]
        print(f"tBgK after (None,0,None,0) shape: {cute.shape(tBgK_sliced)}  stride: {tBgK_sliced.layout.stride}")
        print(f"tVgV after (None,0,None,0) shape: {cute.shape(tVgV_sliced)}  stride: {tVgV_sliced.layout.stride}")


def test():
    torch.manual_seed(42)
    n = 256
    m, hd = 128, HEAD_DIM
    q = torch.randn(m, hd, 1, dtype=torch.bfloat16, device='cuda')
    k = torch.randn(n, hd, 1, dtype=torch.bfloat16, device='cuda')
    v = torch.randn(n, hd, dtype=torch.bfloat16, device='cuda')
    c = torch.zeros(m, hd, 1, dtype=torch.bfloat16, device='cuda')
    v_kernel = v.unsqueeze(-1)

    mQ = ct.from_dlpack(q).mark_layout_dynamic(leading_dim=ct.get_leading_dim(q))
    mK = ct.from_dlpack(k).mark_layout_dynamic(leading_dim=ct.get_leading_dim(k))
    mV = ct.from_dlpack(v_kernel).mark_layout_dynamic(leading_dim=ct.get_leading_dim(v_kernel))
    mC = ct.from_dlpack(c).mark_layout_dynamic(leading_dim=ct.get_leading_dim(c))
    stream = cuda.CUstream(torch.cuda.current_stream().cuda_stream)

    kernel = DiagShapes(s_k=n)
    try:
        kernel(mQ, mK, mV, mC, stream)
    except Exception as e:
        print(f"Error (expected — just needed the prints): {e}")

if __name__ == '__main__':
    test()
