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) with a small K dimension
    """
    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)

M = 16384 * 2
N = 16384 * 2
K = 32 * 2

def get_inputs():
    A = torch.rand(M, K)
    B = torch.rand(K, N)
    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 3 of 6 for this task. Your previous solution (turn 2) 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

# Enable TF32 for any PyTorch fallback path (matches the reference setting).
torch.backends.cuda.matmul.allow_tf32 = True

# ---------------------------------------------------------------------------
# Custom WMMA (Tensor Core) TF32 GEMM, specialized for small-K C = A @ B.
#
# Key ideas vs. the previous FP32 kernel:
#   * FP32 CUDA cores top out ~19 TFLOPS on A100; this GEMM needs ~43 TFLOPS
#     effective, so we use TF32 tensor cores via nvcuda::wmma (m16n16k8).
#   * Inputs are rounded to TF32 (cvt.rna.tf32.f32) while staging into shared
#     memory, matching cuBLAS TF32 numerics (round-to-nearest-even).
#   * 128x128 block tile, 8 warps (2x4), each warp computes a 64x32 tile with
#     16x16x8 fragments. Whole K-slab of 64 is staged once (K=64 -> one pass).
#   * Padded smem layouts (LDA=68, LDB=132, LDC=132) give conflict-free wmma
#     loads/stores and 16B alignment everywhere.
#   * The output tile is staged through shared memory and written to global
#     memory with fully-coalesced float4 stores (this GEMM is C-write bound).
# ---------------------------------------------------------------------------
matmul_cuda_source = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda_runtime.h>
#include <mma.h>

using namespace nvcuda;

#define BM 128
#define BN 128
#define BK 64
#define WM 64
#define WN 32
#define WARPS_N 4
#define NTHREADS 256
#define LDA 68   // BK + 4
#define LDB 132  // BN + 4
#define LDC 132  // BN + 4

#define SMEM_A (BM * LDA)
#define SMEM_B (BK * LDB)
#define SMEM_BYTES ((SMEM_A + SMEM_B) * (int)sizeof(float))  // >= BM*LDC*4

__device__ __forceinline__ float to_tf32(float x) {
#if __CUDA_ARCH__ >= 800
    unsigned r;
    asm volatile("cvt.rna.tf32.f32 %0, %1;\n" : "=r"(r) : "f"(x));
    return __uint_as_float(r);
#else
    return x;
#endif
}

__global__ void __launch_bounds__(NTHREADS, 2)
matmul_wmma_tf32_kernel(const float* __restrict__ A,
                        const float* __restrict__ B,
                        float* __restrict__ C,
                        const int M, const int N, const int K)
{
    extern __shared__ __align__(16) float smem[];
    float* As = smem;              // [BM][LDA]
    float* Bs = smem + SMEM_A;     // [BK][LDB]
    float* Cs = smem;              // [BM][LDC] (overlaid after compute)

    const int tid      = threadIdx.x;
    const int warp     = tid >> 5;
    const int warp_row = (warp / WARPS_N) * WM;   // 0 or 64
    const int warp_col = (warp % WARPS_N) * WN;   // 0, 32, 64, 96

    const int block_row = blockIdx.y * BM;
    const int block_col = blockIdx.x * BN;

    wmma::fragment<wmma::accumulator, 16, 16, 8, float> acc[WM / 16][WN / 16];
    #pragma unroll
    for (int i = 0; i < WM / 16; ++i)
        #pragma unroll
        for (int j = 0; j < WN / 16; ++j)
            wmma::fill_fragment(acc[i][j], 0.0f);

    const float* Ag = A + (size_t)block_row * K;
    const float* Bg = B + block_col;

    // Cooperative load indices (float4 granularity).
    const int a_row = tid >> 4;        // 0..15  (16 threads per A row)
    const int a_f4  = (tid & 15) * 4;
    const int b_row = tid >> 5;        // 0..7   (32 threads per B row)
    const int b_f4  = (tid & 31) * 4;

    for (int ks = 0; ks < K; ks += BK) {
        // ---- Stage A tile into smem (with TF32 rounding) ----
        #pragma unroll
        for (int r = a_row; r < BM; r += 16) {
            float4 v = *reinterpret_cast<const float4*>(Ag + (size_t)r * K + ks + a_f4);
            *reinterpret_cast<float4*>(&As[r * LDA + a_f4]) =
                make_float4(to_tf32(v.x), to_tf32(v.y), to_tf32(v.z), to_tf32(v.w));
        }
        // ---- Stage B tile into smem (with TF32 rounding) ----
        #pragma unroll
        for (int r = b_row; r < BK; r += 8) {
            float4 v = *reinterpret_cast<const float4*>(Bg + (size_t)(ks + r) * N + b_f4);
            *reinterpret_cast<float4*>(&Bs[r * LDB + b_f4]) =
                make_float4(to_tf32(v.x), to_tf32(v.y), to_tf32(v.z), to_tf32(v.w));
        }
        __syncthreads();

        // ---- Tensor-core compute over the K slab ----
        #pragma unroll
        for (int k = 0; k < BK; k += 8) {
            wmma::fragment<wmma::matrix_a, 16, 16, 8, wmma::precision::tf32, wmma::row_major> af[WM / 16];
            wmma::fragment<wmma::matrix_b, 16, 16, 8, wmma::precision::tf32, wmma::row_major> bf[WN / 16];
            #pragma unroll
            for (int i = 0; i < WM / 16; ++i)
                wmma::load_matrix_sync(af[i], &As[(warp_row + 16 * i) * LDA + k], LDA);
            #pragma unroll
            for (int j = 0; j < WN / 16; ++j)
                wmma::load_matrix_sync(bf[j], &Bs[k * LDB + warp_col + 16 * j], LDB);
            #pragma unroll
            for (int i = 0; i < WM / 16; ++i)
                #pragma unroll
                for (int j = 0; j < WN / 16; ++j)
                    wmma::mma_sync(acc[i][j], af[i], bf[j], acc[i][j]);
        }
        __syncthreads();   // everyone done reading As/Bs before Cs overlay
    }

    // ---- Stage C tile in smem, then fully-coalesced float4 write-out ----
    #pragma unroll
    for (int i = 0; i < WM / 16; ++i)
        #pragma unroll
        for (int j = 0; j < WN / 16; ++j)
            wmma::store_matrix_sync(&Cs[(warp_row + 16 * i) * LDC + warp_col + 16 * j],
                                    acc[i][j], LDC, wmma::mem_row_major);
    __syncthreads();

    float* Cg = C + (size_t)block_row * N + block_col;
    #pragma unroll
    for (int idx = tid; idx < BM * (BN / 4); idx += NTHREADS) {
        const int r = idx >> 5;
        const int c = (idx & 31) * 4;
        *reinterpret_cast<float4*>(Cg + (size_t)r * N + c) =
            *reinterpret_cast<const float4*>(&Cs[r * LDC + c]);
    }
}

torch::Tensor matmul_cuda(torch::Tensor A, torch::Tensor B) {
    const int M = A.size(0);
    const int K = A.size(1);
    const int N = B.size(1);

    auto C = torch::empty({M, N}, A.options());

    static bool configured = false;
    if (!configured) {
        cudaFuncSetAttribute(matmul_wmma_tf32_kernel,
                             cudaFuncAttributeMaxDynamicSharedMemorySize,
                             SMEM_BYTES);
        configured = true;
    }

    dim3 grid(N / BN, M / BM);
    auto stream = at::cuda::getCurrentCUDAStream();
    matmul_wmma_tf32_kernel<<<grid, NTHREADS, SMEM_BYTES, stream>>>(
        A.data_ptr<float>(), B.data_ptr<float>(), C.data_ptr<float>(), M, N, K);

    return C;
}
"""

