README

Gather Operator

Operator Overview

The Gather operator collects elements from a dense vector by the index array of a sparse vector, and is a basic sparse vector-dense vector operation in the Generic API system.

The output result X satisfies:

X.values[i] = Y[X.indices[i] - idxBase]   for i = 0 .. nnz-1

where X is the sparse vector (Sparse Vector), containing indices (positions of non-zero elements in the dense vector) and values (values of non-zero elements), and Y is the dense vector (Dense Vector). After the call, X.values is overwritten with the values collected from Y.

When X.nnz > 0, the element stride of Y must be 1. Neither arch22 nor arch35 supports a non-unit stride. Calling Gather after setting another stride through aclsparseDnVecSetStride returns ACL_SPARSE_STATUS_NOT_SUPPORTED, and no kernel is launched. The existing no-op behavior of empty output is not subject to this stride restriction.

This operator does not need a workspace or a preprocess phase, and the computation completes in a single call.

Operator Execution APIs

aclsparseGather

Product support

  • Ascend 950PR&950DT products (arch35): Supported
  • Atlas A3 products (arch22): Supported
  • Atlas A2 products (arch22): Supported

Description: arch22 (Atlas A2 products and Atlas A3 products) and arch35 (Ascend 950PR&950DT products) support different ranges of dtype / index types. See "Supported Data Types / Index Types" below. The arch22 implementation is located in sparse/gather/arch22/, and the arch35 implementation is located in sparse/gather/arch35/. The two are routed by SOC at compile time and do not participate in linking at the same time.

Function prototype

aclsparseStatus_t aclsparseGather(
    aclsparseHandle_t handle,
    aclsparseConstDnVecDescr_t vecY,
    aclsparseSpVecDescr_t vecX)

Parameter description

Parameter Input/Output Type Description Memory Location
handle Input aclsparseHandle_t Context handle of the ops-sparse library, carrying the stream; call aclsparseSetStream first Host
vecY Input aclsparseConstDnVecDescr_t Descriptor of dense vector Y (data source); only values is read Host
vecX Output aclsparseSpVecDescr_t Descriptor of sparse vector X: reads indices and idxBase, writes values Host

Constraints

  • handle cannot be nullptr; otherwise, ACL_SPARSE_STATUS_HANDLE_IS_NULLPTR is returned
  • vecY and vecX cannot be nullptr; otherwise, ACL_SPARSE_STATUS_INVALID_VALUE is returned
  • vecX.valueType must be consistent with vecY.valueType
  • Valid indexes are the core contract: each index value X.indices[i] - idxBase in vecX.indices must fall within the range [0, vecY.size)
    • arch22 (Atlas A2 products and Atlas A3 products): the host side performs per-index range verification (after copying indexes D2H, each index is checked), and out-of-range indexes explicitly return ACL_SPARSE_STATUS_INVALID_VALUE, without silent out-of-range reads
    • arch35 (Ascend 950PR&950DT products): device index out-of-range follows the asynchronous error protocol, so valid indexes are a caller precondition
  • Cardinality constraints between vecX.size and vecY.size:
    • arch35 (Ascend 950PR&950DT products): vecX.size must equal vecY.size, and 0 <= nnz <= size
    • arch22 (Atlas A2 products and Atlas A3 products): no cardinality constraint is imposed, and validity depends entirely on each index landing point (nnz can be greater than vecY.size)
  • The API upper limits of size and nnz are INT64_MAX; in practice, they are also constrained by the allocable device memory, the element byte count, and no overflow of the address range
  • nnz=0 returns success and does not launch a kernel; for size=0, only nnz=0 is allowed. Verification order: handle → early return when nnz==0 → descriptor/data pointers. Therefore, an empty handle returns ACL_SPARSE_STATUS_HANDLE_IS_NULLPTR even when nnz=0, and valid indices/values are not required when nnz is zero
  • Non-empty input, index, and output pointers must be located on the current NPU device and remain valid before the asynchronous execution completes
  • vecY.values and vecX.indices are read-only; vecX.values must not overlap any input buffer
  • No workspace is needed, and no preprocessing phase is needed
  • Out-of-order indexes are supported (indices does not need to be sorted)
  • Duplicate elements in vecX.indices are supported (under arch22, nnz can be greater than vecY.size. For example, vecY.size=1, nnz=2, indices=[0,0] (base 0) outputs the same element twice, consistent with the semantics of torch.index_select)

