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.

common_utils.cc 44 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124
  1. /**
  2. * Copyright 2019 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 "backend/kernel_compiler/common_utils.h"
  17. #include <unordered_map>
  18. #include <map>
  19. #include <iostream>
  20. #include <utility>
  21. #include <fstream>
  22. #include <algorithm>
  23. #include <thread>
  24. #include "nlohmann/json.hpp"
  25. #include "backend/session/anf_runtime_algorithm.h"
  26. #include "common/utils.h"
  27. #include "ir/manager.h"
  28. #include "ir/meta_tensor.h"
  29. #include "ir/func_graph.h"
  30. #include "frontend/operator/ops.h"
  31. #include "ir/graph_utils.h"
  32. namespace mindspore {
  33. namespace kernel {
  34. constexpr char kAxis[] = "axis";
  35. constexpr char kTypeInt32[] = "Int32";
  36. const std::unordered_map<std::string, TypeId> type_id_maps = {
  37. {"float", TypeId::kNumberTypeFloat32}, {"float16", TypeId::kNumberTypeFloat16},
  38. {"float32", TypeId::kNumberTypeFloat32}, {"float64", TypeId::kNumberTypeFloat64},
  39. {"int", TypeId::kNumberTypeInt}, {"int8", TypeId::kNumberTypeInt8},
  40. {"int16", TypeId::kNumberTypeInt16}, {"int32", TypeId::kNumberTypeInt32},
  41. {"int64", TypeId::kNumberTypeInt64}, {"uint", TypeId::kNumberTypeUInt},
  42. {"uint8", TypeId::kNumberTypeUInt8}, {"uint16", TypeId::kNumberTypeUInt16},
  43. {"uint32", TypeId::kNumberTypeUInt32}, {"uint64", TypeId::kNumberTypeUInt64},
  44. {"bool", TypeId::kNumberTypeBool},
  45. };
  46. const std::map<TypeId, std::string> type_id_str_map = {
  47. {TypeId::kNumberTypeFloat32, "float32"}, {TypeId::kNumberTypeFloat16, "float16"},
  48. {TypeId::kNumberTypeFloat, "float"}, {TypeId::kNumberTypeFloat64, "float64"},
  49. {TypeId::kNumberTypeInt, "int"}, {TypeId::kNumberTypeInt8, "int8"},
  50. {TypeId::kNumberTypeInt16, "int16"}, {TypeId::kNumberTypeInt32, "int32"},
  51. {TypeId::kNumberTypeInt64, "int64"}, {TypeId::kNumberTypeUInt, "uint"},
  52. {TypeId::kNumberTypeUInt8, "uint8"}, {TypeId::kNumberTypeUInt16, "uint16"},
  53. {TypeId::kNumberTypeUInt32, "uint32"}, {TypeId::kNumberTypeUInt64, "uint64"},
  54. {TypeId::kNumberTypeBool, "bool"},
  55. };
  56. const std::unordered_map<std::string, std::string> dtype_shortdtype_map_ = {
  57. {"float16", "f16"}, {"float32", "f32"}, {"float64", "f64"}, {"int8", "i8"}, {"int16", "i16"}, {"int32", "i32"},
  58. {"int64", "i64"}, {"uint8", "u8"}, {"uint16", "u16"}, {"uint32", "u32"}, {"uint64", "u64"}, {"bool", "bool"},
  59. };
  60. const std::unordered_map<std::string, size_t> dtype_nbyte_map = {
  61. {"float16", sizeof(float) / 2}, {"float32", sizeof(float)}, {"float64", sizeof(float) * 2},
  62. {"int8", sizeof(int) / 4}, {"int16", sizeof(int) / 2}, {"int32", sizeof(int)},
  63. {"int64", sizeof(int) * 2}, {"uint8", sizeof(int) / 4}, {"uint16", sizeof(int) / 2},
  64. {"uint32", sizeof(int)}, {"uint64", sizeof(int) * 2}, {"bool", sizeof(char)},
  65. };
  66. const std::unordered_map<std::string, FusionType> fusion_type_maps = {
  67. {"CONVLUTION", FusionType::CONVLUTION}, {"ELEMWISE", FusionType::ELEMWISE}, {"COMMREDUCE", FusionType::COMMREDUCE},
  68. {"SEGMENT", FusionType::SEGMENT}, {"OPAQUE", FusionType::OPAQUE},
  69. };
  70. void KernelMeta::Initialize() {
  71. kernel_meta_path_ = std::string(kGpuKernelMeta) + "_" + std::to_string(getpid()) + "/";
  72. // remove old kernel cache
  73. RemoveKernelCache();
  74. #if defined(_WIN32) || defined(_WIN64)
  75. auto ret = mkdir(kernel_meta_path_.c_str());
  76. #else
  77. auto ret = mkdir(kernel_meta_path_.c_str(), S_IRWXG | S_IRWXU);
  78. #endif
  79. if (ret != 0) {
  80. MS_LOG(INFO) << "kernel dir [" << kernel_meta_path_ << "], will be created later";
  81. }
  82. initialized_ = true;
  83. }
  84. void KernelMeta::RemoveKernelCache() {
  85. DIR *dir = opendir(kernel_meta_path_.c_str());
  86. if (dir == nullptr) {
  87. return;
  88. }
  89. struct dirent *entry;
  90. while ((entry = readdir(dir)) != nullptr) {
  91. std::string kernel_file = entry->d_name;
  92. std::string kernel_file_realpath = kernel_meta_path_ + kernel_file;
  93. (void)remove(kernel_file_realpath.c_str());
  94. }
  95. (void)closedir(dir);
  96. (void)rmdir(kernel_meta_path_.c_str());
  97. }
  98. std::string KernelMeta::Search(const std::string &kernel_name) const {
  99. if (!initialized_) {
  100. return "";
  101. }
  102. auto iter = kernel_meta_map_.find(kernel_name);
  103. if (iter == kernel_meta_map_.end()) {
  104. return "";
  105. } else {
  106. return iter->second;
  107. }
  108. }
  109. bool KernelMeta::Insert(const std::string &kernel_name, const std::string &kernel_json) {
  110. if (!initialized_) {
  111. return false;
  112. }
  113. kernel_meta_map_[kernel_name] = kernel_json;
  114. return true;
  115. }
  116. bool CheckCache(const std::string &kernel_name) {
  117. // check cache.
  118. KernelMeta *bin_map = KernelMeta::GetInstance();
  119. if (bin_map == nullptr) {
  120. MS_LOG(DEBUG) << "kernel cache is invalid.";
  121. return false;
  122. }
  123. std::string kernel_json = bin_map->Search(kernel_name);
  124. bool ret = (!kernel_json.empty());
  125. if (ret) {
  126. MS_LOG(INFO) << "Kernel name:" << kernel_name << " has registed.";
  127. } else {
  128. MS_LOG(INFO) << "Kernel name:" << kernel_name << " will been registed.";
  129. }
  130. return ret;
  131. }
  132. KernelPackPtr SearchCache(const std::string &kernel_name, const std::string &processor) {
  133. // search cache.
  134. KernelMeta *bin_map = KernelMeta::GetInstance();
  135. if (bin_map == nullptr) {
  136. MS_LOG(DEBUG) << "kernel cache is invalid.";
  137. return nullptr;
  138. }
  139. std::string kernel_json = bin_map->Search(kernel_name);
  140. if (!kernel_json.empty()) {
  141. KernelPackPtr kernel_pack = std::make_shared<KernelPack>();
  142. // just a tmp solution.
  143. if (!kernel_pack->ReadFromJsonFile(kernel_json, processor)) {
  144. MS_LOG(DEBUG) << "Read cache json and bin file failed[" << kernel_json << "].";
  145. return nullptr;
  146. } else {
  147. return kernel_pack;
  148. }
  149. } else {
  150. MS_LOG(INFO) << "cache kernel not found[" << kernel_name << "].";
  151. return nullptr;
  152. }
  153. }
  154. KernelPackPtr InsertCache(const std::string &kernel_name, const std::string &processor) {
  155. MS_LOG(INFO) << "kernel name:" << kernel_name << ", processr:" << processor;
  156. KernelMeta *bin_map = KernelMeta::GetInstance();
  157. std::string kernel_json;
  158. if (processor == kProcessorAiCore || processor == kProcessorAiCpu) {
  159. kernel_json = kCceKernelMeta;
  160. } else {
  161. kernel_json = bin_map->GetKernelMetaPath();
  162. }
  163. (void)kernel_json.append(kernel_name).append(kJsonSuffix);
  164. KernelPackPtr kernel_pack = std::make_shared<KernelPack>();
  165. if (!kernel_pack->ReadFromJsonFile(kernel_json, processor)) {
  166. MS_LOG(DEBUG) << "Read json and bin file failed[" << kernel_json << "].";
  167. return nullptr;
  168. }
  169. if (bin_map == nullptr) {
  170. MS_LOG(DEBUG) << "kernel cache is invalid.";
  171. return nullptr;
  172. }
  173. if (bin_map->Insert(kernel_name, kernel_json)) {
  174. MS_LOG(INFO) << "Insert to cache success[" << kernel_json << "], kernelname[" << kernel_name << "].";
  175. }
  176. return kernel_pack;
  177. }
  178. TypeId DtypeToTypeId(const std::string &dtypes) {
  179. auto iter = type_id_maps.find(dtypes);
  180. if (iter != type_id_maps.end()) {
  181. return iter->second;
  182. } else {
  183. MS_EXCEPTION(ArgumentError) << "Illegal input device dtype:" << dtypes;
  184. }
  185. }
  186. std::string TypeId2String(TypeId type_id) {
  187. auto iter = type_id_str_map.find(type_id);
  188. if (iter == type_id_str_map.end()) {
  189. return std::string(TypeIdLabel(type_id));
  190. }
  191. return iter->second;
  192. }
  193. std::string Dtype2ShortType(const std::string &dtypes) {
  194. auto iter = dtype_shortdtype_map_.find(dtypes);
  195. if (iter != dtype_shortdtype_map_.end()) {
  196. return iter->second;
  197. } else {
  198. MS_EXCEPTION(ArgumentError) << "Illegal input dtype:" << dtypes;
  199. }
  200. }
  201. size_t GetDtypeNbyte(const std::string &dtypes) {
  202. auto iter = dtype_nbyte_map.find(dtypes);
  203. if (iter != dtype_nbyte_map.end()) {
  204. return iter->second;
  205. } else {
  206. MS_EXCEPTION(ArgumentError) << "Illegal input dtype:" << dtypes;
  207. }
  208. }
  209. bool SetInputKernelBuilderInfo(const std::vector<std::shared_ptr<OpIOInfo>> &inputs, size_t real_input_num,
  210. size_t builder_idex, const std::vector<int> &dyn_input_sizes,
  211. const std::shared_ptr<KernelBuildInfo::KernelBuildInfoBuilder> &builder) {
  212. MS_EXCEPTION_IF_NULL(builder);
  213. std::vector<TypeId> inputs_device_type;
  214. std::vector<std::string> inputs_format;
  215. size_t dyn_input_idx = 0;
  216. size_t kernel_info_index = 0;
  217. MS_EXCEPTION_IF_NULL(inputs[0]);
  218. size_t kernel_info_cnt = inputs[0]->dtypes().size();
  219. for (const auto &input : inputs) {
  220. MS_EXCEPTION_IF_NULL(input);
  221. std::string param_type = input->param_type();
  222. std::vector<std::string> dtypes = input->dtypes();
  223. std::vector<std::string> formats = input->formats();
  224. if (dtypes.size() != kernel_info_cnt || formats.size() != kernel_info_cnt) {
  225. MS_LOG(DEBUG) << "Set input kernel builder info, dtyps size != formats size.";
  226. return false;
  227. }
  228. if (param_type == "dynamic") {
  229. if (dyn_input_sizes.empty()) {
  230. MS_LOG(DEBUG) << "Set input kernel builder info, dyn_input_sizes's size is 0 when param_type is dynamic";
  231. return false;
  232. }
  233. for (int t = 0; t < dyn_input_sizes[dyn_input_idx]; t++) {
  234. kernel_info_index++;
  235. auto type_id = DtypeToTypeId(dtypes[builder_idex]);
  236. inputs_device_type.push_back(type_id);
  237. inputs_format.push_back(formats[builder_idex]);
  238. }
  239. dyn_input_idx++;
  240. } else if (param_type == "required") {
  241. kernel_info_index++;
  242. auto type_id = DtypeToTypeId(dtypes[builder_idex]);
  243. inputs_device_type.push_back(type_id);
  244. inputs_format.push_back(formats[builder_idex]);
  245. } else {
  246. if (kernel_info_index < real_input_num) {
  247. MS_LOG(INFO) << "Set input kernel builder info, input type is optional, input index is :" << kernel_info_index;
  248. kernel_info_index++;
  249. auto type_id = DtypeToTypeId(dtypes[builder_idex]);
  250. inputs_device_type.push_back(type_id);
  251. inputs_format.push_back(formats[builder_idex]);
  252. }
  253. }
  254. }
  255. builder->SetInputsDeviceType(inputs_device_type);
  256. builder->SetInputsFormat(inputs_format);
  257. return true;
  258. }
  259. bool SetOutputKernelBuilderInfo(const std::vector<std::shared_ptr<OpIOInfo>> &outputs, size_t builder_idex,
  260. const size_t &real_output_num,
  261. const std::shared_ptr<KernelBuildInfo::KernelBuildInfoBuilder> &builder) {
  262. // not now but in the next we need to support dynamic output case
  263. MS_EXCEPTION_IF_NULL(builder);
  264. size_t output_idx = 0;
  265. std::vector<TypeId> outputs_device_type;
  266. std::vector<std::string> outputs_format;
  267. MS_EXCEPTION_IF_NULL(outputs[0]);
  268. size_t kernel_info_cnt = outputs[0]->dtypes().size();
  269. for (const auto &output : outputs) {
  270. MS_EXCEPTION_IF_NULL(output);
  271. if (output_idx >= real_output_num) {
  272. MS_LOG(DEBUG) << "real_output_num:" << real_output_num << ", output_idx:" << output_idx << " is out of limit!";
  273. continue;
  274. }
  275. size_t output_num = 0;
  276. if (output->param_type() == "dynamic") {
  277. if (outputs.size() > 1) {
  278. MS_EXCEPTION(ArgumentError) << "Dynamic output is unsupported multi output!";
  279. }
  280. output_num = real_output_num;
  281. } else if (output->param_type() == "required") {
  282. output_num = 1;
  283. } else {
  284. if (output_idx < real_output_num) {
  285. MS_LOG(DEBUG) << "Set output kernel builder info, output type is optional, output index is :" << output_idx;
  286. output_num = 1;
  287. }
  288. }
  289. for (size_t i = 0; i < output_num; i++) {
  290. std::vector<std::string> dtypes = output->dtypes();
  291. std::vector<std::string> formats = output->formats();
  292. if (dtypes.size() != kernel_info_cnt || formats.size() != kernel_info_cnt) {
  293. MS_LOG(DEBUG) << "Set output kernel builder info, dtyps size != formats size.";
  294. return false;
  295. }
  296. auto type_id = DtypeToTypeId(dtypes[builder_idex]);
  297. outputs_device_type.push_back(type_id);
  298. outputs_format.push_back(formats[builder_idex]);
  299. output_idx++;
  300. }
  301. }
  302. builder->SetOutputsFormat(outputs_format);
  303. builder->SetOutputsDeviceType(outputs_device_type);
  304. return true;
  305. }
  306. void SetKernelBuildInfo(const std::shared_ptr<KernelBuildInfo::KernelBuildInfoBuilder> &builder, Processor processor,
  307. const std::shared_ptr<const OpInfo> &op_info_ptr) {
  308. MS_EXCEPTION_IF_NULL(builder);
  309. MS_EXCEPTION_IF_NULL(op_info_ptr);
  310. auto imply_type = op_info_ptr->imply_type();
  311. builder->SetProcessor(processor);
  312. std::string fusion_type = op_info_ptr->fusion_type();
  313. auto iter = fusion_type_maps.find(fusion_type);
  314. if (iter != fusion_type_maps.end()) {
  315. builder->SetFusionType(iter->second);
  316. } else {
  317. if (imply_type == kAKG) {
  318. MS_EXCEPTION(NotExistsError) << "Illegal fusion type from dsl register:" << fusion_type;
  319. }
  320. }
  321. if (imply_type == kAKG) {
  322. builder->SetKernelType(AKG_KERNEL);
  323. } else if (imply_type == kAICPU) {
  324. builder->SetKernelType(AICPU_KERNEL);
  325. } else {
  326. builder->SetKernelType(TBE_KERNEL);
  327. }
  328. }
  329. bool ParseMetadata(const CNodePtr &kernel_node, const std::shared_ptr<const OpInfo> &op_info_ptr, Processor processor,
  330. std::vector<std::shared_ptr<KernelBuildInfo>> *const kernel_info_list) {
  331. MS_EXCEPTION_IF_NULL(kernel_node);
  332. MS_EXCEPTION_IF_NULL(kernel_info_list);
  333. size_t real_input_num = AnfAlgo::GetInputTensorNum(kernel_node);
  334. size_t real_output_num = AnfAlgo::GetOutputTensorNum(kernel_node);
  335. std::vector<std::shared_ptr<OpIOInfo>> inputs = op_info_ptr->inputs_ptr();
  336. std::vector<std::shared_ptr<OpIOInfo>> outputs = op_info_ptr->outputs_ptr();
  337. std::vector<int> dyn_input_sizes;
  338. auto primitive = AnfAlgo::GetCNodePrimitive(kernel_node);
  339. MS_EXCEPTION_IF_NULL(primitive);
  340. if (primitive->GetAttr("dyn_input_sizes") != nullptr) {
  341. dyn_input_sizes = GetValue<std::vector<int>>(primitive->GetAttr("dyn_input_sizes"));
  342. }
  343. if (inputs.size() > 0) {
  344. MS_EXCEPTION_IF_NULL(inputs[0]);
  345. size_t kernel_info_cnt = inputs[0]->dtypes().size();
  346. for (size_t j = 0; j < kernel_info_cnt; j++) {
  347. auto builder = std::make_shared<KernelBuildInfo::KernelBuildInfoBuilder>();
  348. MS_EXCEPTION_IF_NULL(builder);
  349. SetKernelBuildInfo(builder, processor, op_info_ptr);
  350. if (!SetInputKernelBuilderInfo(inputs, real_input_num, j, dyn_input_sizes, builder)) {
  351. MS_LOG(DEBUG) << "Parse kernel metadata, set inputs kernel builder info failed.";
  352. return false;
  353. }
  354. if (outputs.size() > 0) {
  355. if (!SetOutputKernelBuilderInfo(outputs, j, real_output_num, builder)) {
  356. MS_LOG(DEBUG) << "Parse kernel metadata, set outputs kernel builder info failed.";
  357. return false;
  358. }
  359. }
  360. kernel_info_list->push_back(builder->Build());
  361. }
  362. } else if (outputs.size() > 0) {
  363. MS_EXCEPTION_IF_NULL(outputs[0]);
  364. size_t kernel_info_cnt = outputs[0]->dtypes().size();
  365. for (size_t j = 0; j < kernel_info_cnt; j++) {
  366. auto builder = std::make_shared<KernelBuildInfo::KernelBuildInfoBuilder>();
  367. MS_EXCEPTION_IF_NULL(builder);
  368. SetKernelBuildInfo(builder, processor, op_info_ptr);
  369. if (!SetOutputKernelBuilderInfo(outputs, j, real_output_num, builder)) {
  370. MS_LOG(DEBUG) << "Parse kernel metadata, set outputs kernel builder info failed.";
  371. return false;
  372. }
  373. kernel_info_list->push_back(builder->Build());
  374. }
  375. } else {
  376. if (processor == AICPU) {
  377. auto builder = std::make_shared<KernelBuildInfo::KernelBuildInfoBuilder>();
  378. MS_EXCEPTION_IF_NULL(builder);
  379. SetKernelBuildInfo(builder, processor, op_info_ptr);
  380. kernel_info_list->push_back(builder->Build());
  381. }
  382. }
  383. return true;
  384. }
  385. void SaveJsonInfo(const std::string &json_name, const std::string &info) {
  386. char real_path[PATH_MAX] = {0};
  387. std::string path = kCceKernelMeta + json_name + kInfoSuffix;
  388. if (path.size() > PATH_MAX) {
  389. MS_LOG(DEBUG) << "file path " << path << " is too long.";
  390. return;
  391. }
  392. std::ofstream filewrite;
  393. filewrite.open(path);
  394. if (!filewrite.is_open()) {
  395. return;
  396. }
  397. filewrite << info << std::endl;
  398. filewrite.close();
  399. #if defined(_WIN32) || defined(_WIN64)
  400. if (nullptr == _fullpath(real_path, path.c_str(), PATH_MAX)) {
  401. MS_LOG(DEBUG) << "dir " << path << " does not exit.";
  402. return;
  403. }
  404. #else
  405. if (nullptr == realpath(path.c_str(), real_path)) {
  406. MS_LOG(DEBUG) << "dir " << path << " does not exit.";
  407. return;
  408. }
  409. #endif
  410. MS_LOG(INFO) << "real path is :" << real_path;
  411. if (chmod(real_path, S_IRUSR) == -1) {
  412. MS_LOG(DEBUG) << "modify file:" << real_path << " to read only fail.";
  413. }
  414. }
  415. std::string GetProcessor(const AnfNodePtr &anf_node) {
  416. MS_EXCEPTION_IF_NULL(anf_node);
  417. std::string device;
  418. switch (AnfAlgo::GetProcessor(anf_node)) {
  419. case Processor::AICORE:
  420. device = kProcessorAiCore;
  421. break;
  422. case Processor::AICPU:
  423. device = kProcessorAiCpu;
  424. break;
  425. case Processor::CUDA:
  426. device = kProcessorCuda;
  427. break;
  428. default:
  429. MS_LOG(DEBUG) << "Unknown processor type.";
  430. break;
  431. }
  432. return device;
  433. }
  434. bool IsSameShape(const std::vector<size_t> &shape_a, const std::vector<size_t> &shape_b) {
  435. if (shape_a.size() != shape_b.size()) {
  436. return false;
  437. }
  438. for (size_t i = 0; i < shape_a.size(); ++i) {
  439. if (shape_a[i] != shape_b[i]) {
  440. return false;
  441. }
  442. }
  443. return true;
  444. }
  445. int Sign(float x) {
  446. if (x > 0) {
  447. return 1;
  448. }
  449. if (x < 0) {
  450. return -1;
  451. }
  452. return 0;
  453. }
  454. namespace {
  455. struct BucketSparseGradient {
  456. float *value_;
  457. int *indices_;
  458. int *global_indices_;
  459. size_t indices_size_;
  460. };
  461. struct MultiThreadReduceSparseGradientParam {
  462. SparseGradient *input_grad_{nullptr};
  463. SparseGradient *workspace_grad_{nullptr};
  464. SparseGradient *output_grad_{nullptr};
  465. size_t max_index_{0};
  466. size_t value_stride_{0};
  467. size_t thread_num_{0};
  468. bool use_sort_reduce_{false};
  469. };
  470. void CalculateEachBucketSize(const std::shared_ptr<SparseGradient> &sparse_grad, size_t max_index,
  471. std::vector<size_t> *each_bucket_size) {
  472. MS_LOG(DEBUG) << "Start";
  473. MS_EXCEPTION_IF_NULL(sparse_grad);
  474. MS_EXCEPTION_IF_NULL(sparse_grad->indices_);
  475. MS_EXCEPTION_IF_NULL(each_bucket_size);
  476. size_t bucket_num = each_bucket_size->size();
  477. for (size_t i = 0; i < sparse_grad->indices_size_; ++i) {
  478. int index = sparse_grad->indices_[i];
  479. if (index >= 0 && IntToSize(index) < max_index) {
  480. auto bucket_id = index % bucket_num;
  481. each_bucket_size->at(bucket_id)++;
  482. }
  483. }
  484. MS_LOG(DEBUG) << "End";
  485. }
  486. void SplitAndCalculateSegmentBucketSize(const MultiThreadReduceSparseGradientParam &param,
  487. std::vector<std::shared_ptr<SparseGradient>> *segments_ptr,
  488. std::vector<std::shared_ptr<std::vector<size_t>>> *segment_bucket_sizes_ptr) {
  489. MS_EXCEPTION_IF_NULL(param.input_grad_);
  490. MS_EXCEPTION_IF_NULL(segment_bucket_sizes_ptr);
  491. MS_EXCEPTION_IF_NULL(segments_ptr);
  492. auto &segments = *segments_ptr;
  493. auto &segment_bucket_sizes = *segment_bucket_sizes_ptr;
  494. auto input_grad = param.input_grad_;
  495. if (param.thread_num_ < 1) {
  496. MS_EXCEPTION(ArgumentError) << "Input param thread num must > 0!";
  497. }
  498. size_t thread_indices_size = input_grad->indices_size_ / param.thread_num_;
  499. size_t left_indices_size = input_grad->indices_size_ % param.thread_num_;
  500. std::vector<std::thread> threads;
  501. threads.reserve(param.thread_num_);
  502. segments.reserve(param.thread_num_);
  503. size_t current_indices_offset = 0;
  504. for (size_t i = 0; i < param.thread_num_; ++i) {
  505. segment_bucket_sizes.emplace_back(std::make_shared<std::vector<size_t>>(param.thread_num_, 0));
  506. size_t indices_size = thread_indices_size;
  507. if (i < left_indices_size) {
  508. indices_size += 1;
  509. }
  510. segments.emplace_back(std::make_shared<SparseGradient>());
  511. segments[i]->value_ = input_grad->value_ + current_indices_offset * param.value_stride_;
  512. segments[i]->indices_ = input_grad->indices_ + current_indices_offset;
  513. segments[i]->indices_size_ = indices_size;
  514. threads.emplace_back(
  515. std::thread(CalculateEachBucketSize, segments[i], param.max_index_, segment_bucket_sizes[i].get()));
  516. current_indices_offset += indices_size;
  517. }
  518. for (size_t i = 0; i < param.thread_num_; ++i) {
  519. threads[i].join();
  520. }
  521. }
  522. void CopySegmentIndicesToBucket(const MultiThreadReduceSparseGradientParam &param,
  523. const std::shared_ptr<SparseGradient> &segment, size_t bucket_offset,
  524. const std::vector<std::shared_ptr<BucketSparseGradient>> &buckets) {
  525. MS_LOG(DEBUG) << "Start";
  526. MS_EXCEPTION_IF_NULL(segment);
  527. MS_EXCEPTION_IF_NULL(segment->indices_);
  528. std::vector<size_t> bucket_data_num(param.thread_num_, 0);
  529. for (size_t i = 0; i < segment->indices_size_; ++i) {
  530. int index = segment->indices_[i];
  531. if (index >= 0 && IntToSize(index) < param.max_index_) {
  532. auto bucket_id = index % param.thread_num_;
  533. auto bucket_index = bucket_data_num[bucket_id];
  534. buckets[bucket_id]->indices_[bucket_index] = index;
  535. buckets[bucket_id]->global_indices_[bucket_index] = bucket_offset + i;
  536. bucket_data_num[bucket_id]++;
  537. }
  538. }
  539. MS_LOG(DEBUG) << "End";
  540. }
  541. void GatherSegmentIndicesToOutputBucket(const MultiThreadReduceSparseGradientParam &param,
  542. const std::vector<std::shared_ptr<SparseGradient>> &segments,
  543. const std::vector<std::shared_ptr<std::vector<size_t>>> &segment_bucket_sizes,
  544. std::vector<std::shared_ptr<BucketSparseGradient>> *buckets_ptr) {
  545. MS_EXCEPTION_IF_NULL(param.output_grad_);
  546. MS_EXCEPTION_IF_NULL(param.output_grad_->value_);
  547. MS_EXCEPTION_IF_NULL(param.output_grad_->indices_);
  548. MS_EXCEPTION_IF_NULL(buckets_ptr);
  549. auto &buckets = *buckets_ptr;
  550. size_t thread_num = param.thread_num_;
  551. if (thread_num != segment_bucket_sizes.size()) {
  552. MS_EXCEPTION(ArgumentError) << "Input param thread num not equal to segment size!";
  553. }
  554. std::vector<size_t> bucket_data_size(thread_num, 0);
  555. for (size_t i = 0; i < thread_num; ++i) {
  556. for (size_t j = 0; j < thread_num; ++j) {
  557. bucket_data_size[j] += segment_bucket_sizes[i]->at(j);
  558. }
  559. }
  560. size_t current_indices_offset = 0;
  561. for (size_t i = 0; i < thread_num; ++i) {
  562. buckets.emplace_back(std::make_shared<BucketSparseGradient>());
  563. buckets[i]->value_ = param.output_grad_->value_ + current_indices_offset * param.value_stride_;
  564. buckets[i]->indices_ = param.output_grad_->indices_ + current_indices_offset;
  565. buckets[i]->global_indices_ = param.workspace_grad_->indices_ + current_indices_offset;
  566. buckets[i]->indices_size_ = bucket_data_size[i];
  567. current_indices_offset += bucket_data_size[i];
  568. }
  569. std::vector<size_t> tmp_bucket_data_size(thread_num, 0);
  570. std::vector<std::vector<std::shared_ptr<BucketSparseGradient>>> each_thread_buckets;
  571. for (size_t i = 0; i < thread_num; ++i) {
  572. std::vector<std::shared_ptr<BucketSparseGradient>> thread_buckets;
  573. for (size_t j = 0; j < thread_num; ++j) {
  574. thread_buckets.emplace_back(std::make_shared<BucketSparseGradient>());
  575. thread_buckets[j]->indices_ = buckets[j]->indices_ + tmp_bucket_data_size[j];
  576. thread_buckets[j]->global_indices_ = buckets[j]->global_indices_ + tmp_bucket_data_size[j];
  577. thread_buckets[j]->value_ = buckets[j]->value_ + tmp_bucket_data_size[j] * param.value_stride_;
  578. thread_buckets[j]->indices_size_ = segment_bucket_sizes[i]->at(j);
  579. tmp_bucket_data_size[j] += segment_bucket_sizes[i]->at(j);
  580. }
  581. each_thread_buckets.emplace_back(thread_buckets);
  582. }
  583. std::vector<std::thread> threads;
  584. threads.reserve(thread_num);
  585. current_indices_offset = 0;
  586. for (size_t i = 0; i < thread_num; ++i) {
  587. threads.emplace_back(
  588. std::thread(CopySegmentIndicesToBucket, param, segments[i], current_indices_offset, each_thread_buckets[i]));
  589. current_indices_offset += segments[i]->indices_size_;
  590. }
  591. for (size_t i = 0; i < thread_num; ++i) {
  592. threads[i].join();
  593. }
  594. }
  595. void SortAndReduceBucketSparseGradient(const MultiThreadReduceSparseGradientParam &param,
  596. const std::shared_ptr<BucketSparseGradient> &bucket,
  597. const std::shared_ptr<SparseGradient> &reduced_bucket) {
  598. MS_LOG(DEBUG) << "Start";
  599. MS_EXCEPTION_IF_NULL(bucket);
  600. MS_EXCEPTION_IF_NULL(bucket->value_);
  601. MS_EXCEPTION_IF_NULL(bucket->indices_);
  602. MS_EXCEPTION_IF_NULL(reduced_bucket);
  603. MS_EXCEPTION_IF_NULL(reduced_bucket->value_);
  604. MS_EXCEPTION_IF_NULL(reduced_bucket->indices_);
  605. std::vector<std::pair<int, int>> sorted_indices;
  606. sorted_indices.reserve(bucket->indices_size_);
  607. for (size_t i = 0; i < bucket->indices_size_; ++i) {
  608. int index = bucket->indices_[i];
  609. int global_index = bucket->global_indices_[i];
  610. sorted_indices.emplace_back(std::pair<int, int>(index, global_index));
  611. }
  612. std::sort(sorted_indices.begin(), sorted_indices.end());
  613. float *global_value = param.input_grad_->value_;
  614. size_t unique_indices_size = 0;
  615. size_t max_length = reduced_bucket->indices_size_ * param.value_stride_;
  616. int last_index{0};
  617. size_t value_offset{0};
  618. for (size_t i = 0; i < sorted_indices.size(); ++i) {
  619. int index = sorted_indices[i].first;
  620. int global_index = sorted_indices[i].second;
  621. int global_value_offset = global_index * param.value_stride_;
  622. if (i == 0 || index != last_index) {
  623. if (i != 0) {
  624. unique_indices_size++;
  625. }
  626. reduced_bucket->indices_[unique_indices_size] = index;
  627. value_offset = unique_indices_size * param.value_stride_;
  628. auto ret_code = memcpy_s(reduced_bucket->value_ + value_offset, (max_length - value_offset) * sizeof(float),
  629. global_value + global_value_offset, param.value_stride_ * sizeof(float));
  630. if (ret_code != EOK) {
  631. MS_LOG(EXCEPTION) << "Failed to copy data!";
  632. }
  633. } else {
  634. for (size_t j = 0; j < param.value_stride_; ++j) {
  635. reduced_bucket->value_[value_offset + j] += global_value[global_value_offset + j];
  636. }
  637. }
  638. last_index = index;
  639. }
  640. reduced_bucket->indices_size_ = unique_indices_size;
  641. MS_LOG(DEBUG) << "End";
  642. }
  643. void ReduceBucketSparseGradient(const MultiThreadReduceSparseGradientParam &param,
  644. const std::shared_ptr<BucketSparseGradient> &bucket,
  645. const std::shared_ptr<SparseGradient> &reduced_bucket) {
  646. MS_LOG(DEBUG) << "Start";
  647. MS_EXCEPTION_IF_NULL(bucket);
  648. MS_EXCEPTION_IF_NULL(bucket->value_);
  649. MS_EXCEPTION_IF_NULL(bucket->indices_);
  650. MS_EXCEPTION_IF_NULL(reduced_bucket);
  651. MS_EXCEPTION_IF_NULL(reduced_bucket->value_);
  652. MS_EXCEPTION_IF_NULL(reduced_bucket->indices_);
  653. float *global_value = param.input_grad_->value_;
  654. std::unordered_map<int, size_t> index_map;
  655. size_t unique_indices_size = 0;
  656. size_t max_length = reduced_bucket->indices_size_ * param.value_stride_;
  657. for (size_t i = 0; i < bucket->indices_size_; ++i) {
  658. int index = bucket->indices_[i];
  659. int global_index = bucket->global_indices_[i];
  660. auto iter = index_map.find(index);
  661. if (iter == index_map.end()) {
  662. reduced_bucket->indices_[unique_indices_size] = index;
  663. size_t start_index = unique_indices_size * param.value_stride_;
  664. index_map[index] = start_index;
  665. auto ret_code = memcpy_s(reduced_bucket->value_ + start_index, (max_length - start_index) * sizeof(float),
  666. global_value + global_index * param.value_stride_, param.value_stride_ * sizeof(float));
  667. if (ret_code != EOK) {
  668. MS_LOG(EXCEPTION) << "Failed to copy data!";
  669. }
  670. unique_indices_size++;
  671. } else {
  672. size_t start_index = iter->second;
  673. size_t end_index = start_index + param.value_stride_;
  674. for (size_t j = start_index, k = global_index * param.value_stride_; j < end_index; ++j, ++k) {
  675. reduced_bucket->value_[j] += global_value[k];
  676. }
  677. }
  678. }
  679. reduced_bucket->indices_size_ = unique_indices_size;
  680. MS_LOG(DEBUG) << "End";
  681. }
  682. void ReduceBucketSparseGradientToWorkspace(const MultiThreadReduceSparseGradientParam &param,
  683. const std::vector<std::shared_ptr<BucketSparseGradient>> &buckets,
  684. std::vector<std::shared_ptr<SparseGradient>> *reduced_buckets_ptr) {
  685. MS_EXCEPTION_IF_NULL(param.workspace_grad_);
  686. MS_EXCEPTION_IF_NULL(param.workspace_grad_->value_);
  687. MS_EXCEPTION_IF_NULL(param.workspace_grad_->indices_);
  688. MS_EXCEPTION_IF_NULL(reduced_buckets_ptr);
  689. auto &reduced_buckets = *reduced_buckets_ptr;
  690. size_t thread_num = buckets.size();
  691. std::vector<std::thread> threads;
  692. threads.reserve(thread_num);
  693. size_t current_indices_offset = 0;
  694. for (size_t i = 0; i < thread_num; ++i) {
  695. reduced_buckets.emplace_back(std::make_shared<SparseGradient>());
  696. reduced_buckets[i]->value_ = param.workspace_grad_->value_ + current_indices_offset * param.value_stride_;
  697. reduced_buckets[i]->indices_ = param.workspace_grad_->indices_ + current_indices_offset;
  698. reduced_buckets[i]->indices_size_ = buckets[i]->indices_size_;
  699. if (param.use_sort_reduce_) {
  700. threads.emplace_back(std::thread(SortAndReduceBucketSparseGradient, param, buckets[i], reduced_buckets[i]));
  701. } else {
  702. threads.emplace_back(std::thread(ReduceBucketSparseGradient, param, buckets[i], reduced_buckets[i]));
  703. }
  704. current_indices_offset += buckets[i]->indices_size_;
  705. }
  706. for (size_t i = 0; i < thread_num; ++i) {
  707. threads[i].join();
  708. }
  709. }
  710. void MergeReduceSparseGradient(const MultiThreadReduceSparseGradientParam &param,
  711. const std::vector<std::shared_ptr<SparseGradient>> &reduced_buckets) {
  712. MS_EXCEPTION_IF_NULL(param.output_grad_);
  713. auto output_grad = param.output_grad_;
  714. MS_EXCEPTION_IF_NULL(output_grad->value_);
  715. MS_EXCEPTION_IF_NULL(output_grad->indices_);
  716. size_t stride_data_size = param.value_stride_ * sizeof(float);
  717. size_t unique_indices_size = 0;
  718. for (size_t i = 0; i < reduced_buckets.size(); ++i) {
  719. auto &bucket = reduced_buckets[i];
  720. MS_EXCEPTION_IF_NULL(bucket);
  721. if (bucket->indices_size_ == 0) {
  722. continue;
  723. }
  724. auto ret_code = memcpy_s(output_grad->value_ + unique_indices_size * param.value_stride_,
  725. (output_grad->indices_size_ - unique_indices_size) * stride_data_size, bucket->value_,
  726. bucket->indices_size_ * stride_data_size);
  727. if (ret_code != EOK) {
  728. MS_LOG(EXCEPTION) << "Failed to copy data!";
  729. }
  730. ret_code = memcpy_s(output_grad->indices_ + unique_indices_size,
  731. (output_grad->indices_size_ - unique_indices_size) * sizeof(int), bucket->indices_,
  732. bucket->indices_size_ * sizeof(int));
  733. if (ret_code != EOK) {
  734. MS_LOG(EXCEPTION) << "Failed to copy data!";
  735. }
  736. unique_indices_size += bucket->indices_size_;
  737. }
  738. output_grad->indices_size_ = unique_indices_size;
  739. }
  740. } // namespace
  741. void BucketReduceSparseGradient(const ReduceSparseGradientParam &param) {
  742. MS_LOG(DEBUG) << "Start";
  743. MS_EXCEPTION_IF_NULL(param.input_grad_);
  744. size_t thread_num = 23;
  745. if (param.input_grad_->indices_size_ < thread_num) {
  746. thread_num = param.input_grad_->indices_size_;
  747. }
  748. MultiThreadReduceSparseGradientParam multi_thread_param({param.input_grad_, param.workspace_grad_, param.output_grad_,
  749. param.max_index_, param.value_stride_, thread_num,
  750. param.use_sort_reduce_});
  751. std::vector<std::shared_ptr<SparseGradient>> segments;
  752. std::vector<std::shared_ptr<std::vector<size_t>>> segment_bucket_sizes;
  753. SplitAndCalculateSegmentBucketSize(multi_thread_param, &segments, &segment_bucket_sizes);
  754. std::vector<std::shared_ptr<BucketSparseGradient>> buckets;
  755. GatherSegmentIndicesToOutputBucket(multi_thread_param, segments, segment_bucket_sizes, &buckets);
  756. std::vector<std::shared_ptr<SparseGradient>> reduced_buckets;
  757. ReduceBucketSparseGradientToWorkspace(multi_thread_param, buckets, &reduced_buckets);
  758. MergeReduceSparseGradient(multi_thread_param, reduced_buckets);
  759. MS_LOG(DEBUG) << "End";
  760. }
  761. std::pair<AnfNodePtr, size_t> GetKernelInput(const AnfNodePtr &anf_node, size_t index) {
  762. MS_EXCEPTION_IF_NULL(anf_node);
  763. if (index >= AnfAlgo::GetInputTensorNum(anf_node)) {
  764. MS_EXCEPTION(ArgumentError) << "Index is out of the size of anf_node inputs.";
  765. }
  766. auto cnode = anf_node->cast<CNodePtr>();
  767. if (cnode == nullptr) {
  768. return AnfAlgo::VisitKernel(anf_node, 0);
  769. } else {
  770. return AnfAlgo::VisitKernel(anf_node->cast<CNodePtr>()->input(index + 1), 0);
  771. }
  772. }
  773. std::vector<std::pair<AnfNodePtr, std::pair<size_t, size_t>>> GetInputIndex(const std::vector<AnfNodePtr> &node_list,
  774. const std::vector<AnfNodePtr> &input_list) {
  775. std::vector<std::pair<AnfNodePtr, std::pair<size_t, size_t>>> input_index;
  776. for (size_t i = 0; i < input_list.size(); ++i) {
  777. auto const &input = input_list[i];
  778. MS_EXCEPTION_IF_NULL(input);
  779. bool found = false;
  780. // using NodeUsersMap = std::unordered_map<AnfNodePtr, std::set<std::pair<AnfNodePtr, int>>>;
  781. auto mng = input->func_graph()->manager();
  782. MS_EXCEPTION_IF_NULL(mng);
  783. const NodeUsersMap &users = mng->node_users();
  784. auto input_users = users.find(input);
  785. if (input_users == users.end() || input_users->second.empty()) {
  786. MS_EXCEPTION(ArgumentError) << "Input [" << i << "][" << input->DebugString(2) << "] of ["
  787. << input->func_graph()->ToString() << "] has no users.";
  788. }
  789. for (auto const &input_user : input_users->second) {
  790. for (auto const &anf_node : node_list) {
  791. if (anf_node != input_user.first) {
  792. continue;
  793. }
  794. std::vector<int> dyn_input_sizes;
  795. auto prim = AnfAlgo::GetCNodePrimitive(anf_node);
  796. MS_EXCEPTION_IF_NULL(prim);
  797. if (prim->GetAttr(kAttrDynInputSizes) != nullptr) {
  798. dyn_input_sizes = GetValue<const std::vector<int>>(prim->GetAttr(kAttrDynInputSizes));
  799. }
  800. if (dyn_input_sizes.empty()) {
  801. input_index.push_back(std::make_pair(anf_node, std::make_pair(IntToSize(input_user.second - 1), 0)));
  802. found = true;
  803. break;
  804. } else {
  805. int used_as_idx = input_user.second - 1;
  806. int accum_idx = 0;
  807. size_t dyn_i = 0;
  808. for (; dyn_i < dyn_input_sizes.size(); ++dyn_i) {
  809. accum_idx += dyn_input_sizes[dyn_i];
  810. if (used_as_idx < accum_idx) {
  811. input_index.push_back(std::make_pair(
  812. anf_node, std::make_pair(dyn_i, IntToSize(used_as_idx - (accum_idx - dyn_input_sizes[dyn_i])))));
  813. break;
  814. }
  815. }
  816. if (dyn_i != dyn_input_sizes.size()) {
  817. found = true;
  818. break;
  819. }
  820. }
  821. }
  822. if (found) {
  823. break;
  824. }
  825. }
  826. if (!found) {
  827. MS_EXCEPTION(ArgumentError) << "Input [" << i << "][" << input->DebugString(2) << "] of ["
  828. << input->func_graph()->ToString() << "] found no related kernel info.";
  829. }
  830. }
  831. return input_index;
  832. }
  833. std::vector<std::pair<AnfNodePtr, size_t>> GetOutputIndex(const std::vector<AnfNodePtr> &node_list,
  834. const std::vector<AnfNodePtr> &input_list,
  835. const std::vector<AnfNodePtr> &output_list) {
  836. std::vector<std::pair<AnfNodePtr, size_t>> output_index;
  837. for (size_t i = 0; i < output_list.size(); ++i) {
  838. auto const &output = output_list[i];
  839. MS_EXCEPTION_IF_NULL(output);
  840. bool found = false;
  841. auto pree_node = AnfAlgo::VisitKernel(output, 0);
  842. auto pos = std::find(std::begin(node_list), std::end(node_list), pree_node.first);
  843. if (pos != std::end(node_list)) {
  844. output_index.push_back(pree_node);
  845. continue;
  846. }
  847. auto ret = std::find(std::begin(input_list), std::end(input_list), pree_node.first);
  848. if (ret != std::end(input_list)) {
  849. output_index.push_back(std::make_pair(pree_node.first, 0));
  850. found = true;
  851. }
  852. if (!found) {
  853. MS_EXCEPTION(ArgumentError) << "Output [" << i << "][" << output->DebugString(2) << "] of ["
  854. << output->func_graph()->ToString() << "] found no related kernel info.";
  855. }
  856. }
  857. return output_index;
  858. }
  859. void GetValidKernelNodes(const FuncGraphPtr &func_graph, std::vector<AnfNodePtr> *node_list) {
  860. MS_EXCEPTION_IF_NULL(node_list);
  861. MS_EXCEPTION_IF_NULL(func_graph);
  862. std::vector<AnfNodePtr> node_lists = TopoSort(func_graph->get_return());
  863. for (auto const &node : node_lists) {
  864. if (!AnfAlgo::IsRealKernel(node) || !node->isa<CNode>()) {
  865. continue;
  866. }
  867. auto cnode = node->cast<CNodePtr>();
  868. MS_EXCEPTION_IF_NULL(cnode);
  869. if (IsValueNode<Primitive>(cnode->input(kAnfPrimitiveIndex))) {
  870. node_list->push_back(node);
  871. }
  872. }
  873. }
  874. void GetValidKernelNodes(const FuncGraphPtr &func_graph, std::vector<AnfNodePtr> *node_list,
  875. std::vector<AnfNodePtr> *input_list, std::vector<AnfNodePtr> *output_list) {
  876. MS_EXCEPTION_IF_NULL(node_list);
  877. MS_EXCEPTION_IF_NULL(input_list);
  878. MS_EXCEPTION_IF_NULL(output_list);
  879. MS_EXCEPTION_IF_NULL(func_graph);
  880. GetValidKernelNodes(func_graph, node_list);
  881. auto parameters = func_graph->parameters();
  882. input_list->insert(input_list->begin(), parameters.begin(), parameters.end());
  883. auto func_output = func_graph->output();
  884. MS_EXCEPTION_IF_NULL(func_output);
  885. if (func_output->isa<CNode>()) {
  886. // multi output.
  887. auto cnode = func_output->cast<CNodePtr>();
  888. MS_EXCEPTION_IF_NULL(cnode);
  889. auto input0 = cnode->input(kAnfPrimitiveIndex);
  890. MS_EXCEPTION_IF_NULL(input0);
  891. if (IsPrimitive(input0, prim::kPrimMakeTuple)) {
  892. for (size_t input_idx = 1; input_idx < cnode->inputs().size(); ++input_idx) {
  893. auto input_node = cnode->input(input_idx);
  894. MS_EXCEPTION_IF_NULL(input_node);
  895. output_list->push_back(AnfAlgo::VisitKernel(input_node, 0).first);
  896. }
  897. } else {
  898. // single output.
  899. output_list->push_back(AnfAlgo::VisitKernel(func_output, 0).first);
  900. }
  901. } else {
  902. // single output.
  903. output_list->push_back(AnfAlgo::VisitKernel(func_output, 0).first);
  904. }
  905. }
  906. bool GetInputTensorValue(const AnfNodePtr &anf_node, size_t input_idx, nlohmann::json *const node_json) {
  907. MS_EXCEPTION_IF_NULL(anf_node);
  908. MS_EXCEPTION_IF_NULL(node_json);
  909. auto cnode = anf_node->cast<CNodePtr>();
  910. MS_EXCEPTION_IF_NULL(cnode);
  911. if (input_idx + 1 >= cnode->size()) {
  912. MS_EXCEPTION(ArgumentError) << "input_idx [" << input_idx << "] is out of index of inputs of ["
  913. << cnode->inputs().size() << "][" << cnode->DebugString() << "]";
  914. }
  915. auto input_node = cnode->input(input_idx + 1);
  916. if (!IsValueNode<tensor::Tensor>(input_node)) {
  917. return false;
  918. }
  919. auto tensor = GetValueNode<tensor::TensorPtr>(input_node);
  920. if (tensor == nullptr) {
  921. return false;
  922. }
  923. auto type_id = tensor->data_type();
  924. auto *data = tensor->data_c();
  925. MS_EXCEPTION_IF_NULL(data);
  926. if (tensor->DataDim() > 1 || tensor->DataSize() != 1) {
  927. // not const tensor.
  928. MS_LOG(WARNING) << "We take first value of tensor whose datasize != 1, [" << input_node->DebugString(2) << "]";
  929. }
  930. if (type_id == kFloat32->type_id()) {
  931. float *val = static_cast<float *>(data);
  932. MS_EXCEPTION_IF_NULL(val);
  933. (*node_json)["value"] = val[0];
  934. MS_LOG(DEBUG) << "Value of tensor[" << cnode->DebugString() << "] is [float32][" << *val << "].";
  935. return true;
  936. } else if (type_id == kFloat16->type_id()) {
  937. float16 *val = static_cast<float16 *>(data);
  938. MS_EXCEPTION_IF_NULL(val);
  939. (*node_json)["value"] = static_cast<float>(val[0]);
  940. MS_LOG(INFO) << "Value of tensor[" << cnode->DebugString() << "] is [float16][" << *val << "].";
  941. return true;
  942. } else if (type_id == kInt32->type_id()) {
  943. int *val = static_cast<int *>(data);
  944. MS_EXCEPTION_IF_NULL(val);
  945. (*node_json)["value"] = val[0];
  946. MS_LOG(INFO) << "Value of tensor[" << cnode->DebugString() << "] is [int32][" << *val << "].";
  947. return true;
  948. }
  949. MS_LOG(ERROR) << "Unknown value type of tensor[" << cnode->DebugString() << "]";
  950. return false;
  951. }
  952. void GetGraphRealOutput(const FuncGraphPtr &func_graph, std::vector<std::pair<AnfNodePtr, size_t>> *node_list) {
  953. MS_EXCEPTION_IF_NULL(func_graph);
  954. MS_EXCEPTION_IF_NULL(node_list);
  955. auto output = func_graph->output();
  956. MS_EXCEPTION_IF_NULL(output);
  957. if (AnfAlgo::IsRealKernel(output)) {
  958. // single output.
  959. node_list->push_back(std::make_pair(output, 0));
  960. return;
  961. } else if (IsPrimitiveCNode(output, prim::kPrimMakeTuple)) {
  962. auto output_cnode = output->cast<CNodePtr>();
  963. MS_EXCEPTION_IF_NULL(output_cnode);
  964. // multi output.
  965. auto &inputs = output_cnode->inputs();
  966. for (size_t i = 1; i < inputs.size(); ++i) {
  967. auto in_with_idx = AnfAlgo::VisitKernel(inputs[i], 0);
  968. node_list->push_back(in_with_idx);
  969. }
  970. return;
  971. }
  972. MS_EXCEPTION(ArgumentError) << "Unknown output type: " << output->DebugString(2)
  973. << " of graph: " << func_graph->ToString();
  974. }
  975. bool IsWeightBoundary(const AnfNodePtr &node) {
  976. if (node->isa<ValueNode>()) {
  977. return true;
  978. }
  979. if (node->isa<Parameter>() && AnfAlgo::IsParameterWeight(node->cast<ParameterPtr>())) {
  980. return true;
  981. }
  982. return false;
  983. }
  984. void MultiThreadCompute(const MultiThreadComputeFunc &func, MultiThreadComputeParams *params,
  985. size_t total_compute_size) {
  986. const size_t kThreadNum = 24;
  987. std::vector<std::thread> threads;
  988. threads.reserve(kThreadNum);
  989. size_t start = 0;
  990. size_t once_compute_size = (total_compute_size + kThreadNum - 1) / kThreadNum;
  991. while (start < total_compute_size) {
  992. size_t end = (start + once_compute_size) > total_compute_size ? total_compute_size : (start + once_compute_size);
  993. threads.emplace_back(std::thread(func, params, start, end));
  994. start += once_compute_size;
  995. }
  996. for (size_t i = 0; i < threads.size(); ++i) {
  997. threads[i].join();
  998. }
  999. }
  1000. std::vector<int> GetReduceAttrAxis(const CNodePtr &cnode) {
  1001. if (AnfAlgo::GetInputTensorNum(cnode) != AnfAlgo::GetOutputTensorNum(cnode) &&
  1002. AnfAlgo::GetInputTensorNum(cnode) != 1) {
  1003. MS_LOG(EXCEPTION) << "the kind of reduce node [" << cnode->DebugString()
  1004. << "] is not single input or single output ";
  1005. }
  1006. std::vector<int> axis;
  1007. auto input_shape = AnfAlgo::GetPrevNodeOutputInferShape(cnode, 0);
  1008. auto primitive = AnfAlgo::GetCNodePrimitive(cnode);
  1009. MS_EXCEPTION_IF_NULL(primitive);
  1010. auto axis_attr = primitive->GetAttr(kAxis);
  1011. if (axis_attr == nullptr) {
  1012. MS_LOG(ERROR) << "This node does't have axie attr.";
  1013. return std::vector<int>();
  1014. }
  1015. auto type = axis_attr->type();
  1016. MS_EXCEPTION_IF_NULL(type);
  1017. std::vector<int> axis_list;
  1018. if (type->ToString() == kTypeInt32) {
  1019. axis_list.emplace_back(GetValue<int>(axis_attr));
  1020. } else {
  1021. axis_list = GetValue<std::vector<int>>(axis_attr);
  1022. }
  1023. for (const auto &elem : axis_list) {
  1024. if (elem < 0) {
  1025. axis.emplace_back(input_shape.size() + elem);
  1026. } else {
  1027. axis.emplace_back(elem);
  1028. }
  1029. }
  1030. AnfAlgo::SetNodeAttr(kAttrAxis, MakeValue(axis), cnode);
  1031. return axis;
  1032. }
  1033. } // namespace kernel
  1034. } // namespace mindspore