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):
    """
    This model performs a convolution, average pooling, applies sigmoid, and sums the result.
    """
    def __init__(self, in_channels, out_channels, kernel_size, pool_kernel_size):
        super(Model, self).__init__()
        self.conv = nn.Conv2d(in_channels, out_channels, kernel_size)
        self.avg_pool = nn.AvgPool2d(pool_kernel_size)

    def forward(self, x):
        x = self.conv(x)
        x = self.avg_pool(x)
        x = torch.sigmoid(x)
        x = torch.sum(x, dim=[1,2,3]) # Sum over all spatial dimensions
        return x

batch_size = 128
in_channels = 8
out_channels = 64
height, width = 384, 384
kernel_size = 3
pool_kernel_size = 4

def get_inputs():
    return [torch.rand(batch_size, in_channels, height, width)]

def get_init_inputs():
    return [in_channels, out_channels, kernel_size, pool_kernel_size]
    ```
    
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 pooled_conv_sum_cuda(
    torch::Tensor x,
    torch::Tensor weight,
    torch::Tensor bias);
"""

_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 <mma.h>

namespace {

constexpr int CHANNELS = 8;
constexpr int OUTPUTS = 64;
constexpr int K = CHANNELS * 9;
constexpr int TILE = 64;
constexpr int THREADS = 128;

__device__ __forceinline__ float to_tf32(float value)
{
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800
    unsigned int bits;
    asm("cvt.rna.tf32.f32 %0, %1;" : "=r"(bits) : "f"(value));
    return __uint_as_float(bits);
#else
    return value;
#endif
}

__device__ __forceinline__ float warp_sum(float value)
{
    #pragma unroll
    for (int offset = 16; offset > 0; offset >>= 1)
        value += __shfl_down_sync(0xffffffffu, value, offset);
    return value;
}

__global__ __launch_bounds__(THREADS)
void pooled_conv_sigmoid_partial(
    const float* __restrict__ x,
    const float* __restrict__ weight,
    const float* __restrict__ bias,
    float* __restrict__ partial,
    int height,
    int width,
    int out_width,
    int positions,
    int tiles)
{
    const int tid = threadIdx.x;
    const int warp = tid >> 5;
    const int lane = tid & 31;
    const int tile = blockIdx.x;
    const int batch = blockIdx.y;
    const int first_position = tile * TILE;

    __shared__ __align__(32) float storage[OUTPUTS * K + K * TILE];
    float* shared_weight = storage;
    float* shared_input = storage + OUTPUTS * K;

    for (int i = tid; i < OUTPUTS * K; i += THREADS)
        shared_weight[i] = to_tf32(weight[i]);

    #pragma unroll
    for (int j = 0; j < CHANNELS * TILE / THREADS; ++j) {
        const int index = tid + j * THREADS;
        const int channel = index / TILE;
        const int local_position = index % TILE;
        const int p = first_position + local_position;

        float* dst = shared_input + channel * 9 * TILE + local_position;

        if (p < positions) {
            const int iy = (p / out_width) * 4;
            const int ix = (p % out_width) * 4;
            const float* src = x +
                ((static_cast<int64_t>(batch) * CHANNELS + channel)
                 * height + iy) * width + ix;

            float horizontal[6][3];

            #pragma unroll
            for (int r = 0; r < 6; ++r) {
                const float* row = src + r * width;
                float a, b, c, d, e, f;

                if ((width & 3) == 0) {
                    const float4 first =
                        *reinterpret_cast<const float4*>(row);
                    const float2 last =
                        *reinterpret_cast<const float2*>(row + 4);
                    a = first.x;
                    b = first.y;
                    c = first.z;
                    d = first.w;
                    e = last.x;
                    f = last.y;
                } else {
                    a = row[0];
                    b = row[1];
                    c = row[2];
                    d = row[3];
                    e = row[4];
                    f = row[5];
                }

                horizontal[r][0] = ((a + b) + c) + d;
                horizontal[r][1] = ((b + c) + d) + e;
                horizontal[r][2] = ((c + d) + e) + f;
            }

            #pragma unroll
            for (int r = 0; r < 3; ++r) {
                #pragma unroll
                for (int c = 0; c < 3; ++c) {
                    const float value =
                        ((horizontal[r][c] + horizontal[r + 1][c]) +
                         horizontal[r + 2][c]) + horizontal[r + 3][c];
                    dst[(r * 3 + c) * TILE] =
                        to_tf32(value * 0.0625f);
                }
            }
        } else {
            #pragma unroll
            for (int k = 0; k < 9; ++k)
                dst[k * TILE] = 0.0f;
        }
    }
    __syncthreads();

    float total = 0.0f;

#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800
    namespace wmma = nvcuda::wmma;

    wmma::fragment<wmma::accumulator, 16, 16, 8, float> accum[4];

    #pragma unroll
    for (int m = 0; m < 4; ++m)
        wmma::fill_fragment(accum[m], 0.0f);

    #pragma unroll
    for (int k = 0; k < K; k += 8) {
        wmma::fragment<
            wmma::matrix_b, 16, 16, 8,
            wmma::precision::tf32, wmma::row_major
        > b;

        wmma::load_matrix_sync(
            b, shared_input + k * TILE + warp * 16, TILE);

        #pragma unroll
        for (int m = 0; m < 4; ++m) {
            wmma::fragment<
                wmma::matrix_a, 16, 16, 8,
                wmma::precision::tf32, wmma::row_major
            > a;

            wmma::load_matrix_sync(
                a, shared_weight + m * 16 * K + k, K);
            wmma::mma_sync(accum[m], a, b, accum[m]);
        }
    }

    __syncthreads();

    #pragma unroll
    for (int m = 0; m < 4; ++m) {
        wmma::store_matrix_sync(
            storage + m * 16 * TILE + warp * 16,
            accum[m], TILE, wmma::mem_row_major);
    }
    __syncthreads();

    #pragma unroll
    for (int j = 0; j < OUTPUTS * TILE / THREADS; ++j) {
        const int i = tid + j * THREADS;
        const int channel = i / TILE;
        const int p = first_position + i % TILE;

        if (p < positions) {
            const float value = storage[i] + bias[channel];
            total += 1.0f / (1.0f + __expf(-value));
        }
    }
#else
    for (int i = tid; i < OUTPUTS * TILE; i += THREADS) {
        const int channel = i / TILE;
        const int local_position = i % TILE;

        if (first_position + local_position < positions) {
            float value = 0.0f;
            #pragma unroll
            for (int k = 0; k < K; ++k) {
                value = fmaf(
                    shared_weight[channel * K + k],
                    shared_input[k * TILE + local_position],
                    value);
            }
            value += bias[channel];
            total += 1.0f / (1.0f + __expf(-value));
        }
    }
#endif

    __shared__ float warp_totals[4];
    total = warp_sum(total);
    if (lane == 0)
        warp_totals[warp] = total;
    __syncthreads();

    if (warp == 0) {
        total = lane < 4 ? warp_totals[lane] : 0.0f;
        total = warp_sum(total);
        if (lane == 0)
            partial[static_cast<int64_t>(batch) * tiles + tile] = total;
    }
}

__global__ void finish_sum(
    const float* __restrict__ partial,
    float* __restrict__ output,
    int tiles)
{
    const int batch = blockIdx.x;
    const int lane = threadIdx.x & 31;
    const int warp = threadIdx.x >> 5;

    float total = 0.0f;
    for (int i = threadIdx.x; i < tiles; i += blockDim.x)
        total += partial[static_cast<int64_t>(batch) * tiles + i];

    __shared__ float warp_totals[8];
    total = warp_sum(total);
    if (lane == 0)
        warp_totals[warp] = total;
    __syncthreads();

    if (warp == 0) {
        total = lane < 8 ? warp_totals[lane] : 0.0f;
        total = warp_sum(total);
        if (lane == 0)
            output[batch] = total;
    }
}

} // namespace

torch::Tensor pooled_conv_sum_cuda(
    torch::Tensor x,
    torch::Tensor weight,
    torch::Tensor bias)
{
    TORCH_CHECK(x.is_cuda() && weight.is_cuda() && bias.is_cuda(),
                "Expected CUDA tensors");
    TORCH_CHECK(x.device() == weight.device() &&
                x.device() == bias.device(), "Device mismatch");
    TORCH_CHECK(x.scalar_type() == at::kFloat &&
                weight.scalar_type() == at::kFloat &&
                bias.scalar_type() == at::kFloat,
                "Expected float32 tensors");
    TORCH_CHECK(x.is_contiguous() && weight.is_contiguous() &&
                bias.is_contiguous(), "Expected contiguous tensors");
    TORCH_CHECK(x.dim() == 4 && x.size(1) == CHANNELS,
                "Expected NCHW input with eight channels");
    TORCH_CHECK(weight.dim() == 4 &&
                weight.size(0) == OUTPUTS &&
                weight.size(1) == CHANNELS &&
                weight.size(2) == 3 && weight.size(3) == 3 &&
                bias.numel() == OUTPUTS,
                "Expected 64x8x3x3 weights and 64 biases");
    TORCH_CHECK(x.size(2) >= 6 && x.size(3) >= 6,
                "Input is too small");

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

    const int batch = x.size(0);
    const int height = x.size(2);
    const int width = x.size(3);
    const int out_height = (height - 2) / 4;
    const int out_width = (width - 2) / 4;
    const int positions = out_height * out_width;
    const int tiles = (positions + TILE - 1) / TILE;

    auto result = torch::empty({batch}, x.options());
    if (batch == 0)
        return result;

    auto partial = torch::empty({batch, tiles}, x.options());
    const auto stream = at::cuda::getCurrentCUDAStream();

    pooled_conv_sigmoid_partial<<<dim3(tiles, batch), THREADS, 0, stream>>>(
        x.data_ptr<float>(),
        weight.data_ptr<float>(),
        bias.data_ptr<float>(),
        partial.data_ptr<float>(),
        height, width, out_width, positions, tiles);
    C10_CUDA_KERNEL_LAUNCH_CHECK();

    finish_sum<<<batch, 256, 0, stream>>>(
        partial.data_ptr<float>(), result.data_ptr<float>(), tiles);
    C10_CUDA_KERNEL_LAUNCH_CHECK();

    return result;
}
"""

_ops = load_inline(
    name="pooled_conv_fused_sigmoid_sum_v5",
    cpp_sources=_cpp_source,
    cuda_sources=_cuda_source,
    functions=["pooled_conv_sum_cuda"],
    extra_cflags=["-O3"],
    extra_cuda_cflags=["-O3"],
    verbose=False,
)


class ModelNew(nn.Module):
    def __init__(self, in_channels, out_channels, kernel_size, pool_kernel_size):
        super().__init__()
        self.conv = nn.Conv2d(in_channels, out_channels, kernel_size)
        self.avg_pool = nn.AvgPool2d(pool_kernel_size)

        pool_size = (
            (pool_kernel_size, pool_kernel_size)
            if isinstance(pool_kernel_size, int)
            else tuple(pool_kernel_size)
        )
        self._specialized = (
            in_channels == 8
            and out_channels == 64
            and self.conv.kernel_size == (3, 3)
            and pool_size == (4, 4)
        )

    def forward(self, x):
        if (
            self._specialized
            and x.is_cuda
            and x.ndim == 4
            and x.dtype == torch.float32
            and self.conv.weight.dtype == torch.float32
            and self.conv.bias.dtype == torch.float32
            and not torch.is_autocast_enabled()
        ):
            return _ops.pooled_conv_sum_cuda(
                x.contiguous(),
                self.conv.weight.contiguous(),
                self.conv.bias.contiguous(),
            )

        return torch.sigmoid(self.avg_pool(self.conv(x))).sum(dim=(1, 2, 3))
```
Result of evaluating it:
The solution is correct on the test inputs. Mean runtime 1.03 ms; the PyTorch reference (with TF32 enabled) takes 36.9 ms; speedup 35.825x.
Profiler, top device kernels of one forward pass of your solution:
| device kernel | total device time (us) | calls |
|---|---|---|
| (anonymous namespace)::pooled_conv_sigmoid_partial(float const*, float const*, float const | 1003.7 | 1 |
| (anonymous namespace)::finish_sum(float const*, float*, int) | 3.3 | 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.
