causal-attention-cosh-gelu-clamp
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.pydependencies (e.g.transformers/timm/torchvision) are preinstalled and version-pinned - Workspace:
/workspace/(containsreference.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):
"""Fused operator chain: attention_causal -> cosh -> gelu -> clamp."""
def __init__(self):
super(Model, self).__init__()
self.to(torch.float32)
def forward(self, x):
_q = x.view(8, 32768, 8, 64).transpose(1, 2)
_o = torch.nn.functional.scaled_dot_product_attention(_q, _q, _q, is_causal=True)
x = _o.transpose(1, 2).reshape(8, 32768, 512)
x = torch.cosh(x)
x = torch.nn.functional.gelu(x)
x = torch.clamp(x, min=-1.0, max=1.0)
return x
def get_inputs():
return [torch.randn(8, 32768, 512, dtype=DTYPE)]
def get_init_inputs():
return []
Your Task
- Write Triton kernels with
@triton.jitand launch them fromModelNew.forward - Define a
ModelNewclass that is a drop-in replacement forModel - Save your final solution to
/workspace/solution.py, definingModelNewat module level (importable assolution.ModelNew)
Weight contract:
ModelNewis constructed with the same random seed and the sameget_init_inputs()asModel, and nostate_dictis 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:
- Compilable:
solution.pymust load andModelNewmust instantiate without errors - Correctness:
ModelNewoutput must match the reference within tolerance (atol=1e-4, rtol=1e-4; the solution's output dtype must match the reference) - Speedup:
ModelNewmust be at least 1.72x 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
ModelandModelNewrun ineval()mode undertorch.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, fullfloat32_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.compileof it; neither side uses CUDA-graph capture.