op_fusion_pass.cc 15.3 KB
Newer Older
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
// Copyright (c) 2022 CINN 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/cinn/common/type.h"
#include "paddle/cinn/hlir/pass/op_fusion_pass_util.h"

namespace cinn {
namespace hlir {
namespace pass {

using framework::Graph;
using framework::Node;
using framework::NodeData;
using framework::OpPatternKind;
using framework::shape_t;

using common::GraphEdge;
using common::GraphNode;

31
using GroupPtr = std::shared_ptr<Graph::Group>;
32 33
using GroupList = std::vector<GroupPtr>;

34 35
using ConditionFunction =
    std::function<bool(const FusionHelperBase*, const Node*, const GroupPtr&)>;
36 37 38 39 40 41 42

// Op Fusion Pass which performs Ops fusion, Ops are fused
// "vertically", meaning producing Ops are fused into their consumers
// with the intent that the loops which compute their values will be fused in
// code generation.
class OpFusionPassHelper : public FusionHelperBase {
 public:
43
  explicit OpFusionPassHelper(const Graph* graph) : FusionHelperBase(graph) {
44 45 46 47 48 49 50 51
    // init fusion relation
    InitFusionRelation();
    // filter node data, create group for each node
    auto nodes_inorder = std::get<0>(graph->topological_order());
    for (auto graph_node : nodes_inorder) {
      auto node = graph_node->safe_as<Node>();
      if (node) {
        nodes_.push_back(node);
52
        auto group = std::make_shared<Graph::Group>(graph);
53 54 55 56 57 58 59
        // init group
        group->nodes.push_back(node);
        group->nodes_set.insert(node);
        group->output_nodes.insert(node);
        // input node
        for (auto& edge : node->inlinks()) {
          auto input_graph_node = edge->source();
60
          auto input_node_data = input_graph_node->safe_as<NodeData>();
61 62 63 64 65 66 67 68 69 70 71
          CHECK(input_node_data);
          // input data has no source node
          if (input_node_data->source_node.get()) {
            group->input_nodes[input_node_data->source_node.get()] = 1;
          }
        }

        // group type
        group->op_pattern_kind = GetOpKind(node);
        // use current node as master node for schedule
        group->master_nodes.insert(node);
72
        group->group_id = node->id();
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
        fusion_groups_[node] = group;
      }
    }
    // reverse node for output to input
    std::reverse(nodes_.begin(), nodes_.end());
  }

  // return a vector of groups in topological order.
  GroupList operator()(bool do_fusion = true) {
    // do op fusion.
    if (do_fusion) {
      DoOpFusion();
    }

    // find all fusion group.
    GroupList fusion_groups;
    std::unordered_set<Graph::Group*> groups_set;
    for (auto node : nodes_) {
      auto& group = fusion_groups_[node];
      if (!groups_set.count(group.get())) {
        groups_set.insert(group.get());
        fusion_groups.push_back(group);
        // reverse nodes order to producer->consumer.
        std::reverse(group->nodes.begin(), group->nodes.end());
      }
    }

    // producer consumer
    for (auto& consumer : fusion_groups) {
      for (auto& input_node : consumer->input_nodes) {
        auto& producer = fusion_groups_[input_node.first];
104 105
        consumer->mut_producer_groups()->insert(producer);
        producer->mut_consumer_groups()->insert(consumer);
106 107 108 109 110
      }
    }

    // init group depth.
    for (auto& group : fusion_groups) {
111
      for (const auto& consumer : group->consumer_groups()) {
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
        // update depth.
        group->depth = std::max(group->depth, consumer->depth + 1);
      }
    }

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

    return fusion_groups;
  }

