aclnnBernoulli&aclnnInplaceBernoulli
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 : Not supported
Atlas training products : Supported
Function
Description: Extracts binary random numbers (0 or 1) from a Bernoulli distribution. prob specifies the probability of generating binary random numbers, and the input tensor specifies the shape.
Formula:
Specifically, when using aclnnBernoulli, 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 aclnnInplaceBernoulli, 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
- aclnnBernoulli and aclnnInplaceBernoulli implement the same functionality. The differences are as follows. Choose the appropriate operator based on your actual scenario.
- aclnnBernoulli: Requires creating a new output tensor object to store the computation result.
- aclnnInplaceBernoulli: Does not require creating a new output tensor object. The computation result is stored directly in the memory of the input tensor.
- Each operator corresponds to a two-phase API. First call the "aclnnBernoulliGetWorkspaceSize" or "aclnnInplaceBernoulliGetWorkspaceSize" API to obtain the workspace size required for the calculation and the executor that includes the calculation process of the operator. Then call the "aclnnBernoulli" or "aclnnInplaceBernoulli" API to perform the calculation.
aclnnStatus aclnnBernoulliGetWorkspaceSize(
const aclTensor* self,
const aclScalar* prob,
int64_t seed,
int64_t offset,
aclTensor* out,
uint64_t* workspaceSize,
aclOpExecutor** executor)aclnnStatus aclnnBernoulli(
void* workspace,
uint64_t workspaceSize,
aclOpExecutor* executor,
aclrtStream stream)aclnnStatus aclnnInplaceBernoulliGetWorkspaceSize(
const aclTensor* selfRef,
const aclScalar* prob,
int64_t seed,
int64_t offset,
uint64_t* workspaceSize,
aclOpExecutor** executor)aclnnStatus aclnnInplaceBernoulli(
void* workspace,
uint64_t workspaceSize,
aclOpExecutor* executor,
aclrtStream stream)aclnnBernoulliGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Shape Non-contiguous Tensor self (aclTensor*) Input Input tensor. - Supports empty tensor.
- The data type needs to be the same as that of out.
- The shape needs to be the same as that of out.
FLOAT16, FLOAT, DOUBLE, UINT8, INT8, INT16, INT32, INT64, BOOL, BFLOAT16 ND 0-8 √ prob (aclScalar*) Input prob in the formula. Must satisfy 0≤prob≤1. FLOAT16, FLOAT, DOUBLE, BFLOAT16 - - - seed (int64_t) Input Sets the seed of the random number generator. - INT64 - - - offset (int64_t) Input Sets the random number offset. Value constraint: offset % 4 == 0, for example, 0, 4, 8 .... If the constraint is not met, the call fails. INT64 - - - out (aclTensor*) Output The outin the formula.- Supports empty tensors.
- The data type needs to be consistent with self.
- The shape needs to be consistent with self.
FLOAT16, FLOAT, DOUBLE, UINT8, INT8, INT16, INT32, INT64, BOOL, BFLOAT16 ND 0-8 √ workspaceSize (uint64_t*) Output Returns the workspace size to be applied on the Device side. - - - - - executor (aclOpExecutor**) Output Returns the op executor. It includes the calculation flow of the operator. - - - - - Atlas training products : The BFLOAT16 data type is not supported.
Return value
aclnnStatus: return status code. For details, see aclnn Error Codes.
The first-phase API performs input parameter validation and returns an error in the following scenarios:
Error Code Error Code Description ACLNN_ERR_PARAM_NULLPTR 161001 The self, prob, or out parameter is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data type or data format of self or out is not supported. The data type of prob is not supported. The data types of self and out are inconsistent. prob does not meet the requirement of 0≤prob≤1. self or out has more than 8 dimensions. The shapes of self and out are inconsistent.
aclnnBernoulli
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address applied on the Device side. workspaceSize Input Workspace size applied on the Device side, obtained by the first-phase API aclnnBernoulliGetWorkspaceSize. executor Input Op executor, includes the calculation flow of the operator. stream Input Specifies the Stream for task execution. Return value
aclnnStatus: return status code. See specifically aclnn return codes.
aclnnInplaceBernoulliGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor selfRef (aclTensor*) Input/Output out in the formula. Supports empty tensors. FLOAT16, FLOAT, DOUBLE, UINT8, INT8, INT16, INT32, INT64, BOOL, BFLOAT16 ND 0-8 √ prob (aclScalar*) Input prob in the formula. Must satisfy 0≤prob≤1. FLOAT16, FLOAT, DOUBLE, BFLOAT16 - - - seed (int64_t) Input Sets the seed of the random number generator. - INT64 - - - offset (int64_t) Input Sets the random number offset. Value constraint: offset % 4 == 0. For example, the value can be 0, 4, 8 .... The call fails if the constraint is not met. INT64 - - - workspaceSize (uint64_t*) Output Returns the size of the workspace to be applied on the Device side. - - - - - executor (aclOpExecutor**) Output Returns the op executor, which includes the calculation process of the operator. - - - - - Atlas training products : The BFLOAT16 data type is not supported.
Return value
aclnnStatus: Return status code, see specifically aclnn return code.
The first-phase API performs input parameter validation and returns an error in the following scenarios:
Error Code Error Code Description ACLNN_ERR_PARAM_NULLPTR 161001 The selfRef or prob parameter is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data type or data format of selfRef is not within the supported range. The data type of prob is not within the supported range. The value of prob does not satisfy 0≤prob≤1. The dimension of selfRef is greater than 8.
aclnnInplaceBernoulli
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address applied on the Device side. workspaceSize Input Workspace size applied on the Device side, obtained by the first-phase API aclnnInplaceBernoulliGetWorkspaceSize. executor Input Op executor, includes the calculation flow of the operator. stream Input Specifies the Stream for executing tasks. Return value
aclnnStatus: Return status code. See specifically aclnn return code.
Constraints
- Deterministic computation:
- aclnnBernoulli&aclnnInplaceBernoulli 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.
aclnnBernoulli
#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: 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 memory on the Device side.
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 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. For details, see the acl API documentation.
// Fill in 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 == 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> selfShape = {4, 4};
std::vector<int64_t> outShape = {4, 4};
void* selfDeviceAddr = nullptr;
void* outDeviceAddr = nullptr;
aclTensor* self = nullptr;
aclScalar* 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> outHostData(16, 0);
int64_t seed = 0;
int64_t offset = 0;
float probValue = 1.0f;
// Create the self aclTensor.
ret = CreateAclTensor(selfHostData, selfShape, &selfDeviceAddr, aclDataType::ACL_FLOAT, &self);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the prob aclScalar.
prob = aclCreateScalar(&probValue,aclDataType::ACL_FLOAT);
CHECK_RET(prob != nullptr, 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 calling the aclnnBernoulli API
// 3. Call the CANN operator library API.
// Call the aclnnBernoulli first-phase API.
ret = aclnnBernoulliGetWorkspaceSize(self, prob, seed, offset, out, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnBernoulliGetWorkspaceSize 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 aclnnBernoulli second-phase API.
ret = aclnnBernoulli(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnBernoulli failed. ERROR: %d\n", ret); return ret);
// 4. (Boilerplate) Synchronize and 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, copy the result in Device memory to the Host side, and 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(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, and modify them based on the specific API definition.
aclDestroyTensor(self);
aclDestroyScalar(prob);
aclDestroyTensor(out);
// 7. Release device resources. Modify the code according to the interface definition of the specific API.
aclrtFree(selfDeviceAddr);
aclrtFree(outDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}aclnnInplaceBernoulli
#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. 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 memory on the Device side.
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 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 the aclCreateTensor API to create 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 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 needed.
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// 2. Construct the input and output, which need to be customized based on the API.
std::vector<int64_t> selfShape = {4, 4};
void* selfDeviceAddr = nullptr;
aclTensor* self = nullptr;
aclScalar* prob = nullptr;
std::vector<float> selfHostData = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
int64_t seed = 0;
int64_t offset = 0;
float probValue = 1.0f;
// Create the self aclTensor.
ret = CreateAclTensor(selfHostData, selfShape, &selfDeviceAddr, aclDataType::ACL_FLOAT, &self);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the prob aclScalar.
prob = aclCreateScalar(&probValue,aclDataType::ACL_FLOAT);
CHECK_RET(prob != nullptr, return ret);
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// aclnnInplaceBernoulli API call example
// 3. Call the CANN operator library API.
// Call the first-phase API of aclnnInplaceBernoulli.
ret = aclnnInplaceBernoulliGetWorkspaceSize(self, prob, seed, offset, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnInplaceBernoulliGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
// Allocate memory on the Device based on the workspaceSize computed 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 aclnnInplaceBernoulli.
ret = aclnnInplaceBernoulli(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnInplaceBernoulli failed. ERROR: %d\n", ret); return ret);
// 4. (Boilerplate) Synchronize and wait for the task to finish.
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 memory on the Device to the Host. Modify the code based on the specific API definition.
auto size = GetShapeSize(selfShape);
std::vector<float> resultData(size, 0);
ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), selfDeviceAddr,
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 it according to the specific API definition.
aclDestroyTensor(self);
aclDestroyScalar(prob);
// 7. Release device resources. Modify it according to the specific API definition.
aclrtFree(selfDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}