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.

model.h 16 kB

4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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_INCLUDE_API_MODEL_H
  17. #define MINDSPORE_INCLUDE_API_MODEL_H
  18. #include <string>
  19. #include <vector>
  20. #include <map>
  21. #include <memory>
  22. #include <utility>
  23. #include "include/api/status.h"
  24. #include "include/api/types.h"
  25. #include "include/api/graph.h"
  26. #include "include/api/context.h"
  27. #include "include/api/callback/callback.h"
  28. #include "include/api/cell.h"
  29. #include "include/api/cfg.h"
  30. #include "include/api/dual_abi_helper.h"
  31. namespace mindspore {
  32. class ModelImpl;
  33. class Metrics;
  34. namespace dataset {
  35. class Dataset;
  36. } // namespace dataset
  37. /// \brief The Model class is used to define a MindSpore model, facilitating computational graph management.
  38. class MS_API Model {
  39. public:
  40. Model();
  41. ~Model();
  42. Model(const Model &) = delete;
  43. void operator=(const Model &) = delete;
  44. /// \brief Build a model from model buffer so that it can run on a device. Only valid for Lite.
  45. ///
  46. /// \param[in] model_data Define the buffer read from a model file.
  47. /// \param[in] data_size Define bytes number of model buffer.
  48. /// \param[in] model_type Define The type of model file. Options: ModelType::kMindIR, ModelType::kOM. Only
  49. /// ModelType::kMindIR is valid for Lite.
  50. /// \param[in] model_context Define the context used to store options during execution.
  51. ///
  52. /// \return Status.
  53. Status Build(const void *model_data, size_t data_size, ModelType model_type,
  54. const std::shared_ptr<Context> &model_context = nullptr);
  55. /// \brief Load and build a model from model buffer so that it can run on a device. Only valid for Lite.
  56. ///
  57. /// \param[in] model_path Define the model path.
  58. /// \param[in] model_type Define The type of model file. Options: ModelType::kMindIR, ModelType::kOM. Only
  59. /// ModelType::kMindIR is valid for Lite.
  60. /// \param[in] model_context Define the context used to store options during execution.
  61. ///
  62. /// \return Status.
  63. Status Build(const std::string &model_path, ModelType model_type,
  64. const std::shared_ptr<Context> &model_context = nullptr);
  65. /// \brief Build a model from model buffer so that it can run on a device. Only valid for Lite.
  66. ///
  67. /// \param[in] model_data Define the buffer read from a model file.
  68. /// \param[in] data_size Define bytes number of model buffer.
  69. /// \param[in] model_type Define The type of model file. Options: ModelType::kMindIR, ModelType::kOM. Only
  70. /// ModelType::kMindIR is valid for Lite.
  71. /// \param[in] model_context Define the context used to store options during execution.
  72. /// \param[in] dec_key Define the key used to decrypt the ciphertext model. The key length is 16.
  73. /// \param[in] dec_mode Define the decryption mode. Options: AES-GCM.
  74. /// \param[in] cropto_lib_path Define the openssl library path.
  75. ///
  76. /// \return Status.
  77. Status Build(const void *model_data, size_t data_size, ModelType model_type,
  78. const std::shared_ptr<Context> &model_context, const Key &dec_key, const std::string &dec_mode,
  79. const std::string &cropto_lib_path);
  80. /// \brief Load and build a model from model buffer so that it can run on a device. Only valid for Lite.
  81. ///
  82. /// \param[in] model_path Define the model path.
  83. /// \param[in] model_type Define The type of model file. Options: ModelType::kMindIR, ModelType::kOM. Only
  84. /// ModelType::kMindIR is valid for Lite.
  85. /// \param[in] model_context Define the context used to store options during execution.
  86. /// \param[in] dec_key Define the key used to decrypt the ciphertext model. The key length is 16.
  87. /// \param[in] dec_mode Define the decryption mode. Options: AES-GCM.
  88. /// \param[in] cropto_lib_path Define the openssl library path.
  89. ///
  90. /// \return Status.
  91. Status Build(const std::string &model_path, ModelType model_type, const std::shared_ptr<Context> &model_context,
  92. const Key &dec_key, const std::string &dec_mode, const std::string &cropto_lib_path);
  93. /// \brief Builds a model
  94. ///
  95. /// \param[in] graph GraphCell is a derivative of Cell. Cell is not available currently. GraphCell can be constructed
  96. /// from Graph, for example, model.Build(GraphCell(graph), context).
  97. /// \param[in] model_context A context used to store options during execution.
  98. /// \param[in] train_cfg A config used by training.
  99. ///
  100. /// \return Status.
  101. Status Build(GraphCell graph, const std::shared_ptr<Context> &model_context = nullptr,
  102. const std::shared_ptr<TrainCfg> &train_cfg = nullptr);
  103. /// \brief Builds a Transfer Learning model where the backbone weights are fixed and the head weights are trainable
  104. ///
  105. /// \param[in] backbone The static, non-learnable part of the graph
  106. /// \param[in] head The trainable part of the graph
  107. /// \param[in] context A context used to store options during execution
  108. /// \param[in] cfg A config used by training
  109. ///
  110. /// \return Status
  111. Status BuildTransferLearning(GraphCell backbone, GraphCell head, const std::shared_ptr<Context> &context,
  112. const std::shared_ptr<TrainCfg> &train_cfg = nullptr);
  113. /// \brief Resizes the shapes of inputs.
  114. ///
  115. /// \param[in] inputs A vector that includes all input tensors in order.
  116. /// \param[in] dims Defines the new shapes of inputs, should be consistent with inputs.
  117. ///
  118. /// \return Status.
  119. Status Resize(const std::vector<MSTensor> &inputs, const std::vector<std::vector<int64_t>> &dims);
  120. /// \brief Change the size and or content of weight tensors
  121. ///
  122. /// \param[in] new_weights a vector of tensors with new shapes and data to use in the model
  123. /// If data pointer is null, the data of the original tensors will be copied to the new ones
  124. ///
  125. /// \return Status.
  126. Status UpdateWeights(const std::vector<MSTensor> &new_weights);
  127. /// \brief Inference model.
  128. ///
  129. /// \param[in] inputs A vector where model inputs are arranged in sequence.
  130. /// \param[out] outputs Which is a pointer to a vector. The model outputs are filled in the container in sequence.
  131. /// \param[in] before CallBack before predict.
  132. /// \param[in] after CallBack after predict.
  133. ///
  134. /// \return Status.
  135. Status Predict(const std::vector<MSTensor> &inputs, std::vector<MSTensor> *outputs,
  136. const MSKernelCallBack &before = nullptr, const MSKernelCallBack &after = nullptr);
  137. /// \brief Train model by step.
  138. ///
  139. /// \param[in] before CallBack before predict.
  140. /// \param[in] after CallBack after predict.
  141. ///
  142. /// \return Status.
  143. Status RunStep(const MSKernelCallBack &before = nullptr, const MSKernelCallBack &after = nullptr);
  144. /// \brief Inference model with preprocess in model.
  145. ///
  146. /// \param[in] inputs A vector where model inputs are arranged in sequence.
  147. /// \param[out] outputs Which is a pointer to a vector. The model outputs are filled in the container in sequence.
  148. /// \param[in] whether to use data preprocess in model.
  149. /// \param[in] before CallBack before predict.
  150. /// \param[in] after CallBack after predict.
  151. ///
  152. /// \return Status.
  153. Status PredictWithPreprocess(const std::vector<std::vector<MSTensor>> &inputs, std::vector<MSTensor> *outputs,
  154. const MSKernelCallBack &before = nullptr, const MSKernelCallBack &after = nullptr);
  155. /// \brief Apply data preprocess if it exits in model.
  156. ///
  157. /// \param[in] inputs A vector where model inputs are arranged in sequence.
  158. /// \param[out] outputs Which is a pointer to a vector. The model outputs are filled in the container in sequence.
  159. ///
  160. /// \return Status.
  161. Status Preprocess(const std::vector<std::vector<MSTensor>> &inputs, std::vector<MSTensor> *outputs);
  162. /// \brief Check if data preprocess exists in model.
  163. /// \return true if data preprocess exists.
  164. bool HasPreprocess();
  165. /// \brief Load config file.
  166. ///
  167. /// \param[in] config_path config file path.
  168. ///
  169. /// \return Status.
  170. inline Status LoadConfig(const std::string &config_path);
  171. /// \brief Update config.
  172. ///
  173. /// \param[in] section define the config section.
  174. /// \param[in] config define the config will be updated.
  175. ///
  176. /// \return Status.
  177. inline Status UpdateConfig(const std::string &section, const std::pair<std::string, std::string> &config);
  178. /// \brief Obtains all input tensors of the model.
  179. ///
  180. /// \return The vector that includes all input tensors.
  181. std::vector<MSTensor> GetInputs();
  182. /// \brief Obtains the input tensor of the model by name.
  183. ///
  184. /// \return The input tensor with the given name, if the name is not found, an invalid tensor is returned.
  185. inline MSTensor GetInputByTensorName(const std::string &tensor_name);
  186. /// \brief Obtains all gradient tensors of the model.
  187. ///
  188. /// \return The vector that includes all gradient tensors.
  189. std::vector<MSTensor> GetGradients() const;
  190. /// \brief update gradient tensors of the model.
  191. ///
  192. /// \param[in] inputs A vector new gradients.
  193. /// \return Status of operation
  194. Status ApplyGradients(const std::vector<MSTensor> &gradients);
  195. /// \brief Obtains all weights tensors of the model.
  196. ///
  197. /// \return The vector that includes all gradient tensors.
  198. std::vector<MSTensor> GetFeatureMaps() const;
  199. /// \brief update weights tensors of the model.
  200. ///
  201. /// \param[in] inputs A vector new weights.
  202. /// \return Status of operation
  203. Status UpdateFeatureMaps(const std::vector<MSTensor> &new_weights);
  204. /// \brief Obtains optimizer params tensors of the model.
  205. ///
  206. /// \return The vector that includes all params tensors.
  207. std::vector<MSTensor> GetOptimizerParams() const;
  208. /// \brief update the optimizer parameters
  209. ///
  210. /// \param[in] inputs A vector new optimizer params.
  211. /// \return Status of operation
  212. Status SetOptimizerParams(const std::vector<MSTensor> &params);
  213. /// \brief Setup training with virtual batches
  214. ///
  215. /// \param[in] virtual_batch_multiplier - virtual batch multiplier, use any number < 1 to disable
  216. /// \param[in] lr - learning rate to use for virtual batch, -1 for internal configuration
  217. /// \param[in] momentum - batch norm momentum to use for virtual batch, -1 for internal configuration
  218. /// \return Status of operation
  219. Status SetupVirtualBatch(int virtual_batch_multiplier, float lr = -1.0f, float momentum = -1.0f);
  220. /// \brief Sets the Learning Rate of the training
  221. ///
  222. /// \param[in] learning_rate to set
  223. /// \return Status of operation
  224. Status SetLearningRate(float learning_rate);
  225. /// \brief Gets the Learning Rate of the optimizer
  226. ///
  227. /// \return learning rate. 0.0 if no optimizer was found
  228. float GetLearningRate();
  229. Status InitMetrics(std::vector<Metrics *> metrics);
  230. std::vector<Metrics *> GetMetrics();
  231. /// \brief Obtains all output tensors of the model.
  232. ///
  233. /// \return The vector that includes all output tensors.
  234. std::vector<MSTensor> GetOutputs();
  235. /// \brief Obtains names of all output tensors of the model.
  236. ///
  237. /// \return A vector that includes names of all output tensors.
  238. inline std::vector<std::string> GetOutputTensorNames();
  239. /// \brief Obtains the output tensor of the model by name.
  240. ///
  241. /// \return The output tensor with the given name, if the name is not found, an invalid tensor is returned.
  242. inline MSTensor GetOutputByTensorName(const std::string &tensor_name);
  243. /// \brief Get output MSTensors of model by node name.
  244. ///
  245. /// \param[in] node_name Define node name.
  246. ///
  247. /// \note Deprecated, replace with GetOutputByTensorName
  248. ///
  249. /// \return The vector of output MSTensor.
  250. inline std::vector<MSTensor> GetOutputsByNodeName(const std::string &node_name);
  251. /// \brief Bind GLTexture2D object to cl Memory.
  252. ///
  253. /// \param[in] inputGlTexture The input GLTexture id for Model.
  254. /// \param[in] outputGLTexture The output GLTexture id for Model.
  255. ///
  256. /// \return Status of operation.
  257. Status BindGLTexture2DMemory(const std::map<std::string, unsigned int> &inputGLTexture,
  258. std::map<std::string, unsigned int> *outputGLTexture);
  259. /// \brief Inference model.
  260. ///
  261. /// \param[in] device_type Device type,options are kGPU, kAscend etc.
  262. /// \param[in] model_type The type of model file, options are ModelType::kMindIR, ModelType::kOM.
  263. ///
  264. /// \return Is supported or not.
  265. static bool CheckModelSupport(enum DeviceType device_type, ModelType model_type);
  266. Status SetTrainMode(bool train);
  267. bool GetTrainMode() const;
  268. Status Train(int epochs, std::shared_ptr<dataset::Dataset> ds, std::vector<TrainCallBack *> cbs);
  269. Status Evaluate(std::shared_ptr<dataset::Dataset> ds, std::vector<TrainCallBack *> cbs);
  270. private:
  271. friend class Serialization;
  272. // api without std::string
  273. MSTensor GetInputByTensorName(const std::vector<char> &tensor_name);
  274. std::vector<std::vector<char>> GetOutputTensorNamesChar();
  275. MSTensor GetOutputByTensorName(const std::vector<char> &tensor_name);
  276. std::vector<MSTensor> GetOutputsByNodeName(const std::vector<char> &node_name);
  277. Status LoadConfig(const std::vector<char> &config_path);
  278. Status UpdateConfig(const std::vector<char> &section, const std::pair<std::vector<char>, std::vector<char>> &config);
  279. Status Build(const std::vector<char> &model_path, ModelType model_type,
  280. const std::shared_ptr<Context> &model_context);
  281. Status Build(const std::vector<char> &model_path, ModelType model_type, const std::shared_ptr<Context> &model_context,
  282. const Key &dec_key, const std::string &dec_mode, const std::vector<char> &cropto_lib_path);
  283. std::shared_ptr<ModelImpl> impl_;
  284. };
  285. MSTensor Model::GetInputByTensorName(const std::string &tensor_name) {
  286. return GetInputByTensorName(StringToChar(tensor_name));
  287. }
  288. std::vector<std::string> Model::GetOutputTensorNames() { return VectorCharToString(GetOutputTensorNamesChar()); }
  289. MSTensor Model::GetOutputByTensorName(const std::string &tensor_name) {
  290. return GetOutputByTensorName(StringToChar(tensor_name));
  291. }
  292. std::vector<MSTensor> Model::GetOutputsByNodeName(const std::string &node_name) {
  293. return GetOutputsByNodeName(StringToChar(node_name));
  294. }
  295. Status Model::LoadConfig(const std::string &config_path) { return LoadConfig(StringToChar(config_path)); }
  296. Status Model::UpdateConfig(const std::string &section, const std::pair<std::string, std::string> &config) {
  297. std::pair<std::vector<char>, std::vector<char>> config_pair = {StringToChar(config.first),
  298. StringToChar(config.second)};
  299. return UpdateConfig(StringToChar(section), config_pair);
  300. }
  301. inline Status Model::Build(const std::string &model_path, ModelType model_type,
  302. const std::shared_ptr<Context> &model_context, const Key &dec_key,
  303. const std::string &dec_mode, const std::string &cropto_lib_path) {
  304. return Build(StringToChar(model_path), model_type, model_context, dec_key, dec_mode, StringToChar(cropto_lib_path));
  305. }
  306. inline Status Model::Build(const std::string &model_path, ModelType model_type,
  307. const std::shared_ptr<Context> &model_context) {
  308. return Build(StringToChar(model_path), model_type, model_context);
  309. }
  310. } // namespace mindspore
  311. #endif // MINDSPORE_INCLUDE_API_MODEL_H