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

torch.backends.cudnn.benchmark = True

# Fully fused CUDA kernel:
#   conv2d(3x3, Cin=8, fp16 tensor-core mma) + AvgPool(4x4) + sigmoid + global sum
# in ONE kernel launch. The fp32 NCHW input is converted to fp16 on the fly into
# shared memory (fusing the cast + NCHW->NHWC transpose), tiles of 4x4 pooling
# windows are computed with mma.m16n8k16 (one m16 tile == one 4x4 pool window),
# and only one fp32 scalar per image is written. This avoids materializing the
# ~2.4 GB fp16 conv output entirely (no conv-output write/read, no layout
# re-transposes).
_mma_src = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda_runtime.h>
#include <cuda_fp16.h>

#define WIN_DIM 4                 // block covers 4x4 pooling windows
#define TILE_PIX 16               // 4x4 windows -> 16x16 conv output pixels
#define PATCH_DIM (TILE_PIX + 2)  // 18x18 input pixels needed
#define PATCH_STRIDE 20           // padded row stride (pixels)
#define KPAD 80                   // K=72 padded to 5 chunks of 16
#define WSM_STRIDE 82             // padded weight row stride (halves)
#define SMEM_IN_HALVES (PATCH_DIM * PATCH_STRIDE * 8)
#define SMEM_W_HALVES (64 * WSM_STRIDE)

__device__ __forceinline__ void mma16816(float* c, const uint32_t* a, const uint32_t* b) {
    asm volatile(
        "mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 "
        "{%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};\n"
        : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3])
        : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b[0]), "r"(b[1]));
}

