correct
13_QuantVLA_SelectiveLayoutFusion.py
started
2026-05-11T13:31:54Z
timingkernelbench.timing
kernel mean / median / std
0.14 / — / 0.47 μs
ref mean / median / std
0.08 / — / 0.01 μs
numerical precisioneval_kernel_against_ref
gpu memoryextended_metrics.measure_memory
kernel launches / fusiontorch.profiler
fusion ratio (ref / kernel)
1.45x
SOL (speed-of-light)nsight_hardware_counters
roofline / occupancynsight_hardware_counters
dram bandwidth
218.14 GB/s
warp stalls (top 5)nsight
reference PyTorch source (the prompt the agent sees)
import torch
import torch.nn as nn
# Default ModelNew is PyTorch-only. run_and_check: use check_kernel=False with backend=cuda
# until the candidate file contains a real CUDA kernel (see kernel_static_checker).
def _fake_quant_symmetric_int8(x: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:
"""Symmetric int8 fake-quant: round(x/scale) clamped to [-127, 127], times scale."""
q = torch.clamp(torch.round(x / scale), -127.0, 127.0)
return q * scale
class Model(nn.Module):
"""
**QuantVLA selective layout fusion** (reference target for a fused CUDA/Triton kernel).
Vision–language–action stacks often use **token-wise mixed precision**: some
timesteps or modalities tolerate aggressive quantization while others stay in
full precision. This module fuses in **one forward**:
1. **Layout routing** — ``sigmoid(layout_logits)`` yields a per-token mix
coefficient in ``(0, 1)`` (quant vs FP residual).
2. **Quantitative path** — global symmetric **int8-style fake quantization**
(scale from the tensor max, ``/ 127``).
3. **Selective blend** — ``α · x_quant + (1 - α) · x``.
4. **Head** — linear projection on the mixed activations.
This matches a “quantitative selective layout” block: the layout logits (from a
router, modality tags, or calibration) choose how strongly each position uses the
quantized layout vs the identity layout.
"""
def __init__(self, dim: int):
super().__init__()
self.dim = dim
self.out_proj = nn.Linear(dim, dim, bias=True)
def forward(self, x: torch.Tensor, layout_logits: torch.Tensor) -> torch.Tensor:
"""
Args:
x: (B, T, D) VLA token activations (fused modalities).
layout_logits: (B, T) unbounded logits; larger → more mass on quantized path.
Returns:
(B, T, D) updated activations.
"""
B, T, D = x.shape
assert D == self.dim
assert layout_logits.shape == (B, T)
alpha = torch.sigmoid(layout_logits).unsqueeze(-1)
with torch.no_grad():
amax = x.detach().abs().max().clamp(min=1e-8)
scale = amax / 127.0
x_q = _fake_quant_symmetric_int8(x, scale)
mixed = alpha * x_q + (1.0 - alpha) * x
return self.out_proj(mixed)
class ModelNew(nn.Module):
"""KernelBench candidate entry point; default delegates to ``Model``."""
def __init__(self, dim: int):
super().__init__()
self._impl = Model(dim)
def forward(self, x: torch.Tensor, layout_logits: torch.Tensor) -> torch.Tensor:
return self._impl(x, layout_logits)
batch_size = 8
seq_len = 64
dim = 128
def get_inputs():
p = popcorn_pri
x = torch.randn(p.jitter_int(batch_size), p.jitter_int(seq_len), dim)
layout_logits = torch.randn(p.jitter_int(batch_size), p.jitter_int(seq_len))
return [x, layout_logits]
def get_init_inputs():
return [dim]
turn 0372.7s turn · 12.9s LLM · 359.8s tools · tokens in=1,955 · out=6 · total=2,479
reasoning
The task is to replace the forward computation of the PyTorch model with a custom CUDA kernel. The ModelNew class must match the constructor and forward signature, produce equivalent outputs, and run ...I need to replace the forward computation of a PyTorch model with a custom CUDA kernel for a new ModelNew class. It should take the same inputs as the original Model, have the same forward signature, and produce identical numerical outputs, but hopefully run faster.
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 190.9s turn · 7.7s LLM · 83.3s tools · tokens in=2,712 · out=345 · total=3,261
reasoning
H100, high bandwidth.
I need to implement a fused kernel.
call → compile_kernel
callcompile_kernel
{
"kernel_code": "import torch\nimport torch.nn as nn\nfrom torch.utils.cpp_extension import load_inline\n\ncuda_source = \"\"\"\n#include <torch/extension.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n\n__global__ void selective_quant_linear_kernel(\n const float* __restrict__ x,\n const float* __restrict__ layout_logits,\n const float* __restrict__ weight,\n const float* __restrict__ bias,\n float* __restrict__ output,\n int B, int T, int D\n) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int total = B * T * D;\n if (idx >= total) return;\n\n int d = idx % D;\n int t = (idx / D) % T;\n int b = idx / (T * D);\n\n // Compute scale - need reduction, but for simplicity compute per element? No, global max.\n // Problem: scale is global, so better compute outside or separate kernel.\n // For now, assume we pass scale or compute in host.\n}\n\ntorch::Tensor selective_quant_linear(torch::Tensor x, torch::Tensor layout_logits, torch::Tensor weight, torch::Tensor bias) {\n // placeholder\n return x;\n}\n\"\"\"\n\ncpp_source = \"\"\"\ntorch::Tensor selective_quant_linear(torch::Tensor x, torch::Tensor layout_logits, torch::Tensor weight, torch::Tensor bias);\n\"\"\"\n\nmodule = load_inline(\n name='selective_quant',\n cpp_sources=cpp_source,\n cuda_sources=cuda_source,\n functions=['selective_quant_linear'],\n verbose=True\n)\nprint(\"Compiled successfully\")\n"
}
result ← compile_kernel (fail)
failcompile_kernel
compile_kernel FAILED: ModelNew class not found or syntax error prevented execution.
Compiled successfully
turn 2305.4s turn · 6.5s LLM · 298.9s tools · tokens in=3,286 · out=534 · total=3,925
reasoning
It compiled the module but the kernel_code needs to define ModelNew.
call → compile_kernel
callcompile_kernel
{
"kernel_code": "import torch\nimport torch.nn as nn\nfrom torch.utils.cpp_extension import load_inline\n\ncuda_source = r'''\n#include <torch/extension.h>\n#include <cuda_runtime.h>\n\n__global__ void mix_quant_kernel(const float* x, const float* logits, float* mixed, float scale, int B, int T, int D) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int total = B * T * D;\n if (idx >= total) return;\n int bt = idx / D;\n float alpha = 1.0f / (1.0f + expf(-logits[bt]));\n float val = x[idx];\n float q = roundf(val / scale);\n q = fmaxf(fminf(q, 127.0f), -127.0f);\n float xq = q * scale;\n mixed[idx] = alpha * xq + (1.0f - alpha) * val;\n}\n\ntorch::Tensor selective_mix(torch::Tensor x, torch::Tensor layout_logits, float scale) {\n auto B = x.size(0);\n auto T = x.size(1);\n auto D = x.size(2);\n auto mixed = torch::empty_like(x);\n int total = B * T * D;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n mix_quant_kernel<<<blocks, threads>>>(x.data_ptr<float>(), layout_logits.data_ptr<float>(), mixed.data_ptr<float>(), scale, B, T, D);\n return mixed;\n}\n'''\n\ncpp_source = r'''\ntorch::Tensor selective_mix(torch::Tensor x, torch::Tensor layout_logits, float scale);\n'''\n\nmodule = load_inline(\n name=\"selective_quant\",\n cpp_sources=cpp_source,\n cuda_sources=cuda_source,\n functions=[\"selective_mix\"],\n verbose=False\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, dim: int):\n super().__init__()\n self.dim = dim\n self.out_proj = nn.Linear(dim, dim, bias=True)\n\n def forward(self, x: torch.Tensor, layout_logits: torch.Tensor) -> torch.Tensor:\n B, T, D = x.shape\n amax = x.detach().abs().max().clamp(min=1e-8)\n scale = amax.item() / 127.0\n mixed = module.selective_mix(x, layout_logits, scale)\n return self.out_proj(mixed)\n"
}
result ← compile_kernel (ok)
okcompile_kernel
compile_kernel PASSED: kernel compiled without errors.
turn 3149.7s turn · 6.6s LLM · 143.1s tools · tokens in=3,942 · out=535 · total=4,485
reasoning
Good, compiled. Now check correctness.
call → run_correctness
callrun_correctness
{
"kernel_code": "import torch\nimport torch.nn as nn\nfrom torch.utils.cpp_extension import load_inline\n\ncuda_source = r'''\n#include <torch/extension.h>\n#include <cuda_runtime.h>\n\n__global__ void mix_quant_kernel(const float* x, const float* logits, float* mixed, float scale, int B, int T, int D) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int total = B * T * D;\n if (idx >= total) return;\n int bt = idx / D;\n float alpha = 1.0f / (1.0f + expf(-logits[bt]));\n float val = x[idx];\n float q = roundf(val / scale);\n q = fmaxf(fminf(q, 127.0f), -127.0f);\n float xq = q * scale;\n mixed[idx] = alpha * xq + (1.0f - alpha) * val;\n}\n\ntorch::Tensor selective_mix(torch::Tensor x, torch::Tensor layout_logits, float scale) {\n auto B = x.size(0);\n auto T = x.size(1);\n auto D = x.size(2);\n auto mixed = torch::empty_like(x);\n int total = B * T * D;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n mix_quant_kernel<<<blocks, threads>>>(x.data_ptr<float>(), layout_logits.data_ptr<float>(), mixed.data_ptr<float>(), scale, B, T, D);\n return mixed;\n}\n'''\n\ncpp_source = r'''\ntorch::Tensor selective_mix(torch::Tensor x, torch::Tensor layout_logits, float scale);\n'''\n\nmodule = load_inline(\n name=\"selective_quant\",\n cpp_sources=cpp_source,\n cuda_sources=cuda_source,\n functions=[\"selective_mix\"],\n verbose=False\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, dim: int):\n super().__init__()\n self.dim = dim\n self.out_proj = nn.Linear(dim, dim, bias=True)\n\n def forward(self, x: torch.Tensor, layout_logits: torch.Tensor) -> torch.Tensor:\n B, T, D = x.shape\n amax = x.detach().abs().max().clamp(min=1e-8)\n scale = amax.item() / 127.0\n mixed = module.selective_mix(x, layout_logits, scale)\n return self.out_proj(mixed)\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=3.38e-08 max_rel_err=3.23e-02
turn 4184.6s turn · 7.2s LLM · 177.3s tools · tokens in=4,545 · out=534 · total=5,150 · FINAL
reasoning
Correct! Now, to submit, but is it faster? Probably slightly due to fusion of quant and mix, avoiding some intermediates.
call → submit_kernel
callsubmit_kernel
{
"kernel_code": "import torch\nimport torch.nn as nn\nfrom torch.utils.cpp_extension import load_inline\n\ncuda_source = r'''\n#include <torch/extension.h>\n#include <cuda_runtime.h>\n\n__global__ void mix_quant_kernel(const float* x, const float* logits, float* mixed, float scale, int B, int T, int D) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int total = B * T * D;\n if (idx >= total) return;\n int bt = idx / D;\n float alpha = 1.0f / (1.0f + expf(-logits[bt]));\n float val = x[idx];\n float q = roundf(val / scale);\n q = fmaxf(fminf(q, 127.0f), -127.0f);\n float xq = q * scale;\n mixed[idx] = alpha * xq + (1.0f - alpha) * val;\n}\n\ntorch::Tensor selective_mix(torch::Tensor x, torch::Tensor layout_logits, float scale) {\n auto B = x.size(0);\n auto T = x.size(1);\n auto D = x.size(2);\n auto mixed = torch::empty_like(x);\n int total = B * T * D;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n mix_quant_kernel<<<blocks, threads>>>(x.data_ptr<float>(), layout_logits.data_ptr<float>(), mixed.data_ptr<float>(), scale, B, T, D);\n return mixed;\n}\n'''\n\ncpp_source = r'''\ntorch::Tensor selective_mix(torch::Tensor x, torch::Tensor layout_logits, float scale);\n'''\n\nmodule = load_inline(\n name=\"selective_quant\",\n cpp_sources=cpp_source,\n cuda_sources=cuda_source,\n functions=[\"selective_mix\"],\n verbose=False\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, dim: int):\n super().__init__()\n self.dim = dim\n self.out_proj = nn.Linear(dim, dim, bias=True)\n\n def forward(self, x: torch.Tensor, layout_logits: torch.Tensor) -> torch.Tensor:\n B, T, D = x.shape\n amax = x.detach().abs().max().clamp(min=1e-8)\n scale = amax.item() / 127.0\n mixed = module.selective_mix(x, layout_logits, scale)\n return self.out_proj(mixed)\n"
}
result ← submit_kernel (ok)
oksubmit_kernel
submit_kernel PASSED: (5 / 5) correctness trials all passed.
Kernel runtime: 0.14 μs
Runtime stats: mean=0.14μs median=?μs std=0.47μs
Numerical precision: max_abs_err=4.77e-07 mean_abs_err=3.38e-08 max_rel_err=3.23e-02
Memory: 33.88 MB peak (ref: 34.38 MB, ratio: 0.9854x)
Kernel launches: 22 (ref: 32, fusion ratio: 1.4545)
Energy: 277.26 mJ/run (ref: 0.0 mJ, ratio: -1x)
SOL score: 0.1837
final submitted kernel (59 lines, 1,850 chars) — full source, untruncated
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
cuda_source = r'''
#include <torch/extension.h>
#include <cuda_runtime.h>
__global__ void mix_quant_kernel(const float* x, const float* logits, float* mixed, float scale, int B, int T, int D) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
int total = B * T * D;
if (idx >= total) return;
int bt = idx / D;
float alpha = 1.0f / (1.0f + expf(-logits[bt]));
float val = x[idx];
float q = roundf(val / scale);
q = fmaxf(fminf(q, 127.0f), -127.0f);
float xq = q * scale;
mixed[idx] = alpha * xq + (1.0f - alpha) * val;
}
torch::Tensor selective_mix(torch::Tensor x, torch::Tensor layout_logits, float scale) {
auto B = x.size(0);
auto T = x.size(1);
auto D = x.size(2);
auto mixed = torch::empty_like(x);
int total = B * T * D;
int threads = 256;
int blocks = (total + threads - 1) / threads;
mix_quant_kernel<<<blocks, threads>>>(x.data_ptr<float>(), layout_logits.data_ptr<float>(), mixed.data_ptr<float>(), scale, B, T, D);
return mixed;
}
'''
cpp_source = r'''
torch::Tensor selective_mix(torch::Tensor x, torch::Tensor layout_logits, float scale);
'''
module = load_inline(
name="selective_quant",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["selective_mix"],
verbose=False
)
class ModelNew(nn.Module):
def __init__(self, dim: int):
super().__init__()
self.dim = dim
self.out_proj = nn.Linear(dim, dim, bias=True)
def forward(self, x: torch.Tensor, layout_logits: torch.Tensor) -> torch.Tensor:
B, T, D = x.shape
amax = x.detach().abs().max().clamp(min=1e-8)
scale = amax.item() / 127.0
mixed = module.selective_mix(x, layout_logits, scale)
return self.out_proj(mixed)