matmul_cpp_source = "torch::Tensor matmul_cuda(torch::Tensor A, torch::Tensor B);"

# Compile the inline CUDA extension
matmul_ext = load_inline(
    name="matmul_wmma_tf32_v2",
    cpp_sources=matmul_cpp_source,
    cuda_sources=matmul_cuda_source,
    functions=["matmul_cuda"],
    verbose=False,
    extra_cflags=["-O3"],
    extra_cuda_cflags=["-O3"],
)


class ModelNew(nn.Module):
    """
    Optimized model that performs matrix multiplication (C = A * B) using a
    custom WMMA TF32 tensor-core CUDA kernel with shared-memory staging and
    vectorized coalesced output writes. Falls back to torch.matmul (TF32) for
    shapes/devices/dtypes the kernel does not cover.
    """
    def __init__(self):
        super(ModelNew, self).__init__()
        self._mm = matmul_ext.matmul_cuda
        self._tf32_ok = (
            torch.cuda.is_available()
            and torch.cuda.get_device_capability()[0] >= 8
        )

    def forward(self, A: torch.Tensor, B: torch.Tensor) -> torch.Tensor:
        if (
            self._tf32_ok
            and 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.is_contiguous() and B.is_contiguous()
            and A.size(1) == B.size(0)
            and A.size(0) % 128 == 0
            and B.size(1) % 128 == 0
            and A.size(1) % 64 == 0
        ):
            return self._mm(A, B)
        return torch.matmul(A, B)
```
Result of evaluating it:
The solution is correct on the test inputs. Mean runtime 4.38 ms; the PyTorch reference (with TF32 enabled) takes 3.19 ms; speedup 0.728x.
Profiler, top device kernels of one forward pass of your solution:
| device kernel | total device time (us) | calls |
|---|---|---|
| matmul_wmma_tf32_kernel(float const*, float const*, float*, int, int, int) | 4526.1 | 1 |

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.
