aclnnMatmulCompressDequant【免费下载链接】ops-math本项目是CANN提供的数学类基础计算算子库实现网络在NPU上加速计算。项目地址: https://gitcode.com/cann/ops-math 查看源码产品支持情况产品是否支持Ascend 950PR/Ascend 950DT×Atlas A3 训练系列产品/Atlas A3 推理系列产品×Atlas A2 训练系列产品/Atlas A2 推理系列产品×Atlas 200I/500 A2 推理产品×Atlas 推理系列产品√Atlas 训练系列产品×Atlas 200/300/500 推理产品×功能说明接口功能进行lr矩阵乘计算时可先通过msModelSlim工具对r矩阵进行无损压缩减少r矩阵的内存占用大小然后通过本接口完成无损解压缩、矩阵乘、反量化计算。计算公式$$ x2_unzip unzip(x2, compressIndex, compressInfo)\ result(x1 x2_unzip bias)*deqScale $$其中x2表示r矩阵经过msModelSlim工具进行压缩后的一维数据compressIndex以及compressInfo表示压缩算法相关的信息$x2_unzip$是本接口内部进行无损解压缩后的数据与原始r矩阵数据一致压缩和调用本接口的详细使用样例参考调用示例。函数原型每个算子分为两段式接口必须先调用“aclnnMatmulCompressDequantGetWorkspaceSize”接口获取计算所需workspace大小以及包含了算子计算流程的执行器再调用“aclnnMatmulCompressDequant”接口执行计算。aclnnStatus aclnnMatmulCompressDequantGetWorkspaceSize( const aclTensor* x1, const aclTensor* x2, const aclTensor* compressIndex, const aclTensor* bias, const aclTensor* deqScale, const aclTensor* offsetW, int offsetX, const aclIntArray* compressInfo, aclTensor* out, uint64_t* workspaceSize, aclOpExecutor** executor)aclnnStatus aclnnMatmulCompressDequant( void* workspace, uint64_t workspaceSize, aclOpExecutor* executor, aclrtStream stream)aclnnMatmulCompressDequantGetWorkspaceSize参数说明参数名输入/输出描述使用说明数据类型数据格式维度(shape)非连续tensorx1输入表示矩阵乘的左输入。-INT8ND2-x2输入表示压缩后的矩阵乘的右输入为通过msModelSlim工具中weight_compression模块压缩后的输入。-INT8ND1-compressIndex输入表示矩阵乘右输入的压缩索引表。通过示例中的msModelSlim工具中获取INT8ND1-bias输入参与矩阵乘计算的偏置项。支持空指针传入。INT8ND2维shape仅支持(1, n)或者(n)其中n为输出shape(m, n)的n-deqScale输入表示反量化参数。tensor中的值为float通过下述示例中转换后的UINT64的数据。UINT64ND2维shape支持(1, n)或者(1, 1), 其中n为输出shape(m, n)中的n。-offsetW输入标量表示矩阵乘右输入的偏移量。当前仅支持空指针传入。INT8-与x2_unzip一致。-offsetX输入标量表示矩阵乘左输入的偏移量。当前仅支持0。INT32---compressInfo输入整型数据列表数据类型为INT64。其中包括压缩块信息tilingN、tilingK通过msModelSlim工具中weight_compression模块压缩后获取分别表示压缩前shape(n, k)在n方向和k方向上一个基本压缩块的大小压缩前x2矩阵原始shapeshape为2维用(n, k)表示以及压缩块遍历方向的标识。-INT64---out输出计算输出。-FLOAT16ND2-workspaceSize出参返回需要在Device侧申请的workspace大小。-----executor出参返回op执行器包含了算子计算流程。-----返回值aclnnStatus返回状态码具体参见aclnn返回码。第一段接口完成入参校验出现以下场景时报错返回值错误码描述ACLNN_ERR_PARAM_NULLPTR161001传入的x1、x2或out是空指针。ACLNN_ERR_PARAM_INVALID161002x1或x2的数据类型和数据格式不在支持的范围之内。x1或x2无法做数据类型推导。推导出的数据类型无法转换为指定输出out的类型。aclnnMatmulCompressDequant参数说明参数名输入/输出描述workspace输入在Device侧申请的workspace内存地址。workspaceSize输入在Device侧申请的workspace大小由第一段接口aclnnMatmulCompressDequantGetWorkspaceSize获取。executor输入op执行器包含了算子计算流程。stream输入指定执行任务的Stream。返回值aclnnStatus返回状态码具体参见aclnn返回码。约束说明确定性计算aclnnMatmulCompressDequant默认确定性实现。调用示例准备压缩前的数据假设通过脚本gen_data.py生成输入数据示例如下仅供参考import numpy as np import os import sys from numpy import random def write2file(data, path): with open(path, wb) as f: data.tofile(f) if not os.path.exists(./data): os.mkdir(./data) if len(sys.argv) ! 4: print(Usage: python gen_data.py m k n) sys.exit(1) m int(sys.argv[1]) k int(sys.argv[2]) n int(sys.argv[3]) if m 0 or k 0 or n 0: print(Error: m, k and n must be positive integers.) sys.exit(1) # 随机生成矩阵mat1shape为(m,k ) mat1 random.randn(m, k).astype(np.int8) write2file(mat1, ./data/mat1.bin) # 随机生成矩阵mat2shape为(n, k) mat2 random.randint(0, 100, size(n, k)).astype(np.int8) np.save(./data/weight.npy, {weight: mat2}) os.chmod(./data/weight.npy, 0o0640) # 生成output output np.random.randn(m, n).astype(np.float16) write2file(output, ./data/output.bin) # 生成bias bias random.randn(n).astype(np.float32) write2file(bias, ./data/bias.bin) # 生成deq_scale deq_scale random.randn(n).astype(np.float32) write2file(deq_scale, ./data/deqScale_ori.bin) deq_scale_int64 np.fromfile(./data/deqScale_ori.bin, dtypenp.int32).astype(np.int64) deq_scale_int64.tofile(./data/deqScale.bin)执行gen_data.py假设mat1和mat2的shape入参为m512、k1024、n1024。python3 gen_data.py 512 1024 1024对数据进行预处理原始权重通过msModelSlim压缩工具生成压缩后的x2、compressIndex以及compressInfo使用以下接口时需对CANN包中msModelSlim压缩工具进行编译具体操作参考Gitee msit仓中msmodelslim/pytorch/weight_compression目录下的README.md。from msmodelslim.pytorch.weight_compression import CompressConfig, Compressor compress_config CompressConfig(do_pseudo_sparseFalse, sparse_ratio1) compressor Compressor(compress_config, weight_pathweight_path) compress_weight, compress_index, compress_info compressor.run() # 压缩后的权重对应aclnnMatmulCompressDequantGetWorkspaceSize接口的x2 compressor.export(compress_weight, ./data/weight) # 压缩权重的索引对应aclnnMatmulCompressDequantGetWorkspaceSize接口的compressIndex compressor.export(compress_index, ./data/index) # 压缩数据的相关信息对应aclnnMatmulCompressDequantGetWorkspaceSize接口的compressInfo compressor.export(compress_info, ./data/compress_info)将原始float类型的反量化参数deqscale进行转换 得到aclnn接口需要的uint64数据deqScale原始为float类型以int32读取并转换为int64import numpy as np data np.fromfile(./deqScale_original.bin, dtypenp.int32).astype(np.int64) data.tofile(./deqScale.bin)调用aclnn接口运算示例代码如下仅供参考具体编译和执行过程请参考编译与运行样例。#include iostream #include vector #include acl/acl.h #include aclnnop/aclnn_matmul_compress_dequant.h #include fstream #include unistd.h #include sys/stat.h #include stdio.h #include cstdlib #include string #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::vectorint64_t shape) { int64_t shapeSize 1; for (auto i : shape) { shapeSize * i; } return shapeSize; } int Init(int32_t deviceId, aclrtStream* stream) { // 固定写法资源初始化 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; } int ReadBinFileNNop(std::string filePath, void* buffer, size_t bufferSize) { struct stat sBuf; int fileStatus stat(filePath.data(), sBuf); CHECK_RET(fileStatus ACL_SUCCESS, LOG_PRINT(Failed to get file %s\n, filePath); return -1); std::ifstream file; file.open(filePath, std::ios::binary); CHECK_RET(file.is_open(), LOG_PRINT(Open file failed.\n); return -1); file.seekg(0, file.end); uint64_t binFileBufferLen file.tellg(); CHECK_RET(binFileBufferLen 0, std::coutFile size is 0.\n; file.close(); return -1); file.seekg(0, file.beg); file.read(static_castchar *(buffer), binFileBufferLen); file.close(); return ACL_SUCCESS; } int CreateAclTensor(std::string filePath, const std::vectorint64_t shape, int typeSize, void** deviceAddr, aclDataType dataType, aclTensor** tensor) { auto size GetShapeSize(shape) * typeSize; // 调用aclrtMalloc申请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); // 调用aclrtMallocHost申请host侧内存 void* binBufferHost nullptr; ret aclrtMallocHost(binBufferHost, size); CHECK_RET(ret ACL_SUCCESS, LOG_PRINT(aclrtMallocHost failed. ERROR: %d\n, ret); return ret); // 读取文件 ret ReadBinFileNNop(filePath, binBufferHost, size); CHECK_RET(ret ACL_SUCCESS, LOG_PRINT(ReadBinFileNNop failed. ERROR: %d\n, ret); return ret); // 调用aclrtMemcpy将host侧数据拷贝到device侧内存上 ret aclrtMemcpy(*deviceAddr, size, binBufferHost, size, ACL_MEMCPY_HOST_TO_DEVICE); CHECK_RET(ret ACL_SUCCESS, LOG_PRINT(aclrtMemcpy failed. ERROR: %d\n, ret); return ret); // 计算连续tensor的strides std::vectorint64_t strides(shape.size(), 1); for (int64_t i shape.size() - 2; i 0; i--) { strides[i] shape[i 1] * strides[i 1]; } // 调用aclCreateTensor接口创建aclTensor *tensor aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND, shape.data(), shape.size(), *deviceAddr); return 0; } int main(int argc, char* argv[]) { // 1. 固定写法device/stream初始化参考acl API手册 // 根据自己的实际device填写deviceId 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); if (argc ! 6) { std::cerr Error: Invalid number of arguments. Usage: program m k n wCompressedSize indexSize std::endl; return -1; } // 2. 构造输入与输出需要根据API的接口自定义构造 int m atoi(argv[1]); int k atoi(argv[2]); int n atoi(argv[3]); // wShape是右矩阵压缩后数据的大小 int wCompressedSize atoi(argv[4]); // indexShape是压缩索引数据的大小 int indexSize atoi(argv[5]); if (m 0 || k 0 || n 0 || wCompressedSize 0 || indexSize 0) { std::cerr Error: m, k, n, wCompressedSize and indexSize must be positive integers. std::endl; return -1; } std::vectorint64_t mat1Shape {m, k}; std::vectorint64_t mat2CompressedShape {wCompressedSize}; std::vectorint64_t indexShape {indexSize}; std::vectorint64_t biasShape {n}; std::vectorint64_t deqScaleShape {n}; std::vectorint64_t outputShape {m, n}; std::vectorint64_t compressInfoHostData {8, 8, k, n, 1}; void* mat1DeviceAddr nullptr; void* mat2CompressedDeviceAddr nullptr; void* indexDeviceAddr nullptr; void* biasDeviceAddr nullptr; void* deqScaleDeviceAddr nullptr; void* outputDeviceAddr nullptr; aclTensor* mat1 nullptr; aclTensor* mat2Compressed nullptr; aclTensor* index nullptr; aclTensor* bias nullptr; aclTensor* deqScale nullptr; aclTensor* output nullptr; aclIntArray* compressInfo nullptr; std::string rootPath ./data/; // 创建mat1 aclTensor std::string mat1FilePath rootPath mat1.bin; ret CreateAclTensor(mat1FilePath, mat1Shape, sizeof(int8_t), mat1DeviceAddr, aclDataType::ACL_INT8, mat1); CHECK_RET(ret ACL_SUCCESS, LOG_PRINT(Create mat1 tensor failed. ERROR: %d\n, ret); return ret); // 创建mat2Compressed aclTensor std::string mat2FilePath rootPath weight/weight.dat; ret CreateAclTensor(mat2FilePath, mat2CompressedShape, sizeof(int8_t), mat2CompressedDeviceAddr, aclDataType::ACL_INT8, mat2Compressed); CHECK_RET(ret ACL_SUCCESS, LOG_PRINT(Create mat2 tensor failed. ERROR: %d\n, ret); return ret); // 创建index aclTensor std::string indexFilePath rootPath index/weight.dat; ret CreateAclTensor(indexFilePath, indexShape, sizeof(int8_t), indexDeviceAddr, aclDataType::ACL_INT8, index); CHECK_RET(ret ACL_SUCCESS, LOG_PRINT(Create index tensor failed. ERROR: %d\n, ret); return ret); // 创建bias aclTensor std::string biasFilePath rootPath bias.bin; ret CreateAclTensor(biasFilePath, biasShape, sizeof(int32_t), biasDeviceAddr, aclDataType::ACL_INT32, bias); CHECK_RET(ret ACL_SUCCESS, LOG_PRINT(Create bias tensor failed. ERROR: %d\n, ret); return ret); // 创建deqScale aclTensor std::string deqScaleFilePath rootPath deqScale.bin; ret CreateAclTensor(deqScaleFilePath, deqScaleShape, sizeof(int32_t), deqScaleDeviceAddr, aclDataType::ACL_UINT64, deqScale); CHECK_RET(ret ACL_SUCCESS, LOG_PRINT(Create deqScale tensor failed. ERROR: %d\n, ret); return ret); // 创建compressInfo compressInfo aclCreateIntArray(compressInfoHostData.data(), aclDataType::ACL_INT64); // 创建out aclTensor std::string outputFilePath rootPath output.bin; ret CreateAclTensor(outputFilePath, outputShape, 2, outputDeviceAddr, aclDataType::ACL_FLOAT16, output); CHECK_RET(ret ACL_SUCCESS, LOG_PRINT(Create output tensor failed. ERROR: %d\n, ret); return ret); int32_t offsetX 0; // 3. 调用CANN算子库API需要修改为具体的Api名称 uint64_t workspaceSize 0; aclOpExecutor* executor; // 调用aclnnMm第一段接口 ret aclnnMatmulCompressDequantGetWorkspaceSize(mat1, mat2Compressed, index, bias, deqScale, nullptr, offsetX, compressInfo, output, workspaceSize, executor); CHECK_RET(ret ACL_SUCCESS, LOG_PRINT(aclnnMatmulCompressDequantGetWorkspaceSize failed. ERROR: %d\n, ret); return ret); // 根据第一段接口计算出的workspaceSize申请device内存 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); } // 调用aclnnMm第二段接口 ret aclnnMatmulCompressDequant(workspaceAddr, workspaceSize, executor, stream); CHECK_RET(ret ACL_SUCCESS, LOG_PRINT(aclnnMatmulCompressDequant failed. ERROR: %d\n, ret); return ret); // 4. 固定写法同步等待任务执行结束 ret aclrtSynchronizeStream(stream); CHECK_RET(ret ACL_SUCCESS, LOG_PRINT(aclrtSynchronizeStream failed. ERROR: %d\n, ret); return ret); // 5. 获取输出的值将device侧内存上的结果拷贝至host侧需要根据具体API的接口定义修改 auto size GetShapeSize(outputShape); std::vectorfloat resultData(size, 0); ret aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), outputDeviceAddr, 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 size; i) { LOG_PRINT(result[%ld] is: %f\n, i, resultData[i]); } // 6. 释放aclTensor和aclScalar需要根据具体API的接口定义修改 aclDestroyTensor(mat1); aclDestroyTensor(mat2Compressed); aclDestroyTensor(index); aclDestroyTensor(bias); aclDestroyTensor(deqScale); aclDestroyTensor(output); aclDestroyIntArray(compressInfo); // 7.释放硬件资源需要根据具体API的接口定义修改 aclrtFree(mat1DeviceAddr); aclrtFree(mat2CompressedDeviceAddr); aclrtFree(indexDeviceAddr); aclrtFree(biasDeviceAddr); aclrtFree(deqScaleDeviceAddr); aclrtFree(outputDeviceAddr); if (workspaceSize 0) { aclrtFree(workspaceAddr); } aclrtDestroyStream(stream); aclrtResetDevice(deviceId); aclFinalize(); return 0; }【免费下载链接】ops-math本项目是CANN提供的数学类基础计算算子库实现网络在NPU上加速计算。项目地址: https://gitcode.com/cann/ops-math创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
CANN/ops-math矩阵乘法压缩反量化算子
发布时间:2026/7/12 13:54:02
aclnnMatmulCompressDequant【免费下载链接】ops-math本项目是CANN提供的数学类基础计算算子库实现网络在NPU上加速计算。项目地址: https://gitcode.com/cann/ops-math 查看源码产品支持情况产品是否支持Ascend 950PR/Ascend 950DT×Atlas A3 训练系列产品/Atlas A3 推理系列产品×Atlas A2 训练系列产品/Atlas A2 推理系列产品×Atlas 200I/500 A2 推理产品×Atlas 推理系列产品√Atlas 训练系列产品×Atlas 200/300/500 推理产品×功能说明接口功能进行lr矩阵乘计算时可先通过msModelSlim工具对r矩阵进行无损压缩减少r矩阵的内存占用大小然后通过本接口完成无损解压缩、矩阵乘、反量化计算。计算公式$$ x2_unzip unzip(x2, compressIndex, compressInfo)\ result(x1 x2_unzip bias)*deqScale $$其中x2表示r矩阵经过msModelSlim工具进行压缩后的一维数据compressIndex以及compressInfo表示压缩算法相关的信息$x2_unzip$是本接口内部进行无损解压缩后的数据与原始r矩阵数据一致压缩和调用本接口的详细使用样例参考调用示例。函数原型每个算子分为两段式接口必须先调用“aclnnMatmulCompressDequantGetWorkspaceSize”接口获取计算所需workspace大小以及包含了算子计算流程的执行器再调用“aclnnMatmulCompressDequant”接口执行计算。aclnnStatus aclnnMatmulCompressDequantGetWorkspaceSize( const aclTensor* x1, const aclTensor* x2, const aclTensor* compressIndex, const aclTensor* bias, const aclTensor* deqScale, const aclTensor* offsetW, int offsetX, const aclIntArray* compressInfo, aclTensor* out, uint64_t* workspaceSize, aclOpExecutor** executor)aclnnStatus aclnnMatmulCompressDequant( void* workspace, uint64_t workspaceSize, aclOpExecutor* executor, aclrtStream stream)aclnnMatmulCompressDequantGetWorkspaceSize参数说明参数名输入/输出描述使用说明数据类型数据格式维度(shape)非连续tensorx1输入表示矩阵乘的左输入。-INT8ND2-x2输入表示压缩后的矩阵乘的右输入为通过msModelSlim工具中weight_compression模块压缩后的输入。-INT8ND1-compressIndex输入表示矩阵乘右输入的压缩索引表。通过示例中的msModelSlim工具中获取INT8ND1-bias输入参与矩阵乘计算的偏置项。支持空指针传入。INT8ND2维shape仅支持(1, n)或者(n)其中n为输出shape(m, n)的n-deqScale输入表示反量化参数。tensor中的值为float通过下述示例中转换后的UINT64的数据。UINT64ND2维shape支持(1, n)或者(1, 1), 其中n为输出shape(m, n)中的n。-offsetW输入标量表示矩阵乘右输入的偏移量。当前仅支持空指针传入。INT8-与x2_unzip一致。-offsetX输入标量表示矩阵乘左输入的偏移量。当前仅支持0。INT32---compressInfo输入整型数据列表数据类型为INT64。其中包括压缩块信息tilingN、tilingK通过msModelSlim工具中weight_compression模块压缩后获取分别表示压缩前shape(n, k)在n方向和k方向上一个基本压缩块的大小压缩前x2矩阵原始shapeshape为2维用(n, k)表示以及压缩块遍历方向的标识。-INT64---out输出计算输出。-FLOAT16ND2-workspaceSize出参返回需要在Device侧申请的workspace大小。-----executor出参返回op执行器包含了算子计算流程。-----返回值aclnnStatus返回状态码具体参见aclnn返回码。第一段接口完成入参校验出现以下场景时报错返回值错误码描述ACLNN_ERR_PARAM_NULLPTR161001传入的x1、x2或out是空指针。ACLNN_ERR_PARAM_INVALID161002x1或x2的数据类型和数据格式不在支持的范围之内。x1或x2无法做数据类型推导。推导出的数据类型无法转换为指定输出out的类型。aclnnMatmulCompressDequant参数说明参数名输入/输出描述workspace输入在Device侧申请的workspace内存地址。workspaceSize输入在Device侧申请的workspace大小由第一段接口aclnnMatmulCompressDequantGetWorkspaceSize获取。executor输入op执行器包含了算子计算流程。stream输入指定执行任务的Stream。返回值aclnnStatus返回状态码具体参见aclnn返回码。约束说明确定性计算aclnnMatmulCompressDequant默认确定性实现。调用示例准备压缩前的数据假设通过脚本gen_data.py生成输入数据示例如下仅供参考import numpy as np import os import sys from numpy import random def write2file(data, path): with open(path, wb) as f: data.tofile(f) if not os.path.exists(./data): os.mkdir(./data) if len(sys.argv) ! 4: print(Usage: python gen_data.py m k n) sys.exit(1) m int(sys.argv[1]) k int(sys.argv[2]) n int(sys.argv[3]) if m 0 or k 0 or n 0: print(Error: m, k and n must be positive integers.) sys.exit(1) # 随机生成矩阵mat1shape为(m,k ) mat1 random.randn(m, k).astype(np.int8) write2file(mat1, ./data/mat1.bin) # 随机生成矩阵mat2shape为(n, k) mat2 random.randint(0, 100, size(n, k)).astype(np.int8) np.save(./data/weight.npy, {weight: mat2}) os.chmod(./data/weight.npy, 0o0640) # 生成output output np.random.randn(m, n).astype(np.float16) write2file(output, ./data/output.bin) # 生成bias bias random.randn(n).astype(np.float32) write2file(bias, ./data/bias.bin) # 生成deq_scale deq_scale random.randn(n).astype(np.float32) write2file(deq_scale, ./data/deqScale_ori.bin) deq_scale_int64 np.fromfile(./data/deqScale_ori.bin, dtypenp.int32).astype(np.int64) deq_scale_int64.tofile(./data/deqScale.bin)执行gen_data.py假设mat1和mat2的shape入参为m512、k1024、n1024。python3 gen_data.py 512 1024 1024对数据进行预处理原始权重通过msModelSlim压缩工具生成压缩后的x2、compressIndex以及compressInfo使用以下接口时需对CANN包中msModelSlim压缩工具进行编译具体操作参考Gitee msit仓中msmodelslim/pytorch/weight_compression目录下的README.md。from msmodelslim.pytorch.weight_compression import CompressConfig, Compressor compress_config CompressConfig(do_pseudo_sparseFalse, sparse_ratio1) compressor Compressor(compress_config, weight_pathweight_path) compress_weight, compress_index, compress_info compressor.run() # 压缩后的权重对应aclnnMatmulCompressDequantGetWorkspaceSize接口的x2 compressor.export(compress_weight, ./data/weight) # 压缩权重的索引对应aclnnMatmulCompressDequantGetWorkspaceSize接口的compressIndex compressor.export(compress_index, ./data/index) # 压缩数据的相关信息对应aclnnMatmulCompressDequantGetWorkspaceSize接口的compressInfo compressor.export(compress_info, ./data/compress_info)将原始float类型的反量化参数deqscale进行转换 得到aclnn接口需要的uint64数据deqScale原始为float类型以int32读取并转换为int64import numpy as np data np.fromfile(./deqScale_original.bin, dtypenp.int32).astype(np.int64) data.tofile(./deqScale.bin)调用aclnn接口运算示例代码如下仅供参考具体编译和执行过程请参考编译与运行样例。#include iostream #include vector #include acl/acl.h #include aclnnop/aclnn_matmul_compress_dequant.h #include fstream #include unistd.h #include sys/stat.h #include stdio.h #include cstdlib #include string #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::vectorint64_t shape) { int64_t shapeSize 1; for (auto i : shape) { shapeSize * i; } return shapeSize; } int Init(int32_t deviceId, aclrtStream* stream) { // 固定写法资源初始化 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; } int ReadBinFileNNop(std::string filePath, void* buffer, size_t bufferSize) { struct stat sBuf; int fileStatus stat(filePath.data(), sBuf); CHECK_RET(fileStatus ACL_SUCCESS, LOG_PRINT(Failed to get file %s\n, filePath); return -1); std::ifstream file; file.open(filePath, std::ios::binary); CHECK_RET(file.is_open(), LOG_PRINT(Open file failed.\n); return -1); file.seekg(0, file.end); uint64_t binFileBufferLen file.tellg(); CHECK_RET(binFileBufferLen 0, std::coutFile size is 0.\n; file.close(); return -1); file.seekg(0, file.beg); file.read(static_castchar *(buffer), binFileBufferLen); file.close(); return ACL_SUCCESS; } int CreateAclTensor(std::string filePath, const std::vectorint64_t shape, int typeSize, void** deviceAddr, aclDataType dataType, aclTensor** tensor) { auto size GetShapeSize(shape) * typeSize; // 调用aclrtMalloc申请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); // 调用aclrtMallocHost申请host侧内存 void* binBufferHost nullptr; ret aclrtMallocHost(binBufferHost, size); CHECK_RET(ret ACL_SUCCESS, LOG_PRINT(aclrtMallocHost failed. ERROR: %d\n, ret); return ret); // 读取文件 ret ReadBinFileNNop(filePath, binBufferHost, size); CHECK_RET(ret ACL_SUCCESS, LOG_PRINT(ReadBinFileNNop failed. ERROR: %d\n, ret); return ret); // 调用aclrtMemcpy将host侧数据拷贝到device侧内存上 ret aclrtMemcpy(*deviceAddr, size, binBufferHost, size, ACL_MEMCPY_HOST_TO_DEVICE); CHECK_RET(ret ACL_SUCCESS, LOG_PRINT(aclrtMemcpy failed. ERROR: %d\n, ret); return ret); // 计算连续tensor的strides std::vectorint64_t strides(shape.size(), 1); for (int64_t i shape.size() - 2; i 0; i--) { strides[i] shape[i 1] * strides[i 1]; } // 调用aclCreateTensor接口创建aclTensor *tensor aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND, shape.data(), shape.size(), *deviceAddr); return 0; } int main(int argc, char* argv[]) { // 1. 固定写法device/stream初始化参考acl API手册 // 根据自己的实际device填写deviceId 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); if (argc ! 6) { std::cerr Error: Invalid number of arguments. Usage: program m k n wCompressedSize indexSize std::endl; return -1; } // 2. 构造输入与输出需要根据API的接口自定义构造 int m atoi(argv[1]); int k atoi(argv[2]); int n atoi(argv[3]); // wShape是右矩阵压缩后数据的大小 int wCompressedSize atoi(argv[4]); // indexShape是压缩索引数据的大小 int indexSize atoi(argv[5]); if (m 0 || k 0 || n 0 || wCompressedSize 0 || indexSize 0) { std::cerr Error: m, k, n, wCompressedSize and indexSize must be positive integers. std::endl; return -1; } std::vectorint64_t mat1Shape {m, k}; std::vectorint64_t mat2CompressedShape {wCompressedSize}; std::vectorint64_t indexShape {indexSize}; std::vectorint64_t biasShape {n}; std::vectorint64_t deqScaleShape {n}; std::vectorint64_t outputShape {m, n}; std::vectorint64_t compressInfoHostData {8, 8, k, n, 1}; void* mat1DeviceAddr nullptr; void* mat2CompressedDeviceAddr nullptr; void* indexDeviceAddr nullptr; void* biasDeviceAddr nullptr; void* deqScaleDeviceAddr nullptr; void* outputDeviceAddr nullptr; aclTensor* mat1 nullptr; aclTensor* mat2Compressed nullptr; aclTensor* index nullptr; aclTensor* bias nullptr; aclTensor* deqScale nullptr; aclTensor* output nullptr; aclIntArray* compressInfo nullptr; std::string rootPath ./data/; // 创建mat1 aclTensor std::string mat1FilePath rootPath mat1.bin; ret CreateAclTensor(mat1FilePath, mat1Shape, sizeof(int8_t), mat1DeviceAddr, aclDataType::ACL_INT8, mat1); CHECK_RET(ret ACL_SUCCESS, LOG_PRINT(Create mat1 tensor failed. ERROR: %d\n, ret); return ret); // 创建mat2Compressed aclTensor std::string mat2FilePath rootPath weight/weight.dat; ret CreateAclTensor(mat2FilePath, mat2CompressedShape, sizeof(int8_t), mat2CompressedDeviceAddr, aclDataType::ACL_INT8, mat2Compressed); CHECK_RET(ret ACL_SUCCESS, LOG_PRINT(Create mat2 tensor failed. ERROR: %d\n, ret); return ret); // 创建index aclTensor std::string indexFilePath rootPath index/weight.dat; ret CreateAclTensor(indexFilePath, indexShape, sizeof(int8_t), indexDeviceAddr, aclDataType::ACL_INT8, index); CHECK_RET(ret ACL_SUCCESS, LOG_PRINT(Create index tensor failed. ERROR: %d\n, ret); return ret); // 创建bias aclTensor std::string biasFilePath rootPath bias.bin; ret CreateAclTensor(biasFilePath, biasShape, sizeof(int32_t), biasDeviceAddr, aclDataType::ACL_INT32, bias); CHECK_RET(ret ACL_SUCCESS, LOG_PRINT(Create bias tensor failed. ERROR: %d\n, ret); return ret); // 创建deqScale aclTensor std::string deqScaleFilePath rootPath deqScale.bin; ret CreateAclTensor(deqScaleFilePath, deqScaleShape, sizeof(int32_t), deqScaleDeviceAddr, aclDataType::ACL_UINT64, deqScale); CHECK_RET(ret ACL_SUCCESS, LOG_PRINT(Create deqScale tensor failed. ERROR: %d\n, ret); return ret); // 创建compressInfo compressInfo aclCreateIntArray(compressInfoHostData.data(), aclDataType::ACL_INT64); // 创建out aclTensor std::string outputFilePath rootPath output.bin; ret CreateAclTensor(outputFilePath, outputShape, 2, outputDeviceAddr, aclDataType::ACL_FLOAT16, output); CHECK_RET(ret ACL_SUCCESS, LOG_PRINT(Create output tensor failed. ERROR: %d\n, ret); return ret); int32_t offsetX 0; // 3. 调用CANN算子库API需要修改为具体的Api名称 uint64_t workspaceSize 0; aclOpExecutor* executor; // 调用aclnnMm第一段接口 ret aclnnMatmulCompressDequantGetWorkspaceSize(mat1, mat2Compressed, index, bias, deqScale, nullptr, offsetX, compressInfo, output, workspaceSize, executor); CHECK_RET(ret ACL_SUCCESS, LOG_PRINT(aclnnMatmulCompressDequantGetWorkspaceSize failed. ERROR: %d\n, ret); return ret); // 根据第一段接口计算出的workspaceSize申请device内存 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); } // 调用aclnnMm第二段接口 ret aclnnMatmulCompressDequant(workspaceAddr, workspaceSize, executor, stream); CHECK_RET(ret ACL_SUCCESS, LOG_PRINT(aclnnMatmulCompressDequant failed. ERROR: %d\n, ret); return ret); // 4. 固定写法同步等待任务执行结束 ret aclrtSynchronizeStream(stream); CHECK_RET(ret ACL_SUCCESS, LOG_PRINT(aclrtSynchronizeStream failed. ERROR: %d\n, ret); return ret); // 5. 获取输出的值将device侧内存上的结果拷贝至host侧需要根据具体API的接口定义修改 auto size GetShapeSize(outputShape); std::vectorfloat resultData(size, 0); ret aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), outputDeviceAddr, 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 size; i) { LOG_PRINT(result[%ld] is: %f\n, i, resultData[i]); } // 6. 释放aclTensor和aclScalar需要根据具体API的接口定义修改 aclDestroyTensor(mat1); aclDestroyTensor(mat2Compressed); aclDestroyTensor(index); aclDestroyTensor(bias); aclDestroyTensor(deqScale); aclDestroyTensor(output); aclDestroyIntArray(compressInfo); // 7.释放硬件资源需要根据具体API的接口定义修改 aclrtFree(mat1DeviceAddr); aclrtFree(mat2CompressedDeviceAddr); aclrtFree(indexDeviceAddr); aclrtFree(biasDeviceAddr); aclrtFree(deqScaleDeviceAddr); aclrtFree(outputDeviceAddr); if (workspaceSize 0) { aclrtFree(workspaceAddr); } aclrtDestroyStream(stream); aclrtResetDevice(deviceId); aclFinalize(); return 0; }【免费下载链接】ops-math本项目是CANN提供的数学类基础计算算子库实现网络在NPU上加速计算。项目地址: https://gitcode.com/cann/ops-math创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考