aclnnBernoulliTensor&aclnnInplaceBernoulliTensor

📄 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:

    Extracts binary random numbers (0 or 1) from a Bernoulli distribution, where prob is the probability of generating a binary random number, and the input tensor specifies the shape.

  • Formula:

    out∼Bernoulli(prob)out∼Bernoulli(prob)

    Where, when using aclnnBernoulliTensor, prob in the formula corresponds to prob in the first-phase API, and out in the formula corresponds to out in the first-phase API; when using aclnnInplaceBernoulliTensor, prob in the formula corresponds to prob in the first-phase API, and out in the formula corresponds to selfRef in the first-phase API.

Function Prototype

  • Each operator is divided into a two-phase API. You must first call the "aclnnBernoulliTensorGetWorkspaceSize" or "aclnnInplaceBernoulliTensorGetWorkspaceSize" API to obtain the workspace size required for computation and the executor that encapsulates the operator computation process, and then call the "aclnnBernoulliTensor" or "aclnnInplaceBernoulliTensor" API to execute the computation.
aclnnStatus aclnnBernoulliTensorGetWorkspaceSize(
  const aclTensor   *self,
  const aclTensor   *prob,
  int64_t           seed,
  int64_t           offset,
  aclTensor         *out,
  uint64_t          *workspaceSize,
  aclOpExecutor     **executor)
aclnnStatus aclnnBernoulliTensor(
  void           *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor  *executor,
  aclrtStream    stream)
aclnnStatus aclnnInplaceBernoulliTensorGetWorkspaceSize(
  const aclTensor   *selfRef,
  const aclTensor   *prob,
  int64_t           seed,
  int64_t           offset,
  uint64_t          *workspaceSize,
  aclOpExecutor     **executor)
aclnnStatus aclnnInplaceBernoulliTensor(
  void           *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor  *executor,
  aclrtStream    stream)

aclnnBernoulliTensorGetWorkspaceSize

  • Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimensions (shape) Non-contiguous Tensor
self Input Device-side aclTensor that specifies the shape of the output out. The shape must be consistent with the shape of out. FLOAT16, FLOAT, DOUBLE, UINT8, INT8, INT16, INT32, INT64, BOOL, BFLOAT16 ND 0-8 √
prob Input. The prob in the formula, an aclTensor on the Device side. Satisfies 0 ≤ prob ≤ 1. The data format must be consistent with self. FLOAT16, FLOAT, DOUBLE ND 0-8 √
seed Input Host-side integer that sets the seed for the random number generator. - INT64 ND - √
offset Input. An integer on the host side, specifying the random number offset. - INT64 ND - -
out Output out in the formula, an aclTensor on the Device side. The shape must be consistent with the shape of self, and the data type must be consistent with self. FLOAT16, FLOAT, DOUBLE, UINT8, INT8, INT16, INT32, INT64, BOOL, BFLOAT16 ND 0-8 -
workspaceSize Output Returns the workspace size to be requested on the Device side. - - - - -
executor Output Returns the operator executor, which contains the operator computation flow. - - - - -
  • Atlas training products: UINT8, INT8, INT16, INT32, INT64, BOOL, and BFLOAT16 data types are not supported.

  • Atlas A2 training products/Atlas A2 inference products and Atlas A3 training products/Atlas A3 inference products: UINT8, INT8, INT16, INT32, INT64, and BOOL data types are not supported.

  • 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 self, prob, or out is a null pointer.
ACLNN_ERR_PARAM_INVALID 161002 The data type or data format of self, prob, or out is not within the supported range.
The data types of self and out are inconsistent.
The dimension of self, prob, or out exceeds 8.
The shapes of self and out are inconsistent.

aclnnBernoulliTensor

  • 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 from the first-phase API aclnnBernoulliTensorGetWorkspaceSize.
executor Input Operator executor, which contains the operator computation flow.
stream Input Specifies the stream for task execution.

aclnnInplaceBernoulliTensorGetWorkspaceSize

  • Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
