You write custom CUDA kernels to replace the pytorch operators in the given architecture to get speedups. 

    You have complete freedom to choose the set of operators you want to replace. You may make the decision to replace some operators with custom CUDA kernels and leave others unchanged. You may replace multiple operators with custom implementations, consider operator fusion opportunities (combining multiple operators into a single kernel, for example, combining matmul+relu), or algorithmic changes (such as online softmax). You are only limited by your imagination.


        Here's an example to show you the syntax of inline embedding custom CUDA operators in torch: The example given architecture is: 

        ``` 

        # 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
import torch.nn.functional as F


class Model(nn.Module):
    def __init__(self) -> None:
        super().__init__()

    def forward(self, a, b):
        return a + b


def get_inputs():
    # randomly generate input tensors based on the model architecture
    a = torch.randn(1, 128).cuda()
    b = torch.randn(1, 128).cuda()
    return [a, b]


def get_init_inputs():
    # randomly generate tensors required for initialization based on the model architecture
    return []

        ``` 

        The example new arch with custom CUDA kernels looks like this:
        ```
        # 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
import torch.nn.functional as F
from torch.utils.cpp_extension import load_inline

# Define the custom CUDA kernel for element-wise addition
elementwise_add_source = """
#include <torch/extension.h>
#include <cuda_runtime.h>

__global__ void elementwise_add_kernel(const float* a, const float* b, float* out, int size) {
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    if (idx < size) {
        out[idx] = a[idx] + b[idx];
    }
}

torch::Tensor elementwise_add_cuda(torch::Tensor a, torch::Tensor b) {
    auto size = a.numel();
    auto out = torch::zeros_like(a);

    const int block_size = 256;
    const int num_blocks = (size + block_size - 1) / block_size;

    elementwise_add_kernel<<<num_blocks, block_size>>>(a.data_ptr<float>(), b.data_ptr<float>(), out.data_ptr<float>(), size);

    return out;
}
"""

elementwise_add_cpp_source = (
    "torch::Tensor elementwise_add_cuda(torch::Tensor a, torch::Tensor b);"
)

# Compile the inline CUDA code for element-wise addition
elementwise_add = load_inline(
    name="elementwise_add",
    cpp_sources=elementwise_add_cpp_source,
    cuda_sources=elementwise_add_source,
    functions=["elementwise_add_cuda"],
    verbose=True,
    extra_cflags=[""],
    extra_ldflags=[""],
)


class ModelNew(nn.Module):
    def __init__(self) -> None:
        super().__init__()
        self.elementwise_add = elementwise_add

    def forward(self, a, b):
        return self.elementwise_add.elementwise_add_cuda(a, b)

        ``` 

        
    You are given the following architecture: 

    ```
    # 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

class Model(nn.Module):
    """
    Simple model that performs a single matrix multiplication (C = A * B)
    """
    def __init__(self):
        super(Model, self).__init__()
    
    def forward(self, A: torch.Tensor, B: torch.Tensor) -> torch.Tensor:
        """
        Performs matrix multiplication.

        Args:
            A: Input tensor of shape (M, K).
            B: Input tensor of shape (K, N).

        Returns:
            Output tensor of shape (M, N).
        """
        return torch.matmul(A, B.T)

M = 1024 * 2
K = 4096 * 2
N = 2048 * 2

def get_inputs():
    A = torch.rand(M, K)
    B = torch.rand(N, K)
    return [A, B]

def get_init_inputs():
    return []  # No special initialization inputs needed
    ```
    
Optimize the architecture named Model with custom CUDA operators! Name your optimized output architecture ModelNew. Output the new code in codeblocks. Please generate real code, NOT pseudocode, make sure the code compiles and is fully functional. Just output the new model code, no other text, and NO testing code! 



This is turn 5 of 6 for this task. Your previous solution (turn 4) was:
```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())
```
Result of evaluating it:
The solution is correct on the test inputs. Mean runtime 1.11 ms; the PyTorch reference (with TF32 enabled) takes 1.15 ms; speedup 1.036x.
Profiler, top device kernels of one forward pass of your solution:
| device kernel | total device time (us) | calls |
|---|---|---|
| hgemm_fused_cvt(float const*, float const*, float*, int, int, int) | 1090.3 | 1 |

