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

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