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 6 of 6 for this task. Your previous solution (turn 5) 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

# Autotune conv algorithms (helps the generic fallback path) and allow TF32,
# matching the PyTorch reference configuration.
torch.backends.cudnn.benchmark = True
torch.backends.cudnn.benchmark_limit = 0
torch.backends.cudnn.allow_tf32 = True
torch.backends.cuda.matmul.allow_tf32 = True

# ---------------------------------------------------------------------------
# Fully fused Conv2d(3x3, stride 1, pad 0, Cin=8) + bias + HardSwish + ReLU.
#
# Direct convolution formulated as 9 tiny TF32 tensor-core GEMMs (one per
# kernel tap) using nvcuda::wmma 16x16x8 fragments. Each thread block computes
# an 8x32 tile of output pixels for all output channels:
#   - the input tile (10x34x8, zero-padded halo) is staged in shared memory
#     directly from NCHW global memory (channel pitch 12 keeps the fragment
#     loads bank-conflict free);
#   - weights are staged as [kh][kw][oc-tile][ic][16] with a padded pitch of
#     20 floats so weight-fragment loads are conflict-free as well;
#   - each warp owns one output row of 32 pixels and accumulates two 16-pixel
#     column tiles against all 16-channel tiles (6 fragment loads per 8 mma);
#   - the bias + HardSwish + ReLU epilogue is applied through a padded
#     column-major shared stage and written straight to NCHW global memory
#     with fully coalesced 128-byte store transactions.
#
# Only the input (67MB) is read and the final output (520MB) is written, once.
# ---------------------------------------------------------------------------
fused_cuda_source = r"""
#include <torch/extension.h>
#include <cuda_runtime.h>
#include <mma.h>

namespace wm = nvcuda::wmma;

#define TILE_W 32
#define TILE_H 8
#define CIN 8
#define PITCH 12            // input channel pitch (mult of 4 for tf32 wmma)
#define WPITCH 20           // padded weight-tile pitch (conflict-free)
#define SLD 36              // epilogue stage pitch (mult of 4, conflict-free)
#define MAX_NT 4            // supports up to 64 output channels
#define NTHREADS 256

__device__ __forceinline__ float bias_hs_relu(float x, float b) {
    x += b;
    float t = fminf(fmaxf(x + 3.0f, 0.0f), 6.0f);
    return fmaxf(x * t * 0.16666667163372039794921875f, 0.0f);
}

template <int NT>
__global__ void __launch_bounds__(NTHREADS) conv3x3_bias_hs_relu_kernel(
        const float* __restrict__ x,     // NCHW input
        const float* __restrict__ w,     // [C_out][8][3][3]
        const float* __restrict__ bias,  // [C_out]
        float* __restrict__ out,         // NCHW output
        int N, int H, int W, int C_out, int H_out, int W_out) {
    __shared__ float sm_in[(TILE_H + 2) * (TILE_W + 2) * PITCH];
    __shared__ float sm_w[9 * MAX_NT * CIN * WPITCH];
    __shared__ float stage[TILE_H][16 * SLD];
    __shared__ float sm_bias[MAX_NT * 16];

    const int n  = blockIdx.z;
    const int h0 = blockIdx.y * TILE_H;
    const int w0 = blockIdx.x * TILE_W;
    const int tid  = threadIdx.x;
    const int warp = tid >> 5;
    const int lane = tid & 31;

    // ---- stage input tile [hh][ww][c] with zero-padded halo ----
    const int WWt = TILE_W + 2;                    // 34
    const int HWt = (TILE_H + 2) * WWt;            // 340
    const int tile_elems = CIN * HWt;              // 2720
    const long xbase = (long)n * CIN * H * W;
    for (int idx = tid; idx < tile_elems; idx += NTHREADS) {
        int c  = idx / HWt;
        int r  = idx - c * HWt;
        int hh = r / WWt;
        int ww = r - hh * WWt;
        int h = h0 + hh;
        int w = w0 + ww;
        float v = 0.0f;
        if ((unsigned)h < (unsigned)H && (unsigned)w < (unsigned)W) {
            v = x[xbase + ((long)c * H + h) * W + w];
        }
        sm_in[(hh * WWt + ww) * PITCH + c] = v;
    }

    // ---- stage weights into padded [kh][kw][oc16][ic][16] tiles ----
    // Iterate in the natural global order so global reads stay coalesced.
    const int w_elems = C_out * 72;
    for (int idx = tid; idx < w_elems; idx += NTHREADS) {
        int kw = idx % 3;
        int t  = idx / 3;
        int kh = t % 3;
        t /= 3;
        int ic = t & 7;
        int oc = t >> 3;
        sm_w[(((kh * 3 + kw) * NT + (oc >> 4)) * CIN + ic) * WPITCH + (oc & 15)] = w[idx];
    }
    if (tid < C_out) sm_bias[tid] = bias[tid];
    __syncthreads();

    const int h = h0 + warp;   // output row owned by this warp
    if (h >= H_out) return;

    wm::fragment<wm::accumulator, 16, 16, 8, float> acc[2][NT];
    #pragma unroll
    for (int t2 = 0; t2 < 2; ++t2)
        #pragma unroll
        for (int j = 0; j < NT; ++j) wm::fill_fragment(acc[t2][j], 0.0f);

    // direct conv as 9 tensor-core GEMMs (M=32 pixels, N=16ch tiles, K=8)
    #pragma unroll
    for (int kh = 0; kh < 3; ++kh) {
        #pragma unroll
        for (int kw = 0; kw < 3; ++kw) {
            const float* a_ptr = &sm_in[((warp + kh) * WWt + kw) * PITCH];
            wm::fragment<wm::matrix_a, 16, 16, 8, wm::precision::tf32, wm::row_major> a0, a1;
            wm::load_matrix_sync(a0, a_ptr, PITCH);
            wm::load_matrix_sync(a1, a_ptr + 16 * PITCH, PITCH);
            #pragma unroll
            for (int j = 0; j < NT; ++j) {
                wm::fragment<wm::matrix_b, 16, 16, 8, wm::precision::tf32, wm::row_major> b;
                wm::load_matrix_sync(b, &sm_w[((kh * 3 + kw) * NT + j) * CIN * WPITCH], WPITCH);
                wm::mma_sync(acc[0][j], a0, b, acc[0][j]);
                wm::mma_sync(acc[1][j], a1, b, acc[1][j]);
            }
        }
    }

    // ---- fused bias + HardSwish + ReLU epilogue, store NCHW ----
    const long HWo = (long)H_out * W_out;
    const long obase = ((long)n * C_out * H_out + h) * W_out + w0;
    float* stg = stage[warp];
    const bool full32 = (w0 + TILE_W) <= W_out;

    if (full32) {
        // fast path: all 32 pixels of this warp's row are valid
        #pragma unroll
        for (int j = 0; j < NT; ++j) {
            wm::store_matrix_sync(stg,      acc[0][j], SLD, wm::mem_col_major);
            wm::store_matrix_sync(stg + 16, acc[1][j], SLD, wm::mem_col_major);
            __syncwarp();
            #pragma unroll
            for (int i = 0; i < 16; ++i) {
                const int c  = j * 16 + i;
                const float b = sm_bias[c];
                const float* srow = stg + i * SLD;
                float v0 = bias_hs_relu(srow[lane],      b);
                float v1 = bias_hs_relu(srow[lane + 8],  b);
                float v2 = bias_hs_relu(srow[lane + 16], b);
                float v3 = bias_hs_relu(srow[lane + 24], b);
                float* op = out + obase + (long)c * HWo;
                op[lane]      = v0;
                op[lane + 8]  = v1;
                op[lane + 16] = v2;
                op[lane + 24] = v3;
            }
            __syncwarp();
        }
    } else {
        // edge path: predicate every pixel
        const int rem = W_out - w0;   // 1..31
        #pragma unroll
        for (int j = 0; j < NT; ++j) {
            wm::store_matrix_sync(stg,      acc[0][j], SLD, wm::mem_col_major);
            wm::store_matrix_sync(stg + 16, acc[1][j], SLD, wm::mem_col_major);
            __syncwarp();
            #pragma unroll
            for (int i = 0; i < 16; ++i) {
                const int c  = j * 16 + i;
                const float b = sm_bias[c];
                const float* srow = stg + i * SLD;
                float* op = out + obase + (long)c * HWo;
                if (lane      < rem) op[lane]      = bias_hs_relu(srow[lane],      b);
                if (lane + 8  < rem) op[lane + 8]  = bias_hs_relu(srow[lane + 8],  b);
                if (lane + 16 < rem) op[lane + 16] = bias_hs_relu(srow[lane + 16], b);
                if (lane + 24 < rem) op[lane + 24] = bias_hs_relu(srow[lane + 24], b);
            }
            __syncwarp();
        }
    }
}

torch::Tensor conv3x3_bias_hs_relu_cuda(torch::Tensor x, torch::Tensor w, torch::Tensor b) {
    TORCH_CHECK(x.is_cuda() && w.is_cuda() && b.is_cuda(), "inputs must be CUDA");
    TORCH_CHECK(x.scalar_type() == torch::kFloat32, "float32 only");
    TORCH_CHECK(x.dim() == 4 && w.dim() == 4, "bad dims");

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

    const int N     = (int)xc.size(0);
    const int C_in  = (int)xc.size(1);
    const int H     = (int)xc.size(2);
    const int W     = (int)xc.size(3);
    const int C_out = (int)wc.size(0);
    const int H_out = H - 2;
    const int W_out = W - 2;

    TORCH_CHECK(C_in == CIN, "fused kernel needs in_channels == 8");
    TORCH_CHECK((C_out % 16) == 0 && C_out >= 16 && C_out <= MAX_NT * 16,
                "fused kernel needs out_channels in {16,32,48,64}");
    TORCH_CHECK(H_out > 0 && W_out > 0, "bad spatial size");

    auto out = torch::empty({N, C_out, H_out, W_out}, xc.options());
    if (out.numel() == 0) return out;

    dim3 grid((unsigned)((W_out + TILE_W - 1) / TILE_W),
              (unsigned)((H_out + TILE_H - 1) / TILE_H),
              (unsigned)N);
    dim3 block(NTHREADS);

    const float* xp = xc.data_ptr<float>();
    const float* wp = wc.data_ptr<float>();
    const float* bp = bc.data_ptr<float>();
    float* op = out.data_ptr<float>();

    switch (C_out / 16) {
        case 1:
            conv3x3_bias_hs_relu_kernel<1><<<grid, block>>>(xp, wp, bp, op, N, H, W, C_out, H_out, W_out);
            break;
        case 2:
            conv3x3_bias_hs_relu_kernel<2><<<grid, block>>>(xp, wp, bp, op, N, H, W, C_out, H_out, W_out);
            break;
        case 3:
            conv3x3_bias_hs_relu_kernel<3><<<grid, block>>>(xp, wp, bp, op, N, H, W, C_out, H_out, W_out);
            break;
        case 4:
            conv3x3_bias_hs_relu_kernel<4><<<grid, block>>>(xp, wp, bp, op, N, H, W, C_out, H_out, W_out);
            break;
        default:
            TORCH_CHECK(false, "unsupported out_channels");
    }
    return out;
}

// ---------------------------------------------------------------------------
// Generic fallback epilogue: bias + HardSwish + ReLU in a single memory pass
// (used when the fully fused conv kernel's shape constraints are not met).
// ---------------------------------------------------------------------------
__global__ void __launch_bounds__(256) bias_hs_relu_vec_kernel(
        const float4* __restrict__ in,
        float4* __restrict__ out,
        const float* __restrict__ bias,
        int hw4, int C) {
    int plane = blockIdx.y;
    float b = __ldg(bias + (plane % C));
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    if (idx < hw4) {
        long off = (long)plane * hw4 + idx;
        float4 v = in[off];
        v.x = bias_hs_relu(v.x, b);
        v.y = bias_hs_relu(v.y, b);
        v.z = bias_hs_relu(v.z, b);
        v.w = bias_hs_relu(v.w, b);
        out[off] = v;
    }
}

__global__ void __launch_bounds__(256) bias_hs_relu_scalar_kernel(
        const float* __restrict__ in,
        float* __restrict__ out,
        const float* __restrict__ bias,
        int hw, int C) {
    int plane = blockIdx.y;
    float b = __ldg(bias + (plane % C));
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    if (idx < hw) {
        long off = (long)plane * hw + idx;
        out[off] = bias_hs_relu(in[off], b);
    }
}

torch::Tensor bias_hardswish_relu_cuda(torch::Tensor x, torch::Tensor bias) {
    TORCH_CHECK(x.is_cuda() && bias.is_cuda(), "inputs must be CUDA tensors");
    TORCH_CHECK(x.scalar_type() == torch::kFloat32, "input must be float32");
    TORCH_CHECK(x.dim() == 4, "expected NCHW 4D input");

    auto xc = x.contiguous();
    auto out = torch::empty_like(xc);
    if (xc.numel() == 0) return out;

    const long C  = xc.size(1);
    const long HW = xc.size(2) * xc.size(3);
    const long planes = xc.size(0) * C;
    TORCH_CHECK(planes <= 65535, "too many planes for grid.y");

    const int block = 256;
    const float* in_ptr = xc.data_ptr<float>();
    float* out_ptr      = out.data_ptr<float>();
    const float* b_ptr  = bias.data_ptr<float>();

    dim3 grid;
    grid.y = (unsigned)planes;
    if ((HW & 3) == 0) {
        int hw4 = (int)(HW >> 2);
        grid.x = (unsigned)((hw4 + block - 1) / block);
        bias_hs_relu_vec_kernel<<<grid, block>>>(
            reinterpret_cast<const float4*>(in_ptr),
            reinterpret_cast<float4*>(out_ptr),
            b_ptr, hw4, (int)C);
    } else {
        grid.x = (unsigned)((HW + block - 1) / block);
        bias_hs_relu_scalar_kernel<<<grid, block>>>(
            in_ptr, out_ptr, b_ptr, (int)HW, (int)C);
    }
    return out;
}
"""

