correct
11_pipeline_three_stage_mlp.py
started
2026-05-04T20:53:32Z
timingkernelbench.timing
kernel mean / median / std
0.01 / — / 2.83e-04 μs
ref mean / median / std
0.02 / — / 0.00 μs
numerical precisioneval_kernel_against_ref
gpu memoryextended_metrics.measure_memory
kernel launches / fusiontorch.profiler
fusion ratio (ref / kernel)
22.00x
SOL (speed-of-light)nsight_hardware_counters
roofline / occupancynsight_hardware_counters
warp stalls (top 5)nsight
reference PyTorch source (the prompt the agent sees)
"""
Three-stage MLP on packed activations: h1 = relu(h0 @ W1), h2 = relu(h1 @ W2), out = h2 @ W3.
Dimensions are fixed; weights are trainable parameters with default init.
"""
import torch
import torch.nn as nn
from kernelbench.distributed_collectives import default_device
B = 16
H0 = 48
H1 = 64
H2 = 40
H3 = 24
class Model(nn.Module):
def __init__(self):
super().__init__()
self.W1 = nn.Linear(H0, H1, bias=False)
self.W2 = nn.Linear(H1, H2, bias=False)
self.W3 = nn.Linear(H2, H3, bias=False)
def forward(self, h0: torch.Tensor) -> torch.Tensor:
h1 = torch.relu(self.W1(h0))
h2 = torch.relu(self.W2(h1))
return self.W3(h2)
def get_inputs():
dev = default_device()
p = popcorn_pri
return [torch.randn(p.jitter_int(B), H0, device=dev)]
def get_init_inputs():
return []
turn 033.9s turn · 33.9s LLM · 0.0s tools
reasoning
**Optimizing MLP Implementation**
I need to craft a Python file and optimize a tiny MLP with batch size B=16. The weights must be in a specific linear shape. I should ensure that my ModelNew accepts no arguments and has the same parameters as the constructor. It seems I'll initialize weights the same way, probably by copying from a reference model. I also need to consider GPU optimizations and ensure efficient operations with small matrices, using fused kernels for better performance while handling shared weights.
**Optimizing Kernel Launches**
I’m considering one block per batch row with 128 threads, where each thread computes a part of h1. For h2, I’ll loop over 64 threads, and for the output, I’ll loop over 40 threads. This yields about 16 blocks, which is relatively small, yet latency can be minimized with a single launch. However, while using one thread per output could cause serial execution, I wonder if I can parallelize within those outputs. I need to ensure that inputs and weights are contiguous and may want to handle device specifics in my CUDA setup.
**Setting Up PyTorch Extensions**
I need to avoid using a pybind block and focus on using functions like 'mlp_forward'. It seems I should include 'torch/extension.h' in my C++ and ensure the CUDA source includes it as well. I can utilize load_inline to compile both sources, which simplifies things. It might also be helpful to define the declaration in cpp_sources. I’m wondering if the host wrapper can be placed within the cuda_sources instead. That could streamline the process a bit!
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 1121.5s turn · 121.5s LLM · 0.0s tools
reasoning
**Considering CUDA implementation**
I'm looking into how to structure my code with CUDA. I think including the C++ wrapper in the C++ sources and declaring the CUDA launcher in the CUDA files makes sense.
In the C++ source, I should include the necessary header files and define the `mlp_forward` function, which calls `mlp_forward_cuda`. The CUDA source will define the kernel and the `mlp_forward_cuda` function.
It looks like I need to compile it all and then run a test to see if everything works correctly!
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\ntorch::Tensor mlp_forward_cuda(torch::Tensor h0, torch::Tensor w1, torch::Tensor w2, torch::Tensor w3);\n\ntorch::Tensor mlp_forward(torch::Tensor h0, torch::Tensor w1, torch::Tensor w2, torch::Tensor w3) {\n return mlp_forward_cuda(h0, w1, w2, w3);\n}\n'''\n\n_cuda_src = r'''\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n\n#define B 16\n#define H0 48\n#define H1 64\n#define H2 40\n#define H3 24\n\n__global__ __launch_bounds__(64, 4)\nvoid mlp_kernel(const float* __restrict__ h0,\n const float* __restrict__ w1,\n const float* __restrict__ w2,\n const float* __restrict__ w3,\n float* __restrict__ out) {\n const int b = blockIdx.x;\n const int tid = threadIdx.x;\n __shared__ float h1[H1];\n __shared__ float h2[H2];\n\n if (tid < H1) {\n float s = 0.0f;\n const float* x = h0 + b * H0;\n const float* w = w1 + tid * H0;\n #pragma unroll\n for (int k = 0; k < H0; ++k) {\n s = fmaf(x[k], w[k], s);\n }\n h1[tid] = s > 0.0f ? s : 0.0f;\n }\n __syncthreads();\n\n if (tid < H2) {\n float s = 0.0f;\n const float* w = w2 + tid * H1;\n #pragma unroll\n for (int k = 0; k < H1; ++k) {\n s = fmaf(h1[k], w[k], s);\n }\n h2[tid] = s > 0.0f ? s : 0.0f;\n }\n __syncthreads();\n\n if (tid < H3) {\n float s = 0.0f;\n const float* w = w3 + tid * H2;\n #pragma unroll\n for (int k = 0; k < H2; ++k) {\n s = fmaf(h2[k], w[k], s);\n }\n out[b * H3 + tid] = s;\n }\n}\n\ntorch::Tensor mlp_forward_cuda(torch::Tensor h0, torch::Tensor w1, torch::Tensor w2, torch::Tensor w3) {\n auto out = torch::empty({B, H3}, h0.options());\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n mlp_kernel<<<B, H1, 0, stream>>>(h0.data_ptr<float>(), w1.data_ptr<float>(), w2.data_ptr<float>(), w3.data_ptr<float>(), out.data_ptr<float>());\n return out;\n}\n'''\n\n_ext = load_inline(name='mlp_fused_ext_v1', cpp_sources=_cpp_src, cuda_sources=_cuda_src, functions=['mlp_forward'], extra_cflags=['-O3'], extra_cuda_cflags=['-O3'], verbose=False)\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super().__init__()\n self.W1 = nn.Linear(48, 64, bias=False)\n self.W2 = nn.Linear(64, 40, bias=False)\n self.W3 = nn.Linear(40, 24, bias=False)\n\n def forward(self, h0: torch.Tensor) -> torch.Tensor:\n return _ext.mlp_forward(h0, self.W1.weight, self.W2.weight, self.W3.weight)\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\ntorch::Tensor mlp_forward_cuda(torch::Tensor h0, torch::Tensor w1, torch::Tensor w2, torch::Tensor w3);\n\ntorch::Tensor mlp_forward(torch::Tensor h0, torch::Tensor w1, torch::Tensor w2, torch::Tensor w3) {\n return mlp_forward_cuda(h0, w1, w2, w3);\n}\n'''\n\n_cuda_src = r'''\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n\n#define B 16\n#define H0 48\n#define H1 64\n#define H2 40\n#define H3 24\n\n__global__ __launch_bounds__(64, 4)\nvoid mlp_kernel(const float* __restrict__ h0,\n const float* __restrict__ w1,\n const float* __restrict__ w2,\n const float* __restrict__ w3,\n float* __restrict__ out) {\n const int b = blockIdx.x;\n const int tid = threadIdx.x;\n __shared__ float h1[H1];\n __shared__ float h2[H2];\n\n if (tid < H1) {\n float s = 0.0f;\n const float* x = h0 + b * H0;\n const float* w = w1 + tid * H0;\n #pragma unroll\n for (int k = 0; k < H0; ++k) {\n s = fmaf(x[k], w[k], s);\n }\n h1[tid] = s > 0.0f ? s : 0.0f;\n }\n __syncthreads();\n\n if (tid < H2) {\n float s = 0.0f;\n const float* w = w2 + tid * H1;\n #pragma unroll\n for (int k = 0; k < H1; ++k) {\n s = fmaf(h1[k], w[k], s);\n }\n h2[tid] = s > 0.0f ? s : 0.0f;\n }\n __syncthreads();\n\n if (tid < H3) {\n float s = 0.0f;\n const float* w = w3 + tid * H2;\n #pragma unroll\n for (int k = 0; k < H2; ++k) {\n s = fmaf(h2[k], w[k], s);\n }\n out[b * H3 + tid] = s;\n }\n}\n\ntorch::Tensor mlp_forward_cuda(torch::Tensor h0, torch::Tensor w1, torch::Tensor w2, torch::Tensor w3) {\n auto out = torch::empty({B, H3}, h0.options());\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n mlp_kernel<<<B, H1, 0, stream>>>(h0.data_ptr<float>(), w1.data_ptr<float>(), w2.data_ptr<float>(), w3.data_ptr<float>(), out.data_ptr<float>());\n return out;\n}\n'''\n\n_ext = load_inline(name='mlp_fused_ext_v1', cpp_sources=_cpp_src, cuda_sources=_cuda_src, functions=['mlp_forward'], extra_cflags=['-O3'], extra_cuda_cflags=['-O3'], verbose=False)\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super().__init__()\n self.W1 = nn.Linear(48, 64, bias=False)\n self.W2 = nn.Linear(64, 40, bias=False)\n self.W3 = nn.Linear(40, 24, bias=False)\n\n def forward(self, h0: torch.Tensor) -> torch.Tensor:\n return _ext.mlp_forward(h0, self.W1.weight, self.W2.weight, self.W3.weight)\n"
}
result ← run_correctness (ok)
okrun_correctness
run_correctness PASSED: (5 / 5) trials all matched the reference.
Numerical precision: max_abs_err=7.45e-08 mean_abs_err=1.56e-08 max_rel_err=1.76e-05
turn 315.7s turn · 15.7s 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\ntorch::Tensor mlp_forward_cuda(torch::Tensor h0, torch::Tensor w1, torch::Tensor w2, torch::Tensor w3);\n\ntorch::Tensor mlp_forward(torch::Tensor h0, torch::Tensor w1, torch::Tensor w2, torch::Tensor w3) {\n return mlp_forward_cuda(h0, w1, w2, w3);\n}\n'''\n\n_cuda_src = r'''\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n\n#define B 16\n#define H0 48\n#define H1 64\n#define H2 40\n#define H3 24\n\n__global__ __launch_bounds__(64, 4)\nvoid mlp_kernel(const float* __restrict__ h0,\n const float* __restrict__ w1,\n const float* __restrict__ w2,\n const float* __restrict__ w3,\n float* __restrict__ out) {\n const int b = blockIdx.x;\n const int tid = threadIdx.x;\n __shared__ float h1[H1];\n __shared__ float h2[H2];\n\n if (tid < H1) {\n float s = 0.0f;\n const float* x = h0 + b * H0;\n const float* w = w1 + tid * H0;\n #pragma unroll\n for (int k = 0; k < H0; ++k) {\n s = fmaf(x[k], w[k], s);\n }\n h1[tid] = s > 0.0f ? s : 0.0f;\n }\n __syncthreads();\n\n if (tid < H2) {\n float s = 0.0f;\n const float* w = w2 + tid * H1;\n #pragma unroll\n for (int k = 0; k < H1; ++k) {\n s = fmaf(h1[k], w[k], s);\n }\n h2[tid] = s > 0.0f ? s : 0.0f;\n }\n __syncthreads();\n\n if (tid < H3) {\n float s = 0.0f;\n const float* w = w3 + tid * H2;\n #pragma unroll\n for (int k = 0; k < H2; ++k) {\n s = fmaf(h2[k], w[k], s);\n }\n out[b * H3 + tid] = s;\n }\n}\n\ntorch::Tensor mlp_forward_cuda(torch::Tensor h0, torch::Tensor w1, torch::Tensor w2, torch::Tensor w3) {\n auto out = torch::empty({B, H3}, h0.options());\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n mlp_kernel<<<B, H1, 0, stream>>>(h0.data_ptr<float>(), w1.data_ptr<float>(), w2.data_ptr<float>(), w3.data_ptr<float>(), out.data_ptr<float>());\n return out;\n}\n'''\n\n_ext = load_inline(name='mlp_fused_ext_v1', cpp_sources=_cpp_src, cuda_sources=_cuda_src, functions=['mlp_forward'], extra_cflags=['-O3'], extra_cuda_cflags=['-O3'], verbose=False)\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super().__init__()\n self.W1 = nn.Linear(48, 64, bias=False)\n self.W2 = nn.Linear(64, 40, bias=False)\n self.W3 = nn.Linear(40, 24, bias=False)\n\n def forward(self, h0: torch.Tensor) -> torch.Tensor:\n return _ext.mlp_forward(h0, self.W1.weight, self.W2.weight, self.W3.weight)\n"
}
result ← static_check (ok)
okstatic_check
static_check PASSED: no violations or warnings detected.
turn 435.9s turn · 35.9s LLM · 0.0s tools
reasoning
**Considering hybrid implementation**
I'm thinking about whether to infer from the run_correctness output, but it seems there's no timing information. Maybe I should implement a hybrid approach: using a 256-thread block for each row, where each warp computes one output at a time, handling eight outputs altogether. I realize that I only need eight warps and could reuse h1 while using shared h1. This might improve efficiency!
**Analyzing GPU occupancy**
I'm thinking about how 16 blocks occupy 16 streaming multiprocessors (SMs) with high occupancy, each having 1024 threads spread across 32 warps. However, it seems like other SMs would be idle. The launch overhead remains the same, which might lower overall compute efficiency. I wonder if this extra overhead for scheduling could be manageable, especially for smaller data sizes. There’s also uncertainty about timing and correctness, given the differences in reduction order compared to PyTorch.
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>\ntorch::Tensor mlp_forward_cuda(torch::Tensor h0, torch::Tensor w1, torch::Tensor w2, torch::Tensor w3);\ntorch::Tensor mlp_forward(torch::Tensor h0, torch::Tensor w1, torch::Tensor w2, torch::Tensor w3) { return mlp_forward_cuda(h0,w1,w2,w3); }\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#define B 16\n#define H0 48\n#define H1 64\n#define H2 40\n#define H3 24\n\n__inline__ __device__ float warp_sum(float v) {\n v += __shfl_down_sync(0xffffffff, v, 16);\n v += __shfl_down_sync(0xffffffff, v, 8);\n v += __shfl_down_sync(0xffffffff, v, 4);\n v += __shfl_down_sync(0xffffffff, v, 2);\n v += __shfl_down_sync(0xffffffff, v, 1);\n return v;\n}\n\n__global__ __launch_bounds__(1024, 1)\nvoid mlp_kernel_warp(const float* __restrict__ h0,\n const float* __restrict__ w1,\n const float* __restrict__ w2,\n const float* __restrict__ w3,\n float* __restrict__ out) {\n const int b = blockIdx.x;\n const int tid = threadIdx.x;\n const int warp = tid >> 5;\n const int lane = tid & 31;\n __shared__ float h1[H1];\n __shared__ float h2[H2];\n const float* x = h0 + b * H0;\n\n #pragma unroll\n for (int base = 0; base < H1; base += 32) {\n int o = base + warp;\n float s = 0.0f;\n if (o < H1) {\n const float* w = w1 + o * H0;\n #pragma unroll\n for (int k = lane; k < H0; k += 32) s = fmaf(x[k], w[k], s);\n s = warp_sum(s);\n if (lane == 0) h1[o] = s > 0.0f ? s : 0.0f;\n }\n }\n __syncthreads();\n\n #pragma unroll\n for (int base = 0; base < H2; base += 32) {\n int o = base + warp;\n float s = 0.0f;\n if (o < H2) {\n const float* w = w2 + o * H1;\n #pragma unroll\n for (int k = lane; k < H1; k += 32) s = fmaf(h1[k], w[k], s);\n s = warp_sum(s);\n if (lane == 0) h2[o] = s > 0.0f ? s : 0.0f;\n }\n }\n __syncthreads();\n\n int o = warp;\n if (o < H3) {\n float s = 0.0f;\n const float* w = w3 + o * H2;\n #pragma unroll\n for (int k = lane; k < H2; k += 32) s = fmaf(h2[k], w[k], s);\n s = warp_sum(s);\n if (lane == 0) out[b * H3 + o] = s;\n }\n}\n\ntorch::Tensor mlp_forward_cuda(torch::Tensor h0, torch::Tensor w1, torch::Tensor w2, torch::Tensor w3) {\n auto out = torch::empty({B, H3}, h0.options());\n mlp_kernel_warp<<<B, 1024, 0, at::cuda::getCurrentCUDAStream()>>>(h0.data_ptr<float>(), w1.data_ptr<float>(), w2.data_ptr<float>(), w3.data_ptr<float>(), out.data_ptr<float>());\n return out;\n}\n'''\n_ext = load_inline(name='mlp_fused_ext_warp1024_v1', cpp_sources=_cpp_src, cuda_sources=_cuda_src, functions=['mlp_forward'], extra_cflags=['-O3'], extra_cuda_cflags=['-O3'], verbose=False)\nclass ModelNew(nn.Module):\n def __init__(self):\n super().__init__()\n self.W1 = nn.Linear(48,64,bias=False)\n self.W2 = nn.Linear(64,40,bias=False)\n self.W3 = nn.Linear(40,24,bias=False)\n def forward(self,h0: torch.Tensor)->torch.Tensor:\n return _ext.mlp_forward(h0,self.W1.weight,self.W2.weight,self.W3.weight)\n"
}
result ← run_correctness (ok)
okrun_correctness
run_correctness PASSED: (5 / 5) trials all matched the reference.
Numerical precision: max_abs_err=5.22e-08 mean_abs_err=1.25e-08 max_rel_err=1.81e-05
turn 526.9s turn · 26.9s LLM · 0.0s tools
reasoning
**Considering performance maximization**
I’m trying to decide which approach is faster, potentially having the host make a choice or submitting directly. If I decide to submit, I could use 512 threads, balancing them for optimal performance. I think the kernel launch overhead will dominate and might range from 3 to 5 microseconds, plus any additional overhead from pybind. I wonder if execution with 1024 threads might take longer due to underutilization. It’s a complex calculation regarding memory and thread management, especially looking at kernel patterns.
**Analyzing memory performance**
I'm considering the total memory usage, which may reach 3MB, but I’m realizing that memory transactions are serialized due to the kernel loop. With only 32 warps available, I'm not sure it’s enough for efficient global memory access. The L2 cache helps with weights, especially since they’re the same for all blocks. However, with only 16 blocks on the H100, occupancy is low and memory latency isn’t hidden well. Increasing threads to 1024 could improve performance, but it might bring more complexity in execution.
**Exploring memory splitting**
I'm considering the possibility of splitting one row across multiple blocks, but that feels impractical. The warp version requires more warps per row, and using 512 threads would give me 16 warps. For occupancy, I can have 16 warps per active streaming multiprocessor (SM). The configuration for h1 could involve 4 groups, while h2 might have 3 and requires an output stage. This approach might improve performance, but I'm unsure about its feasibility.
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>\ntorch::Tensor mlp_forward_cuda(torch::Tensor h0, torch::Tensor w1, torch::Tensor w2, torch::Tensor w3);\ntorch::Tensor mlp_forward(torch::Tensor h0, torch::Tensor w1, torch::Tensor w2, torch::Tensor w3) { return mlp_forward_cuda(h0,w1,w2,w3); }\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#define B 16\n#define H0 48\n#define H1 64\n#define H2 40\n#define H3 24\n\n__inline__ __device__ float warp_sum(float v) {\n v += __shfl_down_sync(0xffffffff, v, 16);\n v += __shfl_down_sync(0xffffffff, v, 8);\n v += __shfl_down_sync(0xffffffff, v, 4);\n v += __shfl_down_sync(0xffffffff, v, 2);\n v += __shfl_down_sync(0xffffffff, v, 1);\n return v;\n}\n\n__global__ __launch_bounds__(1024, 1)\nvoid mlp_kernel_warp(const float* __restrict__ h0,\n const float* __restrict__ w1,\n const float* __restrict__ w2,\n const float* __restrict__ w3,\n float* __restrict__ out) {\n const int b = blockIdx.x;\n const int tid = threadIdx.x;\n const int warp = tid >> 5;\n const int lane = tid & 31;\n __shared__ float h1[H1];\n __shared__ float h2[H2];\n const float* x = h0 + b * H0;\n\n #pragma unroll\n for (int base = 0; base < H1; base += 32) {\n int o = base + warp;\n float s = 0.0f;\n if (o < H1) {\n const float* w = w1 + o * H0;\n #pragma unroll\n for (int k = lane; k < H0; k += 32) s = fmaf(x[k], w[k], s);\n s = warp_sum(s);\n if (lane == 0) h1[o] = s > 0.0f ? s : 0.0f;\n }\n }\n __syncthreads();\n\n #pragma unroll\n for (int base = 0; base < H2; base += 32) {\n int o = base + warp;\n float s = 0.0f;\n if (o < H2) {\n const float* w = w2 + o * H1;\n #pragma unroll\n for (int k = lane; k < H1; k += 32) s = fmaf(h1[k], w[k], s);\n s = warp_sum(s);\n if (lane == 0) h2[o] = s > 0.0f ? s : 0.0f;\n }\n }\n __syncthreads();\n\n int o = warp;\n if (o < H3) {\n float s = 0.0f;\n const float* w = w3 + o * H2;\n #pragma unroll\n for (int k = lane; k < H2; k += 32) s = fmaf(h2[k], w[k], s);\n s = warp_sum(s);\n if (lane == 0) out[b * H3 + o] = s;\n }\n}\n\ntorch::Tensor mlp_forward_cuda(torch::Tensor h0, torch::Tensor w1, torch::Tensor w2, torch::Tensor w3) {\n auto out = torch::empty({B, H3}, h0.options());\n mlp_kernel_warp<<<B, 1024, 0, at::cuda::getCurrentCUDAStream()>>>(h0.data_ptr<float>(), w1.data_ptr<float>(), w2.data_ptr<float>(), w3.data_ptr<float>(), out.data_ptr<float>());\n return out;\n}\n'''\n_ext = load_inline(name='mlp_fused_ext_warp1024_v1', cpp_sources=_cpp_src, cuda_sources=_cuda_src, functions=['mlp_forward'], extra_cflags=['-O3'], extra_cuda_cflags=['-O3'], verbose=False)\nclass ModelNew(nn.Module):\n def __init__(self):\n super().__init__()\n self.W1 = nn.Linear(48,64,bias=False)\n self.W2 = nn.Linear(64,40,bias=False)\n self.W3 = nn.Linear(40,24,bias=False)\n def forward(self,h0: torch.Tensor)->torch.Tensor:\n return _ext.mlp_forward(h0,self.W1.weight,self.W2.weight,self.W3.weight)\n"
}
result ← static_check (ok)
okstatic_check
static_check PASSED: no violations or warnings detected.
turn 614.7s turn · 14.7s LLM · 0.0s tools · FINAL
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\ntorch::Tensor mlp_forward_cuda(torch::Tensor h0, torch::Tensor w1, torch::Tensor w2, torch::Tensor w3);\n\ntorch::Tensor mlp_forward(torch::Tensor h0, torch::Tensor w1, torch::Tensor w2, torch::Tensor w3) {\n return mlp_forward_cuda(h0, w1, w2, w3);\n}\n'''\n\n_cuda_src = r'''\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n\n#define B 16\n#define H0 48\n#define H1 64\n#define H2 40\n#define H3 24\n\n__inline__ __device__ float warp_sum(float v) {\n v += __shfl_down_sync(0xffffffff, v, 16);\n v += __shfl_down_sync(0xffffffff, v, 8);\n v += __shfl_down_sync(0xffffffff, v, 4);\n v += __shfl_down_sync(0xffffffff, v, 2);\n v += __shfl_down_sync(0xffffffff, v, 1);\n return v;\n}\n\n__global__ __launch_bounds__(1024, 1)\nvoid mlp_kernel(const float* __restrict__ h0,\n const float* __restrict__ w1,\n const float* __restrict__ w2,\n const float* __restrict__ w3,\n float* __restrict__ out) {\n const int b = blockIdx.x;\n const int tid = threadIdx.x;\n const int warp = tid >> 5;\n const int lane = tid & 31;\n __shared__ float h1[H1];\n __shared__ float h2[H2];\n const float* x = h0 + b * H0;\n\n #pragma unroll\n for (int base = 0; base < H1; base += 32) {\n const int o = base + warp;\n float s = 0.0f;\n if (o < H1) {\n const float* w = w1 + o * H0;\n #pragma unroll\n for (int k = lane; k < H0; k += 32) {\n s = fmaf(x[k], w[k], s);\n }\n s = warp_sum(s);\n if (lane == 0) h1[o] = s > 0.0f ? s : 0.0f;\n }\n }\n __syncthreads();\n\n #pragma unroll\n for (int base = 0; base < H2; base += 32) {\n const int o = base + warp;\n float s = 0.0f;\n if (o < H2) {\n const float* w = w2 + o * H1;\n #pragma unroll\n for (int k = lane; k < H1; k += 32) {\n s = fmaf(h1[k], w[k], s);\n }\n s = warp_sum(s);\n if (lane == 0) h2[o] = s > 0.0f ? s : 0.0f;\n }\n }\n __syncthreads();\n\n const int o = warp;\n if (o < H3) {\n float s = 0.0f;\n const float* w = w3 + o * H2;\n #pragma unroll\n for (int k = lane; k < H2; k += 32) {\n s = fmaf(h2[k], w[k], s);\n }\n s = warp_sum(s);\n if (lane == 0) out[b * H3 + o] = s;\n }\n}\n\ntorch::Tensor mlp_forward_cuda(torch::Tensor h0, torch::Tensor w1, torch::Tensor w2, torch::Tensor w3) {\n auto out = torch::empty({B, H3}, h0.options());\n mlp_kernel<<<B, 1024, 0, at::cuda::getCurrentCUDAStream()>>>(\n h0.data_ptr<float>(), w1.data_ptr<float>(), w2.data_ptr<float>(), w3.data_ptr<float>(), out.data_ptr<float>());\n return out;\n}\n'''\n\n_ext = load_inline(\n name='mlp_fused_forward_opt_ext',\n cpp_sources=_cpp_src,\n cuda_sources=_cuda_src,\n functions=['mlp_forward'],\n extra_cflags=['-O3'],\n extra_cuda_cflags=['-O3'],\n verbose=False,\n)\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super().__init__()\n self.W1 = nn.Linear(48, 64, bias=False)\n self.W2 = nn.Linear(64, 40, bias=False)\n self.W3 = nn.Linear(40, 24, bias=False)\n\n def forward(self, h0: torch.Tensor) -> torch.Tensor:\n return _ext.mlp_forward(h0, self.W1.weight, self.W2.weight, self.W3.weight)\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=5.22e-08 mean_abs_err=1.25e-08 max_rel_err=1.81e-05
Memory: 33.06 MB peak (ref: 33.06 MB, ratio: 0.9998x)
Kernel launches: 1 (ref: 22, fusion ratio: 22.0)
SOL score: 0.0022
final submitted kernel (122 lines, 3,501 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>
torch::Tensor mlp_forward_cuda(torch::Tensor h0, torch::Tensor w1, torch::Tensor w2, torch::Tensor w3);
torch::Tensor mlp_forward(torch::Tensor h0, torch::Tensor w1, torch::Tensor w2, torch::Tensor w3) {
return mlp_forward_cuda(h0, w1, w2, w3);
}
'''
_cuda_src = r'''
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda.h>
#include <cuda_runtime.h>
#define B 16
#define H0 48
#define H1 64
#define H2 40
#define H3 24
__inline__ __device__ float warp_sum(float v) {
v += __shfl_down_sync(0xffffffff, v, 16);
v += __shfl_down_sync(0xffffffff, v, 8);
v += __shfl_down_sync(0xffffffff, v, 4);
v += __shfl_down_sync(0xffffffff, v, 2);
v += __shfl_down_sync(0xffffffff, v, 1);
return v;
}
__global__ __launch_bounds__(1024, 1)
void mlp_kernel(const float* __restrict__ h0,
const float* __restrict__ w1,
const float* __restrict__ w2,
const float* __restrict__ w3,
float* __restrict__ out) {
const int b = blockIdx.x;
const int tid = threadIdx.x;
const int warp = tid >> 5;
const int lane = tid & 31;
__shared__ float h1[H1];
__shared__ float h2[H2];
const float* x = h0 + b * H0;
#pragma unroll
for (int base = 0; base < H1; base += 32) {
const int o = base + warp;
float s = 0.0f;
if (o < H1) {
const float* w = w1 + o * H0;
#pragma unroll
for (int k = lane; k < H0; k += 32) {
s = fmaf(x[k], w[k], s);
}
s = warp_sum(s);
if (lane == 0) h1[o] = s > 0.0f ? s : 0.0f;
}
}
__syncthreads();
#pragma unroll
for (int base = 0; base < H2; base += 32) {
const int o = base + warp;
float s = 0.0f;
if (o < H2) {
const float* w = w2 + o * H1;
#pragma unroll
for (int k = lane; k < H1; k += 32) {
s = fmaf(h1[k], w[k], s);
}
s = warp_sum(s);
if (lane == 0) h2[o] = s > 0.0f ? s : 0.0f;
}
}
__syncthreads();
const int o = warp;
if (o < H3) {
float s = 0.0f;
const float* w = w3 + o * H2;
#pragma unroll
for (int k = lane; k < H2; k += 32) {
s = fmaf(h2[k], w[k], s);
}
s = warp_sum(s);
if (lane == 0) out[b * H3 + o] = s;
}
}
torch::Tensor mlp_forward_cuda(torch::Tensor h0, torch::Tensor w1, torch::Tensor w2, torch::Tensor w3) {
auto out = torch::empty({B, H3}, h0.options());
mlp_kernel<<<B, 1024, 0, at::cuda::getCurrentCUDAStream()>>>(
h0.data_ptr<float>(), w1.data_ptr<float>(), w2.data_ptr<float>(), w3.data_ptr<float>(), out.data_ptr<float>());
return out;
}
'''
_ext = load_inline(
name='mlp_fused_forward_opt_ext',
cpp_sources=_cpp_src,
cuda_sources=_cuda_src,
functions=['mlp_forward'],
extra_cflags=['-O3'],
extra_cuda_cflags=['-O3'],
verbose=False,
)
class ModelNew(nn.Module):
def __init__(self):
super().__init__()
self.W1 = nn.Linear(48, 64, bias=False)
self.W2 = nn.Linear(64, 40, bias=False)
self.W3 = nn.Linear(40, 24, bias=False)
def forward(self, h0: torch.Tensor) -> torch.Tensor:
return _ext.mlp_forward(h0, self.W1.weight, self.W2.weight, self.W3.weight)