grok-4.3 · popcorn · pop_l123_all_gpt
correct 13_QuantVLA_SelectiveLayoutFusion.py
model
grok-4.3
turns / max
5 / 15
tool calls
5
tokens (total)
23146
wall clock
736.7s
truncated
no
backend
cuda fp32
variant
popcorn
runtime
0.09 μs
ref runtime
0.10 μs
speedup
1.18x
started
2026-05-11T21:08:27Z
timingkernelbench.timing
kernel runtime
0.09 μs
ref runtime
0.10 μs
speedup
1.18x
kernel mean / median / std
0.09 / — / 0.01 μs
ref mean / median / std
0.10 / — / 0.02 μs
numerical precisioneval_kernel_against_ref
max abs error
4.77e-07
mean abs error
3.40e-08
max rel error
0.03
mean rel error
7.90e-07
gpu memoryextended_metrics.measure_memory
kernel peak
33.88 MB
ref peak
34.38 MB
kernel / ref
0.99x
kernel launches / fusiontorch.profiler
kernel launches
19
ref launches
32
fusion ratio (ref / kernel)
1.68x
total cuda time
468 μs
SOL (speed-of-light)nsight_hardware_counters
SOL score (0–1)
0.182
dram util %
6.6%
compute util %
18.2%
bottleneck
compute-bound
dominant pipe
FP32
arithmetic intensity
—
ridge point
20.00
roofline / occupancynsight_hardware_counters
dram bandwidth
222.27 GB/s
dram util %
6.6%
fp32 tflops
—
fp32 util %
—
fp16 tflops
—
occupancy %
61.6%
bottleneck
compute-bound
dominant pipe %
18.2%
arithmetic intensity
—
ridge point
20.00
L1 hit %
—
L2 hit %
428.2%
ld sectors / req
39.50
st sectors / req
—
regs / thread
189
smem / block
14208 B
block size
1088
peak bw
3350.00 GB/s
peak fp32 tflops
67.00
peak fp16 tflops
1979.00
warp stalls (top 5)nsight
long_scoreboard
7088.1%
short_scoreboard
786.4%
mio_throttle
24.3%
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 0233.3s turn · 10.0s LLM · 223.3s tools · tokens in=2,486 · out=6 · total=3,247
reasoning
The task is to replace the forward computation of the PyTorch model with a custom CUDA kernel. The Model class does: I need to replace the forward computation of the PyTorch model with a custom CUDA GPU kernel. The original Model class computes alpha from layout_logits using sigmoid, scales x using max abs and clamp, quantizes x to int8 range, mixes alpha times quantized x plus (1-alpha) times original x, and finally applies linear projection. For ModelNew, I must accept same args, same forward signature, maintain numerical equivalence, batch_size=8, seq_len=64, dim=128. To speed it up, I'll use torch.utils.cpp_extension.load_inline for an inline CUDA extension.
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 112.0s turn · 5.9s LLM · 6.1s tools · tokens in=3,480 · out=480 · total=4,018
reasoning
GPU is H100, high bandwidth.
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#include <cmath>\n\n__global__ void compute_mixed_kernel(const float* x, const float* layout_logits, float* mixed, \n int B, int T, int D, float scale) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int total = B * T * D;\n if (idx < total) {\n int bt = idx / D;\n float alpha = 1.0f / (1.0f + expf(-layout_logits[bt]));\n float val = x[idx];\n float q = roundf(val / scale);\n q = fminf(fmaxf(q, -127.0f), 127.0f);\n float xq = q * scale;\n mixed[idx] = alpha * xq + (1.0f - alpha) * val;\n }\n}\n\ntorch::Tensor compute_mixed_cuda(torch::Tensor x, torch::Tensor layout_logits) {\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 \n // Compute scale\n auto amax = x.abs().max().clamp_min(1e-8);\n float scale = amax.item<float>() / 127.0f;\n \n int total = B * T * D;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n \n compute_mixed_kernel<<<blocks, threads>>>(\n x.data_ptr<float>(), layout_logits.data_ptr<float>(), mixed.data_ptr<float>(),\n B, T, D, scale\n );\n \n return mixed;\n}\n'''\n\ncpp_source = '''\ntorch::Tensor compute_mixed_cuda(torch::Tensor x, torch::Tensor layout_logits);\n'''\n\nmodule = load_inline(\n name='mixed_quant',\n cpp_sources=cpp_source,\n cuda_sources=cuda_source,\n functions=['compute_mixed_cuda'],\n verbose=True\n)\n'''\n\n# Test if compiles\nprint(\"Kernel compiled successfully\")" }
result ← compile_kernel (fail)
failcompile_kernel compile_kernel FAILED: ModelNew class not found or syntax error prevented execution. Syntax Error in custom generated code or Compilation Error unterminated triple-quoted string literal (detected at line 65) (<string>, line 62)
turn 2162.1s turn · 6.5s LLM · 155.6s tools · tokens in=4,071 · out=554 · total=4,676
reasoning
Syntax error because of quotes in the code. I need to write the full module properly.
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.h>\n#include <cuda_runtime.h>\n#include <cmath>\n\n__global__ void compute_mixed_kernel(const float* x, const float* layout_logits, float* mixed, \n int B, int T, int D, float scale) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int total = B * T * D;\n if (idx < total) {\n int bt = idx / D;\n float alpha = 1.0f / (1.0f + expf(-layout_logits[bt]));\n float val = x[idx];\n float q = roundf(val / scale);\n q = fminf(fmaxf(q, -127.0f), 127.0f);\n float xq = q * scale;\n mixed[idx] = alpha * xq + (1.0f - alpha) * val;\n }\n}\n\ntorch::Tensor compute_mixed_cuda(torch::Tensor x, torch::Tensor layout_logits) {\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 \n // Compute scale\n auto amax = x.abs().max().clamp_min(1e-8);\n float scale = amax.item<float>() / 127.0f;\n \n int total = B * T * D;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n \n compute_mixed_kernel<<<blocks, threads>>>(\n x.data_ptr<float>(), layout_logits.data_ptr<float>(), mixed.data_ptr<float>(),\n B, T, D, scale\n );\n \n return mixed;\n}\n'''\n\ncpp_source = r'''\ntorch::Tensor compute_mixed_cuda(torch::Tensor x, torch::Tensor layout_logits);\n'''\n\nmodule = load_inline(\n name='mixed_quant',\n cpp_sources=cpp_source,\n cuda_sources=cuda_source,\n functions=['compute_mixed_cuda'],\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 mixed = module.compute_mixed_cuda(x, layout_logits)\n return self.out_proj(mixed)\n" }
result ← compile_kernel (ok)
okcompile_kernel compile_kernel PASSED: kernel compiled without errors.
turn 3239.7s turn · 5.1s LLM · 234.7s tools · tokens in=4,693 · out=555 · total=5,255
reasoning
Compiled successfully. 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.h>\n#include <cuda_runtime.h>\n#include <cmath>\n\n__global__ void compute_mixed_kernel(const float* x, const float* layout_logits, float* mixed, \n int B, int T, int D, float scale) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int total = B * T * D;\n if (idx < total) {\n int bt = idx / D;\n float alpha = 1.0f / (1.0f + expf(-layout_logits[bt]));\n float val = x[idx];\n float q = roundf(val / scale);\n q = fminf(fmaxf(q, -127.0f), 127.0f);\n float xq = q * scale;\n mixed[idx] = alpha * xq + (1.0f - alpha) * val;\n }\n}\n\ntorch::Tensor compute_mixed_cuda(torch::Tensor x, torch::Tensor layout_logits) {\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 \n // Compute scale\n auto amax = x.abs().max().clamp_min(1e-8);\n float scale = amax.item<float>() / 127.0f;\n \n int total = B * T * D;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n \n compute_mixed_kernel<<<blocks, threads>>>(\n x.data_ptr<float>(), layout_logits.data_ptr<float>(), mixed.data_ptr<float>(),\n B, T, D, scale\n );\n \n return mixed;\n}\n'''\n\ncpp_source = r'''\ntorch::Tensor compute_mixed_cuda(torch::Tensor x, torch::Tensor layout_logits);\n'''\n\nmodule = load_inline(\n name='mixed_quant',\n cpp_sources=cpp_source,\n cuda_sources=cuda_source,\n functions=['compute_mixed_cuda'],\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 mixed = module.compute_mixed_cuda(x, layout_logits)\n return self.out_proj(mixed)\n" }
result ← run_correctness (ok)
okrun_correctness run_correctness PASSED: (3 / 3) trials all matched the reference. Numerical precision: max_abs_err=4.77e-07 mean_abs_err=3.40e-08 max_rel_err=3.23e-02
turn 489.5s turn · 8.2s LLM · 81.3s tools · tokens in=5,315 · out=554 · total=5,950 · FINAL
reasoning
Correct! Now, to check if faster, but since submit will do timing, and it's likely faster due to fusion, I can submit.
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.h>\n#include <cuda_runtime.h>\n#include <cmath>\n\n__global__ void compute_mixed_kernel(const float* x, const float* layout_logits, float* mixed, \n int B, int T, int D, float scale) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int total = B * T * D;\n if (idx < total) {\n int bt = idx / D;\n float alpha = 1.0f / (1.0f + expf(-layout_logits[bt]));\n float val = x[idx];\n float q = roundf(val / scale);\n q = fminf(fmaxf(q, -127.0f), 127.0f);\n float xq = q * scale;\n mixed[idx] = alpha * xq + (1.0f - alpha) * val;\n }\n}\n\ntorch::Tensor compute_mixed_cuda(torch::Tensor x, torch::Tensor layout_logits) {\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 \n // Compute scale\n auto amax = x.abs().max().clamp_min(1e-8);\n float scale = amax.item<float>() / 127.0f;\n \n int total = B * T * D;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n \n compute_mixed_kernel<<<blocks, threads>>>(\n x.data_ptr<float>(), layout_logits.data_ptr<float>(), mixed.data_ptr<float>(),\n B, T, D, scale\n );\n \n return mixed;\n}\n'''\n\ncpp_source = r'''\ntorch::Tensor compute_mixed_cuda(torch::Tensor x, torch::Tensor layout_logits);\n'''\n\nmodule = load_inline(\n name='mixed_quant',\n cpp_sources=cpp_source,\n cuda_sources=cuda_source,\n functions=['compute_mixed_cuda'],\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 mixed = module.compute_mixed_cuda(x, layout_logits)\n return self.out_proj(mixed)\n" }
result ← submit_kernel (ok)
oksubmit_kernel submit_kernel PASSED: (3 / 3) correctness trials all passed. Kernel runtime: 0.09 μs Runtime stats: mean=0.09μs median=?μs std=0.01μs Numerical precision: max_abs_err=4.77e-07 mean_abs_err=3.40e-08 max_rel_err=3.23e-02 Memory: 33.88 MB peak (ref: 34.38 MB, ratio: 0.9854x) Kernel launches: 19 (ref: 32, fusion ratio: 1.6842) SOL score: 0.1816
final submitted kernel (70 lines, 2,001 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.h>
#include <cuda_runtime.h>
#include <cmath>

__global__ void compute_mixed_kernel(const float* x, const float* layout_logits, float* mixed, 
                                      int B, int T, int D, float scale) {
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    int total = B * T * D;
    if (idx < total) {
        int bt = idx / D;
        float alpha = 1.0f / (1.0f + expf(-layout_logits[bt]));
        float val = x[idx];
        float q = roundf(val / scale);
        q = fminf(fmaxf(q, -127.0f), 127.0f);
        float xq = q * scale;
        mixed[idx] = alpha * xq + (1.0f - alpha) * val;
    }
}

torch::Tensor compute_mixed_cuda(torch::Tensor x, torch::Tensor layout_logits) {
    auto B = x.size(0);
    auto T = x.size(1);
    auto D = x.size(2);
    auto mixed = torch::empty_like(x);
    
    // Compute scale
    auto amax = x.abs().max().clamp_min(1e-8);
    float scale = amax.item<float>() / 127.0f;
    
    int total = B * T * D;
    int threads = 256;
    int blocks = (total + threads - 1) / threads;
    
    compute_mixed_kernel<<<blocks, threads>>>(
        x.data_ptr<float>(), layout_logits.data_ptr<float>(), mixed.data_ptr<float>(),
        B, T, D, scale
    );
    
    return mixed;
}
'''

cpp_source = r'''
torch::Tensor compute_mixed_cuda(torch::Tensor x, torch::Tensor layout_logits);
'''

module = load_inline(
    name='mixed_quant',
    cpp_sources=cpp_source,
    cuda_sources=cuda_source,
    functions=['compute_mixed_cuda'],
    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:
        mixed = module.compute_mixed_cuda(x, layout_logits)
        return self.out_proj(mixed)