## 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 conv problems (wrong results or slower than eager)
- Pitfall: Before hand-writing a dense conv, benchmark against cuDNN; a naive Triton or CUDA kernel rarely wins. Reserve custom kernels for fusing cheap elementwise ops around the conv.
- Pitfall: Don't write direct convolution as one output channel per program with scalar weight loads; each input pixel gets re-read per output channel. Tile over output channels and use tl.dot (implicit GEMM).
- Pitfall: Avoid per-element div/mod index decoding plus per-tap weight gathers in stencil kernels. Use a 2D/3D grid (plane, row-tile, col-tile) and load per-channel weights once per program.
- Pitfall: For depthwise conv, don'...'s 2D output plane, reuse input rows via shared memory or registers, and make kernel dims constexpr.
- Pitfall: Fuse post-conv elementwise/reduction ops with following pooling into one kernel instead of separate launches that write and re-read full-size intermediates. Unfused memory-bound epilogues after cuDNN conv easily end up slower than eager.
- Pitfall: For softmax or reduction over the channel dim of NC... tensors, avoid one program per spatial position with channel-strided loads. Tile a 2D [channels × contiguous spatial block] so loads coalesce along the innermost dimension.

### A verified kernel for a related conv problem (L2_073 Conv2d_BatchNorm_Scaling, 1.68x): adapt what applies
```python
import torch
import torch.nn as nn
import torch.nn.functional as F
import triton
import triton.language as tl


@triton.jit
def stats_kernel2(x_ptr, sum_ptr, sumsq_ptr, N, C, S, SBLK: tl.constexpr):
    c = tl.program_id(0)
    sblk = tl.program_id(1)
    offs = sblk * SBLK + tl.arange(0, SBLK)
    smask = offs < S
    acc_sum = tl.zeros((SBLK,), tl.float32)
    acc_sq = tl.zeros((SBLK,), tl.float32)
    cS = c.to(tl.int64) * S
    NCS = C * S
    for n in range(N):
        base = n.to(tl.int64) * NCS + cS + offs
        v = tl.load(x_ptr + base, mask=smask, other=0.0)
        acc_sum += v
        acc_sq += v * v
    s = tl.sum(acc_sum, axis=0)
    sq = tl.sum(acc_sq, axis=0)
    tl.atomic_add(sum_ptr + c, s)
    tl.atomic_add(sumsq_ptr + c, sq)


@triton.jit
def bn_apply_kernel(x_ptr, out_ptr, mean_ptr, invstd_ptr, w_ptr, b_ptr,
                    scaling, C, S, TOTAL, BLOCK: tl.constexpr):
    pid = tl.program_id(0)
    offs = pid * BLOCK + tl.arange(0, BLOCK)
    mask = offs < TOTAL
    c = (offs // S) % C
    v = tl.load(x_ptr + offs, mask=mask, other=0.0)
    mean = tl.load(mean_ptr + c, mask=mask, other=0.0)
    invstd = tl.load(invstd_ptr + c, mask=mask, other=0.0)
    w = tl.load(w_ptr + c, mask=mask, other=0.0)
    b = tl.load(b_ptr + c, mask=mask, other=0.0)
    r = ((v - mean) * invstd * w + b) * scaling
    tl.store(out_ptr + offs, r, mask=mask)


class ModelNew(nn.Module):
    def __init__(self, in_channels, out_channels, kernel_size, scaling_factor):
        super(ModelNew, self).__init__()
        self.conv = nn.Conv2d(in_channels, out_channels, kernel_size)
        self.bn = nn.BatchNorm2d(out_channels)
        self.scaling_factor = scaling_factor

    def forward(self, x):
        x = self.conv(x).contiguous()
        N, C, H, W = x.shape
        S = H * W
        count = N * S
        device = x.device

        sums = torch.zeros(C, device=device, dtype=torch.float32)
        sumsq = torch.zeros(C, device=device, dtype=torch.float32)
        SBLK = 1024
        nsblk = triton.cdiv(S, SBLK)
        stats_kernel2[(C, nsblk)](x, sums, sumsq, N, C, S, SBLK=SBLK)

        if self.training:
            mean = sums / count
            var = sumsq / count - mean * mean
            with torch.no_grad():
                self.bn.running_mean.mul_(1 - self.bn.momentum).add_(self.bn.momentum * mean.detach())
                unbiased = var * count / (count - 1)
                self.bn.running_var.mul_(1 - self.bn.momentum).add_(self.bn.momentum * unbiased.detach())
        else:
            mean = self.bn.running_mean
            var = self.bn.running_var

        invstd = torch.rsqrt(var + self.bn.eps)
        w = self.bn.weight
        b = self.bn.bias

        out = torch.empty_like(x)
        TOTAL = x.numel()
        BLOCK = 1024
        grid = (triton.cdiv(TOTAL, BLOCK),)
        bn_apply_kernel[grid](x, out, mean.contiguous(), invstd.contiguous(),
                              w.contiguous(), b.contiguous(),
                              float(self.scaling_factor), C, S, TOTAL, BLOCK=BLOCK)
        return out
```

### A verified kernel for a related conv problem (L2_082 Conv2d_Tanh_Scaling_BiasAdd_Max, 1.94x): adapt what applies
```python
import torch
import torch.nn as nn
import torch.nn.functional as F
import triton
import triton.language as tl


@triton.jit
def fused_kernel(x_ptr, bias_ptr, out_ptr,
                 N, C, H, W, OH, OW, P, scaling,
                 BLOCK: tl.constexpr):
    pid = tl.program_id(0)
    offs = pid * BLOCK + tl.arange(0, BLOCK)
    TOTAL = N * C * OH * OW
    mask = offs < TOTAL

    ow = offs % OW
    tmp = offs // OW
    oh = tmp % OH
    tmp = tmp // OH
    c = tmp % C
    n = tmp // C

    b = tl.load(bias_ptr + c, mask=mask, other=0.0)

    h0 = oh * P
    w0 = ow * P
    acc = tl.full((BLOCK,), -1e30, tl.float32)
    base = (n.to(tl.int64) * C + c) * H * W
    for ph in range(P):
        for pw in range(P):
            h = h0 + ph
            w = w0 + pw
            idx = base + h.to(tl.int64) * W + w
            v = tl.load(x_ptr + idx, mask=mask, other=-1e30)
            t = tl.extra.cuda.libdevice.tanh(v)
            t = t * scaling + b
            acc = tl.maximum(acc, t)
    tl.store(out_ptr + offs, acc, mask=mask)


class ModelNew(nn.Module):
    def __init__(self, in_channels, out_channels, kernel_size, scaling_factor, bias_shape, pool_kernel_size):
        super(ModelNew, self).__init__()
        self.conv = nn.Conv2d(in_channels, out_channels, kernel_size)
        self.scaling_factor = scaling_factor
        self.bias = nn.Parameter(torch.randn(bias_shape))
        self.pool_kernel_size = pool_kernel_size

    def forward(self, x):
        x = self.conv(x).contiguous()
        N, C, H, W = x.shape
        P = self.pool_kernel_size
        OH = H // P
        OW = W // P
        out = torch.empty((N, C, OH, OW), device=x.device, dtype=x.dtype)
        TOTAL = N * C * OH * OW
        BLOCK = 256
        grid = (triton.cdiv(TOTAL, BLOCK),)
        fused_kernel[grid](x, self.bias.contiguous().view(-1), out,
                           N, C, H, W, OH, OW, P, float(self.scaling_factor),
                           BLOCK=BLOCK)
        return out
```