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]
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
// Kernel using __ldg() for read-only accesses and vectorized loads using float4 to align to 128-bit boundaries
__global__ void kernel_aligned_ldg(
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) {
int index = blockIdx.x * blockDim.x + threadIdx.x; // overall thread index
int total_elements = batch_size * out_features;
if (index < total_elements) {
int batch_idx = index / out_features; // row
int out_idx = index % out_features; // column
float sum = 0.0f;
// Ensure in_features is divisible by 4 for vectorized load, otherwise fallback to scalar loads
if ((in_features & 3) == 0) {
int numVec = in_features >> 2; // equivalent to in_features / 4
// reinterpret pointers as float4 pointers for aligned 128-bit access
const float4* x_vec = reinterpret_cast<const float4*>(x);
const float4* w_vec = reinterpret_cast<const float4*>(linear_weight);
int x_offset = batch_idx * numVec; // start offset for this row of x
int w_offset = out_idx * numVec; // start offset for the corresponding weight row
#pragma unroll
for (int k = 0; k < numVec; k++) {
// Use __ldg to load from read-only memory
float4 a = __ldg(&x_vec[x_offset + k]);
float4 b = __ldg(&w_vec[w_offset + k]);
sum += a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
}
} else {
// Fallback to scalar loads if in_features is not a multiple of 4
int offset_x = batch_idx * in_features;
int offset_w = out_idx * in_features;
for (int j = 0; j < in_features; j++) {
float xv = __ldg(&x[offset_x + j]);
float wv = __ldg(&linear_weight[offset_w + j]);
sum += xv * wv;
}
}
// Add bias and apply min-subtract constant operation
sum += __ldg(&linear_bias[out_idx]);
float c = __ldg(constant);
sum = (sum > c) ? c : sum;
y[index] = sum - c;
}
}
// Forward function to launch the CUDA 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>();
int total_elements = batch_size * out_features;
int threads = 256;
int blocks = (total_elements + threads - 1) / threads;
kernel_aligned_ldg<<<blocks, threads>>>(
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 forward function");
}
Metric | Value | Unit | Variance | Samples |
---|---|---|---|---|
Executed Ipc Active | 0.320 | inst/cycle | 0.000 | 5 |
Executed Ipc Elapsed | 0.000 | inst/cycle | 0.000 | 5 |
Issue Slots Busy | 8.402 | % | 0.220 | 5 |
Issued Ipc Active | 0.336 | inst/cycle | 0.000 | 5 |
SM Busy | 8.402 | % | 0.220 | 5 |
Memory Throughput | 3170477719.954 | byte/second | 693528729681947.000 | 5 |
Mem Busy | 7.686 | % | 0.008 | 5 |
Max Bandwidth | 3.988 | % | 0.003 | 5 |
L1/TEX Hit Rate | 89.410 | % | 0.000 | 5 |
L2 Hit Rate | 103.108 | % | 0.250 | 5 |
Mem Pipes Busy | 0.070 | % | 0.000 | 5 |
Warp Cycles Per Issued Instruction | 20.138 | cycle | 0.873 | 5 |
Warp Cycles Per Executed Instruction | 21.062 | cycle | 0.958 | 5 |
Avg. Active Threads Per Warp | 32.000 | 0.000 | 5 | |
Avg. Not Predicated Off Threads Per Warp | 29.020 | 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 | 6.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 | 48.000 | warp | 0.000 | 5 |
Theoretical Occupancy | 75.000 | % | 0.000 | 5 |
Achieved Occupancy | 11.062 | % | 0.006 | 5 |
Achieved Active Warps Per SM | 7.082 | warp | 0.003 | 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 Occupancy | This kernel's theoretical occupancy (75.0%) is limited by the number of required registers. The difference between calculated theoretical (75.0%) and measured achieved occupancy (11.2%) 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 | 5679620.79 | μs |
Device Time | 134538.56 | μs |
Self CPU Time | 158484.29 | μ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 | 6014739.89 | μs |
Device Time | 8010530.71 | μs |
Self CPU Time | 371870.66 | μ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 | 5642871.15 | μs |
Device Time | 8010530.71 | μs |
Self CPU Time | 414842.99 | μs |
Self Device Time | 8010530.71 | μ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 | 5605827.25 | μs |
Device Time | 2730.87 | μs |
Self CPU Time | 5605827.25 | μs |
Self Device Time | 2730.87 | μs |
CPU Memory Usage | 0 | B |
Device Memory Usage | 0 | B |
Self CPU Memory Usage | 0 | B |
Self Device Memory Usage | 0 | B |
kernel_aligned_ldg(float const*, float const*, float const*, float const*, float*, int, int, int) | ||
CPU Time | 0.00 | μs |
Device Time | 271278.62 | μs |
Self CPU Time | 0.00 | μs |
Self Device Time | 271278.62 | μ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 | 286654.92 | μs |
Device Time | 346109.44 | μs |
Self CPU Time | 286654.92 | μs |
Self Device Time | 346109.44 | μ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 | 7876621.15 | μs |
Self CPU Time | 0.00 | μs |
Self Device Time | 7876621.15 | μ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 | 329333.87 | μs |
Device Time | 0.00 | μs |
Self CPU Time | 329333.87 | μ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 |
45287 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.