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

# ----------------------------------------------------------------------------
# Custom CUDA implementation of a strided / dilated / padded 2D convolution.
#
# The kernel is a direct, tiled convolution that is aware of the dilation:
#   * Each thread computes a 3x3 block of outputs whose elements are spaced
#     by the dilation factors (2 in height, 3 in width).  Because of this
#     spacing the 9 outputs of a thread share almost all of their input taps:
#     the whole 3x3x(5x9) stencil only needs a (KH+DIL_H) x (KW+DIL_W) input
#     patch (e.g. 7x11 = 77 values) which is kept in registers.
#   * Input tiles (with halo) and the kernel weights are staged in shared
#     memory, input channels are processed in chunks of two.
#   * Accumulation is done in FP32 (FMA) for full accuracy.
# ----------------------------------------------------------------------------

conv2d_cuda_source = r"""
#include <torch/extension.h>
#include <cuda_runtime.h>
#include <cuda.h>
#include <vector>

#define IC_CHUNK 2
#define THREADS 384
#define TILE_TX 24
#define TILE_TY 16

// Round up shared memory usage to the available limit (nProcs is used as a
// rough proxy for how many resident blocks we can afford).
__device__ __forceinline__ int smem_in_elems(int kh, int kw, int dh, int dw) {
    const int tile_h = TILE_TY / 2 * 3 * dh;              // 48 for dh = 2
    const int tile_w = TILE_TX / 3 * 3 * dw;              // 72 for dw = 3
    const int in_h = tile_h + (kh - 1) * dh;
    const int in_w = tile_w + (kw - 1) * dw;
    return IC_CHUNK * in_h * in_w;
}

__global__ void conv2d_direct_kernel(
    const float* __restrict__ x,
    const float* __restrict__ w,
    const float* __restrict__ bias,
    float* __restrict__ out,
    const int N, const int IC, const int H, const int W,
    const int OC, const int HO, const int WO,
    const int KH, const int KW,
    const int stride_h, const int stride_w,
    const int pad_h, const int pad_w,
    const int dil_h, const int dil_w,
    const bool has_bias) {

    const int tile_h = TILE_TY / 2 * 3 * dil_h;   // output rows per block
    const int tile_w = TILE_TX / 3 * 3 * dil_w;   // output cols per block
    const int in_h = tile_h + (KH - 1) * dil_h;   // input tile rows
    const int in_w = tile_w + (KW - 1) * dil_w;   // input tile cols
    const int in_size = in_h * in_w;

    extern __shared__ float smem[];
    float* s_in = smem;                          // IC_CHUNK * in_size floats
    float* s_w  = smem + IC_CHUNK * in_size;     // IC_CHUNK*KH*KW floats

    const int t  = threadIdx.x;
    const int ty = t / TILE_TX;   // 0..15
    const int tx = t % TILE_TX;   // 0..23

    // Dilation-aware 3x3 output assignment for this thread
    const int r0 = 6 * (ty >> 1) + (ty & 1);    // 0..45, covers parity classes
    const int c0 = 9 * (tx / 3) + (tx % 3);     // 0..65, covers mod-3 classes

    const int bx = blockIdx.x;
    const int by = blockIdx.y;
    const int bz = blockIdx.z;
    const int n  = bz / OC;
    const int oc = bz % OC;

    const int oh0 = by * tile_h;
    const int ow0 = bx * tile_w;

    const int K = KH * KW;

    // Global addresses of this thread's 3x3 outputs
    const int oh_base = oh0 + r0;
    const int ow_base = ow0 + c0;

    // Accumulators
    float acc[3][3];
    #pragma unroll
    for (int i = 0; i < 3; ++i)
        #pragma unroll
        for (int j = 0; j < 3; ++j)
            acc[i][j] = has_bias ? bias[oc] : 0.0f;

    const int ow_max = WO > ow_base ? WO - ow_base : 0;  // remaining cols
    const bool edge_h = (oh_base + (3 - 1) * dil_h) >= HO;
    const bool edge_w = (ow_base + (3 - 1) * dil_w) >= WO;
    const bool edge = edge_h || edge_w;

    // Per-thread clamping of the 3x3 register patch for edge threads.
    int m_lim = 3 * dil_h - (KH - 1) * dil_h;   // rows of patch guaranteed valid
    int n_lim = 3 * dil_w - (KW - 1) * dil_w;   // cols of patch guaranteed valid
    if (edge) {
        const int h_top = oh_base - pad_h;
        const int w_left = ow_base - pad_w;
        for (int m = m_lim; m < (KH - 1) * dil_h + 3 * dil_h; ++m) {
            const int ih = h_top + m;
            if (ih < 0 || ih >= H) break;
            m_lim = m + 1;
        }
        for (int nn = n_lim; nn < (KW - 1) * dil_w + 3 * dil_w; ++nn) {
            const int iw = w_left + nn;
            if (iw < 0 || iw >= W) break;
            n_lim = nn + 1;
        }
    }

    const int w_oc_stride = IC * K;

    for (int ic0 = 0; ic0 < IC; ic0 += IC_CHUNK) {
        const int chunk = min(IC_CHUNK, IC - ic0);
        const int n_reg = chunk * in_size;

        // ---- Stage input tile(s) into shared memory ---------------------
        for (int idx = t; idx < n_reg; idx += THREADS) {
            const int ci = idx / in_size;
            const int rem = idx - ci * in_size;
            const int sr = rem / in_w;
            const int sc = rem - sr * in_w;
            const int ih = oh0 - pad_h + sr;
            const int iw = ow0 - pad_w + sc;
            float v = 0.0f;
            if (ih >= 0 && ih < H && iw >= 0 && iw < W) {
                v = x[((n * IC + (ic0 + ci)) * H + ih) * W + iw];
            }
            s_in[idx] = v;
        }

        // ---- Stage weights into shared memory ---------------------------
        const int w_elems = chunk * K;
        for (int idx = t; idx < w_elems; idx += THREADS) {
            const int ci = idx / K;
            const int k = idx - ci * K;
            const int kh = k / KW;
            const int kw = k - kh * KW;
            s_in[IC_CHUNK * in_size + idx] =
                w[((oc * IC + (ic0 + ci)) * KH + kh) * KW + kw];
        }
        __syncthreads();

        // ---- Compute ----------------------------------------------------
        const int m_stride = in_w;              // dil_h rows apart in smem = dil_h*in_w... handled below
        (void)m_stride;

        for (int ci = 0; ci < chunk; ++ci) {
            const float* s_in_ci = s_in + ci * in_size;
            const float* s_w_ci  = s_in + IC_CHUNK * in_size + ci * K;

            if (!edge) {
                // Interior fast path: whole patch guaranteed in-bounds.
                float seg[3 * 2 + (5 - 1) * 2][3 * 3 + (9 - 1) * 3];  // max 7x11 scaled below
                // NOTE: actual extents depend on runtime dilation; use dynamic loop bounds.
                // Load register patch
                // rows: r0 + m, m = 0 .. (KH-1)*dil_h + 2*dil_h step 1
                // cols: c0 + n, n = 0 .. (KW-1)*dil_w + 2*dil_w step 1
                // We only access m in {i + kh*dil_h} and n in {j + kw*dil_w}.
                // To keep registers small, load the full (7 x 11) patch for
                // dil=(2,3) (general case handled by the slow path below).
                #pragma unroll
                for (int m = 0; m < 7; ++m) {
                    #pragma unroll
                    for (int nn = 0; nn < 11; ++nn) {
                        seg[m][nn] = s_in_ci[(r0 + m) * in_w + (c0 + nn)];
                    }
                }

                #pragma unroll
                for (int kh = 0; kh < 5; ++kh) {
                    #pragma unroll
                    for (int kw = 0; kw < 9; ++kw) {
                        const float wv = s_w_ci[kh * 9 + kw];
                        #pragma unroll
                        for (int i = 0; i < 3; ++i) {
                            #pragma unroll
                            for (int j = 0; j < 3; ++j) {
                                acc[i][j] += seg[i + kh * 2][j + kw * 3] * wv;
                            }
                        }
                    }
                }
            } else {
                // Edge path: clamp the patch, read weights from shared.
                const int m_used = m_lim;
                const int n_used = n_lim;
                float seg[7][11];
                #pragma unroll
                for (int m = 0; m < 7; ++m) {
                    #pragma unroll
                    for (int nn = 0; nn < 11; ++nn) {
                        seg[m][nn] = 0.0f;
                    }
                }
                for (int m = 0; m < m_used; ++m) {
                    for (int nn = 0; nn < n_used; ++nn) {
                        seg[m][nn] = s_in_ci[(r0 + m) * in_w + (c0 + nn)];
                    }
                }

                #pragma unroll
                for (int kh = 0; kh < 5; ++kh) {
                    #pragma unroll
                    for (int kw = 0; kw < 9; ++kw) {
                        const float wv = s_w_ci[kh * 9 + kw];
                        #pragma unroll
                        for (int i = 0; i < 3; ++i) {
                            #pragma unroll
                            for (int j = 0; j < 3; ++j) {
                                acc[i][j] += seg[i + kh * 2][j + kw * 3] * wv;
                            }
                        }
                    }
                }
            }
        }
        __syncthreads();
    }

    // ---- Write outputs --------------------------------------------------
    #pragma unroll
    for (int i = 0; i < 3; ++i) {
        const int oh = oh_base + i * dil_h;
        if (oh < HO) {
            #pragma unroll
            for (int j = 0; j < 3; ++j) {
                const int ow = ow_base + j * dil_w;
                if (ow < WO) {
                    out[((n * OC + oc) * HO + oh) * WO + ow] = acc[i][j];
                }
            }
        }
    }
}

torch::Tensor conv2d_forward(torch::Tensor x, torch::Tensor w,
                             c10::optional<torch::Tensor> bias_opt,
                             std::vector<int64_t> stride,
                             std::vector<int64_t> padding,
                             std::vector<int64_t> dilation) {
    TORCH_CHECK(x.is_cuda() && w.is_cuda(), "inputs must be CUDA");
    TORCH_CHECK(x.scalar_type() == torch::kFloat32, "only float32 supported");
    TORCH_CHECK(x.dim() == 4, "x must be NCHW");

    auto x_c = x.contiguous();
    auto w_c = w.contiguous();

    const int N = x_c.size(0);
    const int IC = x_c.size(1);
    const int H = x_c.size(2);
    const int W = x_c.size(3);
    const int OC = w_c.size(0);
    const int KH = w_c.size(2);
    const int KW = w_c.size(3);

    const int stride_h = stride[0], stride_w = stride[1];
    const int pad_h = padding[0], pad_w = padding[1];
    const int dil_h = dilation[0], dil_w = dilation[1];

    TORCH_CHECK(stride_h == 1 && stride_w == 1, "kernel requires stride 1");
    TORCH_CHECK(dil_h == 2 && dil_w == 3, "kernel specialized for dilation (2,3)");
    TORCH_CHECK(KH == 5 && KW == 9, "kernel specialized for kernel (5,9)");

    const int HO = (H + 2 * pad_h - dil_h * (KH - 1) - 1) / stride_h + 1;
    const int WO = (W + 2 * pad_w - dil_w * (KW - 1) - 1) / stride_w + 1;

    auto out = torch::empty({N, OC, HO, WO}, x_c.options());

    const int tile_h = TILE_TY / 2 * 3 * dil_h;
    const int tile_w = TILE_TX / 3 * 3 * dil_w;

    dim3 grid((WO + tile_w - 1) / tile_w,
              (HO + tile_h - 1) / tile_h,
              N * OC);

    const int in_h = tile_h + (KH - 1) * dil_h;
    const int in_w = tile_w + (KW - 1) * dil_w;
    const size_t smem = (IC_CHUNK * in_h * in_w + IC_CHUNK * KH * KW) * sizeof(float);

    const bool has_bias = bias_opt.has_value() && bias_opt->defined();
    const float* bias_ptr = nullptr;
    torch::Tensor bias_c;
    if (has_bias) {
        bias_c = bias_opt->contiguous();
        bias_ptr = bias_c.data_ptr<float>();
    }

    auto stream = at::cuda::getCurrentCUDAStream();
    conv2d_direct_kernel<<<grid, THREADS, smem, stream>>>(
        x_c.data_ptr<float>(), w_c.data_ptr<float>(), bias_ptr,
        out.data_ptr<float>(),
        N, IC, H, W, OC, HO, WO, KH, KW,
        stride_h, stride_w, pad_h, pad_w, dil_h, dil_w, has_bias);

    return out;
}
"""

