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 transposed convolution, applies Mish activation, adds a value, 
    applies Hardtanh activation, and scales the output.
    """
    def __init__(self, in_channels, out_channels, kernel_size, stride, padding, output_padding, add_value, scale):
        super(Model, self).__init__()
        self.conv_transpose = nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride, padding, output_padding)
        self.add_value = add_value
        self.scale = scale

    def forward(self, x):
        x = self.conv_transpose(x)
        x = torch.nn.functional.mish(x) # Mish activation
        x = x + self.add_value
        x = torch.nn.functional.hardtanh(x, min_val=-1, max_val=1) # Hardtanh activation
        x = x * self.scale # Scaling
        return x

batch_size = 128
in_channels  = 64  
out_channels = 64  
height = width = 128  
kernel_size  = 3
stride       = 2  
padding      = 1
output_padding = 1
add_value = 0.5
scale = 2

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

def get_init_inputs():
    return [in_channels, out_channels, kernel_size, stride, padding, output_padding, add_value, scale]
    ```
    
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 5 of 6 for this task. Your previous solution (turn 4) 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

torch.backends.cudnn.benchmark = True
torch.backends.cudnn.benchmark_limit = 0  # exhaustive cudnn algo search
torch.backends.cudnn.allow_tf32 = True
torch.backends.cuda.matmul.allow_tf32 = True

# ---------------------------------------------------------------------------
# Safe-path epilogue: operates on the channels_last (NHWC) output of cudnn's
# transposed convolution and fuses bias add -> Mish -> add_value -> Hardtanh
# -> scale in one streaming pass.
# ---------------------------------------------------------------------------
fused_epilogue_source = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda_runtime.h>

__device__ __forceinline__ float epilogue(float v, float b, float add_value, float scale) {
    float x = v + b;
    float t = expf(fminf(x, 20.0f));
    float u = t * (t + 2.0f);
    float m = x * (u / (u + 2.0f));
    float y = m + add_value;
    y = fminf(fmaxf(y, -1.0f), 1.0f);
    return y * scale;
}

__global__ void fused_epilogue_nhwc_vec4_kernel(const float4* __restrict__ in,
                                                float4* __restrict__ out,
                                                const float* __restrict__ bias,
                                                long n4, long c4,
                                                float add_value, float scale) {
    long stride = (long)gridDim.x * blockDim.x;
    for (long v = (long)blockIdx.x * blockDim.x + threadIdx.x; v < n4; v += stride) {
        long cbase = (v % c4) << 2;
        float4 b = *reinterpret_cast<const float4*>(bias + cbase);
        float4 val = in[v];
        float4 r;
        r.x = epilogue(val.x, b.x, add_value, scale);
        r.y = epilogue(val.y, b.y, add_value, scale);
        r.z = epilogue(val.z, b.z, add_value, scale);
        r.w = epilogue(val.w, b.w, add_value, scale);
        out[v] = r;
    }
}

__global__ void fused_epilogue_nhwc_kernel(const float* __restrict__ in,
                                           float* __restrict__ out,
                                           const float* __restrict__ bias,
                                           long n, long C,
                                           float add_value, float scale) {
    long stride = (long)gridDim.x * blockDim.x;
    for (long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += stride) {
        long c = i % C;
        out[i] = epilogue(in[i], bias[c], add_value, scale);
    }
}

torch::Tensor fused_epilogue_nhwc_cuda(torch::Tensor x, torch::Tensor bias, double add_value, double scale) {
    TORCH_CHECK(x.is_cuda(), "x must be a CUDA tensor");
    TORCH_CHECK(x.scalar_type() == torch::kFloat32, "x must be float32");
    TORCH_CHECK(x.is_contiguous(at::MemoryFormat::ChannelsLast), "x must be channels_last contiguous");
    TORCH_CHECK(bias.is_cuda() && bias.scalar_type() == torch::kFloat32, "bias must be CUDA float32");

    auto b = bias.contiguous();
    const long C = x.size(1);
    TORCH_CHECK(b.numel() == C, "bias size mismatch");

    auto out = torch::empty_like(x);
    const long n = x.numel();
    if (n == 0) return out;

    auto stream = at::cuda::getCurrentCUDAStream();
    const int block = 256;

    if ((n % 4 == 0) && (C % 4 == 0)) {
        const long n4 = n >> 2;
        long blocks = (n4 + block - 1) / block;
        if (blocks > 2147483647L) blocks = 2147483647L;
        fused_epilogue_nhwc_vec4_kernel<<<(unsigned int)blocks, block, 0, stream>>>(
            reinterpret_cast<const float4*>(x.data_ptr<float>()),
            reinterpret_cast<float4*>(out.data_ptr<float>()),
            b.data_ptr<float>(), n4, C >> 2,
            (float)add_value, (float)scale);
    } else {
        long blocks = (n + block - 1) / block;
        if (blocks > 2147483647L) blocks = 2147483647L;
        fused_epilogue_nhwc_kernel<<<(unsigned int)blocks, block, 0, stream>>>(
            x.data_ptr<float>(), out.data_ptr<float>(), b.data_ptr<float>(),
            n, C, (float)add_value, (float)scale);
    }
    return out;
}
"""

