aclnnTril&aclnnInplaceTril

📄 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: Zeros out the upper-right portion of the last two dimensions (counted from left to right by shape) of the input self Tensor along the diagonal. The diagonal parameter can be positive or negative, and defaults to zero. A positive value shifts the main diagonal toward the upper-right direction, and a negative value shifts it toward the lower-left direction.

  • Formula: In the following, i denotes the index for iterating over the second-to-last dimension (i is the row index), j denotes the index for iterating over the last dimension (j is the column index), and d denotes diagonal. In the 2D coordinate plot corresponding to (i, j), i+d==j indicates that the element lies on the diagonal.

    Onandtothelower−leftofthediagonal,i.e.,i+d>=j,retaintheoriginalvalue:outi,j=selfi,jTotheupper−rightofthediagonal,i.e.,i+d<j,settozero(excludingthediagonal):outi,j=0On and to the lower-left of the diagonal, i.e., i+d>=j, retain the original value: out_{i, j} = self_{i, j}\\ To the upper-right of the diagonal, i.e., i+d<j, set to zero (excluding the diagonal): out_{i, j} = 0
  • Example:

    self=[[963][123][341]]self = \begin{bmatrix} [9&6&3] \\ [1&2&3] \\ [3&4&1] \end{bmatrix}, The result of tril(self, diagonal=0) is: [[900][120][341]]\begin{bmatrix} [9&0&0] \\ [1&2&0] \\ [3&4&1] \end{bmatrix}; With diagonal set to 1, the result of tril(self, diagonal=1) is: [[960][123][341]]\begin{bmatrix} [9&6&0] \\ [1&2&3] \\ [3&4&1] \end{bmatrix}; With diagonal set to -1, the result of tril(self, diagonal=-1) is: [[000][100][340]]\begin{bmatrix} [0&0&0] \\ [1&0&0] \\ [3&4&0] \end{bmatrix}.

Function Prototype

  • aclnnTril and aclnnInplaceTril implement the same function. The differences in usage are as follows. Select the appropriate operator based on your actual scenario.
    • aclnnTril: Create a new output tensor object to store the computation result.
    • aclnnInplaceTril: 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 "aclnnTrilGetWorkspaceSize" or "aclnnInplaceTrilGetWorkspaceSize" to obtain the input parameters and calculate the required workspace size based on the computation process, and then call "aclnnTril" or "aclnnInplaceTril" to perform the computation.
aclnnStatus aclnnTrilGetWorkspaceSize(
  const aclTensor* self,
  int64_t          diagonal,
  aclTensor*       out,
  uint64_t*        workspaceSize,
  aclOpExecutor**  executor)
aclnnStatus aclnnTril(
  void*             workspace,
  uint64_t          workspaceSize,
  aclOpExecutor*    executor,
  const aclrtStream stream)
aclnnStatus aclnnInplaceTrilGetWorkspaceSize(
  const aclTensor* selfRef,
  int64_t          diagonal,
  uint64_t*        workspaceSize,
  aclOpExecutor**  executor)
aclnnStatus aclnnInplaceTril(
  void*             workspace,
  uint64_t          workspaceSize,
  aclOpExecutor*    executor,
  const aclrtStream stream)

aclnnTrilGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    self (aclTensor*) Input Target tensor to be converted, that is, self in the formula. - DOUBLE, FLOAT, FLOAT16, INT16, INT32, INT64, INT8, UINT16, UINT32, UINT64, UINT8, BOOL, BFLOAT16, COMPLEX32, COMPLEX64 ND 2-8 √
    diagonal (int64_t) Input Position of the diagonal. - int64_t - - -
    out (aclTensor*) Input Output tensor. - DOUBLE, FLOAT, FLOAT16, INT16, INT32, INT64, INT8, UINT16, UINT32, UINT64, UINT8, BOOL, BFLOAT16, COMPLEX32, COMPLEX64 - 2-8 -
    workspaceSize (uint64_t*) output parameter Returns the workspace size to be allocated on the device. - - - - -
    executor (aclOpExecutor**) output parameter Returns the op executor, which contains the operator computation process. - - - - -
    • Ascend 950PR&950DT products: COMPLEX32 and COMPLEX64 are supported only by this product.
    • Atlas inference products and Atlas training products: The BFLOAT16 data type is not supported.
  • Return Value

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

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

    Return Value Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 The self or out pointer is null.
    ACLNN_ERR_PARAM_INVALID 161002 The data types of self and out are not in the supported range.
    The data types of self and out are inconsistent.
    The shapes of self and out are inconsistent.
    The shapes of self and out are inconsistent.
    The data formats of self and out are inconsistent.
    The dimension of self is greater than 8 or less than 2.

