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):
    """
    Performs a depthwise 2D convolution with asymmetric input and square kernel.

    Args:
        in_channels (int): Number of channels in the input tensor.
        out_channels (int): Number of channels produced by the convolution.
        kernel_size (int): Size of the square convolution kernel.
        stride (int, optional): Stride of the convolution. Defaults to 1.
        padding (int, optional): Padding applied to the input. Defaults to 0.
        bias (bool, optional): If `True`, adds a learnable bias to the output. Defaults to `False`.
    """
    def __init__(self, in_channels: int, out_channels: int, kernel_size: int, stride: int = 1, padding: int = 0, bias: bool = False):
        super(Model, self).__init__()
        self.conv2d = nn.Conv2d(in_channels, out_channels, kernel_size=(kernel_size, kernel_size), stride=stride, padding=padding, groups=in_channels, bias=bias)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """
        Performs the depthwise 2D convolution.

        Args:
            x (torch.Tensor): Input tensor of shape (batch_size, in_channels, height_in, width_in).

        Returns:
            torch.Tensor: Output tensor of shape (batch_size, out_channels, height_out, width_out).
        """
        return self.conv2d(x)

# Test code
batch_size = 64
in_channels = 128
out_channels = 128
kernel_size = 3
width_in = 512
height_in = 256
stride = 1
padding = 0

def get_inputs():
    x = torch.rand(batch_size, in_channels, height_in, width_in)
    return [x]

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

_depthwise_conv_cpp_source = (
    "torch::Tensor depthwise_conv3x3_cuda(torch::Tensor x, torch::Tensor weight, torch::Tensor bias);"
)

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

