"""Stage B debug v3: Same as Stage A but epilogue reads from PV MMA's C layout at offset 256.
Only does QK MMA (no PV). Tests whether the epilogue can handle a different accumulator layout."""
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
import cuda.bindings.driver as cuda

class StageBDebug3:
    def __init__(self, mma_tiler_mn, use_2cta_instrs=False, use_tma_store=True):
        self.acc_dtype = Float32; self.qk_acc_dtype = Float32
        self.a_dtype = BFloat16; self.b_dtype = BFloat16; self.c_dtype = BFloat16
        self.q_dtype = BFloat16; self.o_dtype = BFloat16
        self.use_2cta_instrs = use_2cta_instrs; self.use_tma_store = use_tma_store
        self.mma_tiler_mn = mma_tiler_mn; self.mma_tiler = (*mma_tiler_mn, 1)
        self.cluster_shape_mn = (1, 1)
        self.cta_group = tcgen05.CtaGroup.TWO if use_2cta_instrs else 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.epilog_sync_bar_id = 1
        self.tmem_alloc_sync_bar_id = 2; self.tmem_dealloc_sync_bar_id = 3
        self.num_c_stage = 2

    def _setup(self, qk_mma, pv_mma):
        qk_inst_k = cute.size(qk_mma.shape_mnk, mode=[2])
        self.qk_mma_tiler = (*self.mma_tiler_mn, qk_inst_k * 4)
        self.mma_tiler = self.qk_mma_tiler
        self.cta_tile_shape_mnk = tuple(self.qk_mma_tiler)
        self.cluster_layout_vmnk = cute.tiled_divide(cute.make_layout((1,1,1)), (qk_mma.thr_id.shape,))
        self.epi_tile = utils.sm100.compute_epilogue_tile_shape(self.cta_tile_shape_mnk, False, self.c_layout, self.c_dtype)
        self.num_ab_stage = 1; self.num_acc_stage = 1; self.num_c_stage = 2
        self.a_smem_layout_staged = utils.sm100.make_smem_layout_a(qk_mma, self.mma_tiler, self.a_dtype, 1)
        self.b_smem_layout_staged = utils.sm100.make_smem_layout_b(qk_mma, self.mma_tiler, self.b_dtype, 1)
        self.c_smem_layout_staged = utils.sm100.make_smem_layout_epi(self.c_dtype, self.c_layout, self.epi_tile, 2)
        # Use PV MMA's C fragment for the TMEM allocation
        pv_acc_shape = pv_mma.partition_shape_C(self.mma_tiler_mn)
        tCtO_fake = pv_mma.make_fragment_C(cute.append(pv_acc_shape, 1))
        self.num_tmem_alloc_cols = utils.get_num_tmem_alloc_cols(tCtO_fake, arch="sm_100")
        a_smem = cute.slice_(self.a_smem_layout_staged, (None, None, None, 0))
        b_smem = cute.slice_(self.b_smem_layout_staged, (None, None, None, 0))
        self.num_tma_load_bytes = (cute.size_in_bytes(self.a_dtype, a_smem) + cute.size_in_bytes(self.b_dtype, b_smem)) * cute.size(qk_mma.thr_id.shape)

    @cute.jit
    def __call__(self, a: cute.Tensor, b: cute.Tensor, c: cute.Tensor, stream: cuda.CUstream):
        self.a_dtype = a.element_type; self.b_dtype = b.element_type; self.c_dtype = c.element_type
        self.a_major_mode = LayoutEnum.from_tensor(a).mma_major_mode()
        self.b_major_mode = LayoutEnum.from_tensor(b).mma_major_mode()
        self.c_layout = LayoutEnum.from_tensor(c)
        qk_mma = utils.sm100.make_trivial_tiled_mma(
            self.a_dtype, self.b_dtype, self.a_major_mode, self.b_major_mode,
            self.acc_dtype, self.cta_group, self.mma_tiler_mn, tcgen05.OperandSource.SMEM)
        pv_mma = utils.sm100.make_trivial_tiled_mma(
            self.a_dtype, self.b_dtype, cute.nvgpu.OperandMajorMode.K, self.b_major_mode,
            self.acc_dtype, self.cta_group, self.mma_tiler_mn, tcgen05.OperandSource.TMEM)
        self._setup(qk_mma, pv_mma)
        a_smem = cute.slice_(self.a_smem_layout_staged, (None, None, None, 0))
        b_smem = cute.slice_(self.b_smem_layout_staged, (None, None, None, 0))
        tma_a, tma_tensor_a = cute.nvgpu.make_tiled_tma_atom_A(
            utils.sm100.cluster_shape_to_tma_atom_A(self.cluster_shape_mn, qk_mma.thr_id),
            a, a_smem, self.mma_tiler, qk_mma, self.cluster_layout_vmnk.shape)
        tma_b, tma_tensor_b = cute.nvgpu.make_tiled_tma_atom_B(
            utils.sm100.cluster_shape_to_tma_atom_B(self.cluster_shape_mn, qk_mma.thr_id),
            b, b_smem, self.mma_tiler, qk_mma, self.cluster_layout_vmnk.shape)
        epi_smem = cute.select(self.c_smem_layout_staged, mode=[0, 1])
        tma_c, tma_tensor_c = cpasync.make_tiled_tma_atom(
            cpasync.CopyBulkTensorTileS2GOp(), c, epi_smem, self.epi_tile)
        self._kernel(qk_mma, pv_mma, tma_a, tma_tensor_a, tma_b, tma_tensor_b,
            tma_c, tma_tensor_c, self.cluster_layout_vmnk,
            self.a_smem_layout_staged, self.b_smem_layout_staged, self.c_smem_layout_staged, self.epi_tile
        ).launch(grid=(1,1,1), block=[self.threads_per_cta, 1, 1], stream=stream)

    @cute.kernel
    def _kernel(self, qk_mma, pv_mma, tma_atom_a, mA_mkl, tma_atom_b, mB_nkl,
                tma_atom_c, mC_mnl, cluster_layout_vmnk,
                a_smem_layout_staged, b_smem_layout_staged, c_smem_layout_staged, epi_tile):
        warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx())
        tidx, _, _ = cute.arch.thread_idx()
        is_leader_cta = True

        if warp_idx == self.tma_warp_id:
            cpasync.prefetch_descriptor(tma_atom_a); cpasync.prefetch_descriptor(tma_atom_b); cpasync.prefetch_descriptor(tma_atom_c)

        @cute.struct
        class SharedStorage:
            ab_full_mbar_ptr: cute.struct.MemRange[cutlass.Int64, self.num_ab_stage * 2]
            acc_full_mbar_ptr: cute.struct.MemRange[cutlass.Int64, self.num_acc_stage * 2]
            tmem_dealloc_mbar: cutlass.Int64
            tmem_holding_buf: cutlass.Int32

        smem = utils.SmemAllocator(); storage = smem.allocate(SharedStorage)
        ab_producer, ab_consumer = pipeline.PipelineTmaUmma.create(
            barrier_storage=storage.ab_full_mbar_ptr.data_ptr(), num_stages=self.num_ab_stage,
            producer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread),
            consumer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread, 1),
            tx_count=self.num_tma_load_bytes, cta_layout_vmnk=cluster_layout_vmnk, defer_sync=True
        ).make_participants()
        acc_pipeline = pipeline.PipelineUmmaAsync.create(
            barrier_storage=storage.acc_full_mbar_ptr.data_ptr(), num_stages=self.num_acc_stage,
            producer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread),
            consumer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread, 32 * len(self.epilogue_warp_id)),
            cta_layout_vmnk=cluster_layout_vmnk, defer_sync=True)
        tmem_alloc_barrier = pipeline.NamedBarrier(barrier_id=self.tmem_alloc_sync_bar_id, num_threads=32 * len((self.mma_warp_id, *self.epilogue_warp_id)))
        tmem = utils.TmemAllocator(storage.tmem_holding_buf.ptr, barrier_for_retrieve=tmem_alloc_barrier,
            allocator_warp_id=self.epilogue_warp_id[0], is_two_cta=False,
            two_cta_tmem_dealloc_mbar_ptr=storage.tmem_dealloc_mbar.ptr)
        pipeline.pipeline_init_arrive(cluster_shape_mn=cluster_layout_vmnk, is_relaxed=True)

        sA = smem.allocate_tensor(element_type=self.a_dtype, layout=a_smem_layout_staged.outer, byte_alignment=128, swizzle=a_smem_layout_staged.inner)
        sB = smem.allocate_tensor(element_type=self.b_dtype, layout=b_smem_layout_staged.outer, byte_alignment=128, swizzle=b_smem_layout_staged.inner)
        sC = smem.allocate_tensor(element_type=self.c_dtype, layout=c_smem_layout_staged.outer, byte_alignment=128, swizzle=c_smem_layout_staged.inner)
        gA_mkl = cute.local_tile(mA_mkl, cute.slice_(self.mma_tiler, (None, 0, None)), (None, None, None))
        gB_nkl = cute.local_tile(mB_nkl, cute.slice_(self.mma_tiler, (0, None, None)), (None, None, None))
        gC_mnl = cute.local_tile(mC_mnl, cute.slice_(self.mma_tiler, (None, None, 0)), (None, None, None))
        k_tile_cnt = cute.size(gA_mkl, mode=[3])
        thr_mma = qk_mma.get_slice(0)
        tCgA = thr_mma.partition_A(gA_mkl); tCgB = thr_mma.partition_B(gB_nkl); tCgC = thr_mma.partition_C(gC_mnl)
        a_cta_layout = cute.make_layout(cute.slice_(cluster_layout_vmnk, (0, 0, None, 0)).shape)
        tAsA, tAgA = cpasync.tma_partition(tma_atom_a, 0, a_cta_layout, cute.group_modes(sA, 0, 3), cute.group_modes(tCgA, 0, 3))
        b_cta_layout = cute.make_layout(cute.slice_(cluster_layout_vmnk, (0, None, 0, 0)).shape)
        tBsB, tBgB = cpasync.tma_partition(tma_atom_b, 0, b_cta_layout, cute.group_modes(sB, 0, 3), cute.group_modes(tCgB, 0, 3))
        tAgA_slice = tAgA[(None, 0, None, 0)]; tBgB_slice = tBgB[(None, 0, None, 0)]
        tCrA = qk_mma.make_fragment_A(sA); tCrB = qk_mma.make_fragment_B(sB)
        # Use PV MMA's C fragment for the accumulator (test: can epilogue handle PV's C layout?)
        pv_thr = pv_mma.get_slice(0)
        pv_acc_shape = pv_mma.partition_shape_C(self.mma_tiler_mn)
        tCtAcc_fake = pv_mma.make_fragment_C(cute.append(pv_acc_shape, self.num_acc_stage))
        pipeline.pipeline_init_wait(cluster_shape_mn=cluster_layout_vmnk)

        # TMA
        if warp_idx == self.tma_warp_id:
            ab_producer.reset(); peek = ab_producer.try_acquire()
            for k_tile in cutlass.range(k_tile_cnt, unroll=1):
                handle = ab_producer.acquire_and_advance(peek)
                cute.copy(tma_atom_a, tAgA_slice[(None, handle.count)], tAsA[(None, handle.index)], tma_bar_ptr=handle.barrier)
                cute.copy(tma_atom_b, tBgB_slice[(None, handle.count)], tBsB[(None, handle.index)], tma_bar_ptr=handle.barrier)
                peek = cutlass.Boolean(1)
                if handle.count + 1 < k_tile_cnt: peek = ab_producer.try_acquire()
            ab_producer.tail()

        # MMA
        if warp_idx == self.mma_warp_id:
            tmem.wait_for_alloc(); tmem_ptr = tmem.retrieve_ptr(self.acc_dtype)
            tCtAcc_base = cute.make_tensor(tmem_ptr, tCtAcc_fake.layout)
            tCtAcc = tCtAcc_base[(None, None, None, 0)]
            ab_consumer.reset(); peek = ab_consumer.try_wait()
            acc_producer_state = pipeline.make_pipeline_state(pipeline.PipelineUserType.Producer, self.num_acc_stage)
            acc_pipeline.producer_acquire(acc_producer_state)
            qk_mma.set(tcgen05.Field.ACCUMULATE, False)
            for k_tile in range(k_tile_cnt):
                if is_leader_cta:
                    handle = ab_consumer.wait_and_advance(peek)
                    num_kblocks = cute.size(tCrA, mode=[2])
                    for kblk_idx in cutlass.range(num_kblocks, unroll_full=True):
                        cute.gemm(qk_mma, tCtAcc, tCrA[(None, None, kblk_idx, handle.index)], tCrB[(None, None, kblk_idx, handle.index)], tCtAcc)
                        qk_mma.set(tcgen05.Field.ACCUMULATE, True)
                    handle.release(); peek = cutlass.Boolean(1)
                    if handle.count + 1 < k_tile_cnt: peek = ab_consumer.try_wait()
            acc_pipeline.producer_commit(acc_producer_state)
            acc_producer_state.advance()
            acc_pipeline.producer_tail(acc_producer_state)

        # Epilogue
        if warp_idx < self.mma_warp_id:
            tmem.allocate(self.num_tmem_alloc_cols); tmem.wait_for_alloc()
            tmem_ptr = tmem.retrieve_ptr(self.acc_dtype)
            tCtAcc_base = cute.make_tensor(tmem_ptr, tCtAcc_fake.layout)
            acc_consumer_state = pipeline.make_pipeline_state(pipeline.PipelineUserType.Consumer, self.num_acc_stage)
            c_producer_group = pipeline.CooperativeGroup(pipeline.Agent.Thread, 32 * len(self.epilogue_warp_id))
            c_pipeline = pipeline.PipelineTmaStore.create(num_stages=self.num_c_stage, producer_group=c_producer_group)
            acc_consumer_state = utils.gemm.sm100.epilogue_tma_store(
                self, tidx, warp_idx, tma_atom_c, tCtAcc_base, sC, tCgC,
                epi_tile, 0, const_expr(lambda x: x), (0, 0, 0), acc_consumer_state, acc_pipeline, c_pipeline)
            c_pipeline.producer_tail()
            tmem.relinquish_alloc_permit()
            tmem.free(tmem_ptr)


