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.

remove_value_node_dup.cc 2.4 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /**
  2. * Copyright 2019 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 "pipeline/remove_value_node_dup.h"
  17. #include "ir/anf.h"
  18. #include "ir/meta_tensor.h"
  19. #include "ir/manager.h"
  20. #include "optimizer/cse.h"
  21. #include "utils/log_adapter.h"
  22. #include "utils/hashing.h"
  23. namespace mindspore {
  24. namespace pipeline {
  25. void TryToDoReplace(FuncGraphManager *const manager, const AnfNodePtr &node, HashCache *const hash_cache,
  26. HashValue *const hash_value) {
  27. const auto &to_check_value = GetValueNode(node);
  28. MS_EXCEPTION_IF_NULL(to_check_value);
  29. // Calculate hash value.
  30. size_t h;
  31. auto hash_iter = hash_value->find(node);
  32. if (hash_iter == hash_value->end()) {
  33. h = hash_combine(to_check_value->hash(), (opt::AbsOf(node)->hash()));
  34. (*hash_value)[node] = h;
  35. } else {
  36. h = hash_iter->second;
  37. }
  38. auto bucket_iter = hash_cache->find(h);
  39. if (bucket_iter == hash_cache->end()) {
  40. // Meet for the first time, add bucket.
  41. (*hash_cache)[h] = {node};
  42. return;
  43. }
  44. auto &bucket = bucket_iter->second;
  45. // Check if need to replace node with value node already met.
  46. for (const auto &v : bucket) {
  47. // Already met and cached.
  48. if (v == node) {
  49. return;
  50. }
  51. const auto &existed_value = GetValueNode(v);
  52. MS_EXCEPTION_IF_NULL(existed_value);
  53. auto equal = [&]() -> bool {
  54. if (existed_value->isa<tensor::Tensor>() && to_check_value->isa<tensor::Tensor>()) {
  55. return existed_value->cast<tensor::TensorPtr>()->ValueEqual(*(to_check_value->cast<tensor::TensorPtr>()));
  56. }
  57. return *existed_value == *to_check_value;
  58. };
  59. if (equal()) {
  60. (void)manager->Replace(node, v);
  61. return;
  62. }
  63. }
  64. // Meet for the first time, append node to bucket.
  65. bucket.emplace_back(node);
  66. }
  67. } // namespace pipeline
  68. } // namespace mindspore