```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
from torch.utils.cpp_extension import load_inline

# Fully fused kernel: direct ConvTranspose3d (as a gather-based "sub-pixel" conv)
# + LogSumExp over channels + HardSwish(sigmoid) + bias subtraction + clamp.
# This avoids materializing the huge (B, 16, 31, 63, 63) conv output (~1GB) that
# dominated runtime in the cuDNN dgrad path.
fused_cpp_source = """
torch::Tensor fused_forward(torch::Tensor x, torch::Tensor w, torch::Tensor conv_bias,
                            torch::Tensor bias,
                            int64_t sD, int64_t sH, int64_t sW,
                            int64_t pD, int64_t pH, int64_t pW);
"""

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

__device__ __forceinline__ float post_op(float lse, float bias) {
    // x * sigmoid(x + 3) / 6  ->  subtract bias  ->  clamp(-1, 1)
    float sig = 1.f / (1.f + expf(-(lse + 3.f)));
    float y = lse * sig * (1.f / 6.f) - bias;
    return fminf(fmaxf(y, -1.f), 1.f);
}

// For output coord o of a transposed conv: o = i*stride - pad + k.
// Enumerate all valid (input index i, kernel index k) pairs.
__device__ __forceinline__ int compute_pairs(int o, int K, int stride, int pad, int in_size,
                                             int* iv, int* kv) {
    int cnt = 0;
    for (int k = 0; k < K; ++k) {
        int numer = o + pad - k;
        if (numer < 0) continue;
        if (numer % stride) continue;
        int i = numer / stride;
        if (i >= in_size) continue;
        iv[cnt] = i; kv[cnt] = k; cnt++;
    }
    return cnt;
}

// One thread per output voxel; all CO channel accumulators live in registers.
// Weights are staged into shared memory transposed to [k][ic][oc] for
// contiguous, vectorizable access in the innermost loop.
template <int CI, int CO>
__global__ void fused_convt3d_lse_kernel(
        const float* __restrict__ x,
        const float* __restrict__ w,
        const float* __restrict__ conv_bias,
        const float* __restrict__ bias,
        float* __restrict__ out,
        int D, int H, int W,
        int Do, int Ho, int Wo,
        int KD, int KH, int KW,
        int sD, int sH, int sW,
        int pD, int pH, int pW) {
    extern __shared__ float sw[];
    const int K3 = KD * KH * KW;
    const int wsize = CI * CO * K3;
    for (int i = threadIdx.x; i < wsize; i += blockDim.x) {
        int kk = i % K3;
        int t = i / K3;
        int oc = t % CO;
        int ic = t / CO;
        sw[(kk * CI + ic) * CO + oc] = w[i];
    }
    __shared__ float sb[CO];
    for (int i = threadIdx.x; i < CO; i += blockDim.x) sb[i] = conv_bias[i];
    __syncthreads();

    const int S = Do * Ho * Wo;
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    if (idx >= S) return;
    int b = blockIdx.y;

    int ow = idx % Wo;
    int tmp = idx / Wo;
    int oh = tmp % Ho;
    int od = tmp / Ho;

    int iv[3][8];
    int kv[3][8];
    int nd = compute_pairs(od, KD, sD, pD, D, iv[0], kv[0]);
    int nh = compute_pairs(oh, KH, sH, pH, H, iv[1], kv[1]);
    int nw = compute_pairs(ow, KW, sW, pW, W, iv[2], kv[2]);

    float acc[CO];
    #pragma unroll
    for (int c = 0; c < CO; ++c) acc[c] = sb[c];

    const int HW = H * W;
    const float* xb = x + (size_t)b * CI * HW;

    for (int a = 0; a < nd; ++a) {
        for (int bb = 0; bb < nh; ++bb) {
            int base_off = (iv[0][a] * H + iv[1][bb]) * W;
            int kbase = (kv[0][a] * KH + kv[1][bb]) * KW;
            for (int cc = 0; cc < nw; ++cc) {
                int in_off = base_off + iv[2][cc];
                int k_off = kbase + kv[2][cc];
                #pragma unroll
                for (int ic = 0; ic < CI; ++ic) {
                    float xv = xb[ic * HW + in_off];
                    const float* wp = sw + (k_off * CI + ic) * CO;
                    #pragma unroll
                    for (int oc = 0; oc < CO; ++oc) {
                        acc[oc] = fmaf(xv, wp[oc], acc[oc]);
                    }
                }
            }
        }
    }

    // LogSumExp over channels (numerically stable), then fused element-wise ops.
    float m = -INFINITY;
    #pragma unroll
    for (int c = 0; c < CO; ++c) m = fmaxf(m, acc[c]);
    float sum = 0.f;
    #pragma unroll
    for (int c = 0; c < CO; ++c) sum += expf(acc[c] - m);
    float lse = m + logf(sum);
    out[(size_t)b * S + idx] = post_op(lse, bias[0]);
}

// Generic fallback post-op kernel (used for non-fast-path channel configs).
__global__ void fused_lse_kernel_generic(const float* __restrict__ x,
                                         const float* __restrict__ bias,
                                         float* __restrict__ out,
                                         int C, int S) {
    int s = blockIdx.x * blockDim.x + threadIdx.x;
    if (s >= S) return;
    int b = blockIdx.y;
    const float* ptr = x + (size_t)b * C * S + s;

    float m = -INFINITY;
    for (int c = 0; c < C; ++c) m = fmaxf(m, ptr[(size_t)c * S]);
    float sum = 0.f;
    for (int c = 0; c < C; ++c) sum += expf(ptr[(size_t)c * S] - m);
    float lse = m + logf(sum);
    out[(size_t)b * S + s] = post_op(lse, bias[0]);
}

torch::Tensor fused_forward(torch::Tensor x, torch::Tensor w, torch::Tensor conv_bias,
                            torch::Tensor bias,
                            int64_t sD, int64_t sH, int64_t sW,
                            int64_t pD, int64_t pH, int64_t pW) {
    TORCH_CHECK(x.is_cuda() && w.is_cuda(), "inputs must be CUDA tensors");
    TORCH_CHECK(x.scalar_type() == at::kFloat, "x must be float32");
    TORCH_CHECK(x.dim() == 5, "x must be 5D (B, C, D, H, W)");
    TORCH_CHECK(w.dim() == 5, "w must be 5D (CI, CO, kD, kH, kW)");

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

    int64_t B  = xc.size(0);
    int64_t CI = xc.size(1);
    int64_t D  = xc.size(2), H = xc.size(3), W = xc.size(4);
    int64_t CO = wc.size(1);
    int64_t KD = wc.size(2), KH = wc.size(3), KW = wc.size(4);
    TORCH_CHECK(wc.size(0) == CI, "weight/input channel mismatch");

    // output_padding = 0, dilation = 1 (module defaults)
    int64_t Do = (D - 1) * sD - 2 * pD + KD;
    int64_t Ho = (H - 1) * sH - 2 * pH + KH;
    int64_t Wo = (W - 1) * sW - 2 * pW + KW;

    auto out = at::empty({B, 1, Do, Ho, Wo}, xc.options());
    cudaStream_t stream = at::cuda::getCurrentCUDAStream();

    torch::Tensor cb;
    if (conv_bias.defined() && conv_bias.numel() > 0) {
        cb = conv_bias.contiguous();
    } else {
        cb = at::zeros({CO}, xc.options());
    }

    int64_t S = Do * Ho * Wo;
    const int block = 256;
    dim3 grid((unsigned)((S + block - 1) / block), (unsigned)B);

    bool fast = (CI == 3 && CO == 16 && KD <= 8 && KH <= 8 && KW <= 8);
    if (fast) {
        size_t shmem = (size_t)CI * CO * KD * KH * KW * sizeof(float);
        fused_convt3d_lse_kernel<3, 16><<<grid, block, shmem, stream>>>(
            xc.data_ptr<float>(), wc.data_ptr<float>(), cb.data_ptr<float>(),
            bc.data_ptr<float>(), out.data_ptr<float>(),
            (int)D, (int)H, (int)W, (int)Do, (int)Ho, (int)Wo,
            (int)KD, (int)KH, (int)KW,
            (int)sD, (int)sH, (int)sW, (int)pD, (int)pH, (int)pW);
        C10_CUDA_KERNEL_LAUNCH_CHECK();
        return out;
    }

    // Fallback for arbitrary configs: cuDNN/ATen conv transpose + fused post-op.
    auto yt = at::conv_transpose3d(xc, wc, cb, {sD, sH, sW}, {pD, pH, pW},
                                   {0, 0, 0}, 1, {1, 1, 1}).contiguous();
    int64_t Sf = yt.numel() / (B * CO);
    dim3 gridf((unsigned)((Sf + block - 1) / block), (unsigned)B);
    fused_lse_kernel_generic<<<gridf, block, 0, stream>>>(
        yt.data_ptr<float>(), bc.data_ptr<float>(), out.data_ptr<float>(),
        (int)CO, (int)Sf);
    C10_CUDA_KERNEL_LAUNCH_CHECK();
    return out;
}
"""

fused_ops = load_inline(
    name="fused_convt3d_lse_hswish_clamp_v2",
    cpp_sources=fused_cpp_source,
    cuda_sources=fused_cuda_source,
    functions=["fused_forward"],
    verbose=False,
    extra_cuda_cflags=["-O3"],
)


class ModelNew(nn.Module):
    """
    Optimized model: the ConvTranspose3d, LogSumExp over channels, sigmoid-based
    HardSwish, bias subtraction, and clamp are all fused into a single CUDA
    kernel. The transposed convolution is computed directly (gather-based), so
    the large multi-channel conv output is never materialized in global memory.
    """
    def __init__(self, in_channels, out_channels, kernel_size, stride, padding, bias_shape):
        super(ModelNew, self).__init__()
        self.conv_transpose = nn.ConvTranspose3d(in_channels, out_channels, kernel_size,
                                                 stride=stride, padding=padding)
        self.bias = nn.Parameter(torch.randn(1, 1, 1, 1))

        def _triple(v):
            if isinstance(v, (tuple, list)):
                return tuple(int(t) for t in v)
            return (int(v), int(v), int(v))

        self._stride = _triple(stride)
        self._padding = _triple(padding)
        self._out_channels = out_channels

    def forward(self, x):
        s = self._stride
        p = self._padding
        cb = self.conv_transpose.bias
        if cb is None:
            cb = x.new_zeros(self._out_channels)
        return fused_ops.fused_forward(
            x, self.conv_transpose.weight, cb, self.bias,
            s[0], s[1], s[2], p[0], p[1], p[2])
```