fused_cpp_source = (
    "torch::Tensor conv3x3_bias_hs_relu_cuda(torch::Tensor x, torch::Tensor w, torch::Tensor b);\n"
    "torch::Tensor bias_hardswish_relu_cuda(torch::Tensor x, torch::Tensor bias);"
)

fused_ops = load_inline(
    name="fused_conv3x3_bias_hardswish_relu_v3",
    cpp_sources=fused_cpp_source,
    cuda_sources=fused_cuda_source,
    functions=["conv3x3_bias_hs_relu_cuda", "bias_hardswish_relu_cuda"],
    verbose=False,
    extra_cflags=["-O3"],
    extra_cuda_cflags=["-O3", "--use_fast_math"],
)


class ModelNew(nn.Module):
    """
    Optimized model:
      Fast path (Cin=8, 3x3 stride-1 pad-0 conv, Cout in {16,32,48,64}):
        a single fully fused CUDA kernel performing the convolution with TF32
        tensor cores plus the bias + HardSwish + ReLU epilogue, reading the
        input and writing the final output exactly once (no intermediate
        activations, no layout-transform passes). Each warp computes a full
        32-pixel output row against all output channels for a high
        mma-to-fragment-load ratio and fully coalesced 128B stores.
      Fallback path: cudnn conv (no bias) + fused epilogue kernel.
    """

    def __init__(self, in_channels, out_channels, kernel_size):
        super(ModelNew, 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).
        """
        c = self.conv
        if (
            x.is_cuda
            and x.dtype == torch.float32
            and c.bias is not None
            and c.groups == 1
            and c.stride == (1, 1)
            and c.padding == (0, 0)
            and c.dilation == (1, 1)
            and c.kernel_size == (3, 3)
            and c.in_channels == 8
            and (c.out_channels % 16) == 0
            and 16 <= c.out_channels <= 64
            and x.size(0) <= 65535
            and x.size(2) >= 3
            and x.size(3) >= 3
        ):
            return fused_ops.conv3x3_bias_hs_relu_cuda(x, c.weight, c.bias)

        y = F.conv2d(x, c.weight, None, c.stride, c.padding, c.dilation, c.groups)
        if y.is_cuda and y.dtype == torch.float32 and c.bias is not None:
            return fused_ops.bias_hardswish_relu_cuda(y, c.bias)
        if c.bias is not None:
            y = y + c.bias.view(1, -1, 1, 1)
        return F.relu(F.hardswish(y))


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]
```
Result of evaluating it:
The solution failed to compile. Error output:
```
RuntimeError: Error building extension 'fused_conv3x3_bias_hardswish_relu_v3': [1/3] c++ -MMD -MF main.o.d -DTORCH_EXTENSION_NAME=fused_conv3x3_bias_hardswish_relu_v3 -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 -O3 -c /srv/jobs/1791684112654640941-526805-0/build/fused_conv3x3_bias_hardswish_relu_v3/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_conv3x3_bias_hardswish_relu_v3 -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 --use_fast_math -std=c++20 -c /srv/jobs/1791684112654640941-526805-0/build/fused_conv3x3_bias_hardswish_relu_v3/cuda.cu -o cuda.cuda.o 
FAILED: [code=255] 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_conv3x3_bias_hardswish_relu_v3 -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 --use_fast_math -std=c++20 -c /srv/jobs/1791684112654640941-526805-0/build/fused_conv3x3_bias_hardswish_relu_v3/cuda.cu -o cuda.cuda.o 
ptxas error   : Entry function '_Z27conv3x3_bias_hs_relu_kernelILi4EEvPKfS1_S1_Pfiiiiii' uses too much shared data (0xe2c0 bytes, 0xc000 max)
ptxas error   : Entry function '_Z27conv3x3_bias_hs_relu_kernelILi3EEvPKfS1_S1_Pfiiiiii' uses too much shared data (0xe2c0 bytes, 0xc000 max)
ptxas error   : Entry function '_Z27conv3x3_bias_hs_relu_kernelILi2EEvPKfS1_S1_Pfiiiiii' uses too much shared data (0xe2c0 bytes, 0xc000 max)
ptxas error   : Entry function '_Z27conv3x3_bias_hs_relu_kernelILi1EEvPKfS1_S1_Pfiiiiii' uses too much shared data (0xe2c0 bytes, 0xc000 max)
ninja: build stopped: subcommand failed.

```

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

# Autotune conv algorithms (helps the generic fallback path) and allow TF32,
# matching the PyTorch reference configuration.
torch.backends.cudnn.benchmark = True
torch.backends.cudnn.benchmark_limit = 0
torch.backends.cudnn.allow_tf32 = True
torch.backends.cuda.matmul.allow_tf32 = True

# ---------------------------------------------------------------------------
# Fully fused Conv2d(3x3, stride 1, pad 0, Cin=8) + bias + HardSwish + ReLU.
#
# Strategy: direct convolution formulated as 9 tiny TF32 tensor-core GEMMs
# (one per kernel tap) using nvcuda::wmma 16x16x8 fragments. Each thread block
# computes an 8x16 tile of output pixels for all output channels:
#   - the input tile (10x18x8, zero-padded halo) is staged in shared memory
#     directly from NCHW global memory (no separate NHWC transform pass);
#   - weights are staged transposed as [kh][kw][ic][oc] in shared memory;
#   - each warp owns one output row of 16 pixels, accumulates 16x16 fragments
#     over the 9 taps and all 8 input channels (one K-step per tap);
#   - the bias + HardSwish + ReLU epilogue is applied in registers/shared and
#     written straight to NCHW global memory.
#
# This eliminates every intermediate memory pass of the reference pipeline
# (cudnn conv + bias add + hardswish + relu + layout transforms). Only the
# input (67MB) is read and the final output (520MB) is written, once.
# ---------------------------------------------------------------------------
fused_cuda_source = r"""
#include <torch/extension.h>
#include <cuda_runtime.h>
#include <mma.h>