arch22 (Atlas A2 products and Atlas A3 products) additional host-side constraints (if not satisfied, an error is explicitly returned, no fallback to CPU):

  • vecX.valueType must be consistent with vecY.valueType and must be within {ACL_FLOAT, ACL_FLOAT16, ACL_BF16, ACL_COMPLEX64} (FP64 returns ACL_SPARSE_STATUS_NOT_SUPPORTED)
  • vecX.idxType must be ACL_SPARSE_INDEX_32I (I64 returns ACL_SPARSE_STATUS_NOT_SUPPORTED)
  • vecX.idxBase must be 0 or 1 (other values return ACL_SPARSE_STATUS_INVALID_VALUE)
  • When nnz == 0, ACL_SPARSE_STATUS_SUCCESS is directly returned and no kernel is launched (the output X.values remains unchanged). This early return is located after handle verification, and valid indices/values pointers are not required when nnz is zero

Supported Data Types

Data Type Enum Supported Remarks
FP32 ACL_FLOAT ✅ arch22 / arch35 both supported
FP16 ACL_FLOAT16 ✅ arch22 / arch35 both supported
BF16 ACL_BF16 ✅ arch22 / arch35 both supported
FP64 ACL_DOUBLE ✅ (arch35 only) Not supported by arch22
COMPLEX64 ACL_COMPLEX64 ✅ arch22 / arch35 both supported

The mandatory types declared for the Ascend 950PR&950DT products task are FP16, BF16, FP32, and COMPLEX64. FP64 is an existing compatibility capability of the low-level C++ API; the PyTorch/ATen adaptation opens only the four mandatory types. The support scope of arch22 (Atlas A2 products and Atlas A3 products): FP32 / FP16 / BF16 / COMPLEX64, consistent with the task specification; FP64 is not supported.

Supported Index Types

Index Type Enum Supported Remarks
32-bit signed integer ACL_SPARSE_INDEX_32I ✅ arch22 / arch35 both supported
64-bit signed integer ACL_SPARSE_INDEX_64I ✅ (arch35 only) arch22 supports only I32

The public PyTorch/ATen contract of the task accepts only I32. I64 is reserved as an existing compatibility capability of the low-level C++ API.

Index Base

Base Enum Description
0-based ACL_SPARSE_INDEX_BASE_ZERO C compatible (default)
1-based ACL_SPARSE_INDEX_BASE_ONE Fortran compatible

The index base is specified when creating the sparse vector descriptor (aclsparseCreateSpVec), and Gather computes the actual access position through X.indices[i] - idxBase.

Feature Description

Feature Supported Description
Extra buffer Not required No workspace allocation needed
Preprocess Not required No preprocessing phase
Determinism ✅ The result is bit-wise consistent across calls
Out-of-order indexes ✅ indices does not need to be sorted
Asynchronous execution ✅ After the call, you need aclrtSynchronizeStream to wait for completion

PyTorch/ATen Entry

The adaptation supports PyTorch 2.7+ and torch_npu 26.0.0+. After the extension is loaded, the public entry keeps the standard Dispatcher path:

import torch
import torch_npu
import cann_ops_sparse

source = torch.tensor([10, 20, 30, 40, 50], dtype=torch.float32, device="npu")
index = torch.tensor([0, 2, 4], dtype=torch.int32, device="npu")
output = torch.index_select(source, 0, index)