 private:
  void DoOpFusion() {
    for (auto consumer : nodes_) {
      auto consumer_kind = GetOpKind(consumer);
      // kNonFusible op can't fuse any other op.
      if (consumer_kind == framework::kNonFusible) {
        continue;
      }

      // fusion op for consumer
      auto consumer_fusion = fusion_groups_[consumer];  //
      // check all linkin node
      for (auto& edge : consumer->inlinks()) {
136
        auto graph_node = edge->source();
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
        auto producer_data = graph_node->safe_as<NodeData>();
        CHECK(producer_data);

        auto producer = producer_data->source_node.get();
        // if producer is fused.
        if (consumer_fusion->nodes_set.count(producer)) {
          VLOG(3) << "Op " << producer->id() << " is fused.";
          continue;
        }
        // if producer data is placeholder
        if (!producer) {
          continue;
        }

        // kNonFusible op can't fuse any other op.
        auto producer_kind = GetOpKind(producer);
        if (producer_kind == framework::kNonFusible) {
          continue;
        }
156 157 158 159
        VLOG(3) << "Producer Op: " << producer->id()
                << ", Op Pattern: " << producer_kind
                << " -> Consumer Op: " << consumer->id()
                << ", Op Pattern: " << consumer_kind;
160 161 162 163 164 165
        bool can_fuse = true;
        // checkout producer node outputs are all in fusion op
        for (auto& link : producer_data->outlinks()) {
          auto consumer_node = link->sink()->safe_as<Node>();
          CHECK(consumer_node);
          // if fusion group can't find node, can't merge
166 167
          if (consumer_fusion->nodes_set.find(consumer_node) ==
              consumer_fusion->nodes_set.end()) {
168 169 170 171 172 173
            can_fuse = false;
            break;
          }
        }

        if (!can_fuse || !CanFuse(producer, consumer)) continue;
174 175
        VLOG(3) << "Fuse Op " << producer->id() << " into Op "
                << consumer->id();
176 177

        // fuse producer to fusion group
178 179
        consumer_fusion->group_id =
            producer->id() + "_" + consumer_fusion->group_id;
180 181 182 183
        consumer_fusion->nodes.push_back(producer);
        consumer_fusion->nodes_set.insert(producer);
        consumer_fusion->input_nodes.erase(producer);
        consumer_fusion->op_pattern_kind =
184 185
            static_cast<int>(consumer_fusion->op_pattern_kind) >
                    static_cast<int>(producer_kind)
186 187 188 189 190 191 192 193 194 195
                ? consumer_fusion->op_pattern_kind
                : producer_kind;

        if (producer_kind == framework::kReduction) {
          consumer_fusion->master_nodes.insert(producer);
        }

        if (this->output_nodes_set_.count(producer)) {
          VLOG(3) << "Insert Global Output Node : " << producer->id();
          consumer_fusion->output_nodes.insert(producer);
196 197
        } else if (producer_data->outlinks().size() > 1 &&
                   producer->inlinks().size() > 0 &&
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
                   is_same_size(this, producer, consumer_fusion)) {
          // producer is not a const value node.
          consumer_fusion->internal_nodes.insert(producer);
        }

        // fuse input node
        auto& producer_fusion = fusion_groups_[producer];
        for (auto input_node : producer_fusion->input_nodes) {
          if (consumer_fusion->input_nodes.count(input_node.first)) {
            consumer_fusion->input_nodes[input_node.first] += input_node.second;
          } else {
            consumer_fusion->input_nodes.insert(input_node);
          }
        }

        // update node group
        fusion_groups_[producer] = consumer_fusion;
      }
    }
  }

