aclnnQuantMatmulReduceSumWeightNz
Applicable Products
Ascend 950PR&950DT products : Not 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: Performs quantized grouped matrix computation, and then sums the matrix computation results of all groups and outputs the result.
Formula:
Function Prototype
Each operator uses a two-phase API. Call "aclnnQuantMatmulReduceSumWeightNzGetWorkspaceSize" first to obtain the required workspace size and the executor that contains the operator computation process, and then call "aclnnQuantMatmulReduceSumWeightNz" to perform the computation.
aclnnStatus aclnnQuantMatmulReduceSumWeightNzGetWorkspaceSize(
const aclTensor *x1,
const aclTensor *x2,
const aclTensor *x1Scale,
const aclTensor *x2Scale,
const aclTensor *yScale,
const aclTensor *x1Offset,
const aclTensor *x2Offset,
const aclTensor *yOffset,
const aclTensor *bias,
bool transposeX1,
bool transposeX2,
int64_t groupSize,
const aclIntArray *dims,
bool keepDims,
aclTensor *out,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnQuantMatmulReduceSumWeightNz(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnQuantMatmulReduceSumWeightNzGetWorkspaceSize
Mandatory
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor x1 (aclTensor*) Input x1 in the formula. Empty tensors are not supported. INT8 ND (batch, m, k) - x2 (aclTensor*) Input x2 in the formula. - Empty tensors are not supported.
- The dimensions indicate: (batch, n1, k1, k0, n0), where k0 = 16, n0 = 32, and k in the x1 shape and k1 in the x2 shape must meet the following relationship: ceil(k / 16) = k1. n1 in the x2 shape and n in out meet the following relationship: ceil(n / n0) = n1.
- Use the aclnnCalculateMatmulWeightSizeV2 and aclnnTransMatmulWeight APIs to convert the input format from ND to the AI processor-affinity data layout format. The shape in the original ND format is (batch, k, n).
INT8 NZ 5D - x1Scale (aclTensor*) Input x1Scale in the formula. - Empty tensors are not supported.
- During actual computation, x1Scale is broadcast to (batch, m, n).
FLOAT32 ND (batch, m) √ x2Scale (aclTensor*) Input x2Scale in the formula. - Empty tensors are not supported.
- During computation, x2Scale is broadcast to (batch, m, n).
BFLOAT16 ND (n,) √ yScale (aclTensor*) Input Reserved parameter, not supported in the current version. Pass in nullptr. - - - - x1Offset (aclTensor*) Input Reserved parameter, not supported in the current version. Pass in nullptr. - - - - x2Offset (aclTensor*) Input Reserved parameter, not supported in the current version. Set it to nullptr. - - - - yOffset (aclTensor*) Input Reserved parameter, not supported in the current version. Set it to nullptr. - - - - bias (aclTensor*) Input Reserved parameter, not supported in the current version. Set this parameter to nullptr. - - - - transposeX1(bool) Input Indicates whether the input shape of x1 contains transpose. The current version supports only false, indicating that the meaning of the input shape of x1 remains unchanged. bool - - - transposeX2(bool) Input Whether the input shape of x2 contains transpose. Only false is supported in the current version, indicating that the input shape of x2 remains unchanged. bool - - - groupSize (int64_t) Input Reserved parameter, not supported in the current version. Pass in 0. - - - - dims (aclIntArray *) Input Specifies the reduce dimension. Currently, only [0] is supported, indicating that ReduceSum is performed along dimension 0 (batch dimension). INT64 - - - keepDims (bool) Input Indicates whether to retain the dimensions of the input tensor in the output tensor. Only false is supported in the current version. - - - - out(aclTensor*) Output out in the formula. - BFLOAT16 ND (m, n) √ workspaceSize(uint64_t*) Output Returns the size of the workspace to be allocated on the Device side. - - - - - executor (aclOpExecutor**) Output Returns the op executor, including 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 Value Error Code Description ACLNN_ERR_PARAM_NULLPTR 161001 x1, x2, x1Scale, x2Scale, or out is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data type and data format of x1, x2, x1Scale, x2Scale, or out are not within the supported range. The shape of x1, x2, x1Scale, x2Scale, or out does not meet the check conditions. x1, x2, x1Scale, x2Scale, or out is an empty tensor.
aclnnQuantMatmulReduceSumWeightNz
Mandatory
Parameter Input/Output Description workspace Input Workspace memory address allocated on the Device. workspaceSize Input Workspace size allocated on the Device, obtained by the first-phase API aclnnQuantMatmulReduceSumWeightNzGetWorkspaceSize. executor Input Op executor that contains the operator computation process. stream Input Specifies the stream for task execution. Return Value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
- Determinism:
- aclnnQuantMatmulReduceSumWeightNz defaults to a non-deterministic implementation. Deterministic computation can be enabled through aclrtCtxSetSysParamOpt.
Example
The following sample code is for reference only. For details about compilation and execution, see Compile and Run Samples.
#include <cstdint>
#include <cstring>
#include <iostream>
#include <memory>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_quant_matmul_reduce_sum.h"
#include "aclnnop/aclnn_trans_matmul_weight.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;
}
float Bfloat16ToFloat(uint16_t value)
{
// BF16 is the upper 16 bits of FP32; padding the lower 16 bits with zeros yields the corresponding FP32 bit representation.
const uint32_t bits = static_cast<uint32_t>(value) << 16U;
float result = 0.0F;
std::memcpy(&result, &bits, sizeof(result));
return result;
}
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 the 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 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 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();
}
template <typename T>
int CreateAclTensorX2(const std::vector<T> &hostData, const std::vector<int64_t> &shape, void **deviceAddr,
aclDataType dataType, aclTensor **tensor)
{
auto size = static_cast<uint64_t>(GetShapeSize(shape));
const aclIntArray *mat2Size = aclCreateIntArray(shape.data(), shape.size());
auto ret = aclnnCalculateMatmulWeightSizeV2(mat2Size, dataType, &size);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCalculateMatmulWeightSizeV2 failed. ERROR: %d\n", ret);
return ret);
size *= sizeof(T);
// Call aclrtMalloc to allocate device-side memory.
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 the 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 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];
}
std::vector<int64_t> storageShape;
storageShape.push_back(GetShapeSize(shape));
// Call the aclCreateTensor API to create an aclTensor.
*tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_FRACTAL_NZ,
storageShape.data(), storageShape.size(), *deviceAddr);
return 0;
}
int aclnnQuantMatmulWeightNzTest(int32_t deviceId, 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 input and output, and customize the construction based on the API.
int64_t b = 8;
int64_t m = 2048;
int64_t k = 1024;
int64_t n = 7168;
// Create x1 aclTensor.
std::vector<int64_t> x1Shape = {b, m, k};
void *x1DeviceAddr = nullptr;
aclTensor *x1 = nullptr;
std::vector<int8_t> x1HostData(b * m * k, 1);
ret = CreateAclTensor(x1HostData, x1Shape, &x1DeviceAddr, aclDataType::ACL_INT8, &x1);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> x1TensorPtr(x1, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void *)> x1DeviceAddrPtr(x1DeviceAddr, aclrtFree);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create x2 aclTensor in the AI processor affinity data layout format.
std::vector<int64_t> x2Shape = {b, k, n};
void *x2DeviceAddr = nullptr;
aclTensor *x2 = nullptr;
std::vector<int8_t> x2HostData(b * k * n, 1);
ret = CreateAclTensorX2(x2HostData, x2Shape, &x2DeviceAddr, aclDataType::ACL_INT8, &x2);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> x2HPTensorPtr(x2, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void *)> x2HPDeviceAddrPtr(x2DeviceAddr, aclrtFree);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create x1Scale aclTensor.
std::vector<int64_t> x1ScaleShape = {b, m};
void *x1ScaleDeviceAddr = nullptr;
std::vector<float> x1ScaleHostData(b * m, 1);
aclTensor *x1Scale = nullptr;
ret = CreateAclTensor(x1ScaleHostData, x1ScaleShape, &x1ScaleDeviceAddr, aclDataType::ACL_FLOAT, &x1Scale);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> x1ScaleTensorPtr(x1Scale, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void *)> x1ScaleDeviceAddrPtr(x1ScaleDeviceAddr, aclrtFree);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create x2Scale aclTensor.
std::vector<int64_t> x2ScaleShape = {n};
void *x2ScaleDeviceAddr = nullptr;
aclTensor *x2Scale = nullptr;
constexpr uint16_t bf16One = 0x3F80U;
std::vector<uint16_t> x2ScaleHostData(n, bf16One); // Bit representation of the BF16 value 1.0
ret = CreateAclTensor(x2ScaleHostData, x2ScaleShape, &x2ScaleDeviceAddr, aclDataType::ACL_BF16, &x2Scale);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> x2ScaleTensorPtr(x2Scale, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void *)> x2ScaleDeviceAddrPtr(x2ScaleDeviceAddr, aclrtFree);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create out aclTensor.
std::vector<int64_t> outShape = {m, n};
void *outDeviceAddr = nullptr;
aclTensor *out = nullptr;
std::vector<uint16_t> outHostData(m * n, 0); // Bit representation of the BF16 value 0.0
ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_BF16, &out);
std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> outTensorPtr(out, aclDestroyTensor);
std::unique_ptr<void, aclError (*)(void *)> outDeviceAddrPtr(outDeviceAddr, aclrtFree);
CHECK_RET(ret == ACL_SUCCESS, return ret);
bool transposeX1 = false;
bool transposeX2 = false;
// Create dims aclIntArray.
std::vector<int64_t> dimsData = {0};
aclIntArray *dims = nullptr;
dims = aclCreateIntArray(dimsData.data(), dimsData.size());
CHECK_RET(dims != nullptr, return ret);
// 3. Call the CANN operator library API, and replace it with the specific API name.
uint64_t workspaceSize = 0;
aclOpExecutor *executor = nullptr;
// Call the first-phase API of aclnnQuantMatmulReduceSumWeightNz.
ret = aclnnQuantMatmulReduceSumWeightNzGetWorkspaceSize(
x1, x2, x1Scale, x2Scale, nullptr, nullptr, nullptr, nullptr, nullptr, transposeX1, transposeX2, 0,
dims, false, out, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMatmulReduceSumWeightNzGetWorkspaceSize 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 second-phase API aclnnQuantMatmulReduceSumWeightNz.
ret = aclnnQuantMatmulReduceSumWeightNz(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMatmulReduceSumWeightNz failed. ERROR: %d\n", ret); return ret);
// 4. (boilerplate) Synchronize and 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 device memory to host memory. Modify it according to the API definition of the specific API.
auto size = GetShapeSize(outShape);
// C++ cannot directly print BF16. Read its bit representation with uint16_t first, and then convert BF16 to FP32.
std::vector<uint16_t> resultData(size, 0);
ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), outDeviceAddr,
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 i = 0; i < 5; i++) {
LOG_PRINT("result[%ld] is: %f\n", i, Bfloat16ToFloat(resultData[i]));
}
return ACL_SUCCESS;
}
int main()
{
// 1. (boilerplate) Initialize device/stream. For details, see the acl API manual.
// Set deviceId based on the actual device.
int32_t deviceId = 0;
aclrtStream stream;
auto ret = aclnnQuantMatmulWeightNzTest(deviceId, stream);
CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantMatmulWeightNzTest failed. ERROR: %d\n", ret);
return ret);
Finalize(deviceId, stream);
return 0;
}