aclnnCoalesceSparse

📄 View Source Code

Applicable Products

Applicable ProductsSupported
Ascend 950PR/Ascend 950DT×
Atlas A3 training products/Atlas A3 inference products√
Atlas A2 training products/Atlas A2 inference products√
Atlas 200I/500 A2 inference products×
Atlas inference products×
Atlas training products×

Function

Accumulates and sums the values at identical coordinate points, thereby reducing the memory size of the Coo_Tensor.

Function Prototype

Each operator is divided into a two-phase API. The "aclnnCoalesceSparseGetWorkspaceSize" API must be called first to obtain the workspace size required for computation and the executor that encapsulates the operator computation flow. Then, the "aclnnCoalesceSparse" API is called to perform the computation.

aclnnStatus aclnnCoalesceSparseGetWorkspaceSize(
    const aclTensor   *uniqueLen,
    const aclTensor   *uniqueIndices,
    const aclTensor   *indices,
    const aclTensor   *values,
    const aclTensor   *newIndicesOut,
    const aclTensor   *newValuesOut,
    uint64_t          *workspaceSize,
    aclOpExecutor    **executor);
aclnnStatus aclnnCoalesceSparse(
    void              *workspace,
    uint64_t           workspaceSize,
    aclOpExecutor     *executor,
    aclrtStream        stream);

aclnnCoalesceSparseGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data type. Data format. Shape. Non-contiguous tensor.
    uniqueLen (aclTensor*) Input Number of indices after deduplication. Empty tensors are not supported. INT32, INT64 ND 1 √
    uniqueIndices (aclTensor*) Input Deduplicated index array. Empty tensors are not supported. INT32, INT64 ND 1 √
    indices (aclTensor*) Input. Index array.
    • Empty tensors are not supported.
    • The re-indexed indices value cannot exceed the int32 upper limit.
    INT32, INT64 ND 2 √
    values (aclTensor*) Input The element value corresponding to each coordinate. Empty tensors are not supported. INT32, FLOAT16, FLOAT32 ND 1-8 √
    newIndicesOut (aclTensor*) Output Merged index array. Empty tensors are not supported. INT32, INT64 ND 2 √
    newValuesOut (aclTensor*) Output Merged element values. Empty tensors are not supported. INT32, FLOAT16, FLOAT32 ND 1-8 √
    workspaceSize (uint64_t*) Output Returns the workspace size to be requested on the Device side. - - - - -
    executor(aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - -
  • Return value

    aclnnStatus: return code. For details, see aclnn Return Codes.

    The first-phase API performs input parameter validation and returns an error in the following scenarios:

    Return Code Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 The passed uniqueLen, uniqueIndices, indices, values, newIndicesOut, or newValuesOut is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of uniqueLen, uniqueIndices, indices, values, newIndicesOut, or newValuesOut is not within the supported range.
    The dimension of values or newValuesOut exceeds 8.
    The re-indexed indices value cannot exceed the int32 upper limit.

aclnnCoalesceSparse

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address applied for on the device side.
    workspaceSize Input Workspace size applied for on the device side, obtained from the first-phase API aclnnCoalesceSparseGetWorkspaceSize.
    executor Input Operator executor that contains the operator computation flow.
    stream Input Specifies the stream for task execution.
  • Return value

    aclnnStatus: return code. For details, see aclnn Return Codes.

Constraints

None

Example

The following provides example code for reference only. For details about compilation and running, see Compile and Run Samples.

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_coalesce_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)

int64_t GetShapeSize(const std::vector<int64_t>& shape)
{
    int64_t shapeSize = 1;
    for (auto i : shape) {
        shapeSize *= i;
    }
    return shapeSize;
}

int Init(int32_t deviceId, aclrtStream* stream)
{
    // Boilerplate: initialize.
    auto ret = aclInit(nullptr);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret);
    ret = aclrtSetDevice(deviceId);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret);
    ret = aclrtCreateStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret);
    return 0;
}

template <typename T>
int CreateAclTensor(
    const std::vector<T>& hostData, const std::vector<int64_t>& shape, void** deviceAddr, aclDataType dataType,
    aclTensor** tensor)
{
    auto size = GetShapeSize(shape) * sizeof(T);
    // Call aclrtMalloc to allocate device-side memory.
    auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret);
    // Call aclrtMemcpy to copy host-side data to the device-side memory.
    ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret);

    // Compute the strides of a contiguous tensor.
    std::vector<int64_t> strides(shape.size(), 1);
    for (int64_t i = shape.size() - 2; i >= 0; i--) {
        strides[i] = shape[i + 1] * strides[i + 1];
    }

    // Call the aclCreateTensor API to create an aclTensor.
    *tensor = aclCreateTensor(
        shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND, shape.data(), shape.size(),
        *deviceAddr);
    return 0;
}

