aclnnBernoulliTensor&aclnnInplaceBernoulliTensor
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 is the probability of generating the binary random numbers, and the input tensor is used to specify the shape.
Formula:
When aclnnBernoulliTensor is used, 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 aclnnInplaceBernoulliTensor is used, 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 uses a two-phase API. Call "aclnnBernoulliTensorGetWorkspaceSize" or "aclnnInplaceBernoulliTensorGetWorkspaceSize" first to obtain the workspace size required for the computation and the executor containing the operator computation process, and then call "aclnnBernoulliTensor" or "aclnnInplaceBernoulliTensor" 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 Dimension (shape) Non-contiguous Tensor self Input aclTensor on the Device side, used to specify the shape of output out. The shape must be the same as the shape of out. FLOAT16, FLOAT, DOUBLE, UINT8, INT8, INT16, INT32, INT64, BOOL, BFLOAT16 ND 0-8 √ prob Input aclTensor on the Device side, corresponding to prob in the formula. 0≤prob≤1 must be satisfied. The data format must be the same as that of self. FLOAT16, FLOAT, DOUBLE, BFLOAT16 ND 0-8 √ seed Input An integer on the Host side, which sets the seed of the random number generator. - INT64 ND - √ offset Input Integer on the Host side. 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 ND - - out Output The out in the formula, an aclTensor on the Device side. The shape must be the same as that of self, and the data type must be the same as that of 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 op executor that contains the operator computation flow. - - - - - Atlas training products : Data types UINT8, INT8, INT16, INT32, INT64, BOOL, and BFLOAT16 are not supported.
Atlas A2 products andAtlas A3 products : Data types UINT8, INT8, INT16, INT32, INT64, and BOOL are not supported.
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:
Error Code Error Code Description ACLNN_ERR_PARAM_NULLPTR 161001 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 out of the supported range. The data types of self and out are inconsistent. The dimension of self, prob, or out is greater than 8. The shapes of self and out are inconsistent.
aclnnBernoulliTensor
Parameters:
Parameter Input/Output Description workspace Input The workspace memory address requested on the Device side. workspaceSize Input The workspace size requested on the Device side, obtained by the first-phase API aclnnBernoulliTensorGetWorkspaceSize. executor Input The op executor, which contains the operator computation flow. stream Input Stream used to execute tasks. Return value
aclnnStatus: return status code. For details, see aclnn Error Codes.
aclnnInplaceBernoulliTensorGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor selfRef Input, 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 prob in the formula, an aclTensor on the Host side. - Satisfies 0≤prob≤1.
FLOAT16, FLOAT, DOUBLE, BFLOAT16 ND 0-8 √ seed Input An integer on the Host side, which sets the seed of the random number generator. - INT64 ND - - offset Input Integer on the Host side, specifying the random number offset. Value constraint: offset % 4 == 0, for example, 0, 4, 8, .... The call fails if this constraint is not met. 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 BFLOAT16 data type is not supported.
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:
Error 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 in the supported range. The dimension of selfRef or prob is greater than 8.
aclnnInplaceBernoulliTensor
Parameters:
Parameter Input/Output Description workspace Input The workspace memory address requested on the Device side. workspaceSize Input The workspace size requested on the Device side, obtained by the first-phase API aclnnInplaceBernoulliTensorGetWorkspaceSize. executor Input Op executor that contains the operator calculation process. stream Input Stream for executing tasks. Return value
aclnnStatus: return status code. For details, see aclnn Error Codes.
Constraints
- Deterministic computation: aclnnBernoulliTensor&aclnnInplaceBernoulliTensor default to a deterministic implementation.
- The element values of the input prob must be in the range [0, 1].
- If the shape of the input prob differs from that of the input self/selfRef, only the data of the corresponding elements between the two is computed, and the behavior of the remaining data is undefined. For example, when prob is of shape [4, 2] and self is of shape [4, 4], only the first 8 elements are computed, and the output is of shape [4, 4]. When prob is of shape [4, 4, 2] and self is of shape [4, 4], only the first 16 elements are computed, and the output is of shape [4, 4].
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_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 Device side 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 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 device/stream. For details, see the acl API manual.
// Fill in 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. Perform custom construction based on the API.
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 calling the aclnnBernoulliTensor API
// 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);
// 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 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 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 to the Host side. Modify it according to 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 it according to the specific API definition.
aclDestroyTensor(self);
aclDestroyTensor(prob);
aclDestroyTensor(out);
// 7. Release device resources. Modify it according to the specific API definition.
aclrtFree(selfDeviceAddr);
aclrtFree(probDeviceAddr);
aclrtFree(outDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}