selfRef Input and output. out in the formula, an aclTensor on the Device side. - FLOAT16, FLOAT, DOUBLE, UINT8, INT8, INT16, INT32, INT64, BOOL ND 0-8 √
prob Input The prob in the formula, which is an aclScalar on the host side.
  • Satisfies 0 ≤ prob ≤ 1.
FLOAT16, FLOAT, DOUBLE ND 0-8 √
seed Input Host-side integer that sets the seed of the random number generator. - INT64 ND - -
offset Input Host-side integer that specifies the random number offset. - INT64 ND - -
workspaceSize Output Returns the workspace size to be requested on the Device side. - - - - -
executor Output Returns the op executor, which contains the operator computation process. - - - - -
  • Atlas training products: The data type BFLOAT16 is not supported.

    • 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 input selfRef or prob is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type or data format of selfRef or prob is not within the supported range.
    The dimension of selfRef or prob is greater than 8.

aclnnInplaceBernoulliTensor

  • 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 aclnnInplaceBernoulliTensorGetWorkspaceSize.
executor Input Operator executor, which contains the operator computation flow.
stream Input Specifies the stream that executes the task.
  • Return value

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

Constraints

  • Deterministic computation:

    • aclnnBernoulliTensor and aclnnInplaceBernoulliTensor default to a deterministic implementation. The element values of the input prob must be in the range [0, 1]. When the shape of the input prob is inconsistent with the shape of the input self/selfRef, only the data of the corresponding elements between the two are computed, and the behavior for the remaining data is undefined. For example: when the shape of prob is [4, 2] and the shape of self is [4, 4], only the first 8 elements are computed, and the output shape is [4, 4]; when the shape of prob is [4, 4, 2] and the shape of self is [4, 4], only the first 16 elements are computed, and the output shape is [4, 4].

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_bernoulli.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 code 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 allocate 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);

  // Call aclrtMemcpy to copy data from the host side 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 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. Refer to the ACL API manual.
  // Fill in the deviceId based on your actual device.
  int32_t deviceId = 0;
  aclrtStream stream;
  auto ret = Init(deviceId, &stream);
  // Handle the check as needed.
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);

  // 2. Construct the input and output. Customize the construction based on the API interface.
  std::vector<int64_t> selfShape = {4, 4};
  std::vector<int64_t> probShape = {4, 4};
  std::vector<int64_t> outShape = {4, 4};
  void* selfDeviceAddr = nullptr;
  void* probDeviceAddr = nullptr;
  void* outDeviceAddr = nullptr;
  aclTensor* self = nullptr;
  aclTensor* prob = nullptr;
  aclTensor* out = nullptr;
  std::vector<float> selfHostData = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
  std::vector<float> probHostData = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
  std::vector<float> outHostData(16, 0);
  int64_t seed = 0;
  int64_t offset = 0;
  // Create the self aclTensor.
  ret = CreateAclTensor(selfHostData, selfShape, &selfDeviceAddr, aclDataType::ACL_FLOAT, &self);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the prob aclTensor.
  ret = CreateAclTensor(probHostData, probShape, &probDeviceAddr, aclDataType::ACL_FLOAT, &prob);
  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);

  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;

  // Example of aclnnBernoulliTensor API call.
  // 3. Call the CANN operator library API.
  // Call the first-phase API of aclnnBernoulliTensor.
  ret = aclnnBernoulliTensorGetWorkspaceSize(self, prob, seed, offset, out, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnBernoulliTensorGetWorkspaceSize 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 aclnnBernoulliTensor.
  ret = aclnnBernoulliTensor(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnBernoulliTensor failed. ERROR: %d\n", ret); return ret);

  // 4. (Boilerplate) Synchronously wait for the task 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(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 aclTensor and aclScalar. Modify based on the specific API definition.
  aclDestroyTensor(self);
  aclDestroyTensor(prob);
  aclDestroyTensor(out);

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