int main()
{
    // 1. (Boilerplate) Initialize the device/stream. See the ACL API documentation.
    // Set deviceId based on the actual device.
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = Init(deviceId, &stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);

    // 2. Construct the inputs and outputs. Customize the construction based on the API.
    std::vector<int64_t> uniqueLenShape = {1};
    std::vector<int64_t> uniqueIndicesShape = {2,2};
    std::vector<int64_t> indexShape = {2,4};
    std::vector<int64_t> valueShape = {4};
    std::vector<int64_t> newIndexShape = {4};
    std::vector<int64_t> newValueShape = {2};
    void* uniqueLenDeviceAddr = nullptr;
    void* uniqueIndicesDeviceAddr = nullptr;
    void* indexDeviceAddr = nullptr;
    void* valueDeviceAddr = nullptr;
    void* newIndexDeviceAddr = nullptr;
    void* newValueDeviceAddr = nullptr;
    aclTensor* uniqueLen = nullptr;
    aclTensor* uniqueIndices = nullptr;
    aclTensor* index = nullptr;
    aclTensor* value = nullptr;
    aclTensor* newIndex = nullptr;
    aclTensor* newValue = nullptr;
    std::vector<int32_t> uniqueLenData = {2};
    std::vector<int32_t> uniqueIndicesData = {0, 1, 0, 2};
    std::vector<int32_t> indexData = {0, 0, 1, 1, 0, 0, 2, 2};
    std::vector<float> valueData = {1, 2, 3, 4};
    std::vector<int32_t> newIndexData = {0, 0, 0, 0};
    std::vector<float> newValueData = {0, 0};

    // Create the input aclTensor.
    ret = CreateAclTensor(uniqueLenData, uniqueLenShape, &uniqueLenDeviceAddr, aclDataType::ACL_INT32, &uniqueLen);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the input aclTensor.
    ret = CreateAclTensor(uniqueIndicesData, uniqueIndicesShape, &uniqueIndicesDeviceAddr, aclDataType::ACL_INT32, &uniqueIndices);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the input aclTensor.
    ret = CreateAclTensor(indexData, indexShape, &indexDeviceAddr, aclDataType::ACL_INT32, &index);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the input aclTensor.
    ret = CreateAclTensor(valueData, valueShape, &valueDeviceAddr, aclDataType::ACL_FLOAT, &value);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the output aclTensor.
    ret = CreateAclTensor(newIndexData, newIndexShape, &newIndexDeviceAddr, aclDataType::ACL_INT32, &newIndex);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the out aclTensor.
    ret = CreateAclTensor(newValueData, newValueShape, &newValueDeviceAddr, aclDataType::ACL_FLOAT, &newValue);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // 3. Call the CANN operator library API. Replace with the specific API name.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the first-phase API of aclnnCoalesceSparse.
    ret = aclnnCoalesceSparseGetWorkspaceSize(uniqueLen, uniqueIndices, index, value, newIndex, newValue, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCoalesceSparseGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
    // Apply for device memory based on the workspaceSize calculated by the first-phase API.
    void* workspaceAddr = nullptr;
    if (workspaceSize > static_cast<uint64_t>(0)) {
        ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
    }
    // Call the second-phase API of aclnnCoalesceSparse.
    ret = aclnnCoalesceSparse(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCoalesceSparse failed. ERROR: %d\n", ret); return ret);

    // 4. (Boilerplate) Synchronously wait for the task execution to complete.
    ret = aclrtSynchronizeStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);

    // 5. Obtain the output value and copy the result from the device memory to the host. Modify based on the specific API definition.
    auto size = GetShapeSize(newValueShape);
    std::vector<float> resultData(size, 0);
    ret = aclrtMemcpy(
        resultData.data(), resultData.size() * sizeof(resultData[0]), newValueDeviceAddr, size * sizeof(resultData[0]),
        ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return ret);
    for (int64_t i = 0; i < size; i++) {
        LOG_PRINT("result[%ld] is: %f\n", i, resultData[i]);
    }

    // 6. Release the aclTensor. Modify based on the specific API definition.
    aclDestroyTensor(uniqueLen);
    aclDestroyTensor(uniqueIndices);
    aclDestroyTensor(index);
    aclDestroyTensor(value);
    aclDestroyTensor(newIndex);
    aclDestroyTensor(newValue);

    // 7. Release device resources.
    aclrtFree(uniqueLenDeviceAddr);
    aclrtFree(uniqueIndicesDeviceAddr);
    aclrtFree(indexDeviceAddr);
    aclrtFree(valueDeviceAddr);
    aclrtFree(newIndexDeviceAddr);
    aclrtFree(newValueDeviceAddr);
    if (workspaceSize > static_cast<uint64_t>(0)) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return 0;
}