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):
    """
    A model that performs a sequence of operations:
        - ConvTranspose3d
        - MaxPool3d
        - Softmax
        - Subtract
        - Swish
        - Max
    """
    def __init__(self, in_channels, out_channels, kernel_size, stride, padding, output_padding, pool_kernel_size, pool_stride, pool_padding):
        super(Model, self).__init__()
        self.conv_transpose = nn.ConvTranspose3d(in_channels, out_channels, kernel_size, stride=stride, padding=padding, output_padding=output_padding)
        self.max_pool = nn.MaxPool3d(kernel_size=pool_kernel_size, stride=pool_stride, padding=pool_padding)
        self.subtract = nn.Parameter(torch.randn(out_channels)) # Assuming subtraction is element-wise across channels

    def forward(self, x):
        x = self.conv_transpose(x)
        x = self.max_pool(x)
        x = torch.softmax(x, dim=1) # Apply softmax across channels (dim=1)
        x = x - self.subtract.view(1, -1, 1, 1, 1) # Subtract across channels
        x = torch.sigmoid(x) * x # Swish activation
        x = torch.max(x, dim=1)[0] # Max pooling across channels
        return x

batch_size = 128
in_channels = 3
out_channels = 16
depth, height, width = 16, 32, 32
kernel_size = 3
stride = 2
padding = 1
output_padding = 1
pool_kernel_size = 2
pool_stride = 2
pool_padding = 0

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, output_padding, pool_kernel_size, pool_stride, pool_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 4 of 6 for this task. Your previous solution (turn 3) was:
```python
# 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


cuda_source = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda_runtime.h>

#define IC 3
#define OC 16
#define OC4 4
#define K3 27
#define W4_SIZE (K3 * IC * OC4)
#define W_SIZE (K3 * IC * OC)

__device__ __forceinline__ float fast_swish(float v) {
    return __fdividef(v, 1.0f + __expf(-v));
}

// Fused kernel for the target configuration:
//   ConvTranspose3d(ic=3, oc=16, k=3, s=2, p=1, op=1) -> MaxPool3d(2,2,0)
//   -> softmax(dim=1) -> subtract per-channel -> Swish -> max(dim=1)
//
// Each thread produces two adjacent output voxels along W (pooled positions
// ow and ow+1).  Because the transposed-convolution taps for both positions
// use the same kernel weights, every shared-memory weight load is reused for
// two outputs, halving shared-memory and issue pressure per FMA.
__global__ void __launch_bounds__(256) fused_convt_pool_softmax_sub_swish_max_kernel(
    const float* __restrict__ x,
    const float* __restrict__ w,
    const float* __restrict__ bias,
    const float* __restrict__ sub,
    float* __restrict__ out,
    int N, int Din, int Hin, int Win, int hin_tiles)
{
    // Weights are transposed on the fly from the PyTorch ConvTranspose3d layout
    // [ic][oc][kd][kh][kw] into [k][ic][oc], which permits float4 loads over oc.
    __shared__ float4 sw[W4_SIZE];
    __shared__ float4 sb[OC4];
    __shared__ float4 ss[OC4];

    float* sw_scalar = reinterpret_cast<float*>(sw);
    float* sb_scalar = reinterpret_cast<float*>(sb);
    float* ss_scalar = reinterpret_cast<float*>(ss);

    for (int i = threadIdx.y * blockDim.x + threadIdx.x; i < W_SIZE; i += blockDim.x * blockDim.y) {
        int ic = i / (OC * K3);
        int rem = i - ic * (OC * K3);
        int oc = rem / K3;
        int koff = rem - oc * K3;
        int dst = (koff * IC + ic) * OC + oc;
        sw_scalar[dst] = __ldg(w + i);
    }

    int tid = threadIdx.y * blockDim.x + threadIdx.x;
    if (tid < OC) {
        sb_scalar[tid] = __ldg(bias + tid);
        ss_scalar[tid] = __ldg(sub + tid);
    }
    __syncthreads();

    // 3D grid removes all integer divisions from the per-thread index math.
    int n  = blockIdx.z;
    int od = blockIdx.y / hin_tiles;
    int oh = (blockIdx.y - od * hin_tiles) * 16 + threadIdx.y;
    int ow = (blockIdx.x * 16 + threadIdx.x) * 2;
    if (oh >= Hin || ow >= Win) return;

    long spatial = (long)Din * Hin * Win;
    const float* xn = x + (long)n * IC * spatial;

    // Pooled outputs (od,oh,ow) and (od,oh,ow+1) only depend on the input
    // neighborhood d in [od,od+1], h in [oh,oh+1], w in [ow,ow+2].
    bool vd1 = (od + 1) < Din;
    bool vh1 = (oh + 1) < Hin;
    bool vw1 = (ow + 1) < Win;
    bool vw2 = (ow + 2) < Win;

    float xl[2 * 2 * 3 * IC];  // [ad][ah][aw][ic]

    #pragma unroll
    for (int ad = 0; ad < 2; ++ad) {
        bool okd = (ad == 0) || vd1;
        int xd = okd ? (od + ad) : od;
        #pragma unroll
        for (int ah = 0; ah < 2; ++ah) {
            bool okh = (ah == 0) || vh1;
            int xh = okh ? (oh + ah) : oh;
            #pragma unroll
            for (int aw = 0; aw < 3; ++aw) {
                bool okw = (aw == 0) || ((aw == 1) ? vw1 : vw2);
                int xw = okw ? (ow + aw) : ow;
                bool valid = okd && okh && okw;
                long off = ((long)xd * Hin + xh) * Win + xw;
                const float* xp = xn + off;
                #pragma unroll
                for (int ic = 0; ic < IC; ++ic) {
                    float v = __ldg(xp + (long)ic * spatial);
                    xl[((ad * 2 + ah) * 3 + aw) * IC + ic] = valid ? v : 0.0f;
                }
            }
        }
    }

    float4 pooled0[OC4];
    float4 pooled1[OC4];
    int phase = 0;

    #pragma unroll
    for (int i = 0; i < 2; ++i) {
        #pragma unroll
        for (int j = 0; j < 2; ++j) {
            #pragma unroll
            for (int k = 0; k < 2; ++k) {
                float4 acc0[OC4];
                float4 acc1[OC4];

                // First tap (ad=ah=aw=0, ic=0) initializes the accumulators
                // with multiplies, avoiding explicit zeroing.
                {
                    int kd = (i == 0) ? 1 : 2;
                    int kh = (j == 0) ? 1 : 2;
                    int kw = (k == 0) ? 1 : 2;
                    int koff = kd * 9 + kh * 3 + kw;
                    float x00 = xl[0 * IC + 0];
                    float x10 = xl[1 * IC + 0];
                    const float4* wp = sw + (koff * IC) * OC4;
                    #pragma unroll
                    for (int g = 0; g < OC4; ++g) {
                        float4 wv = wp[g];
                        acc0[g] = make_float4(x00 * wv.x, x00 * wv.y, x00 * wv.z, x00 * wv.w);
                        acc1[g] = make_float4(x10 * wv.x, x10 * wv.y, x10 * wv.z, x10 * wv.w);
                    }
                }

                #pragma unroll
                for (int ad = 0; ad < 2; ++ad) {
                    if (i == 0 && ad > 0) continue;
                    int kd = (i == 0) ? 1 : (2 - 2 * ad);

                    #pragma unroll
                    for (int ah = 0; ah < 2; ++ah) {
                        if (j == 0 && ah > 0) continue;
                        int kh = (j == 0) ? 1 : (2 - 2 * ah);

                        #pragma unroll
                        for (int aw = 0; aw < 2; ++aw) {
                            if (k == 0 && aw > 0) continue;
                            int kw = (k == 0) ? 1 : (2 - 2 * aw);
                            int koff = kd * 9 + kh * 3 + kw;
                            int xbase = ((ad * 2 + ah) * 3 + aw) * IC;

                            #pragma unroll
                            for (int ic = 0; ic < IC; ++ic) {
                                if (ad == 0 && ah == 0 && aw == 0 && ic == 0) continue;
                                float x0v = xl[xbase + ic];
                                float x1v = xl[xbase + IC + ic];
                                const float4* wp = sw + (koff * IC + ic) * OC4;

                                #pragma unroll
                                for (int g = 0; g < OC4; ++g) {
                                    float4 wv = wp[g];
                                    acc0[g].x = fmaf(x0v, wv.x, acc0[g].x);
                                    acc0[g].y = fmaf(x0v, wv.y, acc0[g].y);
                                    acc0[g].z = fmaf(x0v, wv.z, acc0[g].z);
                                    acc0[g].w = fmaf(x0v, wv.w, acc0[g].w);
                                    acc1[g].x = fmaf(x1v, wv.x, acc1[g].x);
                                    acc1[g].y = fmaf(x1v, wv.y, acc1[g].y);
                                    acc1[g].z = fmaf(x1v, wv.z, acc1[g].z);
                                    acc1[g].w = fmaf(x1v, wv.w, acc1[g].w);
                                }
                            }
                        }
                    }
                }

                // Bias is constant across pool phases, so it is added after
                // the running max instead of inside every phase.
                if (phase == 0) {
                    #pragma unroll
                    for (int g = 0; g < OC4; ++g) {
                        pooled0[g] = acc0[g];
                        pooled1[g] = acc1[g];
                    }
                } else {
                    #pragma unroll
                    for (int g = 0; g < OC4; ++g) {
                        pooled0[g].x = fmaxf(pooled0[g].x, acc0[g].x);
                        pooled0[g].y = fmaxf(pooled0[g].y, acc0[g].y);
                        pooled0[g].z = fmaxf(pooled0[g].z, acc0[g].z);
                        pooled0[g].w = fmaxf(pooled0[g].w, acc0[g].w);
                        pooled1[g].x = fmaxf(pooled1[g].x, acc1[g].x);
                        pooled1[g].y = fmaxf(pooled1[g].y, acc1[g].y);
                        pooled1[g].z = fmaxf(pooled1[g].z, acc1[g].z);
                        pooled1[g].w = fmaxf(pooled1[g].w, acc1[g].w);
                    }
                }
                ++phase;
            }
        }
    }

    // Add the per-channel bias (hoisted out of the pool-phase loop).
    float4 p0[OC4];
    float4 p1[OC4];
    #pragma unroll
    for (int g = 0; g < OC4; ++g) {
        float4 b = sb[g];
        p0[g].x = pooled0[g].x + b.x;
        p0[g].y = pooled0[g].y + b.y;
        p0[g].z = pooled0[g].z + b.z;
        p0[g].w = pooled0[g].w + b.w;
        p1[g].x = pooled1[g].x + b.x;
        p1[g].y = pooled1[g].y + b.y;
        p1[g].z = pooled1[g].z + b.z;
        p1[g].w = pooled1[g].w + b.w;
    }

    // Stable softmax across the 16 channels for both outputs.
    float mx0 = p0[0].x, mx1 = p1[0].x;
    #pragma unroll
    for (int g = 0; g < OC4; ++g) {
        if (g > 0) {
            mx0 = fmaxf(mx0, p0[g].x);
            mx1 = fmaxf(mx1, p1[g].x);
        }
        mx0 = fmaxf(mx0, p0[g].y);  mx1 = fmaxf(mx1, p1[g].y);
        mx0 = fmaxf(mx0, p0[g].z);  mx1 = fmaxf(mx1, p1[g].z);
        mx0 = fmaxf(mx0, p0[g].w);  mx1 = fmaxf(mx1, p1[g].w);
    }

    #pragma unroll
    for (int g = 0; g < OC4; ++g) {
        p0[g].x = __expf(p0[g].x - mx0);
        p0[g].y = __expf(p0[g].y - mx0);
        p0[g].z = __expf(p0[g].z - mx0);
        p0[g].w = __expf(p0[g].w - mx0);
        p1[g].x = __expf(p1[g].x - mx1);
        p1[g].y = __expf(p1[g].y - mx1);
        p1[g].z = __expf(p1[g].z - mx1);
        p1[g].w = __expf(p1[g].w - mx1);
    }

    float sum0 = 0.0f, sum1 = 0.0f;
    #pragma unroll
    for (int g = 0; g < OC4; ++g) {
        sum0 += p0[g].x;  sum1 += p1[g].x;
        sum0 += p0[g].y;  sum1 += p1[g].y;
        sum0 += p0[g].z;  sum1 += p1[g].z;
        sum0 += p0[g].w;  sum1 += p1[g].w;
    }
    float inv0 = __fdividef(1.0f, sum0);
    float inv1 = __fdividef(1.0f, sum1);

    // Subtract, Swish, then max across channels.
    float res0 = -INFINITY, res1 = -INFINITY;
    #pragma unroll
    for (int g = 0; g < OC4; ++g) {
        float4 s = ss[g];
        float v;
        v = p0[g].x * inv0 - s.x;
        res0 = fmaxf(res0, fast_swish(v));
        v = p1[g].x * inv1 - s.x;
        res1 = fmaxf(res1, fast_swish(v));
        v = p0[g].y * inv0 - s.y;
        res0 = fmaxf(res0, fast_swish(v));
        v = p1[g].y * inv1 - s.y;
        res1 = fmaxf(res1, fast_swish(v));
        v = p0[g].z * inv0 - s.z;
        res0 = fmaxf(res0, fast_swish(v));
        v = p1[g].z * inv1 - s.z;
        res1 = fmaxf(res1, fast_swish(v));
        v = p0[g].w * inv0 - s.w;
        res0 = fmaxf(res0, fast_swish(v));
        v = p1[g].w * inv1 - s.w;
        res1 = fmaxf(res1, fast_swish(v));
    }

    // Adjacent even/odd W offsets guarantee 8-byte alignment for float2.
    long base = (((long)n * Din + od) * Hin + oh) * Win + ow;
    float2 r = make_float2(res0, res1);
    *reinterpret_cast<float2*>(out + base) = r;
}

torch::Tensor fused_forward(torch::Tensor x, torch::Tensor w, torch::Tensor bias, torch::Tensor sub) {
    TORCH_CHECK(x.is_cuda() && w.is_cuda() && bias.is_cuda() && sub.is_cuda(), "All inputs must be CUDA tensors.");
    TORCH_CHECK(x.scalar_type() == at::kFloat, "x must be float32.");
    TORCH_CHECK(w.scalar_type() == at::kFloat, "weight must be float32.");
    TORCH_CHECK(bias.scalar_type() == at::kFloat, "bias must be float32.");
    TORCH_CHECK(sub.scalar_type() == at::kFloat, "subtract must be float32.");
    TORCH_CHECK(x.size(4) % 2 == 0, "input width must be even for the fused kernel.");

    auto xc = x.contiguous();
    auto wc = w.contiguous();
    auto bc = bias.contiguous();
    auto sc = sub.contiguous();

    int N = (int)xc.size(0);
    int Din = (int)xc.size(2);
    int Hin = (int)xc.size(3);
    int Win = (int)xc.size(4);

    auto out = torch::empty({N, Din, Hin, Win}, xc.options());
    long total = (long)N * Din * Hin * Win;
    if (total == 0) return out;

    int hin_tiles = (Hin + 15) / 16;
    int w_tiles = ((Win / 2) + 15) / 16;
    dim3 block(16, 16, 1);
    dim3 grid(w_tiles, Din * hin_tiles, N);
    auto stream = at::cuda::getCurrentCUDAStream();

    fused_convt_pool_softmax_sub_swish_max_kernel<<<grid, block, 0, stream>>>(
        xc.data_ptr<float>(),
        wc.data_ptr<float>(),
        bc.data_ptr<float>(),
        sc.data_ptr<float>(),
        out.data_ptr<float>(),
        N, Din, Hin, Win, hin_tiles
    );

    return out;
}
"""

cpp_source = "torch::Tensor fused_forward(torch::Tensor x, torch::Tensor w, torch::Tensor bias, torch::Tensor sub);"

fused_op = load_inline(
    name="fused_convt_pool_softmax_sub_swish_max_v3",
    cpp_sources=cpp_source,
    cuda_sources=cuda_source,
    functions=["fused_forward"],
    verbose=False,
    extra_cuda_cflags=["-O3"],
)


class ModelNew(nn.Module):
    """
    Optimized Model with ConvTranspose3d, MaxPool3d, channel softmax,
    subtraction, Swish, and channel max fused into one CUDA kernel for the
    target configuration. Other configurations use the eager PyTorch path.
    """
    def __init__(self, in_channels, out_channels, kernel_size, stride, padding, output_padding, pool_kernel_size, pool_stride, pool_padding):
        super(ModelNew, self).__init__()
        self.conv_transpose = nn.ConvTranspose3d(
            in_channels,
            out_channels,
            kernel_size,
            stride=stride,
            padding=padding,
            output_padding=output_padding,
        )
        self.subtract = nn.Parameter(torch.randn(out_channels))

        self.pool_kernel_size = pool_kernel_size
        self.pool_stride = pool_stride
        self.pool_padding = pool_padding

        self._use_fused = (
            in_channels == 3
            and out_channels == 16
            and kernel_size == 3
            and stride == 2
            and padding == 1
            and output_padding == 1
            and pool_kernel_size == 2
            and pool_stride == 2
            and pool_padding == 0
        )
        self._fused_forward = fused_op.fused_forward

    def forward(self, x):
        if (
            self._use_fused
            and x.is_cuda
            and x.dtype == torch.float32
            and x.size(4) % 2 == 0
            and self.conv_transpose.bias is not None
        ):
            return self._fused_forward(
                x,
                self.conv_transpose.weight,
                self.conv_transpose.bias,
                self.subtract,
            )

        x = self.conv_transpose(x)
        x = F.max_pool3d(
            x,
            kernel_size=self.pool_kernel_size,
            stride=self.pool_stride,
            padding=self.pool_padding,
        )
        x = torch.softmax(x, dim=1)
        x = x - self.subtract.view(1, -1, 1, 1, 1)
        x = torch.sigmoid(x) * x
        x = torch.max(x, dim=1)[0]
        return x
```
Result of evaluating it:
The solution is correct on the test inputs. Mean runtime 0.418 ms; the PyTorch reference (with TF32 enabled) takes 19.6 ms; speedup 46.890x.
Profiler, top device kernels of one forward pass of your solution:
| device kernel | total device time (us) | calls |
|---|---|---|
| fused_convt_pool_softmax_sub_swish_max_kernel(float const*, float const*, float const*, fl | 391.0 | 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.
