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.

kernel_build_client.h 8.9 kB

4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. /**
  2. * Copyright 2020-2021 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. #ifndef MINDSPORE_CCSRC_BACKEND_SESSION_KERNEL_BUILD_CLIENT_H_
  17. #define MINDSPORE_CCSRC_BACKEND_SESSION_KERNEL_BUILD_CLIENT_H_
  18. #include <vector>
  19. #include <string>
  20. #include <cstring>
  21. #include <cstdlib>
  22. #include <memory>
  23. #include <mutex>
  24. #include "common/duplex_pipe.h"
  25. #include "utils/log_adapter.h"
  26. #include "utils/ms_context.h"
  27. namespace mindspore {
  28. namespace kernel {
  29. void ReplaceStr(std::string *dest, const std::string &replace, char new_char);
  30. constexpr inline static int kBufferSize = 4096;
  31. constexpr inline static auto kEnv = "python";
  32. // The TAG as prefix of real command from remote.
  33. constexpr inline static auto kTag = "[~]";
  34. static std::string GetPyExe() {
  35. // get real python executable path
  36. auto ms_context = MsContext::GetInstance();
  37. if (ms_context == nullptr) {
  38. return kEnv;
  39. }
  40. auto env = ms_context->get_param<std::string>(MS_CTX_PYTHON_EXE_PATH);
  41. if (env.empty()) {
  42. return kEnv;
  43. }
  44. return env;
  45. }
  46. class KernelBuildClient {
  47. public:
  48. // Send Finish request to server
  49. constexpr inline static auto kFinish = "FINISH";
  50. constexpr inline static auto kAkgStart = "AKG/START";
  51. constexpr inline static auto kAkgData = "AKG/DATA";
  52. constexpr inline static auto kAkgAttr = "AKG/ATTR";
  53. constexpr inline static auto kAkgWait = "AKG/WAIT";
  54. // Receive the response from server
  55. constexpr inline static auto kAck = "ACK";
  56. constexpr inline static auto kErr = "ERR";
  57. constexpr inline static auto kTrue = "True";
  58. constexpr inline static auto kSuccess = "Success";
  59. // Revert \n, \r, [space].
  60. constexpr inline static auto kLF = "[LF]";
  61. constexpr inline static auto kCR = "[CR]";
  62. constexpr inline static auto kSP = "[SP]";
  63. virtual std::string GetEnv() = 0;
  64. virtual std::string GetScript() = 0;
  65. void Open() {
  66. if (!init_) {
  67. // Exception's thrown if open failed
  68. if (dp_->Open({GetEnv(), GetScript()}, true) != -1) {
  69. dp_->SetFinalizeCallback(std::make_shared<std::function<void()>>([this]() { Close(); }));
  70. init_ = true;
  71. }
  72. }
  73. }
  74. void Close() {
  75. if (init_) {
  76. dp_->Close();
  77. init_ = false;
  78. }
  79. }
  80. // Send a request and fetch its response
  81. std::string SendRequest(std::string data) {
  82. std::lock_guard<std::mutex> locker(mutex_);
  83. Request(data);
  84. return Response();
  85. }
  86. void Request(std::string req) {
  87. if (!init_) {
  88. MS_LOG(EXCEPTION) << "Try to send request before Open()";
  89. }
  90. MS_LOG(DEBUG) << "\t[" << req << "]";
  91. *dp_ << req;
  92. }
  93. std::string Response() {
  94. if (!init_) {
  95. MS_LOG(EXCEPTION) << "Try to get response before Open()";
  96. }
  97. std::string res;
  98. *dp_ >> res;
  99. // Filter out the interference
  100. if (res.empty()) {
  101. MS_LOG(EXCEPTION) << "Response is empty";
  102. }
  103. auto start = res.find(kTag);
  104. if (start == std::string::npos) {
  105. MS_LOG(EXCEPTION) << "Response seems incorrect, res: " << res;
  106. }
  107. auto pos = start + std::strlen(kTag);
  108. if (pos > res.size()) { // Safe check for codedex
  109. MS_LOG(EXCEPTION) << "Response seems incorrect, res(" << res.size() << "): {" << res << "}, start: " << start;
  110. }
  111. res = res.substr(pos);
  112. // Revert the line feed and space
  113. if (res != kSuccess && res != kAck && res != kErr && res != kTrue) {
  114. ReplaceStr(&res, kLF, '\n');
  115. ReplaceStr(&res, kSP, ' ');
  116. }
  117. MS_LOG(DEBUG) << "\t[" << res << "]";
  118. return res;
  119. }
  120. // Run AKG building.
  121. bool AkgStart(int process_num, int wait_time);
  122. bool AkgSendAttr(const std::string &attr);
  123. bool AkgSendData(const std::vector<std::string> &jsons);
  124. bool AkgWait();
  125. protected:
  126. KernelBuildClient() : init_(false), dp_(std::make_shared<DuplexPipe>()) {}
  127. virtual ~KernelBuildClient() = default;
  128. private:
  129. // Support multi-thread.
  130. std::mutex mutex_;
  131. bool init_;
  132. std::shared_ptr<DuplexPipe> dp_;
  133. };
  134. static std::string GetScriptFilePath(const std::string &cmd_env, const std::string &cmd_script,
  135. const std::string &server_script) {
  136. auto ms_context = MsContext::GetInstance();
  137. MS_EXCEPTION_IF_NULL(ms_context);
  138. auto server_dir = ms_context->get_param<std::string>(MS_CTX_KERNEL_BUILD_SERVER_DIR);
  139. if (!server_dir.empty()) {
  140. return server_dir + server_script;
  141. }
  142. std::string cmd = cmd_env;
  143. (void)cmd.append(1, ' ').append(cmd_script);
  144. FILE *fpipe = popen(cmd.c_str(), "r");
  145. if (fpipe == nullptr) {
  146. MS_LOG(EXCEPTION) << "popen failed, errno: " << errno;
  147. }
  148. bool start = false;
  149. std::string result;
  150. char buf[kBufferSize];
  151. while (std::fgets(buf, sizeof(buf), fpipe) != nullptr) {
  152. auto len = std::strlen(buf);
  153. if (len == 0 || len >= kBufferSize) {
  154. // Safe check for codedex
  155. // Should never reach here
  156. MS_LOG(EXCEPTION) << "fgets() failed, len: " << len << ", errno: " << errno;
  157. }
  158. if (std::strncmp(buf, kTag, std::strlen(kTag)) == 0) {
  159. start = true;
  160. }
  161. // Filter with 'kTAG' and '\n'
  162. if (start) {
  163. bool line_end = buf[len - 1] == '\n';
  164. result.append(buf, line_end ? len - 1 : len);
  165. if (line_end) {
  166. break;
  167. }
  168. }
  169. }
  170. pclose(fpipe);
  171. const std::string py_suffix = ".py";
  172. if (result.empty() || result.rfind(py_suffix) != (result.length() - py_suffix.length())) {
  173. MS_LOG(EXCEPTION) << "py file seems incorrect, result: {" << result << "}";
  174. }
  175. if (strlen(kTag) > result.size()) { // Safe check for codedex
  176. MS_LOG(EXCEPTION) << "result size seems incorrect, result(" << result.size() << "): {" << result << "}";
  177. }
  178. result = result.substr(strlen(kTag));
  179. MS_LOG(DEBUG) << "result: " << result;
  180. return result;
  181. }
  182. class AscendKernelBuildClient : public KernelBuildClient {
  183. public:
  184. // Server configure
  185. constexpr inline static auto kGetPathScript =
  186. "-c "
  187. "\""
  188. "import pkgutil;"
  189. "path = pkgutil"
  190. ".get_loader(\\\"mindspore._extends.remote.kernel_build_server_ascend\\\")" // Server module name
  191. ".get_filename();"
  192. "print('[~]' + path)"
  193. "\"";
  194. constexpr inline static auto kServerScript = "kernel_build_server_ascend.py";
  195. // Receive the response from server
  196. constexpr inline static auto kFailed = "-1";
  197. // Send server info. query to server
  198. constexpr inline static auto kFormat = "FORMAT";
  199. constexpr inline static auto kSupport = "SUPPORT";
  200. static AscendKernelBuildClient &Instance() {
  201. static AscendKernelBuildClient instance;
  202. return instance;
  203. }
  204. std::string GetEnv() override { return GetPyExe(); }
  205. std::string GetScript() override {
  206. auto env = GetPyExe();
  207. return GetScriptFilePath(env, kGetPathScript, kServerScript);
  208. }
  209. // Run TBE building.
  210. std::string DispatchToServer(const std::string &job_json_str);
  211. AscendKernelBuildClient(const AscendKernelBuildClient &) = delete;
  212. AscendKernelBuildClient &operator=(const AscendKernelBuildClient &) = delete;
  213. AscendKernelBuildClient(AscendKernelBuildClient &&) = delete;
  214. AscendKernelBuildClient &operator=(AscendKernelBuildClient &&) = delete;
  215. private:
  216. AscendKernelBuildClient() { Open(); }
  217. ~AscendKernelBuildClient() override { Close(); }
  218. };
  219. class AkgKernelBuildClient : public KernelBuildClient {
  220. public:
  221. // Server configure
  222. constexpr inline static auto kGetPathScript =
  223. "-c "
  224. "\""
  225. "import pkgutil;"
  226. "path = pkgutil"
  227. ".get_loader(\\\"mindspore._extends.remote.kernel_build_server_akg\\\")" // Server module name
  228. ".get_filename();"
  229. "print('[~]' + path)"
  230. "\"";
  231. constexpr inline static auto kServerScript = "kernel_build_server_akg.py";
  232. static AkgKernelBuildClient &Instance() {
  233. static AkgKernelBuildClient instance;
  234. return instance;
  235. }
  236. std::string GetEnv() override { return GetPyExe(); }
  237. std::string GetScript() override {
  238. auto env = GetPyExe();
  239. return GetScriptFilePath(env, kGetPathScript, kServerScript);
  240. }
  241. AkgKernelBuildClient(const AkgKernelBuildClient &) = delete;
  242. AkgKernelBuildClient &operator=(const AkgKernelBuildClient &) = delete;
  243. AkgKernelBuildClient(AkgKernelBuildClient &&) = delete;
  244. AkgKernelBuildClient &operator=(AkgKernelBuildClient &&) = delete;
  245. private:
  246. AkgKernelBuildClient() { Open(); }
  247. ~AkgKernelBuildClient() override { Close(); }
  248. };
  249. } // namespace kernel
  250. } // namespace mindspore
  251. #endif // MINDSPORE_CCSRC_BACKEND_SESSION_KERNEL_BUILD_CLIENT_H_