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.

infer_value_range_pass.cc 16 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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/passes/infer_value_range_pass.h"
  17. #include "common/util/error_manager/error_manager.h"
  18. #include "framework/common/debug/ge_log.h"
  19. #include "graph/debug/ge_attr_define.h"
  20. #include "graph/operator_factory_impl.h"
  21. #include "graph/passes/constant_folding_pass.h"
  22. #include "graph/utils/type_utils.h"
  23. #include "common/ge/ge_util.h"
  24. using std::unique_ptr;
  25. namespace ge {
  26. namespace {
  27. #define GET_DATA_BY_DTYPE(DTYPE, TYPE) \
  28. case (DTYPE): \
  29. ConstructValueRange<TYPE>(lower_tensor, higher_tensor, output_tensor_value_range); \
  30. break;
  31. Status RunCpuKernelForValueRange(NodePtr &node, const vector<ConstGeTensorPtr> &inputs,
  32. std::vector<GeTensorPtr> &outputs) {
  33. // should use RunOpKernelWithCheck, RunOpKernel for ut test
  34. auto ret = ConstantFoldingPass::RunOpKernel(node, inputs, outputs);
  35. if (ret != SUCCESS) {
  36. auto op_kernel = folding_pass::GetKernelByType(node);
  37. if (op_kernel == nullptr) {
  38. GELOGW("Calculate value range failed, no op kernel for node %s type %s", node->GetName().c_str(),
  39. node->GetType().c_str());
  40. return NOT_CHANGED;
  41. }
  42. ret = op_kernel->Compute(node->GetOpDesc(), inputs, outputs);
  43. if (ret != SUCCESS) {
  44. GELOGW("Calculate for node %s failed in constant folding", node->GetName().c_str());
  45. return NOT_CHANGED;
  46. }
  47. }
  48. GELOGI("Node %s type %s, run cpu kernel success.", node->GetName().c_str(), node->GetType().c_str());
  49. return SUCCESS;
  50. }
  51. } // namespace
  52. graphStatus InferValueRangePass::Infer(NodePtr &node) {
  53. PrintInOutTensorShape(node, "before_infer_value_range");
  54. auto infer_value_range_param = OperatorFactoryImpl::GetInferValueRangePara(node->GetType());
  55. // Use registered func to calculate value range
  56. if (!infer_value_range_param.use_cpu_kernel) {
  57. if (infer_value_range_param.infer_value_func == nullptr) {
  58. GELOGW("The registered func of node %s to infer value range is nullptr.", node->GetName().c_str());
  59. return GRAPH_NOT_CHANGED;
  60. }
  61. Operator op = OpDescUtils::CreateOperatorFromNode(node);
  62. auto ret = node->GetOpDesc()->CallInferValueRangeFunc(op);
  63. if (ret != GRAPH_SUCCESS) {
  64. GELOGW("Node %s call infer value range func failed, ret: %u.", node->GetName().c_str(), ret);
  65. return GRAPH_NOT_CHANGED;
  66. }
  67. return GRAPH_SUCCESS;
  68. }
  69. // Use CPU kernel func to calculate value range
  70. auto ret = ConstructInputAndInferValueRange(node);
  71. if (ret != GRAPH_SUCCESS) {
  72. GELOGW("Use CPU kernel to calculate value range failed. node: %s, ret: %u", node->GetName().c_str(), ret);
  73. return GRAPH_NOT_CHANGED;
  74. }
  75. return GRAPH_SUCCESS;
  76. }
  77. bool InferValueRangePass::NeedInfer(const NodePtr &node) {
  78. auto infer_value_range_param = OperatorFactoryImpl::GetInferValueRangePara(node->GetType());
  79. if (!infer_value_range_param.is_initialized) {
  80. GELOGD("Node %s does not register func to infer value range, skip infer_value_range_pass.",
  81. node->GetName().c_str());
  82. return false;
  83. }
  84. if (infer_value_range_param.when_call == INPUT_IS_DYNAMIC) {
  85. // Only do infer for node that all inputs are dynamic, such as shape
  86. if (InputIsDynamic(node)) {
  87. return true;
  88. }
  89. GELOGD("Node %s register func to infer value range and when_call is INPUT_IS_DYNAMIC, but check input failed.",
  90. node->GetName().c_str());
  91. } else if (infer_value_range_param.when_call == INPUT_HAS_VALUE_RANGE) {
  92. // Only do infer for node that all inputs have value_range or node type of inputs is constant/const
  93. if (InputIsConstOrHasValueRange(node)) {
  94. return true;
  95. }
  96. GELOGD("Node %s register func to infer value range and when_call is INPUT_HAS_VALUE_RANGE, but check input failed.",
  97. node->GetName().c_str());
  98. }
  99. GELOGD("Node %s does not need to infer value range, skip infer_value_range_pass.", node->GetName().c_str());
  100. return false;
  101. }
  102. bool InferValueRangePass::InputIsDynamic(const NodePtr &node) {
  103. bool input_is_dynamic = false;
  104. auto cur_op_desc = node->GetOpDesc();
  105. for (const auto &input_desc : cur_op_desc->GetAllInputsDescPtr()) {
  106. auto dims = input_desc->GetShape().GetDims();
  107. for (auto dim : dims) {
  108. if (dim == UNKNOWN_DIM || dim == UNKNOWN_DIM_NUM) {
  109. input_is_dynamic = true;
  110. break;
  111. }
  112. }
  113. }
  114. return input_is_dynamic;
  115. }
  116. bool InferValueRangePass::InputIsConstOrHasValueRange(const NodePtr &node) {
  117. bool input_is_const_or_has_value_range = true;
  118. auto cur_op_desc = node->GetOpDesc();
  119. auto in_data_anchors = node->GetAllInDataAnchors();
  120. for (size_t i = 0; i < in_data_anchors.size(); ++i) {
  121. auto peer_out_anchor = in_data_anchors.at(i)->GetPeerOutAnchor();
  122. if (peer_out_anchor == nullptr) {
  123. continue;
  124. }
  125. auto peer_node = peer_out_anchor->GetOwnerNode();
  126. if (peer_node == nullptr || peer_node->GetOpDesc() == nullptr) {
  127. continue;
  128. }
  129. if ((peer_node->GetType() == CONSTANT) || (peer_node->GetType() == CONSTANTOP)) {
  130. continue;
  131. }
  132. const auto &input_desc = cur_op_desc->GetInputDesc(i);
  133. std::vector<std::pair<int64_t, int64_t>> value_range;
  134. (void)input_desc.GetValueRange(value_range);
  135. if (value_range.empty()) {
  136. GELOGD("Node %s input %zu does not have value range, skip infer_value_range_pass for current node.",
  137. node->GetName().c_str(), i);
  138. input_is_const_or_has_value_range = false;
  139. break;
  140. }
  141. }
  142. return input_is_const_or_has_value_range;
  143. }
  144. bool InferValueRangePass::SameTensorDesc(const GeTensorDescPtr &src, const GeTensorDescPtr &dst) {
  145. bool same_desc = true;
  146. std::vector<std::pair<int64_t, int64_t>> src_value_range;
  147. std::vector<std::pair<int64_t, int64_t>> dst_value_range;
  148. (void)src->GetValueRange(src_value_range);
  149. (void)dst->GetValueRange(dst_value_range);
  150. if (src_value_range != dst_value_range) {
  151. same_desc = false;
  152. }
  153. return same_desc;
  154. }
  155. graphStatus InferValueRangePass::UpdatePeerInputDesc(const GeTensorDescPtr &src, GeTensorDescPtr &dst, bool &changed) {
  156. changed = false;
  157. std::vector<std::pair<int64_t, int64_t>> src_value_range;
  158. std::vector<std::pair<int64_t, int64_t>> dst_value_range;
  159. (void)src->GetValueRange(src_value_range);
  160. (void)dst->GetValueRange(dst_value_range);
  161. if (src_value_range != dst_value_range) {
  162. changed = true;
  163. }
  164. dst->SetValueRange(src_value_range);
  165. return GRAPH_SUCCESS;
  166. }
  167. template <typename T>
  168. graphStatus InferValueRangePass::ConstructData(const GeTensorDesc &tensor_desc, bool use_floor_value,
  169. GeTensorPtr &output_ptr) {
  170. std::vector<std::pair<int64_t, int64_t>> value_range;
  171. (void)tensor_desc.GetValueRange(value_range);
  172. if (static_cast<int64_t>(value_range.size()) != tensor_desc.GetShape().GetShapeSize()) {
  173. REPORT_INNER_ERROR("E19999", "Value range of input %s is invalid.", tensor_desc.GetName().c_str());
  174. GELOGE(GRAPH_PARAM_INVALID, "Value range of input %s is invalid.", tensor_desc.GetName().c_str());
  175. return GRAPH_PARAM_INVALID;
  176. }
  177. size_t value_range_data_num = value_range.size();
  178. unique_ptr<T[]> buf(new (std::nothrow) T[value_range_data_num]());
  179. if (buf == nullptr) {
  180. REPORT_INNER_ERROR("E19999", "New buf failed");
  181. GELOGE(MEMALLOC_FAILED, "new buf failed");
  182. return GRAPH_FAILED;
  183. }
  184. for (size_t j = 0; j < value_range_data_num; ++j) {
  185. auto value_range_j = use_floor_value ? value_range[j].first : value_range[j].second;
  186. buf[j] = static_cast<T>(value_range_j);
  187. }
  188. if (output_ptr->SetData(reinterpret_cast<uint8_t *>(buf.get()), value_range_data_num * sizeof(T)) != GRAPH_SUCCESS) {
  189. GELOGE(GRAPH_FAILED, "set data failed");
  190. return GRAPH_FAILED;
  191. }
  192. return GRAPH_SUCCESS;
  193. }
  194. graphStatus InferValueRangePass::ConstructDataByType(const GeTensorDesc &tensor_desc, bool use_floor_value,
  195. GeTensorPtr &output_ptr) {
  196. graphStatus ret = GRAPH_SUCCESS;
  197. auto data_type = tensor_desc.GetDataType();
  198. output_ptr->MutableTensorDesc().SetDataType(data_type);
  199. switch (data_type) {
  200. case DT_FLOAT:
  201. ret = ConstructData<float>(tensor_desc, use_floor_value, output_ptr);
  202. break;
  203. case DT_DOUBLE:
  204. ret = ConstructData<double>(tensor_desc, use_floor_value, output_ptr);
  205. break;
  206. case DT_UINT8:
  207. ret = ConstructData<uint8_t>(tensor_desc, use_floor_value, output_ptr);
  208. break;
  209. case DT_INT8:
  210. ret = ConstructData<int8_t>(tensor_desc, use_floor_value, output_ptr);
  211. break;
  212. case DT_UINT16:
  213. ret = ConstructData<uint16_t>(tensor_desc, use_floor_value, output_ptr);
  214. break;
  215. case DT_INT16:
  216. ret = ConstructData<int16_t>(tensor_desc, use_floor_value, output_ptr);
  217. break;
  218. case DT_INT32:
  219. ret = ConstructData<int32_t>(tensor_desc, use_floor_value, output_ptr);
  220. break;
  221. case DT_INT64:
  222. ret = ConstructData<int64_t>(tensor_desc, use_floor_value, output_ptr);
  223. break;
  224. default:
  225. GELOGW("Data type:%s is not supported.", TypeUtils::DataTypeToSerialString(data_type).c_str());
  226. ret = GRAPH_FAILED;
  227. }
  228. return ret;
  229. }
  230. vector<ConstGeTensorPtr> InferValueRangePass::ConstructInputTensors(const NodePtr &node, bool use_floor_value) {
  231. vector<ConstGeTensorPtr> input_tensors;
  232. auto cur_op_desc = node->GetOpDesc();
  233. auto in_data_anchors = node->GetAllInDataAnchors();
  234. for (size_t i = 0; i < in_data_anchors.size(); ++i) {
  235. auto peer_out_anchor = in_data_anchors.at(i)->GetPeerOutAnchor();
  236. if (peer_out_anchor == nullptr) {
  237. continue;
  238. }
  239. auto peer_node = peer_out_anchor->GetOwnerNode();
  240. if (peer_node == nullptr) {
  241. continue;
  242. }
  243. // construct input tensor by constant node
  244. if ((peer_node->GetType() == CONSTANT) || (peer_node->GetType() == CONSTANTOP)) {
  245. vector<GeTensorPtr> const_weight = OpDescUtils::MutableWeights(peer_node);
  246. if (const_weight.empty()) {
  247. REPORT_INNER_ERROR("E19999", "MutableWeights failed, weight is empty, node: %s(%s)",
  248. peer_node->GetName().c_str(), peer_node->GetType().c_str());
  249. GELOGE(INTERNAL_ERROR, "MutableWeights failed, weight is empty, node: %s(%s)", peer_node->GetName().c_str(),
  250. peer_node->GetType().c_str());
  251. return vector<ConstGeTensorPtr>();
  252. }
  253. // const/constant op has only one weight
  254. if (const_weight.at(0) == nullptr) {
  255. REPORT_INNER_ERROR("E19999", "MutableWeights failed, weight of constant is null, node: %s(%s)",
  256. peer_node->GetName().c_str(), peer_node->GetType().c_str());
  257. GELOGE(INTERNAL_ERROR, "MutableWeights failed, weight of constant is null, node name: %s(%s)",
  258. peer_node->GetName().c_str(), peer_node->GetType().c_str());
  259. return vector<ConstGeTensorPtr>();
  260. }
  261. input_tensors.push_back(const_weight.at(0));
  262. continue;
  263. }
  264. // construct input tensor by boundary of value range
  265. const auto &input_tensor_desc = cur_op_desc->GetInputDesc(i);
  266. GeTensorPtr tmp_tensor_ptr = MakeShared<GeTensor>(input_tensor_desc);
  267. if (tmp_tensor_ptr == nullptr) {
  268. REPORT_INNER_ERROR("E19999", "Make shared failed");
  269. GELOGE(MEMALLOC_FAILED, "Make shared failed");
  270. return vector<ConstGeTensorPtr>();
  271. }
  272. auto ret = ConstructDataByType(input_tensor_desc, use_floor_value, tmp_tensor_ptr);
  273. if (ret != GRAPH_SUCCESS) {
  274. REPORT_INNER_ERROR("E19999", "Input %s construct input tensor by boundary of value range failed.",
  275. input_tensor_desc.GetName().c_str());
  276. GELOGE(GRAPH_PARAM_INVALID, "Input %s construct input tensor by boundary of value range failed.",
  277. input_tensor_desc.GetName().c_str());
  278. return vector<ConstGeTensorPtr>();
  279. }
  280. input_tensors.push_back(tmp_tensor_ptr);
  281. }
  282. return input_tensors;
  283. }
  284. graphStatus InferValueRangePass::ConstructInputAndInferValueRange(NodePtr &node) {
  285. auto inputs = ConstructInputTensors(node, true);
  286. if (inputs.empty()) {
  287. return GRAPH_PARAM_INVALID;
  288. }
  289. vector<GeTensorPtr> outputs_lower;
  290. auto ret = RunCpuKernelForValueRange(node, inputs, outputs_lower);
  291. if (ret != SUCCESS) {
  292. REPORT_INNER_ERROR("E19999", "Calculate for node %s(%s) failed", node->GetName().c_str(), node->GetType().c_str());
  293. GELOGE(GRAPH_FAILED, "Calculate for node %s failed in constant folding", node->GetName().c_str());
  294. return GRAPH_FAILED;
  295. }
  296. inputs = ConstructInputTensors(node, false);
  297. if (inputs.empty()) {
  298. return GRAPH_PARAM_INVALID;
  299. }
  300. vector<GeTensorPtr> outputs_higher;
  301. ret = RunCpuKernelForValueRange(node, inputs, outputs_higher);
  302. if (ret != SUCCESS) {
  303. REPORT_INNER_ERROR("E19999", "Calculate for node %s(%s) failed", node->GetName().c_str(), node->GetType().c_str());
  304. GELOGE(GRAPH_FAILED, "Calculate for node %s failed in constant folding", node->GetName().c_str());
  305. return GRAPH_FAILED;
  306. }
  307. // construct value range from output tensor
  308. OpDescPtr node_desc = node->GetOpDesc();
  309. std::vector<std::pair<int64_t, int64_t>> output_tensor_value_range;
  310. size_t node_output_desc_size = node_desc->GetOutputsSize();
  311. for (size_t i = 0; i < node_output_desc_size; ++i) {
  312. output_tensor_value_range.clear();
  313. auto lower_tensor = outputs_lower[i];
  314. auto lower_tensor_shape_size = lower_tensor->GetTensorDesc().GetShape().GetShapeSize();
  315. auto higher_tensor = outputs_higher[i];
  316. auto higher_tensor_shape_size = higher_tensor->GetTensorDesc().GetShape().GetShapeSize();
  317. auto output_tensor_desc = node_desc->MutableOutputDesc(i);
  318. auto output_tensor_shape_size = output_tensor_desc->GetShape().GetShapeSize();
  319. if (output_tensor_shape_size != lower_tensor_shape_size || output_tensor_shape_size != higher_tensor_shape_size) {
  320. GELOGE(GRAPH_PARAM_INVALID, "Value range of output %s is invalid.", output_tensor_desc->GetName().c_str());
  321. }
  322. auto data_type = output_tensor_desc->GetDataType();
  323. switch (data_type) {
  324. GET_DATA_BY_DTYPE(DT_INT8, int8_t)
  325. GET_DATA_BY_DTYPE(DT_INT16, int16_t)
  326. GET_DATA_BY_DTYPE(DT_INT32, int32_t)
  327. GET_DATA_BY_DTYPE(DT_INT64, int64_t)
  328. GET_DATA_BY_DTYPE(DT_UINT8, uint8_t)
  329. GET_DATA_BY_DTYPE(DT_UINT16, uint16_t)
  330. GET_DATA_BY_DTYPE(DT_UINT32, uint32_t)
  331. GET_DATA_BY_DTYPE(DT_UINT64, uint64_t)
  332. GET_DATA_BY_DTYPE(DT_FLOAT, float)
  333. GET_DATA_BY_DTYPE(DT_DOUBLE, double)
  334. default:
  335. GELOGW("Data type:%s is not supported.", TypeUtils::DataTypeToSerialString(data_type).c_str());
  336. return GRAPH_FAILED;
  337. }
  338. output_tensor_desc->SetValueRange(output_tensor_value_range);
  339. }
  340. return GRAPH_SUCCESS;
  341. }
  342. template <typename T>
  343. void InferValueRangePass::ConstructValueRange(const GeTensorPtr &left_tensor, const GeTensorPtr &right_tensor,
  344. std::vector<std::pair<int64_t, int64_t>> &value_range) {
  345. auto x = reinterpret_cast<const T *>(left_tensor->GetData().GetData());
  346. auto y = reinterpret_cast<const T *>(right_tensor->GetData().GetData());
  347. for (auto j = 0; j < left_tensor->GetTensorDesc().GetShape().GetShapeSize(); ++j) {
  348. auto left = static_cast<int64_t>(*(x + j));
  349. auto right = static_cast<int64_t>(*(y + j));
  350. value_range.emplace_back(std::make_pair(left, right));
  351. }
  352. }
  353. } // namespace ge

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