conv2d_cpp_source = r"""
#include <torch/extension.h>
#include <vector>
torch::Tensor conv2d_forward(torch::Tensor x, torch::Tensor w,
                             c10::optional<torch::Tensor> bias,
                             std::vector<int64_t> stride,
                             std::vector<int64_t> padding,
                             std::vector<int64_t> dilation);
"""

conv2d_ext = load_inline(
    name="conv2d_dilated_tiled",
    cpp_sources=[conv2d_cpp_source],
    cuda_sources=[conv2d_cuda_source],
    functions=["conv2d_forward"],
    verbose=False,
    extra_cuda_cflags=["-O3", "--use_fast_math"],
    extra_cflags=["-O3"],
)


def _pair(v):
    if isinstance(v, (tuple, list)):
        return int(v[0]), int(v[1])
    return int(v), int(v)


class ModelNew(nn.Module):
    """
    Optimized version of Model.  Keeps an nn.Conv2d module so that
    initialization / state_dict are identical to the reference model, but
    computes the forward pass with a custom tiled CUDA kernel that exploits
    the dilation structure (register-blocked 3x3 outputs spaced by the
    dilation, shared-memory input tiles, fully unrolled 5x9 tap loop).
    """

    def __init__(self, in_channels: int, out_channels: int, kernel_size: tuple,
                 stride: int = 1, padding: tuple = (0, 0),
                 dilation: tuple = (1, 1), bias: bool = False):
        super(ModelNew, self).__init__()
        self.conv2d = nn.Conv2d(in_channels, out_channels, kernel_size,
                                stride=stride, padding=padding,
                                dilation=dilation, bias=bias)

        k = _pair(kernel_size)
        s = _pair(stride)
        p = _pair(padding)
        d = _pair(dilation)

        self._stride = [s[0], s[1]]
        self._padding = [p[0], p[1]]
        self._dilation = [d[0], d[1]]
        # The custom kernel is specialized for the configuration of this
        # architecture; fall back to cuDNN for anything else.
        self._use_custom = (k == (5, 9) and s == (1, 1) and d == (2, 3))

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        if self._use_custom and x.is_cuda and x.dtype == torch.float32:
            return conv2d_ext.conv2d_forward(
                x, self.conv2d.weight, self.conv2d.bias,
                self._stride, self._padding, self._dilation)
        return self.conv2d(x)
```