namespace wm = nvcuda::wmma;

#define TILE_W 16
#define TILE_H 8
#define CIN 8
#define PITCH 12            // padded channel pitch (mult of 4 for tf32 wmma)
#define STAGE_LD 20         // padded accumulator stage ld (mult of 4, 2-way-conflict-free reads)
#define MAX_NT 4            // supports up to 64 output channels
#define NTHREADS 256

__device__ __forceinline__ float bias_hs_relu(float x, float b) {
    x += b;
    float t = fminf(fmaxf(x + 3.0f, 0.0f), 6.0f);
    return fmaxf(x * t * 0.16666667163372039794921875f, 0.0f);
}

template <int NT>
__global__ void __launch_bounds__(NTHREADS) conv3x3_bias_hs_relu_kernel(
        const float* __restrict__ x,     // NCHW input
        const float* __restrict__ w,     // [C_out][8][3][3]
        const float* __restrict__ bias,  // [C_out]
        float* __restrict__ out,         // NCHW output
        int N, int H, int W, int C_out, int H_out, int W_out) {
    __shared__ float sm_in[(TILE_H + 2) * (TILE_W + 2) * PITCH];
    __shared__ float sm_w[3 * 3 * CIN * MAX_NT * 16];
    __shared__ float stage[TILE_H][16 * STAGE_LD];

    const int n  = blockIdx.z;
    const int h0 = blockIdx.y * TILE_H;
    const int w0 = blockIdx.x * TILE_W;
    const int tid  = threadIdx.x;
    const int warp = tid >> 5;
    const int lane = tid & 31;

    // ---- stage input tile [hh][ww][c] with zero-padded halo ----
    // Output tile rows h0..h0+7 / cols w0..w0+15 need input rows h0..h0+9
    // and cols w0..w0+17 (valid conv, no extra halo offset).
    const int HWt = (TILE_H + 2) * (TILE_W + 2);   // 180
    const int tile_elems = CIN * HWt;              // 1440
    const long xbase = (long)n * CIN * H * W;
    for (int idx = tid; idx < tile_elems; idx += NTHREADS) {
        int c  = idx / HWt;
        int r  = idx - c * HWt;
        int hh = r / (TILE_W + 2);
        int ww = r - hh * (TILE_W + 2);
        int h = h0 + hh;
        int w = w0 + ww;
        float v = 0.0f;
        if ((unsigned)h < (unsigned)H && (unsigned)w < (unsigned)W) {
            v = x[xbase + ((long)c * H + h) * W + w];
        }
        sm_in[(hh * (TILE_W + 2) + ww) * PITCH + c] = v;
    }

    // ---- stage weights transposed to [kh][kw][ic][oc] ----
    const int w_elems = 9 * CIN * C_out;
    for (int idx = tid; idx < w_elems; idx += NTHREADS) {
        int oc = idx % C_out;
        int t  = idx / C_out;
        int ic = t % CIN;
        t /= CIN;
        int kw = t % 3;
        int kh = t / 3;
        sm_w[idx] = w[((long)(oc * CIN + ic) * 3 + kh) * 3 + kw];
    }
    __syncthreads();

    const int h = h0 + warp;   // output row owned by this warp
    if (h >= H_out) return;

    wm::fragment<wm::accumulator, 16, 16, 8, float> acc[NT];
    #pragma unroll
    for (int j = 0; j < NT; ++j) wm::fill_fragment(acc[j], 0.0f);

    // direct conv as 9 tensor-core GEMMs (M=16 pixels, N=16ch tiles, K=8)
    #pragma unroll
    for (int kh = 0; kh < 3; ++kh) {
        #pragma unroll
        for (int kw = 0; kw < 3; ++kw) {
            wm::fragment<wm::matrix_a, 16, 16, 8, wm::precision::tf32, wm::row_major> a;
            wm::load_matrix_sync(a, &sm_in[((warp + kh) * (TILE_W + 2) + kw) * PITCH], PITCH);
            #pragma unroll
            for (int j = 0; j < NT; ++j) {
                wm::fragment<wm::matrix_b, 16, 16, 8, wm::precision::tf32, wm::row_major> b;
                wm::load_matrix_sync(b, &sm_w[((kh * 3 + kw) * CIN) * C_out + j * 16], C_out);
                wm::mma_sync(acc[j], a, b, acc[j]);
            }
        }
    }

    // ---- fused bias + HardSwish + ReLU epilogue, store NCHW ----
    const long HWo = (long)H_out * W_out;
    const long obase = (long)n * C_out * HWo + (long)h * W_out + w0;
    const int r  = lane & 15;    // pixel column within the 16-wide row
    const int ch = lane >> 4;    // 0 or 1 -> two channels per pass
    const bool valid = (w0 + r) < W_out;

    #pragma unroll
    for (int j = 0; j < NT; ++j) {
        wm::store_matrix_sync(stage[warp], acc[j], STAGE_LD, wm::mem_row_major);
        __syncwarp();
        #pragma unroll
        for (int cc = 0; cc < 8; ++cc) {
            int cl = cc * 2 + ch;
            int c  = j * 16 + cl;
            float v = stage[warp][r * STAGE_LD + cl];
            v = bias_hs_relu(v, __ldg(bias + c));
            if (valid) out[obase + (long)c * HWo + r] = v;
        }
        __syncwarp();
    }
}