The call chain is torch.index_select → aten::index_select → PrivateUse1 implementation → aclsparseGather → Ascend C kernel, without CPU backfill. The public entry is limited to one-dimensional contiguous Strided NPU tensors, dim=0 (-1 is also accepted under one-dimensional semantics), I32 index, and the four task-mandatory values dtypes. The public PyTorch entry uses base 0; the low-level C API continues to support base 0/1. The adaptation is forward-only, does not support autograd, and the output is an independent contiguous tensor.

The PyTorch entry allows the index length to exceed the input length, and indexes can be out of order or duplicated, but each index must still be within the input range. Long indexes call the low-level API in segments through contiguous views of the indexes and the output, all reusing the caller's stream, without copying data or adding linear temporary buffers. The nnz <= size contract of the public SpVec descriptor and the C API remains unchanged.

For build and execution commands, see test/gather/README.md.

Invocation example

The example code is for reference only. For details about compilation and execution, see Compiling and Running a Sample.

#include <cstdio>
#include <memory>
#include <vector>

#include "acl/acl.h"
#include "cann_ops_sparse.h"

#define CHECK_RET(cond, return_expr) \
    do {                             \
        if (!(cond)) {               \
            return_expr;             \
        }                            \
    } while (0)

#define LOG_PRINT(message, ...)         \
    do {                                \
        printf(message, ##__VA_ARGS__); \
    } while (0)

class AclContext {
public:
    explicit AclContext(int32_t deviceId) : deviceId_(deviceId) {}

    ~AclContext()
    {
        if (stream_ != nullptr) {
            aclrtDestroyStream(stream_);
            stream_ = nullptr;
        }
        if (deviceSet_) {
            aclrtResetDevice(deviceId_);
            deviceSet_ = false;
        }
        if (aclInited_) {
            aclFinalize();
            aclInited_ = false;
        }
    }

    int Init()
    {
        auto ret = aclInit(nullptr);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret);
        aclInited_ = true;

        ret = aclrtSetDevice(deviceId_);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret);
        deviceSet_ = true;

        ret = aclrtCreateStream(&stream_);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret);
        return ACL_SUCCESS;
    }

    aclrtStream Stream() const { return stream_; }

private:
    int32_t deviceId_;
    aclrtStream stream_ = nullptr;
    bool aclInited_ = false;
    bool deviceSet_ = false;
};

using DevicePtr = std::unique_ptr<void, aclError (*)(void *)>;

static int AllocAndCopyDevice(DevicePtr &devicePtr, const void *hostPtr, size_t sizeBytes)
{
    void *rawPtr = nullptr;
    auto ret = aclrtMalloc(&rawPtr, sizeBytes, ACL_MEM_MALLOC_HUGE_FIRST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret);
    devicePtr.reset(rawPtr);

    if (hostPtr != nullptr && sizeBytes > 0) {
        ret = aclrtMemcpy(devicePtr.get(), sizeBytes, hostPtr, sizeBytes, ACL_MEMCPY_HOST_TO_DEVICE);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy data to Device failed. ERROR: %d\n", ret); return ret);
    }
    return ACL_SUCCESS;
}

static int AllocDevice(DevicePtr &devicePtr, size_t sizeBytes)
{
    void *rawPtr = nullptr;
    auto ret = aclrtMalloc(&rawPtr, sizeBytes, ACL_MEM_MALLOC_HUGE_FIRST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret);
    devicePtr.reset(rawPtr);
    return ACL_SUCCESS;
}

