CANN/ge:执行动态Shape算子示例代码
发布时间:2026/9/10 6:12:11 锦皓数字建站

执行动态Shape算子示例代码【免费下载链接】geGEGraph Engine是面向昇腾的图编译器和执行器提供了计算图优化、多流并行、内存复用和模型下沉等技术手段加速模型执行效率减少模型内存占用。 GE 提供对 PyTorch、TensorFlow 前端的友好接入能力并同时支持 onnx、pb 等主流模型格式的解析与编译。项目地址: https://gitcode.com/cann/ge本节介绍基于单算子模型执行的方式调用动态Shape算子的关键接口、示例代码。基本原理对于支持动态Shape的算子如果算子输出Shape明确时该类算子执行的基本流程与固定Shape算子执行类似接口调用流程请参见单算子模型执行总体说明执行固定Shape算子的示例代码请参见执行固定Shape算子示例代码。如果无法明确算子的输出Shape时在调用aclopExecuteV2接口前需用户调用aclopInferShape接口、aclGetTensorDescNumDims接口、aclGetTensorDescDimV2接口、aclGetTensorDescDimRange等接口推导或预估算子的输出Shape作为算子执行接口aclopExecuteV2的输入。aclopInferShape接口处算子输入tensor数据的内存必须根据应用运行模式来确定应用运行在Host时此处需申请Host上的内存应用运行在Device时此处需申请Device上的内存。示例代码以下是关键步骤的代码示例不能直接拷贝编译运行仅供参考。调用接口后需增加异常处理的分支并记录报错日志、提示日志此处不一一列举。// ...... const char *opType; int numInputs; aclTensorDesc *inputDesc[2]; aclDataBuffer *inputs[2]; int numOutputs; aclTensorDesc *outputDesc[1]; aclopAttr *attr; aclError ret aclopInferShape(opType, numInputs, inputDesc, inputs, numOutputs, outputDesc, attr); std::vectorstd::vectorint64_t tensorDims; // inferShape之后的输出tensor的Shape // 循环算子的每一个输出推导或预估Shape值 for (int index 0; index numOutputs; index) { std::vectorint64_t dimSize; // 表示执行算子时输出的shape size_t dimNums aclGetTensorDescNumDims(outputDesc[index]); // 表示动态Shape场景下维度个数未知该场景预留 if (dimNums ACL_UNKNOWN_RANK) { // 由用户预估最大Shape值max shape dimSize.push_back(max_shape); } else { for (size_t i 0; i dimNums; i) { int64_t dim; ret aclGetTensorDescDimV2(outputDesc[index], i, dim); // 表示动态Shape场景下维度值是动态的 if(dim -1) { int64_t dimRange[2]; // 获取Shape范围使用该范围中的Shape最大值来构造输出tensorDesc作为aclopExecuteV2的输入 ret aclGetTensorDescDimRange(outputDesc[index], i, 2, dimRange); dim dimRange[1]; } dimSize.push_back(dim); } } tensorDims.push_back(dimSize); } // 构造算子输入tensorDesc和输入tensor作为aclopExecuteV2的输入 aclTensorDesc *inputDescNew[2]; aclDataBuffer *inputsNew[2]; aclDataBuffer *outputsNew[1]; // 以上给出了执行算子时输出的Shape, 根据tensorDims中的dims构造输出tensorDesc即outputDescNew参数值, 用于调用aclopExecuteV2 ret aclopExecuteV2(opType, numInputs, inputDescNew, inputsNew, numOutputs, outputDescNew, outputsNew, attr, stream); // 针对上面用户预估Shape值以及使用Shape范围中的最大Shape的场景在算子执行结束后需增加下面的调用获取准确的Shape // for 循环每一个输出的tensorDesc std::vectorstd::vectorint64_t outTensorDims; // 准确的输出tensorShape for (int index 0; index numOutputs; index) { std::vectorint64_t dimSize; int dimNums aclGetTensorDescNumDims(outputDescNew[index]); for (int i 0; i dimNums; i){ int64_t dim; ret aclGetTensorDescDimV2(outputDescNew[index], i, dim); dimSize.push_back(dim); } outTensorDims.push_back(dimSize); } // ......【免费下载链接】geGEGraph Engine是面向昇腾的图编译器和执行器提供了计算图优化、多流并行、内存复用和模型下沉等技术手段加速模型执行效率减少模型内存占用。 GE 提供对 PyTorch、TensorFlow 前端的友好接入能力并同时支持 onnx、pb 等主流模型格式的解析与编译。项目地址: https://gitcode.com/cann/ge创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
锦
锦皓数字建站
深耕本土企业品牌数字化升级,专注原创端正雅致商务官网,从视觉设计到稳定运维全程保驾护航。