# ---------------------------------------------------------------------------
# Fast NCHW -> NHWC (channels_last) conversion for the conv input.
# ---------------------------------------------------------------------------
nchw2nhwc_source = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda_runtime.h>

__global__ void nchw_to_nhwc_vec4_kernel(const float4* __restrict__ in,
                                         float4* __restrict__ out,
                                         int HW, int C4, long total4) {
    long stride = (long)gridDim.x * blockDim.x;
    for (long idx = (long)blockIdx.x * blockDim.x + threadIdx.x; idx < total4; idx += stride) {
        long s = idx / C4;
        int c4 = (int)(idx - s * C4);
        int n = (int)(s / HW);
        int hw = (int)(s - (long)n * HW);
        float4 v = in[idx];
        const float* in_f = reinterpret_cast<const float*>(in);
        long base = (long)n * (long)C4 * 4 * HW + hw;
        long strideC = (long)HW;
        long obase = (s << 2) + (long)c4 * 4;
        float4 r;
        r.x = in_f[base + (long)(c4 * 4 + 0) * strideC];
        r.y = in_f[base + (long)(c4 * 4 + 1) * strideC];
        r.z = in_f[base + (long)(c4 * 4 + 2) * strideC];
        r.w = in_f[base + (long)(c4 * 4 + 3) * strideC];
        (void)v;
        out[obase >> 2] = r;
    }
}

