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 5 of 6 for this task. Your previous solution (turn 4) 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
    float result;
    asm("cvt.rn.tf32.f32 %0, %1;" : "=f"(result) : "f"(value));
    return result;
#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;
}

// Pool input patches directly into shared memory, multiply by the
// convolution weights, and immediately reduce the sigmoid outputs.
__global__ 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]);
        }
    }

    // All warps must finish reading weights before reusing their storage.
    __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_v4",
    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 failed to compile. Error output:
```
...[truncated]
ires .target sm_90 or higher
ptxas /srv/jobs/1791714698728060782-3456539-0/tmp/tmpxft_0000216d_00000000-6_cuda.ptx, line 1042; error   : Arguments mismatch for instruction 'cvt'
ptxas /srv/jobs/1791714698728060782-3456539-0/tmp/tmpxft_0000216d_00000000-6_cuda.ptx, line 1042; error   : Feature 'cvt with .tf32.f32.rn' requires .target sm_90 or higher
ptxas /srv/jobs/1791714698728060782-3456539-0/tmp/tmpxft_0000216d_00000000-6_cuda.ptx, line 1050; error   : Arguments mismatch for instruction 'cvt'
ptxas /srv/jobs/1791714698728060782-3456539-0/tmp/tmpxft_0000216d_00000000-6_cuda.ptx, line 1050; error   : Feature 'cvt with .tf32.f32.rn' requires .target sm_90 or higher
ptxas /srv/jobs/1791714698728060782-3456539-0/tmp/tmpxft_0000216d_00000000-6_cuda.ptx, line 1058; error   : Arguments mismatch for instruction 'cvt'
ptxas /srv/jobs/1791714698728060782-3456539-0/tmp/tmpxft_0000216d_00000000-6_cuda.ptx, line 1058; error   : Feature 'cvt with .tf32.f32.rn' requires .target sm_90 or higher
ptxas /srv/jobs/1791714698728060782-3456539-0/tmp/tmpxft_0000216d_00000000-6_cuda.ptx, line 1296; error   : Arguments mismatch for instruction 'cvt'
ptxas /srv/jobs/1791714698728060782-3456539-0/tmp/tmpxft_0000216d_00000000-6_cuda.ptx, line 1296; error   : Feature 'cvt with .tf32.f32.rn' requires .target sm_90 or higher
ptxas /srv/jobs/1791714698728060782-3456539-0/tmp/tmpxft_0000216d_00000000-6_cuda.ptx, line 1304; error   : Arguments mismatch for instruction 'cvt'
ptxas /srv/jobs/1791714698728060782-3456539-0/tmp/tmpxft_0000216d_00000000-6_cuda.ptx, line 1304; error   : Feature 'cvt with .tf32.f32.rn' requires .target sm_90 or higher
ptxas /srv/jobs/1791714698728060782-3456539-0/tmp/tmpxft_0000216d_00000000-6_cuda.ptx, line 1312; error   : Arguments mismatch for instruction 'cvt'
ptxas /srv/jobs/1791714698728060782-3456539-0/tmp/tmpxft_0000216d_00000000-6_cuda.ptx, line 1312; error   : Feature 'cvt with .tf32.f32.rn' requires .target sm_90 or higher
ptxas /srv/jobs/1791714698728060782-3456539-0/tmp/tmpxft_0000216d_00000000-6_cuda.ptx, line 1320; error   : Arguments mismatch for instruction 'cvt'
ptxas /srv/jobs/1791714698728060782-3456539-0/tmp/tmpxft_0000216d_00000000-6_cuda.ptx, line 1320; error   : Feature 'cvt with .tf32.f32.rn' requires .target sm_90 or higher
ptxas /srv/jobs/1791714698728060782-3456539-0/tmp/tmpxft_0000216d_00000000-6_cuda.ptx, line 1328; error   : Arguments mismatch for instruction 'cvt'
ptxas /srv/jobs/1791714698728060782-3456539-0/tmp/tmpxft_0000216d_00000000-6_cuda.ptx, line 1328; error   : Feature 'cvt with .tf32.f32.rn' requires .target sm_90 or higher
ptxas /srv/jobs/1791714698728060782-3456539-0/tmp/tmpxft_0000216d_00000000-6_cuda.ptx, line 1336; error   : Arguments mismatch for instruction 'cvt'
ptxas /srv/jobs/1791714698728060782-3456539-0/tmp/tmpxft_0000216d_00000000-6_cuda.ptx, line 1336; error   : Feature 'cvt with .tf32.f32.rn' requires .target sm_90 or higher
ptxas /srv/jobs/1791714698728060782-3456539-0/tmp/tmpxft_0000216d_00000000-6_cuda.ptx, line 1344; error   : Arguments mismatch for instruction 'cvt'
ptxas /srv/jobs/1791714698728060782-3456539-0/tmp/tmpxft_0000216d_00000000-6_cuda.ptx, line 1344; error   : Feature 'cvt with .tf32.f32.rn' requires .target sm_90 or higher
ptxas /srv/jobs/1791714698728060782-3456539-0/tmp/tmpxft_0000216d_00000000-6_cuda.ptx, line 1352; error   : Arguments mismatch for instruction 'cvt'
ptxas /srv/jobs/1791714698728060782-3456539-0/tmp/tmpxft_0000216d_00000000-6_cuda.ptx, line 1352; error   : Feature 'cvt with .tf32.f32.rn' requires .target sm_90 or higher
ptxas /srv/jobs/1791714698728060782-3456539-0/tmp/tmpxft_0000216d_00000000-6_cuda.ptx, line 1360; error   : Arguments mismatch for instruction 'cvt'
ptxas /srv/jobs/1791714698728060782-3456539-0/tmp/tmpxft_0000216d_00000000-6_cuda.ptx, line 1360; error   : Feature 'cvt with .tf32.f32.rn' requires .target sm_90 or higher
ptxas fatal   : Ptx assembly aborted due to errors
ninja: build stopped: subcommand failed.

```

