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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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 Builds a model so that it can run on a device.
  45. ///
  46. /// \param[in] graph GraphCell is a derivative of Cell. Cell is not available currently. GraphCell can be constructed
  47. /// from Graph, for example, model.Build(GraphCell(graph), context).
  48. /// \param[in] model_context A context used to store options during execution.
  49. /// \param[in] train_cfg A config used by training.
  50. ///
  51. /// \return Status.
  52. Status Build(GraphCell graph, const std::shared_ptr<Context> &model_context = nullptr,
  53. const std::shared_ptr<TrainCfg> &train_cfg = nullptr);
  54. /// \brief Resizes the shapes of inputs.
  55. ///
  56. /// \param[in] inputs A vector that includes all input tensors in order.
  57. /// \param[in] dims Defines the new shapes of inputs, should be consistent with inputs.
  58. ///
  59. /// \return Status.
  60. Status Resize(const std::vector<MSTensor> &inputs, const std::vector<std::vector<int64_t>> &dims);
  61. /// \brief Inference model.
  62. ///
  63. /// \param[in] inputs A vector where model inputs are arranged in sequence.
  64. /// \param[out] outputs Which is a pointer to a vector. The model outputs are filled in the container in sequence.
  65. /// \param[in] before CallBack before predict.
  66. /// \param[in] after CallBack after predict.
  67. ///
  68. /// \return Status.
  69. Status Predict(const std::vector<MSTensor> &inputs, std::vector<MSTensor> *outputs,
  70. const MSKernelCallBack &before = nullptr, const MSKernelCallBack &after = nullptr);
  71. /// \brief Inference model with preprocess in model.
  72. ///
  73. /// \param[in] inputs A vector where model inputs are arranged in sequence.
  74. /// \param[out] outputs Which is a pointer to a vector. The model outputs are filled in the container in sequence.
  75. /// \param[in] whether to use data preprocess in model.
  76. /// \param[in] before CallBack before predict.
  77. /// \param[in] after CallBack after predict.
  78. ///
  79. /// \return Status.
  80. Status PredictWithPreprocess(const std::vector<MSTensor> &inputs, std::vector<MSTensor> *outputs,
  81. const MSKernelCallBack &before = nullptr, const MSKernelCallBack &after = nullptr);
  82. /// \brief Apply data preprocess if it exits in model.
  83. ///
  84. /// \param[in] inputs A vector where model inputs are arranged in sequence.
  85. /// \param[out] outputs Which is a pointer to a vector. The model outputs are filled in the container in sequence.
  86. ///
  87. /// \return Status.
  88. Status Preprocess(const std::vector<MSTensor> &inputs, std::vector<MSTensor> *outputs);
  89. /// \brief Check if data preprocess exists in model.
  90. /// \return true if data preprocess exists.
  91. bool HasPreprocess();
  92. /// \brief Load config file.
  93. ///
  94. /// \param[in] config_path config file path.
  95. ///
  96. /// \return Status.
  97. inline Status LoadConfig(const std::string &config_path);
  98. /// \brief Obtains all input tensors of the model.
  99. ///
  100. /// \return The vector that includes all input tensors.
  101. std::vector<MSTensor> GetInputs();
  102. /// \brief Obtains the input tensor of the model by name.
  103. ///
  104. /// \return The input tensor with the given name, if the name is not found, an invalid tensor is returned.
  105. inline MSTensor GetInputByTensorName(const std::string &tensor_name);
  106. /// \brief Obtains all gradient tensors of the model.
  107. ///
  108. /// \return The vector that includes all gradient tensors.
  109. std::vector<MSTensor> GetGradients() const;
  110. /// \brief update gradient tensors of the model.
  111. ///
  112. /// \param[in] inputs A vector new gradients.
  113. /// \return Status of operation
  114. Status ApplyGradients(const std::vector<MSTensor> &gradients);
  115. /// \brief Obtains optimizer params tensors of the model.
  116. ///
  117. /// \return The vector that includes all params tensors.
  118. std::vector<MSTensor> GetOptimizerParams() const;
  119. /// \brief update the optimizer parameters
  120. ///
  121. /// \param[in] inputs A vector new optimizer params.
  122. /// \return Status of operation
  123. Status SetOptimizerParams(const std::vector<MSTensor> &params);
  124. Status InitMetrics(std::vector<Metrics *> metrics);
  125. std::vector<Metrics *> GetMetrics();
  126. /// \brief Obtains all output tensors of the model.
  127. ///
  128. /// \return The vector that includes all output tensors.
  129. std::vector<MSTensor> GetOutputs();
  130. /// \brief Obtains names of all output tensors of the model.
  131. ///
  132. /// \return A vector that includes names of all output tensors.
  133. inline std::vector<std::string> GetOutputTensorNames();
  134. /// \brief Obtains the output tensor of the model by name.
  135. ///
  136. /// \return The output tensor with the given name, if the name is not found, an invalid tensor is returned.
  137. inline MSTensor GetOutputByTensorName(const std::string &tensor_name);
  138. /// \brief Get output MSTensors of model by node name.
  139. ///
  140. /// \param[in] node_name Define node name.
  141. ///
  142. /// \note Deprecated, replace with GetOutputByTensorName
  143. ///
  144. /// \return The vector of output MSTensor.
  145. inline std::vector<MSTensor> GetOutputsByNodeName(const std::string &node_name);
  146. /// \brief Inference model.
  147. ///
  148. /// \param[in] device_type Device type,options are kGPU, kAscend910, etc.
  149. /// \param[in] model_type The type of model file, options are ModelType::kMindIR, ModelType::kOM.
  150. ///
  151. /// \return Is supported or not.
  152. static bool CheckModelSupport(enum DeviceType device_type, ModelType model_type);
  153. Status SetTrainMode(bool train);
  154. bool GetTrainMode() const;
  155. Status Train(int epochs, std::shared_ptr<dataset::Dataset> ds, std::vector<TrainCallBack *> cbs);
  156. Status Evaluate(std::shared_ptr<dataset::Dataset> ds, std::vector<TrainCallBack *> cbs);
  157. /// \brief Build a model from model buffer so that it can run on a device. Only valid for Lite.
  158. ///
  159. /// \param[in] model_data Define the buffer read from a model file.
  160. /// \param[in] size Define bytes number of model buffer.
  161. /// \param[in] model_type Define The type of model file. Options: ModelType::kMindIR, ModelType::kOM. Only
  162. /// ModelType::kMindIR is valid for Lite.
  163. /// \param[in] model_context Define the context used to store options during execution.
  164. /// \param[in] dec_key Define the key used to decrypt the ciphertext model. The key length is 16, 24, or 32.
  165. /// \param[in] dec_mode Define the decryption mode. Options: AES-GCM, AES-CBC.
  166. ///
  167. /// \return Status.
  168. inline Status Build(const void *model_data, size_t data_size, ModelType model_type,
  169. const std::shared_ptr<Context> &model_context = nullptr, const Key &dec_key = {},
  170. const std::string &dec_mode = kDecModeAesGcm);
  171. /// \brief Load and build a model from model buffer so that it can run on a device. Only valid for Lite.
  172. ///
  173. /// \param[in] model_path Define the model path.
  174. /// \param[in] model_type Define The type of model file. Options: ModelType::kMindIR, ModelType::kOM. Only
  175. /// ModelType::kMindIR is valid for Lite.
  176. /// \param[in] model_context Define the context used to store options during execution.
  177. /// \param[in] dec_key Define the key used to decrypt the ciphertext model. The key length is 16, 24, or 32.
  178. /// \param[in] dec_mode Define the decryption mode. Options: AES-GCM, AES-CBC.
  179. ///
  180. /// \return Status.
  181. inline Status Build(const std::string &model_path, ModelType model_type,
  182. const std::shared_ptr<Context> &model_context = nullptr, const Key &dec_key = {},
  183. const std::string &dec_mode = kDecModeAesGcm);
  184. private:
  185. friend class Serialization;
  186. // api without std::string
  187. MSTensor GetInputByTensorName(const std::vector<char> &tensor_name);
  188. std::vector<std::vector<char>> GetOutputTensorNamesChar();
  189. MSTensor GetOutputByTensorName(const std::vector<char> &tensor_name);
  190. std::vector<MSTensor> GetOutputsByNodeName(const std::vector<char> &node_name);
  191. Status LoadConfig(const std::vector<char> &config_path);
  192. Status Build(const void *model_data, size_t data_size, ModelType model_type,
  193. const std::shared_ptr<Context> &model_context, const Key &dec_key, const std::vector<char> &dec_mode);
  194. Status Build(const std::vector<char> &model_path, ModelType model_type, const std::shared_ptr<Context> &model_context,
  195. const Key &dec_key, const std::vector<char> &dec_mode);
  196. std::shared_ptr<ModelImpl> impl_;
  197. };
  198. MSTensor Model::GetInputByTensorName(const std::string &tensor_name) {
  199. return GetInputByTensorName(StringToChar(tensor_name));
  200. }
  201. std::vector<std::string> Model::GetOutputTensorNames() { return VectorCharToString(GetOutputTensorNamesChar()); }
  202. MSTensor Model::GetOutputByTensorName(const std::string &tensor_name) {
  203. return GetOutputByTensorName(StringToChar(tensor_name));
  204. }
  205. std::vector<MSTensor> Model::GetOutputsByNodeName(const std::string &node_name) {
  206. return GetOutputsByNodeName(StringToChar(node_name));
  207. }
  208. Status Model::LoadConfig(const std::string &config_path) {
  209. return LoadConfig(StringToChar(config_path));
  210. }
  211. Status Model::Build(const void *model_data, size_t data_size, ModelType model_type,
  212. const std::shared_ptr<Context> &model_context, const Key &dec_key, const std::string &dec_mode) {
  213. return Build(model_data, data_size, model_type, model_context, dec_key, StringToChar(dec_mode));
  214. }
  215. Status Model::Build(const std::string &model_path, ModelType model_type, const std::shared_ptr<Context> &model_context,
  216. const Key &dec_key, const std::string &dec_mode) {
  217. return Build(StringToChar(model_path), model_type, model_context, dec_key, StringToChar(dec_mode));
  218. }
  219. } // namespace mindspore
  220. #endif // MINDSPORE_INCLUDE_API_MODEL_H