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):
    """
    Simple model that performs a 3D convolution, applies minimum operation along a specific dimension, 
    and then applies softmax.
    """
    def __init__(self, in_channels, out_channels, kernel_size, dim):
        super(Model, self).__init__()
        self.conv = nn.Conv3d(in_channels, out_channels, kernel_size)
        self.dim = dim

    def forward(self, x):
        """
        Args:
            x (torch.Tensor): Input tensor of shape (batch_size, in_channels, D, H, W)
        Returns:
            torch.Tensor: Output tensor of shape (batch_size, out_channels, H, W)
        """
        x = self.conv(x)
        x = torch.min(x, dim=self.dim)[0]  # Apply minimum along the specified dimension
        x = torch.softmax(x, dim=1)  # Apply softmax along the channel dimension
        return x

batch_size = 128
in_channels = 3
out_channels = 24  # Increased output channels
D, H, W = 24, 32, 32  # Increased depth
kernel_size = 3
dim = 2  # Dimension along which to apply minimum operation (e.g., depth)

def get_inputs():
    return [torch.rand(batch_size, in_channels, D, H, W)]

def get_init_inputs():
    return [in_channels, out_channels, kernel_size, dim]
    ```
    
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
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 depth_min_bias_softmax_cuda(
    torch::Tensor x, 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 <math_constants.h>

template<int STATIC_DEPTH>
__global__ void depth_min_bias_softmax_kernel(
    const float* __restrict__ x,
    const float* __restrict__ bias,
    float* __restrict__ output,
    int spatial,
    int dynamic_depth)
{
    constexpr int CHANNELS = 24;
    constexpr int WARPS = 8;

    const int lane = threadIdx.x & 31;
    const int warp = threadIdx.x >> 5;
    const int position = blockIdx.x * WARPS + warp;
    const int batch = blockIdx.y;
    const int depth = STATIC_DEPTH ? STATIC_DEPTH : dynamic_depth;

    if (position >= spatial) {
        return;
    }

    float minimum = CUDART_INF_F;
    if (lane < CHANNELS) {
        const int64_t base =
            (int64_t(batch) * depth * spatial + position) * CHANNELS + lane;
        const int64_t depth_stride = int64_t(spatial) * CHANNELS;

        #pragma unroll
        for (int d = 0; d < (STATIC_DEPTH ? STATIC_DEPTH : dynamic_depth); ++d) {
            const float value = x[base + int64_t(d) * depth_stride];
            minimum = (isnan(value) || value < minimum) ? value : minimum;
        }
        minimum += bias[lane];
    }

    const float value = lane < CHANNELS ? minimum : -CUDART_INF_F;
    float maximum = value;

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

    const float exponential =
        lane < CHANNELS ? __expf(value - maximum) : 0.0f;
    float denominator = exponential;

    #pragma unroll
    for (int offset = 16; offset > 0; offset >>= 1) {
        denominator +=
            __shfl_xor_sync(0xffffffff, denominator, offset);
    }

    if (lane < CHANNELS) {
        const int64_t index =
            (int64_t(batch) * spatial + position) * CHANNELS + lane;
        output[index] = exponential / denominator;
    }
}

torch::Tensor depth_min_bias_softmax_cuda(
    torch::Tensor x, torch::Tensor bias)
{
    TORCH_CHECK(x.is_cuda() && bias.is_cuda(), "Expected CUDA tensors");
    TORCH_CHECK(
        x.scalar_type() == at::kFloat && bias.scalar_type() == at::kFloat,
        "Expected float32 tensors");
    TORCH_CHECK(
        x.dim() == 5 && x.size(1) == 24 && x.size(2) > 0,
        "Expected shape (N, 24, D, H, W)");
    TORCH_CHECK(
        x.is_contiguous(at::MemoryFormat::ChannelsLast3d),
        "Expected channels-last 3D storage");
    TORCH_CHECK(
        bias.numel() == 24 && bias.is_contiguous() &&
        bias.device() == x.device(),
        "Invalid bias");
    TORCH_CHECK(x.size(0) <= 65535, "Batch size exceeds launch limit");

    const c10::cuda::CUDAGuard guard(x.device());
    const int64_t spatial64 = x.size(3) * x.size(4);
    TORCH_CHECK(
        spatial64 <= 2147483640LL && x.size(2) <= 2147483647LL,
        "Tensor dimensions are too large");

    auto storage = torch::empty(
        {x.size(0), x.size(3), x.size(4), x.size(1)}, x.options());
    auto output = storage.permute({0, 3, 1, 2});

    if (storage.numel() == 0) {
        return output;
    }

    const int spatial = static_cast<int>(spatial64);
    const int depth = static_cast<int>(x.size(2));
    const dim3 grid(
        static_cast<unsigned int>((spatial64 + 7) / 8),
        static_cast<unsigned int>(x.size(0)));
    const auto stream = at::cuda::getCurrentCUDAStream();

    if (depth == 22) {
        depth_min_bias_softmax_kernel<22><<<grid, 256, 0, stream>>>(
            x.data_ptr<float>(), bias.data_ptr<float>(),
            storage.data_ptr<float>(), spatial, depth);
    } else {
        depth_min_bias_softmax_kernel<0><<<grid, 256, 0, stream>>>(
            x.data_ptr<float>(), bias.data_ptr<float>(),
            storage.data_ptr<float>(), spatial, depth);
    }

    C10_CUDA_KERNEL_LAUNCH_CHECK();
    return output;
}
"""

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


class ModelNew(nn.Module):
    def __init__(self, in_channels, out_channels, kernel_size, dim):
        super().__init__()
        self.conv = nn.Conv3d(in_channels, out_channels, kernel_size)
        self.conv.to(memory_format=torch.channels_last_3d)
        self.dim = dim

    def forward(self, x):
        if (
            x.is_cuda
            and x.dtype == torch.float32
            and self.conv.weight.dtype == torch.float32
            and self.conv.out_channels == 24
            and self.dim in (2, -3)
            and x.ndim == 5
            and x.shape[0] <= 65535
        ):
            x = x.contiguous(memory_format=torch.channels_last_3d)
            y = F.conv3d(
                x,
                self.conv.weight,
                None,
                self.conv.stride,
                self.conv.padding,
                self.conv.dilation,
                self.conv.groups,
            )
            if y.dtype == torch.float32:
                y = y.contiguous(memory_format=torch.channels_last_3d)
                return _fused_ops.depth_min_bias_softmax_cuda(
                    y, self.conv.bias
                )
            y = y + self.conv.bias.to(y.dtype).view(1, -1, 1, 1, 1)
            return torch.softmax(torch.min(y, dim=self.dim)[0], dim=1)

        y = self.conv(x)
        return torch.softmax(torch.min(y, dim=self.dim)[0], dim=1)
```
Result of evaluating it:
The solution is correct on the test inputs. Mean runtime 1.18 ms; the PyTorch reference (with TF32 enabled) takes 2.06 ms; speedup 1.746x.
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 | 833.4 | 1 |
| void depth_min_bias_softmax_kernel<22>(float const*, float const*, float*, int, int) | 197.7 | 1 |
| void cudnn::engines_precompiled::convertTensor_kernel<float, float, float, (cudnnKernelDat | 62.8 | 2 |
| void at::native::elementwise_kernel<128, 2, at::native::gpu_kernel_impl_nocast<at::native: | 61.1 | 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.
