49_Max_reduction_over_a_dimension
• coalesced_global_access_max_reduce_base
import torch
import torch.nn as nn
import torch.functional as F
def module_fn(x: torch.Tensor, dim: int) -> torch.Tensor:
"""
Applies Max 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 Max reduction over the specified dimension
"""
return torch.max(x, dim=dim)[0]
class Model(nn.Module):
"""
Simple model that performs Max 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 Max 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 Max 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 Max 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 Max reduction over the specified dimension to the input tensor.
Args:
x (torch.Tensor): Input tensor.
Returns:
torch.Tensor: Output tensor after Max reduction over the specified dimension.
"""
return torch.max(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>
// Kernel ensuring coalesced global memory access
// Efficient usage of shared memory for block-wide reduction
template <typename scalar_t>
__global__ void coalesced_global_access_max_reduce_kernel(
const scalar_t* __restrict__ input,
scalar_t* __restrict__ output,
const int64_t dim_size,
const int64_t inner_size,
const int64_t num_outputs
) {
for (int out_idx = blockIdx.x; out_idx < num_outputs; out_idx += gridDim.x) {
int outer_idx = out_idx / inner_size;
int inner_idx = out_idx % inner_size;
int64_t base = outer_idx * dim_size * inner_size + inner_idx;
int tid = threadIdx.x;
int block_size = blockDim.x;
scalar_t thread_max = -INFINITY;
for (int j = tid; j < dim_size; j += block_size) {
scalar_t val = input[base + j * inner_size]; // Coalesced access
thread_max = max(thread_max, val);
}
extern __shared__ char sdata[];
scalar_t* shmem = reinterpret_cast<scalar_t*>(sdata);
shmem[tid] = thread_max;
__syncthreads();
for (unsigned int s = block_size / 2; s > 0; s >>= 1) {
if (tid < s) {
shmem[tid] = max(shmem[tid], shmem[tid + s]);
}
__syncthreads();
}
if (tid == 0) {
output[out_idx] = shmem[0];
}
}
}
// CUDA forward function with coalesced memory access
torch::Tensor max_reduce_cuda_forward(torch::Tensor input, int64_t dim) {
if (dim < 0) dim += input.dim();
int64_t outer_size = 1;
for (int i = 0; i < dim; i++) {
outer_size *= input.size(i);
}
int64_t inner_size = 1;
for (int i = dim + 1; i < input.dim(); i++) {
inner_size *= input.size(i);
}
const int64_t dim_size = input.size(dim);
const int64_t num_outputs = outer_size * inner_size;
auto output_sizes = input.sizes().vec();
output_sizes.erase(output_sizes.begin() + dim);
auto output = torch::empty(output_sizes, input.options());
int block_size = 256;
if (dim_size > 512) {
block_size = 512;
}
if (num_outputs < block_size) {
block_size = num_outputs;
}
int blocks = (num_outputs < 1024) ? num_outputs : 1024;
size_t shared_mem_size = block_size * input.element_size();
AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.scalar_type(), "coalesced_max_reduce_forward", ([&] {
coalesced_global_access_max_reduce_kernel<scalar_t><<<blocks, block_size, shared_mem_size>>>(
input.data_ptr<scalar_t>(),
output.data_ptr<scalar_t>(),
dim_size,
inner_size,
num_outputs
);
}));
return output;
}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
m.def("forward", &max_reduce_cuda_forward, "Max reduce forward with coalesced memory access (CUDA)");
}
Metric | Value | Unit | Variance | Samples |
---|---|---|---|---|
Executed Ipc Active | 1.944 | inst/cycle | 0.000 | 5 |
Executed Ipc Elapsed | 1.606 | inst/cycle | 0.000 | 5 |
Issue Slots Busy | 48.732 | % | 0.009 | 5 |
Issued Ipc Active | 1.948 | inst/cycle | 0.000 | 5 |
SM Busy | 48.732 | % | 0.009 | 5 |
Memory Throughput | 260532991294.238 | byte/second | 3585518902691034624.000 | 5 |
Mem Busy | 59.052 | % | 0.145 | 5 |
Max Bandwidth | 31.120 | % | 1.307 | 5 |
L1/TEX Hit Rate | 0.000 | % | 0.000 | 5 |
L2 Hit Rate | 86.106 | % | 1.790 | 5 |
Mem Pipes Busy | 25.820 | % | 0.026 | 5 |
Warp Cycles Per Issued Instruction | 27.600 | cycle | 0.010 | 5 |
Warp Cycles Per Executed Instruction | 27.670 | cycle | 0.010 | 5 |
Avg. Active Threads Per Warp | 31.740 | 0.000 | 5 | |
Avg. Not Predicated Off Threads Per Warp | 23.290 | 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 | 16.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 | 83.968 | % | 0.034 | 5 |
Achieved Active Warps Per SM | 53.738 | warp | 0.014 | 5 |
Rule | Description |
---|---|
INF HighPipeUtilization | ALU is the highest-utilized pipeline (38.7%) 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 31.7 threads being active per cycle. This is further reduced to 23.3 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 (83.9%) 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 | 377277.74 | μs |
Device Time | 344.86 | μs |
Self CPU Time | 35.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::_to_copy | ||
CPU Time | 377242.52 | μs |
Device Time | 344.86 | μs |
Self CPU Time | 111.57 | μ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 | 376559.50 | μs |
Device Time | 0.00 | μs |
Self CPU Time | 80.40 | μ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 | 375328.59 | μs |
Device Time | 0.00 | μs |
Self CPU Time | 375328.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 | 310773.06 | μs |
Device Time | 11533.02 | μs |
Self CPU Time | 310773.06 | μs |
Self Device Time | 11533.02 | μs |
CPU Memory Usage | 0 | B |
Device Memory Usage | 0 | B |
Self CPU Memory Usage | 0 | B |
Self Device Memory Usage | 0 | B |
void coalesced_global_access_max_reduce_kernel<float>(float const*, float*, long, long, long) | ||
CPU Time | 0.00 | μs |
Device Time | 55336.16 | μs |
Self CPU Time | 0.00 | μs |
Self Device Time | 55336.16 | μ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 | 12277.02 | μs |
Device Time | 22682.36 | μs |
Self CPU Time | 12277.02 | μs |
Self Device Time | 22682.36 | μ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 | 48995.40 | μs |
Device Time | 347367.59 | μs |
Self CPU Time | 6755.21 | μ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 | 42243.41 | μs |
Device Time | 347367.59 | μs |
Self CPU Time | 8550.62 | μs |
Self Device Time | 347367.59 | μ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 | 347367.59 | μs |
Self CPU Time | 0.00 | μs |
Self Device Time | 347367.59 | μs |
CPU Memory Usage | 0 | B |
Device Memory Usage | 0 | B |
Self CPU Memory Usage | 0 | B |
Self Device Memory Usage | 0 | B |
45289 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.