error
50_ReLUSelfAttention.py
started
2026-05-05T05:48:27Z
reference PyTorch source (the prompt the agent sees)
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
# From https://github.com/karpathy/minGPT/blob/master/mingpt/model.py
class NewGELU(nn.Module):
"""
Implementation of the GELU activation function currently in Google BERT repo (identical to OpenAI GPT).
Reference: Gaussian Error Linear Units (GELU) paper: https://arxiv.org/abs/1606.08415
"""
def __init__(self):
super(NewGELU, self).__init__()
def forward(self, x):
return 0.5 * x * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (x + 0.044715 * torch.pow(x, 3.0))))
class Model(nn.Module):
"""
A multi-head masked self-attention layer with a projection at the end that uses ReLU instead of Softmax.
It is possible to use torch.nn.MultiheadAttention here but I am including an
explicit implementation here to show that there is nothing too scary here.
"""
def __init__(self, n_embd, n_head, max_seqlen):
super().__init__()
assert n_embd % n_head == 0
# key, query, value projections for all heads, but in a batch
self.c_attn = nn.Linear(n_embd, 3 * n_embd)
# output projection
self.c_proj = nn.Linear(n_embd, n_embd)
# causal mask to ensure that attention is only applied to the left in the input sequence
self.register_buffer("bias", torch.tril(torch.ones(max_seqlen, max_seqlen))
.view(1, 1, max_seqlen, max_seqlen))
self.n_head = n_head
self.n_embd = n_embd
def forward(self, x):
B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd)
# calculate query, key, values for all heads in batch and move head forward to be the batch dim
q, k ,v = self.c_attn(x).split(self.n_embd, dim=2)
k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
# causal self-attention; Self-attend: (B, nh, T, hs) x (B, nh, hs, T) -> (B, nh, T, T)
att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
att = att.masked_fill(self.bias[:,:,:T,:T] == 0, float('-inf'))
att = F.relu(att)
y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side
return y
batch_size = 16
max_seqlen = 1024
n_embd = 768 # Hidden dimension, typical for BERT-base size
n_head = 12 # Number of attention heads, typical for BERT-base size
def get_inputs():
return [torch.rand(batch_size, max_seqlen, n_embd)]
def get_init_inputs():
return [n_embd, n_head, max_seqlen]turn 010.5s turn · 10.5s LLM · 0.0s tools
reasoning
**Testing output match order**
I’m considering whether it’s okay if cpp_sources has signature declarations. It seems like I might need to test this out. I'm wondering if I need an exact match for the output order. To clarify, I’m referencing the formula q, k, and v from the linear transformation applied to x, multiplying by the weight matrix W.T and adding b. There’s a lot to think about here as I try to ensure everything is aligned properly!
call → get_gpu_specs
callget_gpu_specs
{}
result ← get_gpu_specs (ok)
okget_gpu_specs
GPU specs for NVIDIA H100 80GB HBM3:
total memory (runtime): 79.1 GB
spec entry: H100
GPU Architecture: Hopper
GPU Memory: 80GB
Memory Bandwidth: 3.35 TB/s
FP64 TFLOPS: 34
FP64 Tensor Core TFLOPS: 67
FP32 TFLOPS: 67
TF32 Tensor Core TFLOPS: 989 with sparsity
BFLOAT16 Tensore Core TFLOPS: 1979 with sparsity
FP16 Tensor Core TFLOPS: 1979 with sparsity
FP8 Tensor Core TFLOPS: 3958 with sparsity
INT8 Tensor Core TOPS: 3958 with sparsity
Register File Size: 64K 32-bit registers per SM
Maximum number of registers per thread: 255
Maximum number of thread blocks per SM: 32
Shared memory capacity per SM: 228 KB
Maximum shared memory per thread block: 227 KB
turn 1589.5s turn · 589.5s LLM · 0.0s tools
feedbackLLM call failed: _WorkItemTimeout: work item exceeded soft timeout budget
final submitted kernel (76 lines, 2,419 chars) — full source, untruncated
import torch
import torch.nn as nn
import math
from torch.utils.cpp_extension import load_inline
_cpp_src = r"""
#include <torch/extension.h>
void causal_relu_(torch::Tensor att);
"""
_cuda_src = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAGuard.h>
#include <cuda.h>
#include <cuda_runtime.h>
__global__ void causal_relu_kernel(float* __restrict__ a, long long n, int T) {
long long idx = (long long)blockIdx.x * blockDim.x + threadIdx.x;
long long stride = (long long)blockDim.x * gridDim.x;
for (; idx < n; idx += stride) {
int col = (int)(idx % T);
int row = (int)((idx / T) % T);
float v = a[idx];
if (col > row || v <= 0.0f) v = 0.0f;
a[idx] = v;
}
}
void causal_relu_(torch::Tensor att) {
const c10::cuda::CUDAGuard device_guard(att.device());
long long n = att.numel();
int T = (int)att.size(-1);
int threads = 256;
int blocks = (int)((n + threads - 1) / threads);
if (blocks > 65535) blocks = 65535;
causal_relu_kernel<<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>>(att.data_ptr<float>(), n, T);
}
"""
_attn_ext = load_inline(
name="causal_relu_attn_ext_v1",
cpp_sources=_cpp_src,
cuda_sources=_cuda_src,
functions=["causal_relu_"],
extra_cflags=["-O3"],
extra_cuda_cflags=["-O3"],
verbose=False,
)
class ModelNew(nn.Module):
def __init__(self, n_embd, n_head, max_seqlen):
super().__init__()
assert n_embd % n_head == 0
self.c_attn = nn.Linear(n_embd, 3 * n_embd)
self.c_proj = nn.Linear(n_embd, n_embd)
self.register_buffer("bias", torch.tril(torch.ones(max_seqlen, max_seqlen)).view(1, 1, max_seqlen, max_seqlen))
self.n_head = n_head
self.n_embd = n_embd
self._scale = 1.0 / math.sqrt(n_embd // n_head)
def forward(self, x):
B, T, C = x.size()
hs = C // self.n_head
qkv = self.c_attn(x)
q, k, v = qkv.split(self.n_embd, dim=2)
q = q.view(B, T, self.n_head, hs).transpose(1, 2)
k = k.view(B, T, self.n_head, hs).transpose(1, 2)
v = v.view(B, T, self.n_head, hs).transpose(1, 2)
att = torch.matmul(q, k.transpose(-2, -1))
att.mul_(self._scale)
_attn_ext.causal_relu_(att)
y = torch.matmul(att, v)
y = y.transpose(1, 2).contiguous().view(B, T, C)
return y