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 asymmetric kernel.

    Args:
        in_channels (int): Number of channels in the input tensor.
        out_channels (int): Number of channels produced by the convolution.
        kernel_size_h (int): Height of the convolution kernel.
        kernel_size_w (int): Width of the convolution kernel.
        stride_h (int, optional): Stride of the convolution in height dimension. Defaults to 1.
        stride_w (int, optional): Stride of the convolution in width dimension. Defaults to 1.
        padding_h (int, optional): Padding applied to the input in height dimension. Defaults to 0.
        padding_w (int, optional): Padding applied to the input in width dimension. Defaults to 0.
        dilation_h (int, optional): Spacing between kernel elements in height dimension. Defaults to 1.
        dilation_w (int, optional): Spacing between kernel elements in width dimension. Defaults to 1.
        groups (int, optional): Number of blocked connections from input channels to output channels. Defaults to 1.
        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_h: int, kernel_size_w: int, stride_h: int = 1, stride_w: int = 1, padding_h: int = 0, padding_w: int = 0, dilation_h: int = 1, dilation_w: int = 1, groups: int = 1, bias: bool = False):
        super(Model, self).__init__()
        self.conv2d = nn.Conv2d(in_channels, in_channels, (kernel_size_h, kernel_size_w), stride=(stride_h, stride_w), padding=(padding_h, padding_w), dilation=(dilation_h, dilation_w), 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, width).

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

# Test code
batch_size = 32
in_channels = 128
out_channels = 128
kernel_size_h = 3
kernel_size_w = 7
width = 256
height = 128
stride_h = 1
stride_w = 1
padding_h = 0
padding_w = 0
dilation_h = 1
dilation_w = 1
groups = in_channels

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

