"""
Stage B v8: Fix the identity softmax by using the A-fragment layout
for the TMEM store target instead of the C-fragment composition.

The bug in v7: tStS_P uses composition(tStS.layout, (128, tilePlikeFP32))
which gives layout (128,64):(65536,1) — C-fragment strides.
But the PV MMA reads from TMEM using the A-fragment layout
((128,16),1,4):((64,1),0,16) — physical TMEM strides.

For the store to be read correctly by the PV MMA, the store target
must use the same physical TMEM addressing as the A-fragment.

Key insight from CUTLASS source:
  Physical TMEM for M=128, BK=64, BF16 A from TMEM (K-major):
  tmem[dp=m, col=base_col + 16*mma_k + k_inner] for mma_k in 0..3, k_inner in 0..15
  
  This means: A-fragment address = 64*m + k_inner + 16*mma_k
  C-fragment address for (m, col) = ??? (virtual layout, not physical)
  
  The St32x32b copy atom with tStS_P (C-composition) writes to C-layout addresses.
  The PV MMA reads from A-layout addresses. These are different physical locations.

Fix: Use tP (from p_tmem_s, the A-fragment source layout) as the store target
instead of tStS_P (the C-fragment composition). This ensures the store writes
to physical TMEM addresses that the PV MMA's A-fragment will read correctly.
"""
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


