import torch
import torch.nn as nn
import torch.nn.functional as F
def module_fn(
x: torch.Tensor,
linear_weight: torch.Tensor,
linear_bias: torch.Tensor,
constant: torch.Tensor,
) -> torch.Tensor:
"""
Performs matrix multiplication, applies minimum with constant, and subtracts constant.
Args:
x (torch.Tensor): Input tensor of shape (batch_size, in_features)
linear_weight (torch.Tensor): Weight matrix of shape (out_features, in_features)
linear_bias (torch.Tensor): Bias vector of shape (out_features)
constant (torch.Tensor): Scalar constant tensor
Returns:
torch.Tensor: Output tensor of shape (batch_size, out_features)
"""
x = F.linear(x, linear_weight, linear_bias)
x = torch.min(x, constant)
x = x - constant
return x
class Model(nn.Module):
"""
Simple model that performs a matrix multiplication, applies minimum, and subtracts a constant.
"""
def __init__(self, in_features, out_features, constant):
super(Model, self).__init__()
gemm = nn.Linear(in_features, out_features)
self.linear_weight = nn.Parameter(gemm.weight)
self.linear_bias = nn.Parameter(gemm.bias)
self.constant = nn.Parameter(torch.tensor(constant))
def forward(self, x, fn=module_fn):
return fn(x, self.linear_weight, self.linear_bias, self.constant)
batch_size = 128
in_features = 10
out_features = 5
constant = 2.0
def get_inputs():
return [torch.randn(batch_size, in_features)]
def get_init_inputs():
return [in_features, out_features, constant]
import torch
import torch.nn as nn
class Model(nn.Module):
"""
Simple model that performs a matrix multiplication, applies minimum, and subtracts a constant.
"""
def __init__(self, in_features, out_features, constant):
super(Model, self).__init__()
self.linear = nn.Linear(in_features, out_features)
self.constant = nn.Parameter(torch.tensor(constant))
def forward(self, x):
x = self.linear(x)
x = torch.min(x, self.constant)
x = x - self.constant
return x
batch_size = 128
in_features = 10
out_features = 5
constant = 2.0
def get_inputs():
return [torch.randn(batch_size, in_features)]
def get_init_inputs():
return [in_features, out_features, constant]
Operation Name | 68_Matmul_Min_Subtract |
Level ID | 2 |
Task ID | 68 |
Kernel Name | grid_2d_mapping_edit_1 |
CUDA Speedup (Native) | 2.947x |
CUDA Speedup (Compile) | 1.920x |
CUDA Runtime | 0.008 ms |
PyTorch Runtime (Native) | 0.024 ms |
PyTorch Runtime (Compile) | 0.015 ms |
Correct | True |
Max Diff (vs. Reference) | 0.000000 |
Model | o3-mini-2025-01-31 |
Temperature | 0.00 |
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
// 2D indexed kernel: Each thread computes one element of the output matrix.
__global__ void kernel_2d(
const float* __restrict__ x,
const float* __restrict__ linear_weight,
const float* __restrict__ linear_bias,
const float* __restrict__ constant,
float* __restrict__ y,
int batch_size,
int in_features,
int out_features) {
// Map thread indices to matrix coordinates
int o = blockIdx.x * blockDim.x + threadIdx.x; // output feature index
int b = blockIdx.y * blockDim.y + threadIdx.y; // batch index
if (b < batch_size && o < out_features) {
float dot = 0.0f;
int j = 0;
// Unroll loop for better performance when in_features is divisible by 4
for (; j <= in_features - 4; j += 4) {
dot += x[b * in_features + j] * linear_weight[o * in_features + j];
dot += x[b * in_features + j + 1] * linear_weight[o * in_features + j + 1];
dot += x[b * in_features + j + 2] * linear_weight[o * in_features + j + 2];
dot += x[b * in_features + j + 3] * linear_weight[o * in_features + j + 3];
}
// Handle remaining elements
for (; j < in_features; j++) {
dot += x[b * in_features + j] * linear_weight[o * in_features + j];
}
float bias = linear_bias[o];
const float c = constant[0];
dot = fminf(dot + bias, c) - c;
y[b * out_features + o] = dot;
}
}
// Forward function to launch the kernel
torch::Tensor forward(
torch::Tensor x,
torch::Tensor linear_weight,
torch::Tensor linear_bias,
torch::Tensor constant) {
TORCH_CHECK(x.is_cuda(), "x must be a CUDA tensor");
TORCH_CHECK(linear_weight.is_cuda(), "linear_weight must be a CUDA tensor");
TORCH_CHECK(linear_bias.is_cuda(), "linear_bias must be a CUDA tensor");
TORCH_CHECK(constant.is_cuda(), "constant must be a CUDA tensor");
int batch_size = x.size(0);
int in_features = x.size(1);
int out_features = linear_weight.size(0);
auto y = torch::zeros({batch_size, out_features}, x.options());
const float* x_ptr = x.data_ptr<float>();
const float* weight_ptr = linear_weight.data_ptr<float>();
const float* bias_ptr = linear_bias.data_ptr<float>();
const float* constant_ptr = constant.data_ptr<float>();
float* y_ptr = y.data_ptr<float>();
// Use a 2D block mapping to naturally cover the output matrix dimensions
dim3 block(16, 16);
dim3 grid((out_features + block.x - 1) / block.x, (batch_size + block.y - 1) / block.y);
kernel_2d<<<grid, block>>>(
x_ptr,
weight_ptr,
bias_ptr,
constant_ptr,
y_ptr,
batch_size,
in_features,
out_features);
return y;
}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
m.def("forward", &forward, "CUDA 2D grid indexed forward function");
}
Metric | Value | Unit | Variance | Samples |
---|---|---|---|---|
Executed Ipc Active | 0.358 | inst/cycle | 0.001 | 5 |
Executed Ipc Elapsed | 0.010 | inst/cycle | 0.000 | 5 |
Issue Slots Busy | 9.572 | % | 0.366 | 5 |
Issued Ipc Active | 0.384 | inst/cycle | 0.001 | 5 |
SM Busy | 9.572 | % | 0.366 | 5 |
Memory Throughput | 3066496466.170 | byte/second | 5477903584795605.000 | 5 |
Mem Busy | 7.842 | % | 0.036 | 5 |
Max Bandwidth | 4.056 | % | 0.009 | 5 |
L1/TEX Hit Rate | 94.304 | % | 0.002 | 5 |
L2 Hit Rate | 102.864 | % | 0.030 | 5 |
Mem Pipes Busy | 0.194 | % | 0.000 | 5 |
Warp Cycles Per Issued Instruction | 20.864 | cycle | 1.469 | 5 |
Warp Cycles Per Executed Instruction | 22.286 | cycle | 1.673 | 5 |
Avg. Active Threads Per Warp | 12.150 | 0.000 | 5 | |
Avg. Not Predicated Off Threads Per Warp | 11.660 | 0.000 | 5 | |
Max Active Clusters | 0.000 | cluster | 0.000 | 5 |
Max Cluster Size | 8.000 | block | 0.000 | 5 |
Overall GPU Occupancy | 0.000 | % | 0.000 | 5 |
Cluster Occupancy | 0.000 | % | 0.000 | 5 |
Block Limit SM | 32.000 | block | 0.000 | 5 |
Block Limit Registers | 8.000 | block | 0.000 | 5 |
Block Limit Shared Mem | 32.000 | block | 0.000 | 5 |
Block Limit Warps | 8.000 | block | 0.000 | 5 |
Theoretical Active Warps per SM | 64.000 | warp | 0.000 | 5 |
Theoretical Occupancy | 100.000 | % | 0.000 | 5 |
Achieved Occupancy | 12.452 | % | 0.000 | 5 |
Achieved Active Warps Per SM | 7.970 | warp | 0.000 | 5 |
Rule | Description |
---|---|
WRN HighPipeUtilization | All compute pipelines are under-utilized. Either this kernel is very small or it doesn't issue enough warps per scheduler. Check the Launch Statistics and Scheduler Statistics sections for further details. |
INF CPIStall | Check the Warp Stall Sampling (All Cycles) table for the top stall locations in your source based on sampling data. The Kernel Profiling Guide (https://docs.nvidia.com/nsight-compute/ProfilingGuide/index.html#metrics-reference) provides more details on each stall reason. |
WRN ThreadDivergence | Instructions are executed in warps, which are groups of 32 threads. Optimal instruction throughput is achieved if all 32 threads of a warp execute the same instruction. The chosen launch configuration, early thread completion, and divergent flow control can significantly lower the number of active threads in a warp per cycle. This kernel achieves an average of 12.2 threads being active per cycle. This is further reduced to 11.7 threads per warp due to predication. The compiler may use predication to avoid an actual branch. Instead, all instructions are scheduled, but a per-thread condition code or predicate controls which threads execute the instructions. Try to avoid different execution paths within a warp when possible. In addition, ensure your kernel makes use of Independent Thread Scheduling, which allows a warp to reconverge after a data-dependent conditional block by explicitly calling __syncwarp(). |
WRN Occupancy | This kernel's theoretical occupancy is not impacted by any block limit. The difference between calculated theoretical (100.0%) and measured achieved occupancy (12.4%) can be the result of warp scheduling overheads or workload imbalances during the kernel execution. Load imbalances can occur between warps within a block as well as across blocks of the same kernel. See the CUDA Best Practices Guide (https://docs.nvidia.com/cuda/cuda-c-best-practices-guide/index.html#occupancy) for more details on optimizing occupancy. |
Operation / Metric | Value | Unit |
---|---|---|
aten::zeros | ||
CPU Time | 5562545.45 | μs |
Device Time | 129793.28 | μs |
Self CPU Time | 165718.40 | μs |
Self Device Time | 0.00 | μs |
CPU Memory Usage | 0 | B |
Device Memory Usage | 0 | B |
Self CPU Memory Usage | 0 | B |
Self Device Memory Usage | 0 | B |
aten::zero_ | ||
CPU Time | 5890374.45 | μs |
Device Time | 7697081.05 | μs |
Self CPU Time | 358923.58 | μs |
Self Device Time | 0.00 | μs |
CPU Memory Usage | 0 | B |
Device Memory Usage | 0 | B |
Self CPU Memory Usage | 0 | B |
Self Device Memory Usage | 0 | B |
aten::fill_ | ||
CPU Time | 5531452.84 | μs |
Device Time | 7697081.05 | μs |
Self CPU Time | 400276.39 | μs |
Self Device Time | 7697081.05 | μs |
CPU Memory Usage | 0 | B |
Device Memory Usage | 0 | B |
Self CPU Memory Usage | 0 | B |
Self Device Memory Usage | 0 | B |
cudaLaunchKernel | ||
CPU Time | 5496870.50 | μs |
Device Time | 2574.12 | μs |
Self CPU Time | 5496870.50 | μs |
Self Device Time | 2574.12 | μs |
CPU Memory Usage | 0 | B |
Device Memory Usage | 0 | B |
Self CPU Memory Usage | 0 | B |
Self Device Memory Usage | 0 | B |
kernel_2d(float const*, float const*, float const*, float const*, float*, int, int, int) | ||
CPU Time | 0.00 | μs |
Device Time | 292257.60 | μs |
Self CPU Time | 0.00 | μs |
Self Device Time | 292257.60 | μs |
CPU Memory Usage | 0 | B |
Device Memory Usage | 0 | B |
Self CPU Memory Usage | 0 | B |
Self Device Memory Usage | 0 | B |
cudaEventRecord | ||
CPU Time | 278151.81 | μs |
Device Time | 332715.19 | μs |
Self CPU Time | 278151.81 | μs |
Self Device Time | 332715.19 | μs |
CPU Memory Usage | 0 | B |
Device Memory Usage | 0 | B |
Self CPU Memory Usage | 0 | B |
Self Device Memory Usage | 0 | B |
void at::native::vectorized_elementwise_kernel<4, at::native::FillFunctor<int>, at::detail::Array<char*, 1> >(int, at::native::FillFunctor<int>, at::detail::Array<char*, 1>) | ||
CPU Time | 0.00 | μs |
Device Time | 7567917.66 | μs |
Self CPU Time | 0.00 | μs |
Self Device Time | 7567917.66 | μs |
CPU Memory Usage | 0 | B |
Device Memory Usage | 0 | B |
Self CPU Memory Usage | 0 | B |
Self Device Memory Usage | 0 | B |
cudaEventElapsedTime | ||
CPU Time | 338721.88 | μs |
Device Time | 0.00 | μs |
Self CPU Time | 338721.88 | μs |
Self Device Time | 0.00 | μs |
CPU Memory Usage | 0 | B |
Device Memory Usage | 0 | B |
Self CPU Memory Usage | 0 | B |
Self Device Memory Usage | 0 | B |
45288 warnings generated when compiling for host. Suppressed 45324 warnings (45277 in non-user code, 47 NOLINT). Use -header-filter=.* to display errors from all non-system headers. Use -system-headers to display errors from system headers as well.