  void InitFusionRelation() {
    // fusion relation.
    // 1.kElementwise as producer
    {
      FusionRelation relation;
      // producer -> consumer
225 226 227 228
      relation.op_kind = {framework::kElementWise,
                          framework::kBroadcast,
                          framework::kReduction,
                          framework::kInjective};
229 230
      // producer -> fusion
      relation.fusion_op_kind = {
231 232
          // horizontal or vertical relation(Elementwise + *Elementwise*). As
          // has same output shape, can always fuse.
233
          {framework::kElementWise, always_fuse},
234 235
          // must be horizontal, as Elementwise + Broadcast is left to fusion
          // merge pass.
236
          {framework::kBroadcast,
237 238 239
           [](const FusionHelperBase* helper,
              const Node* producer,
              const GroupPtr& consumer) -> bool {
240 241 242 243 244
             if (is_same_size(helper, producer, consumer)) {
               return true;
             }
             return !helper->output_nodes_set_.count(producer);
           }},
245 246
          // horizontal or vertical relation, check with same output shape with
          // horizontal relation or with last
247 248
          // successive dimension less than 1024 for gpu.
          {framework::kReduction, horizontal_or_vertical_reduce_relation},
249 250
          // can be horizontal or can compute inline, check with same output
          // shape or can compute inline.
251 252 253 254 255 256 257 258 259
          {framework::kInjective, horizontal_or_can_inline},
          // must be horizontal, check with same output shape.
          {framework::kOutFusible, is_same_shape}};
      fusion_relation_map_[framework::kElementWise] = std::move(relation);
    }
    // 2.kBroadcast as producer
    {
      FusionRelation relation;
      // producer -> consumer
260 261 262
      relation.op_kind = {framework::kElementWise,
                          framework::kReduction,
                          framework::kInjective};
263 264
      // producer -> fusion
      relation.fusion_op_kind = {
265 266
          // horizontal or vertical relation(Broadcast + *Elementwise*), check
          // with same output shape.
267 268 269 270 271
          {framework::kElementWise, is_same_size},
          // must be horizontal, as Broadcast + Broadcast is not allowed.
          {framework::kBroadcast, is_same_size},
          // horizontal or vertical relation(Broadcast + Reduce).
          {framework::kReduction, horizontal_or_vertical_reduce_relation},
272 273
          // can be horizontal or can compute inline, check with same output
          // shape or just one consumer.
274 275 276 277 278 279 280 281 282 283 284 285
          {framework::kInjective, horizontal_or_can_inline},
          // must be horizontal, check with same output shape.
          {framework::kOutFusible, is_same_shape}};
      fusion_relation_map_[framework::kBroadcast] = std::move(relation);
    }
    // 3.kReduction as producer
    {
      FusionRelation relation;
      // producer -> consumer
      relation.op_kind = {framework::kElementWise, framework::kBroadcast};
      // producer -> fusion
      relation.fusion_op_kind = {
286 287
          // horizontal or vertical relation(Reduce + Elementwise*), check
          // without last dimension in reduce.
288
          {framework::kElementWise, is_same_size},
289 290
          // must be horizontal relation, check with same output shape and
          // without last dimension in reduce.
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
          {framework::kBroadcast, reduce_fuse_broadcast},
          // must be horizontal relation and with same reduce attr.
          {framework::kReduction, reduce_fuse_reduce},
          // no_fuse
          {framework::kInjective, no_fuse},
          // can't fuse.
          {framework::kOutFusible, no_fuse}};
      fusion_relation_map_[framework::kReduction] = std::move(relation);
    }
    // 4.kInjective
    {
      FusionRelation relation;
      // producer -> consumer
      relation.op_kind = {framework::kElementWise, framework::kInjective};
      // producer -> fusion
      relation.fusion_op_kind = {
307 308
          // can be horizontal or vertical(Injective + Elementwise), check with
          // same output shape.
309 310 311 312 313 314 315 316 317 318 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
          {framework::kElementWise, is_same_size},
          // must be horizontal relation, check with same output shape.
          {framework::kBroadcast, horizontal_with_same_size},
          // left to fusion merge pass.
          {framework::kReduction, no_fuse},
          // must be horizontal relation, check with same output shape.
          {framework::kInjective, horizontal_or_can_inline},
          // can't fuse.
          {framework::kOutFusible, no_fuse},
      };
      fusion_relation_map_[framework::kInjective] = std::move(relation);
    }
    // 5.kOutFusible
    {
      FusionRelation relation;
      // producer -> consumer
      relation.op_kind = {framework::kElementWise, framework::kBroadcast};
      // producer -> fusion
      relation.fusion_op_kind = {
          // horizontal or vertical relation, check has same shape.
          {framework::kElementWise, is_same_shape},
          // it must be horizontal relation, check has same shape.
          {framework::kBroadcast, is_same_shape},
          // can't fuse.
          {framework::kReduction, no_fuse},
          // must be horizontal relation, check has same shape.
          {framework::kInjective, is_same_shape},
          // can't fuse.
          {framework::kOutFusible, no_fuse},
      };
      fusion_relation_map_[framework::kOutFusible] = std::move(relation);
    }
  }

