import torch
import torch.nn as nn
import torch.nn.functional as F
import math
def module_fn(x: torch.Tensor) -> torch.Tensor:
"""
Implementation of the Gaussian Error Linear Units (GELU) activation function currently in Google BERT repo (identical to OpenAI GPT).
Args:
x (torch.Tensor): Input tensor.
Returns:
torch.Tensor: Output tensor.
"""
return (
0.5
* x
* (
1.0
+ torch.tanh(math.sqrt(2.0 / math.pi) * (x + 0.044715 * torch.pow(x, 3.0)))
)
)
class Model(nn.Module):
"""
Implementation of the GELU activation function currently in Google BERT repo (identical to OpenAI GPT).
Reference: Gaussian Error Linear Units (GELU) paper: https://arxiv.org/abs/1606.08415
"""
def __init__(self):
super(Model, self).__init__()
def forward(self, x, fn=module_fn):
return fn(x)
batch_size = 2000
dim = 2000
def get_inputs():
return [torch.randn(batch_size, dim)]
def get_init_inputs():
return []
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
# From https://github.com/karpathy/minGPT/blob/master/mingpt/model.py
class Model(nn.Module):
"""
Implementation of the GELU activation function currently in Google BERT repo (identical to OpenAI GPT).
Reference: Gaussian Error Linear Units (GELU) paper: https://arxiv.org/abs/1606.08415
"""
def __init__(self):
super(Model, self).__init__()
def forward(self, x):
return (
0.5
* x
* (
1.0
+ torch.tanh(
math.sqrt(2.0 / math.pi) * (x + 0.044715 * torch.pow(x, 3.0))
)
)
)
batch_size = 2000
dim = 2000
def get_inputs():
return [torch.randn(batch_size, dim)]
def get_init_inputs():
return []
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <math.h>
// Device function for GELU activation
__device__ __forceinline__ float gelu(float x) {
const float sqrt_2_over_pi = 0.7978845608f;
const float coeff = 0.044715f;
float x_cubed = x * x * x;
float inner = (x + coeff * x_cubed) * sqrt_2_over_pi;
return 0.5f * x * (1.0f + tanhf(inner));
}
// Kernel using vectorized memory accesses to ensure coalescing
__global__ void gelu_kernel_vectorized(const float* __restrict__ x, float* __restrict__ y, int n) {
// Process the bulk of the data using float4 (vectorized) loads and stores
int vec_size = n / 4; // number of float4 elements
int idx = blockIdx.x * blockDim.x + threadIdx.x;
int stride = blockDim.x * gridDim.x;
// Process vectorized part
for (int i = idx; i < vec_size; i += stride) {
// Reinterpret global memory as float4
float4 in_val = reinterpret_cast<const float4*>(x)[i];
float4 out_val;
out_val.x = gelu(in_val.x);
out_val.y = gelu(in_val.y);
out_val.z = gelu(in_val.z);
out_val.w = gelu(in_val.w);
reinterpret_cast<float4*>(y)[i] = out_val;
}
// Process any remaining elements
int remainder = n % 4;
int tail_start = vec_size * 4;
for (int j = idx; j < remainder; j += stride) {
int index = tail_start + j;
y[index] = gelu(x[index]);
}
}
// Host function to launch the vectorized kernel
torch::Tensor gelu_forward(torch::Tensor x) {
TORCH_CHECK(x.is_cuda(), "Input tensor must be on CUDA");
TORCH_CHECK(x.is_contiguous(), "Input tensor must be contiguous");
auto y = torch::empty_like(x);
int n = x.numel();
const int threads = 256;
int num_vec = n / 4;
int blocks = (num_vec + threads - 1) / threads;
// Ensure at least one block is launched
if (blocks == 0) { blocks = 1; }
gelu_kernel_vectorized<<<blocks, threads>>>(x.data_ptr<float>(), y.data_ptr<float>(), n);
return y;
}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
m.def("forward", &gelu_forward, "GELU forward CUDA implementation with vectorized memory accesses");
}
Metric | Value | Unit | Variance | Samples |
---|---|---|---|---|
Executed Ipc Active | 2.506 | inst/cycle | 0.001 | 5 |
Executed Ipc Elapsed | 1.938 | inst/cycle | 0.000 | 5 |
Issue Slots Busy | 63.346 | % | 0.350 | 5 |
Issued Ipc Active | 2.534 | inst/cycle | 0.001 | 5 |
SM Busy | 63.346 | % | 0.350 | 5 |
Memory Throughput | 1440537078757.784 | byte/second | 277097206480609837056.000 | 5 |
Mem Busy | 35.696 | % | 0.146 | 5 |
Max Bandwidth | 43.122 | % | 0.257 | 5 |
L1/TEX Hit Rate | 0.000 | % | 0.000 | 5 |
L2 Hit Rate | 50.466 | % | 0.045 | 5 |
Mem Pipes Busy | 16.000 | % | 0.025 | 5 |
Warp Cycles Per Issued Instruction | 20.038 | cycle | 0.032 | 5 |
Warp Cycles Per Executed Instruction | 20.256 | cycle | 0.033 | 5 |
Avg. Active Threads Per Warp | 23.800 | 0.000 | 5 | |
Avg. Not Predicated Off Threads Per Warp | 22.980 | 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 | 32.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 | 79.780 | % | 0.230 | 5 |
Achieved Active Warps Per SM | 51.060 | warp | 0.094 | 5 |
Rule | Description |
---|---|
INF HighPipeUtilization | FMA is the highest-utilized pipeline (30.9%) based on active cycles, taking into account the rates of its different instructions. It executes 32-bit floating point (FADD, FMUL, FMAD, ...) and integer (IMUL, IMAD) operations. It is well-utilized, but should not be a bottleneck. |
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 23.8 threads being active per cycle. This is further reduced to 23.0 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 (80.4%) 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 | 652213.26 | μs |
Device Time | 1531.42 | μs |
Self CPU Time | 38.34 | μ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 | 652174.92 | μs |
Device Time | 1531.42 | μs |
Self CPU Time | 110.30 | μ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 | 660954.19 | μs |
Device Time | 0.00 | μs |
Self CPU Time | 6421.96 | μ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 | 648456.08 | μs |
Device Time | 0.00 | μs |
Self CPU Time | 648456.08 | μ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 | 203294.40 | μs |
Device Time | 7621.35 | μs |
Self CPU Time | 203294.40 | μs |
Self Device Time | 7621.35 | μs |
CPU Memory Usage | 0 | B |
Device Memory Usage | 0 | B |
Self CPU Memory Usage | 0 | B |
Self Device Memory Usage | 0 | B |
gelu_kernel_vectorized(float const*, float*, int) | ||
CPU Time | 0.00 | μs |
Device Time | 39541.46 | μs |
Self CPU Time | 0.00 | μs |
Self Device Time | 39541.46 | μ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 | 6323.51 | μs |
Device Time | 14689.15 | μs |
Self CPU Time | 6323.51 | μs |
Self Device Time | 14689.15 | μ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 | 45433.16 | μs |
Device Time | 224166.66 | μs |
Self CPU Time | 4140.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 |
aten::fill_ | ||
CPU Time | 41294.90 | μs |
Device Time | 224166.66 | μs |
Self CPU Time | 5526.41 | μs |
Self Device Time | 224166.66 | μ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 | 224244.04 | μs |
Self CPU Time | 0.00 | μs |
Self Device Time | 224244.04 | μs |
CPU Memory Usage | 0 | B |
Device Memory Usage | 0 | B |
Self CPU Memory Usage | 0 | B |
Self Device Memory Usage | 0 | B |
45278 warnings generated when compiling for host. Suppressed 45321 warnings (45274 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.