median-reduction

L1 · single operatorreductionfp329.15× target90 min budget

You write custom Triton 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 Triton kernels and leave others unchanged. You may replace multiple operators with custom implementations.

Environment

  • GPU: NVIDIA L40S (44 GiB VRAM)
  • CUDA: 12.1
  • PyTorch: 2.5.0+cu121, preinstalled (Triton 3.1.0 bundled)
  • Reference deps: this task's reference.py dependencies (e.g. transformers/timm/torchvision) are preinstalled and version-pinned
  • Workspace: /workspace/ (contains reference.py)
  • Solution file: Your final solution must be saved to /workspace/solution.py

Example

Here's an example to show you the syntax of inline embedding custom Triton kernels in PyTorch:

Input architecture:

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():
    # randomly generate input tensors based on the model architecture
    a = torch.randn(1, 128).cuda()
    b = torch.randn(1, 128).cuda()
    return [a, b]


def get_init_inputs():
    # randomly generate tensors required for initialization based on the model architecture
    return []

Optimized with Triton kernels:

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,  # Pointer to first input
    y_ptr,  # Pointer to second input
    out_ptr,  # Pointer to output
    n_elements,  # Total number of elements in input/output
    BLOCK_SIZE: tl.constexpr,
):
    # Each program handles a contiguous block of data of size BLOCK_SIZE
    block_start = tl.program_id(0) * BLOCK_SIZE
    # Create a range of offsets [0..BLOCK_SIZE-1]
    offsets = block_start + tl.arange(0, BLOCK_SIZE)
    # Mask to ensure we don't go out of bounds
    mask = offsets < n_elements
    # Load input values
    x = tl.load(x_ptr + offsets, mask=mask, other=0.0)
    y = tl.load(y_ptr + offsets, mask=mask, other=0.0)
    # Perform the elementwise addition
    out = x + y
    # Store the result
    tl.store(out_ptr + offsets, out, mask=mask)


def triton_add(x: torch.Tensor, y: torch.Tensor):
    """
    This function wraps the Triton kernel call. It:
      1. Ensures the inputs are contiguous on GPU.
      2. Calculates the grid (blocks) needed.
      3. Launches the Triton kernel.
    """
    assert x.is_cuda and y.is_cuda, "Tensors must be on CUDA."
    x = x.contiguous()
    y = y.contiguous()

    # Prepare output tensor
    out = torch.empty_like(x)

    # Number of elements in the tensor
    n_elements = x.numel()
    BLOCK_SIZE = 128  # Tunable parameter for block size

    # Determine the number of blocks needed
    grid = lambda meta: ((n_elements + meta["BLOCK_SIZE"] - 1) // meta["BLOCK_SIZE"],)

    # Launch the Triton kernel
    add_kernel[grid](x, y, out, n_elements, BLOCK_SIZE=BLOCK_SIZE)
    return out


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

    def forward(self, a, b):
        # Instead of "return a + b", call our Triton-based addition
        return triton_add(a, b)

Reference Architecture

The reference PyTorch code is available at /workspace/reference.py:

import torch
import torch.nn as nn

DTYPE = torch.float32


class Model(nn.Module):
    """Single operator: median along the last axis of a (5120, 512, 1024) fp32 tensor."""
    def __init__(self):
        super(Model, self).__init__()
        self.to(torch.float32)

    def forward(self, x):
        x = torch.median(x, dim=2).values
        return x


def get_inputs():
    # A 10 GiB input, drawn on the device.
    return [torch.randn(5120, 512, 1024, dtype=DTYPE, device="cuda")]


def get_init_inputs():
    return []

Your Task

  1. Write Triton kernels with @triton.jit and launch them from ModelNew.forward
  2. Define a ModelNew class that is a drop-in replacement for Model
  3. Save your final solution to /workspace/solution.py, defining ModelNew at module level (importable as solution.ModelNew)

Weight contract: ModelNew is constructed with the same random seed and the same get_init_inputs() as Model, and no state_dict is copied, so __init__ must take the same draws from the RNG, in the same order, and create the reference's parameter submodules with the same shapes, in the same order.

Evaluation Criteria

Your solution will be evaluated on three criteria:

  1. Compilable: solution.py must load and ModelNew must instantiate without errors
  2. Correctness: ModelNew output must match the reference within tolerance (atol=1e-12, rtol=1e-8 (an exact fp32 selection: the median is one element of the row, returned bit for bit); the solution's output dtype must match the reference)
  3. Speedup: ModelNew must be at least 9.15x as fast as the reference. This target is the speedup a strong reference solution achieves, so aim to match or beat it (timing is noisy, so re-measure).

What is rejected. Your speedup must come from Triton kernels you wrote, computing what the reference computes at the reference's precision, entirely at call time. If any part of your speedup comes from anything other than those kernels, the reward is zero, even if the rest of your solution is valid Triton.

How your solution is graded

Both models are compared and timed under the following fixed conditions:

  • Both Model and ModelNew run in eval() mode under torch.no_grad(), with backend flags re-pinned before every forward and checked afterwards for both models: TF32 off (allow_tf32=False), cudnn.benchmark=False, deterministic cuDNN, full float32_matmul_precision, and a fixed BLAS backend.
  • Correctness is checked over several seeded input draws, taken from different value distributions rather than all from the same one. Shapes and dtypes are as get_inputs() produces; your solution must be correct for any values it can produce, and must keep the numerical guards the reference keeps (a running maximum, an eps), which is checked outside that range.
  • The speedup must come from the kernels you write, not from computing in a dtype other than the reference's.
  • Speedup uses cold-cache CUDA-event timing (L2 flushed before every trial), a freshly-allocated input each trial, warmups discarded, averaged over many trials.
  • Baseline = the best generic result. The reference is timed as the faster of its eager run and a generic torch.compile of it; neither side uses CUDA-graph capture.