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.7 kB

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