aclnnRenorm&aclnnInplaceRenorm

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

Function

  • Description: Returns a tensor where each sub-tensor of the input tensor self along the dimension dim is normalized so that the p-norm of the sub-tensor is below the maxNorm value.

  • Formula:

    outputi={inputi,∣∣inputi∣∣p≤maxNorminputimax(∣∣inputi∣∣p,eps)⋅maxNorm,∣∣inputi∣∣p>maxNormoutput_i=\left\{ \begin{aligned} input_i,\quad ||input_i||_p ≤ maxNorm \\ \frac {input_i} {max(||input_i||_p, eps)} \cdot maxNorm,\quad ||input_i||_p>maxNorm \end{aligned} \right.

    Where: ii is a tensor slice along a dimension determined by dim:

    ∣∣inputi∣∣p={reduce_sum(∣inputi∣p,dim)p,(p>0)&(p≠inf)max(∣inputi∣),p=inf||input_i||_p =\left\{ \begin{aligned} \sqrt[p]{reduce\_sum(|input_i|^p, dim)},\quad (p > 0) \& (p ≠ inf) \\ max(|input_i|),\quad p = inf \end{aligned} \right.
  • Example:

    x = tensor([[1.,1.,1.],
                [2.,2.,2.],
                [3.,3.,3.]])
    Here, p=1, dim=0, and maxNorm=5, which are passed to the aclnn API for the call.
    Since dim=0, the judgment and calculation are performed in units of rows (the 0th dimension);
    - The norm of the sub-tensor in the first row is 1+1+1=3, which is less than 5. Therefore, the sub-tensor remains unchanged.
    - The norm of the sub-tensor in the second row is 2+2+2=6, which is greater than 5. Therefore, the sub-tensor is calculated, and the result is (2/6)*5=1.6667.
    - The norm of the sub-tensor in the third row is 3+3+3=9, which is greater than 5. Therefore, the sub-tensor is calculated, and the result is (3/9)*5=1.6667.
      tensor([[1.0000,1.0000,1.0000],
             [1.6667,1.6667,1.6667],
             [1.6667,1.6667,1.6667]])
    If p=2, the norm calculation for the sub-tensor in the first row changes to √1+1+1=1.73. Similarly, the second and third rows become:
    √2 * 2+2 * 2+2 * 2=3.46, √3 * 3+3 * 3+3 * 3=5.19

Function Prototype

  • aclnnRenorm and aclnnInplaceRenorm implement the same function. The differences in usage are as follows. Select the appropriate operator based on your actual scenario.

    • aclnnRenorm: Create a new output tensor object to store the computation result.
    • aclnnInplaceRenorm: No need to create a new output tensor object. The computation result is stored directly in the memory of the input tensor.
  • Each operator uses a two-phase API. First call "aclnnRenormGetWorkspaceSize" or "aclnnInplaceRenormGetWorkspaceSize" to obtain the workspace size required for the computation and the executor that contains the operator computation process. Then call "aclnnRenorm" or "aclnnInplaceRenorm" to perform the computation.

    aclnnStatus aclnnRenormGetWorkspaceSize(
      const aclTensor* self,
      const aclScalar* p,
      int64_t          dim,
      const aclScalar* maxNorm,
      aclTensor*       out,
      uint64_t*        workspaceSize,
      aclOpExecutor**  executor)
    aclnnStatus aclnnRenorm(
      void*          workspace,
      uint64_t       workspaceSize,
      aclOpExecutor* executor,
      aclrtStream    stream)
    aclnnStatus aclnnInplaceRenormGetWorkspaceSize(
      aclTensor*       selfRef,
      const aclScalar* p,
      int64_t          dim,
      const aclScalar* maxNorm,
      uint64_t*        workspaceSize,
      aclOpExecutor**  executor)
    aclnnStatus aclnnInplaceRenorm(
      void*          workspace,
      uint64_t       workspaceSize,
      aclOpExecutor* executor,
      aclrtStream    stream)

aclnnRenormGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    self (aclTensor*) Input Input for renormalization computation, corresponding to `input` in the Formula. Supports empty Tensor. FLOAT32, FLOAT16, BFLOAT16 ND 2-8 √
    p (aclScalar*) Input Norm, corresponding to `p` in the Formula. Value greater than or equal to 0. FLOAT32 - - -
    dim (int64_t) Input Indicates the dimension along which the norm is computed. Corresponds to `i` in the formula. Value range: [-number of dimensions of self, number of dimensions of self-1]. - - - -
    maxNorm (aclScalar*) Input Represents the maximum allowed normalized value. Corresponds to `maxNorm` in the corresponding formula.
    • The value is greater than or equal to 0.
    • If during the operation the `p`-norm of the corresponding dimension (determined by the value of `p`) is greater than `maxNorm`, the values of that dimension are normalized with respect to the `p`-norm and multiplied by `maxNorm`.
    • If during the operation the `p`-norm of the corresponding dimension (determined by the value of `p`) is less than `maxNorm`, the tensor of that dimension is output unchanged.
    FLOAT32 - - -
    out (aclTensor*) Output Represents the final output, corresponding to `output` in the formula.
    • Supports empty tensors.
    • The data type and shape are the same as those of input parameter `self`.
    FLOAT32, FLOAT16, BFLOAT16 ND 2-8 √
    workspaceSize (uint64_t*) Output Returns the workspace size that needs to be applied on the Device side. - - - - -
    executor(aclOpExecutor**) Output Returns the op executor, which contains the operator computation process. - - - - -
    • Atlas training products: The data type of parameters self and out does not support BFLOAT16.
  • Return Value

    aclnnStatus: return status code. See specifically 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, p, maxNorm, or out is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of self or out is not within the supported range.
    The shapes of self and out are inconsistent.
    The dtypes of self and out are inconsistent.
    The value of p does not meet the requirement.
    The value of dim is not within the range [-number of dimensions of self, number of dimensions of self - 1].
    maxNorm < 0.
    When the number of dimensions of the input self is not within the range [2,8].

aclnnRenorm

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address applied on the Device side.
    workspaceSize Input Size of the workspace applied on the Device side, obtained by the first-phase API aclnnRenormGetWorkspaceSize.
    executor Input Executor of the op, containing the operator computation flow.
    stream Input Stream for executing the task.
  • Return Value

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

aclnnInplaceRenormGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    selfRef (aclTensor*) Input/Output Input and final output of the renormalization computation, corresponding to `input` and `output` in the Formula. Supports empty tensors. FLOAT32, FLOAT16, BFLOAT16 ND 2-8 √
    p (aclScalar*) Input Norm, corresponding to `p` in the Formula. Value greater than or equal to 0. FLOAT32 - - -
    dim (int64_t) Input Indicates the dimension along which the norm is computed. Corresponds to `i` in the Formula. Value range: [-number of dimensions of selfRef, number of dimensions of selfRef-1]. - - - -
    maxNorm (aclScalar*) Input Indicates the maximum allowed normalization value. Corresponds to `maxNorm` in the formula.
    • Value greater than or equal to 0.
    • If the operation is performed and the `p` norm (the value is determined by `p`) of the corresponding dimension at that time is greater than `maxNorm`, the values in this dimension are normalized with respect to the `p` norm and multiplied by `maxNorm`.
    • If the operation is performed and the `p` norm (the value is determined by `p`) of the corresponding dimension at that time is less than `maxNorm`, the tensor of this dimension is output unchanged.
    FLOAT32 - - -
    workspaceSize (uint64_t*) Output Returns the size of the workspace that needs to be applied on the Device side. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor that contains the operator computation process. - - - - -
    • Atlas training products: The data type of parameter selfRef does not support BFLOAT16.
  • Return Value

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

    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 selfRef, p, and maxNorm are null pointers.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of selfRef is not within the supported range.
    p < 0.
    The value of dim is not within the range [-number of dimensions of selfRef, number of dimensions of selfRef - 1].
    maxNorm < 0.
    The number of dimensions of input selfRef is not within the range [2,8].

aclnnInplaceRenorm

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address applied on the side of the Device.
    workspaceSize Input Workspace size applied on the side of the Device, obtained by the first-phase API aclnnInplaceRenormGetWorkspaceSize.
    executor Input Executor of the op, containing the operator computation flow.
    stream Input Stream for task execution.
  • Return Value

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

Constraints

  • Deterministic computation:
    • aclnnRenorm defaults to a deterministic implementation.
    • aclnnInplaceRenorm defaults to a deterministic implementation.
  • If input parameter p is 0, see "Formula" in aclnnEmbeddingRenorm for the formula.

Example

The following example code is for reference only. For details about compilation and execution, see Compile and Run Samples.

  • aclnnRenorm sample code:

    #include <iostream>
    #include <vector>
    #include "acl/acl.h"
    #include "aclnnop/aclnn_renorm.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 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 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) Device/stream initialization. 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);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
    
        // 2. Construct the input and output. The construction must be customized based on the API.
        std::vector<int64_t> selfShape = {3, 3};
        std::vector<int64_t> outShape = {3, 3};
        void* selfDeviceAddr = nullptr;
        void* outDeviceAddr = nullptr;
        aclTensor* self = nullptr;
        aclScalar* p = nullptr;
        aclScalar* maxNorm = nullptr;
        aclTensor* out = nullptr;
        std::vector<float> selfHostData = {1, 1, 1, 2, 2, 2, 3, 3, 3};
        std::vector<float> outHostData(9, 0);
        int64_t dim = -1;
        float pValue = 1.0f;
        float maxNormValue = 5.0f;
        // Create the self aclTensor.
        ret = CreateAclTensor(selfHostData, selfShape, &selfDeviceAddr, aclDataType::ACL_FLOAT, &self);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        // Create the p aclScalar.
        p = aclCreateScalar(&pValue, aclDataType::ACL_FLOAT);
        CHECK_RET(p != nullptr, return ret);
        // Create the maxNorm aclScalar.
        maxNorm = aclCreateScalar(&maxNormValue, aclDataType::ACL_FLOAT);
        CHECK_RET(maxNorm != nullptr, return ret);
        // Create the out aclTensor.
        ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT, &out);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
    
        // 3. Call the CANN operator library API. Change it to the specific API name.
        uint64_t workspaceSize = 0;
        aclOpExecutor* executor;
        // Call the first-phase API of aclnnRenorm.
        ret = aclnnRenormGetWorkspaceSize(self, p, dim, maxNorm, out, &workspaceSize, &executor);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnRenormGetWorkspaceSize 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 aclnnRenorm.
        ret = aclnnRenorm(workspaceAddr, workspaceSize, executor, stream);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnRenorm 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. Get the output value and copy the result from the device side to the host side. Modify it 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 it based on the specific API definition.
        aclDestroyTensor(self);
        aclDestroyScalar(p);
        aclDestroyScalar(maxNorm);
        aclDestroyTensor(out);
        return 0;
    }
  • Sample code for aclnnInplaceRenorm:

    #include <iostream>
    #include <vector>
    #include "acl/acl.h"
    #include "aclnnop/aclnn_renorm.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 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 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 the 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);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
    
        // 2. Construct the input and output as required by the API.
        std::vector<int64_t> selfRefShape = {3, 3};
        void* selfRefDeviceAddr = nullptr;
        aclTensor* selfRef = nullptr;
        aclScalar* p = nullptr;
        aclScalar* maxNorm = nullptr;
        aclTensor* out = nullptr;
        std::vector<float> selfRefHostData = {1, 1, 1, 2, 2, 2, 3, 3, 3};
        int64_t dim = -1;
        float pValue = 1.0f;
        float maxNormValue = 5.0f;
        // Create the selfRef aclTensor.
        ret = CreateAclTensor(selfRefHostData, selfRefShape, &selfRefDeviceAddr, aclDataType::ACL_FLOAT, &selfRef);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        // Create the p aclScalar.
        p = aclCreateScalar(&pValue, aclDataType::ACL_FLOAT);
        CHECK_RET(p != nullptr, return ret);
        // Create the maxNorm aclScalar.
        maxNorm = aclCreateScalar(&maxNormValue, aclDataType::ACL_FLOAT);
        CHECK_RET(maxNorm != nullptr, return ret);
    
        // 3. Call the CANN operator library API. Replace it with the specific API name.
        uint64_t workspaceSize = 0;
        aclOpExecutor* executor;
        // Call the first-phase API aclnnInplaceRenorm
        ret = aclnnInplaceRenormGetWorkspaceSize(selfRef, p, dim, maxNorm, &workspaceSize, &executor);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnInplaceRenormGetWorkspaceSize 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 aclnnInplaceRenorm
        ret = aclnnInplaceRenorm(workspaceAddr, workspaceSize, executor, stream);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnInplaceRenorm 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 the device side to the host side. Modify the code according to the specific API definition
        auto size = GetShapeSize(selfRefShape);
        std::vector<float> resultData(size, 0);
        ret = aclrtMemcpy(
            resultData.data(), resultData.size() * sizeof(resultData[0]), selfRefDeviceAddr, 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 according to the specific API definition
        aclDestroyTensor(selfRef);
        aclDestroyScalar(p);
        aclDestroyScalar(maxNorm);
    
        // 7. Release device resources. Modify the code according to the specific API definition
        aclrtFree(selfRefDeviceAddr);
        if (workspaceSize > 0) {
            aclrtFree(workspaceAddr);
        }
        aclrtDestroyStream(stream);
        aclrtResetDevice(deviceId);
        aclFinalize();
        return 0;
    }