51_Argmax_over_a_dimension
• stride_loop_argmax_stride_base
import torch
import torch.nn as nn
import torch.functional as F
def module_fn(x: torch.Tensor, dim: int) -> torch.Tensor:
"""
Applies argmax over the specified dimension to the input tensor.
Args:
x (torch.Tensor): Input tensor
dim (int): Dimension to perform argmax over
Returns:
torch.Tensor: Output tensor with argmax applied over specified dimension
"""
return torch.argmax(x, dim)
class Model(nn.Module):
"""
Simple model that performs Argmax over a specified dimension.
"""
def __init__(self, dim: int):
"""
Initializes the model with the dimension to perform argmax.
Args:
dim (int): The dimension to perform argmax over.
"""
super(Model, self).__init__()
self.dim = dim
def forward(self, x: torch.Tensor, fn=module_fn) -> torch.Tensor:
"""
Applies argmax 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 with argmax applied, with the specified dimension 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 Argmax over a specified dimension.
"""
def __init__(self, dim: int):
"""
Initializes the model with the dimension to perform argmax.
Args:
dim (int): The dimension to perform argmax over.
"""
super(Model, self).__init__()
self.dim = dim
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Applies argmax over the specified dimension to the input tensor.
Args:
x (torch.Tensor): Input tensor.
Returns:
torch.Tensor: Output tensor with argmax applied, with the specified dimension removed.
"""
return torch.argmax(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>
#include <cfloat>
#include <vector>
#define WARP_SIZE 32
// Kernel that uses grid-stride loops and internal stride loops to handle large workloads for the reduction dimension.
// Each thread processes multiple elements from the reduction dimension using a stride loop.
// Warp-level shuffle reductions are used first within each warp, then an inter-warp reduction via shared memory is applied.
// This ensures correct boundary handling when dimSize is larger than the number of threads.
__global__ void argmax_stride_loop_kernel(
const float* __restrict__ x,
int64_t* __restrict__ indices,
const int outerSize,
const int dimSize,
const int innerSize) {
// Total number of (outer, inner) pairs
int total = outerSize * innerSize;
// Process the (outer, inner) pairs using a grid-stride loop
for (int idx = blockIdx.x; idx < total; idx += gridDim.x) {
int outer_idx = idx / innerSize;
int inner_idx = idx % innerSize;
// Compute the starting offset for the current (outer, inner) pair
int start_offset = outer_idx * dimSize * innerSize + inner_idx;
// Each thread uses a stride loop over the reduction dimension
float local_max = -FLT_MAX;
int local_arg = -1;
for (int d = threadIdx.x; d < dimSize; d += blockDim.x) {
float val = __ldg(&x[start_offset + d * innerSize]);
if (val > local_max) {
local_max = val;
local_arg = d;
}
}
// Warp-level reduction: each warp reduces its own candidates using shuffle intrinsics
unsigned int mask = __activemask();
for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) {
float other_val = __shfl_down_sync(mask, local_max, offset);
int other_arg = __shfl_down_sync(mask, local_arg, offset);
if (other_val > local_max) {
local_max = other_val;
local_arg = other_arg;
} else if (other_val == local_max && other_arg < local_arg) {
local_arg = other_arg;
}
}
// Each warp's lane 0 now contains a candidate result.
int warp_id = threadIdx.x / WARP_SIZE;
int lane = threadIdx.x % WARP_SIZE;
int nWarps = (blockDim.x + WARP_SIZE - 1) / WARP_SIZE;
// Use dynamically allocated shared memory for inter-warp reduction
extern __shared__ char shared_mem[];
float* warp_max = (float*)shared_mem; // Space for nWarps float values
int* warp_arg = (int*)(shared_mem + nWarps * sizeof(float)); // Followed by nWarps int values
if (lane == 0) {
warp_max[warp_id] = local_max;
warp_arg[warp_id] = local_arg;
}
__syncthreads();
// Let the first warp reduce the per-warp candidates
if (threadIdx.x < nWarps) {
local_max = warp_max[threadIdx.x];
local_arg = warp_arg[threadIdx.x];
} else {
local_max = -FLT_MAX;
local_arg = -1;
}
if (threadIdx.x < WARP_SIZE) {
mask = 0xffffffff;
for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) {
float other_val = __shfl_down_sync(mask, local_max, offset);
int other_arg = __shfl_down_sync(mask, local_arg, offset);
if (other_val > local_max) {
local_max = other_val;
local_arg = other_arg;
} else if (other_val == local_max && other_arg < local_arg) {
local_arg = other_arg;
}
}
if (threadIdx.x == 0) {
indices[idx] = local_arg;
}
}
__syncthreads(); // Synchronize before proceeding to the next (outer, inner) pair
}
}
// Host function to launch the CUDA kernel
// Computes the outer, reduction (dim) and inner sizes from the input tensor.
// The output tensor has the same shape as the input with the reduction dimension removed.
torch::Tensor argmax_forward_cuda(const torch::Tensor& x, const int64_t dim) {
TORCH_CHECK(x.scalar_type() == at::kFloat, "Only float32 is supported.");
auto x_contig = x.contiguous();
auto sizes = x_contig.sizes();
int ndim = x_contig.dim();
TORCH_CHECK(dim >= 0 && dim < ndim, "Invalid dim for argmax.");
int outerSize = 1;
for (int i = 0; i < dim; i++) {
outerSize *= sizes[i];
}
int dimSize = sizes[dim];
int innerSize = 1;
for (int i = dim + 1; i < ndim; i++) {
innerSize *= sizes[i];
}
// Build the output shape by removing the reduction dimension
std::vector<int64_t> out_sizes;
for (int i = 0; i < ndim; i++) {
if (i != dim)
out_sizes.push_back(sizes[i]);
}
auto options = torch::TensorOptions().device(x.device()).dtype(torch::kLong);
auto indices = torch::empty(out_sizes, options);
// Launch configuration
const int threads = 256;
int total = outerSize * innerSize;
int blocks = (total < 1024) ? total : 1024; // Cap grid size to 1024 blocks
int nWarps = (threads + WARP_SIZE - 1) / WARP_SIZE;
size_t shared_mem_size = nWarps * (sizeof(float) + sizeof(int));
argmax_stride_loop_kernel<<<blocks, threads, shared_mem_size>>>(
x_contig.data_ptr<float>(),
indices.data_ptr<int64_t>(),
outerSize,
dimSize,
innerSize
);
return indices;
}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
m.def("forward", &argmax_forward_cuda, "ArgMax CUDA forward (stride-loop with boundary handling)");
}
Metric | Value | Unit | Variance | Samples |
---|---|---|---|---|
Executed Ipc Active | 1.628 | inst/cycle | 0.000 | 5 |
Executed Ipc Elapsed | 1.288 | inst/cycle | 0.000 | 5 |
Issue Slots Busy | 40.926 | % | 0.006 | 5 |
Issued Ipc Active | 1.636 | inst/cycle | 0.000 | 5 |
SM Busy | 40.972 | % | 0.006 | 5 |
Memory Throughput | 295428138561.232 | byte/second | 10737376756270249984.000 | 5 |
Mem Busy | 53.872 | % | 0.334 | 5 |
Max Bandwidth | 33.018 | % | 0.462 | 5 |
L1/TEX Hit Rate | 0.000 | % | 0.000 | 5 |
L2 Hit Rate | 84.798 | % | 0.232 | 5 |
Mem Pipes Busy | 18.528 | % | 0.039 | 5 |
Warp Cycles Per Issued Instruction | 33.202 | cycle | 0.003 | 5 |
Warp Cycles Per Executed Instruction | 33.382 | cycle | 0.003 | 5 |
Avg. Active Threads Per Warp | 32.000 | 0.000 | 5 | |
Avg. Not Predicated Off Threads Per Warp | 28.680 | 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 | 85.172 | % | 0.078 | 5 |
Achieved Active Warps Per SM | 54.510 | warp | 0.032 | 5 |
Rule | Description |
---|---|
INF HighPipeUtilization | ALU is the highest-utilized pipeline (41.1%) 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 (85.2%) 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 | 610565.98 | μs |
Device Time | 364.51 | μs |
Self CPU Time | 44.15 | μ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 | 610521.84 | μs |
Device Time | 364.51 | μs |
Self CPU Time | 101.27 | μ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 | 609822.78 | μs |
Device Time | 0.00 | μs |
Self CPU Time | 82.84 | μ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 | 608002.66 | μs |
Device Time | 0.00 | μs |
Self CPU Time | 608002.66 | μ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 | 330770.10 | μs |
Device Time | 13745.17 | μs |
Self CPU Time | 330770.10 | μs |
Self Device Time | 13745.17 | μs |
CPU Memory Usage | 0 | B |
Device Memory Usage | 0 | B |
Self CPU Memory Usage | 0 | B |
Self Device Memory Usage | 0 | B |
argmax_stride_loop_kernel(float const*, long*, int, int, int) | ||
CPU Time | 0.00 | μs |
Device Time | 53375.42 | μs |
Self CPU Time | 0.00 | μs |
Self Device Time | 53375.42 | μ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 | 13429.37 | μs |
Device Time | 25193.46 | μs |
Self CPU Time | 13429.37 | μs |
Self Device Time | 25193.46 | μ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 | 48413.16 | μs |
Device Time | 383500.58 | μs |
Self CPU Time | 7590.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 | 40824.85 | μs |
Device Time | 383500.58 | μs |
Self CPU Time | 10926.65 | μs |
Self Device Time | 383500.58 | μ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 | 383500.58 | μs |
Self CPU Time | 0.00 | μs |
Self Device Time | 383500.58 | μs |
CPU Memory Usage | 0 | B |
Device Memory Usage | 0 | B |
Self CPU Memory Usage | 0 | B |
Self Device Memory Usage | 0 | B |
45288 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.