correct
20_RotaryPositionEmbeddingBio.py
started
2026-05-02T19:27:19Z
timingkernelbench.timing
kernel mean / median / std
0.01 / — / 2.70e-04 μs
ref mean / median / std
0.07 / — / 0.01 μs
numerical precisioneval_kernel_against_ref
gpu memoryextended_metrics.measure_memory
kernel launches / fusiontorch.profiler
fusion ratio (ref / kernel)
5.62x
SOL (speed-of-light)nsight_hardware_counters
roofline / occupancynsight_hardware_counters
dram bandwidth
770.13 GB/s
warp stalls (top 5)nsight
reference PyTorch source (the prompt the agent sees)
import torch
import torch.nn as nn
import math
class Model(nn.Module):
"""
Rotary Position Embedding (RoPE) applied to protein residue sequences.
Used in ESM-2 and similar protein language models. Encodes absolute
position via rotation of query/key pairs in 2-D subspaces, preserving
relative-position information in dot-product attention.
"""
def __init__(self, dim, max_seq_len=2048, base=10000.0):
super().__init__()
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
self.register_buffer("inv_freq", inv_freq)
self.max_seq_len = max_seq_len
self.dim = dim
def _build_cos_sin(self, seq_len: int, device: torch.device):
t = torch.arange(seq_len, device=device, dtype=self.inv_freq.dtype)
freqs = torch.outer(t, self.inv_freq)
emb = torch.cat([freqs, freqs], dim=-1)
return emb.cos(), emb.sin()
@staticmethod
def _rotate_half(x: torch.Tensor) -> torch.Tensor:
x1, x2 = x.chunk(2, dim=-1)
return torch.cat([-x2, x1], dim=-1)
def forward(self, q: torch.Tensor, k: torch.Tensor) -> tuple:
"""
Args:
q: (B, H, N, D) – queries
k: (B, H, N, D) – keys
Returns:
(q_rot, k_rot) each (B, H, N, D) with RoPE applied
"""
N = q.shape[2]
cos, sin = self._build_cos_sin(N, q.device) # (N, D)
cos = cos.unsqueeze(0).unsqueeze(0)
sin = sin.unsqueeze(0).unsqueeze(0)
q_rot = q * cos + self._rotate_half(q) * sin
k_rot = k * cos + self._rotate_half(k) * sin
return q_rot, k_rot
dim = 64
num_heads = 8
seq_len = 256
batch_size = 4
def get_inputs():
p = popcorn_pri
bs = p.jitter_int(batch_size)
nh = p.jitter_int(num_heads)
sl = p.jitter_int(seq_len)
q = torch.randn(bs, nh, sl, dim)
k = torch.randn(bs, nh, sl, dim)
return [q, k]
def get_init_inputs():
return [dim]
turn 08.7s turn · 8.7s LLM · 0.0s tools
reasoning
**Considering CUDA and model transfer**
I'm thinking about the possibility of using CUDA, especially if the model isn't moved and buffers are on the CPU. I wonder if forward transfer could still happen. It seems better if the benchmark sets the model as ModelNew(*init).cuda(), as that feels more robust. I could explore compiling an extension that applies q and k using cached cos/sin. Then, for kernel memory, I might need to read q, k, and write qrot, krot for each element pair across two dimensions.
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 1 · 1 tool call(s) · 19.1s turn · 19.1s LLM · 9,706 chars (click to expand)
turn 119.1s turn · 19.1s LLM · 0.0s tools
reasoning
**Evaluating code considerations**
I'm noticing some differences with MA, but maybe it's just a small adjustment. I think the q and k should be fp32 only. I could guard the dtype and skip the try-except block since that might create unnecessary complications. There’s a potential issue with compiling the H100 architecture, and the default for load_inline includes the current architecture. I need to craft the code carefully, set a static check, and then compile it to ensure everything works.
call → compile_kernel
callcompile_kernel
{
"kernel_code": "import torch\nimport torch.nn as nn\nfrom torch.utils.cpp_extension import load_inline\n\n_cpp_src = r\"\"\"\n#include <torch/extension.h>\n#include <vector>\n\nstd::vector<torch::Tensor> rope_forward_cuda(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin);\n\nstd::vector<torch::Tensor> rope_forward(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin) {\n return rope_forward_cuda(q, k, cos, sin);\n}\n\"\"\"\n\n_cuda_src = r\"\"\"\n#include <torch/extension.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <vector>\n\n__global__ void rope_kernel_64(const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ cos,\n const float* __restrict__ sin,\n float* __restrict__ qo,\n float* __restrict__ ko,\n int total_pairs,\n int N) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n if (idx >= total_pairs) return;\n\n // idx covers (B*H, N, D/2) with D fixed at 64 for the benchmark.\n int j = idx & 31; // pair index in [0,31]\n int tmp = idx >> 5;\n int n = tmp % N;\n int bh = tmp / N;\n\n int base = ((bh * N + n) << 6) + j;\n int base2 = base + 32;\n int cs = n * 32 + j;\n\n float c = cos[cs];\n float s = sin[cs];\n\n float q1 = q[base];\n float q2 = q[base2];\n qo[base] = q1 * c - q2 * s;\n qo[base2] = q2 * c + q1 * s;\n\n float k1 = k[base];\n float k2 = k[base2];\n ko[base] = k1 * c - k2 * s;\n ko[base2] = k2 * c + k1 * s;\n}\n\n__global__ void rope_kernel_generic(const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ cos,\n const float* __restrict__ sin,\n float* __restrict__ qo,\n float* __restrict__ ko,\n int total_pairs,\n int N,\n int D,\n int half) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n if (idx >= total_pairs) return;\n\n int j = idx % half;\n int tmp = idx / half;\n int n = tmp % N;\n int bh = tmp / N;\n\n int base = (bh * N + n) * D + j;\n int base2 = base + half;\n int cs = n * half + j;\n\n float c = cos[cs];\n float s = sin[cs];\n\n float q1 = q[base];\n float q2 = q[base2];\n qo[base] = q1 * c - q2 * s;\n qo[base2] = q2 * c + q1 * s;\n\n float k1 = k[base];\n float k2 = k[base2];\n ko[base] = k1 * c - k2 * s;\n ko[base2] = k2 * c + k1 * s;\n}\n\nstd::vector<torch::Tensor> rope_forward_cuda(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin) {\n auto qo = torch::empty_like(q);\n auto ko = torch::empty_like(k);\n\n int B = (int)q.size(0);\n int H = (int)q.size(1);\n int N = (int)q.size(2);\n int D = (int)q.size(3);\n int half = D / 2;\n int total_pairs = B * H * N * half;\n\n const int threads = 256;\n int blocks = (total_pairs + threads - 1) / threads;\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n\n if (D == 64) {\n rope_kernel_64<<<blocks, threads, 0, stream>>>(\n q.data_ptr<float>(), k.data_ptr<float>(), cos.data_ptr<float>(), sin.data_ptr<float>(),\n qo.data_ptr<float>(), ko.data_ptr<float>(), total_pairs, N);\n } else {\n rope_kernel_generic<<<blocks, threads, 0, stream>>>(\n q.data_ptr<float>(), k.data_ptr<float>(), cos.data_ptr<float>(), sin.data_ptr<float>(),\n qo.data_ptr<float>(), ko.data_ptr<float>(), total_pairs, N, D, half);\n }\n return {qo, ko};\n}\n\"\"\"\n\n_rope_ext = load_inline(\n name=\"rope_ext_opt\",\n cpp_sources=[_cpp_src],\n cuda_sources=[_cuda_src],\n functions=[\"rope_forward\"],\n extra_cflags=[\"-O3\"],\n extra_cuda_cflags=[\"-O3\"],\n verbose=False,\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, dim, max_seq_len=2048, base=10000.0):\n super().__init__()\n inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))\n t = torch.arange(max_seq_len, dtype=inv_freq.dtype)\n freqs = torch.outer(t, inv_freq)\n self.register_buffer(\"cos_cached\", freqs.cos(), persistent=False)\n self.register_buffer(\"sin_cached\", freqs.sin(), persistent=False)\n self.register_buffer(\"inv_freq\", inv_freq, persistent=False)\n self.max_seq_len = max_seq_len\n self.dim = dim\n self.base = base\n\n def forward(self, q: torch.Tensor, k: torch.Tensor) -> tuple:\n N = q.shape[2]\n cos = self.cos_cached[:N]\n sin = self.sin_cached[:N]\n return tuple(_rope_ext.rope_forward(q, k, cos, sin))\n"
}
result ← compile_kernel (fail)
failcompile_kernel
compile_kernel FAILED: RuntimeError.
RuntimeError: Error building extension 'rope_ext_opt': [1/3] /opt/conda/bin/x86_64-conda-linux-gnu-c++ -MMD -MF main.o.d -DTORCH_EXTENSION_NAME=rope_ext_opt -DTORCH_API_INCLUDE_EXTENSION_H -isystem /scratch/tejas/PopcornBench/.venv/lib/python3.10/site-packages/torch/include -isystem /scratch/tejas/PopcornBench/.venv/lib/python3.10/site-packages/torch/include/torch/csrc/api/include -isystem /usr/local/cuda/include -isystem /home/prabhune/.local/share/uv/python/cpython-3.10-linux-x86_64-gnu/include/python3.10 -fPIC -std=c++17 -O3 -c /scratch/tejas/PopcornBench/runs/l12_default/popcorn/gpt-5.5-priority/level_1_problem_20_cache/k_596f6855662e/rope_ext_opt/main.cpp -o main.o
[2/3] /usr/local/cuda/bin/nvcc -MD -MF cuda.cuda.o.d -ccbin /opt/conda/bin/x86_64-conda-linux-gnu-cc -DTORCH_EXTENSION_NAME=rope_ext_opt -DTORCH_API_INCLUDE_EXTENSION_H -isystem /scratch/tejas/PopcornBench/.venv/lib/python3.10/site-packages/torch/include -isystem /scratch/tejas/PopcornBench/.venv/lib/python3.10/site-packages/torch/include/torch/csrc/api/include -isystem /usr/local/cuda/include -isystem /home/prabhune/.local/share/uv/python/cpython-3.10-linux-x86_64-gnu/include/python3.10 -D__CUDA_NO_HALF_OPERATORS__ -D__CUDA_NO_HALF_CONVERSIONS__ -D__CUDA_NO_BFLOAT16_CONVERSIONS__ -D__CUDA_NO_HALF2_OPERATORS__ --expt-relaxed-constexpr -gencode=arch=compute_90,code=compute_90 -gencode=arch=compute_90,code=sm_90 --compiler-options '-fPIC' -O3 -std=c++17 -c /scratch/tejas/PopcornBench/runs/l12_default/popcorn/gpt-5.5-priority/level_1_problem_20_cache/k_596f6855662e/rope_ext_opt/cuda.cu -o cuda.cuda.o
FAILED: [code=2] cuda.cuda.o
/usr/local/cuda/bin/nvcc -MD -MF cuda.cuda.o.d -ccbin /opt/conda/bin/x86_64-conda-linux-gnu-cc -DTORCH_EXTENSION_NAME=rope_ext_opt -DTORCH_API_INCLUDE_EXTENSION_H -isystem /scratch/tejas/PopcornBench/.venv/lib/python3.10/site-packages/torch/include -isystem /scratch/tejas/PopcornBench/.venv/lib/python3.10/site-packages/torch/include/torch/csrc/api/include -isystem /usr/local/cuda/include -isystem /home/prabhune/.local/share/uv/python/cpython-3.10-linux-x86_64-gnu/include/python3.10 -D__CUDA_NO_HALF_OPERATORS__ -D__CUDA_NO_HALF_CONVERSIONS__ -D__CUDA_NO_BFLOAT16_CONVERSIONS__ -D__CUDA_NO_HALF2_OPERATORS__ --expt-relaxed-constexpr -gencode=arch=compute_90,code=compute_90 -gencode=arch=compute_90,code=sm_90 --compiler-options '-fPIC' -O3 -std=c++17 -c /scratch/tejas/PopcornBench/runs/l12_default/popcorn/gpt-5.5-priority/level_1_problem_20_cache/k_596f6855662e/rope_ext_opt/cuda.cu -o cuda.cuda.o
nvcc warning : incompatible redefinition for option 'compiler-bindir', the last value of this option was used
/scratch/tejas/PopcornBench/runs/l12_default/popcorn/gpt-5.5-priority/level_1_problem_20_cache/k_596f6855662e/rope_ext_opt/cuda.cu(94): error: namespace "at::cuda" has no member "getCurrentCUDAStream"
cudaStream_t stream = at::cuda::getCurrentCUDAStream();
^
1 error detected in the compilation of "/scratch/tejas/PopcornBench/runs/l12_default/popcorn/gpt-5.5-priority/level_1_problem_20_cache/k_596f6855662e/rope_ext_opt/cuda.cu".
ninja: build stopped: subcommand failed.
turn 29.1s turn · 9.1s LLM · 0.0s tools
call → compile_kernel
callcompile_kernel
{
"kernel_code": "import torch\nimport torch.nn as nn\nfrom torch.utils.cpp_extension import load_inline\n\n_cpp_src = r\"\"\"\n#include <torch/extension.h>\n#include <vector>\n\nstd::vector<torch::Tensor> rope_forward_cuda(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin);\n\nstd::vector<torch::Tensor> rope_forward(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin) {\n return rope_forward_cuda(q, k, cos, sin);\n}\n\"\"\"\n\n_cuda_src = r\"\"\"\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <vector>\n\n__global__ void rope_kernel_64(const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ cos,\n const float* __restrict__ sin,\n float* __restrict__ qo,\n float* __restrict__ ko,\n int total_pairs,\n int N) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n if (idx >= total_pairs) return;\n int j = idx & 31;\n int tmp = idx >> 5;\n int n = tmp % N;\n int bh = tmp / N;\n int base = ((bh * N + n) << 6) + j;\n int base2 = base + 32;\n int cs = n * 32 + j;\n float c = cos[cs];\n float s = sin[cs];\n float q1 = q[base];\n float q2 = q[base2];\n qo[base] = q1 * c - q2 * s;\n qo[base2] = q2 * c + q1 * s;\n float k1 = k[base];\n float k2 = k[base2];\n ko[base] = k1 * c - k2 * s;\n ko[base2] = k2 * c + k1 * s;\n}\n\n__global__ void rope_kernel_generic(const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ cos,\n const float* __restrict__ sin,\n float* __restrict__ qo,\n float* __restrict__ ko,\n int total_pairs,\n int N,\n int D,\n int half) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n if (idx >= total_pairs) return;\n int j = idx % half;\n int tmp = idx / half;\n int n = tmp % N;\n int bh = tmp / N;\n int base = (bh * N + n) * D + j;\n int base2 = base + half;\n int cs = n * half + j;\n float c = cos[cs];\n float s = sin[cs];\n float q1 = q[base];\n float q2 = q[base2];\n qo[base] = q1 * c - q2 * s;\n qo[base2] = q2 * c + q1 * s;\n float k1 = k[base];\n float k2 = k[base2];\n ko[base] = k1 * c - k2 * s;\n ko[base2] = k2 * c + k1 * s;\n}\n\nstd::vector<torch::Tensor> rope_forward_cuda(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin) {\n auto qo = torch::empty_like(q);\n auto ko = torch::empty_like(k);\n int B = (int)q.size(0);\n int H = (int)q.size(1);\n int N = (int)q.size(2);\n int D = (int)q.size(3);\n int half = D / 2;\n int total_pairs = B * H * N * half;\n const int threads = 256;\n int blocks = (total_pairs + threads - 1) / threads;\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n if (D == 64) {\n rope_kernel_64<<<blocks, threads, 0, stream>>>(q.data_ptr<float>(), k.data_ptr<float>(), cos.data_ptr<float>(), sin.data_ptr<float>(), qo.data_ptr<float>(), ko.data_ptr<float>(), total_pairs, N);\n } else {\n rope_kernel_generic<<<blocks, threads, 0, stream>>>(q.data_ptr<float>(), k.data_ptr<float>(), cos.data_ptr<float>(), sin.data_ptr<float>(), qo.data_ptr<float>(), ko.data_ptr<float>(), total_pairs, N, D, half);\n }\n return {qo, ko};\n}\n\"\"\"\n\n_rope_ext = load_inline(\n name=\"rope_ext_opt2\",\n cpp_sources=[_cpp_src],\n cuda_sources=[_cuda_src],\n functions=[\"rope_forward\"],\n extra_cflags=[\"-O3\"],\n extra_cuda_cflags=[\"-O3\"],\n verbose=False,\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, dim, max_seq_len=2048, base=10000.0):\n super().__init__()\n inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))\n t = torch.arange(max_seq_len, dtype=inv_freq.dtype)\n freqs = torch.outer(t, inv_freq)\n self.register_buffer(\"cos_cached\", freqs.cos(), persistent=False)\n self.register_buffer(\"sin_cached\", freqs.sin(), persistent=False)\n self.register_buffer(\"inv_freq\", inv_freq, persistent=False)\n self.max_seq_len = max_seq_len\n self.dim = dim\n self.base = base\n\n def forward(self, q: torch.Tensor, k: torch.Tensor) -> tuple:\n N = q.shape[2]\n return tuple(_rope_ext.rope_forward(q, k, self.cos_cached[:N], self.sin_cached[:N]))\n"
}
result ← compile_kernel (ok)
okcompile_kernel
compile_kernel PASSED: kernel compiled without errors.
turn 39.1s turn · 9.1s LLM · 0.0s tools
call → run_correctness
callrun_correctness
{
"kernel_code": "import torch\nimport torch.nn as nn\nfrom torch.utils.cpp_extension import load_inline\n\n_cpp_src = r\"\"\"\n#include <torch/extension.h>\n#include <vector>\n\nstd::vector<torch::Tensor> rope_forward_cuda(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin);\n\nstd::vector<torch::Tensor> rope_forward(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin) {\n return rope_forward_cuda(q, k, cos, sin);\n}\n\"\"\"\n\n_cuda_src = r\"\"\"\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <vector>\n\n__global__ void rope_kernel_64(const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ cos,\n const float* __restrict__ sin,\n float* __restrict__ qo,\n float* __restrict__ ko,\n int total_pairs,\n int N) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n if (idx >= total_pairs) return;\n int j = idx & 31;\n int tmp = idx >> 5;\n int n = tmp % N;\n int bh = tmp / N;\n int base = ((bh * N + n) << 6) + j;\n int base2 = base + 32;\n int cs = n * 32 + j;\n float c = cos[cs];\n float s = sin[cs];\n float q1 = q[base];\n float q2 = q[base2];\n qo[base] = q1 * c - q2 * s;\n qo[base2] = q2 * c + q1 * s;\n float k1 = k[base];\n float k2 = k[base2];\n ko[base] = k1 * c - k2 * s;\n ko[base2] = k2 * c + k1 * s;\n}\n\n__global__ void rope_kernel_generic(const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ cos,\n const float* __restrict__ sin,\n float* __restrict__ qo,\n float* __restrict__ ko,\n int total_pairs,\n int N,\n int D,\n int half) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n if (idx >= total_pairs) return;\n int j = idx % half;\n int tmp = idx / half;\n int n = tmp % N;\n int bh = tmp / N;\n int base = (bh * N + n) * D + j;\n int base2 = base + half;\n int cs = n * half + j;\n float c = cos[cs];\n float s = sin[cs];\n float q1 = q[base];\n float q2 = q[base2];\n qo[base] = q1 * c - q2 * s;\n qo[base2] = q2 * c + q1 * s;\n float k1 = k[base];\n float k2 = k[base2];\n ko[base] = k1 * c - k2 * s;\n ko[base2] = k2 * c + k1 * s;\n}\n\nstd::vector<torch::Tensor> rope_forward_cuda(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin) {\n auto qo = torch::empty_like(q);\n auto ko = torch::empty_like(k);\n int B = (int)q.size(0);\n int H = (int)q.size(1);\n int N = (int)q.size(2);\n int D = (int)q.size(3);\n int half = D / 2;\n int total_pairs = B * H * N * half;\n const int threads = 256;\n int blocks = (total_pairs + threads - 1) / threads;\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n if (D == 64) {\n rope_kernel_64<<<blocks, threads, 0, stream>>>(q.data_ptr<float>(), k.data_ptr<float>(), cos.data_ptr<float>(), sin.data_ptr<float>(), qo.data_ptr<float>(), ko.data_ptr<float>(), total_pairs, N);\n } else {\n rope_kernel_generic<<<blocks, threads, 0, stream>>>(q.data_ptr<float>(), k.data_ptr<float>(), cos.data_ptr<float>(), sin.data_ptr<float>(), qo.data_ptr<float>(), ko.data_ptr<float>(), total_pairs, N, D, half);\n }\n return {qo, ko};\n}\n\"\"\"\n\n_rope_ext = load_inline(\n name=\"rope_ext_opt2\",\n cpp_sources=[_cpp_src],\n cuda_sources=[_cuda_src],\n functions=[\"rope_forward\"],\n extra_cflags=[\"-O3\"],\n extra_cuda_cflags=[\"-O3\"],\n verbose=False,\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, dim, max_seq_len=2048, base=10000.0):\n super().__init__()\n inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))\n t = torch.arange(max_seq_len, dtype=inv_freq.dtype)\n freqs = torch.outer(t, inv_freq)\n self.register_buffer(\"cos_cached\", freqs.cos(), persistent=False)\n self.register_buffer(\"sin_cached\", freqs.sin(), persistent=False)\n self.register_buffer(\"inv_freq\", inv_freq, persistent=False)\n self.max_seq_len = max_seq_len\n self.dim = dim\n self.base = base\n\n def forward(self, q: torch.Tensor, k: torch.Tensor) -> tuple:\n N = q.shape[2]\n return tuple(_rope_ext.rope_forward(q, k, self.cos_cached[:N], self.sin_cached[:N]))\n"
}
result ← run_correctness (ok)
okrun_correctness
run_correctness PASSED: (5 / 5) trials all matched the reference.
Numerical precision: max_abs_err=4.77e-07 mean_abs_err=1.93e-08 max_rel_err=3.99e-02
turn 4 · 1 tool call(s) · 12.0s turn · 12.0s LLM · 6,307 chars (click to expand)
turn 412.0s turn · 12.0s LLM · 0.0s tools
reasoning
**Optimizing performance timing**
I need to optimize my timing for this task and submit it eventually. There could be overhead from kernel launches and allocation, especially since PyTorch reference operations are likely expensive. I think vectorizing could help — maybe letting one thread handle 4 pairs at once. I have 1024 blocks and around 262k total pairs. Coalescing memory writes is essential. I’ll need to check the efficiency of my output tuple conversion and ensure all timing is accurate before submission.
call → static_check
callstatic_check
{
"kernel_code": "import torch\nimport torch.nn as nn\nfrom torch.utils.cpp_extension import load_inline\n\n_cpp_src = r\"\"\"\n#include <torch/extension.h>\n#include <vector>\n\nstd::vector<torch::Tensor> rope_forward_cuda(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin);\n\nstd::vector<torch::Tensor> rope_forward(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin) {\n return rope_forward_cuda(q, k, cos, sin);\n}\n\"\"\"\n\n_cuda_src = r\"\"\"\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <vector>\n\n__global__ void rope_kernel_64(const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ cos,\n const float* __restrict__ sin,\n float* __restrict__ qo,\n float* __restrict__ ko,\n int total_pairs,\n int N) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n if (idx >= total_pairs) return;\n int j = idx & 31;\n int tmp = idx >> 5;\n int n = tmp % N;\n int bh = tmp / N;\n int base = ((bh * N + n) << 6) + j;\n int base2 = base + 32;\n int cs = n * 32 + j;\n float c = cos[cs];\n float s = sin[cs];\n float q1 = q[base];\n float q2 = q[base2];\n qo[base] = q1 * c - q2 * s;\n qo[base2] = q2 * c + q1 * s;\n float k1 = k[base];\n float k2 = k[base2];\n ko[base] = k1 * c - k2 * s;\n ko[base2] = k2 * c + k1 * s;\n}\n\n__global__ void rope_kernel_generic(const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ cos,\n const float* __restrict__ sin,\n float* __restrict__ qo,\n float* __restrict__ ko,\n int total_pairs,\n int N,\n int D,\n int half) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n if (idx >= total_pairs) return;\n int j = idx % half;\n int tmp = idx / half;\n int n = tmp % N;\n int bh = tmp / N;\n int base = (bh * N + n) * D + j;\n int base2 = base + half;\n int cs = n * half + j;\n float c = cos[cs];\n float s = sin[cs];\n float q1 = q[base];\n float q2 = q[base2];\n qo[base] = q1 * c - q2 * s;\n qo[base2] = q2 * c + q1 * s;\n float k1 = k[base];\n float k2 = k[base2];\n ko[base] = k1 * c - k2 * s;\n ko[base2] = k2 * c + k1 * s;\n}\n\nstd::vector<torch::Tensor> rope_forward_cuda(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin) {\n auto qo = torch::empty_like(q);\n auto ko = torch::empty_like(k);\n int B = (int)q.size(0);\n int H = (int)q.size(1);\n int N = (int)q.size(2);\n int D = (int)q.size(3);\n int half = D / 2;\n int total_pairs = B * H * N * half;\n const int threads = 256;\n int blocks = (total_pairs + threads - 1) / threads;\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n if (D == 64) {\n rope_kernel_64<<<blocks, threads, 0, stream>>>(q.data_ptr<float>(), k.data_ptr<float>(), cos.data_ptr<float>(), sin.data_ptr<float>(), qo.data_ptr<float>(), ko.data_ptr<float>(), total_pairs, N);\n } else {\n rope_kernel_generic<<<blocks, threads, 0, stream>>>(q.data_ptr<float>(), k.data_ptr<float>(), cos.data_ptr<float>(), sin.data_ptr<float>(), qo.data_ptr<float>(), ko.data_ptr<float>(), total_pairs, N, D, half);\n }\n return {qo, ko};\n}\n\"\"\"\n\n_rope_ext = load_inline(\n name=\"rope_ext_opt2\",\n cpp_sources=[_cpp_src],\n cuda_sources=[_cuda_src],\n functions=[\"rope_forward\"],\n extra_cflags=[\"-O3\"],\n extra_cuda_cflags=[\"-O3\"],\n verbose=False,\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, dim, max_seq_len=2048, base=10000.0):\n super().__init__()\n inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))\n t = torch.arange(max_seq_len, dtype=inv_freq.dtype)\n freqs = torch.outer(t, inv_freq)\n self.register_buffer(\"cos_cached\", freqs.cos(), persistent=False)\n self.register_buffer(\"sin_cached\", freqs.sin(), persistent=False)\n self.register_buffer(\"inv_freq\", inv_freq, persistent=False)\n self.max_seq_len = max_seq_len\n self.dim = dim\n self.base = base\n\n def forward(self, q: torch.Tensor, k: torch.Tensor) -> tuple:\n N = q.shape[2]\n return tuple(_rope_ext.rope_forward(q, k, self.cos_cached[:N], self.sin_cached[:N]))\n"
}
result ← static_check (ok)
okstatic_check
static_check PASSED: no violations or warnings detected.
turn 5 · FINAL · 1 tool call(s) · 17.1s turn · 17.1s LLM · 7,049 chars (click to expand)
turn 517.1s turn · 17.1s LLM · 0.0s tools · FINAL
reasoning
**Evaluating kernel specialization**
I'm considering the acceptance of the same constructor for parameters like N. If N equals 256, then D could be 64, and I wonder if total_pairs should be divisible. Should I remove that check? Various trials might suggest N remains the same. The constants in the problem appear fixed, so I think I can rely on the same unless minor adjustments are necessary. Could I write a specialized kernel without bounds if N remains 256?
**Evaluating threading options**
I'm considering a setup with 32 threads per row, which would use 8192 blocks, but that might add more overhead. Currently, I'm working with 1024 blocks of 256, which gives 8 rows per block — that seems fine. Another alternative is having one thread handle the queries and keys for a pair. That sounds good too. Also, I can explore a Python extension that returns a std::vector converted to a list, which is manageable. I'll submit this.
call → submit_kernel
callsubmit_kernel
{
"kernel_code": "import torch\nimport torch.nn as nn\nfrom torch.utils.cpp_extension import load_inline\n\n_cpp_src = r\"\"\"\n#include <torch/extension.h>\n#include <vector>\n\nstd::vector<torch::Tensor> rope_forward_cuda(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin);\n\nstd::vector<torch::Tensor> rope_forward(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin) {\n return rope_forward_cuda(q, k, cos, sin);\n}\n\"\"\"\n\n_cuda_src = r\"\"\"\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <vector>\n\n__global__ void rope_kernel_64(const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ cos,\n const float* __restrict__ sin,\n float* __restrict__ qo,\n float* __restrict__ ko,\n int total_pairs,\n int N) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n if (idx >= total_pairs) return;\n int j = idx & 31;\n int tmp = idx >> 5;\n int n = tmp % N;\n int bh = tmp / N;\n int base = ((bh * N + n) << 6) + j;\n int base2 = base + 32;\n int cs = n * 32 + j;\n float c = cos[cs];\n float s = sin[cs];\n float q1 = q[base];\n float q2 = q[base2];\n qo[base] = q1 * c - q2 * s;\n qo[base2] = q2 * c + q1 * s;\n float k1 = k[base];\n float k2 = k[base2];\n ko[base] = k1 * c - k2 * s;\n ko[base2] = k2 * c + k1 * s;\n}\n\n__global__ void rope_kernel_generic(const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ cos,\n const float* __restrict__ sin,\n float* __restrict__ qo,\n float* __restrict__ ko,\n int total_pairs,\n int N,\n int D,\n int half) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n if (idx >= total_pairs) return;\n int j = idx % half;\n int tmp = idx / half;\n int n = tmp % N;\n int bh = tmp / N;\n int base = (bh * N + n) * D + j;\n int base2 = base + half;\n int cs = n * half + j;\n float c = cos[cs];\n float s = sin[cs];\n float q1 = q[base];\n float q2 = q[base2];\n qo[base] = q1 * c - q2 * s;\n qo[base2] = q2 * c + q1 * s;\n float k1 = k[base];\n float k2 = k[base2];\n ko[base] = k1 * c - k2 * s;\n ko[base2] = k2 * c + k1 * s;\n}\n\nstd::vector<torch::Tensor> rope_forward_cuda(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin) {\n auto qo = torch::empty_like(q);\n auto ko = torch::empty_like(k);\n int B = (int)q.size(0);\n int H = (int)q.size(1);\n int N = (int)q.size(2);\n int D = (int)q.size(3);\n int half = D / 2;\n int total_pairs = B * H * N * half;\n const int threads = 256;\n int blocks = (total_pairs + threads - 1) / threads;\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n if (D == 64) {\n rope_kernel_64<<<blocks, threads, 0, stream>>>(q.data_ptr<float>(), k.data_ptr<float>(), cos.data_ptr<float>(), sin.data_ptr<float>(), qo.data_ptr<float>(), ko.data_ptr<float>(), total_pairs, N);\n } else {\n rope_kernel_generic<<<blocks, threads, 0, stream>>>(q.data_ptr<float>(), k.data_ptr<float>(), cos.data_ptr<float>(), sin.data_ptr<float>(), qo.data_ptr<float>(), ko.data_ptr<float>(), total_pairs, N, D, half);\n }\n return {qo, ko};\n}\n\"\"\"\n\n_rope_ext = load_inline(\n name=\"rope_ext_opt2\",\n cpp_sources=[_cpp_src],\n cuda_sources=[_cuda_src],\n functions=[\"rope_forward\"],\n extra_cflags=[\"-O3\"],\n extra_cuda_cflags=[\"-O3\"],\n verbose=False,\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, dim, max_seq_len=2048, base=10000.0):\n super().__init__()\n inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))\n t = torch.arange(max_seq_len, dtype=inv_freq.dtype)\n freqs = torch.outer(t, inv_freq)\n self.register_buffer(\"cos_cached\", freqs.cos(), persistent=False)\n self.register_buffer(\"sin_cached\", freqs.sin(), persistent=False)\n self.register_buffer(\"inv_freq\", inv_freq, persistent=False)\n self.max_seq_len = max_seq_len\n self.dim = dim\n self.base = base\n\n def forward(self, q: torch.Tensor, k: torch.Tensor) -> tuple:\n N = q.shape[2]\n return tuple(_rope_ext.rope_forward(q, k, self.cos_cached[:N], self.sin_cached[:N]))\n"
}
result ← submit_kernel (ok)
oksubmit_kernel
submit_kernel PASSED: (5 / 5) correctness trials all passed.
Kernel runtime: 0.01 μs
Runtime stats: mean=0.01μs median=?μs std=0.00μs
Numerical precision: max_abs_err=4.77e-07 mean_abs_err=1.93e-08 max_rel_err=3.99e-02
Memory: 41.5 MB peak (ref: 45.63 MB, ratio: 0.9096x)
Kernel launches: 8 (ref: 45, fusion ratio: 5.625)
SOL score: 0.2299
final submitted kernel (130 lines, 4,692 chars) — full source, untruncated
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
_cpp_src = r"""
#include <torch/extension.h>
#include <vector>
std::vector<torch::Tensor> rope_forward_cuda(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin);
std::vector<torch::Tensor> rope_forward(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin) {
return rope_forward_cuda(q, k, cos, sin);
}
"""
_cuda_src = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <vector>
__global__ void rope_kernel_64(const float* __restrict__ q,
const float* __restrict__ k,
const float* __restrict__ cos,
const float* __restrict__ sin,
float* __restrict__ qo,
float* __restrict__ ko,
int total_pairs,
int N) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx >= total_pairs) return;
int j = idx & 31;
int tmp = idx >> 5;
int n = tmp % N;
int bh = tmp / N;
int base = ((bh * N + n) << 6) + j;
int base2 = base + 32;
int cs = n * 32 + j;
float c = cos[cs];
float s = sin[cs];
float q1 = q[base];
float q2 = q[base2];
qo[base] = q1 * c - q2 * s;
qo[base2] = q2 * c + q1 * s;
float k1 = k[base];
float k2 = k[base2];
ko[base] = k1 * c - k2 * s;
ko[base2] = k2 * c + k1 * s;
}
__global__ void rope_kernel_generic(const float* __restrict__ q,
const float* __restrict__ k,
const float* __restrict__ cos,
const float* __restrict__ sin,
float* __restrict__ qo,
float* __restrict__ ko,
int total_pairs,
int N,
int D,
int half) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx >= total_pairs) return;
int j = idx % half;
int tmp = idx / half;
int n = tmp % N;
int bh = tmp / N;
int base = (bh * N + n) * D + j;
int base2 = base + half;
int cs = n * half + j;
float c = cos[cs];
float s = sin[cs];
float q1 = q[base];
float q2 = q[base2];
qo[base] = q1 * c - q2 * s;
qo[base2] = q2 * c + q1 * s;
float k1 = k[base];
float k2 = k[base2];
ko[base] = k1 * c - k2 * s;
ko[base2] = k2 * c + k1 * s;
}
std::vector<torch::Tensor> rope_forward_cuda(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin) {
auto qo = torch::empty_like(q);
auto ko = torch::empty_like(k);
int B = (int)q.size(0);
int H = (int)q.size(1);
int N = (int)q.size(2);
int D = (int)q.size(3);
int half = D / 2;
int total_pairs = B * H * N * half;
const int threads = 256;
int blocks = (total_pairs + threads - 1) / threads;
cudaStream_t stream = at::cuda::getCurrentCUDAStream();
if (D == 64) {
rope_kernel_64<<<blocks, threads, 0, stream>>>(q.data_ptr<float>(), k.data_ptr<float>(), cos.data_ptr<float>(), sin.data_ptr<float>(), qo.data_ptr<float>(), ko.data_ptr<float>(), total_pairs, N);
} else {
rope_kernel_generic<<<blocks, threads, 0, stream>>>(q.data_ptr<float>(), k.data_ptr<float>(), cos.data_ptr<float>(), sin.data_ptr<float>(), qo.data_ptr<float>(), ko.data_ptr<float>(), total_pairs, N, D, half);
}
return {qo, ko};
}
"""
_rope_ext = load_inline(
name="rope_ext_opt2",
cpp_sources=[_cpp_src],
cuda_sources=[_cuda_src],
functions=["rope_forward"],
extra_cflags=["-O3"],
extra_cuda_cflags=["-O3"],
verbose=False,
)
class ModelNew(nn.Module):
def __init__(self, dim, max_seq_len=2048, base=10000.0):
super().__init__()
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
t = torch.arange(max_seq_len, dtype=inv_freq.dtype)
freqs = torch.outer(t, inv_freq)
self.register_buffer("cos_cached", freqs.cos(), persistent=False)
self.register_buffer("sin_cached", freqs.sin(), persistent=False)
self.register_buffer("inv_freq", inv_freq, persistent=False)
self.max_seq_len = max_seq_len
self.dim = dim
self.base = base
def forward(self, q: torch.Tensor, k: torch.Tensor) -> tuple:
N = q.shape[2]
return tuple(_rope_ext.rope_forward(q, k, self.cos_cached[:N], self.sin_cached[:N]))