You write custom CUDA kernels to replace the PyTorch operators in the given EvoNorm architecture to get speedups.
You have complete freedom to choose the set of operators you want to replace. You may make the decision to replace some operators with custom CUDA kernels and leave others unchanged. You may replace multiple operators with custom implementations, consider operator fusion opportunities (combining multiple operators into a single kernel, for example, combining normalization+affine_transform+nonlinear_gating), or algorithmic changes (such as optimized memory access patterns). You are only limited by your imagination.

Technologies Used :

PyTorch: Deep learning framework

CUDA: GPU acceleration for parallel computing

C++/CUDA C++: High-performance kernel programming

Inline C++/CUDA Extension (torch.utils.cpp_extension.load_inline): Just-In-Time (JIT) compilation of custom operators

Negative Log-Likelihood Loss (NLLLoss): Classification loss function for probability distributions

Dual-Kernel Strategy: Separate kernels for "none" reduction vs "mean"/"sum" reduction

Grid-Stride Loops: Efficiently processes data of arbitrary size using fixed thread blocks

Shared Memory Reduction: Uses __shared__ arrays for block-level parallel reduction

Tree Reduction Pattern: Binary tree reduction within thread blocks using __syncthreads()

Device Function: compute_nll_loss_item helper function shared between kernels

Conditional Weight Handling: Supports optional class weights with null pointer checking

Ignore Index Support: Filters out specified target indices from loss calculation

Multi-Dimensional Tensor Support: Handles 2D+ inputs with spatial dimensions

Tensor Flattening: Converts multi-dimensional tensors to flat views for kernel processing

Two-Stage Reduction: Block-level partial reduction followed by host-side final reduction

Boundary Checking: Validates target indices and handles out-of-range values

Memory Coalescing: Ensures contiguous tensor layout for optimal memory access

Fast Math Operations: Uses --use_fast_math compiler flag

Comprehensive Input Validation: Checks tensor dimensions, types, and device placement

Zero-Size Tensor Handling: Returns zero loss for empty inputs

Numerical Stability: Handles zero total weight case for mean reduction

Flexible Reduction Modes: Supports "none", "mean", and "sum" reduction strategies

Optional Tensor Handling: Uses c10::optional for optional weight parameter


Here's an example to show you the syntax of inline embedding custom CUDA operators in torch: The example given architecture is:
import torch
import torch.nn as nn
import torch.nn.functional as F

# -------------------------------------------------------------
# 常量定义
# -------------------------------------------------------------
N, C, H, W = 8, 10, 16, 16  # (N, C, H, W)

# 损失函数参数
WEIGHT = torch.rand(C, dtype=torch.float32)  # (C,)
IGNORE_INDEX = -100
REDUCTION = 'mean'


# -------------------------------------------------------------

class Model(nn.Module):
    """
    nn.NLLLoss 的纯 PyTorch 基准实现
    (K-dim, 2D-example)
    """

    def __init__(self, weight=None, size_average=None, ignore_index=-100,
                 reduce=None, reduction='mean'):
        super().__init__()

        # 处理已弃用的 size_average 和 reduce
        if size_average is not None or reduce is not None:
            # (省略... 遵循 torch.nn.modules.loss)
            pass

        self.reduction = reduction
        self.ignore_index = ignore_index

        # 确保 weight 在正确的设备上
        if weight is not None:
            self.register_buffer('weight', weight)
        else:
            self.weight = None

    def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:

        input_flat = input.view(N, C, -1)

        target_flat = target.view(N, -1)


        loss_unreduced = input_flat.gather(dim=1, index=target_flat.unsqueeze(1))
        loss_unreduced = -loss_unreduced.squeeze(1)  # (N, H*W)


        if self.weight is not None:

            weights_applied = self.weight[target_flat]
            loss_unreduced = loss_unreduced * weights_applied
        else:

            weights_applied = torch.ones_like(target_flat, dtype=input.dtype)


        mask = (target_flat != self.ignore_index)
        loss_unreduced = loss_unreduced * mask
        weights_applied = weights_applied * mask


        if self.reduction == 'mean':

            total_weight = weights_applied.sum()
            if total_weight == 0:
                return torch.tensor(0.0, device=input.device, dtype=input.dtype)
            return loss_unreduced.sum() / total_weight

        elif self.reduction == 'sum':
            return loss_unreduced.sum()

        else:
            return loss_unreduced.view_as(target)


def get_inputs():

    input_log_probs = F.log_softmax(torch.randn(N, C, H, W, dtype=torch.float32), dim=1)
    target = torch.empty(N, H, W, dtype=torch.long).random_(0, C)


    target.view(-1)[::10] = IGNORE_INDEX

    return [input_log_probs, target]


def get_init_inputs():

    return [WEIGHT, None, IGNORE_INDEX, None, REDUCTION]