// Depthwise 3x3 convolution, stride 1, padding 0, float32.
//
// Each thread block computes a 128x64 output tile for one (batch, channel)
// pair. Block = (32, 16) threads; each thread produces a 4(col) x 4(row)
// patch of outputs. The 130x66 input halo is staged in shared memory with
// 16-byte cp.async copies (zero-filling out-of-range tails on sm_80+), so the
// fill does not round-trip through registers. Compute reads shared memory via
// conflict-free float4 accesses and keeps the 3x3 weights in registers, so
// the inner loop is almost pure FMA. Output stores use streaming (evict-first)
// float4; when a row base is not 16B-aligned (OW is 2 mod 4, so exactly every
// other row), warp neighbours exchange halves with __shfl_up_sync so all
// vectorized stores stay aligned.
namespace {

constexpr int TX = 32;
constexpr int TY = 16;
constexpr int TILE_W = TX * 4;   // 128 output cols per block
constexpr int TILE_H = TY * 4;   // 64 output rows per block
constexpr int SM_W = TILE_W + 2; // 130
constexpr int SM_H = TILE_H + 2; // 66
constexpr int PITCH = 132;       // SM_W rounded up to a multiple of 4
constexpr int VPR = PITCH / 4;   // 33 float4 per shared row

__global__ void __launch_bounds__(TX * TY)
depthwise_conv3x3_s1_kernel(
    const float* __restrict__ x,
    const float* __restrict__ w,
    const float* __restrict__ bias,
    float* __restrict__ out,
    int N, int C, int H, int W,
    int OC, int mult, int OH, int OW,
    bool has_bias) {

    __shared__ __align__(16) float tile[SM_H * PITCH];
    __shared__ float ws[9];

    const int tx = threadIdx.x;
    const int ty = threadIdx.y;
    const int tid = ty * TX + tx;

    const int ow0 = blockIdx.x * TILE_W;
    const int oh0 = blockIdx.y * TILE_H;

    const int total_z = N * OC;
    for (int z = blockIdx.z; z < total_z; z += gridDim.z) {
        const int n = z / OC;
        const int oc = z - n * OC;
        const int ic = oc / mult;

        if (tid < 9) {
            ws[tid] = w[oc * 9 + tid];
        }

        const float* __restrict__ xb = x + ((int64_t)n * C + ic) * (int64_t)H * W;

#if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 800)
        // Stage the SM_H x PITCH shared tile through cp.async (16B each).
        // Out-of-range portions are zero-filled via the src-size operand.
        #pragma unroll
        for (int idx = tid; idx < SM_H * VPR; idx += TX * TY) {
            const int sy = idx / VPR;
            const int c4 = idx - sy * VPR;
            const int iy = oh0 + sy;
            const int ix = ow0 + (c4 << 2);
            const float* src = xb + (int64_t)iy * W + ix;
            int nbytes = 0;
            if (iy < H) {
                const int rem = W - ix;  // floats remaining in this row
                nbytes = rem >= 4 ? 16 : (rem > 0 ? rem * 4 : 0);
            }
            if (nbytes == 0) {
                src = xb;  // safe address; nothing is read anyway
            }
            const unsigned dst =
                (unsigned)__cvta_generic_to_shared(&tile[sy * PITCH + (c4 << 2)]);
            asm volatile("cp.async.cg.shared.global [%0], [%1], 16, %2;\n" ::"r"(dst),
                         "l"(src), "r"(nbytes));
        }
        asm volatile("cp.async.commit_group;\n" ::);
        asm volatile("cp.async.wait_group 0;\n" ::);
#else
        #pragma unroll
        for (int idx = tid; idx < SM_H * VPR; idx += TX * TY) {
            const int sy = idx / VPR;
            const int c4 = idx - sy * VPR;
            const int iy = oh0 + sy;
            const int ix = ow0 + (c4 << 2);
            float4 v = make_float4(0.0f, 0.0f, 0.0f, 0.0f);
            if (iy < H) {
                const float* row = xb + (int64_t)iy * W;
                if (ix + 3 < W) {
                    v = *reinterpret_cast<const float4*>(row + ix);
                } else {
                    if (ix + 0 < W) v.x = row[ix + 0];
                    if (ix + 1 < W) v.y = row[ix + 1];
                    if (ix + 2 < W) v.z = row[ix + 2];
                    if (ix + 3 < W) v.w = row[ix + 3];
                }
            }
            *reinterpret_cast<float4*>(&tile[sy * PITCH + (c4 << 2)]) = v;
        }
#endif
        __syncthreads();

        float wr[9];
        #pragma unroll
        for (int k = 0; k < 9; ++k) {
            wr[k] = ws[k];
        }

        const int c0 = tx << 2;   // shared col base
        const int r0 = ty << 2;   // shared row base (uses rows r0..r0+5)

        float acc[4][4];
        #pragma unroll
        for (int j = 0; j < 4; ++j) {
            #pragma unroll
            for (int c = 0; c < 4; ++c) {
                acc[j][c] = 0.0f;
            }
        }

        #pragma unroll
        for (int i = 0; i < 6; ++i) {
            const float* row = &tile[(r0 + i) * PITCH + c0];
            const float4 a = *reinterpret_cast<const float4*>(row);
            const float4 b = *reinterpret_cast<const float4*>(row + 4);
            const float s0 = a.x, s1 = a.y, s2 = a.z, s3 = a.w, s4 = b.x, s5 = b.y;
            #pragma unroll
            for (int j = 0; j < 4; ++j) {
                if (i >= j && i <= j + 2) {
                    const int ky = i - j;
                    const float w0 = wr[ky * 3 + 0], w1 = wr[ky * 3 + 1], w2 = wr[ky * 3 + 2];
                    acc[j][0] += s0 * w0 + s1 * w1 + s2 * w2;
                    acc[j][1] += s1 * w0 + s2 * w1 + s3 * w2;
                    acc[j][2] += s2 * w0 + s3 * w1 + s4 * w2;
                    acc[j][3] += s3 * w0 + s4 * w1 + s5 * w2;
                }
            }
        }

        if (has_bias) {
            const float bv = bias[oc];
            #pragma unroll
            for (int j = 0; j < 4; ++j) {
                #pragma unroll
                for (int c = 0; c < 4; ++c) {
                    acc[j][c] += bv;
                }
            }
        }

        float* __restrict__ ob = out + ((int64_t)n * OC + oc) * (int64_t)OH * OW;
        const int ow = ow0 + c0;
        const bool interior = (ow0 + TILE_W <= OW);

        #pragma unroll
        for (int j = 0; j < 4; ++j) {
            const int oh = oh0 + r0 + j;
            if (oh >= OH) continue;
            float* p = ob + (int64_t)oh * OW + ow;
            if (interior) {
                if ((((uintptr_t)p) & 15) == 0) {
                    __stcs(reinterpret_cast<float4*>(p),
                           make_float4(acc[j][0], acc[j][1], acc[j][2], acc[j][3]));
                } else {
                    // Row base is misaligned by exactly 2 floats (W % 4 == 0
                    // implies OW == 2 mod 4). Shift every lane's (a2, a3)
                    // one lane up so lanes 1..31 write aligned float4 chunks;
                    // lanes 0 and 31 patch the two remaining columns.
                    const float a0 = acc[j][0], a1 = acc[j][1];
                    const float a2 = acc[j][2], a3 = acc[j][3];
                    const float pz = __shfl_up_sync(0xffffffffu, a2, 1);
                    const float pw = __shfl_up_sync(0xffffffffu, a3, 1);
                    if (tx > 0) {
                        __stcs(reinterpret_cast<float4*>(p - 2), make_float4(pz, pw, a0, a1));
                    } else {
                        __stcs(p + 0, a0);
                        __stcs(p + 1, a1);
                    }
                    if (tx == TX - 1) {
                        __stcs(p + 2, a2);
                        __stcs(p + 3, a3);
                    }
                }
            } else {
                #pragma unroll
                for (int c = 0; c < 4; ++c) {
                    if (ow + c < OW) __stcs(p + c, acc[j][c]);
                }
            }
        }

        // Only re-sync when the shared tile will be reused by another z slice.
        if (z + gridDim.z < total_z) {
            __syncthreads();
        }
    }
}

} // namespace

