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 matrix-vector multiplication (C = A * B).
    """
    def __init__(self):
        super(Model, self).__init__()
    
    def forward(self, A: torch.Tensor, B: torch.Tensor) -> torch.Tensor:
        """
        Performs matrix-vector multiplication.

        Args:
            A: Input matrix of shape (M, K).
            B: Input vector of shape (K, 1).

        Returns:
            Output vector of shape (M, 1).
        """
        return torch.matmul(A, B)

M = 256 * 8 # 2048
K = 131072 * 8 # 1048576

def get_inputs():
    A = torch.rand(M, K)
    B = torch.rand(K, 1)
    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

# Fused matrix-vector multiplication (C = A @ B) CUDA kernels.
#
# Workload: A (M, K) = (2048, 1048576), B (K, 1) -> C (M, 1).
# Purely DRAM-bandwidth bound (~8 GiB of A must be streamed exactly once),
# so the whole design is about keeping the memory controllers saturated:
#   * float4 (128-bit) fully-coalesced loads, deep unrolling for
#     memory-level parallelism.
#   * __ldcs (evict-first streaming) for A: every element is read once and
#     must not displace B in the cache hierarchy.
#   * __ldg (read-only) for B: the 4 MiB vector stays resident in L2 and is
#     shared by all blocks.
#   * Two structural variants:
#       - split-K: K is partitioned across several blocks per row group
#         (thousands of independent blocks, atomicAdd finish, great load
#         balance / no tail wave);
#       - row-sequential: each block owns a handful of consecutive rows and
#         streams one long contiguous region of A (very few concurrent DRAM
#         streams, great page locality, no atomics and no memset).
#   * The best variant/geometry is chosen once per process by a short
#     autotuning pass at module construction time on a proxy tensor.

matvec_cuda_source = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAException.h>
#include <cuda_runtime.h>

namespace {

// ------------------------------ split-K kernel ------------------------------
// grid = (ceil(M / R), num_slices); each block computes partial dot products
// for R rows over one slice of K, then atomically accumulates into C.
template <int BLOCK, int R, int UNROLL>
__global__ void __launch_bounds__(BLOCK)
matvec_splitk_kernel(const float4* __restrict__ A4,
                     const float4* __restrict__ B4,
                     float* __restrict__ C,
                     const int M,
                     const int K4,
                     const int slice4) {
    constexpr int NW = BLOCK / 32;
    const int row0 = blockIdx.x * R;
    const int i0   = blockIdx.y * slice4;
    const int i1   = min(K4, i0 + slice4);

    const float4* a_rows[R];
    #pragma unroll
    for (int r = 0; r < R; ++r) {
        int row = row0 + r;
        if (row >= M) row = M - 1;  // tail: valid reads, masked on write
        a_rows[r] = A4 + static_cast<size_t>(row) * K4;
    }

    float4 acc[R];
    #pragma unroll
    for (int r = 0; r < R; ++r) acc[r] = make_float4(0.f, 0.f, 0.f, 0.f);

    const int stride = BLOCK;
    int i = i0 + threadIdx.x;

    for (; i + (UNROLL - 1) * stride < i1; i += UNROLL * stride) {
        float4 b[UNROLL];
        #pragma unroll
        for (int u = 0; u < UNROLL; ++u) b[u] = __ldg(B4 + i + u * stride);
        #pragma unroll
        for (int r = 0; r < R; ++r) {
            #pragma unroll
            for (int u = 0; u < UNROLL; ++u) {
                const float4 a = __ldcs(a_rows[r] + i + u * stride);
                acc[r].x += a.x * b[u].x;
                acc[r].y += a.y * b[u].y;
                acc[r].z += a.z * b[u].z;
                acc[r].w += a.w * b[u].w;
            }
        }
    }
    for (; i < i1; i += stride) {
        const float4 b = __ldg(B4 + i);
        #pragma unroll
        for (int r = 0; r < R; ++r) {
            const float4 a = __ldcs(a_rows[r] + i);
            acc[r].x += a.x * b.x;
            acc[r].y += a.y * b.y;
            acc[r].z += a.z * b.z;
            acc[r].w += a.w * b.w;
        }
    }

    float sum[R];
    #pragma unroll
    for (int r = 0; r < R; ++r) sum[r] = (acc[r].x + acc[r].y) + (acc[r].z + acc[r].w);

    #pragma unroll
    for (int r = 0; r < R; ++r) {
        #pragma unroll
        for (int off = 16; off > 0; off >>= 1)
            sum[r] += __shfl_down_sync(0xffffffffu, sum[r], off);
    }

    __shared__ float ws[R][NW];
    const int lane = threadIdx.x & 31;
    const int wid  = threadIdx.x >> 5;
    if (lane == 0) {
        #pragma unroll
        for (int r = 0; r < R; ++r) ws[r][wid] = sum[r];
    }
    __syncthreads();

    if (wid == 0) {
        #pragma unroll
        for (int r = 0; r < R; ++r) {
            float s = (lane < NW) ? ws[r][lane] : 0.f;
            #pragma unroll
            for (int off = NW / 2; off > 0; off >>= 1)
                s += __shfl_down_sync(0xffffffffu, s, off);
            if (lane == 0) {
                const int row = row0 + r;
                if (row < M) atomicAdd(&C[row], s);
            }
        }
    }
}

// --------------------------- row-sequential kernel --------------------------
// Each block owns rows_per_block consecutive rows and streams them one at a
// time (a long contiguous region of A). Each row is fully reduced by its
// owning block and stored directly - no atomics, no memset.
template <int BLOCK, int UNROLL>
__global__ void __launch_bounds__(BLOCK)
matvec_rowseq_kernel(const float4* __restrict__ A4,
                     const float4* __restrict__ B4,
                     float* __restrict__ C,
                     const int M,
                     const int K4,
                     const int rows_per_block) {
    constexpr int NW = BLOCK / 32;
    __shared__ float ws[NW];
    const int lane = threadIdx.x & 31;
    const int wid  = threadIdx.x >> 5;

    const int r0 = blockIdx.x * rows_per_block;
    const int r1 = min(M, r0 + rows_per_block);

    for (int row = r0; row < r1; ++row) {
        const float4* a = A4 + static_cast<size_t>(row) * K4;
        float4 acc = make_float4(0.f, 0.f, 0.f, 0.f);
        const int stride = BLOCK;
        int i = threadIdx.x;

        for (; i + (UNROLL - 1) * stride < K4; i += UNROLL * stride) {
            float4 b[UNROLL];
            #pragma unroll
            for (int u = 0; u < UNROLL; ++u) b[u] = __ldg(B4 + i + u * stride);
            #pragma unroll
            for (int u = 0; u < UNROLL; ++u) {
                const float4 av = __ldcs(a + i + u * stride);
                acc.x += av.x * b[u].x;
                acc.y += av.y * b[u].y;
                acc.z += av.z * b[u].z;
                acc.w += av.w * b[u].w;
            }
        }
        for (; i < K4; i += stride) {
            const float4 b  = __ldg(B4 + i);
            const float4 av = __ldcs(a + i);
            acc.x += av.x * b.x;
            acc.y += av.y * b.y;
            acc.z += av.z * b.z;
            acc.w += av.w * b.w;
        }

        float s = (acc.x + acc.y) + (acc.z + acc.w);
        #pragma unroll
        for (int off = 16; off > 0; off >>= 1)
            s += __shfl_down_sync(0xffffffffu, s, off);
        if (lane == 0) ws[wid] = s;
        __syncthreads();
        if (wid == 0) {
            float t = (lane < NW) ? ws[lane] : 0.f;
            #pragma unroll
            for (int off = NW / 2; off > 0; off >>= 1)
                t += __shfl_down_sync(0xffffffffu, t, off);
            if (lane == 0) C[row] = t;
        }
        __syncthreads();  // ws reuse next row
    }
}

template <int BLOCK, int R, int UNROLL>
void launch_splitk(const float4* A4, const float4* B4, float* C,
                   int64_t M, int64_t K, int split_target,
                   cudaStream_t stream) {
    const int K4 = static_cast<int>(K >> 2);
    int slice4 = (K4 + split_target - 1) / split_target;
    const int align = BLOCK * UNROLL;
    slice4 = ((slice4 + align - 1) / align) * align;
    const int num_slices = (K4 + slice4 - 1) / slice4;

    const dim3 grid(static_cast<unsigned int>((M + R - 1) / R),
                    static_cast<unsigned int>(num_slices));
    C10_CUDA_CHECK(cudaMemsetAsync(C, 0, static_cast<size_t>(M) * sizeof(float), stream));
    matvec_splitk_kernel<BLOCK, R, UNROLL><<<grid, BLOCK, 0, stream>>>(
        A4, B4, C, static_cast<int>(M), K4, slice4);
    C10_CUDA_KERNEL_LAUNCH_CHECK();
}

template <int BLOCK, int UNROLL>
void launch_rowseq(const float4* A4, const float4* B4, float* C,
                   int64_t M, int64_t K, int target_blocks,
                   cudaStream_t stream) {
    const int K4 = static_cast<int>(K >> 2);
    int rpb = static_cast<int>((M + target_blocks - 1) / target_blocks);
    if (rpb < 1) rpb = 1;
    const int num_blocks = static_cast<int>((M + rpb - 1) / rpb);
    matvec_rowseq_kernel<BLOCK, UNROLL><<<num_blocks, BLOCK, 0, stream>>>(
        A4, B4, C, static_cast<int>(M), K4, rpb);
    C10_CUDA_KERNEL_LAUNCH_CHECK();
}

}  // namespace

int64_t matvec_num_configs() { return 8; }

torch::Tensor matvec_cuda(torch::Tensor A, torch::Tensor B, int64_t config) {
    TORCH_CHECK(A.is_cuda() && B.is_cuda(), "A and B must be CUDA tensors");
    TORCH_CHECK(A.scalar_type() == at::kFloat && B.scalar_type() == at::kFloat,
                "A and B must be float32");
    TORCH_CHECK(A.dim() == 2 && B.dim() == 2 && B.size(1) == 1,
                "Expected shapes A (M, K) and B (K, 1)");
    TORCH_CHECK(A.size(1) == B.size(0), "Inner dimensions must match");

    const int64_t M = A.size(0);
    const int64_t K = A.size(1);
    auto C = torch::empty({M, 1}, A.options());

    if (M == 0 || K == 0) {
        return C.zero_();
    }
    if ((K & 3) != 0) {
        // Alignment fallback (never triggered by this model's shapes).
        C.copy_(torch::matmul(A, B));
        return C;
    }

    const float4* A4 = reinterpret_cast<const float4*>(A.data_ptr<float>());
    const float4* B4 = reinterpret_cast<const float4*>(B.data_ptr<float>());
    float* Cp = C.data_ptr<float>();
    cudaStream_t stream = at::cuda::getCurrentCUDAStream();

    switch (config) {
        case 1:  launch_splitk<256, 4, 4>(A4, B4, Cp, M, K, 8, stream);  break;
        case 2:  launch_splitk<256, 2, 4>(A4, B4, Cp, M, K, 8, stream);  break;
        case 3:  launch_splitk<256, 4, 2>(A4, B4, Cp, M, K, 16, stream); break;
        case 4:  launch_splitk<256, 4, 2>(A4, B4, Cp, M, K, 4, stream);  break;
        case 5:  launch_splitk<512, 4, 2>(A4, B4, Cp, M, K, 8, stream);  break;
        case 6:  launch_rowseq<512, 4>(A4, B4, Cp, M, K, 128, stream);   break;
        case 7:  launch_rowseq<256, 4>(A4, B4, Cp, M, K, 256, stream);   break;
        case 0:
        default: launch_splitk<256, 4, 2>(A4, B4, Cp, M, K, 8, stream);  break;
    }
    return C;
}
"""

