aclnnRenorm&aclnnInplaceRenorm

📄 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: 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<=maxNorminputi∣∣inputi∣∣p⋅maxNorm,∣∣inputi∣∣p>maxNormoutput_i=\left\{ \begin{aligned} input_i,\quad ||input_i||_p <= maxNorm \\ \frac {input_i} {||input_i||_p} \cdot maxNorm,\quad ||input_i||_p>maxNorm \end{aligned} \right.

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

    ∣∣inputi∣∣p=(∑i=0ninputip1p)||input_i||_p = (\sum_{i=0}^{n}{input_i^p}^\frac{1}{p})
  • Example:

    x = tensor([[1.,1.,1.],
                [2.,2.,2.],
                [3.,3.,3.]])
    Here, p=1, dim=0, maxNorm=5, passed to the aclnn interface call.
    Because dim=0, the judgment and calculation are performed row by row (along dimension 0);
    - The norm of the first-row subtensor is 1+1+1=3, which is less than 5, so this subtensor remains unchanged.
    - The norm of the second-row subtensor is 2+2+2=6, which is greater than 5, so this subtensor is calculated, (2/6)*5=1.6667.
    - The norm of the third-row subtensor is 3+3+3=9, which is greater than 5, so this subtensor is calculated, (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 of the first-row subtensor is recalculated as √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 is divided into a two-phase API. You must first call the "aclnnRenormGetWorkspaceSize" or "aclnnInplaceRenormGetWorkspaceSize" API to obtain the workspace size required for computation and the executor that contains the operator computation process, and then call the "aclnnRenorm" or "aclnnInplaceRenorm" API to execute 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 Indicates the input for renormalization computation, corresponding to `input` in the formula. Supports null tensor. FLOAT32, FLOAT16, BFLOAT16 ND 2-8 √
    p (aclScalar*) Input Represents the norm, corresponding to `p` in the formula. The value is greater than or equal to 0. FLOAT32 - - -
    dim (int64_t) Input Specifies 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 Indicates the maximum allowed normalization value. Corresponds to `maxNorm` in the formula.
    • The value must be greater than or equal to 0.
    • If the p-norm (determined by the `p` value) of the corresponding dimension during computation is greater than `maxNorm`, the values of that dimension are normalized with respect to the p-norm and multiplied by `maxNorm`.
    • If the p-norm (determined by the `p` value) of the corresponding dimension during computation 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 null tensor.
    • The data type and shape are consistent with the input parameter `self`.
    FLOAT32, FLOAT16, BFLOAT16 ND 2-8 √
    workspaceSize (uint64_t*) Output Returns the workspace size requested by the user on the Device side. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - -
    • Atlas training products: The data type of the self and out parameters does 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 The passed 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.
    p < 0.
    The value of dim is not within the range of [-number of dimensions of self, number of dimensions of self - 1].
    maxNorm < 0.
    When the dimension of the input self is not within the range [2, 8].

aclnnRenorm

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address requested on the Device side.
    workspaceSize Input Workspace size requested on the Device side, obtained from the first-phase API aclnnRenormGetWorkspaceSize.
    executor Input Operator executor, which contains the operator computation flow.
    stream Input Specifies the computation stream for executing the task.
  • Return Value

    aclnnStatus: return 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 Represents the input and final output of the renormalization computation, corresponding to `input` and `output` in the formula. Supports null Tensor. FLOAT32, FLOAT16, BFLOAT16 ND 2-8 √
    p (aclScalar*) Input Represents the norm, corresponding to `p` in the formula. The value is greater than or equal to 0. FLOAT32 - - -
    dim (int64_t) Input Specifies 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 Represents the maximum allowed normalization value. Corresponds to `maxNorm` in the formula.
    • The value must be greater than or equal to 0.
    • If the `p` norm (determined by the `p` value) of the corresponding dimension during computation is greater than `maxNorm`, the values of that dimension are normalized with respect to the `p` norm and multiplied by `maxNorm`.
    • If the `p` norm (determined by the `p` value) of the corresponding dimension during computation is less than `maxNorm`, the tensor of that dimension remains unchanged in the output.
    FLOAT32 - - -
    workspaceSize (uint64_t*) Output Returns the workspace size requested by the user on the Device side. - - - - -
    executor (aclOpExecutor**) Output Returns the operator executor, which contains the operator computation process. - - - - -
    • Atlas training products: The data type of the parameter selfRef does 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 The passed selfRef, p, or maxNorm is a null pointer.
    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 of [-number of dimensions of selfRef, number of dimensions of selfRef - 1].
    maxNorm < 0.
    When the dimension of the input selfRef is not within the range [2, 8].

aclnnInplaceRenorm

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address requested by the Device side.
    workspaceSize Input Workspace size requested by the Device side, obtained from the first-phase API aclnnInplaceRenormGetWorkspaceSize.
    executor Input Operator executor, which contains the operator computation flow.
    stream Input Specifies the stream for task execution.
  • Return Value

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

Constraints

  • Deterministic computation:

  • aclnnRenorm defaults to a deterministic implementation.

  • aclnnInplaceRenorm 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.

  • 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 request 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 data from the host side 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 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 aclCreateTensor 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.
        // Fill in the deviceId based on your 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. Custom construction is required based on the API interface.
        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. Replace with 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);
        // Apply for device memory based on the workspaceSize computed 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 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 memory. 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);
        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 request 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 data from the host side 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 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);
        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 interface.
        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 with the actual API name.
        uint64_t workspaceSize = 0;
        aclOpExecutor* executor;
        // Call the first-phase API of aclnnInplaceRenorm.
        ret = aclnnInplaceRenormGetWorkspaceSize(selfRef, p, dim, maxNorm, &workspaceSize, &executor);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnInplaceRenormGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
        // Apply for device memory based on the workspaceSize computed 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 aclnnInplaceRenorm.
        ret = aclnnInplaceRenorm(workspaceAddr, workspaceSize, executor, stream);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnRenorm 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 memory. Modify based on 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 based on the specific API definition.
        aclDestroyTensor(selfRef);
        aclDestroyScalar(p);
        aclDestroyScalar(maxNorm);
    
        // 7. Release device resources. Modify based on the specific API definition.
        aclrtFree(selfRefDeviceAddr);
        if (workspaceSize > 0) {
            aclrtFree(workspaceAddr);
        }
        aclrtDestroyStream(stream);
        aclrtResetDevice(deviceId);
        aclFinalize();
        return 0;
    }