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

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