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

# Custom TF32 tensor-core GEMM specialized for the skinny-K case (K = 64),
# FP32 in/out/accumulate (TF32 MMA allowed by the precision rule).
#
# The problem is DRAM-bound: C is 32768 x 32768 floats (4 GB) that must be
# written once, while A and B are only 8 MB each.  This revision keeps the
# persistent-CTA structure of the previous (correct) version and fixes the
# store path that the crashed revision got wrong:
#   * Persistent CTAs keep their B panel (64 x 256) resident in shared
#     memory across a chunk of M, so B is read from DRAM ~once.
#   * Work units are ordered n-fastest so concurrently running CTAs sweep
#     the same M-chunk: their A-tile reads broadcast through L2, so A is
#     read from DRAM ~once.  cp.async fills overlap other work.
#   * C tiles are staged through shared memory (reusing the A-tile buffer
#     after the MMAs complete) and written with 16-byte streaming stores
#     (__stcs float4): every warp store instruction fills complete 128B
#     cache lines in 1 KB linear bursts per C row, maximizing DRAM write
#     efficiency for the 4 GB output, and the evict-first hint keeps the
#     write stream from polluting L2.
#   * The previous revision's crash is avoided: cp.async is used ONLY for
#     global->shared copies (never into registers), and the staging buffer
#     (32 rows x 264 floats = 33 KB) is carefully sized to fit inside the
#     A-tile shared allocation (34 KB) it reuses.
cuda_source = r"""
#include <torch/extension.h>
#include <cuda_runtime.h>
#include <mma.h>

namespace wmma = nvcuda::wmma;

constexpr int TILE_M = 128;
constexpr int TILE_N = 256;
constexpr int TILE_K = 64;
constexpr int M_CHUNK = 512;                // rows of C per work unit
constexpr int M_ITERS = M_CHUNK / TILE_M;   // 4
constexpr int THREADS = 256;                // 8 warps, 2 (M) x 4 (N)

// Padded leading dimensions keep ldmatrix / float4 access conflict-free
// while preserving 16B alignment.
constexpr int LDA = TILE_K + 4;             // 68 floats per A row
constexpr int LDB = TILE_N + 4;             // 260 floats per B row
constexpr int LDS = TILE_N + 8;             // 264 floats per staging row
constexpr int SMEM_A = TILE_M * LDA;        // 8704 floats  (34816 B)
constexpr int SMEM_B = TILE_K * LDB;        // 16640 floats (66560 B)
constexpr int SMEM_STAGE = 32 * LDS;        // 8448 floats  (33792 B) <= SMEM_A
constexpr int SMEM_BYTES = (SMEM_A + SMEM_B) * sizeof(float);  // 101376 B

__device__ __forceinline__ void cp_async16(void* smem_dst, const void* gmem_src) {
    unsigned dst = static_cast<unsigned>(__cvta_generic_to_shared(smem_dst));
    asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::
                 "r"(dst), "l"(gmem_src));
}

__global__ void __launch_bounds__(256) matmul_skinnyk_kernel(
    const float* __restrict__ A,
    const float* __restrict__ B,
    float* __restrict__ C,
    int M, int N, int K)
{
    extern __shared__ float smem[];
    float* As = smem;              // [TILE_M][LDA] row-major (reused as staging)
    float* Bs = smem + SMEM_A;     // [TILE_K][LDB] row-major

    const int tid  = threadIdx.x;
    const int lane = tid & 31;

    const int tiles_n  = N / TILE_N;              // 128
    const int m_chunks = M / M_CHUNK;             // 64
    const int total    = tiles_n * m_chunks;      // 8192 work units

    // 8 warps arranged 2 (M) x 4 (N): warp tile = 64 x 64
    const int warp_id = tid >> 5;
    const int warp_m  = warp_id >> 2;   // 0..1
    const int warp_n  = warp_id & 3;    // 0..3
    const int sw_m    = warp_m * 64;
    const int sw_n    = warp_n * 64;

    // Fragment addressing for m16n16 f32 accumulators.
    const int g   = lane >> 2;          // 0..7  (row group)
    const int tig = lane & 3;           // 0..3  (column pair)

    for (int u = blockIdx.x; u < total; u += gridDim.x) {
        const int mc = u / tiles_n;     // n fastest -> concurrent CTAs
        const int nt = u - mc * tiles_n;// share the same M-chunk in L2

        // ---- Load this unit's B panel (64 x 256) once into shared ----
        {
            const float4* B4 = reinterpret_cast<const float4*>(B + (size_t)nt * TILE_N);
            float4* Bs4 = reinterpret_cast<float4*>(Bs);
            const int r  = tid >> 3;        // 0..31
            const int c  = tid & 7;         // 8 threads per row, strided float4
            const int n4 = N >> 2;
            #pragma unroll
            for (int i = 0; i < 2; ++i) {           // 64 rows
                const int row = r + i * 32;
                #pragma unroll
                for (int h = 0; h < 8; ++h) {       // 64 float4 per row
                    cp_async16(&Bs4[row * (LDB / 4) + c + h * 8],
                               &B4[(size_t)row * n4 + c + h * 8]);
                }
            }
            asm volatile("cp.async.commit_group;\n");
            asm volatile("cp.async.wait_group 0;\n");
        }
        __syncthreads();

        const int m_end = mc * M_CHUNK + M_CHUNK;

        for (int m0 = mc * M_CHUNK; m0 < m_end; m0 += TILE_M) {
            // ---- Load A tile (128 x 64) via 16B async copies ----
            {
                const float4* A4 = reinterpret_cast<const float4*>(A + (size_t)m0 * K);
                float4* As4 = reinterpret_cast<float4*>(As);
                const int r  = tid >> 3;        // 0..31
                const int c  = tid & 7;         // strided float4 pairs
                const int k4 = K >> 2;
                #pragma unroll
                for (int i = 0; i < 4; ++i) {       // 128 rows
                    const int row = r + i * 32;
                    #pragma unroll
                    for (int h = 0; h < 2; ++h) {   // 16 float4 per row
                        cp_async16(&As4[row * (LDA / 4) + c + h * 8],
                                   &A4[(size_t)row * k4 + c + h * 8]);
                    }
                }
                asm volatile("cp.async.commit_group;\n");
                asm volatile("cp.async.wait_group 0;\n");
            }
            __syncthreads();

            // ---- TF32 MMA over the whole K=64 (8 k-steps of 8) ----
            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);

            #pragma unroll
            for (int kk = 0; kk < TILE_K; kk += 8) {
                wmma::fragment<wmma::matrix_a, 16, 16, 8,
                               wmma::precision::tf32, wmma::row_major> a_frag[4];
                wmma::fragment<wmma::matrix_b, 16, 16, 8,
                               wmma::precision::tf32, wmma::row_major> b_frag[4];

                #pragma unroll
                for (int i = 0; i < 4; ++i)
                    wmma::load_matrix_sync(a_frag[i],
                                           &As[(sw_m + i * 16) * LDA + kk], LDA);
                #pragma unroll
                for (int j = 0; j < 4; ++j)
                    wmma::load_matrix_sync(b_frag[j],
                                           &Bs[kk * LDB + sw_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], a_frag[i], b_frag[j], acc[i][j]);
            }

            __syncthreads();   // As no longer needed -> reuse as staging

            // ---- Stage C through shared, stream out with 16B stores ----
            // 128 tile rows are processed in 4 rounds of 32 rows.  In round
            // cc the warps with warp_m == cc/2 stage fragments i in
            // {2*(cc%2), 2*(cc%2)+1} (their rows g and g+8) into the
            // staging buffer; all threads then copy the staged 32 x 1 KB
            // block to global memory with fully-coalesced streaming stores.
            #pragma unroll
            for (int cc = 0; cc < 4; ++cc) {
                if (warp_m == (cc >> 1)) {
                    const int i0 = (cc & 1) * 2;
                    #pragma unroll
                    for (int t = 0; t < 2; ++t) {
                        const int sr  = t * 16 + g;          // staging row
                        #pragma unroll
                        for (int j = 0; j < 4; ++j) {
                            const int sc = sw_n + j * 16 + tig * 2;
                            const float* x = acc[i0 + t][j].x;
                            float2* s0 = reinterpret_cast<float2*>(&As[sr * LDS + sc]);
                            float2* s1 = reinterpret_cast<float2*>(&As[(sr + 8) * LDS + sc]);
                            s0[0] = make_float2(x[0], x[1]);
                            s1[0] = make_float2(x[2], x[3]);
                            s0[4] = make_float2(x[4], x[5]);
                            s1[4] = make_float2(x[6], x[7]);
                        }
                    }
                }
                __syncthreads();   // staging buffer complete

                // Read staged rows into registers (conflict-free float4).
                float4 v[8];
                {
                    const int r  = tid >> 3;                 // 0..31
                    const int c4 = tid & 7;                  // 8 threads/row
                    const float4* src = reinterpret_cast<const float4*>(
                        &As[r * LDS + c4 * 32]);
                    #pragma unroll
                    for (int h = 0; h < 8; ++h) v[h] = src[h * 8];
                }
                __syncthreads();   // staging buffer free for next round

                // Stream 32 rows x 1 KB to global memory: each warp store
                // instruction writes complete 128B lines (4 rows x 128B).
                {
                    const int r  = tid >> 3;
                    const int c4 = tid & 7;
                    float4* dst = reinterpret_cast<float4*>(
                        C + (size_t)(m0 + cc * 32 + r) * N + nt * TILE_N + c4 * 32);
                    #pragma unroll
                    for (int h = 0; h < 8; ++h) __stcs(dst + h * 8, v[h]);
                }
            }
            __syncthreads();   // staging buffer free -> next A tile
        }
    }
}

torch::Tensor matmul_cuda(torch::Tensor A, torch::Tensor B) {
    if (!A.is_cuda() || !B.is_cuda() ||
        A.scalar_type() != at::kFloat || B.scalar_type() != at::kFloat ||
        A.dim() != 2 || B.dim() != 2 || A.size(1) != B.size(0)) {
        return at::matmul(A, B);
    }

    auto Ac = A.contiguous();
    auto Bc = B.contiguous();

    const int64_t M = Ac.size(0);
    const int64_t K = Ac.size(1);
    const int64_t N = Bc.size(1);

    // Fast path: K == 64 and tile-aligned M / N (N % 4 == 0 implied).
    if (K == TILE_K && (M % TILE_M) == 0 && (N % TILE_N) == 0 &&
        (M % M_CHUNK) == 0) {
        auto C = torch::empty({M, N}, Ac.options());

        const int64_t m_chunks = M / M_CHUNK;
        const int64_t total = (N / TILE_N) * m_chunks;

        static int num_ctas = 0;
        if (num_ctas == 0) {
            cudaFuncSetAttribute(matmul_skinnyk_kernel,
                                 cudaFuncAttributeMaxDynamicSharedMemorySize,
                                 SMEM_BYTES);
            int dev = 0;
            cudaGetDevice(&dev);
            int sm_count = 0;
            cudaDeviceGetAttribute(&sm_count, cudaDevAttrMultiProcessorCount, dev);
            if (sm_count <= 0) sm_count = 108;
            int64_t want = (int64_t)sm_count;   // 1 fat CTA per SM (101 KB smem)
            num_ctas = (int)((total < want) ? total : want);
            if (num_ctas < 1) num_ctas = 1;
        }

        matmul_skinnyk_kernel<<<num_ctas, THREADS, SMEM_BYTES>>>(
            Ac.data_ptr<float>(), Bc.data_ptr<float>(), C.data_ptr<float>(),
            (int)M, (int)N, (int)K);
        return C;
    }

    // Generic fallback for any other shape.
    return at::matmul(Ac, Bc);
}
"""

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

