aclnnEinsum

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

Function

  • Description: Performs tensor computation using the Einstein summation convention in the form of "term1, term2 -> output-term". The output tensor is generated according to the following equation, where reduce-sum sums over all indices that appear in the input terms (term1, term2) but not in the output term.
  • Formula:output[output−term]=reduce−sum(input1[term1]∗input2[term2])output[output-term] = reduce-sum(input1[term1] * input2[term2])

Function Prototype

Each operator uses a two-phase API. Call "aclnnEinsumGetWorkspaceSize" first to obtain the workspace size required for computation and the executor that contains the operator computation process, and then call "aclnnEinsum" to execute the computation.

aclnnStatus aclnnEinsumGetWorkspaceSize(
  const aclTensorList *tensors,
  const char          *equation,
  aclTensor           *output,
  uint64_t            *workspaceSize,
  aclOpExecutor       **executor)
aclnnStatus aclnnEinsum(
  void            *workspace,
  uint64_t         workspaceSize,
  aclOpExecutor   *executor,
  aclrtStream      stream)

aclnnEinsumGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    tensors Input Contains two tensors, where tensors[0] represents term1 in the formula and tensors[1] represents term2 in the formula. Empty tensors are not supported. FLOAT16, FLOAT, INT16, UINT16, INT32, UINT32, INT64, UINT64 ND - √
    equation Input Represents the shorthand formula of the Einstein summation convention. Currently, only "abcd,abced->abce" and "a,b->ab" are supported. Expression string on the host. - - - -
    Output Output Output tensor. Empty tensors are not supported. FLOAT16, FLOAT, INT16, UINT16, INT32, UINT32, INT64, UINT64 ND - √
    workspaceSize Output Size of the workspace to be requested on the Device. - - - - -
    executor Output Returns the op executor, which contains the operator computation flow. - - - - -
    • Atlas inference products: tensors and output do not support the FLOAT data type.
  • 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 tensors or output is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of tensors or output is not in the supported range.
    equation (extendable) is not in the registry.
    When equation=='abcd,abced->abce':
    • tensors contains 2 Tensors (i.e. tensors[0] & tensors[1]);
    • The data types of tensors[0], tensors[1], and output must be the same;
    • tensors[0] must be 4-dimensional;
    • tensors[1] must be 5-dimensional;
    • The first 3 dimensions of tensors[0] must be the same as those of tensors[1];
    • The 4th dimension of tensors[0] must be the same as the 5th dimension of tensors[1].
    When equation=='a,b->ab':
    • tensorList contains 2 Tensors (i.e. tensors[0] & tensors[1]);
    • The data types of tensors[0], tensors[1], and output must be the same;
    • tensors[0] must be 1-dimensional;
    • tensors[1] must be 1-dimensional.

aclnnEinsum

  • Parameters:

    Parameter Input/Output Description
    workspace Input Address of the workspace memory allocated on the Device.
    workspaceSize Input Size of the workspace memory allocated on the Device, obtained by the first-phase API aclnnEinsumGetWorkspaceSize.
    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 Codes.

Constraints

  • Determinism description: aclnnEinsum defaults to a deterministic implementation.

  • Currently, the equation must match exactly to find the corresponding function.

Example

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

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_einsum.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)

template <typename T>
int64_t GetShapeSize(const std::vector<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, 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) Initialize device/stream. Refer to the acl API documentation.
  // Set deviceId based on the actual device in use.
  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, which need to be customized based on the API.
  std::vector<int64_t> selfShape1 = {1, 2, 3, 4};
  std::vector<int64_t> selfShape2 = {1, 2, 3, 5, 4};
  std::vector<int64_t> outShape = {1, 2, 3, 5};
  void* input1DeviceAddr = nullptr;
  void* input2DeviceAddr = nullptr;
  void* outDeviceAddr = nullptr;
  aclTensor* input1 = nullptr;
  aclTensor* input2 = nullptr;
  aclTensor* out = nullptr;
  std::vector<int32_t> input1HostData = {0, 1, 2, 6, 5, 1, 6, 4, 4, 8, 0, 3, 5, 2, 2, 6, 9, 9, 9, 2, 0, 8, 0, 9};
  std::vector<int32_t> input2HostData = {4, 7, 1, 6, 9, 6, 6, 1, 3, 7, 1, 3, 5, 0, 0, 7, 6, 3, 3, 7, 2, 0, 5, 0,
                                       0, 7, 9, 3, 7, 2, 3, 3, 5, 1, 9, 0, 0, 9, 8, 9, 4, 3, 1, 2, 8, 3, 0, 5,
                                       5, 0, 1, 5, 4, 6, 6, 0, 5, 5, 2, 6, 4, 8, 2, 1, 7, 7, 9, 8, 9, 3, 9, 9,
                                       5, 5, 8, 1, 5, 8, 9, 1, 8, 6, 6, 9, 9, 6, 7, 9, 1, 8, 5, 2, 0, 2, 3, 1,
                                       5, 3, 7, 9, 6, 2, 5, 3, 6, 6, 4, 9, 8, 7, 6, 5, 0, 0, 9, 2, 6, 1, 0, 6};
  std::vector<int32_t> outHostData(30, 0);

  // Create input1 aclTensor.
  ret = CreateAclTensor(input1HostData, selfShape1, &input1DeviceAddr, aclDataType::ACL_INT32, &input1);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // Create input2 aclTensor.
  ret = CreateAclTensor(input2HostData, selfShape2, &input2DeviceAddr, aclDataType::ACL_INT32, &input2);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

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

  std::vector<aclTensor*> tmp{input1, input2};
  aclTensorList* tensorList = aclCreateTensorList(tmp.data(), tmp.size());

  const char equation[] = "abcd,abced->abce";

  // 3. Call the CANN operator library API.
  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;
  // Call the aclnnEinsum first-phase API
  ret = aclnnEinsumGetWorkspaceSize(tensorList, equation, out, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnEinsumGetWorkspaceSize 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 aclnnEinsum second-phase API
  ret = aclnnEinsum(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnEinsum 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 it based on the specific API definition
  auto size = GetShapeSize(outShape);
  ret = aclrtMemcpy(outHostData.data(), outHostData.size() * sizeof(outHostData[0]),
                    outDeviceAddr, size * sizeof(outHostData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy outHostData from device to host failed. ERROR: %d\n", ret); return ret);
  for (int64_t i = 0; i < size; i++) {
    LOG_PRINT("result[%ld] is: %i\n", i, outHostData[i]);
  }

  // 6. Release aclTensor and aclScalar. Modify it based on the specific API definition
  aclDestroyTensorList(tensorList);
  aclDestroyTensor(out);


  // 7. Release Device resources. Modify it based on the specific API definition
  aclrtFree(input1DeviceAddr);
  aclrtFree(input2DeviceAddr);
  aclrtFree(outDeviceAddr);
  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();
  return 0;
}