torch::Tensor nchw_to_nhwc_cuda(torch::Tensor x) {
    TORCH_CHECK(x.is_cuda() && x.scalar_type() == torch::kFloat32, "x must be CUDA float32");
    TORCH_CHECK(x.dim() == 4 && x.is_contiguous(), "x must be NCHW contiguous");
    auto out = torch::empty_like(x, at::MemoryFormat::ChannelsLast);
    const long N = x.size(0), C = x.size(1), H = x.size(2), W = x.size(3);
    const long total = N * C * H * W;
    if (total == 0) return out;
    auto stream = at::cuda::getCurrentCUDAStream();
    if ((C % 4 == 0) && (total % 4 == 0)) {
        const long total4 = total >> 2;
        const int block = 256;
        long blocks = (total4 + block - 1) / block;
        if (blocks > 2147483647L) blocks = 2147483647L;
        nchw_to_nhwc_vec4_kernel<<<(unsigned int)blocks, block, 0, stream>>>(
            reinterpret_cast<const float4*>(x.data_ptr<float>()),
            reinterpret_cast<float4*>(out.data_ptr<float>()),
            (int)(H * W), (int)(C >> 2), total4);
    } else {
        return x.contiguous(at::MemoryFormat::ChannelsLast);
    }
    return out;
}
"""

# ---------------------------------------------------------------------------
# Fully fused custom kernel: for stride-2 / kernel-3 / pad-1 / out_pad-1 the
# transposed convolution decomposes into 4 "phase" maps over 2x2 input
# patches (each input pixel writes a 2x2 output block).  The kernel computes,
# per 4x32 input-pixel tile of one image, all four phases with TF32 tensor
# core mma (m16n8k8), applies bias+Mish+add+Hardtanh+scale in registers and
# writes the final channels_last output exactly once.
# ---------------------------------------------------------------------------
fused_deconv_source = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda_runtime.h>
#include <mma.h>

using namespace nvcuda;

#define CI 64
#define CO 64
#define HIN 128
#define WIN 128
#define HOUT 256
#define WOUT 256
#define PW 33
#define LDP 34
#define PSZ (5 * LDP * 64)
#define LDS 68
#define STG_ELEMS (8 * 64 * LDS)
#define SMEM_FLOATS (PSZ + STG_ELEMS)

// tap tables: t0[phase*8 + t*2 + 0/1] = (a, b) weight tap for phase tap t
// t1[...] = (di, dj) input patch offset
__constant__ int t0[32] = {
    1,1,  0,0,  0,0,  0,0,   // phase 0: (1,1)
    1,2,  1,0,  0,0,  0,0,   // phase 1: (1,2),(1,0)
    2,1,  0,1,  0,0,  0,0,   // phase 2: (2,1),(0,1)
    2,2,  2,0,  0,2,  0,0    // phase 3: (2,2),(2,0),(0,2),(0,0)
};
__constant__ int t1[32] = {
    0,0,  0,0,  0,0,  0,0,   // phase 0
    0,0,  0,1,  0,0,  0,0,   // phase 1
    0,0,  1,0,  0,0,  0,0,   // phase 2
    0,0,  0,1,  1,0,  1,1    // phase 3
};

__device__ __forceinline__ float epilogue_f(float v, float b, float add_value, float scale) {
    float x = v + b;
    float t = expf(fminf(x, 20.0f));
    float u = t * (t + 2.0f);
    float m = x * (u / (u + 2.0f));
    float y = m + add_value;
    y = fminf(fmaxf(y, -1.0f), 1.0f);
    return y * scale;
}

__global__ __launch_bounds__(256, 1) void fused_deconv_mma_kernel(
        const float* __restrict__ xp,
        const float* __restrict__ wp,   // packed [4][4][CO][CI]
        const float* __restrict__ bias, // [CO]
        float* __restrict__ outp,       // NHWC
        int nImg, int tilesJ,
        float add_value, float scale) {
    __shared__ __align__(16) float smem[SMEM_FLOATS];
    float* patch = smem;            // [5][LDP][64]
    float* stg   = smem + PSZ;      // [8][64][LDS]

    const int img = blockIdx.x / (tilesJ * 32);
    const int rem = blockIdx.x - img * tilesJ * 32;
    const int ti = rem / tilesJ;      // 0..31
    const int tj = rem - ti * tilesJ; // 0..tilesJ-1
    const int i0 = ti * 4;
    const int j0 = tj * 32;

    const float* ximg = xp + (long)img * CI * HIN * WIN;
    float* outimg = outp + (long)img * HOUT * WOUT * CO;

    const int tid = threadIdx.x;
    const int warp = tid >> 5;
    const int wr = warp >> 1;   // 0..3
    const int wc = warp & 1;    // 0..1
    const int lane = tid & 31;

    // ---- load the 5 x 33 x 64 input patch (zero padded at edges) ----
    {
        const int cpair = tid >> 3;   // 0..31 -> channel 2*cpair, 2*cpair+1
        const int q8 = tid & 7;       // j-group of 4, second half covers last 5 j
        const int c0 = cpair * 2;
        #pragma unroll
        for (int ip = 0; ip < 5; ++ip) {
            const int ig = i0 + ip;
            #pragma unroll
            for (int rep = 0; rep < 2; ++rep) {
                int j = q8 * 4 + rep * 32;
                bool last = (rep == 1);
                if (last) { j = 28 + q8; if (q8 > 4) continue; }
                const int jg = j0 + j;
                const bool ok = (ig < HIN) && (jg < WIN) && (jg + ((last || q8==7 && !last) ? 0 : 3) < WIN || last);
                float v00 = 0.f, v01 = 0.f, v02 = 0.f, v03 = 0.f;
                float v10 = 0.f, v11 = 0.f, v12 = 0.f, v13 = 0.f;
                if (ig < HIN && jg < WIN) {
                    const float* src0 = ximg + ((long)c0 * HIN + ig) * WIN + jg;
                    const float* src1 = src0 + (long)HIN * WIN;
                    if (!last && jg + 3 < WIN) {
                        float4 a = *reinterpret_cast<const float4*>(src0);
                        float4 b = *reinterpret_cast<const float4*>(src1);
                        v00 = a.x; v01 = a.y; v02 = a.z; v03 = a.w;
                        v10 = b.x; v11 = b.y; v12 = b.z; v13 = b.w;
                    } else {
                        int cnt = WIN - jg; if (cnt > 4) cnt = 4;
                        if (last) cnt = 1;
                        if (cnt > 0) { v00 = src0[0]; v10 = src1[0]; }
                        if (cnt > 1) { v01 = src0[1]; v11 = src1[1]; }
                        if (cnt > 2) { v02 = src0[2]; v12 = src1[2]; }
                        if (cnt > 3) { v03 = src0[3]; v13 = src1[3]; }
                    }
                }
                float* dst = patch + ((ip * LDP + j) << 6) + c0;
                if (last) {
                    dst[0] = v00; dst[1] = v10;
                } else {
                    dst[0] = v00; dst[1] = v10;
                    dst[64] = v01; dst[65] = v11;
                    dst[128] = v02; dst[129] = v13;
                    dst[192] = v03; dst[193] = v13;
                }
            }
        }
    }
    __syncthreads();

    wmma::fragment<wmma::matrix_a, 16, 8, 8, wmma::precision::tf32, wmma::row_major> afrag[2];
    wmma::fragment<wmma::matrix_b, 16, 8, 8, wmma::precision::tf32, wmma::col_major> bfrag[4];

    // ---- 4 phases ----
    for (int ph = 0; ph < 4; ++ph) {
        const int di = ph >> 1;
        const int dj = ph & 1;
        const int ntap = (ph == 0) ? 1 : (ph == 3 ? 4 : 2);

        wmma::fragment<wmma::accumulator, 16, 8, 8, float> acc[2][4];
        #pragma unroll
        for (int mi = 0; mi < 2; ++mi)
            #pragma unroll
            for (int ni = 0; ni < 4; ++ni)
                wmma::fill_fragment(acc[mi][ni], 0.0f);

        for (int t = 0; t < ntap; ++t) {
            const int a = t0[ph * 8 + t * 2 + 0];
            const int b = t0[ph * 8 + t * 2 + 1];
            const int pdi = t1[ph * 8 + t * 2 + 0];
            const int pdj = t1[ph * 8 + t * 2 + 1];
            const float* wsrc = wp + (((ph * 4 + t) * CO) << 6) + (wr << 4);
            #pragma unroll 8
            for (int ks = 0; ks < 8; ++ks) {
                wmma::load_matrix_sync(afrag[0], wsrc + ((ks << 3) << 6), 64);
                wmma::load_matrix_sync(afrag[1], wsrc + (((ks << 3) + 32) << 6), 64);
                #pragma unroll
                for (int ni = 0; ni < 4; ++ni) {
                    const int jj = wc * 64 + ni * 16 + ((ks & 1) << 3);
                    const int iL = jj >> 5;
                    const int jL = jj & 31;
                    const float* bp = patch + ((((iL + pdi) * LDP + (jL + pdj)) << 6) + (ks << 3));
                    wmma::load_matrix_sync(bfrag[ni], bp, 64);
                }
                #pragma unroll
                for (int mi = 0; mi < 2; ++mi)
                    #pragma unroll
                    for (int ni = 0; ni < 4; ++ni)
                        wmma::mma_sync(acc[mi][ni], afrag[mi], bfrag[ni], acc[mi][ni]);
            }
        }

        // ---- stage accumulators to smem staging ----
        __syncthreads(); // protect staging reuse across phases
        #pragma unroll
        for (int ni = 0; ni < 4; ++ni) {
            const int jj = wc * 64 + ni * 16;
            const int iL = jj >> 5;
            const int jL = jj & 31;
            const int orow = 2 * (i0 + iL) + di;
            const int q0 = 2 * (j0 + jL) + dj;
            float* sbase = stg + ((orow & 7) * 64 + q0) * LDS + wr * 16;
            #pragma unroll
            for (int mi = 0; mi < 2; ++mi) {
                wmma::store_matrix_sync(sbase, acc[mi][ni], LDS * 64, wmma::mem_row_major);
                sbase += 8;
            }
        }
    }

    __syncthreads();

    // ---- epilogue + coalesced store of the 8 x 64 x 64 output tile ----
    {
        // 512 float4 units of 16 channels; 256 threads -> 2 each
        const int q4 = (tid & 7) << 2;      // q-group *4
        const int c4 = (tid >> 3) & 3;      // channel group *16
        const int rh = tid >> 5;            // row half
        #pragma unroll
        for (int rep = 0; rep < 2; ++rep) {
            const int orow = rh + rep * 4;
            const int qq = q4 * 4;
            float* srow = stg + (orow * 64 + qq) * LDS + c4 * 16;
            float* orowp = outimg + (((long)orow * WOUT + qq) << 6) + c4 * 16;
            const float* bp = bias + c4 * 16;
            #pragma unroll
            for (int u = 0; u < 4; ++u) {
                float4 v0 = *reinterpret_cast<const float4*>(srow + u * 4);
                float4 v1 = *reinterpret_cast<const float4*>(srow + 64 * LDS + u * 4);
                float4 v2 = *reinterpret_cast<const float4*>(srow + 128 * LDS + u * 4);
                float4 v3 = *reinterpret_cast<const float4*>(srow + 192 * LDS + u * 4);
                float4 b0 = *reinterpret_cast<const float4*>(bp + u * 4);
                float4 r0, r1, r2, r3;
                r0.x = epilogue_f(v0.x, b0.x, add_value, scale);
                r0.y = epilogue_f(v0.y, b0.y, add_value, scale);
                r0.z = epilogue_f(v0.z, b0.z, add_value, scale);
                r0.w = epilogue_f(v0.w, b0.w, add_value, scale);
                r1.x = epilogue_f(v1.x, b0.x, add_value, scale);
                r1.y = epilogue_f(v1.y, b0.y, add_value, scale);
                r1.z = epilogue_f(v1.z, b0.z, add_value, scale);
                r1.w = epilogue_f(v1.w, b0.w, add_value, scale);
                r2.x = epilogue_f(v2.x, b0.x, add_value, scale);
                r2.y = epilogue_f(v2.y, b0.y, add_value, scale);
                r2.z = epilogue_f(v2.z, b0.z, add_value, scale);
                r2.w = epilogue_f(v2.w, b0.w, add_value, scale);
                r3.x = epilogue_f(v3.x, b0.x, add_value, scale);
                r3.y = epilogue_f(v3.y, b0.y, add_value, scale);
                r3.z = epilogue_f(v3.z, b0.z, add_value, scale);
                r3.w = epilogue_f(v3.w, b0.w, add_value, scale);
                *reinterpret_cast<float4*>(orowp + u * 4) = r0;
                *reinterpret_cast<float4*>(orowp + (64 + u) * 4 * 0 + 256 + u * 4) = r1;
                *reinterpret_cast<float4*>(orowp + 512 + u * 4) = r2;
                *reinterpret_cast<float4*>(orowp + 768 + u * 4) = r3;
            }
        }
    }
}

torch::Tensor fused_deconv_cuda(torch::Tensor x, torch::Tensor wpacked, torch::Tensor bias,
                                double add_value, double scale) {
    TORCH_CHECK(x.is_cuda() && x.scalar_type() == torch::kFloat32 && x.is_contiguous(), "x must be CUDA fp32 NCHW");
    const long N = x.size(0);
    const long C = x.size(1);
    const long H = x.size(2);
    const long W = x.size(3);
    TORCH_CHECK(C == CI && H == HIN && W == WIN, "shape mismatch");
    auto out = torch::empty_like(x, at::MemoryFormat::ChannelsLast);
    out.resize_({N, (long)CO, (long)HOUT, (long)WOUT});
    if (N == 0) return out;
    auto stream = at::cuda::getCurrentCUDAStream();
    const int tilesJ = W / 32;
    const long blocks = N * 32L * tilesJ;
    static bool attr_set = false;
    if (!attr_set) {
        cudaFuncSetAttribute(fused_deconv_mma_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, 0);
        attr_set = true;
    }
    fused_deconv_mma_kernel<<<(unsigned int)blocks, 256, 0, stream>>>(
        x.data_ptr<float>(), wpacked.data_ptr<float>(), bias.data_ptr<float>(),
        out.data_ptr<float>(), (int)N, tilesJ, (float)add_value, (float)scale);
    return out;
}

torch::Tensor pack_weights_cuda(torch::Tensor w) {
    // w: [CI, CO, 3, 3] (ConvTranspose2d layout) -> packed [4,4,CO,CI] float32
    auto opts = torch::TensorOptions().dtype(torch::kFloat32).device(w.device());
    auto packed = torch::zeros({4, 4, CO, CI}, opts);
    // phase tables (a,b) and validity counts
    const int ab[4][4][2] = {
        {{1,1},{0,0},{0,0},{0,0}},
        {{1,2},{1,0},{0,0},{0,0}},
        {{2,1},{0,1},{0,0},{0,0}},
        {{2,2},{2,0},{0,2},{0,0}}
    };
    const int ntap[4] = {1, 2, 2, 4};
    auto wc = w.contiguous();
    for (int ph = 0; ph < 4; ++ph) {
        for (int t = 0; t < ntap[ph]; ++t) {
            int a = ab[ph][t][0], b = ab[ph][t][1];
            // packed[ph, t] = w[:, :, a, b].T  -> [CO, CI]
            packed[ph][t].copy_(wc.select(2, a).select(2, b).permute({1, 0}));
        }
    }
    return packed.contiguous();
}
"""

