aclnnBatchNorm
Applicable Products
| Product | Supported |
|---|---|
| √ | |
| √ | |
| √ | |
| × | |
| √ | |
| √ |
Function
Description: Performs batch normalization on a batch of data. After normalization, the generated data has a statistical result of zero mean and unit standard deviation.
Formula:
E(x) represents the mean, and Var(x) represents the variance, both of which need to be computed internally by the operator. ε represents a very small floating-point number to prevent division by zero.
Function Prototype
Each operator is divided into a two-phase API. You must first call the "aclnnBatchNormGetWorkspaceSize" API to obtain the input parameters and calculate the required workspace size based on the process, and then call the "aclnnBatchNorm" API to perform the computation.
aclnnStatus aclnnBatchNormGetWorkspaceSize(
const aclTensor *input,
const aclTensor *weight,
const aclTensor *bias,
aclTensor *runningMean,
aclTensor *runningVar,
bool training,
double momentum,
double eps,
aclTensor *output,
aclTensor *saveMean,
aclTensor *saveInvstd,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnBatchNorm(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnBatchNormGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (Shape) Non-contiguous Tensor input (aclTensor*) Input Represents the input for BatchNorm computation, corresponding to `x` in the formula. - Supports empty tensors.
- Supported shapes and formats include: 2D (corresponding format: NC), 3D (corresponding format: NCL), 4D (corresponding formats: NCHW, NHWC), 5D (corresponding formats: NCDHW, NDHWC), and 6D–8D (corresponding format: ND, where the second dimension is fixed as the channel axis).
FLOAT32, FLOAT16, BFLOAT16 NC, NCL, NCHW, NHWC, NCDHW, NDHWC, ND 2-8 √ weight (aclTensor*) Input Represents the weight tensor for batch normalization computation, corresponding to `weight` in the formula. - Empty tensors are supported.
- Optional parameter.
- The shape length equals the channel axis length of the input `input`.
FLOAT32, FLOAT16, BFLOAT16 ND 1 √ bias (aclTensor*) Input Represents the bias tensor for BatchNorm computation, corresponding to `bias` in the formula. - Supports empty tensors.
- Optional parameter.
- The shape length equals the channel axis length of the input parameter `input`.
FLOAT32, FLOAT16, BFLOAT16 ND 1 √ runningMean (aclTensor*) Input Represents the mean value used during inference, which corresponds to `E(x)` in the formula. - Supports empty tensors.
- Optional parameter.
- The shape length equals the length of the channel axis in the input parameter `input`.
FLOAT32, FLOAT16, BFLOAT16 ND 1 √ runningVar (aclTensor*) Input Represents the variance used during inference, corresponding to `Var(x)` in the formula. - Supports empty tensors.
- Optional parameter. The value is non-negative.
- The shape length equals the length of the channel axis in the input parameter `input`.
FLOAT32, FLOAT16, BFLOAT16 ND 1 √ training (bool) Input Indicates whether the scenario is training. true indicates a training scenario, and false indicates an inference scenario. - - - - momentum (double) Input Indicates that it is used to update the running mean and variance. - - - - - eps (double) Input Represents the value added to the variance to avoid division by zero. Corresponds to `eps` in the formula. - - - - - output (aclTensor*) Output Represents the output result of BatchNorm, corresponding to `y` in the formula. - Supports empty tensors.
- The data type, data format, and shape are consistent with the input parameter `input`.
FLOAT32, FLOAT16, BFLOAT16 NC, NCL, NCHW, NHWC, NCDHW, NDHWC, ND 2-8 √ saveMean (aclTensor*) Output Output only in training scenarios. Represents the saved mean, corresponding to `E(x)` in the formula. - Supports empty tensors.
- The shape length equals the length of the channel axis in the input parameter `input`.
FLOAT32, FLOAT16, BFLOAT16 ND 1 √ saveInvstd (aclTensor*) Output Output only in the training scenario. Represents the saved input variance or the reciprocal of the input standard deviation, corresponding to `Var(x)` and the reciprocal of the square root of (Var(x) + eps) in the formula, respectively. - Supports empty tensors.
- The shape length equals the length of the channel axis in the input parameter `input`.
FLOAT32, FLOAT16, BFLOAT16 ND 1 √ workspaceSize (uint64_t*) Output Returns the workspace size that the user needs to apply for on the Device side. - - - - - executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - - Atlas training products ,Atlas inference products :The data type of the
input,weight,bias,runningMean,runningVar,output,saveMean, andsaveInvstdparameters does not support BFLOAT16.The data formats of the
inputandoutputparameters do not support NHWC or NDHWC.The
saveInvstdparameter represents the variance of input.
Atlas A2 training products/Atlas A2 inference products ,Atlas A3 training products/Atlas A3 inference products :The data formats of the
inputandoutputparameters do not support NHWC or NDHWC.The
saveInvstdparameter represents the variance of input.
Ascend 950PR/Ascend 950DT : ThesaveInvstdparameter represents the reciprocal of the standard deviation of input.
Return Value
aclnnStatus: return code. For details, see aclnn Return Code.
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 A null pointer is passed as the pointer-type input parameter. ACLNN_ERR_PARAM_INVALID 161002 The data type or data format of the input or output tensor is not within the supported range. The shape of the input or output tensor is not within the supported range. The shape lengths of weight, bias, runningMean, runningVar, saveMean (in training scenarios), and saveInvstd (in training scenarios) are not equal to the channel axis length in the input shape. The data formats of input and output are inconsistent. The shapes of input and output are inconsistent, or the shape dimension is greater than 8 or less than 2.
aclnnBatchNorm
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 aclnnBatchNormGetWorkspaceSize. 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 Code.
Constraints
Deterministic computation:
- aclnnBatchNorm defaults to a non-deterministic implementation. Deterministic computation can be enabled through aclrtCtxSetSysParamOpt.
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_batch_norm.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 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 apply for device memory.
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 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 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];
}
// 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 own needs.
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.
std::vector<int64_t> selfShape = {1, 2, 4};
std::vector<int64_t> weightShape = {2};
std::vector<int64_t> biasShape = {2};
std::vector<int64_t> rMeanShape = {2};
std::vector<int64_t> rVarShape = {2};
std::vector<int64_t> outShape = {1, 2, 4};
std::vector<int64_t> meanShape = {2};
std::vector<int64_t> varShape = {2};
void* selfDeviceAddr = nullptr;
void* weightDeviceAddr = nullptr;
void* biasDeviceAddr = nullptr;
void* rMeanDeviceAddr = nullptr;
void* rVarDeviceAddr = nullptr;
void* outDeviceAddr = nullptr;
void* meanDeviceAddr = nullptr;
void* varDeviceAddr = nullptr;
aclTensor* self = nullptr;
aclTensor* weight = nullptr;
aclTensor* bias = nullptr;
aclTensor* rMean = nullptr;
aclTensor* rVar = nullptr;
aclTensor* out = nullptr;
aclTensor* mean = nullptr;
aclTensor* var = nullptr;
std::vector<float> selfHostData = {0, 1, 2, 3, 4, 5, 6, 7};
std::vector<float> weightHostData = {1, 1};
std::vector<float> biasHostData = {0, 0};
std::vector<float> rMeanHostData = {0, 0};
std::vector<float> rVarHostData = {1, 1};
std::vector<float> outHostData(8, 0);
std::vector<float> meanHostData = {1, 1};
std::vector<float> varHostData = {1, 1};
bool training = true;
double momentum = 0.1;
double eps = 1e-5;
// Create the self aclTensor.
ret = CreateAclTensor(selfHostData, selfShape, &selfDeviceAddr, aclDataType::ACL_FLOAT, &self);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the weight aclTensor.
ret = CreateAclTensor(weightHostData, weightShape, &weightDeviceAddr, aclDataType::ACL_FLOAT, &weight);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the bias aclTensor.
ret = CreateAclTensor(biasHostData, biasShape, &biasDeviceAddr, aclDataType::ACL_FLOAT, &bias);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create rMean aclTensor.
ret = CreateAclTensor(rMeanHostData, rMeanShape, &rMeanDeviceAddr, aclDataType::ACL_FLOAT, &rMean);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create rVar aclTensor.
ret = CreateAclTensor(rVarHostData, rVarShape, &rVarDeviceAddr, aclDataType::ACL_FLOAT, &rVar);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create out aclTensor.
ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT, &out);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create mean aclTensor.
ret = CreateAclTensor(meanHostData, meanShape, &meanDeviceAddr, aclDataType::ACL_FLOAT, &mean);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create var aclTensor.
ret = CreateAclTensor(varHostData, varShape, &varDeviceAddr, aclDataType::ACL_FLOAT, &var);
CHECK_RET(ret == ACL_SUCCESS, return ret);
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// aclnnBatchNorm API call example
// 3. Call the CANN operator library API. Replace with the actual API name.
// Call the first-phase API of aclnnBatchNorm.
ret = aclnnBatchNormGetWorkspaceSize(
self, weight, bias, rMean, rVar, training, momentum, eps, out, mean, var, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnBatchNormGetWorkspaceSize 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 aclnnBatchNorm.
ret = aclnnBatchNorm(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnBatchNorm 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 memory to the Host. 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(weight);
aclDestroyTensor(bias);
aclDestroyTensor(rMean);
aclDestroyTensor(rVar);
aclDestroyTensor(out);
aclDestroyTensor(mean);
aclDestroyTensor(var);
// 7. Release device resources. Modify based on the specific API definition.
aclrtFree(selfDeviceAddr);
aclrtFree(weightDeviceAddr);
aclrtFree(biasDeviceAddr);
aclrtFree(rMeanDeviceAddr);
aclrtFree(rVarDeviceAddr);
aclrtFree(outDeviceAddr);
aclrtFree(meanDeviceAddr);
aclrtFree(varDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}