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
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline

_cpp_source = r"""
#include <torch/extension.h>
torch::Tensor large_k_mm(torch::Tensor a, torch::Tensor b);
"""

_cuda_source = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAGuard.h>
#include <c10/cuda/CUDAException.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <cuda_fp16.h>
#include <cstdint>

namespace {

constexpr int M = 256;
constexpr int N = 256;
constexpr int K = 524288;
constexpr int SPLITS = 128;
constexpr int CHUNK = K / SPLITS;

constexpr int BM = 128;
constexpr int BN = 128;
constexpr int BK = 32;
constexpr int AS = BK + 8;
constexpr int BS = BN + 8;

__device__ __forceinline__ void store_half4(
    __half* destination, const float4 value)
{
    reinterpret_cast<__half2*>(destination)[0] =
        __floats2half2_rn(value.x, value.y);
    reinterpret_cast<__half2*>(destination)[1] =
        __floats2half2_rn(value.z, value.w);
}

#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800

__device__ __forceinline__ void load_a(
    const __half* address, unsigned int (&r)[4])
{
    const unsigned int p =
        static_cast<unsigned int>(__cvta_generic_to_shared(address));

    asm volatile(
        "ldmatrix.sync.aligned.m8n8.x4.shared.b16 "
        "{%0, %1, %2, %3}, [%4];\n"
        : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3])
        : "r"(p));
}

__device__ __forceinline__ void load_b(
    const __half* address, unsigned int (&r)[2])
{
    const unsigned int p =
        static_cast<unsigned int>(__cvta_generic_to_shared(address));

    asm volatile(
        "ldmatrix.sync.aligned.m8n8.x2.trans.shared.b16 "
        "{%0, %1}, [%2];\n"
        : "=r"(r[0]), "=r"(r[1])
        : "r"(p));
}

__device__ __forceinline__ void mma(
    float (&d)[4],
    const unsigned int (&a)[4],
    const unsigned int (&b)[2])
{
    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"(d[0]), "+f"(d[1]), "+f"(d[2]), "+f"(d[3])
        : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]),
          "r"(b[0]), "r"(b[1]));
}

#endif

__global__ __launch_bounds__(256, 2) void fused_split_mm(
    const float* __restrict__ a,
    const float* __restrict__ b,
    float* __restrict__ partial)
{
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800
    __shared__ __align__(32) __half sa[BM * AS];
    __shared__ __align__(32) __half sb[BK * BS];

    const int tid = threadIdx.x;
    const int lane = tid & 31;
    const int warp = tid >> 5;

    const int block_m = blockIdx.y * BM;
    const int block_n = blockIdx.x * BN;
    const int split_k = blockIdx.z * CHUNK;

    const int warp_m = (warp >> 1) * 32;
    const int warp_n = (warp & 1) * 64;

    float accum[2][8][4];

    #pragma unroll
    for (int mi = 0; mi < 2; ++mi) {
        #pragma unroll
        for (int ni = 0; ni < 8; ++ni) {
            #pragma unroll
            for (int j = 0; j < 4; ++j)
                accum[mi][ni][j] = 0.0f;
        }
    }

    float4 next_a[4];
    float4 next_b[4];

    #pragma unroll
    for (int i = 0; i < 4; ++i) {
        const int linear = tid * 4 + i * 1024;
        const int ar = linear / BK;
        const int ac = linear % BK;
        const int br = linear / BN;
        const int bc = linear % BN;

        next_a[i] = *reinterpret_cast<const float4*>(
            a + (block_m + ar) * K + split_k + ac);
        next_b[i] = *reinterpret_cast<const float4*>(
            b + (split_k + br) * N + block_n + bc);
    }

    #pragma unroll 1
    for (int kk = 0; kk < CHUNK; kk += BK) {
        #pragma unroll
        for (int i = 0; i < 4; ++i) {
            const int linear = tid * 4 + i * 1024;
            store_half4(sa + (linear / BK) * AS + linear % BK,
                        next_a[i]);
            store_half4(sb + (linear / BN) * BS + linear % BN,
                        next_b[i]);
        }

        __syncthreads();

        // Prefetch the next tile while the current tile is consumed.
        if (kk + BK < CHUNK) {
            #pragma unroll
            for (int i = 0; i < 4; ++i) {
                const int linear = tid * 4 + i * 1024;
                const int ar = linear / BK;
                const int ac = linear % BK;
                const int br = linear / BN;
                const int bc = linear % BN;

                next_a[i] = *reinterpret_cast<const float4*>(
                    a + (block_m + ar) * K
                      + split_k + kk + BK + ac);
                next_b[i] = *reinterpret_cast<const float4*>(
                    b + (split_k + kk + BK + br) * N
                      + block_n + bc);
            }
        }

        #pragma unroll
        for (int ki = 0; ki < BK; ki += 16) {
            unsigned int af[2][4];

            load_a(
                sa + (warp_m + (lane & 15)) * AS
                   + ki + (lane >> 4) * 8,
                af[0]);
            load_a(
                sa + (warp_m + 16 + (lane & 15)) * AS
                   + ki + (lane >> 4) * 8,
                af[1]);

            #pragma unroll
            for (int ni = 0; ni < 8; ++ni) {
                unsigned int bf[2];
                load_b(
                    sb + (ki + (lane & 15)) * BS
                       + warp_n + ni * 8,
                    bf);
                mma(accum[0][ni], af[0], bf);
                mma(accum[1][ni], af[1], bf);
            }
        }

        __syncthreads();
    }

    float* destination = partial + blockIdx.z * M * N;
    const int lane_row = lane >> 2;
    const int lane_col = (lane & 3) * 2;

    #pragma unroll
    for (int mi = 0; mi < 2; ++mi) {
        const int row = block_m + warp_m + mi * 16 + lane_row;

        #pragma unroll
        for (int ni = 0; ni < 8; ++ni) {
            const int col = block_n + warp_n + ni * 8 + lane_col;

            *reinterpret_cast<float2*>(destination + row * N + col) =
                make_float2(accum[mi][ni][0], accum[mi][ni][1]);
            *reinterpret_cast<float2*>(
                destination + (row + 8) * N + col) =
                make_float2(accum[mi][ni][2], accum[mi][ni][3]);
        }
    }
#endif
}

