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 large K dimension
    """
    def __init__(self):
        super(Model, self).__init__()
    
    def forward(self, A: torch.Tensor, B: torch.Tensor) -> torch.Tensor:
        """
        Performs matrix multiplication of A and B.

        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 = 256
N = 256
K = 131072 * 4

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 6 of 6 for this task. Your previous solution (turn 5) 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

_cuda_src = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda_runtime.h>
#include <cuda_pipeline.h>
#include <mma.h>

using namespace nvcuda;

// ---------------------------------------------------------------------------
// Split-K TF32 tensor-core GEMM for C = A @ B with an enormous K dimension.
//   A: (M, K) row-major, B: (K, N) row-major, C: (M, N) row-major, pre-zeroed.
//
// The problem is purely bandwidth bound: ~1 GB must be streamed from HBM.
// Design:
//  * 128x256 block tile (M=256, N=256 -> only 2 tiles, so A is read exactly
//    once; the twin M-tile block is co-scheduled so the duplicate B read is
//    served from L2).
//  * 256 threads = 8 warps in a 2x4 grid, 64x64 warp tile built from wmma
//    16x16x8 tf32 fragments (best mma:shared-load ratio that fits registers).
//  * cp.async multi-stage pipeline keeps >=100 KB in flight per SM to hide
//    HBM latency; shared-memory padding is chosen to be bank-conflict free.
//  * K is split so the grid exactly fills every SM with one wave of blocks.
//  * Epilogue stages the partial tile in shared memory and reduces it with
//    coalesced atomics (vectorized red.global.add.v4.f32 on sm_90+).
// ---------------------------------------------------------------------------

#define BM 128
#define BN 256
#define NT 256