_ext = load_inline(
    name="tf32_wmma_matmul_v5",
    cpp_sources=cpp_source,
    cuda_sources=cuda_source,
    functions=["matmul_cuda"],
    verbose=False,
    extra_cflags=["-O3"],
    extra_cuda_cflags=["-O3"],
)


class ModelNew(nn.Module):
    """
    Optimized model: single matmul (C = A * B) with small K, accelerated by a
    persistent TF32 tensor-core CUDA kernel (FP32 inputs/outputs/accumulation)
    that keeps B panels resident in shared memory, broadcasts A through L2,
    and writes C as 1 KB linear bursts of 16B streaming stores staged through
    shared memory to maximize DRAM efficiency for the 4 GB output tensor.
    """
    def __init__(self):
        super(ModelNew, self).__init__()
        self._ext = _ext

    def forward(self, A: torch.Tensor, B: torch.Tensor) -> torch.Tensor:
        return self._ext.matmul_cuda(A, B)
```
Result of evaluating it:
The solution compiled but failed at run time. Error output:
```
torch.AcceleratorError: CUDA error: an illegal memory access was encountered
Search for `cudaErrorIllegalAddress' in https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__TYPES.html for more information.
CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.
For debugging consider passing CUDA_LAUNCH_BLOCKING=1
The CUDA driver logged these messages, which may provide useful details:
Sticky error detected
Returning 700 (CUDA_ERROR_ILLEGAL_ADDRESS) from cuMemFree_v2
```