cpp_source = (
    "torch::Tensor fused_epilogue_nhwc_cuda(torch::Tensor x, torch::Tensor bias, double add_value, double scale);\n"
    "torch::Tensor nchw_to_nhwc_cuda(torch::Tensor x);\n"
    "torch::Tensor fused_deconv_cuda(torch::Tensor x, torch::Tensor wpacked, torch::Tensor bias, double add_value, double scale);\n"
    "torch::Tensor pack_weights_cuda(torch::Tensor w);"
)

_ext = load_inline(
    name="fused_deconv_epilogue_v4",
    cpp_sources=cpp_source,
    cuda_sources=fused_epilogue_source + nchw2nhwc_source + fused_deconv_source,
    functions=["fused_epilogue_nhwc_cuda", "nchw_to_nhwc_cuda", "fused_deconv_cuda", "pack_weights_cuda"],
    verbose=False,
    extra_cuda_cflags=["-O3"],
)


class ModelNew(nn.Module):
    """
    Optimized model:
      * Primary path: a single fully-fused custom CUDA kernel that computes the
        stride-2/kernel-3 transposed convolution via its exact 4-phase / 2x2
        patch decomposition using TF32 tensor-core mma, and applies
        bias+Mish+add+Hardtanh+scale in the same kernel. The 2 GB output is
        written exactly once (no intermediate conv output in DRAM, no input
        layout conversion, no separate activation passes).
      * Fallback path: cudnn NHWC transposed convolution (bias=None) + a fused
        elementwise epilogue kernel (known-good, ~2.7x over the reference).
      * On the first eligible forward the two paths are compared once; if the
        custom kernel deviates (or errors), the fallback is used permanently,
        so this is never worse than the safe solution.
      * The conv_transpose module (weight + bias) is kept intact so the
        state_dict matches the reference model.
    """
    def __init__(self, in_channels, out_channels, kernel_size, stride, padding, output_padding, add_value, scale):
        super(ModelNew, self).__init__()
        self.conv_transpose = nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride, padding, output_padding)
        self.add_value = add_value
        self.scale = scale
        self.ext = _ext
        self._wpacked = None
        self._w_key = None
        self._zero_bias = None
        self._checked = False
        self._use_custom = False

    # ---- helpers ----
    def _packed_weights(self, w):
        key = (w.data_ptr(), w._version, w.device)
        if self._wpacked is None or self._w_key != key:
            self._wpacked = self.ext.pack_weights_cuda(w.detach())
            self._w_key = key
        return self._wpacked

    def _bias_f32(self, ct, device):
        bias = ct.bias
        if bias is None:
            if self._zero_bias is None or self._zero_bias.device != device:
                self._zero_bias = torch.zeros(ct.out_channels, device=device, dtype=torch.float32)
            bias = self._zero_bias
        return bias.contiguous()

    def _eligible(self, x, ct):
        s = ct.stride if isinstance(ct.stride, tuple) else (ct.stride, ct.stride)
        p = ct.padding if isinstance(ct.padding, tuple) else (ct.padding, ct.padding)
        op = ct.output_padding if isinstance(ct.output_padding, tuple) else (ct.output_padding, ct.output_padding)
        d = ct.dilation if isinstance(ct.dilation, tuple) else (ct.dilation, ct.dilation)
        k = ct.kernel_size if isinstance(ct.kernel_size, tuple) else (ct.kernel_size, ct.kernel_size)
        return (
            x.is_cuda and x.dtype == torch.float32 and x.is_contiguous()
            and x.size(1) == 64 and x.size(2) == 128 and x.size(3) == 128
            and ct.in_channels == 64 and ct.out_channels == 64
            and k == (3, 3) and s == (2, 2) and p == (1, 1) and op == (1, 1)
            and d == (1, 1) and ct.groups == 1
        )

    def _custom_path(self, x, ct):
        wp = self._packed_weights(ct.weight)
        bias = self._bias_f32(ct, x.device)
        return self.ext.fused_deconv_cuda(x, wp, bias, float(self.add_value), float(self.scale))

    def _safe_path(self, x, ct):
        x = self.ext.nchw_to_nhwc_cuda(x) if x.is_contiguous() else x.contiguous(memory_format=torch.channels_last)
        y = F.conv_transpose2d(
            x, ct.weight, None,
            ct.stride, ct.padding, ct.output_padding, ct.groups, ct.dilation,
        )
        if not y.is_contiguous(memory_format=torch.channels_last):
            y = y.contiguous(memory_format=torch.channels_last)
        bias = self._bias_f32(ct, y.device)
        return self.ext.fused_epilogue_nhwc_cuda(y, bias, float(self.add_value), float(self.scale))

    def forward(self, x):
        ct = self.conv_transpose
        if torch.is_grad_enabled() and (x.requires_grad or ct.weight.requires_grad):
            # keep autograd intact if someone actually trains through this
            y = ct(x)
            y = F.mish(y)
            y = y + self.add_value
            y = F.hardtanh(y, min_val=-1, max_val=1)
            return y * self.scale

        if not (x.is_cuda and x.dtype == torch.float32):
            y = ct(x)
            y = F.mish(y)
            y = y + self.add_value
            y = F.hardtanh(y, min_val=-1, max_val=1)
            return y * self.scale

        eligible = self._eligible(x, ct)

        if eligible and not self._checked:
            self._checked = True
            try:
                y_custom = self._custom_path(x, ct)
                y_safe = self._safe_path(x, ct)
                if torch.allclose(y_custom, y_safe, atol=2e-2, rtol=2e-2):
                    self._use_custom = True
                    return y_custom
                self._use_custom = False
                return y_safe
            except Exception:
                self._use_custom = False

        if eligible and self._use_custom:
            return self._custom_path(x, ct)
        return self._safe_path(x, ct)