template<int BK, int STAGES>
__global__ void __launch_bounds__(NT, 1)
splitk_gemm_tf32(const float* __restrict__ A,
                 const float* __restrict__ B,
                 float* __restrict__ C,
                 int M, int N, int K, int k_chunk, int big_cs)
{
#if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 800)
    constexpr int LDA = BK + 4;
    constexpr int LDB = BN + 8;                 // conflict-free tf32 frag loads
    constexpr int A_FLOATS = BM * LDA;
    constexpr int B_FLOATS = BK * LDB;
    constexpr int STAGE_FLOATS = A_FLOATS + B_FLOATS;

    extern __shared__ float smem[];

    const int tid  = threadIdx.x;
    const int warp = tid >> 5;

    const int tiles_n = N / BN;
    const int bm = blockIdx.x / tiles_n;
    const int bn = blockIdx.x % tiles_n;
    const int m0 = bm * BM;
    const int n0 = bn * BN;

    const int k_begin = blockIdx.y * k_chunk;
    const int k_end   = min(K, k_begin + k_chunk);
    const int T = (k_end - k_begin) / BK;

    // ---- async global -> shared tile loader (16B cp.async chunks) ----------
    auto load_tile = [&](int s, int t) {
        float* sa = smem + s * STAGE_FLOATS;
        float* sb = sa + A_FLOATS;
        const int kg = k_begin + t * BK;
        constexpr int CHA = BK / 4;                 // 16B chunks per A row
        #pragma unroll
        for (int r = 0; r < (BM * CHA) / NT; ++r) {
            const int idx = tid + r * NT;
            const int row = idx / CHA;
            const int ch  = idx % CHA;
            __pipeline_memcpy_async(sa + row * LDA + ch * 4,
                                    A + (long long)(m0 + row) * K + kg + ch * 4, 16);
        }
        constexpr int CHB = BN / 4;                 // 16B chunks per B row
        #pragma unroll
        for (int r = 0; r < (BK * CHB) / NT; ++r) {
            const int idx = tid + r * NT;
            const int row = idx / CHB;
            const int ch  = idx % CHB;
            __pipeline_memcpy_async(sb + row * LDB + ch * 4,
                                    B + (long long)(kg + row) * N + n0 + ch * 4, 16);
        }
    };

    const int warp_m = (warp >> 2) * 64;
    const int warp_n = (warp & 3) * 64;

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

    // ---- pipelined main loop ------------------------------------------------
    #pragma unroll
    for (int s = 0; s < STAGES - 1; ++s) {
        if (s < T) load_tile(s, s);
        __pipeline_commit();
    }

    for (int t = 0; t < T; ++t) {
        __pipeline_wait_prior(STAGES - 2);
        __syncthreads();
        const int tn = t + STAGES - 1;
        if (tn < T) load_tile(tn % STAGES, tn);
        __pipeline_commit();

        const float* sa = smem + (t % STAGES) * STAGE_FLOATS;
        const float* sb = sa + A_FLOATS;

        #pragma unroll
        for (int kk = 0; kk < BK; kk += 8) {
            wmma::fragment<wmma::matrix_a, 16, 16, 8, wmma::precision::tf32, wmma::row_major> af[4];
            wmma::fragment<wmma::matrix_b, 16, 16, 8, wmma::precision::tf32, wmma::row_major> bf[4];
            #pragma unroll
            for (int i = 0; i < 4; ++i)
                wmma::load_matrix_sync(af[i], sa + (warp_m + i * 16) * LDA + kk, LDA);
            #pragma unroll
            for (int j = 0; j < 4; ++j)
                wmma::load_matrix_sync(bf[j], sb + kk * LDB + warp_n + j * 16, LDB);
            #pragma unroll
            for (int i = 0; i < 4; ++i)
                #pragma unroll
                for (int j = 0; j < 4; ++j)
                    wmma::mma_sync(acc[i][j], af[i], bf[j], acc[i][j]);
        }
    }

    // ---- epilogue: stage partial tile in shared, coalesced reduction --------
    __syncthreads();
    if (big_cs) {
        constexpr int LDC = BN + 8;
        float* Cs = smem;   // reuse pipeline smem; BM*(BN+8)*4B must fit
        #pragma unroll
        for (int i = 0; i < 4; ++i)
            #pragma unroll
            for (int j = 0; j < 4; ++j)
                wmma::store_matrix_sync(Cs + (warp_m + i * 16) * LDC + warp_n + j * 16,
                                        acc[i][j], LDC, wmma::mem_row_major);
        __syncthreads();
        #pragma unroll 4
        for (int r = 0; r < (BM * BN) / NT; ++r) {
            const int idx = tid + r * NT;
            const int rr = idx >> 8;               // BN = 256
            const int cc = idx & (BN - 1);
#if __CUDA_ARCH__ >= 900
            if ((cc & 3) == 0) {
                const float4 v = *reinterpret_cast<const float4*>(&Cs[rr * LDC + cc]);
                asm volatile("red.global.add.v4.f32 [%0], {%1,%2,%3,%4};" ::
                             "l"(C + (long long)(m0 + rr) * N + n0 + cc),
                             "f"(v.x), "f"(v.y), "f"(v.z), "f"(v.w) : "memory");
            }
#else
            atomicAdd(C + (long long)(m0 + rr) * N + n0 + cc, Cs[rr * LDC + cc]);
#endif
        }
    } else {
        // small per-warp scratch (for devices with limited shared memory)
        float* scratch = smem + warp * (16 * 17);
        const int lane = tid & 31;
        #pragma unroll
        for (int i = 0; i < 4; ++i) {
            #pragma unroll
            for (int j = 0; j < 4; ++j) {
                wmma::store_matrix_sync(scratch, acc[i][j], 17, wmma::mem_row_major);
                __syncwarp();
                const int gm = m0 + warp_m + i * 16;
                const int gn = n0 + warp_n + j * 16;
                #pragma unroll
                for (int e = 0; e < 8; ++e) {
                    const int idx = lane + e * 32;
                    const int rr = idx >> 4;
                    const int cc = idx & 15;
                    atomicAdd(C + (long long)(gm + rr) * N + gn + cc, scratch[rr * 17 + cc]);
                }
                __syncwarp();
            }
        }
    }
#endif
}

// ------------------------------- host wrapper -------------------------------

template<int BK, int STAGES>
static bool try_launch(const torch::Tensor& A, const torch::Tensor& B,
                       torch::Tensor& C, int M, int N, int K,
                       int sms, int optin_smem, const cudaStream_t stream) {
    constexpr int STAGE_BYTES = (BM * (BK + 4) + BK * (BN + 8)) * (int)sizeof(float);
    constexpr int PIPE_BYTES = STAGES * STAGE_BYTES;
    constexpr int CS_BYTES = BM * (BN + 8) * (int)sizeof(float);
    int big_cs = 1;
    int smem = PIPE_BYTES > CS_BYTES ? PIPE_BYTES : CS_BYTES;
    if (smem > optin_smem) {
        big_cs = 0;
        smem = PIPE_BYTES;
        if (smem > optin_smem) return false;
    }

    static bool attr_done = false;
    if (!attr_done) {
        if (cudaFuncSetAttribute(splitk_gemm_tf32<BK, STAGES>,
                                 cudaFuncAttributeMaxDynamicSharedMemorySize,
                                 smem) != cudaSuccess) {
            return false;
        }
        attr_done = true;
    }

    const int tiles = (M / BM) * (N / BN);
    int sk = sms / tiles;                           // one wave of blocks
    if (sk < 1) sk = 1;
    const int max_sk = K / BK;
    if (sk > max_sk) sk = max_sk;
    const int k_chunk = (int)(((K + (long long)sk * BK - 1) / ((long long)sk * BK)) * BK);
    sk = (int)((K + k_chunk - 1) / k_chunk);

    dim3 grid(tiles, sk);
    splitk_gemm_tf32<BK, STAGES><<<grid, NT, smem, stream>>>(
        A.data_ptr<float>(), B.data_ptr<float>(), C.data_ptr<float>(),
        M, N, K, k_chunk, big_cs);
    return true;
}

