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-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 "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. constexpr inline static auto kAkgStart = "AKG/START";
  50. constexpr inline static auto kAkgData = "AKG/DATA";
  51. constexpr inline static auto kAkgWait = "AKG/WAIT";
  52. // Receive the response from server
  53. constexpr inline static auto kAck = "ACK";
  54. constexpr inline static auto kErr = "ERR";
  55. constexpr inline static auto kTrue = "True";
  56. constexpr inline static auto kSuccess = "Success";
  57. // Revert \n, \r, [space].
  58. constexpr inline static auto kLF = "[LF]";
  59. constexpr inline static auto kCR = "[CR]";
  60. constexpr inline static auto kSP = "[SP]";
  61. constexpr inline static unsigned int kTimeOutSeconds = 350;
  62. virtual std::string GetEnv() = 0;
  63. virtual std::string GetScript() = 0;
  64. void Open() {
  65. if (!init_) {
  66. // Exception's thrown if open failed
  67. if (dp_->Open({GetEnv(), GetScript()}, true) != -1) {
  68. dp_->SetFinalizeCallback(std::make_shared<std::function<void()>>([this]() { Close(); }));
  69. init_ = true;
  70. }
  71. }
  72. }
  73. void Close() {
  74. if (init_) {
  75. dp_->Close();
  76. init_ = false;
  77. }
  78. }
  79. // Send a request and fetch its response
  80. std::string SendRequest(std::string data) {
  81. Request(data);
  82. return Response();
  83. }
  84. void Request(std::string req) {
  85. if (!init_) {
  86. MS_LOG(EXCEPTION) << "Try to send request before Open()";
  87. }
  88. MS_LOG(DEBUG) << "\t[" << req << "]";
  89. *dp_ << req;
  90. }
  91. std::string Response() {
  92. if (!init_) {
  93. MS_LOG(EXCEPTION) << "Try to get response before Open()";
  94. }
  95. std::string res;
  96. *dp_ >> res;
  97. // Filter out the interference
  98. if (res.empty()) {
  99. MS_LOG(EXCEPTION) << "Response is empty";
  100. }
  101. auto start = res.find(kTag);
  102. if (start == std::string::npos) {
  103. MS_LOG(EXCEPTION) << "Response seems incorrect, res: " << res;
  104. }
  105. auto pos = start + std::strlen(kTag);
  106. if (pos > res.size()) { // Safe check for codedex
  107. MS_LOG(EXCEPTION) << "Response seems incorrect, res(" << res.size() << "): {" << res << "}, start: " << start;
  108. }
  109. res = res.substr(pos);
  110. // Revert the line feed and space
  111. if (res != kSuccess && res != kAck && res != kErr && res != kTrue) {
  112. ReplaceStr(&res, kLF, '\n');
  113. ReplaceStr(&res, kSP, ' ');
  114. }
  115. MS_LOG(DEBUG) << "\t[" << res << "]";
  116. return res;
  117. }
  118. // Run AKG building.
  119. bool AkgStart(int process_num, int wait_time);
  120. bool AkgSendData(const std::vector<std::string> &jsons);
  121. bool AkgWait();
  122. protected:
  123. KernelBuildClient() : init_(false), dp_(std::make_shared<DuplexPipe>()) {}
  124. virtual ~KernelBuildClient() = default;
  125. private:
  126. bool init_;
  127. std::shared_ptr<DuplexPipe> dp_;
  128. };
  129. static std::string GetScriptFilePath(const std::string cmd_env, const std::string &cmd_script) {
  130. std::string cmd = cmd_env;
  131. (void)cmd.append(1, ' ').append(cmd_script);
  132. FILE *fpipe = popen(cmd.c_str(), "r");
  133. if (fpipe == nullptr) {
  134. MS_LOG(EXCEPTION) << "popen failed, errno: " << errno;
  135. }
  136. bool start = false;
  137. std::string result;
  138. char buf[kBufferSize];
  139. while (std::fgets(buf, sizeof(buf), fpipe) != nullptr) {
  140. auto len = std::strlen(buf);
  141. if (len == 0 || len >= kBufferSize) {
  142. // Safe check for codedex
  143. // Should never reach here
  144. MS_LOG(EXCEPTION) << "fgets() failed, len: " << len << ", errno: " << errno;
  145. }
  146. if (std::strncmp(buf, kTag, std::strlen(kTag)) == 0) {
  147. start = true;
  148. }
  149. // Filter with 'kTAG' and '\n'
  150. if (start) {
  151. bool line_end = buf[len - 1] == '\n';
  152. result.append(buf, line_end ? len - 1 : len);
  153. if (line_end) {
  154. break;
  155. }
  156. }
  157. }
  158. pclose(fpipe);
  159. const std::string py_suffix = ".py";
  160. if (result.empty() || result.rfind(py_suffix) != (result.length() - py_suffix.length())) {
  161. MS_LOG(EXCEPTION) << "py file seems incorrect, result: {" << result << "}";
  162. }
  163. if (strlen(kTag) > result.size()) { // Safe check for codedex
  164. MS_LOG(EXCEPTION) << "result size seems incorrect, result(" << result.size() << "): {" << result << "}";
  165. }
  166. result = result.substr(strlen(kTag));
  167. MS_LOG(DEBUG) << "result: " << result;
  168. return result;
  169. }
  170. class AscendKernelBuildClient : public KernelBuildClient {
  171. public:
  172. // Server configure
  173. constexpr inline static auto kGetPathScript =
  174. "-c "
  175. "\""
  176. "import pkgutil;"
  177. "path = pkgutil"
  178. ".get_loader(\\\"mindspore._extends.remote.kernel_build_server_ascend\\\")" // Server module name
  179. ".get_filename();"
  180. "print('[~]' + path)"
  181. "\"";
  182. // Receive the response from server
  183. constexpr inline static auto kFailed = "-1";
  184. // Send building request to server
  185. constexpr inline static auto kContinue = "CONTINUE"; // More transactions to be continued
  186. constexpr inline static auto kTbePre = "TBE/PRE";
  187. constexpr inline static auto kTbeStart = "TBE/START";
  188. constexpr inline static auto kTbeWait = "TBE/WAIT";
  189. constexpr inline static auto kTbeReset = "TBE/RESET";
  190. constexpr inline static auto kTbeTune = "TBE/TUNE";
  191. // Send server info. query to server
  192. constexpr inline static auto kFormat = "FORMAT";
  193. constexpr inline static auto kSupport = "SUPPORT";
  194. static AscendKernelBuildClient &Instance() {
  195. static AscendKernelBuildClient instance;
  196. return instance;
  197. }
  198. std::string GetEnv() override { return GetPyExe(); }
  199. std::string GetScript() override {
  200. auto env = GetPyExe();
  201. return GetScriptFilePath(env, kGetPathScript);
  202. }
  203. // Before building.
  204. std::string SelectFormat(const std::string &json);
  205. bool CheckSupported(const std::string &json);
  206. // Run TBE building.
  207. int TbeStart(const std::string &json, const std::string &mode);
  208. bool TbeWait(int *task_id, std::string *task_result, std::string *pre_build_result);
  209. void TbeReset();
  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(const std::string &mode);
  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_