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):
    """
    Performs a transposed 3D convolution with a square input and an asymmetric kernel.

    Args:
        in_channels (int): Number of channels in the input tensor.
        out_channels (int): Number of channels produced by the convolution.
        kernel_size (tuple): Size of the convolution kernel (kernel_depth, kernel_width, kernel_height), 
                             where kernel_width == kernel_height.
        stride (tuple, optional): Stride of the convolution. Defaults to (1, 1, 1).
        padding (tuple, optional): Padding applied to the input. Defaults to (0, 0, 0).
        output_padding (tuple, optional): Additional size added to one side of the output shape. Defaults to (0, 0, 0).
        groups (int, optional): Number of blocked connections from input channels to output channels. Defaults to 1.
        bias (bool, optional): If `True`, adds a learnable bias to the output. Defaults to `False`.
    """
    def __init__(self, in_channels: int, out_channels: int, kernel_size: tuple, stride: tuple = (1, 1, 1), padding: tuple = (0, 0, 0), output_padding: tuple = (0, 0, 0), groups: int = 1, bias: bool = False):
        super(Model, self).__init__()
        self.conv_transpose3d = nn.ConvTranspose3d(in_channels, out_channels, kernel_size, stride=stride, padding=padding, output_padding=output_padding, groups=groups, bias=bias)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """
        Performs the transposed 3D convolution.

        Args:
            x (torch.Tensor): Input tensor of shape (batch_size, in_channels, depth, width, height).

        Returns:
            torch.Tensor: Output tensor of shape (batch_size, out_channels, depth_out, width_out, height_out).
        """
        return self.conv_transpose3d(x)

# Test code
batch_size = 16
in_channels = 32
out_channels = 64
kernel_depth = 3
kernel_width = 5
kernel_height = 5
depth = 64
width = 64
height = 64

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

