aclnnSWhere

📄 View Source Code

Applicable Products

  • Ascend 950PR&950DT products: Supported
  • Atlas A3 products: Supported
  • Atlas A2 products: Supported
  • Atlas 200I/500 A2 inference products: Not supported
  • Atlas inference products: Supported
  • Atlas training products: Supported

Function

  • Description: Selects elements from self or other based on a condition and returns the result (broadcast supported).
  • The formula is as follows:
outi=where(selfi,otheri,conditioni)={selfi,if conditioniotheri,otherwiseout_i=where(self_i,other_i,condition_i)=\begin{cases} self_i, & \text{if condition}_i \\ other_i, & \text{otherwise} \end{cases}

Function Prototype

Each operator uses a two-phase API. Call the "aclnnSWhereGetWorkspaceSize" API first to obtain the workspace size required for computation and the executor that contains the operator computation process, and then call the "aclnnSWhere" API to perform computation.

  • aclnnStatus aclnnSWhereGetWorkspaceSize(const aclTensor *condition, const aclTensor *self, const aclTensor *other, aclTensor *out, uint64_t *workspaceSize, aclOpExecutor **executor)
  • aclnnStatus aclnnSWhere(void *workspace, uint64_t workspaceSize, aclOpExecutor *executor, aclrtStream stream)

aclnnSWhereGetWorkspaceSize

  • Parameters:

    • condition (aclTensor*, computation input): Input condition in the formula. Device-side aclTensor. Data types UINT8 and BOOL are supported. Non-contiguous tensor is supported. The shape needs to satisfy the broadcast relationship with self and other. Non-contiguous tensor is supported. The data format supports ND. Data dimensions above 8 are not supported.

    • self (aclTensor*, computation input): Input self in the formula. The data type of self must satisfy the data type deduction rule with the data type of other (see deduction relationship). Device-side aclTensor. The shape needs to satisfy the broadcast relationship with other and condition. Non-contiguous tensor is supported. The data format supports ND. Data dimensions above 8 are not supported.

      • Atlas A2 products, Atlas A3 products, Ascend 950PR&950DT products: Data types FLOAT, INT32, UINT64, INT64, UINT32, FLOAT16, UINT16, INT16, INT8, UINT8, DOUBLE, BOOL, COMPLEX64, COMPLEX128, BFLOAT16 are supported.
      • Atlas inference products, Atlas training products: Data types FLOAT, INT32, UINT64, INT64, UINT32, FLOAT16, UINT16, INT16, INT8, UINT8, DOUBLE, BOOL, COMPLEX64, COMPLEX128 are supported.
    • other (aclTensor*, computation input): Input other in the formula. The data type of other must satisfy the data type deduction rule with the data type of self (see deduction relationship). Device-side aclTensor. The shape needs to satisfy the broadcast relationship with self and condition. Non-contiguous tensor is supported. The data format supports ND. Data dimensions above 8 are not supported.

      • Atlas A2 products, Atlas A3 products, Ascend 950PR&950DT products: Data types FLOAT, INT32, UINT64, INT64, UINT32, FLOAT16, UINT16, INT16, INT8, UINT8, DOUBLE, BOOL, COMPLEX64, COMPLEX128, BFLOAT16 are supported.
      • Atlas inference products, Atlas training products: Data types FLOAT, INT32, UINT64, INT64, UINT32, FLOAT16, UINT16, INT16, INT8, UINT8, DOUBLE, BOOL, COMPLEX64, COMPLEX128 are supported.
    • out (aclTensor *, computation output): Output out in the formula. Device-side aclTensor. Non-contiguous tensor is supported. The shape must be the shape after self, other, and condition are broadcast. Non-contiguous tensor is supported. The data format supports ND. Data dimensions above 8 are not supported.

      • Atlas A2 products, Atlas A3 products, Ascend 950PR&950DT products: Data types FLOAT, INT32, UINT64, INT64, UINT32, FLOAT16, UINT16, INT16, INT8, UINT8, DOUBLE, BOOL, COMPLEX64, COMPLEX128, BFLOAT16 are supported.
      • Atlas inference products and Atlas training products: data types supported are FLOAT, INT32, UINT64, INT64, UINT32, FLOAT16, UINT16, INT16, INT8, UINT8, DOUBLE, BOOL, COMPLEX64, COMPLEX128.
    • workspaceSize (uint64_t *, output): Returns the size of the workspace to be requested on the Device.

    • executor(aclOpExecutor**, output parameter): Returns the op executor, which contains the computation process of the operator.

  • Return value:

    aclnnStatus: return status 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 self, other, condition, or out is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type or data dimension of self, other, or condition is out of the supported range.
    Data type deduction cannot be performed for self and other.
    Broadcast deduction of self, other, and condition fails, or the broadcast result shape is different from the shape of out.

aclnnSWhere

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address requested on the device.
    workspaceSize Input Workspace size requested on the device, obtained by the first-phase API aclnnSWhereGetWorkspaceSize.
    executor Input Op executor containing the operator computation flow.
    stream Input Stream used to execute the task.
  • Return value:

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

Constraints

  • deterministic computation:
    • aclnnSWhere defaults to a deterministic implementation.

Example

The following sample code is for reference only. For details about compilation and execution, see Compile and Run Samples.

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_s_where.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 shape_size = 1;
  for (auto i : shape) {
    shape_size *= i;
  }
  return shape_size;
}


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); aclFinalize(); return ret);
  ret = aclrtCreateStream(stream);
  CHECK_RET(ret == ACL_SUCCESS,
            LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret);
            aclrtResetDevice(deviceId); aclFinalize(); 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 memory on the device.
  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 data from the host to the device 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);

  // Calculate the strides of the 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 aclCreateTensor 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. For details, see the acl API manual.
  // Set deviceId based on the actual device.
  int32_t deviceId = 0;
  aclrtStream stream;
  auto ret = Init(deviceId, &stream);
  // Handle the check as required.
  CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
  // 2. Construct the input and output as required by the API.
  std::vector<int64_t> selfShape = {4, 2};
  std::vector<int64_t> otherShape = {4, 2};
  std::vector<int64_t> conditionShape = {4, 2};
  std::vector<int64_t> outShape = {4, 2};
  void* selfDeviceAddr = nullptr;
  void* otherDeviceAddr = nullptr;
  void* conditionDeviceAddr = nullptr;
  void* outDeviceAddr = nullptr;
  aclTensor* self = nullptr;
  aclTensor* other = nullptr;
  aclTensor* condition = nullptr;
  aclTensor* out = nullptr;
  std::vector<float> selfHostData = {0, 0, 0, 0, 0, 0, 0, 7};
  std::vector<float> otherHostData = {0, 1, 2, 3, 4, 5, 6, 7};
  std::vector<int8_t> conditionHostData = {false,false,false,false,true,true,true,true};
  std::vector<float> outHostData = {10, 10, 10, 10, 10, 10, 10, 10};

  // Create the self aclTensor.
  ret = CreateAclTensor(selfHostData, selfShape, &selfDeviceAddr, aclDataType::ACL_FLOAT, &self);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the other aclTensor.
  ret = CreateAclTensor(otherHostData, otherShape, &otherDeviceAddr, aclDataType::ACL_FLOAT, &other);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the condition aclTensor.
  ret = CreateAclTensor(conditionHostData, conditionShape, &conditionDeviceAddr, aclDataType::ACL_BOOL, &condition);
  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);

  // 3. Call the CANN operator library APIs.
  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;
  // Call the first-phase API of aclnnSWhere.
  ret = aclnnSWhereGetWorkspaceSize(condition, self, other, out, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSWhereGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
  // Allocate 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 second-phase API of aclnnSWhere.
  ret = aclnnSWhere(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSWhere failed. ERROR: %d\n", ret); return ret);
  // 4. (boilerplate) Wait in synchronous mode until task execution is 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 device memory to host memory. Modify it based on the specific API definition.
  auto size = GetShapeSize(outShape);
  std::vector<float> resultData(size, 0);
  ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), outDeviceAddr, size * sizeof(float),
                    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 aclTensor and aclScalar. Modify it based on the specific API definition.
  aclDestroyTensor(self);
  aclDestroyTensor(other);
  aclDestroyTensor(condition);
  aclDestroyTensor(out);

  // 7. Release device resources. Modify it based on the specific API definition.
  aclrtFree(selfDeviceAddr);
  aclrtFree(otherDeviceAddr);
  aclrtFree(conditionDeviceAddr);
  aclrtFree(outDeviceAddr);
  if (workspaceSize > 0) {
      aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();
  return 0;
}