98_Matmul_AvgPool_GELU_Scale_Max
• fused_matmul_pool_act_max_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>
// Kernel 1: Fused Matrix Multiplication with Bias Addition (using vectorized loads when possible)
__global__ void MatMulWithBiasKernel(const float* __restrict__ A, const float* __restrict__ B,
const float* __restrict__ bias, float* __restrict__ C,
int M, int N, int K) {
int row = blockIdx.y * blockDim.y + threadIdx.y;
int col = blockIdx.x * blockDim.x + threadIdx.x;
if (row < M && col < N) {
float val = 0.0f;
// Use vectorized loads if possible
if (K % 4 == 0) {
for (int i = 0; i < K; i += 4) {
float4 a4 = *reinterpret_cast<const float4*>(&A[row * K + i]);
float4 b4 = *reinterpret_cast<const float4*>(&B[col * K + i]);
val = fmaf(a4.x, b4.x, val);
val = __fmaf_rn(a4.y, b4.y, val);
val = __fmaf_rn(a4.z, b4.z, val);
val = __fmaf_rn(a4.w, b4.w, val);
}
} else {
for (int i = 0; i < K; ++i) {
val = __fmaf_rn(__ldg(&A[row * K + i]), __ldg(&B[col * K + i]), val);
}
}
// Fuse bias addition
val += __ldg(&bias[col]);
C[row * N + col] = val;
}
}
// Kernel 2: Fused Average Pooling, GELU Activation, Scaling, and Max Reduction
// This kernel reads the linear output, performs 1D average pooling over groups of 'pool_kernel_size'
// elements, applies the GELU activation and scaling, and then reduces to a single maximum value per batch row.
__global__ void FusedPoolActMaxKernel(const float* __restrict__ linear_output, float* __restrict__ output,
int M, int N, int pool_kernel_size, float scale_factor) {
// Each block handles one batch element
int batch = blockIdx.x;
// Determine number of pooling segments (assumes N is divisible by pool_kernel_size or truncates remainder)
int out_length = N / pool_kernel_size;
float local_max = -FLT_MAX;
// Each thread processes multiple pooling segments
for (int i = threadIdx.x; i < out_length; i += blockDim.x) {
int start_idx = i * pool_kernel_size;
float sum = 0.0f;
// Compute pooling sum. Boundary check is added for safety.
for (int j = 0; j < pool_kernel_size; ++j) {
int col = start_idx + j;
if (col < N) {
sum += __ldg(&linear_output[batch * N + col]);
}
}
// Average pooling (note: using constant division by pool_kernel_size, as in Kernel 2)
float avg = sum / (float)pool_kernel_size;
// GELU activation (using erf approximation) fused with scaling
float gelu = 0.5f * avg * (1.0f + erff(avg * 0.70710678f));
float scaled = gelu * scale_factor;
// Track the maximum value across pooling segments
local_max = fmaxf(local_max, scaled);
}
// Use shared memory to reduce local maxima within the block
__shared__ float shmem[256]; // Assumes blockDim.x <= 256
int tid = threadIdx.x;
shmem[tid] = local_max;
__syncthreads();
for (int stride = blockDim.x / 2; stride > 0; stride /= 2) {
if (tid < stride) {
shmem[tid] = fmaxf(shmem[tid], shmem[tid + stride]);
}
__syncthreads();
}
// Thread 0 writes the final maximum for this batch element
if (tid == 0) {
output[batch] = shmem[0];
}
}
// The fused forward function which calls the two kernels sequentially
// Step 1: Compute linear transformation with bias fusing matrix multiplication & bias addition
// Step 2: Fuse average pooling, activation, scaling and max reduction in a single kernel to produce a single output per batch
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 inputs are contiguous
x = x.contiguous();
weight = weight.contiguous();
bias = bias.contiguous();
// Dimensions
int M = x.size(0); // batch size
int K = x.size(1); // in_features
int N = weight.size(0); // out_features
auto options = torch::TensorOptions().dtype(x.dtype()).device(x.device());
// Allocate tensor for the linear transform output
auto linear_output = torch::empty({M, N}, options);
// Launch MatMul with Bias kernel using a 16x16 thread block
dim3 threadsPerBlock(16, 16);
dim3 numBlocks((N + threadsPerBlock.x - 1) / threadsPerBlock.x,
(M + threadsPerBlock.y - 1) / threadsPerBlock.y);
MatMulWithBiasKernel<<<numBlocks, threadsPerBlock>>>(
x.data_ptr<float>(),
weight.data_ptr<float>(),
bias.data_ptr<float>(),
linear_output.data_ptr<float>(),
M, N, K);
// Launch the fused pooling, activation, and max reduction kernel
// Each batch element is handled by one block. Using 256 threads per block.
auto output = torch::empty({M}, options);
int threads = 256;
FusedPoolActMaxKernel<<<M, threads>>>(
linear_output.data_ptr<float>(),
output.data_ptr<float>(),
M, N, pool_kernel_size, scale_factor);
return output;
}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
m.def("forward", &forward, "Fused CUDA forward (MatMul+Pool+Act+Max)");
}
Metric | Value | Unit | Variance | Samples |
---|---|---|---|---|
Executed Ipc Active | 0.428 | inst/cycle | 0.000 | 5 |
Executed Ipc Elapsed | 0.180 | inst/cycle | 0.000 | 5 |
Issue Slots Busy | 11.014 | % | 0.142 | 5 |
Issued Ipc Active | 0.438 | inst/cycle | 0.000 | 5 |
SM Busy | 11.014 | % | 0.142 | 5 |
Memory Throughput | 33043091420.430 | byte/second | 19635024446623464.000 | 5 |
Mem Busy | 7.898 | % | 0.004 | 5 |
Max Bandwidth | 4.112 | % | 0.001 | 5 |
L1/TEX Hit Rate | 74.420 | % | 0.000 | 5 |
L2 Hit Rate | 90.946 | % | 0.134 | 5 |
Mem Pipes Busy | 4.120 | % | 0.000 | 5 |
Warp Cycles Per Issued Instruction | 17.312 | cycle | 0.567 | 5 |
Warp Cycles Per Executed Instruction | 17.838 | cycle | 0.601 | 5 |
Avg. Active Threads Per Warp | 31.800 | 0.000 | 5 | |
Avg. Not Predicated Off Threads Per Warp | 23.060 | 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.108 | % | 0.000 | 5 |
Achieved Active Warps Per SM | 7.748 | 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 23.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 | 586218.34 | μs |
Device Time | 33.09 | μs |
Self CPU Time | 54.07 | μ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 | 586164.27 | μs |
Device Time | 33.09 | μs |
Self CPU Time | 111.80 | μ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 | 585796.89 | μs |
Device Time | 0.00 | μs |
Self CPU Time | 116.37 | μ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 | 585058.37 | μs |
Device Time | 0.00 | μs |
Self CPU Time | 585058.37 | μ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 | 510634.89 | μs |
Device Time | 28638.99 | μs |
Self CPU Time | 510634.89 | μs |
Self Device Time | 28638.99 | μs |
CPU Memory Usage | 0 | B |
Device Memory Usage | 0 | B |
Self CPU Memory Usage | 0 | B |
Self Device Memory Usage | 0 | B |
MatMulWithBiasKernel(float const*, float const*, float const*, float*, int, int, int) | ||
CPU Time | 0.00 | μs |
Device Time | 239425.03 | μs |
Self CPU Time | 0.00 | μs |
Self Device Time | 239425.03 | μ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 | 75873.06 | μs |
Device Time | 586983.45 | μs |
Self CPU Time | 15455.31 | μ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 | 60420.22 | μs |
Device Time | 586983.45 | μs |
Self CPU Time | 21313.82 | μs |
Self Device Time | 586983.45 | μ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 | 586983.45 | μs |
Self CPU Time | 0.00 | μs |
Self Device Time | 586983.45 | μ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.