def test():
    torch.manual_seed(42)
    m, n, k = 128, 128, 512
    a = torch.randn(m, k, 1, dtype=torch.bfloat16, device="cuda")
    b = torch.randn(n, k, 1, dtype=torch.bfloat16, device="cuda")
    c = torch.zeros(m, n, 1, dtype=torch.bfloat16, device="cuda")
    ref = a[:, :, 0].float() @ b[:, :, 0].float().T
    import cutlass.torch as cutlass_torch
    mA = cutlass_torch.from_dlpack(a).mark_layout_dynamic(leading_dim=cutlass_torch.get_leading_dim(a))
    mB = cutlass_torch.from_dlpack(b).mark_layout_dynamic(leading_dim=cutlass_torch.get_leading_dim(b))
    mC = cutlass_torch.from_dlpack(c).mark_layout_dynamic(leading_dim=cutlass_torch.get_leading_dim(c))
    stream = cuda.CUstream(torch.cuda.current_stream().cuda_stream)
    kernel = StageBDebug3(mma_tiler_mn=(128, 128), use_2cta_instrs=False, use_tma_store=True)
    compiled = cute.compile(kernel, mA, mB, mC, stream)
    compiled(mA, mB, mC, stream)
    torch.cuda.synchronize()
    output = c[:, :, 0].float()
    cos = torch.nn.functional.cosine_similarity(output.flatten().unsqueeze(0), ref.flatten().unsqueeze(0)).item()
    print("Cosine: {:.6f}".format(cos))

if __name__ == '__main__':
    test()
