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

# Fused CUDA kernel for the element-wise epilogue:
#   out = relu((x - subtract_value) * multiply_value)
# This replaces 3 separate PyTorch kernels (sub, mul, relu) with a single pass.
fused_epilogue_source = """
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda_runtime.h>

__global__ void fused_sub_mul_relu_scalar_kernel(
    const float* __restrict__ in,
    float* __restrict__ out,
    float sub,
    float mul,
    long n) {
    long idx = blockIdx.x * (long)blockDim.x + threadIdx.x;
    if (idx < n) {
        float v = (in[idx] - sub) * mul;
        out[idx] = v > 0.0f ? v : 0.0f;
    }
}

// Vectorized (float4) version for better memory bandwidth utilization
__global__ void fused_sub_mul_relu_vec4_kernel(
    const float4* __restrict__ in,
    float4* __restrict__ out,
    float sub,
    float mul,
    long n4) {
    long idx = blockIdx.x * (long)blockDim.x + threadIdx.x;
    if (idx < n4) {
        float4 v = in[idx];
        v.x = fmaxf((v.x - sub) * mul, 0.0f);
        v.y = fmaxf((v.y - sub) * mul, 0.0f);
        v.z = fmaxf((v.z - sub) * mul, 0.0f);
        v.w = fmaxf((v.w - sub) * mul, 0.0f);
        out[idx] = v;
    }
}

torch::Tensor fused_sub_mul_relu_cuda(torch::Tensor x, double sub, double mul) {
    TORCH_CHECK(x.is_cuda(), "input must be a CUDA tensor");
    TORCH_CHECK(x.scalar_type() == torch::kFloat32, "input must be float32");
    TORCH_CHECK(x.is_contiguous(), "input must be contiguous");

    auto out = torch::empty_like(x);
    long n = (long)x.numel();
    const int block_size = 256;
    cudaStream_t stream = at::cuda::getCurrentCUDAStream();

    if (n % 4 == 0) {
        long n4 = n / 4;
        int num_blocks = (int)((n4 + block_size - 1) / block_size);
        fused_sub_mul_relu_vec4_kernel<<<num_blocks, block_size, 0, stream>>>(
            reinterpret_cast<const float4*>(x.data_ptr<float>()),
            reinterpret_cast<float4*>(out.data_ptr<float>()),
            (float)sub, (float)mul, n4);
    } else {
        int num_blocks = (int)((n + block_size - 1) / block_size);
        fused_sub_mul_relu_scalar_kernel<<<num_blocks, block_size, 0, stream>>>(
            x.data_ptr<float>(),
            out.data_ptr<float>(),
            (float)sub, (float)mul, n);
    }
    return out;
}
"""

fused_epilogue_cpp_source = (
    "torch::Tensor fused_sub_mul_relu_cuda(torch::Tensor x, double sub, double mul);"
)

# Compile the inline CUDA epilogue
fused_epilogue = load_inline(
    name="fused_sub_mul_relu",
    cpp_sources=fused_epilogue_cpp_source,
    cuda_sources=fused_epilogue_source,
    functions=["fused_sub_mul_relu_cuda"],
    verbose=False,
)


class ModelNew(nn.Module):
    """
    Optimized model: keeps the large GEMM on cuBLAS (nn.Linear), and replaces
    the subtract + multiply + ReLU chain with a single fused CUDA kernel.
    """
    def __init__(self, in_features, out_features, subtract_value, multiply_value):
        super(ModelNew, self).__init__()
        self.linear = nn.Linear(in_features, out_features)
        self.subtract_value = float(subtract_value)
        self.multiply_value = float(multiply_value)
        self.fused_epilogue = fused_epilogue

    def forward(self, x):
        x = self.linear(x)
        if x.is_cuda and x.dtype == torch.float32:
            return self.fused_epilogue.fused_sub_mul_relu_cuda(
                x.contiguous(), self.subtract_value, self.multiply_value)
        # Fallback for non-CUDA / non-float32 inputs
        x = x - self.subtract_value
        x = x * self.multiply_value
        return torch.relu(x)
```