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.

model_builder.cc 27 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
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
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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. /**
  2. * Copyright 2019-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 "graph/build/model_builder.h"
  17. #include <iostream>
  18. #include <set>
  19. #include <unordered_map>
  20. #include "common/ge/ge_util.h"
  21. #include "framework/common/debug/ge_log.h"
  22. #include "graph/anchor.h"
  23. #include "graph/attr_value.h"
  24. #include "graph/buffer.h"
  25. #include "graph/build/label_allocator.h"
  26. #include "graph/build/stream_allocator.h"
  27. #include "graph/common/omg_util.h"
  28. #include "graph/debug/ge_attr_define.h"
  29. #include "graph/ge_attr_value.h"
  30. #include "graph/ge_context.h"
  31. #include "graph/ge_error_codes.h"
  32. #include "graph/manager/graph_mem_allocator.h"
  33. #include "graph/manager/graph_var_manager.h"
  34. #include "graph/optimize/common/params.h"
  35. #include "graph/types.h"
  36. #include "graph/utils/attr_utils.h"
  37. #include "graph/utils/graph_utils.h"
  38. #include "graph/utils/node_utils.h"
  39. #include "graph/utils/op_desc_utils.h"
  40. #include "graph/utils/tensor_utils.h"
  41. #include "graph/utils/type_utils.h"
  42. #include "init/gelib.h"
  43. #include "memory/memory_assigner.h"
  44. #include "omg/version.h"
  45. #include "register/op_registry.h"
  46. using ge::FAILED;
  47. using ge::PARAM_INVALID;
  48. using ge::SUCCESS;
  49. using std::map;
  50. using std::set;
  51. using std::string;
  52. using std::vector;
  53. namespace {
  54. const uint32_t kWeightsStartOffset = 512;
  55. const int32_t kWrongIndex = -2;
  56. const float kImgRatioYUV420SP_U8 = 1.5;
  57. const int kImgRatioRGB888_U8 = 3;
  58. const int kImgRatioNC1HWC0DI_FP16 = 12;
  59. const int kInvalidIndexNum = -1;
  60. const uint32_t kInputDimensions2D = 2;
  61. const uint32_t kInputDimensions3D = 3;
  62. const char *const kVectorCore = "VectorCore";
  63. const char *const kCoreType = "ge.engineType";
  64. const std::string kEnableL1Fusion = "ge.l1Fusion";
  65. const set<string> adjust_layer_type_ = {ge::CONVOLUTION};
  66. bool IsGeLocalOp(const ge::ConstOpDescPtr &op_desc) {
  67. auto type = op_desc->GetType();
  68. if (type == ge::CONSTANTOP) {
  69. // constant op just has one output
  70. ge::GeTensorDesc output_desc = op_desc->GetOutputDesc(0);
  71. return !(output_desc.GetDataType() == ge::DT_STRING);
  72. }
  73. const set<string> ge_local_set = {ge::STREAMMERGE, ge::MEMCPYASYNC, ge::STREAMACTIVE, ge::STREAMSWITCH,
  74. ge::VARIABLE, ge::NOOP, ge::CONSTANT, ge::ENTER,
  75. ge::REFENTER, ge::LOOPCOND, ge::NEXTITERATION, ge::REFNEXTITERATION,
  76. ge::EXIT, ge::REFEXIT, ge::MEMCPYADDRASYNC};
  77. return (ge_local_set.find(type) != ge_local_set.end());
  78. }
  79. } // namespace
  80. namespace ge {
  81. ModelBuilder::ModelBuilder(ge::ComputeGraphPtr compute_graph, const Graph2SubGraphInfoList &subgraphs,
  82. const map<string, int> &stream_max_parallel_num, bool hcom_parallel, int mode)
  83. : mem_offset_(0),
  84. weight_offset_(kWeightsStartOffset),
  85. compute_graph_(std::move(compute_graph)),
  86. subgraphs_(subgraphs),
  87. stream_num_(0),
  88. event_num_(0),
  89. label_num_(0),
  90. stream_max_parallel_num_(stream_max_parallel_num),
  91. hcom_parallel_(hcom_parallel),
  92. build_mode_(mode),
  93. max_mem_offset_(0),
  94. platform_type_(0),
  95. is_loop_graph_(false),
  96. is_l1_fusion_enable_(false) {}
  97. ModelBuilder::~ModelBuilder() {}
  98. Status ModelBuilder::CalcOutputSize(const ge::NodePtr &n) {
  99. GE_CHECK_NOTNULL(n);
  100. auto node_op_desc = n->GetOpDesc();
  101. GE_CHECK_NOTNULL(node_op_desc);
  102. uint32_t index = 0;
  103. for (const auto &output_desc_ptr : node_op_desc->GetAllOutputsDescPtr()) {
  104. GeTensorDesc &desc_temp = *output_desc_ptr;
  105. uint32_t dim_num = static_cast<uint32_t>(desc_temp.GetShape().GetDimNum());
  106. GE_IF_BOOL_EXEC(dim_num > DIM_DEFAULT_SIZE, TensorUtils::SetRealDimCnt(desc_temp, dim_num));
  107. // calculate tensor size
  108. int64_t size_temp = 0;
  109. graphStatus graph_status = TensorUtils::GetTensorMemorySizeInBytes(desc_temp, size_temp);
  110. if (graph_status != GRAPH_SUCCESS) {
  111. GELOGE(graph_status, "GetTensorMemorySizeInBytes failed!");
  112. return FAILED;
  113. }
  114. TensorUtils::SetSize(desc_temp, size_temp);
  115. if (node_op_desc->UpdateOutputDesc(index, desc_temp) != SUCCESS) {
  116. GELOGE(FAILED, "UpdateOutputDesc failed.");
  117. return FAILED;
  118. }
  119. GELOGD("update output desc, dim_size: %u, mem_size: %ld, format: %s, type: %s, node name:%s", dim_num, size_temp,
  120. TypeUtils::FormatToSerialString(desc_temp.GetFormat()).c_str(),
  121. TypeUtils::DataTypeToSerialString(desc_temp.GetDataType()).c_str(), node_op_desc->GetName().c_str());
  122. index++;
  123. }
  124. return SUCCESS;
  125. }
  126. void ModelBuilder::SetInputIsConst(const ge::NodePtr &n) {
  127. auto node_op_desc = n->GetOpDesc();
  128. if (node_op_desc == nullptr) {
  129. GELOGW("node_op_desc is nullptr!");
  130. return;
  131. }
  132. auto is_input_const = node_op_desc->GetIsInputConst();
  133. // must set all true input_const to false
  134. for (size_t i = 0; i < is_input_const.size(); i++) {
  135. is_input_const[i] = false;
  136. }
  137. auto in_data_anchors = n->GetAllInDataAnchors();
  138. for (size_t index = 0; index < in_data_anchors.size(); index++) {
  139. auto in_data_anchor = in_data_anchors.at(index);
  140. const auto &peer_out_anchor = in_data_anchor->GetPeerOutAnchor();
  141. GE_IF_BOOL_EXEC(peer_out_anchor == nullptr, continue);
  142. const auto &src_node = peer_out_anchor->GetOwnerNode();
  143. if (src_node->GetType() == CONSTANT) {
  144. GELOGI("SetIsInputConst const");
  145. for (size_t i = is_input_const.size(); i <= index; ++i) {
  146. is_input_const.push_back(false);
  147. }
  148. is_input_const[index] = true;
  149. vector<GeTensorPtr> weights = OpDescUtils::MutableWeights(src_node);
  150. if (weights.empty()) {
  151. GELOGW("SetInputIsConst weights is empty");
  152. return;
  153. }
  154. GeTensorPtr weight = weights[0];
  155. GE_IF_BOOL_EXEC(weight == nullptr, continue);
  156. GeTensorDesc &tensor_desc = weight->MutableTensorDesc();
  157. int64_t data_offset = 0;
  158. if (TensorUtils::GetDataOffset(tensor_desc, data_offset) != GRAPH_SUCCESS) {
  159. GELOGW("Get Offset from weight failed");
  160. return;
  161. }
  162. auto input_tensor = node_op_desc->MutableInputDesc(static_cast<uint32_t>(index));
  163. if (input_tensor == nullptr) {
  164. GELOGW("Get input_tensor failed");
  165. return;
  166. }
  167. TensorUtils::SetDataOffset(*input_tensor, data_offset);
  168. } else if (src_node->GetType() == CONSTANTOP) {
  169. if ((index < is_input_const.size()) && is_input_const[index]) {
  170. is_input_const[index] = false;
  171. }
  172. }
  173. }
  174. std::string input_const_info = ToString(is_input_const);
  175. GELOGD("update opdesc:%s InputConst:%s", node_op_desc->GetName().c_str(), input_const_info.c_str());
  176. node_op_desc->SetIsInputConst(is_input_const);
  177. }
  178. Status ModelBuilder::AdjustConstWeightSize(const ge::NodePtr &node, size_t &mem_offset) {
  179. GE_CHECK_NOTNULL(node);
  180. if (node->GetType() == CONSTANT) {
  181. vector<GeTensorPtr> weights = OpDescUtils::MutableWeights(node);
  182. if (weights.empty()) {
  183. GELOGE(FAILED, "weights size of node %s is empty", node->GetName().c_str());
  184. return FAILED;
  185. }
  186. GeTensorPtr weight = weights[0];
  187. if (weight == nullptr) {
  188. GELOGE(FAILED, "weights[0] is null.");
  189. return FAILED;
  190. }
  191. GeTensorDesc &tensor_desc = weight->MutableTensorDesc();
  192. size_t output_size = weight->GetData().size();
  193. TensorUtils::SetDataOffset(tensor_desc, mem_offset);
  194. mem_offset += output_size;
  195. }
  196. return SUCCESS;
  197. }
  198. Status ModelBuilder::SetInputOutputDesc() {
  199. Status ret;
  200. GELOGI("Start to SetInputOutputDesc.");
  201. for (const ge::NodePtr &n : compute_graph_->GetDirectNode()) {
  202. auto node_op_desc = n->GetOpDesc();
  203. GE_IF_BOOL_EXEC(node_op_desc == nullptr, continue);
  204. if (!is_loop_graph_ && node_op_desc->GetType() == LOOPCOND) {
  205. is_loop_graph_ = true;
  206. }
  207. // if user set input node format ND, the expected node for data and netoutput format is ND in
  208. // final graph.
  209. if ((domi::GetContext().format == domi::DOMI_TENSOR_ND) &&
  210. ((node_op_desc->GetType() == DATA_TYPE) || (node_op_desc->GetType() == NETOUTPUT))) {
  211. GELOGI("The node [%s] format should be set ND.", node_op_desc->GetName().c_str());
  212. auto inputDescsPtr = node_op_desc->GetAllInputsDescPtr();
  213. auto outputDescsPtr = node_op_desc->GetAllOutputsDescPtr();
  214. ge::Format format = ge::FORMAT_ND;
  215. for (auto &inputDescPtr : inputDescsPtr) {
  216. GE_CHECK_NOTNULL(inputDescPtr);
  217. inputDescPtr->SetFormat(format);
  218. inputDescPtr->SetOriginFormat(format);
  219. }
  220. for (auto &outputDescPtr : outputDescsPtr) {
  221. GE_CHECK_NOTNULL(outputDescPtr);
  222. outputDescPtr->SetFormat(format);
  223. outputDescPtr->SetOriginFormat(format);
  224. }
  225. }
  226. if (node_op_desc->GetType() == DATA_TYPE || node_op_desc->GetType() == AIPP_DATA_TYPE) {
  227. GELOGD("Data node: %s.", n->GetName().c_str());
  228. continue;
  229. }
  230. GE_IF_BOOL_EXEC(n->GetInAllNodes().empty() && n->GetOutAllNodes().empty(), continue;);
  231. SetInputIsConst(n);
  232. if (IsGeLocalOp(n->GetOpDesc())) {
  233. GE_CHK_STATUS_RET(CalcOutputSize(n), "Calculate output size failed");
  234. }
  235. ret = AdjustConstWeightSize(n, weight_offset_);
  236. GE_CHK_STATUS_RET(ret, "AdjustConstWeightSize failed");
  237. GE_IF_BOOL_EXEC(((weight_offset_ > 0) && (weight_offset_ % MEM_ALIGN_SIZE != 0)),
  238. weight_offset_ = (weight_offset_ + MEM_ALIGN_SIZE - 1) / MEM_ALIGN_SIZE * MEM_ALIGN_SIZE);
  239. }
  240. GE_CHK_STATUS_RET(compute_graph_->TopologicalSorting(), "TopologicalSorting failed");
  241. return SUCCESS;
  242. }
  243. void ModelBuilder::AddNodeInputProperty() {
  244. for (const ge::NodePtr &node : compute_graph_->GetDirectNode()) {
  245. auto node_op_desc = node->GetOpDesc();
  246. GE_IF_BOOL_EXEC(node_op_desc == nullptr, GELOGW("node_op_desc is nullptr!"); return );
  247. vector<string> src_name_list;
  248. vector<int64_t> src_index_list;
  249. for (const auto &in_data_anchor : node->GetAllInDataAnchors()) {
  250. auto peer_out_anchor = in_data_anchor->GetPeerOutAnchor();
  251. GE_IF_BOOL_EXEC(peer_out_anchor == nullptr, GELOGW("peer_out_anchor is nullptr!"); continue);
  252. GE_IF_BOOL_EXEC(node_op_desc->HasAttr(MERGE_PRENODE_FLAG), continue);
  253. ge::NodePtr src_node = peer_out_anchor->GetOwnerNode();
  254. src_name_list.emplace_back(src_node->GetName());
  255. src_index_list.emplace_back(peer_out_anchor->GetIdx());
  256. }
  257. auto in_control_anchor = node->GetInControlAnchor();
  258. if (in_control_anchor != nullptr) {
  259. string src_name_temp;
  260. for (const auto &out_control_anchor : in_control_anchor->GetPeerOutControlAnchors()) {
  261. ge::NodePtr src_node = out_control_anchor->GetOwnerNode();
  262. src_name_temp = src_name_temp.empty() ? src_node->GetName() : src_name_temp + ":" + src_node->GetName();
  263. }
  264. GE_IF_BOOL_EXEC(!src_name_temp.empty(), src_name_list.emplace_back(src_name_temp);)
  265. }
  266. node_op_desc->SetSrcName(src_name_list);
  267. node_op_desc->SetSrcIndex(src_index_list);
  268. }
  269. for (const ge::NodePtr &node : compute_graph_->GetDirectNode()) {
  270. auto node_op_desc = node->GetOpDesc();
  271. GE_IF_BOOL_EXEC(node_op_desc == nullptr, GELOGW("node_op_desc is nullptr!"); return );
  272. GE_IF_BOOL_EXEC(node_op_desc->GetType() == NETOUTPUT, continue);
  273. auto out_control_anchor = node->GetOutControlAnchor();
  274. GE_IF_BOOL_EXEC(out_control_anchor == nullptr, GELOGW("out_control_anchor is nullptr"); return );
  275. vector<string> dst_name_list;
  276. vector<int64_t> dst_index_list;
  277. string dst_name_temp;
  278. for (const auto &in_control_anchor : out_control_anchor->GetPeerInControlAnchors()) {
  279. ge::NodePtr dst_node = in_control_anchor->GetOwnerNode();
  280. dst_name_temp = dst_name_temp.empty() ? dst_node->GetName() : dst_name_temp + ":" + dst_node->GetName();
  281. }
  282. GE_IF_BOOL_EXEC(!dst_name_temp.empty(), dst_name_list.emplace_back(dst_name_temp));
  283. GE_IF_BOOL_EXEC(!out_control_anchor->GetPeerInControlAnchors().empty(),
  284. dst_index_list.emplace_back(kInvalidIndexNum));
  285. for (const auto &out_data_anchor : node->GetAllOutDataAnchors()) {
  286. GE_IF_BOOL_EXEC(node_op_desc->HasAttr(MERGE_PRENODE_FLAG), break);
  287. dst_name_temp = "";
  288. int64_t dst_index = kWrongIndex; // assign an impossible value to dst_index.
  289. for (const auto &in_data_anchor : out_data_anchor->GetPeerInDataAnchors()) {
  290. GE_IF_BOOL_EXEC(in_data_anchor == nullptr, GELOGW("in_data_anchor is nullptr"); return );
  291. ge::NodePtr dst_node = in_data_anchor->GetOwnerNode();
  292. dst_name_temp = dst_name_temp.empty() ? dst_node->GetName() : dst_name_temp + ":" + dst_node->GetName();
  293. dst_index = in_data_anchor->GetIdx();
  294. }
  295. GE_IF_BOOL_EXEC(dst_index != kWrongIndex, dst_index_list.emplace_back(dst_index)); // not found
  296. GE_IF_BOOL_EXEC(!dst_name_temp.empty(), dst_name_list.emplace_back(dst_name_temp));
  297. }
  298. node_op_desc->SetDstName(dst_name_list);
  299. node_op_desc->SetDstIndex(dst_index_list);
  300. }
  301. }
  302. Status ModelBuilder::AdjustInputTensorFlag() {
  303. GELOGI("Start to AdjustInputTensorFlag.");
  304. for (const ge::NodePtr &n : compute_graph_->GetDirectNode()) {
  305. if ((n->GetType() == DATA_TYPE) || (n->GetType() == AIPP_DATA_TYPE)) {
  306. GELOGD("Data node: %s.", n->GetName().c_str());
  307. for (const auto &anchor : n->GetAllOutDataAnchors()) {
  308. for (const auto &in_anchors : anchor->GetPeerInDataAnchors()) {
  309. GE_IF_BOOL_EXEC(in_anchors == nullptr, continue);
  310. auto owner_node = in_anchors->GetOwnerNode();
  311. auto owner_node_op_desc = owner_node->GetOpDesc();
  312. GE_IF_BOOL_EXEC(owner_node_op_desc == nullptr, continue);
  313. auto input_desc = owner_node_op_desc->GetInputDesc(in_anchors->GetIdx());
  314. ge::TensorUtils::SetInputTensor(input_desc, true);
  315. if (owner_node_op_desc->UpdateInputDesc(in_anchors->GetIdx(), input_desc) != SUCCESS) {
  316. GELOGE(FAILED, "UpdateOutputDesc failed.");
  317. return FAILED;
  318. }
  319. }
  320. }
  321. }
  322. }
  323. return SUCCESS;
  324. }
  325. void ModelBuilder::InitL1FusionOption() {
  326. string is_l1_fusion_enable = "false";
  327. graphStatus ret = ge::GetContext().GetOption(kEnableL1Fusion, is_l1_fusion_enable);
  328. if (ret == GRAPH_SUCCESS) {
  329. is_l1_fusion_enable_ = is_l1_fusion_enable == "true";
  330. GELOGD("The value of %s is %s.", kEnableL1Fusion.c_str(), is_l1_fusion_enable.c_str());
  331. } else {
  332. GELOGW("The value of %s is empty.", kEnableL1Fusion.c_str());
  333. }
  334. }
  335. Status ModelBuilder::BuildModelDef(ge::Model &model) {
  336. ClearOriginalFormat();
  337. max_mem_offset_ = mem_offset_;
  338. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetInt(&model, ATTR_MODEL_MEMORY_SIZE, max_mem_offset_),
  339. GELOGE(FAILED, "SetInt of ATTR_MODEL_MEMORY_SIZE failed.");
  340. return FAILED);
  341. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetInt(&model, ATTR_MODEL_STREAM_NUM, stream_num_),
  342. GELOGE(FAILED, "SetInt of ATTR_MODEL_STREAM_NUM failed.");
  343. return FAILED);
  344. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetInt(&model, ATTR_MODEL_WEIGHT_SIZE, weight_offset_),
  345. GELOGE(FAILED, "SetInt of ATTR_MODEL_WEIGHT_SIZE failed.");
  346. return FAILED);
  347. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetInt(&model, ATTR_MODEL_EVENT_NUM, event_num_),
  348. GELOGE(FAILED, "SetInt of ATTR_MODEL_EVENT_NUM failed.");
  349. return FAILED);
  350. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetInt(&model, ATTR_MODEL_LABEL_NUM, label_num_),
  351. GELOGE(FAILED, "SetInt of ATTR_MODEL_LABEL_NUM failed.");
  352. return FAILED);
  353. string ge_core_type;
  354. Status ret = ge::GetContext().GetOption(kCoreType, ge_core_type);
  355. if (ret != SUCCESS) {
  356. GELOGW("get the option CORE_TYPE fail, set it to default value VECTOR_ENGINE");
  357. }
  358. int64_t core_type = (ge_core_type == kVectorCore) ? 1 : 0;
  359. GELOGI("core_type: %ld", core_type);
  360. if (!ge::AttrUtils::SetInt(&model, ATTR_MODEL_CORE_TYPE, core_type)) {
  361. GELOGE(FAILED, "SetInt of ATTR_CORE_TYPE failed.");
  362. }
  363. InitL1FusionOption();
  364. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetBool(&model, ATTR_NAME_SWITCH_FOR_L1_FUSION, is_l1_fusion_enable_),
  365. GELOGE(FAILED, "SetBool of ATTR_NAME_SWITCH_FOR_L1_FUSION failed.");
  366. return FAILED);
  367. model.SetName(compute_graph_->GetName());
  368. model.SetGraph(ge::GraphUtils::CreateGraphFromComputeGraph(compute_graph_));
  369. GELOGI("weight_offset_: %zu", weight_offset_);
  370. GELOGI("Set event num: %ld.", event_num_);
  371. if (Params::Instance() == nullptr) {
  372. return FAILED;
  373. }
  374. platform_type_ = Params::Instance()->GetTarget_8bit();
  375. return SUCCESS;
  376. }
  377. void ModelBuilder::ClearOriginalFormat() {
  378. for (const ge::NodePtr &n : compute_graph_->GetDirectNode()) {
  379. auto node_op_desc = n->GetOpDesc();
  380. if (node_op_desc != nullptr) {
  381. if (node_op_desc->HasAttr(ATTR_NAME_FORMAT)) {
  382. if (node_op_desc->DelAttr(ATTR_NAME_FORMAT) != SUCCESS) {
  383. GELOGW("DelAttr ATTR_NAME_FORMAT failed.");
  384. }
  385. }
  386. GE_IF_BOOL_EXEC(
  387. node_op_desc->HasAttr(ATTR_NAME_INFERRED_FORMAT),
  388. if (node_op_desc->DelAttr(ATTR_NAME_INFERRED_FORMAT) != SUCCESS) {
  389. GELOGW("DelAttr ATTR_NAME_INFERRED_FORMAT failed.");
  390. });
  391. GE_IF_BOOL_EXEC(
  392. node_op_desc->HasAttr(ATTR_NAME_PRED_PERMUTE_DELETED),
  393. if (node_op_desc->DelAttr(ATTR_NAME_PRED_PERMUTE_DELETED) != SUCCESS) {
  394. GELOGW("DelAttr ATTR_NAME_PRED_PERMUTE_DELETED failed.");
  395. });
  396. GE_IF_BOOL_EXEC(
  397. node_op_desc->HasAttr(ATTR_NAME_IGNORE_PRED_FORMAT),
  398. if (node_op_desc->DelAttr(ATTR_NAME_IGNORE_PRED_FORMAT) != SUCCESS) {
  399. GELOGW("DelAttr ATTR_NAME_IGNORE_PRED_FORMAT failed.");
  400. });
  401. }
  402. }
  403. }
  404. Status ModelBuilder::MergeWeights() {
  405. if (weight_offset_ == 0) {
  406. return SUCCESS;
  407. }
  408. ge::Buffer buffer(weight_offset_);
  409. weight_buffer_ = buffer;
  410. auto base_addr = weight_buffer_.GetData();
  411. for (const ge::NodePtr &node : compute_graph_->GetAllNodes()) {
  412. auto op_desc = node->GetOpDesc();
  413. GE_IF_BOOL_EXEC(op_desc == nullptr, continue);
  414. if (node->GetType() != CONSTANT) {
  415. continue;
  416. }
  417. // Get const op weight pointer
  418. ge::GeTensorPtr weight = nullptr;
  419. // If MutableTensor failed, weight is nullptr.
  420. (void)ge::AttrUtils::MutableTensor(op_desc, ATTR_NAME_WEIGHTS, weight);
  421. if (weight == nullptr) {
  422. GELOGE(FAILED, "Can't get const op weight, name: %s", node->GetName().c_str());
  423. return FAILED;
  424. }
  425. // Get const op weight offset
  426. int64_t offset = 0;
  427. if (ge::TensorUtils::GetDataOffset(weight->GetTensorDesc(), offset) != SUCCESS) {
  428. GELOGW("Can't get const op offset, name: %s", node->GetName().c_str());
  429. continue; // continue to merge if can not get offset
  430. }
  431. // Get const op weight data
  432. auto weight_data = weight->MutableData();
  433. // copy const op weight data to buffer
  434. GELOGI("Move weight data to buffer, name: %s offset: %ld", node->GetName().c_str(), offset);
  435. ge::TensorUtils::SetWeightSize(weight->MutableTensorDesc(), static_cast<uint32_t>(weight_data.size()));
  436. if ((offset == 0) || (weight_data.size() == 0)) {
  437. GELOGI("Size or offset is 0. size: %lu offset: %ld", weight_data.size(), offset);
  438. continue;
  439. }
  440. if (weight_data.data() != nullptr) {
  441. GE_IF_BOOL_EXEC(base_addr == nullptr, GELOGE(FAILED, "Base addr is nullptr."); return FAILED);
  442. GE_CHK_BOOL_EXEC(
  443. memcpy_s(base_addr + offset, weight_offset_ - offset, weight_data.data(), weight_data.size()) == EOK,
  444. return FAILED, "call memcpy_s failed.");
  445. }
  446. weight_data.clear();
  447. }
  448. return SUCCESS;
  449. }
  450. Status ModelBuilder::SaveDataToModel(ge::Model &model, ge::GeModel &ge_model) {
  451. // Add weight
  452. ge_model.SetWeight(weight_buffer_);
  453. // Add TBE Kernels
  454. for (const ge::NodePtr &n : compute_graph_->GetDirectNode()) {
  455. auto node_op_desc = n->GetOpDesc();
  456. GE_IF_BOOL_EXEC(node_op_desc == nullptr, continue);
  457. TBEKernelPtr tbe_kernel = node_op_desc->TryGetExtAttr(ge::OP_EXTATTR_NAME_TBE_KERNEL, TBEKernelPtr());
  458. GE_IF_BOOL_EXEC(tbe_kernel == nullptr, continue);
  459. tbe_kernel_store_.AddTBEKernel(tbe_kernel);
  460. GELOGD("Add tbe kernel bin %s", tbe_kernel->GetName().c_str());
  461. }
  462. if (!tbe_kernel_store_.Build()) {
  463. GELOGE(FAILED, "TBE Kernels store build failed!");
  464. return FAILED;
  465. }
  466. ge_model.SetTBEKernelStore(tbe_kernel_store_);
  467. // Add task
  468. GeAttrValue::BYTES task_def_bytes;
  469. if (!AttrUtils::GetZeroCopyBytes(model, MODEL_ATTR_TASKS, task_def_bytes)) {
  470. GELOGE(INTERNAL_ERROR, "Get zero copy bytes fail.");
  471. return INTERNAL_ERROR;
  472. }
  473. int byte_size = static_cast<int>(task_def_bytes.GetSize());
  474. std::shared_ptr<domi::ModelTaskDef> task = ge::MakeShared<domi::ModelTaskDef>();
  475. GE_CHECK_NOTNULL(task);
  476. GE_CHK_BOOL_EXEC(ReadProtoFromArray(task_def_bytes.GetData(), byte_size, task.get()), return INTERNAL_ERROR,
  477. "ReadProtoFromArray failed.");
  478. ge_model.SetModelTaskDef(task);
  479. // Add graph
  480. ge_model.SetName(model.GetName());
  481. ge_model.SetGraph(model.GetGraph());
  482. ge_model.SetVersion(model.GetVersion());
  483. ge_model.SetPlatformVersion(model.GetPlatformVersion());
  484. ge_model.SetPlatformType(platform_type_);
  485. ge_model.SetAttr(model.MutableAttrMap());
  486. return SUCCESS;
  487. }
  488. void ModelBuilder::SetModelVersion(ge::Model &model) {
  489. // set framework_version TO model
  490. string framework_version;
  491. uint32_t counter = 0;
  492. Status frame_rt = PlatformVersionManager::GetPlatformVersion(framework_version);
  493. GE_IF_BOOL_EXEC((frame_rt == SUCCESS),
  494. string model_framework_version = framework_version + "." + std::to_string(counter);
  495. model.SetPlatformVersion(model_framework_version););
  496. // set IR Version TO model
  497. model.SetVersion(static_cast<uint32_t>(OM_PROTO_VERSION));
  498. }
  499. Status ModelBuilder::PreBuildModel() {
  500. if ((compute_graph_ == nullptr) || !(compute_graph_->IsValid())) {
  501. GELOGE(FAILED, "Graph_ is not valid.");
  502. return FAILED;
  503. }
  504. GELOGI("BuildModel begin.");
  505. GE_CHK_STATUS_RET(SetInputOutputDesc(), "SetInputOutputDesc Failed!");
  506. AddNodeInputProperty();
  507. return SUCCESS;
  508. }
  509. Status ModelBuilder::BuildModelForGetTask(ge::Model &model) {
  510. GE_CHK_STATUS_RET(AdjustInputTensorFlag(), "AdjustInputTensorFlag failed!");
  511. // Assign logical streams.
  512. StreamAllocator stream_allocator(compute_graph_, subgraphs_);
  513. GE_TIMESTAMP_START(AssignLogicalStreams);
  514. GE_CHK_STATUS_RET(stream_allocator.AssignLogicalStreams(stream_max_parallel_num_, hcom_parallel_),
  515. "Assign logical streams failed.");
  516. GE_TIMESTAMP_END(AssignLogicalStreams, "GraphBuilder::AssignLogicalStreams");
  517. // Assign functional op labels.
  518. GE_TIMESTAMP_START(AssignFunctionalLabels);
  519. LabelAllocator label_allocator(compute_graph_);
  520. GE_CHK_STATUS_RET(label_allocator.AssignFunctionalLabels(label_num_), "Assign label failed.");
  521. GE_TIMESTAMP_END(AssignFunctionalLabels, "ModelBuilder::AssignFunctionalLabels");
  522. GE_TIMESTAMP_START(AssignMemory);
  523. MemoryAssigner mem_assigner(compute_graph_);
  524. GE_CHK_STATUS_RET(mem_assigner.AssignMemory(is_loop_graph_, mem_offset_), "Assign Memory Failed!");
  525. GE_TIMESTAMP_END(AssignMemory, "GraphBuilder::AssignMemory");
  526. // Compile single op in graph build stage
  527. GE_TIMESTAMP_START(CompileSingleOp);
  528. GE_CHK_STATUS_RET(CompileSingleOp(), "ATC builder CompileSingleOp() return fail.");
  529. GE_TIMESTAMP_END(CompileSingleOp, "GraphBuilder::CompileSingleOp");
  530. // Refresh real streams and insert event nodes.
  531. GE_TIMESTAMP_START(RefreshRealStream);
  532. GE_CHK_STATUS_RET(stream_allocator.RefreshRealStream(stream_num_, event_num_), "RefreshRealStream failed.");
  533. GE_TIMESTAMP_END(RefreshRealStream, "GraphBuilder::RefreshRealStream");
  534. GE_TIMESTAMP_START(MergeWeights);
  535. GE_CHK_STATUS_RET(MergeWeights(), "MergeWeights Failed!");
  536. GE_TIMESTAMP_END(MergeWeights, "GraphBuilder::MergeWeights");
  537. GE_TIMESTAMP_START(BuildModelDef);
  538. GE_CHK_STATUS_RET(BuildModelDef(model), "BuildModelDef failed!");
  539. GE_TIMESTAMP_END(BuildModelDef, "GraphBuilder::BuildModelDef");
  540. SetModelVersion(model);
  541. return SUCCESS;
  542. }
  543. ge::Buffer ModelBuilder::GetWeightBuffer() const { return weight_buffer_; }
  544. Status ModelBuilder::CompileSingleOp() {
  545. GELOGD("Begin to compile single op.");
  546. // Create ge instance
  547. std::shared_ptr<GELib> instance = ge::GELib::GetInstance();
  548. if ((instance == nullptr) || !instance->InitFlag()) {
  549. GELOGE(ge::GE_CLI_GE_NOT_INITIALIZED, "CompileSingleOp failed.");
  550. return ge::GE_CLI_GE_NOT_INITIALIZED;
  551. }
  552. GE_TIMESTAMP_CALLNUM_START(BatchCompileOp);
  553. std::unordered_map<string, vector<ge::NodePtr>> node_vector_map;
  554. for (auto &node : compute_graph_->GetAllNodes()) {
  555. auto op_desc = node->GetOpDesc();
  556. if (op_desc == nullptr) {
  557. continue;
  558. }
  559. // Graph build stage only supports the individual compilation of atomic clean operator
  560. if (op_desc->GetType() == ATOMICADDRCLEAN) {
  561. GELOGD("Begin to compile single op, op name is %s.", op_desc->GetName().c_str());
  562. string kernel_lib_name = op_desc->GetOpKernelLibName();
  563. if (kernel_lib_name.empty()) {
  564. // Reset op kernel lib
  565. (void)instance->DNNEngineManagerObj().GetDNNEngineName(op_desc);
  566. kernel_lib_name = op_desc->GetOpKernelLibName();
  567. if (kernel_lib_name.empty()) {
  568. GELOGE(ge::INTERNAL_ERROR, "Get node:%s(%s) kernel lib failed.", node->GetName().c_str(),
  569. node->GetType().c_str());
  570. return ge::INTERNAL_ERROR;
  571. }
  572. }
  573. OpsKernelInfoStorePtr kernel_info = instance->OpsKernelManagerObj().GetOpsKernelInfoStore(kernel_lib_name);
  574. if (kernel_info != nullptr) {
  575. node_vector_map[kernel_lib_name].emplace_back(node);
  576. } else {
  577. GELOGE(ge::GE_GRAPH_PARAM_NULLPTR, "Get op %s ops kernel info store failed", node->GetName().c_str());
  578. return ge::GE_GRAPH_PARAM_NULLPTR;
  579. }
  580. }
  581. }
  582. for (auto &it : node_vector_map) {
  583. auto &kernel_lib_name = it.first;
  584. auto &node_vector = it.second;
  585. OpsKernelInfoStorePtr kernel_info = instance->OpsKernelManagerObj().GetOpsKernelInfoStore(kernel_lib_name);
  586. GE_CHECK_NOTNULL(kernel_info);
  587. GE_TIMESTAMP_RESTART(BatchCompileOp);
  588. auto ret = kernel_info->CompileOp(node_vector);
  589. GEEVENT("[GEPERFTRACE] The node size of compile op of %s is %zu", kernel_lib_name.c_str(), node_vector.size());
  590. GE_TIMESTAMP_ADD(BatchCompileOp);
  591. if (ret != ge::SUCCESS) {
  592. GELOGE(ret, "Compile op failed, kernel lib name is %s", kernel_lib_name.c_str());
  593. return ret;
  594. }
  595. }
  596. GE_TIMESTAMP_CALLNUM_END(BatchCompileOp, "GraphBuild::CompileOp");
  597. return ge::SUCCESS;
  598. }
  599. } // namespace ge

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