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 chunk+gelu+elementwise_mul), or algorithmic changes (such as optimized memory access patterns). You are only limited by your imagination.
CUDA kernel for Robust Scale Gate activation with robust normalization statistics.

Optimizations:

Stable sigmoid: Uses exp(-|x|) formulation for numerical stability.

Robust statistics: Uses median and interquartile range (IQR) instead of mean/variance.

CPU-GPU hybrid: Statistics computed on CPU from sorted tensor.

Workflow:

CPU:

Flatten and sort input tensor.

Compute robust statistics:

median (50th percentile)

q1 (25th percentile)

q3 (75th percentile)

IQR = q3 - q1

CUDA kernel (rsg_apply_kernel):

Robust normalization: z_robust = (x - median) / (IQR + ε)

Sigmoid gate: gate = sigmoid(x)

Gated output: output = z_robust * gate

Mathematically:
output = ((x - median)/(IQR + ε))·sigmoid(x)

Characteristics:

Robust to outliers: Median and IQR are less sensitive than mean/variance.

Self-gating: Original input gates robustly normalized value.

Hybrid computation: Statistics computed on CPU (sorting is expensive on GPU).

Use cases:

Data with outliers or heavy-tailed distributions.

Robust feature scaling.

Activation functions needing outlier resistance.

Specialized for scenarios where input data may contain extreme values that would destabilize standard normalization.






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):
        super().__init__()
        self.epsilon = 1e-5

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        x_flat = x.flatten()

        median = torch.quantile(x_flat, 0.5)

        q1 = torch.quantile(x_flat, 0.25)
        q3 = torch.quantile(x_flat, 0.75)
        iqr = q3 - q1

        z_robust = (x - median) / (iqr + self.epsilon)
        gate = torch.sigmoid(x)

        return z_robust * gate


batch_size = 128
feature_dim = 512


def get_inputs():
    x = torch.randn(batch_size, feature_dim, dtype=torch.float32)
    return [x]


def get_init_inputs():
    return []