static bool ptr_dims_ok(const torch::Tensor& A, const torch::Tensor& B,
                        int M, int N, int K, int major) {
    const bool ptr_ok =
        (reinterpret_cast<uintptr_t>(A.data_ptr<float>()) % 16 == 0) &&
        (reinterpret_cast<uintptr_t>(B.data_ptr<float>()) % 16 == 0);
    const bool dims_ok = (M % BM == 0) && (N % BN == 0) && (K % 16 == 0);
    return major >= 8 && ptr_ok && dims_ok;
}

torch::Tensor matmul_cuda(torch::Tensor A, torch::Tensor B) {
    TORCH_CHECK(A.is_cuda() && B.is_cuda(), "inputs must be CUDA tensors");
    TORCH_CHECK(A.scalar_type() == torch::kFloat32 &&
                B.scalar_type() == torch::kFloat32, "float32 only");
    if (!A.is_contiguous()) A = A.contiguous();
    if (!B.is_contiguous()) B = B.contiguous();

    const int M = (int)A.size(0);
    const int K = (int)A.size(1);
    const int N = (int)B.size(1);
    TORCH_CHECK(B.size(0) == K, "inner dimensions must match");

    auto prop = at::cuda::getCurrentDeviceProperties();
    if (!ptr_dims_ok(A, B, M, N, K, prop->major)) {
        return torch::matmul(A, B);
    }

    auto C = torch::zeros({M, N}, A.options());
    const int sms = prop->multiProcessorCount;
    const int optin = (int)prop->sharedMemPerBlockOptin;
    auto stream = at::cuda::getCurrentCUDAStream();

    bool ok = false;
    if (K % 32 == 0) {
        ok = try_launch<32, 3>(A, B, C, M, N, K, sms, optin, stream.stream());
    }
    if (!ok) ok = try_launch<16, 5>(A, B, C, M, N, K, sms, optin, stream.stream());
    if (!ok) ok = try_launch<16, 4>(A, B, C, M, N, K, sms, optin, stream.stream());
    if (!ok) ok = try_launch<16, 3>(A, B, C, M, N, K, sms, optin, stream.stream());
    if (!ok) return torch::matmul(A, B);
    return C;
}

