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

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