aclnnTril

  • Parameters

    Parameter Input/Output Description
    workspace Input The workspace memory address allocated on the Device side.
    workspaceSize Input The workspace size allocated on the Device side, obtained by calling the first-phase API aclnnTrilGetWorkspaceSize.
    executor Input op executor that contains the operator computation flow.
    stream Input Stream for executing the task.
  • Return Value

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

aclnnInplaceTrilGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Shape Non-contiguous Tensor
    selfRef (aclTensor*) Input Indicates the tensor to be converted, self in the formula. - DOUBLE, FLOAT, FLOAT16, INT16, INT32, INT64, INT8, UINT16, UINT32, UINT64, UINT8, BOOL, BFLOAT16, COMPLEX32, COMPLEX64 ND 2-8 √
    diagonal (int64_t) Input Position of the diagonal. - int64 - - -
    workspaceSize (uint64_t*) output parameter Returns the workspace size to be allocated on the Device. - - - - -
    executor (aclOpExecutor**) output parameter Returns the op executor, which contains the operator computation process. - - - - -
    • Ascend 950PR&950DT products: COMPLEX32 and COMPLEX64 are supported only on this product.
    • Atlas inference products and Atlas training products: The BFLOAT16 data type is not supported.
  • Return Value

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

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

    Return Value Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 The selfRef pointer is null.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of selfRef is out of the supported range.
    The dimension of self is greater than 8, or less than 2 and not 0.

aclnnInplaceTril

  • 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 aclnnInplaceTrilGetWorkspaceSize.
    executor Input Executor of the op, containing the operator computation flow.
    stream Input Stream that executes the task.
  • Return Value

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

Constraints

  • Deterministic computation:
    • aclnnTril&aclnnInplaceTril 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.

#include "acl/acl.h"
#include "aclnnop/aclnn_tril.h"
#include <iostream>
#include <vector>

#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 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 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 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. 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);
    // Handle the check as required.
    CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
    // 2. Construct the input and output based on the API definition.
    std::vector<int64_t> selfShape = {3, 3};
    std::vector<int64_t> outShape = {3, 3};

    void* selfDeviceAddr = nullptr;
    void* outDeviceAddr = nullptr;
    aclTensor* self = nullptr;
    aclTensor* out = nullptr;

    std::vector<int> selfHostData = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    std::vector<int> outHostData ={1, 2, 3, 4, 5, 6, 7, 8, 9};
    int diagonal = 0;

    // Create the self aclTensor.
    ret = CreateAclTensor(selfHostData, selfShape, &selfDeviceAddr, aclDataType::ACL_INT32, &self);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the out aclTensor.
    ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_INT32, &out);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // 3. Call the CANN operator library API, which needs to be changed to the specific API.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the aclnnTril first-phase API.
    ret = aclnnTrilGetWorkspaceSize(self, diagonal, out, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnTrilGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
    // Allocate 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 aclnnTril second-phase API.
    ret = aclnnTril(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnTril failed. ERROR: %d\n", ret); return ret);

    uint64_t inplaceWorkspaceSize = 0;
    aclOpExecutor* inplaceExecutor;
    // Call the aclnnInplaceTril first-phase API.
    ret = aclnnInplaceTrilGetWorkspaceSize(self, diagonal, &inplaceWorkspaceSize, &inplaceExecutor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnInplaceTrilGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
    // Allocate device memory based on the workspaceSize computed by the first-phase API.
    void* inplaceWorkspaceAddr = nullptr;
    if (inplaceWorkspaceSize > 0) {
    ret = aclrtMalloc(&inplaceWorkspaceAddr, inplaceWorkspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret;);
    }
    // Call the aclnnInplaceTril second-phase API.
    ret = aclnnInplaceTril(inplaceWorkspaceAddr, inplaceWorkspaceSize, inplaceExecutor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnInplaceTril 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 value, copy the result in the device memory to the host memory, and modify it based on the definition of the specific API.
    auto size = GetShapeSize(outShape);
    std::vector<int> resultData(size, 0);
    ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), outDeviceAddr, size * sizeof(int),
                      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: %d\n", i, resultData[i]);
    }

    auto inplaceSize = GetShapeSize(selfShape);
    std::vector<int> inplaceResultData(inplaceSize, 0);
    ret = aclrtMemcpy(inplaceResultData.data(), inplaceResultData.size() * sizeof(inplaceResultData[0]), selfDeviceAddr,
                      inplaceSize * sizeof(int), 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 < inplaceSize; i++) {
      LOG_PRINT("inplaceResult[%ld] is: %d\n", i, inplaceResultData[i]);
    }

    // 6. Release the aclTensor and aclScalar, and modify it based on the definition of the specific API.
    aclDestroyTensor(self);
    aclDestroyTensor(out);

    // 7. Release device resources. Modify as required by the specific API definition.
    aclrtFree(selfDeviceAddr);
    aclrtFree(outDeviceAddr);
    if (workspaceSize > 0) {
      aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return 0;
}