matvec_cpp_source = (
    "torch::Tensor matvec_cuda(torch::Tensor A, torch::Tensor B, int64_t config);\n"
    "int64_t matvec_num_configs();"
)

matvec_ext = load_inline(
    name="matvec_autotuned_ext",
    cpp_sources=matvec_cpp_source,
    cuda_sources=matvec_cuda_source,
    functions=["matvec_cuda", "matvec_num_configs"],
    verbose=False,
    extra_cflags=["-O3"],
    extra_cuda_cflags=["-O3"],
)

_K_PROXY = 1048576  # keep the real K so per-block streaming behavior matches
_TUNED_CONFIG = None


def _tune_on_proxy(proxy_m):
    """Benchmark every kernel config on a proxy problem; return fastest id."""
    dev = torch.device("cuda", torch.cuda.current_device())
    A = torch.rand(proxy_m, _K_PROXY, device=dev)
    B = torch.rand(_K_PROXY, 1, device=dev)
    ref = None
    try:
        ref = torch.matmul(A, B)
        tol = 1e-2 * max(ref.abs().max().item(), 1.0)
        n = matvec_ext.matvec_num_configs()
        start = torch.cuda.Event(enable_timing=True)
        end = torch.cuda.Event(enable_timing=True)
        best_cfg, best_t = 0, None
        for c in range(n):
            out = matvec_ext.matvec_cuda(A, B, c)
            torch.cuda.synchronize()
            err = (out - ref).abs().max().item()
            del out
            if err > tol:
                continue  # numerically broken config; never use it
            for _ in range(2):
                matvec_ext.matvec_cuda(A, B, c)
            torch.cuda.synchronize()
            start.record()
            for _ in range(3):
                matvec_ext.matvec_cuda(A, B, c)
            end.record()
            torch.cuda.synchronize()
            t = start.elapsed_time(end)
            if best_t is None or t < best_t:
                best_t, best_cfg = t, c
        return best_cfg
    finally:
        del A, B, ref
        torch.cuda.empty_cache()


