You write custom CUDA kernels to replace the pytorch operators in the given 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 matmul+relu), or algorithmic changes (such as online softmax). You are only limited by your imagination.

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

class Model(nn.Module):
    def __init__(self) -> None:
        super().__init__()

    def forward(self, a, b):
        return a + b

def get_inputs():
    a = torch.randn(1, 128).cuda()
    b = torch.randn(1, 128).cuda()
    return [a, b]

def get_init_inputs():
    return []
The example new arch with custom CUDA kernels looks like this:



import torch
import torch.nn as nn
import torch.nn.functional as F

class Model(nn.Module):
    def __init__(self) -> None:
        super().__init__()

    def forward(self, a, b):
        return a + b

def get_inputs():
    a = torch.randn(1, 128).cuda()
    b = torch.randn(1, 128).cuda()
    return [a, b]

def get_init_inputs():
    return []
You are given the following architecture:



import torch
import torch.nn as nn

class Model(nn.Module):
    """
    Baseline Focal Loss implementation using fundamental PyTorch ops.
    This version avoids any built-in fused functions like `binary_cross_entropy_with_logits`
    to provide a fair comparison against a custom fused kernel.
    """
    def __init__(self, alpha=0.25, gamma=2.0, reduction='mean'):
        super(Model, self).__init__()
        self.alpha = alpha
        self.gamma = gamma
        self.reduction = reduction
    
    def forward(self, inputs: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
        # 1. Manually implement Sigmoid
        probs = torch.sigmoid(inputs)

        # 2. Manually implement Binary Cross Entropy
        eps = 1e-7
        bce = -(targets * torch.log(probs + eps) + (1 - targets) * torch.log(1 - probs + eps))

        # 3. Compute pt
        pt = torch.where(targets == 1, probs, 1 - probs)

        # 4. Compute Focal Weight
        focal_weight = self.alpha * torch.pow(1 - pt, self.gamma)

        # 5. Apply Focal Weight
        focal_loss = focal_weight * bce
        
        if self.reduction == 'mean':
            return focal_loss.mean()
        elif self.reduction == 'sum':
            return focal_loss.sum()
        else:
            return focal_loss

batch_size = 1024
num_classes = 1

def get_inputs():
    inputs = torch.randn(batch_size, num_classes, dtype=torch.float32)
    targets = torch.randint(0, 2, (batch_size,), dtype=torch.float32)
    return [inputs, targets]

def get_init_inputs():
    return []
IMPORTANT: The baseline architecture is a step-by-step implementation of Focal Loss, involving multiple separate operations (sigmoid, log, pow, etc.). This creates several intermediate tensors (probs, bce, pt, focal_weight) and requires multiple kernel launches during the forward pass. Furthermore, during backpropagation, PyTorch’s autograd engine will launch separate kernels for each operation’s gradient calculation. The primary optimization goal is operator fusion across the forward and backward passes: combine the entire forward computation and the entire backward gradient computation into a single, highly efficient CUDA kernel. This fusion should eliminate all intermediate tensors, drastically reduce memory traffic, and minimize kernel launch overhead. Focus on creating a novel torch.autograd.Function that encapsulates this fused logic, providing a seamless drop-in replacement that significantly accelerates the training process.