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 convolution, applies HardSwish, and then ReLU.
    """
    def __init__(self, in_channels, out_channels, kernel_size):
        super(Model, self).__init__()
        self.conv = nn.Conv2d(in_channels, out_channels, kernel_size)

    def forward(self, x):
        """
        Args:
            x (torch.Tensor): Input tensor of shape (batch_size, in_channels, height, width).

        Returns:
            torch.Tensor: Output tensor of shape (batch_size, out_channels, height, width).
        """
        x = self.conv(x)
        x = torch.nn.functional.hardswish(x)
        x = torch.relu(x)
        return x

batch_size = 128
in_channels = 8
out_channels = 64
height, width = 128, 128
kernel_size = 3

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

def get_init_inputs():
    return [in_channels, out_channels, kernel_size]
    ```
    
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
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.cpp_extension import load_inline


_cpp_source = r"""
#include <torch/extension.h>
torch::Tensor bias_hardswish_relu_(torch::Tensor x, torch::Tensor bias);
"""

_cuda_source = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAGuard.h>
#include <c10/cuda/CUDAException.h>
#include <cuda_runtime.h>
#include <algorithm>
#include <cstdint>

__device__ __forceinline__ float activate(float x, float b) {
    x += b;
    if (x <= 0.0f) return 0.0f;
    if (x >= 3.0f) return x;
    return (x * (x + 3.0f)) / 6.0f;
}

__device__ __forceinline__ float4 activate4(float4 v, const float4 b) {
    v.x = activate(v.x, b.x);
    v.y = activate(v.y, b.y);
    v.z = activate(v.z, b.z);
    v.w = activate(v.w, b.w);
    return v;
}

__global__ void fused_64_inplace(
    float4* __restrict__ data,
    const float4* __restrict__ bias,
    int64_t count
) {
    constexpr int THREADS = 256;
    constexpr int UNROLL = 4;
    const float4 b = bias[threadIdx.x & 15];
    const int64_t stride = (int64_t)gridDim.x * THREADS * UNROLL;

    for (int64_t base =
             (int64_t)blockIdx.x * THREADS * UNROLL + threadIdx.x;
         base < count; base += stride) {
        if (base + 3 * THREADS < count) {
            float4 v0 = data[base];
            float4 v1 = data[base + THREADS];
            float4 v2 = data[base + 2 * THREADS];
            float4 v3 = data[base + 3 * THREADS];

            v0 = activate4(v0, b);
            v1 = activate4(v1, b);
            v2 = activate4(v2, b);
            v3 = activate4(v3, b);

            data[base] = v0;
            data[base + THREADS] = v1;
            data[base + 2 * THREADS] = v2;
            data[base + 3 * THREADS] = v3;
        } else {
            #pragma unroll
            for (int k = 0; k < UNROLL; ++k) {
                const int64_t i = base + k * THREADS;
                if (i < count)
                    data[i] = activate4(data[i], b);
            }
        }
    }
}

__global__ void fused_vector_inplace(
    float4* __restrict__ data,
    const float4* __restrict__ bias,
    int64_t count,
    int channel_vectors
) {
    const int64_t stride = (int64_t)blockDim.x * gridDim.x;
    for (int64_t i = (int64_t)blockIdx.x * blockDim.x + threadIdx.x;
         i < count; i += stride) {
        data[i] = activate4(data[i], bias[i % channel_vectors]);
    }
}

__global__ void fused_scalar_inplace(
    float* __restrict__ data,
    const float* __restrict__ bias,
    int64_t count,
    int channels
) {
    const int64_t stride = (int64_t)blockDim.x * gridDim.x;
    for (int64_t i = (int64_t)blockIdx.x * blockDim.x + threadIdx.x;
         i < count; i += stride) {
        data[i] = activate(data[i], bias[i % channels]);
    }
}

torch::Tensor bias_hardswish_relu_(torch::Tensor x, torch::Tensor bias) {
    TORCH_CHECK(x.is_cuda() && bias.is_cuda(), "Expected CUDA tensors");
    TORCH_CHECK(x.device() == bias.device(), "Device mismatch");
    TORCH_CHECK(x.scalar_type() == at::kFloat &&
                bias.scalar_type() == at::kFloat, "Expected float32");
    TORCH_CHECK(x.dim() == 4 &&
                x.is_contiguous(at::MemoryFormat::ChannelsLast),
                "Expected channels-last tensor");
    TORCH_CHECK(bias.dim() == 1 && bias.is_contiguous() &&
                bias.numel() == x.size(1), "Invalid bias");

    const c10::cuda::CUDAGuard guard(x.device());
    const int64_t count = x.numel();
    if (count == 0) return x;

    const int channels = static_cast<int>(x.size(1));
    constexpr int threads = 256;
    const auto stream = at::cuda::getCurrentCUDAStream();

    const bool aligned =
        reinterpret_cast<uintptr_t>(x.data_ptr<float>()) % 16 == 0 &&
        reinterpret_cast<uintptr_t>(bias.data_ptr<float>()) % 16 == 0;

    if (channels % 4 == 0 && aligned) {
        const int64_t vectors = count / 4;
        auto* data = reinterpret_cast<float4*>(x.data_ptr<float>());
        const auto* b =
            reinterpret_cast<const float4*>(bias.data_ptr<float>());

        if (channels == 64) {
            const int blocks = static_cast<int>(
                std::min<int64_t>((vectors + 1023) / 1024, 4096));
            fused_64_inplace<<<blocks, threads, 0, stream>>>(
                data, b, vectors);
        } else {
            const int blocks = static_cast<int>(
                std::min<int64_t>((vectors + threads - 1) / threads, 4096));
            fused_vector_inplace<<<blocks, threads, 0, stream>>>(
                data, b, vectors, channels / 4);
        }
    } else {
        const int blocks = static_cast<int>(
            std::min<int64_t>((count + threads - 1) / threads, 4096));
        fused_scalar_inplace<<<blocks, threads, 0, stream>>>(
            x.data_ptr<float>(), bias.data_ptr<float>(), count, channels);
    }

    C10_CUDA_KERNEL_LAUNCH_CHECK();
    return x;
}
"""

