numr 0.15.1

High-performance numerical computing with multi-backend GPU acceleration (CPU/CUDA/WebGPU)
Documentation
//! Index-returning reductions (argmax, argmin) for WebGPU.
//!
//! The output carries positions, so it is always allocated as I32 regardless of
//! the input dtype.

use super::super::helpers::*;
use crate::dtype::DType;
use crate::error::{Error, Result};
use crate::ops::reduce::{ensure_arg_reduce_dim_nonempty, reduce_output_shape};
use crate::runtime::ensure_contiguous;
use crate::runtime::wgpu::shaders::linear_grid::element_count_u32;
use crate::runtime::wgpu::shaders::reduce;
use crate::runtime::wgpu::{WgpuClient, WgpuRuntime};
use crate::tensor::Tensor;

pub(crate) fn native_argreduce_op(
    client: &WgpuClient,
    op: &'static str,
    a: &Tensor<WgpuRuntime>,
    dim: usize,
    keepdim: bool,
) -> Result<Tensor<WgpuRuntime>> {
    let dtype = a.dtype();
    let shape = a.shape();
    let ndim = shape.len();

    if dim >= ndim {
        return Err(Error::InvalidDimension {
            dim: dim as isize,
            ndim,
        });
    }

    let a_contig = ensure_contiguous(a)?;

    let reduce_size = shape[dim];
    // No index names an element of an empty dimension, and the shader's seed
    // read would land past the end of the zero-byte allocation.
    ensure_arg_reduce_dim_nonempty(reduce_size, dim, op)?;
    let outer_size: usize = shape[..dim].iter().product();
    let inner_size: usize = shape[dim + 1..].iter().product();
    let numel_out = outer_size * inner_size;

    // Reducing the only dimension of a 1-D tensor must give a scalar, not `[1]`.
    let out_shape = reduce_output_shape(shape, &[dim], keepdim);

    // Output indices as I32 (WebGPU doesn't support I64, shader uses u32)
    let out = alloc_output(client, &out_shape, DType::I32)?;

    // A zero-element output has nothing to hold, and `get_tensor_buffer` has no
    // buffer to return for its zero-byte allocation. Never restore a `.max(1)` on
    // `outer_size`, `inner_size` or `numel_out`: it would make this guard
    // unreachable and bind a buffer the output does not have.
    if out.numel() == 0 {
        return Ok(out);
    }
    // The input count bounds every size cast to u32 below.
    element_count_u32(a.numel(), "argreduce")?;

    let a_buf = get_tensor_buffer(&a_contig)?;
    let out_buf = get_tensor_buffer(&out)?;

    let params = ArgReduceParams {
        reduce_size: reduce_size as u32,
        outer_size: outer_size as u32,
        inner_size: inner_size as u32,
        numel_out: numel_out as u32,
    };
    let params_buf = create_params_buffer(client, &params);

    reduce::launch_argreduce_op(
        client.pipeline_cache(),
        client.wgpu_queue(),
        op,
        &a_buf,
        &out_buf,
        &params_buf,
        numel_out,
        dtype,
    )?;

    Ok(out)
}