The fastest correct solution so far (1.397x speedup) is:
```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 (building on the previous tensor-core solution):
#   1. Fuse the two fp32->fp16 conversions into a single kernel launch that
#      handles both A and B, using two 16B loads + one 16B store per thread
#      and streaming (evict-first) load hints.
#   2. Improved fp16 tensor-core GEMM (fp32 accumulate) computing C = A @ B^T:
#        - mma.sync.aligned.m16n8k16 PTX tensor-core instructions
#        - ldmatrix.x4 shared-memory operand loads
#        - XOR-swizzled shared layout (conflict-free)
#        - 4-stage cp.async software pipeline
#        - NEW: double-buffered register fragments - the ldmatrix for the
#          next k-step (and the first k-step of the next K-tile, after an
#          early barrier) is issued *before* the mma instructions of the
#          current k-step, hiding shared-memory latency behind tensor-core
#          work and removing pipeline bubbles between K-tiles.
#        - 128x128 CTA tile, 64x32 warp tile, K-tile 64
#        - L2-friendly grouped CTA rasterization
cuda_source = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda_runtime.h>
#include <cuda_fp16.h>
#include <cuda_pipeline.h>
#include <stdint.h>

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

// ---------------------------------------------------------------------------
// Fused fp32 -> fp16 conversion for two tensors in one launch.
// Each thread converts 8 floats: 2x16B loads, 1x16B store.
// ---------------------------------------------------------------------------
__device__ __forceinline__ void cvt8(const float4* __restrict__ in,
                                     uint4* __restrict__ out,
                                     const long long i) {
    float4 v0 = __ldcs(in + 2 * i);
    float4 v1 = __ldcs(in + 2 * i + 1);
    __half2 h0 = __floats2half2_rn(v0.x, v0.y);
    __half2 h1 = __floats2half2_rn(v0.z, v0.w);
    __half2 h2 = __floats2half2_rn(v1.x, v1.y);
    __half2 h3 = __floats2half2_rn(v1.z, v1.w);
    uint4 o;
    o.x = *reinterpret_cast<unsigned*>(&h0);
    o.y = *reinterpret_cast<unsigned*>(&h1);
    o.z = *reinterpret_cast<unsigned*>(&h2);
    o.w = *reinterpret_cast<unsigned*>(&h3);
    out[i] = o;
}

__global__ void f32_to_f16_fused_kernel(const float4* __restrict__ in0,
                                        uint4* __restrict__ out0,
                                        const long long n0,
                                        const float4* __restrict__ in1,
                                        uint4* __restrict__ out1,
                                        const long long n1) {
    const long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x;
    if (i < n0) {
        cvt8(in0, out0, i);
    } else {
        const long long j = i - n0;
        if (j < n1) cvt8(in1, out1, j);
    }
}

// ---------------------------------------------------------------------------
// Tensor-core GEMM: C(M,N) = A(M,K) @ B(N,K)^T, A/B fp16, C fp32.
// Requires M%128==0, N%128==0, K%64==0.
// ---------------------------------------------------------------------------
__global__ void __launch_bounds__(NTHREADS)
hgemm_tensor_op(const half* __restrict__ A, const half* __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;

    // Global->shared tile loader (cp.async, XOR swizzle on 16B chunks)
    auto issue_tile = [&](int kt, int stage) {
        const int k0 = kt * BK;
        half* As_s = As + stage * BM * BK;
        half* Bs_s = Bs + stage * BN * BK;
        #pragma unroll
        for (int i = 0; i < 4; ++i) {
            int idx = tid + i * NTHREADS;       // 0..1023
            int r = idx >> 3, c = idx & 7;
            int pc = c ^ (r & 7);
            const half* srcA = A + (long long)(m0 + r) * K + k0 + c * 8;
            const half* srcB = B + (long long)(n0 + r) * K + k0 + c * 8;
            __pipeline_memcpy_async(As_s + r * BK + pc * 8, srcA, 16);
            __pipeline_memcpy_async(Bs_s + r * BK + pc * 8, srcB, 16);
        }
    };

    #pragma unroll
    for (int s = 0; s < STAGES - 1; ++s) {
        if (s < numTiles) issue_tile(s, s);
        __pipeline_commit();
    }

    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: wait for stage 0 and preload its first k-step fragments.
    __pipeline_wait_prior(STAGES - 2);
    __syncthreads();
    load_frags(0, 0, 0);

    for (int kt = 0; kt < numTiles; ++kt) {
        const int stage = kt % STAGES;
        // Prefetch tile kt+STAGES-1 into the stage freed after the barrier
        // at the end of tile kt-1.
        const int ktn = kt + STAGES - 1;
        if (ktn < numTiles) issue_tile(ktn, ktn % STAGES);
        __pipeline_commit();

        #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) {
                // Prefetch next k-step of this tile while mma runs below.
                load_frags(stage, ks + 16, nxt);
            } else {
                // Last k-step: make the next tile's stage visible early and
                // prefetch its first fragments before the final mma batch.
                __pipeline_wait_prior(STAGES - 2);
                __syncthreads();
                if (kt + 1 < numTiles) load_frags((kt + 1) % STAGES, 0, 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]));
                }
            }
        }
    }

    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 Ah = torch::empty({M, K}, A.options().dtype(at::kHalf));
    auto Bh = torch::empty({N, K}, A.options().dtype(at::kHalf));
    auto C = torch::empty({M, N}, A.options());

    cudaStream_t stream = at::cuda::getCurrentCUDAStream();

    // One fused conversion launch for both A and B (8 floats per thread).
    const long long n0 = (long long)(M * K) / 8;
    const long long n1 = (long long)(N * K) / 8;
    const long long total = n0 + n1;
    const int cthreads = 256;
    const long long cblocks = (total + cthreads - 1) / cthreads;
    f32_to_f16_fused_kernel<<<(unsigned)cblocks, cthreads, 0, stream>>>(
        reinterpret_cast<const float4*>(A.data_ptr<float>()),
        reinterpret_cast<uint4*>(Ah.data_ptr<at::Half>()), n0,
        reinterpret_cast<const float4*>(B.data_ptr<float>()),
        reinterpret_cast<uint4*>(Bh.data_ptr<at::Half>()), n1);

    static bool configured = [] {
        cudaFuncSetAttribute(hgemm_tensor_op,
                             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_tensor_op<<<grid, NTHREADS, smem, stream>>>(
        reinterpret_cast<const half*>(Ah.data_ptr<at::Half>()),
        reinterpret_cast<const half*>(Bh.data_ptr<at::Half>()),
        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_ext_v3",
    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 using custom CUDA kernels:
    fused fp32->fp16 conversion (single launch for A and B) + a pipelined
    tensor-core (mma.m16n8k16) GEMM with fp32 accumulation and
    double-buffered register fragments.
    """
    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
            and A.numel() % 8 == 0 and B.numel() % 8 == 0
        ):
            return self._op.matmul_a_bT_cuda(A, B)
        return torch.matmul(A, B.t())
```

Write an improved complete ModelNew: fix any error, and if the solution is already correct, make it faster. Output the new code in one ```python codeblock. Just the model code, no other text, and NO testing code.