__global__ void __launch_bounds__(256)
fused_conv_pool_sigmoid_sum_mma_kernel(
        const float* __restrict__ x,       // [N,8,H,W] fp32
        const __half* __restrict__ wk,     // [64][KPAD] fp16 (n-major, k contiguous)
        float* __restrict__ out,           // [N] fp32
        const int H, const int W, const int Hp, const int Wp,
        const int tilesY, const int tilesX) {
    __shared__ __half smem_in[SMEM_IN_HALVES];
    __shared__ __half smem_w[SMEM_W_HALVES];
    __shared__ float red[8];

    const int t = threadIdx.x;
    const int n = blockIdx.z;
    const int ty = blockIdx.y;
    const int tx = blockIdx.x;
    const int py0 = ty * TILE_PIX;
    const int px0 = tx * TILE_PIX;

    // ---- load weights [64][KPAD] into smem (row stride WSM_STRIDE) ----
    {
        const uint2* src = reinterpret_cast<const uint2*>(wk);
        uint2* dst = reinterpret_cast<uint2*>(smem_w);
        #pragma unroll
        for (int i = t; i < 1280; i += 256) {
            dst[i] = src[i];
        }
    }

    // ---- load input patch (18x18 px, 8 ch) fp32 NCHW -> fp16 smem ----
    {
        const int area = H * W;
        const float* xbase = x + (size_t)n * 8 * area;
        #pragma unroll
        for (int i = t; i < 2592; i += 256) {
            const int q = i & 3;
            const int r = i >> 2;
            const int dx = r % PATCH_DIM;
            const int dy = r / PATCH_DIM;
            const int gy = py0 + dy;
            const int gx = px0 + dx;
            float2 v = make_float2(0.f, 0.f);
            if (gy < H && gx < W) {
                const size_t off = (size_t)gy * W + gx;
                v.x = xbase[(size_t)(2 * q) * area + off];
                v.y = xbase[(size_t)(2 * q + 1) * area + off];
            }
            *reinterpret_cast<__half2*>(
                &smem_in[((dy * PATCH_STRIDE) + dx) * 8 + 2 * q]) = __floats2half2_rn(v.x, v.y);
        }
    }
    __syncthreads();

    const int warp = t >> 5;
    const int lane = t & 31;
    const int groupID = lane >> 2;   // row within 8-row group
    const int tig = lane & 3;        // thread-in-group (column pair)

    // window assignment: 16 windows / 8 warps = 2 windows per warp
    const int wslot0 = warp << 1;
    const int w0y = (wslot0 >> 2) << 2, w0x = (wslot0 & 3) << 2;   // pixel origin of window 0
    const int w1y = w0y, w1x = w0x + 4;                            // window 1 (same row, +4 px)

    const int gwy0 = (ty << 2) + (wslot0 >> 2);
    const int gwx0 = (tx << 2) + (wslot0 & 3);
    const bool valid0 = (gwy0 < Hp) && (gwx0 < Wp);
    const bool valid1 = (gwy0 < Hp) && (gwx0 + 1 < Wp);

    float acc0[8][4], acc1[8][4];
    #pragma unroll
    for (int i = 0; i < 8; ++i)
        #pragma unroll
        for (int j = 0; j < 4; ++j) { acc0[i][j] = 0.f; acc1[i][j] = 0.f; }

    const int bpair = 2 * tig;
    const int bn = groupID;

    #pragma unroll
    for (int ch = 0; ch < 5; ++ch) {
        const int tap0 = 2 * ch;
        const int r0 = tap0 / 3, q0 = tap0 % 3;
        const int tap1 = (tap0 < 8) ? (tap0 + 1) : 8;
        const int r1 = tap1 / 3, q1 = tap1 % 3;

        // A fragments (window 0 and window 1)
        uint32_t A0[4], A1[4];
        {
            const int rA = groupID;         // rows 0-7
            const int rB = groupID + 8;     // rows 8-15
            // window 0
            {
                const int ya = w0y + (rA >> 2), xa = w0x + (rA & 3);
                const int yb = w0y + (rB >> 2), xb = w0x + (rB & 3);
                A0[0] = *reinterpret_cast<const uint32_t*>(&smem_in[((ya + r0) * PATCH_STRIDE + (xa + q0)) * 8 + bpair]);
                A0[1] = *reinterpret_cast<const uint32_t*>(&smem_in[((yb + r0) * PATCH_STRIDE + (xb + q0)) * 8 + bpair]);
                A0[2] = *reinterpret_cast<const uint32_t*>(&smem_in[((ya + r1) * PATCH_STRIDE + (xa + q1)) * 8 + bpair]);
                A0[3] = *reinterpret_cast<const uint32_t*>(&smem_in[((yb + r1) * PATCH_STRIDE + (xb + q1)) * 8 + bpair]);
            }
            // window 1
            {
                const int ya = w1y + (rA >> 2), xa = w1x + (rA & 3);
                const int yb = w1y + (rB >> 2), xb = w1x + (rB & 3);
                A1[0] = *reinterpret_cast<const uint32_t*>(&smem_in[((ya + r0) * PATCH_STRIDE + (xa + q0)) * 8 + bpair]);
                A1[1] = *reinterpret_cast<const uint32_t*>(&smem_in[((yb + r0) * PATCH_STRIDE + (xb + q0)) * 8 + bpair]);
                A1[2] = *reinterpret_cast<const uint32_t*>(&smem_in[((ya + r1) * PATCH_STRIDE + (xa + q1)) * 8 + bpair]);
                A1[3] = *reinterpret_cast<const uint32_t*>(&smem_in[((yb + r1) * PATCH_STRIDE + (xb + q1)) * 8 + bpair]);
            }
        }

        #pragma unroll
        for (int nt = 0; nt < 8; ++nt) {
            const __half* wp = &smem_w[(nt * 8 + bn) * WSM_STRIDE + ch * 16];
            uint32_t B[2];
            B[0] = *reinterpret_cast<const uint32_t*>(wp + bpair);
            B[1] = *reinterpret_cast<const uint32_t*>(wp + bpair + 8);
            mma16816(acc0[nt], A0, B);
            mma16816(acc1[nt], A1, B);
        }
    }

    // ---- pool (4x4 mean) + sigmoid, accumulate ----
    float wsum0 = 0.f, wsum1 = 0.f;
    if (valid0) {
        #pragma unroll
        for (int nt = 0; nt < 8; ++nt) {
            float* c = acc0[nt];
            #pragma unroll
            for (int off = 4; off < 32; off <<= 1) {
                c[0] += __shfl_down_sync(0xffffffffu, c[0], off);
                c[1] += __shfl_down_sync(0xffffffffu, c[1], off);
                c[2] += __shfl_down_sync(0xffffffffu, c[2], off);
                c[3] += __shfl_down_sync(0xffffffffu, c[3], off);
            }
            if (groupID == 0) {
                wsum0 += 1.0f / (1.0f + expf(-(c[0] + c[2]) * 0.0625f))
                       + 1.0f / (1.0f + expf(-(c[1] + c[3]) * 0.0625f));
            }
        }
    }
    if (valid1) {
        #pragma unroll
        for (int nt = 0; nt < 8; ++nt) {
            float* c = acc1[nt];
            #pragma unroll
            for (int off = 4; off < 32; off <<= 1) {
                c[0] += __shfl_down_sync(0xffffffffu, c[0], off);
                c[1] += __shfl_down_sync(0xffffffffu, c[1], off);
                c[2] += __shfl_down_sync(0xffffffffu, c[2], off);
                c[3] += __shfl_down_sync(0xffffffffu, c[3], off);
            }
            if (groupID == 0) {
                wsum1 += 1.0f / (1.0f + expf(-(c[0] + c[2]) * 0.0625f))
                       + 1.0f / (1.0f + expf(-(c[1] + c[3]) * 0.0625f));
            }
        }
    }
    float wsum = wsum0 + wsum1;
    if (groupID == 0) {
        wsum += __shfl_xor_sync(0xffffffffu, wsum, 1);
        wsum += __shfl_xor_sync(0xffffffffu, wsum, 2);
        if (lane == 0) red[warp] = wsum;
    }
    __syncthreads();
    if (t == 0) {
        float s = 0.f;
        #pragma unroll
        for (int i = 0; i < 8; ++i) s += red[i];
        atomicAdd(&out[n], s);
    }
}

