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):
    """
    Model that performs a 3D transposed convolution, followed by two max pooling layers and a sum operation.
    """
    def __init__(self, in_channels, out_channels, kernel_size, stride, padding):
        super(Model, self).__init__()
        self.conv_transpose = nn.ConvTranspose3d(in_channels, out_channels, kernel_size, stride=stride, padding=padding)
        self.max_pool1 = nn.MaxPool3d(kernel_size=2)
        self.max_pool2 = nn.MaxPool3d(kernel_size=3)

    def forward(self, x):
        x = self.conv_transpose(x)
        x = self.max_pool1(x)
        x = self.max_pool2(x)
        x = torch.sum(x, dim=1, keepdim=True) 
        return x

batch_size = 16
in_channels = 32
out_channels = 64
depth, height, width = 32, 32, 32
kernel_size = 5
stride = 2
padding = 2

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

def get_init_inputs():
    return [in_channels, out_channels, kernel_size, stride, padding]
    ```
    
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
from torch.utils.cpp_extension import load_inline


_cpp_source = r"""
torch::Tensor fused_pool_sum_cuda(torch::Tensor x);
"""

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

template <typename T>
__device__ __forceinline__ T nan_max(T a, T b) {
    return isnan(a) ? a : (isnan(b) ? b : (a > b ? a : b));
}

template <typename scalar_t>
__global__ void fused_pool_sum_kernel(
    const scalar_t* __restrict__ input,
    scalar_t* __restrict__ output,
    int64_t channels,
    int64_t depth,
    int64_t height,
    int64_t width,
    int64_t out_depth,
    int64_t out_height,
    int64_t out_width,
    int64_t output_count
) {
    using acc_t = at::acc_type<scalar_t, true>;
    constexpr int WARPS = 8;
    __shared__ acc_t partial[WARPS];

    const int lane = threadIdx.x & 31;
    const int warp = threadIdx.x >> 5;
    const int64_t spatial_count = out_depth * out_height * out_width;
    const int64_t channel_stride = depth * height * width;

    for (int64_t index = blockIdx.x;
         index < output_count;
         index += gridDim.x) {
        const int64_t batch = index / spatial_count;
        int64_t spatial = index % spatial_count;
        const int64_t ow = spatial % out_width;
        spatial /= out_width;
        const int64_t oh = spatial % out_height;
        const int64_t od = spatial / out_height;

        const int64_t origin =
            batch * channels * channel_stride +
            od * 6 * height * width +
            oh * 6 * width +
            ow * 6;

        acc_t channel_sum = acc_t(0);

        for (int64_t channel = warp; channel < channels; channel += WARPS) {
            const scalar_t* base = input + origin + channel * channel_stride;
            acc_t maximum = -static_cast<acc_t>(INFINITY);

            // Pooling by 2, then by 3, is a single disjoint 6x6x6 maximum.
            #pragma unroll
            for (int iteration = 0; iteration < 7; ++iteration) {
                const int position = lane + iteration * 32;
                if (position < 216) {
                    const int dz = position / 36;
                    const int dy = (position % 36) / 6;
                    const int dx = position % 6;
                    const acc_t value = static_cast<acc_t>(
                        base[dz * height * width + dy * width + dx]
                    );
                    maximum = nan_max(maximum, value);
                }
            }

            #pragma unroll
            for (int offset = 16; offset > 0; offset >>= 1) {
                maximum = nan_max(
                    maximum,
                    __shfl_down_sync(0xffffffff, maximum, offset)
                );
            }

            if (lane == 0) {
                channel_sum += maximum;
            }
        }

        if (lane == 0) {
            partial[warp] = channel_sum;
        }
        __syncthreads();

        if (threadIdx.x == 0) {
            acc_t result = acc_t(0);
            #pragma unroll
            for (int i = 0; i < WARPS; ++i) {
                result += partial[i];
            }
            output[index] = static_cast<scalar_t>(result);
        }
        __syncthreads();
    }
}

torch::Tensor fused_pool_sum_cuda(torch::Tensor x) {
    TORCH_CHECK(x.is_cuda(), "Expected a CUDA tensor");
    TORCH_CHECK(x.dim() == 5, "Expected NCDHW input");
    TORCH_CHECK(x.is_contiguous(), "Expected contiguous input");

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

    const int64_t n = x.size(0);
    const int64_t c = x.size(1);
    const int64_t d = x.size(2);
    const int64_t h = x.size(3);
    const int64_t w = x.size(4);
    const int64_t od = d / 6;
    const int64_t oh = h / 6;
    const int64_t ow = w / 6;

    TORCH_CHECK(c > 0 && od > 0 && oh > 0 && ow > 0,
                "Input is too small for the pooling operations");

    auto output = torch::empty({n, 1, od, oh, ow}, x.options());
    const int64_t count = output.numel();
    if (count == 0) {
        return output;
    }

    const int blocks = static_cast<int>(count < 65535 ? count : 65535);
    const auto stream = at::cuda::getCurrentCUDAStream();

    AT_DISPATCH_FLOATING_TYPES_AND2(
        at::ScalarType::Half,
        at::ScalarType::BFloat16,
        x.scalar_type(),
        "fused_pool_sum_cuda",
        [&] {
            fused_pool_sum_kernel<scalar_t><<<blocks, 256, 0, stream>>>(
                x.data_ptr<scalar_t>(),
                output.data_ptr<scalar_t>(),
                c, d, h, w, od, oh, ow, count
            );
        }
    );
    C10_CUDA_KERNEL_LAUNCH_CHECK();
    return output;
}
"""

_fused_ops = load_inline(
    name="fused_pool3d_2_3_channel_sum",
    cpp_sources=_cpp_source,
    cuda_sources=_cuda_source,
    functions=["fused_pool_sum_cuda"],
    extra_cflags=["-O3"],
    extra_cuda_cflags=["-O3"],
    verbose=False,
)


class ModelNew(nn.Module):
    def __init__(self, in_channels, out_channels, kernel_size, stride, padding):
        super().__init__()
        self.conv_transpose = nn.ConvTranspose3d(
            in_channels,
            out_channels,
            kernel_size,
            stride=stride,
            padding=padding,
        )
        self.max_pool1 = nn.MaxPool3d(kernel_size=2)
        self.max_pool2 = nn.MaxPool3d(kernel_size=3)

    def forward(self, x):
        x = self.conv_transpose(x)
        if not x.is_cuda or (torch.is_grad_enabled() and x.requires_grad):
            return self.max_pool2(self.max_pool1(x)).sum(dim=1, keepdim=True)
        return _fused_ops.fused_pool_sum_cuda(x.contiguous())
```
Result of evaluating it:
The solution is correct on the test inputs. Mean runtime 14.6 ms; the PyTorch reference (with TF32 enabled) takes 14.6 ms; speedup 1.000x.
Profiler, top device kernels of one forward pass of your solution:
| device kernel | total device time (us) | calls |
|---|---|---|
| sm80_xmma_dgrad_implicit_gemm_indexed_tf32f32_tf32f32_f32_nhwckrsc_nhwc_tilesize64x64x64_s | 9790.5 | 1 |
| void cudnn::engines_precompiled::nhwcToNchwKernel<float, float, float, true, false, (cudnn | 1596.1 | 1 |
| void at::native::elementwise_kernel<128, 2, at::native::gpu_kernel_impl_nocast<at::native: | 1525.0 | 1 |
| void at::native::(anonymous namespace)::max_pool3d_with_indices_single_out_frame<float>(fl | 1461.8 | 2 |
| void xmma__5x_cudnn::implicit_gemm::strided_dgrad_indexed::kernel_helper_stage_3<xmma__5x_ | 156.9 | 1 |
| void cudnn::engines_precompiled::nchwToNhwcKernel<float, float, float, false, true, (cudnn | 108.5 | 2 |
| void at::native::reduce_kernel<128, 4, at::native::ReduceOp<float, at::native::func_wrappe | 10.4 | 1 |
| void xmma__5x_cudnn::implicit_gemm::strided_dgrad_indexed::kernel_helper_stage_2<xmma__5x_ | 9.2 | 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.
