aclnnGroupedMatmulAdd
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.
Formula:
$$ yRef_i=x_i\times weight_i + y_i $$
Function Prototype
Each operator uses a two-phase API. First, call "aclnnGroupedMatmulAddGetWorkspaceSize" to obtain the input parameters and calculate the required workspace size based on the computation flow. Then, call "aclnnGroupedMatmulAdd" to perform the computation.
aclnnStatus aclnnGroupedMatmulAddGetWorkspaceSize(
const aclTensor *x,
const aclTensor *weight,
const aclTensor *groupList,
aclTensor *yRef,
bool transposeX,
bool transposeWeight,
int64_t groupType,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnGroupedMatmulAdd(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream
)aclnnGroupedMatmulAddGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor x Input The input x in the formula. - FLOAT16, BFLOAT16 ND 2 √ weight Input The weight in the formula. - FLOAT16, BFLOAT16 ND 2 √ groupList Input Device-side aclTensor, indicating the matmul size distribution along the grouping axis of the inputs and outputs. Only the cumulative sum (cumsum) mode is supported. INT64 - - - yRef Output Output matrix for in-place accumulation, that is, y. - FLOAT32 ND 2, 3 × transposeX attribute Indicates whether the x matrix is transposed. Only True is supported. BOOL - - - transposeWeight attribute Indicates whether the weight matrix is transposed. Only False is supported. BOOL - - - groupType attribute Indicates the grouping type. Only 2 (K-axis grouping) is supported. INT64 - - - workspaceSize Output Returns the size of the workspace to be requested on the Device side. - - - - executor Output Returns the op executor, which contains the computation flow of the operator. - - - - - Ascend 950PR&950DT products :- A 2-dimensional shape is not supported for yRef.
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 input 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 out of the supported range. x and weight have different data types. ACLNN_ERR_INNER_TILING_ERROR 561002 The shape of x, weight, or yRef does not meet the matmul requirements.
aclnnGroupedMatmulAdd
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address allocated on the Device side. workspaceSize Input Size of the workspace allocated on the Device side, obtained by calling the first-phase API aclnnGroupedMatmulAddGetWorkspaceSize.executor Input op executor, which contains the operator computation flow. stream Input Specifies the stream for task execution. Return value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
- aclnnGroupedMatmulAdd defaults to a deterministic implementation.
- After 32-byte alignment, the size of each dimension of each tensor group in x and weight 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.
- Supported input types:
- x is FLOAT16, weight is FLOAT16, and y is FLOAT32.
- x is BFLOAT16, weight is BFLOAT16, and y is FLOAT32.
- groupList must be a non-negative, monotonically non-decreasing sequence (cumulative sum), and the last value must not be greater than the first dimension of the tensor in x. Example with K=256 and E=4 (the group sizes are 64, 0, 128, and 64 in sequence):
[64, 64, 192, 256] - The first dimension of groupList supports a maximum of 1024, i.e., a maximum of 1024 groups.
Example
The sample code is for reference only. For details about compilation and execution, see Compile and Run Samples.
Atlas A3 products ,Atlas A2 products :#include <iostream> #include <vector> #include "acl/acl.h" #include "aclnnop/aclnn_grouped_matmul_add.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); 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 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); // 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-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. std::vector<T> hostData(GetShapeSize(shape), 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; } int CreateAclTensorList(const std::vector<std::vector<int64_t>>& shapes, void** deviceAddr, aclDataType dataType, aclTensorList** tensor) { int size = shapes.size(); std::vector<aclTensor*> tensors(size); for (int i = 0; i < size; i++) { int ret = CreateAclTensor<uint16_t>(shapes[i], deviceAddr + i, dataType, tensors.data() + i); CHECK_RET(ret == ACL_SUCCESS, return ret); } *tensor = aclCreateTensorList(tensors.data(), size); return ACL_SUCCESS; } int main() { // 1. (Boilerplate) Initialize device/stream. For details, see the acl API reference. // Set deviceId based on the actual device. int32_t deviceId = 0; aclrtStream stream; auto ret = Init(deviceId, &stream); // Handle check as required. CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret); // 2. Construct the inputs and outputs. Custom construction is required based on the API. std::vector<int64_t> xShape = {64, 32}; std::vector<int64_t> weightShape= {64, 32}; std::vector<int64_t> yShape = {64, 32}; std::vector<int64_t> groupListShape = {2}; std::vector<int64_t> groupListData = {32, 64}; void* xDeviceAddr; void* weightDeviceAddr; void* yDeviceAddr; void* groupListDeviceAddr; 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; // Create the x aclTensorList. ret = CreateAclTensor<uint16_t>(xShape, &xDeviceAddr, aclDataType::ACL_FLOAT16, &x); CHECK_RET(ret == ACL_SUCCESS, return ret); // Create the weight aclTensorList. ret = CreateAclTensor<uint16_t>(weightShape, &weightDeviceAddr, aclDataType::ACL_FLOAT16, &weight); CHECK_RET(ret == ACL_SUCCESS, return ret); // Create the y aclTensorList. ret = CreateAclTensor<float>(yShape, &yDeviceAddr, aclDataType::ACL_FLOAT, &y); CHECK_RET(ret == ACL_SUCCESS, return ret); // Create the group_list aclTensor. ret = CreateAclTensor_New<int64_t>(groupListData, groupListShape, &groupListDeviceAddr, aclDataType::ACL_INT64, &groupedList); CHECK_RET(ret == ACL_SUCCESS, return ret); yRef = y; uint64_t workspaceSize = 0; aclOpExecutor* executor; // 3. Call the CANN operator library API. // Call the first-phase API of aclnnGroupedMatmulAdd. ret = aclnnGroupedMatmulAddGetWorkspaceSize(x, weight, groupedList, yRef, transpose_x, transpose_weight, group_type, &workspaceSize, &executor); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGroupedMatmulAddGetWorkspaceSize failed. ERROR: %d\n", ret); return ret); // Allocate device memory using 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 aclnnGroupedMatmulAdd. ret = aclnnGroupedMatmulAdd(workspaceAddr, workspaceSize, executor, stream); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGroupedMatmulAdd failed. ERROR: %d\n", ret); return ret); // 4. (Boilerplate) Synchronize and wait for the task execution to finish. 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 device memory to the host. Modify the code based on the actual 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]); } // 6. Release aclTensor and aclScalar. Modify the code based on the actual API definition. aclDestroyTensor(x); aclDestroyTensor(weight); aclDestroyTensor(y); // 7. Release device resources. Modify the code based on the actual API definition. aclrtFree(xDeviceAddr); aclrtFree(weightDeviceAddr); aclrtFree(yDeviceAddr); if (workspaceSize > 0) { aclrtFree(workspaceAddr); } aclrtDestroyStream(stream); aclrtResetDevice(deviceId); aclFinalize(); return 0; }
Ascend 950PR&950DT products :#include <iostream> #include <vector> #include "acl/acl.h" #include "aclnnop/aclnn_grouped_matmul_add.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); 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 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 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 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 Host data to Device memory. std::vector<T> hostData(GetShapeSize(shape), 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); // 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 CreateAclTensorList(const std::vector<std::vector<int64_t>>& shapes, void** deviceAddr, aclDataType dataType, aclTensorList** tensor) { int size = shapes.size(); std::vector<aclTensor*> tensors(size); for (int i = 0; i < size; i++) { int ret = CreateAclTensor<uint16_t>(shapes[i], deviceAddr + i, dataType, tensors.data() + i); CHECK_RET(ret == ACL_SUCCESS, return ret); } *tensor = aclCreateTensorList(tensors.data(), size); return ACL_SUCCESS; } 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 needed. CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret); // 2. Construct the input and output in a custom manner based on the API. std::vector<int64_t> xShape = {64, 32}; std::vector<int64_t> weightShape= {64, 32}; std::vector<int64_t> yShape = {2, 32, 32}; std::vector<int64_t> groupListShape = {2}; std::vector<int64_t> groupListData = {32, 64}; void* xDeviceAddr; void* weightDeviceAddr; void* yDeviceAddr; void* groupListDeviceAddr; 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; // Create the x aclTensorList. ret = CreateAclTensor<uint16_t>(xShape, &xDeviceAddr, aclDataType::ACL_FLOAT16, &x); CHECK_RET(ret == ACL_SUCCESS, return ret); // Create the weight aclTensorList. ret = CreateAclTensor<uint16_t>(weightShape, &weightDeviceAddr, aclDataType::ACL_FLOAT16, &weight); CHECK_RET(ret == ACL_SUCCESS, return ret); // Create y aclTensorList. ret = CreateAclTensor<float>(yShape, &yDeviceAddr, aclDataType::ACL_FLOAT, &y); CHECK_RET(ret == ACL_SUCCESS, return ret); // Create group_list aclTensor. ret = CreateAclTensor_New<int64_t>(groupListData, groupListShape, &groupListDeviceAddr, aclDataType::ACL_INT64, &groupedList); CHECK_RET(ret == ACL_SUCCESS, return ret); yRef = y; uint64_t workspaceSize = 0; aclOpExecutor* executor; // 3. Call the CANN operator library API. // Call the first-phase API of aclnnGroupedMatmulAdd. ret = aclnnGroupedMatmulAddGetWorkspaceSize(x, weight, groupedList, yRef, transpose_x, transpose_weight, group_type, &workspaceSize, &executor); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGroupedMatmulAddGetWorkspaceSize 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 aclnnGroupedMatmulAdd. ret = aclnnGroupedMatmulAdd(workspaceAddr, workspaceSize, executor, stream); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGroupedMatmulAdd 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 and copy the result from Device memory to the Host. Modify the code 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]); } // 6. Release the aclTensor and aclScalar. Modify the code based on the specific API definition. aclDestroyTensor(x); aclDestroyTensor(weight); aclDestroyTensor(y); // 7. Release the device resources. Modify the code based on the specific API definition. aclrtFree(xDeviceAddr); aclrtFree(weightDeviceAddr); aclrtFree(yDeviceAddr); if (workspaceSize > 0) { aclrtFree(workspaceAddr); } aclrtDestroyStream(stream); aclrtResetDevice(deviceId); aclFinalize(); return 0; }