aclnnEinsum

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: 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 is divided into a two-phase API. The "aclnnEinsumGetWorkspaceSize" API must be called first to obtain the workspace size required for computation and the executor that encapsulates the operator computation flow. Then, the "aclnnEinsum" API is called to perform 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 for Einstein summation convention. Currently only "abcd,abced->abce" and "a,b->ab" are supported. A host-side expression string. - - - -
    output Output Output tensor. Empty tensors are not supported. FLOAT16, FLOAT, INT16, UINT16, INT32, UINT32, INT64, UINT64 ND - √
    workspaceSize Output Returns the workspace size to be applied for on the Device side. - - - - -
    executor Output Returns the operator executor, which contains the operator computation flow. - - - - -
    • Atlas inference products: tensors and output do not support the FLOAT data type.
  • 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 Value Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 The input tensors or output is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data types of tensors and output are not within the supported range.
    The equation (extensible) is not in the registry.
    When equation=='abcd,abced->abce':
    • tensors contains two Tensors (i.e. tensors[0] & tensors[1]);
    • tensors[0], tensors[1], and output must have the same data type;
    • tensors[0] must be 4-dimensional;
    • tensors[1] must be 5-dimensional;
    • The first three dimensions of tensors[0] must equal the first three dimensions of tensors[1];
    • The fourth dimension of tensors[0] must equal the fifth dimension of tensors[1].
    When equation=='a,b->ab':
    • tensorList contains two Tensors (i.e. tensors[0] & tensors[1]);
    • tensors[0], tensors[1], and output must have the same data type;
    • tensors[0] must be 1-dimensional;
    • tensors[1] must be 1-dimensional.

aclnnEinsum

  • 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 from the first-phase API aclnnEinsumGetWorkspaceSize.
    executor Input Operator executor, which contains the operator computation flow.
    stream Input Specifies the stream that executes the task.
  • Return Value:

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

Constraints

  • Determinism description: aclnnEinsum defaults to a deterministic implementation.

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

Example

The following provides example code for reference only. For details about compilation and running, 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. Initialize resources.
  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 apply for 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 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 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 inputs and output. Customize the construction 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 the input1 aclTensor.
  ret = CreateAclTensor(input1HostData, selfShape1, &input1DeviceAddr, aclDataType::ACL_INT32, &input1);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // Create the input2 aclTensor.
  ret = CreateAclTensor(input2HostData, selfShape2, &input2DeviceAddr, aclDataType::ACL_INT32, &input2);
  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);

  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 first-phase API of aclnnEinsum.
  ret = aclnnEinsumGetWorkspaceSize(tensorList, equation, out, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnEinsumGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
  // Apply for 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 aclnnEinsum.
  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 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 and copy the result from the device side to the host side. Modify 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 based on the specific API definition.
  aclDestroyTensorList(tensorList);
  aclDestroyTensor(out);


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