gpt-5.5-priority · original · l12_default_gpt
correct 34_InstanceNorm.py
model
gpt-5.5-priority
turns / max
8 / 10
tool calls
8
tokens (total)
0
wall clock
—
truncated
no
backend
cuda fp32
variant
original
runtime
10.90 μs
ref runtime
9.68 μs
speedup
0.89x
started
2026-05-02T16:46:32Z
timingkernelbench.timing
kernel runtime
10.90 μs
ref runtime
9.68 μs
speedup
0.89x
kernel mean / median / std
10.90 / — / 29.60 μs
ref mean / median / std
9.68 / — / 0.20 μs
numerical precisioneval_kernel_against_ref
max abs error
1.79e-06
mean abs error
1.38e-07
max rel error
412955.94
mean rel error
0.00
gpu memoryextended_metrics.measure_memory
kernel peak
14369.00 MB
ref peak
14369.05 MB
kernel / ref
1.00x
kernel launches / fusiontorch.profiler
kernel launches
2
ref launches
16
fusion ratio (ref / kernel)
8.00x
total cuda time
54 μs
energyNVML (pynvml)
kernel mJ / run
3913.76
ref mJ / run
5145.36
ratio (ref / kernel)
1.31x
avg power
496.74 W
ref avg power
529.31 W
SOL (speed-of-light)nsight_hardware_counters
SOL score (0–1)
0.873
dram util %
87.3%
compute util %
0.0%
bottleneck
unknown
dominant pipe
None
arithmetic intensity
—
ridge point
20.00
roofline / occupancynsight_hardware_counters
dram bandwidth
2923.54 GB/s
dram util %
87.3%
fp32 tflops
—
fp32 util %
—
fp16 tflops
—
occupancy %
98.2%
bottleneck
unknown
dominant pipe %
—
arithmetic intensity
—
ridge point
20.00
L1 hit %
—
L2 hit %
34.3%
ld sectors / req
16.00
st sectors / req
—
regs / thread
21
smem / block
1280 B
block size
256
peak bw
3350.00 GB/s
peak fp32 tflops
67.00
peak fp16 tflops
1979.00
warp stalls (top 5)nsight
long_scoreboard
28192.8%
short_scoreboard
4.1%
mio_throttle
0.6%
reference PyTorch source (the prompt the agent sees)
import torch
import torch.nn as nn

class Model(nn.Module):
    """
    Simple model that performs Instance Normalization.
    """
    def __init__(self, num_features: int):
        """
        Initializes the InstanceNorm layer.

        Args:
            num_features (int): Number of features in the input tensor.
        """
        super(Model, self).__init__()
        self.inorm = nn.InstanceNorm2d(num_features=num_features)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """
        Applies Instance Normalization to the input tensor.

        Args:
            x (torch.Tensor): Input tensor of shape (batch_size, num_features, height, width).

        Returns:
            torch.Tensor: Output tensor with Instance Normalization applied, same shape as input.
        """
        return self.inorm(x)

batch_size = 112  # heavier workload
features = 64
dim1 = 512
dim2 = 512

def get_inputs():
    x = torch.rand(batch_size, features, dim1, dim2)
    return [x]

def get_init_inputs():
    return [features]
