import torch
import torch.nn as nn
import torch.nn.functional as F
def module_fn(
x: torch.Tensor,
weight: torch.Tensor,
bias: torch.Tensor,
) -> torch.Tensor:
"""
Applies linear transformation followed by two Mish activations.
Args:
x (torch.Tensor): Input tensor of shape (batch_size, in_features)
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 after linear transformation and two Mish activations,
with shape (batch_size, out_features)
"""
x = F.linear(x, weight, bias)
x = F.mish(x)
x = F.mish(x)
return x
class Model(nn.Module):
"""
Simple model that performs a matrix multiplication, applies Mish, and applies Mish again.
"""
def __init__(self, in_features, out_features):
super(Model, self).__init__()
linear = nn.Linear(in_features, out_features)
self.weight = nn.Parameter(linear.weight)
self.bias = nn.Parameter(linear.bias + torch.ones_like(linear.bias) * 0.02)
def forward(self, x, fn=module_fn):
return fn(x, self.weight, self.bias)
batch_size = 128
in_features = 10
out_features = 20
def get_inputs():
return [torch.randn(batch_size, in_features)]
def get_init_inputs():
return [in_features, out_features]
import torch
import torch.nn as nn
class Model(nn.Module):
"""
Simple model that performs a matrix multiplication, applies Mish, and applies Mish again.
"""
def __init__(self, in_features, out_features):
super(Model, self).__init__()
self.linear = nn.Linear(in_features, out_features)
self.linear.bias = nn.Parameter(self.linear.bias + torch.ones_like(self.linear.bias) * 0.02)
def forward(self, x):
x = self.linear(x)
x = torch.nn.functional.mish(x)
x = torch.nn.functional.mish(x)
return x
batch_size = 128
in_features = 10
out_features = 20
def get_inputs():
return [torch.randn(batch_size, in_features)]
def get_init_inputs():
return [in_features, out_features]
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <math.h>
// Device function: Softplus
__device__ float softplus(float x) {
float abs_x = fabsf(x);
return log1pf(expf(-abs_x)) + fmaxf(x, 0.0f);
}
// Device function: Mish activation
__device__ float mish(float x) {
float sp = softplus(x);
return x * tanhf(sp);
}
// Optimized kernel: each warp computes one output element's dot product using warp-level reduction
__global__ void forward_kernel_optimized(
const float* __restrict__ x,
const float* __restrict__ weight,
const float* __restrict__ bias,
float* __restrict__ output,
int batch_size,
int in_features,
int out_features
) {
// Each warp computes one output element
const int warpSize = 32;
int global_warp_id = (blockIdx.x * (blockDim.x / warpSize)) + (threadIdx.x / warpSize);
int total_outputs = batch_size * out_features;
if (global_warp_id >= total_outputs) return;
int lane = threadIdx.x % warpSize;
int i = global_warp_id / out_features; // Batch index
int j = global_warp_id % out_features; // Output feature index
float sum = 0.0f;
// Each thread in the warp computes a partial sum over the in_features dimension
for (int k = lane; k < in_features; k += warpSize) {
float a = x[i * in_features + k];
float b = weight[j * in_features + k];
sum += a * b;
}
// Use warp-level reduction using __shfl_down_sync
unsigned int mask = 0xffffffff;
for (int offset = warpSize / 2; offset > 0; offset /= 2) {
sum += __shfl_down_sync(mask, sum, offset);
}
// The first lane in the warp finalizes the result
if (lane == 0) {
sum += bias[j];
float y = mish(sum);
output[global_warp_id] = mish(y);
}
}
// Host function to launch the optimized kernel
torch::Tensor forward(
torch::Tensor x,
torch::Tensor weight,
torch::Tensor bias
) {
TORCH_CHECK(x.dim() == 2, "x must be 2D");
TORCH_CHECK(weight.dim() == 2, "weight must be 2D");
TORCH_CHECK(bias.dim() == 1, "bias must be 1D");
int batch_size = x.size(0);
int in_features = x.size(1);
int out_features = weight.size(0);
TORCH_CHECK(weight.size(1) == in_features, "weight shape mismatch");
TORCH_CHECK(bias.size(0) == out_features, "bias shape mismatch");
auto output = torch::empty({batch_size, out_features}, x.options());
// Determine grid and block dimensions using warp-based mapping
const int threads_per_block = 128; // 128 threads = 4 warps per block
int warps_per_block = threads_per_block / 32;
int total_warps = batch_size * out_features;
int grid_size = (total_warps + warps_per_block - 1) / warps_per_block;
forward_kernel_optimized<<<grid_size, threads_per_block, 0, at::cuda::getCurrentCUDAStream()>>>(
x.data_ptr<float>(),
weight.data_ptr<float>(),
bias.data_ptr<float>(),
output.data_ptr<float>(),
batch_size,
in_features,
out_features
);
return output;
}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
m.def("forward", &forward, "Warp-level reduction Linear double Mish forward (CUDA)");
}
Metric | Value | Unit | Variance | Samples |
---|---|---|---|---|
Executed Ipc Active | 1.180 | inst/cycle | 0.000 | 5 |
Executed Ipc Elapsed | 0.548 | inst/cycle | 0.000 | 5 |
Issue Slots Busy | 29.990 | % | 0.102 | 5 |
Issued Ipc Active | 1.200 | inst/cycle | 0.000 | 5 |
SM Busy | 29.990 | % | 0.102 | 5 |
Memory Throughput | 3258435177.308 | byte/second | 5126556049131483.000 | 5 |
Mem Busy | 8.326 | % | 0.002 | 5 |
Max Bandwidth | 4.790 | % | 0.003 | 5 |
L1/TEX Hit Rate | 67.126 | % | 0.006 | 5 |
L2 Hit Rate | 102.468 | % | 0.056 | 5 |
Mem Pipes Busy | 6.520 | % | 0.003 | 5 |
Warp Cycles Per Issued Instruction | 15.444 | cycle | 0.186 | 5 |
Warp Cycles Per Executed Instruction | 15.688 | cycle | 0.190 | 5 |
Avg. Active Threads Per Warp | 11.920 | 0.000 | 5 | |
Avg. Not Predicated Off Threads Per Warp | 10.740 | 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 | 16.000 | block | 0.000 | 5 |
Block Limit Shared Mem | 32.000 | block | 0.000 | 5 |
Block Limit Warps | 16.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 | 28.640 | % | 0.035 | 5 |
Achieved Active Warps Per SM | 18.330 | warp | 0.013 | 5 |
Rule | Description |
---|---|
INF HighPipeUtilization | ALU is the highest-utilized pipeline (21.1%) based on active cycles, taking into account the rates of its different instructions. It executes integer and logic operations. It is well-utilized, but should not be a bottleneck. |
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 11.9 threads being active per cycle. This is further reduced to 10.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 (28.7%) 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. |
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. |
Operation / Metric | Value | Unit |
---|---|---|
aten::to | ||
CPU Time | 271292.92 | μs |
Device Time | 3.78 | μs |
Self CPU Time | 57.02 | μ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 | 271235.90 | μs |
Device Time | 3.78 | μs |
Self CPU Time | 85.70 | μ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 | 271033.25 | μs |
Device Time | 0.00 | μs |
Self CPU Time | 96.69 | μ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 | 270769.36 | μs |
Device Time | 0.00 | μs |
Self CPU Time | 270769.36 | μ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 | 48364.36 | μs |
Device Time | 621731.48 | μs |
Self CPU Time | 15791.09 | μs |
Self Device Time | 621731.48 | μ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 | 442431.05 | μs |
Device Time | 16120.57 | μs |
Self CPU Time | 442431.05 | μs |
Self Device Time | 16120.57 | μs |
CPU Memory Usage | 0 | B |
Device Memory Usage | 0 | B |
Self CPU Memory Usage | 0 | B |
Self Device Memory Usage | 0 | B |
forward_kernel_optimized(float const*, float const*, float const*, float*, int, int, int) | ||
CPU Time | 0.00 | μs |
Device Time | 22775.76 | μs |
Self CPU Time | 0.00 | μs |
Self Device Time | 22775.76 | μ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 | 17221.39 | μs |
Device Time | 32401.09 | μs |
Self CPU Time | 17221.39 | μs |
Self Device Time | 32401.09 | μ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 | 62162.41 | μs |
Device Time | 621731.48 | μs |
Self CPU Time | 13810.95 | μ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 |
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 | 621731.48 | μs |
Self CPU Time | 0.00 | μs |
Self Device Time | 621731.48 | μs |
CPU Memory Usage | 0 | B |
Device Memory Usage | 0 | B |
Self CPU Memory Usage | 0 | B |
Self Device Memory Usage | 0 | B |
45301 warnings generated when compiling for host. Suppressed 45338 warnings (45291 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.