48_Mean_reduction_over_a_dimension
• hybrid_mean_reduce_base
import torch
import torch.nn as nn
import torch.nn.functional as F
def module_fn(x: torch.Tensor, dim: int) -> torch.Tensor:
"""
Reduces the input tensor along the specified dimension by taking the mean.
Args:
x (torch.Tensor): Input tensor of arbitrary shape.
dim (int): The dimension to reduce over.
Returns:
torch.Tensor: Output tensor with reduced dimension. The shape of the output is the same as the input except for the reduced dimension which is removed.
"""
return torch.mean(x, dim=dim)
class Model(nn.Module):
"""
Simple model that performs mean reduction over a specific dimension.
"""
def __init__(self, dim: int):
"""
Initializes the model with the dimension to reduce over.
Args:
dim (int): The dimension to reduce over.
"""
super(Model, self).__init__()
self.dim = dim
def forward(self, x: torch.Tensor, fn=module_fn) -> torch.Tensor:
"""
Reduces the input tensor along the specified dimension by taking the mean.
Args:
x (torch.Tensor): Input tensor of arbitrary shape.
Returns:
torch.Tensor: Output tensor with reduced dimension. The shape of the output is the same as the input except for the reduced dimension which is removed.
"""
return fn(x, self.dim)
batch_size = 16
dim1 = 256
dim2 = 256
def get_inputs():
x = torch.randn(batch_size, dim1, dim2)
return [x]
def get_init_inputs():
return [1]
import torch
import torch.nn as nn
class Model(nn.Module):
"""
Simple model that performs mean reduction over a specific dimension.
"""
def __init__(self, dim: int):
"""
Initializes the model with the dimension to reduce over.
Args:
dim (int): The dimension to reduce over.
"""
super(Model, self).__init__()
self.dim = dim
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Reduces the input tensor along the specified dimension by taking the mean.
Args:
x (torch.Tensor): Input tensor of arbitrary shape.
Returns:
torch.Tensor: Output tensor with reduced dimension. The shape of the output is the same as the input except for the reduced dimension which is removed.
"""
return torch.mean(x, dim=self.dim)
batch_size = 16
dim1 = 256
dim2 = 256
def get_inputs():
x = torch.randn(batch_size, dim1, dim2)
return [x]
def get_init_inputs():
return [1]
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
// Optimized warp reduction using shuffle instructions
template <typename scalar_t>
__device__ __forceinline__ scalar_t warp_reduce_sum(scalar_t val) {
unsigned int mask = 0xffffffff;
for (int offset = 16; offset > 0; offset /= 2) {
val += __shfl_down_sync(mask, val, offset);
}
return val;
}
// Hybrid block reduction combining shared memory and warp shuffles
template <typename scalar_t>
__device__ __forceinline__ scalar_t hybrid_block_reduce(
scalar_t* sdata,
scalar_t thread_sum,
const int tid,
const int blockSize) {
const int lane = tid & 31;
const int wid = tid >> 5;
const int warps = blockSize >> 5;
// First do warp-level reduction
scalar_t warp_sum = warp_reduce_sum(thread_sum);
// Write reduced warp sums to shared memory
if (lane == 0) {
sdata[wid] = warp_sum;
}
__syncthreads();
// Final reduction: let first warp handle all partial sums
scalar_t block_sum = 0;
if (tid < warps) {
block_sum = warp_reduce_sum(tid < warps ? sdata[tid] : 0);
}
return block_sum;
}
template <typename scalar_t>
__global__ void hybrid_mean_reduce_kernel(
const scalar_t* __restrict__ input,
scalar_t* __restrict__ output,
int64_t outer_size,
int64_t dim_size,
int64_t inner_size) {
extern __shared__ char shared_mem[];
scalar_t* sdata = reinterpret_cast<scalar_t*>(shared_mem);
const int tid = threadIdx.x;
const int out_idx = blockIdx.x;
if (out_idx >= outer_size * inner_size)
return;
const int outer_idx = out_idx / inner_size;
const int inner_idx = out_idx % inner_size;
const int base_idx = outer_idx * dim_size * inner_size + inner_idx;
// Coalesced memory access pattern with grid-stride loop
scalar_t thread_sum = 0;
#pragma unroll
for (int i = tid; i < dim_size; i += blockDim.x) {
thread_sum += input[base_idx + i * inner_size];
}
// Perform hybrid reduction
scalar_t block_sum = hybrid_block_reduce(sdata, thread_sum, tid, blockDim.x);
if (tid == 0) {
output[out_idx] = block_sum / static_cast<scalar_t>(dim_size);
}
}
torch::Tensor mean_reduce_cuda(torch::Tensor input, int64_t dim) {
if (dim < 0) dim += input.dim();
auto sizes = input.sizes().vec();
int64_t dim_size = sizes[dim];
int64_t outer_size = 1;
for (int i = 0; i < dim; i++) {
outer_size *= sizes[i];
}
int64_t inner_size = 1;
for (size_t i = dim + 1; i < sizes.size(); i++) {
inner_size *= sizes[i];
}
sizes.erase(sizes.begin() + dim);
auto output = torch::empty(sizes, input.options());
const int threads = 256;
const int blocks = outer_size * inner_size;
const int warps_per_block = threads >> 5;
AT_DISPATCH_FLOATING_TYPES(input.scalar_type(), "hybrid_mean_reduce", ([&] {
const int shared_mem_size = warps_per_block * sizeof(scalar_t);
hybrid_mean_reduce_kernel<scalar_t><<<blocks, threads, shared_mem_size>>>(
input.data_ptr<scalar_t>(),
output.data_ptr<scalar_t>(),
outer_size,
dim_size,
inner_size
);
}));
return output;
}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
m.def("forward", &mean_reduce_cuda, "Hybrid mean reduction (CUDA)");
}
Metric | Value | Unit | Variance | Samples |
---|---|---|---|---|
Executed Ipc Active | 1.646 | inst/cycle | 0.000 | 5 |
Executed Ipc Elapsed | 1.306 | inst/cycle | 0.000 | 5 |
Issue Slots Busy | 42.156 | % | 0.114 | 5 |
Issued Ipc Active | 1.686 | inst/cycle | 0.000 | 5 |
SM Busy | 42.156 | % | 0.114 | 5 |
Memory Throughput | 334568728200.014 | byte/second | 13682238193040314368.000 | 5 |
Mem Busy | 56.690 | % | 0.944 | 5 |
Max Bandwidth | 31.754 | % | 1.534 | 5 |
L1/TEX Hit Rate | 3.976 | % | 0.189 | 5 |
L2 Hit Rate | 85.912 | % | 0.879 | 5 |
Mem Pipes Busy | 15.104 | % | 0.028 | 5 |
Warp Cycles Per Issued Instruction | 27.714 | cycle | 0.020 | 5 |
Warp Cycles Per Executed Instruction | 28.400 | cycle | 0.021 | 5 |
Avg. Active Threads Per Warp | 30.090 | 0.000 | 5 | |
Avg. Not Predicated Off Threads Per Warp | 25.820 | 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 | 10.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 | 73.792 | % | 0.091 | 5 |
Achieved Active Warps Per SM | 47.226 | warp | 0.037 | 5 |
Rule | Description |
---|---|
INF HighPipeUtilization | ALU is the highest-utilized pipeline (25.5%) 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. |
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 Occupancy | This kernel's theoretical occupancy is not impacted by any block limit. The difference between calculated theoretical (100.0%) and measured achieved occupancy (74.3%) 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 | 464848.80 | μs |
Device Time | 378.49 | μs |
Self CPU Time | 32.91 | μ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 | 464815.89 | μs |
Device Time | 378.49 | μs |
Self CPU Time | 82.74 | μ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 | 464127.81 | μs |
Device Time | 0.00 | μs |
Self CPU Time | 66.44 | μ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 | 463858.60 | μs |
Device Time | 0.00 | μs |
Self CPU Time | 463858.60 | μ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 | 529803.09 | μs |
Device Time | 20386.31 | μs |
Self CPU Time | 529803.09 | μs |
Self Device Time | 20386.31 | μs |
CPU Memory Usage | 0 | B |
Device Memory Usage | 0 | B |
Self CPU Memory Usage | 0 | B |
Self Device Memory Usage | 0 | B |
void hybrid_mean_reduce_kernel<float>(float const*, float*, long, long, long) | ||
CPU Time | 0.00 | μs |
Device Time | 83386.17 | μs |
Self CPU Time | 0.00 | μs |
Self Device Time | 83386.17 | μ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 | 19194.73 | μs |
Device Time | 40601.19 | μs |
Self CPU Time | 19194.73 | μs |
Self Device Time | 40601.19 | μ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 | 64485.72 | μs |
Device Time | 606649.04 | μs |
Self CPU Time | 12536.33 | μ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 | 51953.13 | μs |
Device Time | 606649.04 | μs |
Self CPU Time | 14794.33 | μs |
Self Device Time | 606649.04 | μ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 | 606649.04 | μs |
Self CPU Time | 0.00 | μs |
Self Device Time | 606649.04 | μs |
CPU Memory Usage | 0 | B |
Device Memory Usage | 0 | B |
Self CPU Memory Usage | 0 | B |
Self Device Memory Usage | 0 | B |
45287 warnings generated when compiling for host. Suppressed 45322 warnings (45275 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.