task_graph.cpp 38.1 KB
Newer Older
S
Shenghang Tsai 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
Copyright 2020 The OneFlow Authors. All rights reserved.

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.
*/
J
jiyuan 已提交
16
#include "oneflow/core/graph/task_graph.h"
J
Jinhui Yuan 已提交
17
#include "oneflow/core/common/util.h"
L
Li Xinqi 已提交
18
#include "oneflow/core/graph/inplace_lbi_graph.h"
C
cheng cheng 已提交
19
#include "oneflow/core/graph/id_serialization.h"
C
cheng cheng 已提交
20
#include "oneflow/core/register/blob_desc.h"
21
#include "oneflow/core/job/global_for.h"
L
Li Xinqi 已提交
22
#include "oneflow/core/operator/variable_op.h"
J
Juncheng 已提交
23
#include "oneflow/core/graph/op_graph.h"
C
cheng cheng 已提交
24
#include "oneflow/core/graph/normal_forward_compute_task_node.h"
25
#include "oneflow/core/graph/boxing_identity_task_node.h"
C
cheng cheng 已提交
26 27 28
#include "oneflow/core/job/scope.h"
#include "oneflow/core/vm/symbol_storage.h"
#include "oneflow/core/job_rewriter/calculation_pass.h"
29
#include "oneflow/core/job/env_desc.h"
30 31
#include "oneflow/core/graph/boxing/sub_task_graph_builder_util.h"
#include "oneflow/core/graph/boxing/hierarchical_sub_task_graph_builder_impl.h"
C
cheng cheng 已提交
32
#include "oneflow/core/graph/stream_index_getter_registry_manager.h"
J
Juncheng 已提交
33
#include "oneflow/core/primitive/include/memcpy.h"
W
willzhang4a58 已提交
34 35 36

