From 18496bce86f7f55519b8c6bf5efd6b00ecb9a665 Mon Sep 17 00:00:00 2001 From: yskhhh Date: Thu, 17 Jun 2021 14:49:57 +0800 Subject: [PATCH 01/20] add debug task info --- .../node_executor/aicore/aicore_node_executor.cc | 6 +++ ge/hybrid/node_executor/aicore/aicore_op_task.h | 2 + ge/single_op/single_op.cc | 5 ++ ge/single_op/task/build_task_utils.cc | 54 ++++++++++++++++++++-- ge/single_op/task/build_task_utils.h | 8 ++++ ge/single_op/task/op_task.cc | 1 + ge/single_op/task/op_task.h | 2 + tests/ut/ge/hybrid/ge_hybrid_unittest.cc | 31 +++++++++++++ tests/ut/ge/single_op/single_op_unittest.cc | 13 +++++- 9 files changed, 118 insertions(+), 4 deletions(-) diff --git a/ge/hybrid/node_executor/aicore/aicore_node_executor.cc b/ge/hybrid/node_executor/aicore/aicore_node_executor.cc index 7ebb9e39..efa864ed 100755 --- a/ge/hybrid/node_executor/aicore/aicore_node_executor.cc +++ b/ge/hybrid/node_executor/aicore/aicore_node_executor.cc @@ -18,6 +18,7 @@ #include "framework/common/taskdown_common.h" #include "hybrid/executor/hybrid_execution_context.h" #include "external/runtime/rt_error_codes.h" +#include "single_op/task/build_task_utils.h" namespace ge { namespace hybrid { @@ -196,6 +197,11 @@ Status AiCoreNodeTask::ExecuteAsync(TaskContext &context, std::function RECORD_EXECUTION_EVENT(context.GetExecutionContext(), context.GetNodeName(), "[AiCoreNodeLaunchKernel] Start"); GE_CHK_STATUS_RET_NOLOG((*it)->LaunchKernel(context.GetStream())); GE_CHK_STATUS_RET_NOLOG(CheckOverflow(context)); + GE_CHECK_NOTNULL(context.GetExecutionContext()->model); + GELOGD("[DEBUG_TASK_INFO : Executor Task] %s/%s %s", + context.GetExecutionContext()->model->GetModelName().c_str(), + (*it)->GetName().empty() ? (*it)->GetLogName().c_str() : (*it)->GetName().c_str(), + BuildTaskUtils::GetTaskInfo(context).c_str()); // save profiling data uint32_t task_id = 0; uint32_t stream_id = 0; diff --git a/ge/hybrid/node_executor/aicore/aicore_op_task.h b/ge/hybrid/node_executor/aicore/aicore_op_task.h index 8d7b7f1e..9db958d2 100755 --- a/ge/hybrid/node_executor/aicore/aicore_op_task.h +++ b/ge/hybrid/node_executor/aicore/aicore_op_task.h @@ -72,6 +72,8 @@ class AiCoreOpTask { const std::string& GetName() const; + const std::string& GetLogName() const {return log_name_;} + bool GetClearAtomic() const {return clear_atomic_;} uint32_t GetBlockDim() const {return block_dim_;} diff --git a/ge/single_op/single_op.cc b/ge/single_op/single_op.cc index d09e8398..fc34e513 100755 --- a/ge/single_op/single_op.cc +++ b/ge/single_op/single_op.cc @@ -297,6 +297,9 @@ FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY Status SingleOp::ExecuteAsync(c for (auto &task : tasks_) { ret = task->LaunchKernel(stream_); + GELOGD("[DEBUG_TASK_INFO : Static Task] %s %s", + task->GetTaskName().c_str(), + BuildTaskUtils::GetTaskInfo(task->GetOpdesc(), inputs, outputs).c_str()); if (ret != SUCCESS) { return ret; } @@ -447,6 +450,8 @@ Status DynamicSingleOp::ExecuteAsync(const vector &input_desc, } else { GE_CHK_STATUS_RET_NOLOG(op_task_->LaunchKernel(input_desc, input_buffers, output_desc, output_buffers, stream_)); } + GELOGD("[DEBUG_TASK_INFO : Dynamic Task] %s", + BuildTaskUtils::GetTaskInfo(op_task_->GetOpdesc(), input_buffers, output_buffers).c_str()); GE_CHK_STATUS_RET_NOLOG(op_task_->OpenDump(stream_)); GE_CHK_STATUS_RET_NOLOG(ProfilingTaskInfo(op_task_.get(), kShapeTypeDynamic)); return SUCCESS; diff --git a/ge/single_op/task/build_task_utils.cc b/ge/single_op/task/build_task_utils.cc index 9e4d55e1..b3a7ae09 100644 --- a/ge/single_op/task/build_task_utils.cc +++ b/ge/single_op/task/build_task_utils.cc @@ -70,7 +70,9 @@ std::vector BuildTaskUtils::GetKernelArgs(const OpDescPtr &op_desc, return JoinAddresses(addresses); } -std::string BuildTaskUtils::GetTaskInfo(const OpDescPtr &op_desc) { +std::string BuildTaskUtils::InnerGetTaskInfo(const OpDescPtr &op_desc, + const std::vector &input_addrs, + const std::vector &output_addrs) { std::stringstream ss; if (op_desc != nullptr) { auto op_type = op_desc->GetType(); @@ -87,7 +89,10 @@ std::string BuildTaskUtils::GetTaskInfo(const OpDescPtr &op_desc) { } ss << TypeUtils::DataTypeToSerialString(input->GetDataType()) << " "; ss << TypeUtils::FormatToSerialString(input->GetFormat()); - ss << VectorToString(input->GetShape().GetDims()); + ss << VectorToString(input->GetShape().GetDims()) << " "; + if (idx < input_addrs.size()) { + ss << input_addrs[idx]; + } if (idx < op_desc->GetInputsSize() - 1) { ss << ","; } @@ -101,7 +106,10 @@ std::string BuildTaskUtils::GetTaskInfo(const OpDescPtr &op_desc) { const GeShape &out_shape = output->GetShape(); const auto &dims = out_shape.GetDims(); ss << TypeUtils::FormatToSerialString(out_format); - ss << VectorToString(dims); + ss << VectorToString(dims) << " "; + if (idx < output_addrs.size()) { + ss << output_addrs[idx]; + } if (idx < op_desc->GetOutputsSize() - 1) { ss << ","; } @@ -110,4 +118,44 @@ std::string BuildTaskUtils::GetTaskInfo(const OpDescPtr &op_desc) { } return ss.str(); } + +std::string BuildTaskUtils::GetTaskInfo(const OpDescPtr &op_desc) { + vector input_addrs; + vector output_addrs; + return InnerGetTaskInfo(op_desc, input_addrs, output_addrs); +} + +std::string BuildTaskUtils::GetTaskInfo(const OpDescPtr &op_desc, + const std::vector &inputs, + const std::vector &outputs) { + vector input_addrs; + vector output_addrs; + GE_CHECK_NOTNULL_EXEC(op_desc, return ""); + if (op_desc->GetAllInputsSize() == inputs.size()) { + std::for_each(inputs.begin(), inputs.end(), [&](const DataBuffer &db) { input_addrs.push_back(db.data); }); + } + if (op_desc->GetOutputsSize() == outputs.size()) { + std::for_each(outputs.begin(), outputs.end(), [&](const DataBuffer &db) { output_addrs.push_back(db.data); }); + } + return InnerGetTaskInfo(op_desc, input_addrs, output_addrs); +} + +std::string BuildTaskUtils::GetTaskInfo(const hybrid::TaskContext &task_context) { + auto &node_item = task_context.GetNodeItem(); + auto op_desc = node_item.GetOpDesc(); + GE_CHECK_NOTNULL_EXEC(op_desc, return ""); + vector input_addrs; + vector output_addrs; + if (op_desc->GetAllInputsSize() == static_cast(task_context.NumInputs())) { + for (size_t i = 0; i < op_desc->GetAllInputsSize(); ++i) { + input_addrs.push_back(task_context.GetInput(i)->GetData()); + } + } + if (op_desc->GetOutputsSize() == static_cast(task_context.NumOutputs())) { + for (size_t i = 0; i < op_desc->GetOutputsSize(); ++i) { + output_addrs.push_back(task_context.GetOutput(i)->GetData()); + } + } + return InnerGetTaskInfo(op_desc, input_addrs, output_addrs); +} } // namespace ge diff --git a/ge/single_op/task/build_task_utils.h b/ge/single_op/task/build_task_utils.h index 7a2369e4..68894f5b 100644 --- a/ge/single_op/task/build_task_utils.h +++ b/ge/single_op/task/build_task_utils.h @@ -23,6 +23,7 @@ #include "graph/op_desc.h" #include "single_op/single_op.h" #include "single_op/single_op_model.h" +#include "hybrid/node_executor/task_context.h" namespace ge { class BuildTaskUtils { @@ -35,7 +36,14 @@ class BuildTaskUtils { bool keep_workspace = true); static std::vector JoinAddresses(const std::vector> &addresses); static std::vector GetKernelArgs(const OpDescPtr &op_desc, const SingleOpModelParam ¶m); + static std::string InnerGetTaskInfo(const OpDescPtr &op_desc, + const std::vector &input_addrs, + const std::vector &output_addrs); static std::string GetTaskInfo(const OpDescPtr &op_desc); + static std::string GetTaskInfo(const OpDescPtr &op_desc, + const std::vector &inputs, + const std::vector &outputs); + static std::string GetTaskInfo(const hybrid::TaskContext& task_context); template static std::string VectorToString(const std::vector &values) { std::stringstream ss; diff --git a/ge/single_op/task/op_task.cc b/ge/single_op/task/op_task.cc index e48677f8..02fc96f3 100755 --- a/ge/single_op/task/op_task.cc +++ b/ge/single_op/task/op_task.cc @@ -89,6 +89,7 @@ Status OpTask::OpenDump(rtStream_t stream) { void TbeOpTask::SetStubFunc(const std::string &name, const void *stub_func) { this->stub_name_ = name; this->stub_func_ = stub_func; + this->task_name_ = name; } void TbeOpTask::SetKernelArgs(std::unique_ptr &&args, size_t arg_size, uint32_t block_dim, diff --git a/ge/single_op/task/op_task.h b/ge/single_op/task/op_task.h index ed6cf40f..5efb4472 100644 --- a/ge/single_op/task/op_task.h +++ b/ge/single_op/task/op_task.h @@ -44,6 +44,7 @@ class OpTask { virtual Status UpdateArgTable(const SingleOpModelParam ¶m); void SetModelArgs(std::string model_name, uint32_t model_id); Status GetProfilingArgs(TaskDescInfo &task_desc_info, uint32_t &model_id); + const std::string &GetTaskName() const {return task_name_;} void SetOpDesc(const OpDescPtr &op_desc) { op_desc_ = op_desc; } @@ -66,6 +67,7 @@ class OpTask { std::string model_name_; uint32_t model_id_ = 0; uint32_t block_dim_ = 1; + std::string task_name_; }; class TbeOpTask : public OpTask { diff --git a/tests/ut/ge/hybrid/ge_hybrid_unittest.cc b/tests/ut/ge/hybrid/ge_hybrid_unittest.cc index 228af832..24a60413 100644 --- a/tests/ut/ge/hybrid/ge_hybrid_unittest.cc +++ b/tests/ut/ge/hybrid/ge_hybrid_unittest.cc @@ -34,12 +34,14 @@ #include "hybrid/executor/hybrid_execution_context.h" #include "hybrid/executor/hybrid_model_executor.h" #include "hybrid/node_executor/aicore/aicore_task_builder.h" +#include "hybrid/node_executor/aicore/aicore_node_executor.h" #include "graph/load/model_manager/tbe_handle_store.h" #include "graph/manager/graph_mem_allocator.h" #include "hybrid/common/npu_memory_allocator.h" #include "graph/types.h" #include "graph/utils/tensor_utils.h" #include "graph/testcase/ge_graph/graph_builder_utils.h" +#include "single_op/task/build_task_utils.h" #include "graph/op_desc_impl.h" #undef private #undef protected @@ -746,4 +748,33 @@ TEST_F(UtestGeHybrid, TestParseDependencies) { AttrUtils::SetTensor(tensor_desc, "_value", tensor); std::set dependent_for_shape_inference; ASSERT_EQ(builder.ParseDependencies(*node_item, deps, dependent_for_shape_inference), SUCCESS); +} + +TEST_F(UtestGeHybrid, TestTaskExecuteAsync) { + auto graph = make_shared("graph"); + OpDescPtr op_desc = CreateOpDesc("Add", "Add"); + GeShape shape({2, 16}); + GeTensorDesc tensor_desc(shape); + op_desc->AddInputDesc(tensor_desc); + op_desc->AddInputDesc(tensor_desc); + op_desc->AddOutputDesc(tensor_desc); + auto node = graph->AddNode(op_desc); + std::unique_ptr node_item; + NodeItem::Create(node, node_item); + node_item->input_start = 0; + node_item->output_start = 0; + + GraphExecutionContext execution_context; + GraphItem graph_item; + SubgraphContext subgraph_context(&graph_item, &execution_context); + ASSERT_EQ(subgraph_context.Init(), SUCCESS); + subgraph_context.all_inputs_.resize(2); + subgraph_context.all_outputs_.resize(1); + auto node_state = subgraph_context.GetOrCreateNodeState(node_item.get()); + auto task_context = *node_state->GetTaskContext(); + ASSERT_NE(BuildTaskUtils::GetTaskInfo(task_context), ""); + std::unique_ptr task1(new AiCoreOpTask()); + std::vector> tasks; + AiCoreNodeTask node_task(std::move(tasks)); + ASSERT_EQ(node_task.ExecuteAsync(task_context, nullptr), SUCCESS); } \ No newline at end of file diff --git a/tests/ut/ge/single_op/single_op_unittest.cc b/tests/ut/ge/single_op/single_op_unittest.cc index db3de7ec..831f3f16 100644 --- a/tests/ut/ge/single_op/single_op_unittest.cc +++ b/tests/ut/ge/single_op/single_op_unittest.cc @@ -23,6 +23,7 @@ #define private public #include "single_op/single_op.h" #include "single_op/single_op_manager.h" +#include "single_op/task/build_task_utils.h" #undef private #undef protected @@ -126,9 +127,19 @@ TEST_F(UtestSingleOp, test_singleop_execute_async1) { SingleOpModelParam model_params; single_op.running_param_.reset(new (std::nothrow)SingleOpModelParam(model_params)); single_op.args_.resize(1); + + auto *tbe_task = new (std::nothrow) TbeOpTask(); + ge::OpDescPtr op_desc = std::make_shared("Mul", MATMUL); + EXPECT_EQ(op_desc->AddInputDesc("x", GeTensorDesc(GeShape({2}), FORMAT_NCHW)), GRAPH_SUCCESS); + EXPECT_EQ(op_desc->AddOutputDesc("x", GeTensorDesc(GeShape({2}), FORMAT_NCHW)), GRAPH_SUCCESS); + EXPECT_NE(BuildTaskUtils::GetTaskInfo(op_desc), ""); + ge::ComputeGraphPtr graph = std::make_shared("default"); + ge::NodePtr node = graph->AddNode(op_desc); + tbe_task->node_ = node; + tbe_task->op_desc_ = op_desc; + single_op.tasks_.push_back(tbe_task); EXPECT_EQ(single_op.hybrid_model_executor_, nullptr); EXPECT_EQ(single_op.running_param_->mem_base, nullptr); - EXPECT_EQ(single_op.tasks_.size(), 0); EXPECT_EQ(single_op.ExecuteAsync(input_buffers, output_buffers), SUCCESS); } From 3af68a42300f54e50f079ebf8ea41b01a02eeb59 Mon Sep 17 00:00:00 2001 From: zhangxiaokun Date: Fri, 25 Jun 2021 20:53:08 +0800 Subject: [PATCH 02/20] Fix Set Control flow group for -1 --- .../passes/mark_force_unknown_for_cond_pass.cc | 97 ++++++++++++---------- ge/graph/passes/mark_force_unknown_for_cond_pass.h | 11 +++ ge/graph/passes/switch_to_stream_switch_pass.cc | 5 +- ge/hybrid/executor/node_state.cc | 35 +++++--- ge/hybrid/executor/node_state.h | 1 + ge/hybrid/model/node_item.cc | 6 +- ge/hybrid/model/node_item.h | 4 +- ge/hybrid/node_executor/node_executor.cc | 1 + ge/hybrid/node_executor/task_context.cc | 6 ++ ge/hybrid/node_executor/task_context.h | 1 + 10 files changed, 108 insertions(+), 59 deletions(-) diff --git a/ge/graph/passes/mark_force_unknown_for_cond_pass.cc b/ge/graph/passes/mark_force_unknown_for_cond_pass.cc index fbf69c04..233a1ff0 100644 --- a/ge/graph/passes/mark_force_unknown_for_cond_pass.cc +++ b/ge/graph/passes/mark_force_unknown_for_cond_pass.cc @@ -16,8 +16,6 @@ #include "graph/passes/mark_force_unknown_for_cond_pass.h" -#include - #include "graph/utils/node_utils.h" #include "graph/common/omg_util.h" @@ -26,17 +24,7 @@ namespace { inline bool IsMergeInLoop(const NodePtr &node) { const static std::set kLoopMergeInputs{ ENTER, REFENTER, NEXTITERATION, REFNEXTITERATION }; - std::string node_type; - (void)GetOriginalType(node, node_type); - return kLoopMergeInputs.count(node_type) > 0; -} - -inline bool IsSwitchInLoop(const NodePtr &node) { - const static std::set kLoopSwitchInputs{ MERGE, REFMERGE, LOOPCOND }; - - std::string node_type; - (void)GetOriginalType(node, node_type); - return kLoopSwitchInputs.count(node_type) > 0; + return kLoopMergeInputs.count(NodeUtils::GetNodeType(node)) > 0; } } @@ -44,10 +32,7 @@ Status MarkForceUnknownForCondPass::Run(ComputeGraphPtr graph) { GELOGD("MarkForceUnknownForCondPass Enter"); std::map> switch_groups; for (const auto &node : graph->GetDirectNode()) { - std::string node_type; - GE_CHK_STATUS_RET(GetOriginalType(node, node_type), - "[Get][OriginalType] of node in graph:%s failed.", graph->GetName().c_str()); - if (kMergeOpTypes.count(node_type) == 0) { + if (kMergeOpTypes.count(NodeUtils::GetNodeType(node)) == 0) { continue; } @@ -65,6 +50,51 @@ Status MarkForceUnknownForCondPass::Run(ComputeGraphPtr graph) { } /// +/// @brief Deal with Switch node for LoopCond +/// @param [in] Switch node +/// @param [in] dest span +/// @param [out] Search queue +/// @return true: Switch In while loop / false: Not in while Loop. +/// +bool MarkForceUnknownForCondPass::DealWithLoopSwitch(const NodePtr &node, uint32_t dst_span, + std::queue> search_queue) { + /// LoopCond --->\. + /// \. + /// Enter-----------+ \. + /// +--> Merge --> Switch --> Exit + /// NextIteration---+ + const auto is_loop_op = [](const NodePtr &n) { + return NodeUtils::GetNodeType(n) == LOOPCOND; + }; + const auto is_exit_op = [](const NodePtr &n) { + return kExitOpTypes.count(NodeUtils::GetNodeType(n)) > 0; + }; + + const auto src_nodes = node->GetInAllNodes(); + const auto dst_nodes = node->GetOutAllNodes(); + if (std::none_of(src_nodes.begin(), src_nodes.end(), is_loop_op) && + std::none_of(dst_nodes.begin(), dst_nodes.end(), is_exit_op)) { + return false; + } + + for (const auto &m : src_nodes) { + if (kMergeOpTypes.count(NodeUtils::GetNodeType(m)) > 0) { + for (const auto &n : m->GetInAllNodes()) { + if (kNextIterationOpTypes.count(NodeUtils::GetNodeType(n)) > 0) { + continue; + } + + search_queue.push({n, dst_span}); + GELOGD("Travel in Loop: %s <-- %s <-- %s, span is: %u", node->GetName().c_str(), m->GetName().c_str(), + n->GetName().c_str(), dst_span); + } + } + } + + return true; +} + +/// /// @brief Mark force unknown shape for Switch node /// @param [in] merge node /// @param [out] switch group @@ -72,6 +102,7 @@ Status MarkForceUnknownForCondPass::Run(ComputeGraphPtr graph) { /// void MarkForceUnknownForCondPass::MarkUnknownForSwitch(const NodePtr &node, std::vector &switch_group) { // Switch --> {Switch --> Merge} --> Merge + GELOGD("Search Switch node for Merge: %s", node->GetName().c_str()); std::unordered_set nodes_seen; std::queue> search_queue({{node, 0}}); while (!search_queue.empty()) { @@ -79,43 +110,25 @@ void MarkForceUnknownForCondPass::MarkUnknownForSwitch(const NodePtr &node, std: const auto dst_span = search_queue.front().second; search_queue.pop(); - // Switch --> Identity --> Constant - for (const auto &in_node : dst_node->GetInControlNodes()) { - if (nodes_seen.count(in_node) > 0) { - GELOGD("Travel node: %s, Skip already seen node: %s", dst_node->GetName().c_str(), in_node->GetName().c_str()); - continue; - } - nodes_seen.insert(in_node); - - if (in_node->GetType() == IDENTITY) { - GELOGD("Travel node: %s, In control: %s, span is: %u", dst_node->GetName().c_str(), - in_node->GetName().c_str(), dst_span); - search_queue.push({in_node, dst_span}); - } - } - - for (const auto &in_node : dst_node->GetInDataNodes()) { + for (const auto &in_node : dst_node->GetInAllNodes()) { if (nodes_seen.count(in_node) > 0) { GELOGD("Travel node: %s, Skip already seen node: %s", dst_node->GetName().c_str(), in_node->GetName().c_str()); continue; } nodes_seen.insert(in_node); - std::string node_type; - (void)GetOriginalType(in_node, node_type); + const std::string node_type = NodeUtils::GetNodeType(in_node); GELOGD("Travel node: %s, %s node: %s, span is: %u", dst_node->GetName().c_str(), node_type.c_str(), in_node->GetName().c_str(), dst_span); if (kSwitchOpTypes.count(node_type) > 0) { // Switch input node. + if (DealWithLoopSwitch(in_node, dst_span, search_queue)) { + continue; + } + if (dst_span > 0) { search_queue.push({in_node, dst_span - 1}); } else { - const auto &all_in_nodes = in_node->GetInDataNodes(); - if (std::any_of(all_in_nodes.begin(), all_in_nodes.end(), IsSwitchInLoop)) { - GELOGW("Travel node: %s, %s node: %s, Skip LoopCond switch", dst_node->GetName().c_str(), node_type.c_str(), - in_node->GetName().c_str()); - } else { - switch_group.emplace_back(in_node); - } + switch_group.emplace_back(in_node); } } else if (kMergeOpTypes.count(node_type) > 0) { // Merge input node. search_queue.push({in_node, dst_span + 1}); diff --git a/ge/graph/passes/mark_force_unknown_for_cond_pass.h b/ge/graph/passes/mark_force_unknown_for_cond_pass.h index 528a8fdc..d2be9a9e 100644 --- a/ge/graph/passes/mark_force_unknown_for_cond_pass.h +++ b/ge/graph/passes/mark_force_unknown_for_cond_pass.h @@ -19,6 +19,8 @@ #include "inc/graph_pass.h" +#include + namespace ge { class MarkForceUnknownForCondPass : public GraphPass { public: @@ -26,6 +28,15 @@ class MarkForceUnknownForCondPass : public GraphPass { private: /// + /// @brief Deal with Switch node for LoopCond + /// @param [in] Switch node + /// @param [in] dest span + /// @param [out] Search queue + /// @return true: Switch In while loop / false: Not in while Loop. + /// + bool DealWithLoopSwitch(const NodePtr &node, uint32_t dst_span, std::queue> search_queue); + + /// /// @brief Mark force unknown shape for Switch node /// @param [in] merge node /// @param [out] switch group diff --git a/ge/graph/passes/switch_to_stream_switch_pass.cc b/ge/graph/passes/switch_to_stream_switch_pass.cc index 77a7c9db..7fecae31 100644 --- a/ge/graph/passes/switch_to_stream_switch_pass.cc +++ b/ge/graph/passes/switch_to_stream_switch_pass.cc @@ -395,8 +395,9 @@ NodePtr SwitchToStreamSwitchPass::CreateStreamSwitchNode(const ComputeGraphPtr & peer_cond_anchor->GetOwnerNode()->GetName().c_str(), stream_switch->GetName().c_str()); int64_t group_index = -1; - (void)AttrUtils::GetInt(switch_node->GetOpDesc(), ATTR_NAME_CONTROL_FLOW_GROUP, group_index); - SetControlFlowGroup(stream_switch, group_index); + if (AttrUtils::GetInt(switch_node->GetOpDesc(), ATTR_NAME_CONTROL_FLOW_GROUP, group_index)) { + SetControlFlowGroup(stream_switch, group_index); + } return stream_switch; } diff --git a/ge/hybrid/executor/node_state.cc b/ge/hybrid/executor/node_state.cc index 468c84e6..4b0d0c44 100644 --- a/ge/hybrid/executor/node_state.cc +++ b/ge/hybrid/executor/node_state.cc @@ -326,17 +326,37 @@ std::shared_ptr NodeState::GetTaskContext() { } void NodeState::SavePersistTensor(int input_idx, const TensorValue &tensor) { - if (node_item_->root_data_.count(input_idx) > 0) { + const auto is_persist_tensor = [](const std::map> &items, int idx) { + const auto is_exist = [&idx](const std::pair> &items) { + return items.second.count(idx) > 0; + }; + return std::any_of(items.begin(), items.end(), is_exist); + }; + + if (is_persist_tensor(node_item_->root_data_, input_idx)) { GELOGD("[%s] Save Root input tensor: %d", GetName().c_str(), input_idx); root_tensor_values_[input_idx] = tensor; - } - - if (node_item_->enter_data_.count(input_idx) > 0) { + } else if (is_persist_tensor(node_item_->enter_data_, input_idx)) { GELOGD("[%s] Save Enter input tensor: %d", GetName().c_str(), input_idx); root_tensor_values_[input_idx] = tensor; } } +void NodeState::UpdatePersistTensor() { + const auto update_tensor = [&](const std::map> &items) { + for (const auto &item : items) { + for (const auto idx : item.second) { + UpdatePersistTensor(idx); + } + } + }; + + update_tensor(node_item_->root_data_); + if (iteration_count_ > 0) { + update_tensor(node_item_->enter_data_); + } +} + void NodeState::UpdatePersistTensor(int input_idx) { const auto it = root_tensor_values_.find(input_idx); if (it == root_tensor_values_.end()) { @@ -363,16 +383,9 @@ void NodeState::ResetContext(uint64_t iteration) { data_scheduled_ = static_cast(node_item_->root_data_.size()); ctrl_scheduled_ = static_cast(node_item_->root_ctrl_.size()); - for (auto item : node_item_->root_data_) { - UpdatePersistTensor(item.first); - } - if (iteration > 0) { data_scheduled_ += static_cast(node_item_->enter_data_.size()); ctrl_scheduled_ += static_cast(node_item_->enter_ctrl_.size()); - for (auto item : node_item_->enter_data_) { - UpdatePersistTensor(item.first); - } } iteration_count_ = iteration; diff --git a/ge/hybrid/executor/node_state.h b/ge/hybrid/executor/node_state.h index 727402f1..f1cec215 100644 --- a/ge/hybrid/executor/node_state.h +++ b/ge/hybrid/executor/node_state.h @@ -132,6 +132,7 @@ struct NodeState { void RunNextIteration(); void SavePersistTensor(int input_idx, const TensorValue &tensor); + void UpdatePersistTensor(); Status NodeScheduled(const std::function &ready) const; diff --git a/ge/hybrid/model/node_item.cc b/ge/hybrid/model/node_item.cc index 250562ce..8e87c6e2 100644 --- a/ge/hybrid/model/node_item.cc +++ b/ge/hybrid/model/node_item.cc @@ -395,11 +395,13 @@ void NodeItem::SetDataSend(NodeItem *node_item, int anchor_index) { data_send_.emplace(node_item); node_item->data_recv_[this] = anchor_index; if (is_root_node_) { - node_item->root_data_[anchor_index] = this; + auto &data_anchors = node_item->root_data_[this]; + data_anchors.emplace(anchor_index); } // If Enter feed Not Merge, take as root Node. if (IsEnterOp() && (node_item->node_type != STREAMMERGE)) { - node_item->enter_data_[anchor_index] = this; + auto &data_anchors = node_item->enter_data_[this]; + data_anchors.emplace(anchor_index); } GELOGI("Node[%s] will control node[%s]", NodeName().c_str(), node_item->NodeName().c_str()); } diff --git a/ge/hybrid/model/node_item.h b/ge/hybrid/model/node_item.h index 12775b00..f6dcdcf6 100644 --- a/ge/hybrid/model/node_item.h +++ b/ge/hybrid/model/node_item.h @@ -148,9 +148,9 @@ struct NodeItem { int64_t frame_index_ = -1; int64_t parent_frame_ = -1; std::set root_ctrl_; // Recv ctrl from root node - std::map root_data_; // Recv data from root node + std::map> root_data_; // Recv data from root node std::set enter_ctrl_; // Recv ctrl from Enter node - std::map enter_data_; // Recv data from Enter node + std::map> enter_data_; // Recv data from Enter node std::set data_send_; // Send data notify to std::map data_recv_; // Recv data notify from std::set ctrl_send_; // Send ctrl notify to diff --git a/ge/hybrid/node_executor/node_executor.cc b/ge/hybrid/node_executor/node_executor.cc index 9e9354d9..eeb5ba20 100755 --- a/ge/hybrid/node_executor/node_executor.cc +++ b/ge/hybrid/node_executor/node_executor.cc @@ -39,6 +39,7 @@ const char *const kEngineNameHostCpu = "DNN_VM_HOST_CPU_OP_STORE"; Status NodeExecutor::PrepareTask(NodeTask &task, TaskContext &context) const { GE_CHK_STATUS_RET_NOLOG(context.AllocateOutputs()); GE_CHK_STATUS_RET_NOLOG(context.AllocateWorkspaces()); + GE_CHK_STATUS_RET_NOLOG(context.UpdatePersistTensor()); GE_CHK_STATUS_RET_NOLOG(task.UpdateArgs(context)); return SUCCESS; } diff --git a/ge/hybrid/node_executor/task_context.cc b/ge/hybrid/node_executor/task_context.cc index c0464c87..3c288981 100644 --- a/ge/hybrid/node_executor/task_context.cc +++ b/ge/hybrid/node_executor/task_context.cc @@ -470,6 +470,12 @@ Status TaskContext::PropagateOutputs() { return SUCCESS; } +Status TaskContext::UpdatePersistTensor() { + GE_CHECK_NOTNULL(node_state_); + node_state_->UpdatePersistTensor(); + return SUCCESS; +} + const void *TaskContext::GetVarBaseAddr() { return execution_context_->model->GetVarMemBase(); } diff --git a/ge/hybrid/node_executor/task_context.h b/ge/hybrid/node_executor/task_context.h index c96e194e..cff5d680 100644 --- a/ge/hybrid/node_executor/task_context.h +++ b/ge/hybrid/node_executor/task_context.h @@ -78,6 +78,7 @@ class TaskContext { Status AllocateOutputs(AllocationAttr *attr = nullptr); Status AllocateWorkspaces(); Status AllocateWorkspace(size_t size, void **buffer, void *ori_addr = nullptr); + Status UpdatePersistTensor(); bool IsTraceEnabled() const; From d4828ea130d310773161d5f1b8ccc313f283cd1a Mon Sep 17 00:00:00 2001 From: zhangxiaokun Date: Sat, 26 Jun 2021 15:00:53 +0800 Subject: [PATCH 03/20] UpdatePersistTensor from ExecutionEngine --- ge/hybrid/executor/node_state.cc | 4 ++++ ge/hybrid/executor/worker/execution_engine.cc | 1 + ge/hybrid/node_executor/node_executor.cc | 1 - ge/hybrid/node_executor/task_context.cc | 11 +---------- ge/hybrid/node_executor/task_context.h | 1 - 5 files changed, 6 insertions(+), 12 deletions(-) diff --git a/ge/hybrid/executor/node_state.cc b/ge/hybrid/executor/node_state.cc index 4b0d0c44..7ab7b536 100644 --- a/ge/hybrid/executor/node_state.cc +++ b/ge/hybrid/executor/node_state.cc @@ -333,6 +333,10 @@ void NodeState::SavePersistTensor(int input_idx, const TensorValue &tensor) { return std::any_of(items.begin(), items.end(), is_exist); }; + if (root_tensor_values_.count(input_idx) > 0) { + return; + } + if (is_persist_tensor(node_item_->root_data_, input_idx)) { GELOGD("[%s] Save Root input tensor: %d", GetName().c_str(), input_idx); root_tensor_values_[input_idx] = tensor; diff --git a/ge/hybrid/executor/worker/execution_engine.cc b/ge/hybrid/executor/worker/execution_engine.cc index 8eecbc80..d4c73f58 100755 --- a/ge/hybrid/executor/worker/execution_engine.cc +++ b/ge/hybrid/executor/worker/execution_engine.cc @@ -375,6 +375,7 @@ Status ExecutionEngine::DoExecuteAsync(NodeState &node_state, RECORD_EXECUTION_EVENT(&context, task_context.GetNodeName(), "[PrepareTask] Start"); GE_CHK_STATUS_RET(executor->PrepareTask(*task, task_context), "[Prepare][Task] for [%s] failed.", node_state.GetName().c_str()); + node_state.UpdatePersistTensor(); RECORD_EXECUTION_EVENT(&context, task_context.GetNodeName(), "[PrepareTask] End"); GELOGD("[%s] Done task preparation successfully.", node_state.GetName().c_str()); diff --git a/ge/hybrid/node_executor/node_executor.cc b/ge/hybrid/node_executor/node_executor.cc index eeb5ba20..9e9354d9 100755 --- a/ge/hybrid/node_executor/node_executor.cc +++ b/ge/hybrid/node_executor/node_executor.cc @@ -39,7 +39,6 @@ const char *const kEngineNameHostCpu = "DNN_VM_HOST_CPU_OP_STORE"; Status NodeExecutor::PrepareTask(NodeTask &task, TaskContext &context) const { GE_CHK_STATUS_RET_NOLOG(context.AllocateOutputs()); GE_CHK_STATUS_RET_NOLOG(context.AllocateWorkspaces()); - GE_CHK_STATUS_RET_NOLOG(context.UpdatePersistTensor()); GE_CHK_STATUS_RET_NOLOG(task.UpdateArgs(context)); return SUCCESS; } diff --git a/ge/hybrid/node_executor/task_context.cc b/ge/hybrid/node_executor/task_context.cc index 3c288981..4ecc1558 100644 --- a/ge/hybrid/node_executor/task_context.cc +++ b/ge/hybrid/node_executor/task_context.cc @@ -460,22 +460,12 @@ Status TaskContext::PropagateOutputs() { subgraph_context_->all_inputs_[input_offset].SetName( node_item_->NodeName() + "_in_" + std::to_string(dst_input_idx)); } - - auto dst_node_state = subgraph_context_->GetOrCreateNodeState(dst_node_item); - GE_CHECK_NOTNULL(dst_node_state); - dst_node_state->SavePersistTensor(dst_input_idx, *tensor); } } (void)guard; return SUCCESS; } -Status TaskContext::UpdatePersistTensor() { - GE_CHECK_NOTNULL(node_state_); - node_state_->UpdatePersistTensor(); - return SUCCESS; -} - const void *TaskContext::GetVarBaseAddr() { return execution_context_->model->GetVarMemBase(); } @@ -501,6 +491,7 @@ void TaskContext::ReleaseInputsAndOutputs() { void TaskContext::ReleaseInput(int index) { auto input_tensor = MutableInput(index); if (input_tensor != nullptr) { + node_state_->SavePersistTensor(index, *input_tensor); input_tensor->Destroy(); GELOGD("[%s] Tensor of input[%d] released", GetNodeName(), index); } diff --git a/ge/hybrid/node_executor/task_context.h b/ge/hybrid/node_executor/task_context.h index cff5d680..c96e194e 100644 --- a/ge/hybrid/node_executor/task_context.h +++ b/ge/hybrid/node_executor/task_context.h @@ -78,7 +78,6 @@ class TaskContext { Status AllocateOutputs(AllocationAttr *attr = nullptr); Status AllocateWorkspaces(); Status AllocateWorkspace(size_t size, void **buffer, void *ori_addr = nullptr); - Status UpdatePersistTensor(); bool IsTraceEnabled() const; From eccff67f421da4ae147c629f61821676acf550d2 Mon Sep 17 00:00:00 2001 From: zhangxiaokun Date: Sat, 26 Jun 2021 15:42:55 +0800 Subject: [PATCH 04/20] Clear UpdatePersistTensor Warning for first run --- ge/graph/passes/mark_force_unknown_for_cond_pass.cc | 6 +++--- ge/graph/passes/mark_force_unknown_for_cond_pass.h | 2 +- ge/hybrid/executor/node_state.cc | 4 ++++ 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/ge/graph/passes/mark_force_unknown_for_cond_pass.cc b/ge/graph/passes/mark_force_unknown_for_cond_pass.cc index 233a1ff0..aa36a43b 100644 --- a/ge/graph/passes/mark_force_unknown_for_cond_pass.cc +++ b/ge/graph/passes/mark_force_unknown_for_cond_pass.cc @@ -56,8 +56,8 @@ Status MarkForceUnknownForCondPass::Run(ComputeGraphPtr graph) { /// @param [out] Search queue /// @return true: Switch In while loop / false: Not in while Loop. /// -bool MarkForceUnknownForCondPass::DealWithLoopSwitch(const NodePtr &node, uint32_t dst_span, - std::queue> search_queue) { +bool MarkForceUnknownForCondPass::DealAsLoopSwitch(const NodePtr &node, uint32_t dst_span, + std::queue> &search_queue) { /// LoopCond --->\. /// \. /// Enter-----------+ \. @@ -121,7 +121,7 @@ void MarkForceUnknownForCondPass::MarkUnknownForSwitch(const NodePtr &node, std: GELOGD("Travel node: %s, %s node: %s, span is: %u", dst_node->GetName().c_str(), node_type.c_str(), in_node->GetName().c_str(), dst_span); if (kSwitchOpTypes.count(node_type) > 0) { // Switch input node. - if (DealWithLoopSwitch(in_node, dst_span, search_queue)) { + if (DealAsLoopSwitch(in_node, dst_span, search_queue)) { continue; } diff --git a/ge/graph/passes/mark_force_unknown_for_cond_pass.h b/ge/graph/passes/mark_force_unknown_for_cond_pass.h index d2be9a9e..030b55ee 100644 --- a/ge/graph/passes/mark_force_unknown_for_cond_pass.h +++ b/ge/graph/passes/mark_force_unknown_for_cond_pass.h @@ -34,7 +34,7 @@ class MarkForceUnknownForCondPass : public GraphPass { /// @param [out] Search queue /// @return true: Switch In while loop / false: Not in while Loop. /// - bool DealWithLoopSwitch(const NodePtr &node, uint32_t dst_span, std::queue> search_queue); + bool DealAsLoopSwitch(const NodePtr &node, uint32_t dst_span, std::queue> &search_queue); /// /// @brief Mark force unknown shape for Switch node diff --git a/ge/hybrid/executor/node_state.cc b/ge/hybrid/executor/node_state.cc index 7ab7b536..ad38c792 100644 --- a/ge/hybrid/executor/node_state.cc +++ b/ge/hybrid/executor/node_state.cc @@ -355,6 +355,10 @@ void NodeState::UpdatePersistTensor() { } }; + if (root_tensor_values_.empty()) { + return; + } + update_tensor(node_item_->root_data_); if (iteration_count_ > 0) { update_tensor(node_item_->enter_data_); From 572990a616dc60da23bcb70fbd436e7f2948cc88 Mon Sep 17 00:00:00 2001 From: zhangxiaokun Date: Sat, 26 Jun 2021 23:20:31 +0800 Subject: [PATCH 05/20] UT for control flow group --- tests/depends/mmpa/src/mmpa_stub.cc | 4 + tests/ut/ge/CMakeLists.txt | 3 +- .../build/logical_stream_allocator_unittest.cc | 10 +- .../ut/ge/graph/build/stream_allocator_unittest.cc | 2 +- tests/ut/ge/graph/passes/assert_pass_unittest.cc | 6 +- tests/ut/ge/graph/passes/base_pass_unittest.cc | 14 +-- .../ut/ge/graph/passes/cond_branch_v1_unittest.cc | 6 +- .../graph/passes/constant_folding_pass_unittest.cc | 38 +++--- .../passes/dimension_compute_pass_unittest.cc | 8 +- .../ssd_prior_box_kernel_unittest.cc | 2 +- ...e_data_nodes_with_common_input_pass_unittest.cc | 2 +- .../mark_force_unknown_for_cond_pass_unittest.cc | 129 +++++++++++++++------ tests/ut/ge/graph/passes/merge_pass_unittest.cc | 28 ++--- .../graph/passes/parallel_group_pass_unittest.cc | 12 +- .../graph/passes/reshape_recovery_pass_unittest.cc | 6 +- .../graph/passes/reshape_remove_pass_unittest.cc | 16 +-- .../passes/resource_pair_control_pass_unittest.cc | 2 +- .../passes/switch_logic_remove_pass_unittest.cc | 12 +- .../trans_op_breadth_fusion_pass_unittest.cc | 4 +- .../passes/trans_op_depth_fusion_pass_unittest.cc | 14 +-- ...ransop_nearby_allreduce_fusion_pass_unittest.cc | 4 +- .../ge/graph/passes/variable_op_pass_unittest.cc | 2 +- .../ge/graph/variable_accelerate_ctrl_unittest.cc | 10 +- 23 files changed, 195 insertions(+), 139 deletions(-) diff --git a/tests/depends/mmpa/src/mmpa_stub.cc b/tests/depends/mmpa/src/mmpa_stub.cc index aae8de9f..b0f1fb87 100644 --- a/tests/depends/mmpa/src/mmpa_stub.cc +++ b/tests/depends/mmpa/src/mmpa_stub.cc @@ -345,6 +345,10 @@ INT32 mmIsDir(const CHAR *fileName) INT32 mmGetEnv(const CHAR *name, CHAR *value, UINT32 len) { + const char *env = getenv(name); + if (env != nullptr) { + strcpy(value, env); + } return 0; } diff --git a/tests/ut/ge/CMakeLists.txt b/tests/ut/ge/CMakeLists.txt index 95b9e388..57677cf0 100755 --- a/tests/ut/ge/CMakeLists.txt +++ b/tests/ut/ge/CMakeLists.txt @@ -720,7 +720,6 @@ set(PASS_TEST_FILES "graph/passes/memcpy_addr_async_unittest.cc" "graph/passes/hccl_continuous_pass_unittest.cc" "graph/passes/hccl_memcpy_pass_unittest.cc" - ) set(KERNEL_TEST_FILES @@ -850,7 +849,6 @@ set(HYBRID_TEST_FILES "hybrid/executor/hybrid_model_async_executor_unittest.cc" "hybrid/executor/hybrid_model_pipeline_executor_unittest.cc" "hybrid/node_executor/aicore/aicore_task_compiler_unittest.cc" - ) set(OTHERS_TEST_FILES @@ -877,6 +875,7 @@ add_library(ge_ut_graph STATIC target_compile_definitions(ge_ut_graph PRIVATE google=ascend_private + FMK_SUPPORT_DUMP ) target_compile_options(ge_ut_graph PRIVATE diff --git a/tests/ut/ge/graph/build/logical_stream_allocator_unittest.cc b/tests/ut/ge/graph/build/logical_stream_allocator_unittest.cc index 218bfd0d..352984fa 100644 --- a/tests/ut/ge/graph/build/logical_stream_allocator_unittest.cc +++ b/tests/ut/ge/graph/build/logical_stream_allocator_unittest.cc @@ -349,7 +349,7 @@ class UtestLogicalStreamAllocator : public testing::Test { /// B --> C(AllReduce) --- D /// / /// stream id: 0 A - /// \ + /// \. /// E --> F(AllReduce) --- G /// stream id: 2 2 2 /// @@ -599,7 +599,7 @@ TEST_F(UtestLogicalStreamAllocator, test_label_not_reusable2) { /// case of multi-output, then unuse stream /// sub1 -/// / | \ +/// / | \. /// sub2 sub3 sub4 TEST_F(UtestLogicalStreamAllocator, test_multiOut_new_stream) { SubGraphInfoPtr data = CreateDataSubgraph(); @@ -624,7 +624,7 @@ TEST_F(UtestLogicalStreamAllocator, test_multiOut_new_stream) { /// if paralle id 1, then use stream /// sub1 -/// / | | \ +/// / | | \. /// sub2 sub3 sub4 sub5 TEST_F(UtestLogicalStreamAllocator, test_parallel_one) { SubGraphInfoPtr data = CreateDataSubgraph(); @@ -653,7 +653,7 @@ TEST_F(UtestLogicalStreamAllocator, test_parallel_one) { /// if the param of engine independent is true, then set independent stream /// sub1 -/// / | | \ +/// / | | \. /// sub2 sub3 sub4 sub5 TEST_F(UtestLogicalStreamAllocator, test_independent) { SubGraphInfoPtr data = CreateDataSubgraph(); @@ -692,7 +692,7 @@ TEST_F(UtestLogicalStreamAllocator, test_independent) { /// set stream based on stream label, and then based on independent /// sub1 -/// / | | \ +/// / | | \. /// sub2 sub3 sub4 sub5 TEST_F(UtestLogicalStreamAllocator, test_independent_switch_label) { SubGraphInfoPtr data = CreateDataSubgraph(); diff --git a/tests/ut/ge/graph/build/stream_allocator_unittest.cc b/tests/ut/ge/graph/build/stream_allocator_unittest.cc index 019e75d1..4ae871af 100644 --- a/tests/ut/ge/graph/build/stream_allocator_unittest.cc +++ b/tests/ut/ge/graph/build/stream_allocator_unittest.cc @@ -36,7 +36,7 @@ class UtestStreamAllocator : public testing::Test { /// /// A - /// / \ + /// / \. /// B C /// | | /// D 400 diff --git a/tests/ut/ge/graph/passes/assert_pass_unittest.cc b/tests/ut/ge/graph/passes/assert_pass_unittest.cc index 4aa133d3..9247681c 100644 --- a/tests/ut/ge/graph/passes/assert_pass_unittest.cc +++ b/tests/ut/ge/graph/passes/assert_pass_unittest.cc @@ -55,7 +55,7 @@ class UtestGraphPassesAssertPass : public Test { }; /// D E -/// | \ | \ +/// | \ | \. /// F C G /// : | : /// H A I @@ -134,8 +134,8 @@ TEST_F(UtestGraphPassesAssertPass, assert_pass_test2) { EXPECT_EQ(graph->FindNode("D"), nullptr); } -/// E F -/// | \ | \ +/// E F +/// | \ | \. /// H C -> D G /// \ | : /// A I diff --git a/tests/ut/ge/graph/passes/base_pass_unittest.cc b/tests/ut/ge/graph/passes/base_pass_unittest.cc index 9bba5d77..c687e07f 100644 --- a/tests/ut/ge/graph/passes/base_pass_unittest.cc +++ b/tests/ut/ge/graph/passes/base_pass_unittest.cc @@ -130,7 +130,7 @@ class UTESTGraphPassesBasePass : public testing::Test { /// reshape1 /// | /// add1 -/// / \ +/// / \. /// | | /// data1 const1 ComputeGraphPtr BuildGraph1() { @@ -148,9 +148,9 @@ ComputeGraphPtr BuildGraph1() { } /// sum1 -/// / \ -/// / \ -/// / \ +/// / \. +/// / \. +/// / \. /// reshape1 addn1 /// | c | /// add1 <--- shape1 @@ -217,7 +217,7 @@ void CheckIterOrder(UtestTestPass *pass, std::vector &loop, vector &cond) { /******************************************************************************* - * Exit Identify - * \ / \. - * \ / \. - * Switch Add - * / | | - * / | | - * / | | - * LoopCond | | - * \ | | - * \ | | - * \ | | - * Less | | - * \ | NextIteration - * \ | | - * \ | | - * Merge <---------| - * | - * | - * Enter + * | + * +--------------------- Merge ----------------------+ + * / | + * / | + * / | + * / | + * Exit Identify | + * \ / \. | + * \ / \. | + * Switch Add Add + * / | | | + * / | | | + * / | | | + * LoopCond | | | + * \ | | | + * \ | | | + * \ | | | + * Less | | | + * \ | NextIteration | + * \ | | | + * \ | | | + * Merge <---------| | + * | | + * | | + * Enter | + * \ | + * \ | + * Switch Switch + * | | + * +-----------------Equal----------------------+ + * | ******************************************************************************/ - auto data1 = CreateNode(*graph, "data", DATA, 1, 1); + auto data1 = CreateNode(*graph, "data1", DATA, 1, 1); + auto data2 = CreateNode(*graph, "data2", DATA, 1, 1); + + auto equal1 = CreateNode(*graph, "equal1", EQUAL, 2, 1); + auto switch1 = CreateNode(*graph, "switch1", SWITCH, 2, 2); + auto switch2 = CreateNode(*graph, "switch2", SWITCH, 2, 2); + auto enter1 = CreateNode(*graph, "enter", ENTER, 1, 1); - auto merge1 = CreateNode(*graph, "merge", MERGE, 2, 2); - auto less1 = CreateNode(*graph, "less", LESS, 2, 1); + auto merge1 = CreateNode(*graph, "merge1", MERGE, 2, 2); + auto less1 = CreateNode(*graph, "less1", LESS, 2, 1); auto loop1 = CreateNode(*graph, "loopcond", LOOPCOND, 1, 1); - auto switch1 = CreateNode(*graph, "switch", SWITCH, 2, 2); + auto switch3 = CreateNode(*graph, "switch3", SWITCH, 2, 2); auto ident1 = CreateNode(*graph, "identity", IDENTITY, 1, 1); - auto add1 = CreateNode(*graph, "add", ADD, 2, 1); + auto add1 = CreateNode(*graph, "add1", ADD, 2, 1); auto next1 = CreateNode(*graph, "next", NEXTITERATION, 1, 1); auto exit1 = CreateNode(*graph, "exit", EXIT, 1, 1); - auto value0 = CreateNode(*graph, "const", CONSTANT, 0, 1); - auto value1 = CreateNode(*graph, "const", CONSTANT, 0, 1); + auto value1 = CreateNode(*graph, "const1", CONSTANT, 0, 1); + + auto value2 = CreateNode(*graph, "const2", CONSTANT, 0, 1); + auto add2 = CreateNode(*graph, "add2", ADD, 2, 1); + auto merge2 = CreateNode(*graph, "merge2", MERGE, 2, 2); auto output1 = CreateNode(*graph, "net_output", NETOUTPUT, 1, 1); - GraphUtils::AddEdge(data1->GetOutDataAnchor(0), enter1->GetInDataAnchor(0)); + GraphUtils::AddEdge(data1->GetOutDataAnchor(0), equal1->GetInDataAnchor(0)); + GraphUtils::AddEdge(data2->GetOutDataAnchor(0), equal1->GetInDataAnchor(1)); + GraphUtils::AddEdge(data1->GetOutDataAnchor(0), switch1->GetInDataAnchor(0)); + GraphUtils::AddEdge(data2->GetOutDataAnchor(0), switch2->GetInDataAnchor(0)); + GraphUtils::AddEdge(equal1->GetOutDataAnchor(0), switch1->GetInDataAnchor(1)); + GraphUtils::AddEdge(equal1->GetOutDataAnchor(0), switch2->GetInDataAnchor(1)); + cond.emplace_back(switch1); + cond.emplace_back(switch2); + + GraphUtils::AddEdge(switch1->GetOutDataAnchor(0), enter1->GetInDataAnchor(0)); // false GraphUtils::AddEdge(enter1->GetOutDataAnchor(0), merge1->GetInDataAnchor(0)); GraphUtils::AddEdge(merge1->GetOutDataAnchor(0), less1->GetInDataAnchor(0)); GraphUtils::AddEdge(value1->GetOutDataAnchor(0), less1->GetInDataAnchor(1)); GraphUtils::AddEdge(less1->GetOutDataAnchor(0), loop1->GetInDataAnchor(0)); - GraphUtils::AddEdge(loop1->GetOutDataAnchor(0), switch1->GetInDataAnchor(0)); - GraphUtils::AddEdge(merge1->GetOutDataAnchor(0), switch1->GetInDataAnchor(1)); + GraphUtils::AddEdge(loop1->GetOutDataAnchor(0), switch3->GetInDataAnchor(0)); + GraphUtils::AddEdge(merge1->GetOutDataAnchor(0), switch3->GetInDataAnchor(1)); + loop.emplace_back(merge1); - GraphUtils::AddEdge(switch1->GetOutDataAnchor(0), exit1->GetInDataAnchor(0)); - GraphUtils::AddEdge(switch1->GetOutDataAnchor(1), ident1->GetInDataAnchor(0)); + GraphUtils::AddEdge(switch3->GetOutDataAnchor(0), exit1->GetInDataAnchor(0)); // false + GraphUtils::AddEdge(switch3->GetOutDataAnchor(1), ident1->GetInDataAnchor(0)); // true + loop.emplace_back(switch3); GraphUtils::AddEdge(ident1->GetOutDataAnchor(0), add1->GetInDataAnchor(0)); GraphUtils::AddEdge(value1->GetOutDataAnchor(0), add1->GetInDataAnchor(1)); GraphUtils::AddEdge(add1->GetOutDataAnchor(0), next1->GetInDataAnchor(0)); - GraphUtils::AddEdge(next1->GetOutDataAnchor(0), merge1->GetInDataAnchor(1)); - GraphUtils::AddEdge(exit1->GetOutDataAnchor(0), output1->GetInDataAnchor(0)); - merge = merge1; + GraphUtils::AddEdge(switch2->GetOutDataAnchor(1), add2->GetInDataAnchor(1)); // true + GraphUtils::AddEdge(value2->GetOutDataAnchor(0), add2->GetInDataAnchor(0)); + + GraphUtils::AddEdge(exit1->GetOutDataAnchor(0), merge2->GetInDataAnchor(0)); + GraphUtils::AddEdge(add2->GetOutDataAnchor(0), merge2->GetInDataAnchor(1)); + GraphUtils::AddEdge(merge2->GetOutDataAnchor(0), output1->GetInDataAnchor(0)); + + cond.emplace_back(merge2); + merge = merge2; } static void CreateCondGraph(ComputeGraphPtr &graph, NodePtr &merge) { @@ -197,12 +235,27 @@ static void CreateCondGraph(ComputeGraphPtr &graph, NodePtr &merge) { TEST_F(UtestMarkForceUnknownForCondPass, skip_while_loop_merge) { auto graph = std::make_shared("test_graph"); NodePtr merge; - CreateLoopGraph(graph, merge); - - AttrUtils::SetBool(merge->GetOpDesc(), ATTR_NAME_FORCE_UNKNOWN_SHAPE, true); + vector loop; + vector cond; + CreateLoopGraph(graph, merge, loop, cond); MarkForceUnknownForCondPass mark_force_unknown_pass; EXPECT_EQ(mark_force_unknown_pass.Run(graph), SUCCESS); // skip LoopCond + setenv("DUMP_GE_GRAPH", "1", true); + GE_DUMP(graph, "control_group"); + unsetenv("DUMP_GE_GRAPH"); + + EXPECT_EQ(loop.size(), 2); + for (const auto &node : loop) { + EXPECT_FALSE(node->GetOpDesc()->HasAttr(ATTR_NAME_CONTROL_FLOW_GROUP)); + } + + EXPECT_EQ(cond.size(), 3); + for (const auto &node : cond) { + int64_t group_index = -1; + EXPECT_TRUE(AttrUtils::GetInt(node->GetOpDesc(), ATTR_NAME_CONTROL_FLOW_GROUP, group_index)); + EXPECT_EQ(group_index, merge->GetOpDesc()->GetId()); + } } TEST_F(UtestMarkForceUnknownForCondPass, skip_known_shape_merge) { diff --git a/tests/ut/ge/graph/passes/merge_pass_unittest.cc b/tests/ut/ge/graph/passes/merge_pass_unittest.cc index 75fdb21b..f8f0afea 100644 --- a/tests/ut/ge/graph/passes/merge_pass_unittest.cc +++ b/tests/ut/ge/graph/passes/merge_pass_unittest.cc @@ -110,8 +110,8 @@ TEST_F(UtestGraphPassesMergePass, multiple_inputs) { } /// Merge -/// | \ -/// | \ +/// | \. +/// | \. /// Op1 Op2 Merge2 /// \ | | /// \ | Op3 @@ -137,10 +137,10 @@ TEST_F(UtestGraphPassesMergePass, empty_input_cut_branch_meet_net_output_with_da } /// Merge -/// | \ -/// | \ +/// | \. +/// | \. /// Op1 Op2 Merge2 -/// \ | | \ +/// \ | | \. /// \ | Op3 /// \ | : /// NetOutput @@ -165,8 +165,8 @@ TEST_F(UtestGraphPassesMergePass, empty_input_cut_branch_meet_net_output_with_co TEST_F(UtestGraphPassesMergePass, empty_input_cut_branch) { /// Merge - /// | \ - /// | \ + /// | \. + /// | \. /// Op1 Op2 Merge2 /// \ | | /// \ | Op3 @@ -210,7 +210,7 @@ TEST_F(UtestGraphPassesMergePass, empty_input_cut_branch) { /// Op1 Op2 Merge2 /// \ | /// \ Op3 - /// \ + /// \. /// Merge3 ret = pass_.Run(merge_node2); @@ -224,7 +224,7 @@ TEST_F(UtestGraphPassesMergePass, single_non_const_input) { /// Op1 /// | /// Merge - /// / \ + /// / \. /// Op2 Op3 auto merge_node = NewNode("Merge", MERGE, 1, 2); auto node1 = NewNode("Op1", RELU, 1, 1); @@ -253,7 +253,7 @@ TEST_F(UtestGraphPassesMergePass, single_const_input) { /// Const /// | /// Merge Pass Const - /// / \ ===> / \ + /// / \ ===> / \. /// Op1 Op2 Op1 Op2 auto merge_node = NewNode("Merge", MERGE, 1, 2); auto const_node = NewNode("Const", CONSTANT, 1, 1); @@ -284,7 +284,7 @@ TEST_F(UtestGraphPassesMergePass, single_const_input_value_index_two_out_nodes) /// / | ===> / \(control anchor) /// Op1 | \ Op1 Constant /// Op2 Op3 | - /// / \ + /// / \. /// Op2 Op3 auto merge_node = NewNode("Merge", MERGE, 1, 2); auto const_node = NewNode("Const", CONSTANT, 1, 1); @@ -329,7 +329,7 @@ TEST_F(UtestGraphPassesMergePass, single_const_input_value_index_two_out_nodes1) /// / | ===> / \(control anchor) /// Op1 | \ Op1 Constant /// Op2 Op3 | - /// / \ + /// / \. /// Op2 Op3 auto merge_node = NewNode("Merge", MERGE, 1, 2); auto const_node = NewNode("Const", CONSTANT, 1, 1); @@ -357,7 +357,7 @@ TEST_F(UtestGraphPassesMergePass, const_with_control_input) { /// C /// | /// Merge - /// / \ + /// / \. /// Op1 Op2 auto switch_node = NewNode("Switch", SWITCH, 1, 2); auto identity_node = NewNode("Identity", SWITCH, 1, 1); @@ -381,7 +381,7 @@ TEST_F(UtestGraphPassesMergePass, const_with_control_input) { /// . /// . /// C - /// / \ + /// / \. /// Op1 Op2 auto ret = pass_.Run(merge_node); EXPECT_EQ(ret, SUCCESS); diff --git a/tests/ut/ge/graph/passes/parallel_group_pass_unittest.cc b/tests/ut/ge/graph/passes/parallel_group_pass_unittest.cc index d5b1db41..374fe837 100644 --- a/tests/ut/ge/graph/passes/parallel_group_pass_unittest.cc +++ b/tests/ut/ge/graph/passes/parallel_group_pass_unittest.cc @@ -66,11 +66,11 @@ class UtestGraphPassesParallelGgroupPass : public testing::Test { void BuildDefaultGraph() { /// input - /// \ + /// \. /// sqrt pred /// \ / /// cast - /// / \ + /// / \. /// switch_t switch_f /// | | /// F T @@ -118,13 +118,13 @@ class UtestGraphPassesParallelGgroupPass : public testing::Test { void BuildDefaultGraph1() { /// input - /// \ + /// \. /// sqrt pred /// \ / /// Switch /// | | /// ----F T---- - /// \ | / \ + /// \ | / \. /// \ Merge1 Merge2 /// \_________| input_node_ = NewNode("input", RELU, 0, 1); @@ -164,14 +164,14 @@ class UtestGraphPassesParallelGgroupPass : public testing::Test { void BuildDefaultGraph2() { /// input input1 - /// \ \ + /// \ \. /// sqrt pred sqrt1 pred1 /// \ / \ / /// Switch Switch1 /// | | _______| /// | | / /// ____F T____ - /// \ | / \ + /// \ | / \. /// \ Merge1 Merge2 /// \__________| input_node_ = NewNode("input", RELU, 0, 2); diff --git a/tests/ut/ge/graph/passes/reshape_recovery_pass_unittest.cc b/tests/ut/ge/graph/passes/reshape_recovery_pass_unittest.cc index 3be11452..f941645e 100644 --- a/tests/ut/ge/graph/passes/reshape_recovery_pass_unittest.cc +++ b/tests/ut/ge/graph/passes/reshape_recovery_pass_unittest.cc @@ -31,9 +31,9 @@ class UtestReshapeRecoveryPass : public testing::Test { namespace { /// netoutput1 -/// | \ -///transdata1 \ -/// | \ +/// | \. +///transdata1 \. +/// | \. /// | transdata2 /// | / /// var1 const1 diff --git a/tests/ut/ge/graph/passes/reshape_remove_pass_unittest.cc b/tests/ut/ge/graph/passes/reshape_remove_pass_unittest.cc index 351e96d7..ca0cac86 100644 --- a/tests/ut/ge/graph/passes/reshape_remove_pass_unittest.cc +++ b/tests/ut/ge/graph/passes/reshape_remove_pass_unittest.cc @@ -35,7 +35,7 @@ namespace { /// transdata1 /// | /// reshape1 -/// | \ +/// | \. /// var1 const1 ut::GraphBuilder Graph1Builder() { ut::GraphBuilder builder = ut::GraphBuilder("g1"); @@ -55,11 +55,11 @@ ut::GraphBuilder Graph1Builder() { } /// netoutput1 -/// | \ -///transdata1 \ -/// | \ +/// | \. +///transdata1 \. +/// | \. /// reshape1 reshape2 -/// | \ / \ +/// | \ / \. /// var1 const1 var2 ut::GraphBuilder Graph2Builder() { ut::GraphBuilder builder = ut::GraphBuilder("g2"); @@ -83,9 +83,9 @@ ut::GraphBuilder Graph2Builder() { } /// netoutput1 -/// | \ -///transdata1 \ -/// | \ +/// | \. +///transdata1 \. +/// | \. /// reshape1 transdata2 /// | \ / /// var1 const1 diff --git a/tests/ut/ge/graph/passes/resource_pair_control_pass_unittest.cc b/tests/ut/ge/graph/passes/resource_pair_control_pass_unittest.cc index 6d12a49d..8cdfd0c7 100644 --- a/tests/ut/ge/graph/passes/resource_pair_control_pass_unittest.cc +++ b/tests/ut/ge/graph/passes/resource_pair_control_pass_unittest.cc @@ -34,7 +34,7 @@ class UtestResourcePairControlPass : public testing::Test { namespace { /// netoutput1 -/// | \ +/// | \. /// StackPush StackPop /// | | /// var1 const1 diff --git a/tests/ut/ge/graph/passes/switch_logic_remove_pass_unittest.cc b/tests/ut/ge/graph/passes/switch_logic_remove_pass_unittest.cc index dcad318c..22734047 100644 --- a/tests/ut/ge/graph/passes/switch_logic_remove_pass_unittest.cc +++ b/tests/ut/ge/graph/passes/switch_logic_remove_pass_unittest.cc @@ -63,9 +63,9 @@ ComputeGraphPtr BuildGraph1() { /// netoutput1 /// | /// merge1 -/// / \ +/// / \. /// / add1 -/// / F| \ +/// / F| \. /// addn1 swtich2 var3 /// \F T/ | /// switch1 | @@ -101,9 +101,9 @@ ComputeGraphPtr BuildGraph2() { /// add1 /// / \T /// var3 swtich2 -/// T/ \ -/// switch1 \ -/// / \ \ +/// T/ \. +/// switch1 \. +/// / \ \. /// var1 var2 var4 ComputeGraphPtr BuildGraph3() { auto builder = ut::GraphBuilder("g3"); @@ -129,7 +129,7 @@ ComputeGraphPtr BuildGraph3() { /// netoutput1 /// | /// merge1 -/// / \ +/// / \. /// add1 addn1 /// / \T F/ /// var3 swtich2 diff --git a/tests/ut/ge/graph/passes/trans_op_breadth_fusion_pass_unittest.cc b/tests/ut/ge/graph/passes/trans_op_breadth_fusion_pass_unittest.cc index dbb163e1..d05bd695 100644 --- a/tests/ut/ge/graph/passes/trans_op_breadth_fusion_pass_unittest.cc +++ b/tests/ut/ge/graph/passes/trans_op_breadth_fusion_pass_unittest.cc @@ -402,7 +402,7 @@ TEST_F(UtestGraphPassesTransOpBreadthFusionPass, test_multi_anchor_case) { } /// ----> netoutput1 -/// / | \ +/// / | \. /// transdata1 transdata2 transdata3 /// \ / | /// var1-------------- @@ -432,7 +432,7 @@ static ComputeGraphPtr BuildGraph1() { } /// ---------> netoutput1 -/// / | \ +/// / | \. /// transdata1 transdata2(l1) transdata3(l1) /// \ / | /// var1------------------ diff --git a/tests/ut/ge/graph/passes/trans_op_depth_fusion_pass_unittest.cc b/tests/ut/ge/graph/passes/trans_op_depth_fusion_pass_unittest.cc index a9ea41ea..dbac3246 100644 --- a/tests/ut/ge/graph/passes/trans_op_depth_fusion_pass_unittest.cc +++ b/tests/ut/ge/graph/passes/trans_op_depth_fusion_pass_unittest.cc @@ -456,19 +456,19 @@ TEST_F(UtestGraphPassesTransOpDepthFusionPass, test_transop_with_multi_out_edge) /// -->transpose1 -->transpose3-->sinh2 /// | \ / /// | -->transpose2 - /// | \ + /// | \. /// / -->cast3-->cast4-->sinh3 /// / /// / -->transpose4-->transpose5-->sinh4 /// / / /// Node4D-->Cast1-->Cast2-->Cast5 -->reshape2-->sinh5 - /// \ \ + /// \ \. /// \ -->sinh6 - /// \ + /// \. /// \ -->transpose6-->transpose7-->sinh9 /// \ / /// -->reshape-->cast6-->cast7-->sinh8 - /// \ + /// \. /// -->sinh7 /// after optimized graph @@ -479,15 +479,15 @@ TEST_F(UtestGraphPassesTransOpDepthFusionPass, test_transop_with_multi_out_edge) /// / /-->transpose3-->sinh2 /// -->Cast1 /// / \-->sinh7 - /// / \ + /// / \. /// / -->sinh9 /// Node4D /// \ -->sinh4 /// \ / /// -->Cast5-->sinh5 - /// \ \ + /// \ \. /// \ -->sinh6 - /// \ + /// \. /// -->Cast7-->sinh8 ge::ComputeGraphPtr graph = std::make_shared("test"); diff --git a/tests/ut/ge/graph/passes/transop_nearby_allreduce_fusion_pass_unittest.cc b/tests/ut/ge/graph/passes/transop_nearby_allreduce_fusion_pass_unittest.cc index 1220b35e..9c6d8276 100644 --- a/tests/ut/ge/graph/passes/transop_nearby_allreduce_fusion_pass_unittest.cc +++ b/tests/ut/ge/graph/passes/transop_nearby_allreduce_fusion_pass_unittest.cc @@ -180,7 +180,7 @@ ComputeGraphPtr GetGraph7(size_t symmetric_transdata_num, size_t asymmetric_tran /// TransData TransData ... MatMul ... /// \ | / / / /// HcomAllReduce - /// / | \ \ \ + /// / | \ \ \. /// TransData TransData ... RealDiv ... ComputeGraphPtr graph = std::make_shared("test"); NodePtr allreduce = @@ -340,7 +340,7 @@ TEST(UtestTransopNearbyAllreduceFusionPass, test7_all_reduce_with_multiple_trans /// TransData TransData ... MatMul ... /// \ | / / / /// HcomAllReduce - /// / | \ \ \ + /// / | \ \ \. /// TransData TransData ... RealDiv ... size_t symmetric_transdata_num = 20; size_t asymmetric_transdata_num = 20; diff --git a/tests/ut/ge/graph/passes/variable_op_pass_unittest.cc b/tests/ut/ge/graph/passes/variable_op_pass_unittest.cc index f1ea7a27..655867a7 100644 --- a/tests/ut/ge/graph/passes/variable_op_pass_unittest.cc +++ b/tests/ut/ge/graph/passes/variable_op_pass_unittest.cc @@ -66,7 +66,7 @@ namespace { /// transdata2 /// | /// assign1 -/// / \ +/// / \. /// transdata1 | /// | | /// var1 const1 diff --git a/tests/ut/ge/graph/variable_accelerate_ctrl_unittest.cc b/tests/ut/ge/graph/variable_accelerate_ctrl_unittest.cc index 37b4bda7..bf350b6c 100644 --- a/tests/ut/ge/graph/variable_accelerate_ctrl_unittest.cc +++ b/tests/ut/ge/graph/variable_accelerate_ctrl_unittest.cc @@ -35,8 +35,8 @@ namespace { /// shapeNo1 /// | /// addnYes1 -/// / \ -/// / \ +/// / \. +/// / \. /// const1 const2 ComputeGraphPtr BuildGraph1() { @@ -57,9 +57,9 @@ ComputeGraphPtr BuildGraph1() { /// /// netoutput1 -/// / \ \ -/// add1 assign1 \ -/// / \ / \ \ +/// / \ \. +/// add1 assign1 \. +/// / \ / \ \. /// var1 var2 const1 var3 ComputeGraphPtr BuildGraph2() { From a4aae38d72c9bc0e564ecce4d6da4ad02d46a0fd Mon Sep 17 00:00:00 2001 From: zhangxiaokun Date: Sat, 26 Jun 2021 23:25:58 +0800 Subject: [PATCH 06/20] Remove UT dump env --- tests/ut/ge/graph/passes/mark_force_unknown_for_cond_pass_unittest.cc | 3 --- 1 file changed, 3 deletions(-) diff --git a/tests/ut/ge/graph/passes/mark_force_unknown_for_cond_pass_unittest.cc b/tests/ut/ge/graph/passes/mark_force_unknown_for_cond_pass_unittest.cc index 50991822..557359b7 100644 --- a/tests/ut/ge/graph/passes/mark_force_unknown_for_cond_pass_unittest.cc +++ b/tests/ut/ge/graph/passes/mark_force_unknown_for_cond_pass_unittest.cc @@ -241,9 +241,6 @@ TEST_F(UtestMarkForceUnknownForCondPass, skip_while_loop_merge) { MarkForceUnknownForCondPass mark_force_unknown_pass; EXPECT_EQ(mark_force_unknown_pass.Run(graph), SUCCESS); // skip LoopCond - setenv("DUMP_GE_GRAPH", "1", true); - GE_DUMP(graph, "control_group"); - unsetenv("DUMP_GE_GRAPH"); EXPECT_EQ(loop.size(), 2); for (const auto &node : loop) { From 020d7cb8a04780fb7cf99ddd8a578281a26128ce Mon Sep 17 00:00:00 2001 From: lichun Date: Mon, 28 Jun 2021 10:34:54 +0800 Subject: [PATCH 07/20] remove SetDataType --- ge/hybrid/executor/subgraph_executor.cc | 1 - 1 file changed, 1 deletion(-) diff --git a/ge/hybrid/executor/subgraph_executor.cc b/ge/hybrid/executor/subgraph_executor.cc index 6979d05f..33a2846c 100644 --- a/ge/hybrid/executor/subgraph_executor.cc +++ b/ge/hybrid/executor/subgraph_executor.cc @@ -109,7 +109,6 @@ Status SubgraphExecutor::InitInputsForUnknownShape(const std::vectorSetShape(tensor_desc->GetShape()); output_desc->SetOriginShape(tensor_desc->GetOriginShape()); - output_desc->SetDataType(tensor_desc->GetDataType()); node_state->SetSkipInferShape(true); } } From 91fd6e45ddd8ccbc0d1289c59efffac3ebbd2d13 Mon Sep 17 00:00:00 2001 From: WeiGangqiang Date: Tue, 22 Jun 2021 14:53:24 +0800 Subject: [PATCH 08/20] add ge running env config and perfact graph dsl --- .clang-format | 2 +- build.sh | 7 +- ge/ge_runtime/task/hccl_task.cc | 1 + tests/depends/slog/src/slog_stub.cc | 62 ++++++--- tests/framework/CMakeLists.txt | 4 +- tests/framework/cmake/graphengine.cmake | 31 +---- .../include/ge_graph_dsl/op_desc/op_desc_cfg_box.h | 34 +++-- .../framework/ge_graph_dsl/src/op_desc_cfg_box.cc | 29 +++- .../ge_graph_dsl/tests/op_desc_config_test.cc | 75 +++++++++++ .../ge_graph_dsl/tests/stub/optype_stub.cc | 1 + tests/framework/ge_running_env/CMakeLists.txt | 18 +++ .../ge_running_env/include/CMakeLists.txt | 17 +++ .../include/ge_running_env/env_installer.h} | 29 ++-- .../include/ge_running_env/fake_engine.h | 56 ++++++++ .../include/ge_running_env/fake_ns.h | 28 ++++ .../include/ge_running_env/fake_op.h | 49 +++++++ .../ge_running_env/fake_ops_kernel_builder.h} | 39 ++---- .../ge_running_env/fake_ops_kernel_info_store.h | 39 ++++++ .../include/ge_running_env/ge_running_env_faker.h | 45 +++++++ .../include/ge_running_env/info_store_holder.h} | 40 +++--- tests/framework/ge_running_env/src/CMakeLists.txt | 45 +++++++ .../ge_running_env/src/engine/fake_engine.cc | 81 +++++++++++ .../src/engine/fake_ops_kernel_builder.cc} | 43 ++---- .../src/engine/fake_ops_kernel_info_store.cc | 42 ++++++ .../ge_running_env/src/engine/info_store_holder.cc | 49 +++++++ .../src/env/ge_default_running_env.cc | 56 ++++++++ .../src/env/ge_default_running_env.h | 32 +++++ .../ge_running_env/src/env/ge_running_env_faker.cc | 109 +++++++++++++++ tests/framework/ge_running_env/src/op/fake_op.cc | 95 +++++++++++++ .../ge_running_env/src/op/fake_op_repo.cc | 39 ++++++ .../framework/ge_running_env/src/op/fake_op_repo.h | 31 +++++ .../framework/ge_running_env/tests/CMakeLists.txt | 33 +++++ .../tests/test_ge_running_env_faker.cc | 148 +++++++++++++++++++++ tests/framework/ge_running_env/tests/test_main.cc | 34 +++++ tests/framework/stub_engine/CMakeLists.txt | 58 -------- tests/framework/stub_engine/engine/stub_engine.cc | 74 ----------- tests/framework/stub_engine/engine/stub_engine.h | 127 ------------------ tests/framework/stub_engine/inc/st_types.h | 33 ----- .../stub_engine/ops_kernel_store/op/host_op.cc | 41 ------ .../ops_kernel_store/op/stub_op_factory.cc | 51 ------- .../ops_kernel_store/op/stub_op_factory.h | 109 --------------- .../ops_kernel_store/stub_ops_kernel_store.cc | 77 ----------- .../ops_kernel_store/stub_ops_kernel_store.h | 73 ---------- tests/st/testcase/CMakeLists.txt | 2 +- tests/st/testcase/test_framework_dummy.cc | 16 +-- tests/st/testcase/test_main.cc | 37 ++++++ 46 files changed, 1328 insertions(+), 813 deletions(-) create mode 100644 tests/framework/ge_graph_dsl/tests/op_desc_config_test.cc create mode 100644 tests/framework/ge_running_env/CMakeLists.txt create mode 100644 tests/framework/ge_running_env/include/CMakeLists.txt rename tests/framework/{stub_engine/ops_kernel_store/op/host_op.h => ge_running_env/include/ge_running_env/env_installer.h} (52%) create mode 100644 tests/framework/ge_running_env/include/ge_running_env/fake_engine.h create mode 100644 tests/framework/ge_running_env/include/ge_running_env/fake_ns.h create mode 100644 tests/framework/ge_running_env/include/ge_running_env/fake_op.h rename tests/framework/{stub_engine/ops_kernel_store/stub_ops_kernel_builder.h => ge_running_env/include/ge_running_env/fake_ops_kernel_builder.h} (59%) create mode 100644 tests/framework/ge_running_env/include/ge_running_env/fake_ops_kernel_info_store.h create mode 100644 tests/framework/ge_running_env/include/ge_running_env/ge_running_env_faker.h rename tests/framework/{stub_engine/ops_kernel_store/op/op.h => ge_running_env/include/ge_running_env/info_store_holder.h} (51%) create mode 100644 tests/framework/ge_running_env/src/CMakeLists.txt create mode 100644 tests/framework/ge_running_env/src/engine/fake_engine.cc rename tests/framework/{stub_engine/ops_kernel_store/stub_ops_kernel_builder.cc => ge_running_env/src/engine/fake_ops_kernel_builder.cc} (73%) create mode 100644 tests/framework/ge_running_env/src/engine/fake_ops_kernel_info_store.cc create mode 100644 tests/framework/ge_running_env/src/engine/info_store_holder.cc create mode 100644 tests/framework/ge_running_env/src/env/ge_default_running_env.cc create mode 100644 tests/framework/ge_running_env/src/env/ge_default_running_env.h create mode 100644 tests/framework/ge_running_env/src/env/ge_running_env_faker.cc create mode 100644 tests/framework/ge_running_env/src/op/fake_op.cc create mode 100644 tests/framework/ge_running_env/src/op/fake_op_repo.cc create mode 100644 tests/framework/ge_running_env/src/op/fake_op_repo.h create mode 100644 tests/framework/ge_running_env/tests/CMakeLists.txt create mode 100644 tests/framework/ge_running_env/tests/test_ge_running_env_faker.cc create mode 100644 tests/framework/ge_running_env/tests/test_main.cc delete mode 100644 tests/framework/stub_engine/CMakeLists.txt delete mode 100644 tests/framework/stub_engine/engine/stub_engine.cc delete mode 100644 tests/framework/stub_engine/engine/stub_engine.h delete mode 100644 tests/framework/stub_engine/inc/st_types.h delete mode 100644 tests/framework/stub_engine/ops_kernel_store/op/host_op.cc delete mode 100644 tests/framework/stub_engine/ops_kernel_store/op/stub_op_factory.cc delete mode 100644 tests/framework/stub_engine/ops_kernel_store/op/stub_op_factory.h delete mode 100644 tests/framework/stub_engine/ops_kernel_store/stub_ops_kernel_store.cc delete mode 100644 tests/framework/stub_engine/ops_kernel_store/stub_ops_kernel_store.h create mode 100644 tests/st/testcase/test_main.cc diff --git a/.clang-format b/.clang-format index c931e8f0..e7f9d935 100644 --- a/.clang-format +++ b/.clang-format @@ -50,7 +50,7 @@ CommentPragmas: '^ IWYU pragma:' CompactNamespaces: false ConstructorInitializerAllOnOneLineOrOnePerLine: true ConstructorInitializerIndentWidth: 4 -ContinuationIndentWidth: 2 +ContinuationIndentWidth: 4 Cpp11BracedListStyle: true DerivePointerAlignment: true DisableFormat: false diff --git a/build.sh b/build.sh index 61f86945..dbbf696b 100755 --- a/build.sh +++ b/build.sh @@ -144,7 +144,6 @@ build_graphengine() CMAKE_ARGS="${CMAKE_ARGS} -DENABLE_GE_UT=ON" fi - if [[ "X$ENABLE_GE_ST" = "Xon" ]]; then CMAKE_ARGS="${CMAKE_ARGS} -DENABLE_GE_ST=ON" fi @@ -176,7 +175,7 @@ build_graphengine() TARGET="ge_compiler atc_atc.bin ge_executor_shared ${TARGET}" elif [ "X$ENABLE_GE_ST" = "Xon" ] then - TARGET="ge_graph_dsl_test graph_engine_test" + TARGET="ge_graph_dsl_test ge_running_env_test graph_engine_test" elif [ "X$ENABLE_GE_UT" = "Xon" ] then TARGET="ut_libgraph ut_libge_multiparts_utest ut_libge_others_utest ut_libge_kernel_utest ut_libge_distinct_load_utest" @@ -244,13 +243,13 @@ if [[ "X$ENABLE_GE_ST" = "Xon" ]]; then mkdir -p ${OUTPUT_PATH}/plugin/opskernel cp ${BUILD_PATH}/tests/framework/libnnengine.so ${OUTPUT_PATH}/plugin/nnengine cp ${BUILD_PATH}/engine_conf.json ${OUTPUT_PATH}/plugin/nnengine/ge_config - cp ${BUILD_PATH}/tests/framework/libhost_cpu_engine.so ${OUTPUT_PATH}/plugin/opskernel cp ${BUILD_PATH}/tests/framework/libge_local_engine.so ${OUTPUT_PATH}/plugin/opskernel - cp ${BUILD_PATH}/tests/framework/stub_engine/libfe.so ${OUTPUT_PATH}/plugin/opskernel #prepare st execution bin cp ${BUILD_PATH}/tests/st/testcase/graph_engine_test ${OUTPUT_PATH} + cp ${BUILD_PATH}/tests/framework/ge_running_env/tests/ge_running_env_test ${OUTPUT_PATH} cp ${BUILD_PATH}/tests/framework/ge_graph_dsl/tests/ge_graph_dsl_test ${OUTPUT_PATH} #execute st testcase + RUN_TEST_CASE=${OUTPUT_PATH}/ge_running_env_test && ${RUN_TEST_CASE} RUN_TEST_CASE=${OUTPUT_PATH}/graph_engine_test && ${RUN_TEST_CASE} RUN_TEST_CASE=${OUTPUT_PATH}/ge_graph_dsl_test && ${RUN_TEST_CASE} if [[ "$?" -ne 0 ]]; then diff --git a/ge/ge_runtime/task/hccl_task.cc b/ge/ge_runtime/task/hccl_task.cc index 2ffe5185..b1c7158c 100644 --- a/ge/ge_runtime/task/hccl_task.cc +++ b/ge/ge_runtime/task/hccl_task.cc @@ -16,6 +16,7 @@ #include "ge_runtime/task/hccl_task.h" #include +#include "framework/common/util.h" #include "ge_runtime/task/task_factory.h" #include "common/opskernel/ops_kernel_info_store.h" #include "common/opskernel/ge_task_info.h" diff --git a/tests/depends/slog/src/slog_stub.cc b/tests/depends/slog/src/slog_stub.cc index d0eb49c5..238a6b37 100644 --- a/tests/depends/slog/src/slog_stub.cc +++ b/tests/depends/slog/src/slog_stub.cc @@ -23,13 +23,46 @@ void dav_log(int module_id, const char *fmt, ...) {} -void DlogErrorInner(int module_id, const char *fmt, ...) { dav_log(module_id, fmt); } +static int log_level = DLOG_ERROR; + +#define __DO_PRINT() \ + do { \ + const int FMT_BUFF_SIZE = 1024; \ + char fmt_buff[FMT_BUFF_SIZE] = {0}; \ + va_list valist; \ + va_start(valist, fmt); \ + vsnprintf(fmt_buff, FMT_BUFF_SIZE, fmt, valist); \ + va_end(valist); \ + printf("%s \n", fmt_buff); \ + } while (0) + +void DlogErrorInner(int module_id, const char *fmt, ...) { + if (log_level > DLOG_ERROR) { + return; + } + __DO_PRINT(); +} -void DlogWarnInner(int module_id, const char *fmt, ...) { dav_log(module_id, fmt); } +void DlogWarnInner(int module_id, const char *fmt, ...) { + if (log_level > DLOG_WARN) { + return; + } + __DO_PRINT(); +} -void DlogInfoInner(int module_id, const char *fmt, ...) { dav_log(module_id, fmt); } +void DlogInfoInner(int module_id, const char *fmt, ...) { + if (log_level > DLOG_INFO) { + return; + } + __DO_PRINT(); +} -void DlogDebugInner(int module_id, const char *fmt, ...) { dav_log(module_id, fmt); } +void DlogDebugInner(int module_id, const char *fmt, ...) { + if (log_level > DLOG_DEBUG) { + return; + } + __DO_PRINT(); +} void DlogEventInner(int module_id, const char *fmt, ...) { dav_log(module_id, fmt); } @@ -39,30 +72,25 @@ void DlogWithKVInner(int module_id, int level, KeyValue *pst_kv_array, int kv_nu dav_log(module_id, fmt); } -int dlog_setlevel(int module_id, int level, int enable_event) { return DLOG_DEBUG; } +int dlog_setlevel(int module_id, int level, int enable_event) { + log_level = level; + return log_level; +} -int dlog_getlevel(int module_id, int *enable_event) { return DLOG_DEBUG; } +int dlog_getlevel(int module_id, int *enable_event) { return log_level; } -int CheckLogLevel(int moduleId, int logLevel) -{ - return 1; -} +int CheckLogLevel(int moduleId, int log_level_check) { return log_level >= log_level_check; } /** * @ingroup plog * @brief DlogReportInitialize: init log in service process before all device setting. * @return: 0: SUCCEED, others: FAILED */ -int DlogReportInitialize() { - return 0; -} +int DlogReportInitialize() { return 0; } /** * @ingroup plog * @brief DlogReportFinalize: release log resource in service process after all device reset. * @return: 0: SUCCEED, others: FAILED */ -int DlogReportFinalize() { - return 0; -} - +int DlogReportFinalize() { return 0; } diff --git a/tests/framework/CMakeLists.txt b/tests/framework/CMakeLists.txt index d7c806a6..8a2218b4 100644 --- a/tests/framework/CMakeLists.txt +++ b/tests/framework/CMakeLists.txt @@ -15,8 +15,8 @@ include(cmake/graphengine.cmake) add_subdirectory(easy_graph) -add_subdirectory(stub_engine) add_subdirectory(ge_graph_dsl) +add_subdirectory(ge_running_env) file(GLOB_RECURSE UTILS_SRC CONFIGURE_DEPENDS "utils/*.cc" @@ -29,4 +29,4 @@ target_include_directories(framework ) set_target_properties(framework PROPERTIES CXX_STANDARD 11) -target_link_libraries(framework PUBLIC ge_graph_dsl graphengine fe) +target_link_libraries(framework PUBLIC ge_graph_dsl ge_with_env) diff --git a/tests/framework/cmake/graphengine.cmake b/tests/framework/cmake/graphengine.cmake index 81aa00cc..3c18b560 100644 --- a/tests/framework/cmake/graphengine.cmake +++ b/tests/framework/cmake/graphengine.cmake @@ -150,7 +150,7 @@ set_target_properties(metadef_graph PROPERTIES CXX_STANDARD 11) # ---- Target : Local engine ---- -add_library(ge_local_engine SHARED ${LOCAL_ENGINE_SRC} ${METADEF_REGISTER_SRCS}) +add_library(ge_local_engine SHARED ${LOCAL_ENGINE_SRC}) target_include_directories(ge_local_engine PUBLIC @@ -169,38 +169,11 @@ target_compile_options(ge_local_engine PRIVATE target_link_libraries(ge_local_engine PUBLIC $ ${STUB_LIBS} - metadef_graph -lrt -ldl -lpthread -lgcov ) set_target_properties(ge_local_engine PROPERTIES CXX_STANDARD 11) -# ---- Target : Host engine ---- - -add_library(host_cpu_engine SHARED ${HOST_ENGINE_SRC}) - -target_include_directories(host_cpu_engine - PUBLIC - "${INCLUDE_DIRECTORIES}" - "${GE_CODE_DIR}/ge/host_cpu_engine" -) - -target_compile_definitions(host_cpu_engine PRIVATE - google=ascend_private - FMK_SUPPORT_DUMP -) - -target_compile_options(host_cpu_engine PRIVATE - -g --coverage -fprofile-arcs -ftest-coverage - -Werror=format -) - -target_link_libraries(host_cpu_engine PUBLIC - $ ${STUB_LIBS} metadef_graph -lrt -ldl -lpthread -lgcov -) - -set_target_properties(host_cpu_engine PROPERTIES CXX_STANDARD 11) - # ---- Target : engine plugin---- # @@ -273,4 +246,4 @@ target_link_libraries(graphengine PUBLIC ) set_target_properties(graphengine PROPERTIES CXX_STANDARD 11) -add_dependencies(graphengine host_cpu_engine ge_local_engine nnengine engine_conf.json optimizer_priority.pbtxt) +add_dependencies(graphengine ge_local_engine nnengine engine_conf.json optimizer_priority.pbtxt) diff --git a/tests/framework/ge_graph_dsl/include/ge_graph_dsl/op_desc/op_desc_cfg_box.h b/tests/framework/ge_graph_dsl/include/ge_graph_dsl/op_desc/op_desc_cfg_box.h index af3a1971..2be05972 100644 --- a/tests/framework/ge_graph_dsl/include/ge_graph_dsl/op_desc/op_desc_cfg_box.h +++ b/tests/framework/ge_graph_dsl/include/ge_graph_dsl/op_desc/op_desc_cfg_box.h @@ -21,6 +21,7 @@ #include "ge_graph_dsl/ge.h" #include "ge_graph_dsl/op_desc/op_box.h" #include "ge_graph_dsl/op_desc/op_desc_cfg.h" +#include "graph/ge_attr_value.h" #include "graph/op_desc.h" GE_NS_BEGIN @@ -29,19 +30,32 @@ struct OpDescCfgBox : OpBox, private OpDescCfg { OpDescCfgBox(const OpType &opType); OpDescCfgBox &InCnt(int in_cnt); OpDescCfgBox &OutCnt(int out_cnt); + OpDescCfgBox &ParentNodeIndex(int node_index); OpDescCfgBox &TensorDesc(Format format = FORMAT_NCHW, DataType data_type = DT_FLOAT, - std::vector shape = {1, 1, 224, 224}); - template - OpDescCfgBox& Attr(const std::string &name, Type value) { - auto attrvalue = ge::GeAttrValue::CreateFrom(value); - attrs_.emplace(std::make_pair(name, attrvalue)); - return *this; - } + std::vector shape = {1, 1, 224, 224}); + OpDescCfgBox &Weight(GeTensorPtr &); - private: + template + OpDescCfgBox &Attr(const std::string &name, Type &&value) { + auto attrvalue = ge::GeAttrValue::CreateFrom(std::forward(value)); + attrs_.emplace(std::make_pair(name, attrvalue)); + return *this; + } + + template + OpDescCfgBox &Attr(const std::string &name, Type &value) { + auto attrvalue = ge::GeAttrValue::CreateFrom(value); + attrs_.emplace(std::make_pair(name, attrvalue)); + return *this; + } + + OpDescCfgBox &Attr(const std::string &name, int value); + OpDescCfgBox &Attr(const std::string &name, const char *value); OpDescPtr Build(const ::EG_NS::NodeId &id) const override; - void UpdateAttrs(OpDescPtr&) const; - std::map attrs_; + + private: + void UpdateAttrs(OpDescPtr &) const; + std::map attrs_; }; #define OP_CFG(optype) ::GE_NS::OpDescCfgBox(optype) diff --git a/tests/framework/ge_graph_dsl/src/op_desc_cfg_box.cc b/tests/framework/ge_graph_dsl/src/op_desc_cfg_box.cc index fc2a6c1c..be7cd831 100644 --- a/tests/framework/ge_graph_dsl/src/op_desc_cfg_box.cc +++ b/tests/framework/ge_graph_dsl/src/op_desc_cfg_box.cc @@ -17,8 +17,8 @@ #include "ge_graph_dsl/op_desc/op_desc_cfg_box.h" #include "easy_graph/infra/status.h" #include "ge_graph_dsl/op_desc/op_desc_cfg_repo.h" -#include "ge_graph_dsl/op_desc/op_desc_cfg.h" #include "external/graph/gnode.h" +#include "graph/debug/ge_attr_define.h" #include "graph/ge_tensor.h" using ::EG_NS::Status; @@ -44,6 +44,26 @@ OpDescCfgBox &OpDescCfgBox::OutCnt(int out_cnt) { return *this; } +OpDescCfgBox &OpDescCfgBox::ParentNodeIndex(int node_index) { + this->Attr(ATTR_NAME_PARENT_NODE_INDEX, node_index); + return *this; +} + +OpDescCfgBox &OpDescCfgBox::Attr(const std::string &name, int value) { + this->Attr(name, (int64_t)value); + return *this; +} + +OpDescCfgBox &OpDescCfgBox::Attr(const std::string &name, const char *value) { + this->Attr(name, std::string(value)); + return *this; +} + +OpDescCfgBox &OpDescCfgBox::Weight(GeTensorPtr &tensor_ptr) { + this->Attr(ATTR_NAME_WEIGHTS, tensor_ptr); + return *this; +} + OpDescCfgBox &OpDescCfgBox::TensorDesc(Format format, DataType data_type, std::vector shape) { default_tensor_.format_ = format; default_tensor_.data_type_ = data_type; @@ -51,10 +71,9 @@ OpDescCfgBox &OpDescCfgBox::TensorDesc(Format format, DataType data_type, std::v return *this; } -void OpDescCfgBox::UpdateAttrs(OpDescPtr& op_desc) const { - std::for_each(attrs_.begin(), attrs_.end(), [&op_desc](const auto &attr){ - op_desc->SetAttr(attr.first, attr.second); - }); +void OpDescCfgBox::UpdateAttrs(OpDescPtr &op_desc) const { + std::for_each(attrs_.begin(), attrs_.end(), + [&op_desc](const auto &attr) { op_desc->SetAttr(attr.first, attr.second); }); } OpDescPtr OpDescCfgBox::Build(const ::EG_NS::NodeId &id) const { diff --git a/tests/framework/ge_graph_dsl/tests/op_desc_config_test.cc b/tests/framework/ge_graph_dsl/tests/op_desc_config_test.cc new file mode 100644 index 00000000..eee5d7c2 --- /dev/null +++ b/tests/framework/ge_graph_dsl/tests/op_desc_config_test.cc @@ -0,0 +1,75 @@ +/** + * Copyright 2021 Huawei Technologies Co., Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "gtest/gtest.h" +#include "framework/common/types.h" +#include "graph/debug/ge_attr_define.h" +#include "ge_graph_dsl/op_desc/op_desc_cfg_box.h" +#include "graph/ge_tensor.h" +#include "graph/utils/attr_utils.h" +GE_NS_BEGIN + +class OpDescCfgTest : public testing::Test {}; + +TEST_F(OpDescCfgTest, test_attr_set_string_success) { + auto op_ptr = OP_CFG(DATA).Attr(ENTER_ATTR_FRAME_NAME, "1").Build("data1"); + + ge::GeAttrValue ret; + op_ptr->GetAttr(ENTER_ATTR_FRAME_NAME, ret); + std::string value; + ret.GetValue(value); + + ASSERT_EQ(value, "1"); +} + +TEST_F(OpDescCfgTest, test_attr_set_int_success) { + auto op_ptr = OP_CFG(DATA).Attr(ENTER_ATTR_FRAME_NAME, 2).Build("data1"); + + ge::GeAttrValue ret; + op_ptr->GetAttr(ENTER_ATTR_FRAME_NAME, ret); + int64_t value; + ret.GetValue(value); + + ASSERT_EQ(value, 2); +} + +TEST_F(OpDescCfgTest, test_attr_set_perent_node_index_success) { + auto op_ptr = OP_CFG(DATA).ParentNodeIndex(2).Build("data1"); + + ge::GeAttrValue ret; + op_ptr->GetAttr(ATTR_NAME_PARENT_NODE_INDEX, ret); + int64_t value; + ret.GetValue(value); + + ASSERT_EQ(value, 2); +} + +TEST_F(OpDescCfgTest, test_attr_set_weight_success) { + int64_t dims_size = 1; + vector data_vec = {5}; + for_each(data_vec.begin(), data_vec.end(), [&](int64_t &data) { dims_size *= data; }); + vector data_value_vec(dims_size, 1); + GeTensorDesc data_tensor_desc(GeShape(data_vec), FORMAT_NCHW, DT_INT32); + GeTensorPtr data_tensor = std::make_shared(data_tensor_desc, (uint8_t *)data_value_vec.data(), + data_value_vec.size() * sizeof(int32_t)); + + auto op_ptr = OP_CFG(CONSTANT).Weight(data_tensor).Build("const1"); + + ConstGeTensorPtr tensor_value; + ASSERT_TRUE(AttrUtils::GetTensor(op_ptr, ge::ATTR_NAME_WEIGHTS, tensor_value)); + ASSERT_EQ(tensor_value->GetTensorDesc().GetDataType(), DT_INT32); +} + +GE_NS_END diff --git a/tests/framework/ge_graph_dsl/tests/stub/optype_stub.cc b/tests/framework/ge_graph_dsl/tests/stub/optype_stub.cc index b83d68fc..071f8c36 100644 --- a/tests/framework/ge_graph_dsl/tests/stub/optype_stub.cc +++ b/tests/framework/ge_graph_dsl/tests/stub/optype_stub.cc @@ -23,6 +23,7 @@ GE_NS_BEGIN REGISTER_OPTYPE_DEFINE(DATA, "Data"); REGISTER_OPTYPE_DEFINE(HCOMALLGATHER, "HcomAllGather"); REGISTER_OPTYPE_DEFINE(VARIABLE, "Variable"); +REGISTER_OPTYPE_DEFINE(CONSTANT, "Const"); REGISTER_OPTYPE_DEFINE(CONSTANTOP, "Constant"); REGISTER_OPTYPE_DEFINE(LESS, "Less"); REGISTER_OPTYPE_DEFINE(MUL, "Mul"); diff --git a/tests/framework/ge_running_env/CMakeLists.txt b/tests/framework/ge_running_env/CMakeLists.txt new file mode 100644 index 00000000..deac4e03 --- /dev/null +++ b/tests/framework/ge_running_env/CMakeLists.txt @@ -0,0 +1,18 @@ +# Copyright 2021 Huawei Technologies Co., Ltd +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================ + +add_subdirectory(include) +add_subdirectory(src) +add_subdirectory(tests) \ No newline at end of file diff --git a/tests/framework/ge_running_env/include/CMakeLists.txt b/tests/framework/ge_running_env/include/CMakeLists.txt new file mode 100644 index 00000000..b71b0578 --- /dev/null +++ b/tests/framework/ge_running_env/include/CMakeLists.txt @@ -0,0 +1,17 @@ +# Copyright 2021 Huawei Technologies Co., Ltd +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================ + +add_library(ge_running_env_inc INTERFACE) +target_include_directories(ge_running_env_inc INTERFACE ./) diff --git a/tests/framework/stub_engine/ops_kernel_store/op/host_op.h b/tests/framework/ge_running_env/include/ge_running_env/env_installer.h similarity index 52% rename from tests/framework/stub_engine/ops_kernel_store/op/host_op.h rename to tests/framework/ge_running_env/include/ge_running_env/env_installer.h index 464df47a..79b65137 100644 --- a/tests/framework/stub_engine/ops_kernel_store/op/host_op.h +++ b/tests/framework/ge_running_env/include/ge_running_env/env_installer.h @@ -14,23 +14,22 @@ * limitations under the License. */ -#ifndef GE_HOST_CPU_ENGINE_OPS_KERNEL_STORE_OP_HOST_OP_H_ -#define GE_HOST_CPU_ENGINE_OPS_KERNEL_STORE_OP_HOST_OP_H_ +#ifndef H1D9F4FDE_BB21_4DE4_AC7E_751920B45039 +#define H1D9F4FDE_BB21_4DE4_AC7E_751920B45039 -#include "stub_engine/ops_kernel_store/op/op.h" +#include "fake_ns.h" +#include "opskernel_manager/ops_kernel_manager.h" +#include "register/ops_kernel_builder_registry.h" -namespace ge { -namespace st { -class GE_FUNC_VISIBILITY HostOp : public Op { - public: - HostOp(const Node &node, RunContext &run_context) : Op(node, run_context) {} - ~HostOp() override = default; - HostOp &operator=(const HostOp &op) = delete; - HostOp(const HostOp &op) = delete; +FAKE_NS_BEGIN - Status Run() override; +struct EnvInstaller { + virtual void InstallTo(std::map&) const {} + virtual void InstallTo(std::map&) const {} + virtual void InstallTo(std::map&) const {} + virtual void Install() const {} }; -} // namespace st -} // namespace ge -#endif // GE_HOST_CPU_ENGINE_OPS_KERNEL_STORE_OP_HOST_OP_H_ +FAKE_NS_END + +#endif diff --git a/tests/framework/ge_running_env/include/ge_running_env/fake_engine.h b/tests/framework/ge_running_env/include/ge_running_env/fake_engine.h new file mode 100644 index 00000000..c4207223 --- /dev/null +++ b/tests/framework/ge_running_env/include/ge_running_env/fake_engine.h @@ -0,0 +1,56 @@ +/** + * Copyright 2021 Huawei Technologies Co., Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef HAF5E9BF2_752F_4E03_B0A5_E1B912A5FA24 +#define HAF5E9BF2_752F_4E03_B0A5_E1B912A5FA24 + +#include +#include "fake_ns.h" +#include "ge_running_env/env_installer.h" +#include "common/opskernel/ops_kernel_info_types.h" +#include "opskernel_manager/ops_kernel_manager.h" +#include "register/ops_kernel_builder_registry.h" +#include "fake_ops_kernel_builder.h" +#include "fake_ops_kernel_info_store.h" + +FAKE_NS_BEGIN + +using FakeOpsKernelBuilderPtr = std::shared_ptr; +using FakeOpsKernelInfoStorePtr = std::shared_ptr; + +struct FakeEngine : EnvInstaller { + FakeEngine(const std::string& engine_name); + FakeEngine& KernelBuilder(FakeOpsKernelBuilderPtr); + FakeEngine& KernelInfoStore(FakeOpsKernelInfoStorePtr); + FakeEngine& KernelInfoStore(const std::string&); + + private: + void InstallTo(std::map&) const override; + void InstallTo(std::map&) const override; + + private: + template + void InstallFor(std::map& maps, const std::map>&) const; + + private: + std::string engine_name_; + std::set info_store_names_; + std::map custom_builders_; + std::map custom_info_stores_; +}; + +FAKE_NS_END + +#endif diff --git a/tests/framework/ge_running_env/include/ge_running_env/fake_ns.h b/tests/framework/ge_running_env/include/ge_running_env/fake_ns.h new file mode 100644 index 00000000..c802e109 --- /dev/null +++ b/tests/framework/ge_running_env/include/ge_running_env/fake_ns.h @@ -0,0 +1,28 @@ +/** + * Copyright 2021 Huawei Technologies Co., Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef H7AEFF0EA_9FDE_487F_8562_2917A2D48EA2 +#define H7AEFF0EA_9FDE_487F_8562_2917A2D48EA2 + +#define FAKE_NS ge +#define FAKE_NS_BEGIN namespace FAKE_NS { +#define FAKE_NS_END } +#define USING_STUB_NS using namespace FAKE_NS; +#define FWD_DECL_STUB(type) \ + namespace FAKE_NS { \ + struct type; \ + } + +#endif diff --git a/tests/framework/ge_running_env/include/ge_running_env/fake_op.h b/tests/framework/ge_running_env/include/ge_running_env/fake_op.h new file mode 100644 index 00000000..cc442cdb --- /dev/null +++ b/tests/framework/ge_running_env/include/ge_running_env/fake_op.h @@ -0,0 +1,49 @@ +/** + * Copyright 2021 Huawei Technologies Co., Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef H737AD661_27C0_400F_8B08_29701308C5D0 +#define H737AD661_27C0_400F_8B08_29701308C5D0 + +#include +#include +#include "fake_ns.h" +#include "ge_running_env/env_installer.h" +#include "graph/operator_factory.h" + +FAKE_NS_BEGIN + +struct FakeOp : EnvInstaller { + FakeOp(const std::string& op_type); + + FakeOp& Inputs(const std::vector&); + FakeOp& Outputs(const std::vector&); + FakeOp& InferShape(InferShapeFunc); + FakeOp& InfoStoreAndBuilder(const std::string&); + + private: + void Install() const override; + void InstallTo(std::map&) const override; + + private: + const std::string op_type_; + std::vector inputs_; + std::vector outputs_; + InferShapeFunc info_fun_; + std::set info_store_names_; +}; + +FAKE_NS_END + +#endif /* H737AD661_27C0_400F_8B08_29701308C5D0 */ diff --git a/tests/framework/stub_engine/ops_kernel_store/stub_ops_kernel_builder.h b/tests/framework/ge_running_env/include/ge_running_env/fake_ops_kernel_builder.h similarity index 59% rename from tests/framework/stub_engine/ops_kernel_store/stub_ops_kernel_builder.h rename to tests/framework/ge_running_env/include/ge_running_env/fake_ops_kernel_builder.h index 62dab542..acfe5e41 100644 --- a/tests/framework/stub_engine/ops_kernel_store/stub_ops_kernel_builder.h +++ b/tests/framework/ge_running_env/include/ge_running_env/fake_ops_kernel_builder.h @@ -13,39 +13,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#ifndef H39E4E719_91F4_4D0F_BA4F_6BA56CB1E20D +#define H39E4E719_91F4_4D0F_BA4F_6BA56CB1E20D -#ifndef GE_HOST_CPU_ENGINE_OPS_KERNEL_STORE_HOST_CPU_OPS_KERNEL_BUILDER_H_ -#define GE_HOST_CPU_ENGINE_OPS_KERNEL_STORE_HOST_CPU_OPS_KERNEL_BUILDER_H_ +#include "fake_ns.h" +#include "common/opskernel/ops_kernel_builder.h" +#include "info_store_holder.h" -#if defined(_MSC_VER) -#ifdef FUNC_VISIBILITY -#define GE_FUNC_VISIBILITY _declspec(dllexport) -#else -#define GE_FUNC_VISIBILITY -#endif -#else -#ifdef FUNC_VISIBILITY -#define GE_FUNC_VISIBILITY __attribute__((visibility("default"))) -#else -#define GE_FUNC_VISIBILITY -#endif -#endif +FAKE_NS_BEGIN -#include "common/opskernel/ops_kernel_builder.h" +struct FakeOpsKernelBuilder : OpsKernelBuilder, InfoStoreHolder { + FakeOpsKernelBuilder(const std::string &kernel_lib_name); + FakeOpsKernelBuilder(); -namespace ge { -namespace st { -class GE_FUNC_VISIBILITY StubOpsKernelBuilder : public OpsKernelBuilder { - public: + private: Status Initialize(const map &options) override; - Status Finalize() override; - Status CalcOpRunningParam(Node &node) override; - Status GenerateTask(const Node &node, RunContext &context, std::vector &tasks) override; }; -} // namespace st -} // namespace ge -#endif // GE_HOST_CPU_ENGINE_OPS_KERNEL_STORE_HOST_CPU_OPS_KERNEL_BUILDER_H_ +FAKE_NS_END + +#endif diff --git a/tests/framework/ge_running_env/include/ge_running_env/fake_ops_kernel_info_store.h b/tests/framework/ge_running_env/include/ge_running_env/fake_ops_kernel_info_store.h new file mode 100644 index 00000000..4a8ab9dc --- /dev/null +++ b/tests/framework/ge_running_env/include/ge_running_env/fake_ops_kernel_info_store.h @@ -0,0 +1,39 @@ +/** + * Copyright 2021 Huawei Technologies Co., Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef H1EBABA85_7056_48F0_B496_E4DB68E5FED3 +#define H1EBABA85_7056_48F0_B496_E4DB68E5FED3 + +#include "fake_ns.h" +#include "common/opskernel/ops_kernel_info_store.h" +#include "ge/ge_api_types.h" +#include "info_store_holder.h" + +FAKE_NS_BEGIN + +struct FakeOpsKernelInfoStore : OpsKernelInfoStore, InfoStoreHolder { + FakeOpsKernelInfoStore(const std::string &kernel_lib_name); + FakeOpsKernelInfoStore(); + + private: + Status Initialize(const std::map &options) override; + Status Finalize() override; + bool CheckSupported(const OpDescPtr &op_desc, std::string &reason) const override; + void GetAllOpsKernelInfo(std::map &infos) const override; +}; + +FAKE_NS_END + +#endif diff --git a/tests/framework/ge_running_env/include/ge_running_env/ge_running_env_faker.h b/tests/framework/ge_running_env/include/ge_running_env/ge_running_env_faker.h new file mode 100644 index 00000000..6d325c6a --- /dev/null +++ b/tests/framework/ge_running_env/include/ge_running_env/ge_running_env_faker.h @@ -0,0 +1,45 @@ +/** + * Copyright 2021 Huawei Technologies Co., Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef H99C11FC4_700E_4D4D_B073_7808FA88BEBC +#define H99C11FC4_700E_4D4D_B073_7808FA88BEBC + +#include "ge_running_env/fake_engine.h" +#include "fake_ns.h" +#include "opskernel_manager/ops_kernel_manager.h" +#include "register/ops_kernel_builder_registry.h" + +FAKE_NS_BEGIN + +struct GeRunningEnvFaker { + GeRunningEnvFaker(); + GeRunningEnvFaker &Reset(); + GeRunningEnvFaker &Install(const EnvInstaller &); + GeRunningEnvFaker &InstallDefault(); + static void BackupEnv(); + + private: + void flush(); + + private: + std::map> &op_kernel_info_; + std::map &ops_kernel_info_stores_; + std::map &ops_kernel_optimizers_; + std::map &ops_kernel_builders_; +}; + +FAKE_NS_END + +#endif /* H99C11FC4_700E_4D4D_B073_7808FA88BEBC */ diff --git a/tests/framework/stub_engine/ops_kernel_store/op/op.h b/tests/framework/ge_running_env/include/ge_running_env/info_store_holder.h similarity index 51% rename from tests/framework/stub_engine/ops_kernel_store/op/op.h rename to tests/framework/ge_running_env/include/ge_running_env/info_store_holder.h index 3741567a..85b6c75f 100644 --- a/tests/framework/stub_engine/ops_kernel_store/op/op.h +++ b/tests/framework/ge_running_env/include/ge_running_env/info_store_holder.h @@ -13,33 +13,27 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#ifndef H7992249B_058D_40A1_94EA_52BBCB76434E +#define H7992249B_058D_40A1_94EA_52BBCB76434E -#ifndef GE_HOST_CPU_ENGINE_OPS_KERNEL_STORE_OP_OP_H_ -#define GE_HOST_CPU_ENGINE_OPS_KERNEL_STORE_OP_OP_H_ - -#include -#include -#include -#include "common/ge_inner_error_codes.h" +#include "fake_ns.h" #include "common/opskernel/ops_kernel_info_types.h" -#include "graph/node.h" -namespace ge { -namespace st { -/** - * The base class for all op. - */ -class GE_FUNC_VISIBILITY Op { - public: - Op(const Node &node, RunContext &run_context) : run_context_(run_context), node_(node) {} - virtual ~Op() = default; - virtual Status Run() = 0; +FAKE_NS_BEGIN + +struct InfoStoreHolder { + InfoStoreHolder(); + InfoStoreHolder(const std::string&); + void EngineName(std::string engine_name); + void RegistOp(std::string op_type); + std::string GetLibName(); protected: - const RunContext &run_context_; - const Node &node_; + std::map op_info_map_; + std::string kernel_lib_name_; + std::string engine_name_; }; -} // namespace st -} // namespace ge -#endif // GE_HOST_CPU_ENGINE_OPS_KERNEL_STORE_OP_OP_H_ +FAKE_NS_END + +#endif diff --git a/tests/framework/ge_running_env/src/CMakeLists.txt b/tests/framework/ge_running_env/src/CMakeLists.txt new file mode 100644 index 00000000..ae068bd3 --- /dev/null +++ b/tests/framework/ge_running_env/src/CMakeLists.txt @@ -0,0 +1,45 @@ +# Copyright 2021 Huawei Technologies Co., Ltd +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================ + +file(GLOB_RECURSE SOURCES CONFIGURE_DEPENDS "*.cc" "*.CC" "*.cpp" "*.CPP" "*.c++") + +# ---- Target : stub Host engine ---- +add_library(ge_with_env STATIC ${SOURCES}) + +target_include_directories(ge_with_env + PUBLIC + include + ) + +target_include_directories(ge_with_env + PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR} + ) + +target_compile_definitions(ge_with_env PRIVATE + google=ascend_private + FMK_SUPPORT_DUMP + ) + +target_compile_options(ge_with_env PRIVATE + -g --coverage -fprofile-arcs -ftest-coverage + -Werror=format + ) + +target_link_libraries(ge_with_env PUBLIC + $ ge_running_env_inc graphengine -lrt -ldl -lpthread -lgcov + ) + +set_target_properties(ge_with_env PROPERTIES CXX_STANDARD 17) diff --git a/tests/framework/ge_running_env/src/engine/fake_engine.cc b/tests/framework/ge_running_env/src/engine/fake_engine.cc new file mode 100644 index 00000000..4b8fedbc --- /dev/null +++ b/tests/framework/ge_running_env/src/engine/fake_engine.cc @@ -0,0 +1,81 @@ +/** + * Copyright 2021 Huawei Technologies Co., Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ge_running_env/fake_engine.h" +#include "ge_running_env/fake_ops_kernel_builder.h" +#include "ge_running_env/fake_ops_kernel_info_store.h" +#include "opskernel_manager/ops_kernel_manager.h" + +FAKE_NS_BEGIN + +FakeEngine::FakeEngine(const std::string &engine_name) : engine_name_(engine_name) {} + +FakeEngine &FakeEngine::KernelInfoStore(const std::string &info_store) { + info_store_names_.insert(info_store); + return *this; +} + +FakeEngine &FakeEngine::KernelInfoStore(FakeOpsKernelInfoStorePtr ptr) { + info_store_names_.insert(ptr->GetLibName()); + custom_info_stores_.insert(std::make_pair(ptr->GetLibName(), ptr)); + return *this; +} + +FakeEngine &FakeEngine::KernelBuilder(FakeOpsKernelBuilderPtr builder) { + info_store_names_.insert(builder->GetLibName()); + custom_builders_.insert(std::make_pair(builder->GetLibName(), builder)); + return *this; +} + +namespace { +template +void InstallDefault(std::map &maps, const std::string &info_store_name, + const std::string &engine_name) { + auto parent_obj = std::make_shared(info_store_name); + if (parent_obj == nullptr) { + return; + } + parent_obj->EngineName(engine_name); + maps.insert(std::make_pair(parent_obj->GetLibName(), parent_obj)); +} +} // namespace + +template +void FakeEngine::InstallFor(std::map &maps, + const std::map> &child_maps) const { + if (info_store_names_.empty()) { + InstallDefault(maps, engine_name_, engine_name_); + } else { + for (auto &info_store_name : info_store_names_) { + auto iter = child_maps.find(info_store_name); + if (iter == child_maps.end()) { + InstallDefault(maps, info_store_name, engine_name_); + } else { + maps.insert(std::make_pair(iter->second->GetLibName(), iter->second)); + } + } + } +} + +void FakeEngine::InstallTo(std::map &ops_kernel_info_stores) const { + InstallFor(ops_kernel_info_stores, custom_info_stores_); +} + +void FakeEngine::InstallTo(std::map &ops_kernel_builders) const { + InstallFor(ops_kernel_builders, custom_builders_); +} + +FAKE_NS_END diff --git a/tests/framework/stub_engine/ops_kernel_store/stub_ops_kernel_builder.cc b/tests/framework/ge_running_env/src/engine/fake_ops_kernel_builder.cc similarity index 73% rename from tests/framework/stub_engine/ops_kernel_store/stub_ops_kernel_builder.cc rename to tests/framework/ge_running_env/src/engine/fake_ops_kernel_builder.cc index 2de8691f..77472249 100644 --- a/tests/framework/stub_engine/ops_kernel_store/stub_ops_kernel_builder.cc +++ b/tests/framework/ge_running_env/src/engine/fake_ops_kernel_builder.cc @@ -14,40 +14,25 @@ * limitations under the License. */ -#include "stub_ops_kernel_builder.h" -#include +#include "ge_running_env/fake_ops_kernel_builder.h" +#include "graph/utils/node_utils.h" #include "common/ge_inner_error_codes.h" #include "ge/ge_api_types.h" #include "graph/utils/node_utils.h" #include "graph/utils/tensor_utils.h" #include "graph/utils/type_utils.h" -#include #include "framework/common/debug/ge_log.h" -#include "host_cpu_engine/common/constant/constant.h" -#include "register/ops_kernel_builder_registry.h" -#include "inc/st_types.h" +FAKE_NS_BEGIN -namespace ge { -namespace st { -REGISTER_OPS_KERNEL_BUILDER(kAicoreLibName, StubOpsKernelBuilder); -REGISTER_OPS_KERNEL_BUILDER(kVectorLibName, StubOpsKernelBuilder); -REGISTER_OPS_KERNEL_BUILDER(kAicpuLibName, StubOpsKernelBuilder); -REGISTER_OPS_KERNEL_BUILDER(kAicpuAscendLibName, StubOpsKernelBuilder); -REGISTER_OPS_KERNEL_BUILDER(kHcclLibName, StubOpsKernelBuilder); -REGISTER_OPS_KERNEL_BUILDER(kRTSLibName, StubOpsKernelBuilder); +FakeOpsKernelBuilder::FakeOpsKernelBuilder(const std::string &info_store_name) : InfoStoreHolder(info_store_name) {} +FakeOpsKernelBuilder::FakeOpsKernelBuilder() : InfoStoreHolder() {} -Status StubOpsKernelBuilder::Finalize() { - return SUCCESS; -} -Status StubOpsKernelBuilder::Initialize(const map &options) { - return SUCCESS; -} +Status FakeOpsKernelBuilder::Finalize() { return SUCCESS; } +Status FakeOpsKernelBuilder::Initialize(const map &options) { return SUCCESS; } -Status StubOpsKernelBuilder::CalcOpRunningParam(Node &ge_node) { +Status FakeOpsKernelBuilder::CalcOpRunningParam(Node &ge_node) { OpDescPtr op_desc = ge_node.GetOpDesc(); if (op_desc == nullptr) { - GELOGE(FAILED, "[Get][OpDesc]CalcOpRunningParam failed, as op desc is null"); - REPORT_INNER_ERROR("E19999", "GetOpDesc failed."); return FAILED; } @@ -86,9 +71,9 @@ Status StubOpsKernelBuilder::CalcOpRunningParam(Node &ge_node) { name.c_str(), type.c_str(), i, output_mem_size, TypeUtils::FormatToSerialString(format).c_str(), TypeUtils::DataTypeToSerialString(data_type).c_str()); REPORT_CALL_ERROR( - "E19999", "CalcTensorMemSize failed for op[%s:%s] out[%zu] mem size, mem_size=%ld, format=%s, data_type=%s.", - name.c_str(), type.c_str(), i, output_mem_size, TypeUtils::FormatToSerialString(format).c_str(), - TypeUtils::DataTypeToSerialString(data_type).c_str()); + "E19999", "CalcTensorMemSize failed for op[%s:%s] out[%zu] mem size, mem_size=%ld, format=%s, data_type=%s.", + name.c_str(), type.c_str(), i, output_mem_size, TypeUtils::FormatToSerialString(format).c_str(), + TypeUtils::DataTypeToSerialString(data_type).c_str()); return FAILED; } GELOGI("Calc op[%s:%s] out[%zu] mem size is %ld, format=%s, data_type=%s.", name.c_str(), type.c_str(), i, @@ -111,9 +96,9 @@ Status StubOpsKernelBuilder::CalcOpRunningParam(Node &ge_node) { return SUCCESS; } -Status StubOpsKernelBuilder::GenerateTask(const Node &node, RunContext &context, vector &tasks) { +Status FakeOpsKernelBuilder::GenerateTask(const Node &node, RunContext &context, vector &tasks) { // no need to generate device task return SUCCESS; } -} // namespace st -} // namespace ge \ No newline at end of file + +FAKE_NS_END diff --git a/tests/framework/ge_running_env/src/engine/fake_ops_kernel_info_store.cc b/tests/framework/ge_running_env/src/engine/fake_ops_kernel_info_store.cc new file mode 100644 index 00000000..348e1334 --- /dev/null +++ b/tests/framework/ge_running_env/src/engine/fake_ops_kernel_info_store.cc @@ -0,0 +1,42 @@ +/** + * Copyright 2021 Huawei Technologies Co., Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "external/ge/ge_api_error_codes.h" +#include "ge_running_env/fake_ops_kernel_info_store.h" + +FAKE_NS_BEGIN + +FakeOpsKernelInfoStore::FakeOpsKernelInfoStore(const std::string &info_store_name) : InfoStoreHolder(info_store_name) {} + +FakeOpsKernelInfoStore::FakeOpsKernelInfoStore() : InfoStoreHolder() {} + +Status FakeOpsKernelInfoStore::Finalize() { + op_info_map_.clear(); + return SUCCESS; +} + +Status FakeOpsKernelInfoStore::Initialize(const std::map &options) { return SUCCESS; } + +void FakeOpsKernelInfoStore::GetAllOpsKernelInfo(map &infos) const { infos = op_info_map_; } + +bool FakeOpsKernelInfoStore::CheckSupported(const OpDescPtr &op_desc, std::string &) const { + if (op_desc == nullptr) { + return false; + } + return op_info_map_.count(op_desc->GetType()) > 0; +} + +FAKE_NS_END diff --git a/tests/framework/ge_running_env/src/engine/info_store_holder.cc b/tests/framework/ge_running_env/src/engine/info_store_holder.cc new file mode 100644 index 00000000..231af93a --- /dev/null +++ b/tests/framework/ge_running_env/src/engine/info_store_holder.cc @@ -0,0 +1,49 @@ +/** + * Copyright 2021 Huawei Technologies Co., Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ge_running_env/info_store_holder.h" +FAKE_NS_BEGIN + +namespace { +std::string GenStoreName() { + static int store_id = 0; + return "store_" + std::to_string(store_id++); +} +} // namespace + +InfoStoreHolder::InfoStoreHolder(const std::string& kernel_lib_name) : kernel_lib_name_(kernel_lib_name) {} + +InfoStoreHolder::InfoStoreHolder() : kernel_lib_name_(GenStoreName()) {} + +void InfoStoreHolder::RegistOp(std::string op_type) { + OpInfo default_op_info = {.engine = engine_name_, + .opKernelLib = kernel_lib_name_, + .computeCost = 0, + .flagPartial = false, + .flagAsync = false, + .isAtomic = false}; + + auto iter = op_info_map_.find(op_type); + if (iter == op_info_map_.end()) { + op_info_map_.emplace(op_type, default_op_info); + } +} + +void InfoStoreHolder::EngineName(std::string engine_name) { engine_name_ = engine_name; } + +std::string InfoStoreHolder::GetLibName() { return kernel_lib_name_; } + +FAKE_NS_END diff --git a/tests/framework/ge_running_env/src/env/ge_default_running_env.cc b/tests/framework/ge_running_env/src/env/ge_default_running_env.cc new file mode 100644 index 00000000..ab705f55 --- /dev/null +++ b/tests/framework/ge_running_env/src/env/ge_default_running_env.cc @@ -0,0 +1,56 @@ +/** + * Copyright 2021 Huawei Technologies Co., Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ge_default_running_env.h" +#include "ge_running_env/ge_running_env_faker.h" +#include "ge_running_env/fake_op.h" + +FAKE_NS_BEGIN +namespace { +std::vector default_engines = {FakeEngine("AIcoreEngine").KernelInfoStore("AiCoreLib"), + FakeEngine("VectorEngine").KernelInfoStore("VectorLib"), + FakeEngine("DNN_VM_AICPU").KernelInfoStore("AicpuLib"), + FakeEngine("DNN_VM_AICPU_ASCEND").KernelInfoStore("AicpuAscendLib"), + FakeEngine("DNN_HCCL").KernelInfoStore("HcclLib"), + FakeEngine("DNN_VM_RTS").KernelInfoStore("RTSLib")}; + +std::vector fake_ops = { + FakeOp(ENTER).InfoStoreAndBuilder("RTSLib"), FakeOp(MERGE).InfoStoreAndBuilder("RTSLib"), + FakeOp(SWITCH).InfoStoreAndBuilder("RTSLib"), FakeOp(LOOPCOND).InfoStoreAndBuilder("RTSLib"), + FakeOp(STREAMMERGE).InfoStoreAndBuilder("RTSLib"), FakeOp(STREAMSWITCH).InfoStoreAndBuilder("RTSLib"), + FakeOp(STREAMACTIVE).InfoStoreAndBuilder("RTSLib"), FakeOp(EXIT).InfoStoreAndBuilder("RTSLib"), + + FakeOp(LESS).InfoStoreAndBuilder("AiCoreLib"), FakeOp(NEXTITERATION).InfoStoreAndBuilder("AiCoreLib"), + FakeOp(CAST).InfoStoreAndBuilder("AiCoreLib"), FakeOp(TRANSDATA).InfoStoreAndBuilder("AiCoreLib"), + FakeOp(NOOP).InfoStoreAndBuilder("AiCoreLib"), FakeOp(VARIABLE).InfoStoreAndBuilder("AiCoreLib"), + FakeOp(CONSTANT).InfoStoreAndBuilder("AiCoreLib"), FakeOp(ASSIGN).InfoStoreAndBuilder("AiCoreLib"), + FakeOp(ADD).InfoStoreAndBuilder("AiCoreLib"), FakeOp(MUL).InfoStoreAndBuilder("AiCoreLib"), + FakeOp(DATA).InfoStoreAndBuilder("AiCoreLib"), FakeOp(NETOUTPUT).InfoStoreAndBuilder("AiCoreLib"), + +}; +} // namespace + +void GeDefaultRunningEnv::InstallTo(GeRunningEnvFaker& ge_env) { + for (auto& fake_engine : default_engines) { + ge_env.Install(fake_engine); + } + + for (auto& fake_op : fake_ops) { + ge_env.Install(fake_op); + } +} + +FAKE_NS_END \ No newline at end of file diff --git a/tests/framework/ge_running_env/src/env/ge_default_running_env.h b/tests/framework/ge_running_env/src/env/ge_default_running_env.h new file mode 100644 index 00000000..b93c528a --- /dev/null +++ b/tests/framework/ge_running_env/src/env/ge_default_running_env.h @@ -0,0 +1,32 @@ +/** + * Copyright 2021 Huawei Technologies Co., Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INC_5D044B8760CB41ABA108AE2E37E8EBDE +#define INC_5D044B8760CB41ABA108AE2E37E8EBDE + +#include "ge_running_env/fake_ns.h" + +FAKE_NS_BEGIN + +struct GeRunningEnvFaker; + +struct GeDefaultRunningEnv { + static void InstallTo(GeRunningEnvFaker&); +}; + +FAKE_NS_END + +#endif \ No newline at end of file diff --git a/tests/framework/ge_running_env/src/env/ge_running_env_faker.cc b/tests/framework/ge_running_env/src/env/ge_running_env_faker.cc new file mode 100644 index 00000000..2977f6b2 --- /dev/null +++ b/tests/framework/ge_running_env/src/env/ge_running_env_faker.cc @@ -0,0 +1,109 @@ +/** + * Copyright 2021 Huawei Technologies Co., Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include "external/ge/ge_api.h" +#include "opskernel_manager/ops_kernel_builder_manager.h" +#include "init/gelib.h" +#include "utility" +#include "ge_running_env/ge_running_env_faker.h" +#include "ge_default_running_env.h" +#include "ge_running_env/env_installer.h" +#include "op/fake_op_repo.h" + +FAKE_NS_BEGIN + +namespace { +OpsKernelManager& getKernelManger() { + std::shared_ptr instancePtr = ge::GELib::GetInstance(); + return instancePtr->OpsKernelManagerObj(); +} + +struct InitEnv { + static InitEnv& GetInstance() { + static InitEnv instance; + return instance; + } + + void reset(std::map& ops_kernel_info_stores, + std::map& builders) { + std::set remove_info_names; + for (auto iter : ops_kernel_info_stores) { + if (kernel_info_names.find(iter.first) == kernel_info_names.end()) { + remove_info_names.insert(iter.first); + } + } + for (auto info_name : remove_info_names) { + ops_kernel_info_stores.erase(info_name); + builders.erase(info_name); + } + } + + private: + InitEnv() { + for (auto iter : getKernelManger().GetAllOpsKernelInfoStores()) { + kernel_info_names.insert(iter.first); + } + } + + private: + std::set kernel_info_names; +}; +} // namespace + +GeRunningEnvFaker::GeRunningEnvFaker() + : op_kernel_info_(const_cast>&>(getKernelManger().GetAllOpsKernelInfo())), + ops_kernel_info_stores_( + const_cast&>(getKernelManger().GetAllOpsKernelInfoStores())), + ops_kernel_optimizers_( + const_cast&>(getKernelManger().GetAllGraphOptimizerObjs())), + ops_kernel_builders_(const_cast&>( + OpsKernelBuilderManager::Instance().GetAllOpsKernelBuilders())) { + Reset(); +} + +GeRunningEnvFaker& GeRunningEnvFaker::Reset() { + InitEnv& init_env = InitEnv::GetInstance(); + FakeOpRepo::Reset(); + init_env.reset(ops_kernel_info_stores_, ops_kernel_builders_); + flush(); + return *this; +} + +void GeRunningEnvFaker::BackupEnv() { InitEnv::GetInstance(); } + +GeRunningEnvFaker& GeRunningEnvFaker::Install(const EnvInstaller& installer) { + installer.Install(); + installer.InstallTo(ops_kernel_info_stores_); + installer.InstallTo(ops_kernel_optimizers_); + installer.InstallTo(ops_kernel_builders_); + flush(); + return *this; +} + +void GeRunningEnvFaker::flush() { + op_kernel_info_.clear(); + getKernelManger().GetOpsKernelInfo(""); +} + +GeRunningEnvFaker& GeRunningEnvFaker::InstallDefault() { + Reset(); + GeDefaultRunningEnv::InstallTo(*this); + return *this; +} + +FAKE_NS_END diff --git a/tests/framework/ge_running_env/src/op/fake_op.cc b/tests/framework/ge_running_env/src/op/fake_op.cc new file mode 100644 index 00000000..52bbee8d --- /dev/null +++ b/tests/framework/ge_running_env/src/op/fake_op.cc @@ -0,0 +1,95 @@ +/** + * Copyright 2021 Huawei Technologies Co., Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ge_running_env/fake_op.h" +#include "fake_op_repo.h" +#include "ge_running_env/info_store_holder.h" +#include "graph/operator_factory.h" + +FAKE_NS_BEGIN + +FakeOp::FakeOp(const std::string& op_type) : op_type_(op_type) {} + +FakeOp& FakeOp::Inputs(const std::vector& inputs) { + inputs_ = inputs; + return *this; +} + +FakeOp& FakeOp::Outputs(const std::vector& outputs) { + outputs_ = outputs; + return *this; +} + +FakeOp& FakeOp::InferShape(InferShapeFunc infer_fun) { + info_fun_ = infer_fun; + return *this; +} + +FakeOp& FakeOp::InfoStoreAndBuilder(const std::string& name) { + info_store_names_.insert(name); + return *this; +} + +namespace { + +void RegistOpToInfoStore(OpsKernelInfoStorePtr& info_store, const std::string& op_type) { + if (info_store == nullptr) { + return; + } + auto holder = dynamic_cast(info_store.get()); + holder->RegistOp(op_type); +} + +struct FakeOperator : Operator { + FakeOperator(const std::string& op_type) : Operator(op_type) {} + + FakeOperator& RegistInputs(const std::vector& inputs) { + for (auto& input : inputs) { + Operator::InputRegister(input); + } + return *this; + } + + FakeOperator& RegistOutputs(const std::vector& outputs) { + for (auto& output : outputs) { + Operator::OutputRegister(output); + } + return *this; + } +}; +} // namespace + +void FakeOp::InstallTo(std::map& info_stores) const { + std::for_each(info_store_names_.begin(), info_store_names_.end(), [=, &info_stores](auto& info_store_name) { + auto iter = info_stores.find(info_store_name); + if (iter != info_stores.end()) { + RegistOpToInfoStore(iter->second, op_type_); + } + }); +} + +void FakeOp::Install() const { + FakeOpRepo::Regist( + op_type_, + [op_type = this->op_type_, inputs = this->inputs_, outputs = this->outputs_](const std::string&) -> Operator { + return FakeOperator(op_type).RegistInputs(inputs).RegistOutputs(outputs); + }); + if (info_fun_) { + FakeOpRepo::Regist(op_type_, info_fun_); + } +} + +FAKE_NS_END diff --git a/tests/framework/ge_running_env/src/op/fake_op_repo.cc b/tests/framework/ge_running_env/src/op/fake_op_repo.cc new file mode 100644 index 00000000..7d571b8b --- /dev/null +++ b/tests/framework/ge_running_env/src/op/fake_op_repo.cc @@ -0,0 +1,39 @@ +/** + * Copyright 2021 Huawei Technologies Co., Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "graph/operator_factory_impl.h" +#include "ge_running_env/fake_op.h" +#include "fake_op_repo.h" + +FAKE_NS_BEGIN + +void FakeOpRepo::Reset() { + if (OperatorFactoryImpl::operator_creators_) { + OperatorFactoryImpl::operator_creators_->clear(); + } + if (OperatorFactoryImpl::operator_infershape_funcs_) { + OperatorFactoryImpl::operator_infershape_funcs_->clear(); + } +} + +void FakeOpRepo::Regist(const std::string &operator_type, const OpCreator creator) { + OperatorFactoryImpl::RegisterOperatorCreator(operator_type, creator); +} +void FakeOpRepo::Regist(const std::string &operator_type, const InferShapeFunc infer_fun) { + OperatorFactoryImpl::RegisterInferShapeFunc(operator_type, infer_fun); +} + +FAKE_NS_END \ No newline at end of file diff --git a/tests/framework/ge_running_env/src/op/fake_op_repo.h b/tests/framework/ge_running_env/src/op/fake_op_repo.h new file mode 100644 index 00000000..345515e4 --- /dev/null +++ b/tests/framework/ge_running_env/src/op/fake_op_repo.h @@ -0,0 +1,31 @@ +/** + * Copyright 2021 Huawei Technologies Co., Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef DBF6CE7CD4AC4A83BA4ED4B372FC66E4 +#define DBF6CE7CD4AC4A83BA4ED4B372FC66E4 + +#include "ge_running_env/fake_ns.h" +#include "graph/operator_factory.h" + +FAKE_NS_BEGIN + +struct FakeOpRepo { + static void Reset(); + static void Regist(const std::string &operator_type, const OpCreator); + static void Regist(const std::string &operator_type, const InferShapeFunc); +}; + +FAKE_NS_END +#endif \ No newline at end of file diff --git a/tests/framework/ge_running_env/tests/CMakeLists.txt b/tests/framework/ge_running_env/tests/CMakeLists.txt new file mode 100644 index 00000000..67a9bd70 --- /dev/null +++ b/tests/framework/ge_running_env/tests/CMakeLists.txt @@ -0,0 +1,33 @@ +# Copyright 2021 Huawei Technologies Co., Ltd +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================ + +file(GLOB_RECURSE SOURCES CONFIGURE_DEPENDS "*.cc" "*.CC" "*.cpp" "*.CPP") + +add_executable(ge_running_env_test ${SOURCES}) + +target_include_directories(ge_running_env_test + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} +) + +target_compile_options(ge_running_env_test PRIVATE + -g +) +set_target_properties(ge_running_env_test PROPERTIES CXX_STANDARD 17) + +target_link_libraries(ge_running_env_test PUBLIC gtest ge_with_env) + +include(CTest) +enable_testing() +add_test(NAME test COMMAND ge_running_env_test) \ No newline at end of file diff --git a/tests/framework/ge_running_env/tests/test_ge_running_env_faker.cc b/tests/framework/ge_running_env/tests/test_ge_running_env_faker.cc new file mode 100644 index 00000000..4429f4a7 --- /dev/null +++ b/tests/framework/ge_running_env/tests/test_ge_running_env_faker.cc @@ -0,0 +1,148 @@ +/** + * Copyright 2021 Huawei Technologies Co., Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include "graph/operator_factory_impl.h" +#include "init/gelib.h" +#include "external/ge/ge_api.h" +#include "opskernel_manager/ops_kernel_builder_manager.h" +#include "ge_running_env/fake_ops_kernel_builder.h" +#include "ge_running_env/fake_ns.h" +#include "ge_running_env/ge_running_env_faker.h" +#include "ge_running_env/fake_op.h" +FAKE_NS_BEGIN + +#define ASSERT_OPS_LIST_SIZE(list_size) \ + std::vector ops_list; \ + OperatorFactory::GetOpsTypeList(ops_list);\ + ASSERT_EQ(ops_list.size(), list_size); + +class GeRunningEvnFakerTest : public testing::Test { + protected: + void SetUp() {} + OpsKernelManager &kernel_manager = ge::GELib::GetInstance()->OpsKernelManagerObj(); + OpsKernelBuilderManager &builder_manager = OpsKernelBuilderManager::Instance(); +}; + +TEST_F(GeRunningEvnFakerTest, test_reset_running_env_is_success) { + GeRunningEnvFaker ge_env; + ge_env.Reset(); + ASSERT_OPS_LIST_SIZE(0); + ASSERT_EQ(kernel_manager.GetAllOpsKernelInfoStores().size(), 1); + ASSERT_EQ(builder_manager.GetAllOpsKernelBuilders().size(), 1); + ASSERT_EQ(kernel_manager.GetAllOpsKernelInfo().size(), 52); + ASSERT_EQ(kernel_manager.GetOpsKernelInfo(SWITCH).size(), 1); +} + +TEST_F(GeRunningEvnFakerTest, test_install_fake_op_success) { + GeRunningEnvFaker ge_env; + ge_env.Install(FakeOp(DATA)).Install(FakeOp(SWITCH)); + ASSERT_OPS_LIST_SIZE(2); + ASSERT_TRUE(OperatorFactory::IsExistOp(DATA)); + ASSERT_TRUE(OperatorFactory::IsExistOp(SWITCH)); +} + +TEST_F(GeRunningEvnFakerTest, test_install_fake_op_with_inputs_and_outputs_success) { + GeRunningEnvFaker ge_env; + ge_env.Install(FakeOp(ADD).Inputs({"x1", "x2"}).Outputs({"y"})); + + auto add1 = OperatorFactory::CreateOperator("add1", ADD); + + ASSERT_EQ(add1.GetInputsSize(), 2); + ASSERT_EQ(add1.GetOutputsSize(), 1); + ASSERT_OPS_LIST_SIZE(1); +} + +TEST_F(GeRunningEvnFakerTest, test_install_fake_op_with_infer_shape_success) { + GeRunningEnvFaker ge_env; + auto infer_fun = [](Operator &op) -> graphStatus { + TensorDesc input_desc = op.GetInputDescByName("data"); + return GRAPH_SUCCESS; + }; + ASSERT_TRUE(OperatorFactoryImpl::GetInferShapeFunc(DATA) == nullptr); + + ge_env.Install(FakeOp(DATA).Inputs({"data"}).InferShape(infer_fun)); + + ASSERT_TRUE(OperatorFactoryImpl::GetInferShapeFunc(DATA) != nullptr); +} + +TEST_F(GeRunningEvnFakerTest, test_install_engine_with_default_info_store) { + GeRunningEnvFaker ge_env; + ge_env.Install(FakeEngine("DNN_HCCL")); + + ASSERT_EQ(kernel_manager.GetAllOpsKernelInfoStores().size(), 2); + ASSERT_EQ(builder_manager.GetAllOpsKernelBuilders().size(), 2); + ASSERT_EQ(kernel_manager.GetAllOpsKernelInfo().size(), 52); + ASSERT_EQ(kernel_manager.GetOpsKernelInfo(SWITCH).size(), 1); +} + +TEST_F(GeRunningEvnFakerTest, test_install_engine_with_info_store_name) { + GeRunningEnvFaker ge_env; + ge_env.Install(FakeEngine("DNN_HCCL").KernelInfoStore("AiCoreLib2")) + .Install(FakeOp(SWITCH).InfoStoreAndBuilder("AiCoreLib2")); + + ASSERT_EQ(kernel_manager.GetAllOpsKernelInfoStores().size(), 2); + ASSERT_EQ(builder_manager.GetAllOpsKernelBuilders().size(), 2); + ASSERT_EQ(kernel_manager.GetAllOpsKernelInfo().size(), 52); + ASSERT_EQ(kernel_manager.GetOpsKernelInfo(SWITCH).size(), 2); +} + +TEST_F(GeRunningEvnFakerTest, test_install_custom_kernel_builder_success) { + struct FakeKernelBuilder : FakeOpsKernelBuilder { + Status CalcOpRunningParam(Node &node) override { + OpDescPtr op_desc = node.GetOpDesc(); + if (op_desc == nullptr) { + return FAILED; + } + return SUCCESS; + } + }; + + GeRunningEnvFaker ge_env; + auto ai_core_kernel = FakeEngine("DNN_HCCL").KernelBuilder(std::make_shared()); + ge_env.Reset().Install(ai_core_kernel); + + ASSERT_EQ(kernel_manager.GetAllOpsKernelInfoStores().size(), 2); + ASSERT_EQ(builder_manager.GetAllOpsKernelBuilders().size(), 2); + ASSERT_EQ(kernel_manager.GetAllOpsKernelInfo().size(), 52); +} + +TEST_F(GeRunningEvnFakerTest, test_install_custom_kernel_info_store_success) { + struct FakeKernelBuilder : FakeOpsKernelInfoStore { + FakeKernelBuilder(const std::string &kernel_lib_name) : FakeOpsKernelInfoStore(kernel_lib_name) {} + + bool CheckSupported(const OpDescPtr &op_desc, std::string &reason) const override { return FAILED; } + }; + + GeRunningEnvFaker ge_env; + auto ai_core_kernel = FakeEngine("DNN_HCCL").KernelInfoStore(std::make_shared("AiCoreLib2")); + ge_env.Reset().Install(ai_core_kernel); + + ASSERT_EQ(kernel_manager.GetAllOpsKernelInfoStores().size(), 2); + ASSERT_EQ(builder_manager.GetAllOpsKernelBuilders().size(), 2); + ASSERT_EQ(kernel_manager.GetAllOpsKernelInfo().size(), 52); +} + +TEST_F(GeRunningEvnFakerTest, test_install_default_fake_engine_success) { + GeRunningEnvFaker ge_env; + ge_env.InstallDefault(); + + ASSERT_EQ(kernel_manager.GetAllOpsKernelInfoStores().size(), 7); + ASSERT_EQ(builder_manager.GetAllOpsKernelBuilders().size(), 7); + ASSERT_EQ(kernel_manager.GetAllOpsKernelInfo().size(), 66); +} + +FAKE_NS_END diff --git a/tests/framework/ge_running_env/tests/test_main.cc b/tests/framework/ge_running_env/tests/test_main.cc new file mode 100644 index 00000000..ede79c75 --- /dev/null +++ b/tests/framework/ge_running_env/tests/test_main.cc @@ -0,0 +1,34 @@ +/** + * Copyright 2021 Huawei Technologies Co., Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include "common/debug/log.h" +#include "external/ge/ge_api.h" +#include "ge_running_env/ge_running_env_faker.h" + +using namespace std; +using namespace ge; + +int main(int argc, char **argv) { + map options; + ge::GEInitialize(options); + GeRunningEnvFaker::BackupEnv(); + testing::InitGoogleTest(&argc, argv); + int ret = RUN_ALL_TESTS(); + + return ret; +} diff --git a/tests/framework/stub_engine/CMakeLists.txt b/tests/framework/stub_engine/CMakeLists.txt deleted file mode 100644 index c86313c7..00000000 --- a/tests/framework/stub_engine/CMakeLists.txt +++ /dev/null @@ -1,58 +0,0 @@ -list(APPEND INCLUDE_DIRECTORIES - "${CMAKE_CURRENT_SOURCE_DIR}" - "${GE_CODE_DIR}" - "${GE_CODE_DIR}/inc" - "${GE_CODE_DIR}/metadef/inc" - "${GE_CODE_DIR}/ge" - "${GE_CODE_DIR}/ge/inc" - "${GE_CODE_DIR}/ge/ir_build" - "${GE_CODE_DIR}/metadef" - "${GE_CODE_DIR}/metadef/graph" - "${GE_CODE_DIR}/inc/external" - "${GE_CODE_DIR}/inc/framework/common" - "${GE_CODE_DIR}/metadef/inc/external" - "${GE_CODE_DIR}/metadef/inc/external/graph" - "${GE_CODE_DIR}/metadef/inc/graph" - "${GE_CODE_DIR}/inc/framework" - "${GE_CODE_DIR}/metadef/inc/common" - "${GE_CODE_DIR}/metadef/third_party" - "${GE_CODE_DIR}/metadef/third_party/transformer/inc" - "${GE_CODE_DIR}/parser" - "${GE_CODE_DIR}/parser/parser" - "${GE_CODE_DIR}/third_party/fwkacllib/inc" - "${GE_CODE_DIR}/third_party/fwkacllib/inc/cce" - "${GE_CODE_DIR}/third_party/fwkacllib/inc/ops" - "${GE_CODE_DIR}/third_party/fwkacllib/inc/toolchain" - "${GE_CODE_DIR}/tests/ut/ge" - "${GE_CODE_DIR}/tests/ut/common" - "${CMAKE_BINARY_DIR}" - "${CMAKE_BINARY_DIR}/proto/ge" - "${CMAKE_BINARY_DIR}/proto/ge/proto" - ) - -file(GLOB_RECURSE SOURCES CONFIGURE_DEPENDS "*.cc" "*.CC" "*.cpp" "*.CPP" "*.c++") - -# ---- Target : stub Host engine ---- -add_library(fe SHARED ${SOURCES}) - -target_include_directories(fe - PUBLIC - ${INCLUDE_DIRECTORIES} - ${CMAKE_CURRENT_SOURCE_DIR} - ) - -target_compile_definitions(fe PRIVATE - google=ascend_private - FMK_SUPPORT_DUMP - ) - -target_compile_options(fe PRIVATE - -g --coverage -fprofile-arcs -ftest-coverage - -Werror=format - ) - -target_link_libraries(fe PUBLIC - $ ${STUB_LIBS} metadef_graph -lmmpa -L${GE_CODE_DIR}/third_party/prebuild/x86_64 -lrt -ldl -lpthread -lgcov - ) - -set_target_properties(fe PROPERTIES CXX_STANDARD 11) diff --git a/tests/framework/stub_engine/engine/stub_engine.cc b/tests/framework/stub_engine/engine/stub_engine.cc deleted file mode 100644 index 622e8c4e..00000000 --- a/tests/framework/stub_engine/engine/stub_engine.cc +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Copyright 2020 Huawei Technologies Co., Ltd - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "stub_engine.h" -#include -#include -#include -#include -#include "framework/common/debug/ge_log.h" -#include "common/ge/ge_util.h" -#include "inc/st_types.h" - -namespace ge { -namespace st { -StubEngine &StubEngine::Instance() { - static StubEngine instance; - return instance; -} - -Status StubEngine::Initialize(const std::map &options) { - for (const auto engine_2_lib : kStubEngine2KernelLib) { - auto ops_kernel_store = MakeShared(engine_2_lib.second); - if (ops_kernel_store == nullptr) { - return FAILED; - } - ops_kernel_store_map_.insert(make_pair(engine_2_lib.second, ops_kernel_store)); - } - return SUCCESS; -} - -void StubEngine::GetOpsKernelInfoStores(std::map &ops_kernel_map) { - for (const auto name_2_ops_kernel_store : ops_kernel_store_map_) { - ops_kernel_map[name_2_ops_kernel_store.first] = name_2_ops_kernel_store.second; - } -} - -void StubEngine::GetGraphOptimizerObjs(std::map &) { - // no optimizer for host cpu engine -} - -Status StubEngine::Finalize() { - return SUCCESS; -} -} // namespace st -} // namespace ge - -ge::Status Initialize(const std::map &options) { - return ge::st::StubEngine::Instance().Initialize(options); -} - -void GetOpsKernelInfoStores(std::map &ops_kernel_map) { - ge::st::StubEngine::Instance().GetOpsKernelInfoStores(ops_kernel_map); -} - -void GetGraphOptimizerObjs(std::map &graph_optimizers) { - ge::st::StubEngine::Instance().GetGraphOptimizerObjs(graph_optimizers); -} - -ge::Status Finalize() { - return ge::st::StubEngine::Instance().Finalize(); -} diff --git a/tests/framework/stub_engine/engine/stub_engine.h b/tests/framework/stub_engine/engine/stub_engine.h deleted file mode 100644 index d3909115..00000000 --- a/tests/framework/stub_engine/engine/stub_engine.h +++ /dev/null @@ -1,127 +0,0 @@ -/** - * Copyright 2020 Huawei Technologies Co., Ltd - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef GRAPH_ENGINE_LLT_STUB_ENGINE_H_ -#define GRAPH_ENGINE_LLT_STUB_ENGINE_H_ - -#if defined(_MSC_VER) -#ifdef FUNC_VISIBILITY -#define GE_FUNC_VISIBILITY _declspec(dllexport) -#else -#define GE_FUNC_VISIBILITY -#endif -#else -#ifdef FUNC_VISIBILITY -#define GE_FUNC_VISIBILITY __attribute__((visibility("default"))) -#else -#define GE_FUNC_VISIBILITY -#endif -#endif - -#include -#include -#include -#include "inc/st_types.h" -#include "common/opskernel/ops_kernel_info_store.h" -#include "common/optimizer/graph_optimizer.h" -#include "stub_engine/ops_kernel_store/stub_ops_kernel_store.h" - -using OpsKernelInfoStorePtr = std::shared_ptr; -using StubOpsKernelInfoStorePtr = std::shared_ptr; -using GraphOptimizerPtr = std::shared_ptr; - -namespace ge { -namespace st { -/** - * host cpu engine. - * Used for the ops which executes on host. - */ -class GE_FUNC_VISIBILITY StubEngine { - public: - /** - * get StubEngine instance. - * @return StubEngine instance. - */ - static StubEngine &Instance(); - - virtual ~StubEngine() = default; - - /** - * When Ge start, GE will invoke this interface - * @return The status whether initialize successfully - */ - Status Initialize(const std::map &options); - - /** - * After the initialize, GE will invoke this interface - * to get the Ops kernel Store. - * @param ops_kernel_map The host cpu's ops kernel info - */ - void GetOpsKernelInfoStores(std::map &ops_kernel_map); - - /** - * After the initialize, GE will invoke this interface - * to get the Graph Optimizer. - * @param graph_optimizers The host cpu's Graph Optimizer objs - */ - void GetGraphOptimizerObjs(std::map &graph_optimizers); - - /** - * When the graph finished, GE will invoke this interface - * @return The status whether initialize successfully - */ - Status Finalize(); - - StubEngine(const StubEngine &StubEngine) = delete; - StubEngine(const StubEngine &&StubEngine) = delete; - StubEngine &operator=(const StubEngine &StubEngine) = delete; - StubEngine &operator=(StubEngine &&StubEngine) = delete; - - private: - StubEngine() = default; - map ops_kernel_store_map_; -}; -} // namespace st -} // namespace ge - -extern "C" { - -/** - * When Ge start, GE will invoke this interface - * @return The status whether initialize successfully - */ -GE_FUNC_VISIBILITY ge::Status Initialize(const map &options); - -/** - * After the initialize, GE will invoke this interface to get the Ops kernel Store - * @param ops_kernel_map The host cpu's ops kernel info - */ -GE_FUNC_VISIBILITY void GetOpsKernelInfoStores(std::map &ops_kernel_map); - -/** - * After the initialize, GE will invoke this interface to get the Graph Optimizer - * @param graph_optimizers The host cpu's Graph Optimizer objs - */ -GE_FUNC_VISIBILITY void GetGraphOptimizerObjs(std::map &graph_optimizers); - -/** - * When the graph finished, GE will invoke this interface - * @return The status whether initialize successfully - */ -GE_FUNC_VISIBILITY ge::Status Finalize(); -} - -#endif // GRAPH_ENGINE_LLT_STUB_ENGINE_H_ diff --git a/tests/framework/stub_engine/inc/st_types.h b/tests/framework/stub_engine/inc/st_types.h deleted file mode 100644 index 92aa00d9..00000000 --- a/tests/framework/stub_engine/inc/st_types.h +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright 2021 Huawei Technologies Co., Ltd - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef GRAPHENGINE_ST_TYPES_H -#define GRAPHENGINE_ST_TYPES_H -#include -namespace ge { -namespace st { -const std::string kAicoreLibName = "AiCoreLib"; -const std::string kVectorLibName = "VectorLib"; -const std::string kAicpuLibName = "AicpuLib"; -const std::string kAicpuAscendLibName = "AicpuAscendLib"; -const std::string kHcclLibName = "HcclLib"; -const std::string kRTSLibName = "RTSLib"; -const std::map kStubEngine2KernelLib = { - {"AIcoreEngine", "AiCoreLib"}, {"VectorEngine", "VectorLib"}, - {"DNN_VM_AICPU", "AicpuLib"}, {"DNN_VM_AICPU_ASCEND", "AicpuAscendLib"}, - {"DNN_HCCL", "HcclLib"}, {"DNN_VM_RTS", "RTSLib"}}; -} // namespace st -} // namespace ge -#endif // GRAPHENGINE_ST_TYPES_H diff --git a/tests/framework/stub_engine/ops_kernel_store/op/host_op.cc b/tests/framework/stub_engine/ops_kernel_store/op/host_op.cc deleted file mode 100644 index 42678148..00000000 --- a/tests/framework/stub_engine/ops_kernel_store/op/host_op.cc +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Copyright 2021 Huawei Technologies Co., Ltd - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "inc/st_types.h" -#include "stub_engine/ops_kernel_store/op/host_op.h" -#include "framework/common/util.h" -#include "stub_engine/ops_kernel_store/op/stub_op_factory.h" - -namespace ge { -namespace st { -Status HostOp::Run() { - // no need to generate device task - return SUCCESS; -} -REGISTER_OP_CREATOR(Enter, RTSLib, HostOp); -REGISTER_OP_CREATOR(Merge, RTSLib, HostOp); -REGISTER_OP_CREATOR(Switch, RTSLib, HostOp); -REGISTER_OP_CREATOR(Less, AiCoreLib, HostOp); -REGISTER_OP_CREATOR(NextIteration, AiCoreLib, HostOp); -REGISTER_OP_CREATOR(LoopCond, RTSLib, HostOp); -REGISTER_OP_CREATOR(Exit, RTSLib, HostOp); -REGISTER_OP_CREATOR(StreamMerge, RTSLib, HostOp); -REGISTER_OP_CREATOR(StreamSwitch, RTSLib, HostOp); -REGISTER_OP_CREATOR(StreamActive, RTSLib, HostOp); -REGISTER_OP_CREATOR(Cast, AiCoreLib, HostOp); -REGISTER_OP_CREATOR(Transdata, AiCoreLib, HostOp); -} // namespace st -} // namespace ge diff --git a/tests/framework/stub_engine/ops_kernel_store/op/stub_op_factory.cc b/tests/framework/stub_engine/ops_kernel_store/op/stub_op_factory.cc deleted file mode 100644 index 601bca4d..00000000 --- a/tests/framework/stub_engine/ops_kernel_store/op/stub_op_factory.cc +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Copyright 2021 Huawei Technologies Co., Ltd - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "stub_op_factory.h" -#include "framework/common/debug/ge_log.h" -#include "common/ge_inner_error_codes.h" -#include "graph/op_desc.h" - -namespace ge { -namespace st { -OpFactory &OpFactory::Instance() { - static OpFactory instance; - return instance; -} - -std::shared_ptr OpFactory::CreateOp(const Node &node, RunContext &run_context) { - auto iter = op_creator_map_.find(node.GetType()); - if (iter != op_creator_map_.end()) { - return iter->second(node, run_context); - } - GELOGE(FAILED, "Not supported OP, type = %s, name = %s", node.GetType().c_str(), node.GetName().c_str()); - return nullptr; -} - -void OpFactory::RegisterCreator(const std::string &type, const std::string &kernel_lib, const OP_CREATOR_FUNC &func) { - if (func == nullptr) { - GELOGW("Func is NULL."); - return; - } - - if (all_store_ops_.find(kernel_lib) != all_store_ops_.end()) { - all_store_ops_[kernel_lib].emplace_back(type); - } else { - all_store_ops_[kernel_lib] = {type}; - } -} -} // namespace st -} // namespace ge diff --git a/tests/framework/stub_engine/ops_kernel_store/op/stub_op_factory.h b/tests/framework/stub_engine/ops_kernel_store/op/stub_op_factory.h deleted file mode 100644 index f41fd07e..00000000 --- a/tests/framework/stub_engine/ops_kernel_store/op/stub_op_factory.h +++ /dev/null @@ -1,109 +0,0 @@ -/** - * Copyright 2021 Huawei Technologies Co., Ltd - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef GE_HOST_CPU_ENGINE_OPS_KERNEL_STORE_OP_OP_FACTORY_H_ -#define GE_HOST_CPU_ENGINE_OPS_KERNEL_STORE_OP_OP_FACTORY_H_ - -#include -#include -#include -#include -#include -#include "common/ge/ge_util.h" -#include "stub_engine/ops_kernel_store/op/op.h" -#include "inc/st_types.h" - -namespace ge { -namespace st { -using OP_CREATOR_FUNC = std::function(const Node &, RunContext &)>; - -/** - * manage all the op, support create op. - */ -class GE_FUNC_VISIBILITY OpFactory { - public: - static OpFactory &Instance(); - - /** - * @brief create Op. - * @param [in] node share ptr of node - * @param [in] run_context run context - * @return not nullptr success - * @return nullptr fail - */ - std::shared_ptr CreateOp(const Node &node, RunContext &run_context); - - /** - * @brief Register Op create function. - * @param [in] type Op type - * @param [in] func Op create func - */ - void RegisterCreator(const std::string &type, const std::string &lib_name, const OP_CREATOR_FUNC &func); - - const std::vector &GetAllOps() const { - return all_ops_; - } - - const std::vector &GetAllOps(std::string lib_name) const { - auto iter = all_store_ops_.find(lib_name); - if (iter == all_store_ops_.end()) { - return all_ops_; - } - return iter->second; - } - - bool CheckSupported(const std::string &type) { - return op_creator_map_.find(type) != op_creator_map_.end(); - } - - OpFactory(const OpFactory &) = delete; - OpFactory &operator=(const OpFactory &) = delete; - OpFactory(OpFactory &&) = delete; - OpFactory &operator=(OpFactory &&) = delete; - - private: - OpFactory() = default; - ~OpFactory() = default; - - // the op creator function map - std::map op_creator_map_; - std::map> lib_op_creator_map_; - std::vector all_ops_; - std::map> all_store_ops_; -}; - -class GE_FUNC_VISIBILITY OpRegistrar { - public: - OpRegistrar(const std::string &type, const std::string &kernel_lib, const OP_CREATOR_FUNC &func) { - OpFactory::Instance().RegisterCreator(type, kernel_lib, func); - } - ~OpRegistrar() = default; - - OpRegistrar(const OpRegistrar &) = delete; - OpRegistrar &operator=(const OpRegistrar &) = delete; - OpRegistrar(OpRegistrar &&) = delete; - OpRegistrar &operator=(OpRegistrar &&) = delete; -}; - -#define REGISTER_OP_CREATOR(type, lib_name, clazz) \ - std::shared_ptr Creator_##type##Op(const Node &node, RunContext &run_context) { \ - return MakeShared(node, run_context); \ - } \ - OpRegistrar g_##type##Op_creator(#type, #lib_name, Creator_##type##Op) -} // namespace st -} // namespace ge - -#endif // GE_HOST_CPU_ENGINE_OPS_KERNEL_STORE_OP_OP_FACTORY_H_ diff --git a/tests/framework/stub_engine/ops_kernel_store/stub_ops_kernel_store.cc b/tests/framework/stub_engine/ops_kernel_store/stub_ops_kernel_store.cc deleted file mode 100644 index d43fee88..00000000 --- a/tests/framework/stub_engine/ops_kernel_store/stub_ops_kernel_store.cc +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Copyright 2021 Huawei Technologies Co., Ltd - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "stub_ops_kernel_store.h" -#include -#include "ge/ge_api_types.h" -#include "framework/common/debug/ge_log.h" -#include "graph/utils/node_utils.h" -#include "graph/utils/tensor_utils.h" -#include "graph/utils/type_utils.h" -#include "op/stub_op_factory.h" - -namespace ge { -namespace st { -using domi::TaskDef; -using std::map; -using std::string; -using std::vector; - -Status StubOpsKernelInfoStore::Initialize(const map &options) { - GELOGI("StubOpsKernelInfoStore init start."); - string engine_name; - for (const auto &engine_2_lib : kStubEngine2KernelLib) { - if (engine_2_lib.second == store_name_) { - engine_name = engine_2_lib.first; - } - } - if (engine_name.empty()) { - return FAILED; - } - - OpInfo default_op_info = {.engine = engine_name, - .opKernelLib = store_name_, - .computeCost = 0, - .flagPartial = false, - .flagAsync = false, - .isAtomic = false}; - // Init op_info_map_ - auto all_ops_in_store = OpFactory::Instance().GetAllOps(store_name_); - for (auto &op : all_ops_in_store) { - op_info_map_[op] = default_op_info; - } - - GELOGI("StubOpsKernelInfoStore inited success. op num=%zu", op_info_map_.size()); - return SUCCESS; -} - -Status StubOpsKernelInfoStore::Finalize() { - op_info_map_.clear(); - return SUCCESS; -} - -void StubOpsKernelInfoStore::GetAllOpsKernelInfo(map &infos) const { - infos = op_info_map_; -} - -bool StubOpsKernelInfoStore::CheckSupported(const OpDescPtr &op_desc, std::string &) const { - if (op_desc == nullptr) { - return false; - } - return op_info_map_.count(op_desc->GetType()) > 0; -} -} // namespace st -} // namespace ge diff --git a/tests/framework/stub_engine/ops_kernel_store/stub_ops_kernel_store.h b/tests/framework/stub_engine/ops_kernel_store/stub_ops_kernel_store.h deleted file mode 100644 index ea7f712b..00000000 --- a/tests/framework/stub_engine/ops_kernel_store/stub_ops_kernel_store.h +++ /dev/null @@ -1,73 +0,0 @@ -/** - * Copyright 2021 Huawei Technologies Co., Ltd - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef GE_HOST_CPU_ENGINE_OPS_KERNEL_STORE_HOST_CPU_OPS_KERNEL_INFO_H_ -#define GE_HOST_CPU_ENGINE_OPS_KERNEL_STORE_HOST_CPU_OPS_KERNEL_INFO_H_ - -#if defined(_MSC_VER) -#ifdef FUNC_VISIBILITY -#define GE_FUNC_VISIBILITY _declspec(dllexport) -#else -#define GE_FUNC_VISIBILITY -#endif -#else -#ifdef FUNC_VISIBILITY -#define GE_FUNC_VISIBILITY __attribute__((visibility("default"))) -#else -#define GE_FUNC_VISIBILITY -#endif -#endif - -#include -#include -#include - -#include "common/opskernel/ops_kernel_info_store.h" - -namespace ge { -namespace st { -/*const vector kStubOpKernelLibNameVec = { - "AiCoreLib", - "AicpuLib", - "HcclLib", - "RTSLib" -};*/ -class GE_FUNC_VISIBILITY StubOpsKernelInfoStore : public OpsKernelInfoStore { - public: - StubOpsKernelInfoStore(std::string store_name) : store_name_(store_name) {} - ~StubOpsKernelInfoStore() override = default; - Status Initialize(const std::map &options) override; - Status Finalize() override; - bool CheckSupported(const OpDescPtr &op_desc, std::string &reason) const override; - void GetAllOpsKernelInfo(std::map &infos) const override; - std::string GetOpsKernelStoreName() const { - return store_name_; - } - - StubOpsKernelInfoStore(const StubOpsKernelInfoStore &ops_kernel_store) = delete; - StubOpsKernelInfoStore(const StubOpsKernelInfoStore &&ops_kernel_store) = delete; - StubOpsKernelInfoStore &operator=(const StubOpsKernelInfoStore &ops_kernel_store) = delete; - StubOpsKernelInfoStore &operator=(StubOpsKernelInfoStore &&ops_kernel_store) = delete; - - private: - // store op name and OpInfo key-value pair - std::map op_info_map_; - std::string store_name_; -}; -} // namespace st -} // namespace ge - -#endif // GE_HOST_CPU_ENGINE_OPS_KERNEL_STORE_HOST_CPU_OPS_KERNEL_INFO_H_ diff --git a/tests/st/testcase/CMakeLists.txt b/tests/st/testcase/CMakeLists.txt index 9d1d5a0e..b3663708 100644 --- a/tests/st/testcase/CMakeLists.txt +++ b/tests/st/testcase/CMakeLists.txt @@ -8,7 +8,7 @@ target_include_directories(graph_engine_test set_target_properties(graph_engine_test PROPERTIES CXX_STANDARD 17) -target_link_libraries(graph_engine_test PRIVATE gtest gtest_main framework) +target_link_libraries(graph_engine_test PRIVATE gtest framework) include(CTest) enable_testing() diff --git a/tests/st/testcase/test_framework_dummy.cc b/tests/st/testcase/test_framework_dummy.cc index 951e6b2b..0abdd18b 100644 --- a/tests/st/testcase/test_framework_dummy.cc +++ b/tests/st/testcase/test_framework_dummy.cc @@ -17,9 +17,13 @@ #include #include #include "external/ge/ge_api.h" +#include "ge_running_env/fake_engine.h" #include "graph/debug/ge_attr_define.h" #include "framework/common/types.h" + #include "builder/graph_builder_utils.h" +#include "ge_running_env/ge_running_env_faker.h" + #include "graph/operator_reg.h" #include "graph/operator.h" #define protected public @@ -109,8 +113,8 @@ Graph BuildV1ControlFlowGraph() { for_each(data_vec.begin(), data_vec.end(), [&](int64_t &data) { dims_size *= data; }); vector data_value_vec(dims_size, 1); GeTensorDesc data_tensor_desc(GeShape(data_vec), FORMAT_NCHW, DT_INT32); - GeTensorPtr data_tensor = make_shared(data_tensor_desc, (uint8_t *) data_value_vec.data(), - data_value_vec.size() * sizeof(int32_t)); + GeTensorPtr data_tensor = + make_shared(data_tensor_desc, (uint8_t *)data_value_vec.data(), data_value_vec.size() * sizeof(int32_t)); OpDescUtils::SetWeights(const_5->GetOpDesc(), data_tensor); OpDescUtils::SetWeights(const_2->GetOpDesc(), data_tensor); OpDescUtils::SetWeights(const_1->GetOpDesc(), data_tensor); @@ -120,13 +124,9 @@ Graph BuildV1ControlFlowGraph() { } // namespace class FrameworkTest : public testing::Test { protected: - void SetUp() { - // ge initialize - map options; - auto ret = ge::GEInitialize(options); - EXPECT_EQ(ret, SUCCESS); - } + void SetUp() { ge_env.InstallDefault(); } void TearDown() {} + GeRunningEnvFaker ge_env; }; /// data data diff --git a/tests/st/testcase/test_main.cc b/tests/st/testcase/test_main.cc new file mode 100644 index 00000000..a39c68aa --- /dev/null +++ b/tests/st/testcase/test_main.cc @@ -0,0 +1,37 @@ +/** + * Copyright 2021 Huawei Technologies Co., Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include "common/debug/log.h" +#include "external/ge/ge_api.h" +#include "ge_running_env/include/ge_running_env/ge_running_env_faker.h" + +using namespace std; +using namespace ge; + +int main(int argc, char **argv) { + // init the logging + map options; + auto init_status = ge::GEInitialize(options); + if (init_status != SUCCESS) { + std::cout << "ge init failed , ret code:" << init_status << endl; + } + GeRunningEnvFaker::BackupEnv(); + testing::InitGoogleTest(&argc, argv); + int ret = RUN_ALL_TESTS(); + return ret; +} From 07a5635e8b5e08879c2013cffec6164e5697006d Mon Sep 17 00:00:00 2001 From: TangQunzhang Date: Mon, 28 Jun 2021 13:48:18 +0800 Subject: [PATCH 09/20] Print statics when malloc memory fail --- ge/graph/manager/graph_caching_allocator.cc | 18 ++++++++++++------ ge/graph/manager/graph_caching_allocator.h | 10 +++++++++- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/ge/graph/manager/graph_caching_allocator.cc b/ge/graph/manager/graph_caching_allocator.cc index 82bfbda9..7b316fc3 100644 --- a/ge/graph/manager/graph_caching_allocator.cc +++ b/ge/graph/manager/graph_caching_allocator.cc @@ -20,7 +20,6 @@ #include #include -#include "framework/common/debug/ge_log.h" #include "graph/manager/graph_mem_manager.h" namespace ge { @@ -94,7 +93,8 @@ void IncreaseCount(std::map &count, size_t size) { } } -CachingAllocator::CachingAllocator(rtMemType_t memory_type) : memory_type_(memory_type), memory_allocator_(nullptr) { +CachingAllocator::CachingAllocator(rtMemType_t memory_type) + : memory_type_(memory_type), memory_allocator_(nullptr), called_malloc_counts_(0), called_free_counts_(0) { for (uint32_t i = 0; i < kNumBins; i++) { free_block_bins_[i] = nullptr; } @@ -121,6 +121,8 @@ Status CachingAllocator::Initialize(uint32_t device_id) { if (memory_allocator_ == nullptr) { return ACL_ERROR_GE_INTERNAL_ERROR; } + called_malloc_counts_ = 0; + called_free_counts_ = 0; return ge::SUCCESS; } @@ -133,6 +135,7 @@ void CachingAllocator::Finalize(uint32_t device_id) { uint8_t *CachingAllocator::Malloc(size_t size, uint8_t *org_ptr, uint32_t device_id) { GELOGI("Start malloc pool memory, size = %zu, device id = %u", size, device_id); + called_malloc_counts_++; size = GetBlockSize(size); uint8_t *ptr = nullptr; Block *block = FindFreeBlock(size, org_ptr, device_id); @@ -156,6 +159,7 @@ uint8_t *CachingAllocator::Malloc(size_t size, uint8_t *org_ptr, uint32_t device Status CachingAllocator::Free(uint8_t *ptr, uint32_t device_id) { GELOGI("Free device id = %u", device_id); + called_free_counts_++; if (ptr == nullptr) { REPORT_INNER_ERROR("E19999", "Param ptr is nullptr, device_id:%u, check invalid", device_id); GELOGE(PARAM_INVALID, "[Check][Param] Invalid memory pointer, device_id:%u", device_id); @@ -283,6 +287,7 @@ Status CachingAllocator::TryExtendCache(size_t size, uint32_t device_id) { if (memory_addr == nullptr) { GELOGE(ge::FAILED, "[Malloc][Memory] failed, no enough memory for size = %zu, device_id = %u", memory_size, device_id); + PrintStatics(DLOG_ERROR); return ge::FAILED; } GELOGT(TRACE_RUNNING, "Try to free cached memory size:%zu and malloc memory size:%zu success.", @@ -385,14 +390,14 @@ void CachingAllocator::FreeBlockBins() { } void PrintCount(std::map &count, const std::string &name, size_t total_size, size_t total_count) { - GELOGI("%6s total[size:%10zu count:%10zu].", name.c_str(), total_size, total_count); + GEEVENT("%6s total[size:%11zu count:%11zu].", name.c_str(), total_size, total_count); for (auto &it : count) { - GELOGI(" |- block[size:%10zu count:%10zu].", it.first, it.second); + GEEVENT(" |- block[size:%11zu count:%11zu].", it.first, it.second); } } -void CachingAllocator::PrintStatics() { - if (!IsLogEnable(GE_MODULE_NAME, DLOG_INFO)) { +void CachingAllocator::PrintStatics(int32_t level) { + if (!IsLogEnable(GE_MODULE_NAME, level)) { return; } size_t total_using_size = 0; @@ -435,6 +440,7 @@ void CachingAllocator::PrintStatics() { } } while (0); + GEEVENT("Called counts[malloc:%11zu free:%11zu].", called_malloc_counts_.load(), called_free_counts_.load()); PrintCount(malloc_block_stat, "Malloc", total_malloc_size, total_malloc_count); PrintCount(using_block_stat, "Using", total_using_size, total_using_count); PrintCount(free_block_stat, "Free", total_free_size, total_free_count); diff --git a/ge/graph/manager/graph_caching_allocator.h b/ge/graph/manager/graph_caching_allocator.h index 2db00ff2..d00858f3 100644 --- a/ge/graph/manager/graph_caching_allocator.h +++ b/ge/graph/manager/graph_caching_allocator.h @@ -27,6 +27,7 @@ #include #include +#include "framework/common/debug/ge_log.h" #include "framework/common/ge_inner_error_codes.h" #include "graph/node.h" #include "graph/manager/block_memory.h" @@ -192,9 +193,10 @@ class CachingAllocator { /// /// @ingroup ge_graph /// @brief print the memory info in pool + /// @param [in] log level /// @return void /// - void PrintStatics(); + void PrintStatics(int32_t level = DLOG_INFO); private: rtMemType_t memory_type_; @@ -213,6 +215,12 @@ class CachingAllocator { // malloced memorys from device std::map malloced_memory_; + + //user call Malloc total counts + std::atomic called_malloc_counts_; + + //user call Free total counts + std::atomic called_free_counts_; }; } // namespace ge #endif // GE_GRAPH_MANAGER_GRAPH_CACHING_ALLOCATOR_H_ From a6b6229967c1241494d86eb39200db8783e55a52 Mon Sep 17 00:00:00 2001 From: wuweikang Date: Thu, 13 May 2021 16:14:41 +0800 Subject: [PATCH 10/20] add copy graph --- ge/graph/manager/graph_manager.cc | 2 +- ge/hybrid/model/hybrid_model.h | 1 + ge/hybrid/model/hybrid_model_builder.cc | 45 +++++++++++++++++----- ge/hybrid/model/hybrid_model_builder.h | 1 + .../hybrid/executor/subgraph_executor_unittest.cc | 3 ++ .../hybrid/model/hybrid_model_builder_unittest.cc | 26 ++++++++++--- 6 files changed, 63 insertions(+), 15 deletions(-) diff --git a/ge/graph/manager/graph_manager.cc b/ge/graph/manager/graph_manager.cc index 66026f8d..01a2e502 100755 --- a/ge/graph/manager/graph_manager.cc +++ b/ge/graph/manager/graph_manager.cc @@ -3131,10 +3131,10 @@ void GraphManager::PreRunThread(GraphManager *graph_manager) { } // Avoid repeatively prerun for graphs owns same graph_id in online inference concurrency if (count > 1 && graph_node->GetBuildFlag()) { - graph_node->Lock(); GELOGD("Avoid repeatively prerun, graph_id:%u.", args.graph_id); // In online inference concurrency senario, graph_node is allowed to be locked for 'count' times graph_node->SetSemSize(count); + graph_node->Lock(); graph_manager->run_args_q_.Push(RunArgs( { graph_node, args.graph_id, args.session_id, args.error_context, args.input_tensor, graph_node->GetGeRootModel(), GetThreadLocalContext(), args.callback })); GELOGI("[PreRunThread] Loop end. Start to run with cached build model."); diff --git a/ge/hybrid/model/hybrid_model.h b/ge/hybrid/model/hybrid_model.h index 9821242a..77246e20 100644 --- a/ge/hybrid/model/hybrid_model.h +++ b/ge/hybrid/model/hybrid_model.h @@ -147,6 +147,7 @@ class HybridModel { GeRootModelPtr ge_root_model_; std::map input_nodes_; ComputeGraphPtr root_graph_; + ComputeGraphPtr orig_root_graph_; std::map device_variable_nodes_; //lint !e148 std::map host_variable_nodes_; //lint !e148 std::map> variable_tensors_; diff --git a/ge/hybrid/model/hybrid_model_builder.cc b/ge/hybrid/model/hybrid_model_builder.cc index 1f68f374..e80d9b90 100755 --- a/ge/hybrid/model/hybrid_model_builder.cc +++ b/ge/hybrid/model/hybrid_model_builder.cc @@ -147,6 +147,7 @@ Status HybridModelBuilder::Build() { GE_CHK_STATUS_RET(ValidateParams(), "[Invoke][ValidateParams] failed, model_name_:[%s]", GetGraphName()); hybrid_model_.model_name_ = ge_root_model_->GetModelName(); GELOGI("[%s] Start to build hybrid model.", GetGraphName()); + GE_CHK_STATUS_RET(CopyGraph(), "[Invoke][CopyGraph] failed, model_name_:[%s]", GetGraphName()); GE_CHK_STATUS_RET(InitRuntimeParams(), "[Invoke][InitRuntimeParams] failed, model_name_:[%s]", GetGraphName()); GE_CHK_STATUS_RET(RecoverGraphUnknownFlag(), "[Invoke][RecoverGraphUnknownFlag] failed, model_name_:[%s]", GetGraphName()); @@ -171,11 +172,12 @@ Status HybridModelBuilder::Build() { Status HybridModelBuilder::BuildForSingleOp() { GE_CHK_STATUS_RET(ValidateParams(), "[Invoke][ValidateParams] failed, model_name_:[%s]", GetGraphName()); + hybrid_model_.root_graph_ = ge_root_model_->GetRootGraph(); hybrid_model_.model_name_ = ge_root_model_->GetRootGraph()->GetName(); GELOGI("[%s] Start to build hybrid model.", GetGraphName()); auto ret = ge_root_model_->GetSubgraphInstanceNameToModel(); - const GeModelPtr ge_model = ret[ge_root_model_->GetRootGraph()->GetName()]; - GE_CHK_STATUS_RET(IndexTaskDefs(ge_root_model_->GetRootGraph(), ge_model), + const GeModelPtr ge_model = ret[hybrid_model_.root_graph_->GetName()]; + GE_CHK_STATUS_RET(IndexTaskDefs(hybrid_model_.root_graph_, ge_model), "[Invoke][IndexTaskDefs] failed, model_name_:[%s]", GetGraphName()); GE_CHK_STATUS_RET(LoadGraph(), "[Invoke][LoadGraph] failed, model_name_:[%s]", GetGraphName()); GE_CHK_STATUS_RET(InitWeights(), "[Invoke][InitWeights] failed, model_name_:[%s]", GetGraphName()); @@ -190,6 +192,27 @@ Status HybridModelBuilder::ValidateParams() { return SUCCESS; } +Status HybridModelBuilder::CopyGraph() { + GELOGD("Copy compute graph begin."); + auto root_graph = ge_root_model_->GetRootGraph(); + + std::string new_graph_name = ge_root_model_->GetRootGraph()->GetName(); + ComputeGraphPtr new_root_graph = MakeShared(new_graph_name); + GE_CHECK_NOTNULL(new_root_graph); + int32_t depth = 0; + std::map node_old_2_new; + std::map op_desc_old_2_new; + graphStatus ret = GraphUtils::CopyComputeGraph(root_graph, new_root_graph, node_old_2_new, op_desc_old_2_new, depth); + if (ret != GRAPH_SUCCESS) { + GELOGE(GRAPH_FAILED, "Copy compute graph failed."); + return GRAPH_FAILED; + } + hybrid_model_.root_graph_ = new_root_graph; + + GELOGD("Copy compute graph[%s] success.", new_graph_name.c_str()); + return SUCCESS; +} + Status HybridModelBuilder::BuildNodeItem(const NodePtr &node, NodeItem &node_item) { auto op_desc = node->GetOpDesc(); GE_CHK_STATUS_RET(ParseForceInfershapeNodes(node, node_item), @@ -810,12 +833,13 @@ Status HybridModelBuilder::BuildOutputMapping(GraphItem &graph_item, } Status HybridModelBuilder::LoadGraph() { - auto root_graph = ge_root_model_->GetRootGraph(); + auto root_graph = hybrid_model_.root_graph_; if (!GetContext().GetHostExecFlag()) { std::shared_ptr merged_graph; GELOGI("Before merging subgraphs DirectNodesSize = %zu, GetAllNodesSize = %zu", root_graph->GetDirectNodesSize(), root_graph->GetAllNodesSize()); + hybrid_model_.orig_root_graph_ = root_graph; GE_CHK_GRAPH_STATUS_RET(UnfoldSubgraphs(root_graph, merged_graph), "[Invoke][UnfoldSubgraphs]Failed to unfold subgraphs, model_name_:%s.", GetGraphName()); root_graph = std::move(merged_graph); @@ -873,6 +897,7 @@ Status HybridModelBuilder::LoadGraph() { } for (auto &it : hybrid_model_.known_shape_sub_models_) { auto node_item = MutableNodeItem(it.first); + GE_CHECK_NOTNULL(node_item); AscendString graph_name; GE_CHK_GRAPH_STATUS_RET(it.second->GetGraph().GetName(graph_name), "Failed to get subgraph name"); auto subgraph = hybrid_model_.GetRootGraph()->GetSubgraph(graph_name.GetString()); @@ -1121,7 +1146,9 @@ Status HybridModelBuilder::InitWeights() { sub_weight_buffer->GetSize()); auto subgraph = GraphUtils::GetComputeGraph(subgraph_model.second->GetGraph()); if (subgraph != ge_root_model_->GetRootGraph()) { - subgraph = ge_root_model_->GetRootGraph()->GetSubgraph(subgraph_model.first); + subgraph = hybrid_model_.root_graph_->GetSubgraph(subgraph_model.first); + } else { + subgraph = hybrid_model_.root_graph_; } GE_CHECK_NOTNULL(subgraph); hybrid_model_.weight_buffer_map_.emplace(subgraph->GetName(), std::move(sub_weight_buffer)); @@ -1300,7 +1327,7 @@ Status HybridModelBuilder::IndexTaskDefs(const ComputeGraphPtr &sub_graph, const } Status HybridModelBuilder::IndexTaskDefs() { - const auto root_graph = ge_root_model_->GetRootGraph(); + const auto &root_graph = hybrid_model_.root_graph_; const auto &root_graph_name = root_graph->GetName(); if (SetOutputNameAttr(*root_graph) != SUCCESS) { GELOGW("Set output name attr failed."); @@ -1334,7 +1361,7 @@ Status HybridModelBuilder::IndexTaskDefs() { Status HybridModelBuilder::IndexSpecialNodes() { GELOGD("Start to index special nodes"); - const auto &root_graph = ge_root_model_->GetRootGraph(); + const auto &root_graph = hybrid_model_.root_graph_; for (auto &node : root_graph->GetAllNodes()) { GE_CHECK_NOTNULL(node); GE_CHECK_NOTNULL(node->GetOpDesc()); @@ -1489,7 +1516,7 @@ Status HybridModelBuilder::InitRuntimeParams() { runtime_param_.session_id = ret ? static_cast(value) : 0; ret = ge::AttrUtils::GetInt(first_model, ATTR_MODEL_TASK_GEN_VAR_ADDR, value); runtime_param_.logic_var_base = ret ? static_cast(value) : 0; - runtime_param_.graph_id = ge_root_model_->GetRootGraph()->GetGraphID(); + runtime_param_.graph_id = hybrid_model_.root_graph_->GetGraphID(); value = 0; for (auto &it : ge_root_model_->GetSubgraphInstanceNameToModel()) { (void) ge::AttrUtils::GetInt(it.second, ATTR_MODEL_VAR_SIZE, value); @@ -1626,7 +1653,7 @@ Status HybridModelBuilder::TransAllVarData() { } Status HybridModelBuilder::CopyVarData() { - GE_CHK_STATUS_RET(TransVarDataUtils::CopyVarData(ge_root_model_->GetRootGraph(), + GE_CHK_STATUS_RET(TransVarDataUtils::CopyVarData(hybrid_model_.root_graph_, runtime_param_.session_id, hybrid_model_.device_id_), "[Invoke][CopyVarData] failed."); @@ -1709,7 +1736,7 @@ Status HybridModelBuilder::LoadKnownShapedSubgraph(ComputeGraph &graph, NodeItem } Status HybridModelBuilder::RecoverGraphUnknownFlag() { - const auto &root_graph = ge_root_model_->GetRootGraph(); + const auto &root_graph = hybrid_model_.root_graph_; for (auto &sub_graph : root_graph->GetAllSubgraphs()) { GE_CHECK_NOTNULL(sub_graph); for (const auto &node : sub_graph->GetDirectNode()) { diff --git a/ge/hybrid/model/hybrid_model_builder.h b/ge/hybrid/model/hybrid_model_builder.h index 9c1eb187..05830e82 100644 --- a/ge/hybrid/model/hybrid_model_builder.h +++ b/ge/hybrid/model/hybrid_model_builder.h @@ -56,6 +56,7 @@ class HybridModelBuilder { Status BuildOutputMapping(GraphItem &partitioned_call, const NodeItem &node_item, bool is_root_graph); Status ValidateParams(); Status LoadGraph(); + Status CopyGraph(); Status LoadGeModel(ComputeGraph &graph, const GeModelPtr &ge_model); static Status InitHcclExecutorOnDemand(const GeModelPtr &ge_model); Status LoadTask(NodeItem &node_item); diff --git a/tests/ut/ge/hybrid/executor/subgraph_executor_unittest.cc b/tests/ut/ge/hybrid/executor/subgraph_executor_unittest.cc index 2dc3b639..827705ae 100644 --- a/tests/ut/ge/hybrid/executor/subgraph_executor_unittest.cc +++ b/tests/ut/ge/hybrid/executor/subgraph_executor_unittest.cc @@ -249,6 +249,9 @@ TEST_F(UtestSubgraphExecutor, cond_graph_schedule_tasks) { graph_context.callback_manager = std::unique_ptr(new CallbackManager()); ASSERT_EQ(graph_context.callback_manager->Init(), SUCCESS); + auto root_graph = hybrid_model.root_graph_; + switch_t = root_graph->FindNode("switch_t"); + switch_f = root_graph->FindNode("switch_f"); const auto node_it_t = hybrid_model.node_items_.find(switch_t); const auto node_it_f = hybrid_model.node_items_.find(switch_f); ASSERT_NE(hybrid_model.node_items_.end(), node_it_t); diff --git a/tests/ut/ge/hybrid/model/hybrid_model_builder_unittest.cc b/tests/ut/ge/hybrid/model/hybrid_model_builder_unittest.cc index 5567aca2..10f7c0fe 100644 --- a/tests/ut/ge/hybrid/model/hybrid_model_builder_unittest.cc +++ b/tests/ut/ge/hybrid/model/hybrid_model_builder_unittest.cc @@ -214,11 +214,17 @@ TEST_F(UtestHybridModelBuilder, normal_hybrid_model_build) { ASSERT_EQ(it->second->frame_index_, index); ASSERT_EQ(it->second->parent_frame_, -1); }; - TestFrameGroup(enter1, control_group_index); - TestFrameGroup(active1, control_group_index); - TestFrameGroup(active2, control_group_index); - TestFrameGroup(active3, control_group_index); - TestFrameGroup(output1, -1); + auto root_graph = hybrid_model.root_graph_; + auto enter1_node = root_graph->FindNode("enter"); + auto active1_node = root_graph->FindNode("active1"); + auto active2_node = root_graph->FindNode("active2"); + auto active3_node = root_graph->FindNode("active3"); + auto output1_node = root_graph->FindNode("net_output"); + TestFrameGroup(enter1_node, control_group_index); + TestFrameGroup(active1_node, control_group_index); + TestFrameGroup(active2_node, control_group_index); + TestFrameGroup(active3_node, control_group_index); + TestFrameGroup(output1_node, -1); engine_mapping.clear(); task_executor.clear(); @@ -373,4 +379,14 @@ TEST_F(UtestHybridModelBuilder, TestInitHcclExecutorOnDemand) { NodeExecutorManager::GetInstance().builders_.erase(NodeExecutorManager::ExecutorType::HCCL); ASSERT_EQ(HybridModelBuilder::InitHcclExecutorOnDemand(ge_model), SUCCESS); } + +TEST_F(UtestHybridModelBuilder, copy_graph_success) { +ComputeGraphPtr graph = std::make_shared("test"); +GeRootModelPtr ge_root_model = make_shared(graph); +HybridModel hybrid_model(ge_root_model); +HybridModelBuilder hybrid_model_builder(hybrid_model); + +Status st = hybrid_model_builder.CopyGraph(); +EXPECT_EQ(st, SUCCESS); +} } // namespace ge From deecaf160a6a18ca9fa075606163fa16e53dba23 Mon Sep 17 00:00:00 2001 From: wq160 Date: Mon, 28 Jun 2021 10:37:15 +0800 Subject: [PATCH 11/20] Temporarily disable ImmediateRePass --- ge/graph/passes/infer_base_pass.cc | 5 ++--- tests/ut/ge/graph/passes/infer_base_pass_unittest.cc | 4 ++-- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/ge/graph/passes/infer_base_pass.cc b/ge/graph/passes/infer_base_pass.cc index 27eb0c54..25c45677 100644 --- a/ge/graph/passes/infer_base_pass.cc +++ b/ge/graph/passes/infer_base_pass.cc @@ -84,9 +84,8 @@ Status InferBasePass::Run(NodePtr &node) { bool InferBasePass::NeedInfer(const NodePtr &node) const { return true; } void InferBasePass::AddChangedNodesImmediateRepass(const std::set &changed_nodes) { - for (const auto &node_ele : changed_nodes) { - AddImmediateRePassNode(node_ele); - } +// need passed_nodes set to solve the problem that multi-input operators do repass in advance. +// when there is passed_nodes set, wo should call AddImmediateRePassNode for all nodes in changed_nodes. } graphStatus InferBasePass::InferAndUpdate(NodePtr &node, bool before_subgraph, std::set &changed_nodes) { diff --git a/tests/ut/ge/graph/passes/infer_base_pass_unittest.cc b/tests/ut/ge/graph/passes/infer_base_pass_unittest.cc index e9247f75..24cc5c1b 100644 --- a/tests/ut/ge/graph/passes/infer_base_pass_unittest.cc +++ b/tests/ut/ge/graph/passes/infer_base_pass_unittest.cc @@ -255,7 +255,7 @@ TEST_F(UtestGraphInferBasePassStub, AddCurNodeRepass_NotCallUpdatePeerNode_WhenI EXPECT_EQ(stub_base_pass.Run(add_node), SUCCESS); EXPECT_EQ(stub_base_pass.call_infer_times, 1); EXPECT_EQ(stub_base_pass.call_update_tensor_desc_times, 0); - EXPECT_EQ(stub_base_pass.GetNodesNeedRePassImmediately(), std::unordered_set({add_node})); +// EXPECT_EQ(stub_base_pass.GetNodesNeedRePassImmediately(), std::unordered_set({add_node})); } TEST_F(UtestGraphInferBasePassStub, NotAddPeerNodeRepass_AfterUpdatePeerNode_WhenUnchanged) { @@ -291,7 +291,7 @@ TEST_F(UtestGraphInferBasePassStub, AddPeerNodeRepass_AfterUpdatePeerNode_WhenCh EXPECT_EQ(stub_base_pass.Run(add_node), SUCCESS); EXPECT_EQ(stub_base_pass.call_update_tensor_desc_times, 1); - EXPECT_EQ(stub_base_pass.GetNodesNeedRePassImmediately(), std::unordered_set({netoutput})); +// EXPECT_EQ(stub_base_pass.GetNodesNeedRePassImmediately(), std::unordered_set({netoutput})); } TEST_F(UtestGraphInferBasePassStub, TestUpdateSubgraphData_WhenBeforeSubgraph) { From e9bab262b736d4d56e3d78c8ed921fa811b752bd Mon Sep 17 00:00:00 2001 From: zhaozhixuan Date: Mon, 28 Jun 2021 16:43:47 +0800 Subject: [PATCH 12/20] Fix bug of aicore input const. --- ge/single_op/task/op_task.cc | 54 +++++++++++++++++++++--- ge/single_op/task/op_task.h | 2 + tests/ut/ge/single_op/single_op_task_unittest.cc | 37 ++++++++++++++-- 3 files changed, 83 insertions(+), 10 deletions(-) diff --git a/ge/single_op/task/op_task.cc b/ge/single_op/task/op_task.cc index b6a78f9e..92d1e325 100755 --- a/ge/single_op/task/op_task.cc +++ b/ge/single_op/task/op_task.cc @@ -345,6 +345,53 @@ Status TbeOpTask::AllocateWorkspaces(const vector &workspace_sizes) { return SUCCESS; } +Status TbeOpTask::UpdateIoAddr(std::vector &args, const std::vector &inputs, + const std::vector &outputs) { + uintptr_t *arg_base = nullptr; + size_t arg_num = 0; + GetIoAddr(arg_base, arg_num); + + const vector v_is_input_const = op_desc_->GetIsInputConst(); + size_t non_const_index = 0; + for (size_t i = 0; i < op_desc_->GetAllInputsSize(); ++i) { + const GeTensorDescPtr tensor_desc = op_desc_->MutableInputDesc(static_cast(i)); + if (tensor_desc == nullptr) { + GELOGD("SingleOp: %s, Index: %zu, has no input", op_desc_->GetName().c_str(), i); + continue; + } + if (i < v_is_input_const.size() && v_is_input_const[i]) { + if (i >= arg_num) { + GELOGE(ACL_ERROR_GE_PARAM_INVALID, "[Check][Size] Args size is %zu, but get index is %zu.", arg_num, i); + REPORT_INNER_ERROR("E19999", "[Check][Size] Args size is %zu, but get index is %zu.", arg_num, i); + return ACL_ERROR_GE_PARAM_INVALID; + } + auto addr = reinterpret_cast(arg_base[i]); + GELOGD("SingleOp: %s, Index: %zu, input is const, addr = %p", op_desc_->GetName().c_str(), i, addr); + args.emplace_back(addr); + continue; + } + if (non_const_index >= inputs.size()) { + GELOGE(ACL_ERROR_GE_PARAM_INVALID, "[Check][Size] Input size is %zu, but get non_const_index is %zu", + inputs.size(), non_const_index); + REPORT_INNER_ERROR("E19999", "[Check][Size] Input size is %zu, but get non_const_index is %zu", + inputs.size(), non_const_index); + return ACL_ERROR_GE_PARAM_INVALID; + } + auto addr = inputs[non_const_index].data; + GELOGD("SingleOp: %s, input[%zu], addr = %p", op_desc_->GetName().c_str(), i, addr); + args.emplace_back(addr); + non_const_index++; + } + + for (size_t i = 0; i < outputs.size(); ++i) { + auto addr = outputs[i].data; + GELOGD("SingleOp: %s, output[%zu] addr = %p", op_desc_->GetName().c_str(), i, addr); + args.emplace_back(addr); + } + + return SUCCESS; +} + Status TbeOpTask::LaunchKernel(const vector &input_desc, const vector &input_buffers, vector &output_desc, @@ -355,12 +402,7 @@ Status TbeOpTask::LaunchKernel(const vector &input_desc, GE_CHK_STATUS_RET_NOLOG(UpdateRunInfo()); GE_CHK_STATUS_RET(AllocateWorkspaces(run_info_workspaces_), "[Allocate][Workspaces] failed."); std::vector args; - for (auto &buffer : input_buffers) { - args.emplace_back(buffer.data); - } - for (auto &buffer : output_buffers) { - args.emplace_back(buffer.data); - } + GE_CHK_STATUS_RET(UpdateIoAddr(args, input_buffers, output_buffers), "[Update][IoAddr] failed."); for (auto &buffer : workspaces_) { args.emplace_back(buffer); } diff --git a/ge/single_op/task/op_task.h b/ge/single_op/task/op_task.h index 19320bc0..0cbc1a29 100644 --- a/ge/single_op/task/op_task.h +++ b/ge/single_op/task/op_task.h @@ -101,6 +101,8 @@ class TbeOpTask : public OpTask { const vector &output_desc); Status AllocateWorkspaces(const std::vector &workspace_sizes); Status DoLaunchKernel(rtStream_t stream); + Status UpdateIoAddr(std::vector &args, const std::vector &inputs, + const std::vector &outputs); const void *stub_func_ = nullptr; std::unique_ptr args_; diff --git a/tests/ut/ge/single_op/single_op_task_unittest.cc b/tests/ut/ge/single_op/single_op_task_unittest.cc index a17c9012..472a88c3 100644 --- a/tests/ut/ge/single_op/single_op_task_unittest.cc +++ b/tests/ut/ge/single_op/single_op_task_unittest.cc @@ -91,8 +91,9 @@ TEST_F(UtestSingleOpTask, test_build_kernel_task) { TbeOpTask task_tmp; TbeOpTask *task = &task_tmp; ASSERT_EQ(model.BuildKernelTask(task_def, &task), SUCCESS); + ge::DataBuffer data_buffer; vector input_desc; - vector input_buffers; + vector input_buffers = { data_buffer }; vector output_desc; vector output_buffers; task->node_ = node; @@ -110,8 +111,36 @@ TEST_F(UtestSingleOpTask, test_build_kernel_task) { task->args_.reset(&task_args); ASSERT_EQ(task->LaunchKernel(input_desc, input_buffers, output_desc, output_buffers, stream_), SUCCESS); - char handle_tmp = '0'; - char *handle = &handle_tmp; + char *handle = "00"; task->SetHandle(handle); ASSERT_EQ(task->LaunchKernel(input_desc, input_buffers, output_desc, output_buffers, stream_), SUCCESS); -} \ No newline at end of file +} + +TEST_F(UtestSingleOpTask, test_update_ioaddr) { + auto graph = make_shared("graph"); + auto op_desc = make_shared("Add", "Add"); + + GeTensorDesc desc; + op_desc->AddInputDesc(desc); + op_desc->AddInputDesc(desc); + op_desc->AddOutputDesc(desc); + vector is_input_const = { true, false }; + op_desc->SetIsInputConst(is_input_const); + auto node = graph->AddNode(op_desc); + + TbeOpTask task; + task.op_desc_ = op_desc; + task.args_.reset(new (std::nothrow) uint8_t[sizeof(void *) * 3]); + + vector args; + vector inputs; + vector outputs; + ASSERT_EQ(task.UpdateIoAddr(args, inputs, outputs), ACL_ERROR_GE_PARAM_INVALID); + task.arg_size_ = sizeof(void *) * 3; + ASSERT_EQ(task.UpdateIoAddr(args, inputs, outputs), ACL_ERROR_GE_PARAM_INVALID); + + ge::DataBuffer data_buffer; + inputs = { data_buffer }; + ASSERT_EQ(task.UpdateIoAddr(args, inputs, outputs), SUCCESS); +} + From b9715a14584132d72ca9dd49811a943852730eca Mon Sep 17 00:00:00 2001 From: zhangxiaokun Date: Mon, 28 Jun 2021 19:23:31 +0800 Subject: [PATCH 13/20] DSP: Switch -> TransData -> Cast -> Exit --- ge/graph/passes/next_iteration_pass.cc | 33 +++++++++++++++++---------- ge/hybrid/executor/worker/execution_engine.cc | 2 +- 2 files changed, 22 insertions(+), 13 deletions(-) diff --git a/ge/graph/passes/next_iteration_pass.cc b/ge/graph/passes/next_iteration_pass.cc index fb8f8627..1c2d7218 100644 --- a/ge/graph/passes/next_iteration_pass.cc +++ b/ge/graph/passes/next_iteration_pass.cc @@ -24,7 +24,9 @@ using std::string; namespace ge { namespace { -const int64_t kLoopType = 1; +constexpr int64_t kLoopType = 1; +constexpr uint8_t kMaxTransOp = 3; +constexpr uint8_t kTransOpIoSize = 1; } Status NextIterationPass::Run(ComputeGraphPtr graph) { @@ -287,18 +289,25 @@ void NextIterationPass::HandleSwitchExitNodes(const LoopCondGroup &loop_group, i std::string node_type; for (const auto &switch_node : loop_group.switch_nodes) { SetControlFlowGroup(switch_node, group_index); - for (const auto &node : switch_node->GetOutDataNodes()) { - (void)GetOriginalType(node, node_type); - if (kExitOpTypes.count(node_type) > 0) { - SetControlFlowGroup(node, group_index); - } else { - // For: Switch -> Cast -> Exit - for (const auto &n : node->GetOutDataNodes()) { - (void)GetOriginalType(n, node_type); - if (kExitOpTypes.count(node_type) > 0) { - SetControlFlowGroup(n, group_index); - } + for (auto node : switch_node->GetOutDataNodes()) { + // Switch --> Exit + // Switch --> Cast --> Exit + // Switch --> TransData --> Cast --> Exit + for (uint8_t i = 0; i < kMaxTransOp; ++i) { + if (node->GetInDataNodes().size() != kTransOpIoSize || node->GetAllOutDataAnchorsSize() != kTransOpIoSize) { + break; } + + if (kExitOpTypes.count(NodeUtils::GetNodeType(node)) > 0) { + SetControlFlowGroup(node, group_index); + break; + } + + const auto &all_nodes = node->GetOutAllNodes(); + if (all_nodes.size() != kTransOpIoSize) { + break; + } + node = all_nodes.at(0); } } } diff --git a/ge/hybrid/executor/worker/execution_engine.cc b/ge/hybrid/executor/worker/execution_engine.cc index d4c73f58..ca864244 100755 --- a/ge/hybrid/executor/worker/execution_engine.cc +++ b/ge/hybrid/executor/worker/execution_engine.cc @@ -373,9 +373,9 @@ Status ExecutionEngine::DoExecuteAsync(NodeState &node_state, auto executor = node_item.node_executor; GE_CHECK_NOTNULL(executor); RECORD_EXECUTION_EVENT(&context, task_context.GetNodeName(), "[PrepareTask] Start"); + node_state.UpdatePersistTensor(); GE_CHK_STATUS_RET(executor->PrepareTask(*task, task_context), "[Prepare][Task] for [%s] failed.", node_state.GetName().c_str()); - node_state.UpdatePersistTensor(); RECORD_EXECUTION_EVENT(&context, task_context.GetNodeName(), "[PrepareTask] End"); GELOGD("[%s] Done task preparation successfully.", node_state.GetName().c_str()); From 98f34a58bbf8cad99b7e127942c83389a6305574 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=8D=8E?= Date: Wed, 23 Jun 2021 19:36:26 +0800 Subject: [PATCH 14/20] opt info --- CMakeLists.txt | 1 + ge/CMakeLists.txt | 8 ++ ge/ge_opt_info/ge_opt_info.cc | 58 +++++++++++ ge/ge_opt_info/ge_opt_info.h | 31 ++++++ ge/graph/manager/graph_manager.cc | 7 ++ tests/CMakeLists.txt | 1 + tests/depends/opt_info/CMakeLists.txt | 37 +++++++ tests/depends/opt_info/src/opt_info_stub.cc | 46 +++++++++ tests/framework/cmake/graphengine.cmake | 2 + tests/st/testcase/test_ge_opt_info.cc | 123 ++++++++++++++++++++++++ tests/ut/ge/CMakeLists.txt | 14 +++ tests/ut/ge/ge_opt_info/ge_opt_info_unittest.cc | 82 ++++++++++++++++ third_party/fwkacllib/inc/opt_info/opt_info.h | 32 ++++++ 13 files changed, 442 insertions(+) create mode 100644 ge/ge_opt_info/ge_opt_info.cc create mode 100644 ge/ge_opt_info/ge_opt_info.h create mode 100644 tests/depends/opt_info/CMakeLists.txt create mode 100644 tests/depends/opt_info/src/opt_info_stub.cc create mode 100644 tests/st/testcase/test_ge_opt_info.cc create mode 100644 tests/ut/ge/ge_opt_info/ge_opt_info_unittest.cc create mode 100644 third_party/fwkacllib/inc/opt_info/opt_info.h diff --git a/CMakeLists.txt b/CMakeLists.txt index e3cc1e32..41520b14 100755 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -95,6 +95,7 @@ else () #find_module(ascendcl_static libascendcl.a ${GE_LIB_PATH}) else() find_module(slog libalog.so ${ASCEND_ATC_DIR}) + find_module(opt_feature libopt_feature.so ${ASCEND_ATC_DIR}) find_module(static_mmpa libmmpa.a ${ASCEND_ATC_DIR}) if(PLATFORM STREQUAL "train") find_module(adump_server libadump_server.a ${ASCEND_RUNTIME_DIR}) diff --git a/ge/CMakeLists.txt b/ge/CMakeLists.txt index 2b9122da..5db2e7a9 100755 --- a/ge/CMakeLists.txt +++ b/ge/CMakeLists.txt @@ -434,6 +434,7 @@ set(TRAIN_SRC_LIST "graph/build/memory/max_block_mem_assigner.cc" "graph/build/memory/var_mem_assign_util.cc" "graph/build/memory/buffer_pool_mem_assigner.cc" + "ge_opt_info/ge_opt_info.cc" ) set(INFER_SRC_LIST @@ -711,6 +712,7 @@ set(INFER_SRC_LIST "graph/build/memory/max_block_mem_assigner.cc" "graph/build/memory/var_mem_assign_util.cc" "graph/build/memory/buffer_pool_mem_assigner.cc" + "ge_opt_info/ge_opt_info.cc" ) if (NOT ENABLE_D AND NOT ENABLE_ACL AND NOT ENABLE_MS_TESTCASES) @@ -765,11 +767,13 @@ target_include_directories(ge_runner SYSTEM PRIVATE ${GE_CODE_DIR}/../inc ${GE_CODE_DIR}/../toolchain/ide/ide-daemon/external ${GE_CODE_DIR}/../abl/adump/external + ${GE_CODE_DIR}/../abl/licctrl #### blue zone ${ASCEND_DIR}/driver/include ${ASCEND_DIR}/fwkacllib/include ${GE_CODE_DIR}/third_party/fwkacllib/inc ${GE_CODE_DIR}/third_party/fwkacllib/inc/toolchain + ${GE_CODE_DIR}/third_party/fwkacllib/inc/opt_info ) target_link_options(ge_runner PRIVATE @@ -792,6 +796,7 @@ target_link_libraries(ge_runner PRIVATE runtime error_manager ascend_hal_stub + opt_feature -Wl,--as-needed json -lrt @@ -839,11 +844,13 @@ target_include_directories(ge_compiler SYSTEM PRIVATE ${GE_CODE_DIR}/../inc ${GE_CODE_DIR}/../toolchain/ide/ide-daemon/external ${GE_CODE_DIR}/../abl/adump/external + ${GE_CODE_DIR}/../abl/licctrl #### blue zone #### ${ASCEND_DIR}/driver/include ${ASCEND_DIR}/fwkacllib/include ${GE_CODE_DIR}/third_party/fwkacllib/inc ${GE_CODE_DIR}/third_party/fwkacllib/inc/toolchain + ${GE_CODE_DIR}/third_party/fwkacllib/inc/opt_info ) target_link_options(ge_compiler PRIVATE @@ -863,6 +870,7 @@ target_link_libraries(ge_compiler PRIVATE error_manager slog runtime_compile + opt_feature -Wl,--as-needed json -lrt diff --git a/ge/ge_opt_info/ge_opt_info.cc b/ge/ge_opt_info/ge_opt_info.cc new file mode 100644 index 00000000..8c1b84ab --- /dev/null +++ b/ge/ge_opt_info/ge_opt_info.cc @@ -0,0 +1,58 @@ +/** + * Copyright 2021 Huawei Technologies Co., Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ge_opt_info/ge_opt_info.h" + +#include +#include +#include "graph/ge_local_context.h" +#include "ge/ge_api_types.h" +#include "common/debug/ge_log.h" +#include "opt_info.h" + +namespace ge { +Status GeOptInfo::SetOptInfo() { + std::string soc_ver; + graphStatus ret = GetThreadLocalContext().GetOption(SOC_VERSION, soc_ver); + if (ret != GRAPH_SUCCESS) { + REPORT_CALL_ERROR("E19999", "Get soc version failed."); + GELOGE(FAILED, "[Get][SocVersion]Get soc version failed."); + return FAILED; + } + GELOGD("Soc version:%s.", soc_ver.c_str()); + std::map opt_info; + // the first arg does not work at present. + if (gelc::GetOptInfo(gelc::kOffline, soc_ver, opt_info) != gelc::SUCCESS) { + REPORT_CALL_ERROR("E19999", "Get optional information failed, is_offline:%d, soc version:%s", + gelc::kOffline, soc_ver.c_str()); + GELOGE(FAILED, "[Get][OptInfo]Get optional information failed, is_offline:%d, soc version:%s", + gelc::kOffline, soc_ver.c_str()); + return FAILED; + } + // do nothing if get empty information + if (opt_info.empty()) { + GELOGI("Optional information is empty."); + return SUCCESS; + } + std::map graph_options = GetThreadLocalContext().GetAllGraphOptions(); + for (const auto &itr : opt_info) { + graph_options.emplace(itr.first, itr.second); + GELOGI("Get optional information success, key:%s, value:%s.", itr.first.c_str(), itr.second.c_str()); + } + GetThreadLocalContext().SetGraphOption(graph_options); + return SUCCESS; +} +} // namespace ge diff --git a/ge/ge_opt_info/ge_opt_info.h b/ge/ge_opt_info/ge_opt_info.h new file mode 100644 index 00000000..935dff25 --- /dev/null +++ b/ge/ge_opt_info/ge_opt_info.h @@ -0,0 +1,31 @@ +/** + * Copyright 2021 Huawei Technologies Co., Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef GE_OPT_INFO_GE_OPT_INFO_H_ +#define GE_OPT_INFO_GE_OPT_INFO_H_ + +#include "ge/ge_api_error_codes.h" +#include "register/register_types.h" + +namespace ge { +class FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY GeOptInfo { + public: + GeOptInfo() = default; + static Status SetOptInfo(); +}; +} // namespace ge + +#endif // GE_OPT_INFO_GE_OPT_INFO_H_ diff --git a/ge/graph/manager/graph_manager.cc b/ge/graph/manager/graph_manager.cc index b862a7d6..0a4633ad 100755 --- a/ge/graph/manager/graph_manager.cc +++ b/ge/graph/manager/graph_manager.cc @@ -27,6 +27,7 @@ #include "common/math/math_util.h" #include "common/thread_pool.h" #include "common/dump/dump_manager.h" +#include "ge_opt_info/ge_opt_info.h" #include "analyzer/analyzer.h" #include "graph/common/ge_call_wrapper.h" #include "graph/common/local_context.h" @@ -1001,6 +1002,12 @@ Status GraphManager::PreRun(const GraphNodePtr &graph_node, const std::vector + c_sec +) + +target_include_directories(opt_feature_stub INTERFACE ${CMAKE_CURRENT_LIST_DIR}/src) diff --git a/tests/depends/opt_info/src/opt_info_stub.cc b/tests/depends/opt_info/src/opt_info_stub.cc new file mode 100644 index 00000000..df518c4b --- /dev/null +++ b/tests/depends/opt_info/src/opt_info_stub.cc @@ -0,0 +1,46 @@ +/** + * Copyright 2021 Huawei Technologies Co., Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "opt_info.h" +#include +#include +#include +#include + +namespace gelc { +namespace { +const std::vector kSocVersions = {"Ascend910"}; +} + +void SetAllOptInfo(std::map &opt_infos) { + opt_infos.emplace("opt_module.fe", "all"); + opt_infos.emplace("opt_module.pass", "all"); + opt_infos.emplace("opt_module.op_tune", "all"); + opt_infos.emplace("opt_module.rl_tune", "all"); + opt_infos.emplace("opt_module.aoe", "all"); +} + +Status GetOptInfo(WorkMode mode, const std::string &soc_ver, + std::map &opt_infos) { + if (std::find(kSocVersions.begin(), kSocVersions.end(), soc_ver)== kSocVersions.end()) { + SetAllOptInfo(opt_infos); + return SUCCESS; + } + opt_infos.emplace("opt_module.fe", "all"); + opt_infos.emplace("opt_module.pass", "all"); + opt_infos.emplace("opt_module.op_tune", "all"); + return SUCCESS; +} +} // namespace gelc diff --git a/tests/framework/cmake/graphengine.cmake b/tests/framework/cmake/graphengine.cmake index 81aa00cc..c4380016 100644 --- a/tests/framework/cmake/graphengine.cmake +++ b/tests/framework/cmake/graphengine.cmake @@ -103,6 +103,7 @@ list(APPEND INCLUDE_DIRECTORIES "${GE_CODE_DIR}/third_party/fwkacllib/inc/cce" "${GE_CODE_DIR}/third_party/fwkacllib/inc/ops" "${GE_CODE_DIR}/third_party/fwkacllib/inc/toolchain" + "${GE_CODE_DIR}/third_party/fwkacllib/inc/opt_info" "${GE_CODE_DIR}/tests/ut/ge" "${GE_CODE_DIR}/tests/ut/common" "${CMAKE_BINARY_DIR}" @@ -117,6 +118,7 @@ list(APPEND STUB_LIBS runtime_stub profiler_stub hccl_stub + opt_feature_stub error_manager_stub ascend_protobuf json diff --git a/tests/st/testcase/test_ge_opt_info.cc b/tests/st/testcase/test_ge_opt_info.cc new file mode 100644 index 00000000..457473b1 --- /dev/null +++ b/tests/st/testcase/test_ge_opt_info.cc @@ -0,0 +1,123 @@ +/** + * Copyright 2021 Huawei Technologies Co., Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include "easy_graph/graph/box.h" +#include "easy_graph/graph/node.h" +#include "easy_graph/builder/graph_dsl.h" +#include "easy_graph/builder/box_builder.h" +#include "easy_graph/layout/graph_layout.h" +#include "easy_graph/layout/engines/graph_easy/graph_easy_option.h" +#include "easy_graph/layout/engines/graph_easy/graph_easy_executor.h" +#include "graph/graph.h" +#include "graph/compute_graph.h" +#include "framework/common/types.h" +#include "graph/debug/ge_attr_define.h" +#include "ge_graph_dsl/graph_dsl.h" +#include "ge_graph_dsl/op_desc/op_desc_cfg_box.h" +#define protected public +#define private public +#include "ge_opt_info/ge_opt_info.h" +#undef private +#undef protected + +namespace ge { +class STEST_opt_info : public testing::Test { + protected: + void SetUp() {} + void TearDown() {} +}; + +TEST_F(STEST_opt_info, get_opt_info_all) { + std::map options = {{ge::SOC_VERSION, "Ascend310"}}; + GetThreadLocalContext().SetGlobalOption(options); + + /// data1 data2 + /// \ / + /// add + // build graph + DEF_GRAPH(g1) { + CHAIN(NODE("data1", DATA)->NODE("add", ADD)); + CHAIN(NODE("data2", DATA)->NODE("add")); + }); + + auto graph = ToGeGraph(g1); + + // new session & add graph + Session session(options); + auto ret = session.AddGraph(1, graph, options); + EXPECT_EQ(ret, SUCCESS); + // build input tensor + std::vector inputs; + // build_graph through session + ret = session.BuildGraph(1, inputs); + EXPECT_EQ(ret, SUCCESS); + + std::map graph_options = GetThreadLocalContext().GetAllGraphOptions(); + auto itr = graph_options.find("opt_module.fe"); + EXPECT_NE(itr, graph_options.end()); + EXPECT_EQ(itr->second, "all"); + itr = graph_options.find("opt_module.pass"); + EXPECT_NE(itr, graph_options.end()); + EXPECT_EQ(itr->second, "all"); + itr = graph_options.find("opt_module.op_tune"); + EXPECT_NE(itr, graph_options.end()); + EXPECT_EQ(itr->second, "all"); + itr = graph_options.find("opt_module.rl_tune"); + EXPECT_NE(itr, graph_options.end()); + EXPECT_EQ(itr->second, "all"); + itr = graph_options.find("opt_module.aoe"); + EXPECT_NE(itr, graph_options.end()); + EXPECT_EQ(itr->second, "all"); +} + +TEST_F(STEST_opt_info, get_opt_info_success) { + std::map options = {{ge::SOC_VERSION, "Ascend910"}}; + GetThreadLocalContext().SetGlobalOption(options); + + /// data1 data2 + /// \ / + /// add + // build graph + DEF_GRAPH(g1) { + CHAIN(NODE("data1", DATA)->NODE("add", ADD)); + CHAIN(NODE("data2", DATA)->NODE("add")); + }); + + auto graph = ToGeGraph(g1); + + // new session & add graph + Session session(options); + auto ret = session.AddGraph(1, graph, options); + EXPECT_EQ(ret, SUCCESS); + // build input tensor + std::vector inputs; + // build_graph through session + ret = session.BuildGraph(1, inputs); + EXPECT_EQ(ret, SUCCESS); + + std::map graph_options = GetThreadLocalContext().GetAllGraphOptions(); + auto itr = graph_options.find("opt_module.fe"); + EXPECT_NE(itr, graph_options.end()); + EXPECT_EQ(itr->second, "all"); + itr = graph_options.find("opt_module.pass"); + EXPECT_NE(itr, graph_options.end()); + EXPECT_EQ(itr->second, "all"); + itr = graph_options.find("opt_module.op_tune"); + EXPECT_NE(itr, graph_options.end()); + EXPECT_EQ(itr->second, "all"); +} +} // namespace ge diff --git a/tests/ut/ge/CMakeLists.txt b/tests/ut/ge/CMakeLists.txt index 06b3e0f2..cf573343 100755 --- a/tests/ut/ge/CMakeLists.txt +++ b/tests/ut/ge/CMakeLists.txt @@ -62,6 +62,7 @@ include_directories(${GE_CODE_DIR}/third_party/fwkacllib/inc) include_directories(${GE_CODE_DIR}/third_party/fwkacllib/inc/cce) include_directories(${GE_CODE_DIR}/third_party/fwkacllib/inc/ops) include_directories(${GE_CODE_DIR}/third_party/fwkacllib/inc/toolchain) +include_directories(${GE_CODE_DIR}/third_party/fwkacllib/inc/opt_info) include_directories(${GE_CODE_DIR}/tests/ut/ge) include_directories(${GE_CODE_DIR}/tests/ut/common) include_directories(${CMAKE_BINARY_DIR}) @@ -346,6 +347,7 @@ set(COMMON_SRC_FILES "${GE_CODE_DIR}/ge/common/ge/datatype_util.cc" "${GE_CODE_DIR}/ge/ge_local_engine/engine/host_cpu_engine.cc" "${GE_CODE_DIR}/ge/session/omg.cc" + "${GE_CODE_DIR}/ge/ge_opt_info/ge_opt_info.cc" ) set(COMMON_FORMAT_SRC_FILES @@ -453,6 +455,7 @@ set(GRAPH_EXECUTE_COMMON_SRC_FILES "${GE_CODE_DIR}/ge/graph/manager/graph_manager.cc" "${GE_CODE_DIR}/ge/graph/manager/graph_context.cc" "${GE_CODE_DIR}/ge/graph/manager/util/rt_context_util.cc" + "${GE_CODE_DIR}/ge/ge_opt_info/ge_opt_info.cc" "${GE_CODE_DIR}/ge/graph/manager/graph_context.h" ) @@ -628,6 +631,10 @@ set(SINGLE_OP_SRC_FILES "${GE_CODE_DIR}/ge/hybrid/hybrid_davinci_model.cc" ) +set(GE_OPT_INFO_SRC_FILES + "${GE_CODE_DIR}/ge/ge_opt_info/ge_opt_info.cc" +) + # test files set(COMMON_TEST_FILES "graph/passes/graph_builder_utils.cc" @@ -813,6 +820,10 @@ set(MULTI_PARTS_TEST_FILES "common/host_cpu_engine_unittest.cc" ) +set(GE_OPT_INFO_TEST_FILES + "ge_opt_info/ge_opt_info_unittest.cc" +) + set(GENERATOR_TEST_FILES "generator/ge_generator_unittest.cc" ) @@ -864,6 +875,7 @@ list(APPEND COMMON_SHARED_LIBRARIES mmpa_stub hccl_stub error_manager_stub + opt_feature_stub ascend_protobuf json ) @@ -1109,10 +1121,12 @@ target_link_libraries(ut_libge_multiparts_utest # libge_others_utest add_executable(ut_libge_others_utest + ${GE_OPT_INFO_SRC_FILES} ${COMMON_TEST_FILES} ${PASS_TEST_FILES} ${EXECUTE_TEST_FILES} ${OTHERS_TEST_FILES} + ${GE_OPT_INFO_TEST_FILES} ) target_compile_options(ut_libge_others_utest PRIVATE diff --git a/tests/ut/ge/ge_opt_info/ge_opt_info_unittest.cc b/tests/ut/ge/ge_opt_info/ge_opt_info_unittest.cc new file mode 100644 index 00000000..20c123e9 --- /dev/null +++ b/tests/ut/ge/ge_opt_info/ge_opt_info_unittest.cc @@ -0,0 +1,82 @@ +/** + * Copyright 2021 Huawei Technologies Co., Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#define protected public +#define private public +#include "ge_opt_info/ge_opt_info.h" +#include "graph/ge_local_context.h" +#include "external/ge/ge_api_types.h" +#undef private +#undef protected + +namespace ge { +class UTEST_opt_info : public testing::Test { + protected: + void SetUp() {} + void TearDown() {} +}; + +TEST_F(UTEST_opt_info, get_opt_info_success) { + std::map options = {{ge::SOC_VERSION, "Ascend910"}}; + GetThreadLocalContext().SetGlobalOption(options); + auto ret = GeOptInfo::SetOptInfo(); + EXPECT_EQ(ret, ge::SUCCESS); + std::map graph_options = GetThreadLocalContext().GetAllGraphOptions(); + auto itr = graph_options.find("opt_module.fe"); + EXPECT_NE(itr, graph_options.end()); + EXPECT_EQ(itr->second, "all"); + itr = graph_options.find("opt_module.pass"); + EXPECT_NE(itr, graph_options.end()); + EXPECT_EQ(itr->second, "all"); + itr = graph_options.find("opt_module.op_tune"); + EXPECT_NE(itr, graph_options.end()); + EXPECT_EQ(itr->second, "all"); +} + +TEST_F(UTEST_opt_info, get_opt_info_all) { + std::map global_options = {{ge::SOC_VERSION, "Ascend310"}}; + GetThreadLocalContext().SetGlobalOption(global_options); + auto ret = GeOptInfo::SetOptInfo(); + EXPECT_EQ(ret, ge::SUCCESS); + std::map graph_options = GetThreadLocalContext().GetAllGraphOptions(); + auto itr = graph_options.find("opt_module.fe"); + EXPECT_NE(itr, graph_options.end()); + EXPECT_EQ(itr->second, "all"); + itr = graph_options.find("opt_module.pass"); + EXPECT_NE(itr, graph_options.end()); + EXPECT_EQ(itr->second, "all"); + itr = graph_options.find("opt_module.op_tune"); + EXPECT_NE(itr, graph_options.end()); + EXPECT_EQ(itr->second, "all"); + itr = graph_options.find("opt_module.rl_tune"); + EXPECT_NE(itr, graph_options.end()); + EXPECT_EQ(itr->second, "all"); + itr = graph_options.find("opt_module.aoe"); + EXPECT_NE(itr, graph_options.end()); + EXPECT_EQ(itr->second, "all"); +} + +TEST_F(UTEST_opt_info, get_opt_info_failed) { + std::map options; + GetThreadLocalContext().SetGlobalOption(options); + auto ret = GeOptInfo::SetOptInfo(); + EXPECT_EQ(ret, ge::FAILED); +} + +} // namespace ge diff --git a/third_party/fwkacllib/inc/opt_info/opt_info.h b/third_party/fwkacllib/inc/opt_info/opt_info.h new file mode 100644 index 00000000..4dff695b --- /dev/null +++ b/third_party/fwkacllib/inc/opt_info/opt_info.h @@ -0,0 +1,32 @@ +/** + * Copyright 2021 Huawei Technologies Co., Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +namespace gelc { +using Status = uint32_t; +using WorkMode = uint32_t; +const Status SUCCESS = 0x0; +const Status FAILED = 0xFFFFFFFF; +const WorkMode kOffline = 0x0; +const WorkMode kInline = 0x01; + +__attribute__((visibility ("default"))) +Status GetOptInfo(WorkMode mode, const std::string &soc_ver, + std::map &opt_info_map); +} // namespace gelc + From ae348cf55a6cb7c5729dd6b4b5fb700723e8362b Mon Sep 17 00:00:00 2001 From: zhaozhixuan Date: Tue, 29 Jun 2021 15:42:36 +0800 Subject: [PATCH 15/20] Fix ut. --- ge/single_op/task/op_task.cc | 120 ++++++++++++----------- ge/single_op/task/op_task.h | 6 +- ge/single_op/task/tbe_task_builder.cc | 1 + tests/ut/ge/single_op/single_op_task_unittest.cc | 23 +++-- tests/ut/ge/single_op/single_op_unittest.cc | 2 +- 5 files changed, 84 insertions(+), 68 deletions(-) diff --git a/ge/single_op/task/op_task.cc b/ge/single_op/task/op_task.cc index 92d1e325..632cd4d8 100755 --- a/ge/single_op/task/op_task.cc +++ b/ge/single_op/task/op_task.cc @@ -345,14 +345,46 @@ Status TbeOpTask::AllocateWorkspaces(const vector &workspace_sizes) { return SUCCESS; } -Status TbeOpTask::UpdateIoAddr(std::vector &args, const std::vector &inputs, - const std::vector &outputs) { - uintptr_t *arg_base = nullptr; - size_t arg_num = 0; - GetIoAddr(arg_base, arg_num); +Status TbeOpTask::UpdateTilingArgs(rtStream_t stream) { + size_t args_size = op_desc_->GetInputsSize() + op_desc_->GetOutputsSize() + workspaces_.size(); + if (tiling_buffer_ != nullptr) { + args_size++; + } + size_t temp_size = args_size * sizeof(void *); + if (arg_size_ < temp_size) { + GELOGD("Need to reset size of args_ from %zu to %zu.", arg_size_, temp_size); + std::unique_ptr args(new (std::nothrow) uint8_t[temp_size]()); + GE_CHECK_NOTNULL(args); + if (memcpy_s(args.get(), temp_size, args_.get(), arg_size_) != EOK) { + GELOGE(ACL_ERROR_GE_MEMORY_OPERATE_FAILED, "[Update][KernelArgs] failed for [%s].", node_->GetName().c_str()); + REPORT_INNER_ERROR("E19999", "update kernel args failed for %s.", node_->GetName().c_str()); + return ACL_ERROR_GE_MEMORY_OPERATE_FAILED; + } + args_.reset(args.release()); + arg_size_ = temp_size; + } + + uintptr_t *arg_base = reinterpret_cast(args_.get()); + size_t arg_index = op_desc_->GetInputsSize() + op_desc_->GetOutputsSize(); + for (size_t i = 0; i < workspaces_.size(); ++i) { + arg_base[arg_index++] = reinterpret_cast(workspaces_[i]); + } + + if (tiling_buffer_ != nullptr) { + GELOGD("[%s] Start to copy tiling info. size = %zu", node_->GetName().c_str(), tiling_data_.size()); + GE_CHK_RT_RET(rtMemcpyAsync(tiling_buffer_, max_tiling_size_, tiling_data_.data(), tiling_data_.size(), + RT_MEMCPY_HOST_TO_DEVICE_EX, stream)); + arg_base[arg_index] = reinterpret_cast(tiling_buffer_); + } + + return SUCCESS; +} + +Status TbeOpTask::SetArgIndex() { + arg_index_.clear(); const vector v_is_input_const = op_desc_->GetIsInputConst(); - size_t non_const_index = 0; + size_t input_index = 0; for (size_t i = 0; i < op_desc_->GetAllInputsSize(); ++i) { const GeTensorDescPtr tensor_desc = op_desc_->MutableInputDesc(static_cast(i)); if (tensor_desc == nullptr) { @@ -360,33 +392,33 @@ Status TbeOpTask::UpdateIoAddr(std::vector &args, const std::vector= arg_num) { - GELOGE(ACL_ERROR_GE_PARAM_INVALID, "[Check][Size] Args size is %zu, but get index is %zu.", arg_num, i); - REPORT_INNER_ERROR("E19999", "[Check][Size] Args size is %zu, but get index is %zu.", arg_num, i); - return ACL_ERROR_GE_PARAM_INVALID; - } - auto addr = reinterpret_cast(arg_base[i]); - GELOGD("SingleOp: %s, Index: %zu, input is const, addr = %p", op_desc_->GetName().c_str(), i, addr); - args.emplace_back(addr); + GELOGD("SingleOp: %s, Index: %zu, input is const", op_desc_->GetName().c_str(), i); + input_index++; continue; } - if (non_const_index >= inputs.size()) { - GELOGE(ACL_ERROR_GE_PARAM_INVALID, "[Check][Size] Input size is %zu, but get non_const_index is %zu", - inputs.size(), non_const_index); - REPORT_INNER_ERROR("E19999", "[Check][Size] Input size is %zu, but get non_const_index is %zu", - inputs.size(), non_const_index); - return ACL_ERROR_GE_PARAM_INVALID; - } - auto addr = inputs[non_const_index].data; - GELOGD("SingleOp: %s, input[%zu], addr = %p", op_desc_->GetName().c_str(), i, addr); - args.emplace_back(addr); - non_const_index++; + arg_index_.emplace_back(input_index); + input_index++; } + return SUCCESS; +} - for (size_t i = 0; i < outputs.size(); ++i) { - auto addr = outputs[i].data; - GELOGD("SingleOp: %s, output[%zu] addr = %p", op_desc_->GetName().c_str(), i, addr); - args.emplace_back(addr); +Status TbeOpTask::UpdateIoAddr(const vector &inputs, const vector &outputs) { + if (arg_index_.size() != inputs.size()) { + GELOGE(ACL_ERROR_GE_PARAM_INVALID, "[Check][Size] Args size is %zu, but get input size is %zu.", + arg_index_.size(), inputs.size()); + REPORT_INNER_ERROR("E19999", "[Check][Size] Args size is %zu, but get input size is %zu.", + arg_index_.size(), inputs.size()); + return ACL_ERROR_GE_PARAM_INVALID; + } + + uintptr_t *arg_base = reinterpret_cast(args_.get()); + for (size_t i = 0; i < arg_index_.size(); ++i) { + arg_base[arg_index_[i]] = reinterpret_cast(inputs[i].data); + } + + size_t input_size = op_desc_->GetInputsSize(); + for (size_t i = 0; i < op_desc_->GetOutputsSize(); ++i) { + arg_base[input_size + i] = reinterpret_cast(outputs[i].data); } return SUCCESS; @@ -398,37 +430,11 @@ Status TbeOpTask::LaunchKernel(const vector &input_desc, vector &output_buffers, rtStream_t stream) { GELOGD("[%s] Start to launch kernel", node_->GetName().c_str()); + GE_CHK_STATUS_RET(UpdateIoAddr(input_buffers, output_buffers), "[Update][IoAddr] failed."); GE_CHK_STATUS_RET_NOLOG(UpdateNodeByShape(input_desc, output_desc)); GE_CHK_STATUS_RET_NOLOG(UpdateRunInfo()); GE_CHK_STATUS_RET(AllocateWorkspaces(run_info_workspaces_), "[Allocate][Workspaces] failed."); - std::vector args; - GE_CHK_STATUS_RET(UpdateIoAddr(args, input_buffers, output_buffers), "[Update][IoAddr] failed."); - for (auto &buffer : workspaces_) { - args.emplace_back(buffer); - } - - if (tiling_buffer_ != nullptr) { - GELOGD("[%s] Start to copy tiling info. size = %zu", node_->GetName().c_str(), tiling_data_.size()); - GE_CHK_RT_RET(rtMemcpyAsync(tiling_buffer_, max_tiling_size_, tiling_data_.data(), tiling_data_.size(), - RT_MEMCPY_HOST_TO_DEVICE_EX, stream)); - - args.emplace_back(tiling_buffer_); - } - - GELOGD("Dst size is %zu, src size is %zu.", arg_size_, args.size() * sizeof(void *)); - // node with workspace: build can not get size of workspace, need to update arg_size_ when execute - if (arg_size_ < (args.size() * sizeof(void *))) { - size_t temp_size = args.size() * sizeof(void *); - GELOGD("Need to reset size of args_ from %zu to %zu.", arg_size_, temp_size); - args_.reset(new(std::nothrow) uint8_t[temp_size]()); - GE_CHECK_NOTNULL(args_); - arg_size_ = temp_size; - } - if (memcpy_s(args_.get(), arg_size_, args.data(), args.size() * sizeof(void *)) != EOK) { - GELOGE(ACL_ERROR_GE_MEMORY_OPERATE_FAILED, "[Update][KernelArgs] failed for [%s].", node_->GetName().c_str()); - REPORT_INNER_ERROR("E19999", "update kernel args failed for %s.", node_->GetName().c_str()); - return ACL_ERROR_GE_MEMORY_OPERATE_FAILED; - } + GE_CHK_STATUS_RET(UpdateTilingArgs(stream), "[Update][TilingArgs] failed."); GELOGD("[%s] Start to invoke rtKernelLaunch", node_->GetName().c_str()); GE_CHK_STATUS_RET(DoLaunchKernel(stream), "Failed to do launch kernel."); diff --git a/ge/single_op/task/op_task.h b/ge/single_op/task/op_task.h index 0cbc1a29..d3e8383d 100644 --- a/ge/single_op/task/op_task.h +++ b/ge/single_op/task/op_task.h @@ -85,6 +85,7 @@ class TbeOpTask : public OpTask { const OpDescPtr &op_desc, const domi::KernelDefWithHandle& kernel_def_with_handle); Status UpdateRunInfo() override; + Status SetArgIndex(); const void *GetArgs() const; size_t GetArgSize() const; @@ -100,9 +101,9 @@ class TbeOpTask : public OpTask { Status UpdateNodeByShape(const vector &input_desc, const vector &output_desc); Status AllocateWorkspaces(const std::vector &workspace_sizes); + Status UpdateTilingArgs(rtStream_t stream); Status DoLaunchKernel(rtStream_t stream); - Status UpdateIoAddr(std::vector &args, const std::vector &inputs, - const std::vector &outputs); + Status UpdateIoAddr(const vector &inputs, const vector &outputs); const void *stub_func_ = nullptr; std::unique_ptr args_; @@ -122,6 +123,7 @@ class TbeOpTask : public OpTask { void* handle_ = nullptr; std::string original_kernel_key_; std::string node_info_; + std::vector arg_index_; }; class AiCpuBaseTask : public OpTask { diff --git a/ge/single_op/task/tbe_task_builder.cc b/ge/single_op/task/tbe_task_builder.cc index c7ff13d1..e5206ea6 100644 --- a/ge/single_op/task/tbe_task_builder.cc +++ b/ge/single_op/task/tbe_task_builder.cc @@ -387,6 +387,7 @@ Status TbeTaskBuilder::BuildTask(TbeOpTask &task, const SingleOpModelParam ¶ } task.SetStubFunc(stub_name_, stub_func); } + GE_CHK_STATUS_RET(task.SetArgIndex(), "[Set][ArgTable] failed."); return SUCCESS; } diff --git a/tests/ut/ge/single_op/single_op_task_unittest.cc b/tests/ut/ge/single_op/single_op_task_unittest.cc index 472a88c3..020efc23 100644 --- a/tests/ut/ge/single_op/single_op_task_unittest.cc +++ b/tests/ut/ge/single_op/single_op_task_unittest.cc @@ -95,7 +95,7 @@ TEST_F(UtestSingleOpTask, test_build_kernel_task) { vector input_desc; vector input_buffers = { data_buffer }; vector output_desc; - vector output_buffers; + vector output_buffers = { data_buffer }; task->node_ = node; OpTilingFunc op_tiling_func = [](const TeOpParas &, const OpCompileInfo &, OpRunInfo &) -> bool {return true;}; OpTilingRegistryInterf("Add", op_tiling_func); @@ -107,8 +107,7 @@ TEST_F(UtestSingleOpTask, test_build_kernel_task) { task->max_tiling_size_ = 64; task->tiling_data_ = "tiling_data"; task->arg_size_ = 64; - uint8_t task_args{0}; - task->args_.reset(&task_args); + task->args_.reset(new (std::nothrow) uint8_t[sizeof(void *) * 3]); ASSERT_EQ(task->LaunchKernel(input_desc, input_buffers, output_desc, output_buffers, stream_), SUCCESS); char *handle = "00"; @@ -130,17 +129,25 @@ TEST_F(UtestSingleOpTask, test_update_ioaddr) { TbeOpTask task; task.op_desc_ = op_desc; - task.args_.reset(new (std::nothrow) uint8_t[sizeof(void *) * 3]); + task.node_ = node; + ASSERT_EQ(task.SetArgIndex(), SUCCESS); + task.arg_size_ = sizeof(void *) * 4; + task.args_.reset(new (std::nothrow) uint8_t[task.arg_size_]); + task.arg_index_ = {0}; vector args; vector inputs; vector outputs; - ASSERT_EQ(task.UpdateIoAddr(args, inputs, outputs), ACL_ERROR_GE_PARAM_INVALID); - task.arg_size_ = sizeof(void *) * 3; - ASSERT_EQ(task.UpdateIoAddr(args, inputs, outputs), ACL_ERROR_GE_PARAM_INVALID); + ASSERT_EQ(task.UpdateIoAddr(inputs, outputs), ACL_ERROR_GE_PARAM_INVALID); ge::DataBuffer data_buffer; inputs = { data_buffer }; - ASSERT_EQ(task.UpdateIoAddr(args, inputs, outputs), SUCCESS); + outputs = { data_buffer }; + ASSERT_EQ(task.UpdateIoAddr(inputs, outputs), SUCCESS); + + task.tiling_buffer_ = (void *)0x0001; + task.workspaces_ = { (void *)0x0002 }; + ASSERT_EQ(task.UpdateTilingArgs(nullptr), SUCCESS); + task.tiling_buffer_ = nullptr; } diff --git a/tests/ut/ge/single_op/single_op_unittest.cc b/tests/ut/ge/single_op/single_op_unittest.cc index db3de7ec..09aac153 100644 --- a/tests/ut/ge/single_op/single_op_unittest.cc +++ b/tests/ut/ge/single_op/single_op_unittest.cc @@ -103,7 +103,7 @@ TEST_F(UtestSingleOp, test_dynamic_singleop_execute_async1) { EXPECT_EQ(desc_ptr->AddInputDesc("x", GeTensorDesc(GeShape({2}), FORMAT_NCHW)), GRAPH_SUCCESS); dynamic_single_op.op_task_->op_desc_ = desc_ptr; // UpdateRunInfo failed - EXPECT_EQ(dynamic_single_op.ExecuteAsync(input_desc, input_buffers, output_desc, output_buffers), PARAM_INVALID); + EXPECT_EQ(dynamic_single_op.ExecuteAsync(input_desc, input_buffers, output_desc, output_buffers), ACL_ERROR_GE_PARAM_INVALID); } From a781b6c3548ec748d869cbb8d51e11d515c322a1 Mon Sep 17 00:00:00 2001 From: zhaozhixuan Date: Tue, 29 Jun 2021 16:56:06 +0800 Subject: [PATCH 16/20] Fix bug of atomic profiling. --- ge/hybrid/node_executor/aicore/aicore_node_executor.cc | 2 +- ge/hybrid/node_executor/aicore/aicore_op_task.cc | 10 ++++++++++ ge/hybrid/node_executor/aicore/aicore_op_task.h | 4 ++++ ge/hybrid/node_executor/aicpu/aicpu_node_executor.cc | 2 +- ge/hybrid/node_executor/task_context.cc | 6 +++--- ge/hybrid/node_executor/task_context.h | 4 ++-- .../ut/ge/hybrid/executor/worker/execution_engine_unittest.cc | 2 +- tests/ut/ge/hybrid/ge_hybrid_unittest.cc | 11 ++++++++++- 8 files changed, 32 insertions(+), 9 deletions(-) diff --git a/ge/hybrid/node_executor/aicore/aicore_node_executor.cc b/ge/hybrid/node_executor/aicore/aicore_node_executor.cc index c2ce24a4..7a22a062 100755 --- a/ge/hybrid/node_executor/aicore/aicore_node_executor.cc +++ b/ge/hybrid/node_executor/aicore/aicore_node_executor.cc @@ -208,7 +208,7 @@ Status AiCoreNodeTask::ExecuteAsync(TaskContext &context, std::function context.SetTaskId(task_id); context.SetStreamId(stream_id); GELOGD("Aicore node[%s] task_id: %u, stream_id: %u.", context.GetNodeName(), task_id, stream_id); - (void)context.SaveProfilingTaskDescInfo(task_id, stream_id, kTaskTypeAicore, (*it)->GetBlockDim()); + (void)context.SaveProfilingTaskDescInfo(task_id, stream_id, kTaskTypeAicore, (*it)->GetBlockDim(), (*it)->GetOpType()); RECORD_EXECUTION_EVENT(context.GetExecutionContext(), context.GetNodeName(), "[AiCoreNodeLaunchKernel] End"); RECORD_EXECUTION_EVENT(context.GetExecutionContext(), context.GetNodeName(), "[AiCoreNodeLaunchKernel] End"); } diff --git a/ge/hybrid/node_executor/aicore/aicore_op_task.cc b/ge/hybrid/node_executor/aicore/aicore_op_task.cc index a32f2999..b34cc0c6 100644 --- a/ge/hybrid/node_executor/aicore/aicore_op_task.cc +++ b/ge/hybrid/node_executor/aicore/aicore_op_task.cc @@ -33,6 +33,7 @@ namespace { constexpr char const *kAttrSupportDynamicShape = "support_dynamicshape"; constexpr char const *kAttrOpParamSize = "op_para_size"; constexpr char const *kAttrAtomicOpParamSize = "atomic_op_para_size"; +const string kAtomicOpType = "DynamicAtomicAddrClean"; std::atomic log_id(0); } // namespace @@ -51,6 +52,7 @@ bool TbeHandleRegistry::AddHandle(std::unique_ptr &&holder) { } Status AiCoreOpTask::Init(const OpDesc &op_desc, const domi::TaskDef &task_def) { + op_type_ = op_desc.GetType(); log_name_ = op_desc.GetName() + "_tvmbin"; log_id_ = log_id++; auto op_desc_ptr = MakeShared(op_desc); @@ -538,6 +540,10 @@ const std::string &AiCoreOpTask::GetName() const { return stub_name_; } +const std::string &AiCoreOpTask::GetOpType() const { + return op_type_; +} + std::string AiCoreOpTask::GetKeyForOpParamSize() const { return kAttrOpParamSize; } @@ -631,6 +637,10 @@ std::string AtomicAddrCleanOpTask::GetKeyForKernelName(const OpDesc &op_desc) co return op_desc.GetName() + "_atomic_kernelname"; } +const std::string &AtomicAddrCleanOpTask::GetOpType() const { + return kAtomicOpType; +} + Status AtomicAddrCleanOpTask::CalcTilingInfo(const NodePtr &node, OpRunInfo &tiling_info) { GELOGD("[%s] Start to invoke OpAtomicCalculate.", node->GetName().c_str()); GE_CHK_STATUS_RET(optiling::OpAtomicCalculateV2(*node, tiling_info), diff --git a/ge/hybrid/node_executor/aicore/aicore_op_task.h b/ge/hybrid/node_executor/aicore/aicore_op_task.h index b03bd9e4..8d7be0db 100755 --- a/ge/hybrid/node_executor/aicore/aicore_op_task.h +++ b/ge/hybrid/node_executor/aicore/aicore_op_task.h @@ -78,6 +78,8 @@ class AiCoreOpTask { void SetSingleOp(bool is_single_op) {is_single_op_ = is_single_op;}; + virtual const std::string& GetOpType() const; + protected: Status UpdateTilingInfo(TaskContext &context); virtual std::string GetKeyForOpParamSize() const; @@ -117,12 +119,14 @@ class AiCoreOpTask { uint64_t log_id_ = 0; std::string log_name_; uint32_t offset_ = 0; + std::string op_type_; }; class AtomicAddrCleanOpTask : public AiCoreOpTask { public: Status Init(const OpDesc &op_desc, const domi::TaskDef &task_def) override; Status UpdateArgs(TaskContext &task_context) override; + const std::string& GetOpType() const override; protected: std::string GetKeyForOpParamSize() const override; diff --git a/ge/hybrid/node_executor/aicpu/aicpu_node_executor.cc b/ge/hybrid/node_executor/aicpu/aicpu_node_executor.cc index c83a76d1..820c9b56 100755 --- a/ge/hybrid/node_executor/aicpu/aicpu_node_executor.cc +++ b/ge/hybrid/node_executor/aicpu/aicpu_node_executor.cc @@ -207,7 +207,7 @@ Status AicpuNodeTaskBase::ExecuteAsync(TaskContext &context, std::functionSynchronize(GetStream()); } -Status TaskContext::SaveProfilingTaskDescInfo(uint32_t task_id, uint32_t stream_id, - const std::string &task_type, uint32_t block_dim) { +Status TaskContext::SaveProfilingTaskDescInfo(uint32_t task_id, uint32_t stream_id, const std::string &task_type, + uint32_t block_dim, const std::string &op_type) { if (ProfilingManager::Instance().ProfilingModelLoadOn()) { const NodeItem &node_item = GetNodeItem(); auto op_desc = node_item.GetOpDesc(); @@ -589,7 +589,7 @@ Status TaskContext::SaveProfilingTaskDescInfo(uint32_t task_id, uint32_t stream TaskDescInfo tmp_task_desc_info; tmp_task_desc_info.model_name = dynamic_model_name; tmp_task_desc_info.op_name = op_desc->GetName(); - tmp_task_desc_info.op_type = op_desc->GetType(); + tmp_task_desc_info.op_type = op_type; tmp_task_desc_info.block_dim = block_dim; tmp_task_desc_info.task_type = task_type; tmp_task_desc_info.task_id = task_id; diff --git a/ge/hybrid/node_executor/task_context.h b/ge/hybrid/node_executor/task_context.h index c96e194e..5304606b 100644 --- a/ge/hybrid/node_executor/task_context.h +++ b/ge/hybrid/node_executor/task_context.h @@ -118,8 +118,8 @@ class TaskContext { void *handle_ = nullptr; const std::vector& GetProfilingTaskDescInfo() const { return task_desc_info; } - Status SaveProfilingTaskDescInfo(uint32_t task_id, uint32_t stream_id, - const std::string &task_type, uint32_t block_dim); + Status SaveProfilingTaskDescInfo(uint32_t task_id, uint32_t stream_id, const std::string &task_type, + uint32_t block_dim, const std::string &op_type); void ClearProfilingTaskDescInfo() { task_desc_info.clear(); } private: diff --git a/tests/ut/ge/hybrid/executor/worker/execution_engine_unittest.cc b/tests/ut/ge/hybrid/executor/worker/execution_engine_unittest.cc index cc20d614..07701f4d 100644 --- a/tests/ut/ge/hybrid/executor/worker/execution_engine_unittest.cc +++ b/tests/ut/ge/hybrid/executor/worker/execution_engine_unittest.cc @@ -119,7 +119,7 @@ TEST_F(UtestExecutionEngine, ExecuteAsync_without_callback_and_kernel_task) { uint32_t stream_id = 1; std::string task_type = "rts"; uint32_t block_dim = 0; - node_state->GetTaskContext()->SaveProfilingTaskDescInfo(task_id, stream_id, task_type, block_dim); + node_state->GetTaskContext()->SaveProfilingTaskDescInfo(task_id, stream_id, task_type, block_dim, op_desc->GetType()); ASSERT_TRUE(node_state->GetTaskContext() != nullptr); diff --git a/tests/ut/ge/hybrid/ge_hybrid_unittest.cc b/tests/ut/ge/hybrid/ge_hybrid_unittest.cc index 4f14f628..688d3a34 100644 --- a/tests/ut/ge/hybrid/ge_hybrid_unittest.cc +++ b/tests/ut/ge/hybrid/ge_hybrid_unittest.cc @@ -100,7 +100,7 @@ TEST_F(UtestGeHybrid, aicore_op_task_init_success) { op_desc->SetExtAttr(ge::OP_EXTATTR_NAME_TBE_KERNEL, tbe_kernel); std::string kernel_name("kernel/Add"); AttrUtils::SetStr(op_desc, op_desc->GetName() + "_kernelname", kernel_name); - ASSERT_EQ(aicore_task->InitWithTaskDef(*op_desc.get(), task_def), SUCCESS); + ASSERT_EQ(aicore_task->Init(*op_desc.get(), task_def), SUCCESS); rtStream_t stream = nullptr; rtStreamCreate(&stream, 0); ASSERT_EQ(aicore_task->LaunchKernel(stream), SUCCESS); @@ -676,6 +676,15 @@ TEST_F(UtestGeHybrid, test_key_for_kernel_bin) { EXPECT_EQ(atomic_task->GetKeyForKernelName(op_desc), "Sum_atomic_kernelname"); } +TEST_F(UtestGeHybrid, test_op_type) { + auto aicore_task = std::unique_ptr(new(std::nothrow)hybrid::AiCoreOpTask()); + aicore_task->op_type_ = "Add"; + EXPECT_EQ(aicore_task->GetOpType(), "Add"); + + auto atomic_task = std::unique_ptr(new(std::nothrow)hybrid::AtomicAddrCleanOpTask()); + EXPECT_EQ(atomic_task->GetOpType(), "DynamicAtomicAddrClean"); +} + TEST_F(UtestGeHybrid, TestParseDependentInputNodesForHccl) { NodeExecutorManager::GetInstance().engine_mapping_.emplace("ops_kernel_info_hccl", NodeExecutorManager::ExecutorType::HCCL); From 813f2fe4a2eb234153ce0ad5a5801c98bdb9be4f Mon Sep 17 00:00:00 2001 From: zhaozhixuan Date: Tue, 29 Jun 2021 19:11:56 +0800 Subject: [PATCH 17/20] Fix ut. --- ge/single_op/task/op_task.cc | 10 ++++------ ge/single_op/task/op_task.h | 4 +++- ge/single_op/task/tbe_task_builder.cc | 2 ++ 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/ge/single_op/task/op_task.cc b/ge/single_op/task/op_task.cc index 632cd4d8..28ec7f64 100755 --- a/ge/single_op/task/op_task.cc +++ b/ge/single_op/task/op_task.cc @@ -346,7 +346,7 @@ Status TbeOpTask::AllocateWorkspaces(const vector &workspace_sizes) { } Status TbeOpTask::UpdateTilingArgs(rtStream_t stream) { - size_t args_size = op_desc_->GetInputsSize() + op_desc_->GetOutputsSize() + workspaces_.size(); + size_t args_size = input_num_ + output_num_ + workspaces_.size(); if (tiling_buffer_ != nullptr) { args_size++; } @@ -361,12 +361,12 @@ Status TbeOpTask::UpdateTilingArgs(rtStream_t stream) { return ACL_ERROR_GE_MEMORY_OPERATE_FAILED; } - args_.reset(args.release()); + args_ = std::move(args); arg_size_ = temp_size; } uintptr_t *arg_base = reinterpret_cast(args_.get()); - size_t arg_index = op_desc_->GetInputsSize() + op_desc_->GetOutputsSize(); + size_t arg_index = input_num_ + output_num_; for (size_t i = 0; i < workspaces_.size(); ++i) { arg_base[arg_index++] = reinterpret_cast(workspaces_[i]); } @@ -382,7 +382,6 @@ Status TbeOpTask::UpdateTilingArgs(rtStream_t stream) { } Status TbeOpTask::SetArgIndex() { - arg_index_.clear(); const vector v_is_input_const = op_desc_->GetIsInputConst(); size_t input_index = 0; for (size_t i = 0; i < op_desc_->GetAllInputsSize(); ++i) { @@ -416,9 +415,8 @@ Status TbeOpTask::UpdateIoAddr(const vector &inputs, const vector(inputs[i].data); } - size_t input_size = op_desc_->GetInputsSize(); for (size_t i = 0; i < op_desc_->GetOutputsSize(); ++i) { - arg_base[input_size + i] = reinterpret_cast(outputs[i].data); + arg_base[input_num_ + i] = reinterpret_cast(outputs[i].data); } return SUCCESS; diff --git a/ge/single_op/task/op_task.h b/ge/single_op/task/op_task.h index d3e8383d..f93e031a 100644 --- a/ge/single_op/task/op_task.h +++ b/ge/single_op/task/op_task.h @@ -123,7 +123,9 @@ class TbeOpTask : public OpTask { void* handle_ = nullptr; std::string original_kernel_key_; std::string node_info_; - std::vector arg_index_; + std::vector arg_index_; // data index in args + size_t input_num_; // Include const input + size_t output_num_; }; class AiCpuBaseTask : public OpTask { diff --git a/ge/single_op/task/tbe_task_builder.cc b/ge/single_op/task/tbe_task_builder.cc index e5206ea6..db8ecfe2 100644 --- a/ge/single_op/task/tbe_task_builder.cc +++ b/ge/single_op/task/tbe_task_builder.cc @@ -388,6 +388,8 @@ Status TbeTaskBuilder::BuildTask(TbeOpTask &task, const SingleOpModelParam ¶ task.SetStubFunc(stub_name_, stub_func); } GE_CHK_STATUS_RET(task.SetArgIndex(), "[Set][ArgTable] failed."); + task.input_num_ = op_desc_->GetInputsSize(); + task.output_num_ = op_desc_->GetOutputsSize(); return SUCCESS; } From 59c97eef3eef0903c54052fe4b6428e5597db58c Mon Sep 17 00:00:00 2001 From: wq160 Date: Tue, 29 Jun 2021 10:58:45 +0800 Subject: [PATCH 18/20] set scalar tensor value range --- ge/graph/passes/infer_value_range_pass.cc | 3 ++ ge/graph/passes/replace_with_empty_const_pass.cc | 14 ++++--- ge/graph/passes/replace_with_empty_const_pass.h | 2 +- .../passes/infer_value_range_pass_unittest.cc | 48 ++++++++++++++++++++++ 4 files changed, 61 insertions(+), 6 deletions(-) diff --git a/ge/graph/passes/infer_value_range_pass.cc b/ge/graph/passes/infer_value_range_pass.cc index b9cb88bc..e714e90a 100644 --- a/ge/graph/passes/infer_value_range_pass.cc +++ b/ge/graph/passes/infer_value_range_pass.cc @@ -286,6 +286,9 @@ graphStatus InferValueRangePass::GenerateWorstValueRange(NodePtr &node) { } std::vector> output_i_value_range(output_i_shape_size, {1, -1}); + if (output_i_shape.IsScalar()) { + output_i_value_range.emplace_back(1, -1); + } output_desc->SetValueRange(output_i_value_range); GELOGD("Node %s output %zu shape is %s, the generated worst value range is %s.", node->GetName().c_str(), i, formats::ShapeToString(output_i_shape).c_str(), formats::RangeToString(output_i_value_range).c_str()); diff --git a/ge/graph/passes/replace_with_empty_const_pass.cc b/ge/graph/passes/replace_with_empty_const_pass.cc index 3176d1ee..6cb31627 100644 --- a/ge/graph/passes/replace_with_empty_const_pass.cc +++ b/ge/graph/passes/replace_with_empty_const_pass.cc @@ -71,7 +71,7 @@ Status ReplaceWithEmptyConstPass::Run(NodePtr &node) { GELOGI("Node %s Got empty output_desc_ptr, ignore current pass.", node->GetName().c_str()); return SUCCESS; } - if (!IsEmptyTenor(output_desc_ptr->GetShape())) { + if (!IsKnownEmptyTenor(output_desc_ptr->GetShape())) { is_all_output_empty = false; break; } @@ -107,12 +107,16 @@ Status ReplaceWithEmptyConstPass::GetOutputsOfCurrNode(const NodePtr &node_to_re return SUCCESS; } -bool ReplaceWithEmptyConstPass::IsEmptyTenor(const GeShape &shape) const { +bool ReplaceWithEmptyConstPass::IsKnownEmptyTenor(const GeShape &shape) const { + bool is_known_empty_tensor = false; for (auto dim : shape.GetDims()) { - if (dim == 0) { - return true; + if (dim < 0) { + // current dim is unknown dim, skip replace + return false; + } else if (dim == 0) { + is_known_empty_tensor = true; } } - return false; + return is_known_empty_tensor; } } // namespace ge diff --git a/ge/graph/passes/replace_with_empty_const_pass.h b/ge/graph/passes/replace_with_empty_const_pass.h index fde75358..90103432 100644 --- a/ge/graph/passes/replace_with_empty_const_pass.h +++ b/ge/graph/passes/replace_with_empty_const_pass.h @@ -26,7 +26,7 @@ class ReplaceWithEmptyConstPass : public FoldingPass { private: Status GetOutputsOfCurrNode(const NodePtr &node_to_replace, vector &outputs); - bool IsEmptyTenor(const GeShape &shape) const; + bool IsKnownEmptyTenor(const GeShape &shape) const; }; } // namespace ge #endif // GE_GRAPH_PASSES_REPLACE_WITH_EMPTY_CONST_PASS_H_ diff --git a/tests/ut/ge/graph/passes/infer_value_range_pass_unittest.cc b/tests/ut/ge/graph/passes/infer_value_range_pass_unittest.cc index fea1b27d..576d679c 100644 --- a/tests/ut/ge/graph/passes/infer_value_range_pass_unittest.cc +++ b/tests/ut/ge/graph/passes/infer_value_range_pass_unittest.cc @@ -362,6 +362,54 @@ TEST_F(UtestGraphInferValueRangePass, CallRun_NoSubgraph_UseCpuKernel_InputsHave EXPECT_EQ(unknown_target_value_range, output_value_range); } +TEST_F(UtestGraphInferValueRangePass, CallRun_NoSubgraph_UseCpuKernel_InputsHaveUnKnownValueRange_ScalarOutput) { + // shape --- add --- sqrt + // constant / + auto graph = std::make_shared("test_graph"); + vector data_vec = {1}; + GeTensorDesc const_tensor_desc(ge::GeShape(), ge::FORMAT_NCHW, ge::DT_INT64); + GeTensorPtr const_tensor = + std::make_shared(const_tensor_desc, (uint8_t *)data_vec.data(), data_vec.size() * sizeof(int64_t)); + + auto const_op_desc = std::make_shared("Constant", "Constant"); + const_op_desc->AddOutputDesc(const_tensor_desc); + EXPECT_EQ(OpDescUtils::SetWeights(const_op_desc, const_tensor), GRAPH_SUCCESS); + auto const_node = graph->AddNode(const_op_desc); + + GeTensorDesc shape_tensor_desc(GeShape(), ge::FORMAT_NCHW, ge::DT_INT64); + std::vector> unknown_value_range = {make_pair(1, -1)}; + shape_tensor_desc.SetValueRange(unknown_value_range); + auto shape_op_desc = std::make_shared("Shape", "Shape"); + shape_op_desc->AddOutputDesc(shape_tensor_desc); + auto shape_node = graph->AddNode(shape_op_desc); + + GeTensorDesc add_tensor_desc(GeShape(), ge::FORMAT_NCHW, ge::DT_INT64); + auto add_op_desc = std::make_shared("Add", "Add"); + add_op_desc->AddInputDesc(shape_tensor_desc); + add_op_desc->AddInputDesc(const_tensor_desc); + add_op_desc->AddOutputDesc(add_tensor_desc); + auto add_node = graph->AddNode(add_op_desc); + + ge::GraphUtils::AddEdge(shape_node->GetOutDataAnchor(0), add_node->GetInDataAnchor(0)); + ge::GraphUtils::AddEdge(const_node->GetOutDataAnchor(0), add_node->GetInDataAnchor(1)); + + // test unknown value range + InferValueRangePass infer_pass; + EXPECT_EQ(infer_pass.Run(add_node), SUCCESS); + auto output_0_desc = add_node->GetOpDesc()->GetOutputDesc(0); + std::vector> out_value_range; + output_0_desc.GetValueRange(out_value_range); + EXPECT_EQ(out_value_range.size(), 1); + + std::vector unknown_target_value_range = {1, -1}; + std::vector output_value_range; + for (auto pair : out_value_range) { + output_value_range.push_back(pair.first); + output_value_range.push_back(pair.second); + } + EXPECT_EQ(unknown_target_value_range, output_value_range); +} + TEST_F(UtestGraphInferValueRangePass, CallRun_NoSubgraph_UseCpuKernel_InputsAreKnownValueRange_Int64) { // shape --- add --- sqrt // constant / From 4f3f54d56407d045fa37bf02508cc101a46e1bef Mon Sep 17 00:00:00 2001 From: zhaozhixuan Date: Tue, 29 Jun 2021 19:19:08 +0800 Subject: [PATCH 19/20] Fix ut. --- ge/single_op/task/op_task.h | 2 +- tests/ut/ge/single_op/single_op_task_unittest.cc | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/ge/single_op/task/op_task.h b/ge/single_op/task/op_task.h index f93e031a..97d8a342 100644 --- a/ge/single_op/task/op_task.h +++ b/ge/single_op/task/op_task.h @@ -124,7 +124,7 @@ class TbeOpTask : public OpTask { std::string original_kernel_key_; std::string node_info_; std::vector arg_index_; // data index in args - size_t input_num_; // Include const input + size_t input_num_; // include const input size_t output_num_; }; diff --git a/tests/ut/ge/single_op/single_op_task_unittest.cc b/tests/ut/ge/single_op/single_op_task_unittest.cc index 020efc23..b0c98205 100644 --- a/tests/ut/ge/single_op/single_op_task_unittest.cc +++ b/tests/ut/ge/single_op/single_op_task_unittest.cc @@ -134,6 +134,8 @@ TEST_F(UtestSingleOpTask, test_update_ioaddr) { task.arg_size_ = sizeof(void *) * 4; task.args_.reset(new (std::nothrow) uint8_t[task.arg_size_]); task.arg_index_ = {0}; + task.input_num_ = 2; + task.output_num_ = 1; vector args; vector inputs; From 9f6aff6759714c0093045b563f9b6f5bba8d46a6 Mon Sep 17 00:00:00 2001 From: wuweikang Date: Fri, 18 Jun 2021 09:32:57 +0800 Subject: [PATCH 20/20] check dump option --- ge/common/dump/dump_properties.cc | 243 ++++++++++++++++++++++--- ge/common/dump/dump_properties.h | 18 +- ge/session/inner_session.cc | 2 +- tests/ut/ge/CMakeLists.txt | 1 + tests/ut/ge/common/dump_properties_unittest.cc | 126 +++++++++++++ 5 files changed, 364 insertions(+), 26 deletions(-) create mode 100644 tests/ut/ge/common/dump_properties_unittest.cc diff --git a/ge/common/dump/dump_properties.cc b/ge/common/dump/dump_properties.cc index ef755540..010347c0 100644 --- a/ge/common/dump/dump_properties.cc +++ b/ge/common/dump/dump_properties.cc @@ -18,6 +18,7 @@ #include #include +#include #include "common/ge/ge_util.h" #include "framework/common/util.h" @@ -37,6 +38,159 @@ const uint32_t kAtomicOverflow = (0x1 << 1); const uint32_t kAllOverflow = (kAicoreOverflow | kAtomicOverflow); } // namespace namespace ge { +FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY void DumpProperties::Split(const std::string &s, + std::vector &result, + const char *delchar) { + if (s.empty()) { + return; + } + result.clear(); + + char *buffer = new (std::nothrow)char[s.size() + 1]; + if (buffer == nullptr) { + GELOGE(FAILED, "[Split][string] failed while malloc memory, string value is:%s", s.c_str()); + REPORT_CALL_ERROR("E19999", "Memory malloc may fail when split string, get fatal exception, " + "string value is:%s", s.c_str()); + return; + } + buffer[s.size()] = '\0'; + errno_t e = strcpy_s(buffer, s.size() + 1, s.c_str()); + if (e != EOK) { + delete[] buffer; + return; + } + char *context = nullptr; + char *p = strtok_s(buffer, delchar, &context); + while (p != nullptr) { + result.emplace_back(p); + p = strtok_s(nullptr, delchar, &context); + } + delete[] buffer; +} + +FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY Status DumpProperties::CheckDumpStep(const std::string &dump_step) { + std::string modified_dum_step = dump_step + "|"; + std::smatch result; + std::vector match_vecs; + std::regex pattern(R"((\d{1,}-\d{1,}\||\d{1,}\|)+)"); + if (regex_match(modified_dum_step, result, pattern)) { + Split(result.str(), match_vecs, "|"); + if (match_vecs.empty()) { + REPORT_CALL_ERROR("E19999", "Split may get fatal exception, dump_step:%s.", dump_step.c_str()); + GELOGE(FAILED, "[Check][Param] failed. Split may get fatal exception, ge.exec.dumpStep:%s.", dump_step.c_str()); + return FAILED; + } + // 100 is the max sets of dump steps. + if (match_vecs.size() > 100) { + REPORT_INPUT_ERROR("E10001", std::vector({"parameter", "value", "reason"}), + std::vector({ + "ge.exec.dumpStep", + dump_step.c_str(), + " is not supported, only support dump <= 100 sets of data"})); + GELOGE(PARAM_INVALID, "[Check][Param] get dump_step value:%s, " + "dump_step only support dump <= 100 sets of data.", dump_step.c_str()); + return PARAM_INVALID; + } + for (const auto &match_vec : match_vecs) { + std::vector vec_after_split; + Split(match_vec, vec_after_split, "-"); + if (match_vecs.empty()) { + REPORT_CALL_ERROR("E19999", "Split may get fatal exception."); + GELOGE(FAILED, "[Check][Param] failed, split may get fatal exception."); + return FAILED; + } + if (vec_after_split.size() > 1) { + if (std::atoi(vec_after_split[0].c_str()) >= std::atoi(vec_after_split[1].c_str())) { + REPORT_INPUT_ERROR("E10001", std::vector({"parameter", "value", "reason"}), + std::vector({ + "ge.exec.dumpStep", + dump_step.c_str(), + " is not supported." + "in range steps, the first step is >= second step, correct example:'0|5|10-20"})); + GELOGE(PARAM_INVALID, "[Check][Param] get dump_step value:%s, " + "in range steps, the first step is >= second step, correct example:'0|5|10-20'", dump_step.c_str()); + return PARAM_INVALID; + } + } + } + } else { + REPORT_INPUT_ERROR("E10001", std::vector({"parameter", "value", "reason"}), + std::vector({ + "ge.exec.dumpStep", + dump_step.c_str(), + " is not supported, correct example:'0|5|10|50-100."})); + GELOGE(PARAM_INVALID, "[Check][Param] get dump_step value:%s, " + "dump_step string style is error, correct example:'0|5|10|50-100.'", dump_step.c_str()); + return PARAM_INVALID; + } + return SUCCESS; +} + +FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY Status DumpProperties::CheckDumpMode(const std::string &dump_mode) { + const std::set dump_mode_list = {"input", "output", "all"}; + std::set::iterator iter; + + if ((iter = dump_mode_list.find(dump_mode)) == dump_mode_list.end()) { + REPORT_INPUT_ERROR("E10001", std::vector({"parameter", "value", "reason"}), + std::vector({ + "ge.exec.dumpMode", + dump_mode.c_str(), + " is not supported, should be one of the following:[input, output, all]"})); + GELOGE(PARAM_INVALID, "[Check][Param] the dump_debug_mode:%s, is is not supported," + "should be one of the following:[input, output, all].", dump_mode.c_str()); + return PARAM_INVALID; + } + return SUCCESS; +} + +FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY Status DumpProperties::CheckDumpPath(const std::string &input) { + if (mmIsDir(input.c_str()) != EN_OK) { + REPORT_INPUT_ERROR("E10001", std::vector({"parameter", "value", "reason"}), + std::vector({ + "ge.exec.dumpPath", + input.c_str(), + " is not a directory."})); + GELOGE(PARAM_INVALID, "[Check][Param] the path:%s, is not directory.", input.c_str()); + return PARAM_INVALID; + } + char trusted_path[MMPA_MAX_PATH] = { "\0" }; + if (mmRealPath(input.c_str(), trusted_path, MMPA_MAX_PATH) != EN_OK) { + REPORT_INPUT_ERROR("E10001", std::vector({"parameter", "value", "reason"}), + std::vector({ + "ge.exec.dumpPath", + input.c_str(), + " dumpPath invalid."})); + GELOGE(PARAM_INVALID, "[Check][Param] the dumpPath:%s, is invalid.", input.c_str()); + return PARAM_INVALID; + } + if (mmAccess2(trusted_path, R_OK | W_OK) != EN_OK) { + REPORT_INPUT_ERROR("E10001", std::vector({"parameter", "value", "reason"}), + std::vector({ + "ge.exec.dumpPath", + input.c_str(), + " does't have read, write permissions."})); + GELOGE(PARAM_INVALID, "[Check][Param] the path:%s, does't have read, write permissions.", input.c_str()); + return PARAM_INVALID; + } + return SUCCESS; +} + +FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY Status DumpProperties::CheckEnableDump(const std::string &input) { + std::set enable_dump_option_list = {"1", "0"}; + auto it = enable_dump_option_list.find(input); + if (it == enable_dump_option_list.end()) { + REPORT_INPUT_ERROR("E10001", std::vector({"parameter", "value", "reason"}), + std::vector({ + "ge.exec.enableDump", + input.c_str(), + " only support 1 or 0."})); + GELOGE(PARAM_INVALID, "[Check][Param] Not support ge.exec.enableDump or ge.exec.enableDumpDebug format:%s, " + "only support 1 or 0.", input.c_str()); + return PARAM_INVALID; + } + return SUCCESS; +} + FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY DumpProperties::DumpProperties(const DumpProperties &other) { CopyFrom(other); } @@ -47,7 +201,26 @@ FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY DumpProperties &DumpProperties: return *this; } -FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY void DumpProperties::InitByOptions() { +FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY Status DumpProperties::SetDumpOptions() { + if (enable_dump_ == kEnableFlag) { + std::string dump_step; + if (GetContext().GetOption(OPTION_EXEC_DUMP_STEP, dump_step) == GRAPH_SUCCESS) { + GE_CHK_STATUS_RET(CheckDumpStep(dump_step), "[Check][dump_step] failed."); + GELOGI("Get dump step %s successfully", dump_step.c_str()); + SetDumpStep(dump_step); + } + string dump_mode = "output"; + if (GetContext().GetOption(OPTION_EXEC_DUMP_MODE, dump_mode) == GRAPH_SUCCESS) { + GELOGI("Get dump mode %s successfully", dump_mode.c_str()); + GE_CHK_STATUS_RET(CheckDumpMode(dump_mode), "[Check][dump_mode] failed."); + SetDumpMode(dump_mode); + } + AddPropertyValue(DUMP_ALL_MODEL, {}); + } + return SUCCESS; +} + +FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY Status DumpProperties::InitByOptions() { enable_dump_.clear(); enable_dump_debug_.clear(); dump_path_.clear(); @@ -57,17 +230,32 @@ FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY void DumpProperties::InitByOpti is_infer_op_debug_ = false; op_debug_mode_ = 0; - std::string enable_dump; + std::string enable_dump = std::to_string(false); (void)GetContext().GetOption(OPTION_EXEC_ENABLE_DUMP, enable_dump); enable_dump_ = enable_dump; + if (!enable_dump_.empty()) { + GE_CHK_STATUS_RET(CheckEnableDump(enable_dump_), "[Check][enable_dump] failed."); + } - std::string enable_dump_debug; + std::string enable_dump_debug = std::to_string(false); (void)GetContext().GetOption(OPTION_EXEC_ENABLE_DUMP_DEBUG, enable_dump_debug); enable_dump_debug_ = enable_dump_debug; - + if (!enable_dump_debug_.empty()) { + GE_CHK_STATUS_RET(CheckEnableDump(enable_dump_debug_), "[Check][enable_dump_debug] failed."); + } + if ((enable_dump_ == kEnableFlag) && (enable_dump_debug_ == kEnableFlag)) { + REPORT_INPUT_ERROR("E10001", std::vector({"parameter", "value", "reason"}), + std::vector({ + "ge.exec.enableDump and ge.exec.enableDumpDebug", + enable_dump_ + ", " + enable_dump_debug, + "ge.exec.enableDump and ge.exec.enableDumpDebug cannot be set to 1 at the same time."})); + GELOGE(FAILED, "ge.exec.enableDump and ge.exec.enableDumpDebug cannot be both set to 1 at the same time."); + return FAILED; + } if ((enable_dump_ == kEnableFlag) || (enable_dump_debug_ == kEnableFlag)) { std::string dump_path; if (GetContext().GetOption(OPTION_EXEC_DUMP_PATH, dump_path) == GRAPH_SUCCESS) { + GE_CHK_STATUS_RET(CheckDumpPath(dump_path), "Check dump path failed."); if (!dump_path.empty() && dump_path[dump_path.size() - 1] != '/') { dump_path = dump_path + "/"; } @@ -75,25 +263,21 @@ FMK_FUNC_HOST_VISIBILITY FMK_FUNC_DEV_VISIBILITY void DumpProperties::InitByOpti GELOGI("Get dump path %s successfully", dump_path.c_str()); SetDumpPath(dump_path); } else { - GELOGW("Dump path is not set"); + REPORT_INPUT_ERROR("E10001", std::vector({"parameter", "value", "reason"}), + std::vector({ + "ge.exec.dumpPath", + dump_path, + "ge.exec.dumpPath is not set."})); + GELOGE(FAILED, "[Check][dump_path] failed. Dump path is not set."); + return FAILED; } } - if (enable_dump_ == kEnableFlag) { - std::string dump_step; - if (GetContext().GetOption(OPTION_EXEC_DUMP_STEP, dump_step) == GRAPH_SUCCESS) { - GELOGI("Get dump step %s successfully", dump_step.c_str()); - SetDumpStep(dump_step); - } - string dump_mode; - if (GetContext().GetOption(OPTION_EXEC_DUMP_MODE, dump_mode) == GRAPH_SUCCESS) { - GELOGI("Get dump mode %s successfully", dump_mode.c_str()); - SetDumpMode(dump_mode); - } - AddPropertyValue(DUMP_ALL_MODEL, {}); - } + GE_CHK_STATUS_RET(SetDumpOptions(), "SetDumpOptions failed."); + + GE_CHK_STATUS_RET(SetDumpDebugOptions(), "SetDumpDebugOptions failed."); - SetDumpDebugOptions(); + return SUCCESS; } // The following is the new dump scenario of the fusion operator @@ -253,14 +437,20 @@ void DumpProperties::CopyFrom(const DumpProperties &other) { } } -void DumpProperties::SetDumpDebugOptions() { +Status DumpProperties::SetDumpDebugOptions() { if (enable_dump_debug_ == kEnableFlag) { std::string dump_debug_mode; if (GetContext().GetOption(OPTION_EXEC_DUMP_DEBUG_MODE, dump_debug_mode) == GRAPH_SUCCESS) { GELOGD("Get dump debug mode %s successfully", dump_debug_mode.c_str()); } else { - GELOGW("Dump debug mode is not set."); - return; + REPORT_INPUT_ERROR("E10001", std::vector({"parameter", "value", "reason"}), + std::vector({ + "ge.exec.dumpDebugMode", + dump_debug_mode, + "ge.exec.dumpDebugMode is not set."})); + GELOGE(PARAM_INVALID, "[Check][dump_debug_mode] failed. Dump debug mode is not set."); + + return PARAM_INVALID; } if (dump_debug_mode == OP_DEBUG_AICORE) { @@ -276,10 +466,17 @@ void DumpProperties::SetDumpDebugOptions() { is_train_op_debug_ = true; op_debug_mode_ = kAllOverflow; } else { - GELOGW("ge.exec.dumpDebugMode is invalid."); + REPORT_INPUT_ERROR("E10001", std::vector({"parameter", "value", "reason"}), + std::vector({ + "ge.exec.dumpDebugMode", + dump_debug_mode, + "ge.exec.dumpDebugMode is invalid."})); + GELOGE(PARAM_INVALID, "[Set][DumpDebugOptions] failed, ge.exec.dumpDebugMode is invalid."); + return PARAM_INVALID; } } else { GELOGI("ge.exec.enableDumpDebug is false or is not set."); } + return SUCCESS; } } // namespace ge diff --git a/ge/common/dump/dump_properties.h b/ge/common/dump/dump_properties.h index 98487491..cbfc362d 100644 --- a/ge/common/dump/dump_properties.h +++ b/ge/common/dump/dump_properties.h @@ -23,6 +23,7 @@ #include namespace ge { +using Status = uint32_t; class DumpProperties { public: DumpProperties() = default; @@ -33,7 +34,7 @@ class DumpProperties { DumpProperties &operator=(const DumpProperties &dump); - void InitByOptions(); + Status InitByOptions(); void AddPropertyValue(const std::string &model, const std::set &layers); @@ -95,7 +96,20 @@ class DumpProperties { private: void CopyFrom(const DumpProperties &other); - void SetDumpDebugOptions(); + Status SetDumpDebugOptions(); + + Status SetDumpOptions(); + + void Split(const std::string &s, std::vector &result, const char *delchar); + + Status CheckDumpStep(const std::string &dump_step); + + Status CheckDumpMode(const std::string &dump_mode); + + Status CheckDumpPath(const std::string &input); + + Status CheckEnableDump(const std::string &input); + std::string enable_dump_; std::string enable_dump_debug_; diff --git a/ge/session/inner_session.cc b/ge/session/inner_session.cc index aabbe19c..b3df08ce 100755 --- a/ge/session/inner_session.cc +++ b/ge/session/inner_session.cc @@ -109,7 +109,7 @@ Status InnerSession::Initialize() { GE_CHK_RT_RET(rtSetDevice(GetContext().DeviceId())); DumpProperties dump_properties; - dump_properties.InitByOptions(); + GE_CHK_STATUS_RET(dump_properties.InitByOptions(), "Init dump properties failed."); GE_CHK_STATUS_RET(AddDumpProperties(dump_properties), "[Add][DumpProperties] failed."); ret = graph_manager_.Initialize(options_); diff --git a/tests/ut/ge/CMakeLists.txt b/tests/ut/ge/CMakeLists.txt index cf573343..d7568ccc 100755 --- a/tests/ut/ge/CMakeLists.txt +++ b/tests/ut/ge/CMakeLists.txt @@ -774,6 +774,7 @@ set(MULTI_PARTS_TEST_FILES "common/util_unittest.cc" "common/dump_manager_unittest.cc" "common/dump_op_unittest.cc" + "common/dump_properties_unittest.cc" "common/dump_exception_unittest.cc" "common/opdebug_register_unittest.cc" "common/format_transfer_unittest.cc" diff --git a/tests/ut/ge/common/dump_properties_unittest.cc b/tests/ut/ge/common/dump_properties_unittest.cc new file mode 100644 index 00000000..57809013 --- /dev/null +++ b/tests/ut/ge/common/dump_properties_unittest.cc @@ -0,0 +1,126 @@ +/** + * Copyright 2019-2020 Huawei Technologies Co., Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#define protected public +#define private public + +#include "common/dump/dump_properties.h" +#include "ge_local_context.h" +#include "ge/ge_api_types.h" +#include "common/debug/log.h" +#include "common/ge_inner_error_codes.h" + +namespace ge { +class UTEST_dump_properties : public testing::Test { + protected: + void SetUp() {} + void TearDown() {} +}; + +TEST_F(UTEST_dump_properties, check_dump_step) { + DumpProperties dp; + std::string dump_step{"0|3-5|10"}; + std::string unsupport_input1{"0|5-3|10"}; + std::string unsupport_input2{"one"}; + std::string unsupport_input3; + for (int i = 0; i < 200; ++i) { + unsupport_input3 += std::to_string(i) + "|"; + } + unsupport_input3.pop_back(); + Status st = dp.CheckDumpStep(dump_step); + EXPECT_EQ(st, SUCCESS); + st = dp.CheckDumpStep(unsupport_input1); + EXPECT_NE(st, SUCCESS); + st = dp.CheckDumpStep(unsupport_input2); + EXPECT_NE(st, SUCCESS); + st = dp.CheckDumpStep(unsupport_input3); + EXPECT_NE(st, SUCCESS); +} + +TEST_F(UTEST_dump_properties, check_dump_mode) { + DumpProperties dp; + std::string dump_mode_1{"input"}; + std::string dump_mode_2{"output"}; + std::string dump_mode_3{"all"}; + std::string unsupport_input1{"mode1"}; + Status st = dp.CheckDumpMode(dump_mode_1); + EXPECT_EQ(st, SUCCESS); + st = dp.CheckDumpMode(dump_mode_2); + EXPECT_EQ(st, SUCCESS); + st = dp.CheckDumpMode(dump_mode_3); + EXPECT_EQ(st, SUCCESS); + st = dp.CheckDumpMode(unsupport_input1); + EXPECT_NE(st, SUCCESS); +} + +TEST_F(UTEST_dump_properties, check_dump_path) { + DumpProperties dp; + std::string dump_path{"/tmp/"}; + std::string unsupport_input1{" \\unsupported"}; + Status st = dp.CheckDumpPath(dump_path); + EXPECT_EQ(st, SUCCESS); + st = dp.CheckDumpPath(unsupport_input1); + EXPECT_NE(st, SUCCESS); +} + +TEST_F(UTEST_dump_properties, check_enable_dump) { + DumpProperties dp; + std::string enable_dump_t{"1"}; + std::string enable_dump_f{"0"}; + std::string unsupport_input1{"true"}; + std::string unsupport_input2{"false"}; + Status st = dp.CheckEnableDump(enable_dump_t); + EXPECT_EQ(st, SUCCESS); + st = dp.CheckEnableDump(enable_dump_f); + EXPECT_EQ(st, SUCCESS); + st = dp.CheckEnableDump(unsupport_input1); + EXPECT_NE(st, SUCCESS); + st = dp.CheckEnableDump(unsupport_input2); + EXPECT_NE(st, SUCCESS); +} + +TEST_F(UTEST_dump_properties, init_by_options_success_1) { + DumpProperties dp; + std::map options {{OPTION_EXEC_ENABLE_DUMP, "1"}, + {OPTION_EXEC_DUMP_PATH, "/tmp/"}, + {OPTION_EXEC_DUMP_STEP, "0|1-3|10"}, + {OPTION_EXEC_DUMP_MODE, "all"}}; + GetThreadLocalContext().SetGlobalOption(options); + Status st = dp.InitByOptions(); + EXPECT_EQ(st, SUCCESS); +} + +TEST_F(UTEST_dump_properties, init_by_options_success_2) { + DumpProperties dp; + std::map options {{OPTION_EXEC_ENABLE_DUMP_DEBUG, "1"}, + {OPTION_EXEC_DUMP_PATH, "/tmp/"}, + {OPTION_EXEC_DUMP_DEBUG_MODE, "aicore_overflow"}}; + GetThreadLocalContext().SetGlobalOption(options); + Status st = dp.InitByOptions(); + EXPECT_EQ(st, SUCCESS); +} + +TEST_F(UTEST_dump_properties, init_by_options_failed) { + DumpProperties dp; + std::map options {{OPTION_EXEC_ENABLE_DUMP_DEBUG, "1"}, + {OPTION_EXEC_DUMP_PATH, "/tmp/"}}; + GetThreadLocalContext().SetGlobalOption(options); + Status st = dp.InitByOptions(); + EXPECT_NE(st, SUCCESS); +} +} // namespace ge \ No newline at end of file