// Configurable variant used for autotuning from Python.
torch::Tensor matmul_cfg(torch::Tensor A, torch::Tensor B, int64_t bk, int64_t stages) {
    TORCH_CHECK(A.is_cuda() && B.is_cuda(), "inputs must be CUDA tensors");
    if (!A.is_contiguous()) A = A.contiguous();
    if (!B.is_contiguous()) B = B.contiguous();

    const int M = (int)A.size(0);
    const int K = (int)A.size(1);
    const int N = (int)B.size(1);

    auto prop = at::cuda::getCurrentDeviceProperties();
    auto C = torch::zeros({M, N}, A.options());
    const int sms = prop->multiProcessorCount;
    const int optin = (int)prop->sharedMemPerBlockOptin;
    auto stream = at::cuda::getCurrentCUDAStream();

    bool ok = false;
    if (bk == 32 && stages == 4)      ok = try_launch<32, 4>(A, B, C, M, N, K, sms, optin, stream.stream());
    else if (bk == 32 && stages == 3) ok = try_launch<32, 3>(A, B, C, M, N, K, sms, optin, stream.stream());
    else if (bk == 64 && stages == 2) ok = try_launch<64, 2>(A, B, C, M, N, K, sms, optin, stream.stream());
    else if (bk == 16 && stages == 6) ok = try_launch<16, 6>(A, B, C, M, N, K, sms, optin, stream.stream());
    else if (bk == 16 && stages == 5) ok = try_launch<16, 5>(A, B, C, M, N, K, sms, optin, stream.stream());
    else if (bk == 16 && stages == 4) ok = try_launch<16, 4>(A, B, C, M, N, K, sms, optin, stream.stream());
    else if (bk == 16 && stages == 3) ok = try_launch<16, 3>(A, B, C, M, N, K, sms, optin, stream.stream());
    TORCH_CHECK(ok, "requested config does not fit this device");
    return C;
}
"""

_cpp_src = (
    "torch::Tensor matmul_cuda(torch::Tensor A, torch::Tensor B);\n"
    "torch::Tensor matmul_cfg(torch::Tensor A, torch::Tensor B, int64_t bk, int64_t stages);"
)

_ext = load_inline(
    name="tf32_splitk_gemm_v5",
    cpp_sources=_cpp_src,
    cuda_sources=_cuda_src,
    functions=["matmul_cuda", "matmul_cfg"],
    verbose=False,
    extra_cuda_cflags=["-O3", "--use_fast_math"],
)


class ModelNew(nn.Module):
    """
    Matrix multiplication C = A @ B accelerated with a custom split-K TF32
    tensor-core CUDA kernel (128x256 block tile so A is read exactly once,
    64x64 warp tiles, cp.async multi-stage pipeline with >=100KB in flight
    per SM, shared-memory staged coalesced atomic reduction). At init time a
    small set of pipeline configurations is autotuned (including the PyTorch
    cuBLAS baseline) and the fastest is cached. Falls back to torch.matmul
    when shapes or hardware are unsupported.
    """

    _CONFIGS = [(32, 4), (32, 3), (64, 2), (16, 6), (16, 5), (16, 4)]

    def __init__(self):
        super(ModelNew, self).__init__()
        self._ext = _ext
        self._cfg = None          # (bk, stages) of the fastest custom kernel
        self._use_torch = False   # True if the cuBLAS baseline wins
        self._tuned = False

    def _supported(self, A, B):
        return (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(0)
                and A.size(0) % 128 == 0 and B.size(1) % 256 == 0
                and A.size(1) % 16 == 0
                and A.data_ptr() % 16 == 0 and B.data_ptr() % 16 == 0)

    def _autotune(self, A, B):
        best_time = float("inf")
        best_cfg = None
        # Candidate custom kernel configurations.
        for bk, st in self._CONFIGS:
            if A.size(1) % bk != 0:
                continue
            try:
                for _ in range(2):          # warmup
                    self._ext.matmul_cfg(A, B, bk, st)
                torch.cuda.synchronize()
                start = torch.cuda.Event(enable_timing=True)
                end = torch.cuda.Event(enable_timing=True)
                start.record()
                for _ in range(3):
                    self._ext.matmul_cfg(A, B, bk, st)
                end.record()
                torch.cuda.synchronize()
                t = start.elapsed_time(end)
                if t < best_time:
                    best_time = t
                    best_cfg = (bk, st)
            except Exception:
                continue
        # PyTorch cuBLAS baseline as a safety net.
        try:
            for _ in range(2):
                torch.matmul(A, B)
            torch.cuda.synchronize()
            start = torch.cuda.Event(enable_timing=True)
            end = torch.cuda.Event(enable_timing=True)
            start.record()
            for _ in range(3):
                torch.matmul(A, B)
            end.record()
            torch.cuda.synchronize()
            t = start.elapsed_time(end)
            if t < 0.9 * best_time:         # require a clear win to switch
                best_cfg = None
        except Exception:
            pass
        self._cfg = best_cfg
        self._use_torch = best_cfg is None
        self._tuned = True

    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):
            if not self._tuned and self._supported(A, B):
                try:
                    self._autotune(A, B)
                except Exception:
                    self._tuned = True
                    self._use_torch = False
                    self._cfg = None
            if self._tuned:
                if self._use_torch:
                    return torch.matmul(A, B)
                if self._cfg is not None and self._supported(A, B):
                    return self._ext.matmul_cfg(A, B, self._cfg[0], self._cfg[1])
            return self._ext.matmul_cuda(A, B)
        return torch.matmul(A, B)
```
Result of evaluating it:
The solution is correct on the test inputs. Mean runtime 1.1 ms; the PyTorch reference (with TF32 enabled) takes 0.939 ms; speedup 0.854x.
Profiler, top device kernels of one forward pass of your solution:
| device kernel | total device time (us) | calls |
|---|---|---|
| void splitk_gemm_tf32<16, 4>(float const*, float const*, float*, int, int, int, int, int) | 1070.1 | 1 |
| void at::native::vectorized_elementwise_kernel<4, at::native::FillFunctor<float>, std::arr | 2.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.