_fused_ops = load_inline(
    name="conv_bias_hardswish_relu_nhwc_inplace_v4",
    cpp_sources=_cpp_source,
    cuda_sources=_cuda_source,
    functions=["bias_hardswish_relu_"],
    extra_cflags=["-O3"],
    extra_cuda_cflags=["-O3"],
    verbose=False,
)


class _BiasHardSwishReLUInplace(torch.autograd.Function):
    @staticmethod
    def forward(ctx, x, bias):
        ctx.mark_dirty(x)
        result = _fused_ops.bias_hardswish_relu_(x, bias)
        if ctx.needs_input_grad[0] or ctx.needs_input_grad[1]:
            ctx.save_for_backward(result)
        return result

    @staticmethod
    def backward(ctx, grad_output):
        (output,) = ctx.saved_tensors
        # For 0 < z <= 3, y = z(z + 3)/6, so
        # dy/dz = sqrt(1/4 + 2y/3).
        slope = torch.where(
            output <= 0,
            torch.zeros_like(output),
            torch.where(
                output <= 3,
                torch.sqrt(output * (2.0 / 3.0) + 0.25),
                torch.ones_like(output),
            ),
        )
        grad = grad_output * slope
        return (
            grad if ctx.needs_input_grad[0] else None,
            grad.sum((0, 2, 3)) if ctx.needs_input_grad[1] else None,
        )


