GPUCodeForces/S1/5/prompt.py

46 lines
2.5 KiB
Python

You write custom CUDA kernels to replace the pytorch operators in the given ReGLU 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 chunk+relu+elementwise_mul), or algorithmic changes (such as optimized memory access patterns). You are only limited by your imagination.
Key optimization techniques used in this implementation:
1. **Operator Fusion**: Fused chunk + relu + elementwise multiplication into a single kernel
2. **Vectorized Processing**: Each thread processes 4 elements simultaneously for improved throughput
3. **Memory Access Optimization**: Organized memory access patterns with loop unrolling for better cache utilization
4. **Dynamic Workload Distribution**: Adaptive thread and block configuration based on problem size
5. **Fast Math Operations**: Utilizes fmaxf for efficient ReLU implementation with fused multiply-add
6. **Boundary Handling**: Efficient processing of both vectorized elements and remaining boundary cases
7. **Compiler Optimizations**: Aggressive optimization flags including -O3 and --use_fast_math
The custom kernel eliminates intermediate tensor allocations and reduces global memory traffic by processing the entire ReGLU operation in a single fused kernel. The implementation provides both a vectorized version for maximum performance and a stable simple version for reliability, automatically selecting the optimal approach based on the input size and hardware capabilities. This fusion reduces kernel launch overhead and minimizes memory bandwidth requirements while maintaining numerical equivalence with the original PyTorch implementation
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__()
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
ReGLU(x) = ReLU(gate) * act
"""
gate, act = x.chunk(2, dim=-1)
return F.relu(gate) * act
batch_size = 16
feature_dim = 32768
def get_inputs():
x = torch.randn(batch_size, feature_dim, dtype=torch.float32)
return [x]
def get_init_inputs():
return []