aclnnAmpUpdateScale

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: Not supported

Function

  • Description: Implements the dynamic Scale update logic in AMP (Automatic Mixed Precision) training. Dynamically adjusts the loss scale size based on the current scale value, the growth tracker counter, and whether Inf/NaN is found.

  • Formula:

    updated_scale={current_scale×backoff_factorif found_inf≠0current_scale×growth_factorif growth_tracker + 1 = growth_interval and new_scale is finitecurrent_scaleotherwise\text{updated\_scale} = \begin{cases} \text{current\_scale} \times \text{backoff\_factor} & \text{if found\_inf} \neq 0 \\ \text{current\_scale} \times \text{growth\_factor} & \text{if growth\_tracker + 1 = growth\_interval and new\_scale is finite} \\ \text{current\_scale} & \text{otherwise} \end{cases} updated_growth_tracker={0if found_inf≠0 or growth triggeredgrowth_tracker+1otherwise\text{updated\_growth\_tracker} = \begin{cases} 0 & \text{if found\_inf} \neq 0 \text{ or growth triggered} \\ \text{growth\_tracker} + 1 & \text{otherwise} \end{cases}

    NOTE:

    • If found_inf is not 0, the scale is multiplied by backoff_factor to decrease, and growth_tracker is reset to 0
    • If found_inf is 0 and growth_tracker + 1 equals growth_interval, the scale is multiplied by growth_factor to increase
    • If the increased new_scale overflows (inf/nan), the current scale remains unchanged, and growth_tracker is reset to 0
    • In other cases, the scale remains unchanged, and growth_tracker increments by 1
  • Use case: dynamic loss scaling (Dynamic Loss Scaling) in AMP training, to prevent gradient underflow in FP16/BF16 mixed-precision training.

Function Prototype

Each operator uses a two-phase API. You must first call the "aclnnAmpUpdateScaleGetWorkspaceSize" API to obtain the workspace size required for computation and an executor containing the operator computation process, and then call the "aclnnAmpUpdateScale" API to perform the computation.

aclnnStatus aclnnAmpUpdateScaleGetWorkspaceSize(
  const aclTensor* currentScale,
  const aclTensor* growthTracker,
  const aclTensor* foundInf,
  double           growthFactor,
  double           backoffFactor,
  int64_t          growthInterval,
  const aclTensor* updatedScale,
  const aclTensor* updatedGrowthTracker,
  uint64_t*        workspaceSize,
  aclOpExecutor**  executor)
aclnnStatus aclnnAmpUpdateScale(
  void*            workspace,
  uint64_t         workspaceSize,
  aclOpExecutor*   executor,
  aclrtStream      stream)

aclnnAmpUpdateScaleGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    currentScale (aclTensor*) Input Current loss scale value. The shape is a scalar [1]. FLOAT, FLOAT16, BFLOAT16 ND 1 ×
    growthTracker (aclTensor*) Input Counter of consecutive steps without Inf/NaN. The shape is a scalar [1]. INT32 ND 1 ×
    foundInf (aclTensor*) Input Indicates whether Inf/NaN is detected. The shape is a scalar [1]. 0 indicates normal, and a non-zero value indicates that Inf/NaN is detected. The data type must be the same as currentScale. FLOAT, FLOAT16, BFLOAT16 ND 1 ×
    growthFactor (float) Input Scale growth factor. When no Inf/NaN is detected for consecutive growth_interval steps, the scale is multiplied by this factor. Typically set to 2.0. - - - -
    backoffFactor (float) Input Scale backoff factor. When Inf/NaN is detected, the scale is multiplied by this factor. Typically set to 0.5. - - - -
    growthInterval (int64_t) Input Interval in steps for triggering scale growth. That is, the scale increases after the specified number of consecutive steps in which no Inf/NaN is detected. Value range: >= 1. - - - -
    updatedScale (aclTensor*) Output Updated loss scale value. Shape is [1]. The data type must be the same as the data type of currentScale. FLOAT, FLOAT16, BFLOAT16 ND 1 ×
    updatedGrowthTracker (aclTensor*) Output Updated growth tracker counter. Shape is [1]. INT32 ND 1 ×
    workspaceSize (uint64_t*) Output Returns the workspace size to be allocated on the device. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor containing the operator computation flow. - - - - -
  • Return value

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

    The first-phase API performs input parameter validation and returns an error in the following scenarios:

    Return Value Error Code Description
    ACLNN_ERR_INNER_TILING_ERROR 561002 The shape of input currentScale, growthTracker, or foundInf is not a scalar [1].
    growthInterval exceeds the value range [1, 2147483647].
    ACLNN_ERR_PARAM_NULLPTR 161001 The input currentScale, growthTracker, foundInf, updatedScale, or updatedGrowthTracker is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of currentScale is not in the supported range.
    The data type of foundInf is inconsistent with currentScale.
    The data type of updatedScale is inconsistent with currentScale.
    The data type of growthTracker is not INT32.

aclnnAmpUpdateScale

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address requested on the device.
    workspaceSize Input Workspace size requested on the device, obtained by the first-phase API aclnnAmpUpdateScaleGetWorkspaceSize.
    executor Input Op executor, which contains the operator computation process.
    stream Input Stream for task execution.
  • Return value

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

Constraints

  • Deterministic computation:

    • aclnnAmpUpdateScale defaults to a deterministic implementation.
  • Data type constraint: The data type of current_scale must be the same as that of found_inf; the data type of updated_scale must be the same as that of current_scale.

  • Shape constraint: All input and output tensors are scalars, with shape [1].

  • growthInterval constraint: The value range of growthInterval is [1, 2147483647].

  • Inf/NaN priority: If found_inf is not 0, the fallback logic is executed directly, ignoring the status of growth_tracker.

  • Overflow protection: If the new value of scale overflows (inf/nan), the current scale remains unchanged and growth_tracker is reset to 0.

Example

The following 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_amp_update_scale.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 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 host data to 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);

  // 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 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 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);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);

  // 2. Construct input and output. Custom construction is required based on the API.
  std::vector<int64_t> scalarShape = {1};
  void* currentScaleDeviceAddr = nullptr;
  void* growthTrackerDeviceAddr = nullptr;
  void* foundInfDeviceAddr = nullptr;
  void* updatedScaleDeviceAddr = nullptr;
  void* updatedGrowthTrackerDeviceAddr = nullptr;
  aclTensor* currentScale = nullptr;
  aclTensor* growthTracker = nullptr;
  aclTensor* foundInf = nullptr;
  aclTensor* updatedScale = nullptr;
  aclTensor* updatedGrowthTracker = nullptr;

  // Create currentScale.
  std::vector<float> currentScaleHost = {65536.0f};
  ret = CreateAclTensor(currentScaleHost, scalarShape, ¤tScaleDeviceAddr, ACL_FLOAT, ¤tScale);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // Create growthTracker.
  std::vector<int32_t> growthTrackerHost = {900};
  ret = CreateAclTensor(growthTrackerHost, scalarShape, &growthTrackerDeviceAddr, ACL_INT32, &growthTracker);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // Create foundInf.
  std::vector<float> foundInfHost = {0.0f};
  ret = CreateAclTensor(foundInfHost, scalarShape, &foundInfDeviceAddr, ACL_FLOAT, &foundInf);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // Create the output updatedScale.
  std::vector<float> updatedScaleHost = {0.0f};
  ret = CreateAclTensor(updatedScaleHost, scalarShape, &updatedScaleDeviceAddr, ACL_FLOAT, &updatedScale);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // Create the output updatedGrowthTracker.
  std::vector<int32_t> updatedGrowthTrackerHost = {0};
  ret = CreateAclTensor(updatedGrowthTrackerHost, scalarShape, &updatedGrowthTrackerDeviceAddr, ACL_INT32,
                        &updatedGrowthTracker);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // 3. Call the first-phase API to obtain the workspace size and executor.
  float growthFactor = 2.0f;
  float backoffFactor = 0.5f;
  int64_t growthInterval = 1000;

  uint64_t workspaceSize = 0;
  aclOpExecutor* executor = nullptr;
  ret = aclnnAmpUpdateScaleGetWorkspaceSize(currentScale, growthTracker, foundInf, growthFactor, backoffFactor,
                                            growthInterval, updatedScale, updatedGrowthTracker, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnAmpUpdateScaleGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);

  // 4. Allocate workspace memory based on workspaceSize.
  void* workspace = nullptr;
  if (workspaceSize > 0) {
    ret = aclrtMalloc(&workspace, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
  }

  // 5. Call the second-phase API to execute the computation.
  ret = aclnnAmpUpdateScale(workspace, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnAmpUpdateScale failed. ERROR: %d\n", ret); return ret);

  // 6. 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);

  // 7. Copy the output data from device to host and print the result.
  float updatedScaleVal = 0.0f;
  int32_t updatedGrowthTrackerVal = 0;
  ret = aclrtMemcpy(&updatedScaleVal, sizeof(float), updatedScaleDeviceAddr, sizeof(float),
                    ACL_MEMCPY_DEVICE_TO_HOST);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy updatedScale failed. ERROR: %d\n", ret); return ret);
  ret = aclrtMemcpy(&updatedGrowthTrackerVal, sizeof(int32_t), updatedGrowthTrackerDeviceAddr, sizeof(int32_t),
                    ACL_MEMCPY_DEVICE_TO_HOST);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy updatedGrowthTracker failed. ERROR: %d\n", ret); return ret);
  LOG_PRINT("aclnnAmpUpdateScale result: updatedScale = %f, updatedGrowthTracker = %d\n", updatedScaleVal,
            updatedGrowthTrackerVal);

  // 8. (boilerplate) Release resources.
  aclDestroyTensor(currentScale);
  aclDestroyTensor(growthTracker);
  aclDestroyTensor(foundInf);
  aclDestroyTensor(updatedScale);
  aclDestroyTensor(updatedGrowthTracker);
  aclrtFree(currentScaleDeviceAddr);
  aclrtFree(growthTrackerDeviceAddr);
  aclrtFree(foundInfDeviceAddr);
  aclrtFree(updatedScaleDeviceAddr);
  aclrtFree(updatedGrowthTrackerDeviceAddr);
  if (workspaceSize > 0) {
    aclrtFree(workspace);
  }
  aclrtDestroyStream(stream);
  auto aclRet = aclrtResetDevice(deviceId);
  CHECK_RET(aclRet == ACL_SUCCESS, LOG_PRINT("reset device failed. ERROR: %d\n", aclRet); return aclRet);
  aclRet = aclFinalize();
  CHECK_RET(aclRet == ACL_SUCCESS, LOG_PRINT("finalize acl failed. ERROR: %d\n", aclRet); return aclRet);
  return 0;
}