```
Result of evaluating it:
The solution failed to compile. Error output:
```
...[truncated]
MD -MF main.o.d -DTORCH_EXTENSION_NAME=fused_deconv_epilogue_v4 -DTORCH_API_INCLUDE_EXTENSION_H -isystem /opt/kbv/v/lib/python3.12/site-packages/torch/include -isystem /opt/kbv/v/lib/python3.12/site-packages/torch/include/torch/csrc/api/include -isystem /opt/kbv/v/lib/python3.12/site-packages/nvidia/cu13/include -isystem /usr/include/python3.12 -fPIC -std=c++20 -c /srv/jobs/1791601978486768049-3349698-0/build/fused_deconv_epilogue_v4/main.cpp -o main.o 
[2/3] /opt/kbv/v/lib/python3.12/site-packages/nvidia/cu13/bin/nvcc -MD -MF cuda.cuda.o.d -DTORCH_EXTENSION_NAME=fused_deconv_epilogue_v4 -DTORCH_API_INCLUDE_EXTENSION_H -isystem /opt/kbv/v/lib/python3.12/site-packages/torch/include -isystem /opt/kbv/v/lib/python3.12/site-packages/torch/include/torch/csrc/api/include -isystem /opt/kbv/v/lib/python3.12/site-packages/nvidia/cu13/include -isystem /usr/include/python3.12 -D__CUDA_NO_HALF_OPERATORS__ -D__CUDA_NO_HALF_CONVERSIONS__ -D__CUDA_NO_BFLOAT16_CONVERSIONS__ -D__CUDA_NO_HALF2_OPERATORS__ --expt-relaxed-constexpr -gencode=arch=compute_80,code=sm_80 --compiler-options '-fPIC' -O3 -std=c++20 -c /srv/jobs/1791601978486768049-3349698-0/build/fused_deconv_epilogue_v4/cuda.cu -o cuda.cuda.o 
FAILED: [code=2] cuda.cuda.o 
/opt/kbv/v/lib/python3.12/site-packages/nvidia/cu13/bin/nvcc -MD -MF cuda.cuda.o.d -DTORCH_EXTENSION_NAME=fused_deconv_epilogue_v4 -DTORCH_API_INCLUDE_EXTENSION_H -isystem /opt/kbv/v/lib/python3.12/site-packages/torch/include -isystem /opt/kbv/v/lib/python3.12/site-packages/torch/include/torch/csrc/api/include -isystem /opt/kbv/v/lib/python3.12/site-packages/nvidia/cu13/include -isystem /usr/include/python3.12 -D__CUDA_NO_HALF_OPERATORS__ -D__CUDA_NO_HALF_CONVERSIONS__ -D__CUDA_NO_BFLOAT16_CONVERSIONS__ -D__CUDA_NO_HALF2_OPERATORS__ --expt-relaxed-constexpr -gencode=arch=compute_80,code=sm_80 --compiler-options '-fPIC' -O3 -std=c++20 -c /srv/jobs/1791601978486768049-3349698-0/build/fused_deconv_epilogue_v4/cuda.cu -o cuda.cuda.o 
/srv/jobs/1791601978486768049-3349698-0/build/fused_deconv_epilogue_v4/cuda.cu(257): error: incomplete type "nvcuda::wmma::fragment<nvcuda::wmma::matrix_a, 16, 8, 8, nvcuda::wmma::precision::tf32, nvcuda::wmma::row_major> [2]" is not allowed
      wmma::fragment<wmma::matrix_a, 16, 8, 8, wmma::precision::tf32, wmma::row_major> afrag[2];
                                                                                       ^

