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.

cpu_kernel_runtime.cc 12 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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 "device/cpu/cpu_kernel_runtime.h"
  17. #include <string>
  18. #include <vector>
  19. #include <memory>
  20. #include <numeric>
  21. #include <utility>
  22. #include <functional>
  23. #include <unordered_map>
  24. #include "kernel/kernel.h"
  25. #include "device/cpu/cpu_device_address.h"
  26. #include "utils/context/ms_context.h"
  27. #include "utils/config_manager.h"
  28. #include "common/utils.h"
  29. #include "session/anf_runtime_algorithm.h"
  30. #include "operator/ops.h"
  31. namespace mindspore {
  32. namespace device {
  33. namespace cpu {
  34. const size_t INIT_NODE_REF = 1;
  35. void CPUKernelRuntime::AssignKernelAddress(session::KernelGraph *kernel_graph) {
  36. AssignValueNodeAddress(kernel_graph);
  37. AssignInputNodeAddress(kernel_graph);
  38. AssignKernelOutputAddress(kernel_graph);
  39. resource_manager_.MemPlan(kernel_graph);
  40. resource_manager_.MemMalloc(kernel_graph);
  41. }
  42. void CPUKernelRuntime::AssignValueNodeAddress(session::KernelGraph *kernel_graph) {
  43. MS_EXCEPTION_IF_NULL(kernel_graph);
  44. size_t type_size = sizeof(float);
  45. for (auto &item_node : kernel_graph->graph_value_nodes()) {
  46. MS_EXCEPTION_IF_NULL(item_node);
  47. if (item_node->isa<ValueNode>()) {
  48. auto value_node = item_node->cast<ValueNodePtr>();
  49. MS_EXCEPTION_IF_NULL(value_node);
  50. auto node_value = value_node->value();
  51. MS_EXCEPTION_IF_NULL(node_value);
  52. if (!node_value->isa<tensor::Tensor>()) {
  53. continue;
  54. }
  55. auto tensor = node_value->cast<TensorPtr>();
  56. MS_EXCEPTION_IF_NULL(tensor);
  57. std::vector<int> data_shape = tensor->shape();
  58. size_t tensor_size = std::accumulate(data_shape.begin(), data_shape.end(), type_size, std::multiplies<size_t>());
  59. DeviceAddressPtr address = CreateDeviceAddress(nullptr, tensor_size, kOpFormat_DEFAULT, kNumberTypeFloat32);
  60. if (tensor->data_type() == kNumberTypeFloat32 || tensor->data_type() == kNumberTypeInt32) {
  61. address->ptr_ = tensor->data_c(false);
  62. } else {
  63. address->ptr_ = resource_manager_.MemMalloc(tensor_size);
  64. if (!address->SyncHostToDevice(data_shape, LongToSize(tensor->data().nbytes()), tensor->data_type(),
  65. tensor->data_c(false))) {
  66. MS_LOG(EXCEPTION) << "Value node sync host to device failed!";
  67. }
  68. }
  69. address->ref_count_ = INIT_NODE_REF;
  70. AnfAlgo::SetOutputAddr(address, 0, item_node.get());
  71. }
  72. }
  73. }
  74. void CPUKernelRuntime::AssignInputNodeAddress(const session::KernelGraph *kernel_graph) {
  75. MS_EXCEPTION_IF_NULL(kernel_graph);
  76. size_t type_size = sizeof(float);
  77. for (auto &item : kernel_graph->inputs()) {
  78. MS_EXCEPTION_IF_NULL(item);
  79. if (item->isa<Parameter>()) {
  80. auto output_num = AnfAlgo::GetOutputTensorNum(item);
  81. for (size_t index = 0; index < output_num; index++) {
  82. TypeId output_type_id = AnfAlgo::GetOutputDeviceDataType(item, index);
  83. std::vector<size_t> fmt_shape = AnfAlgo::GetOutputDeviceShape(item, index);
  84. size_t tensor_size =
  85. fmt_shape.empty() ? type_size
  86. : std::accumulate(fmt_shape.begin(), fmt_shape.end(), type_size, std::multiplies<size_t>());
  87. auto format = AnfAlgo::GetOutputFormat(item, index);
  88. auto address = CreateDeviceAddress(nullptr, tensor_size, format, output_type_id);
  89. AnfAlgo::SetOutputAddr(address, index, item.get());
  90. }
  91. }
  92. }
  93. }
  94. void CPUKernelRuntime::AssignKernelOutputAddress(const session::KernelGraph *kernel_graph) {
  95. MS_EXCEPTION_IF_NULL(kernel_graph);
  96. auto kernels = kernel_graph->execution_order();
  97. for (auto &kernel : kernels) {
  98. auto kernel_mod = AnfAlgo::GetKernelMod(kernel);
  99. MS_EXCEPTION_IF_NULL(kernel_mod);
  100. auto output_sizes = kernel_mod->GetOutputSizeList();
  101. for (size_t i = 0; i < output_sizes.size(); ++i) {
  102. auto output_format = AnfAlgo::GetOutputFormat(kernel, i);
  103. auto output_type = AnfAlgo::GetOutputDeviceDataType(kernel, i);
  104. AnfAlgo::SetOutputAddr(CreateDeviceAddress(nullptr, output_sizes[i], output_format, output_type), i,
  105. kernel.get());
  106. }
  107. auto workspace_sizes = kernel_mod->GetWorkspaceSizeList();
  108. for (size_t i = 0; i < workspace_sizes.size(); ++i) {
  109. AnfAlgo::SetWorkspaceAddr(CreateDeviceAddress(nullptr, workspace_sizes[i], kOpFormat_DEFAULT, kNumberTypeFloat32),
  110. i, kernel.get());
  111. }
  112. }
  113. }
  114. DeviceAddressPtr CPUKernelRuntime::CreateDeviceAddress(void *device_ptr, size_t device_size, const string &format,
  115. TypeId type_id) {
  116. return std::make_shared<CPUDeviceAddress>(device_ptr, device_size, format, type_id);
  117. }
  118. BaseRef CPUKernelRuntime::CreatTensorForOutput(const AnfNodePtr &input_node, size_t index,
  119. const std::unordered_map<AnfNode *, tensor::TensorPtr> &input_map) {
  120. MS_EXCEPTION_IF_NULL(input_node);
  121. if (input_node->isa<CNode>() && AnfAlgo::GetCNodeName(input_node) == prim::kPrimMakeTuple->name()) {
  122. auto cnode = input_node->cast<CNodePtr>();
  123. MS_EXCEPTION_IF_NULL(cnode);
  124. VectorRef ret;
  125. for (size_t i = 1; i < cnode->inputs().size(); i++) {
  126. auto item_with_index = AnfAlgo::VisitKernelWithReturnType(cnode->input(i), 0);
  127. auto out = CreatTensorForOutput(item_with_index.first, item_with_index.second, input_map);
  128. ret.push_back(out);
  129. }
  130. return ret;
  131. }
  132. if (input_node->isa<CNode>()) {
  133. auto node = input_node->cast<CNodePtr>();
  134. MS_EXCEPTION_IF_NULL(node);
  135. size_t output_size = AnfAlgo::GetOutputTensorNum(node);
  136. if (index >= output_size) {
  137. MS_LOG(EXCEPTION) << "Invalid input index " << index;
  138. }
  139. auto address = AnfAlgo::GetMutableOutputAddr(node, index);
  140. MS_EXCEPTION_IF_NULL(address);
  141. auto shape = AnfAlgo::GetOutputInferShape(node, index);
  142. std::vector<int> temp_shape;
  143. (void)temp_shape.insert(temp_shape.end(), shape.begin(), shape.end());
  144. TypeId type_id = AnfAlgo::GetOutputInferDataType(node, index);
  145. if (type_id == kNumberTypeUInt32) {
  146. type_id = kNumberTypeInt32;
  147. }
  148. if (type_id == kNumberTypeFloat || type_id == kNumberTypeFloat16 || type_id == kNumberTypeFloat32 ||
  149. type_id == kNumberTypeFloat64) {
  150. type_id = kNumberTypeFloat32;
  151. }
  152. if (type_id != kNumberTypeInt32 && type_id != kNumberTypeFloat32) {
  153. MS_LOG(EXCEPTION) << "Check output type failed.";
  154. }
  155. tensor::TensorPtr tensor = std::make_shared<tensor::Tensor>(type_id, temp_shape);
  156. MS_EXCEPTION_IF_NULL(tensor);
  157. address->ptr_ = tensor->data_c(true);
  158. address->ref_count_ = INIT_NODE_REF;
  159. tensor->set_dirty(false);
  160. return tensor;
  161. } else if (input_node->isa<Parameter>() || input_node->isa<ValueNode>()) {
  162. auto iter = input_map.find(input_node.get());
  163. if (iter != input_map.end()) {
  164. return iter->second;
  165. }
  166. }
  167. return BaseRef();
  168. }
  169. void CPUKernelRuntime::BindInputOutput(const session::KernelGraph *kernel_graph,
  170. const std::vector<tensor::TensorPtr> &inputs, VectorRef *outputs) {
  171. MS_EXCEPTION_IF_NULL(kernel_graph);
  172. MS_EXCEPTION_IF_NULL(outputs);
  173. // bind input ptr
  174. auto &input_nodes = kernel_graph->inputs();
  175. if (input_nodes.size() != inputs.size()) {
  176. MS_LOG(EXCEPTION) << "Input size not equal to input node size!";
  177. }
  178. std::unordered_map<AnfNode *, tensor::TensorPtr> input_map;
  179. size_t input_idx = 0;
  180. size_t type_size = sizeof(float);
  181. for (auto &item : input_nodes) {
  182. MS_EXCEPTION_IF_NULL(item);
  183. input_map[item.get()] = inputs[input_idx];
  184. if (item->isa<Parameter>()) {
  185. auto address = AnfAlgo::GetMutableOutputAddr(item, 0);
  186. auto tensor = inputs[input_idx];
  187. MS_EXCEPTION_IF_NULL(address);
  188. MS_EXCEPTION_IF_NULL(tensor);
  189. std::vector<int> data_shape = tensor->shape();
  190. size_t tensor_size = std::accumulate(data_shape.begin(), data_shape.end(), type_size, std::multiplies<size_t>());
  191. if (tensor->data_type() == kNumberTypeFloat32 || tensor->data_type() == kNumberTypeInt32) {
  192. address->ptr_ = tensor->data_c(false);
  193. } else {
  194. address->ptr_ = resource_manager_.MemMalloc(tensor_size);
  195. if (!address->SyncHostToDevice(data_shape, LongToSize(tensor->data().nbytes()), tensor->data_type(),
  196. tensor->data_c(false))) {
  197. MS_LOG(EXCEPTION) << "Parameter node sync host to device failed!";
  198. }
  199. tensor->set_dirty(true);
  200. }
  201. address->ref_count_ = INIT_NODE_REF;
  202. tensor->set_device_address(address);
  203. }
  204. input_idx++;
  205. }
  206. // new output and bind ptr
  207. auto output_nodes = kernel_graph->outputs();
  208. for (const auto &item : output_nodes) {
  209. auto item_with_index = AnfAlgo::VisitKernelWithReturnType(item, 0);
  210. auto out = CreatTensorForOutput(item_with_index.first, item_with_index.second, input_map);
  211. outputs->push_back(std::move(out));
  212. }
  213. }
  214. void CPUKernelRuntime::AddRuntimeAddress(DeviceAddress *address, std::vector<kernel::AddressPtr> *input_list) {
  215. MS_EXCEPTION_IF_NULL(address);
  216. kernel::AddressPtr input = std::make_shared<kernel::Address>();
  217. MS_EXCEPTION_IF_NULL(input);
  218. if (address->ptr_ == nullptr) {
  219. address->ptr_ = resource_manager_.MemMalloc(address->size_);
  220. }
  221. MS_EXCEPTION_IF_NULL(address->ptr_);
  222. input->addr = address->ptr_;
  223. input->size = address->size_;
  224. input_list->push_back(input);
  225. }
  226. bool CPUKernelRuntime::Run(session::KernelGraph *kernel_graph) {
  227. MS_EXCEPTION_IF_NULL(kernel_graph);
  228. resource_manager_.ResetAddressRefCount(kernel_graph);
  229. auto kernels = kernel_graph->execution_order();
  230. for (const auto &kernel : kernels) {
  231. std::vector<kernel::AddressPtr> kernel_inputs;
  232. std::vector<kernel::AddressPtr> kernel_workspaces;
  233. std::vector<kernel::AddressPtr> kernel_outputs;
  234. size_t input_num = AnfAlgo::GetInputTensorNum(kernel);
  235. for (size_t i = 0; i < input_num; ++i) {
  236. auto device_address = AnfAlgo::GetPrevNodeMutableOutputAddr(kernel, i).get();
  237. MS_EXCEPTION_IF_NULL(device_address);
  238. AddRuntimeAddress(device_address, &kernel_inputs);
  239. }
  240. size_t output_num = AnfAlgo::GetOutputTensorNum(kernel);
  241. for (size_t i = 0; i < output_num; ++i) {
  242. auto device_address = AnfAlgo::GetMutableOutputAddr(kernel, i).get();
  243. MS_EXCEPTION_IF_NULL(device_address);
  244. AddRuntimeAddress(device_address, &kernel_outputs);
  245. }
  246. auto kernel_mod = AnfAlgo::GetKernelMod(kernel);
  247. MS_EXCEPTION_IF_NULL(kernel_mod);
  248. for (size_t i = 0; i < kernel_mod->GetWorkspaceSizeList().size(); ++i) {
  249. auto device_address = AnfAlgo::GetWorkspaceAddr(kernel, i);
  250. MS_EXCEPTION_IF_NULL(device_address);
  251. AddRuntimeAddress(device_address, &kernel_workspaces);
  252. }
  253. auto ret = kernel_mod->Launch(kernel_inputs, kernel_workspaces, kernel_outputs, 0);
  254. resource_manager_.DecreaseAddressRefCount(kernel);
  255. if (!ret) {
  256. MS_LOG(EXCEPTION) << "Launch kernel failed.";
  257. }
  258. }
  259. return true;
  260. }
  261. } // namespace cpu
  262. } // namespace device
  263. } // namespace mindspore