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

# Match the reference numerics settings (TF32) for any fallback paths.
try:
    torch.backends.cuda.matmul.allow_tf32 = True
    torch.backends.cudnn.allow_tf32 = True
    torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction = True
except Exception:
    pass

# v2 strategy (training-mode forward is the benchmarked path):
#   1. Custom vectorized fp32 -> fp16 cast kernel (replaces slow ATen copy).
#   2. Bias-free fp16 tensor-core GEMM via cublasLt with one-time autotuning
#      over the available algorithms (fp32 accumulate). The Linear bias is
#      algebraically cancelled by BatchNorm's mean subtraction in training
#      mode, and is folded into the affine coefficient in eval mode / for the
#      running-mean update, so results are unchanged.
#   3. Column batch-statistics via a high-occupancy fp16->fp32 reduction
#      kernel with float atomics into a persistent scratch buffer (kept
#      zeroed by the finish kernel, removing the separate memset launch).
#   4. Tiny finish kernel folding BatchNorm + scalar scale into per-channel
#      affine coefficients (and updating running stats exactly like ATen).
#   5. Fused affine + numerically-stable softmax kernel, one block per row,
#      values cached in registers, fast __expf, fp32 output.
_cuda_source = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda_runtime.h>
#include <cuda_fp16.h>
#include <cublasLt.h>
#include <math.h>

#define BLOCK_SIZE 256
#define NUM_WARPS (BLOCK_SIZE / 32)
#define MAX_ITERS 4
#define STATS_THREADS 256
#define ROWS_PER_BLOCK 8
#define LT_NUM_ALGOS 48
#define LT_WORKSPACE_CAP (64 * 1024 * 1024)

// ---------------------------------------------------------------------------
// Vectorized fp32 -> fp16 cast. Each thread converts 8 floats.
// ---------------------------------------------------------------------------
__global__ void cast_f32_to_f16_kernel(
    const float4* __restrict__ x,
    float4* __restrict__ out,
    long nvec8)
{
    long i = (long)blockIdx.x * blockDim.x + threadIdx.x;
    if (i >= nvec8) return;
    float4 f0 = x[2 * i];
    float4 f1 = x[2 * i + 1];
    __half2 h[4];
    h[0] = __floats2half2_rn(f0.x, f0.y);
    h[1] = __floats2half2_rn(f0.z, f0.w);
    h[2] = __floats2half2_rn(f1.x, f1.y);
    h[3] = __floats2half2_rn(f1.z, f1.w);
    out[i] = *reinterpret_cast<float4*>(h);
}

// ---------------------------------------------------------------------------
// Per-column sum / sum-of-squares over an fp16 [B, n] matrix accumulated in
// fp32 (ATen batch-norm also accumulates in float for fp32 inputs). Uses
// float atomics into a pre-zeroed persistent scratch buffer.
// ---------------------------------------------------------------------------
__global__ void col_stats_half_kernel(
    const float4* __restrict__ xh,
    float* __restrict__ sum,
    float* __restrict__ sumsq,
    int B,
    int nvec8,
    int rows_per_block)
{
    int c = blockIdx.x * STATS_THREADS + threadIdx.x;
    if (c >= nvec8) return;
    int r0 = blockIdx.y * rows_per_block;
    int r1 = min(B, r0 + rows_per_block);

    float s[8], q[8];
    #pragma unroll
    for (int k = 0; k < 8; ++k) { s[k] = 0.0f; q[k] = 0.0f; }

    const float4* p = xh + (size_t)r0 * nvec8 + c;
    #pragma unroll
    for (int r = 0; r < ROWS_PER_BLOCK; ++r) {
        if (r0 + r < r1) {
            float4 raw = *p;
            const __half2* h = reinterpret_cast<const __half2*>(&raw);
            #pragma unroll
            for (int k = 0; k < 4; ++k) {
                float2 f = __half22float2(h[k]);
                s[2 * k]     += f.x;
                s[2 * k + 1] += f.y;
                q[2 * k]     += f.x * f.x;
                q[2 * k + 1] += f.y * f.y;
            }
        }
        p += nvec8;
    }
    int base = c * 8;
    #pragma unroll
    for (int k = 0; k < 8; ++k) {
        atomicAdd(&sum[base + k], s[k]);
        atomicAdd(&sumsq[base + k], q[k]);
    }
}