class ModelNew(nn.Module):
    def __init__(self, in_channels, out_channels, kernel_size):
        super().__init__()
        self.conv = nn.Conv2d(in_channels, out_channels, kernel_size)
        self.conv.to(memory_format=torch.channels_last)

    def forward(self, x):
        if (
            not x.is_cuda
            or x.ndim != 4
            or x.dtype != torch.float32
            or self.conv.weight.dtype != torch.float32
            or self.conv.bias is None
            or self.conv.bias.dtype != torch.float32
            or torch.is_autocast_enabled()
        ):
            return F.relu(F.hardswish(self.conv(x)))

        x = x.contiguous(memory_format=torch.channels_last)
        y = F.conv2d(
            x,
            self.conv.weight,
            None,
            self.conv.stride,
            self.conv.padding,
            self.conv.dilation,
            self.conv.groups,
        )

        if not y.is_contiguous(memory_format=torch.channels_last):
            return F.relu(
                F.hardswish(y + self.conv.bias.view(1, -1, 1, 1))
            )

        if torch.is_grad_enabled() and (
            y.requires_grad or self.conv.bias.requires_grad
        ):
            return _BiasHardSwishReLUInplace.apply(y, self.conv.bias)

        return _fused_ops.bias_hardswish_relu_(y, self.conv.bias)
```
Result of evaluating it:
The solution is correct on the test inputs. Mean runtime 1.62 ms; the PyTorch reference (with TF32 enabled) takes 4.84 ms; speedup 2.988x.
Profiler, top device kernels of one forward pass of your solution:
| device kernel | total device time (us) | calls |
|---|---|---|
| fused_64_inplace(float4*, float4 const*, long) | 768.5 | 1 |
| sm80_xmma_fprop_implicit_gemm_indexed_wo_smem_tf32f32_tf32f32_f32_nhwckrsc_nhwc_tilesize12 | 597.9 | 1 |
| void at::native::elementwise_kernel<128, 2, at::native::gpu_kernel_impl_nocast<at::native: | 114.3 | 1 |
| void cudnn::engines_precompiled::convertTensor_kernel<float, float, float, (cudnnKernelDat | 110.7 | 2 |

The fastest correct solution so far (3.006x speedup) is:
```python
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.cpp_extension import load_inline


_cpp_source = r"""
#include <torch/extension.h>
torch::Tensor bias_hardswish_relu_nhwc(torch::Tensor x, torch::Tensor bias);
"""

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

__device__ __forceinline__ float activate(float x, float b) {
    x += b;
    float y = (x * fminf(fmaxf(x + 3.0f, 0.0f), 6.0f)) / 6.0f;
    return y < 0.0f ? 0.0f : y;
}

template<int FixedChannelVectors>
__global__ void fused_nhwc_vector(
    const float4* __restrict__ input,
    const float4* __restrict__ bias,
    float4* __restrict__ output,
    int64_t count,
    int channel_vectors
) {
    const int cv = FixedChannelVectors > 0
        ? FixedChannelVectors : channel_vectors;
    const int64_t stride = (int64_t)blockDim.x * gridDim.x;

    for (int64_t i = (int64_t)blockIdx.x * blockDim.x + threadIdx.x;
         i < count; i += stride) {
        float4 v = input[i];
        const float4 b = bias[i % cv];
        v.x = activate(v.x, b.x);
        v.y = activate(v.y, b.y);
        v.z = activate(v.z, b.z);
        v.w = activate(v.w, b.w);
        output[i] = v;
    }
}

__global__ void fused_nhwc_scalar(
    const float* __restrict__ input,
    const float* __restrict__ bias,
    float* __restrict__ output,
    int64_t count,
    int channels
) {
    const int64_t stride = (int64_t)blockDim.x * gridDim.x;
    for (int64_t i = (int64_t)blockIdx.x * blockDim.x + threadIdx.x;
         i < count; i += stride) {
        output[i] = activate(input[i], bias[i % channels]);
    }
}

