aclnnGroupedMatmulAddV2

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

Function

  • Description: Implements grouped matrix multiplication, where the dimensions of each group can differ. The basic function is matrix multiplication, as in $y_i[m_i,n_i]=x_i[m_i,k_i] \times weight_i[k_i,n_i]+y_i[m_i,n_i], i=1...g$, where g is the number of groups and $m_i/k_i/n_i$ are the corresponding shapes. Both input and output data types are aclTensor, with K-axis grouping.

    • K-axis grouping: $k_i$ values differ across groups, but $m_i/n_i$ are the same for each group.
    • New features compared with the GroupedMatmulAdd API:
      • Supports using the values in groupList as the size of each group on the grouping axis.
  • Formula:

    $$ yRef_i^{out}=x_i\times weight_i + yRef_i^{in} $$

Function Prototype

Each operator uses a two-phase API. You must first call the "aclnnGroupedMatmulAddV2GetWorkspaceSize" API to obtain the input parameters and calculate the required workspace size based on the computation flow, and then call the "aclnnGroupedMatmulAddV2" API to execute the computation.

aclnnStatus aclnnGroupedMatmulAddV2GetWorkspaceSize(
    const aclTensor *x,
    const aclTensor *weight,
    const aclTensor *groupList,
    aclTensor       *yRef,
    bool             transposeX,
    bool             transposeWeight,
    int64_t          groupType,
    int64_t          groupListType,
    uint64_t        *workspaceSize,
    aclOpExecutor   **executor)
aclnnStatus aclnnGroupedMatmulAddV2(
    void          *workspace,
    uint64_t       workspaceSize,
    aclOpExecutor *executor,
    aclrtStream    stream)

aclnnGroupedMatmulAddV2GetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    x (aclTensor) Input Input x in the formula.
    • x must be transposed.
    FLOAT16, BFLOAT16 ND 2 √
    weight (aclTensor) Input Represents the weight, that is, weight in the formula.
    • weight does not support transposition.
    FLOAT16, BFLOAT16 ND 2 √
    groupList (aclTensor) Input Indicates the matmul size distribution of the input and output along the grouping axis. - INT64 - - -
    transposeX (bool) Input Indicates whether the x matrix is transposed. A Boolean value on the host.
    • Currently, only True is supported.
    BOOL - - -
    transposeWeight (bool) Input Indicates whether the weight matrix is transposed.
    • Only False is supported currently.
    BOOL - - -
    groupType (int64_t) Input Represents the grouping type.
    • Currently only 2 (K-axis grouping) is supported.
    INT64 - - -
    groupListType (int64_t) Input Integer parameter. Currently only two values are supported.
    • 0: Values in groupList are the cumsum result of grouping axis sizes (accumulated sum).
    • 1: Values in groupList are the size of each group on the grouping axis.
    INT64 - - -
    yRef (aclTensor) Input/Output Input/output matrix for in-place accumulation, an aclTensor on the device. Corresponds to y/yRef in the formula. - FLOAT32 ND 3 -
    workspaceSize (uint64_t) Output Returns the workspace size to be allocated on the Device side. - - - -
    executor (aclOpExecutor) Output Returns the op executor containing the operator computation flow. - - - - -
  • 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 Values Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 x, weight, groupList, or yRef is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type or data format of x, weight, groupList, or yRef is unsupported.
    The data types of x and weight are inconsistent.
    ACLNN_ERR_INNER_TILING_ERROR 561002 The shapes of x, weight, and yRef do not meet the matrix multiplication requirements.

aclnnGroupedMatmulAddV2

  • Parameters:

    ParameterInput/OutputDescription
    workspaceInputWorkspace memory address allocated on the Device.
    workspaceSizeInputWorkspace size allocated on the Device, obtained by the first-phase API aclnnGroupedMatmulAddV2GetWorkspaceSize.
    executorInputOp executor that contains the operator computation flow.
    streamInputStream for task execution.
  • Return value

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

Constraints

  • Deterministic computation description: aclnnGroupedMatmulAddV2 defaults to a deterministic implementation.
  • The size of each dimension of each group of tensors in x and weight, after 32-byte alignment, must be less than the maximum int32 value 2147483647.
  • The last dimension of each group of tensors in x and weight must be less than 65536. The last dimension of $x$ refers to the K axis of $x$ when x is not transposed, or the M axis of $x$ when x is transposed. The last dimension of $weight$ refers to the N axis of $weight$ when weight is not transposed, or the K axis of $weight$ when weight is transposed.
  • The supported input type combinations are as follows:
    • x is FLOAT16, weight is FLOAT16, and yRef is FLOAT32.
    • x is BFLOAT16, weight is BFLOAT16, and yRef is FLOAT32.
  • groupListType: 0 and 1 are supported.
    • groupListType=0: groupList must be a non-negative monotonic non-decreasing sequence (cumulative sum), and the last value must not exceed the first dimension of the tensor in x. Example with K=256 and E=4 (group sizes of 64, 0, 128, 64): [64, 64, 192, 256]
    • groupListType=1: The groupList must be a non-negative number column (size of each group). The total value cannot be greater than the first dimension of the tensor in x. Example: [64, 0, 128, 64]
  • The first dimension of groupList supports a maximum of 1024, i.e., a maximum of 1024 groups.

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 <memory>
#include "acl/acl.h"
#include "aclnnop/aclnn_grouped_matmul_add_v2.h"

