aclnnBincount

📄 View Source Code

Applicable Products

ProductSupported
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

  • Description:

    Computes the frequency of each value in a non-negative integer array. minlength specifies the minimum size of the output tensor. When weights is a null pointer, each occurrence of self[i] in self increments its frequency by 1. When weights is not null, each occurrence of self[i] increments its frequency by weights[i], and the result is stored at position self[i]+1 in out. Therefore, the size of out is the maximum of (the maximum value in self + 1) and minlength.

  • Formula:

    If n is the value of self at position i, and weights is specified, then

    $$ out[self_i] = out[self_i] + weights_i $$

    Otherwise:

    $$ out[self_i] = out[self_i] + 1 $$

Function Prototype

Each operator is divided into a two-phase API. You must first call the "aclnnBincountGetWorkspaceSize" API to obtain the workspace size required for computation and the executor that encapsulates the operator computation flow, and then call the "aclnnBincount" API to perform the computation.

aclnnStatus aclnnBincountGetWorkspaceSize(
  const aclTensor*        self,
  const aclTensor*        weights,
  int64_t                 minlength,
  aclTensor*              out,
  uint64_t*               workspaceSize,
  aclOpExecutor**         executor)
aclnnStatus aclnnBincount(
  void*                   workspace,
  uint64_t                workspaceSize,
  aclOpExecutor*          executor,
  const aclrtStream       stream)

aclnnBincountGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    self (aclTensor*) Input Input tensor. Must be a non-negative integer. INT8, INT16, INT32, INT64, UINT8 1D ND - √
    weights (aclTensor*) Input Weight of each value in self. Can be a null pointer. The shape must be the same as that of self. FLOAT, FLOAT16, FLOAT64, INT8, INT16, INT32, INT64, UINT8, BOOL 1D ND - √
    minlength (int64_t) Input Specifies the minimum length of the output tensor. If the computed maximum value of self is less than minlength, the length of out is minlength; otherwise, it is the maximum value of self plus 1. int64_t - - -
    out(aclTensor*) Output Output tensor. The length of out is the maximum of the maximum value of self plus 1 and minlength. INT32, INT64, FLOAT, DOUBLE 1D ND - √
    workspaceSize (uint64_t*) Output Returns the workspace size to be requested on the Device side. - - - - -
    executor (aclOpExecutor**) Output Returns the operator executor, which contains the operator computation process. - - - - -
  • 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 Value Error Code Description
ACLNN_ERR_PARAM_NULLPTR 161001 The input self or out is a null pointer.
ACLNN_ERR_PARAM_INVALID 161002 The data type or data format of self, out, or weights is not within the supported range.
When weights is not empty, the shapes of self and weights are inconsistent.

aclnnBincount

  • Parameters:

    Parameter Input/Output Description
    workspace Input Address of the workspace memory applied on the Device side.
    workspaceSize Input Size of the workspace applied on the Device side, obtained through the first-phase API aclnnBincountGetWorkspaceSize.
    executor Input Operator executor, which contains the operator computation process.
    stream Input Specifies the stream for task execution.
  • Return value

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

Constraints

  • Deterministic computation:

    • Atlas A2 training products/Atlas A2 inference products, Atlas A3 training products/Atlas A3 inference products, Atlas inference products, Atlas training products: defaults to a deterministic implementation.

    • Ascend 950PR/Ascend 950DT: defaults to a non-deterministic implementation. You can enable deterministic computation by calling aclrtCtxSetSysParamOpt.

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_bincount.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: resource initialization.
    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 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);
    // Copy data from the host to the device memory using aclrtMemcpy.
    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);

    // Calculate 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()
{
    // Initialize the device/stream. For details, see the ACL API reference.
    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);

    std::vector<int64_t> selfShape = {8};
    std::vector<int64_t> maxOutShape = {1};

    void* selfDeviceAddr = nullptr;
    aclTensor* self = nullptr;

    std::vector<int32_t> selfHostData = {8, 1, 2, 3, 4, 5, 6, 7};

    // Create the self aclTensor.
    ret = CreateAclTensor(selfHostData, selfShape, &selfDeviceAddr, aclDataType::ACL_INT32, &self);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // Call bincount. The example fixes outSize to 9.
    int64_t minlength = 0;
    int64_t outSize = 9;
    std::vector<int64_t> weightsShape = {8};
    std::vector<int64_t> outShape = {outSize};

    void* weightsDeviceAddr = nullptr;
    void* outDeviceAddr = nullptr;
    aclTensor* weights = nullptr;
    aclTensor* out = nullptr;
    std::vector<float> weightsHostData = {1, 1, 1.1, 2, 2, 2, 3, 3};
    std::vector<float> outHostData(outSize, 0);
    // Create the weights aclTensor.
    ret = CreateAclTensor(weightsHostData, weightsShape, &weightsDeviceAddr, aclDataType::ACL_FLOAT, &weights);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the out aclTensor.
    ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT, &out);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // Call the CANN operator library API.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the first-phase API of aclnnBincount.
    ret = aclnnBincountGetWorkspaceSize(self, weights, minlength, out, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnBincountGetWorkspaceSize 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 > 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 aclnnBincount second-phase API.
    ret = aclnnBincount(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnBincount failed. ERROR: %d\n", ret); return ret);

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

    // Obtain the output value and copy the result from device memory to host memory.
    auto size = GetShapeSize(outShape);
    std::vector<float> bincountResultData(size, 0);
    ret = aclrtMemcpy(
        bincountResultData.data(), bincountResultData.size() * sizeof(bincountResultData[0]), outDeviceAddr,
        size * sizeof(bincountResultData[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, bincountResultData[i]);
    }
    // Release aclTensor.
    aclDestroyTensor(self);
    aclDestroyTensor(weights);
    aclDestroyTensor(out);

    // Release resources.
    aclrtFree(selfDeviceAddr);
    aclrtFree(outDeviceAddr);

    aclrtFree(weightsDeviceAddr);
    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }

    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();

    return 0;
}