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 39 kB

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
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
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
4 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
4 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
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 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
4 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
4 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  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 "graph/build/model_builder.h"
  17. #include <securectype.h>
  18. #include <iostream>
  19. #include <set>
  20. #include <unordered_map>
  21. #include "common/ge/ge_util.h"
  22. #include "common/dump/dump_manager.h"
  23. #include "framework/common/debug/ge_log.h"
  24. #include "graph/anchor.h"
  25. #include "graph/attr_value.h"
  26. #include "graph/buffer.h"
  27. #include "graph/build/stream_allocator.h"
  28. #include "graph/common/omg_util.h"
  29. #include "graph/common/ge_call_wrapper.h"
  30. #include "graph/common/local_context.h"
  31. #include "graph/debug/ge_attr_define.h"
  32. #include "graph/ge_attr_value.h"
  33. #include "graph/ge_context.h"
  34. #include "graph/ge_error_codes.h"
  35. #include "graph/manager/graph_mem_allocator.h"
  36. #include "graph/manager/graph_var_manager.h"
  37. #include "graph/optimize/common/params.h"
  38. #include "graph/types.h"
  39. #include "graph/utils/attr_utils.h"
  40. #include "graph/utils/graph_utils.h"
  41. #include "graph/utils/node_utils.h"
  42. #include "graph/utils/op_desc_utils.h"
  43. #include "graph/utils/tensor_utils.h"
  44. #include "graph/utils/type_utils.h"
  45. #include "init/gelib.h"
  46. #include "memory/memory_assigner.h"
  47. #include "omg/version.h"
  48. #include "register/op_registry.h"
  49. #include "graph/passes/set_input_output_offset_pass.h"
  50. using std::map;
  51. using std::set;
  52. using std::string;
  53. using std::vector;
  54. namespace {
  55. const uint32_t kWeightsStartOffset = 512;
  56. const int32_t kWrongIndex = -2;
  57. const int kInvalidIndexNum = -1;
  58. const char *const kVectorCore = "VectorCore";
  59. const char *const kCoreType = "ge.engineType";
  60. const std::string kEnableL1Fusion = "ge.l1Fusion";
  61. const set<string> adjust_layer_type_ = {ge::CONVOLUTION};
  62. bool IsGeLocalOp(const ge::ConstOpDescPtr &op_desc) {
  63. auto type = op_desc->GetType();
  64. if (type == ge::CONSTANTOP) {
  65. // constant op just has one output
  66. ge::GeTensorDesc output_desc = op_desc->GetOutputDesc(0);
  67. return !(output_desc.GetDataType() == ge::DT_STRING);
  68. }
  69. const set<string> ge_local_set = {ge::STREAMMERGE, ge::MEMCPYASYNC, ge::STREAMACTIVE, ge::STREAMSWITCH,
  70. ge::VARIABLE, ge::NOOP, ge::CONSTANT, ge::ENTER,
  71. ge::REFENTER, ge::LOOPCOND, ge::NEXTITERATION, ge::REFNEXTITERATION,
  72. ge::EXIT, ge::REFEXIT, ge::MERGE, ge::MEMCPYADDRASYNC};
  73. return (ge_local_set.find(type) != ge_local_set.end());
  74. }
  75. } // namespace
  76. namespace ge {
  77. ModelBuilder::ModelBuilder(uint64_t session_id, ge::ComputeGraphPtr compute_graph,
  78. const Graph2SubGraphInfoList &subgraphs, const map<string, int> &stream_max_parallel_num,
  79. bool hcom_parallel, int mode)
  80. : session_id_(session_id),
  81. weight_offset_(kWeightsStartOffset),
  82. compute_graph_(std::move(compute_graph)),
  83. subgraphs_(subgraphs),
  84. stream_num_(0),
  85. event_num_(0),
  86. label_num_(0),
  87. stream_max_parallel_num_(stream_max_parallel_num),
  88. hcom_parallel_(hcom_parallel),
  89. build_mode_(mode),
  90. max_mem_offset_(0),
  91. p2p_mem_offset_(0),
  92. zero_copy_mem_size_(0),
  93. platform_type_(0),
  94. is_loop_graph_(false),
  95. is_l1_fusion_enable_(false) {}
  96. ModelBuilder::~ModelBuilder() {}
  97. Status ModelBuilder::CalcOutputSize(const ge::NodePtr &n) {
  98. GE_CHECK_NOTNULL(n);
  99. auto node_op_desc = n->GetOpDesc();
  100. GE_CHECK_NOTNULL(node_op_desc);
  101. uint32_t index = 0;
  102. for (const auto &output_desc_ptr : node_op_desc->GetAllOutputsDescPtr()) {
  103. GeTensorDesc &desc_temp = *output_desc_ptr;
  104. uint32_t dim_num = static_cast<uint32_t>(desc_temp.GetShape().GetDimNum());
  105. GE_IF_BOOL_EXEC(dim_num > DIM_DEFAULT_SIZE, TensorUtils::SetRealDimCnt(desc_temp, dim_num));
  106. // calculate tensor size
  107. int64_t size_temp = 0;
  108. graphStatus graph_status = TensorUtils::GetTensorMemorySizeInBytes(desc_temp, size_temp);
  109. if (graph_status != GRAPH_SUCCESS) {
  110. GELOGE(graph_status, "GetTensorMemorySizeInBytes failed!");
  111. return FAILED;
  112. }
  113. TensorUtils::SetSize(desc_temp, size_temp);
  114. if (node_op_desc->UpdateOutputDesc(index, desc_temp) != SUCCESS) {
  115. GELOGE(FAILED, "UpdateOutputDesc failed.");
  116. return FAILED;
  117. }
  118. GELOGD("update output desc, dim_size: %u, mem_size: %ld, format: %s, type: %s, node name:%s", dim_num, size_temp,
  119. TypeUtils::FormatToSerialString(desc_temp.GetFormat()).c_str(),
  120. TypeUtils::DataTypeToSerialString(desc_temp.GetDataType()).c_str(), node_op_desc->GetName().c_str());
  121. index++;
  122. }
  123. return SUCCESS;
  124. }
  125. bool ModelBuilder::SetInputConst(const OpDescPtr &op_desc, const NodePtr &src_node, size_t index,
  126. vector<bool> &is_input_const) {
  127. GELOGI("SetIsInputConst const: %s, source node: %s", op_desc->GetName().c_str(), src_node->GetName().c_str());
  128. for (size_t i = is_input_const.size(); i <= index; ++i) {
  129. is_input_const.push_back(false);
  130. }
  131. is_input_const[index] = true;
  132. vector<GeTensorPtr> weights = OpDescUtils::MutableWeights(src_node);
  133. if (weights.empty()) {
  134. GELOGW("SetInputIsConst weights is empty, node: %s", src_node->GetName().c_str());
  135. return false;
  136. }
  137. GeTensorPtr weight = weights[0];
  138. GE_IF_BOOL_EXEC(weight == nullptr, return true);
  139. GeTensorDesc &tensor_desc = weight->MutableTensorDesc();
  140. int64_t data_offset = 0;
  141. if (TensorUtils::GetDataOffset(tensor_desc, data_offset) != GRAPH_SUCCESS) {
  142. GELOGW("Get Offset from weight failed");
  143. return false;
  144. }
  145. auto input_tensor = op_desc->MutableInputDesc(static_cast<uint32_t>(index));
  146. if (input_tensor == nullptr) {
  147. GELOGW("Get input_tensor failed");
  148. return false;
  149. }
  150. TensorUtils::SetDataOffset(*input_tensor, data_offset);
  151. return true;
  152. }
  153. void ModelBuilder::SetInputIsConst(const ge::NodePtr &n) {
  154. auto node_op_desc = n->GetOpDesc();
  155. GE_CHECK_NOTNULL_JUST_RETURN(node_op_desc);
  156. auto is_input_const = node_op_desc->GetIsInputConst();
  157. // must set all true input_const to false
  158. for (size_t i = 0; i < is_input_const.size(); i++) {
  159. is_input_const[i] = false;
  160. }
  161. std::string const_type;
  162. auto in_data_anchors = n->GetAllInDataAnchors();
  163. for (size_t index = 0; index < in_data_anchors.size(); index++) {
  164. auto in_data_anchor = in_data_anchors.at(index);
  165. const auto &peer_out_anchor = in_data_anchor->GetPeerOutAnchor();
  166. GE_IF_BOOL_EXEC(peer_out_anchor == nullptr, continue);
  167. const auto &src_node = peer_out_anchor->GetOwnerNode();
  168. if (!NodeUtils::GetConstOpType(src_node, const_type)) {
  169. continue;
  170. }
  171. if (const_type == CONSTANT) {
  172. if (!SetInputConst(node_op_desc, src_node, index, is_input_const)) {
  173. return;
  174. }
  175. } else {
  176. if ((index < is_input_const.size()) && is_input_const[index]) {
  177. is_input_const[index] = false;
  178. }
  179. }
  180. }
  181. std::string input_const_info = ToString(is_input_const);
  182. GELOGD("update opdesc:%s InputConst:%s", node_op_desc->GetName().c_str(), input_const_info.c_str());
  183. node_op_desc->SetIsInputConst(is_input_const);
  184. }
  185. Status ModelBuilder::AdjustConstWeightSize(const ge::NodePtr &node, size_t &mem_offset) {
  186. GE_CHECK_NOTNULL(node);
  187. if (node->GetType() == CONSTANT) {
  188. vector<GeTensorPtr> weights = OpDescUtils::MutableWeights(node);
  189. if (weights.empty()) {
  190. GELOGE(FAILED, "weights size of node %s is empty", node->GetName().c_str());
  191. return FAILED;
  192. }
  193. GeTensorPtr weight = weights[0];
  194. if (weight == nullptr) {
  195. GELOGE(FAILED, "weights[0] is null.");
  196. return FAILED;
  197. }
  198. GeTensorDesc &tensor_desc = weight->MutableTensorDesc();
  199. size_t output_size = weight->GetData().size();
  200. TensorUtils::SetDataOffset(tensor_desc, mem_offset);
  201. GELOGD("Node: %s, weight size: %zu.", node->GetName().c_str(), output_size);
  202. mem_offset += output_size;
  203. }
  204. return SUCCESS;
  205. }
  206. Status ModelBuilder::SetInputOutputDesc() {
  207. Status ret;
  208. for (const ge::NodePtr &n : compute_graph_->GetNodes(compute_graph_->GetGraphUnknownFlag())) {
  209. auto node_op_desc = n->GetOpDesc();
  210. GE_IF_BOOL_EXEC(node_op_desc == nullptr, continue);
  211. if (!is_loop_graph_ && node_op_desc->GetType() == LOOPCOND) {
  212. is_loop_graph_ = true;
  213. }
  214. // if user set input node format ND, the expected node for data and netoutput format is ND in
  215. // final graph.
  216. if ((GetLocalOmgContext().format == domi::DOMI_TENSOR_ND) && (!node_op_desc->HasAttr("_is_single_op")) &&
  217. ((node_op_desc->GetType() == DATA_TYPE) || (node_op_desc->GetType() == NETOUTPUT))) {
  218. auto inputDescsPtr = node_op_desc->GetAllInputsDescPtr();
  219. auto outputDescsPtr = node_op_desc->GetAllOutputsDescPtr();
  220. ge::Format format = ge::FORMAT_ND;
  221. for (auto &inputDescPtr : inputDescsPtr) {
  222. GE_CHECK_NOTNULL(inputDescPtr);
  223. inputDescPtr->SetFormat(format);
  224. inputDescPtr->SetOriginFormat(format);
  225. }
  226. for (auto &outputDescPtr : outputDescsPtr) {
  227. GE_CHECK_NOTNULL(outputDescPtr);
  228. outputDescPtr->SetFormat(format);
  229. outputDescPtr->SetOriginFormat(format);
  230. }
  231. }
  232. if (node_op_desc->GetType() == DATA_TYPE || node_op_desc->GetType() == AIPP_DATA_TYPE) {
  233. GELOGD("Data node: %s.", n->GetName().c_str());
  234. continue;
  235. }
  236. GE_IF_BOOL_EXEC(n->GetInAllNodes().empty() && n->GetOutAllNodes().empty(), continue;);
  237. SetInputIsConst(n);
  238. bool is_unknow = false;
  239. (void)NodeUtils::GetNodeUnknownShapeStatus(*n, is_unknow);
  240. if ((IsGeLocalOp(n->GetOpDesc())) && (!is_unknow)) {
  241. GE_CHK_STATUS_RET(CalcOutputSize(n), "Calculate output size failed");
  242. }
  243. ret = AdjustConstWeightSize(n, weight_offset_);
  244. GE_CHK_STATUS_RET(ret, "AdjustConstWeightSize failed");
  245. GE_IF_BOOL_EXEC(((weight_offset_ > 0) && (weight_offset_ % MEM_ALIGN_SIZE != 0)),
  246. weight_offset_ = (weight_offset_ + MEM_ALIGN_SIZE - 1) / MEM_ALIGN_SIZE * MEM_ALIGN_SIZE);
  247. }
  248. GE_CHK_STATUS_RET(compute_graph_->TopologicalSorting(), "TopologicalSorting failed");
  249. return SUCCESS;
  250. }
  251. void ModelBuilder::AddNodeInputProperty() {
  252. for (const ge::NodePtr &node : compute_graph_->GetNodes(compute_graph_->GetGraphUnknownFlag())) {
  253. auto node_op_desc = node->GetOpDesc();
  254. GE_IF_BOOL_EXEC(node_op_desc == nullptr, GELOGW("node_op_desc is nullptr!"); return);
  255. vector<string> src_name_list;
  256. vector<int64_t> src_index_list;
  257. for (const auto &in_data_anchor : node->GetAllInDataAnchors()) {
  258. auto peer_out_anchor = in_data_anchor->GetPeerOutAnchor();
  259. GE_IF_BOOL_EXEC(peer_out_anchor == nullptr, continue);
  260. GE_IF_BOOL_EXEC(node_op_desc->HasAttr(MERGE_PRENODE_FLAG), continue);
  261. ge::NodePtr src_node = peer_out_anchor->GetOwnerNode();
  262. src_name_list.emplace_back(src_node->GetName());
  263. src_index_list.emplace_back(peer_out_anchor->GetIdx());
  264. }
  265. auto in_control_anchor = node->GetInControlAnchor();
  266. if (in_control_anchor != nullptr) {
  267. string src_name_temp;
  268. for (const auto &out_control_anchor : in_control_anchor->GetPeerOutControlAnchors()) {
  269. ge::NodePtr src_node = out_control_anchor->GetOwnerNode();
  270. src_name_temp = src_name_temp.empty() ? src_node->GetName() : src_name_temp + ":" + src_node->GetName();
  271. }
  272. GE_IF_BOOL_EXEC(!src_name_temp.empty(), src_name_list.emplace_back(src_name_temp);)
  273. }
  274. node_op_desc->SetSrcName(src_name_list);
  275. node_op_desc->SetSrcIndex(src_index_list);
  276. }
  277. for (const ge::NodePtr &node : compute_graph_->GetNodes(compute_graph_->GetGraphUnknownFlag())) {
  278. auto node_op_desc = node->GetOpDesc();
  279. GE_IF_BOOL_EXEC(node_op_desc == nullptr, GELOGW("node_op_desc is nullptr!"); return);
  280. GE_IF_BOOL_EXEC(node_op_desc->GetType() == NETOUTPUT, continue);
  281. auto out_control_anchor = node->GetOutControlAnchor();
  282. GE_IF_BOOL_EXEC(out_control_anchor == nullptr, GELOGW("out_control_anchor is nullptr"); return);
  283. vector<string> dst_name_list;
  284. vector<int64_t> dst_index_list;
  285. string dst_name_temp;
  286. for (const auto &in_control_anchor : out_control_anchor->GetPeerInControlAnchors()) {
  287. ge::NodePtr dst_node = in_control_anchor->GetOwnerNode();
  288. dst_name_temp = dst_name_temp.empty() ? dst_node->GetName() : dst_name_temp + ":" + dst_node->GetName();
  289. }
  290. GE_IF_BOOL_EXEC(!dst_name_temp.empty(), dst_name_list.emplace_back(dst_name_temp));
  291. GE_IF_BOOL_EXEC(!out_control_anchor->GetPeerInControlAnchors().empty(),
  292. dst_index_list.emplace_back(kInvalidIndexNum));
  293. for (const auto &out_data_anchor : node->GetAllOutDataAnchors()) {
  294. GE_IF_BOOL_EXEC(node_op_desc->HasAttr(MERGE_PRENODE_FLAG), break);
  295. dst_name_temp = "";
  296. int64_t dst_index = kWrongIndex; // assign an impossible value to dst_index.
  297. for (const auto &in_data_anchor : out_data_anchor->GetPeerInDataAnchors()) {
  298. GE_IF_BOOL_EXEC(in_data_anchor == nullptr, GELOGW("in_data_anchor is nullptr"); return);
  299. ge::NodePtr dst_node = in_data_anchor->GetOwnerNode();
  300. dst_name_temp = dst_name_temp.empty() ? dst_node->GetName() : dst_name_temp + ":" + dst_node->GetName();
  301. dst_index = in_data_anchor->GetIdx();
  302. }
  303. GE_IF_BOOL_EXEC(dst_index != kWrongIndex, dst_index_list.emplace_back(dst_index)); // not found
  304. GE_IF_BOOL_EXEC(!dst_name_temp.empty(), dst_name_list.emplace_back(dst_name_temp));
  305. }
  306. node_op_desc->SetDstName(dst_name_list);
  307. node_op_desc->SetDstIndex(dst_index_list);
  308. }
  309. }
  310. Status ModelBuilder::AdjustInputTensorFlag() {
  311. for (const ge::NodePtr &n : compute_graph_->GetNodes(compute_graph_->GetGraphUnknownFlag())) {
  312. if ((n->GetType() == DATA_TYPE) || (n->GetType() == AIPP_DATA_TYPE)) {
  313. GELOGD("Data node: %s.", n->GetName().c_str());
  314. for (const auto &anchor : n->GetAllOutDataAnchors()) {
  315. for (const auto &in_anchors : anchor->GetPeerInDataAnchors()) {
  316. GE_IF_BOOL_EXEC(in_anchors == nullptr, continue);
  317. auto owner_node = in_anchors->GetOwnerNode();
  318. auto owner_node_op_desc = owner_node->GetOpDesc();
  319. GE_IF_BOOL_EXEC(owner_node_op_desc == nullptr, continue);
  320. auto input_desc = owner_node_op_desc->GetInputDesc(in_anchors->GetIdx());
  321. ge::TensorUtils::SetInputTensor(input_desc, true);
  322. if (owner_node_op_desc->UpdateInputDesc(in_anchors->GetIdx(), input_desc) != SUCCESS) {
  323. GELOGE(FAILED, "UpdateOutputDesc failed.");
  324. return FAILED;
  325. }
  326. }
  327. }
  328. }
  329. }
  330. return SUCCESS;
  331. }
  332. void ModelBuilder::InitL1FusionOption() {
  333. string buffer_optimize = "off_optimize";
  334. graphStatus ret = ge::GetContext().GetOption(BUFFER_OPTIMIZE, buffer_optimize);
  335. if (ret == GRAPH_SUCCESS) {
  336. bool off_superkernel = false;
  337. (void)AttrUtils::GetBool(compute_graph_, ATTR_NAME_OFF_SUPERKERNEL_ATTR, off_superkernel);
  338. is_l1_fusion_enable_ = ((buffer_optimize == "l1_optimize") && (!off_superkernel));
  339. GELOGI("Compute graph %s the value of %s is %s, superkernel flag %d.", compute_graph_->GetName().c_str(),
  340. BUFFER_OPTIMIZE.c_str(), buffer_optimize.c_str(), is_l1_fusion_enable_);
  341. } else {
  342. GELOGW("The value of %s is empty.", kEnableL1Fusion.c_str());
  343. }
  344. }
  345. Status ModelBuilder::BuildModelDef(ge::Model &model) {
  346. ClearOriginalFormat();
  347. max_mem_offset_ = mem_type_to_mem_offset_[RT_MEMORY_HBM];
  348. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetInt(&model, ATTR_MODEL_MEMORY_SIZE, max_mem_offset_),
  349. GELOGE(FAILED, "SetInt of ATTR_MODEL_MEMORY_SIZE failed.");
  350. return FAILED);
  351. if (mem_type_to_mem_offset_.find(RT_MEMORY_P2P_DDR) != mem_type_to_mem_offset_.end()) {
  352. p2p_mem_offset_ = mem_type_to_mem_offset_[RT_MEMORY_P2P_DDR];
  353. }
  354. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetInt(&model, ATTR_MODEL_P2P_MEMORY_SIZE, p2p_mem_offset_),
  355. GELOGE(FAILED, "SetInt of ATTR_MODEL_P2P_MEMORY_SIZE failed.");
  356. return FAILED);
  357. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetInt(&model, ATTR_MODEL_WEIGHT_SIZE, weight_offset_),
  358. GELOGE(FAILED, "SetInt of ATTR_MODEL_WEIGHT_SIZE failed.");
  359. return FAILED);
  360. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetInt(&model, ATTR_MODEL_STREAM_NUM, stream_num_),
  361. GELOGE(FAILED, "SetInt of ATTR_MODEL_STREAM_NUM failed.");
  362. return FAILED);
  363. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetInt(&model, ATTR_MODEL_EVENT_NUM, event_num_),
  364. GELOGE(FAILED, "SetInt of ATTR_MODEL_EVENT_NUM failed.");
  365. return FAILED);
  366. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetListInt(&model, ATTR_MODEL_HUGE_STREAM_LIST, huge_streams_),
  367. GELOGE(FAILED, "SetInt of ATTR_MODEL_HUGE_STREAM_LIST failed.");
  368. return FAILED);
  369. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetInt(&model, ATTR_MODEL_LABEL_NUM, label_num_),
  370. GELOGE(FAILED, "SetInt of ATTR_MODEL_LABEL_NUM failed.");
  371. return FAILED);
  372. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetInt(&model, ATTR_MODEL_ZERO_COPY_MEMORY_SIZE, zero_copy_mem_size_),
  373. GELOGE(FAILED, "SetInt of ATTR_MODEL_ZERO_COPY_MEMORY_SIZE failed.");
  374. return FAILED);
  375. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetListStr(&model, ATTR_MODEL_OUT_NODES_NAME, GetLocalOmgContext().net_out_nodes),
  376. GELOGE(FAILED, "SetListStr of ATTR_MODEL_OUT_NODES_NAME failed.");
  377. return FAILED);
  378. GELOGI("For model, max_mem_offset_: %zu, p2p_mem_size: %zu, zero_copy_mem_size_: %zu", max_mem_offset_,
  379. p2p_mem_offset_, zero_copy_mem_size_);
  380. string fp_ceiling_mode;
  381. if (ge::GetContext().GetOption("ge.fpCeilingMode", fp_ceiling_mode) == SUCCESS) {
  382. if (!ge::AttrUtils::SetStr(&model, ATTR_FP_CEILING_MODE, fp_ceiling_mode)) {
  383. GELOGE(FAILED, "Failed to set attr ATTR_FP_CEILING_MODE");
  384. return FAILED;
  385. }
  386. GELOGI("Set attr ATTR_FP_CEILING_MODE to model, value is %s.", fp_ceiling_mode.c_str());
  387. }
  388. string ge_core_type;
  389. Status ret = ge::GetContext().GetOption(kCoreType, ge_core_type);
  390. if (ret != SUCCESS) {
  391. GELOGW("get the option CORE_TYPE fail, set it to default value VECTOR_ENGINE");
  392. }
  393. int64_t core_type = (ge_core_type == kVectorCore) ? 1 : 0;
  394. GELOGI("core_type: %ld", core_type);
  395. if (!ge::AttrUtils::SetInt(&model, ATTR_MODEL_CORE_TYPE, core_type)) {
  396. GELOGE(FAILED, "SetInt of ATTR_CORE_TYPE failed.");
  397. }
  398. InitL1FusionOption();
  399. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetBool(&model, ATTR_NAME_SWITCH_FOR_L1_FUSION, is_l1_fusion_enable_),
  400. GELOGE(FAILED, "SetBool of ATTR_NAME_SWITCH_FOR_L1_FUSION failed.");
  401. return FAILED);
  402. const DumpProperties &dump_properties = DumpManager::GetInstance().GetDumpProperties(session_id_);
  403. bool is_op_debug = dump_properties.IsOpDebugOpen();
  404. if (is_op_debug) {
  405. if (!ge::AttrUtils::SetBool(&model, ATTR_OP_DEBUG_FLAG, is_op_debug)) {
  406. GELOGE(FAILED, "SetBool of ATTR_OP_DEBUG_FLAG failed.");
  407. return FAILED;
  408. }
  409. uint32_t op_debug_mode = dump_properties.GetOpDebugMode();
  410. GELOGI("Get op debug mode:%d", op_debug_mode);
  411. if (!ge::AttrUtils::SetInt(&model, ATTR_OP_DEBUG_MODE, op_debug_mode)) {
  412. GELOGE(FAILED, "SetBool of ATTR_OP_DEBUG_MODE failed.");
  413. return FAILED;
  414. }
  415. }
  416. model.SetName(compute_graph_->GetName());
  417. model.SetGraph(ge::GraphUtils::CreateGraphFromComputeGraph(compute_graph_));
  418. GELOGI("weight_offset_: %zu", weight_offset_);
  419. GELOGI("Set event num: %ld.", event_num_);
  420. if (Params::Instance() == nullptr) {
  421. return FAILED;
  422. }
  423. platform_type_ = Params::Instance()->GetTarget_8bit();
  424. return SUCCESS;
  425. }
  426. void ModelBuilder::ClearOriginalFormat() {
  427. for (const ge::NodePtr &n : compute_graph_->GetNodes(compute_graph_->GetGraphUnknownFlag())) {
  428. auto node_op_desc = n->GetOpDesc();
  429. if (node_op_desc != nullptr) {
  430. if (node_op_desc->HasAttr(ATTR_NAME_FORMAT)) {
  431. if (node_op_desc->DelAttr(ATTR_NAME_FORMAT) != SUCCESS) {
  432. GELOGW("DelAttr ATTR_NAME_FORMAT failed.");
  433. }
  434. }
  435. GE_IF_BOOL_EXEC(
  436. node_op_desc->HasAttr(ATTR_NAME_INFERRED_FORMAT),
  437. if (node_op_desc->DelAttr(ATTR_NAME_INFERRED_FORMAT) != SUCCESS) {
  438. GELOGW("DelAttr ATTR_NAME_INFERRED_FORMAT failed.");
  439. });
  440. GE_IF_BOOL_EXEC(
  441. node_op_desc->HasAttr(ATTR_NAME_PRED_PERMUTE_DELETED),
  442. if (node_op_desc->DelAttr(ATTR_NAME_PRED_PERMUTE_DELETED) != SUCCESS) {
  443. GELOGW("DelAttr ATTR_NAME_PRED_PERMUTE_DELETED failed.");
  444. });
  445. GE_IF_BOOL_EXEC(
  446. node_op_desc->HasAttr(ATTR_NAME_IGNORE_PRED_FORMAT),
  447. if (node_op_desc->DelAttr(ATTR_NAME_IGNORE_PRED_FORMAT) != SUCCESS) {
  448. GELOGW("DelAttr ATTR_NAME_IGNORE_PRED_FORMAT failed.");
  449. });
  450. }
  451. }
  452. }
  453. Status ModelBuilder::MergeWeights() {
  454. if (weight_offset_ == 0) {
  455. return SUCCESS;
  456. }
  457. ge::Buffer buffer(weight_offset_);
  458. weight_buffer_ = buffer;
  459. auto base_addr = weight_buffer_.GetData();
  460. for (const ge::NodePtr &node : compute_graph_->GetNodes(compute_graph_->GetGraphUnknownFlag())) {
  461. auto op_desc = node->GetOpDesc();
  462. GE_IF_BOOL_EXEC(op_desc == nullptr, continue);
  463. if (node->GetType() != CONSTANT) {
  464. continue;
  465. }
  466. // Get const op weight pointer
  467. ge::GeTensorPtr weight = nullptr;
  468. // If MutableTensor failed, weight is nullptr.
  469. (void)ge::AttrUtils::MutableTensor(op_desc, ATTR_NAME_WEIGHTS, weight);
  470. if (weight == nullptr) {
  471. GELOGE(FAILED, "Can't get const op weight, name: %s", node->GetName().c_str());
  472. return FAILED;
  473. }
  474. // Get const op weight offset
  475. int64_t offset = 0;
  476. if (ge::TensorUtils::GetDataOffset(weight->GetTensorDesc(), offset) != SUCCESS) {
  477. GELOGW("Can't get const op offset, name: %s", node->GetName().c_str());
  478. continue; // continue to merge if can not get offset
  479. }
  480. // Get const op weight data
  481. auto weight_data = weight->MutableData();
  482. // copy const op weight data to buffer
  483. GELOGI("Move to buffer, name: %s offset: %ld size: %zu", node->GetName().c_str(), offset, weight_data.size());
  484. ge::TensorUtils::SetWeightSize(weight->MutableTensorDesc(), static_cast<uint32_t>(weight_data.size()));
  485. if ((offset == 0) || (weight_data.size() == 0)) {
  486. GELOGI("Size or offset is 0. size: %lu offset: %ld", weight_data.size(), offset);
  487. continue;
  488. }
  489. if (weight_data.data() != nullptr) {
  490. GE_IF_BOOL_EXEC(base_addr == nullptr, GELOGE(FAILED, "Base addr is nullptr."); return FAILED);
  491. if (weight_offset_ - offset < weight_data.size()) {
  492. GELOGE(FAILED, "left weight size not enough. left_size:%lu, weight_size:%lu",
  493. weight_offset_ - offset, weight_data.size());
  494. return FAILED;
  495. }
  496. uintptr_t dst_ptr = reinterpret_cast<uintptr_t>(base_addr) + offset;
  497. uintptr_t src_ptr = reinterpret_cast<uintptr_t>(weight_data.data());
  498. size_t left_size = weight_data.size();
  499. while (left_size > SECUREC_MEM_MAX_LEN) {
  500. auto err = memcpy_s(reinterpret_cast<void *>(dst_ptr), SECUREC_MEM_MAX_LEN, reinterpret_cast<void *>(src_ptr),
  501. SECUREC_MEM_MAX_LEN);
  502. if (err != EOK) {
  503. GELOGE(FAILED, "mem copy failed. errret:%u, "
  504. "dst_ptr:%lx, dst_size:%lu, src_ptr:%lx, src_size:%lu",
  505. err, dst_ptr, SECUREC_MEM_MAX_LEN, src_ptr, SECUREC_MEM_MAX_LEN);
  506. return FAILED;
  507. }
  508. left_size -= SECUREC_MEM_MAX_LEN;
  509. dst_ptr = dst_ptr + SECUREC_MEM_MAX_LEN;
  510. src_ptr = src_ptr + SECUREC_MEM_MAX_LEN;
  511. }
  512. auto err = memcpy_s(reinterpret_cast<void *>(dst_ptr), left_size, reinterpret_cast<void *>(src_ptr), left_size);
  513. if (err != EOK) {
  514. GELOGE(FAILED, "mem copy failed. errret:%u, "
  515. "dst_ptr:%lx, dst_size:%lu, src_ptr:%lx, src_size:%lu",
  516. err, dst_ptr, SECUREC_MEM_MAX_LEN, src_ptr, SECUREC_MEM_MAX_LEN);
  517. return FAILED;
  518. }
  519. }
  520. weight->ClearData();
  521. }
  522. return SUCCESS;
  523. }
  524. Status ModelBuilder::SaveAtomicTBEKernel(const OpDescPtr &op_desc) {
  525. ge::NodePtr atomic_clean_node = nullptr;
  526. atomic_clean_node = op_desc->TryGetExtAttr("atomic_clean_node_ptr", atomic_clean_node);
  527. if (atomic_clean_node == nullptr) {
  528. return SUCCESS;
  529. }
  530. ge::OpDescPtr atomic_op_desc = atomic_clean_node->GetOpDesc();
  531. GE_CHECK_NOTNULL(atomic_op_desc);
  532. TBEKernelPtr tbe_kernel = atomic_op_desc->TryGetExtAttr(ge::OP_EXTATTR_NAME_TBE_KERNEL, TBEKernelPtr());
  533. if (tbe_kernel == nullptr) {
  534. std::string kernel_name;
  535. GeAttrValue::BYTES kernel_buffer;
  536. (void) AttrUtils::GetStr(atomic_op_desc, ATTR_NAME_TBE_KERNEL_NAME, kernel_name);
  537. (void) AttrUtils::GetBytes(atomic_op_desc, ATTR_NAME_TBE_KERNEL_BUFFER, kernel_buffer);
  538. if (!kernel_name.empty() && (kernel_buffer.GetSize() > 0)) {
  539. GE_CHECK_NOTNULL(kernel_buffer.GetData());
  540. std::vector<char> data(kernel_buffer.GetData(), kernel_buffer.GetData() + kernel_buffer.GetSize());
  541. tbe_kernel = MakeShared<OpKernelBin>(kernel_name, std::move(data));
  542. GE_CHECK_NOTNULL(tbe_kernel);
  543. }
  544. }
  545. if (tbe_kernel == nullptr) {
  546. GELOGD("Atomic_clean_node doesn't have tbe_kernel.");
  547. return SUCCESS;
  548. }
  549. tbe_kernel_store_.AddTBEKernel(tbe_kernel);
  550. GELOGD("Atomic_clean_node tbe_kernel_name %s!", tbe_kernel->GetName().c_str());
  551. (void) AttrUtils::SetStr(op_desc, ATOMIC_ATTR_TBE_KERNEL_NAME, tbe_kernel->GetName());
  552. std::string kernel_name;
  553. (void) AttrUtils::GetStr(atomic_op_desc, atomic_op_desc->GetName() + "_kernelname", kernel_name);
  554. (void) AttrUtils::SetStr(op_desc, op_desc->GetName() + "_atomic_kernelname", kernel_name);
  555. std::string meta_data;
  556. (void) AttrUtils::GetStr(atomic_op_desc, TVM_ATTR_NAME_METADATA, meta_data);
  557. (void) AttrUtils::SetStr(op_desc, ATOMIC_ATTR_TVM_METADATA, meta_data);
  558. std::string json_string;
  559. (void) AttrUtils::GetStr(atomic_op_desc, TVM_ATTR_NAME_MAGIC, json_string);
  560. (void) AttrUtils::SetStr(op_desc, ATOMIC_ATTR_TVM_MAGIC, json_string);
  561. return SUCCESS;
  562. }
  563. Status ModelBuilder::SaveDataToModel(ge::Model &model, ge::GeModel &ge_model) {
  564. // Add weight
  565. ge_model.SetWeight(weight_buffer_);
  566. // Add TBE Kernels and custom aicpu op bin
  567. std::set<std::string> tbe_name_set;
  568. std::set<std::string> aicpu_name_set;
  569. std::set<std::string> aicpu_op_types;
  570. std::set<std::string> aicpu_tf_op_types;
  571. for (const ge::NodePtr &n : compute_graph_->GetNodes(compute_graph_->GetGraphUnknownFlag())) {
  572. auto node_op_desc = n->GetOpDesc();
  573. GE_IF_BOOL_EXEC(node_op_desc == nullptr, continue);
  574. // check aicpu op type
  575. CollectCheckAicpuAttr(node_op_desc, aicpu_op_types, aicpu_tf_op_types);
  576. TBEKernelPtr tbe_kernel = node_op_desc->TryGetExtAttr(ge::OP_EXTATTR_NAME_TBE_KERNEL, TBEKernelPtr());
  577. if (tbe_kernel == nullptr) {
  578. std::string kernel_name;
  579. GeAttrValue::BYTES kernel_buffer;
  580. (void) AttrUtils::GetStr(node_op_desc, ATTR_NAME_TBE_KERNEL_NAME, kernel_name);
  581. (void) AttrUtils::GetBytes(node_op_desc, ATTR_NAME_TBE_KERNEL_BUFFER, kernel_buffer);
  582. if (!kernel_name.empty() && (kernel_buffer.GetSize() > 0)) {
  583. GE_CHECK_NOTNULL(kernel_buffer.GetData());
  584. std::vector<char> data(kernel_buffer.GetData(), kernel_buffer.GetData() + kernel_buffer.GetSize());
  585. tbe_kernel = std::make_shared<OpKernelBin>(kernel_name, std::move(data));
  586. }
  587. }
  588. GE_IF_BOOL_EXEC(tbe_kernel == nullptr, continue);
  589. if (tbe_name_set.count(tbe_kernel->GetName()) > 0) {
  590. GELOGE(FAILED, "tbe_kernel name %s can't be the same", tbe_kernel->GetName().c_str());
  591. return FAILED;
  592. }
  593. tbe_name_set.insert(tbe_kernel->GetName());
  594. tbe_kernel_store_.AddTBEKernel(tbe_kernel);
  595. GE_CHK_STATUS_RET(SaveAtomicTBEKernel(node_op_desc), "[Save][TBEKernel] save atomic tbekernel failed!");
  596. }
  597. SetModelCheckAicpuAttr(model, aicpu_op_types, aicpu_tf_op_types);
  598. for (const ge::NodePtr &n : compute_graph_->GetNodes(compute_graph_->GetGraphUnknownFlag())) {
  599. auto node_op_desc = n->GetOpDesc();
  600. GE_IF_BOOL_EXEC(node_op_desc == nullptr, continue);
  601. CustAICPUKernelPtr cust_aicpu_kernel =
  602. node_op_desc->TryGetExtAttr(ge::OP_EXTATTR_CUSTAICPU_KERNEL, CustAICPUKernelPtr());
  603. GE_IF_BOOL_EXEC(cust_aicpu_kernel == nullptr, continue);
  604. if (aicpu_name_set.count(cust_aicpu_kernel->GetName()) > 0) {
  605. GELOGE(FAILED, "aicpu_kernel name %s can't be the same", cust_aicpu_kernel->GetName().c_str());
  606. return FAILED;
  607. }
  608. aicpu_name_set.insert(cust_aicpu_kernel->GetName());
  609. cust_aicpu_kernel_store_.AddCustAICPUKernel(cust_aicpu_kernel);
  610. GELOGI("Add cust aicpu kernel bin %s", cust_aicpu_kernel->GetName().c_str());
  611. }
  612. if (!tbe_kernel_store_.Build()) {
  613. GELOGE(FAILED, "TBE Kernels store build failed!");
  614. return FAILED;
  615. }
  616. if (!cust_aicpu_kernel_store_.Build()) {
  617. GELOGE(FAILED, "custom AICPU kernels store build failed!");
  618. return FAILED;
  619. }
  620. ge_model.SetTBEKernelStore(tbe_kernel_store_);
  621. ge_model.SetCustAICPUKernelStore(cust_aicpu_kernel_store_);
  622. // Add task
  623. GeAttrValue::BYTES task_def_bytes;
  624. if (!AttrUtils::GetZeroCopyBytes(model, MODEL_ATTR_TASKS, task_def_bytes)) {
  625. GELOGE(INTERNAL_ERROR, "Get zero copy bytes fail.");
  626. return INTERNAL_ERROR;
  627. }
  628. int byte_size = static_cast<int>(task_def_bytes.GetSize());
  629. std::shared_ptr<domi::ModelTaskDef> task = ge::MakeShared<domi::ModelTaskDef>();
  630. GE_CHECK_NOTNULL(task);
  631. GE_CHK_BOOL_EXEC(ReadProtoFromArray(task_def_bytes.GetData(), byte_size, task.get()), return INTERNAL_ERROR,
  632. "ReadProtoFromArray failed.");
  633. ge_model.SetModelTaskDef(task);
  634. // Add graph
  635. ge_model.SetName(model.GetName());
  636. ge_model.SetGraph(model.GetGraph());
  637. ge_model.SetVersion(model.GetVersion());
  638. ge_model.SetPlatformVersion(model.GetPlatformVersion());
  639. ge_model.SetPlatformType(platform_type_);
  640. ge_model.SetAttr(model.MutableAttrMap());
  641. return SUCCESS;
  642. }
  643. void ModelBuilder::SetModelVersion(ge::Model &model) {
  644. // set framework_version TO model
  645. string framework_version;
  646. uint32_t counter = 0;
  647. Status frame_rt = PlatformVersionManager::GetPlatformVersion(framework_version);
  648. GE_IF_BOOL_EXEC((frame_rt == SUCCESS),
  649. string model_framework_version = framework_version + "." + std::to_string(counter);
  650. model.SetPlatformVersion(model_framework_version););
  651. // set IR Version TO model
  652. model.SetVersion(static_cast<uint32_t>(OM_PROTO_VERSION));
  653. }
  654. Status ModelBuilder::PreBuildModel() {
  655. if ((compute_graph_ == nullptr) || !(compute_graph_->IsValid())) {
  656. GELOGE(FAILED, "Graph_ is not valid.");
  657. return FAILED;
  658. }
  659. GE_CHK_STATUS_RET(SetInputOutputDesc(), "SetInputOutputDesc Failed!");
  660. AddNodeInputProperty();
  661. return SUCCESS;
  662. }
  663. Status ModelBuilder::BuildModelForGetTask(ge::Model &model) {
  664. GE_CHK_STATUS_RET(AdjustInputTensorFlag(), "AdjustInputTensorFlag failed!");
  665. ErrorManager::GetInstance().SetStage(ErrorMessage::kModelCompile, ErrorMessage::kStreamAlloc);
  666. // Assign logical streams.
  667. StreamAllocator stream_allocator(compute_graph_, subgraphs_);
  668. GE_TIMESTAMP_START(AssignLogicalStreams);
  669. GE_CHK_STATUS_RET(stream_allocator.AssignLogicalStreams(stream_max_parallel_num_, hcom_parallel_),
  670. "Assign logical streams failed.");
  671. GE_TIMESTAMP_END(AssignLogicalStreams, "GraphBuilder::AssignLogicalStreams");
  672. ErrorManager::GetInstance().SetStage(ErrorMessage::kModelCompile, ErrorMessage::kMemoryAlloc);
  673. // Assign functional op labels.
  674. auto root_graph = GraphUtils::FindRootGraph(compute_graph_);
  675. (void)AttrUtils::GetInt(*root_graph, ATTR_MODEL_LABEL_NUM, label_num_);
  676. GE_TIMESTAMP_START(AssignMemory);
  677. MemoryAssigner mem_assigner(compute_graph_);
  678. GE_CHK_STATUS_RET(mem_assigner.AssignMemory(is_loop_graph_, mem_type_to_mem_offset_, zero_copy_mem_size_),
  679. "Assign Memory Failed!");
  680. GE_TIMESTAMP_END(AssignMemory, "GraphBuilder::AssignMemory");
  681. ErrorManager::GetInstance().SetStage(ErrorMessage::kModelCompile, ErrorMessage::kOther);
  682. GE_TIMESTAMP_START(SetInputOutputOffset);
  683. SetInputOutputOffsetPass input_output_offset;
  684. GE_CHK_STATUS_RET(input_output_offset.Run(compute_graph_), "Set input output offset failed.");
  685. GE_TIMESTAMP_END(SetInputOutputOffset, "SetInputOutputOffsetPass::Run");
  686. // Compile single op in graph build stage
  687. GE_TIMESTAMP_START(CompileSingleOp);
  688. GE_CHK_STATUS_RET(CompileSingleOp(), "ATC builder CompileSingleOp() return fail.");
  689. GE_TIMESTAMP_EVENT_END(CompileSingleOp, "GraphBuilder::CompileSingleOp");
  690. ErrorManager::GetInstance().SetStage(ErrorMessage::kModelCompile, ErrorMessage::kStreamAlloc);
  691. // Refresh real streams and insert event nodes.
  692. GE_TIMESTAMP_START(RefreshRealStream);
  693. GE_CHK_STATUS_RET(stream_allocator.RefreshRealStream(stream_num_, event_num_), "RefreshRealStream failed.");
  694. huge_streams_ = stream_allocator.GetHugeStreams();
  695. GE_TIMESTAMP_END(RefreshRealStream, "GraphBuilder::RefreshRealStream");
  696. ErrorManager::GetInstance().SetStage(ErrorMessage::kModelCompile, ErrorMessage::kOther);
  697. GE_TIMESTAMP_START(MergeWeights);
  698. GE_CHK_STATUS_RET(MergeWeights(), "MergeWeights Failed!");
  699. GE_TIMESTAMP_END(MergeWeights, "GraphBuilder::MergeWeights");
  700. GE_TIMESTAMP_START(BuildModelDef);
  701. GE_CHK_STATUS_RET(BuildModelDef(model), "BuildModelDef failed!");
  702. GE_TIMESTAMP_END(BuildModelDef, "GraphBuilder::BuildModelDef");
  703. SetModelVersion(model);
  704. return SUCCESS;
  705. }
  706. Status ModelBuilder::BuildModelForGetDynShapeTask(ge::Model &model_def) {
  707. GE_TIMESTAMP_START(BuildModelDef);
  708. GE_CHK_STATUS_RET(BuildModelDef(model_def), "BuildModelDef failed!");
  709. GE_TIMESTAMP_END(BuildModelDef, "GraphBuilder::BuildModelDef");
  710. SetModelVersion(model_def);
  711. return SUCCESS;
  712. }
  713. ge::Buffer ModelBuilder::GetWeightBuffer() const { return weight_buffer_; }
  714. Status ModelBuilder::CompileSingleOp() {
  715. GELOGD("Begin to compile single op.");
  716. // Create ge instance
  717. std::shared_ptr<GELib> instance = ge::GELib::GetInstance();
  718. if ((instance == nullptr) || !instance->InitFlag()) {
  719. GELOGE(ge::GE_CLI_GE_NOT_INITIALIZED, "CompileSingleOp failed.");
  720. return ge::GE_CLI_GE_NOT_INITIALIZED;
  721. }
  722. GE_TIMESTAMP_CALLNUM_START(BatchCompileOp);
  723. std::unordered_map<string, vector<ge::NodePtr>> node_vector_map;
  724. for (auto &node : compute_graph_->GetNodes(compute_graph_->GetGraphUnknownFlag())) {
  725. auto op_desc = node->GetOpDesc();
  726. if (op_desc == nullptr) {
  727. continue;
  728. }
  729. // Graph build stage only supports the individual compilation of atomic clean operator
  730. if (op_desc->GetType() == ATOMICADDRCLEAN) {
  731. GELOGD("Begin to compile single op, op name is %s.", op_desc->GetName().c_str());
  732. string kernel_lib_name = op_desc->GetOpKernelLibName();
  733. if (kernel_lib_name.empty()) {
  734. // Reset op kernel lib
  735. (void)instance->DNNEngineManagerObj().GetDNNEngineName(node);
  736. kernel_lib_name = op_desc->GetOpKernelLibName();
  737. if (kernel_lib_name.empty()) {
  738. GELOGE(ge::INTERNAL_ERROR, "Get node:%s(%s) kernel lib failed.", node->GetName().c_str(),
  739. node->GetType().c_str());
  740. return ge::INTERNAL_ERROR;
  741. }
  742. }
  743. OpsKernelInfoStorePtr kernel_info = instance->OpsKernelManagerObj().GetOpsKernelInfoStore(kernel_lib_name);
  744. if (kernel_info != nullptr) {
  745. node_vector_map[kernel_lib_name].emplace_back(node);
  746. } else {
  747. GELOGE(ge::GE_GRAPH_PARAM_NULLPTR, "Get op %s ops kernel info store failed", node->GetName().c_str());
  748. return ge::GE_GRAPH_PARAM_NULLPTR;
  749. }
  750. }
  751. }
  752. for (auto &it : node_vector_map) {
  753. auto &kernel_lib_name = it.first;
  754. auto &node_vector = it.second;
  755. OpsKernelInfoStorePtr kernel_info = instance->OpsKernelManagerObj().GetOpsKernelInfoStore(kernel_lib_name);
  756. GE_CHECK_NOTNULL(kernel_info);
  757. GE_TIMESTAMP_RESTART(BatchCompileOp);
  758. auto ret = kernel_info->CompileOp(node_vector);
  759. GELOGI("[GEPERFTRACE] The node size of compile op of %s is %zu", kernel_lib_name.c_str(), node_vector.size());
  760. GE_TIMESTAMP_ADD(BatchCompileOp);
  761. if (ret != ge::SUCCESS) {
  762. GELOGE(ret, "Compile op failed, kernel lib name is %s", kernel_lib_name.c_str());
  763. return ret;
  764. }
  765. }
  766. GE_TIMESTAMP_CALLNUM_END(BatchCompileOp, "GraphBuild::CompileOp");
  767. return ge::SUCCESS;
  768. }
  769. void ModelBuilder::CollectCheckAicpuAttr(const OpDescPtr &op_desc, std::set<std::string> &aicpu_op_types,
  770. std::set<std::string> &aicpu_tf_op_types) {
  771. std::string aicpu_optype;
  772. bool has_attr_check_cpu = ge::AttrUtils::GetStr(op_desc, "needCheckCpu", aicpu_optype);
  773. std::vector<std::string> tf_optypes;
  774. bool has_attr_check_tf = ge::AttrUtils::GetListStr(op_desc, "needCheckTf", tf_optypes);
  775. if (has_attr_check_cpu && !aicpu_optype.empty()) {
  776. aicpu_op_types.insert(aicpu_optype);
  777. }
  778. if (has_attr_check_tf && !tf_optypes.empty()) {
  779. aicpu_tf_op_types.insert(tf_optypes.begin(), tf_optypes.end());
  780. }
  781. return;
  782. }
  783. void ModelBuilder::SetModelCheckAicpuAttr(ge::Model &model, std::set<std::string> &aicpu_op_types,
  784. std::set<std::string> &aicpu_tf_op_types) {
  785. std::vector<std::string> aicpu_optype_list;
  786. std::vector<std::string> aicpu_tf_optype_list;
  787. if (ge::AttrUtils::GetListStr(&model, "needCheckCpu", aicpu_optype_list)) {
  788. GELOGI("Already have aicpu optype size: %zu", aicpu_optype_list.size());
  789. aicpu_op_types.insert(aicpu_optype_list.begin(), aicpu_optype_list.end());
  790. }
  791. if (ge::AttrUtils::GetListStr(&model, "needCheckTf", aicpu_tf_optype_list)) {
  792. GELOGI("Already have aicpu tf optype size: %zu", aicpu_tf_optype_list.size());
  793. aicpu_tf_op_types.insert(aicpu_tf_optype_list.begin(), aicpu_tf_optype_list.end());
  794. }
  795. // reset list with set
  796. aicpu_optype_list.assign(aicpu_op_types.begin(), aicpu_op_types.end());
  797. aicpu_tf_optype_list.assign(aicpu_tf_op_types.begin(), aicpu_tf_op_types.end());
  798. GELOGI(
  799. "Check Aicpu op types ComputeGraph: %s aicpu_op_types: %zu, aicpu_optype_list: %zu, aicpu_tf_op_types: %zu, "
  800. "aicpu_tf_optype_list:%zu.",
  801. compute_graph_->GetName().c_str(), aicpu_op_types.size(), aicpu_optype_list.size(), aicpu_tf_op_types.size(),
  802. aicpu_tf_optype_list.size());
  803. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetListStr(&model, "needCheckCpu", aicpu_optype_list), return,
  804. "Set attr needCheckCpu fail.");
  805. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetListStr(&model, "needCheckTf", aicpu_tf_optype_list), return,
  806. "Set attr needCheckTf fail.");
  807. return;
  808. }
  809. } // namespace ge

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