torch::Tensor fused_conv3x3_c8_pool4_sigmoid_sum(
        torch::Tensor x, torch::Tensor wk) {
    TORCH_CHECK(x.is_cuda() && x.dim() == 4, "input must be CUDA NCHW");
    TORCH_CHECK(x.scalar_type() == torch::kFloat, "input must be fp32");
    auto xc = x.contiguous();
    const int N = (int)xc.size(0);
    const int C = (int)xc.size(1);
    const int H = (int)xc.size(2);
    const int W = (int)xc.size(3);
    TORCH_CHECK(C == 8, "in_channels must be 8");
    TORCH_CHECK(wk.is_cuda() && wk.scalar_type() == torch::kHalf, "wk must be CUDA fp16");
    TORCH_CHECK(wk.numel() == 64 * KPAD, "wk must be [64,80]");

    auto wkc = wk.contiguous();
    const int Ho = H - 2;
    const int Wo = W - 2;
    const int Hp = Ho / 4;
    const int Wp = Wo / 4;

    auto out = torch::zeros({N}, xc.options().dtype(torch::kFloat32));
    if (N == 0 || Hp == 0 || Wp == 0) return out;

    const int tilesY = (Hp + WIN_DIM - 1) / WIN_DIM;
    const int tilesX = (Wp + WIN_DIM - 1) / WIN_DIM;
    dim3 grid(tilesX, tilesY, N);
    auto stream = at::cuda::getCurrentCUDAStream();
    fused_conv_pool_sigmoid_sum_mma_kernel<<<grid, 256, 0, stream>>>(
        xc.data_ptr<float>(),
        reinterpret_cast<const __half*>(wkc.data_ptr<at::Half>()),
        out.data_ptr<float>(),
        H, W, Hp, Wp, tilesY, tilesX);
    return out;
}
"""

_mma_cpp = (
    "torch::Tensor fused_conv3x3_c8_pool4_sigmoid_sum(torch::Tensor x, torch::Tensor wk);"
)

_mma_ext = load_inline(
    name="fused_conv_pool_sigmoid_sum_mma_v3",
    cpp_sources=_mma_cpp,
    cuda_sources=_mma_src,
    functions=["fused_conv3x3_c8_pool4_sigmoid_sum"],
    verbose=False,
    extra_cuda_cflags=["-O3"],
)

# Backup fused ops (AvgPool + sigmoid + global sum) used when the conv runs via
# cuDNN for configurations the mma kernel does not cover.
_cuda_src = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda_runtime.h>
#include <cuda_fp16.h>

namespace {

__device__ __forceinline__ void block_reduce_atomic(float acc, float* out) {
    #pragma unroll
    for (int off = 16; off > 0; off >>= 1)
        acc += __shfl_down_sync(0xffffffffu, acc, off);
    __shared__ float warp_sums[32];
    const int lane = threadIdx.x & 31;
    const int wid  = threadIdx.x >> 5;
    if (lane == 0) warp_sums[wid] = acc;
    __syncthreads();
    if (wid == 0) {
        const int nwarps = (blockDim.x + 31) >> 5;
        float v = (lane < nwarps) ? warp_sums[lane] : 0.0f;
        #pragma unroll
        for (int off = 16; off > 0; off >>= 1)
            v += __shfl_down_sync(0xffffffffu, v, off);
        if (lane == 0) atomicAdd(out, v);
    }
}

__global__ void nchw_to_nhwc_fp16_c8_kernel(
        const float* __restrict__ in, __half* __restrict__ out,
        const size_t HW, const size_t total_pixels) {
    const size_t p = (size_t)blockIdx.x * blockDim.x + threadIdx.x;
    if (p >= total_pixels) return;
    const size_t n = p / HW;
    const size_t s = p - n * HW;
    const float* base = in + n * 8 * HW + s;
    uint4 packed;
    __half2* ph = reinterpret_cast<__half2*>(&packed);
    #pragma unroll
    for (int c = 0; c < 4; ++c) {
        ph[c] = __floats2half2_rn(base[(size_t)(2 * c) * HW],
                                  base[(size_t)(2 * c + 1) * HW]);
    }
    *reinterpret_cast<uint4*>(out + p * 8) = packed;
}

__global__ void nchw_to_nhwc_fp16_generic_kernel(
        const float* __restrict__ in, __half* __restrict__ out,
        const int C, const size_t HW, const size_t total) {
    const size_t idx = (size_t)blockIdx.x * blockDim.x + threadIdx.x;
    if (idx >= total) return;
    const int c = (int)(idx % (size_t)C);
    const size_t p = idx / (size_t)C;
    const size_t n = p / HW;
    const size_t s = p - n * HW;
    out[idx] = __float2half_rn(in[(n * (size_t)C + c) * HW + s]);
}

template <int POOL>
__global__ void fused_pool_sigmoid_sum_nhwc_kernel(
        const __half* __restrict__ x, float* __restrict__ out,
        const int C, const int H, const int W,
        const int Hp, const int Wp, const int units_per_image) {
    const int n = blockIdx.y;
    const __half* __restrict__ img = x + (size_t)n * ((size_t)H * W * C);
    const int cg_count = C >> 3;

    float acc = 0.0f;
    const int stride = gridDim.x * blockDim.x;
    for (int v = blockIdx.x * blockDim.x + threadIdx.x; v < units_per_image; v += stride) {
        const int cg = v % cg_count;
        const int t  = v / cg_count;
        const int wx = t % Wp;
        const int wy = t / Wp;
        const int c0 = cg << 3;

        const __half* base = img + ((size_t)(wy * POOL) * W + (size_t)(wx * POOL)) * C + c0;
        float sums[8] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};
        #pragma unroll
        for (int r = 0; r < POOL; ++r) {
            const __half* row = base + (size_t)r * W * C;
            #pragma unroll
            for (int q = 0; q < POOL; ++q) {
                const uint4 raw = *reinterpret_cast<const uint4*>(row + (size_t)q * C);
                const __half2* h2 = reinterpret_cast<const __half2*>(&raw);
                #pragma unroll
                for (int i = 0; i < 4; ++i) {
                    const float2 f = __half22float2(h2[i]);
                    sums[2 * i]     += f.x;
                    sums[2 * i + 1] += f.y;
                }
            }
        }
        constexpr float inv = 1.0f / (float)(POOL * POOL);
        #pragma unroll
        for (int i = 0; i < 8; ++i) {
            const float m = sums[i] * inv;
            acc += 1.0f / (1.0f + expf(-m));
        }
    }
    block_reduce_atomic(acc, &out[n]);
}

__device__ __forceinline__ float2 load_two(const float* p) {
    return *reinterpret_cast<const float2*>(p);
}
__device__ __forceinline__ float2 load_two(const __half* p) {
    return __half22float2(*reinterpret_cast<const __half2*>(p));
}

template <typename scalar_t, int POOL>
__global__ void fused_pool_sigmoid_sum_nchw_kernel(
        const scalar_t* __restrict__ x, float* __restrict__ out,
        const int C, const int H, const int W,
        const int Hp, const int Wp, const int num_windows) {
    const int n = blockIdx.y;
    const scalar_t* __restrict__ img = x + (size_t)n * C * H * W;

    float acc = 0.0f;
    const int stride = gridDim.x * blockDim.x;
    constexpr float inv = 1.0f / (float)(POOL * POOL);

    for (int v = blockIdx.x * blockDim.x + threadIdx.x; v < num_windows; v += stride) {
        const int wx = v % Wp;
        const int t  = v / Wp;
        const int wy = t % Hp;
        const int c  = t / Hp;

        const scalar_t* p = img + ((size_t)c * H + (size_t)wy * POOL) * W + (size_t)wx * POOL;
        float s = 0.0f;
        #pragma unroll
        for (int r = 0; r < POOL; ++r) {
            #pragma unroll
            for (int q = 0; q < POOL / 2; ++q) {
                const float2 val = load_two(p + 2 * q);
                s += val.x + val.y;
            }
            p += W;
        }
        const float m = s * inv;
        acc += 1.0f / (1.0f + expf(-m));
    }
    block_reduce_atomic(acc, &out[n]);
}

} // namespace

torch::Tensor nchw_to_nhwc_fp16(torch::Tensor x) {
    TORCH_CHECK(x.is_cuda() && x.dim() == 4, "input must be CUDA NCHW");
    TORCH_CHECK(x.scalar_type() == torch::kFloat, "input must be fp32");
    auto xc = x.contiguous();
    const int64_t N = xc.size(0), C = xc.size(1), H = xc.size(2), W = xc.size(3);

    auto out = torch::empty({N, C, H, W},
        xc.options().dtype(torch::kHalf).memory_format(torch::MemoryFormat::ChannelsLast));

    const size_t HW = (size_t)H * (size_t)W;
    const size_t total_pixels = (size_t)N * HW;
    if (total_pixels == 0) return out;

    auto stream = at::cuda::getCurrentCUDAStream();
    const int threads = 256;
    __half* out_ptr = reinterpret_cast<__half*>(out.data_ptr<at::Half>());

    if (C == 8) {
        const size_t blocks = (total_pixels + threads - 1) / threads;
        nchw_to_nhwc_fp16_c8_kernel<<<blocks, threads, 0, stream>>>(
            xc.data_ptr<float>(), out_ptr, HW, total_pixels);
    } else {
        const size_t total = total_pixels * (size_t)C;
        const size_t blocks = (total + threads - 1) / threads;
        nchw_to_nhwc_fp16_generic_kernel<<<blocks, threads, 0, stream>>>(
            xc.data_ptr<float>(), out_ptr, (int)C, HW, total);
    }
    return out;
}

torch::Tensor fused_pool_sigmoid_sum_nhwc(torch::Tensor x, int64_t pool) {
    TORCH_CHECK(x.is_cuda() && x.dim() == 4, "input must be CUDA NCHW4d");
    TORCH_CHECK(x.scalar_type() == torch::kHalf, "input must be fp16");
    TORCH_CHECK(x.is_contiguous(at::MemoryFormat::ChannelsLast), "input must be channels_last");

    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);
    TORCH_CHECK(C % 8 == 0, "channels must be a multiple of 8");

    const int Hp = H / (int)pool;
    const int Wp = W / (int)pool;
    auto out = torch::zeros({N}, x.options().dtype(torch::kFloat32));
    if (N == 0 || C == 0 || Hp == 0 || Wp == 0) return out;

    const int units = Hp * Wp * (C >> 3);
    const int threads = 256;
    int blocks = (units + threads - 1) / threads;
    if (blocks > 1024) blocks = 1024;
    dim3 grid(blocks, N);
    auto stream = at::cuda::getCurrentCUDAStream();
    const __half* ptr = reinterpret_cast<const __half*>(x.data_ptr<at::Half>());

    if (pool == 4) {
        fused_pool_sigmoid_sum_nhwc_kernel<4><<<grid, threads, 0, stream>>>(
            ptr, out.data_ptr<float>(), C, H, W, Hp, Wp, units);
    } else if (pool == 2) {
        fused_pool_sigmoid_sum_nhwc_kernel<2><<<grid, threads, 0, stream>>>(
            ptr, out.data_ptr<float>(), C, H, W, Hp, Wp, units);
    } else {
        TORCH_CHECK(false, "unsupported pool size");
    }
    return out;
}

torch::Tensor fused_pool_sigmoid_sum_nchw(torch::Tensor x, int64_t pool) {
    TORCH_CHECK(x.is_cuda() && x.dim() == 4, "input must be CUDA NCHW");
    auto xc = x.contiguous();

    const int N = (int)xc.size(0);
    const int C = (int)xc.size(1);
    const int H = (int)xc.size(2);
    const int W = (int)xc.size(3);
    TORCH_CHECK(W % 2 == 0, "width must be even");

    const int Hp = H / (int)pool;
    const int Wp = W / (int)pool;
    auto out = torch::zeros({N}, xc.options().dtype(torch::kFloat32));
    if (N == 0 || C == 0 || Hp == 0 || Wp == 0) return out;

    const int num_windows = C * Hp * Wp;
    const int threads = 256;
    int blocks = (num_windows + threads - 1) / threads;
    if (blocks > 1024) blocks = 1024;
    dim3 grid(blocks, N);
    auto stream = at::cuda::getCurrentCUDAStream();

    if (xc.scalar_type() == torch::kHalf) {
        const __half* ptr = reinterpret_cast<const __half*>(xc.data_ptr<at::Half>());
        if (pool == 4) {
            fused_pool_sigmoid_sum_nchw_kernel<__half, 4><<<grid, threads, 0, stream>>>(
                ptr, out.data_ptr<float>(), C, H, W, Hp, Wp, num_windows);
        } else if (pool == 2) {
            fused_pool_sigmoid_sum_nchw_kernel<__half, 2><<<grid, threads, 0, stream>>>(
                ptr, out.data_ptr<float>(), C, H, W, Hp, Wp, num_windows);
        } else {
            TORCH_CHECK(false, "unsupported pool size");
        }
    } else if (xc.scalar_type() == torch::kFloat) {
        const float* ptr = xc.data_ptr<float>();
        if (pool == 4) {
            fused_pool_sigmoid_sum_nchw_kernel<float, 4><<<grid, threads, 0, stream>>>(
                ptr, out.data_ptr<float>(), C, H, W, Hp, Wp, num_windows);
        } else if (pool == 2) {
            fused_pool_sigmoid_sum_nchw_kernel<float, 2><<<grid, threads, 0, stream>>>(
                ptr, out.data_ptr<float>(), C, H, W, Hp, Wp, num_windows);
        } else {
            TORCH_CHECK(false, "unsupported pool size");
        }
    } else {
        TORCH_CHECK(false, "unsupported dtype");
    }
    return out;
}
"""