The fastest correct solution so far (0.818x 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

# Custom TF32 tensor-core GEMM specialized for the skinny-K case (K = 64),
# FP32 in/out/accumulate (TF32 MMA allowed by the precision rule).
#
# Performance analysis: the kernel is DRAM-bound. C is 32768x32768 floats
# (4 GB) that must be written once; A and B are only 8 MB each. The naive
# 2-D tiling re-reads A and B panels from DRAM hundreds of times because the
# 4 GB write stream flowing through L2 evicts the input panels between
# reuses (~2x total traffic -> ~0.9 TB/s effective).
#
# This version kills the redundant read traffic:
#  * Persistent CTAs: each CTA owns an output slab (N-slit x M-chunk) and
#    keeps its B panel (64x128) resident in shared memory across all M
#    iterations, so B is read from memory essentially once.
#  * Work units are ordered n-fastest so all concurrently running CTAs
#    sweep the same M-chunk: their A-tile reads hit the same lines in L2
#    (broadcast), so A is read from DRAM approximately once as well.
#  * Work is statically interleaved (u = blockIdx.x + k*gridDim.x) over
#    many small units (8192) to avoid wave-quantization tails.
#  * C is written with 8-byte streaming stores (__stcs) issued directly
#    from accumulator fragments: each warp instruction fills complete 32B
#    sectors and the evict-first hint keeps input panels resident in L2.
cuda_source = r"""
#include <torch/extension.h>
#include <cuda_runtime.h>
#include <mma.h>

namespace wmma = nvcuda::wmma;

constexpr int TILE_M = 128;
constexpr int TILE_N = 128;
constexpr int TILE_K = 64;
constexpr int M_CHUNK = 1024;               // rows of C per work unit
constexpr int M_ITERS = M_CHUNK / TILE_M;   // 8

// Padded leading dimensions keep every ldmatrix bank-conflict free while
// preserving 16B alignment for float4 copies.
constexpr int LDA = TILE_K + 4;             // 68 floats per A row
constexpr int LDB = TILE_N + 4;             // 132 floats per B row
constexpr int SMEM_A = TILE_M * LDA;        // 8704 floats
constexpr int SMEM_B = TILE_K * LDB;        // 8448 floats
constexpr int SMEM_BYTES = (SMEM_A + SMEM_B) * sizeof(float);  // 68608 B

__global__ void __launch_bounds__(256) matmul_skinnyk_kernel(
    const float* __restrict__ A,
    const float* __restrict__ B,
    float* __restrict__ C,
    int M, int N, int K)
{
    extern __shared__ float smem[];
    float* As = smem;              // [TILE_M][LDA] row-major
    float* Bs = smem + SMEM_A;     // [TILE_K][LDB] row-major

    const int tid  = threadIdx.x;
    const int lane = tid & 31;

    const int tiles_n   = N / TILE_N;          // 256
    const int m_chunks  = M / M_CHUNK;         // 32
    const int total     = tiles_n * m_chunks;  // 8192 work units

    // 8 warps arranged 2 (M) x 4 (N): warp tile = 64 x 32
    const int warp_id = tid >> 5;
    const int warp_m  = warp_id >> 2;   // 0..1
    const int warp_n  = warp_id & 3;    // 0..3
    const int sw_m    = warp_m * 64;
    const int sw_n    = warp_n * 32;

    // Fragment-store addressing: m16n16 f32 accumulator layout.
    const int g   = lane >> 2;          // 0..7  (row group)
    const int tig = lane & 3;           // 0..3  (column pair)

    for (int u = blockIdx.x; u < total; u += gridDim.x) {
        const int mc = u / tiles_n;     // n fastest -> concurrent CTAs
        const int nt = u - mc * tiles_n;// share the same M-chunk in L2

        // ---- Load this unit's B panel (64 x 128) once into shared ----
        {
            const float4* B4 = reinterpret_cast<const float4*>(B + (size_t)nt * TILE_N);
            float4* Bs4 = reinterpret_cast<float4*>(Bs);
            const int r = tid >> 5;        // 0..7
            const int c = tid & 31;        // 32 float4 per row of B
            const int n4 = N >> 2;
            #pragma unroll
            for (int i = 0; i < TILE_K / 8; ++i) {
                const int row = r + i * 8;
                Bs4[row * (LDB / 4) + c] = B4[(size_t)row * n4 + c];
            }
        }
        __syncthreads();

        const int m_end = mc * M_CHUNK + M_CHUNK;

        for (int m0 = mc * M_CHUNK; m0 < m_end; m0 += TILE_M) {
            // ---- Load A tile (128 x 64) via float4 ----
            {
                const float4* A4 = reinterpret_cast<const float4*>(A + (size_t)m0 * K);
                float4* As4 = reinterpret_cast<float4*>(As);
                const int r = tid >> 4;        // 0..15
                const int c = tid & 15;        // 16 float4 per row of A
                const int k4 = K >> 2;
                #pragma unroll
                for (int i = 0; i < TILE_M / 16; ++i) {
                    const int row = r + i * 16;
                    As4[row * (LDA / 4) + c] = A4[(size_t)row * k4 + c];
                }
            }
            __syncthreads();

            // ---- TF32 MMA over the whole K=64 (8 k-steps of 8) ----
            wmma::fragment<wmma::accumulator, 16, 16, 8, float> acc[4][2];
            #pragma unroll
            for (int i = 0; i < 4; ++i)
                #pragma unroll
                for (int j = 0; j < 2; ++j)
                    wmma::fill_fragment(acc[i][j], 0.0f);

            #pragma unroll
            for (int kk = 0; kk < TILE_K; kk += 8) {
                wmma::fragment<wmma::matrix_a, 16, 16, 8,
                               wmma::precision::tf32, wmma::row_major> a_frag[4];
                wmma::fragment<wmma::matrix_b, 16, 16, 8,
                               wmma::precision::tf32, wmma::row_major> b_frag[2];

                #pragma unroll
                for (int i = 0; i < 4; ++i)
                    wmma::load_matrix_sync(a_frag[i],
                                           &As[(sw_m + i * 16) * LDA + kk], LDA);
                #pragma unroll
                for (int j = 0; j < 2; ++j)
                    wmma::load_matrix_sync(b_frag[j],
                                           &Bs[kk * LDB + sw_n + j * 16], LDB);

                #pragma unroll
                for (int i = 0; i < 4; ++i)
                    #pragma unroll
                    for (int j = 0; j < 2; ++j)
                        wmma::mma_sync(acc[i][j], a_frag[i], b_frag[j], acc[i][j]);
            }

            // ---- Store C tile: 8B streaming stores, full 32B sectors ----
            const int row_base = m0 + sw_m + g;
            const int col_base = nt * TILE_N + sw_n + tig * 2;
            #pragma unroll
            for (int i = 0; i < 4; ++i) {
                #pragma unroll
                for (int j = 0; j < 2; ++j) {
                    const int r0 = row_base + i * 16;
                    const int c0 = col_base + j * 16;
                    const float* x = acc[i][j].x;
                    float2* p0 = reinterpret_cast<float2*>(C + (size_t)r0 * N + c0);
                    float2* p1 = reinterpret_cast<float2*>(C + (size_t)(r0 + 8) * N + c0);
                    __stcs(p0,     make_float2(x[0], x[1]));
                    __stcs(p1,     make_float2(x[2], x[3]));
                    __stcs(p0 + 4, make_float2(x[4], x[5]));
                    __stcs(p1 + 4, make_float2(x[6], x[7]));
                }
            }
            __syncthreads();   // As is reused next iteration
        }
    }
}

torch::Tensor matmul_cuda(torch::Tensor A, torch::Tensor B) {
    if (!A.is_cuda() || !B.is_cuda() ||
        A.scalar_type() != at::kFloat || B.scalar_type() != at::kFloat ||
        A.dim() != 2 || B.dim() != 2 || A.size(1) != B.size(0)) {
        return at::matmul(A, B);
    }

    auto Ac = A.contiguous();
    auto Bc = B.contiguous();

    const int64_t M = Ac.size(0);
    const int64_t K = Ac.size(1);
    const int64_t N = Bc.size(1);

    // Fast path: K == 64 and tile-aligned M / N (N % 4 == 0 implied).
    if (K == TILE_K && (M % TILE_M) == 0 && (N % TILE_N) == 0) {
        auto C = torch::empty({M, N}, Ac.options());

        const int64_t m_chunks = (M + M_CHUNK - 1) / M_CHUNK;
        const int64_t total = (N / TILE_N) * m_chunks;

        static int num_ctas = 0;
        if (num_ctas == 0) {
            cudaFuncSetAttribute(matmul_skinnyk_kernel,
                                 cudaFuncAttributeMaxDynamicSharedMemorySize,
                                 SMEM_BYTES);
            int dev = 0;
            cudaGetDevice(&dev);
            int sm_count = 0;
            cudaDeviceGetAttribute(&sm_count, cudaDevAttrMultiProcessorCount, dev);
            if (sm_count <= 0) sm_count = 108;
            int64_t want = (int64_t)sm_count * 2;   // 2 CTAs/SM (67 KB smem each)
            num_ctas = (int)((total < want) ? total : want);
            if (num_ctas < 1) num_ctas = 1;
        }

        matmul_skinnyk_kernel<<<num_ctas, 256, SMEM_BYTES>>>(
            Ac.data_ptr<float>(), Bc.data_ptr<float>(), C.data_ptr<float>(),
            (int)M, (int)N, (int)K);
        return C;
    }

    // Generic fallback for any other shape.
    return at::matmul(Ac, Bc);
}
"""

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

_ext = load_inline(
    name="tf32_wmma_matmul_v3",
    cpp_sources=cpp_source,
    cuda_sources=cuda_source,
    functions=["matmul_cuda"],
    verbose=False,
    extra_cflags=["-O3"],
    extra_cuda_cflags=["-O3"],
)


class ModelNew(nn.Module):
    """
    Optimized model: single matmul (C = A * B) with small K, accelerated by a
    persistent TF32 tensor-core CUDA kernel (FP32 inputs/outputs/accumulation)
    that keeps B panels resident in shared memory, broadcasts A through L2,
    and writes C with fully-coalesced streaming stores to minimize DRAM
    traffic for the 4 GB output tensor.
    """
    def __init__(self):
        super(ModelNew, self).__init__()
        self._ext = _ext

    def forward(self, A: torch.Tensor, B: torch.Tensor) -> torch.Tensor:
        return self._ext.matmul_cuda(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.


Precision rule: the timed forward must compute in FP32 (TF32 tensor-core math is allowed, as in the PyTorch reference). Do not cast inputs, weights or intermediate results to float16 or bfloat16 and do not call half-precision kernels in forward().
