aclnnClampMaxTensor&aclnnInplaceClampMaxTensor

📄 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: Clamps all elements of the input to the range [-inf, max].

  • Formula:

    outi=min(selfi,maxi){out}_{i} = min({{self}_{i}},{max}_{i})

Function Prototype

  • aclnnClampMaxTensor and aclnnInplaceClampMaxTensor implement the same function. The differences are as follows. Select the appropriate operator based on your actual scenario.

    • aclnnClampMaxTensor: Creates a new output tensor object to store the computation result.
    • aclnnInplaceClampMaxTensor: Does not require creating a new output tensor object. Stores the computation result directly in the input tensor memory.
  • Each operator uses a two-phase API. Call "aclnnClampMaxTensorGetWorkspaceSize" or "aclnnInplaceClampMaxTensorGetWorkspaceSize" first to obtain the workspace size required for the computation and the executor containing the computation process. Then call "aclnnClampMaxTensor" or "aclnnInplaceClampMaxTensor" to execute the computation.

aclnnStatus aclnnClampMaxTensorGetWorkspaceSize(
    const aclTensor* self,
    const aclTensor* max,
    aclTensor*       out,
    uint64_t*        workspaceSize,
    aclOpExecutor**  executor)

```cpp
aclnnStatus aclnnClampMaxTensor(
    void*          workspace,
    uint64_t       workspaceSize,
    aclOpExecutor* executor,
    aclrtStream    stream)
aclnnStatus aclnnInplaceClampMaxTensorGetWorkspaceSize(
    aclTensor*       selfRef,
    const aclTensor* max,
    uint64_t*        workspaceSize,
    aclOpExecutor**  executor)
aclnnStatus aclnnInplaceClampMaxTensor(
    void*          workspace,
    uint64_t       workspaceSize,
    aclOpExecutor* executor,
    aclrtStream    stream)

aclnnClampMaxTensorGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    self (aclTensor*) Input Input tensor to be clamped, which is selfi in the formula. The shape can be broadcast with that of max, and the data type must satisfy the data type conversion rules (see conversion relationship). FLOAT16, FLOAT, DOUBLE, INT8, UINT8, INT16, INT32, INT64, BFLOAT16 ND 1-8 √
    max (aclTensor*) Input Input tensor specifying the upper bound of self, which is maxi in the formula. The shape can be broadcast with self, and its data type must satisfy the data type conversion rules with the data type of self (see conversion relationship). FLOAT16, FLOAT, DOUBLE, INT8, UINT8, INT16, INT32, INT64, BFLOAT16, BOOL ND 1-8 √
    out (aclTensor*) Output Output tensor, which is outi in the formula. The shape must be the shape after self and max are broadcast, and the data type must be a data type convertible between self and max. FLOAT16, FLOAT, DOUBLE, INT8, UINT8, INT16, INT32, INT64, BFLOAT16 ND 1-8 √
    workspaceSize (uint64_t*) Output Returns the workspace size to allocate on the device. - - - - -
    (aclOpExecutor**) Output Returns the op executor containing the operator computation flow. - - - - -
    • Atlas training products, Atlas inference products:
      • The data types of self and out do not support BOOL or BFLOAT16.
      • The data type of max does not support BFLOAT16.
    • Atlas A2 products, Atlas A3 products: The data types of self and out do not support BOOL.
  • Return Values:

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

    The first-phase API validates input parameters and reports an error in the following use cases:

    Return Values Error Codes Description
    ACLNN_ERR_PARAM_NULLPTR 161001 self or out is a null pointer, or max is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of self, max, or out is out of the supported range.
    The shapes of self and max do not satisfy the broadcast relationship, or the shape after broadcast is inconsistent with the shape of the output out.
    Type inference for self and max fails, or the inferred type cannot be converted to the data type of out.
    The dimension of self, max, or out exceeds 8.

aclnnClampMaxTensor

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address applied for on the Device side.
    workspaceSize Input Workspace memory size applied for on the Device side, obtained through the first-phase API aclnnClampMaxTensorGetWorkspaceSize.
    executor op executor, which contains the operator computation flow. Input
    stream Input Stream used to execute the task.
  • Return Values:

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

aclnnInplaceClampMaxTensorGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    selfRef (aclTensor*) Input/Output Input tensor to be clamped, that is, selfi and outi in the formula. Its shape can be broadcast with that of max, and its data type must comply with the data type conversion rules (see conversion relationship). FLOAT16, FLOAT, DOUBLE, INT8, UINT8, INT16, INT32, INT64, BFLOAT16 ND 1-8 √
    max (aclTensor*) Input Input tensor specifying the upper bound of self, that is, maxi in the formula. Its shape can be broadcast with that of selfRef, and its data type must comply with the data type conversion rules (see conversion relationship). FLOAT16, FLOAT, DOUBLE, INT8, UINT8, INT16, INT32, INT64, BFLOAT16, BOOL ND 1-8 √
    workspaceSize (uint64_t*) Output Returns the workspace size that needs to be applied for on the Device side. - - - - -
    (aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - -
    • Atlas training products, Atlas inference products:
      • The data type of selfRef does not support BOOL or BFLOAT16.
      • The data type of max does not support BFLOAT16.
    • Atlas A2 products, Atlas A3 products, Ascend 950PR&950DT products:
      • The data types of selfRef and max must comply with the data type deduction rules (see TensorScalar deduction relationship).
      • BOOL is not supported for the data type of selfRef.
  • Returns:

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

    The first-phase API performs input parameter validation and reports an error in the following use cases:

    Return Value Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 The input selfRef or max is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data types of selfRef and max are not in the supported range.
    The shapes of selfRef and max do not satisfy the broadcast relationship.
    Type inference of selfRef and max fails.
    The dimension of selfRef or max exceeds 8.
    Type inference of selfRef and max fails, or the inferred data type cannot be converted to the data type of selfRef.

aclnnInplaceClampMaxTensor

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address applied for on the Device side.
    workspaceSize Input Workspace size applied for on the Device side, obtained by the first-phase API aclnnInplaceClampMaxTensorGetWorkspaceSize.
    executor Input Op executor, which contains the operator computation flow.
    stream Input Stream for task execution.
  • Return Values:

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

Constraints

  • Deterministic computation:
    • aclnnClampMaxTensor&aclnnInplaceClampMaxTensor default to a deterministic implementation.

Example

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

aclnnClampMaxTensor example:

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_clamp.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); aclFinalize(); return ret);
  ret = aclrtCreateStream(stream);
  CHECK_RET(ret == ACL_SUCCESS,
            LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret);
            aclrtResetDevice(deviceId); aclFinalize(); 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 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 data 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 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 PrepareInputAndOutput(
    std::vector<int64_t>& selfShape, std::vector<int64_t>& outShape, std::vector<int64_t>& maxShape,
    void** selfDeviceAddr, aclTensor** self, void** maxDeviceAddr, aclTensor** max, void** outDeviceAddr,
    aclTensor** out)
{
  std::vector<double> selfHostData = {0, 1, 2, 3, 4, 5, 6, 7};
  std::vector<double> maxHostData = {1, 1, 1, 2, 2, 2, 3, 3};
  std::vector<double> outHostData(8, 0);

  // Create self aclTensor.
  auto ret = CreateAclTensor(selfHostData, selfShape, selfDeviceAddr, aclDataType::ACL_DOUBLE, self);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create max aclTensor.
  ret = CreateAclTensor(maxHostData, maxShape, maxDeviceAddr, aclDataType::ACL_DOUBLE, max);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create out aclTensor.
  ret = CreateAclTensor(outHostData, outShape, outDeviceAddr, aclDataType::ACL_DOUBLE, out);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  return ACL_SUCCESS;
}

void ReleaseTensorAndScalar(aclTensor* self, aclTensor* max, aclTensor* out)
{
  aclDestroyTensor(self);
  aclDestroyTensor(max);
  aclDestroyTensor(out);
}

void ReleaseDevice(
    void* selfDeviceAddr, void* maxDeviceAddr, void* outDeviceAddr, uint64_t workspaceSize, void* workspaceAddr, aclrtStream stream,
    int32_t deviceId)
{
  aclrtFree(selfDeviceAddr);
  aclrtFree(maxDeviceAddr);
  aclrtFree(outDeviceAddr);
  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();
}

int main() {
  // 1. (Boilerplate) Initialize 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 inputs and outputs. Custom construction needs to be based on the API interface definition.
  std::vector<int64_t> selfShape = {4, 2};
  std::vector<int64_t> maxShape = {4, 2};
  std::vector<int64_t> outShape = {4, 2};
  void* selfDeviceAddr = nullptr;
  void* maxDeviceAddr = nullptr;
  void* outDeviceAddr = nullptr;
  aclTensor* self = nullptr;
  aclTensor* max = nullptr;
  aclTensor* out = nullptr;

  ret = PrepareInputAndOutput(
      selfShape, outShape, maxShape, &selfDeviceAddr, &self, &maxDeviceAddr, &max, &outDeviceAddr, &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 aclnnClampMaxTensor
  ret = aclnnClampMaxTensorGetWorkspaceSize(self, max, out, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnClampMaxTensorGetWorkspaceSize 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 aclnnClampMaxTensor
  ret = aclnnClampMaxTensor(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnClampMaxTensor failed. ERROR: %d\n", ret); return ret);

  // 4. (Boilerplate) 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 result from the device memory to the host side. Change it based on the specific API's interface definition.
  auto size = GetShapeSize(outShape);
  std::vector<double> 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. Change it based on the specific API's interface definition.
  ReleaseTensorAndScalar(self, max, out);

  // 7. Release device resources. Change it based on the specific API's interface definition.
  ReleaseDevice(selfDeviceAddr, maxDeviceAddr, outDeviceAddr, workspaceSize, workspaceAddr, stream, deviceId);

  return 0;
}

aclnnInplaceClampMaxTensor call example:

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_clamp.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); aclFinalize(); return ret);
  ret = aclrtCreateStream(stream);
  CHECK_RET(ret == ACL_SUCCESS,
            LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret);
            aclrtResetDevice(deviceId); aclFinalize(); 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 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 the host data onto 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 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 PrepareInputAndOutput(
    std::vector<int64_t>& selfShape, std::vector<int64_t>& maxShape, void** selfDeviceAddr, aclTensor** self,
    void** maxDeviceAddr, aclTensor** max)
{
  std::vector<double> selfHostData = {0, 1, 2, 3, 4, 5, 6, 7};
  std::vector<double> maxHostData = {1, 1, 1, 2, 2, 2, 3, 3};
  // Create self aclTensor
  auto ret = CreateAclTensor(selfHostData, selfShape, selfDeviceAddr, aclDataType::ACL_DOUBLE, self);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create max aclTensor
  ret = CreateAclTensor(maxHostData, maxShape, maxDeviceAddr, aclDataType::ACL_DOUBLE, max);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  return ACL_SUCCESS;
}

void ReleaseTensorAndScalar(aclTensor* self, aclTensor* max)
{
  aclDestroyTensor(self);
  aclDestroyTensor(max);
}

void ReleaseDevice(
    void* selfDeviceAddr, void* maxDeviceAddr, uint64_t workspaceSize, void* workspaceAddr, aclrtStream stream,
    int32_t deviceId)
{
  aclrtFree(selfDeviceAddr);
  aclrtFree(maxDeviceAddr);
  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();
}

int main() {
  // 1. (Boilerplate) Initialize 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 input and output, which need to be customized based on the API definition.
  std::vector<int64_t> selfShape = {4, 2};
  std::vector<int64_t> maxShape = {4, 2};
  void* selfDeviceAddr = nullptr;
  void* maxDeviceAddr = nullptr;
  aclTensor* self = nullptr;
  aclTensor* max = nullptr;

  ret = PrepareInputAndOutput(selfShape, maxShape, &selfDeviceAddr, &self, &maxDeviceAddr, &max);
  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 aclnnInplaceClampMaxTensor.
  ret = aclnnInplaceClampMaxTensorGetWorkspaceSize(self, max, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnInplaceClampMaxTensorGetWorkspaceSize 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 aclnnInplaceClampMaxTensor.
  ret = aclnnInplaceClampMaxTensor(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnInplaceClampMaxTensor failed. ERROR: %d\n", ret); return ret);

  // 4. (Boilerplate) Synchronize and wait until the task execution is 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 on the device side memory to the host side. It needs to be modified based on the specific API definition.
  auto size = GetShapeSize(selfShape);
  std::vector<double> resultData(size, 0);
  ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), selfDeviceAddr,
                    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. It needs to be modified based on the specific API definition.
  ReleaseTensorAndScalar(self, max);

  // 7. Release device resources. It needs to be modified based on the specific API definition.
  ReleaseDevice(selfDeviceAddr, maxDeviceAddr, workspaceSize, workspaceAddr, stream, deviceId);

  return 0;
}
\`\`\`