The fastest correct solution so far (24.276x 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 pooled_conv_sum_cuda(
    torch::Tensor x,
    torch::Tensor weight,
    torch::Tensor bias,
    int64_t pool_h,
    int64_t pool_w);
"""

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

constexpr int THREADS = 256;
constexpr int CHUNK = 4096;

// Pool each convolution input patch before performing the channel mixing.
// The resulting matrix has shape [batch, in_channels * kh * kw, pitch].
__global__ void lower_pool_3x3_4x4(
    const float* __restrict__ x,
    float* __restrict__ lowered,
    int channels, int height, int width,
    int out_width, int positions, int pitch)
{
    const int p = blockIdx.x * blockDim.x + threadIdx.x;
    const int channel = blockIdx.y;
    const int batch = blockIdx.z;
    if (p >= pitch)
        return;

    float* dst = lowered +
        (static_cast<int64_t>(batch) * channels + channel) * 9 * pitch + p;

    if (p >= positions) {
        #pragma unroll
        for (int k = 0; k < 9; ++k)
            dst[static_cast<int64_t>(k) * pitch] = 0.0f;
        return;
    }

    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 a = src[r * width];
        const float b = src[r * width + 1];
        const float c = src[r * width + 2];
        const float d = src[r * width + 3];
        const float e = src[r * width + 4];
        const float f = src[r * width + 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[static_cast<int64_t>(r * 3 + c) * pitch] =
                value * 0.0625f;
        }
    }
}

__global__ void lower_pool_generic(
    const float* __restrict__ x,
    float* __restrict__ lowered,
    int channels, int height, int width,
    int kh, int kw, int ph, int pw,
    int out_width, int positions, int pitch)
{
    const int p = blockIdx.x * blockDim.x + threadIdx.x;
    const int channel = blockIdx.y;
    const int batch = blockIdx.z;
    if (p >= pitch)
        return;

    float* dst = lowered +
        (static_cast<int64_t>(batch) * channels + channel) * kh * kw * pitch
        + p;

    const int iy = (p / out_width) * ph;
    const int ix = (p % out_width) * pw;
    const float scale = 1.0f / static_cast<float>(ph * pw);

    for (int r = 0; r < kh; ++r) {
        for (int c = 0; c < kw; ++c) {
            float value = 0.0f;
            if (p < positions) {
                const float* src = x +
                    ((static_cast<int64_t>(batch) * channels + channel)
                     * height + iy + r) * width + ix + c;

                for (int pr = 0; pr < ph; ++pr)
                    for (int pc = 0; pc < pw; ++pc)
                        value += src[pr * width + pc];
            }
            dst[static_cast<int64_t>(r * kw + c) * pitch] = value * scale;
        }
    }
}

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

__device__ __forceinline__ float block_sum(float value)
{
    __shared__ float sums[8];
    const int lane = threadIdx.x & 31;
    const int warp = threadIdx.x >> 5;

    value = warp_sum(value);
    if (lane == 0)
        sums[warp] = value;
    __syncthreads();

    value = threadIdx.x < 8 ? sums[lane] : 0.0f;
    if (warp == 0)
        value = warp_sum(value);
    return value;
}

__global__ void bias_sigmoid_partial(
    const float* __restrict__ input,
    const float* __restrict__ bias,
    float* __restrict__ partial,
    int positions, int pitch, int channels, int parts)
{
    const int batch = blockIdx.y;
    const int part = blockIdx.x;
    const int64_t sample_size = static_cast<int64_t>(channels) * pitch;
    const int64_t begin = static_cast<int64_t>(part) * CHUNK;
    const float* src = input + static_cast<int64_t>(batch) * sample_size;

    float total = 0.0f;
    #pragma unroll
    for (int j = 0; j < CHUNK / THREADS; ++j) {
        const int64_t i = begin + threadIdx.x + j * THREADS;
        if (i < sample_size) {
            const int channel = i / pitch;
            const int p = i - static_cast<int64_t>(channel) * pitch;
            if (p < positions) {
                const float value = src[i] + bias[channel];
                total += 1.0f / (1.0f + expf(-value));
            }
        }
    }

    total = block_sum(total);
    if (threadIdx.x == 0)
        partial[static_cast<int64_t>(batch) * parts + part] = total;
}

__global__ void finish_sum(
    const float* __restrict__ partial,
    float* __restrict__ output,
    int parts)
{
    const int batch = blockIdx.x;
    float total = 0.0f;
    for (int i = threadIdx.x; i < parts; i += blockDim.x)
        total += partial[static_cast<int64_t>(batch) * parts + i];

    total = block_sum(total);
    if (threadIdx.x == 0)
        output[batch] = total;
}

torch::Tensor pooled_conv_sum_cuda(
    torch::Tensor x,
    torch::Tensor weight,
    torch::Tensor bias,
    int64_t pool_h,
    int64_t pool_w)
{
    TORCH_CHECK(x.is_cuda() && weight.is_cuda() && bias.is_cuda(),
                "All tensors must be CUDA tensors");
    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 && weight.dim() == 4,
                "Expected NCHW input and OIHW weights");
    TORCH_CHECK(x.device() == weight.device() &&
                x.device() == bias.device(), "Device mismatch");
    TORCH_CHECK(pool_h > 0 && pool_w > 0, "Invalid pooling size");

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

    const int batch = x.size(0);
    const int channels = x.size(1);
    const int height = x.size(2);
    const int width = x.size(3);
    const int outputs = weight.size(0);
    const int kh = weight.size(2);
    const int kw = weight.size(3);
    const int ph = pool_h;
    const int pw = pool_w;

    TORCH_CHECK(weight.size(1) == channels && bias.numel() == outputs,
                "Channel mismatch");
    TORCH_CHECK(height >= kh + ph - 1 && width >= kw + pw - 1,
                "Input is too small");

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

    const int oh = (height - kh + 1) / ph;
    const int ow = (width - kw + 1) / pw;
    const int positions = oh * ow;
    const int pitch = ((positions + 31) / 32) * 32;
    const int reduction_size = channels * kh * kw;

    auto lowered = torch::empty(
        {batch, reduction_size, pitch}, x.options());
    auto products = torch::empty(
        {batch, outputs, pitch}, x.options());

    const auto stream = at::cuda::getCurrentCUDAStream();
    const dim3 grid((pitch + THREADS - 1) / THREADS, channels, batch);

    if (kh == 3 && kw == 3 && ph == 4 && pw == 4) {
        lower_pool_3x3_4x4<<<grid, THREADS, 0, stream>>>(
            x.data_ptr<float>(), lowered.data_ptr<float>(),
            channels, height, width, ow, positions, pitch);
    } else {
        lower_pool_generic<<<grid, THREADS, 0, stream>>>(
            x.data_ptr<float>(), lowered.data_ptr<float>(),
            channels, height, width, kh, kw, ph, pw,
            ow, positions, pitch);
    }
    C10_CUDA_KERNEL_LAUNCH_CHECK();

    // Column-major GEMM:
    // [pitch, reduction_size] @ [reduction_size, outputs].
    // The weights are shared across all batch elements.
    cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle();
    const float alpha = 1.0f;
    const float beta = 0.0f;
    const auto compute_type =
        at::cuda::getCurrentDeviceProperties()->major >= 8
        ? CUBLAS_COMPUTE_32F_FAST_TF32
        : CUBLAS_COMPUTE_32F;

    const cublasStatus_t status = cublasGemmStridedBatchedEx(
        handle,
        CUBLAS_OP_N, CUBLAS_OP_N,
        pitch, outputs, reduction_size,
        &alpha,
        lowered.data_ptr<float>(), CUDA_R_32F, pitch,
        static_cast<long long>(pitch) * reduction_size,
        weight.data_ptr<float>(), CUDA_R_32F, reduction_size,
        0,
        &beta,
        products.data_ptr<float>(), CUDA_R_32F, pitch,
        static_cast<long long>(pitch) * outputs,
        batch,
        compute_type,
        CUBLAS_GEMM_DEFAULT);

    TORCH_CHECK(status == CUBLAS_STATUS_SUCCESS,
                "cublasGemmStridedBatchedEx failed: ",
                static_cast<int>(status));

    const int64_t sample_size = static_cast<int64_t>(outputs) * pitch;
    const int parts = (sample_size + CHUNK - 1) / CHUNK;
    auto partial = torch::empty({batch, parts}, x.options());

    bias_sigmoid_partial<<<dim3(parts, batch), THREADS, 0, stream>>>(
        products.data_ptr<float>(), bias.data_ptr<float>(),
        partial.data_ptr<float>(), positions, pitch, outputs, parts);
    C10_CUDA_KERNEL_LAUNCH_CHECK();

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

    return result;
}
"""

_ops = load_inline(
    name="pooled_patch_conv_sigmoid_sum_v2",
    cpp_sources=_cpp_source,
    cuda_sources=_cuda_source,
    functions=["pooled_conv_sum_cuda"],
    extra_cflags=["-O3"],
    extra_cuda_cflags=["-O3"],
    extra_ldflags=["-lcublas"],
    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)
        self.pool_size = (
            (pool_kernel_size, pool_kernel_size)
            if isinstance(pool_kernel_size, int)
            else tuple(pool_kernel_size)
        )

    def forward(self, x):
        if (
            not x.is_cuda
            or x.dtype != torch.float32
            or self.conv.weight.dtype != torch.float32
            or self.conv.bias.dtype != torch.float32
            or torch.is_autocast_enabled()
        ):
            return torch.sigmoid(self.avg_pool(self.conv(x))).sum(
                dim=(1, 2, 3)
            )

        return _ops.pooled_conv_sum_cuda(
            x.contiguous(),
            self.conv.weight.contiguous(),
            self.conv.bias.contiguous(),
            self.pool_size[0],
            self.pool_size[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.