def get_init_inputs():
    return [in_channels, out_channels, kernel_size_h, kernel_size_w, stride_h, stride_w, padding_h, padding_w, dilation_h, dilation_w, groups]
    ```
    
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
import torch.nn.functional as F
from torch.utils.cpp_extension import load_inline

# Custom CUDA kernels for depthwise 2D convolution (v4).
#
# Fast path (stride=1, pad=0, dilation=1, common kernel sizes):
#   * 128x18 output tile per block (192 threads, each thread produces a
#     3x4 register block of outputs -> 12 outputs/thread);
#   * the (18+KH-1) x padded(128+KW-1) input halo tile is staged in shared
#     memory with aligned float4 global/shared accesses whenever the tensor
#     layout allows (W % 4 == 0 and 16B-aligned rows), so each input element
#     is fetched from DRAM ~once (halo re-reads are served by L2);
#   * filter taps are staged in shared memory (broadcast, zero bank
#     conflicts) to keep register pressure low enough for 3 resident
#     blocks/SM (576 threads/SM);
#   * each thread pulls its shared-memory region into registers exactly once
#     with aligned float4 loads (conflict free);
#   * output stores are vectorized (float4 when outW % 4 == 0, float2 when
#     outW % 2 == 0, scalar otherwise).
# Fallback path: a fully general depthwise kernel handling any kernel size,
# stride, padding and dilation.
dwconv2d_cuda_source = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda_runtime.h>
#include <cstdint>

#define DW_TX 32   // threads along width
#define DW_TY 6    // threads along height
#define DW_RW 4    // output columns per thread
#define DW_RH 3    // output rows per thread
#define DW_NT (DW_TX * DW_TY)
#define DW_TILE_W (DW_TX * DW_RW)   // 128 output columns per block
#define DW_TILE_H (DW_TY * DW_RH)   // 18 output rows per block

template <int KH, int KW>
__global__ void __launch_bounds__(DW_NT, 3)
dwconv2d_tile_kernel(
    const float* __restrict__ input,
    const float* __restrict__ weight,
    const float* __restrict__ bias,
    float* __restrict__ output,
    int N, int C, int H, int W, int outH, int outW,
    int tilesX, int tilesPerSlice, int vecOK)
{
    // Register-block width rounded up to a float4 multiple; SH_W is padded so
    // that every per-thread register-block row is 16B aligned in shared memory.
    constexpr int REG_W = (((DW_RW + KW - 1) + 3) >> 2) << 2;
    constexpr int SH_W  = (DW_TILE_W - DW_RW) + REG_W;
    constexpr int SH_H  = DW_TILE_H + KH - 1;

    __shared__ __align__(16) float sh[SH_H * SH_W];
    __shared__ float wsh[KH * KW];

    const int tile = blockIdx.x % tilesPerSlice;
    const int nc   = blockIdx.x / tilesPerSlice;
    const int ty   = tile / tilesX;
    const int tx   = tile % tilesX;
    const int n    = nc / C;
    const int c    = nc % C;

    const int ow0 = tx * DW_TILE_W;
    const int oh0 = ty * DW_TILE_H;
    const int tid = threadIdx.y * DW_TX + threadIdx.x;

    // Stage this channel's filter taps in shared memory (broadcast reads).
    if (tid < KH * KW) wsh[tid] = weight[(long)c * (KH * KW) + tid];

    // Stage the input halo tile in shared memory (zero outside the image).
    const float* in_base = input + ((long)n * C + c) * H * W;
    if (vecOK) {
        constexpr int V4ROW = SH_W / 4;
        constexpr int V4TOT = SH_H * V4ROW;
        #pragma unroll 4
        for (int idx = tid; idx < V4TOT; idx += DW_NT) {
            const int sy = idx / V4ROW;
            const int sx = (idx - sy * V4ROW) * 4;
            const int gy = oh0 + sy;
            const int gx = ow0 + sx;
            float4 v = make_float4(0.0f, 0.0f, 0.0f, 0.0f);
            if (gy < H) {
                const float* gptr = in_base + (long)gy * W + gx;
                if (gx + 3 < W) {
                    v = *reinterpret_cast<const float4*>(gptr);
                } else {
                    v.x = (gx + 0 < W) ? gptr[0] : 0.0f;
                    v.y = (gx + 1 < W) ? gptr[1] : 0.0f;
                    v.z = (gx + 2 < W) ? gptr[2] : 0.0f;
                    v.w = (gx + 3 < W) ? gptr[3] : 0.0f;
                }
            }
            *reinterpret_cast<float4*>(sh + sy * SH_W + sx) = v;
        }
    } else {
        #pragma unroll 2
        for (int idx = tid; idx < SH_H * SH_W; idx += DW_NT) {
            const int sy = idx / SH_W;
            const int sx = idx - sy * SH_W;
            const int gy = oh0 + sy;
            const int gx = ow0 + sx;
            sh[idx] = (gy < H && gx < W) ? in_base[(long)gy * W + gx] : 0.0f;
        }
    }
    __syncthreads();

    const int sy0 = threadIdx.y * DW_RH;
    const int sx0 = threadIdx.x * DW_RW;

    // Pull this thread's shared-memory region into registers exactly once
    // using aligned float4 loads (conflict free).
    float reg[DW_RH + KH - 1][REG_W];
    #pragma unroll
    for (int i = 0; i < DW_RH + KH - 1; ++i) {
        const float* srow = sh + (sy0 + i) * SH_W + sx0;
        #pragma unroll
        for (int j = 0; j < REG_W / 4; ++j) {
            const float4 v = *reinterpret_cast<const float4*>(srow + 4 * j);
            reg[i][4 * j + 0] = v.x;
            reg[i][4 * j + 1] = v.y;
            reg[i][4 * j + 2] = v.z;
            reg[i][4 * j + 3] = v.w;
        }
    }

    const float b0 = (bias != nullptr) ? bias[c] : 0.0f;
    float acc[DW_RH][DW_RW];
    #pragma unroll
    for (int i = 0; i < DW_RH; ++i)
        #pragma unroll
        for (int j = 0; j < DW_RW; ++j)
            acc[i][j] = b0;

    #pragma unroll
    for (int kh = 0; kh < KH; ++kh) {
        #pragma unroll
        for (int kw = 0; kw < KW; ++kw) {
            const float wv = wsh[kh * KW + kw];
            #pragma unroll
            for (int i = 0; i < DW_RH; ++i) {
                #pragma unroll
                for (int j = 0; j < DW_RW; ++j) {
                    acc[i][j] = fmaf(reg[i + kh][j + kw], wv, acc[i][j]);
                }
            }
        }
    }

    const int ow = ow0 + sx0;
    const int oh = oh0 + sy0;
    float* out_base = output + ((long)n * C + c) * outH * outW;
    // ow is always a multiple of DW_RW (4) and out is a fresh 16B-aligned
    // allocation, so stores can be safely vectorized based on outW divisibility.
    if ((outW & 3) == 0) {
        #pragma unroll
        for (int i = 0; i < DW_RH; ++i) {
            const int oy = oh + i;
            if (oy < outH && ow < outW) {
                *reinterpret_cast<float4*>(out_base + (long)oy * outW + ow) =
                    make_float4(acc[i][0], acc[i][1], acc[i][2], acc[i][3]);
            }
        }
    } else if ((outW & 1) == 0) {
        #pragma unroll
        for (int i = 0; i < DW_RH; ++i) {
            const int oy = oh + i;
            if (oy < outH) {
                float* orow = out_base + (long)oy * outW + ow;
                if (ow < outW) {
                    *reinterpret_cast<float2*>(orow) = make_float2(acc[i][0], acc[i][1]);
                }
                if (ow + 2 < outW) {
                    *reinterpret_cast<float2*>(orow + 2) = make_float2(acc[i][2], acc[i][3]);
                }
            }
        }
    } else {
        #pragma unroll
        for (int i = 0; i < DW_RH; ++i) {
            const int oy = oh + i;
            if (oy < outH) {
                float* orow = out_base + (long)oy * outW + ow;
                #pragma unroll
                for (int j = 0; j < DW_RW; ++j) {
                    if (ow + j < outW) orow[j] = acc[i][j];
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------
// General depthwise kernel: any kernel size / stride / padding / dilation.
// ---------------------------------------------------------------------------
__global__ void dwconv2d_generic_kernel(
    const float* __restrict__ input,
    const float* __restrict__ weight,
    const float* __restrict__ bias,
    float* __restrict__ output,
    int N, int C, int H, int W, int outH, int outW,
    int KH, int KW, int strideH, int strideW, int padH, int padW, int dilH, int dilW)
{
    const long idx = (long)blockIdx.x * blockDim.x + threadIdx.x;
    const long total = (long)N * C * outH * outW;
    if (idx >= total) return;

    const int ow = (int)(idx % outW);
    const int oh = (int)((idx / outW) % outH);
    const int c  = (int)((idx / ((long)outW * outH)) % C);
    const int n  = (int)(idx / ((long)outW * outH * C));

    const float* in_base = input + ((long)n * C + c) * H * W;
    const float* w_base  = weight + (long)c * KH * KW;

    float sum = (bias != nullptr) ? bias[c] : 0.0f;
    for (int kh = 0; kh < KH; ++kh) {
        const int ih = oh * strideH - padH + kh * dilH;
        if (ih < 0 || ih >= H) continue;
        const float* in_row = in_base + (long)ih * W;
        const float* w_row  = w_base + kh * KW;
        for (int kw = 0; kw < KW; ++kw) {
            const int iw = ow * strideW - padW + kw * dilW;
            if (iw < 0 || iw >= W) continue;
            sum = fmaf(in_row[iw], w_row[kw], sum);
        }
    }
    output[idx] = sum;
}

template <int KH, int KW>
static void launch_tile(
    const float* input, const float* weight, const float* bias, float* output,
    int N, int C, int H, int W, int outH, int outW, int vecOK, cudaStream_t stream)
{
    const int tilesX = (outW + DW_TILE_W - 1) / DW_TILE_W;
    const int tilesY = (outH + DW_TILE_H - 1) / DW_TILE_H;
    const int tilesPerSlice = tilesX * tilesY;
    const long blocks = (long)tilesPerSlice * N * C;
    dim3 grid((unsigned int)blocks);
    dim3 block(DW_TX, DW_TY);
    dwconv2d_tile_kernel<KH, KW><<<grid, block, 0, stream>>>(
        input, weight, bias, output, N, C, H, W, outH, outW, tilesX, tilesPerSlice, vecOK);
}

torch::Tensor dwconv2d_forward(
    torch::Tensor input,
    torch::Tensor weight,
    c10::optional<torch::Tensor> bias,
    int64_t strideH, int64_t strideW,
    int64_t padH, int64_t padW,
    int64_t dilH, int64_t dilW)
{
    TORCH_CHECK(input.is_cuda(), "input must be a CUDA tensor");
    TORCH_CHECK(input.scalar_type() == at::kFloat, "input must be float32");

    auto x = input.contiguous();
    auto w = weight.contiguous();

    const int N  = (int)x.size(0);
    const int C  = (int)x.size(1);
    const int H  = (int)x.size(2);
    const int W  = (int)x.size(3);
    const int KH = (int)w.size(2);
    const int KW = (int)w.size(3);

    const int outH = (int)((H + 2 * padH - dilH * (KH - 1) - 1) / strideH + 1);
    const int outW = (int)((W + 2 * padW - dilW * (KW - 1) - 1) / strideW + 1);

    auto out = torch::empty({N, C, outH, outW}, x.options());
    if (out.numel() == 0) return out;

    const float* in_ptr = x.data_ptr<float>();
    const float* w_ptr  = w.data_ptr<float>();
    float* out_ptr      = out.data_ptr<float>();

    torch::Tensor b;
    const float* b_ptr = nullptr;
    if (bias.has_value() && bias->defined()) {
        b = bias->contiguous();
        b_ptr = b.data_ptr<float>();
    }

    cudaStream_t stream = at::cuda::getCurrentCUDAStream();

    const bool fast = (strideH == 1 && strideW == 1 && padH == 0 && padW == 0 &&
                       dilH == 1 && dilW == 1 && H >= KH && W >= KW);

    if (fast) {
        // 16B-aligned base, 16B-aligned rows and per-slice offsets allow
        // fully vectorized float4 staging.
        const int vecOK = (((reinterpret_cast<uintptr_t>(in_ptr)) & 15) == 0 &&
                           (W & 3) == 0 &&
                           (((long)H * W) & 3) == 0) ? 1 : 0;
        if (KH == 3 && KW == 7) { launch_tile<3, 7>(in_ptr, w_ptr, b_ptr, out_ptr, N, C, H, W, outH, outW, vecOK, stream); return out; }
        if (KH == 7 && KW == 3) { launch_tile<7, 3>(in_ptr, w_ptr, b_ptr, out_ptr, N, C, H, W, outH, outW, vecOK, stream); return out; }
        if (KH == 3 && KW == 3) { launch_tile<3, 3>(in_ptr, w_ptr, b_ptr, out_ptr, N, C, H, W, outH, outW, vecOK, stream); return out; }
        if (KH == 5 && KW == 5) { launch_tile<5, 5>(in_ptr, w_ptr, b_ptr, out_ptr, N, C, H, W, outH, outW, vecOK, stream); return out; }
        if (KH == 7 && KW == 7) { launch_tile<7, 7>(in_ptr, w_ptr, b_ptr, out_ptr, N, C, H, W, outH, outW, vecOK, stream); return out; }
        if (KH == 3 && KW == 1) { launch_tile<3, 1>(in_ptr, w_ptr, b_ptr, out_ptr, N, C, H, W, outH, outW, vecOK, stream); return out; }
        if (KH == 1 && KW == 3) { launch_tile<1, 3>(in_ptr, w_ptr, b_ptr, out_ptr, N, C, H, W, outH, outW, vecOK, stream); return out; }
        if (KH == 1 && KW == 1) { launch_tile<1, 1>(in_ptr, w_ptr, b_ptr, out_ptr, N, C, H, W, outH, outW, vecOK, stream); return out; }
    }

    const long total = (long)N * C * outH * outW;
    const int threads = 256;
    const long blocks = (total + threads - 1) / threads;
    dwconv2d_generic_kernel<<<(unsigned int)blocks, threads, 0, stream>>>(
        in_ptr, w_ptr, b_ptr, out_ptr,
        N, C, H, W, outH, outW,
        KH, KW, (int)strideH, (int)strideW, (int)padH, (int)padW, (int)dilH, (int)dilW);
    return out;
}
"""

dwconv2d_cpp_source = (
    "torch::Tensor dwconv2d_forward(torch::Tensor input, torch::Tensor weight, "
    "c10::optional<torch::Tensor> bias, int64_t strideH, int64_t strideW, "
    "int64_t padH, int64_t padW, int64_t dilH, int64_t dilW);"
)

# Compile the inline CUDA extension
dwconv2d_ext = load_inline(
    name="dwconv2d_ext_v4",
    cpp_sources=dwconv2d_cpp_source,
    cuda_sources=dwconv2d_cuda_source,
    functions=["dwconv2d_forward"],
    verbose=False,
    extra_cuda_cflags=["-O3"],
)

_dwconv2d_forward = dwconv2d_ext.dwconv2d_forward


class ModelNew(nn.Module):
    """
    Depthwise 2D convolution backed by a custom CUDA kernel.

    The nn.Conv2d submodule is kept so that parameter initialization and
    state_dict layout exactly match the reference Model.
    """
    def __init__(self, in_channels: int, out_channels: int, kernel_size_h: int, kernel_size_w: int, stride_h: int = 1, stride_w: int = 1, padding_h: int = 0, padding_w: int = 0, dilation_h: int = 1, dilation_w: int = 1, groups: int = 1, bias: bool = False):
        super(ModelNew, self).__init__()
        self.conv2d = nn.Conv2d(in_channels, in_channels, (kernel_size_h, kernel_size_w), stride=(stride_h, stride_w), padding=(padding_h, padding_w), dilation=(dilation_h, dilation_w), groups=in_channels, bias=bias)
        self.stride_h = stride_h
        self.stride_w = stride_w
        self.padding_h = padding_h
        self.padding_w = padding_w
        self.dilation_h = dilation_h
        self.dilation_w = dilation_w

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        weight = self.conv2d.weight
        if x.is_cuda and weight.is_cuda and x.dtype == torch.float32 and weight.dtype == torch.float32:
            return _dwconv2d_forward(
                x, weight, self.conv2d.bias,
                self.stride_h, self.stride_w,
                self.padding_h, self.padding_w,
                self.dilation_h, self.dilation_w)
        return F.conv2d(
            x, weight, self.conv2d.bias,
            stride=(self.stride_h, self.stride_w),
            padding=(self.padding_h, self.padding_w),
            dilation=(self.dilation_h, self.dilation_w),
            groups=self.conv2d.groups)
```
Result of evaluating it:
The solution is correct on the test inputs. Mean runtime 1.16 ms; the PyTorch reference (with TF32 enabled) takes 3.7 ms; speedup 3.190x.
Profiler, top device kernels of one forward pass of your solution:
| device kernel | total device time (us) | calls |
|---|---|---|
| void dwconv2d_tile_kernel<3, 7>(float const*, float const*, float const*, float*, int, int | 1133.5 | 1 |

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

# Custom CUDA kernels for depthwise 2D convolution.
#
# Fast path (stride=1, pad=0, dilation=1, common kernel sizes):
#   * each block stages a (TILE_H+KH-1) x padded(TILE_W+KW-1) input halo tile
#     in shared memory so every input element is fetched from DRAM ~once;
#   * staging uses aligned float4 global/shared accesses whenever the tensor
#     layout allows it (W % 4 == 0 and a 16B-aligned base), with per-slot
#     scalar fallback on image edges;
#   * filter taps are cached in registers;
#   * each thread computes a DW_RH x DW_RW register block of outputs, loading
#     the required shared-memory region into registers exactly once with
#     aligned float4 loads (zero bank conflicts);
#   * output stores are vectorized (float4 when outW % 4 == 0, float2 when
#     outW % 2 == 0, scalar otherwise).
# Fallback path: a fully general depthwise kernel handling any kernel size,
# stride, padding and dilation.
dwconv2d_cuda_source = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda_runtime.h>
#include <cstdint>

#define DW_TX 32   // threads along width
#define DW_TY 8    // threads along height
#define DW_RW 4    // output columns per thread
#define DW_RH 2    // output rows per thread
#define DW_NT (DW_TX * DW_TY)
#define DW_TILE_W (DW_TX * DW_RW)   // 128 output columns per block
#define DW_TILE_H (DW_TY * DW_RH)   // 16 output rows per block

template <int KH, int KW>
__global__ void __launch_bounds__(DW_NT)
dwconv2d_tile_kernel(
    const float* __restrict__ input,
    const float* __restrict__ weight,
    const float* __restrict__ bias,
    float* __restrict__ output,
    int N, int C, int H, int W, int outH, int outW,
    int tilesX, int tilesPerSlice, int vecOK)
{
    // Register-block width rounded up to a float4 multiple; SH_W is padded so
    // that every per-thread register-block row is 16B aligned in shared memory.
    constexpr int REG_W = (((DW_RW + KW - 1) + 3) >> 2) << 2;
    constexpr int SH_W  = (DW_TILE_W - DW_RW) + REG_W;
    constexpr int SH_H  = DW_TILE_H + KH - 1;

    __shared__ float sh[SH_H * SH_W];

    const int tile = blockIdx.x % tilesPerSlice;
    const int nc   = blockIdx.x / tilesPerSlice;
    const int ty   = tile / tilesX;
    const int tx   = tile % tilesX;
    const int n    = nc / C;
    const int c    = nc % C;

    const int ow0 = tx * DW_TILE_W;
    const int oh0 = ty * DW_TILE_H;

    // Cache this channel's filter taps in registers.
    float wr[KH * KW];
    const float* w_base = weight + (long)c * (KH * KW);
    #pragma unroll
    for (int i = 0; i < KH * KW; ++i) wr[i] = w_base[i];

    // Stage the input halo tile in shared memory (zero outside the image).
    const float* in_base = input + ((long)n * C + c) * H * W;
    const int tid = threadIdx.y * DW_TX + threadIdx.x;
    if (vecOK) {
        constexpr int V4ROW = SH_W / 4;
        constexpr int V4TOT = SH_H * V4ROW;
        #pragma unroll 2
        for (int idx = tid; idx < V4TOT; idx += DW_NT) {
            const int sy = idx / V4ROW;
            const int sx = (idx - sy * V4ROW) * 4;
            const int gy = oh0 + sy;
            const int gx = ow0 + sx;
            float4 v = make_float4(0.0f, 0.0f, 0.0f, 0.0f);
            if (gy < H) {
                const float* gptr = in_base + (long)gy * W + gx;
                if (gx + 3 < W) {
                    v = *reinterpret_cast<const float4*>(gptr);
                } else {
                    v.x = (gx + 0 < W) ? gptr[0] : 0.0f;
                    v.y = (gx + 1 < W) ? gptr[1] : 0.0f;
                    v.z = (gx + 2 < W) ? gptr[2] : 0.0f;
                    v.w = (gx + 3 < W) ? gptr[3] : 0.0f;
                }
            }
            *reinterpret_cast<float4*>(sh + sy * SH_W + sx) = v;
        }
    } else {
        #pragma unroll 2
        for (int idx = tid; idx < SH_H * SH_W; idx += DW_NT) {
            const int sy = idx / SH_W;
            const int sx = idx - sy * SH_W;
            const int gy = oh0 + sy;
            const int gx = ow0 + sx;
            sh[idx] = (gy < H && gx < W) ? in_base[(long)gy * W + gx] : 0.0f;
        }
    }
    __syncthreads();

    const int sy0 = threadIdx.y * DW_RH;
    const int sx0 = threadIdx.x * DW_RW;

    // Pull this thread's shared-memory region into registers exactly once
    // using aligned float4 loads (conflict free).
    float reg[DW_RH + KH - 1][REG_W];
    #pragma unroll
    for (int i = 0; i < DW_RH + KH - 1; ++i) {
        const float* srow = sh + (sy0 + i) * SH_W + sx0;
        #pragma unroll
        for (int j = 0; j < REG_W / 4; ++j) {
            const float4 v = *reinterpret_cast<const float4*>(srow + 4 * j);
            reg[i][4 * j + 0] = v.x;
            reg[i][4 * j + 1] = v.y;
            reg[i][4 * j + 2] = v.z;
            reg[i][4 * j + 3] = v.w;
        }
    }

    const float b0 = (bias != nullptr) ? bias[c] : 0.0f;
    float acc[DW_RH][DW_RW];
    #pragma unroll
    for (int i = 0; i < DW_RH; ++i)
        #pragma unroll
        for (int j = 0; j < DW_RW; ++j)
            acc[i][j] = b0;

    #pragma unroll
    for (int kh = 0; kh < KH; ++kh) {
        #pragma unroll
        for (int kw = 0; kw < KW; ++kw) {
            const float wv = wr[kh * KW + kw];
            #pragma unroll
            for (int i = 0; i < DW_RH; ++i) {
                #pragma unroll
                for (int j = 0; j < DW_RW; ++j) {
                    acc[i][j] = fmaf(reg[i + kh][j + kw], wv, acc[i][j]);
                }
            }
        }
    }

    const int ow = ow0 + sx0;
    const int oh = oh0 + sy0;
    float* out_base = output + ((long)n * C + c) * outH * outW;
    // ow is always a multiple of DW_RW (4) and out is a fresh 16B-aligned
    // allocation, so stores can be safely vectorized based on outW divisibility.
    if ((outW & 3) == 0) {
        #pragma unroll
        for (int i = 0; i < DW_RH; ++i) {
            const int oy = oh + i;
            if (oy < outH && ow < outW) {
                *reinterpret_cast<float4*>(out_base + (long)oy * outW + ow) =
                    make_float4(acc[i][0], acc[i][1], acc[i][2], acc[i][3]);
            }
        }
    } else if ((outW & 1) == 0) {
        #pragma unroll
        for (int i = 0; i < DW_RH; ++i) {
            const int oy = oh + i;
            if (oy < outH) {
                float* orow = out_base + (long)oy * outW + ow;
                if (ow < outW) {
                    *reinterpret_cast<float2*>(orow) = make_float2(acc[i][0], acc[i][1]);
                }
                if (ow + 2 < outW) {
                    *reinterpret_cast<float2*>(orow + 2) = make_float2(acc[i][2], acc[i][3]);
                }
            }
        }
    } else {
        #pragma unroll
        for (int i = 0; i < DW_RH; ++i) {
            const int oy = oh + i;
            if (oy < outH) {
                float* orow = out_base + (long)oy * outW + ow;
                #pragma unroll
                for (int j = 0; j < DW_RW; ++j) {
                    if (ow + j < outW) orow[j] = acc[i][j];
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------
// General depthwise kernel: any kernel size / stride / padding / dilation.
// ---------------------------------------------------------------------------
__global__ void dwconv2d_generic_kernel(
    const float* __restrict__ input,
    const float* __restrict__ weight,
    const float* __restrict__ bias,
    float* __restrict__ output,
    int N, int C, int H, int W, int outH, int outW,
    int KH, int KW, int strideH, int strideW, int padH, int padW, int dilH, int dilW)
{
    const long idx = (long)blockIdx.x * blockDim.x + threadIdx.x;
    const long total = (long)N * C * outH * outW;
    if (idx >= total) return;

    const int ow = (int)(idx % outW);
    const int oh = (int)((idx / outW) % outH);
    const int c  = (int)((idx / ((long)outW * outH)) % C);
    const int n  = (int)(idx / ((long)outW * outH * C));

    const float* in_base = input + ((long)n * C + c) * H * W;
    const float* w_base  = weight + (long)c * KH * KW;

    float sum = (bias != nullptr) ? bias[c] : 0.0f;
    for (int kh = 0; kh < KH; ++kh) {
        const int ih = oh * strideH - padH + kh * dilH;
        if (ih < 0 || ih >= H) continue;
        const float* in_row = in_base + (long)ih * W;
        const float* w_row  = w_base + kh * KW;
        for (int kw = 0; kw < KW; ++kw) {
            const int iw = ow * strideW - padW + kw * dilW;
            if (iw < 0 || iw >= W) continue;
            sum = fmaf(in_row[iw], w_row[kw], sum);
        }
    }
    output[idx] = sum;
}

template <int KH, int KW>
static void launch_tile(
    const float* input, const float* weight, const float* bias, float* output,
    int N, int C, int H, int W, int outH, int outW, int vecOK, cudaStream_t stream)
{
    const int tilesX = (outW + DW_TILE_W - 1) / DW_TILE_W;
    const int tilesY = (outH + DW_TILE_H - 1) / DW_TILE_H;
    const int tilesPerSlice = tilesX * tilesY;
    const long blocks = (long)tilesPerSlice * N * C;
    dim3 grid((unsigned int)blocks);
    dim3 block(DW_TX, DW_TY);
    dwconv2d_tile_kernel<KH, KW><<<grid, block, 0, stream>>>(
        input, weight, bias, output, N, C, H, W, outH, outW, tilesX, tilesPerSlice, vecOK);
}

torch::Tensor dwconv2d_forward(
    torch::Tensor input,
    torch::Tensor weight,
    c10::optional<torch::Tensor> bias,
    int64_t strideH, int64_t strideW,
    int64_t padH, int64_t padW,
    int64_t dilH, int64_t dilW)
{
    TORCH_CHECK(input.is_cuda(), "input must be a CUDA tensor");
    TORCH_CHECK(input.scalar_type() == at::kFloat, "input must be float32");

    auto x = input.contiguous();
    auto w = weight.contiguous();

    const int N  = (int)x.size(0);
    const int C  = (int)x.size(1);
    const int H  = (int)x.size(2);
    const int W  = (int)x.size(3);
    const int KH = (int)w.size(2);
    const int KW = (int)w.size(3);

    const int outH = (int)((H + 2 * padH - dilH * (KH - 1) - 1) / strideH + 1);
    const int outW = (int)((W + 2 * padW - dilW * (KW - 1) - 1) / strideW + 1);

    auto out = torch::empty({N, C, outH, outW}, x.options());
    if (out.numel() == 0) return out;

    const float* in_ptr = x.data_ptr<float>();
    const float* w_ptr  = w.data_ptr<float>();
    float* out_ptr      = out.data_ptr<float>();

    torch::Tensor b;
    const float* b_ptr = nullptr;
    if (bias.has_value() && bias->defined()) {
        b = bias->contiguous();
        b_ptr = b.data_ptr<float>();
    }

    cudaStream_t stream = at::cuda::getCurrentCUDAStream();

    const bool fast = (strideH == 1 && strideW == 1 && padH == 0 && padW == 0 &&
                       dilH == 1 && dilW == 1 && H >= KH && W >= KW);

    if (fast) {
        // 16B-aligned base, 16B-aligned rows and per-slice offsets allow
        // fully vectorized float4 staging.
        const int vecOK = (((reinterpret_cast<uintptr_t>(in_ptr)) & 15) == 0 &&
                           (W & 3) == 0 &&
                           (((long)H * W) & 3) == 0) ? 1 : 0;
        if (KH == 3 && KW == 7) { launch_tile<3, 7>(in_ptr, w_ptr, b_ptr, out_ptr, N, C, H, W, outH, outW, vecOK, stream); return out; }
        if (KH == 7 && KW == 3) { launch_tile<7, 3>(in_ptr, w_ptr, b_ptr, out_ptr, N, C, H, W, outH, outW, vecOK, stream); return out; }
        if (KH == 3 && KW == 3) { launch_tile<3, 3>(in_ptr, w_ptr, b_ptr, out_ptr, N, C, H, W, outH, outW, vecOK, stream); return out; }
        if (KH == 5 && KW == 5) { launch_tile<5, 5>(in_ptr, w_ptr, b_ptr, out_ptr, N, C, H, W, outH, outW, vecOK, stream); return out; }
        if (KH == 7 && KW == 7) { launch_tile<7, 7>(in_ptr, w_ptr, b_ptr, out_ptr, N, C, H, W, outH, outW, vecOK, stream); return out; }
        if (KH == 3 && KW == 1) { launch_tile<3, 1>(in_ptr, w_ptr, b_ptr, out_ptr, N, C, H, W, outH, outW, vecOK, stream); return out; }
        if (KH == 1 && KW == 3) { launch_tile<1, 3>(in_ptr, w_ptr, b_ptr, out_ptr, N, C, H, W, outH, outW, vecOK, stream); return out; }
        if (KH == 1 && KW == 1) { launch_tile<1, 1>(in_ptr, w_ptr, b_ptr, out_ptr, N, C, H, W, outH, outW, vecOK, stream); return out; }
    }

    const long total = (long)N * C * outH * outW;
    const int threads = 256;
    const long blocks = (total + threads - 1) / threads;
    dwconv2d_generic_kernel<<<(unsigned int)blocks, threads, 0, stream>>>(
        in_ptr, w_ptr, b_ptr, out_ptr,
        N, C, H, W, outH, outW,
        KH, KW, (int)strideH, (int)strideW, (int)padH, (int)padW, (int)dilH, (int)dilW);
    return out;
}
"""

dwconv2d_cpp_source = (
    "torch::Tensor dwconv2d_forward(torch::Tensor input, torch::Tensor weight, "
    "c10::optional<torch::Tensor> bias, int64_t strideH, int64_t strideW, "
    "int64_t padH, int64_t padW, int64_t dilH, int64_t dilW);"
)

# Compile the inline CUDA extension
dwconv2d_ext = load_inline(
    name="dwconv2d_ext_v3",
    cpp_sources=dwconv2d_cpp_source,
    cuda_sources=dwconv2d_cuda_source,
    functions=["dwconv2d_forward"],
    verbose=False,
    extra_cuda_cflags=["-O3"],
)


class ModelNew(nn.Module):
    """
    Depthwise 2D convolution backed by a custom CUDA kernel.

    The nn.Conv2d submodule is kept so that parameter initialization and
    state_dict layout exactly match the reference Model.
    """
    def __init__(self, in_channels: int, out_channels: int, kernel_size_h: int, kernel_size_w: int, stride_h: int = 1, stride_w: int = 1, padding_h: int = 0, padding_w: int = 0, dilation_h: int = 1, dilation_w: int = 1, groups: int = 1, bias: bool = False):
        super(ModelNew, self).__init__()
        self.conv2d = nn.Conv2d(in_channels, in_channels, (kernel_size_h, kernel_size_w), stride=(stride_h, stride_w), padding=(padding_h, padding_w), dilation=(dilation_h, dilation_w), groups=in_channels, bias=bias)
        self.stride_h = stride_h
        self.stride_w = stride_w
        self.padding_h = padding_h
        self.padding_w = padding_w
        self.dilation_h = dilation_h
        self.dilation_w = dilation_w

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        weight = self.conv2d.weight
        bias = self.conv2d.bias
        if x.is_cuda and weight.is_cuda and x.dtype == torch.float32 and weight.dtype == torch.float32:
            return dwconv2d_ext.dwconv2d_forward(
                x, weight, bias,
                self.stride_h, self.stride_w,
                self.padding_h, self.padding_w,
                self.dilation_h, self.dilation_w)
        return F.conv2d(
            x, weight, bias,
            stride=(self.stride_h, self.stride_w),
            padding=(self.padding_h, self.padding_w),
            dilation=(self.dilation_h, self.dilation_w),
            groups=self.conv2d.groups)
```

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().
