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

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816
  1. /**
  2. * Copyright 2019-2020 Huawei Technologies Co., Ltd
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "graph/build/model_builder.h"
  17. #include <securectype.h>
  18. #include <iostream>
  19. #include <set>
  20. #include <unordered_map>
  21. #include "common/ge/ge_util.h"
  22. #include "framework/common/debug/ge_log.h"
  23. #include "graph/anchor.h"
  24. #include "graph/attr_value.h"
  25. #include "graph/buffer.h"
  26. #include "graph/build/label_allocator.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 "graph/passes/memcpy_addr_async_pass.h"
  46. #include "init/gelib.h"
  47. #include "memory/memory_assigner.h"
  48. #include "omg/version.h"
  49. #include "register/op_registry.h"
  50. #include "graph/passes/set_input_output_offset_pass.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 float kImgRatioYUV420SP_U8 = 1.5;
  59. const int kImgRatioRGB888_U8 = 3;
  60. const int kImgRatioNC1HWC0DI_FP16 = 12;
  61. const int kInvalidIndexNum = -1;
  62. const uint32_t kInputDimensions2D = 2;
  63. const uint32_t kInputDimensions3D = 3;
  64. const char *const kVectorCore = "VectorCore";
  65. const char *const kCoreType = "ge.engineType";
  66. const std::string kEnableL1Fusion = "ge.l1Fusion";
  67. const set<string> adjust_layer_type_ = {ge::CONVOLUTION};
  68. bool IsGeLocalOp(const ge::ConstOpDescPtr &op_desc) {
  69. auto type = op_desc->GetType();
  70. if (type == ge::CONSTANTOP) {
  71. // constant op just has one output
  72. ge::GeTensorDesc output_desc = op_desc->GetOutputDesc(0);
  73. return !(output_desc.GetDataType() == ge::DT_STRING);
  74. }
  75. const set<string> ge_local_set = {ge::STREAMMERGE, ge::MEMCPYASYNC, ge::STREAMACTIVE, ge::STREAMSWITCH,
  76. ge::VARIABLE, ge::NOOP, ge::CONSTANT, ge::ENTER,
  77. ge::REFENTER, ge::LOOPCOND, ge::NEXTITERATION, ge::REFNEXTITERATION,
  78. ge::EXIT, ge::REFEXIT, ge::MERGE, ge::MEMCPYADDRASYNC};
  79. return (ge_local_set.find(type) != ge_local_set.end());
  80. }
  81. } // namespace
  82. namespace ge {
  83. ModelBuilder::ModelBuilder(uint64_t session_id, ge::ComputeGraphPtr compute_graph,
  84. const Graph2SubGraphInfoList &subgraphs, const map<string, int> &stream_max_parallel_num,
  85. bool hcom_parallel, int mode)
  86. : session_id_(session_id),
  87. mem_offset_(0),
  88. weight_offset_(kWeightsStartOffset),
  89. compute_graph_(std::move(compute_graph)),
  90. subgraphs_(subgraphs),
  91. stream_num_(0),
  92. event_num_(0),
  93. label_num_(0),
  94. stream_max_parallel_num_(stream_max_parallel_num),
  95. hcom_parallel_(hcom_parallel),
  96. build_mode_(mode),
  97. max_mem_offset_(0),
  98. zero_copy_mem_size_(0),
  99. platform_type_(0),
  100. is_loop_graph_(false),
  101. is_l1_fusion_enable_(false) {}
  102. ModelBuilder::~ModelBuilder() {}
  103. Status ModelBuilder::CalcOutputSize(const ge::NodePtr &n) {
  104. GE_CHECK_NOTNULL(n);
  105. auto node_op_desc = n->GetOpDesc();
  106. GE_CHECK_NOTNULL(node_op_desc);
  107. uint32_t index = 0;
  108. for (const auto &output_desc_ptr : node_op_desc->GetAllOutputsDescPtr()) {
  109. GeTensorDesc &desc_temp = *output_desc_ptr;
  110. uint32_t dim_num = static_cast<uint32_t>(desc_temp.GetShape().GetDimNum());
  111. GE_IF_BOOL_EXEC(dim_num > DIM_DEFAULT_SIZE, TensorUtils::SetRealDimCnt(desc_temp, dim_num));
  112. // calculate tensor size
  113. int64_t size_temp = 0;
  114. graphStatus graph_status = TensorUtils::GetTensorMemorySizeInBytes(desc_temp, size_temp);
  115. if (graph_status != GRAPH_SUCCESS) {
  116. GELOGE(graph_status, "GetTensorMemorySizeInBytes failed!");
  117. return FAILED;
  118. }
  119. TensorUtils::SetSize(desc_temp, size_temp);
  120. if (node_op_desc->UpdateOutputDesc(index, desc_temp) != SUCCESS) {
  121. GELOGE(FAILED, "UpdateOutputDesc failed.");
  122. return FAILED;
  123. }
  124. GELOGD("update output desc, dim_size: %u, mem_size: %ld, format: %s, type: %s, node name:%s", dim_num, size_temp,
  125. TypeUtils::FormatToSerialString(desc_temp.GetFormat()).c_str(),
  126. TypeUtils::DataTypeToSerialString(desc_temp.GetDataType()).c_str(), node_op_desc->GetName().c_str());
  127. index++;
  128. }
  129. return SUCCESS;
  130. }
  131. bool ModelBuilder::SetInputConst(const OpDescPtr &op_desc, const NodePtr &src_node, size_t index,
  132. vector<bool> &is_input_const) {
  133. GELOGI("SetIsInputConst const: %s", op_desc->GetName().c_str());
  134. for (size_t i = is_input_const.size(); i <= index; ++i) {
  135. is_input_const.push_back(false);
  136. }
  137. is_input_const[index] = true;
  138. vector<GeTensorPtr> weights = OpDescUtils::MutableWeights(src_node);
  139. if (weights.empty()) {
  140. GELOGW("SetInputIsConst weights is empty");
  141. return false;
  142. }
  143. GeTensorPtr weight = weights[0];
  144. GE_IF_BOOL_EXEC(weight == nullptr, return true);
  145. GeTensorDesc &tensor_desc = weight->MutableTensorDesc();
  146. int64_t data_offset = 0;
  147. if (TensorUtils::GetDataOffset(tensor_desc, data_offset) != GRAPH_SUCCESS) {
  148. GELOGW("Get Offset from weight failed");
  149. return false;
  150. }
  151. auto input_tensor = op_desc->MutableInputDesc(static_cast<uint32_t>(index));
  152. if (input_tensor == nullptr) {
  153. GELOGW("Get input_tensor failed");
  154. return false;
  155. }
  156. TensorUtils::SetDataOffset(*input_tensor, data_offset);
  157. return true;
  158. }
  159. void ModelBuilder::SetInputIsConst(const ge::NodePtr &n) {
  160. auto node_op_desc = n->GetOpDesc();
  161. GE_CHECK_NOTNULL_JUST_RETURN(node_op_desc);
  162. auto is_input_const = node_op_desc->GetIsInputConst();
  163. // must set all true input_const to false
  164. for (size_t i = 0; i < is_input_const.size(); i++) {
  165. is_input_const[i] = false;
  166. }
  167. std::string const_type;
  168. auto in_data_anchors = n->GetAllInDataAnchors();
  169. for (size_t index = 0; index < in_data_anchors.size(); index++) {
  170. auto in_data_anchor = in_data_anchors.at(index);
  171. const auto &peer_out_anchor = in_data_anchor->GetPeerOutAnchor();
  172. GE_IF_BOOL_EXEC(peer_out_anchor == nullptr, continue);
  173. const auto &src_node = peer_out_anchor->GetOwnerNode();
  174. if (!NodeUtils::GetConstOpType(src_node, const_type)) {
  175. continue;
  176. }
  177. if (const_type == CONSTANT) {
  178. if (!SetInputConst(node_op_desc, src_node, index, is_input_const)) {
  179. return;
  180. }
  181. } else {
  182. if ((index < is_input_const.size()) && is_input_const[index]) {
  183. is_input_const[index] = false;
  184. }
  185. }
  186. }
  187. std::string input_const_info = ToString(is_input_const);
  188. GELOGD("update opdesc:%s InputConst:%s", node_op_desc->GetName().c_str(), input_const_info.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. GELOGE(FAILED, "weights size of node %s is empty", node->GetName().c_str());
  197. return FAILED;
  198. }
  199. GeTensorPtr weight = weights[0];
  200. if (weight == nullptr) {
  201. GELOGE(FAILED, "weights[0] is null.");
  202. return FAILED;
  203. }
  204. GeTensorDesc &tensor_desc = weight->MutableTensorDesc();
  205. size_t output_size = weight->GetData().size();
  206. TensorUtils::SetDataOffset(tensor_desc, mem_offset);
  207. mem_offset += output_size;
  208. }
  209. return SUCCESS;
  210. }
  211. Status ModelBuilder::SetInputOutputDesc() {
  212. Status ret;
  213. GELOGI("Start to SetInputOutputDesc.");
  214. for (const ge::NodePtr &n : compute_graph_->GetNodes(compute_graph_->GetGraphUnknownFlag())) {
  215. auto node_op_desc = n->GetOpDesc();
  216. GE_IF_BOOL_EXEC(node_op_desc == nullptr, continue);
  217. if (!is_loop_graph_ && node_op_desc->GetType() == LOOPCOND) {
  218. is_loop_graph_ = true;
  219. }
  220. // if user set input node format ND, the expected node for data and netoutput format is ND in
  221. // final graph.
  222. if ((GetLocalOmgContext().format == domi::DOMI_TENSOR_ND) && (!node_op_desc->HasAttr("_is_single_op")) &&
  223. ((node_op_desc->GetType() == DATA_TYPE) || (node_op_desc->GetType() == NETOUTPUT))) {
  224. GELOGI("The node [%s] format should be set ND.", node_op_desc->GetName().c_str());
  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. if (IsGeLocalOp(n->GetOpDesc())) {
  246. GE_CHK_STATUS_RET(CalcOutputSize(n), "Calculate output size failed");
  247. }
  248. ret = AdjustConstWeightSize(n, weight_offset_);
  249. GE_CHK_STATUS_RET(ret, "AdjustConstWeightSize failed");
  250. GE_IF_BOOL_EXEC(((weight_offset_ > 0) && (weight_offset_ % MEM_ALIGN_SIZE != 0)),
  251. weight_offset_ = (weight_offset_ + MEM_ALIGN_SIZE - 1) / MEM_ALIGN_SIZE * MEM_ALIGN_SIZE);
  252. }
  253. GE_CHK_STATUS_RET(compute_graph_->TopologicalSorting(), "TopologicalSorting failed");
  254. return SUCCESS;
  255. }
  256. void ModelBuilder::AddNodeInputProperty() {
  257. for (const ge::NodePtr &node : compute_graph_->GetNodes(compute_graph_->GetGraphUnknownFlag())) {
  258. auto node_op_desc = node->GetOpDesc();
  259. GE_IF_BOOL_EXEC(node_op_desc == nullptr, GELOGW("node_op_desc is nullptr!"); return );
  260. vector<string> src_name_list;
  261. vector<int64_t> src_index_list;
  262. for (const auto &in_data_anchor : node->GetAllInDataAnchors()) {
  263. auto peer_out_anchor = in_data_anchor->GetPeerOutAnchor();
  264. GE_IF_BOOL_EXEC(peer_out_anchor == nullptr, GELOGW("peer_out_anchor is nullptr!"); continue);
  265. GE_IF_BOOL_EXEC(node_op_desc->HasAttr(MERGE_PRENODE_FLAG), continue);
  266. ge::NodePtr src_node = peer_out_anchor->GetOwnerNode();
  267. src_name_list.emplace_back(src_node->GetName());
  268. src_index_list.emplace_back(peer_out_anchor->GetIdx());
  269. }
  270. auto in_control_anchor = node->GetInControlAnchor();
  271. if (in_control_anchor != nullptr) {
  272. string src_name_temp;
  273. for (const auto &out_control_anchor : in_control_anchor->GetPeerOutControlAnchors()) {
  274. ge::NodePtr src_node = out_control_anchor->GetOwnerNode();
  275. src_name_temp = src_name_temp.empty() ? src_node->GetName() : src_name_temp + ":" + src_node->GetName();
  276. }
  277. GE_IF_BOOL_EXEC(!src_name_temp.empty(), src_name_list.emplace_back(src_name_temp);)
  278. }
  279. node_op_desc->SetSrcName(src_name_list);
  280. node_op_desc->SetSrcIndex(src_index_list);
  281. }
  282. for (const ge::NodePtr &node : compute_graph_->GetNodes(compute_graph_->GetGraphUnknownFlag())) {
  283. auto node_op_desc = node->GetOpDesc();
  284. GE_IF_BOOL_EXEC(node_op_desc == nullptr, GELOGW("node_op_desc is nullptr!"); return );
  285. GE_IF_BOOL_EXEC(node_op_desc->GetType() == NETOUTPUT, continue);
  286. auto out_control_anchor = node->GetOutControlAnchor();
  287. GE_IF_BOOL_EXEC(out_control_anchor == nullptr, GELOGW("out_control_anchor is nullptr"); return );
  288. vector<string> dst_name_list;
  289. vector<int64_t> dst_index_list;
  290. string dst_name_temp;
  291. for (const auto &in_control_anchor : out_control_anchor->GetPeerInControlAnchors()) {
  292. ge::NodePtr dst_node = in_control_anchor->GetOwnerNode();
  293. dst_name_temp = dst_name_temp.empty() ? dst_node->GetName() : dst_name_temp + ":" + dst_node->GetName();
  294. }
  295. GE_IF_BOOL_EXEC(!dst_name_temp.empty(), dst_name_list.emplace_back(dst_name_temp));
  296. GE_IF_BOOL_EXEC(!out_control_anchor->GetPeerInControlAnchors().empty(),
  297. dst_index_list.emplace_back(kInvalidIndexNum));
  298. for (const auto &out_data_anchor : node->GetAllOutDataAnchors()) {
  299. GE_IF_BOOL_EXEC(node_op_desc->HasAttr(MERGE_PRENODE_FLAG), break);
  300. dst_name_temp = "";
  301. int64_t dst_index = kWrongIndex; // assign an impossible value to dst_index.
  302. for (const auto &in_data_anchor : out_data_anchor->GetPeerInDataAnchors()) {
  303. GE_IF_BOOL_EXEC(in_data_anchor == nullptr, GELOGW("in_data_anchor is nullptr"); return );
  304. ge::NodePtr dst_node = in_data_anchor->GetOwnerNode();
  305. dst_name_temp = dst_name_temp.empty() ? dst_node->GetName() : dst_name_temp + ":" + dst_node->GetName();
  306. dst_index = in_data_anchor->GetIdx();
  307. }
  308. GE_IF_BOOL_EXEC(dst_index != kWrongIndex, dst_index_list.emplace_back(dst_index)); // not found
  309. GE_IF_BOOL_EXEC(!dst_name_temp.empty(), dst_name_list.emplace_back(dst_name_temp));
  310. }
  311. node_op_desc->SetDstName(dst_name_list);
  312. node_op_desc->SetDstIndex(dst_index_list);
  313. }
  314. }
  315. Status ModelBuilder::AdjustInputTensorFlag() {
  316. GELOGI("Start to AdjustInputTensorFlag.");
  317. for (const ge::NodePtr &n : compute_graph_->GetNodes(compute_graph_->GetGraphUnknownFlag())) {
  318. if ((n->GetType() == DATA_TYPE) || (n->GetType() == AIPP_DATA_TYPE)) {
  319. GELOGD("Data node: %s.", n->GetName().c_str());
  320. for (const auto &anchor : n->GetAllOutDataAnchors()) {
  321. for (const auto &in_anchors : anchor->GetPeerInDataAnchors()) {
  322. GE_IF_BOOL_EXEC(in_anchors == nullptr, continue);
  323. auto owner_node = in_anchors->GetOwnerNode();
  324. auto owner_node_op_desc = owner_node->GetOpDesc();
  325. GE_IF_BOOL_EXEC(owner_node_op_desc == nullptr, continue);
  326. auto input_desc = owner_node_op_desc->GetInputDesc(in_anchors->GetIdx());
  327. ge::TensorUtils::SetInputTensor(input_desc, true);
  328. if (owner_node_op_desc->UpdateInputDesc(in_anchors->GetIdx(), input_desc) != SUCCESS) {
  329. GELOGE(FAILED, "UpdateOutputDesc failed.");
  330. return FAILED;
  331. }
  332. }
  333. }
  334. }
  335. }
  336. return SUCCESS;
  337. }
  338. void ModelBuilder::InitL1FusionOption() {
  339. string buffer_optimize = "off_optimize";
  340. graphStatus ret = ge::GetContext().GetOption(BUFFER_OPTIMIZE, buffer_optimize);
  341. if (ret == GRAPH_SUCCESS) {
  342. is_l1_fusion_enable_ = (buffer_optimize == "l1_optimize");
  343. GELOGD("The value of %s is %s.", BUFFER_OPTIMIZE.c_str(), buffer_optimize.c_str());
  344. } else {
  345. GELOGW("The value of %s is empty.", kEnableL1Fusion.c_str());
  346. }
  347. }
  348. Status ModelBuilder::BuildModelDef(ge::Model &model) {
  349. ClearOriginalFormat();
  350. max_mem_offset_ = mem_offset_;
  351. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetInt(&model, ATTR_MODEL_MEMORY_SIZE, max_mem_offset_),
  352. GELOGE(FAILED, "SetInt of ATTR_MODEL_MEMORY_SIZE failed.");
  353. return FAILED);
  354. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetInt(&model, ATTR_MODEL_WEIGHT_SIZE, weight_offset_),
  355. GELOGE(FAILED, "SetInt of ATTR_MODEL_WEIGHT_SIZE failed.");
  356. return FAILED);
  357. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetInt(&model, ATTR_MODEL_STREAM_NUM, stream_num_),
  358. GELOGE(FAILED, "SetInt of ATTR_MODEL_STREAM_NUM failed.");
  359. return FAILED);
  360. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetInt(&model, ATTR_MODEL_EVENT_NUM, event_num_),
  361. GELOGE(FAILED, "SetInt of ATTR_MODEL_EVENT_NUM failed.");
  362. return FAILED);
  363. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetListInt(&model, ATTR_MODEL_HUGE_STREAM_LIST, huge_streams_),
  364. GELOGE(FAILED, "SetInt of ATTR_MODEL_HUGE_STREAM_LIST failed.");
  365. return FAILED);
  366. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetInt(&model, ATTR_MODEL_LABEL_NUM, label_num_),
  367. GELOGE(FAILED, "SetInt of ATTR_MODEL_LABEL_NUM failed.");
  368. return FAILED);
  369. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetInt(&model, ATTR_MODEL_ZERO_COPY_MEMORY_SIZE, zero_copy_mem_size_),
  370. GELOGE(FAILED, "SetInt of ATTR_MODEL_ZERO_COPY_MEMORY_SIZE failed.");
  371. return FAILED);
  372. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetListStr(&model, ATTR_MODEL_OUT_NODES_NAME, GetLocalOmgContext().net_out_nodes),
  373. GELOGE(FAILED, "SetListStr of ATTR_MODEL_OUT_NODES_NAME failed.");
  374. return FAILED);
  375. GELOGI("For model, max_mem_offset_: %zu, zero_copy_mem_size_: %zu", max_mem_offset_, zero_copy_mem_size_);
  376. string ge_core_type;
  377. Status ret = ge::GetContext().GetOption(kCoreType, ge_core_type);
  378. if (ret != SUCCESS) {
  379. GELOGW("get the option CORE_TYPE fail, set it to default value VECTOR_ENGINE");
  380. }
  381. int64_t core_type = (ge_core_type == kVectorCore) ? 1 : 0;
  382. GELOGI("core_type: %ld", core_type);
  383. if (!ge::AttrUtils::SetInt(&model, ATTR_MODEL_CORE_TYPE, core_type)) {
  384. GELOGE(FAILED, "SetInt of ATTR_CORE_TYPE failed.");
  385. }
  386. InitL1FusionOption();
  387. GE_CHK_BOOL_EXEC(ge::AttrUtils::SetBool(&model, ATTR_NAME_SWITCH_FOR_L1_FUSION, is_l1_fusion_enable_),
  388. GELOGE(FAILED, "SetBool of ATTR_NAME_SWITCH_FOR_L1_FUSION failed.");
  389. return FAILED);
  390. const DumpProperties &dump_properties = PropertiesManager::Instance().GetDumpProperties(session_id_);
  391. bool is_op_debug = dump_properties.IsOpDebugOpen();
  392. GELOGI("Get op debug:%d", is_op_debug);
  393. if (is_op_debug) {
  394. if (!ge::AttrUtils::SetBool(&model, ATTR_OP_DEBUG_FLAG, is_op_debug)) {
  395. GELOGE(FAILED, "SetBool of ATTR_OP_DEBUG_FLAG failed.");
  396. return FAILED;
  397. }
  398. uint32_t op_debug_mode = dump_properties.GetOpDebugMode();
  399. GELOGI("Get op debug mode:%d", op_debug_mode);
  400. if (!ge::AttrUtils::SetInt(&model, ATTR_OP_DEBUG_MODE, op_debug_mode)) {
  401. GELOGE(FAILED, "SetBool of ATTR_OP_DEBUG_MODE failed.");
  402. return FAILED;
  403. }
  404. }
  405. model.SetName(compute_graph_->GetName());
  406. model.SetGraph(ge::GraphUtils::CreateGraphFromComputeGraph(compute_graph_));
  407. GELOGI("weight_offset_: %zu", weight_offset_);
  408. GELOGI("Set event num: %ld.", event_num_);
  409. if (Params::Instance() == nullptr) {
  410. return FAILED;
  411. }
  412. platform_type_ = Params::Instance()->GetTarget_8bit();
  413. return SUCCESS;
  414. }
  415. void ModelBuilder::ClearOriginalFormat() {
  416. for (const ge::NodePtr &n : compute_graph_->GetNodes(compute_graph_->GetGraphUnknownFlag())) {
  417. auto node_op_desc = n->GetOpDesc();
  418. if (node_op_desc != nullptr) {
  419. if (node_op_desc->HasAttr(ATTR_NAME_FORMAT)) {
  420. if (node_op_desc->DelAttr(ATTR_NAME_FORMAT) != SUCCESS) {
  421. GELOGW("DelAttr ATTR_NAME_FORMAT failed.");
  422. }
  423. }
  424. GE_IF_BOOL_EXEC(
  425. node_op_desc->HasAttr(ATTR_NAME_INFERRED_FORMAT),
  426. if (node_op_desc->DelAttr(ATTR_NAME_INFERRED_FORMAT) != SUCCESS) {
  427. GELOGW("DelAttr ATTR_NAME_INFERRED_FORMAT failed.");
  428. });
  429. GE_IF_BOOL_EXEC(
  430. node_op_desc->HasAttr(ATTR_NAME_PRED_PERMUTE_DELETED),
  431. if (node_op_desc->DelAttr(ATTR_NAME_PRED_PERMUTE_DELETED) != SUCCESS) {
  432. GELOGW("DelAttr ATTR_NAME_PRED_PERMUTE_DELETED failed.");
  433. });
  434. GE_IF_BOOL_EXEC(
  435. node_op_desc->HasAttr(ATTR_NAME_IGNORE_PRED_FORMAT),
  436. if (node_op_desc->DelAttr(ATTR_NAME_IGNORE_PRED_FORMAT) != SUCCESS) {
  437. GELOGW("DelAttr ATTR_NAME_IGNORE_PRED_FORMAT failed.");
  438. });
  439. }
  440. }
  441. }
  442. Status ModelBuilder::MergeWeights() {
  443. if (weight_offset_ == 0) {
  444. return SUCCESS;
  445. }
  446. ge::Buffer buffer(weight_offset_);
  447. weight_buffer_ = buffer;
  448. auto base_addr = weight_buffer_.GetData();
  449. for (const ge::NodePtr &node : compute_graph_->GetNodes(compute_graph_->GetGraphUnknownFlag())) {
  450. auto op_desc = node->GetOpDesc();
  451. GE_IF_BOOL_EXEC(op_desc == nullptr, continue);
  452. if (node->GetType() != CONSTANT) {
  453. continue;
  454. }
  455. // Get const op weight pointer
  456. ge::GeTensorPtr weight = nullptr;
  457. // If MutableTensor failed, weight is nullptr.
  458. (void)ge::AttrUtils::MutableTensor(op_desc, ATTR_NAME_WEIGHTS, weight);
  459. if (weight == nullptr) {
  460. GELOGE(FAILED, "Can't get const op weight, name: %s", node->GetName().c_str());
  461. return FAILED;
  462. }
  463. // Get const op weight offset
  464. int64_t offset = 0;
  465. if (ge::TensorUtils::GetDataOffset(weight->GetTensorDesc(), offset) != SUCCESS) {
  466. GELOGW("Can't get const op offset, name: %s", node->GetName().c_str());
  467. continue; // continue to merge if can not get offset
  468. }
  469. // Get const op weight data
  470. auto weight_data = weight->MutableData();
  471. // copy const op weight data to buffer
  472. GELOGI("Move to buffer, name: %s offset: %ld size: %zu", node->GetName().c_str(), offset, weight_data.size());
  473. ge::TensorUtils::SetWeightSize(weight->MutableTensorDesc(), static_cast<uint32_t>(weight_data.size()));
  474. if ((offset == 0) || (weight_data.size() == 0)) {
  475. GELOGI("Size or offset is 0. size: %lu offset: %ld", weight_data.size(), offset);
  476. continue;
  477. }
  478. if (weight_data.data() != nullptr) {
  479. GE_IF_BOOL_EXEC(base_addr == nullptr, GELOGE(FAILED, "Base addr is nullptr."); return FAILED);
  480. if (weight_offset_ - offset < weight_data.size()) {
  481. GELOGE(FAILED, "left weight size not enough. left_size:%lu, weight_size:%lu", weight_offset_ - offset,
  482. weight_data.size());
  483. return FAILED;
  484. }
  485. uintptr_t dst_ptr = reinterpret_cast<uintptr_t>(base_addr) + offset;
  486. uintptr_t src_ptr = reinterpret_cast<uintptr_t>(weight_data.data());
  487. size_t left_size = weight_data.size();
  488. while (left_size > SECUREC_MEM_MAX_LEN) {
  489. auto err = memcpy_s(reinterpret_cast<void *>(dst_ptr), SECUREC_MEM_MAX_LEN, reinterpret_cast<void *>(src_ptr),
  490. SECUREC_MEM_MAX_LEN);
  491. if (err != EOK) {
  492. GELOGE(FAILED,
  493. "mem copy failed. errret:%u, "
  494. "dst_ptr:%lx, dst_size:%lu, src_ptr:%lx, src_size:%lu",
  495. err, dst_ptr, SECUREC_MEM_MAX_LEN, src_ptr, SECUREC_MEM_MAX_LEN);
  496. return FAILED;
  497. }
  498. left_size -= SECUREC_MEM_MAX_LEN;
  499. dst_ptr = dst_ptr + SECUREC_MEM_MAX_LEN;
  500. src_ptr = src_ptr + SECUREC_MEM_MAX_LEN;
  501. }
  502. auto err = memcpy_s(reinterpret_cast<void *>(dst_ptr), left_size, reinterpret_cast<void *>(src_ptr), left_size);
  503. if (err != EOK) {
  504. GELOGE(FAILED,
  505. "mem copy failed. errret:%u, "
  506. "dst_ptr:%lx, dst_size:%lu, src_ptr:%lx, src_size:%lu",
  507. err, dst_ptr, SECUREC_MEM_MAX_LEN, src_ptr, SECUREC_MEM_MAX_LEN);
  508. return FAILED;
  509. }
  510. }
  511. weight_data.clear();
  512. }
  513. return SUCCESS;
  514. }
  515. Status ModelBuilder::SaveDataToModel(ge::Model &model, ge::GeModel &ge_model) {
  516. // Add weight
  517. ge_model.SetWeight(weight_buffer_);
  518. // Add TBE Kernels and custom aicpu op bin
  519. std::set<std::string> tbe_name_set;
  520. std::set<std::string> aicpu_name_set;
  521. for (const ge::NodePtr &n : compute_graph_->GetNodes(compute_graph_->GetGraphUnknownFlag())) {
  522. auto node_op_desc = n->GetOpDesc();
  523. GE_IF_BOOL_EXEC(node_op_desc == nullptr, continue);
  524. TBEKernelPtr tbe_kernel = node_op_desc->TryGetExtAttr(ge::OP_EXTATTR_NAME_TBE_KERNEL, TBEKernelPtr());
  525. if (tbe_kernel == nullptr) {
  526. std::string kernel_name;
  527. GeAttrValue::BYTES kernel_buffer;
  528. (void)AttrUtils::GetStr(node_op_desc, ATTR_NAME_TBE_KERNEL_NAME, kernel_name);
  529. (void)AttrUtils::GetBytes(node_op_desc, ATTR_NAME_TBE_KERNEL_BUFFER, kernel_buffer);
  530. if (!kernel_name.empty() && (kernel_buffer.GetSize() > 0)) {
  531. GE_CHECK_NOTNULL(kernel_buffer.GetData());
  532. std::vector<char> data(kernel_buffer.GetData(), kernel_buffer.GetData() + kernel_buffer.GetSize());
  533. tbe_kernel = std::make_shared<OpKernelBin>(kernel_name, std::move(data));
  534. }
  535. }
  536. GE_IF_BOOL_EXEC(tbe_kernel == nullptr, continue);
  537. if (tbe_name_set.count(tbe_kernel->GetName()) > 0) {
  538. GELOGE(FAILED, "tbe_kernel name %s can't be the same", tbe_kernel->GetName().c_str());
  539. return FAILED;
  540. }
  541. tbe_name_set.insert(tbe_kernel->GetName());
  542. tbe_kernel_store_.AddTBEKernel(tbe_kernel);
  543. GELOGI("Add tbe kernel bin %s", tbe_kernel->GetName().c_str());
  544. }
  545. for (const ge::NodePtr &n : compute_graph_->GetNodes(compute_graph_->GetGraphUnknownFlag())) {
  546. auto node_op_desc = n->GetOpDesc();
  547. GE_IF_BOOL_EXEC(node_op_desc == nullptr, continue);
  548. CustAICPUKernelPtr cust_aicpu_kernel =
  549. node_op_desc->TryGetExtAttr(ge::OP_EXTATTR_CUSTAICPU_KERNEL, CustAICPUKernelPtr());
  550. GE_IF_BOOL_EXEC(cust_aicpu_kernel == nullptr, continue);
  551. if (aicpu_name_set.count(cust_aicpu_kernel->GetName()) > 0) {
  552. GELOGE(FAILED, "aicpu_kernel name %s can't be the same", cust_aicpu_kernel->GetName().c_str());
  553. return FAILED;
  554. }
  555. aicpu_name_set.insert(cust_aicpu_kernel->GetName());
  556. cust_aicpu_kernel_store_.AddCustAICPUKernel(cust_aicpu_kernel);
  557. GELOGI("Add cust aicpu kernel bin %s", cust_aicpu_kernel->GetName().c_str());
  558. }
  559. if (!tbe_kernel_store_.Build()) {
  560. GELOGE(FAILED, "TBE Kernels store build failed!");
  561. return FAILED;
  562. }
  563. if (!cust_aicpu_kernel_store_.Build()) {
  564. GELOGE(FAILED, "custom AICPU kernels store build failed!");
  565. return FAILED;
  566. }
  567. ge_model.SetTBEKernelStore(tbe_kernel_store_);
  568. ge_model.SetCustAICPUKernelStore(cust_aicpu_kernel_store_);
  569. // Add task
  570. GeAttrValue::BYTES task_def_bytes;
  571. if (!AttrUtils::GetZeroCopyBytes(model, MODEL_ATTR_TASKS, task_def_bytes)) {
  572. GELOGE(INTERNAL_ERROR, "Get zero copy bytes fail.");
  573. return INTERNAL_ERROR;
  574. }
  575. int byte_size = static_cast<int>(task_def_bytes.GetSize());
  576. std::shared_ptr<domi::ModelTaskDef> task = ge::MakeShared<domi::ModelTaskDef>();
  577. GE_CHECK_NOTNULL(task);
  578. GE_CHK_BOOL_EXEC(ReadProtoFromArray(task_def_bytes.GetData(), byte_size, task.get()), return INTERNAL_ERROR,
  579. "ReadProtoFromArray failed.");
  580. ge_model.SetModelTaskDef(task);
  581. // Add graph
  582. ge_model.SetName(model.GetName());
  583. ge_model.SetGraph(model.GetGraph());
  584. ge_model.SetVersion(model.GetVersion());
  585. ge_model.SetPlatformVersion(model.GetPlatformVersion());
  586. ge_model.SetPlatformType(platform_type_);
  587. ge_model.SetAttr(model.MutableAttrMap());
  588. return SUCCESS;
  589. }
  590. void ModelBuilder::SetModelVersion(ge::Model &model) {
  591. // set framework_version TO model
  592. string framework_version;
  593. uint32_t counter = 0;
  594. Status frame_rt = PlatformVersionManager::GetPlatformVersion(framework_version);
  595. GE_IF_BOOL_EXEC((frame_rt == SUCCESS),
  596. string model_framework_version = framework_version + "." + std::to_string(counter);
  597. model.SetPlatformVersion(model_framework_version););
  598. // set IR Version TO model
  599. model.SetVersion(static_cast<uint32_t>(OM_PROTO_VERSION));
  600. }
  601. Status ModelBuilder::PreBuildModel() {
  602. if ((compute_graph_ == nullptr) || !(compute_graph_->IsValid())) {
  603. GELOGE(FAILED, "Graph_ is not valid.");
  604. return FAILED;
  605. }
  606. GELOGI("BuildModel begin.");
  607. GE_CHK_STATUS_RET(SetInputOutputDesc(), "SetInputOutputDesc Failed!");
  608. AddNodeInputProperty();
  609. return SUCCESS;
  610. }
  611. Status ModelBuilder::BuildModelForGetTask(ge::Model &model) {
  612. GE_CHK_STATUS_RET(AdjustInputTensorFlag(), "AdjustInputTensorFlag failed!");
  613. // Assign logical streams.
  614. StreamAllocator stream_allocator(compute_graph_, subgraphs_);
  615. GE_TIMESTAMP_START(AssignLogicalStreams);
  616. GE_CHK_STATUS_RET(stream_allocator.AssignLogicalStreams(stream_max_parallel_num_, hcom_parallel_),
  617. "Assign logical streams failed.");
  618. GE_TIMESTAMP_END(AssignLogicalStreams, "GraphBuilder::AssignLogicalStreams");
  619. // Assign functional op labels.
  620. GE_TIMESTAMP_START(AssignFunctionalLabels);
  621. LabelAllocator label_allocator(compute_graph_);
  622. GE_CHK_STATUS_RET(label_allocator.AssignFunctionalLabels(label_num_), "Assign label failed.");
  623. GE_TIMESTAMP_END(AssignFunctionalLabels, "ModelBuilder::AssignFunctionalLabels");
  624. // Add memcpy_addr_async node.
  625. rtFeatureType_t feature_type = FEATURE_TYPE_MEMCPY;
  626. int32_t feature_info = MEMCPY_INFO_SUPPORT_ZEROCOPY;
  627. int64_t value = 0;
  628. rtError_t rt_ret = rtGetRtCapability(feature_type, feature_info, &value);
  629. if (rt_ret != RT_ERROR_NONE) {
  630. GELOGE(RT_FAILED, "rtGetRtCapability failed.");
  631. return RT_FAILED;
  632. } else {
  633. if (value == RT_CAPABILITY_SUPPORT) {
  634. GE_TIMESTAMP_START(AddMemcpyAddrAsyncNode);
  635. MemcpyAddrAsyncPass memcpy_addr;
  636. GE_CHK_STATUS_RET(memcpy_addr.Run(compute_graph_), "Add memcpy_addr_async node failed.");
  637. GE_TIMESTAMP_END(AddMemcpyAddrAsyncNode, "MemcpyAddrAsyncPass::Run.");
  638. } else {
  639. GELOGW("rtGetRtCapability not support memcpy_addr_async.");
  640. }
  641. }
  642. GE_TIMESTAMP_START(AssignMemory);
  643. MemoryAssigner mem_assigner(compute_graph_);
  644. GE_CHK_STATUS_RET(mem_assigner.AssignMemory(is_loop_graph_, mem_offset_, zero_copy_mem_size_),
  645. "Assign Memory Failed!");
  646. GE_TIMESTAMP_END(AssignMemory, "GraphBuilder::AssignMemory");
  647. GE_TIMESTAMP_START(SetInputOutputOffset);
  648. SetInputOutputOffsetPass input_output_offset;
  649. GE_CHK_STATUS_RET(input_output_offset.Run(compute_graph_), "Set input output offset failed.");
  650. GE_TIMESTAMP_END(SetInputOutputOffset, "SetInputOutputOffsetPass::Run.");
  651. // Compile single op in graph build stage
  652. GE_TIMESTAMP_START(CompileSingleOp);
  653. GE_CHK_STATUS_RET(CompileSingleOp(), "ATC builder CompileSingleOp() return fail.");
  654. GE_TIMESTAMP_EVENT_END(CompileSingleOp, "GraphBuilder::CompileSingleOp");
  655. // Refresh real streams and insert event nodes.
  656. GE_TIMESTAMP_START(RefreshRealStream);
  657. GE_CHK_STATUS_RET(stream_allocator.RefreshRealStream(stream_num_, event_num_), "RefreshRealStream failed.");
  658. huge_streams_ = stream_allocator.GetHugeStreams();
  659. GE_TIMESTAMP_END(RefreshRealStream, "GraphBuilder::RefreshRealStream");
  660. GE_TIMESTAMP_START(MergeWeights);
  661. GE_CHK_STATUS_RET(MergeWeights(), "MergeWeights Failed!");
  662. GE_TIMESTAMP_END(MergeWeights, "GraphBuilder::MergeWeights");
  663. GE_TIMESTAMP_START(BuildModelDef);
  664. GE_CHK_STATUS_RET(BuildModelDef(model), "BuildModelDef failed!");
  665. GE_TIMESTAMP_END(BuildModelDef, "GraphBuilder::BuildModelDef");
  666. SetModelVersion(model);
  667. return SUCCESS;
  668. }
  669. Status ModelBuilder::BuildModelForGetDynShapeTask(ge::Model &model_def) {
  670. GE_TIMESTAMP_START(BuildModelDef);
  671. GE_CHK_STATUS_RET(BuildModelDef(model_def), "BuildModelDef failed!");
  672. GE_TIMESTAMP_END(BuildModelDef, "GraphBuilder::BuildModelDef");
  673. SetModelVersion(model_def);
  674. return SUCCESS;
  675. }
  676. ge::Buffer ModelBuilder::GetWeightBuffer() const { return weight_buffer_; }
  677. Status ModelBuilder::CompileSingleOp() {
  678. GELOGD("Begin to compile single op.");
  679. // Create ge instance
  680. std::shared_ptr<GELib> instance = ge::GELib::GetInstance();
  681. if ((instance == nullptr) || !instance->InitFlag()) {
  682. GELOGE(ge::GE_CLI_GE_NOT_INITIALIZED, "CompileSingleOp failed.");
  683. return ge::GE_CLI_GE_NOT_INITIALIZED;
  684. }
  685. GE_TIMESTAMP_CALLNUM_START(BatchCompileOp);
  686. std::unordered_map<string, vector<ge::NodePtr>> node_vector_map;
  687. for (auto &node : compute_graph_->GetNodes(compute_graph_->GetGraphUnknownFlag())) {
  688. auto op_desc = node->GetOpDesc();
  689. if (op_desc == nullptr) {
  690. continue;
  691. }
  692. // Graph build stage only supports the individual compilation of atomic clean operator
  693. if (op_desc->GetType() == ATOMICADDRCLEAN) {
  694. GELOGD("Begin to compile single op, op name is %s.", op_desc->GetName().c_str());
  695. string kernel_lib_name = op_desc->GetOpKernelLibName();
  696. if (kernel_lib_name.empty()) {
  697. // Reset op kernel lib
  698. (void)instance->DNNEngineManagerObj().GetDNNEngineName(node);
  699. kernel_lib_name = op_desc->GetOpKernelLibName();
  700. if (kernel_lib_name.empty()) {
  701. GELOGE(ge::INTERNAL_ERROR, "Get node:%s(%s) kernel lib failed.", node->GetName().c_str(),
  702. node->GetType().c_str());
  703. return ge::INTERNAL_ERROR;
  704. }
  705. }
  706. OpsKernelInfoStorePtr kernel_info = instance->OpsKernelManagerObj().GetOpsKernelInfoStore(kernel_lib_name);
  707. if (kernel_info != nullptr) {
  708. node_vector_map[kernel_lib_name].emplace_back(node);
  709. } else {
  710. GELOGE(ge::GE_GRAPH_PARAM_NULLPTR, "Get op %s ops kernel info store failed", node->GetName().c_str());
  711. return ge::GE_GRAPH_PARAM_NULLPTR;
  712. }
  713. }
  714. }
  715. for (auto &it : node_vector_map) {
  716. auto &kernel_lib_name = it.first;
  717. auto &node_vector = it.second;
  718. OpsKernelInfoStorePtr kernel_info = instance->OpsKernelManagerObj().GetOpsKernelInfoStore(kernel_lib_name);
  719. GE_CHECK_NOTNULL(kernel_info);
  720. GE_TIMESTAMP_RESTART(BatchCompileOp);
  721. auto ret = kernel_info->CompileOp(node_vector);
  722. GELOGI("[GEPERFTRACE] The node size of compile op of %s is %zu", kernel_lib_name.c_str(), node_vector.size());
  723. GE_TIMESTAMP_ADD(BatchCompileOp);
  724. if (ret != ge::SUCCESS) {
  725. GELOGE(ret, "Compile op failed, kernel lib name is %s", kernel_lib_name.c_str());
  726. return ret;
  727. }
  728. }
  729. GE_TIMESTAMP_CALLNUM_END(BatchCompileOp, "GraphBuild::CompileOp");
  730. return ge::SUCCESS;
  731. }
  732. } // namespace ge

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