#define CHECK_RET(cond, return_expr) \
    do {                             \
        if (!(cond)) {               \
            return_expr;             \
        }                            \
    } while (0)

#define CHECK_FREE_RET(cond, return_expr) \
    do {                                  \
        if (!(cond)) {                    \
            Finalize(deviceId, stream);   \
            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_New(const std::vector<int64_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 data from the Host 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 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;
}

template <typename T>
int CreateAclTensor(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 data from the Host to the Device memory.
    std::vector<T> hostData(size, 0);
    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 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;
}

void Finalize(int32_t deviceId, aclrtStream stream)
{
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
}

int aclnnGroupedMatmulAddV2Test(int32_t deviceId, aclrtStream &stream) {
    auto ret = Init(deviceId, &stream);
    // Handle the check as required.
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);

    // 2. Construct the input and output based on the API.
    std::vector<int64_t> xShape = {512, 256};
    std::vector<int64_t> weightShape= {512, 256};
    std::vector<int64_t> yShape = {2, 256, 256};
    std::vector<int64_t> groupListShape = {2};
    std::vector<int64_t> groupListData = {256, 512};
    void* xDeviceAddr = nullptr;
    void* weightDeviceAddr = nullptr;
    void* yDeviceAddr = nullptr;
    void* groupListDeviceAddr = nullptr;
    aclTensor* x = nullptr;
    aclTensor* weight = nullptr;
    aclTensor* groupedList = nullptr;
    aclTensor* y = nullptr;
    aclTensor* yRef = nullptr;
    bool transpose_x = true;
    bool transpose_weight = false;
    int group_type = 2;
    int groupListType = 0;

    // Create the aclTensorList for x.
    ret = CreateAclTensor<uint16_t>(xShape, &xDeviceAddr, aclDataType::ACL_BF16, &x);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> xTensorPtr(x, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void *)> xDeviceAddrPtr(xDeviceAddr, aclrtFree);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create weight aclTensorList.
    ret = CreateAclTensor<uint16_t>(weightShape, &weightDeviceAddr, aclDataType::ACL_BF16, &weight);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> weightTensorPtr(weight, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void *)> weightDeviceAddrPtr(weightDeviceAddr, aclrtFree);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create y aclTensorList.
    ret = CreateAclTensor<float>(yShape, &yDeviceAddr, aclDataType::ACL_FLOAT, &y);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> yTensorPtr(y, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void *)> yDeviceAddrPtr(yDeviceAddr, aclrtFree);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create group_list aclTensor.
    ret = CreateAclTensor_New<int64_t>(groupListData, groupListShape, &groupListDeviceAddr, aclDataType::ACL_INT64, &groupedList);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> groupedListTensorPtr(groupedList, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void *)> groupListDeviceAddrPtr(groupListDeviceAddr, aclrtFree);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    yRef = y;

    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;

    // 3. Call the CANN operator library API.
    // Call the aclnnGroupedMatmulAddV2 first-phase API.
    ret = aclnnGroupedMatmulAddV2GetWorkspaceSize(x, weight, groupedList, yRef, transpose_x, transpose_weight, group_type, groupListType, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGroupedMatmulAddV2GetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
    // Allocate device memory based on the workspaceSize computed by the first-phase API.
    void* workspaceAddr = nullptr;
    std::unique_ptr<void, aclError (*)(void *)> workspaceAddrPtr(nullptr, aclrtFree);
    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);
        workspaceAddrPtr.reset(workspaceAddr);
    }
    // Call the aclnnGroupedMatmulAddV2 second-phase API.
    ret = aclnnGroupedMatmulAddV2(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGroupedMatmulAddV2 failed. ERROR: %d\n", ret); return ret);

    // 4. (boilerplate) Synchronously wait for the task 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 Device memory to the Host, and modify it based on the specific API definition.
    auto size = GetShapeSize(yShape);
    std::vector<float> resultData(size, 0);
    ret = aclrtMemcpy(resultData.data(), size * sizeof(resultData[0]), yDeviceAddr,
                          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 j = 0; j < size; j++) {
        LOG_PRINT("result[%ld] is: %f\n", j, resultData[j]);
    }
    return ACL_SUCCESS;
}
int main()
{
    // 1. (boilerplate) Initialize device/stream. For details, see the AscendCL API list.
    // Fill in deviceId according to the actual device.
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = aclnnGroupedMatmulAddV2Test(deviceId, stream);
    CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGroupedMatmulAddV2Test failed. ERROR: %d\n", ret); return ret);

    Finalize(deviceId, stream);
    return 0;
}