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

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

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