def _autotune():
    global _TUNED_CONFIG
    if _TUNED_CONFIG is not None:
        return _TUNED_CONFIG
    cfg = 0
    if torch.cuda.is_available():
        for proxy_m in (1024, 256):
            try:
                cfg = _tune_on_proxy(proxy_m)
                break
            except Exception:
                torch.cuda.empty_cache()
                cfg = 0
    _TUNED_CONFIG = cfg
    return cfg


class ModelNew(nn.Module):
    """
    Optimized matrix-vector multiplication (C = A @ B) backed by custom
    bandwidth-saturating CUDA kernels (split-K and row-sequential variants,
    autotuned once at construction). Falls back to torch.matmul for any
    unsupported input configuration.
    """

    def __init__(self):
        super(ModelNew, self).__init__()
        self._fn = matvec_ext.matvec_cuda
        self._cfg = _autotune()

    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 B.size(1) == 1
            and A.size(1) == B.size(0)
        ):
            return self._fn(A.contiguous(), B.contiguous(), self._cfg)
        return torch.matmul(A, B)
```
Result of evaluating it:
The solution is correct on the test inputs. Mean runtime 5.74 ms; the PyTorch reference (with TF32 enabled) takes 6.1 ms; speedup 1.063x.
Profiler, top device kernels of one forward pass of your solution:
| device kernel | total device time (us) | calls |
|---|---|---|
| void (anonymous namespace)::matvec_splitk_kernel<512, 4, 2>(float4 const*, float4 const*,  | 5751.0 | 1 |
| Memset (Device) | 1.8 | 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.
