```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

# Let cuDNN pick the fastest algorithm for the transposed convolution.
torch.backends.cudnn.benchmark = True

# Fused epilogue kernel: Mish -> Add -> Hardtanh -> Scale in a single pass.
# This collapses 4 memory-bound elementwise kernels (each reading+writing the
# full activation tensor) into one kernel, drastically cutting global memory
# traffic. Vectorized float4 loads/stores are used when possible.
_fused_cuda_src = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda_runtime.h>
#include <cstdint>

namespace {

__device__ __forceinline__ float epilogue(float x, float add_value, float scale) {
    // Mish: x * tanh(softplus(x)), softplus with numerically stable threshold
    float sp = (x > 20.0f) ? x : log1pf(expf(x));
    float v = x * tanhf(sp);
    // Add scalar
    v = v + add_value;
    // Hardtanh in [-1, 1]
    v = fminf(fmaxf(v, -1.0f), 1.0f);
    // Scale
    return v * scale;
}

__global__ void epilogue_vec4_kernel(const float4* __restrict__ in,
                                     float4* __restrict__ out,
                                     int n4, float add_value, float scale) {
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    if (idx < n4) {
        float4 v = in[idx];
        v.x = epilogue(v.x, add_value, scale);
        v.y = epilogue(v.y, add_value, scale);
        v.z = epilogue(v.z, add_value, scale);
        v.w = epilogue(v.w, add_value, scale);
        out[idx] = v;
    }
}

__global__ void epilogue_kernel(const float* __restrict__ in,
                                float* __restrict__ out,
                                long n, float add_value, float scale) {
    long idx = (long)blockIdx.x * blockDim.x + threadIdx.x;
    if (idx < n) {
        out[idx] = epilogue(in[idx], add_value, scale);
    }
}

} // namespace

torch::Tensor fused_mish_add_hardtanh_scale(torch::Tensor x, double add_value, double scale) {
    TORCH_CHECK(x.is_cuda(), "input must be a CUDA tensor");
    TORCH_CHECK(x.scalar_type() == at::kFloat, "input must be float32");

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

    const float av = static_cast<float>(add_value);
    const float sc = static_cast<float>(scale);
    const int threads = 256;
    cudaStream_t stream = at::cuda::getCurrentCUDAStream();

    const float* in_ptr = xc.data_ptr<float>();
    float* out_ptr = out.data_ptr<float>();

    const bool aligned =
        ((reinterpret_cast<uintptr_t>(in_ptr) & 15) == 0) &&
        ((reinterpret_cast<uintptr_t>(out_ptr) & 15) == 0);

    if ((n & 3) == 0 && aligned) {
        const long n4 = n >> 2;
        const long blocks = (n4 + threads - 1) / threads;
        epilogue_vec4_kernel<<<(unsigned int)blocks, threads, 0, stream>>>(
            reinterpret_cast<const float4*>(in_ptr),
            reinterpret_cast<float4*>(out_ptr),
            static_cast<int>(n4), av, sc);
    } else {
        const long blocks = (n + threads - 1) / threads;
        epilogue_kernel<<<(unsigned int)blocks, threads, 0, stream>>>(
            in_ptr, out_ptr, n, av, sc);
    }
    return out;
}
"""

_fused_cpp_src = "torch::Tensor fused_mish_add_hardtanh_scale(torch::Tensor x, double add_value, double scale);"

# Compile the fused epilogue CUDA kernel.
fused_ops = load_inline(
    name="fused_mish_add_hardtanh_scale",
    cpp_sources=_fused_cpp_src,
    cuda_sources=_fused_cuda_src,
    functions=["fused_mish_add_hardtanh_scale"],
    verbose=False,
    extra_cflags=["-O3"],
    extra_cuda_cflags=["-O3"],
)


class ModelNew(nn.Module):
    """
    Optimized model: ConvTranspose2d (cuDNN) followed by a single fused CUDA
    kernel performing Mish + add + Hardtanh + scaling in one memory pass.
    """
    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 = float(add_value)
        self.scale = float(scale)

    def forward(self, x):
        x = self.conv_transpose(x)
        if x.is_cuda and x.dtype == torch.float32:
            return fused_ops.fused_mish_add_hardtanh_scale(x, self.add_value, self.scale)
        # Fallback to the reference PyTorch implementation (e.g. on CPU).
        x = F.mish(x)
        x = x + self.add_value
        x = F.hardtanh(x, min_val=-1, max_val=1)
        x = x * self.scale
        return x
```