torch::Tensor conv3x3_bias_hs_relu_cuda(torch::Tensor x, torch::Tensor w, torch::Tensor b) {
    TORCH_CHECK(x.is_cuda() && w.is_cuda() && b.is_cuda(), "inputs must be CUDA");
    TORCH_CHECK(x.scalar_type() == torch::kFloat32, "float32 only");
    TORCH_CHECK(x.dim() == 4 && w.dim() == 4, "bad dims");

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

    const int N     = (int)xc.size(0);
    const int C_in  = (int)xc.size(1);
    const int H     = (int)xc.size(2);
    const int W     = (int)xc.size(3);
    const int C_out = (int)wc.size(0);
    const int H_out = H - 2;
    const int W_out = W - 2;

    TORCH_CHECK(C_in == CIN, "fused kernel needs in_channels == 8");
    TORCH_CHECK((C_out % 16) == 0 && C_out >= 16 && C_out <= MAX_NT * 16,
                "fused kernel needs out_channels in {16,32,48,64}");
    TORCH_CHECK(H_out > 0 && W_out > 0, "bad spatial size");

    auto out = torch::empty({N, C_out, H_out, W_out}, xc.options());
    if (out.numel() == 0) return out;

    dim3 grid((unsigned)((W_out + TILE_W - 1) / TILE_W),
              (unsigned)((H_out + TILE_H - 1) / TILE_H),
              (unsigned)N);
    dim3 block(NTHREADS);

    const float* xp = xc.data_ptr<float>();
    const float* wp = wc.data_ptr<float>();
    const float* bp = bc.data_ptr<float>();
    float* op = out.data_ptr<float>();

    switch (C_out / 16) {
        case 1:
            conv3x3_bias_hs_relu_kernel<1><<<grid, block>>>(xp, wp, bp, op, N, H, W, C_out, H_out, W_out);
            break;
        case 2:
            conv3x3_bias_hs_relu_kernel<2><<<grid, block>>>(xp, wp, bp, op, N, H, W, C_out, H_out, W_out);
            break;
        case 3:
            conv3x3_bias_hs_relu_kernel<3><<<grid, block>>>(xp, wp, bp, op, N, H, W, C_out, H_out, W_out);
            break;
        case 4:
            conv3x3_bias_hs_relu_kernel<4><<<grid, block>>>(xp, wp, bp, op, N, H, W, C_out, H_out, W_out);
            break;
        default:
            TORCH_CHECK(false, "unsupported out_channels");
    }
    return out;
}