int aclsparseGatherTest(AclContext &ctx)
{
    aclrtStream stream = ctx.Stream();

    // 1. Create the ops-sparse handle
    aclsparseHandle_t rawHandle = nullptr;
    auto sparseRet = aclsparseCreate(&rawHandle);
    CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("aclsparseCreate failed: %d\n", sparseRet);
              return sparseRet);
    std::unique_ptr<aclsparseContext, aclsparseStatus_t (*)(aclsparseHandle_t)> handlePtr(rawHandle, aclsparseDestroy);

    sparseRet = aclsparseSetStream(static_cast<aclsparseHandle_t>(handlePtr.get()), stream);
    CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("aclsparseSetStream failed: %d\n", sparseRet);
              return sparseRet);

    // 2. Prepare host-side data
    //    Dense vector Y = {10.0, 20.0, 30.0, 40.0, 50.0}
    //    Sparse vector X.indices = {0, 2, 4} (0-based), nnz = 3
    //    Expected output X.values = {10.0, 30.0, 50.0}
    int64_t vecSize = 5;
    int64_t nnz = 3;

    std::vector<float> hY = {10.0f, 20.0f, 30.0f, 40.0f, 50.0f};
    std::vector<int32_t> hIndices = {0, 2, 4};

    // 3. Copy data to the device
    DevicePtr dY(nullptr, aclrtFree);
    DevicePtr dIndices(nullptr, aclrtFree);
    DevicePtr dXValues(nullptr, aclrtFree);

    auto aclRet = AllocAndCopyDevice(dY, hY.data(), vecSize * sizeof(float));
    CHECK_RET(aclRet == ACL_SUCCESS, return aclRet);
    aclRet = AllocAndCopyDevice(dIndices, hIndices.data(), nnz * sizeof(int32_t));
    CHECK_RET(aclRet == ACL_SUCCESS, return aclRet);
    aclRet = AllocDevice(dXValues, nnz * sizeof(float));
    CHECK_RET(aclRet == ACL_SUCCESS, return aclRet);

    // 4. Create the dense vector descriptor (data source Y)
    aclsparseConstDnVecDescr_t dnVecY = nullptr;
    sparseRet = aclsparseCreateConstDnVec(&dnVecY, vecSize, dY.get(), ACL_FLOAT);
    CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("aclsparseCreateConstDnVec failed: %d\n", sparseRet);
              return sparseRet);

    // 5. Create the sparse vector descriptor (output X)
    aclsparseSpVecDescr_t spVecX = nullptr;
    sparseRet = aclsparseCreateSpVec(&spVecX, vecSize, nnz, dIndices.get(), dXValues.get(),
                                     ACL_SPARSE_INDEX_32I, ACL_SPARSE_INDEX_BASE_ZERO, ACL_FLOAT);
    CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("aclsparseCreateSpVec failed: %d\n", sparseRet);
              return sparseRet);

    // 6. Call Gather
    sparseRet = aclsparseGather(handlePtr.get(), dnVecY, spVecX);
    CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("aclsparseGather failed: %d\n", sparseRet);
              return sparseRet);

    // 7. Synchronize and wait for the computation to complete
    aclRet = aclrtSynchronizeStream(stream);
    CHECK_RET(aclRet == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", aclRet); return aclRet);

    // 8. Copy the result back to the host and print it
    std::vector<float> hXValues(nnz, 0.0f);
    aclRet = aclrtMemcpy(hXValues.data(), nnz * sizeof(float), dXValues.get(), nnz * sizeof(float),
                         ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_RET(aclRet == ACL_SUCCESS, LOG_PRINT("copy X.values to Host failed. ERROR: %d\n", aclRet); return aclRet);

    LOG_PRINT("\nResult:\n");
    LOG_PRINT("  X.values: ");
    for (int64_t i = 0; i < nnz; i++) {
        LOG_PRINT("%.1f ", hXValues[i]);
    }
    LOG_PRINT("\n");

    // 9. Clean up the descriptors
    aclsparseDestroySpVec(spVecX);
    aclsparseDestroyDnVec(dnVecY);

    return ACL_SPARSE_STATUS_SUCCESS;
}

int main()
{
    AclContext ctx(0);
    auto ret = ctx.Init();
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    ret = aclsparseGatherTest(ctx);
    CHECK_RET(ret == ACL_SPARSE_STATUS_SUCCESS, LOG_PRINT("aclsparseGatherTest failed: %d\n", ret); return ret);
    return 0;
}

The expected output is as follows:

Result:
  X.values: 10.0 30.0 50.0