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 3 of 6 for this task. Your previous solution (turn 2) 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"""
torch::Tensor pool6_bias_sum_cuda(torch::Tensor x, torch::Tensor bias);
"""

_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_runtime.h>
#include <cmath>
#include <cstdint>

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

template <typename scalar_t>
__global__ void pool6_bias_sum_kernel(
    const scalar_t* __restrict__ x,
    const scalar_t* __restrict__ bias,
    scalar_t* __restrict__ out,
    int channels,
    int od, int oh, int ow,
    int64_t sn, int64_t sc,
    int64_t sd, int64_t sh, int64_t sw
) {
    using acc_t = at::acc_type<scalar_t, true>;
    __shared__ acc_t maxima[4][64];
    __shared__ acc_t sums[2];

    const int tid = threadIdx.x;
    const int channel_lane = tid & 63;
    const int group = tid >> 6;
    const int index = blockIdx.x;
    const int spatial_size = od * oh * ow;

    const int n = index / spatial_size;
    int spatial = index % spatial_size;
    const int w = spatial % ow;
    spatial /= ow;
    const int h = spatial % oh;
    const int d = spatial / oh;

    const int64_t origin =
        int64_t(n) * sn + int64_t(d * 6) * sd +
        int64_t(h * 6) * sh + int64_t(w * 6) * sw;

    acc_t channel_sum = acc_t(0);

    for (int first_channel = 0; first_channel < channels;
         first_channel += 64) {
        const int channel = first_channel + channel_lane;
        acc_t value = -static_cast<acc_t>(INFINITY);

        if (channel < channels) {
            const scalar_t* base = x + origin + int64_t(channel) * sc;

            #pragma unroll
            for (int p = group; p < 216; p += 4) {
                const int dz = p / 36;
                const int dy = (p % 36) / 6;
                const int dx = p % 6;
                value = maximum_nan(
                    value,
                    static_cast<acc_t>(
                        base[int64_t(dz) * sd +
                             int64_t(dy) * sh + int64_t(dx) * sw]
                    )
                );
            }
        }

        maxima[group][channel_lane] = value;
        __syncthreads();

        if (group == 0 && channel < channels) {
            acc_t pooled = maximum_nan(
                maximum_nan(maxima[0][channel_lane],
                            maxima[1][channel_lane]),
                maximum_nan(maxima[2][channel_lane],
                            maxima[3][channel_lane])
            );

            // Match the convolution output's dtype before channel reduction.
            scalar_t biased = static_cast<scalar_t>(
                pooled + static_cast<acc_t>(bias[channel])
            );
            channel_sum += static_cast<acc_t>(biased);
        }
        __syncthreads();
    }

    if (tid < 64) {
        #pragma unroll
        for (int offset = 16; offset > 0; offset >>= 1) {
            channel_sum += __shfl_down_sync(
                0xffffffff, channel_sum, offset
            );
        }
        if ((tid & 31) == 0) {
            sums[tid >> 5] = channel_sum;
        }
    }
    __syncthreads();

    if (tid == 0) {
        out[index] = static_cast<scalar_t>(sums[0] + sums[1]);
    }
}

torch::Tensor pool6_bias_sum_cuda(torch::Tensor x, torch::Tensor bias) {
    TORCH_CHECK(x.is_cuda() && bias.is_cuda(), "Expected CUDA tensors");
    TORCH_CHECK(x.dim() == 5, "Expected a five-dimensional tensor");
    TORCH_CHECK(x.device() == bias.device(), "Device mismatch");

    const c10::cuda::CUDAGuard guard(x.device());
    const int64_t n = x.size(0);
    const int c = static_cast<int>(x.size(1));
    const int od = static_cast<int>(x.size(2) / 6);
    const int oh = static_cast<int>(x.size(3) / 6);
    const int ow = static_cast<int>(x.size(4) / 6);

    TORCH_CHECK(c > 0 && od > 0 && oh > 0 && ow > 0,
                "Input is too small for pooling");
    TORCH_CHECK(bias.numel() == c, "Invalid bias size");

    bias = bias.to(x.scalar_type()).contiguous();
    auto output = torch::empty({n, 1, od, oh, ow}, x.options());
    if (output.numel() == 0) {
        return output;
    }

    const auto stream = at::cuda::getCurrentCUDAStream();

    AT_DISPATCH_FLOATING_TYPES_AND2(
        at::ScalarType::Half,
        at::ScalarType::BFloat16,
        x.scalar_type(),
        "pool6_bias_sum_cuda",
        [&] {
            pool6_bias_sum_kernel<scalar_t>
                <<<static_cast<unsigned int>(output.numel()), 256, 0, stream>>>(
                    x.data_ptr<scalar_t>(),
                    bias.data_ptr<scalar_t>(),
                    output.data_ptr<scalar_t>(),
                    c, od, oh, ow,
                    x.stride(0), x.stride(1), x.stride(2),
                    x.stride(3), x.stride(4)
                );
        }
    );
    C10_CUDA_KERNEL_LAUNCH_CHECK();
    return output;
}
"""

_fused_ops = load_inline(
    name="pool6_bias_sum_channels_last_v2",
    cpp_sources=_cpp_source,
    cuda_sources=_cuda_source,
    functions=["pool6_bias_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,
        ).to(memory_format=torch.channels_last_3d)

        self.max_pool1 = nn.MaxPool3d(kernel_size=2)
        self.max_pool2 = nn.MaxPool3d(kernel_size=3)

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

        conv = self.conv_transpose
        x = x.contiguous(memory_format=torch.channels_last_3d)
        weight = conv.weight.contiguous(memory_format=torch.channels_last_3d)

        x = F.conv_transpose3d(
            x,
            weight,
            bias=None,
            stride=conv.stride,
            padding=conv.padding,
            output_padding=conv.output_padding,
            groups=conv.groups,
            dilation=conv.dilation,
        )
        return _fused_ops.pool6_bias_sum_cuda(x, conv.bias)
```
Result of evaluating it:
The solution is correct on the test inputs. Mean runtime 11.3 ms; the PyTorch reference (with TF32 enabled) takes 14.6 ms; speedup 1.292x.
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 | 9780.1 | 1 |
| void pool6_bias_sum_kernel<float>(float const*, float const*, float*, int, int, int, int,  | 1198.0 | 1 |
| void xmma__5x_cudnn::implicit_gemm::strided_dgrad_indexed::kernel_helper_stage_3<xmma__5x_ | 156.5 | 1 |
| void at::native::elementwise_kernel<128, 2, at::native::gpu_kernel_impl_nocast<at::native: | 126.0 | 1 |
| void cudnn::engines_precompiled::convertTensor_kernel<float, float, float, (cudnnKernelDat | 110.9 | 2 |
| void xmma__5x_cudnn::implicit_gemm::strided_dgrad_indexed::kernel_helper_stage_2<xmma__5x_ | 10.2 | 1 |
| void xmma__5x_cudnn::implicit_gemm::strided_dgrad_indexed::kernel_helper_stage_1<xmma__5x_ | 4.4 | 1 |
| void xmma__5x_cudnn::implicit_gemm::strided_dgrad_indexed::kernel_helper_stage_0<xmma__5x_ | 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.