// ---------------------------------------------------------------------------
// Generic fallback epilogue: bias + HardSwish + ReLU in a single memory pass
// (used when the fully fused conv kernel's shape constraints are not met).
// ---------------------------------------------------------------------------
__global__ void __launch_bounds__(256) bias_hs_relu_vec_kernel(
        const float4* __restrict__ in,
        float4* __restrict__ out,
        const float* __restrict__ bias,
        int hw4, int C) {
    int plane = blockIdx.y;
    float b = __ldg(bias + (plane % C));
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    if (idx < hw4) {
        long off = (long)plane * hw4 + idx;
        float4 v = in[off];
        v.x = bias_hs_relu(v.x, b);
        v.y = bias_hs_relu(v.y, b);
        v.z = bias_hs_relu(v.z, b);
        v.w = bias_hs_relu(v.w, b);
        out[off] = v;
    }
}

__global__ void __launch_bounds__(256) bias_hs_relu_scalar_kernel(
        const float* __restrict__ in,
        float* __restrict__ out,
        const float* __restrict__ bias,
        int hw, int C) {
    int plane = blockIdx.y;
    float b = __ldg(bias + (plane % C));
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    if (idx < hw) {
        long off = (long)plane * hw + idx;
        out[off] = bias_hs_relu(in[off], b);
    }
}

