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 2 of 6 for this task. Your previous solution (turn 1) was:
```python
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.cpp_extension import load_inline


_cpp_source = r"""
#include <torch/extension.h>

torch::Tensor expand_pool_weights(
    torch::Tensor weight, int64_t pool_h, int64_t pool_w);
torch::Tensor sigmoid_sum_cuda(torch::Tensor input);
"""

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

__global__ void expand_weights_kernel(
    const float* __restrict__ weight,
    float* __restrict__ expanded,
    int64_t count,
    int kh, int kw, int ph, int pw,
    int eh, int ew)
{
    for (int64_t idx = int64_t(blockIdx.x) * blockDim.x + threadIdx.x;
         idx < count;
         idx += int64_t(blockDim.x) * gridDim.x)
    {
        const int col = idx % ew;
        const int row = (idx / ew) % eh;
        const int64_t channel_pair = idx / (int64_t(eh) * ew);
        const float* src = weight + channel_pair * kh * kw;

        const int r0 = max(0, row - ph + 1);
        const int r1 = min(kh - 1, row);
        const int c0 = max(0, col - pw + 1);
        const int c1 = min(kw - 1, col);

        float value = 0.0f;
        for (int r = r0; r <= r1; ++r)
            for (int c = c0; c <= c1; ++c)
                value += src[r * kw + c];

        expanded[idx] = value / float(ph * pw);
    }
}

__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 warp_sums[8];
    const int lane = threadIdx.x & 31;
    const int warp = threadIdx.x >> 5;

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

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

constexpr int REDUCTION_CHUNK = 4096;

__global__ void sigmoid_partial_kernel(
    const float* __restrict__ input,
    float* __restrict__ partial,
    int64_t sample_size,
    int parts)
{
    const int batch = blockIdx.y;
    const int part = blockIdx.x;
    const int64_t begin = int64_t(part) * REDUCTION_CHUNK;
    const int64_t end =
        min(begin + int64_t(REDUCTION_CHUNK), sample_size);
    const float* src = input + int64_t(batch) * sample_size;

    float total = 0.0f;
    for (int64_t i = begin + threadIdx.x; i < end; i += blockDim.x) {
        const float value = src[i];
        total += 1.0f / (1.0f + expf(-value));
    }

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

__global__ void finish_sum_kernel(
    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[int64_t(batch) * parts + i];

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

torch::Tensor expand_pool_weights(
    torch::Tensor weight, int64_t pool_h, int64_t pool_w)
{
    TORCH_CHECK(weight.is_cuda() && weight.scalar_type() == at::kFloat,
                "Expected CUDA float32 weights");
    TORCH_CHECK(weight.dim() == 4 && weight.is_contiguous(),
                "Expected contiguous OIHW weights");
    TORCH_CHECK(pool_h > 0 && pool_w > 0, "Invalid pooling size");

    const c10::cuda::CUDAGuard guard(weight.device());
    const int kh = weight.size(2);
    const int kw = weight.size(3);
    const int eh = kh + pool_h - 1;
    const int ew = kw + pool_w - 1;

    auto expanded = torch::empty(
        {weight.size(0), weight.size(1), eh, ew}, weight.options());
    const int64_t count = expanded.numel();
    const int blocks =
        static_cast<int>(std::min<int64_t>((count + 255) / 256, 65535));

    expand_weights_kernel<<<
        blocks, 256, 0, at::cuda::getCurrentCUDAStream()
    >>>(
        weight.data_ptr<float>(), expanded.data_ptr<float>(), count,
        kh, kw, pool_h, pool_w, eh, ew);
    C10_CUDA_KERNEL_LAUNCH_CHECK();
    return expanded;
}

torch::Tensor sigmoid_sum_cuda(torch::Tensor input)
{
    TORCH_CHECK(input.is_cuda() && input.scalar_type() == at::kFloat,
                "Expected CUDA float32 input");
    TORCH_CHECK(input.dim() == 4 && input.is_contiguous(),
                "Expected contiguous NCHW input");

    const c10::cuda::CUDAGuard guard(input.device());
    const int64_t batch = input.size(0);
    auto output = torch::empty({batch}, input.options());
    if (batch == 0)
        return output;

    const int64_t sample_size =
        input.size(1) * input.size(2) * input.size(3);
    const int parts =
        static_cast<int>((sample_size + REDUCTION_CHUNK - 1) /
                         REDUCTION_CHUNK);
    auto partial = torch::empty({batch, parts}, input.options());
    auto stream = at::cuda::getCurrentCUDAStream();

    sigmoid_partial_kernel<<<dim3(parts, batch), 256, 0, stream>>>(
        input.data_ptr<float>(), partial.data_ptr<float>(),
        sample_size, parts);
    C10_CUDA_KERNEL_LAUNCH_CHECK();

    finish_sum_kernel<<<batch, 256, 0, stream>>>(
        partial.data_ptr<float>(), output.data_ptr<float>(), parts);
    C10_CUDA_KERNEL_LAUNCH_CHECK();
    return output;
}
"""

_ops = load_inline(
    name="conv_avgpool_sigmoid_sum_fused_v1",
    cpp_sources=_cpp_source,
    cuda_sources=_cuda_source,
    functions=["expand_pool_weights", "sigmoid_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)

        if isinstance(pool_kernel_size, int):
            self.pool_size = (pool_kernel_size, pool_kernel_size)
        else:
            self.pool_size = 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 torch.is_autocast_enabled()
        ):
            x = self.avg_pool(self.conv(x))
            return torch.sigmoid(x).sum(dim=(1, 2, 3))

        # Average pooling after convolution is equivalent to a strided
        # convolution whose weights incorporate the pooling box filter.
        weight = _ops.expand_pool_weights(
            self.conv.weight.contiguous(), *self.pool_size
        )
        pooled = F.conv2d(
            x,
            weight,
            self.conv.bias,
            stride=self.pool_size,
        )
        return _ops.sigmoid_sum_cuda(pooled.contiguous())
```
Result of evaluating it:
The solution is correct on the test inputs. Mean runtime 3.93 ms; the PyTorch reference (with TF32 enabled) takes 36.9 ms; speedup 9.389x.
Profiler, top device kernels of one forward pass of your solution:
| device kernel | total device time (us) | calls |
|---|---|---|
| sm80_xmma_fprop_implicit_gemm_indexed_wo_smem_tf32f32_tf32f32_f32_nhwckrsc_nhwc_tilesize12 | 1428.4 | 1 |
| void cudnn::engines_precompiled::nchwToNhwcKernel<float, float, float, false, true, (cudnn | 1315.6 | 2 |
| void at::native::elementwise_kernel<128, 2, at::native::gpu_kernel_impl_nocast<at::native: | 443.1 | 1 |
| void cudnn::engines_precompiled::nhwcToNchwKernel<float, float, float, true, false, (cudnn | 427.0 | 1 |
| sigmoid_partial_kernel(float const*, float*, long, int) | 300.0 | 1 |
| expand_weights_kernel(float const*, float*, long, int, int, int, int, int, int) | 3.9 | 1 |
| finish_sum_kernel(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.