namespace oneflow {

L
Li Xinqi 已提交
37 38
namespace {

39 40 41 42 43 44 45 46 47 48 49
bool IsMemcpyPrimitiveSupported(DeviceType device_type, primitive::MemcpyKind kind) {
  auto primitive = primitive::NewPrimitive<primitive::MemcpyFactory>(device_type, kind);
  return primitive.operator bool();
}

bool IsMemcpyHtoDSupported(DeviceType device_type) {
  return IsMemcpyPrimitiveSupported(device_type, primitive::MemcpyKind::kHtoD);
}

bool IsMemcpyDtoHSupported(DeviceType device_type) {
  return IsMemcpyPrimitiveSupported(device_type, primitive::MemcpyKind::kDtoH);
L
Li Xinqi 已提交
50 51
}

L
Li Xinqi 已提交
52 53 54
bool IsConnectToTickOp(const TaskNode* node) {
  const auto* comp_task_node = dynamic_cast<const CompTaskNode*>(node);
  if (comp_task_node == nullptr) { return false; }
C
cheng cheng 已提交
55
  const Operator* op = comp_task_node->op().get();
L
Li Xinqi 已提交
56 57 58 59
  if (dynamic_cast<const VariableOp*>(op) != nullptr) { return true; }
  return false;
}

60 61 62 63 64 65 66 67 68 69 70
std::string GetOpConfCalculationPassName(const OperatorConf& op_conf) {
  CHECK(op_conf.has_scope_symbol_id());
  int64_t scope_symbol_id = op_conf.scope_symbol_id();
  CHECK(Global<symbol::Storage<Scope>>::Get()->Has(scope_symbol_id))
      << " Error! op : \n " << op_conf.DebugString()
      << " has error scope_symbol_id = " << scope_symbol_id
      << " which cannot find in Global<symbol::Storage<Scope>>::Get()\n";
  const Scope& scope = Global<symbol::Storage<Scope>>::Get()->Get(scope_symbol_id);
  return scope.scope_proto().calculation_pass_name();
}

C
cheng cheng 已提交
71 72 73 74 75 76 77 78
bool IsOptimizerPassOp(const Operator* op) {
  // NOTE(chengcheng): use scope::calculation_pass_name instead of area_id to not merge optimizer
  // ops with fw/bw ops
  if (!op->op_conf().has_scope_symbol_id()) {
    // NOTE(chengcheng): Some system op insert to OpGraph may not set scope_symbol_id, it MUST NOT
    // optimizer subgraph ops.
    return false;
  }
79
  return GetOpConfCalculationPassName(op->op_conf()) == kOptimizerPass;
C
cheng cheng 已提交
80 81
}

C
cheng cheng 已提交
82 83 84 85 86 87 88 89
bool IsSubsetTickOpConf(const OperatorConf& op_conf) {
  return op_conf.has_src_subset_tick_conf() || op_conf.has_dst_subset_tick_conf();
}

bool IsTickOpConf(const OperatorConf& conf) {
  return IsClassRegistered<int32_t, IsTickTockOpTypeCase>(conf.op_type_case());
}

C
cheng cheng 已提交
90 91
bool IsSpecialOpNotConsiderMergeInChain(const Operator* op) {
  const OperatorConf& op_conf = op->op_conf();
C
cheng cheng 已提交
92 93 94 95 96 97
  if (op_conf.has_variable_conf() || op_conf.has_tick_conf() || op_conf.has_device_tick_conf()
      || op_conf.has_src_subset_tick_conf() || op_conf.has_dst_subset_tick_conf()
      || op_conf.has_source_tick_conf() || op_conf.has_sink_tick_conf()
      || op_conf.has_acc_tick_conf()) {
    return true;
  }
98 99 100
  if (op_conf.has_user_conf()) {
    const std::string& user_type_name = op_conf.user_conf().op_type_name();
    if (user_type_name == "repeat" || user_type_name == "acc" || user_type_name == "pack"
101
        || user_type_name == "unpack" || user_type_name == "identity_buffer") {
102 103 104
      return true;
    }
  }
C
cheng cheng 已提交
105 106 107
  // NOTE(chengcheng): ONLY nccl_use_compute_stream = false will exclude optimizer pass ops
  if (!Global<ResourceDesc, ForSession>::Get()->nccl_use_compute_stream()
      && IsOptimizerPassOp(op)) {
C
cheng cheng 已提交
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
    return true;
  }
  return false;
}

bool IsTaskNodeProducedResgtHasMultiRegstNum(const TaskNode* node) {
  for (const auto& pair : node->produced_regsts()) {
    if (pair.second->min_register_num() > 1) { return true; }
  }
  return false;
}

bool CanBeMergedInChain(const TaskNode* node) {
  // ONLY the node which is NormalForward and in GPU and NOT variable can be merged.
  if (IsTaskNodeProducedResgtHasMultiRegstNum(node)) { return false; }
  const auto* fw_comp_node = dynamic_cast<const NormalForwardCompTaskNode*>(node);
  if (fw_comp_node == nullptr) { return false; }
  if (fw_comp_node->device_type() != DeviceType::kGPU) { return false; }
C
cheng cheng 已提交
126
  const Operator* op = fw_comp_node->op().get();
C
cheng cheng 已提交
127 128 129 130
  if (IsSpecialOpNotConsiderMergeInChain(op)) { return false; }
  return true;
}

131 132 133 134 135 136
std::shared_ptr<const Shape> GetTaskNodeTimeShape(const TaskNode* node) {
  const auto* fw_comp_node = dynamic_cast<const NormalForwardCompTaskNode*>(node);
  CHECK(fw_comp_node != nullptr);
  return CHECK_JUST(fw_comp_node->op()->GetOpTimeShape());
}

C
cheng cheng 已提交
137 138 139 140
void TraverseConnectedSubGraphMergeInThisChain(TaskNode* this_node, const int64_t this_chain_id) {
  CHECK_NE(this_chain_id, -1);
  CHECK_EQ(this_node->chain_id(), -1);
  // bfs search all node can be merged in this chain
141
  std::shared_ptr<const Shape> seed_time_shape = GetTaskNodeTimeShape(this_node);
C
cheng cheng 已提交
142 143 144 145 146 147 148 149 150 151 152
  HashSet<TaskNode*> visited_nodes;
  std::queue<TaskNode*> queued_nodes;
  queued_nodes.push(this_node);
  visited_nodes.insert(this_node);
  while (!queued_nodes.empty()) {
    TaskNode* cur_node = queued_nodes.front();
    queued_nodes.pop();

    CHECK_EQ(cur_node->chain_id(), -1);
    cur_node->set_chain_id(this_chain_id);

153
    cur_node->ForEachNodeOnInOutDataEdge([&](TaskNode* next_node) {
C
cheng cheng 已提交
154
      if (visited_nodes.find(next_node) == visited_nodes.end() && CanBeMergedInChain(next_node)
155
          && this_node->thrd_id() == next_node->thrd_id()
156
          && (*GetTaskNodeTimeShape(next_node)) == (*seed_time_shape)) {
C
cheng cheng 已提交
157 158 159 160 161 162 163 164 165 166 167
        if (next_node->chain_id() == -1) {
          queued_nodes.push(next_node);
          visited_nodes.insert(next_node);
        } else {
          CHECK_EQ(next_node->chain_id(), this_chain_id);
        }
      }
    });
  }
}

L
Li Xinqi 已提交
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
std::function<TaskNode*(const std::string&)> MakeGetterTaskNode4SoleOpName(
    const HashSet<TaskNode*>& task_nodes) {
  auto op_name2task_nodes = std::make_shared<HashMap<std::string, HashSet<TaskNode*>>>();
  for (TaskNode* task_node : task_nodes) {
    if (task_node->exec_gph().node_num() == 1) {
      ExecNode* exec_node = task_node->exec_gph().SoleNode();
      CHECK((*op_name2task_nodes)[exec_node->op()->op_name()].emplace(task_node).second);
    }
  }
  return [op_name2task_nodes](const std::string& op_name) -> TaskNode* {
    const auto& iter = op_name2task_nodes->find(op_name);
    if (iter == op_name2task_nodes->end()) { return nullptr; }
    if (iter->second.size() > 1) { return nullptr; }
    return *iter->second.begin();
  };
J
Juncheng 已提交
183
}
L
Li Xinqi 已提交
184 185 186 187 188 189 190 191 192

bool IsLbiOnTaskEdge(const TaskEdge* edge, const LogicalBlobId& lbi) {
  for (const auto& regst_desc : edge->GetRegsts()) {
    if (regst_desc->HasLbi(lbi)) { return true; }
  }
  return false;
}

std::function<bool(const LogicalBlobId&, const std::string&)>
S
scxfjiang 已提交
193
MakePredicatorIsLbiAllConsumersReachable(
J
Juncheng 已提交
194 195 196
    const std::function<const TaskNode*(const std::string&)>& TaskNode4SoleOpName,
    const std::function<bool(const std::string&, const std::string&)>&
        IsOpNameDataOrCtrlReachable) {
S
scxfjiang 已提交
197 198 199 200 201 202 203 204 205 206
  auto IsDataOrCtrlReachable = [IsOpNameDataOrCtrlReachable](const TaskNode* src_node,
                                                             const TaskNode* dst_node) -> bool {
    if (src_node->chain_id() == dst_node->chain_id()
        && src_node->order_in_graph() <= dst_node->order_in_graph()) {
      return true;
    }
    const CompTaskNode* comp_src_node = dynamic_cast<const CompTaskNode*>(src_node);
    if (comp_src_node == nullptr) { return false; }
    const CompTaskNode* comp_dst_node = dynamic_cast<const CompTaskNode*>(dst_node);
    if (comp_dst_node == nullptr) { return false; }
C
cheng cheng 已提交
207 208
    return IsOpNameDataOrCtrlReachable(comp_src_node->op()->op_name(),
                                       comp_dst_node->op()->op_name());
S
scxfjiang 已提交
209 210 211
  };
  return [TaskNode4SoleOpName, IsDataOrCtrlReachable](const LogicalBlobId& lbi,
                                                      const std::string& op_name) -> bool {
L
Li Xinqi 已提交
212 213 214
    const TaskNode* src_task_node = TaskNode4SoleOpName(lbi.op_name());
    const TaskNode* dst_task_node = TaskNode4SoleOpName(op_name);
    size_t out_edges_size = 0;
L
Li Xinqi 已提交
215
    size_t reachable_out_edges_size = 0;
L
Li Xinqi 已提交
216 217 218
    for (TaskEdge* out_edge : src_task_node->out_edges()) {
      if (IsLbiOnTaskEdge(out_edge, lbi)) {
        out_edges_size += 1;
S
scxfjiang 已提交
219
        reachable_out_edges_size += IsDataOrCtrlReachable(out_edge->dst_node(), dst_task_node);
L
Li Xinqi 已提交
220 221
      }
    }
L
Li Xinqi 已提交
222
    return out_edges_size > 0 && out_edges_size == reachable_out_edges_size;
L
Li Xinqi 已提交
223 224 225 226 227 228 229 230 231 232 233 234 235 236
  };
}

bool IsInplaceAllowed(
    TaskNode* task_node, const std::vector<std::string>& bns,
    const std::function<const TaskNode*(const std::string&)>& TaskNode4SoleOpName) {
  if (task_node->exec_gph().node_num() != 1) { return false; }
  const auto& exec_node = *task_node->exec_gph().SoleNode();
  for (const auto& bn : bns) {
    // TaskNode for bn is not nullptr if it's on the same device with `task_node`
    if (TaskNode4SoleOpName(exec_node.op()->BnInOp2Lbi(bn).op_name()) == nullptr) { return false; }
    const RegstDesc& regst_desc = *exec_node.RegstDesc4BnInOp(bn);
    if (regst_desc.NumOfLbi() != 1) { return false; }
  }
L
lixinqi 已提交
237
  const BlobDesc* first_blob = nullptr;
238
  for (const auto& bn : bns) {
L
lixinqi 已提交
239 240 241
    const BlobDesc* blob_desc = exec_node.RegstDesc4BnInOp(bn)->SoleBlobDesc();
    if (first_blob == nullptr) {
      first_blob = blob_desc;
242
    } else {
J
Juncheng 已提交
243
      if (!(first_blob->shape().elem_cnt() == blob_desc->shape().elem_cnt()
L
lixinqi 已提交
244 245 246
            && first_blob->data_type() == blob_desc->data_type())) {
        return false;
      }
247 248
    }
  }
L
Li Xinqi 已提交
249 250 251
  return true;
}

qq_22305325's avatar
qq_22305325 已提交
252 253 254 255 256 257 258 259 260
std::unique_ptr<BoxingLogger> CreateBoxingLogger() {
  if (Global<ResourceDesc, ForSession>::Get()->enable_debug_mode()) {
    return std::unique_ptr<BoxingLogger>(
        new CsvBoxingLogger(StrCat("boxing/log/", GlobalJobDesc().job_id()) + ".csv"));
  } else {
    return std::unique_ptr<BoxingLogger>(new NullBoxingLogger());
  }
}

L
Li Xinqi 已提交
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
Maybe<void> MakeGetterTaskNode4MachineId7ThrdId(
    const std::vector<CompTaskNode*>& task_nodes,
    std::function<Maybe<CompTaskNode*>(int64_t mchn_id, int64_t thrd_id)>* Getter) {
  // ticks are shared within a machine/process
  auto machine_id2task_node = std::make_shared<HashMap<int64_t, CompTaskNode*>>();
  for (auto* task_node : task_nodes) {
    machine_id2task_node->emplace(task_node->machine_id(), task_node);
  }
  *Getter = [machine_id2task_node](int64_t mchn_id, int64_t thrd_id) -> Maybe<CompTaskNode*> {
    const auto& iter = machine_id2task_node->find(mchn_id);
    CHECK_OR_RETURN(iter != machine_id2task_node->end());
    return iter->second;
  };
  return Maybe<void>::Ok();
}

C
cheng cheng 已提交
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
void GenSortedCompTaskNodes(const OpNode* op_node, std::vector<CompTaskNode*>* sorted_comp_tasks) {
  int64_t parallel_idx = 0;
  const ParallelDesc& parallel_desc = op_node->parallel_desc();
  int64_t parallel_num = parallel_desc.parallel_num();
  for (int64_t machine_id : parallel_desc.sorted_machine_ids()) {
    for (int64_t dev_phy_id : parallel_desc.sorted_dev_phy_ids(machine_id)) {
      CompTaskNode* comp_task_node = NewCompTaskNode4OpNode(op_node);
      comp_task_node->set_machine_id(machine_id);
      comp_task_node->mut_parallel_ctx()->set_parallel_id(parallel_idx++);
      comp_task_node->mut_parallel_ctx()->set_parallel_num(parallel_num);

      DeviceId::device_index_t device_index =
          parallel_desc.device_type() == DeviceType::kCPU
              ? DeviceId::kCPUDeviceIndex
              : static_cast<DeviceId::device_index_t>(dev_phy_id);
      DeviceId device_id{static_cast<DeviceId::rank_t>(machine_id), parallel_desc.device_type(),
                         device_index};
294
      StreamId::stream_index_t stream_index{};
295 296 297 298 299 300 301 302
      if (op_node->op().op_conf().has_stream_index_hint()) {
        int32_t stream_index_hint = op_node->op().op_conf().stream_index_hint();
        LOG(INFO) << "set op: " << op_node->op().op_name() << " to stream: " << stream_index_hint;
        stream_index = static_cast<StreamId::stream_index_t>(stream_index_hint);
      } else {
        stream_index = StreamIndexGetterRegistryManager::Get().StreamIndex4DeviceIdAndTaskType(
            device_id, comp_task_node->GetTaskType());
      }
C
cheng cheng 已提交
303 304 305 306 307 308 309
      comp_task_node->set_thrd_id(SerializeStreamIdToInt64(StreamId{device_id, stream_index}));
      comp_task_node->set_op_node(op_node);
      sorted_comp_tasks->push_back(comp_task_node);
    }
  }
}

310
bool IsConnectedLbisAllSameNdSbp(const OpEdge* op_edge) {
C
cheng cheng 已提交
311 312 313 314 315
  const OpNode* src_node = op_edge->src_node();
  const OpNode* dst_node = op_edge->dst_node();
  CHECK_GT(op_edge->lbis().size(), 0);
  HashSet<bool> predicators;
  for (const LogicalBlobId& lbi : op_edge->lbis()) {
316 317
    const cfg::NdSbp& src_nd_sbp = src_node->NdSbp4Lbi(lbi);
    const cfg::NdSbp& dst_nd_sbp = dst_node->NdSbp4Lbi(lbi);
318
    predicators.insert(src_nd_sbp == dst_nd_sbp);
C
cheng cheng 已提交
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
  }
  CHECK_EQ(predicators.size(), 1);
  return *predicators.begin();
}

BldSubTskGphMthd GetMthdForBldSubTskGph(const OpEdge* op_edge) {
  const OpNode* src_node = op_edge->src_node();
  const OpNode* dst_node = op_edge->dst_node();
  const ParallelDesc& src_pd = src_node->parallel_desc();
  const ParallelDesc& dst_pd = dst_node->parallel_desc();
  const OperatorConf& src_op_conf = src_node->op().op_conf();
  const OperatorConf& dst_op_conf = dst_node->op().op_conf();

  // WaitAndSendIds -> Reentrantlock
  if (src_op_conf.has_wait_and_send_ids_conf() && dst_op_conf.has_reentrant_lock_conf()) {
    CHECK_EQ(src_pd.parallel_num(), 1);
    CHECK_EQ(dst_pd.parallel_num(), 1);
    return &TaskGraph::BldSubTskGphByBoxing;
  }

  // *Tick -> *Tick
  if (IsTickOpConf(src_op_conf) || IsTickOpConf(dst_op_conf)) {
    if (src_op_conf.has_source_tick_conf()) {
      CHECK(dst_op_conf.has_tick_conf());
      CHECK_EQ(src_pd.parallel_num(), 1);
      CHECK_EQ(dst_pd.parallel_num(), 1);
      return &TaskGraph::BldSubTskGphByBoxing;
    } else if (dst_op_conf.has_sink_tick_conf()) {
      CHECK(src_op_conf.has_tick_conf() || src_op_conf.has_sink_tick_conf());
      CHECK_EQ(src_pd.parallel_num(), 1);
      CHECK_EQ(dst_pd.parallel_num(), 1);
      return &TaskGraph::BldSubTskGphByBoxing;
    } else if (IsSubsetTickOpConf(src_op_conf)) {
      return &TaskGraph::BldSubTskGphBySrcSubsetConnect;
    } else if (IsSubsetTickOpConf(dst_op_conf)) {
      return &TaskGraph::BldSubTskGphByDstSubsetConnect;
    } else if (IsTickOpConf(src_op_conf) && IsTickOpConf(dst_op_conf)) {
      if (src_pd.parallel_num() == dst_pd.parallel_num()) {
        return &TaskGraph::BldSubTskGphByOneToOne;
      } else {
        CHECK_EQ(src_pd.parallel_num(), 1);
        return &TaskGraph::BldSubTskGphByBroadcastToBroadcast;
      }
    }
  }

  std::shared_ptr<CompTaskNode> src_comp_task(NewCompTaskNode4OpNode(src_node));
  std::shared_ptr<CompTaskNode> dst_comp_task(NewCompTaskNode4OpNode(dst_node));
  // NOTE(chengcheng): MUST use TaskType instead of OpTypeCase because may
  //   Multi-op correspoding to SAME TaskType such as:
  //     DistributeConcatOpConf and DistributeAddOpConf -> TaskType::kDistributeConcat
  //     DistributeSplitOpConf  and DistributeCloneOpConf -> TaskType::kDistributeSplit
  // * -> DistributeConcat
  if (dst_comp_task->GetTaskType() == TaskType::kDistributeConcat) {
    return &TaskGraph::BldSubTskGphByPartialInLbiConnect;
  }

  // DistributeSplit -> *
  if (src_comp_task->GetTaskType() == TaskType::kDistributeSplit) {
    return &TaskGraph::BldSubTskGphByPartialOutLbiConnect;
  }

  // NormalForward -> DecodeH2D
  if (src_comp_task->GetTaskType() == TaskType::kNormalForward
      && dst_comp_task->GetTaskType() == TaskType::kDecodeH2D) {
    return &TaskGraph::BldSubTskGphNormalForwardToDecodeH2D;
  }

  if (src_pd.parallel_num() == 1 && dst_pd.parallel_num() == 1) {
    return &TaskGraph::BldSubTskGphByOneToOne;
  }

  // one to one
  if (src_pd.parallel_num() == dst_pd.parallel_num() && *src_pd.hierarchy() == *dst_pd.hierarchy()
393
      && IsConnectedLbisAllSameNdSbp(op_edge)) {
C
cheng cheng 已提交
394 395 396 397 398 399 400
    return &TaskGraph::BldSubTskGphByOneToOne;
  }

  return &TaskGraph::BldSubTskGphByBoxing;
}

void ForEachOpGraphNecessaryCtrlEdge(
401
    const OpGraph* op_graph, const std::function<void(const OpNode*, const OpNode*)>& Handler) {
C
cheng cheng 已提交
402 403 404 405 406 407
  auto IsOpGraphDataReachable = op_graph->MakePredicatorIsReachable();
  op_graph->ForEachNode([&](OpNode* dst) {
    for (const auto& ctrl_in_op_name : dst->op().op_conf().ctrl_in_op_name()) {
      const OpNode* src = op_graph->OpNode4OpName(ctrl_in_op_name);
      CHECK(!IsOpGraphDataReachable(dst, src));
      if (!IsOpGraphDataReachable(src, dst)) {
J
Juncheng 已提交
408
        CHECK_EQ(dst->parallel_desc().parallel_num(), src->parallel_desc().parallel_num());
C
cheng cheng 已提交
409 410 411 412 413
        const Shape* src_time_shape = CHECK_JUST(src->op().GetOpTimeShape()).get();
        const Shape* dst_time_shape = CHECK_JUST(dst->op().GetInputBlobFastestTimeShape()).get();
        if (dst_time_shape == nullptr) {
          dst_time_shape = CHECK_JUST(dst->op().GetOpTimeShape()).get();
        }
414 415
        CHECK_EQ(src_time_shape->elem_cnt(), dst_time_shape->elem_cnt());
        Handler(src, dst);
C
cheng cheng 已提交
416 417 418 419 420
      }
    }
  });
}

L
Li Xinqi 已提交
421 422
}  // namespace

C
cheng cheng 已提交
423 424
TaskGraph::TaskGraph() {
  OpGraph* op_graph = Global<OpGraph>::Get();
J
Juncheng 已提交
425
  sub_tsk_gph_builder_ctx_.reset(new SubTskGphBuilderCtx(this));
qq_22305325's avatar
qq_22305325 已提交
426
  boxing_logger_ = CreateBoxingLogger();
427
  hierarchical_sub_tsk_gph_builder_.reset(new DispatchHierarchicalSubTskGphBuilder());
428
  HashMap<const OpNode*, std::vector<CompTaskNode*>> op_node2sorted_comp_tasks;
W
willzhang4a58 已提交
429

C
cheng cheng 已提交
430
  op_graph->ForEachNode([&](const OpNode* op_node) {
431
    std::vector<CompTaskNode*>* sorted_comp_tasks = &(op_node2sorted_comp_tasks[op_node]);
C
cheng cheng 已提交
432 433
    GenSortedCompTaskNodes(op_node, sorted_comp_tasks);
    for (CompTaskNode* comp_task : *sorted_comp_tasks) { AddAllocatedNode(comp_task); }
434
  });
N
Niu Chong 已提交
435

C
cheng cheng 已提交
436 437
  op_graph->ForEachEdge([&](const OpEdge* op_edge) {
    BldSubTskGphMthd method = GetMthdForBldSubTskGph(op_edge);
438 439
    (this->*method)(op_edge, op_node2sorted_comp_tasks.at(op_edge->src_node()),
                    op_node2sorted_comp_tasks.at(op_edge->dst_node()));
440
  });
441

442 443 444 445 446 447 448 449 450 451 452
  ForEachOpGraphNecessaryCtrlEdge(op_graph, [&](const OpNode* src, const OpNode* dst) {
    const auto& src_task_nodes = op_node2sorted_comp_tasks.at(src);
    const auto& dst_task_nodes = op_node2sorted_comp_tasks.at(dst);
    if (src->op().op_conf().has_src_subset_tick_conf()) {
      UNIMPLEMENTED();
    } else if (dst->op().op_conf().has_dst_subset_tick_conf()) {
      UNIMPLEMENTED();
    } else {
      ConnectCtrlEdges(src_task_nodes, dst_task_nodes);
    }
  });
L
Li Xinqi 已提交
453

C
cheng cheng 已提交
454
  SetOrderInGraphForEachNode();
455
  if (Global<ResourceDesc, ForSession>::Get()->enable_debug_mode()) { ToDotWithAutoFilePath(); }
W
Will Zhang 已提交
456 457
}

458 459
TaskGraph::~TaskGraph() = default;

460 461 462 463 464 465 466 467 468 469 470 471 472
TaskEdge* TaskGraph::NewTaskEdgeWithLbi(const LogicalBlobId& lbi) {
  TaskEdge* edge = NewEdge();
  edge->AddLbi(lbi);
  return edge;
}

TaskEdge* TaskGraph::NewTaskEdgeWithLbis(const std::vector<LogicalBlobId>& lbis) {
  TaskEdge* edge = NewEdge();
  edge->AddLbis(lbis);
  return edge;
}

TaskNode* TaskGraph::GetProxyNode(TaskNode* src_node, const LogicalBlobId& lbi,
L
leaves-zwx 已提交
473 474 475 476 477 478 479
                                  const MemZoneId& dst_mem_zone_id) {
  const auto& src_mem_zone_id = src_node->MemZoneId121();
  const ProxyKey key(src_node, lbi, dst_mem_zone_id);
  auto it = proxy2node.find(key);
  if (it != proxy2node.cend()) {
    // hit cache
    return it->second;
480
  } else {
L
leaves-zwx 已提交
481 482
    if (src_mem_zone_id == dst_mem_zone_id) {
      // in the same memory zone
483 484
      proxy2node[key] = src_node;
      return src_node;
L
leaves-zwx 已提交
485 486 487 488
    } else if (dst_mem_zone_id.device_type() == DeviceType::kCPU) {
      if (src_mem_zone_id.node_index() == dst_mem_zone_id.node_index()) {
        // on the same node, not on the same device
        // src must be not on the cpu mem zone, copy d2h first
489
        CHECK(IsMemcpyDtoHSupported(src_mem_zone_id.device_id().device_type()));
L
leaves-zwx 已提交
490
        CopyHdTaskNode* copy_task = NewNode<CopyHdTaskNode>();
491
        copy_task->Init(CopyHdOpConf::D2H, src_mem_zone_id.device_id(), lbi);
L
leaves-zwx 已提交
492 493 494
        Connect<TaskNode>(src_node, NewTaskEdgeWithLbi(lbi), copy_task);
        proxy2node[key] = copy_task;
        return copy_task;
495
      } else {
L
leaves-zwx 已提交
496 497 498 499
        // not on the same node, need CopyCommNet from src to dst
        // build src cpu proxy first
        TaskNode* proxy_on_src_host =
            GetProxyNode(src_node, lbi, GetNodeCPUMemZoneId(src_mem_zone_id.node_index()));
500
        CopyCommNetTaskNode* copy_comm_net_task = NewNode<CopyCommNetTaskNode>();
L
leaves-zwx 已提交
501
        copy_comm_net_task->Init(dst_mem_zone_id.node_index(), lbi);
502 503 504 505 506
        Connect<TaskNode>(proxy_on_src_host, NewTaskEdgeWithLbi(lbi), copy_comm_net_task);
        proxy2node[key] = copy_comm_net_task;
        return copy_comm_net_task;
      }
    } else {
L
leaves-zwx 已提交
507 508
      TaskNode* proxy_on_dst_host =
          GetProxyNode(src_node, lbi, GetNodeCPUMemZoneId(dst_mem_zone_id.node_index()));
509
      CHECK(IsMemcpyHtoDSupported(dst_mem_zone_id.device_id().device_type()));
L
leaves-zwx 已提交
510
      CopyHdTaskNode* copy_task = NewNode<CopyHdTaskNode>();
511
      copy_task->Init(CopyHdOpConf::H2D, dst_mem_zone_id.device_id(), lbi);
L
leaves-zwx 已提交
512 513 514
      Connect<TaskNode>(proxy_on_dst_host, NewTaskEdgeWithLbi(lbi), copy_task);
      proxy2node[key] = copy_task;
      return copy_task;
515
    }
L
Li Xinqi 已提交
516
  }
517 518 519 520 521 522 523
  return nullptr;
}

TaskNode* TaskGraph::GetProxyNode(TaskNode* src_node, const LogicalBlobId& lbi,
                                  const ParallelDesc& dst_parallel_desc, int64_t dst_parallel_id) {
  const int64_t dst_machine_id =
      CHECK_JUST(dst_parallel_desc.MachineId4ParallelId(dst_parallel_id));
L
leaves-zwx 已提交
524 525 526 527 528 529 530 531
  const int64_t dev_id = CHECK_JUST(dst_parallel_desc.DeviceId4ParallelId(dst_parallel_id));
  DeviceType device_type = dst_parallel_desc.device_type();
  auto device_index =
      (device_type == DeviceType::kCPU ? DeviceId::kCPUDeviceIndex
                                       : static_cast<DeviceId::device_index_t>(dev_id));
  MemZoneId mem_zone_id{static_cast<MemZoneId::node_index_t>(dst_machine_id), device_type,
                        device_index};
  return GetProxyNode(src_node, lbi, mem_zone_id);
L
Li Xinqi 已提交
532 533
}

L
Li Xinqi 已提交
534
void TaskGraph::ConnectCtrlEdges(const std::vector<CompTaskNode*>& src_task_nodes,
535
                                 const std::vector<CompTaskNode*>& dst_task_nodes) {
L
Li Xinqi 已提交
536 537
  CHECK_EQ(src_task_nodes.size(), dst_task_nodes.size());
  FOR_RANGE(int32_t, i, 0, src_task_nodes.size()) {
538
    std::string regst_desc_name;
L
Li Xinqi 已提交
539
    src_task_nodes.at(i)->BuildCtrlRegstDesc(dst_task_nodes.at(i), &regst_desc_name);
540 541 542
    TaskEdge* edge = NewEdge();
    Connect<TaskNode>(src_task_nodes.at(i), edge, dst_task_nodes.at(i));
    src_task_nodes.at(i)->BindEdgeWithProducedRegst(edge, regst_desc_name);
L
Li Xinqi 已提交
543 544 545
  }
}

546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
void TaskGraph::AddCtrlEdgeBetweenSrcDstTickAndInputOutputInSameRank() {
  if (!CHECK_JUST(GlobalMultiClientEnv())) { return; }
  HashMap<int64_t, TaskNode*> rank_id2src_tick;
  HashMap<int64_t, TaskNode*> rank_id2dst_tick;
  HashMap<int64_t, HashSet<TaskNode*>> rank_id2input_output_nodes;

  ForEachNode([&](TaskNode* node) {
    if (node->GetTaskType() == TaskType::kSrcSubsetTick) {
      CHECK(rank_id2src_tick.emplace(node->machine_id(), node).second);
    } else if (node->GetTaskType() == TaskType::kDstSubsetTick) {
      CHECK(rank_id2dst_tick.emplace(node->machine_id(), node).second);
    } else if (node->GetTaskType() == TaskType::kNormalForward) {
      auto* forward_node = reinterpret_cast<NormalForwardCompTaskNode*>(node);
      CHECK(forward_node);
      if (forward_node->op()->op_conf().has_input_conf()
          || forward_node->op()->op_conf().has_output_conf()) {
        CHECK(rank_id2input_output_nodes[node->machine_id()].insert(node).second);
      }
    }
  });

  auto AddCtrlEdge = [&](TaskNode* src, TaskNode* dst) {
    std::string ctrl_regst_name;
    src->BuildCtrlRegstDesc(dst, &ctrl_regst_name);
    TaskEdge* edge = NewEdge();
    Connect<TaskNode>(src, edge, dst);
    src->BindEdgeWithProducedRegst(edge, ctrl_regst_name);
  };

  for (auto& pair : rank_id2src_tick) {
    int64_t rank_id = pair.first;
    TaskNode* src = pair.second;
    for (TaskNode* io_task : rank_id2input_output_nodes[rank_id]) { AddCtrlEdge(src, io_task); }
  }

  for (auto& pair : rank_id2dst_tick) {
    int64_t rank_id = pair.first;
    TaskNode* dst = pair.second;
    for (TaskNode* io_task : rank_id2input_output_nodes[rank_id]) { AddCtrlEdge(io_task, dst); }
  }
}

J
Jinhui Yuan 已提交
588
void TaskGraph::RemoveEmptyRegsts() {
L
Luyang 已提交
589
  ForEachNode([&](TaskNode* node) { node->EraseUninitializedShapeProducedBlob(); });
J
Jinhui Yuan 已提交
590 591
  ForEachNode([&](TaskNode* node) { node->EraseZeroSizeConsumedRegst(); });
  ForEachNode([&](TaskNode* node) { node->EraseZeroSizeProducedRegst(); });
592
  ForEachNode([&](TaskNode* node) { node->UnbindBnWithEmptyRegst(); });
J
Jinhui Yuan 已提交
593 594
}

C
cheng cheng 已提交
595 596 597 598
void TaskGraph::MergeChainAndAddOrderingCtrlEdgeInSameChain() {
  MergeChain();
  BuildCtrlRegstDescInSameChain();
}
J
Jinhui Yuan 已提交
599

C
cheng cheng 已提交
600
void TaskGraph::SetOrderInGraphForEachNode() {
J
Jinhui Yuan 已提交
601
  int64_t order_in_graph = 0;
C
cheng cheng 已提交
602
  auto SetOrderInGraph = [&](TaskNode* task_node) {
603 604 605
    task_node->set_order_in_graph(order_in_graph);
    ordered_task_nodes_.emplace_back(task_node);
    ++order_in_graph;
C
cheng cheng 已提交
606
  };
607
  TopoForEachNode(SetOrderInGraph);
C
cheng cheng 已提交
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
}

void TaskGraph::MergeChain() {
  int64_t chain_id = 0;
  for (auto* this_node : ordered_task_nodes_) {
    // skip if this node has been set in a chain.
    if (this_node->chain_id() != -1) { continue; }

    CHECK_EQ(this_node->chain_id(), -1);
    if (CanBeMergedInChain(this_node)) {
      TraverseConnectedSubGraphMergeInThisChain(this_node, chain_id);
    } else {
      this_node->set_chain_id(chain_id);
    }

    ++chain_id;
  }
  for (auto* node : ordered_task_nodes_) { CHECK_NE(node->chain_id(), -1); }
J
Jinhui Yuan 已提交
626 627
}

628
void TaskGraph::BuildCtrlRegstDescInSameChain() {
J
Jinhui Yuan 已提交
629
  HashMap<int64_t, TaskNode*> chain_id2node;
L
Li Xinqi 已提交
630 631
  for (auto* node : ordered_task_nodes_) {
    if (IsConnectToTickOp(node)) { continue; }
J
Jinhui Yuan 已提交
632 633 634 635 636
    int64_t chain_id = node->chain_id();
    auto iter = chain_id2node.find(chain_id);
    if (iter == chain_id2node.end()) {
      CHECK(chain_id2node.emplace(chain_id, node).second);
    } else {
637 638 639 640 641 642 643 644 645 646 647
      TaskNode* src_node = iter->second;
      TaskNode* dst_node = node;
      std::string ctrl_regst_name;
      bool build_ctrl_edge = src_node->BuildCtrlRegstDescIfNeed(dst_node, &ctrl_regst_name);
      if (build_ctrl_edge) {
        CHECK(!ctrl_regst_name.empty());
        TaskEdge* edge = NewEdge();
        Connect<TaskNode>(src_node, edge, dst_node);
        src_node->BindEdgeWithProducedRegst(edge, ctrl_regst_name);
      }
      iter->second = dst_node;
J
Jinhui Yuan 已提交
648 649 650 651
    }
  }
}

L
Li Xinqi 已提交
652
void TaskGraph::GetInplaceOpBlobArgList(
653
    InplaceObasInfo* obas_info, const HashSet<TaskNode*>& dev_nodes,
L
Li Xinqi 已提交
654
    const std::function<const TaskNode*(const std::string&)>& TaskNode4OpName) const {
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
  auto AddMutableInplaceArgPair = [&](TaskNode* node, const std::string& ibn,
                                      const std::string& obn, const std::string& op_name) {
    if (IsInplaceAllowed(node, {ibn, obn}, TaskNode4OpName)) {
      auto* pair = obas_info->mut_inplace_oba_pairs.mutable_pair()->Add();
      *pair->mutable_first() = GenOpBlobArg(op_name, ibn);
      *pair->mutable_second() = GenOpBlobArg(op_name, obn);
    }
  };
  auto AddConstInplaceArgPair = [&](TaskNode* node, const std::string& ibn, const std::string& obn,
                                    const std::string& op_name) {
    if (IsInplaceAllowed(node, {ibn, obn}, TaskNode4OpName)) {
      auto* pair = obas_info->con_inplace_oba_pairs.mutable_pair()->Add();
      *pair->mutable_first() = GenOpBlobArg(op_name, ibn);
      *pair->mutable_second() = GenOpBlobArg(op_name, obn);
    }
  };

L
Li Xinqi 已提交
672 673 674 675 676 677
  for (TaskNode* task_node : dev_nodes) {
    if (task_node->exec_gph().node_num() != 1) { continue; }
    const auto& op = *task_node->exec_gph().SoleNode()->op();
    for (const std::string& ibn : op.input_bns()) {
      if (op.InputBlobModifier4Ibn(ibn).is_mutable()) {
        CHECK(IsInplaceAllowed(task_node, {ibn}, TaskNode4OpName));
678
        *obas_info->mut_in_obas.mutable_oba()->Add() = GenOpBlobArg(op.op_name(), ibn);
L
Li Xinqi 已提交
679 680
      }
    }
681 682
    for (const auto& pair : task_node->exec_gph().SoleNode()->mut_inplace_obn2ibn()) {
      AddMutableInplaceArgPair(task_node, pair.second, pair.first, op.op_name());
683
    }
684 685
    for (const auto& pair : task_node->exec_gph().SoleNode()->con_inplace_obn2ibn()) {
      AddConstInplaceArgPair(task_node, pair.second, pair.first, op.op_name());
L
Li Xinqi 已提交
686
    }
L
Li Xinqi 已提交
687 688 689 690
  }
}

void TaskGraph::GetSafeInplaceOpBlobArgList(
691
    InplaceObasInfo* safe_obas_info, const HashSet<TaskNode*>& dev_nodes,
J
Juncheng 已提交
692 693
    const std::function<bool(const std::string&, const std::string&)>& IsOpNameDataOrCtrlReachable)
    const {
L
Li Xinqi 已提交
694
  auto TaskNode4SoleOpName = MakeGetterTaskNode4SoleOpName(dev_nodes);
695 696
  InplaceObasInfo obas_info;
  GetInplaceOpBlobArgList(&obas_info, dev_nodes, TaskNode4SoleOpName);
L
Li Xinqi 已提交
697 698 699
  auto Op4OpName = [&](const std::string& op_name) -> const Operator* {
    return TaskNode4SoleOpName(op_name)->exec_gph().SoleNode()->op().get();
  };
S
scxfjiang 已提交
700 701
  auto IsLbiAllConsumersReachable =
      MakePredicatorIsLbiAllConsumersReachable(TaskNode4SoleOpName, IsOpNameDataOrCtrlReachable);
702 703 704
  InplaceLbiGraph origin_graph(obas_info, Op4OpName);
  InplaceLbiGraph safe_graph(*safe_obas_info, Op4OpName);
  origin_graph.ComputeSafeInplaceObns(safe_obas_info, IsLbiAllConsumersReachable);
705
  if (Global<ResourceDesc, ForSession>::Get()->enable_debug_mode()) {
J
Juncheng 已提交
706 707 708 709 710
    origin_graph.ToDotWithFilePath(
        JoinPath("dot", "InplaceLbiGraph", GlobalJobDesc().job_name() + "_origin.dot"));
    safe_graph.ToDotWithFilePath(
        JoinPath("dot", "InplaceLbiGraph", GlobalJobDesc().job_name() + "_safe.dot"));
  }
L
Li Xinqi 已提交
711 712
}

713
void TaskGraph::SetTaskRegstInplaceInfo(const InplaceObasInfo& obas_info,
L
Li Xinqi 已提交
714 715 716 717 718
                                        const HashSet<TaskNode*>& dev_nodes) const {
  auto TaskNode4SoleOpName = MakeGetterTaskNode4SoleOpName(dev_nodes);
  auto Op4OpName = [&](const std::string& op_name) -> const Operator* {
    return TaskNode4SoleOpName(op_name)->exec_gph().SoleNode()->op().get();
  };
719
  InplaceLbiGraph inplace_gph(obas_info, Op4OpName);
J
Juncheng 已提交
720
  inplace_gph.ForEachConnectedComponent([&](const HashSet<const InplaceLbiNode*>& inplace_nodes) {
L
Li Xinqi 已提交
721 722 723 724 725 726 727
    for (const auto* inplace_node : inplace_nodes) {
      if (inplace_node->in_edges().empty()) { continue; }
      const auto* inplace_edge = inplace_node->SoleInEdge();
      auto* exec_node = TaskNode4SoleOpName(inplace_edge->op().op_name())->exec_gph().SoleNode();
      RegstDesc* in_regst = exec_node->RegstDesc4BnInOp(inplace_edge->ibn());
      RegstDesc* out_regst = exec_node->RegstDesc4BnInOp(inplace_edge->obn());
      out_regst->set_hint_inplace_consumed_regst_desc_id(in_regst->regst_desc_id());
L
Li Xinqi 已提交
728
    }
L
Li Xinqi 已提交
729 730 731 732 733 734 735 736
  });
}

void TaskGraph::ForEachGpuDeviceNodes(
    const std::function<void(const HashSet<TaskNode*>& dev_nodes)>& Handler) const {
  HashMap<std::pair<int64_t, int64_t>, HashSet<TaskNode*>> global_dev_phy_id2nodes;
  ForEachNode([&](TaskNode* task_node) {
    if (task_node->device_type() != DeviceType::kGPU) { return; }
737
    int64_t dev_phy_id = task_node->stream_id().device_id().device_index();
L
Li Xinqi 已提交
738 739 740 741 742 743
    global_dev_phy_id2nodes[{task_node->machine_id(), dev_phy_id}].emplace(task_node);
  });
  for (const auto& pair : global_dev_phy_id2nodes) { Handler(pair.second); }
}

void TaskGraph::EnableInplaceMemSharing(
S
scxfjiang 已提交
744 745
    const std::function<bool(const std::string&, const std::string&)>&
        IsOpNameDataOrCtrlReachable) {
L
Li Xinqi 已提交
746
  ForEachGpuDeviceNodes([&](const HashSet<TaskNode*>& dev_nodes) {
747 748 749
    InplaceObasInfo safe_inplace_obas_info;
    GetSafeInplaceOpBlobArgList(&safe_inplace_obas_info, dev_nodes, IsOpNameDataOrCtrlReachable);
    SetTaskRegstInplaceInfo(safe_inplace_obas_info, dev_nodes);
L
Li Xinqi 已提交
750 751 752
  });
}

753 754
#define DEFINE_BLD_SUB_TASK_GRAPH_METHOD(method_name) \
  void TaskGraph::method_name BLD_SUB_TSK_GPH_MTHD_ARGS()
755 756

DEFINE_BLD_SUB_TASK_GRAPH_METHOD(BldSubTskGphByBoxing) {
C
cheng cheng 已提交
757 758 759
  const OpNode* src_op_node = op_edge->src_node();
  const OpNode* dst_op_node = op_edge->dst_node();
  for (const LogicalBlobId& lbi : op_edge->lbis()) {
760
    std::vector<TaskNode*> in_nodes(sorted_src_comp_tasks.begin(), sorted_src_comp_tasks.end());
761 762 763
    std::vector<TaskNode*> out_nodes;
    out_nodes.reserve(sorted_dst_comp_tasks.size());
    std::vector<std::vector<TaskNode*>> sorted_ctrl_tasks;
764 765
    const cfg::NdSbp& src_nd_sbp = src_op_node->NdSbp4Lbi(lbi);
    const cfg::NdSbp& dst_nd_sbp = dst_op_node->NdSbp4Lbi(lbi);
C
cheng cheng 已提交
766 767 768
    const ParallelDesc& src_parallel_desc = src_op_node->parallel_desc();
    const ParallelDesc& dst_parallel_desc = dst_op_node->parallel_desc();
    const BlobDesc& blob_desc = src_op_node->LogicalBlobDesc4Lbi(lbi);
769
    auto status = CHECK_JUST(hierarchical_sub_tsk_gph_builder_->Build(
C
cheng cheng 已提交
770
        sub_tsk_gph_builder_ctx_.get(), in_nodes, &out_nodes, &sorted_ctrl_tasks, src_parallel_desc,
771
        dst_parallel_desc, lbi, blob_desc, src_nd_sbp, dst_nd_sbp,
C
cheng cheng 已提交
772 773
        *(CHECK_JUST(src_op_node->op().GetOpTimeShape()).get())));
    boxing_logger_->Log(*status, src_op_node->op().op_name(), dst_op_node->op().op_name(),
774 775
                        src_parallel_desc, dst_parallel_desc, src_nd_sbp, dst_nd_sbp, lbi,
                        blob_desc);
776 777 778 779
    CHECK_EQ(out_nodes.size(), sorted_dst_comp_tasks.size());
    FOR_RANGE(size_t, i, 0, out_nodes.size()) {
      ConnectWithLbi(out_nodes.at(i), sorted_dst_comp_tasks.at(i), lbi);
    }
780 781 782 783
    if (!sorted_ctrl_tasks.empty()) {
      CHECK_EQ(sorted_ctrl_tasks.size(), sorted_dst_comp_tasks.size());
      FOR_RANGE(size_t, i, 0, sorted_dst_comp_tasks.size()) {
        for (TaskNode* ctrl_node : sorted_ctrl_tasks.at(i)) {
784 785 786 787 788
          std::string regst_desc_name;
          ctrl_node->BuildCtrlRegstDesc(sorted_dst_comp_tasks.at(i), &regst_desc_name);
          TaskEdge* edge = NewEdge();
          Connect<TaskNode>(ctrl_node, edge, sorted_dst_comp_tasks.at(i));
          ctrl_node->BindEdgeWithProducedRegst(edge, regst_desc_name);
789 790 791
        }
      }
    }
J
Juncheng 已提交
792 793 794
  }
}

795
DEFINE_BLD_SUB_TASK_GRAPH_METHOD(BldSubTskGphByOneToOne) {
W
Will Zhang 已提交
796 797
  CHECK_EQ(sorted_src_comp_tasks.size(), sorted_dst_comp_tasks.size());
  FOR_RANGE(size_t, i, 0, sorted_src_comp_tasks.size()) {
798 799 800
    for (const LogicalBlobId& lbi : op_edge->lbis()) {
      BuildTaskPath(sorted_src_comp_tasks.at(i), sorted_dst_comp_tasks.at(i), lbi);
    }
W
Will Zhang 已提交
801
  }
W
willzhang4a58 已提交
802 803
}

804
DEFINE_BLD_SUB_TASK_GRAPH_METHOD(BldSubTskGphByBroadcastToBroadcast) {
L
Li Xinqi 已提交
805
  for (CompTaskNode* dst_node : sorted_dst_comp_tasks) {
J
Juncheng 已提交
806 807 808
    CompTaskNode* nearest_src_node =
        SubTskGphBuilderUtil::FindNearestNode(sorted_src_comp_tasks, dst_node);
    CHECK_NOTNULL(nearest_src_node);
809 810 811
    for (const LogicalBlobId& lbi : op_edge->lbis()) {
      BuildTaskPath(nearest_src_node, dst_node, lbi);
    }
L
Li Xinqi 已提交
812 813 814
  }
}

L
Li Xinqi 已提交
815
DEFINE_BLD_SUB_TASK_GRAPH_METHOD(BldSubTskGphByPartialInLbiConnect) {
C
cheng cheng 已提交
816 817
  const Operator& src_op = op_edge->src_node()->op();
  const Operator& dst_op = op_edge->dst_node()->op();
L
Li Xinqi 已提交
818
  HashSet<LogicalBlobId> lbis;
C
cheng cheng 已提交
819
  for (const auto& obn : src_op.output_bns()) { lbis.insert(src_op.BnInOp2Lbi(obn)); }
L
Li Xinqi 已提交
820
  CHECK_EQ(sorted_src_comp_tasks.size(), 1);
C
cheng cheng 已提交
821
  CHECK_EQ(dst_op.input_bns().size(), sorted_dst_comp_tasks.size());
L
Li Xinqi 已提交
822
  FOR_RANGE(int, i, 0, sorted_dst_comp_tasks.size()) {
C
cheng cheng 已提交
823
    const auto& lbi = dst_op.BnInOp2Lbi(dst_op.input_bns().Get(i));
L
Li Xinqi 已提交
824
    if (lbis.find(lbi) != lbis.end()) {
825
      BuildTaskPath(sorted_src_comp_tasks.at(0), sorted_dst_comp_tasks.at(i), lbi);
L
Li Xinqi 已提交
826 827 828 829 830
    }
  }
}

DEFINE_BLD_SUB_TASK_GRAPH_METHOD(BldSubTskGphByPartialOutLbiConnect) {
C
cheng cheng 已提交
831 832
  const Operator& src_op = op_edge->src_node()->op();
  const Operator& dst_op = op_edge->dst_node()->op();
L
Li Xinqi 已提交
833
  HashSet<LogicalBlobId> lbis;
C
cheng cheng 已提交
834
  for (const auto& ibn : dst_op.input_bns()) { lbis.insert(dst_op.BnInOp2Lbi(ibn)); }
L
Li Xinqi 已提交
835
  CHECK_EQ(sorted_dst_comp_tasks.size(), 1);
C
cheng cheng 已提交
836
  CHECK_EQ(src_op.output_bns().size(), sorted_src_comp_tasks.size());
L
Li Xinqi 已提交
837
  FOR_RANGE(int, i, 0, sorted_src_comp_tasks.size()) {
C
cheng cheng 已提交
838
    const auto& lbi = src_op.BnInOp2Lbi(src_op.output_bns().Get(i));
L
Li Xinqi 已提交
839
    if (lbis.find(lbi) != lbis.end()) {
840
      BuildTaskPath(sorted_src_comp_tasks.at(i), sorted_dst_comp_tasks.at(0), lbi);
L
Li Xinqi 已提交
841 842 843 844
    }
  }
}

845
DEFINE_BLD_SUB_TASK_GRAPH_METHOD(BldSubTskGphBySrcSubsetConnect) {
L
Li Xinqi 已提交
846
  std::function<Maybe<CompTaskNode*>(int64_t mchn_id, int64_t thrd_id)> TaskNode4MachineId7ThrdId;
847 848 849 850 851 852
  CHECK_JUST(
      MakeGetterTaskNode4MachineId7ThrdId(sorted_src_comp_tasks, &TaskNode4MachineId7ThrdId));
  for (CompTaskNode* dst_task_node : sorted_dst_comp_tasks) {
    CompTaskNode* src_task_node = CHECK_JUST(
        TaskNode4MachineId7ThrdId(dst_task_node->machine_id(), dst_task_node->thrd_id()));
    Connect<TaskNode>(src_task_node, NewTaskEdgeWithLbis(op_edge->lbis()), dst_task_node);
L
Li Xinqi 已提交
853 854 855 856
  }
}

DEFINE_BLD_SUB_TASK_GRAPH_METHOD(BldSubTskGphByDstSubsetConnect) {
857 858 859 860 861 862 863 864
  std::function<Maybe<CompTaskNode*>(int64_t mchn_id, int64_t thrd_id)> TaskNode4MachineId7ThrdId;
  CHECK_JUST(
      MakeGetterTaskNode4MachineId7ThrdId(sorted_dst_comp_tasks, &TaskNode4MachineId7ThrdId));
  for (CompTaskNode* src_task_node : sorted_src_comp_tasks) {
    CompTaskNode* dst_task_node = CHECK_JUST(
        TaskNode4MachineId7ThrdId(src_task_node->machine_id(), src_task_node->thrd_id()));
    Connect<TaskNode>(src_task_node, NewTaskEdgeWithLbis(op_edge->lbis()), dst_task_node);
  }
L
Li Xinqi 已提交
865 866
}

867 868 869 870 871
DEFINE_BLD_SUB_TASK_GRAPH_METHOD(BldSubTskGphNormalForwardToDecodeH2D) {
  CHECK_EQ(sorted_src_comp_tasks.size(), sorted_dst_comp_tasks.size());
  FOR_RANGE(size_t, i, 0, sorted_src_comp_tasks.size()) {
    CompTaskNode* src = sorted_src_comp_tasks.at(i);
    CompTaskNode* dst = sorted_dst_comp_tasks.at(i);
J
Juncheng 已提交
872
    for (const LogicalBlobId& lbi : op_edge->lbis()) { ConnectWithLbi(src, dst, lbi); }
873 874 875
  }
}

876 877 878 879 880 881 882
void TaskGraph::ConnectWithLbi(TaskNode* src_node, TaskNode* dst_node, const LogicalBlobId& lbi) {
  if (src_node == dst_node) { return; }
  for (TaskEdge* out_edge : src_node->out_edges()) {
    TaskNode* out_node = out_edge->dst_node();
    if (out_node == dst_node) {
      out_edge->AddLbi(lbi);
      return;
883
    }
L
lixinqi 已提交
884
  }
885

886 887 888
  TaskEdge* connected_edge = NewEdge();
  connected_edge->AddLbi(lbi);
  Connect<TaskNode>(src_node, connected_edge, dst_node);
W
willzhang4a58 已提交
889 890
}

891
void TaskGraph::BuildTaskPath(TaskNode* src_node, TaskNode* dst_node, const LogicalBlobId& lbi) {
L
leaves-zwx 已提交
892
  TaskNode* proxy_node = GetProxyNode(src_node, lbi, dst_node->MemZoneId121());
893
  ConnectWithLbi(proxy_node, dst_node, lbi);
W
willzhang4a58 已提交
894 895
}

W
willzhang4a58 已提交
896
}  // namespace oneflow