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.

dump_proto.cc 24 kB

6 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  1. /**
  2. * Copyright 2019-2022 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 "debug/dump_proto.h"
  17. #include <algorithm>
  18. #include <fstream>
  19. #include <map>
  20. #include <memory>
  21. #include <utility>
  22. #include <vector>
  23. #include "debug/anf_ir_utils.h"
  24. #include "proto/anf_ir.pb.h"
  25. #include "ir/graph_utils.h"
  26. #include "utils/ms_context.h"
  27. #include "utils/symbolic.h"
  28. #include "utils/utils.h"
  29. #include "pipeline/jit/base.h"
  30. #include "utils/anf_utils.h"
  31. namespace mindspore {
  32. class ProtoExporter {
  33. public:
  34. ProtoExporter() {}
  35. ~ProtoExporter() {}
  36. std::string GetFuncGraphProtoString(const FuncGraphPtr &func_graph);
  37. void ExportFuncGraph(const FuncGraphPtr &func_graph, irpb::GraphProto *graph_proto);
  38. private:
  39. void InitModelInfo();
  40. void GetOpNodeTypeAndAttrs(const FuncGraphPtr &func_graph, const CNodePtr &cnode, irpb::NodeProto *node_proto);
  41. std::string GetOpNodeInputId(const FuncGraphPtr &func_graph, const AnfNodePtr &node,
  42. const std::map<AnfNodePtr, size_t> &apply_map,
  43. std::map<AnfNodePtr, size_t> *const_map_ptr);
  44. void SetValueToProtoBasicTypes(const ValuePtr &attr_value, irpb::ValueProto *value_proto);
  45. void SetValueToProto(const ValuePtr &attr_value, irpb::ValueProto *value_proto);
  46. void SetScalarToProto(const ScalarPtr &val, irpb::ValueProto *value_proto);
  47. void SetSequenceToProto(const ValueSequencePtr &val, irpb::ValueProto *value_proto);
  48. void SetDictionaryToProto(const ValueDictionaryPtr &val, irpb::ValueProto *value_proto);
  49. void SetNodeOutputType(const AnfNodePtr &node, irpb::TypeProto *type_proto);
  50. void SetNodeOutputType(const TypePtr &node, const BaseShapePtr &shape, irpb::TypeProto *type_proto);
  51. void ExportParameters(const FuncGraphPtr &func_graph, irpb::GraphProto *graph_proto);
  52. void ExportCNodes(const FuncGraphPtr &func_graph, irpb::GraphProto *graph_proto,
  53. std::map<AnfNodePtr, size_t> *const_map_ptr);
  54. void ExportCNode(const FuncGraphPtr &func_graph, const CNodePtr &node, std::map<AnfNodePtr, size_t> *apply_map_ptr,
  55. std::map<AnfNodePtr, size_t> *const_map_ptr, irpb::GraphProto *graph_proto);
  56. void ExportFuncGraphOutput(const FuncGraphPtr &func_graph, const CNodePtr &ret_node,
  57. const std::map<AnfNodePtr, size_t> &apply_map, std::map<AnfNodePtr, size_t> *const_map_ptr,
  58. irpb::GraphProto *graph_proto);
  59. void ExportValueNodes(const std::map<AnfNodePtr, size_t> &const_map, irpb::GraphProto *graph_proto);
  60. static std::string GetConstNodeId(size_t idx) { return std::string("cst") + std::to_string(idx); }
  61. irpb::ModelProto model_;
  62. };
  63. static irpb::DataType GetNumberDataType(const TypePtr &type) {
  64. switch (type->type_id()) {
  65. case kNumberTypeBool:
  66. return irpb::DT_BOOL;
  67. case kNumberTypeInt8:
  68. return irpb::DT_INT8;
  69. case kNumberTypeInt16:
  70. return irpb::DT_INT16;
  71. case kNumberTypeInt32:
  72. return irpb::DT_INT32;
  73. case kNumberTypeInt64:
  74. return irpb::DT_INT64;
  75. case kNumberTypeUInt8:
  76. return irpb::DT_UINT8;
  77. case kNumberTypeUInt16:
  78. return irpb::DT_UINT16;
  79. case kNumberTypeUInt32:
  80. return irpb::DT_UINT32;
  81. case kNumberTypeUInt64:
  82. return irpb::DT_UINT64;
  83. case kNumberTypeFloat16:
  84. return irpb::DT_FLOAT16;
  85. case kNumberTypeFloat32:
  86. return irpb::DT_FLOAT32;
  87. case kNumberTypeFloat64:
  88. return irpb::DT_FLOAT64;
  89. case kNumberTypeInt:
  90. return irpb::DT_BASE_INT;
  91. case kNumberTypeUInt:
  92. return irpb::DT_BASE_UINT;
  93. case kNumberTypeFloat:
  94. return irpb::DT_BASE_FLOAT;
  95. case kNumberTypeComplex64:
  96. return irpb::DT_COMPLEX64;
  97. case kNumberTypeComplex128:
  98. return irpb::DT_COMPLEX128;
  99. default:
  100. MS_LOG(EXCEPTION) << "Unexpected type " << type->type_name();
  101. }
  102. }
  103. void CheckIfValidType(const TypePtr &type) {
  104. MS_EXCEPTION_IF_NULL(type);
  105. if (type->isa<Problem>()) {
  106. MS_LOG(WARNING) << "The type: " << type->type_name();
  107. return;
  108. }
  109. if (!(type->isa<Number>() || type->isa<TensorType>() || type->isa<Tuple>() || type->isa<TypeType>() ||
  110. type->isa<List>() || type->isa<TypeAnything>() || type->isa<RefKeyType>() || type->isa<RefType>() ||
  111. type->isa<Function>() || type->isa<TypeNone>() || type->isa<String>() || type->isa<RowTensorType>() ||
  112. type->isa<CSRTensorType>() || type->isa<UndeterminedType>() || type->isa<SparseTensorType>() ||
  113. type->isa<SymbolicKeyType>() || type->isa<MonadType>())) {
  114. MS_LOG(EXCEPTION) << "Unknown type: " << type->type_name();
  115. }
  116. }
  117. void SetTensorType(const TypePtr &type, const BaseShapePtr &shape, irpb::TypeProto *type_proto) {
  118. TypePtr elem_type = dyn_cast<TensorType>(type)->element();
  119. type_proto->mutable_tensor_type()->set_elem_type(GetNumberDataType(elem_type));
  120. type_proto->set_data_type(irpb::DT_TENSOR);
  121. if (shape != nullptr && shape->isa<abstract::Shape>()) {
  122. abstract::ShapePtr shape_info = dyn_cast<abstract::Shape>(shape);
  123. for (const auto &elem : shape_info->shape()) {
  124. type_proto->mutable_tensor_type()->mutable_shape()->add_dim()->set_size(elem);
  125. }
  126. }
  127. }
  128. void ProtoExporter::SetNodeOutputType(const TypePtr &type, const BaseShapePtr &shape, irpb::TypeProto *type_proto) {
  129. if (type_proto == nullptr) {
  130. return;
  131. }
  132. if (type == nullptr) {
  133. type_proto->set_data_type(irpb::DT_UNDEFINED);
  134. return;
  135. }
  136. if (type->isa<External>()) {
  137. return;
  138. }
  139. CheckIfValidType(type);
  140. if (type->isa<Number>()) {
  141. type_proto->set_data_type(GetNumberDataType(type));
  142. } else if (type->isa<TensorType>()) {
  143. SetTensorType(type, shape, type_proto);
  144. } else if (type->isa<Tuple>()) {
  145. TuplePtr tuple_type = dyn_cast<Tuple>(type);
  146. type_proto->set_data_type(irpb::DT_TUPLE);
  147. for (const auto &elem_type : tuple_type->elements()) {
  148. SetNodeOutputType(elem_type, nullptr, type_proto->mutable_sequence_type()->add_elem_types());
  149. }
  150. } else if (type->isa<TypeType>()) {
  151. type_proto->set_data_type(irpb::DT_TYPE);
  152. } else if (type->isa<List>()) {
  153. ListPtr list_type = dyn_cast<List>(type);
  154. type_proto->set_data_type(irpb::DT_LIST);
  155. for (const auto &elem_type : list_type->elements()) {
  156. SetNodeOutputType(elem_type, nullptr, type_proto->mutable_sequence_type()->add_elem_types());
  157. }
  158. } else if (type->isa<TypeAnything>()) {
  159. type_proto->set_data_type(irpb::DT_ANYTHING);
  160. } else if (type->isa<RefKeyType>()) {
  161. type_proto->set_data_type(irpb::DT_REFKEY);
  162. } else if (type->isa<RefType>()) {
  163. type_proto->set_data_type(irpb::DT_REF);
  164. } else if (type->isa<Function>()) {
  165. type_proto->set_data_type(irpb::DT_GRAPH);
  166. } else if (type->isa<TypeNone>()) {
  167. type_proto->set_data_type(irpb::DT_NONE);
  168. } else if (type->isa<String>()) {
  169. type_proto->set_data_type(irpb::DT_STRING);
  170. }
  171. }
  172. void ProtoExporter::SetNodeOutputType(const AnfNodePtr &node, irpb::TypeProto *type_proto) {
  173. if (node == nullptr || type_proto == nullptr) {
  174. return;
  175. }
  176. SetNodeOutputType(node->Type(), node->Shape(), type_proto);
  177. }
  178. void ProtoExporter::SetValueToProtoBasicTypes(const ValuePtr &val, irpb::ValueProto *value_proto) {
  179. if (val->isa<StringImm>()) {
  180. const StringImmPtr &value = dyn_cast<StringImm>(val);
  181. value_proto->set_dtype(irpb::DT_STRING);
  182. value_proto->set_str_val(value->value());
  183. } else if (val->isa<Scalar>()) {
  184. SetScalarToProto(dyn_cast<Scalar>(val), value_proto);
  185. } else if (val->isa<Bool>()) {
  186. value_proto->set_dtype(irpb::DT_TYPE);
  187. value_proto->mutable_type_val()->set_data_type(irpb::DT_BOOL);
  188. } else if (val->isa<Int>()) {
  189. value_proto->set_dtype(irpb::DT_TYPE);
  190. value_proto->mutable_type_val()->set_data_type(irpb::DT_BASE_INT);
  191. } else if (val->isa<UInt>()) {
  192. value_proto->set_dtype(irpb::DT_TYPE);
  193. value_proto->mutable_type_val()->set_data_type(irpb::DT_BASE_UINT);
  194. } else if (val->isa<Float>()) {
  195. value_proto->set_dtype(irpb::DT_TYPE);
  196. value_proto->mutable_type_val()->set_data_type(irpb::DT_BASE_FLOAT);
  197. }
  198. }
  199. void ProtoExporter::SetValueToProto(const ValuePtr &val, irpb::ValueProto *value_proto) {
  200. if (val == nullptr || value_proto == nullptr) {
  201. return;
  202. }
  203. SetValueToProtoBasicTypes(val, value_proto);
  204. if (val->isa<ValueSequence>()) {
  205. SetSequenceToProto(dyn_cast<ValueSequence>(val), value_proto);
  206. } else if (val->isa<None>()) {
  207. value_proto->set_dtype(irpb::DT_NONE);
  208. value_proto->set_str_val("None");
  209. } else if (val->isa<SymbolicKeyInstance>()) {
  210. SymbolicKeyInstancePtr sym_inst = dyn_cast<SymbolicKeyInstance>(val);
  211. ParameterPtr sym_node = dyn_cast<Parameter>(sym_inst->node());
  212. value_proto->set_dtype(irpb::DT_SYM_INST);
  213. value_proto->set_str_val(sym_node == nullptr ? std::string("nullptr") : sym_node->ToString());
  214. } else if (val->isa<ValueDictionary>()) {
  215. SetDictionaryToProto(dyn_cast<ValueDictionary>(val), value_proto);
  216. } else if (val->isa<tensor::Tensor>()) {
  217. tensor::TensorPtr tensor_ptr = dyn_cast<tensor::Tensor>(val);
  218. value_proto->set_dtype(irpb::DT_TENSOR);
  219. irpb::TensorProto *tensor_proto = value_proto->mutable_tensor_val();
  220. tensor_proto->set_data_type(GetNumberDataType(tensor_ptr->Dtype()));
  221. for (auto &elem : tensor_ptr->shape()) {
  222. tensor_proto->add_dims(elem);
  223. }
  224. } else if (val->isa<TensorType>()) {
  225. value_proto->set_dtype(irpb::DT_TYPE);
  226. irpb::TypeProto *type_proto = value_proto->mutable_type_val();
  227. type_proto->set_data_type(irpb::DT_TENSOR);
  228. TypePtr elem_type = dyn_cast<TensorType>(val)->element();
  229. type_proto->mutable_tensor_type()->set_elem_type(GetNumberDataType(elem_type));
  230. } else if (val->isa<Monad>() || val->isa<MonadType>()) {
  231. value_proto->set_str_val(val->ToString());
  232. } else if (val->isa<Complex>()) {
  233. value_proto->set_dtype(irpb::DT_TYPE);
  234. value_proto->mutable_type_val()->set_data_type(irpb::DT_BASE_COMPLEX);
  235. } else {
  236. MS_LOG(DEBUG) << "Unsupported type " << val->type_name();
  237. }
  238. }
  239. void ProtoExporter::SetScalarToProto(const ScalarPtr &val, irpb::ValueProto *value_proto) {
  240. if (val == nullptr || value_proto == nullptr) {
  241. return;
  242. }
  243. if (val->isa<BoolImm>()) {
  244. const BoolImmPtr &value = dyn_cast<BoolImm>(val);
  245. value_proto->set_dtype(irpb::DT_BOOL);
  246. value_proto->set_bool_val(value->value());
  247. } else if (val->isa<Int8Imm>()) {
  248. const Int8ImmPtr &value = dyn_cast<Int8Imm>(val);
  249. value_proto->set_dtype(irpb::DT_INT8);
  250. value_proto->set_int_val(value->value());
  251. } else if (val->isa<Int16Imm>()) {
  252. const Int16ImmPtr &value = dyn_cast<Int16Imm>(val);
  253. value_proto->set_dtype(irpb::DT_INT16);
  254. value_proto->set_int_val(value->value());
  255. } else if (val->isa<Int32Imm>()) {
  256. const Int32ImmPtr &value = dyn_cast<Int32Imm>(val);
  257. value_proto->set_dtype(irpb::DT_INT32);
  258. value_proto->set_int_val(value->value());
  259. } else if (val->isa<Int64Imm>()) {
  260. const Int64ImmPtr &value = dyn_cast<Int64Imm>(val);
  261. value_proto->set_dtype(irpb::DT_INT64);
  262. value_proto->set_int_val(value->value());
  263. } else if (val->isa<UInt8Imm>()) {
  264. const UInt8ImmPtr &value = dyn_cast<UInt8Imm>(val);
  265. value_proto->set_dtype(irpb::DT_UINT8);
  266. value_proto->set_uint_val(value->value());
  267. } else if (val->isa<UInt16Imm>()) {
  268. const UInt16ImmPtr &value = dyn_cast<UInt16Imm>(val);
  269. value_proto->set_dtype(irpb::DT_UINT16);
  270. value_proto->set_uint_val(value->value());
  271. } else if (val->isa<UInt32Imm>()) {
  272. const UInt32ImmPtr &value = dyn_cast<UInt32Imm>(val);
  273. value_proto->set_dtype(irpb::DT_UINT32);
  274. value_proto->set_uint_val(value->value());
  275. } else if (val->isa<UInt64Imm>()) {
  276. const UInt64ImmPtr &value = dyn_cast<UInt64Imm>(val);
  277. value_proto->set_dtype(irpb::DT_UINT64);
  278. value_proto->set_uint_val(value->value());
  279. } else if (val->isa<FP32Imm>()) {
  280. const FP32ImmPtr &value = dyn_cast<FP32Imm>(val);
  281. value_proto->set_dtype(irpb::DT_FLOAT32);
  282. value_proto->set_float_val(value->value());
  283. } else if (val->isa<FP64Imm>()) {
  284. const FP64ImmPtr &value = dyn_cast<FP64Imm>(val);
  285. value_proto->set_dtype(irpb::DT_FLOAT64);
  286. value_proto->set_double_val(value->value());
  287. } else {
  288. MS_LOG(EXCEPTION) << "Unknown scalar type " << val->ToString();
  289. }
  290. }
  291. void ProtoExporter::SetSequenceToProto(const ValueSequencePtr &val, irpb::ValueProto *value_proto) {
  292. if (val == nullptr || value_proto == nullptr) {
  293. return;
  294. }
  295. if (val->isa<ValueTuple>()) {
  296. const ValueTuplePtr &value = dyn_cast<ValueTuple>(val);
  297. value_proto->set_dtype(irpb::DT_TUPLE);
  298. for (const auto &item : value->value()) {
  299. SetValueToProto(item, value_proto->add_values());
  300. }
  301. } else if (val->isa<ValueList>()) {
  302. const ValueListPtr &value = dyn_cast<ValueList>(val);
  303. value_proto->set_dtype(irpb::DT_LIST);
  304. for (const auto &item : value->value()) {
  305. SetValueToProto(item, value_proto->add_values());
  306. }
  307. }
  308. }
  309. void ProtoExporter::SetDictionaryToProto(const ValueDictionaryPtr &val, irpb::ValueProto *value_proto) {
  310. if (val == nullptr || value_proto == nullptr) {
  311. return;
  312. }
  313. value_proto->set_dtype(irpb::DT_DICT);
  314. for (const auto &item : val->value()) {
  315. irpb::NamedValueProto *named_val = value_proto->add_dict_val();
  316. named_val->set_key(item.first);
  317. SetValueToProto(item.second, named_val->mutable_value());
  318. }
  319. }
  320. void ProtoExporter::GetOpNodeTypeAndAttrs(const FuncGraphPtr &, const CNodePtr &cnode, irpb::NodeProto *node_proto) {
  321. const auto &inputs = cnode->inputs();
  322. AnfNodePtr op_node = inputs[0];
  323. if (op_node == nullptr || node_proto == nullptr) {
  324. return;
  325. }
  326. if (op_node->isa<CNode>() || op_node->isa<Parameter>() || IsValueNode<FuncGraph>(op_node)) {
  327. MS_LOG(EXCEPTION) << "Op node can not be CNode, Parameter or ValueNode Graph. But got " << op_node->ToString();
  328. }
  329. if (!IsValueNode<Primitive>(op_node)) {
  330. MS_LOG(EXCEPTION) << "Op node is not primitive: " << op_node->ToString();
  331. }
  332. const PrimitivePtr &prim = GetValueNode<PrimitivePtr>(op_node);
  333. node_proto->set_op_type(prim->name());
  334. for (const auto &attr : prim->attrs()) {
  335. irpb::AttributeProto *attr_proto = node_proto->add_attribute();
  336. attr_proto->set_name(attr.first);
  337. SetValueToProto(attr.second, attr_proto->mutable_value());
  338. }
  339. // Only CNode save the operator strategy
  340. auto operator_info = cnode->user_data<parallel::OperatorInfo>();
  341. if (operator_info != nullptr) {
  342. auto strategy = operator_info->strategy();
  343. if (strategy != nullptr) {
  344. ValuePtr strategy_value = MakeValue(strategy->GetInputDim());
  345. irpb::AttributeProto *attr_proto = node_proto->add_attribute();
  346. attr_proto->set_name(mindspore::parallel::IN_STRATEGY);
  347. SetValueToProto(strategy_value, attr_proto->mutable_value());
  348. }
  349. }
  350. node_proto->set_scope(op_node->scope()->name());
  351. }
  352. std::string ProtoExporter::GetOpNodeInputId(const FuncGraphPtr &, const AnfNodePtr &node,
  353. const std::map<AnfNodePtr, size_t> &apply_map,
  354. std::map<AnfNodePtr, size_t> *const_map_ptr) {
  355. if (node == nullptr || const_map_ptr == nullptr) {
  356. return "";
  357. }
  358. if (node->isa<CNode>()) {
  359. auto iter = apply_map.find(node);
  360. if (iter == apply_map.end()) {
  361. MS_LOG(EXCEPTION) << "Can not find node '" << node->ToString() << "' in apply_map";
  362. }
  363. return std::to_string(iter->second);
  364. }
  365. if (node->isa<Parameter>()) {
  366. return node->ToString();
  367. }
  368. if (AnfUtils::IsCustomActorNode(node)) {
  369. return AnfUtils::GetCustomActorName(node);
  370. }
  371. if (node->isa<ValueNode>()) {
  372. auto iter = const_map_ptr->find(node);
  373. if (iter == const_map_ptr->end()) {
  374. // Start index number from 1
  375. auto const_idx = const_map_ptr->size() + 1;
  376. (*const_map_ptr)[node] = const_idx;
  377. }
  378. return GetConstNodeId((*const_map_ptr)[node]);
  379. }
  380. MS_LOG(EXCEPTION) << "Unknown node type. node is '" << node->ToString() << "'";
  381. }
  382. std::string ProtoExporter::GetFuncGraphProtoString(const FuncGraphPtr &func_graph) {
  383. if (func_graph == nullptr) {
  384. return "";
  385. }
  386. InitModelInfo();
  387. irpb::GraphProto *graph_proto = model_.mutable_graph();
  388. ExportFuncGraph(func_graph, graph_proto);
  389. return model_.SerializeAsString();
  390. }
  391. void ProtoExporter::ExportFuncGraph(const FuncGraphPtr &func_graph, irpb::GraphProto *graph_proto) {
  392. if (func_graph == nullptr || graph_proto == nullptr) {
  393. return;
  394. }
  395. // map for store ValueNodes of this graph
  396. std::map<AnfNodePtr, size_t> const_map;
  397. // set graph name
  398. graph_proto->set_name(func_graph->ToString());
  399. ExportParameters(func_graph, graph_proto);
  400. ExportCNodes(func_graph, graph_proto, &const_map);
  401. ExportValueNodes(const_map, graph_proto);
  402. }
  403. void ProtoExporter::ExportParameters(const FuncGraphPtr &func_graph, irpb::GraphProto *graph_proto) {
  404. if (func_graph == nullptr || graph_proto == nullptr) {
  405. return;
  406. }
  407. std::vector<AnfNodePtr> parameters = func_graph->parameters();
  408. for (auto &param : parameters) {
  409. irpb::ParameterProto *param_proto = graph_proto->add_parameters();
  410. param_proto->set_name(param->ToString());
  411. SetNodeOutputType(param, param_proto->mutable_type());
  412. const ParameterPtr param_ptr = dyn_cast<Parameter>(param);
  413. if (param_ptr == nullptr) {
  414. MS_LOG(EXCEPTION) << "Parameter '" << param->ToString() << "' could not cast to parameter.";
  415. }
  416. }
  417. }
  418. void ProtoExporter::ExportCNodes(const FuncGraphPtr &func_graph, irpb::GraphProto *graph_proto,
  419. std::map<AnfNodePtr, size_t> *const_map_ptr) {
  420. if (func_graph == nullptr || graph_proto == nullptr || const_map_ptr == nullptr) {
  421. return;
  422. }
  423. // topo sort nodes
  424. std::vector<AnfNodePtr> nodes = TopoSort(func_graph->get_return(), SuccIncoming, AlwaysInclude);
  425. std::map<AnfNodePtr, size_t> apply_map;
  426. for (const AnfNodePtr &node : nodes) {
  427. MS_EXCEPTION_IF_NULL(node);
  428. if (!node->isa<CNode>()) {
  429. continue;
  430. }
  431. auto cnode = node->cast<CNodePtr>();
  432. if (cnode != func_graph->get_return()) {
  433. ExportCNode(func_graph, cnode, &apply_map, const_map_ptr, graph_proto);
  434. } else {
  435. ExportFuncGraphOutput(func_graph, cnode, apply_map, const_map_ptr, graph_proto);
  436. }
  437. }
  438. }
  439. void ProtoExporter::ExportCNode(const FuncGraphPtr &func_graph, const CNodePtr &node,
  440. std::map<AnfNodePtr, size_t> *apply_map_ptr,
  441. std::map<AnfNodePtr, size_t> *const_map_ptr, irpb::GraphProto *graph_proto) {
  442. if (func_graph == nullptr || node == nullptr || apply_map_ptr == nullptr || const_map_ptr == nullptr ||
  443. graph_proto == nullptr) {
  444. return;
  445. }
  446. auto apply_idx = apply_map_ptr->size() + 1;
  447. (*apply_map_ptr)[node] = apply_idx;
  448. auto &inputs = node->inputs();
  449. if (inputs.size() < 1) {
  450. MS_LOG(EXCEPTION) << "Inputs of apply node is empty";
  451. }
  452. AnfNodePtr op = inputs[0];
  453. irpb::NodeProto *node_proto = graph_proto->add_node();
  454. // CNode/ConstGraph/Const/Parameter
  455. if (op->isa<CNode>() || IsValueNode<FuncGraph>(op) || op->isa<Parameter>()) {
  456. MS_LOG(DEBUG) << "Operator must be a primitive";
  457. } else {
  458. GetOpNodeTypeAndAttrs(func_graph, node, node_proto);
  459. node_proto->set_name(std::to_string(apply_idx));
  460. node_proto->set_scope(node->scope()->name());
  461. node_proto->set_full_name(GetKernelNodeName(node));
  462. // process OP inputs
  463. for (size_t i = 1; i < inputs.size(); ++i) {
  464. irpb::InputProto *input_proto = node_proto->add_input();
  465. input_proto->set_type(irpb::InputProto_EdgeType_DATA_EDGE);
  466. std::string id = GetOpNodeInputId(func_graph, inputs[i], *apply_map_ptr, const_map_ptr);
  467. input_proto->set_name(id);
  468. }
  469. // set node output type
  470. SetNodeOutputType(node, node_proto->mutable_output_type());
  471. if (IsValueNode<Primitive>(op)) {
  472. PrimitivePtr primitive = GetValueNode<PrimitivePtr>(op);
  473. if (!primitive->instance_name().empty()) {
  474. node_proto->set_instance_name(primitive->instance_name());
  475. }
  476. }
  477. }
  478. }
  479. void ProtoExporter::ExportFuncGraphOutput(const FuncGraphPtr &func_graph, const CNodePtr &ret_node,
  480. const std::map<AnfNodePtr, size_t> &apply_map,
  481. std::map<AnfNodePtr, size_t> *const_map_ptr, irpb::GraphProto *graph_proto) {
  482. if (ret_node == nullptr || !ret_node->isa<CNode>()) {
  483. MS_LOG(EXCEPTION) << "Graph return node is illegal";
  484. }
  485. // ret node has two input 1 ret op + 1 value
  486. const size_t ret_input_size = 2;
  487. if (ret_node->inputs().size() != ret_input_size) {
  488. return;
  489. }
  490. AnfNodePtr arg = ret_node->input(1);
  491. if (graph_proto == nullptr) {
  492. MS_LOG(EXCEPTION) << "graph_proto is nullptr";
  493. }
  494. irpb::OutputProto *output_proto = graph_proto->add_outputs();
  495. if (output_proto == nullptr) {
  496. MS_LOG(EXCEPTION) << "output_proto is nullptr";
  497. }
  498. std::string id = GetOpNodeInputId(func_graph, arg, apply_map, const_map_ptr);
  499. output_proto->set_name(id);
  500. SetNodeOutputType(arg, output_proto->mutable_type());
  501. }
  502. static bool CompareValue(const std::pair<AnfNodePtr, size_t> &x, const std::pair<AnfNodePtr, size_t> &y) {
  503. return x.second < y.second;
  504. }
  505. void ProtoExporter::ExportValueNodes(const std::map<AnfNodePtr, size_t> &const_map, irpb::GraphProto *graph_proto) {
  506. std::vector<std::pair<AnfNodePtr, size_t>> nodes;
  507. (void)std::transform(const_map.cbegin(), const_map.cend(), std::back_inserter(nodes),
  508. [](const std::pair<AnfNodePtr, size_t> &item) { return item; });
  509. sort(nodes.begin(), nodes.end(), CompareValue);
  510. for (auto &item : nodes) {
  511. if (graph_proto == nullptr) {
  512. MS_LOG(EXCEPTION) << "graph_proto is nullptr";
  513. }
  514. irpb::NamedValueProto *named_value = graph_proto->add_const_vals();
  515. MS_EXCEPTION_IF_NULL(named_value);
  516. named_value->set_key(GetConstNodeId(item.second));
  517. SetValueToProto(GetValueNode(item.first), named_value->mutable_value());
  518. }
  519. }
  520. void ProtoExporter::InitModelInfo() { model_.set_ir_version(irpb::IR_VERSION); }
  521. std::string GetFuncGraphProtoString(const FuncGraphPtr &func_graph) {
  522. ProtoExporter exporter;
  523. return exporter.GetFuncGraphProtoString(func_graph);
  524. }
  525. void GetFuncGraphProto(const FuncGraphPtr &func_graph, irpb::GraphProto *graph_proto) {
  526. ProtoExporter exporter;
  527. exporter.ExportFuncGraph(func_graph, graph_proto);
  528. }
  529. #ifdef ENABLE_DUMP_IR
  530. void DumpIRProto(const FuncGraphPtr &func_graph, const std::string &suffix) {
  531. if (func_graph == nullptr) {
  532. MS_LOG(ERROR) << "Func graph is nullptr";
  533. return;
  534. }
  535. std::string file_path = GetSaveGraphsPathName("ms_output_" + suffix + ".pb");
  536. auto realpath = Common::CreatePrefixPath(file_path);
  537. if (!realpath.has_value()) {
  538. MS_LOG(ERROR) << "Get real path failed, path=" << file_path;
  539. return;
  540. }
  541. ChangeFileMode(realpath.value(), S_IWUSR);
  542. // write to pb file
  543. std::ofstream ofs(file_path);
  544. if (!ofs.is_open()) {
  545. MS_LOG(ERROR) << "Open file '" << file_path << "' failed!" << ErrnoToString(errno);
  546. return;
  547. }
  548. ofs << GetFuncGraphProtoString(func_graph);
  549. ofs.close();
  550. // set file mode to read only by user
  551. ChangeFileMode(file_path, S_IRUSR);
  552. }
  553. #else
  554. void DumpIRProto(const FuncGraphPtr &, const std::string &) {
  555. static bool already_printed = false;
  556. if (already_printed) {
  557. return;
  558. }
  559. already_printed = true;
  560. MS_LOG(WARNING) << "The functionality of dumping function graph IR in protobuf format is disabled, "
  561. << "please recompile source to enable it. See help of building script.";
  562. }
  563. #endif
  564. } // namespace mindspore