torch::Tensor bias_hardswish_relu_cuda(torch::Tensor x, torch::Tensor bias) {
    TORCH_CHECK(x.is_cuda() && bias.is_cuda(), "inputs must be CUDA tensors");
    TORCH_CHECK(x.scalar_type() == torch::kFloat32, "input must be float32");
    TORCH_CHECK(x.dim() == 4, "expected NCHW 4D input");

    auto xc = x.contiguous();
    auto out = torch::empty_like(xc);
    if (xc.numel() == 0) return out;

    const long C  = xc.size(1);
    const long HW = xc.size(2) * xc.size(3);
    const long planes = xc.size(0) * C;
    TORCH_CHECK(planes <= 65535, "too many planes for grid.y");

    const int block = 256;
    const float* in_ptr = xc.data_ptr<float>();
    float* out_ptr      = out.data_ptr<float>();
    const float* b_ptr  = bias.data_ptr<float>();

    dim3 grid;
    grid.y = (unsigned)planes;
    if ((HW & 3) == 0) {
        int hw4 = (int)(HW >> 2);
        grid.x = (unsigned)((hw4 + block - 1) / block);
        bias_hs_relu_vec_kernel<<<grid, block>>>(
            reinterpret_cast<const float4*>(in_ptr),
            reinterpret_cast<float4*>(out_ptr),
            b_ptr, hw4, (int)C);
    } else {
        grid.x = (unsigned)((HW + block - 1) / block);
        bias_hs_relu_scalar_kernel<<<grid, block>>>(
            in_ptr, out_ptr, b_ptr, (int)HW, (int)C);
    }
    return out;
}
"""

fused_cpp_source = (
    "torch::Tensor conv3x3_bias_hs_relu_cuda(torch::Tensor x, torch::Tensor w, torch::Tensor b);\n"
    "torch::Tensor bias_hardswish_relu_cuda(torch::Tensor x, torch::Tensor bias);"
)

fused_ops = load_inline(
    name="fused_conv3x3_bias_hardswish_relu_v2",
    cpp_sources=fused_cpp_source,
    cuda_sources=fused_cuda_source,
    functions=["conv3x3_bias_hs_relu_cuda", "bias_hardswish_relu_cuda"],
    verbose=False,
    extra_cflags=["-O3"],
    extra_cuda_cflags=["-O3", "--use_fast_math"],
)


class ModelNew(nn.Module):
    """
    Optimized model:
      Fast path (Cin=8, 3x3 stride-1 pad-0 conv, Cout in {16,32,48,64}):
        a single fully fused CUDA kernel performing the convolution with TF32
        tensor cores plus the bias + HardSwish + ReLU epilogue, reading the
        input and writing the final output exactly once (no intermediate
        activations, no layout-transform passes).
      Fallback path: cudnn conv (no bias) + fused epilogue kernel.
    """

    def __init__(self, in_channels, out_channels, kernel_size):
        super(ModelNew, 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).
        """
        c = self.conv
        if (
            x.is_cuda
            and x.dtype == torch.float32
            and c.bias is not None
            and c.groups == 1
            and c.stride == (1, 1)
            and c.padding == (0, 0)
            and c.dilation == (1, 1)
            and c.kernel_size == (3, 3)
            and c.in_channels == 8
            and (c.out_channels % 16) == 0
            and 16 <= c.out_channels <= 64
            and x.size(0) <= 65535
            and x.size(2) >= 3
            and x.size(3) >= 3
        ):
            return fused_ops.conv3x3_bias_hs_relu_cuda(x, c.weight, c.bias)

        y = F.conv2d(x, c.weight, None, c.stride, c.padding, c.dilation, c.groups)
        if y.is_cuda and y.dtype == torch.float32 and c.bias is not None:
            return fused_ops.bias_hardswish_relu_cuda(y, c.bias)
        if c.bias is not None:
            y = y + c.bias.view(1, -1, 1, 1)
        return F.relu(F.hardswish(y))


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

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.


Precision rule: the timed forward must compute in FP32 (TF32 tensor-core math is allowed, as in the PyTorch reference). Do not cast inputs, weights or intermediate results to float16 or bfloat16 and do not call half-precision kernels in forward().
