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.

graph_kernel_flags.cc 11 kB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. /**
  2. * Copyright 2021-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/context/graph_kernel_flags.h"
  17. #include <map>
  18. #include <string>
  19. #include <cstring>
  20. #include <vector>
  21. #include <utility>
  22. #include "nlohmann/json.hpp"
  23. #include "utils/ms_context.h"
  24. namespace mindspore::graphkernel {
  25. namespace {
  26. // Split string to tokens
  27. std::vector<std::string> GetTokens(const std::string &str, const std::string &delim) {
  28. std::vector<std::string> tokens;
  29. std::vector<char> c_str(str.begin(), str.end());
  30. c_str.push_back('\0');
  31. char *saveptr = nullptr;
  32. char *pch = strtok_r(&c_str[0], delim.c_str(), &saveptr);
  33. while (pch != nullptr) {
  34. tokens.emplace_back(pch);
  35. pch = strtok_r(nullptr, delim.c_str(), &saveptr);
  36. }
  37. return tokens;
  38. }
  39. // Parse flag string to key-value pair.
  40. // Flag format: "--key=value", bool flag's value can be implicit, the "--key" means "--key=true"
  41. std::pair<std::string, std::string> ParseFlag(const std::string &flag) {
  42. auto i = flag.find("--");
  43. // check the string starts with "--".
  44. constexpr size_t leading_size = 2;
  45. if (flag.size() <= leading_size || i != 0) {
  46. return std::pair<std::string, std::string>();
  47. }
  48. i += leading_size;
  49. auto j = flag.find('=', i + 1); // the key should not be empty, "--=" is invalid
  50. if (j >= flag.size()) {
  51. // no value, treated as bool flag.
  52. return std::make_pair(flag.substr(i), "");
  53. } else if (j + 1 < flag.size() && flag.find('=', j + 1) == std::string::npos) {
  54. // normal "--key=value" format
  55. return std::make_pair(flag.substr(i, j - i), flag.substr(j + 1));
  56. }
  57. // string with two "=" is invalid.
  58. return std::pair<std::string, std::string>();
  59. }
  60. std::map<std::string, std::string> ParseFlags(const std::string &flags) {
  61. std::map<std::string, std::string> flag_map;
  62. auto tokens = GetTokens(flags, " ");
  63. for (const auto &token : tokens) {
  64. auto flag = ParseFlag(token);
  65. if (flag.first != "") {
  66. if (!flag_map.insert(flag).second) {
  67. MS_LOG(WARNING) << "Repeated GraphKernel flag: " << flag.first;
  68. }
  69. } else {
  70. MS_LOG(WARNING) << "Invalid GraphKernel flag: " << token;
  71. }
  72. }
  73. return flag_map;
  74. }
  75. class FlagRegister {
  76. public:
  77. explicit FlagRegister(std::map<std::string, std::string> *flag_map) : flag_map_(*flag_map) {}
  78. ~FlagRegister() = default;
  79. template <typename T>
  80. void AddFlag(const std::string &flag_name, T *const flag_var, T default_value = T()) const {
  81. auto iter = flag_map_.find(flag_name);
  82. if (iter != flag_map_.end()) {
  83. T var;
  84. bool ret = ParseValue(iter->second, &var);
  85. if (ret) {
  86. *flag_var = std::move(var);
  87. } else {
  88. *flag_var = std::move(default_value);
  89. if (iter->second.empty()) {
  90. MS_LOG(WARNING) << "Invalid GraphKernel flag: --" << iter->first;
  91. } else {
  92. MS_LOG(WARNING) << "Invalid GraphKernel flag: --" << iter->first << "=" << iter->second;
  93. }
  94. }
  95. flag_map_.erase(iter);
  96. } else {
  97. *flag_var = std::move(default_value);
  98. }
  99. }
  100. private:
  101. bool ParseValue(const std::string &s, std::vector<std::string> *result) const {
  102. *result = GetTokens(s, ",");
  103. return !result->empty();
  104. }
  105. bool ParseValue(const std::string &s, bool *result) const {
  106. *result = (s.empty() || s == "true" || s == "on" || s == "1");
  107. return *result || s == "false" || s == "off" || s == "0";
  108. }
  109. template <typename T>
  110. bool ParseValue(const std::string &s, T *result) const {
  111. if (s.empty()) {
  112. return false;
  113. }
  114. std::istringstream iss(s);
  115. iss >> (*result);
  116. return iss.eof();
  117. }
  118. template <typename T>
  119. bool ParseValue(const std::string &s, std::vector<T> *result) const {
  120. result->clear();
  121. auto tokens = GetTokens(s, ",");
  122. if (tokens.empty()) {
  123. return false;
  124. }
  125. for (const auto &tok : tokens) {
  126. T temp;
  127. if (!ParseValue(tok, &temp)) {
  128. result->clear();
  129. return false;
  130. }
  131. result->emplace_back(temp);
  132. }
  133. return true;
  134. }
  135. std::map<std::string, std::string> &flag_map_;
  136. };
  137. } // namespace
  138. const GraphKernelFlags &GraphKernelFlags::GetInstance() {
  139. static std::unique_ptr<GraphKernelFlags> flags(nullptr);
  140. auto contexts = GetGraphKernelContext();
  141. if (flags == nullptr || contexts.first != flags->flags_cache_ || contexts.second != flags->enable_graph_kernel_) {
  142. flags.reset(new GraphKernelFlags(contexts.first, contexts.second));
  143. flags->Refresh();
  144. }
  145. return *flags;
  146. }
  147. std::pair<std::string, bool> GraphKernelFlags::GetGraphKernelContext() {
  148. // This environment variable is deprecated.
  149. auto flags = common::GetEnv("MS_GRAPH_KERNEL_FLAGS");
  150. bool enable_context{false};
  151. #ifndef MSLITE_ENABLE_GRAPH_KERNEL
  152. static bool print_warning = true;
  153. if ((!flags.empty()) && print_warning) {
  154. print_warning = false;
  155. MS_LOG(WARNING) << "The environment variable \"MS_GRAPH_KERNEL_FLAGS\" is deprecated from version 1.6 "
  156. << "and will be removed in a future version, "
  157. << "use context \"graph_kernel_flags\" instead.";
  158. }
  159. auto context = MsContext::GetInstance();
  160. MS_EXCEPTION_IF_NULL(context);
  161. if (flags.empty()) {
  162. flags = context->get_param<std::string>(MS_CTX_GRAPH_KERNEL_FLAGS);
  163. }
  164. enable_context = context->get_param<bool>(MS_CTX_ENABLE_GRAPH_KERNEL);
  165. #endif
  166. return std::make_pair(flags, enable_context);
  167. }
  168. void GraphKernelFlags::CheckSupport() const {
  169. #ifndef MSLITE_ENABLE_GRAPH_KERNEL
  170. if (IsEnableGraphKernel()) {
  171. auto context = MsContext::GetInstance();
  172. MS_EXCEPTION_IF_NULL(context);
  173. if (context->get_param<int>(MS_CTX_EXECUTION_MODE) != kGraphMode) {
  174. MS_LOG(WARNING) << "GraphKernel only support GRAPH_MODE.";
  175. const_cast<GraphKernelFlags *>(this)->opt_level = OptLevel_0;
  176. return;
  177. }
  178. #ifndef USE_LLVM
  179. auto is_cpu = (context->get_param<std::string>(MS_CTX_DEVICE_TARGET) == kCPUDevice);
  180. if (is_cpu) {
  181. MS_LOG(WARNING) << "GraphKernel is not usable without LLVM on cpu platform.";
  182. const_cast<GraphKernelFlags *>(this)->opt_level = OptLevel_0;
  183. return;
  184. }
  185. #endif
  186. }
  187. #endif
  188. }
  189. void GraphKernelFlags::Refresh() {
  190. auto flag_map = ParseFlags(flags_cache_);
  191. RegisterFlags(&flag_map);
  192. for (auto &item : flag_map) {
  193. MS_LOG(WARNING) << "Unknown GraphKernel flag: " << item.first;
  194. }
  195. #ifndef MSLITE_ENABLE_GRAPH_KERNEL
  196. if (IsEnableGraphKernel()) {
  197. CheckSupport();
  198. auto context = MsContext::GetInstance();
  199. MS_EXCEPTION_IF_NULL(context);
  200. auto is_ascend = (context->get_param<std::string>(MS_CTX_DEVICE_TARGET) == kAscendDevice);
  201. if (is_ascend) {
  202. MS_LOG(WARNING)
  203. << "GraphKernel on Ascend is experimental, please disable it if you meet some compiling or running error. For "
  204. "more details, please refer to 'mindspore.context' at https://www.mindspore.cn.";
  205. }
  206. }
  207. #endif
  208. // If enable graphkernel, Dump flags so that people can check the setting.
  209. if (IsEnableGraphKernel()) {
  210. MS_LOG(INFO) << "graph_kernel_flags = \"" << flags_cache_ << "\", all flags: " << DumpAllFlags();
  211. }
  212. }
  213. void GraphKernelFlags::RegisterFlags(std::map<std::string, std::string> *flag_map) {
  214. FlagRegister reg(flag_map);
  215. bool is_ascend{false};
  216. #ifndef MSLITE_ENABLE_GRAPH_KERNEL
  217. auto context_ptr = MsContext::GetInstance();
  218. MS_EXCEPTION_IF_NULL(context_ptr);
  219. is_ascend = (context_ptr->get_param<std::string>(MS_CTX_DEVICE_TARGET) == kAscendDevice);
  220. #endif
  221. // Set opt_level first, some flags' default value depends on it.
  222. // Default optimization level is level 2 when enable graphkernel
  223. reg.AddFlag("opt_level", &opt_level, enable_graph_kernel_ ? OptLevel_2 : OptLevel_0);
  224. if (opt_level > OptLevel_3) {
  225. MS_LOG(WARNING) << "GraphKernelFlag: opt_level should be in the range [0,3] but got " << opt_level;
  226. opt_level = OptLevel_3;
  227. }
  228. // Boolean flags
  229. reg.AddFlag("dump_as_text", &dump_as_text);
  230. reg.AddFlag("enable_stitch_fusion", &enable_stitch_fusion, opt_level == OptLevel_3);
  231. reg.AddFlag("enable_recompute_fusion", &enable_recompute_fusion, opt_level >= OptLevel_2);
  232. reg.AddFlag("enable_parallel_fusion", &enable_parallel_fusion, opt_level == OptLevel_3);
  233. reg.AddFlag("enable_horizontal_fusion", &enable_horizontal_fusion, false);
  234. reg.AddFlag("enable_low_precision", &enable_low_precision);
  235. reg.AddFlag("enable_trans_op_optimize", &enable_trans_op_optimize);
  236. // Integer flags
  237. reg.AddFlag("online_tuning", &online_tuning);
  238. reg.AddFlag("fusion_ops_level", &fusion_ops_level, is_ascend ? OpLevel_0 : OpLevel_MAX);
  239. reg.AddFlag("parallel_ops_level", &parallel_ops_level);
  240. reg.AddFlag("recompute_increment_threshold", &recompute_increment_threshold);
  241. reg.AddFlag("recompute_peak_threshold", &recompute_peak_threshold);
  242. // String flags
  243. reg.AddFlag("repository_path", &repository_path);
  244. // String list flags
  245. reg.AddFlag("enable_expand_ops", &enable_expand_ops);
  246. reg.AddFlag("enable_expand_ops_only", &enable_expand_ops_only);
  247. reg.AddFlag("disable_expand_ops", &disable_expand_ops);
  248. reg.AddFlag("enable_cluster_ops", &enable_cluster_ops);
  249. reg.AddFlag("enable_cluster_ops_only", &enable_cluster_ops_only);
  250. reg.AddFlag("disable_cluster_ops", &disable_cluster_ops);
  251. reg.AddFlag("enable_simplify_exprs_only", &enable_simplify_exprs_only);
  252. reg.AddFlag("disable_simplify_exprs", &disable_simplify_exprs);
  253. reg.AddFlag("enable_pass", &enable_pass);
  254. reg.AddFlag("disable_pass", &disable_pass);
  255. }
  256. std::string GraphKernelFlags::DumpAllFlags() const {
  257. nlohmann::json json;
  258. json["dump_as_text"] = dump_as_text;
  259. json["enable_stitch_fusion"] = enable_stitch_fusion;
  260. json["enable_recompute_fusion"] = enable_recompute_fusion;
  261. json["enable_parallel_fusion"] = enable_parallel_fusion;
  262. json["enable_horizontal_fusion"] = enable_horizontal_fusion;
  263. json["enable_low_precision"] = enable_low_precision;
  264. json["enable_trans_op_optimize"] = enable_trans_op_optimize;
  265. json["opt_level"] = opt_level;
  266. json["fusion_ops_level"] = fusion_ops_level;
  267. json["parallel_ops_level"] = parallel_ops_level;
  268. json["online_tuning"] = online_tuning;
  269. json["recompute_increment_threshold"] = recompute_increment_threshold;
  270. json["recompute_peak_threshold"] = recompute_peak_threshold;
  271. json["repository_path"] = repository_path;
  272. json["enable_expand_ops"] = enable_expand_ops;
  273. json["enable_expand_ops_only"] = enable_expand_ops_only;
  274. json["disable_expand_ops"] = disable_expand_ops;
  275. json["enable_cluster_ops"] = enable_cluster_ops;
  276. json["enable_cluster_ops_only"] = enable_cluster_ops_only;
  277. json["disable_cluster_ops"] = disable_cluster_ops;
  278. json["enable_simplify_exprs_only"] = enable_simplify_exprs_only;
  279. json["disable_simplify_exprs"] = disable_simplify_exprs;
  280. json["enable_pass"] = enable_pass;
  281. json["disable_pass"] = disable_pass;
  282. return json.dump();
  283. }
  284. } // namespace mindspore::graphkernel