// ---------------------------------------------------------------------------
// Fold BatchNorm (+ running-stat update, + Linear bias where needed) and the
// scalar scale into per-channel affine coefficients z = a * y' + b, where
// y' is the bias-free GEMM output. Also re-zeros the stats scratch.
//   training : mean/var from batch stats of y'; bias cancels in the forward
//              affine exactly, but is added back for the running_mean update.
//   eval     : bias folded into b since y' lacks it.
// ---------------------------------------------------------------------------
__global__ void finish_coef_kernel(
    float* __restrict__ sum,
    float* __restrict__ sumsq,
    float* __restrict__ running_mean,
    float* __restrict__ running_var,
    long long* __restrict__ nbt,
    const float* __restrict__ gamma,
    const float* __restrict__ beta,
    const float* __restrict__ scale,
    const float* __restrict__ bias,
    float* __restrict__ a,
    float* __restrict__ b,
    double momentum,
    double eps,
    int n,
    int batch,
    int training)
{
    if (training && blockIdx.x == 0 && threadIdx.x == 0 && nbt != nullptr) {
        *nbt += 1;
    }
    int j = blockIdx.x * blockDim.x + threadIdx.x;
    if (j >= n) return;

    const float bj = (bias != nullptr) ? bias[j] : 0.0f;
    double mean, var;
    if (training) {
        double invB = 1.0 / (double)batch;
        double m0 = (double)sum[j];
        double q0 = (double)sumsq[j];
        sum[j] = 0.0f;    // keep scratch zeroed for the next call
        sumsq[j] = 0.0f;
        mean = m0 * invB;
        var = q0 * invB - mean * mean;
        if (var < 0.0) var = 0.0;
        double rm = (double)running_mean[j];
        running_mean[j] = (float)(rm + momentum * ((mean + (double)bj) - rm));
        double unb = var * ((double)batch / (double)(batch - 1));
        double rv = (double)running_var[j];
        running_var[j] = (float)(rv + momentum * (unb - rv));
    } else {
        mean = (double)running_mean[j];
        var = (double)running_var[j];
    }

    double g = (double)gamma[j];
    double inv_std = 1.0 / sqrt(var + eps);
    double s = (double)scale[0];
    double aj = s * g * inv_std;
    a[j] = (float)aj;
    if (training) {
        b[j] = (float)(s * ((double)beta[j] - mean * g * inv_std));
    } else {
        b[j] = (float)(s * (double)beta[j] + aj * ((double)bj - mean));
    }
}

__device__ __forceinline__ float warp_reduce_max(float v) {
    #pragma unroll
    for (int offset = 16; offset > 0; offset >>= 1) {
        v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, offset));
    }
    return v;
}

__device__ __forceinline__ float warp_reduce_sum(float v) {
    #pragma unroll
    for (int offset = 16; offset > 0; offset >>= 1) {
        v += __shfl_xor_sync(0xffffffffu, v, offset);
    }
    return v;
}

