## Technique library (KFORGE: techniques verified by the protected evaluator on training problems; use what fits this problem, ignore the rest)

### Verified technique (E-H5, admitted by the KFORGE engine): Training-mode BatchNorm with a following elementwise or pool tail: two Triton kernels (parallel Welford partials, then a fused apply) beat cuDNN BN plus eager activations
The recorded losses came from computing stats with several torch reductions and scalar ops (many launches and passes), not from replacing cuDNN BN as such. Under 1e-4 numerics, two kernels with at most one tiny torch op between them should give 1.2-1.6x on post-conv BN plus activation chains. The first kernel computes per-(channel, block) Welford partials and the second fuses the combine, normalize, affine, activation and pool.
Physics: Eager training BN reads the tensor twice and writes once, then each activation or pool adds a full read and write. The fused path reads the tensor twice and writes once, or writes 1/4 for a 2x2 pool. For tensors of 100 MB or more on 1.5 TB/s, that saves 0.1-0.5 ms per removed pass. Welford/Chan merging avoids the cancellation of E[x^2] - E[x]^2, so fp32 matches cuDNN to about 1e-6.
How: Kernel A uses a grid of (C, P) blocks, each streaming a contiguous HW chunk over all N. It writes count, mean and M2 partials to a [C, P] buffer. Kernel B has each program first merge its channel's P partials in registers with the Chan formula; this is cheap with P <= 64 and avoids a separate finalize launch. It then computes scale = gamma*rstd and shift = beta - mean*scale, applies the activation and any pool, and stores the result. Update running_mean and running_var (unbiased, factor M/(M-1)) with one in-place torch op under no_grad, using self.<x> buffers only. Keep the conv in cuDNN, or use H1/H2, and use int64 offsets throughout.
- Verified on training problems (protected evaluator): L2_097 Matmul_BatchNorm_BiasAdd_Divide_Swish: 3.53x vs 3.47x with the previous library; L3_046 NetVladWithGhostClusters: 2.96x vs 2.91x with the previous library.
- Verified example implementing it (L3_046, 2.96x; adapt what applies):
```python
import math
import torch
import torch.nn as nn
import triton
import triton.language as tl


@triton.jit
def assign_kernel(x_ptr, w_ptr, a_ptr, pmean_ptr, pm2_ptr, pcnt_ptr, M, C,
                  D: tl.constexpr, BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr):
    pid = tl.program_id(0)
    rm = pid * BM + tl.arange(0, BM)
    rn = tl.arange(0, BN)
    rk = tl.arange(0, BK)
    rm64 = rm.to(tl.int64)
    rmask = rm < M
    nmask = rn < C
    xp = x_ptr + rm64[:, None] * D + rk[None, :]
    wp = w_ptr + rk[:, None] * C + rn[None, :]
    acc = tl.zeros((BM, BN), dtype=tl.float32)
    acc2 = tl.zeros((BM, BN), dtype=tl.float32)
    for k in range(0, D, BK):
        a = tl.load(xp, mask=rmask[:, None], other=0.0)
        b = tl.load(wp, mask=nmask[None, :], other=0.0)
        ah = a.to(tl.bfloat16)
        al = (a - ah.to(tl.float32)).to(tl.bfloat16)
        bh = b.to(tl.bfloat16)
        bl = (b - bh.to(tl.float32)).to(tl.bfloat16)
        acc2 = tl.dot(ah, bl, acc2)
        acc2 = tl.dot(al, bh, acc2)
        acc = tl.dot(ah, bh, acc)
        xp += BK
        wp += BK * C
    v = acc + acc2
    tl.store(a_ptr + rm64[:, None] * C + rn[None, :], v, mask=rmask[:, None] & nmask[None, :])
    cnt = tl.minimum(M - pid * BM, BM).to(tl.float32)
    vm = tl.where(rmask[:, None], v, 0.0)
    mean = tl.sum(vm, 0) / cnt
    dl = tl.where(rmask[:, None], v - mean[None, :], 0.0)
    m2 = tl.sum(dl * dl, 0)
    tl.store(pmean_ptr + pid * BN + rn, mean)
    tl.store(pm2_ptr + pid * BN + rn, m2)
    tl.store(pcnt_ptr + pid, cnt)


@triton.jit
def stats_kernel(pmean_ptr, pm2_ptr, pcnt_ptr, g_ptr, b_ptr, sc_ptr, sh_ptr, mean_ptr, var_ptr,
                 P, C, Mtot, eps, BP: tl.constexpr, BN: tl.constexpr):
    rn = tl.arange(0, BN)
    nm = rn < C
    s = tl.zeros((BN,), dtype=tl.float32)
    for p0 in range(0, P, BP):
        rp = p0 + tl.arange(0, BP)
        pk = rp < P
        mu = tl.load(pmean_ptr + rp[:, None] * BN + rn[None, :], mask=pk[:, None], other=0.0)
        c = tl.load(pcnt_ptr + rp, mask=pk, other=0.0)
        s += tl.sum(mu * c[:, None], 0)
    mean = s / Mtot
    m2 = tl.zeros((BN,), dtype=tl.float32)
    for p0 in range(0, P, BP):
        rp = p0 + tl.arange(0, BP)
        pk = rp < P
        mu = tl.load(pmean_ptr + rp[:, None] * BN + rn[None, :], mask=pk[:, None], other=0.0)
        q = tl.load(pm2_ptr + rp[:, None] * BN + rn[None, :], mask=pk[:, None], other=0.0)
        c = tl.load(pcnt_ptr + rp, mask=pk, other=0.0)
        d = mu - mean[None, :]
        m2 += tl.sum(q + c[:, None] * d * d, 0)
    var = m2 / Mtot
    rstd = 1.0 / tl.sqrt(var + eps)
    g = tl.load(g_ptr + rn, mask=nm, other=0.0)
    bt = tl.load(b_ptr + rn, mask=nm, other=0.0)
    sc = g * rstd
    sh = bt - mean * sc
    tl.store(sc_ptr + rn, sc)
    tl.store(sh_ptr + rn, sh)
    tl.store(mean_ptr + rn, mean)
    tl.store(var_ptr + rn, var)


@triton.jit
def vlad_kernel(x_ptr, a_ptr, sc_ptr, sh_ptr, c2_ptr, out_ptr, NS, C,
                D: tl.constexpr, K: tl.constexpr, BNS: tl.constexpr, BC: tl.constexpr, BD: tl.constexpr):
    b = tl.program_id(0).to(tl.int64)
    rn = tl.arange(0, BNS)
    nmask = rn < NS
    rc = tl.arange(0, BC)
    cmask = rc < C
    rowbase = b * NS + rn
    t = tl.load(a_ptr + rowbase[:, None] * C + rc[None, :], mask=nmask[:, None] & cmask[None, :], other=0.0)
    sc = tl.load(sc_ptr + rc)
    sh = tl.load(sh_ptr + rc)
    z = t * sc[None, :] + sh[None, :]
    z = tl.where(cmask[None, :], z, float("-inf"))
    mx = tl.max(z, 1)
    e = tl.exp(z - mx[:, None])
    den = tl.sum(e, 1)
    rk = tl.arange(0, K)
    t2 = tl.load(a_ptr + rowbase[:, None] * C + rk[None, :], mask=nmask[:, None], other=0.0)
    sck = tl.load(sc_ptr + rk)
    shk = tl.load(sh_ptr + rk)
    A = tl.exp(t2 * sck[None, :] + shk[None, :] - mx[:, None]) / den[:, None]
    A = tl.where(nmask[:, None], A, 0.0)
    asum = tl.sum(A, 0)
    At = tl.trans(A)
    Ah = At.to(tl.bfloat16)
    Al = (At - Ah.to(tl.float32)).to(tl.bfloat16)
    ss = tl.zeros((K,), dtype=tl.float32)
    xbase = x_ptr + b * NS * D
    obase = out_ptr + b * D * K
    for d0 in range(0, D, BD):
        rd = d0 + tl.arange(0, BD)
        xt = tl.load(xbase + rn[:, None] * D + rd[None, :], mask=nmask[:, None], other=0.0)
        xh = xt.to(tl.bfloat16)
        xl = (xt - xh.to(tl.float32)).to(tl.bfloat16)
        v2 = tl.zeros((K, BD), dtype=tl.float32)
        v2 = tl.dot(Ah, xl, v2)
        v2 = tl.dot(Al, xh, v2)
        v = tl.zeros((K, BD), dtype=tl.float32)
        v = tl.dot(Ah, xh, v)
        v = v + v2
        c2 = tl.load(c2_ptr + rd[None, :] * K + rk[:, None])
        v = v - asum[:, None] * c2
        ss += tl.sum(v * v, 1)
        tl.store(obase + rd[None, :] * K + rk[:, None], v)
    kn = tl.maximum(tl.sqrt(ss), 1e-12)
    inv = 1.0 / kn
    tot = tl.sum(ss * inv * inv, 0)
    g = tl.maximum(tl.sqrt(tot), 1e-12)
    f = inv / g
    tl.debug_barrier()
    for d0 in range(0, D, BD):
        rd = d0 + tl.arange(0, BD)
        p = obase + rd[None, :] * K + rk[:, None]
        v = tl.load(p)
        tl.store(p, v * f[:, None])


class ModelNew(nn.Module):
    def __init__(self, cluster_size, feature_size, ghost_clusters):
        super(ModelNew, self).__init__()
        self.feature_size = feature_size
        self.cluster_size = cluster_size
        self.ghost_clusters = ghost_clusters
        init_sc = (1 / math.sqrt(feature_size))
        clusters = cluster_size + ghost_clusters
        self.clusters = nn.Parameter(init_sc * torch.randn(feature_size, clusters))
        self.batch_norm = nn.BatchNorm1d(clusters)
        self.clusters2 = nn.Parameter(init_sc * torch.randn(1, feature_size, cluster_size))
        self.out_dim = self.cluster_size * feature_size

    def forward(self, x, mask=None):
        B, NS, D = x.shape
        K = self.cluster_size
        x2 = x.reshape(-1, D).contiguous()
        M = x2.shape[0]
        C = K + self.ghost_clusters
        BN = max(16, triton.next_power_of_2(C))
        dev = x.device
        w = self```