_cpp_src = (
    "torch::Tensor nchw_to_nhwc_fp16(torch::Tensor x);\n"
    "torch::Tensor fused_pool_sigmoid_sum_nhwc(torch::Tensor x, int64_t pool);\n"
    "torch::Tensor fused_pool_sigmoid_sum_nchw(torch::Tensor x, int64_t pool);"
)

_ext = load_inline(
    name="conv_pool_sigmoid_fused_v2",
    cpp_sources=_cpp_src,
    cuda_sources=_cuda_src,
    functions=[
        "nchw_to_nhwc_fp16",
        "fused_pool_sigmoid_sum_nhwc",
        "fused_pool_sigmoid_sum_nchw",
    ],
    verbose=False,
    extra_cuda_cflags=["-O3"],
)


class ModelNew(nn.Module):
    """
    Optimized version:
      * Fast path: a single custom tensor-core (mma.m16n8k16) kernel fuses the
        3x3 conv (fp16, fp32 accumulation), the 4x4 average pool, the sigmoid
        and the global sum. The fp32 NCHW input is converted to fp16 directly
        into shared memory (fusing the cast + layout transpose), and the
        ~2.4 GB conv output is never materialized.
      * Backup path: cuDNN fp16 channels_last conv + a fused
        pool+sigmoid+sum kernel.
      * Fallback: original PyTorch ops.
    """
    def __init__(self, in_channels, out_channels, kernel_size, pool_kernel_size):
        super(ModelNew, self).__init__()
        self.conv = nn.Conv2d(in_channels, out_channels, kernel_size)
        self.avg_pool = nn.AvgPool2d(pool_kernel_size)
        self.pool_kernel_size = pool_kernel_size
        self._wk = None
        self._w16 = None
        self._b16 = None
        self._w_key = None

    def _refresh_caches(self):
        w = self.conv.weight
        key = (w.data_ptr(), w._version)
        if self._w_key == key:
            return
        self._w_key = key
        b = self.conv.bias
        # Rearranged + zero-padded fp16 weights [64, 80] (n-major, k contiguous),
        # bias folded into the padded k entries (k = 72..79).
        try:
            if (
                w.shape[1] == 8
                and w.shape[2] == 3
                and w.shape[3] == 3
                and w.shape[0] % 8 == 0
                and w.shape[0] <= 64
            ):
                co = w.shape[0]
                wp = w.detach().permute(1, 2, 3, 0).reshape(72, co).half()
                wk = w.new_zeros((co, 80), dtype=torch.float16, device=w.device)
                wk[:, :72] = wp.t().contiguous()
                if b is not None:
                    wk[:, 72] = b.detach().half() * 16.0
                self._wk = wk
            else:
                self._wk = None
        except Exception:
            self._wk = None
        try:
            self._w16 = w.detach().half().contiguous(memory_format=torch.channels_last)
            self._b16 = b.detach().half() if b is not None else None
        except Exception:
            self._w16 = None
            self._b16 = None

    def forward(self, x):
        pool = self.pool_kernel_size
        fast_mma = (
            x.is_cuda
            and x.dtype == torch.float32
            and isinstance(pool, int)
            and pool == 4
            and self.conv.in_channels == 8
            and self.conv.kernel_size[0] == 3
            and self.conv.kernel_size[1] == 3
            and self.conv.stride == (1, 1)
            and self.conv.padding == (0, 0)
            and self.conv.dilation == (1, 1)
            and self.conv.groups == 1
            and self.conv.out_channels == 64
            and x.size(2) >= 3
            and x.size(3) >= 3
        )
        if fast_mma:
            try:
                self._refresh_caches()
                if self._wk is not None:
                    return _mma_ext.fused_conv3x3_c8_pool4_sigmoid_sum(x, self._wk)
            except RuntimeError:
                pass

        fast_v2 = (
            x.is_cuda
            and x.dtype == torch.float32
            and isinstance(pool, int)
            and pool in (2, 4)
            and self.conv.out_channels % 8 == 0
        )
        if fast_v2:
            try:
                self._refresh_caches()
                if self._w16 is not None:
                    x16 = _ext.nchw_to_nhwc_fp16(x)
                    y = F.conv2d(
                        x16,
                        self._w16,
                        self._b16,
                        self.conv.stride,
                        self.conv.padding,
                        self.conv.dilation,
                        self.conv.groups,
                    )
                    if y.is_contiguous(memory_format=torch.channels_last):
                        return _ext.fused_pool_sigmoid_sum_nhwc(y, pool)
                    if y.is_contiguous() and y.shape[-1] % 2 == 0:
                        return _ext.fused_pool_sigmoid_sum_nchw(y, pool)
                    y = self.avg_pool(y.float())
                    return torch.sum(torch.sigmoid(y), dim=[1, 2, 3])
            except RuntimeError:
                pass

        x = self.conv(x)
        x = self.avg_pool(x)
       