// ---------------------------------------------------------------------------
// Fused affine transform + numerically stable softmax over rows of the fp16
// (bias-free) GEMM output. One block per row; 8 columns per thread per
// iteration, cached in registers between the passes. fp32 output.
// Requires nvec8 == iters * BLOCK_SIZE with 1 <= iters <= MAX_ITERS.
// ---------------------------------------------------------------------------
__global__ void __launch_bounds__(BLOCK_SIZE) fused_affine_softmax_half_kernel(
    const float4* __restrict__ xh,
    const float4* __restrict__ a,
    const float4* __restrict__ b,
    float4* __restrict__ out,
    int nvec8,
    int iters)
{
    const int row = blockIdx.x;
    const float4* __restrict__ x_row = xh + (size_t)row * nvec8;
    float4* __restrict__ out_row = out + (size_t)row * (nvec8 * 2);

    __shared__ float smax[NUM_WARPS];
    __shared__ float ssum[NUM_WARPS];
    __shared__ float srow_max;
    __shared__ float srow_sum;

    const int tid = threadIdx.x;
    const int lane = tid & 31;
    const int wid = tid >> 5;

    float z[MAX_ITERS][8];

    // Pass 1: z = a * x + b, cache in registers, track row max.
    float m = -INFINITY;
    #pragma unroll
    for (int it = 0; it < MAX_ITERS; ++it) {
        if (it < iters) {
            int idx = tid + it * BLOCK_SIZE;
            float4 raw = x_row[idx];
            const __half2* h = reinterpret_cast<const __half2*>(&raw);
            float4 av0 = a[2 * idx];
            float4 av1 = a[2 * idx + 1];
            float4 bv0 = b[2 * idx];
            float4 bv1 = b[2 * idx + 1];
            float2 f0 = __half22float2(h[0]);
            float2 f1 = __half22float2(h[1]);
            float2 f2 = __half22float2(h[2]);
            float2 f3 = __half22float2(h[3]);
            z[it][0] = fmaf(av0.x, f0.x, bv0.x);
            z[it][1] = fmaf(av0.y, f0.y, bv0.y);
            z[it][2] = fmaf(av0.z, f1.x, bv0.z);
            z[it][3] = fmaf(av0.w, f1.y, bv0.w);
            z[it][4] = fmaf(av1.x, f2.x, bv1.x);
            z[it][5] = fmaf(av1.y, f2.y, bv1.y);
            z[it][6] = fmaf(av1.z, f3.x, bv1.z);
            z[it][7] = fmaf(av1.w, f3.y, bv1.w);
            #pragma unroll
            for (int k = 0; k < 8; ++k) m = fmaxf(m, z[it][k]);
        }
    }
    m = warp_reduce_max(m);
    if (lane == 0) smax[wid] = m;
    __syncthreads();
    if (wid == 0) {
        float v = (lane < NUM_WARPS) ? smax[lane] : -INFINITY;
        v = warp_reduce_max(v);
        if (lane == 0) srow_max = v;
    }
    __syncthreads();
    const float row_max = srow_max;

    // Pass 2: exponentiate (from registers) and accumulate partition sum.
    float s = 0.0f;
    #pragma unroll
    for (int it = 0; it < MAX_ITERS; ++it) {
        if (it < iters) {
            #pragma unroll
            for (int k = 0; k < 8; ++k) {
                z[it][k] = __expf(z[it][k] - row_max);
                s += z[it][k];
            }
        }
    }
    s = warp_reduce_sum(s);
    if (lane == 0) ssum[wid] = s;
    __syncthreads();
    if (wid == 0) {
        float v = (lane < NUM_WARPS) ? ssum[lane] : 0.0f;
        v = warp_reduce_sum(v);
        if (lane == 0) srow_sum = v;
    }
    __syncthreads();
    const float inv_sum = 1.0f / srow_sum;

    // Pass 3: normalize and store as fp32.
    #pragma unroll
    for (int it = 0; it < MAX_ITERS; ++it) {
        if (it < iters) {
            int idx = tid + it * BLOCK_SIZE;
            float4 o0, o1;
            o0.x = z[it][0] * inv_sum;
            o0.y = z[it][1] * inv_sum;
            o0.z = z[it][2] * inv_sum;
            o0.w = z[it][3] * inv_sum;
            o1.x = z[it][4] * inv_sum;
            o1.y = z[it][5] * inv_sum;
            o1.z = z[it][6] * inv_sum;
            o1.w = z[it][7] * inv_sum;
            out_row[2 * idx] = o0;
            out_row[2 * idx + 1] = o1;
        }
    }
}