  bool CanFuse(const Node* producer, const Node* consumer) {
    auto& relation = fusion_relation_map_[GetOpKind(producer)];
    // first step: check producer can be fused into consumer
    if (relation.op_kind.count(GetOpKind(consumer))) {
      auto& consumer_group = fusion_groups_[consumer];
      // second step: check producer can be fused into consumer group
349 350 351 352 353
      VLOG(3) << "Call ConditionFunction, Producer Op Pattern : "
              << GetOpKind(producer) << " , Consumer Group Pattern : "
              << consumer_group->op_pattern_kind;
      return relation.fusion_op_kind[consumer_group->op_pattern_kind](
          this, producer, fusion_groups_[consumer]);
354 355 356 357 358 359 360 361 362 363 364
    }

    return false;
  }
  std::vector<Node*> nodes_;
  std::unordered_map<const Node*, GroupPtr> fusion_groups_;

  struct FusionRelation {
    // producer -> consumer
    std::unordered_set<framework::OpPatternKind> op_kind = {};
    // producer -> fusion sonsumer
365 366
    std::unordered_map<framework::OpPatternKind, ConditionFunction>
        fusion_op_kind = {};
367
  };
368 369
  std::unordered_map<framework::OpPatternKind, FusionRelation>
      fusion_relation_map_;
370 371 372 373 374
};

void OpFusionPassInternal(Graph* graph) {
  VLOG(3) << "OpFusionPass...!";
  auto op_fusion_helper = OpFusionPassHelper(graph);
375
  graph->fusion_groups = op_fusion_helper();
376 377 378

  for (auto& group : graph->fusion_groups) {
    VLOG(3) << "Group Id : " << group->group_id;
379
    for (const auto& producer : group->producer_groups()) {
380 381
      VLOG(3) << "  producer group -> " << producer->group_id;
    }
382
    for (const auto& consumer : group->consumer_groups()) {
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
      VLOG(3) << "  consumer group -> " << consumer->group_id;
    }
  }
  VLOG(3) << "OpFusionPass Finish...!";
}

void BuildNonFusedGroupsPassInternal(framework::Graph* graph) {
  auto op_fusion_helper = OpFusionPassHelper(graph);
  VLOG(3) << "Apply OpFusionPass to generate initial non-fusion groups";
  graph->fusion_groups = op_fusion_helper(false);
}

}  // namespace pass
}  // namespace hlir
}  // namespace cinn

CINN_REGISTER_HELPER(OpFusionPass) {
  CINN_REGISTER_PASS(OpFusionPass)
      .describe(
402 403
          "Op Fusion Pass which performs Ops fusion, Producer Ops are fused "
          "into Consumer Ops with certain conditions.")
404 405 406 407 408 409 410 411 412 413
      .set_change_structure(false)
      .set_body(cinn::hlir::pass::OpFusionPassInternal);

  CINN_REGISTER_PASS(BuildNonFusedGroupsPass)
      .describe("Build No Fused Groups.")
      .set_change_structure(false)
      .set_body(cinn::hlir::pass::BuildNonFusedGroupsPassInternal);

  return true;
}