def get_init_inputs():
    return [in_channels, out_channels, (kernel_depth, kernel_width, kernel_height)]  # Provide in_channels, out_channels, kernel_size for initialization
    ```
    
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
# 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

# ---------------------------------------------------------------------------
# Optimized ConvTranspose3d.
#
# Two ideas combined:
#  1) Algorithmic change (from turn 1): a ConvTranspose3d with stride == 1 and
#     output_padding == 0 is mathematically a *forward* Conv3d with spatially
#     flipped, channel-swapped weights and padding (K-1-p).  Forward convs hit
#     much faster GEMM kernels than transposed (backward-data) convs.
#  2) Half-precision tensor cores: the forward conv is executed in fp16 with
#     fp32 accumulation.  fp16 has the same 10-bit mantissa as the TF32 the
#     reference runs with, so the accuracy profile is comparable, while the
#     tensor-core peak throughput doubles.  Custom fused CUDA kernels do the
#     NCHW-fp32 -> NHWC-fp16 packing of the input, the weight
#     flip/transpose/cast, and the NHWC-fp16 -> NCHW-fp32 unpack of the
#     output, so cuDNN runs a pure NHWC tensor-core kernel with no internal
#     layout conversions.
#
# Robust fallbacks: fp16 failure -> fp32 rewritten conv; any other config ->
# native conv_transpose3d.
# ---------------------------------------------------------------------------

_cpp_source = r"""
#include <vector>
#include <c10/util/Optional.h>
torch::Tensor convt3d_forward(torch::Tensor x, torch::Tensor weight,
                              c10::optional<torch::Tensor> bias,
                              std::vector<int64_t> conv_pad, int64_t groups);
"""

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

#define TILE 32

// Fused cast + layout transform: fp32 NCHW -> fp16 NHWC (channels_last_3d).
// Per batch item this transposes a [C x S] matrix into [S x C] (S = D*H*W)
// using a 32x32 shared-memory tile: coalesced reads and writes.
__global__ void pack_nchw_to_nhwc_half_kernel(
    const float* __restrict__ in, __half* __restrict__ out,
    const int C, const int64_t S) {
  __shared__ float tile[TILE][TILE + 1];
  const int cTiles = (C + TILE - 1) / TILE;
  const int n = blockIdx.y / cTiles;
  const int c0 = (blockIdx.y % cTiles) * TILE;
  const int64_t s0 = (int64_t)blockIdx.x * TILE;
  const int tx = threadIdx.x, ty = threadIdx.y;
  const float* in_n = in + (int64_t)n * C * S;
  #pragma unroll
  for (int i = 0; i < TILE / 8; ++i) {
    const int row = ty + i * 8;
    const int c = c0 + row;
    const int64_t s = s0 + tx;
    float v = 0.f;
    if (c < C && s < S) v = in_n[(int64_t)c * S + s];
    tile[row][tx] = v;
  }
  __syncthreads();
  __half* out_n = out + (int64_t)n * C * S;
  #pragma unroll
  for (int i = 0; i < TILE / 8; ++i) {
    const int row = ty + i * 8;
    const int64_t s = s0 + row;
    const int c = c0 + tx;
    if (s < S && c < C) out_n[s * C + c] = __float2half(tile[row][tx]);
  }
}

// Fused cast + layout transform: fp16 NHWC -> fp32 NCHW contiguous.
__global__ void unpack_nhwc_half_to_nchw_float_kernel(
    const __half* __restrict__ in, float* __restrict__ out,
    const int C, const int64_t S) {
  __shared__ __half tile[TILE][TILE + 1];
  const int cTiles = (C + TILE - 1) / TILE;
  const int n = blockIdx.y / cTiles;
  const int c0 = (blockIdx.y % cTiles) * TILE;
  const int64_t s0 = (int64_t)blockIdx.x * TILE;
  const int tx = threadIdx.x, ty = threadIdx.y;
  const __half* in_n = in + (int64_t)n * C * S;
  #pragma unroll
  for (int i = 0; i < TILE / 8; ++i) {
    const int row = ty + i * 8;
    const int64_t s = s0 + row;
    const int c = c0 + tx;
    __half v = __float2half(0.f);
    if (s < S && c < C) v = in_n[s * C + c];
    tile[row][tx] = v;
  }
  __syncthreads();
  float* out_n = out + (int64_t)n * C * S;
  #pragma unroll
  for (int i = 0; i < TILE / 8; ++i) {
    const int row = ty + i * 8;
    const int c = c0 + row;
    const int64_t s = s0 + tx;
    if (c < C && s < S) out_n[(int64_t)c * S + s] = __half2float(tile[tx][row]);
  }
}

// ConvTranspose3d weight (C_in, C_out/g, KD, KH, KW) fp32 NCHW
//   -> forward Conv3d weight (C_out, C_in/g, KD, KH, KW) fp16 NHWC (KRSC),
// flipping the spatial dims and swapping the grouped in/out channel indices.
__global__ void transform_weight_half_kernel(
    const float* __restrict__ w, __half* __restrict__ out,
    const int64_t C_out_g, const int64_t C_in_g,
    const int64_t KD, const int64_t KH, const int64_t KW,
    const int64_t total) {
  const int64_t idx = blockIdx.x * (int64_t)blockDim.x + threadIdx.x;
  if (idx >= total) return;
  int64_t t = idx;
  const int64_t i2 = t % C_in_g; t /= C_in_g;
  const int64_t kw = t % KW; t /= KW;
  const int64_t kh = t % KH; t /= KH;
  const int64_t kd = t % KD;
  const int64_t o = t / KD;
  const int64_t go = o / C_out_g;
  const int64_t o_local = o - go * C_out_g;
  const int64_t i = go * C_in_g + i2;
  const int64_t src =
      ((((i * C_out_g + o_local) * KD + (KD - 1 - kd)) * KH +
        (KH - 1 - kh)) * KW) + (KW - 1 - kw);
  out[idx] = __float2half(w[src]);
}

// Same transform, fp32 NCHW output (fallback path).
__global__ void transform_weight_float_kernel(
    const float* __restrict__ w, float* __restrict__ out,
    const int64_t C_out_g, const int64_t C_in_g,
    const int64_t KD, const int64_t KH, const int64_t KW,
    const int64_t total) {
  const int64_t idx = blockIdx.x * (int64_t)blockDim.x + threadIdx.x;
  if (idx >= total) return;
  int64_t t = idx;
  const int64_t kw = t % KW; t /= KW;
  const int64_t kh = t % KH; t /= KH;
  const int64_t kd = t % KD; t /= KD;
  const int64_t i2 = t % C_in_g;
  const int64_t o = t / C_in_g;
  const int64_t go = o / C_out_g;
  const int64_t o_local = o - go * C_out_g;
  const int64_t i = go * C_in_g + i2;
  const int64_t src =
      ((((i * C_out_g + o_local) * KD + (KD - 1 - kd)) * KH +
        (KH - 1 - kh)) * KW) + (KW - 1 - kw);
  out[idx] = w[src];
}

torch::Tensor convt3d_forward(torch::Tensor x, torch::Tensor weight,
                              c10::optional<torch::Tensor> bias,
                              std::vector<int64_t> conv_pad, int64_t groups) {
  const int64_t KD = weight.size(2);
  const int64_t KH = weight.size(3);
  const int64_t KW = weight.size(4);
  c10::optional<at::Tensor> bias_opt = c10::nullopt;
  if (bias.has_value() && bias->defined() && bias->numel() > 0)
    bias_opt = *bias;

  const bool fast_ok = x.is_cuda() && weight.is_cuda() &&
                       x.scalar_type() == at::kFloat &&
                       weight.scalar_type() == at::kFloat;
  if (!fast_ok) {
    std::vector<int64_t> pad = {KD - 1 - conv_pad[0], KH - 1 - conv_pad[1],
                                KW - 1 - conv_pad[2]};
    return at::conv_transpose3d(x, weight, bias_opt, {1, 1, 1}, pad,
                                {0, 0, 0}, groups, {1, 1, 1});
  }

  auto x_c = x.contiguous();
  auto w_c = weight.contiguous();
  const int64_t N = x_c.size(0), C_in = x_c.size(1);
  const int64_t D = x_c.size(2), H = x_c.size(3), Wd = x_c.size(4);
  const int64_t C_out_g = w_c.size(1);
  const int64_t C_in_g = C_in / groups;
  const int64_t C_out = C_out_g * groups;
  cudaStream_t stream = at::cuda::getCurrentCUDAStream();

  // ---- fp16 tensor-core fast path --------------------------------------
  try {
    auto half_nhwc = x_c.options()
                         .dtype(at::kHalf)
                         .memory_format(at::MemoryFormat::ChannelsLast3d);
    auto x_h = at::empty({N, C_in, D, H, Wd}, half_nhwc);
    {
      const int64_t S = D * H * Wd;
      dim3 block(TILE, 8);
      dim3 grid((unsigned)((S + TILE - 1) / TILE),
                (unsigned)(N * ((C_in + TILE - 1) / TILE)));
      pack_nchw_to_nhwc_half_kernel<<<grid, block, 0, stream>>>(
          x_c.data_ptr<float>(),
          reinterpret_cast<__half*>(x_h.data_ptr<at::Half>()),
          (int)C_in, S);
    }
    auto w_h = at::empty({C_out, C_in_g, KD, KH, KW}, half_nhwc);
    {
      const int64_t total = w_h.numel();
      const int threads = 256;
      const int64_t blocks = (total + threads - 1) / threads;
      transform_weight_half_kernel<<<blocks, threads, 0, stream>>>(
          w_c.data_ptr<float>(),
          reinterpret_cast<__half*>(w_h.data_ptr<at::Half>()),
          C_out_g, C_in_g, KD, KH, KW, total);
    }
    c10::optional<at::Tensor> bias_h = c10::nullopt;
    if (bias_opt.has_value()) bias_h = bias_opt->to(at::kHalf);

    auto y = at::conv3d(x_h, w_h, bias_h, {1, 1, 1}, conv_pad, {1, 1, 1},
                        groups);
    if (y.is_contiguous(at::MemoryFormat::ChannelsLast3d)) {
      auto yf = at::empty(y.sizes(), y.options().dtype(at::kFloat));
      const int64_t S = y.size(2) * y.size(3) * y.size(4);
      const int64_t C = y.size(1);
      dim3 block(TILE, 8);
      dim3 grid((unsigned)((S + TILE - 1) / TILE),
                (unsigned)(y.size(0) * ((C + TILE - 1) / TILE)));
      unpack_nhwc_half_to_nchw_float_kernel<<<grid, block, 0, stream>>>(
          reinterpret_cast<const __half*>(y.data_ptr<at::Half>()),
          yf.data_ptr<float>(), (int)C, S);
      return yf;
    }
    return y.to(at::kFloat);
  } catch (...) {
    // fall through to the fp32 path
  }

  // ---- fp32 (TF32) rewritten-forward-conv fallback ----------------------
  try {
    auto w2 = at::empty({C_out, C_in_g, KD, KH, KW}, w_c.options());
    const int64_t total = w2.numel();
    const int threads = 256;
    const int64_t blocks = (total + threads - 1) / threads;
    transform_weight_float_kernel<<<blocks, threads, 0, stream>>>(
        w_c.data_ptr<float>(), w2.data_ptr<float>(), C_out_g, C_in_g, KD,
        KH, KW, total);
    return at::conv3d(x_c, w2, bias_opt, {1, 1, 1}, conv_pad, {1, 1, 1},
                      groups);
  } catch (...) {
    std::vector<int64_t> pad = {KD - 1 - conv_pad[0], KH - 1 - conv_pad[1],
                                KW - 1 - conv_pad[2]};
    return at::conv_transpose3d(x, weight, bias_opt, {1, 1, 1}, pad,
                                {0, 0, 0}, groups, {1, 1, 1});
  }
}
"""

_ext = None
try:
    _ext = load_inline(
        name="fast_conv_transpose3d_v2",
        cpp_sources=_cpp_source,
        cuda_sources=_cuda_source,
        functions=["convt3d_forward"],
        verbose=False,
        extra_cuda_cflags=["-O3"],
    )
except Exception:
    _ext = None

# Let cuDNN autotune the best algorithm for the fixed problem shapes.
torch.backends.cudnn.benchmark = True
torch.backends.cudnn.allow_tf32 = True


class ModelNew(nn.Module):
    """
    Optimized version of Model.  Rewrites the stride-1 transposed 3D
    convolution as an equivalent forward 3D convolution and executes it in
    fp16 on tensor cores (fp32 accumulation, fp32 output), using custom fused
    CUDA kernels for the weight transform and the NCHW<->NHWC casts.  Falls
    back to fp32 / native implementations for any other configuration.
    """

    def __init__(self, in_channels: int, out_channels: int, kernel_size: tuple,
                 stride: tuple = (1, 1, 1), padding: tuple = (0, 0, 0),
                 output_padding: tuple = (0, 0, 0), groups: int = 1,
                 bias: bool = False):
        super(ModelNew, self).__init__()
        # Same submodule/parameter names as the reference model so state_dicts
        # remain fully compatible.
        self.conv_transpose3d = nn.ConvTranspose3d(
            in_channels, out_channels, kernel_size, stride=stride,
            padding=padding, output_padding=output_padding, groups=groups,
            bias=bias)
        ks = tuple(kernel_size)
        conv_pad = (ks[0] - 1 - padding[0],
                    ks[1] - 1 - padding[1],
                    ks[2] - 1 - padding[2])
        self._fast_ok = (all(s == 1 for s in stride)
                         and all(op == 0 for op in output_padding)
                         and min(conv_pad) >= 0)
        self._conv_pad = conv_pad

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        ct = self.conv_transpose3d
        if (_ext is not None and self._fast_ok and x.is_cuda
                and x.dtype == torch.float32
                and ct.weight.dtype == torch.float32):
            return _ext.convt3d_forward(x, ct.weight, ct.bias,
                                        list(self._conv_pad), ct.groups)
        return ct(x)
```
Result of evaluating it:
The solution compiled and ran but its output did not match the reference. Details:
```
{"avg_difference": ["0.119379", "0.119384", "0.119400", "0.119403", "0.119404"], "correctness_issue": "Output mismatch", "correctness_trials": "(0 / 5)", "max_difference": ["0.939833", "0.994419", "0.965123", "0.980690", "0.979274"]}
```

