aclnnGroupNorm

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

  • Formula:

    Let x=selfx=self, where E[x]=xˉE[x] = \bar{x} denotes the mean of xx, and Var[x]=1n∗∑i=1n(xi−E[x])2Var[x] = \frac{1}{n} * \sum_{i=1}^n(x_i - E[x])^2 denotes 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 uses a two-phase API. You must first call the aclnnGroupNormGetWorkspaceSize API to obtain the workspace size required for the calculation and the executor containing the operator calculation process, and then call the aclnnGroupNorm API to perform the calculation.

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 Shape Non-contiguous Tensor
    self (aclTensor*) Input Indicates the input of the normalization calculation, which is `x` in the corresponding formula.
    • Supports null Tensor.
    FLOAT32, FLOAT16, BFLOAT16 ND 2-8 √
    gamma (aclTensor*) Input Indicates the scaling factor (weight) of the normalization calculation, which is `γ` in the corresponding formula.
    • Supports null tensors.
    • Data type is the same as self.
    • Number of elements must be the same as C.
    FLOAT32, FLOAT16, BFLOAT16 ND 1 √
    beta (aclTensor*) Input Offset for the normalization calculation, corresponding to `β` in the formula.
    • Supports null tensors.
    • Data type is the same as self.
    • Number of elements must be the same as C.
    FLOAT32, FLOAT16, BFLOAT16 ND 1 √
    N (int64_t) Input Represents the spatial size of input self on the N dimension. - - - - -
    C (int64_t) Input Specifies the spatial size of input self on the C dimension. - - - - -
    HxW (int64_t) Input Represents the spatial size of input self on dimensions other than N and C.
    • If there are no other dimensions, the value is 1.
    - - - -
    group (int64_t) Input Indicates that the C dimension of input self is divided into group groups.
    • group must be greater than 0.
    - - - -
    eps (double) Input Value of `eps` in the formula for computing 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 Represents the result of the normalization calculation, corresponding to `out` in the formula.
    • Supports null Tensor.
    • The data type and shape are the same as those of self.
    • The data format is the same as that of self.
    FLOAT32, FLOAT16, BFLOAT16 ND 2-8 √
    meanOut (aclTensor*) Output Represents the mean after the normalization calculation, corresponding to `meanOut` in the formula.
    • Support null tensor.
    • Data type is the same as self.
    • Shape is (N, group).
    FLOAT32, FLOAT16, BFLOAT16 ND 2 √
    rstdOut (aclTensor*) Output Denotes the reciprocal of the standard deviation after the normalization calculation, corresponding to `rstdOut` in the corresponding formula.
    • Supports null tensors.
    • The data type is the same as that of self.
    • The shape is (N, group).
    FLOAT32, FLOAT16, BFLOAT16 ND 2 √
    workspaceSize (uint64_t*) Output Returns the size of the workspace that the user needs to allocate on the Device. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which contains 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 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 If a parameter is a required input, output, or required attribute, and is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data types of self, gamma, beta, out, meanOut, or rstdOut are not within the supported range.
    The data types of gamma, beta, out, meanOut, or rstdOut are not the same as that of self.
    The number of dimensions 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 is not the same as that of x.
    The shape of meanOut and rstdOut is not equal to (N, group).
    The spatial size of self on the N dimension is not equal to N.
    The spatial size of self on the C dimension is not equal to C.
    The product of the sizes of the third and subsequent dimensions of self is not equal to HxW (if 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 the number of elements is not equal to C.
    beta is not 1-dimensional and the number of elements is not equal to C.
    The formats of self and out are not the same.

aclnnGroupNorm

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address allocated on the Device.
    workspaceSize Input Workspace size allocated on the Device, obtained by calling the first-phase API aclnnGroupNormGetWorkspaceSize.
    executor Input Executor of the op, which contains the calculation process of the operator.
    stream Input Stream for executing the task.
  • Return Value

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

Constraints

  • Deterministic computation:
    • aclnnGroupNorm defaults to a deterministic implementation.

Example

The sample code below is for reference only. For the compilation and execution process, 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 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 allocate memory on the device.
    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 to the device 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);

    // Compute 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 documentation.
    // Set deviceId based on the actual device.
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = Init(deviceId, &stream);
    // Handle check as needed.
    CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
    // 2. Construct inputs and outputs as required by the API.
    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. Change it to the specific API.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the aclnnGroupNorm first-phase API.
    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);
    // 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 aclnnGroupNorm second-phase API.
    ret = aclnnGroupNorm(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGroupNorm 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 values and copy the results from device-side memory to the host side. Modify them 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;
}