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.

grad.cc 2.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 "optimizer/ad/grad.h"
  17. #include "optimizer/ad/dfunctor.h"
  18. #include "ir/func_graph_cloner.h"
  19. #include "utils/context/ms_context.h"
  20. #include "utils/symbolic.h"
  21. #include "utils/graph_utils.h"
  22. namespace mindspore {
  23. namespace ad {
  24. FuncGraphPtr Grad(const FuncGraphPtr &func_graph, const pipeline::ResourceBasePtr &resources) {
  25. MS_EXCEPTION_IF_NULL(func_graph);
  26. auto gradkv = func_graph->transforms().find("grad");
  27. if (gradkv != func_graph->transforms().end()) {
  28. return gradkv->second.func_graph();
  29. }
  30. auto manager_ptr = resources->manager();
  31. MS_EXCEPTION_IF_NULL(manager_ptr);
  32. manager_ptr->AddFuncGraph(func_graph);
  33. auto multi_graph_sink = [&func_graph](const FuncGraphPtr &f) {
  34. if (MsContext::GetInstance()->is_multi_graph_sink()) {
  35. if (func_graph->has_flag(FUNC_GRAPH_FLAG_IGNORE_VALUES)) {
  36. f->set_flags(FUNC_GRAPH_FLAG_IGNORE_VALUES, true);
  37. }
  38. }
  39. };
  40. auto f = std::make_shared<DFunctor>(func_graph, resources);
  41. auto user_defined = f->KUserDefined(func_graph);
  42. if (user_defined != nullptr) {
  43. multi_graph_sink(user_defined);
  44. DFunctor::Clear();
  45. return user_defined;
  46. }
  47. f->Init(f, true);
  48. f->MapObject();
  49. f->MapMorphism();
  50. auto ret = f->k_graph();
  51. DFunctor::Clear();
  52. multi_graph_sink(ret);
  53. return ret;
  54. }
  55. FuncGraphPtr Kprim(const ValueNodePtr &value_node, const pipeline::ResourceBasePtr &resources) {
  56. auto fg = g_k_prims.KPrimitive(value_node, resources);
  57. if (fg == nullptr) {
  58. return nullptr;
  59. }
  60. return BasicClone(fg);
  61. }
  62. MetaFuncGraphPtr Kmeta(const PrimitivePtr &prim, const pipeline::ResourceBasePtr &) {
  63. MetaFuncGraphPtr fg = g_k_prims.KMetaFuncGraph(prim);
  64. return fg;
  65. }
  66. } // namespace ad
  67. } // namespace mindspore