torch::Tensor depthwise_conv3x3_cuda(torch::Tensor x, torch::Tensor weight, torch::Tensor bias) {
    TORCH_CHECK(x.is_cuda() && weight.is_cuda(), "depthwise_conv3x3_cuda expects CUDA tensors");
    TORCH_CHECK(x.scalar_type() == at::kFloat && weight.scalar_type() == at::kFloat,
                "depthwise_conv3x3_cuda expects float32 tensors");
    TORCH_CHECK(x.dim() == 4 && weight.dim() == 4, "bad tensor ranks");
    TORCH_CHECK(weight.size(1) == 1 && weight.size(2) == 3 && weight.size(3) == 3,
                "expected depthwise 3x3 weights of shape (OC, 1, 3, 3)");

    auto xc = x.contiguous();
    auto wc = weight.contiguous();

    const int64_t N = xc.size(0);
    const int64_t C = xc.size(1);
    const int64_t H = xc.size(2);
    const int64_t W = xc.size(3);
    const int64_t OC = wc.size(0);
    TORCH_CHECK(OC % C == 0, "out_channels must be a multiple of in_channels");
    const int64_t mult = OC / C;
    const int64_t OH = H - 2;
    const int64_t OW = W - 2;
    TORCH_CHECK(OH > 0 && OW > 0, "input spatial size must be >= 3");
    TORCH_CHECK(W % 4 == 0, "input width must be a multiple of 4");
    TORCH_CHECK((OH + TILE_H - 1) / TILE_H <= 65535, "input height too large");
    TORCH_CHECK((reinterpret_cast<uintptr_t>(xc.data_ptr<float>()) & 15) == 0,
                "input data pointer must be 16-byte aligned");

    auto out = at::empty({N, OC, OH, OW}, xc.options());

    const bool has_bias = bias.defined() && bias.numel() > 0;
    torch::Tensor bc;
    const float* bias_ptr = nullptr;
    if (has_bias) {
        bc = bias.contiguous();
        bias_ptr = bc.data_ptr<float>();
    }

    dim3 block(TX, TY);
    dim3 grid(
        (unsigned int)((OW + TILE_W - 1) / TILE_W),
        (unsigned int)((OH + TILE_H - 1) / TILE_H),
        (unsigned int)std::min<int64_t>(N * OC, 65535));

    auto stream = at::cuda::getCurrentCUDAStream();
    depthwise_conv3x3_s1_kernel<<<grid, block, 0, stream>>>(
        xc.data_ptr<float>(),
        wc.data_ptr<float>(),
        bias_ptr,
        out.data_ptr<float>(),
        (int)N, (int)C, (int)H, (int)W,
        (int)OC, (int)mult, (int)OH, (int)OW,
        has_bias);
    C10_CUDA_KERNEL_LAUNCH_CHECK();

    return out;
}
"""

_depthwise_conv_ext = load_inline(
    name="depthwise_conv3x3_s1_v4_ext",
    cpp_sources=_depthwise_conv_cpp_source,
    cuda_sources=_depthwise_conv_cuda_source,
    functions=["depthwise_conv3x3_cuda"],
    verbose=False,
    extra_cflags=["-O3"],
    extra_cuda_cflags=["-O3"],
)


class ModelNew(nn.Module):
    """
    Depthwise 2D convolution accelerated with a custom fused CUDA kernel for
    the common 3x3 / stride 1 / no-padding float32 case. Falls back to the
    reference nn.Conv2d implementation for every other configuration.
    """
    def __init__(self, in_channels: int, out_channels: int, kernel_size: int, stride: int = 1, padding: int = 0, bias: bool = False):
        super(ModelNew, self).__init__()
        self.conv2d = nn.Conv2d(
            in_channels,
            out_channels,
            kernel_size=(kernel_size, kernel_size),
            stride=stride,
            padding=padding,
            groups=in_channels,
            bias=bias,
        )
        self._use_custom_kernel = (kernel_size == 3 and stride == 1 and padding == 0)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        if (
            self._use_custom_kernel
            and x.is_cuda
            and x.dtype == torch.float32
            and x.dim() == 4
            and x.size(2) >= 3
            and x.size(3) >= 4
            and (x.size(3) & 3) == 0
            and (x.data_ptr() & 15) == 0
            and ((x.size(2) - 2 + 63) // 64) <= 65535
        ):
            bias = self.conv2d.bias
            if bias is None:
                bias = x.new_empty(0)
            return _depthwise_conv_ext.depthwise_conv3x3_cuda(x, self.conv2d.weight, bias)
        return self.conv2d(x)
```
Result of evaluating it:
The solution is correct on the test inputs. Mean runtime 6.28 ms; the PyTorch reference (with TF32 enabled) takes 15.2 ms; speedup 2.420x.
Profiler, top device kernels of one forward pass of your solution:
| device kernel | total device time (us) | calls |
|---|---|---|
| (anonymous namespace)::depthwise_conv3x3_s1_kernel(float const*, float const*, float const | 6250.5 | 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.