The fastest correct solution so far (3.190x speedup) is:
```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

# ---------------------------------------------------------------------------
# Custom CUDA operator.
#
# Algorithmic change: a ConvTranspose3d with stride == 1 and output_padding == 0
# is mathematically equivalent to a *forward* Conv3d whose weights have their
# spatial dims flipped and input/output channel dims swapped, with padding
# (K-1 - p).  Forward convolutions map to much better optimized GEMM-based
# kernels than transposed (backward-data) convolutions, so this reformulation
# gives a speedup.  The weight transformation is implemented as a custom CUDA
# kernel below; any configuration that does not meet the requirements falls
# back to the native transposed convolution.
# ---------------------------------------------------------------------------

_cpp_source = r"""
#include <vector>
torch::Tensor conv_transpose3d_forward(
    torch::Tensor x,
    torch::Tensor weight,
    torch::Tensor bias,
    std::vector<int64_t> stride,
    std::vector<int64_t> padding,
    std::vector<int64_t> output_padding,
    int64_t groups);
"""

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

// Custom CUDA kernel that converts a ConvTranspose3d weight tensor of shape
//   (C_in, C_out / groups, KD, KH, KW)
// into an equivalent forward-Conv3d weight tensor of shape
//   (C_out, C_in / groups, KD, KH, KW)
// by swapping the (grouped) input/output channel indices and flipping the
// spatial kernel dimensions.  The mapping is group-aware.
__global__ void flip_transpose_weight_kernel(
    const float* __restrict__ w,
    float* __restrict__ out,
    const int64_t C_in,
    const int64_t C_out,
    const int64_t C_in_g,
    const int64_t C_out_g,
    const int64_t KD,
    const int64_t KH,
    const int64_t KW,
    const int64_t total) {
  const int64_t idx = blockIdx.x * (int64_t)blockDim.x + threadIdx.x;
  if (idx >= total) return;

  int64_t t = idx;
  const int64_t kw = t % KW; t /= KW;
  const int64_t kh = t % KH; t /= KH;
  const int64_t kd = t % KD; t /= KD;
  const int64_t i2 = t % C_in_g;         // input channel inside its group
  const int64_t o  = t / C_in_g;         // global output channel

  const int64_t go      = o / C_out_g;   // group this output channel belongs to
  const int64_t i       = go * C_in_g + i2;   // global input channel
  const int64_t o_local = o - go * C_out_g;   // output channel inside its group

  // source layout: w[i][o_local][KD-1-kd][KH-1-kh][KW-1-kw]
  const int64_t src =
      ((((int64_t)i * C_out_g + o_local) * KD + (KD - 1 - kd)) * KH +
       (KH - 1 - kh)) * KW + (KW - 1 - kw);
  out[idx] = w[src];
}

torch::Tensor conv_transpose3d_forward(
    torch::Tensor x,
    torch::Tensor weight,
    torch::Tensor bias,
    std::vector<int64_t> stride,
    std::vector<int64_t> padding,
    std::vector<int64_t> output_padding,
    int64_t groups) {

  const bool has_bias = bias.defined() && bias.numel() > 0;
  c10::optional<at::Tensor> bias_opt = c10::nullopt;
  if (has_bias) bias_opt = bias;

  const int64_t KD = weight.size(2);
  const int64_t KH = weight.size(3);
  const int64_t KW = weight.size(4);

  const bool unit_stride =
      (stride[0] == 1 && stride[1] == 1 && stride[2] == 1);
  const bool no_out_pad =
      (output_padding[0] == 0 && output_padding[1] == 0 && output_padding[2] == 0);
  const bool nonneg_conv_pad =
      (KD - 1 - padding[0] >= 0) && (KH - 1 - padding[1] >= 0) &&
      (KW - 1 - padding[2] >= 0);

  const bool use_fast_path =
      x.is_cuda() && weight.is_cuda() &&
      x.scalar_type() == at::kFloat && weight.scalar_type() == at::kFloat &&
      unit_stride && no_out_pad && nonneg_conv_pad;

  if (!use_fast_path) {
    // Fully general fallback to the native operator.
    return at::conv_transpose3d(x, weight, bias_opt, stride, padding,
                                output_padding, groups, {1, 1, 1});
  }

  auto x_c = x.contiguous();
  auto w_c = weight.contiguous();

  const int64_t C_in   = w_c.size(0);
  const int64_t C_out_g = w_c.size(1);
  const int64_t C_in_g = C_in / groups;
  const int64_t C_out  = C_out_g * groups;

  // Transform the weights with the custom CUDA kernel.
  auto w2 = at::empty({C_out, C_in_g, KD, KH, KW}, w_c.options());
  const int64_t total = w2.numel();
  const int threads = 256;
  const int64_t blocks = (total + threads - 1) / threads;
  cudaStream_t stream = at::cuda::getCurrentCUDAStream();
  flip_transpose_weight_kernel<<<blocks, threads, 0, stream>>>(
      w_c.data_ptr<float>(), w2.data_ptr<float>(),
      C_in, C_out, C_in_g, C_out_g, KD, KH, KW, total);

  // Equivalent forward convolution (padding = K - 1 - p).
  std::vector<int64_t> conv_pad = {KD - 1 - padding[0],
                                   KH - 1 - padding[1],
                                   KW - 1 - padding[2]};
  return at::conv3d(x_c, w2, bias_opt, {1, 1, 1}, conv_pad, {1, 1, 1}, groups);
}
"""

_ext = None
try:
    _ext = load_inline(
        name="fast_conv_transpose3d",
        cpp_sources=_cpp_source,
        cuda_sources=_cuda_source,
        functions=["conv_transpose3d_forward"],
        verbose=False,
        extra_cuda_cflags=["-O3"],
    )
except Exception:
    _ext = None

# Let cuDNN autotune the best algorithm for the fixed problem shapes.
torch.backends.cudnn.benchmark = True


class ModelNew(nn.Module):
    """
    Optimized version of Model.  Uses a custom CUDA operator that rewrites the
    transposed 3D convolution as an equivalent (and faster) forward 3D
    convolution, with the weight flip/transpose done by a custom CUDA kernel.
    Falls back to the native op for configurations outside the fast path.
    """

    def __init__(self, in_channels: int, out_channels: int, kernel_size: tuple,
                 stride: tuple = (1, 1, 1), padding: tuple = (0, 0, 0),
                 output_padding: tuple = (0, 0, 0), groups: int = 1,
                 bias: bool = False):
        super(ModelNew, self).__init__()
        # Keep the same submodule/parameter names as the reference model so
        # state_dicts remain fully compatible.
        self.conv_transpose3d = nn.ConvTranspose3d(
            in_channels, out_channels, kernel_size, stride=stride,
            padding=padding, output_padding=output_padding, groups=groups,
            bias=bias)

    def _torch_fallback(self, x: torch.Tensor) -> torch.Tensor:
        ct = self.conv_transpose3d
        w = ct.weight
        g = ct.groups
        if (all(s == 1 for s in ct.stride)
                and all(p == 0 for p in ct.output_padding)):
            C_in, C_out_g, KD, KH, KW = w.shape
            pad = (KD - 1 - ct.padding[0],
                   KH - 1 - ct.padding[1],
                   KW - 1 - ct.padding[2])
            if min(pad) >= 0:
                C_in_g = C_in // g
                wg = (w.reshape(g, C_in_g, C_out_g, KD, KH, KW)
                        .permute(0, 2, 1, 3, 4, 5)
                        .flip([3, 4, 5])
                        .reshape(g * C_out_g, C_in_g, KD, KH, KW)
                        .contiguous())
                return F.conv3d(x, wg, ct.bias, (1, 1, 1), pad, (1, 1, 1), g)
        return ct(x)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        ct = self.conv_transpose3d
        if _ext is not None:
            bias = ct.bias if ct.bias is not None else x.new_empty(0)
            return _ext.conv_transpose3d_forward(
                x, ct.weight, bias,
                list(ct.stride), list(ct.padding),
                list(ct.output_padding), ct.groups)
        return self._torch_fallback(x)
```

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.
