fusion_merge_pass_util.h 18.9 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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
// 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.
#pragma once

#include <queue>

#include "paddle/cinn/hlir/pass/fusion_helper_base.h"

namespace cinn {
namespace hlir {
namespace pass {

#define CONDITION_FUNC(func)                                   \
  inline bool func(const FusionHelperBase* helper,             \
                   const std::shared_ptr<Graph::Group>& first, \
                   const std::shared_ptr<Graph::Group>& second)

// limit the group args number to less equal 512, as args stack size is 4K.
CONDITION_FUNC(limit_args) {
  std::unordered_set<Node*> args;
  for (auto& group : {first, second}) {
    for (auto node : group->input_nodes) {
      args.insert(node.first);
    }
    for (auto node : group->output_nodes) {
      args.insert(node);
    }
  }

  if (args.size() > 512) {
    return false;
  } else {
    return true;
  }
}

CONDITION_FUNC(always_fuse) { return true; }

CONDITION_FUNC(is_same_shape) {
  if (!limit_args(helper, first, second)) {
    return false;
  }
  auto output_var_0 = helper->GetNodeDataShape(*first->master_nodes.begin());
  auto output_var_1 = helper->GetNodeDataShape(*second->master_nodes.begin());
  return output_var_0 == output_var_1;
}

CONDITION_FUNC(is_same_size) {
  if (!limit_args(helper, first, second)) {
    return false;
  }
  auto output_var_0 = helper->GetNodeDataShape(*first->master_nodes.begin());
  auto output_var_1 = helper->GetNodeDataShape(*second->master_nodes.begin());
  if (output_var_0 == output_var_1) {
    return true;
  }

69 70 71 72
  auto size_0 = std::accumulate(
      output_var_0.begin(), output_var_0.end(), 1, std::multiplies<int>());
  auto size_1 = std::accumulate(
      output_var_1.begin(), output_var_1.end(), 1, std::multiplies<int>());
73 74 75
  return size_0 == size_1;
}

76 77 78 79
bool is_const_group(const FusionHelperBase* helper,
                    const std::shared_ptr<Graph::Group>& group) {
  return group->CollectNodes().size() == 1 &&
         helper->IsConstOp(group->CollectNodes()[0]);
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

CONDITION_FUNC(elementwise_fuse_broadcast) {
  // if producer just include const op.
  if (is_const_group(helper, first)) {
    return true;
  }
  // if same shape with horizontal relation
  if (is_same_size(helper, first, second)) {
    return true;
  }
  // if first's output is not all in second's input
  for (auto output : first->output_nodes) {
    if (!second->input_nodes.count(output)) {
      return false;
    }
    if (helper->output_nodes_set_.count(output)) {
      return false;
    }
  }
  // 1.compute io-size
  // 2.compute computation-size
  // 3.compute recompute-times
  // 4.compute cost
  // TODO(sunli) : cost-model.
  return true;
}

CONDITION_FUNC(honrizontal_elementwise_fuse_reduce) {
  std::shared_ptr<Graph::Group> ele_group, reduce_group;
  if (first->op_pattern_kind == framework::kReduction) {
111
    ele_group = second;
112 113
    reduce_group = first;
  } else {
114
    ele_group = first;
115 116 117 118 119 120 121
    reduce_group = second;
  }
  // if same shape with horizontal relation
  if (is_same_size(helper, first, second)) {
    return true;
  }

122 123 124 125
  shape_t ele_node_shape =
      helper->GetNodeDataShape(*ele_group->master_nodes.begin());
  int32_t size_ele = std::accumulate(
      ele_node_shape.begin(), ele_node_shape.end(), 1, std::multiplies<int>());
126 127
  for (Node* master : reduce_group->master_nodes) {
    shape_t master_node_shape = helper->GetNodeDataShape(master);
128 129 130 131
    int32_t size_master = std::accumulate(master_node_shape.begin(),
                                          master_node_shape.end(),
                                          1,
                                          std::multiplies<int>());
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
    if (size_ele == size_master) {
      return true;
    }
  }

  return false;
}

CONDITION_FUNC(elementwise_fuse_reduce) {
  if (helper->target_ == common::DefaultHostTarget()) {
    return true;
  }
  // if same shape with horizontal relation
  if (is_same_size(helper, first, second)) {
    return true;
  }

  // if reduce nodes not in consumers of first group
  std::queue<Node*> candidates;
151
  std::unordered_set<Node*> first_node_set = first->NodeSet();
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
  std::unordered_set<Node*> second_node_set = second->NodeSet();
  for (const auto& pair : second->input_nodes) {
    if (first_node_set.find(pair.first) != first_node_set.end()) {
      candidates.push(pair.first);
    }
  }
  std::unordered_set<Node*> visited;
  std::unordered_set<Node*> masters_in_consumers;

  while (!candidates.empty()) {
    Node* candidate = candidates.front();
    candidates.pop();

    std::vector<Node*> consumers = helper->GetConsumerNode(candidate);
    for (auto consumer : consumers) {
      if (visited.count(consumer)) {
        continue;
      }
      if (second_node_set.find(consumer) != second_node_set.end()) {
        visited.insert(consumer);
        candidates.push(consumer);
      }
      if (second->master_nodes.count(consumer)) {
        masters_in_consumers.insert(consumer);
      }
    }
  }
  if (!masters_in_consumers.empty()) {
180 181 182 183 184 185 186
    bool flag = true;
    shape_t first_node_shape =
        helper->GetNodeDataShape(*first->master_nodes.begin());
    int32_t size_first = std::accumulate(first_node_shape.begin(),
                                         first_node_shape.end(),
                                         1,
                                         std::multiplies<int>());
187 188
    for (Node* master : masters_in_consumers) {
      shape_t second_node_shape = helper->GetNodeDataShape(master);
189 190 191 192
      int32_t size_second = std::accumulate(second_node_shape.begin(),
                                            second_node_shape.end(),
                                            1,
                                            std::multiplies<int>());
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
      if (size_first != size_second) {
        flag = false;
        break;
      }
    }
    if (flag) {
      return true;
    }
  }

  // if reduce using block_reduce, can't fuse producer.
  Node* reducer = nullptr;
  for (auto& node : second->master_nodes) {
    if (helper->GetOpKind(node) == framework::kReduction) {
      reducer = node;
      break;
    }
  }
  CHECK(reducer) << "Can't find reduce op in group " << second->group_id;

213 214 215 216
  // If the elementwise's output should be fetched, the output var cannot be
  // computed inline into reduce's loop, in other words, the elementwise's
  // cannot fused into reduce's loop Like: group1 = {cast_0},
  // group2={broadcast_0 -> elementwise_0 -> cast_1 -> reduce_max_0}
217 218 219 220
  if (helper->output_nodes_set_.count(*first->master_nodes.begin())) {
    return false;
  }

221 222 223 224
  auto input_shape =
      helper->shape_dict_.at(reducer->inlinks_in_order()[0]->source()->id());
  auto reduce_axes =
      absl::get<std::vector<int>>(reducer->attrs.attr_store.at("dim"));
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239

  int max_num_threads = helper->target_.max_num_threads();
  // if without last dimension in reduce.
  int lane = 1;
  if (helper->WithoutLastDimInReduce(input_shape, reduce_axes)) {
    for (int idx = reduce_axes.back() + 1; idx < input_shape.size(); ++idx) {
      lane *= input_shape[idx];
    }
    if (lane > max_num_threads / 2) {
      return true;
    }
  }

  int index = reduce_axes.size() - 1;
  for (; index >= 0; --index) {
240 241
    if (index + 1 < reduce_axes.size() &&
        reduce_axes[index] + 1 != reduce_axes[index + 1]) {
242 243 244 245 246 247 248 249 250 251 252 253
      break;
    }
    lane *= input_shape[reduce_axes[index]];
    if (lane > max_num_threads / 2) {
      break;
    }
  }

  if (lane <= max_num_threads) {
    return true;
  } else {
    int prefix = input_shape[reduce_axes[index]];
254 255 256
    int tail = lane / prefix;
    for (int idx = max_num_threads / tail; idx > (max_num_threads / 2) / tail;
         --idx) {
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
      if (prefix % idx == 0) {
        return true;
      }
    }
  }
  return false;
}

CONDITION_FUNC(broadcast_fuse_reduce) {
  // if same shape with horizontal relation
  if (is_same_size(helper, first, second)) {
    return true;
  }
  Node* reducer = nullptr;
  for (auto& node : second->master_nodes) {
    if (helper->GetOpKind(node) == OpPatternKind::kReduction) {
      reducer = node;
      break;
    }
  }
  CHECK(reducer) << "Can't find reduce op in group " << second->group_id;

279 280 281 282
  auto input_shape =
      helper->shape_dict_.at(reducer->inlinks_in_order()[0]->source()->id());
  auto input_size = std::accumulate(
      input_shape.begin(), input_shape.end(), 1, std::multiplies<int>());
283 284

  auto output_shape = helper->GetNodeDataShape(*first->master_nodes.begin());
285 286
  auto output_size = std::accumulate(
      output_shape.begin(), output_shape.end(), 1, std::multiplies<int>());
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303

  if (input_size == output_size) {
    return elementwise_fuse_reduce(helper, first, second);
  }
  return false;
}

CONDITION_FUNC(reduce_fuse_elementwise) {
  if (!is_same_size(helper, first, second)) {
    return false;
  }
  // if with last axis in reduce, fuse will waste computation resource.
  // so use a simple model evaluate the cost.
  // TODO(sunli) : cost-model.
  return true;
}

304 305 306 307 308
inline bool horizontal_relation(
    const FusionHelperBase* helper,
    const std::shared_ptr<Graph::Group>& first,
    const std::shared_ptr<Graph::Group>& second,
    const framework::OpPatternKind op_pattern_kind) {
309 310 311 312
  // merge injective
  auto merge_nodes_set = [](const std::shared_ptr<Graph::Group>& group) {
    std::unordered_set<Node*> nodes_set = group->nodes_set;
    for (auto& sub_group : group->fused_sub_groups) {
313 314
      nodes_set.insert(sub_group->nodes_set.begin(),
                       sub_group->nodes_set.end());
315 316 317
    }
    return nodes_set;
  };
318
  auto first_set = merge_nodes_set(first);
319 320
  auto second_set = merge_nodes_set(second);

321 322
  auto select_node_set = [helper](const std::unordered_set<Node*>& nodes,
                                  framework::OpPatternKind kind) {
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
    std::unordered_set<Node*> selected;
    for (auto node : nodes) {
      if (helper->GetOpKind(node) == kind) {
        selected.insert(node);
      }
    }
    return selected;
  };
  auto selected_nodes = select_node_set(second_set, op_pattern_kind);

  auto check_depency = [&](const Node* node) {
    std::queue<const Node*> candidates;
    std::unordered_set<const Node*> visited_set;
    candidates.push(node);

    while (!candidates.empty()) {
      auto& candidate = candidates.front();
      candidates.pop();
      // visit all producer node
      for (auto producer : helper->GetProducerNode(candidate)) {
        // check dependency.
        if (first_set.count(producer)) {
          return true;
        }
        // check node is in region.
        if (!second_set.count(producer)) {
          continue;
        }
        // recorded visited node.
        if (!visited_set.count(producer)) {
          visited_set.insert(producer);
          candidates.push(producer);
        }
      }
    }

    return false;
  };

  for (auto node : selected_nodes) {
    if (check_depency(node)) {
      return false;
    }
  }

  return true;
}

CONDITION_FUNC(horizontal_with_injective) {
  if (is_const_group(helper, first)) {
    return true;
  }

  if (!is_same_size(helper, first, second)) {
    return false;
  }
379 380
  return horizontal_relation(
      helper, first, second, framework::OpPatternKind::kInjective);
381 382 383 384
}

CONDITION_FUNC(injective_horizontal_with_reduce) {
  // check injective with injective.
385 386
  if (!horizontal_relation(
          helper, first, second, framework::OpPatternKind::kInjective)) {
387 388 389 390 391 392 393 394 395 396 397
    return false;
  }
  return elementwise_fuse_reduce(helper, first, second);
}

CONDITION_FUNC(reduce_fuse_broadcast) {
  // if same shape with horizontal relation
  if (is_same_size(helper, first, second)) {
    return true;
  }

398 399 400 401 402 403
  // Traversing all reducers in all producers requires two types of conditions
  // to be met. The first type is the condition that the reducer itself needs to
  // meet, and the second type is the condition that the relationship between
  // each reducer and its consumers with type of Broadcast needs to meet. It is
  // required that each consumer of type Broadcast meet the same shape after
  // broadcast as before reduce.
404 405 406 407 408 409 410
  for (auto& node_in_master : first->master_nodes) {
    if (helper->GetOpKind(node_in_master) != OpPatternKind::kReduction) {
      continue;
    }
    Node* reducer = node_in_master;
    // First type conditions
    // Get some reduce information
411
    auto reducer_input_shape = helper->GetNodeInputShape(reducer);
412
    auto reducer_output_shape = helper->GetNodeDataShape(reducer);
413 414 415
    auto reduce_axes =
        absl::get<std::vector<int>>(reducer->attrs.attr_store.at("dim"));
    auto keep_dim = absl::get<bool>(reducer->attrs.attr_store.at("keep_dim"));
416 417 418 419 420 421 422 423 424 425 426 427 428 429
    for (auto& axis : reduce_axes) {
      if (axis == -1) {
        axis = reducer_input_shape.size() - 1;
      }
    }
    // Check if the reduce axes are continuous
    int reduce_size = reducer_input_shape.back();
    for (auto idx = reduce_axes.size() - 1; idx >= 1; --idx) {
      if (reduce_axes[idx] != reduce_axes[idx - 1] + 1) {
        return false;
      }
      reduce_size *= reducer_input_shape[idx - 1];
    }
    // Check if the reduce size exceeds the hardware limit
430 431
    if (helper->target_ == common::DefaultNVGPUTarget() &&
        reduce_size > helper->target_.max_num_threads()) {
432 433 434 435
      return false;
    }

    // Second type conditions
436 437 438 439
    // Find directly or indirectly consumers with type of Broadcast in the
    // second group
    auto find_broadcasters_in_descendants =
        [&](const Node* producer) -> std::unordered_set<const Node*> {
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
      std::queue<const Node*> candidates;
      std::unordered_set<const Node*> visited_set;
      std::unordered_set<const Node*> broadcasters;
      candidates.push(producer);

      while (!candidates.empty()) {
        auto candidate = candidates.front();
        candidates.pop();

        for (auto consumer : helper->GetConsumerNode(candidate)) {
          if (!visited_set.count(consumer)) {
            visited_set.insert(consumer);
            candidates.push(consumer);
          }
          if (helper->GetOpKind(consumer) == OpPatternKind::kBroadcast &&
              second->NodeSet().find(consumer) != second->NodeSet().end()) {
            broadcasters.insert(consumer);
          }
        }
      }

      return broadcasters;
    };

    // Check if each broadcast node meets the conditions
465 466
    std::unordered_set<const Node*> broadcasters_in_consumers =
        find_broadcasters_in_descendants(reducer);
467
    for (auto broadcaster : broadcasters_in_consumers) {
468 469 470 471
      auto broadcaster_output_shape = absl::get<std::vector<int>>(
          broadcaster->attrs.attr_store.at("out_shape"));
      auto broadcast_axes = absl::get<std::vector<int>>(
          broadcaster->attrs.attr_store.at("broadcast_axes"));
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
      for (auto& axis : broadcast_axes) {
        if (axis == -1) {
          axis = broadcaster_output_shape.size() - 1;
        }
      }

      if (reducer_input_shape != broadcaster_output_shape) {
        return false;
      }

      if (keep_dim) {
        continue;
      } else {
        // if reducer_output_shape = [1]
        if (reducer_output_shape.size() == 1 && reducer_output_shape[0] == 1) {
          continue;
        }
        // check union [reduce_axes, broadcast_axes] = reducer_input_shape
        for (int idx = 0; idx < reducer_input_shape.size(); ++idx) {
491 492 493 494
          if (!(std::find(broadcast_axes.begin(), broadcast_axes.end(), idx) ==
                broadcast_axes.end()) ^
              std::find(reduce_axes.begin(), reduce_axes.end(), idx) ==
                  reduce_axes.end()) {
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
            return false;
          }
        }
      }
    }
  }

  return true;
}

CONDITION_FUNC(reduce_fuse_reduce) {
  if (!limit_args(helper, first, second)) {
    return false;
  }
  Node* reducer_0 = nullptr;
  for (auto& reducer : first->master_nodes) {
    if (helper->GetOpKind(reducer) == OpPatternKind::kReduction) {
      reducer_0 = reducer;
      break;
    }
  }
  CHECK(reducer_0) << "Can't find reduce op in group " << first->group_id;

  Node* reducer_1 = nullptr;
  for (auto& reducer : second->master_nodes) {
    if (helper->GetOpKind(reducer) == OpPatternKind::kReduction) {
      reducer_1 = reducer;
      break;
    }
  }
  CHECK(reducer_1) << "Can't find reduce op in group " << second->group_id;

  // check reduce has same input shape and output shape
528 529 530 531
  auto reducer_0_input_shape =
      helper->shape_dict_.at(reducer_0->inlinks_in_order()[0]->source()->id());
  auto reducer_0_output_shape =
      helper->shape_dict_.at(reducer_0->outlinks_in_order()[0]->sink()->id());
532

533 534 535 536
  auto reducer_1_input_shape =
      helper->shape_dict_.at(reducer_1->inlinks_in_order()[0]->source()->id());
  auto reducer_1_output_shape =
      helper->shape_dict_.at(reducer_1->outlinks_in_order()[0]->sink()->id());
537

538 539 540 541
  auto reducer_0_reduce_dim =
      absl::get<std::vector<int>>(reducer_0->attrs.attr_store.at("dim"));
  auto reducer_1_reduce_dim =
      absl::get<std::vector<int>>(reducer_1->attrs.attr_store.at("dim"));
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557

  for (auto& dim : reducer_0_reduce_dim) {
    // if dim = -1, set as shape.size() - 1
    if (dim == -1) {
      dim = reducer_0_reduce_dim.size() - 1;
    }
  }

  for (auto& dim : reducer_1_reduce_dim) {
    // if dim = -1,  set as shape.size() - 1
    if (dim == -1) {
      dim = reducer_1_reduce_dim.size() - 1;
    }
  }

  // check shape is same
558 559
  if (reducer_0_input_shape == reducer_1_input_shape &&
      reducer_0_output_shape == reducer_1_output_shape &&
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
      reducer_0_reduce_dim == reducer_1_reduce_dim) {
    auto shared_size = 0;
    for (auto& fusion_group : {first, second}) {
      for (auto* master : fusion_group->master_nodes) {
        if (helper->GetOpKind(master) == framework::kReduction) {
          shared_size += helper->GetSharedSize(master);
        }
      }
    }

#define MAX_AVAILABLE_SHREAD 32 * 1024
    if (shared_size > MAX_AVAILABLE_SHREAD) {
      return false;
    }
#undef MAX_AVAILABLE_SHREAD
    return true;
  }

578 579 580 581 582 583
  if (helper->WithoutLastDimInReduce(reducer_0_input_shape,
                                     reducer_0_reduce_dim) &&
      helper->WithoutLastDimInReduce(reducer_1_input_shape,
                                     reducer_1_reduce_dim) &&
      reducer_0_output_shape == reducer_1_output_shape &&
      reducer_0_reduce_dim == reducer_1_reduce_dim) {
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
    auto shared_size = 0;
    for (auto& fusion_group : {first, second}) {
      for (auto* master : fusion_group->master_nodes) {
        if (helper->GetOpKind(master) == framework::kReduction) {
          shared_size += helper->GetSharedSize(master);
        }
      }
    }

#define MAX_AVAILABLE_SHREAD 32 * 1024
    if (shared_size > MAX_AVAILABLE_SHREAD) {
      return false;
    }
#undef MAX_AVAILABLE_SHREAD
    return true;
  }

  return false;
}

#undef CONDITION_FUNC

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