aclnnGroupNorm

📄 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: Computes the group normalization result out, mean meanOut, and reciprocal of standard deviation rstdOut for the input self.

  • Formula:

    Let x=selfx=self, E[x]=xˉE[x] = \bar{x} represent the mean of xx, and Var[x]=1n−1∗∑i=1n(xi−E[x])2Var[x] = \frac{1}{n - 1} * \sum_{i=1}^n(x_i - E[x])^2 represent the sample variance of xx, then

    out=x−E[x]Var[x]+eps∗γ+βout = \frac{x - E[x]}{\sqrt{Var[x] + eps}} * \gamma + \beta meanOut=E[x]meanOut = E[x] rstdOut=1Var[x]+epsrstdOut = \frac{1}{\sqrt{Var[x] + eps}}

Function Prototype

Each operator is divided into a two-phase API. The aclnnGroupNormGetWorkspaceSize API must be called first to obtain the workspace size required for computation and the executor that encapsulates the operator computation flow. Then, the aclnnGroupNorm API is called to perform the computation.

aclnnStatus aclnnGroupNormGetWorkspaceSize(
  const aclTensor *self,
  const aclTensor *gamma,
  const aclTensor *beta,
  int64_t          N,
  int64_t          C,
  int64_t          HxW,
  int64_t          group,
  double           eps,
  aclTensor       *out,
  aclTensor       *meanOut,
  aclTensor       *rstdOut,
  uint64_t        *workspaceSize,
  aclOpExecutor  **executor)