/srv/jobs/1791601978486768049-3349698-0/build/fused_deconv_epilogue_v4/cuda.cu(258): error: incomplete type "nvcuda::wmma::fragment<nvcuda::wmma::matrix_b, 16, 8, 8, nvcuda::wmma::precision::tf32, nvcuda::wmma::col_major> [4]" is not allowed
      wmma::fragment<wmma::matrix_b, 16, 8, 8, wmma::precision::tf32, wmma::col_major> bfrag[4];
                                                                                       ^

/srv/jobs/1791601978486768049-3349698-0/build/fused_deconv_epilogue_v4/cuda.cu(266): error: incomplete type "nvcuda::wmma::fragment<nvcuda::wmma::accumulator, 16, 8, 8, float, void> [2][4]" is not allowed
          wmma::fragment<wmma::accumulator, 16, 8, 8, float> acc[2][4];
                                                             ^

/srv/jobs/1791601978486768049-3349698-0/build/fused_deconv_epilogue_v4/cuda.cu(271): error: no instance of function template "nvcuda::wmma::fill_fragment" matches the argument list
            argument types are: (<error-type>, float)
                  wmma::fill_fragment(acc[mi][ni], 0.0f);
                  ^
/opt/kbv/v/lib/python3.12/site-packages/nvidia/cu13/include/crt/mma.h(260): note #3327-D: candidate function template "nvcuda::wmma::fill_fragment" failed deduction
      static __attribute__((device)) __inline__ void fill_fragment(__frag_base<FragEleType, size, packed_size>& f,
                                                     ^

4 errors detected in the compilation of "/srv/jobs/1791601978486768049-3349698-0/build/fused_deconv_epilogue_v4/cuda.cu".
ninja: build stopped: subcommand failed.

```

The fastest correct solution so far (2.691x 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

torch.backends.cudnn.benchmark = True
torch.backends.cudnn.benchmark_limit = 0  # exhaustive cudnn algo search
torch.backends.cudnn.allow_tf32 = True
torch.backends.cuda.matmul.allow_tf32 = True

# Fused epilogue operating directly on the channels_last (NHWC) output of the
# transposed convolution. Since the epilogue is element-wise, the NHWC layout
# is irrelevant except for mapping a flat index -> channel for the bias add,
# which in NHWC is simply (flat_idx % C). This kernel fuses:
#   bias add -> Mish -> add_value -> Hardtanh -> scale
# eliminating ATen's separate bias pass and cudnn's NHWC->NCHW transpose.
fused_epilogue_source = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda_runtime.h>

__device__ __forceinline__ float epilogue(float v, float b, float add_value, float scale) {
    float x = v + b;
    // mish(x) = x * tanh(softplus(x)) = x * u / (u + 2), u = t*(t+2), t = exp(x)
    float t = expf(fminf(x, 20.0f));
    float u = t * (t + 2.0f);
    float m = x * (u / (u + 2.0f));
    float y = m + add_value;
    y = fminf(fmaxf(y, -1.0f), 1.0f);  // hardtanh in [-1, 1]
    return y * scale;
}

// Vectorized path (requires numel % 4 == 0 and C % 4 == 0): each float4 spans
// 4 consecutive channels in NHWC, so the bias is also read as an aligned float4.
__global__ void fused_epilogue_nhwc_vec4_kernel(const float4* __restrict__ in,
                                                float4* __restrict__ out,
                                                const float* __restrict__ bias,
                                                long n4, long c4,
                                                float add_value, float scale) {
    long stride = (long)gridDim.x * blockDim.x;
    for (long v = (long)blockIdx.x * blockDim.x + threadIdx.x; v < n4; v += stride) {
        long cbase = (v % c4) << 2;
        float4 b = *reinterpret_cast<const float4*>(bias + cbase);
        float4 val = in[v];
        float4 r;
        r.x = epilogue(val.x, b.x, add_value, scale);
        r.y = epilogue(val.y, b.y, add_value, scale);
        r.z = epilogue(val.z, b.z, add_value, scale);
        r.w = epilogue(val.w, b.w, add_value, scale);
        out[v] = r;
    }
}

// Generic fallback path.
__global__ void fused_epilogue_nhwc_kernel(const float* __restrict__ in,
                                           float* __restrict__ out,
                                           const float* __restrict__ bias,
                                           long n, long C,
                                           float add_value, float scale) {
    long stride = (long)gridDim.x * blockDim.x;
    for (long i = (long)blockIdx.x * blockDim.x + threadIdx.x; i < n; i += stride) {
        long c = i % C;
        out[i] = epilogue(in[i], bias[c], add_value, scale);
    }
}

torch::Tensor fused_epilogue_nhwc_cuda(torch::Tensor x, torch::Tensor bias, double add_value, double scale) {
    TORCH_CHECK(x.is_cuda(), "x must be a CUDA tensor");
    TORCH_CHECK(x.scalar_type() == torch::kFloat32, "x must be float32");
    TORCH_CHECK(x.is_contiguous(at::MemoryFormat::ChannelsLast), "x must be channels_last contiguous");
    TORCH_CHECK(bias.is_cuda() && bias.scalar_type() == torch::kFloat32, "bias must be CUDA float32");

    auto b = bias.contiguous();
    const long C = x.size(1);
    TORCH_CHECK(b.numel() == C, "bias size mismatch");

    auto out = torch::empty_like(x);  // preserves channels_last layout
    const long n = x.numel();
    if (n == 0) return out;

    auto stream = at::cuda::getCurrentCUDAStream();
    const int block = 256;

    if ((n % 4 == 0) && (C % 4 == 0)) {
        const long n4 = n >> 2;
        long blocks = (n4 + block - 1) / block;
        if (blocks > 2147483647L) blocks = 2147483647L;
        fused_epilogue_nhwc_vec4_kernel<<<(unsigned int)blocks, block, 0, stream>>>(
            reinterpret_cast<const float4*>(x.data_ptr<float>()),
            reinterpret_cast<float4*>(out.data_ptr<float>()),
            b.data_ptr<float>(), n4, C >> 2,
            (float)add_value, (float)scale);
    } else {
        long blocks = (n + block - 1) / block;
        if (blocks > 2147483647L) blocks = 2147483647L;
        fused_epilogue_nhwc_kernel<<<(unsigned int)blocks, block, 0, stream>>>(
            x.data_ptr<float>(), out.data_ptr<float>(), b.data_ptr<float>(),
            n, C, (float)add_value, (float)scale);
    }
    return out;
}
"""

fused_epilogue_cpp_source = (
    "torch::Tensor fused_epilogue_nhwc_cuda(torch::Tensor x, torch::Tensor bias, double add_value, double scale);"
)

fused_epilogue = load_inline(
    name="fused_bias_mish_add_hardtanh_scale_nhwc_v2",
    cpp_sources=fused_epilogue_cpp_source,
    cuda_sources=fused_epilogue_source,
    functions=["fused_epilogue_nhwc_cuda"],
    verbose=False,
    extra_cuda_cflags=["-O3"],
)


class ModelNew(nn.Module):
    """
    Optimized model:
      * Runs the transposed convolution in channels_last so cudnn's fast NHWC
        dgrad GEMM is used without the expensive NHWC->NCHW output transpose.
      * Calls F.conv_transpose2d with bias=None and folds the bias into a
        single fused CUDA epilogue (bias + Mish + add + Hardtanh + scale),
        removing ATen's separate bias-add pass and three memory round-trips.
      * The conv_transpose module (incl. its bias parameter) is kept intact so
        the state_dict remains identical to the reference model.
    """
    def __init__(self, in_channels, out_channels, kernel_size, stride, padding, output_padding, add_value, scale):
        super(ModelNew, self).__init__()
        self.conv_transpose = nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride, padding, output_padding)
        self.add_value = add_value
        self.scale = scale
        self.fused_epilogue = fused_epilogue

    def forward(self, x):
        x = x.contiguous(memory_format=torch.channels_last)
        y = F.conv_transpose2d(
            x,
            self.conv_transpose.weight,
            None,  # bias folded into the fused epilogue
            self.conv_transpose.stride,
            self.conv_transpose.padding,
            self.conv_transpose.output_padding,
            self.conv_transpose.groups,
            self.conv_transpose.dilation,
        )
        y = y.contiguous(memory_format=torch.channels_last)
        bias = self.conv_transpose.bias
        if bias is None:
            bias = torch.zeros(y.size(1), device=y.device, dtype=y.dtype)
        y = self.fused_epilogue.fused_epilogue_nhwc_cuda(y, bias, self.add_value, self.scale)
        return y
```

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.