class StageBIdentitySoftmaxV8:
    def __init__(self, mma_tiler_mn, use_2cta_instrs=False, use_tma_store=True):
        self.acc_dtype = Float32; self.qk_acc_dtype = Float32
        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)
        pv_inst_k = cute.size(pv_mma.shape_mnk, mode=[2])
        self.pv_mma_tiler = (*self.mma_tiler_mn, pv_inst_k * 4)
        self.mma_tiler = self.qk_mma_tiler
        self.cta_tile_shape_mnk = (
            self.qk_mma_tiler[0] // cute.size(qk_mma.thr_id.shape),
            self.qk_mma_tiler[1],
            self.qk_mma_tiler[2],
        )
        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, self.use_2cta_instrs, self.c_layout, self.o_dtype)
        self.num_ab_stage = 1; self.num_acc_stage = 1

        self.a_smem_s = utils.sm100.make_smem_layout_a(qk_mma, self.mma_tiler, self.a_dtype, 1)
        self.b_smem_s = utils.sm100.make_smem_layout_b(qk_mma, self.mma_tiler, self.b_dtype, 1)
        self.v_smem_s = utils.sm100.make_smem_layout_b(pv_mma, self.pv_mma_tiler, self.b_dtype, 1)
        self.p_tmem_s = utils.sm100.make_smem_layout_a(pv_mma, self.pv_mma_tiler, self.q_dtype, 1)
        self.c_smem_s = utils.sm100.make_smem_layout_epi(self.o_dtype, self.c_layout, self.epi_tile, 2)

        qk_thr = qk_mma.get_slice(0)
        qk_acc_shape = qk_thr.partition_shape_C(self.mma_tiler[:2])
        tStS = qk_thr.make_fragment_C(qk_acc_shape)
        s_cols = find_tmem_tensor_col_offset(tStS)

        pv_thr = pv_mma.get_slice(0)
        pv_acc_shape = pv_thr.partition_shape_C(self.mma_tiler[:2])
        tOtO = pv_thr.make_fragment_C(pv_acc_shape)
        o_cols = find_tmem_tensor_col_offset(tOtO)

        self.tmem_s0_offset = 0
        self.tmem_p0_offset = 32
        self.tmem_o0_offset = s_cols  # 128
        self.tmem_alloc_cols = s_cols + o_cols  # 256

        self.tilePlikeFP32 = self.qk_mma_tiler[1] * self.q_dtype.width // 32

        tCtS_fake = qk_mma.make_fragment_C(cute.append(qk_acc_shape, 1))
        tCtO_fake = pv_mma.make_fragment_C(cute.append(pv_acc_shape, 1))
        self.num_tmem_alloc_cols = utils.get_num_tmem_alloc_cols([tCtS_fake, tCtO_fake], arch="sm_100")

        a_smem = cute.slice_(self.a_smem_s, (None, None, None, 0))
        b_smem = cute.slice_(self.b_smem_s, (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 = LayoutEnum.from_tensor(a).mma_major_mode()
        self.b_major = 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, self.b_major,
            self.qk_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,
            self.qk_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_s, (None, None, None, 0))
        b_smem = cute.slice_(self.b_smem_s, (None, None, None, 0))
        tma_a, tma_ta = 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_tb = 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_s, mode=[0, 1])
        tma_c, tma_tc = cpasync.make_tiled_tma_atom(cpasync.CopyBulkTensorTileS2GOp(), c, epi_smem, self.epi_tile)

        self._kernel(qk_mma, pv_mma, tma_a, tma_ta, tma_b, tma_tb, tma_c, tma_tc,
            self.cluster_layout_vmnk, self.a_smem_s, self.b_smem_s, self.v_smem_s, self.p_tmem_s, self.c_smem_s, 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_a, mA, tma_b, mB, tma_c, mC, cl_vmnk,
                a_smem_s, b_smem_s, v_smem_s, p_tmem_s, c_smem_s, epi_tile):
        warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx())
        tidx, _, _ = cute.arch.thread_idx()
        use_2cta = cute.size(qk_mma.thr_id.shape) == 2

        if warp_idx == self.tma_warp_id:
            cpasync.prefetch_descriptor(tma_a); cpasync.prefetch_descriptor(tma_b); cpasync.prefetch_descriptor(tma_c)

        @cute.struct
        class SS:
            ab_bar: cute.struct.MemRange[cutlass.Int64, self.num_ab_stage * 2]
            mma_si_bar: cute.struct.MemRange[cutlass.Int64, 2]
            acc_bar: cute.struct.MemRange[cutlass.Int64, self.num_acc_stage * 2]
            tmem_dealloc: cutlass.Int64
            holding: cutlass.Int32

        smem = utils.SmemAllocator(); st = smem.allocate(SS)

        ab_p, ab_c = pipeline.PipelineTmaUmma.create(
            barrier_storage=st.ab_bar.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=cl_vmnk, defer_sync=True
        ).make_participants()

        mma_si_prod, mma_si_cons = pipeline.PipelineUmmaAsync.create(
            barrier_storage=st.mma_si_bar.data_ptr(), num_stages=1,
            producer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread),
            consumer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread, 32 * len(self.epilogue_warp_id)),
            cta_layout_vmnk=cl_vmnk, defer_sync=True
        ).make_participants()

        acc_pipe = pipeline.PipelineUmmaAsync.create(
            barrier_storage=st.acc_bar.data_ptr(), num_stages=self.num_acc_stage,
            producer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread),
            consumer_group=pipeline.CooperativeGroup(
                pipeline.Agent.Thread, len(self.epilogue_warp_id) * (2 if use_2cta else 1)),
            cta_layout_vmnk=cl_vmnk, defer_sync=True)

        tmem_bar = 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(st.holding.ptr, barrier_for_retrieve=tmem_bar,
            allocator_warp_id=self.epilogue_warp_id[0], is_two_cta=use_2cta,
            two_cta_tmem_dealloc_mbar_ptr=st.tmem_dealloc.ptr)

        pipeline.pipeline_init_arrive(cluster_shape_mn=cl_vmnk, is_relaxed=True)

        sA = smem.allocate_tensor(element_type=self.a_dtype, layout=a_smem_s.outer, byte_alignment=128, swizzle=a_smem_s.inner)
        sB = smem.allocate_tensor(element_type=self.b_dtype, layout=b_smem_s.outer, byte_alignment=128, swizzle=b_smem_s.inner)
        sV_ptr = cute.recast_ptr(sB.iterator, v_smem_s.inner)
        sV = cute.make_tensor(sV_ptr, v_smem_s.outer)
        sC = smem.allocate_tensor(element_type=self.o_dtype, layout=c_smem_s.outer, byte_alignment=128, swizzle=c_smem_s.inner)

        gA = cute.local_tile(mA, cute.slice_(self.mma_tiler, (None,0,None)), (None,None,None))
        gB = cute.local_tile(mB, cute.slice_(self.mma_tiler, (0,None,None)), (None,None,None))
        gC = cute.local_tile(mC, cute.slice_(self.mma_tiler, (None,None,0)), (None,None,None))
        k_cnt = cute.size(gA, mode=[3])

        qk_thr = qk_mma.get_slice(0)
        tCgA = qk_thr.partition_A(gA); tCgB = qk_thr.partition_B(gB); tCgC = qk_thr.partition_C(gC)
        a_lay = cute.make_layout(cute.slice_(cl_vmnk, (0,0,None,0)).shape)
        tAsA, tAgA = cpasync.tma_partition(tma_a, 0, a_lay, cute.group_modes(sA,0,3), cute.group_modes(tCgA,0,3))
        b_lay = cute.make_layout(cute.slice_(cl_vmnk, (0,None,0,0)).shape)
        tBsB, tBgB = cpasync.tma_partition(tma_b, 0, b_lay, cute.group_modes(sB,0,3), cute.group_modes(tCgB,0,3))
        tAgA = tAgA[(None,0,None,0)]; tBgB = tBgB[(None,0,None,0)]

        tCrA = qk_mma.make_fragment_A(sA); tCrB = qk_mma.make_fragment_B(sB)
        tCrV = pv_mma.make_fragment_B(sV)

        # TMEM tensors
        qk_acc_shape = qk_thr.partition_shape_C(self.mma_tiler[:2])
        tStS = qk_thr.make_fragment_C(qk_acc_shape)
        tStS0 = cute.make_tensor(tStS.iterator + self.tmem_s0_offset, tStS.layout)

        pv_thr = pv_mma.get_slice(0)
        pv_acc_shape = pv_thr.partition_shape_C(self.mma_tiler[:2])
        tOtO = pv_thr.make_fragment_C(pv_acc_shape)
        tOtO0 = cute.make_tensor(tOtO.iterator + self.tmem_o0_offset, tOtO.layout)

        # P tensor for PV MMA A-fragment
        tP = cute.make_tensor(tStS.iterator, p_tmem_s.outer)
        tOrP = pv_thr.make_fragment_A(tP)[None, None, None, 0]
        tOrP0 = cute.make_tensor(
            tOrP.iterator + self.qk_acc_dtype.width // self.q_dtype.width * self.tmem_p0_offset,
            tOrP.layout)

        # ── KEY FIX: Store target uses A-fragment layout (tP) not C-fragment composition ──
        # The store must write to physical TMEM addresses that the PV MMA reads via A-fragment.
        # tP has layout ((128,16),1,4,1):((64,1),0,16,0) — the A-fragment's physical TMEM layout.
        # We need the store target at tmem_p0_offset = 32 columns into the S region.
        # tP's iterator starts at tStS.iterator (base of S region).
        # tOrP0 starts at tStS.iterator + 2*32 (scaled by F32/BF16 width ratio for the A-fragment).
        # The store target should use the SAME layout as tP but with the p0 offset applied.
        tP_store = cute.make_tensor(
            tStS.iterator + self.qk_acc_dtype.width // self.q_dtype.width * self.tmem_p0_offset,
            p_tmem_s.outer)

        print(f'[v8] tP.layout: {tP.layout}')
        print(f'[v8] tP_store.layout: {tP_store.layout}')
        print(f'[v8] tOrP0.layout: {tOrP0.layout}')
        print(f'[v8] tStS.layout: {tStS.layout}')

        tCtS_fake = qk_mma.make_fragment_C(cute.append(qk_acc_shape, self.num_acc_stage))
        tCtO_fake = pv_mma.make_fragment_C(cute.append(pv_acc_shape, self.num_acc_stage))

        pipeline.pipeline_init_wait(cluster_shape_mn=cl_vmnk)

        # ── TMA WARP ──
        if warp_idx == self.tma_warp_id:
            ab_p.reset(); peek = ab_p.try_acquire()
            for kt in cutlass.range(k_cnt, unroll=1):
                h = ab_p.acquire_and_advance(peek)
                cute.copy(tma_a, tAgA[(None,h.count)], tAsA[(None,h.index)], tma_bar_ptr=h.barrier)
                cute.copy(tma_b, tBgB[(None,h.count)], tBsB[(None,h.index)], tma_bar_ptr=h.barrier)
                peek = cutlass.Boolean(1)
                if h.count+1<k_cnt: peek = ab_p.try_acquire()
            ab_p.tail()

        # ── MMA WARP ──
        if warp_idx == self.mma_warp_id:
            tmem.wait_for_alloc()

            ab_c.reset(); peek = ab_c.try_wait()
            s0_handle = mma_si_prod.acquire_and_advance()

            acc_prod_st = pipeline.make_pipeline_state(pipeline.PipelineUserType.Producer, self.num_acc_stage)
            acc_pipe.producer_acquire(acc_prod_st)
            qk_mma.set(tcgen05.Field.ACCUMULATE, False)
            for kt in range(k_cnt):
                h = ab_c.wait_and_advance(peek)
                nblk = cute.size(tCrA, mode=[2])
                for kb in cutlass.range(nblk, unroll_full=True):
                    cute.gemm(qk_mma, tStS0, tCrA[(None,None,kb,h.index)], tCrB[(None,None,kb,h.index)], tStS0)
                    qk_mma.set(tcgen05.Field.ACCUMULATE, True)
                h.release(); peek = cutlass.Boolean(1)
                if h.count+1<k_cnt: peek = ab_c.try_wait()

            cute.arch.fence_view_async_tmem_store()
            s0_handle.commit()

            s0_handle = mma_si_prod.acquire_and_advance()

            pv_mma.set(tcgen05.Field.ACCUMULATE, True)
            tCrV_s = tCrV[(None, None, None, 0)]
            nblk_pv = cute.size(tOrP0, mode=[2])
            for kb in cutlass.range(nblk_pv, unroll_full=True):
                cute.gemm(pv_mma, tOtO0, tOrP0[(None,None,kb)], tCrV_s[(None,None,kb)], tOtO0)

            acc_pipe.producer_commit(acc_prod_st)
            acc_prod_st.advance()
            acc_pipe.producer_tail(acc_prod_st)

        # ── SOFTMAX / EPILOGUE WARPS ──
        if warp_idx < self.mma_warp_id:
            tmem.allocate(self.num_tmem_alloc_cols)
            tmem.wait_for_alloc()
            tmem_ptr = tmem.retrieve_ptr(self.qk_acc_dtype)
            sfw_idx = tidx % (32 * len(self.epilogue_warp_id))

            # ── LOAD from C-layout (reading QK scores) ──
            tmem_load_atom = cute.make_copy_atom(
                tcgen05.copy.Ld32x32bOp(tcgen05.copy.Repetition(32)), self.qk_acc_dtype)
            tiled_tmem_load = tcgen05.make_tmem_copy(tmem_load_atom, tStS0)
            thr_load = tiled_tmem_load.get_slice(sfw_idx)
            tTMEM_LOADtS = thr_load.partition_S(tStS0)
            cS = cute.make_identity_tensor((self.qk_mma_tiler[0], self.qk_mma_tiler[1]))
            tScS = qk_thr.partition_C(cS)
            tTMEM_LOADcS = thr_load.partition_D(tScS)

            # ── STORE to A-layout (writing P for PV MMA) ──
            # Use tP_store (A-fragment physical layout) as the store target
            tmem_store_atom = cute.make_copy_atom(
                tcgen05.copy.St32x32bOp(tcgen05.copy.Repetition(32)), self.qk_acc_dtype)
            tiled_tmem_store = tcgen05.make_tmem_copy(tmem_store_atom, tP_store)
            thr_store = tiled_tmem_store.get_slice(sfw_idx)
            tTMEM_STOREtP = thr_store.partition_D(tP_store)
            # Identity tensor for the A-layout shape
            cS_P = cute.make_identity_tensor((128, self.qk_mma_tiler[1]))  # (M, K) for A-layout
            # Wait, A-layout is (M, K) but the partition is different...
            # make_fragment_A uses p_tmem_s which is an smem_layout_a — that's (M, K, L) shape
            # tP has shape ((128,16),1,4,1) — the 4 is MMA_K, 16 is K_inner
            # The identity tensor for partition_S should match tP's logical shape
            # But tP is a TMEM tensor, not SMEM. The partition_S for the store uses tP_store
            # as the destination. We need an identity tensor for the source.
            # Actually in fmha, partition_S uses tScS_P (composed from C-fragment identity).
            # Let me try the same approach: partition the store's source side with an
            # identity tensor that matches the LOAD output (C-layout).
            
            # The store takes register data (from the load) and writes to TMEM (A-layout).
            # The register data has C-layout ordering (from the load).
            # The store target has A-layout addresses (tP_store).
            # We need the source partition of the store to match the register layout.
            # Since the register layout came from the load's destination (tTMEM_LOADcS),
            # and the store's source partition should match...
            
            # Actually, the correct approach from fmha:
            # thr_store.partition_S maps the source (register) identity tensor
            # thr_store.partition_D maps the destination (TMEM) tensor
            # The copy operation copies from register[partition_S] to TMEM[partition_D]
            # The register layout must match what we computed (from the load)
            
            # fmha uses tScS_P (composition of C-fragment identity) for partition_S
            # But if our store target is A-layout, the partition_S should use A-layout identity
            
            # Let me just try using the A-layout identity tensor
            # tP_store has shape ((128,16),1,4,1) — need identity of (128, 64) for (M, K) 
            # Actually tP's outer shape is ((128,16),1,4,1):((64,1),0,16,0)
            # The logical (M, K) identity: cS_A = make_identity_tensor((128, 64))
            cS_A = cute.make_identity_tensor((128, 64))
            tScS_A = tiled_tmem_store.get_slice(sfw_idx).partition_S(cS_A)

            # Wait for scores
            si_handle = mma_si_cons.wait_and_advance()

            # Load from C-layout
            tTMEM_LOADrS = cute.make_rmem_tensor(tTMEM_LOADcS.shape, self.qk_acc_dtype)
            cute.copy(tiled_tmem_load, tTMEM_LOADtS, tTMEM_LOADrS)
            cute.arch.fence_view_async_tmem_load()

            # Identity: F32 -> BF16
            tTMEM_STORErP = cute.make_rmem_tensor(tScS_A.shape, self.qk_acc_dtype)
            tTMEM_STORErP_e = cute.make_tensor(
                cute.recast_ptr(tTMEM_STORErP.iterator, dtype=self.q_dtype),
                tTMEM_LOADrS.layout)
            s_vec = tTMEM_LOADrS.load()
            tTMEM_STORErP_e.store(s_vec.to(self.q_dtype))

            # Store to A-layout TMEM
            cute.copy(tiled_tmem_store, tTMEM_STORErP, tTMEM_STOREtP)
            cute.arch.fence_view_async_tmem_store()

            si_handle.release()

            # ── Epilogue ──
            tCtO_base = cute.make_tensor(tmem_ptr + self.tmem_o0_offset, tCtO_fake.layout)
            acc_cons_st = pipeline.make_pipeline_state(pipeline.PipelineUserType.Consumer, self.num_acc_stage)
            c_grp = pipeline.CooperativeGroup(pipeline.Agent.Thread, 32 * len(self.epilogue_warp_id))
            c_pipe = pipeline.PipelineTmaStore.create(num_stages=self.num_c_stage, producer_group=c_grp)
            acc_cons_st = utils.gemm.sm100.epilogue_tma_store(
                self, tidx, warp_idx, tma_c, tCtO_base, sC, tCgC,
                epi_tile, 0, const_expr(lambda x: x), (0,0,0), acc_cons_st, acc_pipe, c_pipe)
            c_pipe.producer_tail()
            tmem.relinquish_alloc_permit()
            tmem.free(tmem_ptr)


