## 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 matmul problems (wrong results or slower than eager)
- Pitfall: For memory-bound broadcast or elementwise ops, eager is already near peak bandwidth. Use 2D row/column tiling instead of per-element integer division on flat indices, and load each broadcast operand once per tile.
- Pitfall: When using split-K, keep the split count small; a very large split writes and re-reads a huge partial-sum buffer plus an extra reduction launch, eating the occupancy gain.
- Pitfall: Strict fp32 Triton tl.dot (allow_tf32=False) rarely beats cuBLAS on matmul; a hand split-K version was correct but still 0.88x. Fuse surrounding ops or exploit structure instead of reimplementing plain GEMM.
- Pitfall: For bandwidth-bound Triton kernels, give each program more work: larger tiles, multiple rows per program, more warps. Tiny per-program work and Python launch overhead lose to cuBLAS/ATen kernels.
- Pitfall: Don't expect a single-pass memory-bound elementwise or broadcast kernel to beat eager, which already runs near bandwidth peak. Win by fusing multiple ops or reducing memory traffic.
- Pitfall: If writing a Triton GEMM anyway, use @triton.autotune over several BM/BN/BK, num_warps and num_stages configs, plus grouped tile ordering. A single fixed 64x64x32 config is far slower than eager.

### A verified kernel for a related matmul problem (L2_051 Gemm_Subtract_GlobalAvgPool_LogSumExp_GELU_ResidualAdd, 36.02x): 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 add_kernel(x_ptr, s_ptr, out_ptr, n_feat, n, BLOCK: tl.constexpr):
    pid = tl.program_id(0)
    offs = pid * BLOCK + tl.arange(0, BLOCK)
    mask = offs < n
    row = offs // n_feat
    v = tl.load(x_ptr + offs, mask=mask)
    s = tl.load(s_ptr + row, mask=mask)
    tl.store(out_ptr + offs, v + s, mask=mask)


class ModelNew(nn.Module):
    def __init__(self, in_features, out_features, bias=True):
        super().__init__()
        self.gemm = nn.Linear(in_features, out_features, bias=bias)
        self.subtract = nn.Parameter(torch.randn(out_features))
        self.out_features = out_features

    def forward(self, x):
        # mean over output features of (Wx + b - subtract) = (colsum/out)·x + c
        colsum = self.gemm.weight.sum(dim=0) / self.out_features  # (in,)
        if self.gemm.bias is not None:
            c = (self.gemm.bias - self.subtract).mean()
        else:
            c = (-self.subtract).mean()
        s = x @ colsum + c  # (batch,)
        # logsumexp over single element (dim=1 after keepdim mean) is identity
        s = F.gelu(s)
        out = torch.empty_like(x)
        n = x.numel()
        n_feat = x.shape[1]
        BLOCK = 1024
        grid = (triton.cdiv(n, BLOCK),)
        add_kernel[grid](x, s, out, n_feat, n, BLOCK=BLOCK)
        return out
```

### A verified kernel for a related matmul problem (L1_015 Matmul_for_lower_triangular_matrices, 4.58x): adapt what applies
```python
import torch
import torch.nn as nn
import triton
import triton.language as tl

@triton.jit
def tril_mm_kernel(A_ptr, B_ptr, C_ptr, N,
                   BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr):
    pid_m = tl.program_id(0)
    pid_n = tl.program_id(1)

    m_lo = pid_m * BLOCK_M
    n_lo = pid_n * BLOCK_N

    if n_lo > (m_lo + BLOCK_M - 1):
        return

    offs_m = m_lo + tl.arange(0, BLOCK_M)
    offs_n = n_lo + tl.arange(0, BLOCK_N)
    offs_k = tl.arange(0, BLOCK_K)

    acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32)

    k_start = (n_lo // BLOCK_K) * BLOCK_K
    k_end = tl.minimum(m_lo + BLOCK_M, N)

    k = k_start
    while k < k_end:
        kk = k + offs_k
        a = tl.load(A_ptr + offs_m[:, None] * N + kk[None, :],
                    mask=(offs_m[:, None] < N) & (kk[None, :] < N), other=0.0)
        b = tl.load(B_ptr + kk[:, None] * N + offs_n[None, :],
                    mask=(kk[:, None] < N) & (offs_n[None, :] < N), other=0.0)
        acc += tl.dot(a, b, allow_tf32=False)
        k += BLOCK_K

    mask_tri = offs_m[:, None] >= offs_n[None, :]
    acc = tl.where(mask_tri, acc, 0.0)
    store_mask = (offs_m[:, None] < N) & (offs_n[None, :] < N)
    tl.store(C_ptr + offs_m[:, None] * N + offs_n[None, :], acc, mask=store_mask)


class ModelNew(nn.Module):
    def __init__(self):
        super().__init__()

    def forward(self, A, B):
        A = A.contiguous()
        B = B.contiguous()
        N = A.shape[0]
        C = torch.zeros_like(A)
        BLOCK_M = 64
        BLOCK_N = 64
        BLOCK_K = 32
        grid = (triton.cdiv(N, BLOCK_M), triton.cdiv(N, BLOCK_N))
        tril_mm_kernel[grid](A, B, C, N, BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N, BLOCK_K=BLOCK_K,
                             num_warps=4, num_stages=3)
        return C
```