cinn_subgraph_detector.cc 8.6 KB
Newer Older
S
sunli 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
/* Copyright (c) 2018 PaddlePaddle 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. */

#include "paddle/fluid/framework/paddle2cinn/cinn_subgraph_detector.h"
#include "glog/logging.h"
#include "paddle/fluid/framework/ir/subgraph_detector.h"

namespace paddle {
namespace framework {
namespace paddle2cinn {

std::unordered_set<Node*> GetProducerOps(Node* node) {
  CHECK(node->IsOp());
  std::unordered_set<Node*> producers;

  for (auto input_var : node->inputs) {
    CHECK(input_var->IsVar());
    for (auto input_op : input_var->inputs) {
      CHECK(input_op->IsOp());
      producers.insert(input_op);
    }
  }

  return producers;
}

std::unordered_set<Node*> GetConsumerOps(Node* node) {
  CHECK(node->IsOp());
  std::unordered_set<Node*> consumers;

  for (auto output_var : node->outputs) {
    CHECK(output_var->IsVar());
    for (auto output_op : output_var->outputs) {
      CHECK(output_op->IsOp());
      consumers.insert(output_op);
    }
  }

  return consumers;
}

S
sunli 已提交
53 54 55
void CinnSubGraph::Insert(Node* op) {
  nodes.push_back(op);
  node_set.insert(op);
S
sunli 已提交
56

S
sunli 已提交
57 58 59
  auto producers = GetProducerOps(op);
  for (auto producer : producers) {
    input_nodes.insert(producer);
S
sunli 已提交
60
  }
S
sunli 已提交
61 62
  input_nodes.erase(op);
}
S
sunli 已提交
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155

void CinnSubgraphDetector::DoOpFusion() {
  // sort node from input to output
  for (auto& node : TopologicalSort(*graph_)) {
    if (node.IsVar()) {
      continue;
    }
    nodes_.push_back(&node);
  }
  // reverse from output to input
  std::reverse(nodes_.begin(), nodes_.end());

  // do fusion
  for (auto* node : nodes_) {
    auto subgraph =
        subgraph_map_.count(node)
            ? subgraph_map_[node]
            : std::make_shared<CinnSubGraph>(node, node_classifier_(node));
    if (!subgraph_map_.count(node)) {
      subgraph_map_[node] = subgraph;
    }
    auto producers = GetProducerOps(node);

    for (auto producer : producers) {
      if (node_classifier_(producer) != subgraph->substitute) {
        continue;
      }

      bool can_fused = true;
      auto consumers = GetConsumerOps(producer);
      for (auto consumer : consumers) {
        if (!subgraph->node_set.count(consumer)) {
          can_fused = false;
          break;
        }
      }

      if (!can_fused) {
        continue;
      }

      // fuse producer to sub-graph
      subgraph->Insert(producer);
      subgraph_map_[producer] = subgraph;
    }
  }
}

void CinnSubgraphDetector::BuildSubGraph() {
  std::unordered_set<CinnSubGraph*> subgraph_set;
  for (auto node : nodes_) {
    CHECK(subgraph_map_.count(node));
    auto& subgraph = subgraph_map_[node];
    if (subgraph_set.count(subgraph.get())) {
      continue;
    }

    subgraph_set.insert(subgraph.get());
    subgraph_list_.push_back(subgraph);
  }

  for (auto& subgraph : subgraph_list_) {
    for (auto& input_node : subgraph->input_nodes) {
      CHECK(subgraph_map_.count(input_node));
      auto& producer = subgraph_map_[input_node];
      subgraph->producers.insert(producer);
      producer->consumers.insert(subgraph);
    }
  }

  // init group depth.
  for (auto& subgraph : subgraph_list_) {
    for (auto& consumer : subgraph->consumers) {
      // update depth.
      subgraph->depth = std::max(subgraph->depth, consumer->depth + 1);
    }
    subgraph->max_depth = subgraph->depth;
    subgraph->min_depth = subgraph->depth;
  }

  // reverse to keep fusion group in order.
  std::reverse(subgraph_list_.begin(), subgraph_list_.end());
}

void CinnSubgraphDetector::DoSubGraphFusion() {
  while (true) {
    bool update = false;
    for (auto& subgraph : subgraph_list_) {
      // sub graph is not substitute
      if (!subgraph->substitute) {
        continue;
      }
      // do fusion
S
sunli 已提交
156
      update |= FuseSubGraph(subgraph);
S
sunli 已提交
157 158 159 160 161 162 163
    }
    if (!update) {
      break;
    }
  }
}

S
sunli 已提交
164 165
bool CinnSubgraphDetector::FuseSubGraph(CinnSubGraphPtr subgraph_ptr) {
  auto producer = subgraph_ptr;
S
sunli 已提交
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
  auto& consumers = producer->consumers;
  std::vector<CinnSubGraphPtr> candidates;
  for (auto& consumer : consumers) {
    if (!consumer->substitute) {
      continue;
    }
    // fast depency check.
    if (IsDependencySimplify(producer, consumer, consumers)) {
      continue;
    }
    // global depency check.
    if (IsDependency(producer, consumer, consumers)) {
      continue;
    }

    candidates.push_back(consumer);
  }

  if (!candidates.size()) {
    return false;
  }

  // fuse candidate to producer
  for (auto& candidate : candidates) {
    candidate->substitute = false;

    // merge nodes
    producer->nodes.insert(producer->nodes.end(),
                           candidate->nodes.begin(),
                           candidate->nodes.end());
    producer->node_set.insert(candidate->node_set.begin(),
                              candidate->node_set.end());

    // update bound for check depency
    producer->max_depth = std::max(producer->max_depth, candidate->max_depth);
    producer->min_depth = std::min(producer->min_depth, candidate->min_depth);

    // merge producer/consumer
    producer->producers.insert(candidate->producers.begin(),
                               candidate->producers.end());
    producer->consumers.insert(candidate->consumers.begin(),
                               candidate->consumers.end());
    // update producers's consumer
    for (auto& tmp : candidate->producers) {
      if (tmp.get() == producer.get()) {
        continue;
      }
      tmp->consumers.insert(producer);
      tmp->consumers.erase(candidate);
    }
    // update consumers's producer
    for (auto& tmp : candidate->consumers) {
      tmp->producers.insert(producer);
      tmp->producers.erase(candidate);
    }

    // remove candicate in producer/consumer
    producer->producers.erase(candidate);
    producer->consumers.erase(candidate);

    // merge input nodes
    producer->input_nodes.insert(candidate->input_nodes.begin(),
                                 candidate->input_nodes.end());
  }

  // remove input nodes that is in node set
  auto input_nodes = producer->input_nodes;
  for (auto input_node : input_nodes) {
    if (producer->node_set.count(input_node)) {
      producer->input_nodes.erase(input_node);
    }
  }

  // remove producer from set.
  producer->producers.erase(producer);
  producer->consumers.erase(producer);

  return true;
}

bool CinnSubgraphDetector::IsDependency(
    const CinnSubGraphPtr& producer_g,
    const CinnSubGraphPtr& consumer,
S
sunli 已提交
249
    const std::unordered_set<CinnSubGraphPtr>& consumers) {
S
sunli 已提交
250 251 252
  std::queue<CinnSubGraphPtr> candidates;
  candidates.push(consumer);

S
sunli 已提交
253
  std::unordered_set<CinnSubGraphPtr> visited_set;
S
sunli 已提交
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
  while (!candidates.empty()) {
    auto& candidate = candidates.front();
    candidates.pop();
    for (auto& producer : candidate->producers) {
      if (producer.get() == producer_g.get()) {
        continue;
      }
      if (consumers.count(producer)) {
        return true;
      }
      if (!visited_set.count(producer)) {
        visited_set.insert(producer);
        candidates.push(producer);
      }
    }
  }
  return false;
}

bool CinnSubgraphDetector::IsDependencySimplify(
    const CinnSubGraphPtr& producer_g,
    const CinnSubGraphPtr& consumer,
S
sunli 已提交
276
    const std::unordered_set<CinnSubGraphPtr>& consumers) {
S
sunli 已提交
277 278 279 280
  std::queue<CinnSubGraphPtr> candidates;
  candidates.push(consumer);
  // check upper bound.
  int check_upper_depth = producer_g->max_depth;
S
sunli 已提交
281
  std::unordered_set<CinnSubGraphPtr> visited_set;
S
sunli 已提交
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
  while (!candidates.empty()) {
    auto& candidate = candidates.front();
    candidates.pop();
    for (auto& producer : candidate->producers) {
      if (producer.get() == producer_g.get()) {
        continue;
      }
      if (producer->min_depth > check_upper_depth) {
        continue;
      }
      if (consumers.count(producer)) {
        return true;
      }
      if (!visited_set.count(producer)) {
        visited_set.insert(producer);
        candidates.push(producer);
      }
    }
  }
  return false;
}

std::vector<std::vector<Node*>> CinnSubgraphDetector::operator()() {
  DoOpFusion();
  BuildSubGraph();
  DoSubGraphFusion();

  std::vector<std::vector<Node*>> clusters;
  for (auto& subgraph : subgraph_list_) {
    if (!subgraph->substitute) {
      continue;
    }
    clusters.push_back(subgraph->nodes);
  }

  return clusters;
}

}  // namespace paddle2cinn
}  // namespace framework
}  // namespace paddle