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.

serialization.cc 14 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. #include "include/api/serialization.h"
  17. #include <fstream>
  18. #include <sstream>
  19. #include "cxx_api/graph/graph_data.h"
  20. #include "utils/log_adapter.h"
  21. #include "mindspore/core/load_mindir/load_model.h"
  22. #if !defined(_WIN32) && !defined(_WIN64)
  23. #include "cxx_api/dlutils.h"
  24. #include "minddata/dataset/engine/serdes.h"
  25. #include "minddata/dataset/include/dataset/execute.h"
  26. #endif
  27. #include "utils/crypto.h"
  28. namespace mindspore {
  29. static Status RealPath(const std::string &file, std::string *realpath_str) {
  30. MS_EXCEPTION_IF_NULL(realpath_str);
  31. char real_path_mem[PATH_MAX] = {0};
  32. char *real_path_ret = nullptr;
  33. #if defined(_WIN32) || defined(_WIN64)
  34. real_path_ret = _fullpath(real_path_mem, common::SafeCStr(file), PATH_MAX);
  35. #else
  36. real_path_ret = realpath(common::SafeCStr(file), real_path_mem);
  37. #endif
  38. if (real_path_ret == nullptr) {
  39. return Status(kMEInvalidInput, "File: " + file + " does not exist.");
  40. }
  41. *realpath_str = real_path_mem;
  42. return kSuccess;
  43. }
  44. static Buffer ReadFile(const std::string &file) {
  45. Buffer buffer;
  46. if (file.empty()) {
  47. MS_LOG(ERROR) << "Pointer file is nullptr";
  48. return buffer;
  49. }
  50. std::string real_path;
  51. auto status = RealPath(file, &real_path);
  52. if (status != kSuccess) {
  53. MS_LOG(ERROR) << status.GetErrDescription();
  54. return buffer;
  55. }
  56. std::ifstream ifs(real_path);
  57. if (!ifs.good()) {
  58. MS_LOG(ERROR) << "File: " << real_path << " does not exist";
  59. return buffer;
  60. }
  61. if (!ifs.is_open()) {
  62. MS_LOG(ERROR) << "File: " << real_path << " open failed";
  63. return buffer;
  64. }
  65. (void)ifs.seekg(0, std::ios::end);
  66. size_t size = static_cast<size_t>(ifs.tellg());
  67. buffer.ResizeData(size);
  68. if (buffer.DataSize() != size) {
  69. MS_LOG(ERROR) << "Malloc buf failed, file: " << real_path;
  70. ifs.close();
  71. return buffer;
  72. }
  73. (void)ifs.seekg(0, std::ios::beg);
  74. (void)ifs.read(reinterpret_cast<char *>(buffer.MutableData()), static_cast<std::streamsize>(size));
  75. ifs.close();
  76. return buffer;
  77. }
  78. Key::Key(const char *dec_key, size_t key_len) {
  79. len = 0;
  80. if (key_len >= max_key_len) {
  81. MS_LOG(ERROR) << "Invalid key len " << key_len << " is more than max key len " << max_key_len;
  82. return;
  83. }
  84. auto sec_ret = memcpy_s(key, max_key_len, dec_key, key_len);
  85. if (sec_ret != EOK) {
  86. MS_LOG(ERROR) << "memcpy_s failed, src_len = " << key_len << ", dst_len = " << max_key_len << ", ret = " << sec_ret;
  87. return;
  88. }
  89. len = key_len;
  90. }
  91. Status Serialization::Load(const void *model_data, size_t data_size, ModelType model_type, Graph *graph,
  92. const Key &dec_key, const std::vector<char> &dec_mode) {
  93. std::stringstream err_msg;
  94. if (graph == nullptr) {
  95. err_msg << "Output args graph is nullptr.";
  96. MS_LOG(ERROR) << err_msg.str();
  97. return Status(kMEInvalidInput, err_msg.str());
  98. }
  99. if (model_type == kMindIR) {
  100. FuncGraphPtr anf_graph = nullptr;
  101. try {
  102. if (dec_key.len > dec_key.max_key_len) {
  103. err_msg << "The key length exceeds maximum length: " << dec_key.max_key_len;
  104. MS_LOG(ERROR) << err_msg.str();
  105. return Status(kMEInvalidInput, err_msg.str());
  106. } else if (dec_key.len == 0) {
  107. if (IsCipherFile(reinterpret_cast<const unsigned char *>(model_data))) {
  108. err_msg << "Load model failed. The model_data may be encrypted, please pass in correct key.";
  109. MS_LOG(ERROR) << err_msg.str();
  110. return Status(kMEInvalidInput, err_msg.str());
  111. } else {
  112. anf_graph = ConvertStreamToFuncGraph(reinterpret_cast<const char *>(model_data), data_size);
  113. }
  114. } else {
  115. size_t plain_data_size;
  116. auto plain_data = mindspore::Decrypt(&plain_data_size, reinterpret_cast<const unsigned char *>(model_data),
  117. data_size, dec_key.key, dec_key.len, CharToString(dec_mode));
  118. if (plain_data == nullptr) {
  119. err_msg << "Load model failed. Please check the valid of dec_key and dec_mode.";
  120. MS_LOG(ERROR) << err_msg.str();
  121. return Status(kMEInvalidInput, err_msg.str());
  122. }
  123. anf_graph = ConvertStreamToFuncGraph(reinterpret_cast<const char *>(plain_data.get()), plain_data_size);
  124. }
  125. } catch (const std::exception &) {
  126. err_msg << "Load model failed. Please check the valid of dec_key and dec_mode.";
  127. MS_LOG(ERROR) << err_msg.str();
  128. return Status(kMEInvalidInput, err_msg.str());
  129. }
  130. *graph = Graph(std::make_shared<Graph::GraphData>(anf_graph, kMindIR));
  131. return kSuccess;
  132. } else if (model_type == kOM) {
  133. *graph = Graph(std::make_shared<Graph::GraphData>(Buffer(model_data, data_size), kOM));
  134. return kSuccess;
  135. }
  136. err_msg << "Unsupported ModelType " << model_type;
  137. MS_LOG(ERROR) << err_msg.str();
  138. return Status(kMEInvalidInput, err_msg.str());
  139. }
  140. Status Serialization::Load(const std::vector<char> &file, ModelType model_type, Graph *graph) {
  141. return Load(file, model_type, graph, Key{}, StringToChar(kDecModeAesGcm));
  142. }
  143. Status Serialization::Load(const std::vector<char> &file, ModelType model_type, Graph *graph, const Key &dec_key,
  144. const std::vector<char> &dec_mode) {
  145. std::stringstream err_msg;
  146. if (graph == nullptr) {
  147. MS_LOG(ERROR) << "Output args graph is nullptr.";
  148. return Status(kMEInvalidInput, "Output args graph is nullptr.");
  149. }
  150. std::string file_path;
  151. auto status = RealPath(CharToString(file), &file_path);
  152. if (status != kSuccess) {
  153. MS_LOG(ERROR) << status.GetErrDescription();
  154. return status;
  155. }
  156. if (model_type == kMindIR) {
  157. FuncGraphPtr anf_graph;
  158. if (dec_key.len > dec_key.max_key_len) {
  159. err_msg << "The key length exceeds maximum length: " << dec_key.max_key_len;
  160. MS_LOG(ERROR) << err_msg.str();
  161. return Status(kMEInvalidInput, err_msg.str());
  162. } else if (dec_key.len == 0 && IsCipherFile(file_path)) {
  163. err_msg << "Load model failed. The file may be encrypted, please pass in correct key.";
  164. MS_LOG(ERROR) << err_msg.str();
  165. return Status(kMEInvalidInput, err_msg.str());
  166. } else {
  167. MindIRLoader mindir_loader(false, dec_key.len == 0 ? nullptr : dec_key.key, dec_key.len, CharToString(dec_mode),
  168. false);
  169. anf_graph = mindir_loader.LoadMindIR(file_path);
  170. }
  171. if (anf_graph == nullptr) {
  172. err_msg << "Load model failed. Please check the valid of dec_key and dec_mode";
  173. MS_LOG(ERROR) << err_msg.str();
  174. return Status(kMEInvalidInput, err_msg.str());
  175. }
  176. auto graph_data = std::make_shared<Graph::GraphData>(anf_graph, kMindIR);
  177. #if !defined(_WIN32) && !defined(_WIN64)
  178. // Config preprocessor, temporary way to let mindspore.so depends on _c_dataengine
  179. std::string preprocessor = LoadPreprocess(file_path);
  180. if (!preprocessor.empty()) {
  181. std::string dataengine_so_path;
  182. Status dlret = DLSoPath(&dataengine_so_path);
  183. CHECK_FAIL_AND_RELEASE(dlret, nullptr, "Parse dataengine_so failed: " + dlret.GetErrDescription());
  184. void *handle = nullptr;
  185. void *function = nullptr;
  186. dlret = DLSoOpen(dataengine_so_path, "ParseMindIRPreprocess_C", &handle, &function);
  187. CHECK_FAIL_AND_RELEASE(dlret, handle, "Parse ParseMindIRPreprocess_C failed: " + dlret.GetErrDescription());
  188. auto ParseMindIRPreprocessFun =
  189. (void (*)(const std::string &, const std::string &, std::vector<std::shared_ptr<mindspore::dataset::Execute>> *,
  190. Status *))(function);
  191. std::vector<std::shared_ptr<dataset::Execute>> data_graph;
  192. ParseMindIRPreprocessFun(preprocessor, "image", &data_graph, &dlret);
  193. CHECK_FAIL_AND_RELEASE(dlret, handle, "Load preprocess failed: " + dlret.GetErrDescription());
  194. DLSoClose(handle);
  195. if (!data_graph.empty()) {
  196. graph_data->SetPreprocess(data_graph);
  197. }
  198. }
  199. #endif
  200. *graph = Graph(graph_data);
  201. return kSuccess;
  202. } else if (model_type == kOM) {
  203. Buffer data = ReadFile(file_path);
  204. if (data.Data() == nullptr) {
  205. err_msg << "Read file " << file_path << " failed.";
  206. MS_LOG(ERROR) << err_msg.str();
  207. return Status(kMEInvalidInput, err_msg.str());
  208. }
  209. *graph = Graph(std::make_shared<Graph::GraphData>(data, kOM));
  210. return kSuccess;
  211. }
  212. err_msg << "Unsupported ModelType " << model_type;
  213. MS_LOG(ERROR) << err_msg.str();
  214. return Status(kMEInvalidInput, err_msg.str());
  215. }
  216. Status Serialization::Load(const std::vector<std::vector<char>> &files, ModelType model_type,
  217. std::vector<Graph> *graphs, const Key &dec_key, const std::vector<char> &dec_mode) {
  218. std::stringstream err_msg;
  219. if (graphs == nullptr) {
  220. MS_LOG(ERROR) << "Output args graph is nullptr.";
  221. return Status(kMEInvalidInput, "Output args graph is nullptr.");
  222. }
  223. if (files.size() == 1) {
  224. std::vector<Graph> result(files.size());
  225. auto ret = Load(files[0], model_type, &result[0], dec_key, dec_mode);
  226. *graphs = std::move(result);
  227. return ret;
  228. }
  229. std::vector<std::string> files_path;
  230. for (const auto &file : files) {
  231. std::string file_path;
  232. auto status = RealPath(CharToString(file), &file_path);
  233. if (status != kSuccess) {
  234. MS_LOG(ERROR) << status.GetErrDescription();
  235. return status;
  236. }
  237. files_path.emplace_back(std::move(file_path));
  238. }
  239. if (model_type == kMindIR) {
  240. if (dec_key.len > dec_key.max_key_len) {
  241. err_msg << "The key length exceeds maximum length: " << dec_key.max_key_len;
  242. MS_LOG(ERROR) << err_msg.str();
  243. return Status(kMEInvalidInput, err_msg.str());
  244. }
  245. MindIRLoader mindir_loader(false, dec_key.len == 0 ? nullptr : dec_key.key, dec_key.len, CharToString(dec_mode),
  246. true);
  247. auto anf_graphs = mindir_loader.LoadMindIRs(files_path);
  248. if (anf_graphs.size() != files_path.size()) {
  249. err_msg << "Load model failed, " << files_path.size() << " files got " << anf_graphs.size() << " graphs.";
  250. MS_LOG(ERROR) << err_msg.str();
  251. return Status(kMEInvalidInput, err_msg.str());
  252. }
  253. #if !defined(_WIN32) && !defined(_WIN64)
  254. // Dataset so loading
  255. std::string dataengine_so_path;
  256. Status dlret = DLSoPath(&dataengine_so_path);
  257. CHECK_FAIL_AND_RELEASE(dlret, nullptr, "Parse dataengine_so failed: " + dlret.GetErrDescription());
  258. void *handle = nullptr;
  259. void *function = nullptr;
  260. dlret = DLSoOpen(dataengine_so_path, "ParseMindIRPreprocess_C", &handle, &function);
  261. CHECK_FAIL_AND_RELEASE(dlret, handle, "Parse ParseMindIRPreprocess_C failed: " + dlret.GetErrDescription());
  262. auto ParseMindIRPreprocessFun =
  263. (void (*)(const std::string &, const std::string &, std::vector<std::shared_ptr<mindspore::dataset::Execute>> *,
  264. Status *))(function);
  265. #endif
  266. std::vector<Graph> results;
  267. for (size_t i = 0; i < anf_graphs.size(); ++i) {
  268. if (anf_graphs[i] == nullptr) {
  269. if (dec_key.len == 0 && IsCipherFile(files_path[i])) {
  270. err_msg << "Load model failed. The file " << files_path[i] << " be encrypted, please pass in correct key.";
  271. } else {
  272. err_msg << "Load model " << files_path[i] << " failed.";
  273. }
  274. MS_LOG(ERROR) << err_msg.str();
  275. return Status(kMEInvalidInput, err_msg.str());
  276. }
  277. auto graph_data = std::make_shared<Graph::GraphData>(anf_graphs[i], kMindIR);
  278. #if !defined(_WIN32) && !defined(_WIN64)
  279. // Config preprocessor, temporary way to let mindspore.so depends on _c_dataengine
  280. std::string preprocessor = LoadPreprocess(files_path[i]);
  281. if (!preprocessor.empty()) {
  282. std::vector<std::shared_ptr<dataset::Execute>> data_graph;
  283. ParseMindIRPreprocessFun(preprocessor, "image", &data_graph, &dlret);
  284. CHECK_FAIL_AND_RELEASE(dlret, handle, "Load preprocess failed: " + dlret.GetErrDescription());
  285. if (!data_graph.empty()) {
  286. graph_data->SetPreprocess(data_graph);
  287. }
  288. }
  289. #endif
  290. results.emplace_back(graph_data);
  291. }
  292. #if !defined(_WIN32) && !defined(_WIN64)
  293. // Dataset so release
  294. DLSoClose(handle);
  295. #endif
  296. *graphs = std::move(results);
  297. return kSuccess;
  298. }
  299. err_msg << "Unsupported ModelType " << model_type;
  300. MS_LOG(ERROR) << err_msg.str();
  301. return Status(kMEInvalidInput, err_msg.str());
  302. }
  303. Status Serialization::SetParameters(const std::map<std::string, Buffer> &, Model *) {
  304. MS_LOG(ERROR) << "Unsupported feature.";
  305. return kMEFailed;
  306. }
  307. Status Serialization::ExportModel(const Model &, ModelType, Buffer *) {
  308. MS_LOG(ERROR) << "Unsupported feature.";
  309. return kMEFailed;
  310. }
  311. Status Serialization::ExportModel(const Model &, ModelType, const std::vector<char> &, QuantizationType, bool,
  312. const std::vector<std::vector<char>> &output_tensor_name) {
  313. MS_LOG(ERROR) << "Unsupported feature.";
  314. return kMEFailed;
  315. }
  316. } // namespace mindspore