aclnnBatchNorm

📄 View Source Code

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: Supported
  • Atlas training products: Supported

Function

  • Description: Normalizes a batch of data. The normalized data has a mean of 0 and a standard deviation of 1.

  • Formula:

    y=(x−E(x))Var(x)+eps∗weight+biasy = \frac{(x - E(x))}{\sqrt{Var(x) + eps}} * weight + bias

    E(x) denotes the mean, and Var(x) denotes the variance. Both need to be computed inside the operator. eps denotes a very small floating-point number to prevent the denominator from being 0.

Function Prototype

Each operator uses a two-phase API. First call the "aclnnBatchNormGetWorkspaceSize" API to obtain the input parameters and calculate the required workspace size according to the procedure, 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 Denotes the input for the BatchNorm computation, corresponding to `x` in the formula.
    • Supports empty tensors.
    • Supported shapes and formats: 2D (corresponding format: NC), 3D (corresponding format: NCL), 4D (corresponding formats: NCHW, NHWC), 5D (corresponding formats: NCDHW, NDHWC), and 6-8D (corresponding format: ND, where the second dimension is fixed to the channel axis).
    FLOAT32, FLOAT16, BFLOAT16 NC, NCL, NCHW, NHWC, NCDHW, NDHWC, ND 2-8 √
    weight (aclTensor*) Input Denotes the weight tensor for the BatchNorm computation, corresponding to `weight` in the formula.
    • Supports empty tensor.
    • Optional parameter.
    • The shape length equals the length of the channel axis in the input parameter `input`.
    FLOAT32, FLOAT16, BFLOAT16 ND 1 √
    bias (aclTensor*) Input Denotes the bias Tensor used for the BatchNorm computation, corresponding to `bias` in the corresponding formula.
    • Supports empty tensor.
    • Optional parameter.
    • The shape length equals the length of the channel axis in the input parameter `input`.
    FLOAT32, FLOAT16, BFLOAT16 ND 1 √
    runningMean(aclTensor*) Input/Output Training scenario: the mean before and after momentum update during training; inference scenario: the mean used during inference, which is `E(x)` in the corresponding formula.
    • Supports empty Tensor.
    • Optional parameter.
    • The shape length equals the channel axis length in input `input`.
    FLOAT32, FLOAT16, BFLOAT16 ND 1 √
    runningVar (aclTensor*) Input/Output Training scenario: variance before and after momentum update during training; inference scenario: variance used during inference, corresponding to `Var(x)` in the formula.
    • Supports empty tensors.
    • Optional parameter with a non-negative value.
    • The shape length equals the channel axis length in `input`.
    FLOAT32, FLOAT16, BFLOAT16 ND 1 √
    training (bool) Input Specifies whether it is the training scenario. true indicates the training scenario, and false indicates the inference scenario. - - - -
    momentum (double) Input Specifies the momentum coefficient used to update the running mean and variance. - - - - -
    eps (double) Input Denotes the value added to the variance to avoid division by zero. Corresponds to `eps` in the corresponding formula. - - - - -
    output (aclTensor*) Output Denotes the output result of BatchNorm, corresponding to `y` in the formula.
    • Supports empty tensor.
    • The data type, data format, and shape are the same as those of the input parameter `input`.
    FLOAT32, FLOAT16, BFLOAT16 NC, NCL, NCHW, NHWC, NCDHW, NDHWC, ND 2-8 √
    saveMean (aclTensor*) Output Output only in the training scenario. Denotes the saved mean, which is `E(x)` in the corresponding formula.
    • Supports empty tensor.
    • 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. Saves the 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 is equal to the channel axis length of the input parameter `input`.
    FLOAT32, FLOAT16, BFLOAT16 ND 1 √
    workspaceSize (uint64_t*) Output Returns the size of the workspace the user needs to allocate on the device side. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor containing the operator computation flow. - - - - -
    • Atlas training products, Atlas inference products:
      • The data type of the input, weight, bias, runningMean, runningVar, output, saveMean, and saveInvstd parameters does not support BFLOAT16.
      • The data formats of the input and output parameters do not support NHWC or NDHWC.
      • The saveInvstd parameter represents the variance of input.
    • Atlas A2 products, Atlas A3 products:
      • The data formats of the input and output parameters do not support NHWC or NDHWC.
      • The saveInvstd parameter represents the variance of input.
    • Ascend 950PR&950DT products: The parameter saveInvstd indicates the reciprocal of the standard deviation of input.
  • 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 pointer-type input parameter passed in is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type or data format of the input or output tensor is out of the supported range.
    The shape of the input or output tensor is out of the supported range.
    The shape lengths of weight, bias, runningMean, runningVar, saveMean (in the training scenario), and saveInvstd (in the training scenario) 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 number of shape dimensions is greater than 8 or less than 2.

aclnnBatchNorm

  • Parameters

    Parameter Input/Output Description
    workspace Input Device side-applied workspace memory address.
    workspaceSize Input Device side-applied workspace size, obtained by calling the first-phase API aclnnBatchNormGetWorkspaceSize.
    executor Input Op executor that contains the operator computation flow.
    stream Input Stream for task execution.
  • Return Value

    aclnnStatus: return status code. For details, see aclnn Error Codes.

Constraints

  • Deterministic computation:

    • Atlas A3 products, Atlas A2 products, Atlas training products, Atlas inference products: aclnnBatchNorm defaults to a non-deterministic implementation. Deterministic computation can be enabled through aclrtCtxSetSysParamOpt.
    • Ascend 950PR&950DT products: aclnnBatchNorm defaults to a deterministic implementation.

Example

The 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_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: initialize resources.
    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); aclFinalize(); return ret);
    ret = aclrtCreateStream(stream);
    CHECK_RET(ret == ACL_SUCCESS,
        LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret);
        aclrtResetDevice(deviceId); aclFinalize(); 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 host-side data to 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.
    // 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. Customize the construction according to 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 the rMean aclTensor.
    ret = CreateAclTensor(rMeanHostData, rMeanShape, &rMeanDeviceAddr, aclDataType::ACL_FLOAT, &rMean);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the rVar aclTensor.
    ret = CreateAclTensor(rVarHostData, rVarShape, &rVarDeviceAddr, aclDataType::ACL_FLOAT, &rVar);
    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);
    // Create the mean aclTensor.
    ret = CreateAclTensor(meanHostData, meanShape, &meanDeviceAddr, aclDataType::ACL_FLOAT, &mean);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the var aclTensor.
    ret = CreateAclTensor(varHostData, varShape, &varDeviceAddr, aclDataType::ACL_FLOAT, &var);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;

    // Example of calling the aclnnBatchNorm API.
    // 3. Call the CANN operator library API. Replace it 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);
    // 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 aclnnBatchNorm.
    ret = aclnnBatchNorm(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnBatchNorm 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 and copy the result from Device-side memory to the Host side. Modify the code 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 the code 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 the code 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;
}