53_Min_reduction_over_a_dimension
• efficient_min_reduce_kernel_base
import torch
import torch.nn as nn
import torch.functional as F
def module_fn(x: torch.Tensor, dim: int) -> torch.Tensor:
"""
Applies min reduction over the specified dimension to the input tensor.
Args:
x (torch.Tensor): Input tensor
dim (int): The dimension to reduce over
Returns:
torch.Tensor: Output tensor after min reduction over the specified dimension
"""
return torch.min(x, dim)[0]
class Model(nn.Module):
"""
Simple model that performs min 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:
"""
Applies min reduction over the specified dimension to the input tensor.
Args:
x (torch.Tensor): Input tensor
fn: Function to apply (defaults to module_fn)
Returns:
torch.Tensor: Output tensor after min reduction over the specified dimension
"""
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] # Example, change to desired dimension
import torch
import torch.nn as nn
class Model(nn.Module):
"""
Simple model that performs min 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:
"""
Applies min reduction over the specified dimension to the input tensor.
Args:
x (torch.Tensor): Input tensor.
Returns:
torch.Tensor: Output tensor after min reduction over the specified dimension.
"""
return torch.min(x, dim=self.dim)[0]
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] # Example, change to desired dimension
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <vector>
#include <limits>
#include <c10/cuda/CUDAStream.h>
// Improved CUDA kernel that uses warp-level primitives to perform
// a more efficient min reduction along a specified dimension.
template <typename scalar_t>
__global__ void efficient_min_reduce_kernel(
const scalar_t* __restrict__ input,
scalar_t* __restrict__ output,
const int outer,
const int r,
const int inner) {
// Calculate globally unique thread index
int idx = blockIdx.x * blockDim.x + threadIdx.x;
int total_threads = outer * inner;
// Each warp is responsible for reducing elements over the r dimension
int warpId = idx / 32;
if (warpId >= total_threads) return;
int outer_idx = warpId / inner;
int inner_idx = warpId % inner;
// Starting index for reduction in the r dimension
int base = outer_idx * (r * inner) + inner_idx;
int lane = threadIdx.x % 32;
// Use warp shuffle to calculate minimum
scalar_t my_min = std::numeric_limits<scalar_t>::max();
for (int j = lane; j < r; j += 32) {
scalar_t val = input[base + j * inner];
if (val < my_min) {
my_min = val;
}
}
// Perform warp reduction
for (int offset = 16; offset > 0; offset /= 2) {
scalar_t other = __shfl_down_sync(0xffffffff, my_min, offset);
if (other < my_min) {
my_min = other;
}
}
// Write reduced value to output array
if (lane == 0) {
output[warpId] = my_min;
}
}
// Forward function: prepares tensor dimensions and launches the kernel
torch::Tensor forward(torch::Tensor input, int64_t dim) {
TORCH_CHECK(input.is_cuda(), "input must be a CUDA tensor");
if (!input.is_contiguous()) {
input = input.contiguous();
}
int ndim = input.dim();
TORCH_CHECK(dim >= 0 && dim < ndim, "dim out of range");
// Calculate sizes
int outer = 1;
for (int i = 0; i < dim; i++) {
outer *= input.size(i);
}
int r = input.size(dim);
int inner = 1;
for (int i = dim + 1; i < ndim; i++) {
inner *= input.size(i);
}
// Create output tensor
std::vector<int64_t> output_shape;
for (int i = 0; i < ndim; i++) {
if (i != dim) {
output_shape.push_back(input.size(i));
}
}
auto output = torch::empty(output_shape, input.options());
int total_warps = outer * inner;
int threads_per_block = 128;
int num_blocks = (total_warps * 32 + threads_per_block - 1) / threads_per_block;
AT_DISPATCH_ALL_TYPES(input.scalar_type(), "efficient_min_reduce", ([&] {
efficient_min_reduce_kernel<scalar_t><<<num_blocks, threads_per_block, 0,
c10::cuda::getCurrentCUDAStream().stream()>>>(
input.data_ptr<scalar_t>(),
output.data_ptr<scalar_t>(),
outer,
r,
inner);
}));
return output;
}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
m.def("forward", &forward, "Min reduction over a specified dimension using improved CUDA kernel");
}
Metric | Value | Unit | Variance | Samples |
---|---|---|---|---|
Executed Ipc Active | 0.386 | inst/cycle | 0.000 | 5 |
Executed Ipc Elapsed | 0.284 | inst/cycle | 0.000 | 5 |
Issue Slots Busy | 9.962 | % | 0.009 | 5 |
Issued Ipc Active | 0.398 | inst/cycle | 0.000 | 5 |
SM Busy | 9.962 | % | 0.009 | 5 |
Memory Throughput | 459986501054.912 | byte/second | 23412416578237489152.000 | 5 |
Mem Busy | 56.570 | % | 0.304 | 5 |
Max Bandwidth | 14.882 | % | 0.093 | 5 |
L1/TEX Hit Rate | 74.552 | % | 0.000 | 5 |
L2 Hit Rate | 61.982 | % | 0.015 | 5 |
Mem Pipes Busy | 3.440 | % | 0.001 | 5 |
Warp Cycles Per Issued Instruction | 59.770 | cycle | 0.179 | 5 |
Warp Cycles Per Executed Instruction | 61.912 | cycle | 0.190 | 5 |
Avg. Active Threads Per Warp | 30.590 | 0.000 | 5 | |
Avg. Not Predicated Off Threads Per Warp | 28.400 | 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 | 37.732 | % | 0.013 | 5 |
Achieved Active Warps Per SM | 24.150 | warp | 0.005 | 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 Occupancy | This kernel's theoretical occupancy is not impacted by any block limit. The difference between calculated theoretical (100.0%) and measured achieved occupancy (37.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. |
Operation / Metric | Value | Unit |
---|---|---|
aten::to | ||
CPU Time | 366772.80 | μs |
Device Time | 386.94 | μs |
Self CPU Time | 44.09 | μ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 | 366728.72 | μs |
Device Time | 386.94 | μs |
Self CPU Time | 97.29 | μ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 | 366007.44 | μs |
Device Time | 0.00 | μs |
Self CPU Time | 80.59 | μ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 | 365723.59 | μs |
Device Time | 0.00 | μs |
Self CPU Time | 365723.59 | μ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 | 484226.29 | μs |
Device Time | 627.77 | μs |
Self CPU Time | 484226.29 | μs |
Self Device Time | 627.77 | μs |
CPU Memory Usage | 0 | B |
Device Memory Usage | 0 | B |
Self CPU Memory Usage | 0 | B |
Self Device Memory Usage | 0 | B |
void efficient_min_reduce_kernel<float>(float const*, float*, int, int, int) | ||
CPU Time | 0.00 | μs |
Device Time | 55416.68 | μs |
Self CPU Time | 0.00 | μs |
Self Device Time | 55416.68 | μ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 | 60843.06 | μs |
Device Time | 584626.39 | μs |
Self CPU Time | 12417.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::fill_ | ||
CPU Time | 48429.69 | μs |
Device Time | 584626.39 | μs |
Self CPU Time | 14922.17 | μs |
Self Device Time | 584626.39 | μ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 | 584626.39 | μs |
Self CPU Time | 0.00 | μs |
Self Device Time | 584626.39 | μs |
CPU Memory Usage | 0 | B |
Device Memory Usage | 0 | B |
Self CPU Memory Usage | 0 | B |
Self Device Memory Usage | 0 | B |
45296 warnings generated when compiling for host. Suppressed 45327 warnings (45280 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.