## Kernel memory (items verified by the protected evaluator on training problems; may not all apply)

### Lessons about this environment (from official checker verdicts and verified outcomes)
- Pitfall: A reply without a ```python fenced code block was rejected by the checker. Always wrap the full ModelNew source in a ```python block.
- Checker rule: getattr needs a literal, non-private attribute name
- Pitfall: Output mismatch beyond 1e-4 occurred repeatedly. Fix by forcing exact fp32 tl.dot(allow_tf32=False) and exact masking: K bounds at block granularity, tril mask, and zero-initialized output for skipped tiles.
- Checker rule: forward modified its input tensors in place
- Checker rule: do not define a class named Model (the reference); define ModelNew only
- Process: never SUBMIT code that has not passed ACTION: CHECK in this episode. Untested submissions that fail to compile or mismatch the reference score 0; a CHECK costs one reply and shows the compiler output.
- Pitfall: cpp_sources is compiled by plain c++ without CUDA headers: never use cudaStream_t or at::cuda::getCurrentCUDAStream there. Put wrappers needing streams in cuda_sources, keeping only plain-type prototypes in cpp_sources.
- Pitfall: If cpp_sources must reference CUDA types or the current stream, explicitly #include <cuda_runtime.h> and <ATen/cuda/CUDAContext.h>; torch/extension.h does not provide them.
- Checker rule: assignment to attribute 'm.conv1' is not allowed (only self.<x>)
- Checker rule: assignment to attribute 'm.bn1' is not allowed (only self.<x>)
- Checker rule: assignment to attribute 'm.conv2' is not allowed (only self.<x>)
- Checker rule: assignment to attribute 'm.bn2' is not allowed (only self.<x>)
- Checker rule: assignment to attribute 'm.downsample' is not allowed (only self.<x>)
- Checker rule: At least one of your own kernels must actually launch during forward; a pure torch path (even with a compiled but unused kernel) is rejected as no_custom_kernel.

### Pitfalls seen on earlier network problems (wrong results or slower than eager)
- Pitfall: Don'...'s fused path alone.
- Pitfall: In training mode, don't replace fused cuDNN BatchNorm with Python-level mean/var reductions plus separate scale/shift ops; each adds kernel launches and memory passes, which makes the result much slower than eager.
- Pitfall: Avoid extra .contiguous()/torch.empty_like allocations and per-call Triton launch overhead on small tensors; launch overhead often exceeds savings from fusing two cheap elementwise ops.
- Pitfall: In conv-dominated networks, fusing only a tiny elementwise op (add+ReLU) via Triton can't offset launch/Python overhead; fuse BatchNorm into conv weights (eval mode) or target the dominant ops instead.
- Pitfall: In training-mode BN, computing batch mean and var with separate torch reductions plus running-stat updates adds full memory passes. Eager's fused cudnn batch_norm is hard to beat this way; benchmark per layer before replacing.
- Pitfall: Don't fuse only BN+ReLU after cuDNN convs while computing BN scale/shift with many small eager ops each forward; the extra launches and passes outweigh the fusion. Fold BN into conv weights or fuse into the conv epilogue.