You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

ge_generator.cc 49 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153
  1. /**
  2. * Copyright 2020 Huawei Technologies Co., Ltd
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "generator/ge_generator.h"
  17. #include <atomic>
  18. #include "common/ge/ge_util.h"
  19. #include "common/ge/plugin_manager.h"
  20. #include "common/helper/model_helper.h"
  21. #include "common/helper/om_file_helper.h"
  22. #include "common/util.h"
  23. #include "common/util/error_manager/error_manager.h"
  24. #include "framework/common/debug/ge_log.h"
  25. #include "framework/common/debug/log.h"
  26. #include "ge/ge_api.h"
  27. #include "graph/debug/ge_attr_define.h"
  28. #include "graph/ge_context.h"
  29. #include "graph/manager/graph_manager.h"
  30. #include "graph/manager/util/rt_context_util.h"
  31. #include "graph/opsproto_manager.h"
  32. #include "graph/utils/graph_utils.h"
  33. #include "graph/utils/type_utils.h"
  34. #include "init/gelib.h"
  35. #include "model/ge_model.h"
  36. #include "analyzer/analyzer.h"
  37. using std::map;
  38. using std::string;
  39. using std::vector;
  40. namespace {
  41. const char *const kAttrOpType = "op_type";
  42. const char *const kEngineNameDefault = "default";
  43. const char *const kVectorEngine = "VectorEngine";
  44. const char *const kAIcoreEngine = "AIcoreEngine";
  45. const char *const kFileNameSuffix = "online";
  46. const char *const kAicpuAllshape = "_AllShape";
  47. constexpr char const *kAttrSupportDynamicShape = "support_dynamicshape";
  48. const int64_t kDynamicDimValue = -2;
  49. const int kDefaultDeviceId = 0;
  50. const int kDefaultJobId = 0;
  51. const int32_t kFuzzBuildPattern = 1;
  52. std::map<ge::OpEngineType, std::string> engine_type_map{
  53. {ge::ENGINE_SYS, kEngineNameDefault},
  54. {ge::ENGINE_AICORE, kAIcoreEngine},
  55. {ge::ENGINE_VECTOR, kVectorEngine}};
  56. bool ContainsDynamicInpus(const ge::OpDesc &op_desc) {
  57. for (auto &tensor_desc : op_desc.GetAllInputsDescPtr()) {
  58. if (tensor_desc->MutableShape().IsUnknownShape()) {
  59. GELOGI("Contains unknown shape input. set is_dynamic_input to true.");
  60. return true;
  61. }
  62. }
  63. return false;
  64. }
  65. // if optional in/out, format is format_reserved and dtype is dt_undefined
  66. bool IsOptional(const ge::GeTensorDesc &tensor_desc) {
  67. return tensor_desc.GetFormat() == ge::FORMAT_RESERVED && tensor_desc.GetDataType() == ge::DT_UNDEFINED;
  68. }
  69. } // namespace
  70. namespace ge {
  71. static Status CheckEngineTypeSupport(const NodePtr &node, OpEngineType engine_type) {
  72. const OpDescPtr &op_desc = node->GetOpDesc();
  73. GE_CHECK_NOTNULL_EXEC(op_desc, return PARAM_INVALID);
  74. if (engine_type == ENGINE_SYS) {
  75. GELOGI("CheckEngineType: use default engine.");
  76. return SUCCESS;
  77. }
  78. // get op engine name
  79. string op_engine_name;
  80. auto iter = engine_type_map.find(engine_type);
  81. if (iter != engine_type_map.end()) {
  82. op_engine_name = iter->second;
  83. GELOGI("CheckEngineType: engine type: %d", static_cast<int>(engine_type));
  84. } else {
  85. ErrorManager::GetInstance().ATCReportErrMessage("E14001", {"opname", "optype", "value", "reason"},
  86. {op_desc->GetName(), op_desc->GetType(), "engine type",
  87. "it only support default/AIcoreEngine/VectorEngine"});
  88. GELOGE(FAILED, "[Check][Param] value:%d not support, "
  89. "only support default/AIcoreEngine/VectorEngine now", static_cast<int>(engine_type));
  90. return FAILED;
  91. }
  92. if (op_desc->HasAttr(ATTR_NAME_UNREGST_OPPATH)) {
  93. op_desc->SetOpEngineName(op_engine_name);
  94. op_desc->SetOpKernelLibName(op_engine_name);
  95. return SUCCESS;
  96. }
  97. // set op engine name and opkernelLib. when engine support
  98. std::shared_ptr<GELib> instance_ptr = ge::GELib::GetInstance();
  99. if ((instance_ptr == nullptr) || (!instance_ptr->InitFlag())) {
  100. REPORT_INNER_ERROR("E19999", "get gelib failed, as get instance failed or initflag failed.");
  101. GELOGE(GE_CLI_GE_NOT_INITIALIZED, "[Get][GELib] CheckEngineType failed, as get gelib failed.");
  102. return FAILED;
  103. }
  104. OpsKernelManager &ops_kernel_manager = instance_ptr->OpsKernelManagerObj();
  105. std::vector<OpInfo> op_infos = ops_kernel_manager.GetOpsKernelInfo(op_desc->GetType());
  106. if (op_infos.empty()) {
  107. ErrorManager::GetInstance().ATCReportErrMessage("E14001", {"opname", "optype", "value", "reason"},
  108. {op_desc->GetName(), op_desc->GetType(), "optype", "it can not find"});
  109. GELOGE(FAILED, "[Get][OpInfo] by op type %s failed.", op_desc->GetType().c_str());
  110. return FAILED;
  111. }
  112. string kernel_name;
  113. for (const auto &it : op_infos) {
  114. if (it.engine == op_engine_name) {
  115. kernel_name = it.opKernelLib;
  116. break;
  117. }
  118. }
  119. if (kernel_name.empty()) {
  120. ErrorManager::GetInstance().ATCReportErrMessage("E14001", {"opname", "optype", "value", "reason"},
  121. {op_desc->GetName(), op_desc->GetType(), "engine name" + FmtToStr(op_engine_name), "it can not find"});
  122. GELOGE(FAILED, "[Check][Param] Can not find ops kernel, engine name:%s. op:%s(%s)",
  123. op_engine_name.c_str(), op_desc->GetName().c_str(), op_desc->GetType().c_str());
  124. return FAILED;
  125. }
  126. auto &kernel_map = ops_kernel_manager.GetAllOpsKernelInfoStores();
  127. auto kernel_info_store = kernel_map.find(kernel_name);
  128. if (kernel_info_store != kernel_map.end()) {
  129. std::string unsupported_reason;
  130. if (kernel_info_store->second->CheckSupported(node, unsupported_reason)) {
  131. op_desc->SetOpEngineName(op_engine_name);
  132. op_desc->SetOpKernelLibName(kernel_name);
  133. GELOGI("CheckEngineType:Set OpKernelLibName %s and engine name %s into op_desc %s", kernel_name.c_str(),
  134. op_engine_name.c_str(), op_desc->GetName().c_str());
  135. return SUCCESS;
  136. } else {
  137. ErrorManager::GetInstance().ATCReportErrMessage(
  138. "E13002", {"optype", "opskernel", "reason"}, {op_desc->GetType(), kernel_name, unsupported_reason});
  139. GELOGE(FAILED, "[Call][CheckSupported] failed, Op type %s of ops kernel %s is unsupported, reason:%s",
  140. op_desc->GetType().c_str(), kernel_name.c_str(), unsupported_reason.c_str());
  141. return FAILED;
  142. }
  143. } else {
  144. ErrorManager::GetInstance().ATCReportErrMessage(
  145. "E13003", {"opname", "optype"}, {op_desc->GetName(), op_desc->GetType()});
  146. GELOGE(FAILED, "[Check][Param] Can not find any supported ops kernel info store by kernel_name %s,"
  147. "op type is %s, op name is %s",
  148. kernel_name.c_str(), op_desc->GetType().c_str(), op_desc->GetName().c_str());
  149. }
  150. return FAILED;
  151. }
  152. static Status AddInputs(const ComputeGraphPtr &graph, const NodePtr &node, const GeTensorDesc &tensor, int32_t index,
  153. bool attr, int32_t &data_index) {
  154. GE_CHECK_NOTNULL_EXEC(graph, return PARAM_INVALID);
  155. GE_CHECK_NOTNULL_EXEC(node, return PARAM_INVALID);
  156. auto format = tensor.GetFormat();
  157. auto data_type = tensor.GetDataType();
  158. if (format == FORMAT_RESERVED && data_type == DT_UNDEFINED) {
  159. return SUCCESS;
  160. }
  161. string op_type;
  162. bool is_const = false;
  163. (void)AttrUtils::GetBool(tensor, CONST_ATTR_NAME_INPUT, is_const);
  164. if (is_const) {
  165. GELOGD("Get input[%d] is const", index);
  166. op_type = CONSTANTOP;
  167. } else if (!AttrUtils::GetStr(tensor, kAttrOpType, op_type) || op_type.empty()) {
  168. op_type = DATA;
  169. }
  170. string op_name = node->GetName() + "_in_" + std::to_string(index);
  171. OpDescPtr data_op = MakeShared<ge::OpDesc>(op_name, op_type);
  172. if (data_op == nullptr) {
  173. REPORT_CALL_ERROR("E19999", "create OpDesc failed, name:%s", op_name.c_str());
  174. GELOGE(FAILED, "[Create][OpDesc] failed, name:%s", op_name.c_str());
  175. return FAILED;
  176. }
  177. if (is_const) {
  178. ConstGeTensorPtr tensor_value;
  179. if (!AttrUtils::GetTensor(tensor, ge::ATTR_NAME_WEIGHTS, tensor_value)) {
  180. REPORT_CALL_ERROR("E19999", "get attr %s failed, tensor:%s.",
  181. ge::ATTR_NAME_WEIGHTS.c_str(), tensor.GetName().c_str());
  182. GELOGE(FAILED, "[Get][Attr] %s failed, tensor:%s.", ge::ATTR_NAME_WEIGHTS.c_str(), tensor.GetName().c_str());
  183. return FAILED;
  184. }
  185. if (!AttrUtils::SetTensor(data_op, ge::ATTR_NAME_WEIGHTS, tensor_value)) {
  186. REPORT_CALL_ERROR("E19999", "set attr %s failed, op:%s.", ge::ATTR_NAME_WEIGHTS.c_str(), op_name.c_str());
  187. GELOGE(FAILED, "[Set][Attr] %s failed, op:%s.", ge::ATTR_NAME_WEIGHTS.c_str(), op_name.c_str());
  188. return FAILED;
  189. }
  190. }
  191. (void)AttrUtils::SetBool(data_op, "_is_single_op", true);
  192. GE_CHK_BOOL_EXEC(data_op->AddInputDesc(tensor) == GRAPH_SUCCESS,
  193. REPORT_CALL_ERROR("E19999", "AddInputDesc failed for node:%s", data_op->GetName().c_str());
  194. return FAILED, "[Add][InputDesc] fail for node:%s", data_op->GetName().c_str());
  195. GE_CHK_BOOL_EXEC(data_op->AddOutputDesc(tensor) == GRAPH_SUCCESS,
  196. REPORT_CALL_ERROR("E19999", "AddOutputDesc failed for node:%s", data_op->GetName().c_str());
  197. return FAILED, "[Add][OutputDesc] fail for node:%s", data_op->GetName().c_str());
  198. if (attr && !is_const) {
  199. GE_CHK_BOOL_EXEC(AttrUtils::SetInt(data_op, ATTR_NAME_INDEX, data_index),
  200. REPORT_CALL_ERROR("E19999", "set attr %s failed for node:%s",
  201. ATTR_NAME_INDEX.c_str(), data_op->GetName().c_str());
  202. return FAILED,
  203. "[Set][Attr:%s] fail for node:%s", ATTR_NAME_INDEX.c_str(), data_op->GetName().c_str());
  204. ++data_index;
  205. }
  206. ge::NodePtr arg_node = graph->AddNode(data_op);
  207. GE_CHK_BOOL_EXEC(arg_node != nullptr,
  208. REPORT_CALL_ERROR("E19999", "add node:%s to graph:%s failed", data_op->GetName().c_str(),
  209. graph->GetName().c_str());
  210. return FAILED, "[Add][Node] Insert Data node:%s fail", data_op->GetName().c_str());
  211. GE_CHK_STATUS(GraphUtils::AddEdge(arg_node->GetOutDataAnchor(0), node->GetInDataAnchor(index)),
  212. "[Add][Edge]fail from node:%s to node:%s", data_op->GetName().c_str(), node->GetName().c_str());
  213. return SUCCESS;
  214. }
  215. static Status AddOutputs(const ComputeGraphPtr &graph, const NodePtr &node, const vector<GeTensor> &outputs) {
  216. OpDescPtr op_desc = MakeShared<ge::OpDesc>(graph->GetName() + "_" + NODE_NAME_NET_OUTPUT, NETOUTPUT);
  217. if (op_desc == nullptr) {
  218. REPORT_CALL_ERROR("E19999", "create OpDesc failed, graph:%s", graph->GetName().c_str());
  219. GELOGE(FAILED, "[Create][OpDesc] failed, graph:%s", graph->GetName().c_str());
  220. return FAILED;
  221. }
  222. (void)AttrUtils::SetBool(op_desc, "_is_single_op", true);
  223. int32_t count = 0;
  224. for (const auto &out_desc : outputs) {
  225. GeTensorDesc tensor = out_desc.GetTensorDesc();
  226. TensorUtils::SetInputTensor(tensor, true);
  227. GE_CHK_BOOL_EXEC(op_desc->AddInputDesc(tensor) == GRAPH_SUCCESS,
  228. REPORT_CALL_ERROR("E19999", "AddInputDesc failed for node:%s", op_desc->GetName().c_str());
  229. return FAILED, "[Add][InputDesc]fail for node:%s", op_desc->GetName().c_str());
  230. TensorUtils::SetInputTensor(tensor, false);
  231. TensorUtils::SetOutputTensor(tensor, true);
  232. GE_CHK_BOOL_EXEC(op_desc->AddOutputDesc(tensor) == GRAPH_SUCCESS,
  233. REPORT_CALL_ERROR("E19999", "AddOutputDesc failed for node:%s", op_desc->GetName().c_str());
  234. return FAILED, "[Add][OutputDesc]fail for node:%s", op_desc->GetName().c_str());
  235. count++;
  236. }
  237. GE_CHECK_NOTNULL_EXEC(graph, return PARAM_INVALID);
  238. ge::NodePtr out_node = graph->AddNode(op_desc);
  239. GE_CHK_BOOL_EXEC(out_node != nullptr,
  240. REPORT_CALL_ERROR("E19999", "add node:%s to graph:%u failed.",
  241. op_desc->GetName().c_str(), graph->GetGraphID());
  242. return FAILED,
  243. "[Add][Node:%s]fail in graph:%u", op_desc->GetName().c_str(), graph->GetGraphID());
  244. GE_CHECK_NOTNULL_EXEC(node, return PARAM_INVALID);
  245. for (int32_t i = 0; i < count; ++i) {
  246. GE_CHK_STATUS(GraphUtils::AddEdge(node->GetOutDataAnchor(i), out_node->GetInDataAnchor(i)),
  247. "[Add][Edge]fail from node:%s to node:%s", node->GetName().c_str(), out_node->GetName().c_str());
  248. }
  249. return SUCCESS;
  250. }
  251. static void GetOpsProtoPath(string &opsproto_path) {
  252. const char *path_env = std::getenv("ASCEND_OPP_PATH");
  253. if (path_env != nullptr) {
  254. string path = path_env;
  255. string file_path = RealPath(path.c_str());
  256. if (file_path.empty()) {
  257. REPORT_CALL_ERROR("E19999", "File path %s is invalid.", path.c_str());
  258. GELOGE(FAILED, "[Call][RealPath] File path %s is invalid.", path.c_str());
  259. return;
  260. }
  261. opsproto_path = (path + "/op_proto/custom/" + ":") + (path + "/op_proto/built-in/");
  262. GELOGI("Get opsproto so path from env : %s", path.c_str());
  263. return;
  264. }
  265. string path_base = PluginManager::GetPath();
  266. GELOGI("path_base is %s", path_base.c_str());
  267. path_base = path_base.substr(0, path_base.rfind('/'));
  268. path_base = path_base.substr(0, path_base.rfind('/') + 1);
  269. opsproto_path = (path_base + "ops/op_proto/custom/" + ":") + (path_base + "ops/op_proto/built-in/");
  270. }
  271. static Status ResetTensorVecShape(const vector<GeTensor> &inputs, vector<GeTensor> &inputs_dynamic) {
  272. for (auto input : inputs) {
  273. auto input_desc = input.GetTensorDesc();
  274. GeShape shape_ori = input_desc.GetShape();
  275. std::vector<int64_t> dynamic_shape_dims = {kDynamicDimValue};
  276. GeShape dynamic_shape(dynamic_shape_dims);
  277. std::vector<std::pair<int64_t, int64_t>> dynamic_shape_range;
  278. ge::GeTensor inputTensor;
  279. ge::GeTensorDesc desc(input_desc);
  280. bool is_const = false;
  281. (void)AttrUtils::GetBool(input_desc, CONST_ATTR_NAME_INPUT, is_const);
  282. if (!is_const) {
  283. int64_t storage_format = FORMAT_NCHW;
  284. if (ge::AttrUtils::GetInt(desc, ge::ATTR_NAME_STORAGE_FORMAT, storage_format) &&
  285. !ge::AttrUtils::SetListInt(desc, ge::ATTR_NAME_STORAGE_SHAPE, dynamic_shape_dims)) {
  286. REPORT_CALL_ERROR("E19999", "Set attr ATTR_NAME_STORAGE_SHAPE failed to op:%s.", desc.GetName().c_str());
  287. GELOGE(FAILED, "[Set][Attr] ATTR_NAME_STORAGE_SHAPE fail.");
  288. return FAILED;
  289. }
  290. desc.SetShape(dynamic_shape);
  291. desc.SetShapeRange(dynamic_shape_range);
  292. }
  293. inputTensor.SetTensorDesc(desc);
  294. inputs_dynamic.push_back(inputTensor);
  295. }
  296. return SUCCESS;
  297. }
  298. static Status GetFuzzBuildAttrs(const OpDescPtr &op_desc, const GeRootModelPtr &ge_root_model,
  299. GeAttrValue::LIST_NAMED_ATTRS &fuzz_build_attrs) {
  300. GELOGD("Start get fuzz build attrs of %s.", op_desc->GetName().c_str());
  301. GE_CHECK_NOTNULL(ge_root_model->GetRootGraph());
  302. for (const auto &node : ge_root_model->GetRootGraph()->GetAllNodes()) {
  303. GE_CHECK_NOTNULL(node);
  304. GE_CHECK_NOTNULL(node->GetOpDesc());
  305. GELOGD("Delete fuzz build attr of %s after build.", node->GetName().c_str());
  306. node->GetOpDesc()->DelAttr(ATTR_NAME_FUZZ_BUILD);
  307. }
  308. (void)AttrUtils::GetListNamedAttrs(op_desc, ATTR_NAME_FUZZ_BUILD_RES_ATTRS, fuzz_build_attrs);
  309. if (!fuzz_build_attrs.empty()) {
  310. GELOGD("%s has split, get ATTR_NAME_FUZZ_BUILD_RES_ATTRS directly.", op_desc->GetName().c_str());
  311. return SUCCESS;
  312. } else {
  313. GELOGW("%s build with fuzz build pattern, but not set ATTR_NAME_FUZZ_BUILD_RES_ATTRS.", op_desc->GetName().c_str());
  314. }
  315. return SUCCESS;
  316. }
  317. static bool HasShapeRange(const vector<GeTensor> &inputs) {
  318. for (const auto &input : inputs) {
  319. vector<pair<int64_t, int64_t>> shape_range;
  320. (void)input.GetTensorDesc().GetShapeRange(shape_range);
  321. if (!shape_range.empty()) {
  322. GELOGD("Has set shape range.");
  323. return true;
  324. }
  325. }
  326. return false;
  327. }
  328. class GeGenerator::Impl {
  329. public:
  330. Impl(OmgContext &omg_context) : omg_context_(omg_context) {}
  331. ~Impl() = default;
  332. Status BuildModel(const Graph &graph, const vector<GeTensor> &inputs, GeRootModelPtr &ge_models);
  333. Status SaveModel(const string &file_name_prefix, GeModelPtr &models, ModelBufferData &model);
  334. Status SaveRootModel(const string &file_name_prefix, GeRootModelPtr &model, ModelBufferData &model_buff);
  335. Status SaveParams(GeModelPtr &ge_model, const string &type, const map<string, GeAttrValue> &attrs,
  336. const vector<GeTensor> &inputs, const vector<GeTensor> &outputs);
  337. Status GenerateInfershapeGraph(const Graph &graph);
  338. OmgContext &omg_context_;
  339. GraphManager graph_manager_;
  340. SaveParam save_param_;
  341. bool is_offline_ = true;
  342. bool is_singleop_unregistered_ = false;
  343. std::string build_mode_;
  344. std::string build_step_;
  345. static std::mutex mutex_;
  346. private:
  347. static std::string Trim(const std::string &str);
  348. bool ParseVersion(const std::string &line, std::string &version);
  349. bool GetVersionFromPath(const std::string &file_path, std::string &version);
  350. bool SetAtcVersionInfo(AttrHolder &obj);
  351. bool SetOppVersionInfo(AttrHolder &obj);
  352. bool SetOmSystemInfo(AttrHolder &obj);
  353. };
  354. Status GeGenerator::Initialize(const map<string, string> &options) {
  355. return Initialize(options, domi::GetContext());
  356. }
  357. Status GeGenerator::Initialize(const map<string, string> &options, OmgContext &omg_context) {
  358. impl_ = ge::MakeShared<Impl>(omg_context);
  359. if (impl_ == nullptr) {
  360. REPORT_CALL_ERROR("E19999", "create Impl failed.");
  361. GELOGE(MEMALLOC_FAILED, "[Create][Impl] Make shared failed");
  362. return MEMALLOC_FAILED;
  363. }
  364. ErrorManager::GetInstance().SetStage(error_message::kInitialize, error_message::kOpsProtoInit);
  365. string opsproto_path;
  366. GetOpsProtoPath(opsproto_path);
  367. GELOGI("Get opsproto path is %s", opsproto_path.c_str());
  368. OpsProtoManager *manager = OpsProtoManager::Instance();
  369. map<string, string> option_tmp;
  370. option_tmp.emplace(std::pair<string, string>(string("ge.opsProtoLibPath"), opsproto_path));
  371. (void)manager->Initialize(option_tmp);
  372. Status ret = impl_->graph_manager_.Initialize(options);
  373. if (ret != SUCCESS) {
  374. GELOGE(GE_GENERATOR_GRAPH_MANAGER_INIT_FAILED, "[Call][Initialize] Graph manager initialize failed.");
  375. return GE_GENERATOR_GRAPH_MANAGER_INIT_FAILED;
  376. }
  377. // get ek file
  378. auto iter = options.find(EK_FILE);
  379. if (iter != options.end()) {
  380. impl_->save_param_.ek_file = iter->second;
  381. }
  382. // get cert file
  383. iter = options.find(CERT_FILE);
  384. if (iter != options.end()) {
  385. impl_->save_param_.cert_file = iter->second;
  386. }
  387. // get hw key file
  388. iter = options.find(HW_KEY_FILE);
  389. if (iter != options.end()) {
  390. impl_->save_param_.hw_key_file = iter->second;
  391. }
  392. // get private file
  393. iter = options.find(PRIVATE_KEY_FILE);
  394. if (iter != options.end()) {
  395. impl_->save_param_.pri_key_file = iter->second;
  396. }
  397. // get build mode
  398. iter = options.find(BUILD_MODE);
  399. if (iter != options.end()) {
  400. impl_->build_mode_ = iter->second;
  401. }
  402. // get build step
  403. iter = options.find(BUILD_STEP);
  404. if (iter != options.end()) {
  405. impl_->build_step_ = iter->second;
  406. }
  407. return SUCCESS;
  408. }
  409. Status GeGenerator::Finalize() {
  410. ErrorManager::GetInstance().SetStage(error_message::kFinalize, error_message::kFinalize);
  411. GE_CHECK_NOTNULL_EXEC(impl_, return PARAM_INVALID);
  412. Status ret = impl_->graph_manager_.Finalize();
  413. if (ret != SUCCESS) {
  414. GELOGE(GE_GENERATOR_GRAPH_MANAGER_FINALIZE_FAILED, "[Call][Finalize] Graph manager finalize failed.");
  415. return GE_GENERATOR_GRAPH_MANAGER_FINALIZE_FAILED;
  416. }
  417. return SUCCESS;
  418. }
  419. Status GeGenerator::GenerateOfflineModel(const Graph &graph, const string &file_name_prefix,
  420. const vector<GeTensor> &inputs) {
  421. ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther);
  422. GELOGI("Start to generate offline model.");
  423. ModelBufferData model;
  424. return GenerateModel(graph, file_name_prefix, inputs, model, true);
  425. }
  426. Status GeGenerator::GenerateOnlineModel(const Graph &graph, const vector<GeTensor> &inputs, ModelBufferData &model) {
  427. ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther);
  428. return GenerateModel(graph, "online", inputs, model, false);
  429. }
  430. Status GeGenerator::GenerateInfershapeGraph(const Graph &graph) {
  431. GE_CHECK_NOTNULL_EXEC(impl_, return PARAM_INVALID);
  432. Status ret = impl_->GenerateInfershapeGraph(graph);
  433. if (ret != SUCCESS) {
  434. GELOGE(ret, "[Call][GenerateInfershapeGraph] Dump infershape json failed");
  435. if (impl_->graph_manager_.Finalize() != SUCCESS) {
  436. GELOGE(FAILED, "[Call][Finalize] graph_manager finalize fail.");
  437. }
  438. return ret;
  439. }
  440. GELOGI("Generate infer shape graph success");
  441. return SUCCESS;
  442. }
  443. std::mutex GeGenerator::Impl::mutex_;
  444. // Remove the space and tab before and after the string
  445. std::string GeGenerator::Impl::Trim(const std::string &str) {
  446. if (str.empty()) {
  447. return str;
  448. }
  449. std::string::size_type start = str.find_first_not_of(" \t\r\n");
  450. if (start == std::string::npos) {
  451. return str;
  452. }
  453. std::string::size_type end = str.find_last_not_of(" \t\r\n") + 1;
  454. return str.substr(start, end);
  455. }
  456. // Parsing the command line
  457. bool GeGenerator::Impl::ParseVersion(const std::string &line, std::string &version) {
  458. std::string flag = "Version=";
  459. std::string temp = Trim(line);
  460. if (temp.empty()) {
  461. GELOGW("line is empty.");
  462. return false;
  463. }
  464. std::string::size_type pos = temp.find(flag);
  465. if (pos == std::string::npos) {
  466. GELOGW("Incorrect line [%s], it must include [%s].", line.c_str(), flag.c_str());
  467. return false;
  468. }
  469. if (temp.size() == flag.size()) {
  470. GELOGW("version information is empty. %s", line.c_str());
  471. return false;
  472. }
  473. version = temp.substr(pos + flag.size());
  474. return true;
  475. }
  476. bool GeGenerator::Impl::GetVersionFromPath(const std::string &file_path, std::string &version) {
  477. // Normalize the path
  478. string resolved_file_path = RealPath(file_path.c_str());
  479. if (resolved_file_path.empty()) {
  480. GELOGW("Invalid input file path [%s], make sure that the file path is correct.", file_path.c_str());
  481. return false;
  482. }
  483. std::ifstream fs(resolved_file_path, std::ifstream::in);
  484. if (!fs.is_open()) {
  485. GELOGW("Open %s failed.", file_path.c_str());
  486. return false;
  487. }
  488. std::string line;
  489. if (getline(fs, line)) {
  490. if (!ParseVersion(line, version)) {
  491. GELOGW("Parse version failed. content is [%s].", line.c_str());
  492. fs.close();
  493. return false;
  494. }
  495. } else {
  496. GELOGW("No version information found in the file path:%s", file_path.c_str());
  497. fs.close();
  498. return false;
  499. }
  500. fs.close(); // close the file
  501. return true;
  502. }
  503. // Set package version information in the model
  504. bool GeGenerator::Impl::SetAtcVersionInfo(AttrHolder &obj) {
  505. std::string path_base = ge::GELib::GetPath();
  506. path_base = path_base.substr(0, path_base.rfind('/'));
  507. path_base = path_base.substr(0, path_base.rfind('/') + 1);
  508. std::string version_path = path_base + "version.info";
  509. std::string version;
  510. if (!GetVersionFromPath(version_path, version)) {
  511. GELOGW("Get atc version information failed!");
  512. return false;
  513. }
  514. // set version info
  515. if (!ge::AttrUtils::SetStr(obj, ATTR_MODEL_ATC_VERSION, version)) {
  516. GELOGW("Ge model set atc version failed!");
  517. return false;
  518. }
  519. return true;
  520. }
  521. // Set package version information in the model
  522. bool GeGenerator::Impl::SetOppVersionInfo(AttrHolder &obj) {
  523. const char *path_env = std::getenv("ASCEND_OPP_PATH");
  524. if (path_env == nullptr) {
  525. GELOGW("Get environment variable ASCEND_OPP_PATH failed!");
  526. return false;
  527. }
  528. std::string version_path = path_env;
  529. version_path += "/version.info";
  530. std::string version;
  531. if (!GetVersionFromPath(version_path, version)) {
  532. GELOGW("Get opp version information failed!");
  533. return false;
  534. }
  535. // set version info
  536. if (!ge::AttrUtils::SetStr(obj, ATTR_MODEL_OPP_VERSION, version)) {
  537. GELOGW("Ge model set opp version failed!");
  538. return false;
  539. }
  540. return true;
  541. }
  542. bool GeGenerator::Impl::SetOmSystemInfo(AttrHolder &obj) {
  543. std::string soc_version;
  544. (void)ge::GetContext().GetOption(ge::SOC_VERSION, soc_version);
  545. GELOGI("SetOmSystemInfo soc_version: %s", soc_version.c_str());
  546. if (!ge::AttrUtils::SetStr(obj, "soc_version", soc_version)) {
  547. GELOGW("SetStr of soc_version failed.");
  548. return false;
  549. }
  550. std::string framework_type;
  551. (void)ge::GetContext().GetOption(ge::FRAMEWORK_TYPE, framework_type);
  552. GELOGI("SetOmSystemInfo framework_type: %s", framework_type.c_str());
  553. auto iter = ge::kFwkTypeToStr.find(framework_type);
  554. if (iter == ge::kFwkTypeToStr.end()) {
  555. GELOGW("Can not find framework_type in the map.");
  556. return false;
  557. }
  558. if (!ge::AttrUtils::SetStr(obj, "framework_type", iter->second)) {
  559. GELOGW("SetStr of framework_type failed.");
  560. return false;
  561. }
  562. return true;
  563. }
  564. Status GeGenerator::SetModelNameForDump(const GeRootModelPtr &ge_root_model) {
  565. bool is_unknown_shape = false;
  566. Status ret = ge_root_model->CheckIsUnknownShape(is_unknown_shape);
  567. if (ret != SUCCESS) {
  568. GELOGE(FAILED, "[Check][IsUnknownShape]Check root model is unknown shape failed, model id:%u",
  569. ge_root_model->GetModelId());
  570. REPORT_CALL_ERROR("E19999", "Check root model is unknown shape failed, model id:%u",
  571. ge_root_model->GetModelId());
  572. return FAILED;
  573. }
  574. GeModelPtr model_root = nullptr;
  575. if (is_unknown_shape) {
  576. model_root = MakeShared<GeModel>();
  577. GE_CHECK_NOTNULL(model_root);
  578. model_root->SetGraph(GraphUtils::CreateGraphFromComputeGraph(ge_root_model->GetRootGraph()));
  579. ge_root_model->SetSubgraphInstanceNameToModel(ge_root_model->GetRootGraph()->GetName(), model_root);
  580. }
  581. ModelHelper model_helper;
  582. string model_name;
  583. GE_CHECK_NOTNULL(ge_root_model->GetRootGraph());
  584. Status name_ret = model_helper.GetModelNameFromMergedGraphName(ge_root_model->GetRootGraph()->GetName(),
  585. model_name);
  586. if (name_ret != SUCCESS) {
  587. ErrorManager::GetInstance().ATCReportErrMessage("E10000", {"parameter"}, {"output"});
  588. GELOGE(FAILED, "[Check][GetModelNameStep]Get model_name failed. Param --output is invalid, root graph name: %s",
  589. ge_root_model->GetRootGraph()->GetName().c_str());
  590. return PARAM_INVALID;
  591. }
  592. map<string, GeModelPtr> name_to_ge_model = ge_root_model->GetSubgraphInstanceNameToModel();
  593. GeModelPtr &ge_model = name_to_ge_model[ge_root_model->GetRootGraph()->GetName()];
  594. GE_CHECK_NOTNULL(ge_model);
  595. ge_model->SetName(model_name);
  596. return SUCCESS;
  597. }
  598. Status GeGenerator::GenerateModel(const Graph &graph, const string &file_name_prefix, const vector<GeTensor> &inputs,
  599. ModelBufferData &model, bool is_offline) {
  600. rtContext_t ctx = nullptr;
  601. auto rt = rtCtxGetCurrent(&ctx);
  602. if (rt != RT_ERROR_NONE) {
  603. GELOGD("Current ctx is null.");
  604. ctx = nullptr;
  605. }
  606. GeRootModelPtr ge_root_model = nullptr;
  607. GE_CHECK_NOTNULL_EXEC(impl_, return PARAM_INVALID);
  608. impl_->is_offline_ = is_offline;
  609. Status ret = impl_->BuildModel(graph, inputs, ge_root_model);
  610. if (ret != SUCCESS) {
  611. GELOGE(ret, "[Build][Model] failed, ret:%d.", ret);
  612. if (impl_->graph_manager_.Finalize() != SUCCESS) {
  613. GELOGE(FAILED, "[Call][Finalize] graph_manager finalize fail.");
  614. }
  615. return ret;
  616. }
  617. /// BUILD_MODE_TUNING with BUILD_STEP_BEFORE_UB_MATCH no need save model;
  618. /// BUILD_MODE_TUNING with BUILD_STEP_AFTER_BUILDER no need save model;
  619. /// BUILD_MODE_TUNING with BUILD_STEP_AFTER_BUILDER_SUB no need save model.
  620. if ((impl_->build_mode_ == BUILD_MODE_TUNING) &&
  621. (impl_->build_step_ == BUILD_STEP_BEFORE_UB_MATCH || impl_->build_step_ == BUILD_STEP_AFTER_BUILDER ||
  622. impl_->build_step_ == BUILD_STEP_AFTER_BUILDER_SUB)) {
  623. GELOGI("Build mode:%s with step:%s no need SaveModel.",
  624. impl_->build_mode_.c_str(),
  625. impl_->build_step_.c_str());
  626. return SUCCESS;
  627. }
  628. GE_CHECK_NOTNULL(ge_root_model);
  629. ret = SetModelNameForDump(ge_root_model);
  630. if (ret != SUCCESS) {
  631. return ret;
  632. }
  633. ret = impl_->SaveRootModel(file_name_prefix, ge_root_model, model);
  634. if (ret != SUCCESS) {
  635. GELOGE(ret, "[Save][RootModel] failed, ret:%d, file:%s", ret, file_name_prefix.c_str());
  636. if (impl_->graph_manager_.Finalize() != SUCCESS) {
  637. GELOGE(FAILED, "graph_manager finalize fail.");
  638. }
  639. return ret;
  640. }
  641. if (ctx != nullptr) {
  642. (void)rtCtxSetCurrent(ctx);
  643. }
  644. return SUCCESS;
  645. }
  646. namespace {
  647. bool IsNeedConnectInputOpForSingleOp(GeTensorDesc &tensor_desc) {
  648. bool is_need = true;
  649. // format and dtype is all reserved, stand for Optional input. When singleop scene
  650. if (tensor_desc.GetFormat() == FORMAT_RESERVED && tensor_desc.GetDataType() == DT_UNDEFINED) {
  651. is_need = false;
  652. }
  653. return is_need;
  654. }
  655. Status CheckDynamicSupport(GeModelPtr &ge_model, const ComputeGraphPtr &graph) {
  656. bool support_dynamic = true;
  657. bool is_dynamic = false;
  658. for (const auto &node : graph->GetDirectNode()) {
  659. GE_CHECK_NOTNULL(node);
  660. auto op_desc = node->GetOpDesc();
  661. GE_CHECK_NOTNULL(op_desc);
  662. if (op_desc->GetOpEngineName() != kAIcoreEngine) {
  663. continue;
  664. }
  665. if (AttrUtils::HasAttr(op_desc, kAttrSupportDynamicShape)) {
  666. is_dynamic = true;
  667. (void) AttrUtils::GetBool(op_desc, kAttrSupportDynamicShape, support_dynamic);
  668. if (!support_dynamic) {
  669. GELOGW("Node[%s] doesn't support dynamic shape.", node->GetName().c_str());
  670. break;
  671. }
  672. }
  673. }
  674. if (is_dynamic) {
  675. (void) AttrUtils::SetBool(ge_model, kAttrSupportDynamicShape, support_dynamic);
  676. }
  677. return SUCCESS;
  678. }
  679. }
  680. bool GeGenerator::CheckNoAicore(const ComputeGraphPtr &graph) {
  681. for (const auto &node : graph->GetDirectNode()) {
  682. if (node == nullptr) {
  683. continue;
  684. }
  685. auto op_desc = node->GetOpDesc();
  686. if (op_desc == nullptr) {
  687. continue;
  688. }
  689. if (op_desc->GetOpEngineName() == kAIcoreEngine) {
  690. return false;
  691. }
  692. }
  693. return true;
  694. }
  695. void GeGenerator::RemoveConst(const vector<GeTensor> &inputs, vector<GeTensor> &outputs) {
  696. for (auto &input : inputs) {
  697. GeTensorDesc input_desc = input.GetTensorDesc();
  698. bool is_const = false;
  699. (void)AttrUtils::GetBool(input_desc, CONST_ATTR_NAME_INPUT, is_const);
  700. bool is_optional = IsOptional(input_desc);
  701. if (!is_optional && !is_const) {
  702. outputs.emplace_back(input);
  703. }
  704. }
  705. }
  706. Status GeGenerator::CheckForSingleOp(OpDescPtr &op_desc, const vector<GeTensor> &inputs,
  707. const vector<GeTensor> &outputs) {
  708. GE_CHECK_NOTNULL_EXEC(op_desc, return PARAM_INVALID);
  709. if (!inputs.empty() && (inputs.size() != op_desc->GetAllInputsSize())) {
  710. ErrorManager::GetInstance().ATCReportErrMessage("E14001", {"opname", "optype", "value", "reason"},
  711. {op_desc->GetName(), op_desc->GetType(), "inputs size" + FmtToStr(op_desc->GetAllInputsSize()),
  712. "tensor size is " + FmtToStr(inputs.size())});
  713. GELOGE(PARAM_INVALID, "[Check][Param] Tensor size: %zu, op:%s(%s) Inputs size: %zu, not equal",
  714. inputs.size(), op_desc->GetName().c_str(), op_desc->GetType().c_str(), op_desc->GetAllInputsSize());
  715. return PARAM_INVALID;
  716. }
  717. if (!outputs.empty() && (outputs.size() != op_desc->GetOutputsSize())) {
  718. ErrorManager::GetInstance().ATCReportErrMessage("E14001", {"opname", "optype", "value", "reason"},
  719. {op_desc->GetName(), op_desc->GetType(), "outputs size" + FmtToStr(op_desc->GetOutputsSize()),
  720. "tensor size is " + FmtToStr(outputs.size())});
  721. GELOGE(PARAM_INVALID, "[Check][Param] Tensor size: %zu, op:%s(%s) Outputs size: %zu, not equal",
  722. outputs.size(), op_desc->GetName().c_str(), op_desc->GetType().c_str(), op_desc->GetOutputsSize());
  723. return PARAM_INVALID;
  724. }
  725. return SUCCESS;
  726. }
  727. Status GeGenerator::BuildSingleOp(OpDescPtr &op_desc, const vector<GeTensor> &inputs, const vector<GeTensor> &outputs,
  728. const string &model_file_name, OpEngineType engine_type, ModelBufferData &model_buff,
  729. bool is_offline, int32_t compile_flag) {
  730. GELOGD("Inputs size is %zu, outputs size is %zu.", inputs.size(), outputs.size());
  731. GE_CHECK_NOTNULL_EXEC(impl_, return PARAM_INVALID);
  732. impl_->is_offline_ = is_offline;
  733. (void)AttrUtils::SetBool(op_desc, ATTR_SINGLE_OP_SCENE, true);
  734. if (CheckForSingleOp(op_desc, inputs, outputs) != SUCCESS) {
  735. GELOGE(PARAM_INVALID, "[Check][Param] input param is invalid when build single op:%s!",
  736. op_desc->GetName().c_str());
  737. return PARAM_INVALID;
  738. }
  739. OmgContext &omg_context = (impl_ == nullptr) ? domi::GetContext() : impl_->omg_context_;
  740. omg_context.is_dynamic_input = ContainsDynamicInpus(*op_desc);
  741. if (op_desc->HasAttr(ATTR_NAME_UNREGST_OPPATH)) {
  742. impl_->is_singleop_unregistered_ = true;
  743. }
  744. // 0. Save original attributes.
  745. OpDescPtr op_desc_tmp = AttrUtils::CloneOpDesc(op_desc);
  746. GE_CHECK_NOTNULL(op_desc_tmp);
  747. bool fuzz_compile_flag = false;
  748. if (!HasShapeRange(inputs) && compile_flag == kFuzzBuildPattern) {
  749. fuzz_compile_flag = true;
  750. }
  751. if (!AttrUtils::SetBool(op_desc, ATTR_NAME_FUZZ_BUILD, fuzz_compile_flag)) {
  752. REPORT_CALL_ERROR("E19999", "set ATTR_NAME_FUZZ_BUILD failed for %s.", op_desc->GetName().c_str());
  753. GELOGE(FAILED, "[Set][ATTR_NAME_FUZZ_BUILD] Failed to set attr for %s.", op_desc->GetName().c_str());
  754. return FAILED;
  755. }
  756. impl_->omg_context_.fuzz_compile_flag = fuzz_compile_flag;
  757. // 1. Create ComputeGraph.
  758. string name = ge::CurrentTimeInStr() + "_" + model_file_name;
  759. Graph graph;
  760. GE_CHK_STATUS(BuildSingleOpGraph(op_desc, inputs, outputs, name, graph),
  761. "[Build][Graph] for single op:%s fail.", op_desc->GetName().c_str());
  762. auto op = OpDescUtils::CreateOperatorFromOpDesc(op_desc);
  763. GE_CHK_STATUS_RET(op_desc->CallInferFormatFunc(op),
  764. "[Call][InferFormatFunc] for single op:%s fail.", op_desc->GetName().c_str());
  765. // 2. check engine type when compile online
  766. if (model_file_name == kFileNameSuffix) {
  767. auto comp_graph = GraphUtils::GetComputeGraph(graph);
  768. GE_CHECK_NOTNULL(comp_graph);
  769. auto node = comp_graph->FindNode(op_desc->GetName());
  770. Status ret = CheckEngineTypeSupport(node, engine_type);
  771. if (ret != SUCCESS) {
  772. GELOGE(ret, "[Check][EngineType]not support node:%s with engine of %d.", node->GetName().c_str(), engine_type);
  773. return ret;
  774. }
  775. }
  776. GELOGI("ATC parser success in single op build.");
  777. GeRootModelPtr ge_root_model = nullptr;
  778. vector<GeTensor> data_inputs;
  779. RemoveConst(inputs, data_inputs);
  780. GE_CHK_STATUS_RET_NOLOG(impl_->BuildModel(graph, data_inputs, ge_root_model));
  781. map<string, GeAttrValue> op_attrs = op_desc_tmp->GetAllAttrs();
  782. GE_CHECK_NOTNULL(ge_root_model);
  783. GE_CHECK_NOTNULL(ge_root_model->GetRootGraph());
  784. map<string, GeModelPtr> name_to_ge_model = ge_root_model->GetSubgraphInstanceNameToModel();
  785. if (name_to_ge_model.empty()) {
  786. REPORT_CALL_ERROR("E19999", "GetSubgraphInstanceNameToModel failed.");
  787. GELOGE(PARAM_INVALID, "[Get][Name] GetSubgraphInstanceNameToModel is empty.");
  788. return PARAM_INVALID;
  789. }
  790. const ComputeGraphPtr root_graph = ge_root_model->GetRootGraph();
  791. GeModelPtr &ge_model = name_to_ge_model.begin()->second;
  792. GE_CHK_STATUS_RET_NOLOG(CheckDynamicSupport(ge_model, root_graph));
  793. GELOGI("After build model, The opType in op_desc_tmp is [%s]", op_desc_tmp->GetType().c_str());
  794. bool all_shape = false;
  795. (void)AttrUtils::GetBool(op_desc, kAicpuAllshape, all_shape);
  796. GELOGD("Node: %s, all_shape is %d, compile_flag is %d.", op_desc->GetName().c_str(), all_shape, compile_flag);
  797. (void)AttrUtils::SetInt(ge_model, ATTR_NAME_BUILD_MODE, fuzz_compile_flag);
  798. if (all_shape) {
  799. (void)AttrUtils::SetBool(ge_model, kAicpuAllshape, all_shape);
  800. }
  801. if (all_shape && CheckNoAicore(root_graph)) {
  802. GELOGD("Get aicpu all_shape kernel!");
  803. vector<GeTensor> inputs_dynamic;
  804. vector<GeTensor> outputs_dynamic;
  805. GE_CHK_STATUS_RET_NOLOG(ResetTensorVecShape(inputs, inputs_dynamic));
  806. GE_CHK_STATUS_RET_NOLOG(ResetTensorVecShape(outputs, outputs_dynamic));
  807. GE_CHK_STATUS_RET_NOLOG(
  808. impl_->SaveParams(ge_model, op_desc_tmp->GetType(), op_attrs, inputs_dynamic, outputs_dynamic));
  809. } else if (fuzz_compile_flag) {
  810. GeAttrValue::LIST_NAMED_ATTRS fuzz_build_attrs;
  811. if (GetFuzzBuildAttrs(op_desc, ge_root_model, fuzz_build_attrs) != SUCCESS) {
  812. GELOGE(FAILED, "[Get][FuzzRet]Failed to get fuzz build result of %s.", op_desc->GetName().c_str());
  813. return FAILED;
  814. }
  815. if (!fuzz_build_attrs.empty()) {
  816. GE_CHK_BOOL_EXEC(AttrUtils::SetListNamedAttrs(ge_model, ATTR_NAME_FUZZ_BUILD_RES_ATTRS, fuzz_build_attrs),
  817. REPORT_CALL_ERROR("E19999", "Set model:%s(id:%u) attr:%s failed.",
  818. ge_model->GetName().c_str(), ge_model->GetModelId(),
  819. ATTR_NAME_FUZZ_BUILD_RES_ATTRS.c_str());
  820. return FAILED, "Set model:%s(id:%u) attr:%s failed.",
  821. ge_model->GetName().c_str(), ge_model->GetModelId(), ATTR_NAME_FUZZ_BUILD_RES_ATTRS.c_str());
  822. }
  823. GE_CHK_STATUS_RET_NOLOG(impl_->SaveParams(ge_model, op_desc_tmp->GetType(), op_attrs, inputs, outputs));
  824. } else {
  825. GE_CHK_STATUS_RET_NOLOG(impl_->SaveParams(ge_model, op_desc_tmp->GetType(), op_attrs, inputs, outputs));
  826. }
  827. GELOGI("Start save GeModel to Model buffer");
  828. GE_CHK_STATUS_RET_NOLOG(impl_->SaveModel(model_file_name, ge_model, model_buff));
  829. return SUCCESS;
  830. }
  831. /**
  832. * @ingroup ge
  833. * @brief Compiling a single operator into an offline model
  834. * @param [in] OpDescPtr &op_desc: Operator description info that needs to be compiled into an offline model file
  835. * @param [in] vector<GeTensor> &inputs: Operator input data description information.
  836. * @param [in] vector<GeTensor> &outputs: Operator output data description information.
  837. * @param [in] const string &model_file_name: Offline model filename.
  838. * @param [in] compile_flag: op build flag from atc
  839. * @return SUCCESS handle successfully / others handle failed
  840. */
  841. Status GeGenerator::BuildSingleOpModel(OpDescPtr &op_desc, const vector<GeTensor> &inputs,
  842. const vector<GeTensor> &outputs, const string &model_file_name,
  843. int32_t compile_flag) {
  844. ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther);
  845. GELOGI("Start to build single op offline model, input size: %zu, output size: %zu", inputs.size(), outputs.size());
  846. ModelBufferData model_buff;
  847. OpEngineType engine_type = ENGINE_SYS;
  848. Status status = BuildSingleOp(op_desc, inputs, outputs, model_file_name, engine_type, model_buff, true, compile_flag);
  849. GELOGI("Finish build single offline model, status: %u", status);
  850. return status;
  851. }
  852. /**
  853. * @ingroup ge
  854. * @brief Compiling a single operator into online buffer
  855. * @param [in] OpDescPtr &op_desc: Operator description info that needs to be compiled into an offline model file
  856. * @param [in] vector<GeTensor> &inputs: Operator input data description information.
  857. * @param [in] vector<GeTensor> &outputs: Operator output data description information.
  858. * @param [in] engine_type: specific engine.
  859. * @param [in] compile_flag: op build flag, compile flag by acl
  860. * @param [out] ModelBufferData &Model_buff: Model_buff: model buffer of the op.
  861. * @return SUCCESS handle successfully / others handle failed
  862. */
  863. Status GeGenerator::BuildSingleOpModel(OpDescPtr &op_desc, const vector<GeTensor> &inputs,
  864. const vector<GeTensor> &outputs, OpEngineType engine_type,
  865. ModelBufferData &model_buff) {
  866. ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther);
  867. GELOGI("Start to build single op online, input size: %zu, output size: %zu", inputs.size(), outputs.size());
  868. Status status = BuildSingleOp(op_desc, inputs, outputs, kFileNameSuffix, engine_type, model_buff, false);
  869. GELOGI("Finish build single online model, status: %u", status);
  870. return status;
  871. }
  872. Status GeGenerator::BuildSingleOpModel(OpDescPtr &op_desc, const vector<GeTensor> &inputs,
  873. const vector<GeTensor> &outputs, OpEngineType engine_type, int32_t compile_flag,
  874. ModelBufferData &model_buff) {
  875. ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther);
  876. GELOGI("Start to build single op online, input size: %zu, output size: %zu", inputs.size(), outputs.size());
  877. Status status = BuildSingleOp(op_desc, inputs, outputs, kFileNameSuffix, engine_type, model_buff, false,
  878. compile_flag);
  879. GELOGI("Finish build single online model, status: %u", status);
  880. return status;
  881. }
  882. Status GeGenerator::BuildSingleOpGraph(OpDescPtr &op_desc, const vector<GeTensor> &inputs,
  883. const vector<GeTensor> &outputs, std::string graph_name, Graph &graph) {
  884. ge::ComputeGraphPtr compute_graph = MakeShared<ComputeGraph>(graph_name);
  885. GE_CHECK_NOTNULL_EXEC(compute_graph, return INTERNAL_ERROR);
  886. // 1. Add Node to ComputeGraph.
  887. NodePtr op_node = compute_graph->AddNode(op_desc);
  888. GE_CHECK_NOTNULL_EXEC(op_node, return INTERNAL_ERROR);
  889. // 2. Create InputData node.
  890. int32_t arg_index = 0;
  891. int32_t data_index = 0;
  892. if (inputs.empty()) {
  893. for (const auto &input_desc : op_desc->GetAllInputsDescPtr()) {
  894. GE_CHECK_NOTNULL_EXEC(input_desc, return INTERNAL_ERROR);
  895. if (!IsNeedConnectInputOpForSingleOp(*input_desc)) {
  896. continue;
  897. }
  898. GE_CHK_STATUS_RET_NOLOG(AddInputs(compute_graph, op_node, *input_desc, arg_index, false, data_index));
  899. arg_index++;
  900. }
  901. } else {
  902. for (const auto &in_desc : inputs) {
  903. GE_CHK_STATUS_RET_NOLOG(AddInputs(compute_graph, op_node, in_desc.GetTensorDesc(), arg_index, true, data_index));
  904. arg_index++;
  905. }
  906. }
  907. // 3. Create Output node.
  908. if (!outputs.empty()) {
  909. GE_CHK_STATUS_RET_NOLOG(AddOutputs(compute_graph, op_node, outputs));
  910. }
  911. // dump ComputeGraph node.
  912. compute_graph->Dump();
  913. graph = ge::GraphUtils::CreateGraphFromComputeGraph(compute_graph);
  914. return SUCCESS;
  915. }
  916. Status GeGenerator::Impl::SaveParams(GeModelPtr &ge_model, const string &type, const map<string, GeAttrValue> &attrs,
  917. const vector<GeTensor> &inputs, const vector<GeTensor> &outputs) {
  918. GE_CHECK_NOTNULL_EXEC(ge_model, return PARAM_INVALID);
  919. GE_CHK_BOOL_EXEC_NOLOG(graph_manager_.SaveParams(*ge_model, type, attrs, inputs, outputs) == SUCCESS,
  920. (void)graph_manager_.Finalize();
  921. return FAILED);
  922. return SUCCESS;
  923. }
  924. Status GeGenerator::Impl::SaveModel(const string &file_name_prefix, GeModelPtr &model, ModelBufferData &model_buff) {
  925. // set atc version
  926. if (!SetAtcVersionInfo(*(model.get()))) {
  927. GELOGW("SetPackageVersionInfo of atc failed!");
  928. }
  929. // set opp version
  930. if (!SetOppVersionInfo(*(model.get()))) {
  931. GELOGW("SetPackageVersionInfo of ops failed!");
  932. }
  933. ModelHelper model_helper;
  934. model_helper.SetSaveMode(is_offline_);
  935. Status ret = model_helper.SaveToOmModel(model, save_param_, file_name_prefix, model_buff);
  936. if (ret != SUCCESS) {
  937. GELOGE(ret, "[Call][SaveToOmModel] Save to om model failed");
  938. return ret;
  939. }
  940. return SUCCESS;
  941. }
  942. Status GeGenerator::Impl::SaveRootModel(const string &file_name_prefix, GeRootModelPtr &ge_root_model,
  943. ModelBufferData &model_buff) {
  944. bool is_unknown_shape = false;
  945. auto ret = ge_root_model->CheckIsUnknownShape(is_unknown_shape);
  946. if (ret != SUCCESS) {
  947. REPORT_CALL_ERROR("E19999", "root model(id:%u) CheckIsUnknownShape failed, ret:%d",
  948. ge_root_model->GetModelId(), ret);
  949. GELOGE(FAILED, "[Check][RootModel] is unkonwn shape failed, ret:%d", ret);
  950. return FAILED;
  951. }
  952. GELOGD("begin save root model, cur model is unkonwn shape model ? : %d", is_unknown_shape);
  953. GE_CHK_BOOL_EXEC(!ge_root_model->GetSubgraphInstanceNameToModel().empty(),
  954. REPORT_CALL_ERROR("E19999", "root model(id:%u) has no sub model.", ge_root_model->GetModelId());
  955. return FAILED, "[Get][SubModel] ge root model has no sub model")
  956. GeModelPtr model_root = nullptr;
  957. if (is_unknown_shape) {
  958. auto name_to_ge_model = ge_root_model->GetSubgraphInstanceNameToModel();
  959. model_root = name_to_ge_model[ge_root_model->GetRootGraph()->GetName()];
  960. } else {
  961. model_root = ge_root_model->GetSubgraphInstanceNameToModel().begin()->second;
  962. }
  963. GE_CHECK_NOTNULL(model_root);
  964. // set atc version
  965. if (!SetAtcVersionInfo(*(model_root.get()))) {
  966. GELOGW("SetPackageVersionInfo of atc failed!");
  967. }
  968. // set opp version
  969. if (!SetOppVersionInfo(*(model_root.get()))) {
  970. GELOGW("SetPackageVersionInfo of ops failed!");
  971. }
  972. if (!SetOmSystemInfo(*(model_root.get()))) {
  973. GELOGW("SetOmsystemInfo failed!");
  974. }
  975. ModelHelper model_helper;
  976. model_helper.SetSaveMode(is_offline_);
  977. ret = model_helper.SaveToOmRootModel(ge_root_model, save_param_, file_name_prefix, model_buff, is_unknown_shape);
  978. if (ret != SUCCESS) {
  979. REPORT_CALL_ERROR("E19999", "SaveToOmRootModel failed, ret:%d, model id:%u", ret, ge_root_model->GetModelId());
  980. GELOGE(ret, "[Call][SaveToOmRootModel] failed, ret:%d, model id:%u", ret, ge_root_model->GetModelId());
  981. return ret;
  982. }
  983. return SUCCESS;
  984. }
  985. Status GeGenerator::Impl::BuildModel(const Graph &graph, const vector<GeTensor> &inputs,
  986. GeRootModelPtr &ge_root_model) {
  987. static std::atomic<GraphId> atomic_graph_id(0);
  988. auto graph_id = atomic_graph_id.fetch_add(1);
  989. const std::map<std::string, std::string> options;
  990. Status ret = graph_manager_.AddGraph(graph_id, graph, options, omg_context_);
  991. if (ret != SUCCESS) {
  992. REPORT_CALL_ERROR("E19999", "add graph(id:%u) failed, ret:%d", graph_id, ret);
  993. GELOGE(GE_GENERATOR_GRAPH_MANAGER_ADD_GRAPH_FAILED, "[Add][Graph] fail, graph id: %u", graph_id);
  994. (void)graph_manager_.Finalize();
  995. return GE_GENERATOR_GRAPH_MANAGER_ADD_GRAPH_FAILED;
  996. }
  997. graph_manager_.SetOptionsRunGraphFlag(false);
  998. static std::atomic<uint64_t> atomic_session_id(0);
  999. auto session_id = atomic_session_id.fetch_add(1);
  1000. // This is a temporary add for graph with variable
  1001. auto version = static_cast<int32_t>(SessionVersion::ClOUD_VERSION);
  1002. ret = VarManager::Instance(session_id)->Init(version, session_id, kDefaultDeviceId, kDefaultJobId);
  1003. GELOGI("Start init var instance, session_id %lu", session_id);
  1004. if (ret != SUCCESS) {
  1005. GELOGW("Failed init var instance, session_id %lu", session_id);
  1006. }
  1007. if (is_singleop_unregistered_) {
  1008. ret = graph_manager_.BuildGraphForUnregisteredOp(graph_id, inputs, ge_root_model, session_id);
  1009. } else {
  1010. ret = graph_manager_.BuildGraph(graph_id, inputs, ge_root_model, session_id);
  1011. }
  1012. ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther);
  1013. if (ret != SUCCESS) {
  1014. REPORT_CALL_ERROR("E19999", "build graph failed, graph id:%u, ret:%d", graph_id, ret);
  1015. GELOGE(GE_GENERATOR_GRAPH_MANAGER_BUILD_GRAPH_FAILED, "[Build][Graph] fail, graph id: %u", graph_id);
  1016. ret = GE_GENERATOR_GRAPH_MANAGER_BUILD_GRAPH_FAILED;
  1017. }
  1018. RtContextUtil::GetInstance().DestroyRtContexts(session_id);
  1019. Analyzer::GetInstance()->DestroySessionJsonObject(session_id);
  1020. VarManagerPool::Instance().RemoveVarManager(session_id);
  1021. return ret;
  1022. }
  1023. Status GeGenerator::Impl::GenerateInfershapeGraph(const Graph &graph) {
  1024. static std::atomic<GraphId> atomic_graph_id(0);
  1025. auto graph_id = atomic_graph_id.fetch_add(1);
  1026. const std::map<std::string, std::string> options;
  1027. Status ret = graph_manager_.AddGraph(graph_id, graph, options, omg_context_);
  1028. if (ret != SUCCESS) {
  1029. REPORT_CALL_ERROR("E19999", "add graph failed, graph id:%u, ret:%d", graph_id, ret);
  1030. GELOGE(GE_GENERATOR_GRAPH_MANAGER_ADD_GRAPH_FAILED, "[Add][Graph] failed, graph id: %u", graph_id);
  1031. (void)graph_manager_.Finalize();
  1032. return GE_GENERATOR_GRAPH_MANAGER_ADD_GRAPH_FAILED;
  1033. }
  1034. ret = graph_manager_.GenerateInfershapeGraph(graph_id);
  1035. if (ret != SUCCESS) {
  1036. REPORT_CALL_ERROR("E19999", "GenerateInfershapeGraph failed, graph id:%u, ret:%d", graph_id, ret);
  1037. GELOGE(GE_GENERATOR_GRAPH_MANAGER_BUILD_GRAPH_FAILED,
  1038. "[Generate][Graph] failed, graph id:%u, ret:%d", graph_id, ret);
  1039. return GE_GENERATOR_GRAPH_MANAGER_BUILD_GRAPH_FAILED;
  1040. }
  1041. return SUCCESS;
  1042. }
  1043. } // namespace ge

图引擎模块(GE)是MindSpore的一个子模块,其代码由C++实现,位于前端模块ME和底层硬件之间,起到承接作用。图引擎模块以ME下发的图作为输入,然后进行一系列的深度图优化操作,最后输出一张可以在底层硬件上高效运行的图。GE针对昇腾AI处理器的硬件结构特点,做了特定的优化工作,以此来充分发挥出昇腾AI处理器的强大算力。在进行模型训练/推理时,GE会被自动调用而用户并不感知。GE主要由GE API和GE Core两部分组成,详细的架构图如下所示