47_Sum_reduction_over_a_dimension
• hybrid_warp_shared_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:
"""
Applies sum reduction over the specified dimension.
Args:
x (torch.Tensor): Input tensor of shape (..., dim, ...).
dim (int): Dimension to reduce over.
Returns:
torch.Tensor: Output tensor after sum reduction, shape (..., 1, ...).
"""
return torch.sum(x, dim=dim, keepdim=True)
class Model(nn.Module):
"""
Simple model that performs sum reduction over a specified dimension.
"""
def __init__(self, dim: int):
"""
Initializes the model with the dimension to reduce over.
Args:
dim (int): Dimension to reduce over.
"""
super(Model, self).__init__()
self.dim = dim
def forward(self, x: torch.Tensor, fn=module_fn) -> torch.Tensor:
"""
Applies sum reduction over the specified dimension.
Args:
x (torch.Tensor): Input tensor of shape (..., dim, ...).
Returns:
torch.Tensor: Output tensor after sum reduction, shape (..., 1, ...).
"""
return fn(x, self.dim)
batch_size = 16
dim1 = 256
dim2 = 256
reduce_dim = 1
def get_inputs():
x = torch.randn(batch_size, dim1, dim2)
return [x]
def get_init_inputs():
return [reduce_dim]
import torch
import torch.nn as nn
class Model(nn.Module):
"""
Simple model that performs sum reduction over a specified dimension.
"""
def __init__(self, dim: int):
"""
Initializes the model with the dimension to reduce over.
Args:
dim (int): Dimension to reduce over.
"""
super(Model, self).__init__()
self.dim = dim
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Applies sum reduction over the specified dimension.
Args:
x (torch.Tensor): Input tensor of shape (..., dim, ...).
Returns:
torch.Tensor: Output tensor after sum reduction, shape (..., 1, ...).
"""
return torch.sum(x, dim=self.dim, keepdim=True)
batch_size = 16
dim1 = 256
dim2 = 256
reduce_dim = 1
def get_inputs():
x = torch.randn(batch_size, dim1, dim2)
return [x]
def get_init_inputs():
return [reduce_dim]
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
// Hybrid kernel combining shared memory tiling with warp-level primitives
template <typename scalar_t>
__global__ void hybrid_reduce_kernel(
const scalar_t* __restrict__ input,
scalar_t* __restrict__ output,
int64_t reduce_size,
int64_t inner_size) {
constexpr int WARP_SIZE = 32;
constexpr int BLOCK_WARPS = 8; // 8 warps per block = 256 threads
constexpr int BLOCK_SIZE = WARP_SIZE * BLOCK_WARPS;
// Shared memory for block-level reduction
extern __shared__ char smem[];
scalar_t* shared_data = reinterpret_cast<scalar_t*>(smem);
int tid = threadIdx.x;
int warp_id = tid / WARP_SIZE;
int lane_id = tid % WARP_SIZE;
int block_output_idx = blockIdx.x;
// Calculate global indices
int outer_idx = block_output_idx / inner_size;
int inner_idx = block_output_idx % inner_size;
// Each thread processes multiple elements with stride equal to block size
scalar_t thread_sum = 0;
int base_idx = outer_idx * (reduce_size * inner_size) + inner_idx;
// Phase 1: Parallel reduction with loop unrolling
#pragma unroll 4
for (int i = tid; i < reduce_size; i += BLOCK_SIZE) {
thread_sum += input[base_idx + i * inner_size];
}
// Phase 2: Warp-level reduction using shuffle
#pragma unroll
for (int offset = WARP_SIZE/2; offset > 0; offset /= 2) {
thread_sum += __shfl_down_sync(0xffffffff, thread_sum, offset);
}
// First thread in each warp writes to shared memory
if (lane_id == 0) {
shared_data[warp_id] = thread_sum;
}
__syncthreads();
// Phase 3: Final reduction across warps using first warp
if (warp_id == 0) {
// Load warp results
thread_sum = (lane_id < BLOCK_WARPS) ? shared_data[lane_id] : 0;
// Final warp reduction
#pragma unroll
for (int offset = WARP_SIZE/2; offset > 0; offset /= 2) {
thread_sum += __shfl_down_sync(0xffffffff, thread_sum, offset);
}
// Write final result
if (lane_id == 0) {
output[block_output_idx] = thread_sum;
}
}
}
torch::Tensor sum_reduce_cuda(torch::Tensor input, int64_t dim) {
if (dim < 0) dim += input.dim();
auto sizes = input.sizes().vec();
int64_t reduce_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 (int i = dim + 1; i < sizes.size(); i++) inner_size *= sizes[i];
sizes[dim] = 1;
auto output = torch::empty(sizes, input.options());
const int BLOCK_SIZE = 256;
int total_outputs = outer_size * inner_size;
int blocks = total_outputs;
AT_DISPATCH_FLOATING_TYPES(input.scalar_type(), "sum_reduce_cuda", ([&] {
hybrid_reduce_kernel<scalar_t><<<blocks, BLOCK_SIZE,
(BLOCK_SIZE/32) * sizeof(scalar_t)>>>(
input.data_ptr<scalar_t>(),
output.data_ptr<scalar_t>(),
reduce_size,
inner_size
);
}));
return output;
}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
m.def("forward", &sum_reduce_cuda, "Hybrid sum reduction (CUDA)");
}
Metric | Value | Unit | Variance | Samples |
---|---|---|---|---|
Executed Ipc Active | 1.554 | inst/cycle | 0.000 | 5 |
Executed Ipc Elapsed | 1.236 | inst/cycle | 0.000 | 5 |
Issue Slots Busy | 39.070 | % | 0.025 | 5 |
Issued Ipc Active | 1.560 | inst/cycle | 0.000 | 5 |
SM Busy | 39.070 | % | 0.025 | 5 |
Memory Throughput | 365222882624.662 | byte/second | 5168921417524110336.000 | 5 |
Mem Busy | 65.996 | % | 0.084 | 5 |
Max Bandwidth | 29.988 | % | 0.111 | 5 |
L1/TEX Hit Rate | 0.926 | % | 0.065 | 5 |
L2 Hit Rate | 86.032 | % | 0.689 | 5 |
Mem Pipes Busy | 17.352 | % | 0.012 | 5 |
Warp Cycles Per Issued Instruction | 31.956 | cycle | 0.229 | 5 |
Warp Cycles Per Executed Instruction | 32.118 | cycle | 0.231 | 5 |
Avg. Active Threads Per Warp | 31.660 | 0.000 | 5 | |
Avg. Not Predicated Off Threads Per Warp | 27.610 | 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 | 77.426 | % | 0.020 | 5 |
Achieved Active Warps Per SM | 49.554 | warp | 0.008 | 5 |
Rule | Description |
---|---|
INF HighPipeUtilization | ALU is the highest-utilized pipeline (26.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 (77.5%) 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 | 215818.69 | μs |
Device Time | 299.71 | μs |
Self CPU Time | 36.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 |
aten::_to_copy | ||
CPU Time | 215782.32 | μs |
Device Time | 299.71 | μs |
Self CPU Time | 94.49 | μ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 | 215151.64 | μs |
Device Time | 0.00 | μs |
Self CPU Time | 63.82 | μ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 | 214887.67 | μs |
Device Time | 0.00 | μs |
Self CPU Time | 214887.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 |
cudaLaunchKernel | ||
CPU Time | 514920.37 | μs |
Device Time | 21039.16 | μs |
Self CPU Time | 514920.37 | μs |
Self Device Time | 21039.16 | μ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_reduce_kernel<float>(float const*, float*, long, long) | ||
CPU Time | 0.00 | μs |
Device Time | 83896.85 | μs |
Self CPU Time | 0.00 | μs |
Self Device Time | 83896.85 | μ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 | 18179.32 | μs |
Device Time | 38845.98 | μs |
Self CPU Time | 18179.32 | μs |
Self Device Time | 38845.98 | μ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 | 67660.67 | μs |
Device Time | 582399.67 | μs |
Self CPU Time | 13357.38 | μ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 | 54307.79 | μs |
Device Time | 582399.67 | μs |
Self CPU Time | 14171.48 | μs |
Self Device Time | 582399.67 | μ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 | 582399.67 | μs |
Self CPU Time | 0.00 | μs |
Self Device Time | 582399.67 | μs |
CPU Memory Usage | 0 | B |
Device Memory Usage | 0 | B |
Self CPU Memory Usage | 0 | B |
Self Device Memory Usage | 0 | B |
45285 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.