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

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