turn 015.0s turn · 15.0s LLM · 0.0s tools
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 1 · 1 tool call(s) · 52.4s turn · 52.4s LLM · 9,301 chars (click to expand)
turn 152.4s turn · 52.4s LLM · 0.0s tools
reasoning
**Reviewing input expectations** I think InstanceNorm shouldn't need parameters, but I'm wondering if there's an issue with input not being contiguous. Maybe calling forward could enforce contiguity? If I use contiguous, it adds a copy, and that might be problematic. Should I check x.contiguous()? Hm, something feels off there. I'll need to import torch and nn as well. It’s important to ensure my module's name is unique, and I might use torch.empty_like. Alright, let's compile and correct things!
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 instance_norm_forward(torch::Tensor x);\n'''\n\n_cuda_src = r'''\n#include <torch/extension.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <stdint.h>\n\n#ifndef CHECK_CUDA\n#define CHECK_CUDA(x) TORCH_CHECK(x.is_cuda(), #x \" must be a CUDA tensor\")\n#define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x \" must be contiguous\")\n#define CHECK_FLOAT(x) TORCH_CHECK(x.scalar_type() == at::kFloat, #x \" must be float32\")\n#endif\n\n__inline__ __device__ float warp_reduce_sum(float v) {\n #pragma unroll\n for (int offset = 16; offset > 0; offset >>= 1) {\n v += __shfl_down_sync(0xffffffff, v, offset);\n }\n return v;\n}\n\n__inline__ __device__ float block_reduce_sum(float v) {\n static __shared__ float shared[32];\n int lane = threadIdx.x & 31;\n int wid = threadIdx.x >> 5;\n v = warp_reduce_sum(v);\n if (lane == 0) shared[wid] = v;\n __syncthreads();\n v = (threadIdx.x < (blockDim.x >> 5)) ? shared[lane] : 0.0f;\n if (wid == 0) v = warp_reduce_sum(v);\n return v;\n}\n\n__global__ __launch_bounds__(256, 2)\nvoid inst_norm_kernel(const float* __restrict__ x, float* __restrict__ y,\n int64_t instances, int64_t spatial) {\n int inst = blockIdx.x;\n if ((int64_t)inst >= instances) return;\n const float* base = x + ((int64_t)inst) * spatial;\n float* out = y + ((int64_t)inst) * spatial;\n\n float sum = 0.0f;\n float sumsq = 0.0f;\n\n // spatial is divisible by 4 for the benchmark, and base is 16B aligned.\n int64_t n4 = spatial >> 2;\n const float4* b4 = reinterpret_cast<const float4*>(base);\n for (int64_t i = threadIdx.x; i < n4; i += blockDim.x) {\n float4 v = b4[i];\n sum += v.x + v.y + v.z + v.w;\n sumsq += v.x*v.x + v.y*v.y + v.z*v.z + v.w*v.w;\n }\n // Remainder path for general shapes.\n for (int64_t i = (n4 << 2) + threadIdx.x; i < spatial; i += blockDim.x) {\n float v = base[i];\n sum += v;\n sumsq += v * v;\n }\n\n float total = block_reduce_sum(sum);\n float total2 = block_reduce_sum(sumsq);\n\n float mean = total / (float)spatial;\n float var = total2 / (float)spatial - mean * mean;\n var = fmaxf(var, 0.0f);\n float invstd = rsqrtf(var + 1.0e-5f);\n\n float4* o4 = reinterpret_cast<float4*>(out);\n for (int64_t i = threadIdx.x; i < n4; i += blockDim.x) {\n float4 v = b4[i];\n float4 r;\n r.x = (v.x - mean) * invstd;\n r.y = (v.y - mean) * invstd;\n r.z = (v.z - mean) * invstd;\n r.w = (v.w - mean) * invstd;\n o4[i] = r;\n }\n for (int64_t i = (n4 << 2) + threadIdx.x; i < spatial; i += blockDim.x) {\n out[i] = (base[i] - mean) * invstd;\n }\n}\n\ntorch::Tensor instance_norm_forward(torch::Tensor x) {\n CHECK_CUDA(x);\n CHECK_CONTIGUOUS(x);\n CHECK_FLOAT(x);\n TORCH_CHECK(x.dim() == 4, \"expected NCHW 4D tensor\");\n auto y = torch::empty_like(x);\n int64_t N = x.size(0);\n int64_t C = x.size(1);\n int64_t H = x.size(2);\n int64_t W = x.size(3);\n int64_t instances = N * C;\n int64_t spatial = H * W;\n if (instances == 0 || spatial == 0) return y;\n dim3 grid((unsigned int)instances);\n dim3 block(256);\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n inst_norm_kernel<<<grid, block, 0, stream>>>(x.data_ptr<float>(), y.data_ptr<float>(), instances, spatial);\n C10_CUDA_KERNEL_LAUNCH_CHECK();\n return y;\n}\n'''\n\n_ext = load_inline(\n name='instancenorm2d_custom_ext_v1',\n cpp_sources=[_cpp_src],\n cuda_sources=[_cuda_src],\n functions=['instance_norm_forward'],\n extra_cuda_cflags=['-O3', '--use_fast_math'],\n extra_cflags=['-O3'],\n verbose=False,\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, num_features: int):\n super(ModelNew, self).__init__()\n self.num_features = num_features\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n return _ext.instance_norm_forward(x)\n" }
result ← compile_kernel (fail)
failcompile_kernel compile_kernel FAILED: RuntimeError. RuntimeError: Error building extension 'instancenorm2d_custom_ext_v1': [1/3] /opt/conda/bin/x86_64-conda-linux-gnu-c++ -MMD -MF main.o.d -DTORCH_EXTENSION_NAME=instancenorm2d_custom_ext_v1 -DTORCH_API_INCLUDE_EXTENSION_H -isystem /scratch/tejas/PopcornBench/.venv/lib/python3.10/site-packages/torch/include -isystem /scratch/tejas/PopcornBench/.venv/lib/python3.10/site-packages/torch/include/torch/csrc/api/include -isystem /usr/local/cuda/include -isystem /home/prabhune/.local/share/uv/python/cpython-3.10-linux-x86_64-gnu/include/python3.10 -fPIC -std=c++17 -O3 -c /scratch/tejas/PopcornBench/runs/l12_default/original/gpt-5.5-priority/level_1_problem_34_cache/k_48ab83653430/instancenorm2d_custom_ext_v1/main.cpp -o main.o [2/3] /usr/local/cuda/bin/nvcc -MD -MF cuda.cuda.o.d -ccbin /opt/conda/bin/x86_64-conda-linux-gnu-cc -DTORCH_EXTENSION_NAME=instancenorm2d_custom_ext_v1 -DTORCH_API_INCLUDE_EXTENSION_H -isystem /scratch/tejas/PopcornBench/.venv/lib/python3.10/site-packages/torch/include -isystem /scratch/tejas/PopcornBench/.venv/lib/python3.10/site-packages/torch/include/torch/csrc/api/include -isystem /usr/local/cuda/include -isystem /home/prabhune/.local/share/uv/python/cpython-3.10-linux-x86_64-gnu/include/python3.10 -D__CUDA_NO_HALF_OPERATORS__ -D__CUDA_NO_HALF_CONVERSIONS__ -D__CUDA_NO_BFLOAT16_CONVERSIONS__ -D__CUDA_NO_HALF2_OPERATORS__ --expt-relaxed-constexpr -gencode=arch=compute_90,code=compute_90 -gencode=arch=compute_90,code=sm_90 --compiler-options '-fPIC' -O3 --use_fast_math -std=c++17 -c /scratch/tejas/PopcornBench/runs/l12_default/original/gpt-5.5-priority/level_1_problem_34_cache/k_48ab83653430/instancenorm2d_custom_ext_v1/cuda.cu -o cuda.cuda.o FAILED: [code=2] cuda.cuda.o /usr/local/cuda/bin/nvcc -MD -MF cuda.cuda.o.d -ccbin /opt/conda/bin/x86_64-conda-linux-gnu-cc -DTORCH_EXTENSION_NAME=instancenorm2d_custom_ext_v1 -DTORCH_API_INCLUDE_EXTENSION_H -isystem /scratch/tejas/PopcornBench/.venv/lib/python3.10/site-packages/torch/include -isystem /scratch/tejas/PopcornBench/.venv/lib/python3.10/site-packages/torch/include/torch/csrc/api/include -isystem /usr/local/cuda/include -isystem /home/prabhune/.local/share/uv/python/cpython-3.10-linux-x86_64-gnu/include/python3.10 -D__CUDA_NO_HALF_OPERATORS__ -D__CUDA_NO_HALF_CONVERSIONS__ -D__CUDA_NO_BFLOAT16_CONVERSIONS__ -D__CUDA_NO_HALF2_OPERATORS__ --expt-relaxed-constexpr -gencode=arch=compute_90,code=compute_90 -gencode=arch=compute_90,code=sm_90 --compiler-options '-fPIC' -O3 --use_fast_math -std=c++17 -c /scratch/tejas/PopcornBench/runs/l12_default/original/gpt-5.5-priority/level_1_problem_34_cache/k_48ab83653430/instancenorm2d_custom_ext_v1/cuda.cu -o cuda.cuda.o nvcc warning : incompatible redefinition for option 'compiler-bindir', the last value of this option was used /scratch/tejas/PopcornBench/runs/l12_default/original/gpt-5.5-priority/level_1_problem_34_cache/k_48ab83653430/instancenorm2d_custom_ext_v1/cuda.cu(100): error: namespace "at::cuda" has no member "getCurrentCUDAStream" cudaStream_t stream = at::cuda::getCurrentCUDAStream(); ^ /scratch/tejas/PopcornBench/runs/l12_default/original/gpt-5.5-priority/level_1_problem_34_cache/k_48ab83653430/instancenorm2d_custom_ext_v1/cuda.cu(102): error: identifier "C10_CUDA_KERNEL_LAUNCH_CHECK" is undefined C10_CUDA_KERNEL_LAUNCH_CHECK(); ^ 2 errors detected in the compilation of "/scratch/tejas/PopcornBench/runs/l12_default/original/gpt-5.5-priority/level_1_problem_34_cache/k_48ab83653430/instancenorm2d_custom_ext_v1/cuda.cu". ninja: build stopped: subcommand failed.
turn 210.3s turn · 10.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>\ntorch::Tensor instance_norm_forward(torch::Tensor x);\n'''\n\n_cuda_src = r'''\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <c10/cuda/CUDAException.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <stdint.h>\n\n#define CHECK_CUDA(x) TORCH_CHECK(x.is_cuda(), #x \" must be a CUDA tensor\")\n#define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x \" must be contiguous\")\n#define CHECK_FLOAT(x) TORCH_CHECK(x.scalar_type() == at::kFloat, #x \" must be float32\")\n\n__inline__ __device__ float warp_reduce_sum(float v) {\n #pragma unroll\n for (int offset = 16; offset > 0; offset >>= 1) v += __shfl_down_sync(0xffffffff, v, offset);\n return v;\n}\n\n__inline__ __device__ float block_reduce_sum(float v) {\n static __shared__ float shared[32];\n int lane = threadIdx.x & 31;\n int wid = threadIdx.x >> 5;\n v = warp_reduce_sum(v);\n if (lane == 0) shared[wid] = v;\n __syncthreads();\n v = (threadIdx.x < (blockDim.x >> 5)) ? shared[lane] : 0.0f;\n if (wid == 0) v = warp_reduce_sum(v);\n return v;\n}\n\n__global__ __launch_bounds__(256, 2)\nvoid inst_norm_kernel(const float* __restrict__ x, float* __restrict__ y,\n int64_t instances, int64_t spatial) {\n int inst = blockIdx.x;\n if ((int64_t)inst >= instances) return;\n const float* base = x + ((int64_t)inst) * spatial;\n float* out = y + ((int64_t)inst) * spatial;\n float sum = 0.0f, sumsq = 0.0f;\n int64_t n4 = spatial >> 2;\n const float4* b4 = reinterpret_cast<const float4*>(base);\n for (int64_t i = threadIdx.x; i < n4; i += blockDim.x) {\n float4 v = b4[i];\n sum += (v.x + v.y) + (v.z + v.w);\n sumsq += (v.x*v.x + v.y*v.y) + (v.z*v.z + v.w*v.w);\n }\n for (int64_t i = (n4 << 2) + threadIdx.x; i < spatial; i += blockDim.x) {\n float v = base[i]; sum += v; sumsq += v*v;\n }\n float total = block_reduce_sum(sum);\n float total2 = block_reduce_sum(sumsq);\n float mean = total / (float)spatial;\n float var = total2 / (float)spatial - mean * mean;\n var = fmaxf(var, 0.0f);\n float invstd = rsqrtf(var + 1.0e-5f);\n float4* o4 = reinterpret_cast<float4*>(out);\n for (int64_t i = threadIdx.x; i < n4; i += blockDim.x) {\n float4 v = b4[i];\n float4 r;\n r.x = (v.x - mean) * invstd;\n r.y = (v.y - mean) * invstd;\n r.z = (v.z - mean) * invstd;\n r.w = (v.w - mean) * invstd;\n o4[i] = r;\n }\n for (int64_t i = (n4 << 2) + threadIdx.x; i < spatial; i += blockDim.x) out[i] = (base[i] - mean) * invstd;\n}\n\ntorch::Tensor instance_norm_forward(torch::Tensor x) {\n CHECK_CUDA(x); CHECK_CONTIGUOUS(x); CHECK_FLOAT(x);\n TORCH_CHECK(x.dim() == 4, \"expected NCHW 4D tensor\");\n auto y = torch::empty_like(x);\n int64_t instances = x.size(0) * x.size(1);\n int64_t spatial = x.size(2) * x.size(3);\n if (instances == 0 || spatial == 0) return y;\n inst_norm_kernel<<<(unsigned int)instances, 256, 0, at::cuda::getCurrentCUDAStream()>>>(x.data_ptr<float>(), y.data_ptr<float>(), instances, spatial);\n C10_CUDA_KERNEL_LAUNCH_CHECK();\n return y;\n}\n'''\n\n_ext = load_inline(name='instancenorm2d_custom_ext_v2', cpp_sources=[_cpp_src], cuda_sources=[_cuda_src], functions=['instance_norm_forward'], extra_cuda_cflags=['-O3', '--use_fast_math'], extra_cflags=['-O3'], verbose=False)\n\nclass ModelNew(nn.Module):\n def __init__(self, num_features: int):\n super(ModelNew, self).__init__()\n self.num_features = num_features\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n return _ext.instance_norm_forward(x)\n" }
result ← compile_kernel (ok)
okcompile_kernel compile_kernel PASSED: kernel compiled without errors.
turn 38.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>\ntorch::Tensor instance_norm_forward(torch::Tensor x);\n'''\n\n_cuda_src = r'''\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <c10/cuda/CUDAException.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <stdint.h>\n\n#define CHECK_CUDA(x) TORCH_CHECK(x.is_cuda(), #x \" must be a CUDA tensor\")\n#define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x \" must be contiguous\")\n#define CHECK_FLOAT(x) TORCH_CHECK(x.scalar_type() == at::kFloat, #x \" must be float32\")\n\n__inline__ __device__ float warp_reduce_sum(float v) {\n #pragma unroll\n for (int offset = 16; offset > 0; offset >>= 1) v += __shfl_down_sync(0xffffffff, v, offset);\n return v;\n}\n\n__inline__ __device__ float block_reduce_sum(float v) {\n static __shared__ float shared[32];\n int lane = threadIdx.x & 31;\n int wid = threadIdx.x >> 5;\n v = warp_reduce_sum(v);\n if (lane == 0) shared[wid] = v;\n __syncthreads();\n v = (threadIdx.x < (blockDim.x >> 5)) ? shared[lane] : 0.0f;\n if (wid == 0) v = warp_reduce_sum(v);\n return v;\n}\n\n__global__ __launch_bounds__(256, 2)\nvoid inst_norm_kernel(const float* __restrict__ x, float* __restrict__ y,\n int64_t instances, int64_t spatial) {\n int inst = blockIdx.x;\n if ((int64_t)inst >= instances) return;\n const float* base = x + ((int64_t)inst) * spatial;\n float* out = y + ((int64_t)inst) * spatial;\n float sum = 0.0f, sumsq = 0.0f;\n int64_t n4 = spatial >> 2;\n const float4* b4 = reinterpret_cast<const float4*>(base);\n for (int64_t i = threadIdx.x; i < n4; i += blockDim.x) {\n float4 v = b4[i];\n sum += (v.x + v.y) + (v.z + v.w);\n sumsq += (v.x*v.x + v.y*v.y) + (v.z*v.z + v.w*v.w);\n }\n for (int64_t i = (n4 << 2) + threadIdx.x; i < spatial; i += blockDim.x) {\n float v = base[i]; sum += v; sumsq += v*v;\n }\n float total = block_reduce_sum(sum);\n float total2 = block_reduce_sum(sumsq);\n float mean = total / (float)spatial;\n float var = total2 / (float)spatial - mean * mean;\n var = fmaxf(var, 0.0f);\n float invstd = rsqrtf(var + 1.0e-5f);\n float4* o4 = reinterpret_cast<float4*>(out);\n for (int64_t i = threadIdx.x; i < n4; i += blockDim.x) {\n float4 v = b4[i];\n float4 r;\n r.x = (v.x - mean) * invstd;\n r.y = (v.y - mean) * invstd;\n r.z = (v.z - mean) * invstd;\n r.w = (v.w - mean) * invstd;\n o4[i] = r;\n }\n for (int64_t i = (n4 << 2) + threadIdx.x; i < spatial; i += blockDim.x) out[i] = (base[i] - mean) * invstd;\n}\n\ntorch::Tensor instance_norm_forward(torch::Tensor x) {\n CHECK_CUDA(x); CHECK_CONTIGUOUS(x); CHECK_FLOAT(x);\n TORCH_CHECK(x.dim() == 4, \"expected NCHW 4D tensor\");\n auto y = torch::empty_like(x);\n int64_t instances = x.size(0) * x.size(1);\n int64_t spatial = x.size(2) * x.size(3);\n if (instances == 0 || spatial == 0) return y;\n inst_norm_kernel<<<(unsigned int)instances, 256, 0, at::cuda::getCurrentCUDAStream()>>>(x.data_ptr<float>(), y.data_ptr<float>(), instances, spatial);\n C10_CUDA_KERNEL_LAUNCH_CHECK();\n return y;\n}\n'''\n\n_ext = load_inline(name='instancenorm2d_custom_ext_v2', cpp_sources=[_cpp_src], cuda_sources=[_cuda_src], functions=['instance_norm_forward'], extra_cuda_cflags=['-O3', '--use_fast_math'], extra_cflags=['-O3'], verbose=False)\n\nclass ModelNew(nn.Module):\n def __init__(self, num_features: int):\n super(ModelNew, self).__init__()\n self.num_features = num_features\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n return _ext.instance_norm_forward(x)\n" }
result ← run_correctness (fail)
failrun_correctness run_correctness FAILED: (0 / 5) trials did not all match. correctness_issue: Output mismatch max_difference: ['314.504242', '314.504517', '314.503784', '314.503326', '314.504669'] avg_difference: ['153.195389', '153.195374', '153.197968', '153.199326', '153.196716']
turn 413.0s turn · 13.0s 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>\ntorch::Tensor instance_norm_forward(torch::Tensor x);\n'''\n\n_cuda_src = r'''\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <c10/cuda/CUDAException.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <stdint.h>\n#define CHECK_CUDA(x) TORCH_CHECK(x.is_cuda(), #x \" must be a CUDA tensor\")\n#define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x \" must be contiguous\")\n#define CHECK_FLOAT(x) TORCH_CHECK(x.scalar_type() == at::kFloat, #x \" must be float32\")\n\n__inline__ __device__ float warp_reduce_sum(float v) {\n #pragma unroll\n for (int offset = 16; offset > 0; offset >>= 1) v += __shfl_down_sync(0xffffffff, v, offset);\n return v;\n}\n\n__inline__ __device__ float block_reduce_sum(float v) {\n __shared__ float shared[32];\n int lane = threadIdx.x & 31;\n int wid = threadIdx.x >> 5;\n v = warp_reduce_sum(v);\n if (lane == 0) shared[wid] = v;\n __syncthreads();\n v = (threadIdx.x < (blockDim.x >> 5)) ? shared[lane] : 0.0f;\n if (wid == 0) v = warp_reduce_sum(v);\n if (threadIdx.x == 0) shared[0] = v;\n __syncthreads();\n return shared[0];\n}\n\n__global__ __launch_bounds__(256, 2)\nvoid inst_norm_kernel(const float* __restrict__ x, float* __restrict__ y,\n int64_t instances, int64_t spatial) {\n int inst = blockIdx.x;\n const float* base = x + ((int64_t)inst) * spatial;\n float* out = y + ((int64_t)inst) * spatial;\n float sum = 0.0f, sumsq = 0.0f;\n int64_t n4 = spatial >> 2;\n const float4* b4 = reinterpret_cast<const float4*>(base);\n for (int64_t i = threadIdx.x; i < n4; i += blockDim.x) {\n float4 v = b4[i];\n sum += (v.x + v.y) + (v.z + v.w);\n sumsq += (v.x*v.x + v.y*v.y) + (v.z*v.z + v.w*v.w);\n }\n for (int64_t i = (n4 << 2) + threadIdx.x; i < spatial; i += blockDim.x) { float v = base[i]; sum += v; sumsq += v*v; }\n float total = block_reduce_sum(sum);\n float total2 = block_reduce_sum(sumsq);\n float mean = total / (float)spatial;\n float var = total2 / (float)spatial - mean * mean;\n var = fmaxf(var, 0.0f);\n float invstd = rsqrtf(var + 1.0e-5f);\n float4* o4 = reinterpret_cast<float4*>(out);\n for (int64_t i = threadIdx.x; i < n4; i += blockDim.x) {\n float4 v = b4[i];\n o4[i] = make_float4((v.x-mean)*invstd, (v.y-mean)*invstd, (v.z-mean)*invstd, (v.w-mean)*invstd);\n }\n for (int64_t i = (n4 << 2) + threadIdx.x; i < spatial; i += blockDim.x) out[i] = (base[i]-mean)*invstd;\n}\n\ntorch::Tensor instance_norm_forward(torch::Tensor x) {\n CHECK_CUDA(x); CHECK_CONTIGUOUS(x); CHECK_FLOAT(x); TORCH_CHECK(x.dim()==4, \"expected NCHW 4D tensor\");\n auto y = torch::empty_like(x);\n int64_t instances = x.size(0)*x.size(1), spatial = x.size(2)*x.size(3);\n if (instances == 0 || spatial == 0) return y;\n inst_norm_kernel<<<(unsigned int)instances, 256, 0, at::cuda::getCurrentCUDAStream()>>>(x.data_ptr<float>(), y.data_ptr<float>(), instances, spatial);\n C10_CUDA_KERNEL_LAUNCH_CHECK();\n return y;\n}\n'''\n_ext = load_inline(name='instancenorm2d_custom_ext_v3', cpp_sources=[_cpp_src], cuda_sources=[_cuda_src], functions=['instance_norm_forward'], extra_cuda_cflags=['-O3','--use_fast_math'], extra_cflags=['-O3'], verbose=False)\nclass ModelNew(nn.Module):\n def __init__(self, num_features: int):\n super(ModelNew, self).__init__(); self.num_features=num_features\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n return _ext.instance_norm_forward(x)\n" }
result ← run_correctness (ok)
okrun_correctness run_correctness PASSED: (5 / 5) trials all matched the reference. Numerical precision: max_abs_err=1.79e-06 mean_abs_err=1.37e-07 max_rel_err=4.13e+05
turn 518.3s turn · 18.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>\ntorch::Tensor instance_norm_forward(torch::Tensor x);\n'''\n\n_cuda_src = r'''\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <c10/cuda/CUDAException.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <stdint.h>\n#define CHECK_CUDA(x) TORCH_CHECK(x.is_cuda(), #x \" must be a CUDA tensor\")\n#define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x \" must be contiguous\")\n#define CHECK_FLOAT(x) TORCH_CHECK(x.scalar_type() == at::kFloat, #x \" must be float32\")\n\n__inline__ __device__ float warp_sum(float v) {\n #pragma unroll\n for (int o = 16; o > 0; o >>= 1) v += __shfl_down_sync(0xffffffff, v, o);\n return v;\n}\n\n__inline__ __device__ void block_reduce_pair(float &a, float &b) {\n __shared__ float sh_a[32];\n __shared__ float sh_b[32];\n int lane = threadIdx.x & 31;\n int wid = threadIdx.x >> 5;\n a = warp_sum(a);\n b = warp_sum(b);\n if (lane == 0) { sh_a[wid] = a; sh_b[wid] = b; }\n __syncthreads();\n a = (threadIdx.x < (blockDim.x >> 5)) ? sh_a[lane] : 0.0f;\n b = (threadIdx.x < (blockDim.x >> 5)) ? sh_b[lane] : 0.0f;\n if (wid == 0) { a = warp_sum(a); b = warp_sum(b); }\n if (threadIdx.x == 0) { sh_a[0] = a; sh_b[0] = b; }\n __syncthreads();\n a = sh_a[0]; b = sh_b[0];\n}\n\n__global__ __launch_bounds__(256, 2)\nvoid inst_norm_kernel(const float* __restrict__ x, float* __restrict__ y,\n int instances, int spatial) {\n int inst = blockIdx.x;\n int offset = inst * spatial;\n const float* base = x + offset;\n float* out = y + offset;\n float sum = 0.0f, sumsq = 0.0f;\n int n4 = spatial >> 2;\n const float4* __restrict__ b4 = reinterpret_cast<const float4*>(base);\n for (int i = threadIdx.x; i < n4; i += blockDim.x) {\n float4 v = b4[i];\n float s = (v.x + v.y) + (v.z + v.w);\n sum += s;\n sumsq += fmaf(v.x, v.x, fmaf(v.y, v.y, fmaf(v.z, v.z, v.w*v.w)));\n }\n for (int i = (n4 << 2) + threadIdx.x; i < spatial; i += blockDim.x) { float v = base[i]; sum += v; sumsq = fmaf(v, v, sumsq); }\n block_reduce_pair(sum, sumsq);\n float mean = sum / (float)spatial;\n float var = sumsq / (float)spatial - mean * mean;\n float invstd = rsqrtf(fmaxf(var, 0.0f) + 1.0e-5f);\n float4* __restrict__ o4 = reinterpret_cast<float4*>(out);\n for (int i = threadIdx.x; i < n4; i += blockDim.x) {\n float4 v = b4[i];\n o4[i] = make_float4((v.x-mean)*invstd, (v.y-mean)*invstd, (v.z-mean)*invstd, (v.w-mean)*invstd);\n }\n for (int i = (n4 << 2) + threadIdx.x; i < spatial; i += blockDim.x) out[i] = (base[i]-mean)*invstd;\n}\n\ntorch::Tensor instance_norm_forward(torch::Tensor x) {\n CHECK_CUDA(x); CHECK_CONTIGUOUS(x); CHECK_FLOAT(x); TORCH_CHECK(x.dim()==4, \"expected NCHW 4D tensor\");\n auto y = torch::empty_like(x);\n int64_t inst64 = x.size(0)*x.size(1), sp64 = x.size(2)*x.size(3);\n if (inst64 == 0 || sp64 == 0) return y;\n TORCH_CHECK(inst64 <= INT_MAX && sp64 <= INT_MAX && x.numel() <= (int64_t)INT_MAX * 4LL, \"unsupported size\");\n inst_norm_kernel<<<(unsigned int)inst64, 256, 0, at::cuda::getCurrentCUDAStream()>>>(x.data_ptr<float>(), y.data_ptr<float>(), (int)inst64, (int)sp64);\n C10_CUDA_KERNEL_LAUNCH_CHECK();\n return y;\n}\n'''\n_ext = load_inline(name='instancenorm2d_custom_ext_v4', cpp_sources=[_cpp_src], cuda_sources=[_cuda_src], functions=['instance_norm_forward'], extra_cuda_cflags=['-O3','--use_fast_math'], extra_cflags=['-O3'], verbose=False)\nclass ModelNew(nn.Module):\n def __init__(self, num_features: int):\n super(ModelNew, self).__init__(); self.num_features=num_features\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n return _ext.instance_norm_forward(x)\n" }
result ← run_correctness (ok)
okrun_correctness run_correctness PASSED: (5 / 5) trials all matched the reference. Numerical precision: max_abs_err=1.79e-06 mean_abs_err=1.38e-07 max_rel_err=4.13e+05
turn 617.7s turn · 17.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>\ntorch::Tensor instance_norm_forward(torch::Tensor x);\n'''\n\n_cuda_src = r'''\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <c10/cuda/CUDAException.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <stdint.h>\n#define CHECK_CUDA(x) TORCH_CHECK(x.is_cuda(), #x \" must be a CUDA tensor\")\n#define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x \" must be contiguous\")\n#define CHECK_FLOAT(x) TORCH_CHECK(x.scalar_type() == at::kFloat, #x \" must be float32\")\n\n__inline__ __device__ float warp_sum(float v) {\n #pragma unroll\n for (int o = 16; o > 0; o >>= 1) v += __shfl_down_sync(0xffffffff, v, o);\n return v;\n}\n\n__inline__ __device__ void block_reduce_pair(float &a, float &b) {\n __shared__ float sh_a[32];\n __shared__ float sh_b[32];\n int lane = threadIdx.x & 31;\n int wid = threadIdx.x >> 5;\n a = warp_sum(a);\n b = warp_sum(b);\n if (lane == 0) { sh_a[wid] = a; sh_b[wid] = b; }\n __syncthreads();\n a = (threadIdx.x < (blockDim.x >> 5)) ? sh_a[lane] : 0.0f;\n b = (threadIdx.x < (blockDim.x >> 5)) ? sh_b[lane] : 0.0f;\n if (wid == 0) { a = warp_sum(a); b = warp_sum(b); }\n if (threadIdx.x == 0) { sh_a[0] = a; sh_b[0] = b; }\n __syncthreads();\n a = sh_a[0]; b = sh_b[0];\n}\n\n__global__ __launch_bounds__(256, 2)\nvoid inst_norm_kernel(const float* __restrict__ x, float* __restrict__ y,\n int instances, int spatial) {\n int inst = blockIdx.x;\n int offset = inst * spatial;\n const float* base = x + offset;\n float* out = y + offset;\n float sum = 0.0f, sumsq = 0.0f;\n int n4 = spatial >> 2;\n const float4* __restrict__ b4 = reinterpret_cast<const float4*>(base);\n for (int i = threadIdx.x; i < n4; i += blockDim.x) {\n float4 v = b4[i];\n float s = (v.x + v.y) + (v.z + v.w);\n sum += s;\n sumsq += fmaf(v.x, v.x, fmaf(v.y, v.y, fmaf(v.z, v.z, v.w*v.w)));\n }\n for (int i = (n4 << 2) + threadIdx.x; i < spatial; i += blockDim.x) { float v = base[i]; sum += v; sumsq = fmaf(v, v, sumsq); }\n block_reduce_pair(sum, sumsq);\n float mean = sum / (float)spatial;\n float var = sumsq / (float)spatial - mean * mean;\n float invstd = rsqrtf(fmaxf(var, 0.0f) + 1.0e-5f);\n float4* __restrict__ o4 = reinterpret_cast<float4*>(out);\n for (int i = threadIdx.x; i < n4; i += blockDim.x) {\n float4 v = b4[i];\n o4[i] = make_float4((v.x-mean)*invstd, (v.y-mean)*invstd, (v.z-mean)*invstd, (v.w-mean)*invstd);\n }\n for (int i = (n4 << 2) + threadIdx.x; i < spatial; i += blockDim.x) out[i] = (base[i]-mean)*invstd;\n}\n\ntorch::Tensor instance_norm_forward(torch::Tensor x) {\n CHECK_CUDA(x); CHECK_CONTIGUOUS(x); CHECK_FLOAT(x); TORCH_CHECK(x.dim()==4, \"expected NCHW 4D tensor\");\n auto y = torch::empty_like(x);\n int64_t inst64 = x.size(0)*x.size(1), sp64 = x.size(2)*x.size(3);\n if (inst64 == 0 || sp64 == 0) return y;\n TORCH_CHECK(inst64 <= INT_MAX && sp64 <= INT_MAX && x.numel() <= (int64_t)INT_MAX * 4LL, \"unsupported size\");\n inst_norm_kernel<<<(unsigned int)inst64, 256, 0, at::cuda::getCurrentCUDAStream()>>>(x.data_ptr<float>(), y.data_ptr<float>(), (int)inst64, (int)sp64);\n C10_CUDA_KERNEL_LAUNCH_CHECK();\n return y;\n}\n'''\n_ext = load_inline(name='instancenorm2d_custom_ext_v4final', cpp_sources=[_cpp_src], cuda_sources=[_cuda_src], functions=['instance_norm_forward'], extra_cuda_cflags=['-O3','--use_fast_math'], extra_cflags=['-O3'], verbose=False)\nclass ModelNew(nn.Module):\n def __init__(self, num_features: int):\n super(ModelNew, self).__init__(); self.num_features=num_features\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n return _ext.instance_norm_forward(x)\n" }
result ← static_check (ok)
okstatic_check static_check PASSED: no violations or warnings detected.
turn 79.8s turn · 9.8s LLM · 0.0s tools · FINAL
reasoning
**Considering submission correctness** I’m thinking I could submit my response, but maybe I should double-check the correctness of the fmaf function. Ultimately, I need to prepare the final answer for the submission through the kernel tool with the appropriate code. I realize the final response can actually be pretty brief, which is helpful. Once I confirm everything looks good, I can go ahead and submit!
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>\ntorch::Tensor instance_norm_forward(torch::Tensor x);\n'''\n\n_cuda_src = r'''\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <c10/cuda/CUDAException.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <stdint.h>\n#define CHECK_CUDA(x) TORCH_CHECK(x.is_cuda(), #x \" must be a CUDA tensor\")\n#define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x \" must be contiguous\")\n#define CHECK_FLOAT(x) TORCH_CHECK(x.scalar_type() == at::kFloat, #x \" must be float32\")\n\n__inline__ __device__ float warp_sum(float v) {\n #pragma unroll\n for (int o = 16; o > 0; o >>= 1) v += __shfl_down_sync(0xffffffff, v, o);\n return v;\n}\n\n__inline__ __device__ void block_reduce_pair(float &a, float &b) {\n __shared__ float sh_a[32];\n __shared__ float sh_b[32];\n int lane = threadIdx.x & 31;\n int wid = threadIdx.x >> 5;\n a = warp_sum(a);\n b = warp_sum(b);\n if (lane == 0) { sh_a[wid] = a; sh_b[wid] = b; }\n __syncthreads();\n a = (threadIdx.x < (blockDim.x >> 5)) ? sh_a[lane] : 0.0f;\n b = (threadIdx.x < (blockDim.x >> 5)) ? sh_b[lane] : 0.0f;\n if (wid == 0) { a = warp_sum(a); b = warp_sum(b); }\n if (threadIdx.x == 0) { sh_a[0] = a; sh_b[0] = b; }\n __syncthreads();\n a = sh_a[0]; b = sh_b[0];\n}\n\n__global__ __launch_bounds__(256, 2)\nvoid inst_norm_kernel(const float* __restrict__ x, float* __restrict__ y,\n int instances, int spatial) {\n int inst = blockIdx.x;\n int offset = inst * spatial;\n const float* base = x + offset;\n float* out = y + offset;\n float sum = 0.0f, sumsq = 0.0f;\n int n4 = spatial >> 2;\n const float4* __restrict__ b4 = reinterpret_cast<const float4*>(base);\n for (int i = threadIdx.x; i < n4; i += blockDim.x) {\n float4 v = b4[i];\n float s = (v.x + v.y) + (v.z + v.w);\n sum += s;\n sumsq += fmaf(v.x, v.x, fmaf(v.y, v.y, fmaf(v.z, v.z, v.w*v.w)));\n }\n for (int i = (n4 << 2) + threadIdx.x; i < spatial; i += blockDim.x) {\n float v = base[i];\n sum += v;\n sumsq = fmaf(v, v, sumsq);\n }\n block_reduce_pair(sum, sumsq);\n float mean = sum / (float)spatial;\n float var = sumsq / (float)spatial - mean * mean;\n float invstd = rsqrtf(fmaxf(var, 0.0f) + 1.0e-5f);\n float4* __restrict__ o4 = reinterpret_cast<float4*>(out);\n for (int i = threadIdx.x; i < n4; i += blockDim.x) {\n float4 v = b4[i];\n o4[i] = make_float4((v.x-mean)*invstd, (v.y-mean)*invstd, (v.z-mean)*invstd, (v.w-mean)*invstd);\n }\n for (int i = (n4 << 2) + threadIdx.x; i < spatial; i += blockDim.x) {\n out[i] = (base[i]-mean)*invstd;\n }\n}\n\ntorch::Tensor instance_norm_forward(torch::Tensor x) {\n CHECK_CUDA(x); CHECK_CONTIGUOUS(x); CHECK_FLOAT(x);\n TORCH_CHECK(x.dim()==4, \"expected NCHW 4D tensor\");\n auto y = torch::empty_like(x);\n int64_t inst64 = x.size(0)*x.size(1), sp64 = x.size(2)*x.size(3);\n if (inst64 == 0 || sp64 == 0) return y;\n TORCH_CHECK(inst64 <= INT_MAX && sp64 <= INT_MAX && x.numel() <= (int64_t)INT_MAX * 4LL, \"unsupported size\");\n inst_norm_kernel<<<(unsigned int)inst64, 256, 0, at::cuda::getCurrentCUDAStream()>>>(x.data_ptr<float>(), y.data_ptr<float>(), (int)inst64, (int)sp64);\n C10_CUDA_KERNEL_LAUNCH_CHECK();\n return y;\n}\n'''\n_ext = load_inline(name='instancenorm2d_custom_ext_final', cpp_sources=[_cpp_src], cuda_sources=[_cuda_src], functions=['instance_norm_forward'], extra_cuda_cflags=['-O3','--use_fast_math'], extra_cflags=['-O3'], verbose=False)\nclass ModelNew(nn.Module):\n def __init__(self, num_features: int):\n super(ModelNew, self).__init__()\n self.num_features = num_features\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n return _ext.instance_norm_forward(x)\n" }
result ← submit_kernel (ok)
oksubmit_kernel submit_kernel PASSED: (5 / 5) correctness trials all passed. Kernel runtime: 10.90 μs Runtime stats: mean=10.90μs median=?μs std=29.60μs Numerical precision: max_abs_err=1.79e-06 mean_abs_err=1.38e-07 max_rel_err=4.13e+05 Memory: 14369.0 MB peak (ref: 14369.05 MB, ratio: 1.0x) Kernel launches: 2 (ref: 16, fusion ratio: 8.0) Energy: 3913.76 mJ/run (ref: 5145.36 mJ, ratio: 1.3147x) SOL score: 0.8727
final submitted kernel (98 lines, 3,883 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 instance_norm_forward(torch::Tensor x);
'''

_cuda_src = r'''
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAException.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <stdint.h>
#define CHECK_CUDA(x) TORCH_CHECK(x.is_cuda(), #x " must be a CUDA tensor")
#define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be contiguous")
#define CHECK_FLOAT(x) TORCH_CHECK(x.scalar_type() == at::kFloat, #x " must be float32")

__inline__ __device__ float warp_sum(float v) {
    #pragma unroll
    for (int o = 16; o > 0; o >>= 1) v += __shfl_down_sync(0xffffffff, v, o);
    return v;
}

__inline__ __device__ void block_reduce_pair(float &a, float &b) {
    __shared__ float sh_a[32];
    __shared__ float sh_b[32];
    int lane = threadIdx.x & 31;
    int wid = threadIdx.x >> 5;
    a = warp_sum(a);
    b = warp_sum(b);
    if (lane == 0) { sh_a[wid] = a; sh_b[wid] = b; }
    __syncthreads();
    a = (threadIdx.x < (blockDim.x >> 5)) ? sh_a[lane] : 0.0f;
    b = (threadIdx.x < (blockDim.x >> 5)) ? sh_b[lane] : 0.0f;
    if (wid == 0) { a = warp_sum(a); b = warp_sum(b); }
    if (threadIdx.x == 0) { sh_a[0] = a; sh_b[0] = b; }
    __syncthreads();
    a = sh_a[0]; b = sh_b[0];
}

__global__ __launch_bounds__(256, 2)
void inst_norm_kernel(const float* __restrict__ x, float* __restrict__ y,
                      int instances, int spatial) {
    int inst = blockIdx.x;
    int offset = inst * spatial;
    const float* base = x + offset;
    float* out = y + offset;
    float sum = 0.0f, sumsq = 0.0f;
    int n4 = spatial >> 2;
    const float4* __restrict__ b4 = reinterpret_cast<const float4*>(base);
    for (int i = threadIdx.x; i < n4; i += blockDim.x) {
        float4 v = b4[i];
        float s = (v.x + v.y) + (v.z + v.w);
        sum += s;
        sumsq += fmaf(v.x, v.x, fmaf(v.y, v.y, fmaf(v.z, v.z, v.w*v.w)));
    }
    for (int i = (n4 << 2) + threadIdx.x; i < spatial; i += blockDim.x) {
        float v = base[i];
        sum += v;
        sumsq = fmaf(v, v, sumsq);
    }
    block_reduce_pair(sum, sumsq);
    float mean = sum / (float)spatial;
    float var = sumsq / (float)spatial - mean * mean;
    float invstd = rsqrtf(fmaxf(var, 0.0f) + 1.0e-5f);
    float4* __restrict__ o4 = reinterpret_cast<float4*>(out);
    for (int i = threadIdx.x; i < n4; i += blockDim.x) {
        float4 v = b4[i];
        o4[i] = make_float4((v.x-mean)*invstd, (v.y-mean)*invstd, (v.z-mean)*invstd, (v.w-mean)*invstd);
    }
    for (int i = (n4 << 2) + threadIdx.x; i < spatial; i += blockDim.x) {
        out[i] = (base[i]-mean)*invstd;
    }
}

torch::Tensor instance_norm_forward(torch::Tensor x) {
    CHECK_CUDA(x); CHECK_CONTIGUOUS(x); CHECK_FLOAT(x);
    TORCH_CHECK(x.dim()==4, "expected NCHW 4D tensor");
    auto y = torch::empty_like(x);
    int64_t inst64 = x.size(0)*x.size(1), sp64 = x.size(2)*x.size(3);
    if (inst64 == 0 || sp64 == 0) return y;
    TORCH_CHECK(inst64 <= INT_MAX && sp64 <= INT_MAX && x.numel() <= (int64_t)INT_MAX * 4LL, "unsupported size");
    inst_norm_kernel<<<(unsigned int)inst64, 256, 0, at::cuda::getCurrentCUDAStream()>>>(x.data_ptr<float>(), y.data_ptr<float>(), (int)inst64, (int)sp64);
    C10_CUDA_KERNEL_LAUNCH_CHECK();
    return y;
}
'''
_ext = load_inline(name='instancenorm2d_custom_ext_final', cpp_sources=[_cpp_src], cuda_sources=[_cuda_src], functions=['instance_norm_forward'], extra_cuda_cflags=['-O3','--use_fast_math'], extra_cflags=['-O3'], verbose=False)
class ModelNew(nn.Module):
    def __init__(self, num_features: int):
        super(ModelNew, self).__init__()
        self.num_features = num_features
    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return _ext.instance_norm_forward(x)