55_Matmul_MaxPool_Sum_Scale
• warp_reduction_opt_kernel_base_base
import torch
import torch.nn as nn
import torch.nn.functional as F
def module_fn(
x: torch.Tensor,
kernel_size: int,
scale_factor: float,
weight: torch.Tensor,
bias: torch.Tensor,
) -> torch.Tensor:
"""
Performs matrix multiplication, max pooling, sum, and scaling.
Args:
x (torch.Tensor): Input tensor of shape (batch_size, in_features)
kernel_size (int): Size of max pooling kernel
scale_factor (float): Factor to scale the output by
weight (torch.Tensor): Weight matrix of shape (out_features, in_features)
bias (torch.Tensor): Bias vector of shape (out_features)
Returns:
torch.Tensor: Output tensor of shape (batch_size,)
"""
x = F.linear(x, weight, bias)
x = F.max_pool1d(x.unsqueeze(1), kernel_size).squeeze(1)
x = torch.sum(x, dim=1)
x = x * scale_factor
return x
class Model(nn.Module):
"""
Model that performs matrix multiplication, max pooling, sum, and scaling.
"""
def __init__(self, in_features, out_features, kernel_size, scale_factor):
super(Model, self).__init__()
gemm = nn.Linear(in_features, out_features)
self.weight = nn.Parameter(gemm.weight)
self.bias = nn.Parameter(gemm.bias)
def forward(self, x, kernel_size, scale_factor, fn=module_fn):
return fn(x, kernel_size, scale_factor, self.weight, self.bias)
batch_size = 128
in_features = 10
out_features = 5
kernel_size = 2
scale_factor = 0.5
def get_inputs():
return [torch.randn(batch_size, in_features), kernel_size, scale_factor]
def get_init_inputs():
return [in_features, out_features, kernel_size, scale_factor]
import torch
import torch.nn as nn
class Model(nn.Module):
"""
Model that performs matrix multiplication, max pooling, sum, and scaling.
"""
def __init__(self, in_features, out_features, kernel_size, scale_factor):
super(Model, self).__init__()
self.matmul = nn.Linear(in_features, out_features)
self.max_pool = nn.MaxPool1d(kernel_size)
self.scale_factor = scale_factor
def forward(self, x):
"""
Args:
x (torch.Tensor): Input tensor of shape (batch_size, in_features).
Returns:
torch.Tensor: Output tensor of shape (batch_size, out_features).
"""
x = self.matmul(x)
x = self.max_pool(x.unsqueeze(1)).squeeze(1)
x = torch.sum(x, dim=1)
x = x * self.scale_factor
return x
batch_size = 128
in_features = 10
out_features = 5
kernel_size = 2
scale_factor = 0.5
def get_inputs():
return [torch.randn(batch_size, in_features)]
def get_init_inputs():
return [in_features, out_features, kernel_size, scale_factor]
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
__global__ void warp_reduction_opt_kernel(
const float* __restrict__ x,
const float* __restrict__ weight,
const float* __restrict__ bias,
float* __restrict__ output,
int B, // batch_size
int inF, // number of input features
int outF, // number of output features
int kernel_size,
float scale_factor
) {
const unsigned int tid = threadIdx.x;
const unsigned int bid = blockIdx.x;
const unsigned int warp_size = 32;
const unsigned int warp_id = tid / warp_size;
const unsigned int lane_id = tid % warp_size;
const unsigned int num_warps = blockDim.x / warp_size;
// Shared memory layout optimized for bank conflicts
extern __shared__ float smem[];
float* warp_results = smem; // Size: num_warps
float* temp_storage = &smem[num_warps]; // Size: outF
// Register for accumulating partial results
float local_sum = 0.0f;
// Step 1: Compute linear transformation with vectorized memory access
// Each warp handles a portion of the output features
const int features_per_warp = (outF + num_warps - 1) / num_warps;
const int warp_start = warp_id * features_per_warp;
const int warp_end = min(warp_start + features_per_warp, outF);
// Each thread in the warp processes multiple features
for (int j = warp_start + lane_id; j < warp_end; j += warp_size) {
float acc = bias[j];
// Vectorized dot product
#pragma unroll 4
for (int i = 0; i < inF; i++) {
acc = __fmaf_rn(x[bid * inF + i], weight[j * inF + i], acc);
}
temp_storage[j] = acc;
}
__syncthreads();
// Step 2: Max pooling using warp-level operations
const int pooled_len = (outF >= kernel_size) ? ((outF - kernel_size) / kernel_size + 1) : 0;
// Each thread processes multiple pooling windows
for (int seg = tid; seg < pooled_len; seg += blockDim.x) {
const int start_idx = seg * kernel_size;
float max_val = temp_storage[start_idx];
#pragma unroll
for (int k = 1; k < kernel_size && (start_idx + k) < outF; k++) {
max_val = fmaxf(max_val, temp_storage[start_idx + k]);
}
local_sum += max_val;
}
// Step 3: Warp-level reduction using shuffle operations
#pragma unroll
for (int offset = warp_size/2; offset > 0; offset /= 2) {
local_sum += __shfl_down_sync(0xffffffff, local_sum, offset);
}
// First thread in each warp writes its result
if (lane_id == 0) {
warp_results[warp_id] = local_sum;
}
__syncthreads();
// Final reduction across warps using the first warp
if (warp_id == 0) {
local_sum = (lane_id < num_warps) ? warp_results[lane_id] : 0.0f;
// Warp-level reduction for final result
#pragma unroll
for (int offset = warp_size/2; offset > 0; offset /= 2) {
local_sum += __shfl_down_sync(0xffffffff, local_sum, offset);
}
if (lane_id == 0) {
output[bid] = local_sum * scale_factor;
}
}
}
at::Tensor forward(
at::Tensor x,
int64_t kernel_size,
double scale_factor,
at::Tensor weight,
at::Tensor bias
) {
TORCH_CHECK(x.is_cuda(), "x must be a CUDA tensor");
TORCH_CHECK(weight.is_cuda(), "weight must be a CUDA tensor");
TORCH_CHECK(bias.is_cuda(), "bias must be a CUDA tensor");
TORCH_CHECK(x.dim() == 2, "x must have shape (batch_size, in_features)");
TORCH_CHECK(weight.dim() == 2, "weight must have shape (out_features, in_features)");
TORCH_CHECK(bias.dim() == 1, "bias must have shape (out_features)");
const auto B = x.size(0);
const auto inF = x.size(1);
const auto outF = weight.size(0);
auto out = torch::empty({B}, x.options());
// Configure kernel launch parameters
const int threads_per_block = 256;
const int warps_per_block = threads_per_block / 32;
// Shared memory size: space for warp results and temporary storage
const size_t smem_size = (warps_per_block + outF) * sizeof(float);
warp_reduction_opt_kernel<<<B, threads_per_block, smem_size>>>(
x.data_ptr<float>(),
weight.data_ptr<float>(),
bias.data_ptr<float>(),
out.data_ptr<float>(),
B,
inF,
outF,
static_cast<int>(kernel_size),
static_cast<float>(scale_factor)
);
return out;
}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
m.def("forward", &forward, "Warp-optimized CUDA forward implementation");
}
Metric | Value | Unit | Variance | Samples |
---|---|---|---|---|
Executed Ipc Active | 0.376 | inst/cycle | 0.000 | 5 |
Executed Ipc Elapsed | 0.178 | inst/cycle | 0.000 | 5 |
Issue Slots Busy | 9.512 | % | 0.035 | 5 |
Issued Ipc Active | 0.380 | inst/cycle | 0.000 | 5 |
SM Busy | 9.512 | % | 0.035 | 5 |
Memory Throughput | 2836982692.814 | byte/second | 3168213929551257.000 | 5 |
Mem Busy | 7.162 | % | 0.021 | 5 |
Max Bandwidth | 3.776 | % | 0.004 | 5 |
L1/TEX Hit Rate | 89.620 | % | 0.000 | 5 |
L2 Hit Rate | 102.814 | % | 0.261 | 5 |
Mem Pipes Busy | 3.554 | % | 0.004 | 5 |
Warp Cycles Per Issued Instruction | 19.812 | cycle | 0.520 | 5 |
Warp Cycles Per Executed Instruction | 20.162 | cycle | 0.538 | 5 |
Avg. Active Threads Per Warp | 18.440 | 0.000 | 5 | |
Avg. Not Predicated Off Threads Per Warp | 15.370 | 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 | 28.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 | 11.534 | % | 0.000 | 5 |
Achieved Active Warps Per SM | 7.382 | 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 18.4 threads being active per cycle. This is further reduced to 15.4 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 (11.5%) 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::to | ||
CPU Time | 322972.36 | μs |
Device Time | 5.54 | μs |
Self CPU Time | 42.35 | μ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::_to_copy | ||
CPU Time | 322930.02 | μs |
Device Time | 5.54 | μs |
Self CPU Time | 83.42 | μ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::empty_strided | ||
CPU Time | 322732.87 | μs |
Device Time | 0.00 | μs |
Self CPU Time | 87.22 | μ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 |
cudaDeviceGetStreamPriorityRange | ||
CPU Time | 322459.98 | μs |
Device Time | 0.00 | μs |
Self CPU Time | 322459.98 | μ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 |
cudaLaunchKernel | ||
CPU Time | 500347.27 | μs |
Device Time | 21485.88 | μs |
Self CPU Time | 500347.27 | μs |
Self Device Time | 21485.88 | μs |
CPU Memory Usage | 0 | B |
Device Memory Usage | 0 | B |
Self CPU Memory Usage | 0 | B |
Self Device Memory Usage | 0 | B |
warp_reduction_opt_kernel(float const*, float const*, float const*, float*, int, int, int, int, float) | ||
CPU Time | 0.00 | μs |
Device Time | 33238.14 | μs |
Self CPU Time | 0.00 | μs |
Self Device Time | 33238.14 | μ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 | 21865.54 | μs |
Device Time | 42562.45 | μs |
Self CPU Time | 21865.54 | μs |
Self Device Time | 42562.45 | μ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 | 65180.43 | μs |
Device Time | 637085.35 | μs |
Self CPU Time | 13250.35 | μ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 | 51930.88 | μs |
Device Time | 637085.35 | μs |
Self CPU Time | 16823.13 | μs |
Self Device Time | 637085.35 | μ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 | 637085.35 | μs |
Self CPU Time | 0.00 | μs |
Self Device Time | 637085.35 | μs |
CPU Memory Usage | 0 | B |
Device Memory Usage | 0 | B |
Self CPU Memory Usage | 0 | B |
Self Device Memory Usage | 0 | B |
45292 warnings generated when compiling for host. Suppressed 45325 warnings (45278 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.