// ---------------------------------------------------------------------------
// Persistent device-side scratch buffers.
// ---------------------------------------------------------------------------
static torch::Tensor g_stats;   // [2, n] float, kept all-zero between calls
static torch::Tensor g_coef;    // [2, n] float (a, b)
static torch::Tensor g_xh;      // [B, n] half GEMM output buffer
static torch::Tensor g_ws;      // cublasLt workspace

// ---------------------------------------------------------------------------
// cublasLt autotuned bias-free fp16 GEMM: out[M,N](row-major) =
// x[M,K](row-major) * w[N,K](row-major)^T, fp32 accumulate.
// Implemented as col-major C[N,M] = op_T(A[K,N]) * op_N(B[K,M]).
// ---------------------------------------------------------------------------
struct LtPlan {
    int M = -1, N = -1, K = -1;
    cublasLtMatmulDesc_t opdesc = nullptr;
    cublasLtMatrixLayout_t adesc = nullptr, bdesc = nullptr, cdesc = nullptr;
    cublasLtMatmulAlgo_t algo;
    size_t ws = 0;
    bool ready = false;
};
static LtPlan g_plan;
static cublasLtHandle_t g_lt = nullptr;

static void lt_plan_destroy() {
    if (g_plan.cdesc) { cublasLtMatrixLayoutDestroy(g_plan.cdesc); g_plan.cdesc = nullptr; }
    if (g_plan.bdesc) { cublasLtMatrixLayoutDestroy(g_plan.bdesc); g_plan.bdesc = nullptr; }
    if (g_plan.adesc) { cublasLtMatrixLayoutDestroy(g_plan.adesc); g_plan.adesc = nullptr; }
    if (g_plan.opdesc) { cublasLtMatmulDescDestroy(g_plan.opdesc); g_plan.opdesc = nullptr; }
    g_plan.ready = false;
    g_plan.M = g_plan.N = g_plan.K = -1;
}

static bool lt_plan_build(int M, int N, int K, const void* A, const void* B, void* C,
                          cudaStream_t stream) {
    lt_plan_destroy();
    if (g_lt == nullptr) {
        if (cublasLtCreate(&g_lt) != CUBLAS_STATUS_SUCCESS) return false;
    }
    if (cublasLtMatmulDescCreate(&g_plan.opdesc, CUBLAS_COMPUTE_32F, CUDA_R_32F) != CUBLAS_STATUS_SUCCESS) return false;
    cublasOperation_t opT = CUBLAS_OP_T, opN = CUBLAS_OP_N;
    cublasLtMatmulDescSetAttribute(g_plan.opdesc, CUBLASLT_MATMUL_DESC_TRANSA, &opT, sizeof(opT));
    cublasLtMatmulDescSetAttribute(g_plan.opdesc, CUBLASLT_MATMUL_DESC_TRANSB, &opN, sizeof(opN));
    if (cublasLtMatrixLayoutCreate(&g_plan.adesc, CUDA_R_16F, K, N, K) != CUBLAS_STATUS_SUCCESS) return false;
    if (cublasLtMatrixLayoutCreate(&g_plan.bdesc, CUDA_R_16F, K, M, K) != CUBLAS_STATUS_SUCCESS) return false;
    if (cublasLtMatrixLayoutCreate(&g_plan.cdesc, CUDA_R_16F, N, M, N) != CUBLAS_STATUS_SUCCESS) return false;

    if (!g_ws.defined() || g_ws.numel() < LT_WORKSPACE_CAP) {
        g_ws = torch::empty({LT_WORKSPACE_CAP}, torch::TensorOptions().dtype(torch::kUInt8).device(torch::kCUDA));
    }
    void* ws_ptr = g_ws.data_ptr();

    cublasLtMatmulPreference_t pref = nullptr;
    if (cublasLtMatmulPreferenceCreate(&pref) != CUBLAS_STATUS_SUCCESS) return false;
    size_t cap = LT_WORKSPACE_CAP;
    cublasLtMatmulPreferenceSetAttribute(pref, CUBLASLT_MATMUL_PREF_MAX_WORKSPACE_BYTES, &cap, sizeof(cap));

    cublasLtMatmulHeuristicResult_t results[LT_NUM_ALGOS];
    int nres = 0;
    cublasStatus_t st = cublasLtMatmulAlgoGetHeuristic(
        g_lt, g_plan.opdesc, g_plan.adesc, g_plan.bdesc, g_plan.cdesc, g_plan.cdesc,
        pref, LT_NUM_ALGOS, results, &nres);
    cublasLtMatmulPreferenceDestroy(pref);
    if (st != CUBLAS_STATUS_SUCCESS || nres <= 0) return false;

    const float alpha = 1.0f, beta = 0.0f;
    cudaEvent_t ev0, ev1;
    cudaEventCreate(&ev0);
    cudaEventCreate(&ev1);

    float best_ms = 1e30f;
    int best = -1;
    for (int i = 0; i < nres; ++i) {
        if (results[i].workspaceSize > cap) continue;
        st = cublasLtMatmul(g_lt, g_plan.opdesc, &alpha, A, g_plan.adesc, B, g_plan.bdesc,
                            &beta, C, g_plan.cdesc, C, g_plan.cdesc,
                            &results[i].algo, ws_ptr, results[i].workspaceSize, stream);
        if (st != CUBLAS_STATUS_SUCCESS) continue;
        cudaEventRecord(ev0, stream);
        for (int r = 0; r < 3; ++r) {
            cublasLtMatmul(g_lt, g_plan.opdesc, &alpha, A, g_plan.adesc, B, g_plan.bdesc,
                           &beta, C, g_plan.cdesc, C, g_plan.cdesc,
                           &results[i].algo, ws_ptr, results[i].workspaceSize, stream);
        }
        cudaEventRecord(ev1, stream);
        cudaEventSynchronize(ev1);
        float ms = 0.0f;
        cudaEventElapsedTime(&ms, ev0, ev1);
        if (ms < best_ms) { best_ms = ms; best = i; }
    }
    cudaEventDestroy(ev0);
    cudaEventDestroy(ev1);
    if (best < 0) return false;

    g_plan.algo = results[best].algo;
    g_plan.ws = results[best].workspaceSize;
    g_plan.M = M; g_plan.N = N; g_plan.K = K;
    g_plan.ready = true;
    return true;
}

