98_Matmul_AvgPool_GELU_Scale_Max
• constant_memory_optimization_base_base
import torch
import torch.nn as nn
import torch.nn.functional as F
def module_fn(
x: torch.Tensor,
pool_kernel_size: int,
scale_factor: float,
weight: torch.Tensor,
bias: torch.Tensor,
) -> torch.Tensor:
"""
Implements Matmul_AvgPool_GELU_Scale_Max pattern using functional operations.
Args:
x (torch.Tensor): Input tensor of shape (batch_size, in_features)
pool_kernel_size (int): Kernel size for average pooling
scale_factor (float): Scale factor to multiply features by
weight (torch.Tensor): Weight matrix for linear layer
bias (torch.Tensor): Bias vector for linear layer
Returns:
torch.Tensor: Output tensor of shape (batch_size,)
"""
x = F.linear(x, weight, bias)
x = F.avg_pool1d(x.unsqueeze(1), kernel_size=pool_kernel_size).squeeze(1)
x = F.gelu(x)
x = x * scale_factor
x = torch.max(x, dim=1).values
return x
class Model(nn.Module):
"""
A model implementing the pattern "Matmul_AvgPool_GELU_Scale_Max".
"""
def __init__(self, in_features, out_features, pool_kernel_size, scale_factor):
super(Model, self).__init__()
gemm = nn.Linear(in_features, out_features)
self.weight = gemm.weight
self.bias = gemm.bias
def forward(self, x, pool_kernel_size, scale_factor, fn=module_fn):
return fn(x, pool_kernel_size, scale_factor, self.weight, self.bias)
batch_size = 128
in_features = 512
out_features = 256
pool_kernel_size = 4
scale_factor = 2.0
def get_inputs():
return [torch.randn(batch_size, in_features), pool_kernel_size, scale_factor]
def get_init_inputs():
return [in_features, out_features, pool_kernel_size, scale_factor]
import torch
import torch.nn as nn
class Model(nn.Module):
"""
A model implementing the pattern "Matmul_AvgPool_GELU_Scale_Max".
"""
def __init__(self, in_features, out_features, pool_kernel_size, scale_factor):
super(Model, self).__init__()
self.matmul = nn.Linear(in_features, out_features)
self.avg_pool = nn.AvgPool1d(kernel_size=pool_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.avg_pool(x.unsqueeze(1)).squeeze(1)
x = torch.nn.functional.gelu(x)
x = x * self.scale_factor
x = torch.max(x, dim=1).values
return x
batch_size = 128
in_features = 512
out_features = 256
pool_kernel_size = 4
scale_factor = 2.0
def get_inputs():
return [torch.randn(batch_size, in_features)]
def get_init_inputs():
return [in_features, out_features, pool_kernel_size, scale_factor]
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <math.h>
#include <float.h>
#ifndef TILE_SIZE
#define TILE_SIZE 16
#endif
// Constant memory for bias
__constant__ float const_bias[1024]; // Adjust size according to maximum expected bias size
//---------------------------------------------------------------------------
// Fused Matrix Multiplication with Bias Addition Kernel
// Computes: C = A * (B^T) + bias, where A is [M x K], B is [N x K] (stored row-wise),
// and bias is a vector of length N. Uses shared memory tiling for improved performance.
//---------------------------------------------------------------------------
__global__ void FusedMatMulBiasKernel(const float* __restrict__ A,
const float* __restrict__ B,
float* __restrict__ C,
int M, int N, int K) {
__shared__ float Asub[TILE_SIZE][TILE_SIZE];
__shared__ float Bsub[TILE_SIZE][TILE_SIZE];
int row = blockIdx.y * TILE_SIZE + threadIdx.y;
int col = blockIdx.x * TILE_SIZE + threadIdx.x;
float sum = 0.0f;
// Loop over tiles
for (int t = 0; t < (K + TILE_SIZE - 1) / TILE_SIZE; t++) {
int tiled_k = t * TILE_SIZE;
// Load A tile
if (row < M && (tiled_k + threadIdx.x) < K)
Asub[threadIdx.y][threadIdx.x] = A[row * K + tiled_k + threadIdx.x];
else
Asub[threadIdx.y][threadIdx.x] = 0.0f;
// Load B tile (B is stored such that we use its transpose logic)
if (col < N && (tiled_k + threadIdx.y) < K)
Bsub[threadIdx.y][threadIdx.x] = B[col * K + tiled_k + threadIdx.y];
else
Bsub[threadIdx.y][threadIdx.x] = 0.0f;
__syncthreads();
// Multiply the two tiles together
for (int i = 0; i < TILE_SIZE; i++) {
sum += Asub[threadIdx.y][i] * Bsub[i][threadIdx.x];
}
__syncthreads();
}
// Write result with bias addition
if (row < M && col < N) {
C[row * N + col] = sum + const_bias[col];
}
}
//---------------------------------------------------------------------------
// Fused Pooling, Activation, Scaling and Max Reduction Kernel
// Input: the linear output from the previous stage of shape [M x N].
// Operation per row:
// 1. Average Pooling: groups contiguous elements with pool_kernel_size.
// (If the group is incomplete at the end, it computes the average over available elements.)
// 2. GELU Activation (using the approximate formula: 0.5 * x * (1 + erf(x * 0.70710678))).
// 3. Scaling by scale_factor.
// 4. Maximum reduction over the pooled/activated values.
// Each block processes one row; multiple threads in a block cooperatively reduce the maximum.
//---------------------------------------------------------------------------
__global__ void FusedPoolActMaxKernel(const float* __restrict__ linear_output,
float* __restrict__ output,
int M, int N,
int pool_kernel_size,
int output_length,
float scale_factor) {
// One block per row
int row = blockIdx.x;
int tid = threadIdx.x;
float local_max = -FLT_MAX;
// Each thread processes multiple pooling bins using striding
for (int bin = tid; bin < output_length; bin += blockDim.x) {
int start = bin * pool_kernel_size;
float sum = 0.0f;
int count = 0;
for (int j = 0; j < pool_kernel_size; j++) {
int col = start + j;
if (col < N) {
sum += linear_output[row * N + col];
count++;
}
}
float avg = sum / count; // Average pooling result
// Apply GELU activation: 0.5 * avg * (1 + erf(avg * 0.70710678))
float gelu = 0.5f * avg * (1.0f + erff(avg * 0.70710678f));
// Scale the activated output
gelu *= scale_factor;
local_max = fmaxf(local_max, gelu);
}
// Reduction within block using shared memory
extern __shared__ float sdata[]; // Dynamically allocated shared memory
sdata[tid] = local_max;
__syncthreads();
// Parallel reduction (assumes blockDim.x is a power of 2)
for (unsigned int s = blockDim.x / 2; s > 0; s >>= 1) {
if (tid < s) {
sdata[tid] = fmaxf(sdata[tid], sdata[tid + s]);
}
__syncthreads();
}
// The first thread writes the maximum value for this row
if (tid == 0) {
output[row] = sdata[0];
}
}
//---------------------------------------------------------------------------
// Forward function that chains the fused operations
// Steps:
// 1. Compute linear transformation: linear = x * (weight^T) + bias using a tiled matmul kernel.
// 2. Apply fused average pooling, GELU activation, scaling, and maximum reduction across pooled bins.
//---------------------------------------------------------------------------
torch::Tensor forward(
torch::Tensor x,
int pool_kernel_size,
float scale_factor,
torch::Tensor weight,
torch::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");
// Ensure tensors are contiguous
x = x.contiguous();
weight = weight.contiguous();
bias = bias.contiguous();
// Dimensions
int M = x.size(0); // Batch size (number of rows)
int K = x.size(1); // Input features
int N = weight.size(0); // Output features (number of rows in weight, since weight is transposed)
auto options = torch::TensorOptions().dtype(x.dtype()).device(x.device());
// Allocate tensor for the linear transformation results
auto linear_output = torch::empty({M, N}, options);
// Copy bias to constant memory
cudaMemcpyToSymbol(const_bias, bias.data_ptr<float>(), N * sizeof(float));
// Launch fused matrix multiplication + bias addition kernel
dim3 blockDim(TILE_SIZE, TILE_SIZE);
dim3 gridDim((N + TILE_SIZE - 1) / TILE_SIZE, (M + TILE_SIZE - 1) / TILE_SIZE);
FusedMatMulBiasKernel<<<gridDim, blockDim>>>(
x.data_ptr<float>(),
weight.data_ptr<float>(),
linear_output.data_ptr<float>(),
M, N, K);
// Determine pooling output length
int output_length = (N + pool_kernel_size - 1) / pool_kernel_size;
// Allocate tensor for final output (one value per batch row)
auto output = torch::empty({M}, options);
// Launch fused pooling, activation, scaling, and max reduction kernel
// One block per row, use 256 threads (or adjust based on output_length)
int threads = 256;
size_t sharedMemSize = threads * sizeof(float);
FusedPoolActMaxKernel<<<M, threads, sharedMemSize>>>(
linear_output.data_ptr<float>(),
output.data_ptr<float>(),
M, N, pool_kernel_size, output_length, scale_factor);
return output;
}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
m.def("forward", &forward, "Fused CUDA forward (MatMul+Bias, Pool, GELU, Scale, Max Reduction)");
}
Metric | Value | Unit | Variance | Samples |
---|---|---|---|---|
Executed Ipc Active | 0.368 | inst/cycle | 0.000 | 5 |
Executed Ipc Elapsed | 0.150 | inst/cycle | 0.000 | 5 |
Issue Slots Busy | 9.582 | % | 0.168 | 5 |
Issued Ipc Active | 0.384 | inst/cycle | 0.000 | 5 |
SM Busy | 9.582 | % | 0.168 | 5 |
Memory Throughput | 32849753760.306 | byte/second | 174366150560550336.000 | 5 |
Mem Busy | 7.748 | % | 0.008 | 5 |
Max Bandwidth | 4.096 | % | 0.002 | 5 |
L1/TEX Hit Rate | 74.420 | % | 0.000 | 5 |
L2 Hit Rate | 91.356 | % | 0.015 | 5 |
Mem Pipes Busy | 3.306 | % | 0.001 | 5 |
Warp Cycles Per Issued Instruction | 19.518 | cycle | 0.223 | 5 |
Warp Cycles Per Executed Instruction | 20.378 | cycle | 0.242 | 5 |
Avg. Active Threads Per Warp | 31.760 | 0.000 | 5 | |
Avg. Not Predicated Off Threads Per Warp | 22.070 | 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 | 16.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.094 | % | 0.000 | 5 |
Achieved Active Warps Per SM | 7.738 | 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 31.8 threads being active per cycle. This is further reduced to 22.1 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.1%) 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 | 590324.69 | μs |
Device Time | 34.24 | μs |
Self CPU Time | 83.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::_to_copy | ||
CPU Time | 590241.02 | μs |
Device Time | 34.24 | μs |
Self CPU Time | 154.97 | μ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 | 589814.26 | μs |
Device Time | 0.00 | μs |
Self CPU Time | 165.51 | μ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 | 578184.67 | μs |
Device Time | 0.00 | μs |
Self CPU Time | 578184.67 | μ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 |
cudaMemcpyToSymbol | ||
CPU Time | 348515.96 | μs |
Device Time | 706.33 | μs |
Self CPU Time | 348515.96 | μs |
Self Device Time | 706.33 | μ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 | 95444.98 | μs |
Device Time | 55626.67 | μs |
Self CPU Time | 95444.98 | μs |
Self Device Time | 55626.67 | μs |
CPU Memory Usage | 0 | B |
Device Memory Usage | 0 | B |
Self CPU Memory Usage | 0 | B |
Self Device Memory Usage | 0 | B |
FusedMatMulBiasKernel(float const*, float const*, float*, int, int, int) | ||
CPU Time | 0.00 | μs |
Device Time | 154606.71 | μs |
Self CPU Time | 0.00 | μs |
Self Device Time | 154606.71 | μ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 | 70082.91 | μs |
Device Time | 511366.18 | μs |
Self CPU Time | 13330.05 | μ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 | 56754.82 | μs |
Device Time | 511366.18 | μs |
Self CPU Time | 16507.97 | μs |
Self Device Time | 511366.18 | μ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 | 511366.18 | μs |
Self CPU Time | 0.00 | μs |
Self Device Time | 511366.18 | μs |
CPU Memory Usage | 0 | B |
Device Memory Usage | 0 | B |
Self CPU Memory Usage | 0 | B |
Self Device Memory Usage | 0 | B |
45289 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.