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.

main.cc 6.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. /**
  2. * Copyright 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. #include <algorithm>
  17. #include <random>
  18. #include <iostream>
  19. #include <fstream>
  20. #include <cstring>
  21. #include "include/errorcode.h"
  22. #include "include/model.h"
  23. #include "include/context.h"
  24. #include "include/lite_session.h"
  25. std::string RealPath(const char *path) {
  26. size_t max = 4096;
  27. if (path == nullptr) {
  28. std::cerr << "path is nullptr" << std::endl;
  29. return "";
  30. }
  31. if ((strlen(path)) >= max) {
  32. std::cerr << "path is too long" << std::endl;
  33. return "";
  34. }
  35. auto resolved_path = std::make_unique<char[]>(max);
  36. if (resolved_path == nullptr) {
  37. std::cerr << "new resolved_path failed" << std::endl;
  38. return "";
  39. }
  40. #ifdef _WIN32
  41. char *real_path = _fullpath(resolved_path.get(), path, 1024);
  42. #else
  43. char *real_path = realpath(path, resolved_path.get());
  44. #endif
  45. if (real_path == nullptr || strlen(real_path) == 0) {
  46. std::cerr << "file path is not valid : " << path << std::endl;
  47. return "";
  48. }
  49. std::string res = resolved_path.get();
  50. return res;
  51. }
  52. char *ReadFile(const char *file, size_t *size) {
  53. if (file == nullptr) {
  54. std::cerr << "file is nullptr." << std::endl;
  55. return nullptr;
  56. }
  57. std::ifstream ifs(file);
  58. if (!ifs.good()) {
  59. std::cerr << "file: " << file << " is not exist." << std::endl;
  60. return nullptr;
  61. }
  62. if (!ifs.is_open()) {
  63. std::cerr << "file: " << file << " open failed." << std::endl;
  64. return nullptr;
  65. }
  66. ifs.seekg(0, std::ios::end);
  67. *size = ifs.tellg();
  68. std::unique_ptr<char[]> buf(new (std::nothrow) char[*size]);
  69. if (buf == nullptr) {
  70. std::cerr << "malloc buf failed, file: " << file << std::endl;
  71. ifs.close();
  72. return nullptr;
  73. }
  74. ifs.seekg(0, std::ios::beg);
  75. ifs.read(buf.get(), *size);
  76. ifs.close();
  77. return buf.release();
  78. }
  79. template <typename T, typename Distribution>
  80. void GenerateRandomData(int size, void *data, Distribution distribution) {
  81. std::mt19937 random_engine;
  82. int elements_num = size / sizeof(T);
  83. (void)std::generate_n(static_cast<T *>(data), elements_num,
  84. [&]() { return static_cast<T>(distribution(random_engine)); });
  85. }
  86. int GenerateInputDataWithRandom(std::vector<mindspore::tensor::MSTensor *> inputs) {
  87. for (auto tensor : inputs) {
  88. auto input_data = tensor->MutableData();
  89. if (input_data == nullptr) {
  90. std::cerr << "MallocData for inTensor failed." << std::endl;
  91. return -1;
  92. }
  93. GenerateRandomData<float>(tensor->Size(), input_data, std::uniform_real_distribution<float>(0.1f, 1.0f));
  94. }
  95. return mindspore::lite::RET_OK;
  96. }
  97. int Run(mindspore::session::LiteSession *session) {
  98. auto inputs = session->GetInputs();
  99. auto ret = GenerateInputDataWithRandom(inputs);
  100. if (ret != mindspore::lite::RET_OK) {
  101. std::cerr << "Generate Random Input Data failed." << std::endl;
  102. return ret;
  103. }
  104. ret = session->RunGraph();
  105. if (ret != mindspore::lite::RET_OK) {
  106. std::cerr << "Inference error " << ret << std::endl;
  107. return ret;
  108. }
  109. auto out_tensors = session->GetOutputs();
  110. for (auto tensor : out_tensors) {
  111. std::cout << "tensor name is:" << tensor.first << " tensor size is:" << tensor.second->Size()
  112. << " tensor elements num is:" << tensor.second->ElementsNum() << std::endl;
  113. auto out_data = reinterpret_cast<float *>(tensor.second->MutableData());
  114. std::cout << "output data is:";
  115. for (int i = 0; i < tensor.second->ElementsNum() && i <= 50; i++) {
  116. std::cout << out_data[i] << " ";
  117. }
  118. std::cout << std::endl;
  119. }
  120. return mindspore::lite::RET_OK;
  121. }
  122. mindspore::session::LiteSession *Compile(mindspore::lite::Model *model) {
  123. // Create and init context.
  124. auto context = std::make_shared<mindspore::lite::Context>();
  125. if (context == nullptr) {
  126. std::cerr << "New context failed while." << std::endl;
  127. return nullptr;
  128. }
  129. // Create the session.
  130. mindspore::session::LiteSession *session = mindspore::session::LiteSession::CreateSession(context.get());
  131. if (session == nullptr) {
  132. std::cerr << "CreateSession failed while running." << std::endl;
  133. return nullptr;
  134. }
  135. // Compile graph.
  136. auto ret = session->CompileGraph(model);
  137. if (ret != mindspore::lite::RET_OK) {
  138. delete session;
  139. std::cerr << "Compile failed while running." << std::endl;
  140. return nullptr;
  141. }
  142. // Note: when use model->Free(), the model can not be compiled again.
  143. if (model != nullptr) {
  144. model->Free();
  145. }
  146. return session;
  147. }
  148. int CompileAndRun(int argc, const char **argv) {
  149. if (argc < 2) {
  150. std::cerr << "Usage: ./mindspore_quick_start_cpp ../model/mobilenetv2.ms\n";
  151. return -1;
  152. }
  153. // Read model file.
  154. auto model_path = RealPath(argv[1]);
  155. if (model_path.empty()) {
  156. std::cerr << "model path " << argv[1] << " is invalid.";
  157. return -1;
  158. }
  159. size_t size = 0;
  160. char *model_buf = ReadFile(model_path.c_str(), &size);
  161. if (model_buf == nullptr) {
  162. std::cerr << "Read model file failed." << std::endl;
  163. return -1;
  164. }
  165. // Load the .ms model.
  166. auto model = mindspore::lite::Model::Import(model_buf, size);
  167. delete[](model_buf);
  168. if (model == nullptr) {
  169. std::cerr << "Import model file failed." << std::endl;
  170. return -1;
  171. }
  172. // Compile MindSpore Lite model.
  173. auto session = Compile(model);
  174. if (session == nullptr) {
  175. delete model;
  176. std::cerr << "Create session failed." << std::endl;
  177. return -1;
  178. }
  179. // Run inference.
  180. auto ret = Run(session);
  181. if (ret != mindspore::lite::RET_OK) {
  182. delete model;
  183. delete session;
  184. std::cerr << "MindSpore Lite run failed." << std::endl;
  185. return -1;
  186. }
  187. // Delete model buffer.
  188. delete model;
  189. // Delete session buffer.
  190. delete session;
  191. return mindspore::lite::RET_OK;
  192. }
  193. int main(int argc, const char **argv) { return CompileAndRun(argc, argv); }