aclnnSWhere

📄 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

  • Operator function: 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 is divided into a two-phase API. The "aclnnSWhereGetWorkspaceSize" API must be called first to obtain the workspace size required for computation and the executor that encapsulates the operator computation flow. Then, the "aclnnSWhere" API is called to perform the 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): The input condition in the formula, a Device-side aclTensor. The data type supports UINT8 and BOOL. It supports Non-contiguous Tensor. The shape must satisfy the Broadcast Relationship with self and other. It supports Non-contiguous Tensor. The Data Format supports ND. Data dimensions of 8 and above are not supported.

    • self (aclTensor*, Computation Input): The input self in the formula. The data type must satisfy the data type deduction rules with the data type of other (see Deduction Relationship). It is a Device-side aclTensor. The shape must satisfy the Broadcast Relationship with other and condition. It supports Non-contiguous Tensor. The Data Format supports ND. Data dimensions of 8 and above are not supported.

      • Atlas A2 training products/Atlas A2 inference products, Atlas A3 training products/Atlas A3 inference products , Ascend 950PR/Ascend 950DT: The data type supports FLOAT, INT32, UINT64, INT64, UINT32, FLOAT16, UINT16, INT16, INT8, UINT8, DOUBLE, BOOL, COMPLEX64, COMPLEX128, and BFLOAT16.

      • Atlas inference products, Atlas training products: The supported data types include FLOAT, INT32, UINT64, INT64, UINT32, FLOAT16, UINT16, INT16, INT8, UINT8, DOUBLE, BOOL, COMPLEX64, and COMPLEX128.

    • other (aclTensor*, Computation Input): In the formula, the input other. Its data type and the data type of self must satisfy the data type deduction rules (see Deduction Relationship). It is a Device-side aclTensor, and its shape must satisfy the Broadcast Relationship with self and condition. Non-contiguous Tensor is supported. The Data Format supports ND. Data Dimension is not supported for 8 dimensions and above.

      • Atlas A2 training products/Atlas A2 inference products, Atlas A3 training products/Atlas A3 inference products, Ascend 950PR/Ascend 950DT: The supported data types include FLOAT, INT32, UINT64, INT64, UINT32, FLOAT16, UINT16, INT16, INT8, UINT8, DOUBLE, BOOL, COMPLEX64, COMPLEX128, and BFLOAT16.

      • Atlas inference products, Atlas training products: The supported data types include FLOAT, INT32, UINT64, INT64, UINT32, FLOAT16, UINT16, INT16, INT8, UINT8, DOUBLE, BOOL, COMPLEX64, and COMPLEX128.

    • out (aclTensor*, Computation Output): In the formula, the output out. Non-contiguous Tensor is supported. It is a Device-side aclTensor, and its shape must be the shape after broadcasting self, other, and condition. Non-contiguous Tensor is supported. The Data Format supports ND. Data Dimension is not supported for 8 dimensions and above.

      • Atlas A2 training products/Atlas A2 inference products, Atlas A3 training products/Atlas A3 inference products, Ascend 950PR/Ascend 950DT: The supported data types include FLOAT, INT32, UINT64, INT64, UINT32, FLOAT16, UINT16, INT16, INT8, UINT8, DOUBLE, BOOL, COMPLEX64, COMPLEX128, and BFLOAT16.

      • Atlas inference products, Atlas training products: The supported data types include FLOAT, INT32, UINT64, INT64, UINT32, FLOAT16, UINT16, INT16, INT8, UINT8, DOUBLE, BOOL, COMPLEX64, and COMPLEX128.

    • workspaceSize (uint64_t*, output parameter): Returns the workspace size to be allocated on the Device side.

    • executor(aclOpExecutor**, output parameter): 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 Value Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 The passed self, other, condition, or out is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type or dimension of self, other, or condition is not within the supported range.
    Data type deduction cannot be performed between self and other.
    Broadcast deduction fails for self, other, and condition, or the broadcast result has a different shape than out.

aclnnSWhere

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address requested on the Device side.
    workspaceSize Input Size of the workspace requested on the Device side, obtained through the first-phase API aclnnSWhereGetWorkspaceSize.
    executor Input Operator executor, which includes the operator computation flow.
    stream Input Specifies the stream on which the task is executed.
  • Return value:

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

Constraints

  • Deterministic computation:

    • aclnnSWhere defaults to a deterministic implementation.

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_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 for 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 request memory on the device side.
  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 side to the device memory by calling 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 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];
  }

  // Create an aclTensor by calling the aclCreateTensor API.
  *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 manual.
  // Set deviceId based on the actual device.
  int32_t deviceId = 0;
  aclrtStream stream;
  auto ret = Init(deviceId, &stream);
  // Handle the check based on your requirements.
  CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
  // 2. Construct the inputs and outputs. Customize the construction based on the API interface.
  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 self 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 API.
  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);
  // 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 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) 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);
  // 5. Obtain the output value and copy the result from the device-side memory to the host side. Modify 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 based on the specific API definition.
  aclDestroyTensor(self);
  aclDestroyTensor(other);
  aclDestroyTensor(condition);
  aclDestroyTensor(out);

  // 7.Release device resources. Modify 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;
}