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.

convert_utils.cc 12 kB

4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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 "include/common/utils/convert_utils.h"
  17. #include <vector>
  18. #include <string>
  19. #include <memory>
  20. #include <algorithm>
  21. #include <utility>
  22. #include <cfloat>
  23. #include "ir/value.h"
  24. #include "ir/tensor.h"
  25. #include "ir/param_info.h"
  26. #include "utils/ms_context.h"
  27. #include "utils/anf_utils.h"
  28. namespace mindspore {
  29. bool ValueToBool(const ValuePtr &v, bool *value) {
  30. MS_EXCEPTION_IF_NULL(v);
  31. if (v->isa<BoolImm>()) {
  32. *value = v->cast<BoolImmPtr>()->value();
  33. } else if (v->isa<Int32Imm>()) {
  34. *value = v->cast<Int32ImmPtr>()->value() != 0;
  35. } else if (v->isa<UInt32Imm>()) {
  36. *value = v->cast<UInt32ImmPtr>()->value() != 0;
  37. } else if (v->isa<FP32Imm>()) {
  38. *value = v->cast<FP32ImmPtr>()->value() != 0;
  39. } else if (v->isa<FP64Imm>()) {
  40. *value = v->cast<FP64ImmPtr>()->value() != 0;
  41. } else if (v->isa<tensor::Tensor>()) {
  42. auto tensor = v->cast<tensor::TensorPtr>();
  43. MS_EXCEPTION_IF_NULL(tensor);
  44. tensor->data_sync();
  45. bool *tensor_data = static_cast<bool *>(tensor->data_c());
  46. // maybe need to support if tensor is a bool array
  47. auto vb = tensor_data[0];
  48. *value = vb;
  49. } else {
  50. MS_LOG(WARNING) << "value is not supported to cast to be bool";
  51. return false;
  52. }
  53. return true;
  54. }
  55. bool BaseRefToInt(const ValuePtr &v, int64_t *value) {
  56. MS_EXCEPTION_IF_NULL(v);
  57. if (v->isa<tensor::Tensor>()) {
  58. auto tensor = v->cast<tensor::TensorPtr>();
  59. tensor->data_sync();
  60. if (tensor->Dtype()->ToString() == "Int32") {
  61. auto *tensor_data = static_cast<int32_t *>(tensor->data_c());
  62. auto vb = tensor_data[0];
  63. *value = static_cast<int64_t>(vb);
  64. } else if (tensor->Dtype()->ToString() == "Int64") {
  65. auto *tensor_data = static_cast<int64_t *>(tensor->data_c());
  66. auto vb = tensor_data[0];
  67. *value = vb;
  68. } else {
  69. MS_LOG(ERROR) << "Index must be Int type.";
  70. }
  71. return true;
  72. }
  73. MS_LOG(ERROR) << "Index must be tensor type.";
  74. return false;
  75. }
  76. bool BaseRefToBool(const BaseRef &v, bool *value) {
  77. if (utils::isa<ValuePtr>(v)) {
  78. return ValueToBool(utils::cast<ValuePtr>(v), value);
  79. } else if (utils::isa<bool>(v)) {
  80. auto vb = utils::cast<bool>(v);
  81. *value = vb;
  82. } else if (utils::isa<int>(v)) {
  83. auto vb = utils::cast<int>(v);
  84. *value = vb != 0;
  85. } else if (utils::isa<unsigned int>(v)) {
  86. auto vb = utils::cast<unsigned int>(v);
  87. *value = vb != 0;
  88. } else if (utils::isa<float>(v)) {
  89. auto vb = utils::cast<float>(v);
  90. *value = !(vb >= -FLT_EPSILON && vb <= FLT_EPSILON);
  91. } else if (utils::isa<double>(v)) {
  92. auto vb = utils::cast<double>(v);
  93. *value = !(vb >= -DBL_EPSILON && vb <= DBL_EPSILON);
  94. } else {
  95. MS_LOG(DEBUG) << "value is not supported to cast to be bool";
  96. return false;
  97. }
  98. return true;
  99. }
  100. namespace {
  101. // Isomorphism
  102. bool SameNode(const AnfNodePtr &node1, const AnfNodePtr &node2, FuncGraphPairMapEquiv *equiv_func_graph,
  103. NodeMapEquiv *const equiv_node);
  104. bool SameValueNode(const AnfNodePtr &node1, const AnfNodePtr &node2) {
  105. auto a1 = GetValueNode(node1);
  106. auto a2 = GetValueNode(node2);
  107. if (a1->isa<Primitive>() && a2->isa<Primitive>()) {
  108. return a1->cast<PrimitivePtr>()->name() == a2->cast<PrimitivePtr>()->name();
  109. } else if (a1->isa<tensor::Tensor>() && a2->isa<tensor::Tensor>()) {
  110. return a1->cast<tensor::TensorPtr>()->ValueEqual(*(a2->cast<tensor::TensorPtr>()));
  111. }
  112. return *a1 == *a2;
  113. }
  114. bool SameNodeShallow(const AnfNodePtr &node1, const AnfNodePtr &node2, FuncGraphPairMapEquiv *equiv_func_graph,
  115. NodeMapEquiv *const equiv_node) {
  116. if (equiv_node == nullptr) {
  117. MS_LOG(ERROR) << "Invalid equiv_node";
  118. return false;
  119. }
  120. if (equiv_node->count(node1) > 0 && (*equiv_node)[node1] == node2) {
  121. return true;
  122. }
  123. if (IsValueNode<FuncGraph>(node1) && IsValueNode<FuncGraph>(node2)) {
  124. return Isomorphic(GetValueNode<FuncGraphPtr>(node1), GetValueNode<FuncGraphPtr>(node2), equiv_func_graph,
  125. equiv_node);
  126. }
  127. if (node1->isa<ValueNode>() && node2->isa<ValueNode>()) {
  128. return SameValueNode(node1, node2);
  129. }
  130. if (node1->isa<Parameter>() && node2->isa<Parameter>()) {
  131. auto para1 = node1->cast<ParameterPtr>();
  132. auto para2 = node2->cast<ParameterPtr>();
  133. if (para1->name() == para2->name()) {
  134. return true;
  135. }
  136. MS_LOG(DEBUG) << "two parameters are not equal.";
  137. return false;
  138. }
  139. if (AnfUtils::IsCustomActorNode(node1) && AnfUtils::IsCustomActorNode(node2)) {
  140. return AnfUtils::IsCutomActorNodeSame(node1, node2);
  141. }
  142. if (node1->isa<CNode>() && node2->isa<CNode>()) {
  143. return SameNode(node1, node2, equiv_func_graph, equiv_node);
  144. }
  145. MS_LOG(ERROR) << "type error";
  146. return false;
  147. }
  148. bool SameNode(const AnfNodePtr &node1, const AnfNodePtr &node2, FuncGraphPairMapEquiv *equiv_func_graph,
  149. NodeMapEquiv *const equiv_node) {
  150. MS_EXCEPTION_IF_NULL(node1);
  151. MS_EXCEPTION_IF_NULL(node2);
  152. if (node1->isa<CNode>() && node2->isa<CNode>()) {
  153. auto &inputs1 = node1->cast<CNodePtr>()->inputs();
  154. auto &inputs2 = node2->cast<CNodePtr>()->inputs();
  155. for (std::size_t i = 0; i < inputs1.size(); ++i) {
  156. if (!SameNodeShallow(inputs1[i], inputs2[i], equiv_func_graph, equiv_node)) {
  157. return false;
  158. }
  159. }
  160. return true;
  161. }
  162. return SameNodeShallow(node1, node2, equiv_func_graph, equiv_node);
  163. }
  164. bool SameSubgraph(const AnfNodePtr &root1, const AnfNodePtr &root2, FuncGraphPairMapEquiv *equiv_func_graph,
  165. NodeMapEquiv *const equiv_node) {
  166. mindspore::HashSet<AnfNodePtr> done;
  167. std::stack<std::pair<AnfNodePtr, AnfNodePtr>> todo;
  168. todo.push(std::make_pair(root1, root2));
  169. while (!todo.empty()) {
  170. AnfNodePtr node1 = todo.top().first;
  171. if (done.count(node1) > 0) {
  172. todo.pop();
  173. continue;
  174. }
  175. AnfNodePtr node2 = todo.top().second;
  176. bool condition = false;
  177. const auto &s1 = GetInputs(node1);
  178. const auto &s2 = GetInputs(node2);
  179. if (s1.size() != s2.size()) {
  180. return false;
  181. }
  182. for (std::size_t i = 0; i < s1.size(); ++i) {
  183. if (done.count(s1[i]) == 0) {
  184. todo.push(std::make_pair(s1[i], s2[i]));
  185. condition = true;
  186. }
  187. }
  188. if (condition) {
  189. continue;
  190. }
  191. (void)done.insert(node1);
  192. auto res = SameNode(node1, node2, equiv_func_graph, equiv_node);
  193. if (res) {
  194. (*equiv_node)[node1] = node2;
  195. } else {
  196. return false;
  197. }
  198. todo.pop();
  199. }
  200. return true;
  201. }
  202. } // namespace
  203. bool Isomorphic(const FuncGraphPtr &fg1, const FuncGraphPtr &fg2, FuncGraphPairMapEquiv *equiv_func_graph,
  204. NodeMapEquiv *const equiv_node) {
  205. auto fg1_fg2 = std::make_pair(fg1, fg2);
  206. if (equiv_func_graph == nullptr) {
  207. MS_LOG(ERROR) << "equiv_func_graph not init";
  208. return false;
  209. }
  210. if (equiv_func_graph->find(fg1_fg2) != equiv_func_graph->end()) {
  211. return (*equiv_func_graph)[fg1_fg2] != kNotEquiv;
  212. }
  213. if (fg1 == nullptr || fg2 == nullptr) {
  214. MS_LOG(ERROR) << "Invalid function graph";
  215. return false;
  216. }
  217. if (fg1->parameters().size() != fg2->parameters().size()) {
  218. MS_LOG(DEBUG) << "parameters size not match";
  219. return false;
  220. }
  221. if (equiv_node != nullptr) {
  222. for (std::size_t i = 0; i < fg1->parameters().size(); ++i) {
  223. (*equiv_node)[fg1->parameters()[i]] = fg2->parameters()[i];
  224. }
  225. (*equiv_func_graph)[fg1_fg2] = kPending;
  226. auto result = SameSubgraph(fg1->get_return(), fg2->get_return(), equiv_func_graph, equiv_node);
  227. (*equiv_func_graph)[fg1_fg2] = EquivState(result);
  228. return result;
  229. }
  230. MS_LOG(ERROR) << "equiv_node not init";
  231. return false;
  232. }
  233. tensor::TensorPtr ScalarToTensor(const ScalarPtr &scalar) {
  234. if (scalar == nullptr) {
  235. MS_EXCEPTION(ArgumentError) << "Nullptr Error!";
  236. }
  237. TypePtr data_type = scalar->type();
  238. MS_EXCEPTION_IF_NULL(data_type);
  239. TypeId type_id = data_type->type_id();
  240. switch (type_id) {
  241. case kNumberTypeBool:
  242. return std::make_shared<tensor::Tensor>(GetValue<bool>(scalar), data_type);
  243. case kNumberTypeInt8:
  244. return std::make_shared<tensor::Tensor>(static_cast<int64_t>(GetValue<int8_t>(scalar)), data_type);
  245. case kNumberTypeInt16:
  246. return std::make_shared<tensor::Tensor>(static_cast<int64_t>(GetValue<int16_t>(scalar)), data_type);
  247. case kNumberTypeInt32:
  248. return std::make_shared<tensor::Tensor>(static_cast<int64_t>(GetValue<int32_t>(scalar)), data_type);
  249. case kNumberTypeInt64:
  250. return std::make_shared<tensor::Tensor>(GetValue<int64_t>(scalar), data_type);
  251. case kNumberTypeUInt8:
  252. return std::make_shared<tensor::Tensor>(static_cast<uint64_t>(GetValue<uint8_t>(scalar)), data_type);
  253. case kNumberTypeUInt16:
  254. return std::make_shared<tensor::Tensor>(static_cast<uint64_t>(GetValue<uint16_t>(scalar)), data_type);
  255. case kNumberTypeUInt32:
  256. return std::make_shared<tensor::Tensor>(static_cast<uint64_t>(GetValue<uint32_t>(scalar)), data_type);
  257. case kNumberTypeUInt64:
  258. return std::make_shared<tensor::Tensor>(GetValue<uint64_t>(scalar), data_type);
  259. case kNumberTypeFloat32:
  260. return std::make_shared<tensor::Tensor>(GetValue<float>(scalar), data_type);
  261. case kNumberTypeFloat64:
  262. return std::make_shared<tensor::Tensor>(GetValue<double>(scalar), data_type);
  263. default:
  264. MS_LOG(EXCEPTION) << "When convert scalar to tensor, the scalar type: " << data_type << " is invalid.";
  265. }
  266. }
  267. void TensorValueToTensor(const ValuePtr &value, std::vector<tensor::TensorPtr> *tensors) {
  268. MS_EXCEPTION_IF_NULL(value);
  269. MS_EXCEPTION_IF_NULL(tensors);
  270. if (value->isa<ValueTuple>()) {
  271. auto value_tuple = value->cast<ValueTuplePtr>();
  272. MS_EXCEPTION_IF_NULL(value_tuple);
  273. for (size_t i = 0; i < value_tuple->size(); ++i) {
  274. ValuePtr element = value_tuple->value()[i];
  275. if (element->isa<tensor::Tensor>()) {
  276. auto tensor = element->cast<tensor::TensorPtr>();
  277. MS_EXCEPTION_IF_NULL(tensor);
  278. tensors->emplace_back(tensor);
  279. } else if (element->isa<ValueTuple>()) {
  280. TensorValueToTensor(element, tensors);
  281. }
  282. }
  283. } else if (value->isa<tensor::Tensor>()) {
  284. auto tensor = value->cast<tensor::TensorPtr>();
  285. MS_EXCEPTION_IF_NULL(tensor);
  286. tensors->emplace_back(tensor);
  287. }
  288. }
  289. ValuePtr ShallowCopyTensorValue(const ValuePtr &value) {
  290. MS_EXCEPTION_IF_NULL(value);
  291. if (value->isa<tensor::Tensor>()) {
  292. auto tensor_value = value->cast<tensor::TensorPtr>();
  293. MS_EXCEPTION_IF_NULL(tensor_value);
  294. return std::make_shared<tensor::Tensor>(*tensor_value);
  295. } else if (value->isa<ValueTuple>()) {
  296. std::vector<ValuePtr> values;
  297. auto value_tuple = value->cast<ValueTuplePtr>();
  298. MS_EXCEPTION_IF_NULL(value_tuple);
  299. (void)std::transform(value_tuple->value().begin(), value_tuple->value().end(), std::back_inserter(values),
  300. [](const ValuePtr &elem) { return ShallowCopyTensorValue(elem); });
  301. return std::make_shared<ValueTuple>(values);
  302. } else {
  303. return value;
  304. }
  305. }
  306. size_t CountValueNum(const ValueTuplePtr &value_tuple) {
  307. MS_EXCEPTION_IF_NULL(value_tuple);
  308. size_t cnt = 0;
  309. const auto &value_list = value_tuple->value();
  310. for (const auto &value : value_list) {
  311. if (value->isa<None>()) {
  312. continue;
  313. } else if (value->isa<ValueTuple>()) {
  314. cnt += CountValueNum(value->cast<ValueTuplePtr>());
  315. } else {
  316. cnt++;
  317. }
  318. }
  319. return cnt;
  320. }
  321. bool IsAKGSparseOP(const AnfNodePtr &cnode) {
  322. MS_EXCEPTION_IF_NULL(cnode);
  323. const PrimitiveSet prims{prim::kPrimCSRReduceSum, prim::kPrimCSRMul, prim::kPrimCSRMV, prim::kPrimCSRGather,
  324. prim::kPrimCSR2COO, prim::kPrimCOO2CSR, prim::kPrimCSRDiv};
  325. return IsOneOfPrimitiveCNode(cnode, prims);
  326. }
  327. } // namespace mindspore