```python
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.

import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline

# Strategy (v4): single fused kernel, no separate fp32->fp16 pass.
#   Previous version: 225 us conversion kernel + 588 us GEMM = 813 us total,
#   and ~300 MB of intermediate fp16 DRAM traffic.
#   This version fuses conversion into the GEMM:
#     - Global fp32 A/B tiles are loaded straight into registers (16 x
#       ld.global.v4 per thread), one K-tile ahead of consumption so the
#       ~1 K-cycle compute of the current tile hides global latency.
#     - Registers are converted to fp16 and written to shared memory with
#       16 B stores (8 x st.shared.v4) in the XOR-swizzled layout consumed
#       by ldmatrix.
#     - 3-stage shared-memory ring buffer needs only one __syncthreads()
#       per K-tile.
#     - Compute path unchanged from the proven tensor-core kernel:
#       mma.sync.aligned.m16n8k16 (fp32 accumulate), ldmatrix.x4 operand
#       loads, double-buffered register fragments prefetched one k-step
#       (and one tile) ahead, 128x128 CTA tile / 64x32 warp tile,
#       L2-friendly grouped CTA rasterization.
#   Net effect: removes the entire 225 us conversion kernel and its DRAM
#   round trip.
cuda_source = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda_runtime.h>
#include <cuda_fp16.h>
#include <stdint.h>

#define BM 128
#define BN 128
#define BK 64
#define STAGES 3
#define GROUPN 8
#define NTHREADS 256

// ---------------------------------------------------------------------------
// Fused fp32 -> fp16 tensor-core GEMM: C(M,N) = A(M,K) @ B(N,K)^T, C fp32.
// Requires M%128==0, N%128==0, K%64==0.
// ---------------------------------------------------------------------------
__global__ void __launch_bounds__(NTHREADS)
hgemm_fused_cvt(const float* __restrict__ A, const float* __restrict__ B,
                float* __restrict__ C, const int M, const int N, const int K) {
    extern __shared__ __align__(16) char smem[];
    half* As = reinterpret_cast<half*>(smem);                    // [STAGES][BM][BK]
    half* Bs = reinterpret_cast<half*>(smem) + STAGES * BM * BK; // [STAGES][BN][BK]

    const int tid = threadIdx.x;
    const int lane = tid & 31;
    const int warp = tid >> 5;
    const int warp_m = warp >> 2;   // 0..1 (64 rows each)
    const int warp_n = warp & 3;    // 0..3 (32 cols each)

    // Grouped rasterization for L2 reuse
    const int grid_m = M / BM;
    const int grid_n = N / BN;
    const int bid = blockIdx.x;
    const int group_size = GROUPN * grid_m;
    const int group_id = bid / group_size;
    const int first_n = group_id * GROUPN;
    const int gsz = min(GROUPN, grid_n - first_n);
    const int rem = bid - group_id * group_size;
    const int tile_n = first_n + (rem % gsz);
    const int tile_m = rem / gsz;
    const int m0 = tile_m * BM;
    const int n0 = tile_n * BN;

    const int numTiles = K / BK;

    // Register staging for one fp32 K-tile of A and B (64 registers).
    float4 ra[8];
    float4 rb[8];

    // Issue global loads for tile kt into the staging registers.
    auto load_tile = [&](int kt) {
        const long long k0 = (long long)kt * BK;
        const float* Ag = A + k0;
        const float* Bg = B + k0;
        #pragma unroll
        for (int i = 0; i < 4; ++i) {
            int c = tid + i * NTHREADS;          // fp16-chunk id, 0..1023
            int r = c >> 3, ch = c & 7;
            const float4* pa = reinterpret_cast<const float4*>(
                Ag + (long long)(m0 + r) * K + ch * 8);
            ra[2 * i]     = pa[0];
            ra[2 * i + 1] = pa[1];
            const float4* pb = reinterpret_cast<const float4*>(
                Bg + (long long)(n0 + r) * K + ch * 8);
            rb[2 * i]     = pb[0];
            rb[2 * i + 1] = pb[1];
        }
    };

    // Convert staged fp32 -> fp16 and store into the swizzled shared tile.
    auto cvt_store = [&](int stage) {
        half* As_s = As + stage * BM * BK;
        half* Bs_s = Bs + stage * BN * BK;
        #pragma unroll
        for (int i = 0; i < 4; ++i) {
            int c = tid + i * NTHREADS;
            int r = c >> 3, ch = c & 7;
            int pc = ch ^ (r & 7);
            __half2 h0 = __floats2half2_rn(ra[2 * i].x, ra[2 * i].y);
            __half2 h1 = __floats2half2_rn(ra[2 * i].z, ra[2 * i].w);
            __half2 h2 = __floats2half2_rn(ra[2 * i + 1].x, ra[2 * i + 1].y);
            __half2 h3 = __floats2half2_rn(ra[2 * i + 1].z, ra[2 * i + 1].w);
            uint4 u;
            u.x = *reinterpret_cast<unsigned*>(&h0);
            u.y = *reinterpret_cast<unsigned*>(&h1);
            u.z = *reinterpret_cast<unsigned*>(&h2);
            u.w = *reinterpret_cast<unsigned*>(&h3);
            *reinterpret_cast<uint4*>(As_s + r * BK + pc * 8) = u;
            __half2 g0 = __floats2half2_rn(rb[2 * i].x, rb[2 * i].y);
            __half2 g1 = __floats2half2_rn(rb[2 * i].z, rb[2 * i].w);
            __half2 g2 = __floats2half2_rn(rb[2 * i + 1].x, rb[2 * i + 1].y);
            __half2 g3 = __floats2half2_rn(rb[2 * i + 1].z, rb[2 * i + 1].w);
            uint4 v;
            v.x = *reinterpret_cast<unsigned*>(&g0);
            v.y = *reinterpret_cast<unsigned*>(&g1);
            v.z = *reinterpret_cast<unsigned*>(&g2);
            v.w = *reinterpret_cast<unsigned*>(&g3);
            *reinterpret_cast<uint4*>(Bs_s + r * BK + pc * 8) = v;
        }
    };

    const uint32_t As_base = (uint32_t)__cvta_generic_to_shared(As);
    const uint32_t Bs_base = (uint32_t)__cvta_generic_to_shared(Bs);

    // ldmatrix A lane offsets: rows (lane&15), k halves 0/8 by bit4
    const int a_row = warp_m * 64 + (lane & 15);
    const int a_kh  = ((lane & 16) ? 8 : 0);
    // ldmatrix B lane offsets: n rows by bits (bit4, 0..7), k halves by bit3
    const int b_row = warp_n * 32 + ((lane & 16) ? 8 : 0) + (lane & 7);
    const int b_kh  = ((lane & 8) ? 8 : 0);

    // Double-buffered register fragments
    uint32_t afr[2][4][4];
    uint32_t bfr[2][4][2];
    float acc[4][4][4];
    #pragma unroll
    for (int i = 0; i < 4; ++i)
        #pragma unroll
        for (int j = 0; j < 4; ++j)
            #pragma unroll
            for (int r = 0; r < 4; ++r) acc[i][j][r] = 0.0f;

    // Load fragments for one (stage, k-step) into buffer `buf`.
    // NOTE: buf must be a compile-time constant at every call site (the k
    // loop below is fully unrolled) so the arrays stay in registers.
    auto load_frags = [&](int stage, int ks, int buf) {
        const uint32_t a_st = As_base + (uint32_t)(stage * (BM * BK * 2));
        const uint32_t b_st = Bs_base + (uint32_t)(stage * (BN * BK * 2));
        #pragma unroll
        for (int mi = 0; mi < 4; ++mi) {
            int r = a_row + mi * 16;
            int chunk = ((ks + a_kh) >> 3) ^ (r & 7);
            uint32_t addr = a_st + (uint32_t)(r * (BK * 2) + chunk * 16);
            asm volatile(
                "ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3}, [%4];\n"
                : "=r"(afr[buf][mi][0]), "=r"(afr[buf][mi][1]),
                  "=r"(afr[buf][mi][2]), "=r"(afr[buf][mi][3])
                : "r"(addr));
        }
        #pragma unroll
        for (int np = 0; np < 2; ++np) {
            int r = b_row + np * 16;
            int chunk = ((ks + b_kh) >> 3) ^ (r & 7);
            uint32_t addr = b_st + (uint32_t)(r * (BK * 2) + chunk * 16);
            uint32_t t0, t1, t2, t3;
            asm volatile(
                "ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3}, [%4];\n"
                : "=r"(t0), "=r"(t1), "=r"(t2), "=r"(t3)
                : "r"(addr));
            bfr[buf][np * 2][0] = t0;     bfr[buf][np * 2][1] = t1;
            bfr[buf][np * 2 + 1][0] = t2; bfr[buf][np * 2 + 1][1] = t3;
        }
    };

    // Prologue: tile 0 -> smem stage 0, tile 1 -> registers, first frags.
    load_tile(0);
    cvt_store(0);
    if (1 < numTiles) load_tile(1);
    __syncthreads();
    load_frags(0, 0, 0);

    for (int kt = 0; kt < numTiles; ++kt) {
        const int stage = kt % STAGES;
        // Compute the 64x32 warp tile for this K-tile: 4 k-steps of 16 mma.
        #pragma unroll
        for (int ksi = 0; ksi < BK / 16; ++ksi) {
            const int ks = ksi * 16;
            const int cur = ksi & 1;      // compile-time after unroll
            const int nxt = cur ^ 1;
            if (ksi + 1 < BK / 16) load_frags(stage, ks + 16, nxt);
            #pragma unroll
            for (int mi = 0; mi < 4; ++mi) {
                #pragma unroll
                for (int ni = 0; ni < 4; ++ni) {
                    asm volatile(
                        "mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 "
                        "{%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};\n"
                        : "+f"(acc[mi][ni][0]), "+f"(acc[mi][ni][1]),
                          "+f"(acc[mi][ni][2]), "+f"(acc[mi][ni][3])
                        : "r"(afr[cur][mi][0]), "r"(afr[cur][mi][1]),
                          "r"(afr[cur][mi][2]), "r"(afr[cur][mi][3]),
                          "r"(bfr[cur][ni][0]), "r"(bfr[cur][ni][1]));
                }
            }
        }
        // Convert staged tile kt+1 into its smem stage, start loads kt+2,
        // barrier, then prefetch the first fragments of the next tile.
        if (kt + 1 < numTiles) {
            cvt_store((kt + 1) % STAGES);
            if (kt + 2 < numTiles) load_tile(kt + 2);
            __syncthreads();
            load_frags((kt + 1) % STAGES, 0, 0);
        }
    }

    const int gid = lane >> 2;
    const int tig = lane & 3;
    #pragma unroll
    for (int mi = 0; mi < 4; ++mi) {
        int gr = m0 + warp_m * 64 + mi * 16 + gid;
        #pragma unroll
        for (int ni = 0; ni < 4; ++ni) {
            int gc = n0 + warp_n * 32 + ni * 8 + tig * 2;
            float2* p0 = reinterpret_cast<float2*>(C + (long long)gr * N + gc);
            *p0 = make_float2(acc[mi][ni][0], acc[mi][ni][1]);
            float2* p1 = reinterpret_cast<float2*>(C + (long long)(gr + 8) * N + gc);
            *p1 = make_float2(acc[mi][ni][2], acc[mi][ni][3]);
        }
    }
}

// ---------------------------------------------------------------------------
// Host wrapper
// ---------------------------------------------------------------------------
torch::Tensor matmul_a_bT_cuda(torch::Tensor A, torch::Tensor B) {
    const int64_t M = A.size(0);
    const int64_t K = A.size(1);
    const int64_t N = B.size(0);

    auto C = torch::empty({M, N}, A.options());
    cudaStream_t stream = at::cuda::getCurrentCUDAStream();

    static bool configured = [] {
        cudaFuncSetAttribute(hgemm_fused_cvt,
                             cudaFuncAttributeMaxDynamicSharedMemorySize,
                             STAGES * (BM + BN) * BK * 2);
        return true;
    }();
    (void)configured;

    const size_t smem = STAGES * (BM + BN) * BK * 2;
    const int grid = (int)((M / BM) * (N / BN));
    hgemm_fused_cvt<<<grid, NTHREADS, smem, stream>>>(
        A.data_ptr<float>(), B.data_ptr<float>(), C.data_ptr<float>(),
        (int)M, (int)N, (int)K);

    return C;
}
"""

cpp_source = "torch::Tensor matmul_a_bT_cuda(torch::Tensor A, torch::Tensor B);"

_matmul_ext = load_inline(
    name="hgemm_a_bT_fused_v4",
    cpp_sources=cpp_source,
    cuda_sources=cuda_source,
    functions=["matmul_a_bT_cuda"],
    verbose=False,
    extra_cflags=["-O3"],
    extra_cuda_cflags=["-O3"],
)


class ModelNew(nn.Module):
    """
    Optimized C = A @ B^T with a single fused CUDA kernel: fp32 tiles are
    loaded from global memory, converted to fp16 in registers, staged in
    shared memory, and multiplied with tensor cores (mma.m16n8k16, fp32
    accumulation). No separate conversion kernel or intermediate tensors.
    """
    def __init__(self):
        super(ModelNew, self).__init__()
        self._op = _matmul_ext

    def forward(self, A: torch.Tensor, B: torch.Tensor) -> torch.Tensor:
        if (
            A.is_cuda and B.is_cuda
            and A.dtype == torch.float32 and B.dtype == torch.float32
            and A.dim() == 2 and B.dim() == 2
            and A.size(1) == B.size(1)
            and A.is_contiguous() and B.is_contiguous()
            and A.size(0) % 128 == 0
            and B.size(0) % 128 == 0
            and A.size(1) % 64 == 0
        ):
            return self._op.matmul_a_bT_cuda(A, B)
        return torch.matmul(A, B.t())
```