correct
20_RotaryPositionEmbeddingBio.py
started
2026-05-04T09:55:26Z
timingkernelbench.timing
kernel mean / median / std
0.01 / — / 2.48e-04 μs
ref mean / median / std
0.34 / — / 0.82 μs
numerical precisioneval_kernel_against_ref
gpu memoryextended_metrics.measure_memory
kernel launches / fusiontorch.profiler
fusion ratio (ref / kernel)
22.50x
SOL (speed-of-light)nsight_hardware_counters
roofline / occupancynsight_hardware_counters
dram bandwidth
827.53 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 010.6s turn · 10.6s LLM · 0.0s tools
reasoning
**Evaluating thread accesses**
I’m thinking about how looping over bh inside a thread leads to strided accesses. This means that warp threads will access consecutive i at the same n. It makes me wonder if, during the BH loop, each bh will load contiguous i for half of the process? This seems like it could impact performance or efficiency, so I want to dive a bit deeper into how this works in a practical sense.
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 131.7s turn · 31.7s LLM · 0.0s tools
reasoning
**Optimizing cache management**
I'm considering how to maintain cache effectively. It seems output allocation is taking precedence right now. I wonder if I can extend my approach to accept cosine and sine calculations. If I precompute these functions, I might be able to avoid the combined sine and cosine calculations altogether. That could be great! I think I'll build the cosine and sine functions in the __init__ method using torch operations, referencing max_seq_len and registering buffers.
**Evaluating execution timing**
I’m thinking about whether I could lazily build on q.device just once and store it. However, the timing likely needs to account for the forward pass, and maybe the first iteration could serve as a warmup. I’m noting that correctness should come first. It makes me wonder if the full timing might need multiple calls, as a lazy build during the first forward pass could skew measurements. Still, maybe I shouldn’t include that initial run.
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(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin);\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_pair_kernel(const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ cosv,\n const float* __restrict__ sinv,\n float* __restrict__ qo,\n float* __restrict__ ko,\n int total, int N, int D, int half) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int stride = blockDim.x * gridDim.x;\n for (; idx < total; idx += stride) {\n int i = idx % half;\n int t = idx / half;\n int n = t % N;\n int bh = t / N;\n int base = (bh * N + n) * D + i;\n float c = cosv[n * D + i];\n float s = sinv[n * D + i];\n\n float q1 = q[base];\n float q2 = q[base + half];\n float k1 = k[base];\n float k2 = k[base + half];\n\n qo[base] = q1 * c - q2 * s;\n qo[base + half] = q2 * c + q1 * s;\n ko[base] = k1 * c - k2 * s;\n ko[base + half] = k2 * c + k1 * s;\n }\n}\n\nstd::vector<torch::Tensor> rope_forward(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 >> 1;\n int total = B * H * N * half;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n if (blocks > 4096) blocks = 4096;\n rope_pair_kernel<<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>>(\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, N, D, half);\n return {qo, ko};\n}\n\"\"\"\n\n_rope_ext = load_inline(\n name=\"rope_ext_pair_v1\",\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 emb = torch.cat([freqs, freqs], dim=-1)\n self.register_buffer(\"cos_cached\", emb.cos().contiguous())\n self.register_buffer(\"sin_cached\", emb.sin().contiguous())\n self.max_seq_len = max_seq_len\n self.dim = dim\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 (ok)
okcompile_kernel
compile_kernel PASSED: kernel compiled without errors.
turn 26.7s turn · 6.7s 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(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin);\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_pair_kernel(const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ cosv,\n const float* __restrict__ sinv,\n float* __restrict__ qo,\n float* __restrict__ ko,\n int total, int N, int D, int half) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int stride = blockDim.x * gridDim.x;\n for (; idx < total; idx += stride) {\n int i = idx % half;\n int t = idx / half;\n int n = t % N;\n int bh = t / N;\n int base = (bh * N + n) * D + i;\n float c = cosv[n * D + i];\n float s = sinv[n * D + i];\n\n float q1 = q[base];\n float q2 = q[base + half];\n float k1 = k[base];\n float k2 = k[base + half];\n\n qo[base] = q1 * c - q2 * s;\n qo[base + half] = q2 * c + q1 * s;\n ko[base] = k1 * c - k2 * s;\n ko[base + half] = k2 * c + k1 * s;\n }\n}\n\nstd::vector<torch::Tensor> rope_forward(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 >> 1;\n int total = B * H * N * half;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n if (blocks > 4096) blocks = 4096;\n rope_pair_kernel<<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>>(\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, N, D, half);\n return {qo, ko};\n}\n\"\"\"\n\n_rope_ext = load_inline(\n name=\"rope_ext_pair_v1\",\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 emb = torch.cat([freqs, freqs], dim=-1)\n self.register_buffer(\"cos_cached\", emb.cos().contiguous())\n self.register_buffer(\"sin_cached\", emb.sin().contiguous())\n self.max_seq_len = max_seq_len\n self.dim = dim\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 ← 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 3 · 1 tool call(s) · 10.4s turn · 10.4s LLM · 6,145 chars (click to expand)
turn 310.4s turn · 10.4s LLM · 0.0s tools
reasoning
**Optimizing performance**
I’m thinking about the need for performance and how I might submit something while still optimizing it. Profiling could be a useful step here to understand where the bottlenecks are or what needs improvement. I guess it’s about balancing speed and efficiency while ensuring everything works smoothly. So, I’ll consider ways to enhance performance before taking any action on submission. It's all about making sure it’s as effective as possible!
call → profile_kernel
callprofile_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(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin);\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_pair_kernel(const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ cosv,\n const float* __restrict__ sinv,\n float* __restrict__ qo,\n float* __restrict__ ko,\n int total, int N, int D, int half) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int stride = blockDim.x * gridDim.x;\n for (; idx < total; idx += stride) {\n int i = idx % half;\n int t = idx / half;\n int n = t % N;\n int bh = t / N;\n int base = (bh * N + n) * D + i;\n float c = cosv[n * D + i];\n float s = sinv[n * D + i];\n\n float q1 = q[base];\n float q2 = q[base + half];\n float k1 = k[base];\n float k2 = k[base + half];\n\n qo[base] = q1 * c - q2 * s;\n qo[base + half] = q2 * c + q1 * s;\n ko[base] = k1 * c - k2 * s;\n ko[base + half] = k2 * c + k1 * s;\n }\n}\n\nstd::vector<torch::Tensor> rope_forward(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 >> 1;\n int total = B * H * N * half;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n if (blocks > 4096) blocks = 4096;\n rope_pair_kernel<<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>>(\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, N, D, half);\n return {qo, ko};\n}\n\"\"\"\n\n_rope_ext = load_inline(\n name=\"rope_ext_pair_v1\",\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 emb = torch.cat([freqs, freqs], dim=-1)\n self.register_buffer(\"cos_cached\", emb.cos().contiguous())\n self.register_buffer(\"sin_cached\", emb.sin().contiguous())\n self.max_seq_len = max_seq_len\n self.dim = dim\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 ← profile_kernel (ok)
okprofile_kernel
profile_kernel PASSED: profiling complete.
=== Kernel Profile Summary ===
--- Kernel Breakdown (by GPU time) ---
#1: aten::slice 78.0μs (43%) calls=1
#2: aten::empty_like 35.0μs (19%) calls=1
#3: aten::empty_strided 22.0μs (12%) calls=1
#4: aten::slice 13.0μs (7%) calls=1
#5: aten::empty_like 13.0μs (7%) calls=1
... +3 more kernels
--- Timing ---
GPU time: 5.63 μs
--- Memory Bandwidth ---
DRAM BW: 757.6/3350 GB/s (22.6%)
read=757.6 write=0.0 GB/s
Hit rates: L2=59.1%
--- Compute Throughput ---
Dominant pipe: FP32 util=12.6%
Pipe util: FMA=12.6%, Tensor=0.5%
--- Roofline Analysis ---
Ridge point (FP32): 20.00 FLOPs/byte
Classification: MEMORY-BOUND
--- Occupancy ---
Achieved: 70.7%
Eligible warps/cycle: 1.63
Launch: regs/thread=32, smem/blk=1024B, block=256, grid=1024
--- Memory Access Quality ---
Global ld coalescing: 4.00 sectors/req (4.0x wasted BW)
--- Warp Stall Reasons (% of issue cycles) ---
long_scoreboard 1282.3% ####################
mio_throttle 506.3% ####################
short_scoreboard 237.5% ####################
--- Optimization Hints ---
-> 1282% stalls: global memory latency (waiting for DRAM/L2). + sectors/req=4.0 -> uncoalesced global loads, restructure access pattern or use __ldg Try shared-memory tiling, prefetching, or reducing working set.
-> Global load coalescing=4.0x (ideal=1.0) -> 4x wasted DRAM BW. Make per-warp accesses contiguous.
turn 420.4s turn · 20.4s LLM · 0.0s tools
reasoning
**Evaluating warp arrangements**
I'm coalescing my thoughts about warp arrangements, specifically focusing on optimizing the speed for 32 threads. It seems efficient to set y=0 and range x from 0 to 31, which is promising. The current linear setup also allows for achieving similar benefits by warping within half for the same n/bh. I wonder if avoiding division might contribute to improved speed, so that’s worth considering in my optimization efforts!
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>\nstd::vector<torch::Tensor> rope_forward(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin);\n\"\"\"\n\n_cuda_src = r\"\"\"\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda_runtime.h>\n#include <vector>\n\n__global__ void rope64_kernel(const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ cosv,\n const float* __restrict__ sinv,\n float* __restrict__ qo,\n float* __restrict__ ko,\n int BH, int N) {\n int i = threadIdx.x; // 0..31\n int yy = threadIdx.y; // BH within tile\n int n = blockIdx.x;\n int bh = blockIdx.y * blockDim.y + yy;\n if (bh < BH) {\n int base = (bh * N + n) * 64 + i;\n float c = cosv[n * 64 + i];\n float s = sinv[n * 64 + i];\n float q1 = q[base];\n float q2 = q[base + 32];\n float k1 = k[base];\n float k2 = k[base + 32];\n qo[base] = q1 * c - q2 * s;\n qo[base + 32] = q2 * c + q1 * s;\n ko[base] = k1 * c - k2 * s;\n ko[base + 32] = k2 * c + k1 * s;\n }\n}\n\n__global__ void rope_pair_kernel(const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ cosv,\n const float* __restrict__ sinv,\n float* __restrict__ qo,\n float* __restrict__ ko,\n int total, int N, int D, int half) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int stride = blockDim.x * gridDim.x;\n for (; idx < total; idx += stride) {\n int i = idx % half;\n int t = idx / half;\n int n = t % N;\n int bh = t / N;\n int base = (bh * N + n) * D + i;\n float c = cosv[n * D + i];\n float s = sinv[n * D + i];\n float q1 = q[base], q2 = q[base + half];\n float k1 = k[base], k2 = k[base + half];\n qo[base] = q1 * c - q2 * s;\n qo[base + half] = q2 * c + q1 * s;\n ko[base] = k1 * c - k2 * s;\n ko[base + half] = k2 * c + k1 * s;\n }\n}\n\nstd::vector<torch::Tensor> rope_forward(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), H = (int)q.size(1), N = (int)q.size(2), D = (int)q.size(3);\n int BH = B * H;\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n if (D == 64) {\n dim3 block(32, 8, 1);\n dim3 grid(N, (BH + 7) / 8, 1);\n rope64_kernel<<<grid, block, 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>(), BH, N);\n } else {\n int half = D >> 1;\n int total = BH * N * half;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n if (blocks > 4096) blocks = 4096;\n rope_pair_kernel<<<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, N, D, half);\n }\n return {qo, ko};\n}\n\"\"\"\n\n_rope_ext = load_inline(name=\"rope_ext_pair_v2\", cpp_sources=_cpp_src, cuda_sources=_cuda_src, functions=[\"rope_forward\"], extra_cflags=[\"-O3\"], extra_cuda_cflags=[\"-O3\"], verbose=False)\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 emb = torch.cat([freqs, freqs], dim=-1)\n self.register_buffer(\"cos_cached\", emb.cos().contiguous())\n self.register_buffer(\"sin_cached\", emb.sin().contiguous())\n self.max_seq_len = max_seq_len\n self.dim = dim\n def forward(self, q: torch.Tensor, k: torch.Tensor) -> tuple:\n return tuple(_rope_ext.rope_forward(q, k, self.cos_cached, self.sin_cached))\n"
}
result ← compile_kernel (ok)
okcompile_kernel
compile_kernel PASSED: kernel compiled without errors.
turn 58.3s turn · 8.3s 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>\nstd::vector<torch::Tensor> rope_forward(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin);\n\"\"\"\n\n_cuda_src = r\"\"\"\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda_runtime.h>\n#include <vector>\n\n__global__ void rope64_kernel(const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ cosv,\n const float* __restrict__ sinv,\n float* __restrict__ qo,\n float* __restrict__ ko,\n int BH, int N) {\n int i = threadIdx.x; // 0..31\n int yy = threadIdx.y; // BH within tile\n int n = blockIdx.x;\n int bh = blockIdx.y * blockDim.y + yy;\n if (bh < BH) {\n int base = (bh * N + n) * 64 + i;\n float c = cosv[n * 64 + i];\n float s = sinv[n * 64 + i];\n float q1 = q[base];\n float q2 = q[base + 32];\n float k1 = k[base];\n float k2 = k[base + 32];\n qo[base] = q1 * c - q2 * s;\n qo[base + 32] = q2 * c + q1 * s;\n ko[base] = k1 * c - k2 * s;\n ko[base + 32] = k2 * c + k1 * s;\n }\n}\n\n__global__ void rope_pair_kernel(const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ cosv,\n const float* __restrict__ sinv,\n float* __restrict__ qo,\n float* __restrict__ ko,\n int total, int N, int D, int half) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int stride = blockDim.x * gridDim.x;\n for (; idx < total; idx += stride) {\n int i = idx % half;\n int t = idx / half;\n int n = t % N;\n int bh = t / N;\n int base = (bh * N + n) * D + i;\n float c = cosv[n * D + i];\n float s = sinv[n * D + i];\n float q1 = q[base], q2 = q[base + half];\n float k1 = k[base], k2 = k[base + half];\n qo[base] = q1 * c - q2 * s;\n qo[base + half] = q2 * c + q1 * s;\n ko[base] = k1 * c - k2 * s;\n ko[base + half] = k2 * c + k1 * s;\n }\n}\n\nstd::vector<torch::Tensor> rope_forward(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), H = (int)q.size(1), N = (int)q.size(2), D = (int)q.size(3);\n int BH = B * H;\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n if (D == 64) {\n dim3 block(32, 8, 1);\n dim3 grid(N, (BH + 7) / 8, 1);\n rope64_kernel<<<grid, block, 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>(), BH, N);\n } else {\n int half = D >> 1;\n int total = BH * N * half;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n if (blocks > 4096) blocks = 4096;\n rope_pair_kernel<<<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, N, D, half);\n }\n return {qo, ko};\n}\n\"\"\"\n\n_rope_ext = load_inline(name=\"rope_ext_pair_v2\", cpp_sources=_cpp_src, cuda_sources=_cuda_src, functions=[\"rope_forward\"], extra_cflags=[\"-O3\"], extra_cuda_cflags=[\"-O3\"], verbose=False)\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 emb = torch.cat([freqs, freqs], dim=-1)\n self.register_buffer(\"cos_cached\", emb.cos().contiguous())\n self.register_buffer(\"sin_cached\", emb.sin().contiguous())\n self.max_seq_len = max_seq_len\n self.dim = dim\n def forward(self, q: torch.Tensor, k: torch.Tensor) -> tuple:\n return tuple(_rope_ext.rope_forward(q, k, self.cos_cached, self.sin_cached))\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 6 · 1 tool call(s) · 9.9s turn · 9.9s LLM · 7,311 chars (click to expand)
turn 69.9s turn · 9.9s LLM · 0.0s tools
call → profile_kernel
callprofile_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>\nstd::vector<torch::Tensor> rope_forward(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin);\n\"\"\"\n\n_cuda_src = r\"\"\"\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda_runtime.h>\n#include <vector>\n\n__global__ void rope64_kernel(const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ cosv,\n const float* __restrict__ sinv,\n float* __restrict__ qo,\n float* __restrict__ ko,\n int BH, int N) {\n int i = threadIdx.x; // 0..31\n int yy = threadIdx.y; // BH within tile\n int n = blockIdx.x;\n int bh = blockIdx.y * blockDim.y + yy;\n if (bh < BH) {\n int base = (bh * N + n) * 64 + i;\n float c = cosv[n * 64 + i];\n float s = sinv[n * 64 + i];\n float q1 = q[base];\n float q2 = q[base + 32];\n float k1 = k[base];\n float k2 = k[base + 32];\n qo[base] = q1 * c - q2 * s;\n qo[base + 32] = q2 * c + q1 * s;\n ko[base] = k1 * c - k2 * s;\n ko[base + 32] = k2 * c + k1 * s;\n }\n}\n\n__global__ void rope_pair_kernel(const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ cosv,\n const float* __restrict__ sinv,\n float* __restrict__ qo,\n float* __restrict__ ko,\n int total, int N, int D, int half) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int stride = blockDim.x * gridDim.x;\n for (; idx < total; idx += stride) {\n int i = idx % half;\n int t = idx / half;\n int n = t % N;\n int bh = t / N;\n int base = (bh * N + n) * D + i;\n float c = cosv[n * D + i];\n float s = sinv[n * D + i];\n float q1 = q[base], q2 = q[base + half];\n float k1 = k[base], k2 = k[base + half];\n qo[base] = q1 * c - q2 * s;\n qo[base + half] = q2 * c + q1 * s;\n ko[base] = k1 * c - k2 * s;\n ko[base + half] = k2 * c + k1 * s;\n }\n}\n\nstd::vector<torch::Tensor> rope_forward(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), H = (int)q.size(1), N = (int)q.size(2), D = (int)q.size(3);\n int BH = B * H;\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n if (D == 64) {\n dim3 block(32, 8, 1);\n dim3 grid(N, (BH + 7) / 8, 1);\n rope64_kernel<<<grid, block, 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>(), BH, N);\n } else {\n int half = D >> 1;\n int total = BH * N * half;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n if (blocks > 4096) blocks = 4096;\n rope_pair_kernel<<<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, N, D, half);\n }\n return {qo, ko};\n}\n\"\"\"\n\n_rope_ext = load_inline(name=\"rope_ext_pair_v2\", cpp_sources=_cpp_src, cuda_sources=_cuda_src, functions=[\"rope_forward\"], extra_cflags=[\"-O3\"], extra_cuda_cflags=[\"-O3\"], verbose=False)\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 emb = torch.cat([freqs, freqs], dim=-1)\n self.register_buffer(\"cos_cached\", emb.cos().contiguous())\n self.register_buffer(\"sin_cached\", emb.sin().contiguous())\n self.max_seq_len = max_seq_len\n self.dim = dim\n def forward(self, q: torch.Tensor, k: torch.Tensor) -> tuple:\n return tuple(_rope_ext.rope_forward(q, k, self.cos_cached, self.sin_cached))\n"
}
result ← profile_kernel (ok)
okprofile_kernel
profile_kernel PASSED: profiling complete.
=== Kernel Profile Summary ===
--- Kernel Breakdown (by GPU time) ---
#1: aten::empty_like 68.0μs (55%) calls=1
#2: aten::empty_strided 38.0μs (31%) calls=1
#3: aten::empty_like 13.0μs (10%) calls=1
#4: aten::empty_strided 5.0μs (4%) calls=1
--- Timing ---
GPU time: 5.44 μs [↓0.2μs ok]
--- Memory Bandwidth ---
DRAM BW: 783.7/3350 GB/s (23.4%) [↑0.8% ok]
read=783.7 write=0.0 GB/s
Hit rates: L2=55.9%
--- Compute Throughput ---
Dominant pipe: FP32 util=5.6% [↓7.0% REGRESSED]
Pipe util: FMA=5.6%, Tensor=0.0%
--- Roofline Analysis ---
Ridge point (FP32): 20.00 FLOPs/byte
Classification: MEMORY-BOUND
--- Occupancy ---
Achieved: 66.1% [↓4.6% REGRESSED]
Eligible warps/cycle: 0.45
WARNING: <1 eligible warp/cycle = latency-bound, needs more parallelism
Launch: regs/thread=24, smem/blk=1024B, block=256, grid=1024
--- Memory Access Quality ---
Global ld coalescing: 4.00 sectors/req (4.0x wasted BW)
--- Warp Stall Reasons (% of issue cycles) ---
long_scoreboard 4392.8% ####################
mio_throttle 1033.0% ####################
short_scoreboard 204.9% ####################
--- Optimization Hints ---
-> 4393% stalls: global memory latency (waiting for DRAM/L2). + sectors/req=4.0 -> uncoalesced global loads, restructure access pattern or use __ldg Try shared-memory tiling, prefetching, or reducing working set.
-> Global load coalescing=4.0x (ideal=1.0) -> 4x wasted DRAM BW. Make per-warp accesses contiguous.
-> Low eligible warps + low BW% + low compute% = LATENCY-BOUND. Need more parallelism (larger grid, more ILP, prefetching).
--- Delta vs Previous Iteration ---
GPU time: 5.63→5.44μs (↓0.19) ok
DRAM BW%: 22.62→23.39% (↑0.78) ok
Compute%: 12.62→5.63% (↓6.99) REGRESSED
Occupancy: 70.69→66.13% (↓4.56) REGRESSED
Eligible warps/cyc: 1.63→0.45 (↓1.18) REGRESSED
L2 hit%: 59.12→55.93% (↓3.19) REGRESSED
turn 716.3s turn · 16.3s 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>\nstd::vector<torch::Tensor> rope_forward(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin);\n\"\"\"\n\n_cuda_src = r\"\"\"\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda_runtime.h>\n#include <vector>\n\n__global__ void rope64_kernel(const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ cosv,\n const float* __restrict__ sinv,\n float* __restrict__ qo,\n float* __restrict__ ko,\n int BH, int N) {\n int i = threadIdx.x;\n int bh = blockIdx.y * blockDim.y + threadIdx.y;\n int n = blockIdx.x;\n if (bh < BH) {\n int base = (bh * N + n) * 64 + i;\n float c = cosv[n * 64 + i];\n float s = sinv[n * 64 + i];\n float q1 = q[base], q2 = q[base + 32];\n float k1 = k[base], k2 = k[base + 32];\n qo[base] = q1 * c - q2 * s;\n qo[base + 32] = q2 * c + q1 * s;\n ko[base] = k1 * c - k2 * s;\n ko[base + 32] = k2 * c + k1 * s;\n }\n}\n\n__global__ void rope_pair_kernel(const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ cosv,\n const float* __restrict__ sinv,\n float* __restrict__ qo,\n float* __restrict__ ko,\n int total, int N, int D, int half) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int stride = blockDim.x * gridDim.x;\n for (; idx < total; idx += stride) {\n int i = idx % half;\n int t = idx / half;\n int n = t % N;\n int bh = t / N;\n int base = (bh * N + n) * D + i;\n float c = cosv[n * D + i];\n float s = sinv[n * D + i];\n float q1 = q[base], q2 = q[base + half];\n float k1 = k[base], k2 = k[base + half];\n qo[base] = q1 * c - q2 * s;\n qo[base + half] = q2 * c + q1 * s;\n ko[base] = k1 * c - k2 * s;\n ko[base + half] = k2 * c + k1 * s;\n }\n}\n\nstd::vector<torch::Tensor> rope_forward(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin) {\n int64_t B64 = q.size(0), H64 = q.size(1), N64 = q.size(2), D64 = q.size(3);\n auto out = torch::empty({2, B64, H64, N64, D64}, q.options());\n auto qo = out.select(0, 0);\n auto ko = out.select(0, 1);\n int B = (int)B64, H = (int)H64, N = (int)N64, D = (int)D64;\n int BH = B * H;\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n if (D == 64) {\n dim3 block(32, 8, 1);\n dim3 grid(N, (BH + 7) / 8, 1);\n rope64_kernel<<<grid, block, 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>(), BH, N);\n } else {\n int half = D >> 1;\n int total = BH * N * half;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n if (blocks > 4096) blocks = 4096;\n rope_pair_kernel<<<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, N, D, half);\n }\n return {qo, ko};\n}\n\"\"\"\n\n_rope_ext = load_inline(name=\"rope_ext_pair_v3\", cpp_sources=_cpp_src, cuda_sources=_cuda_src, functions=[\"rope_forward\"], extra_cflags=[\"-O3\"], extra_cuda_cflags=[\"-O3\"], verbose=False)\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 emb = torch.cat([freqs, freqs], dim=-1)\n self.register_buffer(\"cos_cached\", emb.cos().contiguous())\n self.register_buffer(\"sin_cached\", emb.sin().contiguous())\n self.max_seq_len = max_seq_len\n self.dim = dim\n def forward(self, q: torch.Tensor, k: torch.Tensor) -> tuple:\n return tuple(_rope_ext.rope_forward(q, k, self.cos_cached, self.sin_cached))\n"
}
result ← compile_kernel (ok)
okcompile_kernel
compile_kernel PASSED: kernel compiled without errors.
turn 89.9s turn · 9.9s 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>\nstd::vector<torch::Tensor> rope_forward(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin);\n\"\"\"\n\n_cuda_src = r\"\"\"\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda_runtime.h>\n#include <vector>\n\n__global__ void rope64_kernel(const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ cosv,\n const float* __restrict__ sinv,\n float* __restrict__ qo,\n float* __restrict__ ko,\n int BH, int N) {\n int i = threadIdx.x;\n int bh = blockIdx.y * blockDim.y + threadIdx.y;\n int n = blockIdx.x;\n if (bh < BH) {\n int base = (bh * N + n) * 64 + i;\n float c = cosv[n * 64 + i];\n float s = sinv[n * 64 + i];\n float q1 = q[base], q2 = q[base + 32];\n float k1 = k[base], k2 = k[base + 32];\n qo[base] = q1 * c - q2 * s;\n qo[base + 32] = q2 * c + q1 * s;\n ko[base] = k1 * c - k2 * s;\n ko[base + 32] = k2 * c + k1 * s;\n }\n}\n\n__global__ void rope_pair_kernel(const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ cosv,\n const float* __restrict__ sinv,\n float* __restrict__ qo,\n float* __restrict__ ko,\n int total, int N, int D, int half) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int stride = blockDim.x * gridDim.x;\n for (; idx < total; idx += stride) {\n int i = idx % half;\n int t = idx / half;\n int n = t % N;\n int bh = t / N;\n int base = (bh * N + n) * D + i;\n float c = cosv[n * D + i];\n float s = sinv[n * D + i];\n float q1 = q[base], q2 = q[base + half];\n float k1 = k[base], k2 = k[base + half];\n qo[base] = q1 * c - q2 * s;\n qo[base + half] = q2 * c + q1 * s;\n ko[base] = k1 * c - k2 * s;\n ko[base + half] = k2 * c + k1 * s;\n }\n}\n\nstd::vector<torch::Tensor> rope_forward(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin) {\n int64_t B64 = q.size(0), H64 = q.size(1), N64 = q.size(2), D64 = q.size(3);\n auto out = torch::empty({2, B64, H64, N64, D64}, q.options());\n auto qo = out.select(0, 0);\n auto ko = out.select(0, 1);\n int B = (int)B64, H = (int)H64, N = (int)N64, D = (int)D64;\n int BH = B * H;\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n if (D == 64) {\n dim3 block(32, 8, 1);\n dim3 grid(N, (BH + 7) / 8, 1);\n rope64_kernel<<<grid, block, 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>(), BH, N);\n } else {\n int half = D >> 1;\n int total = BH * N * half;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n if (blocks > 4096) blocks = 4096;\n rope_pair_kernel<<<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, N, D, half);\n }\n return {qo, ko};\n}\n\"\"\"\n\n_rope_ext = load_inline(name=\"rope_ext_pair_v3\", cpp_sources=_cpp_src, cuda_sources=_cuda_src, functions=[\"rope_forward\"], extra_cflags=[\"-O3\"], extra_cuda_cflags=[\"-O3\"], verbose=False)\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 emb = torch.cat([freqs, freqs], dim=-1)\n self.register_buffer(\"cos_cached\", emb.cos().contiguous())\n self.register_buffer(\"sin_cached\", emb.sin().contiguous())\n self.max_seq_len = max_seq_len\n self.dim = dim\n def forward(self, q: torch.Tensor, k: torch.Tensor) -> tuple:\n return tuple(_rope_ext.rope_forward(q, k, self.cos_cached, self.sin_cached))\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 9 · 1 tool call(s) · 11.8s turn · 11.8s LLM · 7,252 chars (click to expand)
turn 911.8s turn · 11.8s LLM · 0.0s tools
call → profile_kernel
callprofile_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>\nstd::vector<torch::Tensor> rope_forward(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin);\n\"\"\"\n\n_cuda_src = r\"\"\"\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda_runtime.h>\n#include <vector>\n\n__global__ void rope64_kernel(const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ cosv,\n const float* __restrict__ sinv,\n float* __restrict__ qo,\n float* __restrict__ ko,\n int BH, int N) {\n int i = threadIdx.x;\n int bh = blockIdx.y * blockDim.y + threadIdx.y;\n int n = blockIdx.x;\n if (bh < BH) {\n int base = (bh * N + n) * 64 + i;\n float c = cosv[n * 64 + i];\n float s = sinv[n * 64 + i];\n float q1 = q[base], q2 = q[base + 32];\n float k1 = k[base], k2 = k[base + 32];\n qo[base] = q1 * c - q2 * s;\n qo[base + 32] = q2 * c + q1 * s;\n ko[base] = k1 * c - k2 * s;\n ko[base + 32] = k2 * c + k1 * s;\n }\n}\n\n__global__ void rope_pair_kernel(const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ cosv,\n const float* __restrict__ sinv,\n float* __restrict__ qo,\n float* __restrict__ ko,\n int total, int N, int D, int half) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int stride = blockDim.x * gridDim.x;\n for (; idx < total; idx += stride) {\n int i = idx % half;\n int t = idx / half;\n int n = t % N;\n int bh = t / N;\n int base = (bh * N + n) * D + i;\n float c = cosv[n * D + i];\n float s = sinv[n * D + i];\n float q1 = q[base], q2 = q[base + half];\n float k1 = k[base], k2 = k[base + half];\n qo[base] = q1 * c - q2 * s;\n qo[base + half] = q2 * c + q1 * s;\n ko[base] = k1 * c - k2 * s;\n ko[base + half] = k2 * c + k1 * s;\n }\n}\n\nstd::vector<torch::Tensor> rope_forward(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin) {\n int64_t B64 = q.size(0), H64 = q.size(1), N64 = q.size(2), D64 = q.size(3);\n auto out = torch::empty({2, B64, H64, N64, D64}, q.options());\n auto qo = out.select(0, 0);\n auto ko = out.select(0, 1);\n int B = (int)B64, H = (int)H64, N = (int)N64, D = (int)D64;\n int BH = B * H;\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n if (D == 64) {\n dim3 block(32, 8, 1);\n dim3 grid(N, (BH + 7) / 8, 1);\n rope64_kernel<<<grid, block, 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>(), BH, N);\n } else {\n int half = D >> 1;\n int total = BH * N * half;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n if (blocks > 4096) blocks = 4096;\n rope_pair_kernel<<<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, N, D, half);\n }\n return {qo, ko};\n}\n\"\"\"\n\n_rope_ext = load_inline(name=\"rope_ext_pair_v3\", cpp_sources=_cpp_src, cuda_sources=_cuda_src, functions=[\"rope_forward\"], extra_cflags=[\"-O3\"], extra_cuda_cflags=[\"-O3\"], verbose=False)\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 emb = torch.cat([freqs, freqs], dim=-1)\n self.register_buffer(\"cos_cached\", emb.cos().contiguous())\n self.register_buffer(\"sin_cached\", emb.sin().contiguous())\n self.max_seq_len = max_seq_len\n self.dim = dim\n def forward(self, q: torch.Tensor, k: torch.Tensor) -> tuple:\n return tuple(_rope_ext.rope_forward(q, k, self.cos_cached, self.sin_cached))\n"
}
result ← profile_kernel (ok)
okprofile_kernel
profile_kernel PASSED: profiling complete.
=== Kernel Profile Summary ===
--- Kernel Breakdown (by GPU time) ---
#1: aten::select 41.0μs (45%) calls=1
#2: aten::empty 31.0μs (34%) calls=1
#3: aten::select 10.0μs (11%) calls=1
#4: aten::as_strided 7.0μs (8%) calls=1
#5: aten::as_strided 3.0μs (3%) calls=1
--- Timing ---
GPU time: 5.44 μs
--- Memory Bandwidth ---
DRAM BW: 783.6/3350 GB/s (23.4%)
read=783.6 write=0.0 GB/s
Hit rates: L2=55.8%
--- Compute Throughput ---
Dominant pipe: FP32 util=5.6% [↓0.1% REGRESSED]
Pipe util: FMA=5.6%, Tensor=0.0%
--- Roofline Analysis ---
Ridge point (FP32): 20.00 FLOPs/byte
Classification: MEMORY-BOUND
--- Occupancy ---
Achieved: 69.6% [↑3.4% ok]
Eligible warps/cycle: 0.41
WARNING: <1 eligible warp/cycle = latency-bound, needs more parallelism
Launch: regs/thread=24, smem/blk=1024B, block=256, grid=1024
--- Memory Access Quality ---
Global ld coalescing: 4.00 sectors/req (4.0x wasted BW)
--- Warp Stall Reasons (% of issue cycles) ---
long_scoreboard 4769.1% ####################
mio_throttle 1031.3% ####################
short_scoreboard 203.7% ####################
--- Optimization Hints ---
-> 4769% stalls: global memory latency (waiting for DRAM/L2). + sectors/req=4.0 -> uncoalesced global loads, restructure access pattern or use __ldg Try shared-memory tiling, prefetching, or reducing working set.
-> Global load coalescing=4.0x (ideal=1.0) -> 4x wasted DRAM BW. Make per-warp accesses contiguous.
-> Low eligible warps + low BW% + low compute% = LATENCY-BOUND. Need more parallelism (larger grid, more ILP, prefetching).
--- Delta vs Previous Iteration ---
Compute%: 5.63→5.55% (↓0.08) REGRESSED
Occupancy: 66.13→69.57% (↑3.45) ok
Eligible warps/cyc: 0.45→0.41 (↓0.03) REGRESSED
L2 hit%: 55.93→55.83% (↓0.10) REGRESSED
turn 1021.3s turn · 21.3s 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 <tuple>\nstd::tuple<torch::Tensor, torch::Tensor> rope_forward(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin);\n\"\"\"\n\n_cuda_src = r\"\"\"\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda_runtime.h>\n#include <tuple>\n\n__global__ void rope64_kernel(const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ cosv,\n const float* __restrict__ sinv,\n float* __restrict__ qo,\n float* __restrict__ ko,\n int BH, int N) {\n int i = threadIdx.x;\n int bh = blockIdx.y * 8 + threadIdx.y;\n int n = blockIdx.x;\n if (bh < BH) {\n int base = (bh * N + n) * 64 + i;\n float c = cosv[n * 64 + i];\n float s = sinv[n * 64 + i];\n float q1 = q[base], q2 = q[base + 32];\n float k1 = k[base], k2 = k[base + 32];\n qo[base] = q1 * c - q2 * s;\n qo[base + 32] = q2 * c + q1 * s;\n ko[base] = k1 * c - k2 * s;\n ko[base + 32] = k2 * c + k1 * s;\n }\n}\n\n__global__ void rope_pair_kernel(const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ cosv,\n const float* __restrict__ sinv,\n float* __restrict__ qo,\n float* __restrict__ ko,\n int total, int N, int D, int half) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int stride = blockDim.x * gridDim.x;\n for (; idx < total; idx += stride) {\n int i = idx % half;\n int t = idx / half;\n int n = t % N;\n int bh = t / N;\n int base = (bh * N + n) * D + i;\n float c = cosv[n * D + i];\n float s = sinv[n * D + i];\n float q1 = q[base], q2 = q[base + half];\n float k1 = k[base], k2 = k[base + half];\n qo[base] = q1 * c - q2 * s;\n qo[base + half] = q2 * c + q1 * s;\n ko[base] = k1 * c - k2 * s;\n ko[base + half] = k2 * c + k1 * s;\n }\n}\n\nstd::tuple<torch::Tensor, torch::Tensor> rope_forward(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin) {\n int64_t B64 = q.size(0), H64 = q.size(1), N64 = q.size(2), D64 = q.size(3);\n auto qo = torch::empty({B64, H64, N64, D64}, q.options());\n auto ko = torch::empty({B64, H64, N64, D64}, q.options());\n int B = (int)B64, H = (int)H64, N = (int)N64, D = (int)D64;\n int BH = B * H;\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n if (D == 64) {\n dim3 block(32, 8, 1);\n dim3 grid(N, (BH + 7) / 8, 1);\n rope64_kernel<<<grid, block, 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>(), BH, N);\n } else {\n int half = D >> 1;\n int total = BH * N * half;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n if (blocks > 4096) blocks = 4096;\n rope_pair_kernel<<<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, N, D, half);\n }\n return std::make_tuple(qo, ko);\n}\n\"\"\"\n\n_rope_ext = load_inline(name=\"rope_ext_pair_v4\", cpp_sources=_cpp_src, cuda_sources=_cuda_src, functions=[\"rope_forward\"], extra_cflags=[\"-O3\"], extra_cuda_cflags=[\"-O3\"], verbose=False)\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 emb = torch.cat([freqs, freqs], dim=-1)\n self.register_buffer(\"cos_cached\", emb.cos().contiguous())\n self.register_buffer(\"sin_cached\", emb.sin().contiguous())\n self.max_seq_len = max_seq_len\n self.dim = dim\n def forward(self, q: torch.Tensor, k: torch.Tensor) -> tuple:\n return _rope_ext.rope_forward(q, k, self.cos_cached, self.sin_cached)\n"
}
result ← compile_kernel (ok)
okcompile_kernel
compile_kernel PASSED: kernel compiled without errors.
turn 1110.4s turn · 10.4s 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 <tuple>\nstd::tuple<torch::Tensor, torch::Tensor> rope_forward(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin);\n\"\"\"\n\n_cuda_src = r\"\"\"\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda_runtime.h>\n#include <tuple>\n\n__global__ void rope64_kernel(const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ cosv,\n const float* __restrict__ sinv,\n float* __restrict__ qo,\n float* __restrict__ ko,\n int BH, int N) {\n int i = threadIdx.x;\n int bh = blockIdx.y * 8 + threadIdx.y;\n int n = blockIdx.x;\n if (bh < BH) {\n int base = (bh * N + n) * 64 + i;\n float c = cosv[n * 64 + i];\n float s = sinv[n * 64 + i];\n float q1 = q[base], q2 = q[base + 32];\n float k1 = k[base], k2 = k[base + 32];\n qo[base] = q1 * c - q2 * s;\n qo[base + 32] = q2 * c + q1 * s;\n ko[base] = k1 * c - k2 * s;\n ko[base + 32] = k2 * c + k1 * s;\n }\n}\n\n__global__ void rope_pair_kernel(const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ cosv,\n const float* __restrict__ sinv,\n float* __restrict__ qo,\n float* __restrict__ ko,\n int total, int N, int D, int half) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int stride = blockDim.x * gridDim.x;\n for (; idx < total; idx += stride) {\n int i = idx % half;\n int t = idx / half;\n int n = t % N;\n int bh = t / N;\n int base = (bh * N + n) * D + i;\n float c = cosv[n * D + i];\n float s = sinv[n * D + i];\n float q1 = q[base], q2 = q[base + half];\n float k1 = k[base], k2 = k[base + half];\n qo[base] = q1 * c - q2 * s;\n qo[base + half] = q2 * c + q1 * s;\n ko[base] = k1 * c - k2 * s;\n ko[base + half] = k2 * c + k1 * s;\n }\n}\n\nstd::tuple<torch::Tensor, torch::Tensor> rope_forward(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin) {\n int64_t B64 = q.size(0), H64 = q.size(1), N64 = q.size(2), D64 = q.size(3);\n auto qo = torch::empty({B64, H64, N64, D64}, q.options());\n auto ko = torch::empty({B64, H64, N64, D64}, q.options());\n int B = (int)B64, H = (int)H64, N = (int)N64, D = (int)D64;\n int BH = B * H;\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n if (D == 64) {\n dim3 block(32, 8, 1);\n dim3 grid(N, (BH + 7) / 8, 1);\n rope64_kernel<<<grid, block, 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>(), BH, N);\n } else {\n int half = D >> 1;\n int total = BH * N * half;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n if (blocks > 4096) blocks = 4096;\n rope_pair_kernel<<<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, N, D, half);\n }\n return std::make_tuple(qo, ko);\n}\n\"\"\"\n\n_rope_ext = load_inline(name=\"rope_ext_pair_v4\", cpp_sources=_cpp_src, cuda_sources=_cuda_src, functions=[\"rope_forward\"], extra_cflags=[\"-O3\"], extra_cuda_cflags=[\"-O3\"], verbose=False)\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 emb = torch.cat([freqs, freqs], dim=-1)\n self.register_buffer(\"cos_cached\", emb.cos().contiguous())\n self.register_buffer(\"sin_cached\", emb.sin().contiguous())\n self.max_seq_len = max_seq_len\n self.dim = dim\n def forward(self, q: torch.Tensor, k: torch.Tensor) -> tuple:\n return _rope_ext.rope_forward(q, k, self.cos_cached, self.sin_cached)\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 1212.0s turn · 12.0s LLM · 0.0s tools
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 <tuple>\nstd::tuple<torch::Tensor, torch::Tensor> rope_forward(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin);\n\"\"\"\n\n_cuda_src = r\"\"\"\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda_runtime.h>\n#include <tuple>\n\n__global__ void rope64_kernel(const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ cosv,\n const float* __restrict__ sinv,\n float* __restrict__ qo,\n float* __restrict__ ko,\n int BH, int N) {\n int i = threadIdx.x;\n int bh = blockIdx.y * 8 + threadIdx.y;\n int n = blockIdx.x;\n if (bh < BH) {\n int base = (bh * N + n) * 64 + i;\n float c = cosv[n * 64 + i];\n float s = sinv[n * 64 + i];\n float q1 = q[base], q2 = q[base + 32];\n float k1 = k[base], k2 = k[base + 32];\n qo[base] = q1 * c - q2 * s;\n qo[base + 32] = q2 * c + q1 * s;\n ko[base] = k1 * c - k2 * s;\n ko[base + 32] = k2 * c + k1 * s;\n }\n}\n\n__global__ void rope_pair_kernel(const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ cosv,\n const float* __restrict__ sinv,\n float* __restrict__ qo,\n float* __restrict__ ko,\n int total, int N, int D, int half) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int stride = blockDim.x * gridDim.x;\n for (; idx < total; idx += stride) {\n int i = idx % half;\n int t = idx / half;\n int n = t % N;\n int bh = t / N;\n int base = (bh * N + n) * D + i;\n float c = cosv[n * D + i];\n float s = sinv[n * D + i];\n float q1 = q[base], q2 = q[base + half];\n float k1 = k[base], k2 = k[base + half];\n qo[base] = q1 * c - q2 * s;\n qo[base + half] = q2 * c + q1 * s;\n ko[base] = k1 * c - k2 * s;\n ko[base + half] = k2 * c + k1 * s;\n }\n}\n\nstd::tuple<torch::Tensor, torch::Tensor> rope_forward(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin) {\n int64_t B64 = q.size(0), H64 = q.size(1), N64 = q.size(2), D64 = q.size(3);\n auto qo = torch::empty({B64, H64, N64, D64}, q.options());\n auto ko = torch::empty({B64, H64, N64, D64}, q.options());\n int B = (int)B64, H = (int)H64, N = (int)N64, D = (int)D64;\n int BH = B * H;\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n if (D == 64) {\n dim3 block(32, 8, 1);\n dim3 grid(N, (BH + 7) / 8, 1);\n rope64_kernel<<<grid, block, 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>(), BH, N);\n } else {\n int half = D >> 1;\n int total = BH * N * half;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n if (blocks > 4096) blocks = 4096;\n rope_pair_kernel<<<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, N, D, half);\n }\n return std::make_tuple(qo, ko);\n}\n\"\"\"\n\n_rope_ext = load_inline(name=\"rope_ext_pair_v4\", cpp_sources=_cpp_src, cuda_sources=_cuda_src, functions=[\"rope_forward\"], extra_cflags=[\"-O3\"], extra_cuda_cflags=[\"-O3\"], verbose=False)\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 emb = torch.cat([freqs, freqs], dim=-1)\n self.register_buffer(\"cos_cached\", emb.cos().contiguous())\n self.register_buffer(\"sin_cached\", emb.sin().contiguous())\n self.max_seq_len = max_seq_len\n self.dim = dim\n def forward(self, q: torch.Tensor, k: torch.Tensor) -> tuple:\n return _rope_ext.rope_forward(q, k, self.cos_cached, self.sin_cached)\n"
}
result ← static_check (ok)
okstatic_check
static_check PASSED: no violations or warnings detected.
turn 13 · FINAL · 1 tool call(s) · 12.1s turn · 12.1s LLM · 6,303 chars (click to expand)
turn 1312.1s turn · 12.1s LLM · 0.0s tools · FINAL
reasoning
**Submitting code choices**
I need to submit the code, but I'm considering whether to choose version 4 or version 2. Version 4 seems to use the same kernel, but it might have lower host overhead. Plus, the profiling might not show the actual total. The timing is at 5.44 seconds, and the reference is likely much slower, so I want to make sure I have the final complete code. I think I should go ahead and submit it!
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 <tuple>\nstd::tuple<torch::Tensor, torch::Tensor> rope_forward(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin);\n\"\"\"\n\n_cuda_src = r\"\"\"\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda_runtime.h>\n#include <tuple>\n\n__global__ void rope64_kernel(const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ cosv,\n const float* __restrict__ sinv,\n float* __restrict__ qo,\n float* __restrict__ ko,\n int BH, int N) {\n int i = threadIdx.x;\n int bh = blockIdx.y * 8 + threadIdx.y;\n int n = blockIdx.x;\n if (bh < BH) {\n int base = (bh * N + n) * 64 + i;\n float c = cosv[n * 64 + i];\n float s = sinv[n * 64 + i];\n float q1 = q[base], q2 = q[base + 32];\n float k1 = k[base], k2 = k[base + 32];\n qo[base] = q1 * c - q2 * s;\n qo[base + 32] = q2 * c + q1 * s;\n ko[base] = k1 * c - k2 * s;\n ko[base + 32] = k2 * c + k1 * s;\n }\n}\n\n__global__ void rope_pair_kernel(const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ cosv,\n const float* __restrict__ sinv,\n float* __restrict__ qo,\n float* __restrict__ ko,\n int total, int N, int D, int half) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int stride = blockDim.x * gridDim.x;\n for (; idx < total; idx += stride) {\n int i = idx % half;\n int t = idx / half;\n int n = t % N;\n int bh = t / N;\n int base = (bh * N + n) * D + i;\n float c = cosv[n * D + i];\n float s = sinv[n * D + i];\n float q1 = q[base], q2 = q[base + half];\n float k1 = k[base], k2 = k[base + half];\n qo[base] = q1 * c - q2 * s;\n qo[base + half] = q2 * c + q1 * s;\n ko[base] = k1 * c - k2 * s;\n ko[base + half] = k2 * c + k1 * s;\n }\n}\n\nstd::tuple<torch::Tensor, torch::Tensor> rope_forward(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin) {\n int64_t B64 = q.size(0), H64 = q.size(1), N64 = q.size(2), D64 = q.size(3);\n auto qo = torch::empty({B64, H64, N64, D64}, q.options());\n auto ko = torch::empty({B64, H64, N64, D64}, q.options());\n int B = (int)B64, H = (int)H64, N = (int)N64, D = (int)D64;\n int BH = B * H;\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n if (D == 64) {\n dim3 block(32, 8, 1);\n dim3 grid(N, (BH + 7) / 8, 1);\n rope64_kernel<<<grid, block, 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>(), BH, N);\n } else {\n int half = D >> 1;\n int total = BH * N * half;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n if (blocks > 4096) blocks = 4096;\n rope_pair_kernel<<<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, N, D, half);\n }\n return std::make_tuple(qo, ko);\n}\n\"\"\"\n\n_rope_ext = load_inline(name=\"rope_ext_pair_final\", cpp_sources=_cpp_src, cuda_sources=_cuda_src, functions=[\"rope_forward\"], extra_cflags=[\"-O3\"], extra_cuda_cflags=[\"-O3\"], verbose=False)\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 emb = torch.cat([freqs, freqs], dim=-1)\n self.register_buffer(\"cos_cached\", emb.cos().contiguous())\n self.register_buffer(\"sin_cached\", emb.sin().contiguous())\n self.max_seq_len = max_seq_len\n self.dim = dim\n\n def forward(self, q: torch.Tensor, k: torch.Tensor) -> tuple:\n return _rope_ext.rope_forward(q, k, self.cos_cached, self.sin_cached)\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: 42.0 MB peak (ref: 46.13 MB, ratio: 0.9106x)
Kernel launches: 2 (ref: 45, fusion ratio: 22.5)
SOL score: 0.247
Flagged for excessive speedup — this submission may have been rejected by automated review.
final submitted kernel (105 lines, 4,443 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 <tuple>
std::tuple<torch::Tensor, torch::Tensor> rope_forward(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin);
"""
_cuda_src = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda_runtime.h>
#include <tuple>
__global__ void rope64_kernel(const float* __restrict__ q,
const float* __restrict__ k,
const float* __restrict__ cosv,
const float* __restrict__ sinv,
float* __restrict__ qo,
float* __restrict__ ko,
int BH, int N) {
int i = threadIdx.x;
int bh = blockIdx.y * 8 + threadIdx.y;
int n = blockIdx.x;
if (bh < BH) {
int base = (bh * N + n) * 64 + i;
float c = cosv[n * 64 + i];
float s = sinv[n * 64 + i];
float q1 = q[base], q2 = q[base + 32];
float k1 = k[base], k2 = k[base + 32];
qo[base] = q1 * c - q2 * s;
qo[base + 32] = q2 * c + q1 * s;
ko[base] = k1 * c - k2 * s;
ko[base + 32] = k2 * c + k1 * s;
}
}
__global__ void rope_pair_kernel(const float* __restrict__ q,
const float* __restrict__ k,
const float* __restrict__ cosv,
const float* __restrict__ sinv,
float* __restrict__ qo,
float* __restrict__ ko,
int total, int N, int D, int half) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
int stride = blockDim.x * gridDim.x;
for (; idx < total; idx += stride) {
int i = idx % half;
int t = idx / half;
int n = t % N;
int bh = t / N;
int base = (bh * N + n) * D + i;
float c = cosv[n * D + i];
float s = sinv[n * D + i];
float q1 = q[base], q2 = q[base + half];
float k1 = k[base], k2 = k[base + half];
qo[base] = q1 * c - q2 * s;
qo[base + half] = q2 * c + q1 * s;
ko[base] = k1 * c - k2 * s;
ko[base + half] = k2 * c + k1 * s;
}
}
std::tuple<torch::Tensor, torch::Tensor> rope_forward(torch::Tensor q, torch::Tensor k, torch::Tensor cos, torch::Tensor sin) {
int64_t B64 = q.size(0), H64 = q.size(1), N64 = q.size(2), D64 = q.size(3);
auto qo = torch::empty({B64, H64, N64, D64}, q.options());
auto ko = torch::empty({B64, H64, N64, D64}, q.options());
int B = (int)B64, H = (int)H64, N = (int)N64, D = (int)D64;
int BH = B * H;
cudaStream_t stream = at::cuda::getCurrentCUDAStream();
if (D == 64) {
dim3 block(32, 8, 1);
dim3 grid(N, (BH + 7) / 8, 1);
rope64_kernel<<<grid, block, 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>(), BH, N);
} else {
int half = D >> 1;
int total = BH * N * half;
int threads = 256;
int blocks = (total + threads - 1) / threads;
if (blocks > 4096) blocks = 4096;
rope_pair_kernel<<<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, N, D, half);
}
return std::make_tuple(qo, ko);
}
"""
_rope_ext = load_inline(name="rope_ext_pair_final", 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)
emb = torch.cat([freqs, freqs], dim=-1)
self.register_buffer("cos_cached", emb.cos().contiguous())
self.register_buffer("sin_cached", emb.sin().contiguous())
self.max_seq_len = max_seq_len
self.dim = dim
def forward(self, q: torch.Tensor, k: torch.Tensor) -> tuple:
return _rope_ext.rope_forward(q, k, self.cos_cached, self.sin_cached)