static bool lt_gemm_f16(const void* A, const void* B, void* C, int M, int N, int K,
                        cudaStream_t stream) {
    if (!g_plan.ready || g_plan.M != M || g_plan.N != N || g_plan.K != K) {
        cudaStreamSynchronize(stream);
        if (!lt_plan_build(M, N, K, A, B, C, stream)) return false;
    }
    const float alpha = 1.0f, beta = 0.0f;
    return cublasLtMatmul(g_lt, g_plan.opdesc, &alpha, A, g_plan.adesc, B, g_plan.bdesc,
                          &beta, C, g_plan.cdesc, C, g_plan.cdesc,
                          &g_plan.algo, g_ws.data_ptr(), g_plan.ws, stream) == CUBLAS_STATUS_SUCCESS;
}

torch::Tensor fused_gemm_bn_scale_softmax(
    torch::Tensor x,
    torch::Tensor wh,
    torch::Tensor gamma,
    torch::Tensor beta,
    torch::Tensor scale,
    torch::Tensor bias,
    torch::Tensor running_mean,
    torch::Tensor running_var,
    torch::Tensor nbt,
    double momentum,
    double eps,
    bool training)
{
    TORCH_CHECK(x.is_cuda() && x.scalar_type() == at::kFloat && x.dim() == 2, "bad input");
    TORCH_CHECK(x.is_contiguous() && wh.is_contiguous() && gamma.is_contiguous() &&
                beta.is_contiguous() && scale.is_contiguous() &&
                running_mean.is_contiguous() && running_var.is_contiguous(),
                "tensors must be contiguous");

    const int batch = x.size(0);
    const int kdim = x.size(1);
    const int n = wh.size(0);
    TORCH_CHECK(kdim % 8 == 0, "input dim must be divisible by 8");
    TORCH_CHECK(n % (8 * BLOCK_SIZE) == 0, "feature dim must be divisible by 2048");
    const int nvec8 = n / 8;
    const int iters = nvec8 / BLOCK_SIZE;
    TORCH_CHECK(iters >= 1 && iters <= MAX_ITERS, "unsupported feature dim");

    auto half_opts = wh.options().dtype(at::kHalf);
    auto float_opts = gamma.options().dtype(at::kFloat);
    if (!g_xh.defined() || g_xh.size(0) != batch || g_xh.size(1) != n ||
        g_xh.device() != x.device()) {
        g_xh = torch::empty({batch, n}, half_opts);
    }
    if (!g_coef.defined() || g_coef.size(1) != n || g_coef.device() != x.device()) {
        g_coef = torch::empty({2, n}, float_opts);
    }
    auto out = torch::empty({batch, n}, float_opts);

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

    // 1. Cast input to fp16 into a scratch buffer.
    auto xh_in = torch::empty({batch, kdim}, half_opts);
    long cast_nvec8 = ((long)batch * kdim) / 8;
    int cast_blocks = (int)((cast_nvec8 + BLOCK_SIZE - 1) / BLOCK_SIZE);
    cast_f32_to_f16_kernel<<<cast_blocks, BLOCK_SIZE, 0, stream>>>(
        reinterpret_cast<const float4*>(x.data_ptr<float>()),
        reinterpret_cast<float4*>(xh_in.data_ptr<at::Half>()),
        cast_nvec8);

    // 2. Bias-free fp16 GEMM with fp32 accumulate (autotuned cublasLt,
    //    falling back to ATen if unavailable).
    if (!lt_gemm_f16(wh.data_ptr<at::Half>(), xh_in.data_ptr<at::Half>(),
                     g_xh.data_ptr<at::Half>(), batch, n, kdim, stream)) {
        auto y = at::linear(xh_in, wh);
        g_xh.copy_(y);
    }

    // 3. Batch statistics (training mode only), fp16 -> fp32 atomics.
    float* sum_ptr = nullptr;
    float* sumsq_ptr = nullptr;
    if (training) {
        if (!g_stats.defined() || g_stats.size(1) != n || g_stats.device() != x.device()) {
            g_stats = torch::zeros({2, n}, float_opts);
        }
        sum_ptr = g_stats.data_ptr<float>();
        sumsq_ptr = sum_ptr + n;
        dim3 stats_grid(nvec8 / STATS_THREADS, (batch + ROWS_PER_BLOCK - 1) / ROWS_PER_BLOCK);
        col_stats_half_kernel<<<stats_grid, STATS_THREADS, 0, stream>>>(
            reinterpret_cast<const float4*>(g_xh.data_ptr<at::Half>()),
            sum_ptr, sumsq_ptr, batch, nvec8, ROWS_PER_BLOCK);
    }

    // 4. Fold BN + scale (+ bias) into affine coefficients.
    float* a_ptr = g_coef.data_ptr<float>();
    float* b_ptr = a_ptr + n;
    const float* bias_ptr = bias.numel() > 0 ? bias.data_ptr<float>() : nullptr;
    const int coef_blocks = (n + BLOCK_SIZE - 1) / BLOCK_SIZE;
    finish_coef_kernel<<<coef_blocks, BLOCK_SIZE, 0, stream>>>(
        sum_ptr, sumsq_ptr,
        running_mean.data_ptr<float>(),
        running_var.data_ptr<float>(),
        reinterpret_cast<long long*>(nbt.data_ptr<int64_t>()),
        gamma.data_ptr<float>(),
        beta.data_ptr<float>(),
        scale.data_ptr<float>(),
        bias_ptr,
        a_ptr, b_ptr,
        momentum, eps, n, batch, training ? 1 : 0);

    // 5. Fused affine + softmax.
    fused_affine_softmax_half_kernel<<<batch, BLOCK_SIZE, 0, stream>>>(
        reinterpret_cast<const float4*>(g_xh.data_ptr<at::Half>()),
        reinterpret_cast<const float4*>(a_ptr),
        reinterpret_cast<const float4*>(b_ptr),
        reinterpret_cast<float4*>(out.data_ptr<float>()),
        nvec8, iters);

    return out;
}
"""

_cpp_source = (
    "torch::Tensor fused_gemm_bn_scale_softmax(torch::Tensor x, torch::Tensor wh, "
    "torch::Tensor gamma, torch::Tensor beta, torch::Tensor scale, torch::Tensor bias, "
    "torch::Tensor running_mean, torch::Tensor running_var, torch::Tensor nbt, "
    "double momentum, double eps, bool training);"
)

_fused_ops = load_inline(
    name="fused_gemm_bn_scale_softmax_ext_v2",
    cpp_sources=_cpp_source,
    cuda_sources=_cuda_source,
    functions=["fused_gemm_bn_scale_softmax"],
    extra_cflags=["-O3"],
    extra_cuda_cflags=["-O3"],
    extra_ldflags=["-lcublas", "-lcublasLt"],
    verbose=False,
)

_BLOCK_SIZE = 256
_MAX_ITERS = 4


class ModelNew(nn.Module):
    """
    Optimized version of Model:
      * fp32 input is cast to fp16 by a custom vectorized kernel.
      * The Linear layer runs as a bias-free fp16 tensor-core GEMM (fp32
        accumulation) via cublasLt with one-time algorithm autotuning, using
        a cached fp16 copy of the weight. The Linear bias is cancelled
        exactly by BatchNorm's mean subtraction in training mode and folded
        into the affine coefficient in eval mode, so results are unchanged.
      * BatchNorm batch statistics use a custom fp16->fp32 reduction kernel.
      * BatchNorm + scalar scale + Softmax are fused into a single custom
        CUDA kernel (plus a tiny coefficient kernel), reading the GEMM output
        once and writing the final probabilities once.
    Falls back to the original ops for unsupported configurations.
    """

    def __init__(self, in_features, out_features, bn_eps=1e-5, bn_momentum=0.1, scale_shape=(1,)):
        super(ModelNew, self).__init__()
        self.gemm = nn.Linear(in_features, out_features)
        self.bn = nn.BatchNorm1d(out_features, eps=bn_eps, momentum=bn_momentum)
        self.scale = nn.Parameter(torch.ones(scale_shape))
        self.out_features = out_features
        self._half_cache = None

    def _half_weight(self):
        w = self.gemm.weight
        key = (w._version, w.device)
        cache = self._half_cache
        if cache is None or cache[0] is not w or cache[1] != key:
            wh = w.detach().to(torch.float16).contiguous()
            cache = (w, key, wh)
            self._half_cache = cache
        return cache[2]

    def forward(self, x):
        bn = self.bn
        n = self.out_features
        in_features = self.gemm.in_features

        fused_ok = (
            x.is_cuda
            and x.dtype == torch.float32
            and x.dim() == 2
            and bn.affine
            and bn.track_running_stats
            and bn.momentum is not None
            and bn.running_mean is not None
            and self.scale.numel() == 1
            and (in_features % 8) == 0
            and (n % (8 * _BLOCK_SIZE)) == 0
            and 1 <= (n // (8 * _BLOCK_SIZE)) <= _MAX_ITERS
        )

        if fused_ok:
            if not x.is_contiguous():
                x = x.contiguous()
            bias = self.gemm.bias
            if bias is None:
                bias = x.new_empty(0)
            return _fused_ops.fused_gemm_bn_scale_softmax(
                x,
                self._half_weight(),
                bn.weight,
                bn.bias,
                self.scale,
                bias.contiguous(),
                bn.running_mean,
                bn.running_var,
                bn.num_batches_tracked,
                float(bn.momentum),
                float(bn.eps),
                bool(bn.training),
            )

        # Generic fallback: original operator sequence.
        x = self.gemm(x)
        x = bn(x)
        x = self.scale * x
        return F.softmax(x, dim=1)
```