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

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