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.

host_cpu_engine.cc 14 kB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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 "host_cpu_engine.h"
  17. #include "graph/common/omg_util.h"
  18. #include "graph/utils/op_desc_utils.h"
  19. #include "graph/utils/tensor_adapter.h"
  20. #include "register/op_kernel_registry.h"
  21. #include "register/host_cpu_context.h"
  22. #include "common/ge/ge_util.h"
  23. #include "common/ge/plugin_manager.h"
  24. #include "graph/utils/type_utils.h"
  25. #include "common/fp16_t.h"
  26. #include "common/math/math_util.h"
  27. namespace {
  28. #define CREATE_OUTPUT_CASE(DTYPE, TYPE) \
  29. case (DTYPE): { \
  30. GeTensorPtr ge_tensor = nullptr; \
  31. if (need_create_flag) { \
  32. uint64_t size = data_num * sizeof(TYPE); \
  33. ge_tensor = MakeShared<GeTensor>(out_desc, size); \
  34. GE_CHECK_NOTNULL(ge_tensor); \
  35. GELOGD("node:%s allocate output %zu success, size=%lld", op_desc->GetName().c_str(), i, size); \
  36. ge_tensor->MutableTensorDesc().SetDataType(out_desc.GetDataType()); \
  37. ge_tensor->MutableTensorDesc().SetShape(out_desc.GetShape()); \
  38. outputs.emplace_back(ge_tensor); \
  39. } else { \
  40. ge_tensor = outputs[i]; \
  41. GE_CHECK_NOTNULL(ge_tensor); \
  42. GELOGD("node:%s existed output %zu", op_desc->GetName().c_str(), i); \
  43. } \
  44. auto tensor = TensorAdapter::AsTensor(*ge_tensor); \
  45. auto tensor_name = op_desc->GetOutputNameByIndex(i); \
  46. GE_RETURN_WITH_LOG_IF_TRUE(tensor_name.empty(), "Failed to get output name. node = %s, index = %zu", \
  47. op_desc->GetName().c_str(), i); \
  48. named_outputs.emplace(tensor_name, tensor); \
  49. break; \
  50. }
  51. }
  52. namespace ge {
  53. namespace {
  54. const char *kEnvKeyOppPath = "ASCEND_OPP_PATH";
  55. const char *kHostCpuLibRelativePath = "/op_impl/built-in/host_cpu";
  56. }
  57. Status GetDataNumber(const GeTensorDesc &out_desc, uint64_t &data_num) {
  58. int64_t num_size = out_desc.GetShape().IsScalar() ? 1 : out_desc.GetShape().GetShapeSize();
  59. if (out_desc.GetShape().IsUnknownShape()) {
  60. std::vector<std::pair<int64_t, int64_t>> range;
  61. if (out_desc.GetShapeRange(range) != GRAPH_SUCCESS) {
  62. GELOGE(INTERNAL_ERROR, "Get shape range failed.");
  63. return INTERNAL_ERROR;
  64. }
  65. int64_t max_range_size = 1;
  66. for (const auto& item : range) {
  67. FMK_INT64_MULCHECK(max_range_size, item.second);
  68. max_range_size *= item.second;
  69. }
  70. num_size = max_range_size;
  71. }
  72. if (num_size < 0) {
  73. GELOGE(INTERNAL_ERROR, "Get negative size, num_size=%lld.", num_size);
  74. return INTERNAL_ERROR;
  75. }
  76. data_num = static_cast<uint64_t>(num_size);
  77. return SUCCESS;
  78. }
  79. void HostCpuEngine::CloseSo() {
  80. for (auto handle : lib_handles_) {
  81. if (mmDlclose(handle) != 0) {
  82. GELOGW("failed to close handle, message: %s", mmDlerror());
  83. }
  84. }
  85. lib_handles_.clear();
  86. }
  87. ge::Status HostCpuEngine::Initialize() {
  88. std::lock_guard<std::mutex> lock(mu_);
  89. if (initialized_) {
  90. GELOGI("HostCpuEngine is already initialized");
  91. return SUCCESS;
  92. }
  93. std::string lib_dir;
  94. GE_CHK_STATUS_RET_NOLOG(GetLibPath(lib_dir));
  95. std::vector<std::string> so_paths;
  96. if (ListSoFiles(lib_dir, so_paths) == SUCCESS) {
  97. (void) LoadLibs(so_paths);
  98. }
  99. initialized_ = true;
  100. return SUCCESS;
  101. }
  102. void HostCpuEngine::Finalize() {
  103. GELOGI("start HostCpuEngine::Finalize");
  104. }
  105. bool HostCpuEngine::CheckSupported(const string &op_type) {
  106. return OpKernelRegistry::GetInstance().IsRegistered(op_type);
  107. }
  108. Status HostCpuEngine::FindOpKernel(const ge::NodePtr &node, std::unique_ptr<HostCpuOp> &op_kernel) {
  109. std::string op_type;
  110. auto status = GetOriginalType(node, op_type);
  111. GE_CHK_BOOL_EXEC_NOLOG(status == SUCCESS, return status);
  112. auto kernel = OpKernelRegistry::GetInstance().CreateHostCpuOp(op_type);
  113. if (kernel == nullptr) {
  114. GELOGD("Op of type %s is not supported by host cpu engine", op_type.c_str());
  115. return UNSUPPORTED;
  116. }
  117. GELOGD("Successfully created op kernel. op type = %s", op_type.c_str());
  118. op_kernel = std::move(kernel);
  119. return SUCCESS;
  120. }
  121. Status HostCpuEngine::PrepareInputs(const ge::ConstOpDescPtr &op_desc,
  122. const vector<ConstGeTensorPtr> &inputs,
  123. map<std::string, const Tensor> &named_inputs) {
  124. auto num_inputs = op_desc->GetInputsSize();
  125. if (num_inputs != inputs.size()) {
  126. GELOGE(PARAM_INVALID,
  127. "Mismatching input sizes. op_desc has %zu input(s), but given %zu",
  128. num_inputs,
  129. inputs.size());
  130. return PARAM_INVALID;
  131. }
  132. for (size_t i = 0; i < num_inputs; ++i) {
  133. auto ge_tensor = inputs[i];
  134. GE_CHECK_NOTNULL(ge_tensor);
  135. auto tensor = TensorAdapter::AsTensor(*ge_tensor);
  136. auto tensor_name = op_desc->GetInputNameByIndex(i);
  137. GE_RETURN_WITH_LOG_IF_TRUE(tensor_name.empty(),
  138. "Failed to get input name. node = %s, index = %zu", op_desc->GetName().c_str(), i);
  139. GELOGD("Successfully inserted input tensor. node = %s, index = %zu, input name = %s",
  140. op_desc->GetName().c_str(), i, tensor_name.c_str());
  141. named_inputs.emplace(tensor_name, tensor);
  142. }
  143. return SUCCESS;
  144. }
  145. Status HostCpuEngine::PrepareOutputs(const ge::ConstOpDescPtr &op_desc,
  146. vector<GeTensorPtr> &outputs,
  147. map<std::string, Tensor> &named_outputs) {
  148. if (!outputs.empty() && (outputs.size() != op_desc->GetOutputsSize())) {
  149. GELOGW("size of outputs not match, size of outputs = %zu, exactly output_num=%zu.",
  150. outputs.size(), op_desc->GetOutputsSize());
  151. outputs.clear();
  152. }
  153. bool need_create_flag = (outputs.size() != op_desc->GetOutputsSize());
  154. for (size_t i = 0; i < op_desc->GetOutputsSize(); ++i) {
  155. const auto &out_desc = op_desc->GetOutputDesc(i);
  156. uint64_t data_num = 0;
  157. if (need_create_flag) {
  158. if (GetDataNumber(out_desc, data_num) != SUCCESS) {
  159. GELOGE(INTERNAL_ERROR, "node:%s, get size for output %zu failed", op_desc->GetName().c_str(), i);
  160. return INTERNAL_ERROR;
  161. }
  162. }
  163. switch (out_desc.GetDataType()) {
  164. CREATE_OUTPUT_CASE(DT_BOOL, bool)
  165. CREATE_OUTPUT_CASE(DT_INT8, int8_t)
  166. CREATE_OUTPUT_CASE(DT_INT16, int16_t)
  167. CREATE_OUTPUT_CASE(DT_INT32, int32_t)
  168. CREATE_OUTPUT_CASE(DT_INT64, int64_t)
  169. CREATE_OUTPUT_CASE(DT_UINT8, uint8_t)
  170. CREATE_OUTPUT_CASE(DT_UINT16, uint16_t)
  171. CREATE_OUTPUT_CASE(DT_UINT32, uint32_t)
  172. CREATE_OUTPUT_CASE(DT_UINT64, uint64_t)
  173. CREATE_OUTPUT_CASE(DT_FLOAT16, fp16_t)
  174. CREATE_OUTPUT_CASE(DT_FLOAT, float)
  175. CREATE_OUTPUT_CASE(DT_DOUBLE, double)
  176. default:
  177. GELOGW("data type %s not support.",
  178. TypeUtils::DataTypeToSerialString(out_desc.GetDataType()).c_str());
  179. return NOT_CHANGED;
  180. }
  181. }
  182. return SUCCESS;
  183. }
  184. Status HostCpuEngine::RunInternal(const ge::OpDescPtr &op_desc,
  185. HostCpuOp &op_kernel,
  186. map<std::string, const Tensor> &named_inputs,
  187. map<std::string, Tensor> &named_outputs) {
  188. GELOGD("Run operation on host cpu, op name: %s", op_desc->GetName().c_str());
  189. Operator op = ge::OpDescUtils::CreateOperatorFromOpDesc(op_desc);
  190. auto ret = op_kernel.Compute(op, named_inputs, named_outputs);
  191. if (ret != GRAPH_SUCCESS) {
  192. GELOGW("Failed to compute host cpu op. node = %s", op_desc->GetName().c_str());
  193. return FAILED;
  194. }
  195. op.BreakConnect();
  196. return SUCCESS;
  197. }
  198. Status HostCpuEngine::Run(NodePtr &node, const vector<ConstGeTensorPtr> &inputs, std::vector<GeTensorPtr> &outputs) {
  199. GE_CHECK_NOTNULL(node);
  200. GE_CHECK_NOTNULL(node->GetOpDesc());
  201. GELOGD("Run node by host cpu engine. node name = %s", node->GetName().c_str());
  202. std::unique_ptr<HostCpuOp> op_kernel;
  203. GE_CHK_STATUS_RET_NOLOG(FindOpKernel(node, op_kernel));
  204. std::map<std::string, const Tensor> named_inputs;
  205. std::vector<GeTensorPtr> tmp_outputs;
  206. tmp_outputs.swap(outputs);
  207. std::map<std::string, Tensor> named_outputs;
  208. auto op_desc = node->GetOpDesc();
  209. GE_CHK_STATUS_RET_NOLOG(PrepareInputs(op_desc, inputs, named_inputs));
  210. GE_CHK_STATUS_RET_NOLOG(PrepareOutputs(op_desc, tmp_outputs, named_outputs));
  211. GE_CHK_STATUS_RET_NOLOG(RunInternal(op_desc, *op_kernel, named_inputs, named_outputs));
  212. GELOGD("Run node by host cpu engine successfully. name node = %s", node->GetName().c_str());
  213. outputs.swap(tmp_outputs);
  214. return SUCCESS;
  215. }
  216. ge::Status HostCpuEngine::GetLibPath(std::string &lib_path) {
  217. GELOGI("Start to get host cpu lib path");
  218. const char *path_env = std::getenv(kEnvKeyOppPath);
  219. if (path_env != nullptr) {
  220. lib_path = path_env;
  221. if (!lib_path.empty()) {
  222. lib_path += kHostCpuLibRelativePath;
  223. GELOGI("Get host cpu so path from env: %s", lib_path.c_str());
  224. return SUCCESS;
  225. }
  226. }
  227. lib_path = PluginManager::GetPath();
  228. GELOGI("path_base is %s", lib_path.c_str());
  229. lib_path = lib_path.substr(0, lib_path.rfind('/'));
  230. lib_path = lib_path.substr(0, lib_path.rfind('/'));
  231. lib_path += "/opp";
  232. lib_path += kHostCpuLibRelativePath;
  233. GELOGI("Get host cpu so path from PluginManager::GetPath: %s", lib_path.c_str());
  234. return SUCCESS;
  235. }
  236. static int RegularFileFilterFn(const mmDirent *entry) {
  237. return entry->d_type == DT_REG;
  238. }
  239. Status HostCpuEngine::ListSoFiles(const std::string &base_dir, std::vector<std::string> &names) {
  240. std::string real_path = base_dir;
  241. GE_CHK_STATUS_RET_NOLOG(GetRealPath(real_path));
  242. real_path.push_back('/');
  243. mmDirent **entries = nullptr;
  244. auto ret = mmScandir(real_path.c_str(), &entries, RegularFileFilterFn, nullptr);
  245. if (ret < 0) {
  246. GELOGW("scan dir failed. path = %s, ret = %d", real_path.c_str(), ret);
  247. return INTERNAL_ERROR;
  248. }
  249. for (int i = 0; i < ret; ++i) {
  250. mmDirent *dir_ent = entries[i];
  251. string name = string(dir_ent->d_name);
  252. if (IsSoFile(name)) {
  253. names.emplace_back(real_path + name);
  254. }
  255. }
  256. mmScandirFree(entries, ret);
  257. GELOGI("Found %d libs to load", ret);
  258. return SUCCESS;
  259. }
  260. bool HostCpuEngine::IsSoFile(const std::string &file_name) {
  261. static const std::string so_suffix(".so");
  262. auto pos = file_name.rfind(so_suffix);
  263. if (pos == string::npos) {
  264. return false;
  265. }
  266. return pos == file_name.size() - so_suffix.size();
  267. }
  268. Status HostCpuEngine::LoadLibs(std::vector<std::string> &lib_paths) {
  269. for (auto &so_path : lib_paths) {
  270. GE_CHK_STATUS_RET_NOLOG(GetRealPath(so_path));
  271. GE_CHK_STATUS_RET_NOLOG(LoadLib(so_path));
  272. }
  273. return SUCCESS;
  274. }
  275. Status HostCpuEngine::LoadLib(const std::string &lib_path) {
  276. GELOGI("To invoke dlopen on lib: %s", lib_path.c_str());
  277. auto handle = mmDlopen(lib_path.c_str(), MMPA_RTLD_NOW | MMPA_RTLD_GLOBAL);
  278. if (handle == nullptr) {
  279. GELOGE(INTERNAL_ERROR, "Failed to invoke dlopen. path = %s, error = %s", lib_path.c_str(), mmDlerror());
  280. return INTERNAL_ERROR;
  281. }
  282. auto initialize = (Status (*)(const HostCpuContext &))mmDlsym(handle, "Initialize");
  283. if (initialize != nullptr) {
  284. GELOGI("Invoke function Initialize in lib: %s", lib_path.c_str());
  285. if (initialize(HostCpuContext()) != SUCCESS) {
  286. GELOGW("Failed to invoke function Initialize in lib: %s", lib_path.c_str());
  287. }
  288. }
  289. GELOGI("Lib: %s has been opened", lib_path.c_str());
  290. lib_handles_.emplace_back(handle);
  291. return SUCCESS;
  292. }
  293. Status HostCpuEngine::GetRealPath(std::string &path) {
  294. std::string real_path = RealPath(path.c_str());
  295. if (real_path.empty()) {
  296. GELOGW("File path %s is invalid.", path.c_str());
  297. return INTERNAL_ERROR;
  298. }
  299. path = real_path;
  300. return SUCCESS;
  301. }
  302. } // namespace ge

图引擎模块(GE)是MindSpore的一个子模块,其代码由C++实现,位于前端模块ME和底层硬件之间,起到承接作用。图引擎模块以ME下发的图作为输入,然后进行一系列的深度图优化操作,最后输出一张可以在底层硬件上高效运行的图。GE针对昇腾AI处理器的硬件结构特点,做了特定的优化工作,以此来充分发挥出昇腾AI处理器的强大算力。在进行模型训练/推理时,GE会被自动调用而用户并不感知。GE主要由GE API和GE Core两部分组成,详细的架构图如下所示