torch::Tensor bias_hardswish_relu_nhwc(
    torch::Tensor x, torch::Tensor bias
) {
    TORCH_CHECK(x.is_cuda() && bias.is_cuda(), "Expected CUDA tensors");
    TORCH_CHECK(x.device() == bias.device(), "Device mismatch");
    TORCH_CHECK(x.scalar_type() == at::kFloat &&
                bias.scalar_type() == at::kFloat, "Expected float32");
    TORCH_CHECK(x.dim() == 4 &&
                x.is_contiguous(at::MemoryFormat::ChannelsLast),
                "Expected channels-last tensor");
    TORCH_CHECK(bias.dim() == 1 && bias.is_contiguous() &&
                bias.numel() == x.size(1), "Invalid bias");

    const c10::cuda::CUDAGuard guard(x.device());
    auto output = torch::empty_like(x);
    const int64_t count = x.numel();
    if (count == 0) return output;

    const int channels = static_cast<int>(x.size(1));
    constexpr int threads = 256;
    auto stream = at::cuda::getCurrentCUDAStream();

    if (channels % 4 == 0) {
        const int64_t vectors = count / 4;
        const int blocks = static_cast<int>(
            std::min<int64_t>((vectors + threads - 1) / threads, 4096));
        const float4* input_ptr =
            reinterpret_cast<const float4*>(x.data_ptr<float>());
        const float4* bias_ptr =
            reinterpret_cast<const float4*>(bias.data_ptr<float>());
        float4* output_ptr =
            reinterpret_cast<float4*>(output.data_ptr<float>());

        if (channels == 64) {
            fused_nhwc_vector<16><<<blocks, threads, 0, stream>>>(
                input_ptr, bias_ptr, output_ptr, vectors, 16);
        } else {
            fused_nhwc_vector<0><<<blocks, threads, 0, stream>>>(
                input_ptr, bias_ptr, output_ptr, vectors, channels / 4);
        }
    } else {
        const int blocks = static_cast<int>(
            std::min<int64_t>((count + threads - 1) / threads, 4096));
        fused_nhwc_scalar<<<blocks, threads, 0, stream>>>(
            x.data_ptr<float>(), bias.data_ptr<float>(),
            output.data_ptr<float>(), count, channels);
    }

    C10_CUDA_KERNEL_LAUNCH_CHECK();
    return output;
}
"""

_fused_ops = load_inline(
    name="conv_bias_hardswish_relu_nhwc_v3",
    cpp_sources=_cpp_source,
    cuda_sources=_cuda_source,
    functions=["bias_hardswish_relu_nhwc"],
    extra_cflags=["-O3"],
    extra_cuda_cflags=["-O3"],
    verbose=False,
)


class _BiasHardSwishReLU(torch.autograd.Function):
    @staticmethod
    def forward(ctx, x, bias):
        if ctx.needs_input_grad[0] or ctx.needs_input_grad[1]:
            ctx.save_for_backward(x, bias)
        return _fused_ops.bias_hardswish_relu_nhwc(x, bias)

    @staticmethod
    def backward(ctx, grad_output):
        x, bias = ctx.saved_tensors
        z = x + bias.view(1, -1, 1, 1)
        slope = torch.where(
            z <= 0,
            torch.zeros_like(z),
            torch.where(z <= 3, z / 3 + 0.5, torch.ones_like(z)),
        )
        grad = grad_output * slope
        return (
            grad if ctx.needs_input_grad[0] else None,
            grad.sum((0, 2, 3)) if ctx.needs_input_grad[1] else None,
        )


class ModelNew(nn.Module):
    def __init__(self, in_channels, out_channels, kernel_size):
        super().__init__()
        self.conv = nn.Conv2d(in_channels, out_channels, kernel_size)
        self.conv.to(memory_format=torch.channels_last)

    def forward(self, x):
        use_custom = (
            x.is_cuda
            and x.ndim == 4
            and x.dtype == torch.float32
            and self.conv.weight.dtype == torch.float32
            and self.conv.bias.dtype == torch.float32
            and not torch.is_autocast_enabled()
        )
        if not use_custom:
            return F.relu(F.hardswish(self.conv(x)))

        x = x.contiguous(memory_format=torch.channels_last)
        y = F.conv2d(
            x,
            self.conv.weight,
            None,
            self.conv.stride,
            self.conv.padding,
            self.conv.dilation,
            self.conv.groups,
        )
        if y.is_contiguous(memory_format=torch.channels_last):
            return _BiasHardSwishReLU.apply(y, self.conv.bias)

        return F.relu(
            F.hardswish(y + self.conv.bias.view(1, -1, 1, 1))
        )
```

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.