def test():
    torch.manual_seed(42)
    m, n, k = 128, 128, 128
    q = torch.randn(m, k, 1, dtype=torch.bfloat16, device='cuda')
    kv = torch.randn(n, k, 1, dtype=torch.bfloat16, device='cuda')
    c = torch.zeros(m, n, 1, dtype=torch.bfloat16, device='cuda')
    qf = q[:,:,0].float(); kvf = kv[:,:,0].float()
    ref = qf @ kvf.T @ kvf
    import cutlass.torch as ct
    mQ = ct.from_dlpack(q).mark_layout_dynamic(leading_dim=ct.get_leading_dim(q))
    mK = ct.from_dlpack(kv).mark_layout_dynamic(leading_dim=ct.get_leading_dim(kv))
    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 = StageBIdentitySoftmaxV8(mma_tiler_mn=(128, 128), use_2cta_instrs=False, use_tma_store=True)
    print('Compiling...', flush=True)
    compiled = cute.compile(kernel, mQ, mK, mC, stream)
    print('Running...', flush=True)
    compiled(mQ, mK, mC, stream)
    torch.cuda.synchronize()
    out = c[:,:,0].float()
    cos = torch.nn.functional.cosine_similarity(out.flatten().unsqueeze(0), ref.flatten().unsqueeze(0)).item()
    max_err = (out - ref).abs().max().item()
    print('Stage B v8: (Q @ K^T) @ V with identity softmax (A-layout store)')
    print('  Cosine: {:.6f}, Max error: {:.6f}'.format(cos, max_err))
    print('  {}'.format('PASS' if cos >= 0.99 else 'FAIL'))

if __name__ == '__main__':
    test()
