correct
4_GJKRobotEnvironmentIntersection.py
started
2026-05-11T13:35:52Z
timingkernelbench.timing
kernel mean / median / std
0.01 / — / 1.85e-04 μs
ref mean / median / std
5.20 / — / 0.00 μs
numerical precisioneval_kernel_against_ref
gpu memoryextended_metrics.measure_memory
kernel launches / fusiontorch.profiler
fusion ratio (ref / kernel)
295.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)
"""
Robot–environment convex collision in **xy** (ground plane).
For an **axis-aligned robot footprint** vs. a **single convex obstacle triangle**, a
**separating-axis test (SAT)** gives the same **intersection predicate** as **GJK** in
2D, with a compact fully batched reference. A fused device kernel often implements
**GJK (+ EPA for penetration depth)** for arbitrary 3D polyhedra; this problem is
the canonical 2D footprint special case.
"""
import torch
import torch.nn as nn
# Default ModelNew is PyTorch-only. run_and_check: use check_kernel=False with backend=cuda
def _rect_corners_xy(robot_min: torch.Tensor, robot_max: torch.Tensor) -> torch.Tensor:
"""(B, 4, 2) corners of axis-aligned rectangles."""
x0, x1 = robot_min[:, 0], robot_max[:, 0]
y0, y1 = robot_min[:, 1], robot_max[:, 1]
return torch.stack(
(
torch.stack((x0, y0), dim=-1),
torch.stack((x1, y0), dim=-1),
torch.stack((x1, y1), dim=-1),
torch.stack((x0, y1), dim=-1),
),
dim=1,
)
def _project_min_max(points: torch.Tensor, axis: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
"""points (B, K, 2), axis (B, 2) or (2,) broadcast → (B,) min and max projections."""
if axis.dim() == 1:
axis = axis.view(1, 2).expand(points.shape[0], -1)
proj = (points * axis.unsqueeze(1)).sum(dim=-1)
return proj.min(dim=-1).values, proj.max(dim=-1).values
def _batched_sat_rect_triangle(
robot_min: torch.Tensor,
robot_max: torch.Tensor,
env_triangle: torch.Tensor,
eps: float,
) -> torch.Tensor:
"""
Separating-axis test: AABB vs triangle in 2D, fully vectorized over batch.
Returns (B,) float 1.0 if overlapping else 0.0.
"""
B = robot_min.shape[0]
corners = _rect_corners_xy(robot_min, robot_max)
hit = torch.ones(B, device=robot_min.device, dtype=robot_min.dtype)
# World axes (rectangle is AABB)
for ax in (
torch.tensor([1.0, 0.0], device=robot_min.device, dtype=robot_min.dtype),
torch.tensor([0.0, 1.0], device=robot_min.device, dtype=robot_min.dtype),
):
r0, r1 = _project_min_max(corners, ax)
t0, t1 = _project_min_max(env_triangle, ax)
separated = (r1 < t0 - eps) | (t1 < r0 - eps)
hit = hit * (~separated).to(hit.dtype)
# Triangle edge normals (per batch)
for i in range(3):
e = env_triangle[:, (i + 1) % 3] - env_triangle[:, i]
n = torch.stack((-e[:, 1], e[:, 0]), dim=-1)
n = n / (n.norm(dim=-1, keepdim=True) + 1e-8)
r0, r1 = _project_min_max(corners, n)
t0, t1 = _project_min_max(env_triangle, n)
separated = (r1 < t0 - eps) | (t1 < r0 - eps)
hit = hit * (~separated).to(hit.dtype)
return hit
class Model(nn.Module):
"""
**Batched robot footprint vs. environment triangle** intersection in **xy**.
Robot: axis-aligned box ``[robot_min, robot_max]`` per batch element.
Environment: one **triangle** ``(B, 3, 2)``.
Reference: **vectorized SAT** (5 axis tests). Fused-kernel target: same
predicate via **GJK/EPA** or specialized SAT SIMD for planning loops.
"""
def __init__(self, eps: float = 1e-6):
super().__init__()
self.eps = eps
def forward(
self,
robot_min: torch.Tensor,
robot_max: torch.Tensor,
env_triangle: torch.Tensor,
) -> torch.Tensor:
"""
Args:
robot_min: (B, 2), robot_max: (B, 2) with max >= min componentwise.
env_triangle: (B, 3, 2) obstacle vertices in order (any consistent winding).
Returns:
(B, 1) float in ``{0.0, 1.0}`` — **1** if the sets intersect.
"""
B = robot_min.shape[0]
assert robot_max.shape == (B, 2) and env_triangle.shape == (B, 3, 2)
h = _batched_sat_rect_triangle(robot_min, robot_max, env_triangle, self.eps)
return h.unsqueeze(-1)
class ModelNew(nn.Module):
"""KernelBench candidate entry point; default delegates to ``Model``."""
def __init__(self, eps: float = 1e-6):
super().__init__()
self._impl = Model(eps=eps)
def forward(
self,
robot_min: torch.Tensor,
robot_max: torch.Tensor,
env_triangle: torch.Tensor,
) -> torch.Tensor:
return self._impl(robot_min, robot_max, env_triangle)
batch_size = 16
def get_inputs():
bs = popcorn_pri.jitter_int(batch_size)
robot_min = torch.empty(bs, 2).uniform_(-1.0, 0.5)
robot_max = robot_min + torch.empty(bs, 2).uniform_(0.2, 0.8)
env_triangle = torch.empty(bs, 3, 2).uniform_(-0.8, 0.8)
return [robot_min, robot_max, env_triangle]
def get_init_inputs():
return []
turn 021.6s turn · 21.6s LLM · 0.0s tools · tokens in=2,568 · out=1,214 · total=4,123
reasoning
The task is to replace the forward computation with a custom CUDA kernel for this robot-environment convex collision detection using separating-axis test (SAT) for an axis-aligned rectangle vs. a tria...
assistant```python
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
cuda_source = """
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
__global__ void sat_rect_triangle_kernel(
const float* __restrict__ robot_min,
const float* __restrict__ robot_max,
const float* __restrict__ env_triangle,
float* __restrict__ output,
int B,
float eps
) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i >= B) return;
// Load robot min/max
float rx0 = robot_min[2*i];
float ry0 = robot_min[2*i + 1];
float rx1 = robot_max[2*i];
float ry1 = robot_max[2*i + 1];
// Load triangle vertices
float tx[3], ty[3];
for (int v = 0; v < 3; ++v) {
tx[v] = env_triangle[6*i + 2*v];
ty[v] = env_triangle[6*i + 2*v + 1];
}
bool overlap = true;
// Axis 1: x-axis (1,0)
{
float rmin = rx0, rmax = rx1;
float tmin = fminf(fminf(tx[0], tx[1]), tx[2]);
float tmax = fmaxf(fmaxf(tx[0], tx[1]), tx[2]);
if (rmax < tmin - eps || tmax < rmin - eps) overlap = false;
}
// Axis 2: y-axis (0,1)
if (overlap) {
float rmin = ry0, rmax = ry1;
float tmin = fminf(fminf(ty[0], ty[1]), ty[2]);
float tmax = fmaxf(fmaxf(ty[0], ty[1]), ty[2]);
if (rmax < tmin - eps || tmax < rmin - eps) overlap = false;
}
// Triangle edge normals
if (overlap) {
for (int e = 0; e < 3; ++e) {
int v0 = e;
int v1 = (e + 1) % 3;
float ex = tx[v1] - tx[v0];
float ey = ty[v1] - ty[v0];
float nx = -ey;
float ny = ex;
float nlen = sqrtf(nx*nx + ny*ny) + 1e-8f;
nx /= nlen;
ny /= nlen;
// Project rect corners
float rprojs[4];
rprojs[0] = rx0 * nx + ry0 * ny;
rprojs[1] = rx1 * nx + ry0 * ny;
rprojs[2] = rx1 * nx + ry1 * ny;
rprojs[3] = rx0 * nx + ry1 * ny;
float rmin = fminf(fminf(rprojs[0], rprojs[1]), fminf(rprojs[2], rprojs[3]));
float rmax = fmaxf(fmaxf(rprojs[0], rprojs[1]), fmaxf(rprojs[2], rprojs[3]));
// Project triangle
float tprojs[3];
for (int v = 0; v < 3; ++v) {
tprojs[v] = tx[v] * nx + ty[v] * ny;
}
float tmin = fminf(fminf(tprojs[0], tprojs[1]), tprojs[2]);
float tmax = fmaxf(fmaxf(tprojs[0], tprojs[1]), tprojs[2]);
if (rmax < tmin - eps || tmax < rmin - eps) {
overlap = false;
break;
}
}
}
output[i] = overlap ? 1.0f : 0.0f;
}
torch::Tensor sat_rect_triangle_cuda(
torch::Tensor robot_min,
torch::Tensor robot_max,
torch::Tensor env_triangle,
float eps
) {
int B = robot_min.size(0);
auto output = torch::empty({B, 1}, robot_min.options());
int threads = 256;
int blocks = (B + threads - 1) / threads;
sat_rect_triangle_kernel<<<blocks, threads>>>(
robot_min.data_ptr<float>(),
robot_max.data_ptr<float>(),
env_triangle.data_ptr<float>(),
output.data_ptr<float>(),
B,
eps
);
return output;
}
"""
cpp_source = """
torch::Tensor sat_rect_triangle_cuda(
torch::Tensor robot_min,
torch::Tensor robot_max,
torch::Tensor env_triangle,
float eps
);
"""
module = load_inline(
name='sat_module',
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=['sat_rect_triangle_cuda'],
verbose=False
)
class ModelNew(nn.Module):
def __init__(self, eps: float = 1e-6):
super().__init__()
self.eps = eps
def forward(
self,
robot_min: torch.Tensor,
robot_max: torch.Tensor,
env_triangle: torch.Tensor,
) -> torch.Tensor:
return module.sat_rect_triangle_cuda(robot_min, robot_max, env_triangle, self.eps)
```
turn 1671.0s turn · 13.3s LLM · 657.6s tools · tokens in=4,191 · out=1,221 · total=5,494
reasoning
The instruction says: "You must call at least one tool this turn: use `compile_kernel` / `run_correctness` to iterate, or call `submit_kernel` with your best `ModelNew` implementation to finalize the ...
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 sat_rect_triangle_kernel(\n const float* __restrict__ robot_min,\n const float* __restrict__ robot_max,\n const float* __restrict__ env_triangle,\n float* __restrict__ output,\n int B,\n float eps\n) {\n int i = blockIdx.x * blockDim.x + threadIdx.x;\n if (i >= B) return;\n\n // Load robot min/max\n float rx0 = robot_min[2*i];\n float ry0 = robot_min[2*i + 1];\n float rx1 = robot_max[2*i];\n float ry1 = robot_max[2*i + 1];\n\n // Load triangle vertices\n float tx[3], ty[3];\n for (int v = 0; v < 3; ++v) {\n tx[v] = env_triangle[6*i + 2*v];\n ty[v] = env_triangle[6*i + 2*v + 1];\n }\n\n bool overlap = true;\n\n // Axis 1: x-axis (1,0)\n {\n float rmin = rx0, rmax = rx1;\n float tmin = fminf(fminf(tx[0], tx[1]), tx[2]);\n float tmax = fmaxf(fmaxf(tx[0], tx[1]), tx[2]);\n if (rmax < tmin - eps || tmax < rmin - eps) overlap = false;\n }\n\n // Axis 2: y-axis (0,1)\n if (overlap) {\n float rmin = ry0, rmax = ry1;\n float tmin = fminf(fminf(ty[0], ty[1]), ty[2]);\n float tmax = fmaxf(fmaxf(ty[0], ty[1]), ty[2]);\n if (rmax < tmin - eps || tmax < rmin - eps) overlap = false;\n }\n\n // Triangle edge normals\n if (overlap) {\n for (int e = 0; e < 3; ++e) {\n int v0 = e;\n int v1 = (e + 1) % 3;\n float ex = tx[v1] - tx[v0];\n float ey = ty[v1] - ty[v0];\n float nx = -ey;\n float ny = ex;\n float nlen = sqrtf(nx*nx + ny*ny) + 1e-8f;\n nx /= nlen;\n ny /= nlen;\n\n // Project rect corners\n float rprojs[4];\n rprojs[0] = rx0 * nx + ry0 * ny;\n rprojs[1] = rx1 * nx + ry0 * ny;\n rprojs[2] = rx1 * nx + ry1 * ny;\n rprojs[3] = rx0 * nx + ry1 * ny;\n float rmin = fminf(fminf(rprojs[0], rprojs[1]), fminf(rprojs[2], rprojs[3]));\n float rmax = fmaxf(fmaxf(rprojs[0], rprojs[1]), fmaxf(rprojs[2], rprojs[3]));\n\n // Project triangle\n float tprojs[3];\n for (int v = 0; v < 3; ++v) {\n tprojs[v] = tx[v] * nx + ty[v] * ny;\n }\n float tmin = fminf(fminf(tprojs[0], tprojs[1]), tprojs[2]);\n float tmax = fmaxf(fmaxf(tprojs[0], tprojs[1]), tprojs[2]);\n\n if (rmax < tmin - eps || tmax < rmin - eps) {\n overlap = false;\n break;\n }\n }\n }\n\n output[i] = overlap ? 1.0f : 0.0f;\n}\n\ntorch::Tensor sat_rect_triangle_cuda(\n torch::Tensor robot_min,\n torch::Tensor robot_max,\n torch::Tensor env_triangle,\n float eps\n) {\n int B = robot_min.size(0);\n auto output = torch::empty({B, 1}, robot_min.options());\n\n int threads = 256;\n int blocks = (B + threads - 1) / threads;\n\n sat_rect_triangle_kernel<<<blocks, threads>>>(\n robot_min.data_ptr<float>(),\n robot_max.data_ptr<float>(),\n env_triangle.data_ptr<float>(),\n output.data_ptr<float>(),\n B,\n eps\n );\n\n return output;\n}\n\"\"\"\n\ncpp_source = \"\"\"\ntorch::Tensor sat_rect_triangle_cuda(\n torch::Tensor robot_min,\n torch::Tensor robot_max,\n torch::Tensor env_triangle,\n float eps\n);\n\"\"\"\n\nmodule = load_inline(\n name='sat_module',\n cpp_sources=cpp_source,\n cuda_sources=cuda_source,\n functions=['sat_rect_triangle_cuda'],\n verbose=False\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, eps: float = 1e-6):\n super().__init__()\n self.eps = eps\n\n def forward(\n self,\n robot_min: torch.Tensor,\n robot_max: torch.Tensor,\n env_triangle: torch.Tensor,\n ) -> torch.Tensor:\n return module.sat_rect_triangle_cuda(robot_min, robot_max, env_triangle, self.eps)\n"
}
result ← compile_kernel (ok)
okcompile_kernel
compile_kernel PASSED: kernel compiled without errors.
turn 2441.5s turn · 12.2s LLM · 429.4s tools · tokens in=5,511 · out=1,222 · total=6,746
reasoning
Compilation succeeded. Now I should check correctness with run_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 = \"\"\"\n#include <torch/extension.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n\n__global__ void sat_rect_triangle_kernel(\n const float* __restrict__ robot_min,\n const float* __restrict__ robot_max,\n const float* __restrict__ env_triangle,\n float* __restrict__ output,\n int B,\n float eps\n) {\n int i = blockIdx.x * blockDim.x + threadIdx.x;\n if (i >= B) return;\n\n // Load robot min/max\n float rx0 = robot_min[2*i];\n float ry0 = robot_min[2*i + 1];\n float rx1 = robot_max[2*i];\n float ry1 = robot_max[2*i + 1];\n\n // Load triangle vertices\n float tx[3], ty[3];\n for (int v = 0; v < 3; ++v) {\n tx[v] = env_triangle[6*i + 2*v];\n ty[v] = env_triangle[6*i + 2*v + 1];\n }\n\n bool overlap = true;\n\n // Axis 1: x-axis (1,0)\n {\n float rmin = rx0, rmax = rx1;\n float tmin = fminf(fminf(tx[0], tx[1]), tx[2]);\n float tmax = fmaxf(fmaxf(tx[0], tx[1]), tx[2]);\n if (rmax < tmin - eps || tmax < rmin - eps) overlap = false;\n }\n\n // Axis 2: y-axis (0,1)\n if (overlap) {\n float rmin = ry0, rmax = ry1;\n float tmin = fminf(fminf(ty[0], ty[1]), ty[2]);\n float tmax = fmaxf(fmaxf(ty[0], ty[1]), ty[2]);\n if (rmax < tmin - eps || tmax < rmin - eps) overlap = false;\n }\n\n // Triangle edge normals\n if (overlap) {\n for (int e = 0; e < 3; ++e) {\n int v0 = e;\n int v1 = (e + 1) % 3;\n float ex = tx[v1] - tx[v0];\n float ey = ty[v1] - ty[v0];\n float nx = -ey;\n float ny = ex;\n float nlen = sqrtf(nx*nx + ny*ny) + 1e-8f;\n nx /= nlen;\n ny /= nlen;\n\n // Project rect corners\n float rprojs[4];\n rprojs[0] = rx0 * nx + ry0 * ny;\n rprojs[1] = rx1 * nx + ry0 * ny;\n rprojs[2] = rx1 * nx + ry1 * ny;\n rprojs[3] = rx0 * nx + ry1 * ny;\n float rmin = fminf(fminf(rprojs[0], rprojs[1]), fminf(rprojs[2], rprojs[3]));\n float rmax = fmaxf(fmaxf(rprojs[0], rprojs[1]), fmaxf(rprojs[2], rprojs[3]));\n\n // Project triangle\n float tprojs[3];\n for (int v = 0; v < 3; ++v) {\n tprojs[v] = tx[v] * nx + ty[v] * ny;\n }\n float tmin = fminf(fminf(tprojs[0], tprojs[1]), tprojs[2]);\n float tmax = fmaxf(fmaxf(tprojs[0], tprojs[1]), tprojs[2]);\n\n if (rmax < tmin - eps || tmax < rmin - eps) {\n overlap = false;\n break;\n }\n }\n }\n\n output[i] = overlap ? 1.0f : 0.0f;\n}\n\ntorch::Tensor sat_rect_triangle_cuda(\n torch::Tensor robot_min,\n torch::Tensor robot_max,\n torch::Tensor env_triangle,\n float eps\n) {\n int B = robot_min.size(0);\n auto output = torch::empty({B, 1}, robot_min.options());\n\n int threads = 256;\n int blocks = (B + threads - 1) / threads;\n\n sat_rect_triangle_kernel<<<blocks, threads>>>(\n robot_min.data_ptr<float>(),\n robot_max.data_ptr<float>(),\n env_triangle.data_ptr<float>(),\n output.data_ptr<float>(),\n B,\n eps\n );\n\n return output;\n}\n\"\"\"\n\ncpp_source = \"\"\"\ntorch::Tensor sat_rect_triangle_cuda(\n torch::Tensor robot_min,\n torch::Tensor robot_max,\n torch::Tensor env_triangle,\n float eps\n);\n\"\"\"\n\nmodule = load_inline(\n name='sat_module',\n cpp_sources=cpp_source,\n cuda_sources=cuda_source,\n functions=['sat_rect_triangle_cuda'],\n verbose=False\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, eps: float = 1e-6):\n super().__init__()\n self.eps = eps\n\n def forward(\n self,\n robot_min: torch.Tensor,\n robot_max: torch.Tensor,\n env_triangle: torch.Tensor,\n ) -> torch.Tensor:\n return module.sat_rect_triangle_cuda(robot_min, robot_max, env_triangle, self.eps)\n"
}
result ← run_correctness (ok)
okrun_correctness
run_correctness PASSED: (5 / 5) trials all matched the reference.
Numerical precision: max_abs_err=0.00e+00 mean_abs_err=0.00e+00 max_rel_err=0.00e+00
turn 3571.1s turn · 11.7s LLM · 559.4s tools · tokens in=6,806 · out=1,221 · total=8,042 · FINAL
reasoning
Correctness passed perfectly. Now I can submit it as the final kernel.
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 = \"\"\"\n#include <torch/extension.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n\n__global__ void sat_rect_triangle_kernel(\n const float* __restrict__ robot_min,\n const float* __restrict__ robot_max,\n const float* __restrict__ env_triangle,\n float* __restrict__ output,\n int B,\n float eps\n) {\n int i = blockIdx.x * blockDim.x + threadIdx.x;\n if (i >= B) return;\n\n // Load robot min/max\n float rx0 = robot_min[2*i];\n float ry0 = robot_min[2*i + 1];\n float rx1 = robot_max[2*i];\n float ry1 = robot_max[2*i + 1];\n\n // Load triangle vertices\n float tx[3], ty[3];\n for (int v = 0; v < 3; ++v) {\n tx[v] = env_triangle[6*i + 2*v];\n ty[v] = env_triangle[6*i + 2*v + 1];\n }\n\n bool overlap = true;\n\n // Axis 1: x-axis (1,0)\n {\n float rmin = rx0, rmax = rx1;\n float tmin = fminf(fminf(tx[0], tx[1]), tx[2]);\n float tmax = fmaxf(fmaxf(tx[0], tx[1]), tx[2]);\n if (rmax < tmin - eps || tmax < rmin - eps) overlap = false;\n }\n\n // Axis 2: y-axis (0,1)\n if (overlap) {\n float rmin = ry0, rmax = ry1;\n float tmin = fminf(fminf(ty[0], ty[1]), ty[2]);\n float tmax = fmaxf(fmaxf(ty[0], ty[1]), ty[2]);\n if (rmax < tmin - eps || tmax < rmin - eps) overlap = false;\n }\n\n // Triangle edge normals\n if (overlap) {\n for (int e = 0; e < 3; ++e) {\n int v0 = e;\n int v1 = (e + 1) % 3;\n float ex = tx[v1] - tx[v0];\n float ey = ty[v1] - ty[v0];\n float nx = -ey;\n float ny = ex;\n float nlen = sqrtf(nx*nx + ny*ny) + 1e-8f;\n nx /= nlen;\n ny /= nlen;\n\n // Project rect corners\n float rprojs[4];\n rprojs[0] = rx0 * nx + ry0 * ny;\n rprojs[1] = rx1 * nx + ry0 * ny;\n rprojs[2] = rx1 * nx + ry1 * ny;\n rprojs[3] = rx0 * nx + ry1 * ny;\n float rmin = fminf(fminf(rprojs[0], rprojs[1]), fminf(rprojs[2], rprojs[3]));\n float rmax = fmaxf(fmaxf(rprojs[0], rprojs[1]), fmaxf(rprojs[2], rprojs[3]));\n\n // Project triangle\n float tprojs[3];\n for (int v = 0; v < 3; ++v) {\n tprojs[v] = tx[v] * nx + ty[v] * ny;\n }\n float tmin = fminf(fminf(tprojs[0], tprojs[1]), tprojs[2]);\n float tmax = fmaxf(fmaxf(tprojs[0], tprojs[1]), tprojs[2]);\n\n if (rmax < tmin - eps || tmax < rmin - eps) {\n overlap = false;\n break;\n }\n }\n }\n\n output[i] = overlap ? 1.0f : 0.0f;\n}\n\ntorch::Tensor sat_rect_triangle_cuda(\n torch::Tensor robot_min,\n torch::Tensor robot_max,\n torch::Tensor env_triangle,\n float eps\n) {\n int B = robot_min.size(0);\n auto output = torch::empty({B, 1}, robot_min.options());\n\n int threads = 256;\n int blocks = (B + threads - 1) / threads;\n\n sat_rect_triangle_kernel<<<blocks, threads>>>(\n robot_min.data_ptr<float>(),\n robot_max.data_ptr<float>(),\n env_triangle.data_ptr<float>(),\n output.data_ptr<float>(),\n B,\n eps\n );\n\n return output;\n}\n\"\"\"\n\ncpp_source = \"\"\"\ntorch::Tensor sat_rect_triangle_cuda(\n torch::Tensor robot_min,\n torch::Tensor robot_max,\n torch::Tensor env_triangle,\n float eps\n);\n\"\"\"\n\nmodule = load_inline(\n name='sat_module',\n cpp_sources=cpp_source,\n cuda_sources=cuda_source,\n functions=['sat_rect_triangle_cuda'],\n verbose=False\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, eps: float = 1e-6):\n super().__init__()\n self.eps = eps\n\n def forward(\n self,\n robot_min: torch.Tensor,\n robot_max: torch.Tensor,\n env_triangle: torch.Tensor,\n ) -> torch.Tensor:\n return module.sat_rect_triangle_cuda(robot_min, robot_max, env_triangle, self.eps)\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=0.00e+00 mean_abs_err=0.00e+00 max_rel_err=0.00e+00
Kernel launches: 1 (ref: 295, fusion ratio: 295.0)
SOL score: 0.0017
Flagged for excessive speedup — this submission may have been rejected by automated review.
final submitted kernel (146 lines, 3,963 chars) — full source, untruncated
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
cuda_source = """
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
__global__ void sat_rect_triangle_kernel(
const float* __restrict__ robot_min,
const float* __restrict__ robot_max,
const float* __restrict__ env_triangle,
float* __restrict__ output,
int B,
float eps
) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i >= B) return;
// Load robot min/max
float rx0 = robot_min[2*i];
float ry0 = robot_min[2*i + 1];
float rx1 = robot_max[2*i];
float ry1 = robot_max[2*i + 1];
// Load triangle vertices
float tx[3], ty[3];
for (int v = 0; v < 3; ++v) {
tx[v] = env_triangle[6*i + 2*v];
ty[v] = env_triangle[6*i + 2*v + 1];
}
bool overlap = true;
// Axis 1: x-axis (1,0)
{
float rmin = rx0, rmax = rx1;
float tmin = fminf(fminf(tx[0], tx[1]), tx[2]);
float tmax = fmaxf(fmaxf(tx[0], tx[1]), tx[2]);
if (rmax < tmin - eps || tmax < rmin - eps) overlap = false;
}
// Axis 2: y-axis (0,1)
if (overlap) {
float rmin = ry0, rmax = ry1;
float tmin = fminf(fminf(ty[0], ty[1]), ty[2]);
float tmax = fmaxf(fmaxf(ty[0], ty[1]), ty[2]);
if (rmax < tmin - eps || tmax < rmin - eps) overlap = false;
}
// Triangle edge normals
if (overlap) {
for (int e = 0; e < 3; ++e) {
int v0 = e;
int v1 = (e + 1) % 3;
float ex = tx[v1] - tx[v0];
float ey = ty[v1] - ty[v0];
float nx = -ey;
float ny = ex;
float nlen = sqrtf(nx*nx + ny*ny) + 1e-8f;
nx /= nlen;
ny /= nlen;
// Project rect corners
float rprojs[4];
rprojs[0] = rx0 * nx + ry0 * ny;
rprojs[1] = rx1 * nx + ry0 * ny;
rprojs[2] = rx1 * nx + ry1 * ny;
rprojs[3] = rx0 * nx + ry1 * ny;
float rmin = fminf(fminf(rprojs[0], rprojs[1]), fminf(rprojs[2], rprojs[3]));
float rmax = fmaxf(fmaxf(rprojs[0], rprojs[1]), fmaxf(rprojs[2], rprojs[3]));
// Project triangle
float tprojs[3];
for (int v = 0; v < 3; ++v) {
tprojs[v] = tx[v] * nx + ty[v] * ny;
}
float tmin = fminf(fminf(tprojs[0], tprojs[1]), tprojs[2]);
float tmax = fmaxf(fmaxf(tprojs[0], tprojs[1]), tprojs[2]);
if (rmax < tmin - eps || tmax < rmin - eps) {
overlap = false;
break;
}
}
}
output[i] = overlap ? 1.0f : 0.0f;
}
torch::Tensor sat_rect_triangle_cuda(
torch::Tensor robot_min,
torch::Tensor robot_max,
torch::Tensor env_triangle,
float eps
) {
int B = robot_min.size(0);
auto output = torch::empty({B, 1}, robot_min.options());
int threads = 256;
int blocks = (B + threads - 1) / threads;
sat_rect_triangle_kernel<<<blocks, threads>>>(
robot_min.data_ptr<float>(),
robot_max.data_ptr<float>(),
env_triangle.data_ptr<float>(),
output.data_ptr<float>(),
B,
eps
);
return output;
}
"""
cpp_source = """
torch::Tensor sat_rect_triangle_cuda(
torch::Tensor robot_min,
torch::Tensor robot_max,
torch::Tensor env_triangle,
float eps
);
"""
module = load_inline(
name='sat_module',
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=['sat_rect_triangle_cuda'],
verbose=False
)
class ModelNew(nn.Module):
def __init__(self, eps: float = 1e-6):
super().__init__()
self.eps = eps
def forward(
self,
robot_min: torch.Tensor,
robot_max: torch.Tensor,
env_triangle: torch.Tensor,
) -> torch.Tensor:
return module.sat_rect_triangle_cuda(robot_min, robot_max, env_triangle, self.eps)