__global__ void reduce_partials(
    const float* __restrict__ partial,
    float* __restrict__ output)
{
    const int index = blockIdx.x * blockDim.x + threadIdx.x;
    constexpr int elements = M * N;

    float s0 = 0.0f;
    float s1 = 0.0f;
    float s2 = 0.0f;
    float s3 = 0.0f;

    #pragma unroll
    for (int split = 0; split < SPLITS; split += 4) {
        s0 += partial[(split + 0) * elements + index];
        s1 += partial[(split + 1) * elements + index];
        s2 += partial[(split + 2) * elements + index];
        s3 += partial[(split + 3) * elements + index];
    }

    output[index] = (s0 + s1) + (s2 + s3);
}

} // namespace

torch::Tensor large_k_mm(torch::Tensor a, torch::Tensor b)
{
    TORCH_CHECK(a.is_cuda() && b.is_cuda(), "Expected CUDA inputs");
    TORCH_CHECK(a.device() == b.device(), "Inputs must share a device");

    const c10::cuda::CUDAGuard guard(a.device());

    if (a.dim() != 2 || b.dim() != 2 ||
        a.scalar_type() != at::kFloat ||
        b.scalar_type() != at::kFloat ||
        !a.is_contiguous() || !b.is_contiguous() ||
        a.size(0) != M || a.size(1) != K ||
        b.size(0) != K || b.size(1) != N ||
        (reinterpret_cast<uintptr_t>(a.data_ptr<float>()) & 15) ||
        (reinterpret_cast<uintptr_t>(b.data_ptr<float>()) & 15) ||
        at::cuda::getCurrentDeviceProperties()->major < 8) {
        return at::matmul(a, b);
    }

    auto partial = torch::empty({SPLITS, M, N}, a.options());
    auto output = torch::empty({M, N}, a.options());

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

    fused_split_mm<<<dim3(N / BN, M / BM, SPLITS), 256, 0, stream>>>(
        a.data_ptr<float>(),
        b.data_ptr<float>(),
        partial.data_ptr<float>());
    C10_CUDA_KERNEL_LAUNCH_CHECK();

    reduce_partials<<<M * N / 256, 256, 0, stream>>>(
        partial.data_ptr<float>(),
        output.data_ptr<float>());
    C10_CUDA_KERNEL_LAUNCH_CHECK();

    return output;
}
"""

_extension = load_inline(
    name="large_k_fused_tensorcore_v5",
    cpp_sources=_cpp_source,
    cuda_sources=_cuda_source,
    functions=["large_k_mm"],
    extra_cflags=["-O3"],
    extra_cuda_cflags=["-O3"],
    verbose=False,
)


class ModelNew(nn.Module):
    def __init__(self):
        super().__init__()

    def forward(self, A: torch.Tensor, B: torch.Tensor) -> torch.Tensor:
        if (
            not A.is_cuda
            or not B.is_cuda
            or (torch.is_grad_enabled() and (A.requires_grad or B.requires_grad))
        ):
            return torch.matmul(A, B)
        return _extension.large_k_mm(A, B)
```
Result of evaluating it:
The solution is correct on the test inputs. Mean runtime 1.11 ms; the PyTorch reference (with TF32 enabled) takes 0.939 ms; speedup 0.846x.
Profiler, top device kernels of one forward pass of your solution:
| device kernel | total device time (us) | calls |
|---|---|---|
| (anonymous namespace)::fused_split_mm(float const*, float const*, float*) | 1062.3 | 1 |
| (anonymous namespace)::reduce_partials(float const*, float*) | 29.5 | 1 |

The fastest correct solution so far (0.903x speedup) is:
```python
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline

_cpp_source = r"""
#include <torch/extension.h>
torch::Tensor large_k_matmul(torch::Tensor a, torch::Tensor b);
"""

_cuda_source = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAGuard.h>
#include <c10/cuda/CUDAException.h>
#include <cuda_runtime.h>
#include <cublas_v2.h>
#include <climits>

namespace {

template<int SPLITS>
__global__ void reduce_partials(
    const float* __restrict__ partial,
    float* __restrict__ output,
    int elements)
{
    const int index = blockIdx.x * blockDim.x + threadIdx.x;
    if (index >= elements) return;

    float s0 = 0.0f;
    float s1 = 0.0f;
    float s2 = 0.0f;
    float s3 = 0.0f;

    #pragma unroll
    for (int split = 0; split < SPLITS; split += 4) {
        s0 += partial[(int64_t)(split + 0) * elements + index];
        s1 += partial[(int64_t)(split + 1) * elements + index];
        s2 += partial[(int64_t)(split + 2) * elements + index];
        s3 += partial[(int64_t)(split + 3) * elements + index];
    }
    output[index] = (s0 + s1) + (s2 + s3);
}

} // namespace

torch::Tensor large_k_matmul(torch::Tensor a, torch::Tensor b) {
    TORCH_CHECK(a.is_cuda() && b.is_cuda(), "Expected CUDA inputs");
    TORCH_CHECK(a.device() == b.device(), "Inputs must share a device");
    TORCH_CHECK(a.dim() == 2 && b.dim() == 2, "Expected matrices");
    TORCH_CHECK(a.size(1) == b.size(0), "Incompatible dimensions");

    const c10::cuda::CUDAGuard guard(a.device());

    constexpr int splits = 64;

    if (a.scalar_type() != at::kFloat ||
        b.scalar_type() != at::kFloat ||
        !a.is_contiguous() || !b.is_contiguous() ||
        a.size(0) == 0 || b.size(1) == 0 ||
        a.size(1) < 65536 ||
        a.size(1) % (splits * 32) != 0 ||
        a.size(0) > INT_MAX || a.size(1) > INT_MAX ||
        b.size(1) > INT_MAX ||
        a.size(0) * b.size(1) > INT_MAX ||
        at::cuda::getCurrentDeviceProperties()->major < 8) {
        return at::matmul(a, b);
    }

    const int m = static_cast<int>(a.size(0));
    const int k = static_cast<int>(a.size(1));
    const int n = static_cast<int>(b.size(1));
    const int chunk = k / splits;
    const int elements = m * n;

    auto partial = torch::empty({splits, m, n}, a.options());
    auto output = torch::empty({m, n}, a.options());

    cudaStream_t stream = at::cuda::getCurrentCUDAStream();
    cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle();

    const float alpha = 1.0f;
    const float beta = 0.0f;

    // Row-major A @ B is column-major B^T @ A^T.
    // Each batch reads a disjoint K interval directly from the inputs.
    const cublasStatus_t status = cublasGemmStridedBatchedEx(
        handle,
        CUBLAS_OP_N,
        CUBLAS_OP_N,
        n,
        m,
        chunk,
        &alpha,
        b.data_ptr<float>(),
        CUDA_R_32F,
        n,
        static_cast<long long>(chunk) * n,
        a.data_ptr<float>(),
        CUDA_R_32F,
        k,
        static_cast<long long>(chunk),
        &beta,
        partial.data_ptr<float>(),
        CUDA_R_32F,
        n,
        static_cast<long long>(elements),
        splits,
        CUBLAS_COMPUTE_32F_FAST_TF32,
        CUBLAS_GEMM_DEFAULT_TENSOR_OP);

    TORCH_CHECK(
        status == CUBLAS_STATUS_SUCCESS,
        "Split-K GEMM failed with cuBLAS status ",
        static_cast<int>(status));

    reduce_partials<splits><<<(elements + 255) / 256, 256, 0, stream>>>(
        partial.data_ptr<float>(),
        output.data_ptr<float>(),
        elements);
    C10_CUDA_KERNEL_LAUNCH_CHECK();

    return output;
}
"""

_extension = load_inline(
    name="large_k_batched_tf32_v2",
    cpp_sources=_cpp_source,
    cuda_sources=_cuda_source,
    functions=["large_k_matmul"],
    extra_cflags=["-O3"],
    extra_cuda_cflags=["-O3"],
    extra_ldflags=["-lcublas"],
    verbose=False,
)


class ModelNew(nn.Module):
    def __init__(self):
        super().__init__()

    def forward(self, A: torch.Tensor, B: torch.Tensor) -> torch.Tensor:
        if (
            not A.is_cuda
            or not B.is_cuda
            or A.ndim != 2
            or B.ndim != 2
            or (torch.is_grad_enabled() and (A.requires_grad or B.requires_grad))
        ):
            return torch.matmul(A, B)
        return _extension.large_k_matmul(A, B)
```

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.