aclnnStatus aclnnGroupNorm(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnGroupNormGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (Shape) Non-contiguous Tensor
    self (aclTensor*) Input Indicates the input for normalization calculation, corresponding to `x` in the formula.
    • Supports empty tensor.
    FLOAT32、FLOAT16、BFLOAT16 ND 2-8 √
    gamma (aclTensor*) Input Indicates the scale factor (weight) for performing normalization calculation, corresponding to `γ` in the formula.
    • Supports empty tensor.
    • The data type is the same as self.
    • The number of elements must be the same as C.
    FLOAT32, FLOAT16, BFLOAT16 ND 1 √
    beta (aclTensor*) Input Indicates the offset for performing normalization calculation, corresponding to `β` in the formula.
    • Supports empty tensor.
    • The data type is the same as self.
    • The number of elements must be the same as C.
    FLOAT32, FLOAT16, BFLOAT16 ND 1 √
    N (int64_t) Input. Indicates the spatial size of the input self in the N dimension. - - - - -
    C (int64_t) Input Indicates the spatial size of the input self in the C dimension. - - - - -
    HxW (int64_t) Input Indicates the spatial size of the input self excluding the N and C dimensions.
    • If there are no other dimensions, it is 1.
    - - - -
    group (int64_t) Input Indicates dividing the C dimension of the input self into group groups.
    • group must be greater than 0.
    - - - -
    eps (double) Input The `eps` value in the calculation formulas of out and rstdOut, which is added to the denominator for numerical stability.
    • Must be greater than 0. To maintain precision, eps must be greater than or equal to 1e-5.
    - - - -
    out (aclTensor*) Output Indicates the result of performing normalization calculation, corresponding to `out` in the formula.
    • Supports empty tensor.
    • The data type and shape are the same as self.
    • The data format is the same as self.
    FLOAT32, FLOAT16, BFLOAT16 ND 2-8 √
    meanOut (aclTensor*) Output Indicates the mean after normalization, corresponding to `meanOut` in the formula.
    • Supports empty tensor.
    • The data type is the same as self.
    • The shape is (N, group).
    FLOAT32, FLOAT16, BFLOAT16 ND 2 √
    rstdOut (aclTensor*) Output Indicates the reciprocal of the standard deviation after normalization, corresponding to `rstdOut` in the formula.
    • Supports empty tensor.
    • The data type is the same as self.
    • The shape is (N, group).
    FLOAT32, FLOAT16, BFLOAT16 ND 2 √
    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 includes the operator calculation flow. - - - - -
    • Atlas training products, Atlas inference products:

      The data types of the self, gamma, beta, out, meanOut, and rstdOut parameters do not support BFLOAT16.

  • 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 If the passed parameter is a mandatory input, output, or mandatory attribute and is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of self, gamma, beta, out, meanOut, or rstdOut is not within the supported range.
    The data type of gamma, beta, out, meanOut, or rstdOut is different from that of self.
    The dimension of self is less than 2 or greater than 8.
    group is not greater than 0.
    C is not divisible by group.
    eps is not greater than 0.
    The shape of out differs from that of x.
    The shape of meanOut and rstdOut is not (N, group).
    The spatial size of self in the N dimension is not equal to N.
    The spatial size of self in the C dimension is not equal to C.
    The product of sizes of self from the third dimension onward is not equal to HxW (when self is two-dimensional, HxW must be 1).
    The number of elements in self is not equal to N*C*HxW.
    gamma is not 1-dimensional and its number of elements is not equal to C.
    beta is not 1-dimensional and its number of elements is not equal to C.
    self and out have different formats.

aclnnGroupNorm

  • Parameters

    Parameter Input/Output Description
    workspace Input Memory address of the workspace applied on the Device side.
    workspaceSize Input Size of the workspace applied on the Device side, obtained through the first-phase API aclnnGroupNormGetWorkspaceSize.
    executor Input Operator executor, which includes the operator calculation process.
    stream Input Specifies the stream for executing the task.
  • Return Value

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

Constraints

  • Deterministic computation:

    • aclnnGroupNorm defaults to a deterministic implementation.

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_group_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 shape_size = 1;
    for (auto i : shape) {
        shape_size *= i;
    }
    return shape_size;
}

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 apply for device-side 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);

    // 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 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. See the acl API manual.
    // Set deviceId based on your actual device.
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = Init(deviceId, &stream);
    // Handle based on your own needs.
    CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
    // 2. Construct inputs and outputs. Customize the construction based on the API interface.
    std::vector<int64_t> selfShape = {2, 3, 4};
    std::vector<int64_t> gammaShape = {3};
    std::vector<int64_t> betaShape = {3};
    std::vector<int64_t> outShape = {2, 3, 4};
    std::vector<int64_t> meanOutShape = {2, 1};
    std::vector<int64_t> rstdOutShape = {2, 1};
    void* selfDeviceAddr = nullptr;
    void* gammaDeviceAddr = nullptr;
    void* betaDeviceAddr = nullptr;
    void* outDeviceAddr = nullptr;
    void* meanOutDeviceAddr = nullptr;
    void* rstdOutDeviceAddr = nullptr;
    aclTensor* self = nullptr;
    aclTensor* gamma = nullptr;
    aclTensor* beta = nullptr;
    aclTensor* out = nullptr;
    aclTensor* meanOut = nullptr;
    aclTensor* rstdOut = nullptr;
    std::vector<float> selfHostData = {1.0,  2.0,  3.0,  4.0,  5.0,  6.0,  7.0,  8.0,  9.0,  10.0, 11.0, 12.0,
                                       13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0};
    std::vector<float> gammaHostData = {2.0, 2, 2};
    std::vector<float> betaHostData = {2.0, 2, 2};
    std::vector<float> outHostData = {1.0,  2.0,  3.0,  4.0,  5.0,  6.0,  7.0,  8.0,  9.0,  10.0, 11.0, 12.0,
                                      13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0};
    std::vector<float> meanOutHostData = {2.0, 2};
    std::vector<float> rstdOutHostData = {2.0, 2};
    int64_t N = 2;
    int64_t C = 3;
    int64_t HxW = 4;
    int64_t group = 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 gamma aclTensor.
    ret = CreateAclTensor(gammaHostData, gammaShape, &gammaDeviceAddr, aclDataType::ACL_FLOAT, &gamma);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the beta aclTensor.
    ret = CreateAclTensor(betaHostData, betaShape, &betaDeviceAddr, aclDataType::ACL_FLOAT, &beta);
    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 meanOut aclTensor.
    ret = CreateAclTensor(meanOutHostData, meanOutShape, &meanOutDeviceAddr, aclDataType::ACL_FLOAT, &meanOut);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the rstdOut aclTensor.
    ret = CreateAclTensor(rstdOutHostData, rstdOutShape, &rstdOutDeviceAddr, aclDataType::ACL_FLOAT, &rstdOut);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // 3. Call the CANN operator library API. Replace it with the specific API.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the first-phase API of aclnnGroupNorm.
    ret = aclnnGroupNormGetWorkspaceSize(
        self, gamma, beta, N, C, HxW, group, eps, out, meanOut, rstdOut, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGroupNormGetWorkspaceSize 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 aclnnGroupNorm.
    ret = aclnnGroupNorm(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGroupNorm failed. ERROR: %d\n", ret); return ret);
    // 4. (Boilerplate) Synchronize and 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 device memory to host memory. Modify based on the specific API definition.
    auto size = GetShapeSize(outShape);
    std::vector<float> outResultData(size, 0);
    ret = aclrtMemcpy(
        outResultData.data(), outResultData.size() * sizeof(outResultData[0]), outDeviceAddr, size * sizeof(float),
        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("outResultData[%ld] is: %f\n", i, outResultData[i]);
    }

    size = GetShapeSize(meanOutShape);
    std::vector<float> meanResultData(size, 0);
    ret = aclrtMemcpy(
        meanResultData.data(), meanResultData.size() * sizeof(meanResultData[0]), meanOutDeviceAddr,
        size * sizeof(float), 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("meanResultData[%ld] is: %f\n", i, meanResultData[i]);
    }

    size = GetShapeSize(rstdOutShape);
    std::vector<float> rstdResultData(size, 0);
    ret = aclrtMemcpy(
        rstdResultData.data(), rstdResultData.size() * sizeof(rstdResultData[0]), rstdOutDeviceAddr,
        size * sizeof(float), 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("rstdResultData[%ld] is: %f\n", i, rstdResultData[i]);
    }

    // 6. Release aclTensor and aclScalar. Modify based on the specific API definition.
    aclDestroyTensor(self);
    aclDestroyTensor(gamma);
    aclDestroyTensor(beta);
    aclDestroyTensor(out);
    aclDestroyTensor(meanOut);
    aclDestroyTensor(rstdOut);

    // 7. Release device resources. Modify based on the specific API definition.
    aclrtFree(selfDeviceAddr);
    aclrtFree(gammaDeviceAddr);
    aclrtFree(betaDeviceAddr);
    aclrtFree(outDeviceAddr);
    aclrtFree(meanOutDeviceAddr);
    aclrtFree(rstdOutDeviceAddr);

    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return 0;
}