reduction.cc 40.5 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
// Copyright (c) 2021 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/hlir/pe/reduction.h"

#include <paddle/cinn/ir/ir_base.h>

#include <algorithm>

#include "paddle/cinn/common/common.h"
#include "paddle/cinn/common/ir_util.h"
#include "paddle/cinn/hlir/pe/broadcast.h"
#include "paddle/cinn/hlir/pe/elementwise.h"
#include "paddle/cinn/hlir/pe/nn_util.h"
#include "paddle/cinn/ir/ir_operators.h"
#include "paddle/cinn/ir/tensor.h"
#include "paddle/cinn/lang/builtin.h"
#include "paddle/cinn/lang/compute.h"
#include "paddle/cinn/utils/string.h"

namespace cinn {
namespace hlir {
namespace pe {

using ir::Tensor;
using lang::Compute;

/**
40 41
 * @brief transform reduction axes which could be empty or have negative
 * elements into real axes with valid dimension indices.
42 43 44
 *
 * @param ndim Number of dimensions of the output tensor.
 * @param axes The axes parameter.
45 46
 * @param real_axes A non-empty sorted array of valid dimension indices, with no
 * duplicates.
47
 *
48 49 50
 * @notes If the input axes are empty, the result will be axes including all
 * dimensions. If any input element is negative, it will be treated as an offset
 * from the last dimension (same as python indexing rules).
51
 */
52 53 54
void GetRealAxes(int ndim,
                 const std::vector<int>& axes,
                 std::vector<int>* real_axes) {
55 56 57 58 59 60 61 62 63 64
  CHECK(real_axes);
  if (axes.empty()) {
    for (int i = 0; i < ndim; ++i) {
      real_axes->push_back(i);
    }
  } else {
    for (auto axis : axes) {
      if (axis < 0) {
        axis += ndim;
      }
65 66
      CHECK_LE(axis, ndim) << "exceeds the maximum dimension: " << ndim
                           << std::endl;
67 68 69
      CHECK_GE(axis, 0);
      real_axes->push_back(axis);
    }
70 71
    real_axes->resize(std::unique(real_axes->begin(), real_axes->end()) -
                      real_axes->begin());
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
    std::sort(real_axes->begin(), real_axes->end());
  }
}

std::string Type2StrForReduce(common::Type type) {
  std::string suffix;
  if (type.is_int(32)) {
    return "_int32";
  } else if (type.is_int(64)) {
    return "_int64";
  } else if (type.is_bfloat16()) {
    return "_bf16";
  } else if (type.is_float16()) {
    return "_fp16";
  } else if (type.is_float(32)) {
    return "_fp32";
  } else if (type.is_float(64)) {
    return "_fp64";
  } else if (type.is_bool()) {
    return "";
  }
  LOG(FATAL) << "Reduce Not Support " << type;
  return "";
}

/**
 * @brief Calculate the target reduced shape.
 *
100 101
 * @param real_axes A non-empty sorted array of valid dimension indices, with no
 * duplicates.
102 103
 * @param output_shape The output Tensor shape.
 * @param tensor The input tensor.
104 105 106
 * @param keep_dims If this is set to true, the reduced axes are kept as
 * dimensions with size one. This enables the result to broadcast correctly
 * against the input array.
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
 */
void GetOutputShape(const std::vector<int>& real_axes,
                    std::vector<Expr>* output_shape,
                    const Tensor& tensor,
                    bool keep_dims) {
  CHECK(output_shape);
  auto ndim = tensor->shape.size();
  if (keep_dims) {
    for (size_t i = 0; i < ndim; ++i) {
      if (std::find(real_axes.begin(), real_axes.end(), i) != real_axes.end()) {
        output_shape->push_back(common::make_one());
      } else {
        output_shape->push_back(tensor->shape[i]);
      }
    }
  } else {
    for (size_t i = 0; i < ndim; ++i) {
      if (std::find(real_axes.begin(), real_axes.end(), i) == real_axes.end()) {
        output_shape->push_back(tensor->shape[i]);
      }
    }
  }
  if (output_shape->empty()) {
    output_shape->push_back(common::make_one());
  }
}

/*!
 * @brief Create a reduction PE.
 *
 * @param tensor The input tensor.
 * @param fn The reduction function eg. ReduceSum
 * @param output_shape The output Tensor shape.
 * @param real_axes The real axes where the reduction is performed.
141 142
 * @param squeeze_axes The real axes to squeeze. If unsqueezed, reduced axes
 * will have shape 1 in the output tensor.
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
 * @param initial Starting value for the sum.
 * @param output_name The name of the output Tensor.
 *
 * @return The result tensor.
 */
template <typename FuncOp>
Tensor DoReduce(const Tensor& tensor,
                const FuncOp& fn,
                const std::vector<Expr>& output_shape,
                const std::vector<int>& real_axes,
                const std::vector<int>& squeeze_axes,
                Expr initial,
                const std::string& output_name) {
  std::vector<Var> reduce_axes;
  int reduce_k_id = 0;
  for (auto& axis : real_axes) {
159 160
    std::string name =
        cinn::UniqName(std::string("reduce_k_") + std::to_string(reduce_k_id));
161 162 163 164 165 166 167 168 169
    reduce_axes.push_back(Var(tensor->shape[axis], name));
    reduce_k_id++;
  }
  auto compute = [&](const std::vector<Expr>& indices) -> Expr {
    std::vector<Expr> eval_indice;
    int indice_cnt = 0;
    int reduce_cnt = 0;

    for (size_t i = 0; i < tensor->shape.size(); ++i) {
170 171
      bool squeeze_i = std::find(squeeze_axes.begin(), squeeze_axes.end(), i) !=
                       squeeze_axes.end();
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
      if (std::find(real_axes.begin(), real_axes.end(), i) != real_axes.end()) {
        eval_indice.push_back(reduce_axes[reduce_cnt]);
        reduce_cnt++;
        indice_cnt += !squeeze_i;
        continue;
      }
      eval_indice.push_back(indices[indice_cnt]);
      indice_cnt++;
    }
    return fn(tensor(eval_indice), reduce_axes, initial);
  };

  Tensor C = Compute(output_shape, compute, output_name);
  return C;
}

/**
 * @brief reduction PE
 *
 * @param tensor The input tensor.
 * @param axes The axes along which the reduction are performed.
 * @param fn The reduction function eg. ReduceSum
194 195
 * @param keep_dims If it is set true, the axes which are reduced are left in
 * the result as dimensions with size one.
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
 * @param initial Starting value for the sum.
 *
 * @return The result tensor.
 */
template <typename FuncOp>
Tensor Reduce(const Tensor& tensor,
              const std::vector<int>& axes,
              const FuncOp& fn,
              bool keep_dims,
              ir::Expr initial,
              const std::string& output_name) {
  auto ndim = tensor->shape.size();
  CHECK_GT(ndim, 0) << "Reduce tensor's dim must be more than 0";
  std::vector<int> real_axes;
  GetRealAxes(static_cast<int>(ndim), axes, &real_axes);
  std::vector<Expr> output_shapes;
  GetOutputShape(real_axes, &output_shapes, tensor, keep_dims);
213 214 215 216 217 218 219
  return DoReduce(tensor,
                  fn,
                  output_shapes,
                  real_axes,
                  keep_dims ? std::vector<int>() : real_axes,
                  initial,
                  output_name);
220 221
}

222 223 224 225 226 227
Tensor ReduceSum(const Tensor& A,
                 const std::vector<int>& axes,
                 const bool keep_dims,
                 const std::string& output_name) {
  return Reduce(
      A, axes, lang::ReduceSum, keep_dims, ir::Zero(A->type()), output_name);
228 229
}

230 231 232 233 234 235
Tensor ReduceProd(const Tensor& A,
                  const std::vector<int>& axes,
                  const bool keep_dims,
                  const std::string& output_name) {
  return Reduce(
      A, axes, lang::ReduceMul, keep_dims, lang::One(A->type()), output_name);
236 237
}

238 239 240 241 242 243 244 245 246 247
Tensor ReduceMax(const Tensor& A,
                 const std::vector<int>& axes,
                 const bool keep_dims,
                 const std::string& output_name) {
  return Reduce(A,
                axes,
                lang::ReduceMax,
                keep_dims,
                lang::min_value(A->type()),
                output_name);
248 249
}

250 251 252 253 254 255 256 257 258 259
Tensor ReduceMin(const Tensor& A,
                 const std::vector<int>& axes,
                 const bool keep_dims,
                 const std::string& output_name) {
  return Reduce(A,
                axes,
                lang::ReduceMin,
                keep_dims,
                lang::max_value(A->type()),
                output_name);
260 261
}

262 263 264 265
Tensor ReduceAll(const Tensor& A,
                 const std::vector<int>& axes,
                 const bool keep_dims,
                 const std::string& output_name) {
266 267 268
  return Reduce(A, axes, lang::ReduceAll, keep_dims, Expr(true), output_name);
}

269 270 271 272
Tensor ReduceAny(const Tensor& A,
                 const std::vector<int>& axes,
                 const bool keep_dims,
                 const std::string& output_name) {
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
  return Reduce(A, axes, lang::ReduceAny, keep_dims, Expr(false), output_name);
}

std::vector<Tensor> WarpReduce(const ir::Tensor& A,
                               const int last_reduce_dim_num,
                               const bool keep_dim,
                               const std::string& reduce_type,
                               const std::string& output_name) {
  // compute shape size without last reduce dimension.
  int shape_size_without_reduce_dim = A->shape.size() - last_reduce_dim_num;

  // compute reduce dimension size.
  Expr reduce_width(1);
  for (int idx = shape_size_without_reduce_dim; idx < A->shape.size(); ++idx) {
    reduce_width = reduce_width * A->shape[idx].as_int32();
  }

  // comput tmp output shape.
291 292
  std::vector<Expr> tmp_shape(A->shape.begin(),
                              A->shape.begin() + shape_size_without_reduce_dim);
293 294 295 296
  tmp_shape.push_back(Expr(32));
  auto tmp_out = Compute(
      tmp_shape,
      [=](const std::vector<Expr>& indexs) -> Expr {
297 298
        std::vector<Expr> tmp_indexs(indexs.begin(),
                                     indexs.begin() + indexs.size() - 1);
299 300 301 302 303 304 305 306 307 308
        for (int idx = 0; idx < last_reduce_dim_num; ++idx) {
          tmp_indexs.push_back(Expr(0));
        }
        CHECK_EQ(A->shape.size(), tmp_indexs.size());
        Expr offset = common::IndiceToAbsOffset(A->shape, tmp_indexs);
        return lang::CallExtern(reduce_type, {A, offset, reduce_width});
      },
      UniqName(output_name + "_" + reduce_type));

  // compute ouput shape.
309 310
  std::vector<Expr> out_shape(A->shape.begin(),
                              A->shape.begin() + shape_size_without_reduce_dim);
311 312 313 314 315 316 317 318 319 320
  for (int idx = 0; idx < last_reduce_dim_num && keep_dim; ++idx) {
    out_shape.push_back(Expr(1));
  }
  // if reduce on all dimension, the out_shape = {1}.
  if (out_shape.size() == 0) {
    out_shape.push_back(Expr(1));
  }
  auto out = Compute(
      out_shape,
      [=](const std::vector<Expr>& indexs) -> Expr {
321 322
        std::vector<Expr> tmp_indexs(
            indexs.begin(), indexs.begin() + shape_size_without_reduce_dim);
323 324 325 326 327 328 329 330 331 332 333 334
        tmp_indexs.push_back(Expr(0));
        return tmp_out(tmp_indexs);
      },
      output_name);

  return {out, tmp_out};
}

std::vector<ir::Tensor> WarpReduceMax(const ir::Tensor& A,
                                      const int last_reduce_dim_num,
                                      const bool keep_dim,
                                      const std::string& output_name) {
335 336 337 338 339
  return WarpReduce(A,
                    last_reduce_dim_num,
                    keep_dim,
                    "cinn_warp_reduce_max" + Type2StrForReduce(A->type()),
                    output_name);
340 341 342 343 344 345
}

std::vector<ir::Tensor> WarpReduceSum(const ir::Tensor& A,
                                      const int last_reduce_dim_num,
                                      const bool keep_dim,
                                      const std::string& output_name) {
346 347 348 349 350
  return WarpReduce(A,
                    last_reduce_dim_num,
                    keep_dim,
                    "cinn_warp_reduce_sum" + Type2StrForReduce(A->type()),
                    output_name);
351 352 353 354 355 356
}

std::vector<ir::Tensor> WarpReduceAvg(const ir::Tensor& A,
                                      const int last_reduce_dim_num,
                                      const bool keep_dim,
                                      const std::string& output_name) {
357 358 359 360 361
  return WarpReduce(A,
                    last_reduce_dim_num,
                    keep_dim,
                    "cinn_warp_reduce_avg" + Type2StrForReduce(A->type()),
                    output_name);
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
}

std::vector<ir::Tensor> BlockReduceInternal(const ir::Tensor& A,
                                            const std::vector<int>& axes,
                                            const bool keep_dim,
                                            const std::string& reduce_type,
                                            const std::string& output_name) {
  CHECK_GE(A->shape.size(), axes.back() + 1) << "Axes is over size!";
  // compute reduce dimension size.
  Expr reduce_width(1);
  for (int idx = axes.front(); idx < A->shape.size(); ++idx) {
    reduce_width = reduce_width * A->shape[idx].as_int32();
  }

  // compute tmp output shape.
377 378
  std::vector<Expr> tmp_shape(A->shape.begin(),
                              A->shape.begin() + axes.front());
379 380 381 382
  tmp_shape.push_back(reduce_width);

  // compute the reduce dimension stride.
  std::vector<Expr> last_reduce_stride(A->shape.size() - axes.front(), Expr(1));
383 384 385
  for (int idx = A->shape.size(), index = int(last_reduce_stride.size()) - 2;
       index >= 0;
       --index) {
386 387 388 389 390 391 392 393
    last_reduce_stride[index] = last_reduce_stride[index + 1] * A->shape[--idx];
  }

  auto tmp_out = Compute(
      tmp_shape,
      [=](const std::vector<Expr>& indexs) -> Expr {
        // comput index map from output to input.
        auto last_index = indexs.back();
394 395
        std::vector<Expr> input_indexs(indexs.begin(),
                                       indexs.begin() + indexs.size() - 1);
396 397 398 399 400 401 402 403 404 405 406 407
        for (int idx = 0; idx < A->shape.size() - axes.front(); ++idx) {
          input_indexs.push_back(last_index / last_reduce_stride[idx]);
          last_index = last_index % last_reduce_stride[idx];
        }

        // checkout input_indexs size equals input shape
        CHECK_EQ(input_indexs.size(), A->shape.size());
        return lang::CallExtern(reduce_type, {A(input_indexs)});
      },
      UniqName(output_name + "_tmp"));

  // compute output shape.
408 409 410 411
  std::vector<Expr> out_shape(A->shape.begin(),
                              A->shape.begin() + axes.front());
  int tailf = keep_dim ? (int(A->shape.size()) - axes.front())
                       : (int(A->shape.size()) - axes.back() - 1);
412 413 414 415 416 417 418 419 420 421
  for (int idx = 0; idx < tailf; ++idx) {
    out_shape.push_back(Expr(1));
  }
  // if reduce on all dimension, the out_shape = {1}.
  if (out_shape.size() == 0) {
    out_shape.push_back(Expr(1));
  }
  auto out = Compute(
      out_shape,
      [=](const std::vector<Expr>& indexs) -> Expr {
422 423
        std::vector<Expr> tmp_indexs(indexs.begin(),
                                     indexs.begin() + axes.front());
424 425 426 427 428 429 430 431 432 433 434 435
        tmp_indexs.push_back(Expr(0));
        return tmp_out(tmp_indexs);
      },
      output_name);
  return {out, tmp_out};
}

std::vector<ir::Tensor> BlockReduceSumInternal(const ir::Tensor& A,
                                               const std::vector<int>& axes,
                                               const bool keep_dim,
                                               const std::string& output_name) {
  return BlockReduceInternal(
436 437 438 439 440
      A,
      axes,
      keep_dim,
      "cinn_block_reduce_sum" + Type2StrForReduce(A->type()) + "_internal",
      output_name);
441 442
}

443 444 445 446 447
std::vector<ir::Tensor> BlockReduceProdInternal(
    const ir::Tensor& A,
    const std::vector<int>& axes,
    const bool keep_dim,
    const std::string& output_name) {
448
  return BlockReduceInternal(
449 450 451 452 453
      A,
      axes,
      keep_dim,
      "cinn_block_reduce_prod" + Type2StrForReduce(A->type()) + "_internal",
      output_name);
454 455 456 457 458 459 460
}

std::vector<ir::Tensor> BlockReduceMaxInternal(const ir::Tensor& A,
                                               const std::vector<int>& axes,
                                               const bool keep_dim,
                                               const std::string& output_name) {
  return BlockReduceInternal(
461 462 463 464 465
      A,
      axes,
      keep_dim,
      "cinn_block_reduce_max" + Type2StrForReduce(A->type()) + "_internal",
      output_name);
466 467 468 469 470 471 472
}

std::vector<ir::Tensor> BlockReduceMinInternal(const ir::Tensor& A,
                                               const std::vector<int>& axes,
                                               const bool keep_dim,
                                               const std::string& output_name) {
  return BlockReduceInternal(
473 474 475 476 477
      A,
      axes,
      keep_dim,
      "cinn_block_reduce_min" + Type2StrForReduce(A->type()) + "_internal",
      output_name);
478 479 480 481 482 483
}

std::vector<ir::Tensor> BlockReduceAllInternal(const ir::Tensor& A,
                                               const std::vector<int>& axes,
                                               const bool keep_dim,
                                               const std::string& output_name) {
484 485
  return BlockReduceInternal(
      A, axes, keep_dim, "cinn_block_reduce_all_internal", output_name);
486 487 488 489 490 491
}

std::vector<ir::Tensor> BlockReduceAnyInternal(const ir::Tensor& A,
                                               const std::vector<int>& axes,
                                               const bool keep_dim,
                                               const std::string& output_name) {
492 493
  return BlockReduceInternal(
      A, axes, keep_dim, "cinn_block_reduce_any_internal", output_name);
494 495 496
}

/**
497 498
 * @brief compute the sum of array elements over the last dimension with block
 * reduce
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
 *
 * @param A The input Tensor.
 * @param last_reduce_dim_num the number of last reduce dimension.
 * @param keep_dim keep the output tensor shape size as input.
 * @param output_name The name of the output Tensor.
 */
std::vector<ir::Tensor> BlockReduce(const ir::Tensor& A,
                                    const std::vector<int>& axes,
                                    const int block_size,
                                    const bool keep_dim,
                                    const std::string& reduce_type,
                                    const std::string& output_name) {
  // compute reduce dimension size.
  Expr reduce_width(1);
  for (int idx = axes.front(); idx < A->shape.size(); ++idx) {
    reduce_width = reduce_width * A->shape[idx].as_int32();
  }

  // compute tmp output tensor shape
518 519
  std::vector<Expr> tmp_shape(A->shape.begin(),
                              A->shape.begin() + axes.front());
520 521 522 523
  tmp_shape.push_back(Expr(block_size));
  auto tmp_out = Compute(
      tmp_shape,
      [=](const std::vector<Expr>& indexs) -> Expr {
524 525
        std::vector<Expr> tmp_indexs(indexs.begin(),
                                     indexs.begin() + axes.front());
526 527 528 529 530 531 532 533 534 535 536 537 538
        for (int idx = 0; idx < A->shape.size() - axes.front(); ++idx) {
          tmp_indexs.push_back(Expr(0));
        }
        // checkout input shape size equals tmp indexs size.
        CHECK_EQ(A->shape.size(), tmp_indexs.size());
        // compute offset.
        Expr offset = common::IndiceToAbsOffset(A->shape, tmp_indexs);
        // call block reduce sum
        return lang::CallExtern(reduce_type, {A, offset, reduce_width});
      },
      UniqName(output_name + "_tmp"));

  // compute output tensor shape.
539 540 541 542
  std::vector<Expr> out_shape(A->shape.begin(),
                              A->shape.begin() + axes.front());
  int tailf = keep_dim ? (int(A->shape.size()) - axes.front())
                       : (int(A->shape.size()) - axes.back() - 1);
543 544 545 546 547 548 549 550 551 552 553
  for (int idx = 0; idx < tailf; ++idx) {
    out_shape.push_back(Expr(1));
  }
  // if reduce on all dimension, the out_shape = {1}.
  if (out_shape.size() == 0) {
    out_shape.push_back(Expr(1));
  }
  auto out = Compute(
      out_shape,
      [=](const std::vector<Expr>& indexs) -> Expr {
        // compute input index
554 555
        std::vector<Expr> tmp_indexs(indexs.begin(),
                                     indexs.begin() + axes.front());
556 557 558 559 560 561 562 563 564 565 566 567 568
        tmp_indexs.push_back(Expr(0));
        return tmp_out(tmp_indexs);
      },
      output_name);

  return {out, tmp_out};
}

std::vector<ir::Tensor> BlockReduceSum(const ir::Tensor& A,
                                       const std::vector<int>& axes,
                                       const int block_size,
                                       const bool keep_dim,
                                       const std::string& output_name) {
569 570 571 572 573 574
  return BlockReduce(A,
                     axes,
                     block_size,
                     keep_dim,
                     "cinn_block_reduce_sum" + Type2StrForReduce(A->type()),
                     output_name);
575 576 577 578 579 580 581
}

std::vector<ir::Tensor> BlockReduceProd(const ir::Tensor& A,
                                        const std::vector<int>& axes,
                                        const int block_size,
                                        const bool keep_dim,
                                        const std::string& output_name) {
582 583 584 585 586 587
  return BlockReduce(A,
                     axes,
                     block_size,
                     keep_dim,
                     "cinn_block_reduce_prod" + Type2StrForReduce(A->type()),
                     output_name);
588 589 590 591 592 593 594
}

std::vector<ir::Tensor> BlockReduceMax(const ir::Tensor& A,
                                       const std::vector<int>& axes,
                                       const int block_size,
                                       const bool keep_dim,
                                       const std::string& output_name) {
595 596 597 598 599 600
  return BlockReduce(A,
                     axes,
                     block_size,
                     keep_dim,
                     "cinn_block_reduce_max" + Type2StrForReduce(A->type()),
                     output_name);
601 602 603 604 605 606 607
}

std::vector<ir::Tensor> BlockReduceMin(const ir::Tensor& A,
                                       const std::vector<int>& axes,
                                       const int block_size,
                                       const bool keep_dim,
                                       const std::string& output_name) {
608 609 610 611 612 613
  return BlockReduce(A,
                     axes,
                     block_size,
                     keep_dim,
                     "cinn_block_reduce_min" + Type2StrForReduce(A->type()),
                     output_name);
614 615 616 617 618 619 620
}

std::vector<ir::Tensor> BlockReduceAll(const ir::Tensor& A,
                                       const std::vector<int>& axes,
                                       const int block_size,
                                       const bool keep_dim,
                                       const std::string& output_name) {
621 622
  return BlockReduce(
      A, axes, block_size, keep_dim, "cinn_block_reduce_all", output_name);
623 624 625 626 627 628 629
}

std::vector<ir::Tensor> BlockReduceAny(const ir::Tensor& A,
                                       const std::vector<int>& axes,
                                       const int block_size,
                                       const bool keep_dim,
                                       const std::string& output_name) {
630 631
  return BlockReduce(
      A, axes, block_size, keep_dim, "cinn_block_reduce_any", output_name);
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
}

int GetPostParallelSize(const ir::Tensor& A, const std::vector<int>& axes) {
  int parallel_size = 1;
  for (int idx = axes.back() + 1; idx < A->shape.size(); ++idx) {
    parallel_size *= A->shape[idx].as_int32();
  }
  return parallel_size;
}

int GetParallelSize(const ir::Tensor& A, const std::vector<int>& axes) {
  int parallel_size = 1;
  for (int idx = 0; idx < A->shape.size(); ++idx) {
    if (std::find(axes.begin(), axes.end(), idx) != axes.end()) {
      continue;
    }
    parallel_size *= A->shape[idx].as_int32();
  }
  return parallel_size;
}

653 654 655 656
using ReduceFunc = std::function<ir::Tensor(const ir::Tensor&,
                                            const std::vector<int>&,
                                            const bool,
                                            const std::string&)>;
657 658 659 660 661 662 663 664

std::vector<ir::Tensor> ReduceInternal(const ir::Tensor& A,
                                       const std::vector<int>& axes,
                                       const bool keep_dim,
                                       const std::string& output_name,
                                       ReduceFunc reduce_func,
                                       ir::Expr initial,
                                       std::string reduce_type) {
665
  int tail = 0;
666 667
  bool inbound = true;
  std::vector<int> inshape;
668 669 670 671
  std::transform(A->shape.begin(),
                 A->shape.end(),
                 std::back_inserter(inshape),
                 [](ir::Expr expr) { return expr.as_int32(); });
672 673 674
  auto reduce_shape = GetFirstStepReduceShape(inshape, axes, inbound, tail);
  CHECK_GT(reduce_shape.size(), 0);

675 676 677 678 679
  VLOG(4) << "Reduce " << output_name << " on " << reduce_type
          << " with input shape=[" << cinn::utils::Join(inshape, ", ")
          << "], and first step reduce_shape=["
          << cinn::utils::Join(reduce_shape, ", ") << "] at axes=["
          << cinn::utils::Join(axes, ", ") << "]";
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697

  // reshape input
  auto do_reshape_inbound = [&]() {
    int axis = axes.back();
    std::vector<ir::Expr> reshape_output_shape;
    // last successive axis in reduce axes.
    int axis_index = axes.size() - 1;
    for (; axis_index >= 1; --axis_index) {
      if (axes[axis_index] - 1 != axes[axis_index - 1]) {
        break;
      }
    }
    // compute reduce stride.
    std::vector<ir::Expr> strides(1, ir::Expr(1));
    for (int idx = axes.back(); idx > axes[axis_index]; --idx) {
      strides.insert(strides.begin(), strides.front() * ir::Expr(inshape[idx]));
    }
    CHECK_EQ(strides.size(), axes.size() - axis_index);
698 699 700 701
    std::transform(reduce_shape.begin(),
                   reduce_shape.end(),
                   std::back_inserter(reshape_output_shape),
                   [](int val) { return ir::Expr(val); });
702 703 704 705
    return Compute(
        reshape_output_shape,
        [=](const std::vector<Expr>& indexs) -> Expr {
          // index is last axis in axes and index is last axis >= tail.
706 707 708 709 710
          auto selected = ir::And::Make(
              ir::EQ::Make(indexs[axis], ir::Expr(reduce_shape[axis] - 1)),
              ir::GE::Make(indexs[axis + 1], ir::Expr(tail)));
          auto index = indexs[axis] * ir::Expr(reshape_output_shape[axis + 1]) +
                       indexs[axis + 1];
711 712

          // first part index
713 714
          std::vector<ir::Expr> tmp_indexs(indexs.begin(),
                                           indexs.begin() + axes[axis_index]);
715 716 717 718 719 720 721 722 723 724
          // second part index
          for (int idx = 0; idx < strides.size(); ++idx) {
            tmp_indexs.push_back(index / strides[idx]);
            index = index % strides[idx];
          }
          // third part index
          for (int idx = axis + 2; idx < indexs.size(); ++idx) {
            tmp_indexs.push_back(indexs[idx]);
          }

725 726
          CHECK_EQ(tmp_indexs.size(), A->shape.size())
              << "Indexs size is not equal to Input shape!";
727 728 729 730
          return ir::Select::Make(selected, A(tmp_indexs), initial);
        },
        UniqName(output_name + "_reshape"));
  };
731 732 733
  auto reshape = inbound
                     ? pe::Reshape(A, reduce_shape, output_name + "_reshape")
                     : do_reshape_inbound();
734
  // do first step reduce
735 736
  auto internal =
      reduce_func(reshape, axes, keep_dim, output_name + "_internal");
737 738 739 740 741 742 743 744 745 746 747 748
  // do second step reduce
  std::vector<int> s_axes = {};
  if (keep_dim) {
    s_axes = {axes.back() + 1};
  } else {
    s_axes = {axes.back() + 1 - static_cast<int>(axes.size())};
  }
  auto reduce_out = reduce_func(internal, s_axes, false, output_name);

  return {reduce_out, internal, reshape};
}

749 750 751 752 753 754 755 756 757 758 759 760 761
#define BLOCK_SHUFFLE_REDUCE(name, reduce_type, initial)                       \
  std::vector<ir::Tensor> BlockShuffleReduce##name(                            \
      const ir::Tensor& A,                                                     \
      const std::vector<int>& axes,                                            \
      const bool keep_dim,                                                     \
      const std::string& output_name) {                                        \
    if (common::GetMaxThreads() / GetParallelSize(A, axes) <= 1) {             \
      return {Reduce##name(A, axes, keep_dim, output_name)};                   \
    } else {                                                                   \
      auto rs = ReduceInternal(                                                \
          A, axes, keep_dim, output_name, Reduce##name, initial, reduce_type); \
      if (rs.size() == 0) {                                                    \
        return {Reduce##name(A, axes, keep_dim, output_name)};                 \
762
      } else {                                                                 \
763
        return rs;                                                             \
764
      }                                                                        \
765
    }                                                                          \
766 767
  }

768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
BLOCK_SHUFFLE_REDUCE(Sum,
                     "block_shuffle_sum" + Type2StrForReduce(A->type()),
                     ir::Zero(A->type()));
BLOCK_SHUFFLE_REDUCE(Prod,
                     "block_shuffle_prod" + Type2StrForReduce(A->type()),
                     lang::One(A->type()));
BLOCK_SHUFFLE_REDUCE(Max,
                     "block_shuffle_max" + Type2StrForReduce(A->type()),
                     lang::min_value(A->type()));
BLOCK_SHUFFLE_REDUCE(Min,
                     "block_shuffle_min" + Type2StrForReduce(A->type()),
                     lang::max_value(A->type()));
BLOCK_SHUFFLE_REDUCE(All,
                     "block_shuffle_all" + Type2StrForReduce(A->type()),
                     Expr(true));
BLOCK_SHUFFLE_REDUCE(Any,
                     "block_shuffle_any" + Type2StrForReduce(A->type()),
                     Expr(false));

bool WithoutLastDimInReduce(const std::vector<ir::Expr>& inshape,
                            const std::vector<int>& axes) {
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804
  // if last axis is in reduce.
  if (std::find(axes.begin(), axes.end(), inshape.size() - 1) != axes.end() ||
      std::find(axes.begin(), axes.end(), -1) != axes.end()) {
    return false;
  }

  int sum_last_axes = 1;
  for (int idx = axes.back() + 1; idx < inshape.size(); ++idx) {
    sum_last_axes *= inshape[idx].as_int32();
  }

  if (sum_last_axes > 1) {
    return true;
  } else {
    return false;
  }
805
}
806 807

using BlockReduceFunc =
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
    std::function<std::vector<ir::Tensor>(const ir::Tensor&,
                                          const std::vector<int>&,
                                          const bool,
                                          const std::string&)>;

std::vector<ir::Tensor> TwoStepBlockReduceInternal(
    const ir::Tensor& A,
    const std::vector<int>& axes,
    const bool keep_dim,
    const std::string& output_name,
    ReduceFunc reduce_func,
    BlockReduceFunc block_reduce_func,
    ir::Expr initial) {
  CHECK(!WithoutLastDimInReduce(A->shape, axes))
      << "Can't find last axis in reduce!";
823 824 825
  // If the number of current device SM is smaller than the number of SM
  // required by Warp Reduce, the performance of Warp Reduce is better.
  // Otherwise, use Block Reduce.
826
  auto max_num_threads = common::DefaultNVGPUTarget().max_num_threads();
827 828 829 830 831 832 833
  int need_reduce_last_count = 1;
  for (int i = 0; i < A->shape.size(); i++) {
    if (find(axes.begin(), axes.end(), i) == axes.end()) {
      need_reduce_last_count *= A->shape[i].as_int32();
    }
  }
  int warp_reduce_need_sm_count =
834 835
      ceil((need_reduce_last_count * 32) /
           float(common::DefaultNVGPUTarget().get_max_threads_per_sm()));
836
  // Set Num_max_threads to 32 is Warp Reduce
837 838
  if (common::DefaultNVGPUTarget().get_multi_processor_count() <
      warp_reduce_need_sm_count) {
839 840 841
    max_num_threads = 32;
  }

842
  int lane = A->shape[axes.back()].as_int32();
843 844 845 846 847 848 849 850 851 852 853 854 855
  int index = static_cast<int>(axes.size()) - 2;
  for (; index >= 0; --index) {
    if (lane >= max_num_threads / 2) {
      break;
    }
    if (axes[index] != axes[index + 1] - 1) {
      break;
    }
    lane *= A->shape[axes[index]].as_int32();
  }
  std::vector<int> first_axes(axes.begin(), axes.begin() + index + 1);
  std::vector<int> second_axes(axes.begin() + index + 1, axes.end());

856 857
  bool keep_dim_first = keep_dim;
  bool keep_dim_second = keep_dim;
858 859 860 861 862 863 864 865 866 867 868 869 870
  auto reduce_reshape_func = [&first_axes,
                              &keep_dim_first,
                              &second_axes,
                              &keep_dim_second,
                              A,
                              axes,
                              keep_dim,
                              output_name,
                              lane,
                              index,
                              max_num_threads,
                              &initial]() {
    bool check_bound = true;
871 872
    std::vector<Expr> out_shape(A->shape.begin(),
                                A->shape.begin() + second_axes.front());
873 874
    if (second_axes.size() == 1) {
      int times = 1;
875
      int tail = max_num_threads;
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
      for (; tail >= max_num_threads / 2; --tail) {
        if (lane % tail == 0) {
          check_bound = false;
          break;
        }
      }
      if (!check_bound) {
        times = lane / tail;
        out_shape.emplace_back(times);
        out_shape.emplace_back(tail);
      } else {
        times = (lane + max_num_threads - 1) / max_num_threads;
        out_shape.emplace_back(times);
        out_shape.emplace_back(max_num_threads);
      }
    } else {
      int times = 1;
893 894
      int head = A->shape[second_axes.front()].as_int32();
      int tail = lane / head;
895
      // from (1024, 512) check one size as tail.
896 897 898
      for (int idx = (max_num_threads / tail);
           idx > (max_num_threads / 2 / tail);
           --idx) {
899 900
        if (head % idx == 0) {
          check_bound = false;
901
          times = idx;
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
          tail *= idx;
          break;
        }
      }
      if (!check_bound) {
        out_shape.emplace_back(head / times);
        out_shape.emplace_back(tail);
      } else {
        times = max_num_threads / tail;
        out_shape.emplace_back((head + times - 1) / times);
        out_shape.emplace_back(tail * times);
      }
    }
    first_axes.push_back(out_shape.size() - 2);

    int tail_count = 0;
    if (keep_dim) {
      second_axes = {static_cast<int>(out_shape.size()) - 1};
      if (out_shape.size() > A->shape.size()) {
        keep_dim_second = false;
      } else {
        keep_dim_second = true;
924
        tail_count = A->shape.size() - out_shape.size();
925 926 927 928 929
        for (int idx = 0; idx < tail_count; ++idx) {
          out_shape.push_back(Expr(1));
        }
      }
    } else {
930 931
      second_axes = {static_cast<int>(out_shape.size()) -
                     static_cast<int>(first_axes.size()) - 1};
932 933 934 935
    }

    int size_without_tail = out_shape.size() - tail_count;
    std::vector<int> tail_strides(A->shape.size() - (size_without_tail - 2), 1);
936 937 938
    for (int idx = static_cast<int>(tail_strides.size()) - 2,
             index = static_cast<int>(A->shape.size()) - 1;
         idx >= 0;
939 940 941 942 943 944
         --idx, --index) {
      tail_strides[idx] = tail_strides[idx + 1] * A->shape[index].as_int32();
    }
    auto out = Compute(
        out_shape,
        [=](const std::vector<Expr>& indexs) -> Expr {
945 946 947 948 949
          Expr index =
              indexs[size_without_tail - 1] +
              indexs[size_without_tail - 2] * out_shape[size_without_tail - 1];
          std::vector<Expr> tmp_indexs(indexs.begin(),
                                       indexs.begin() + size_without_tail - 2);
950 951 952 953 954 955 956
          // last and the second of last.
          auto selected = ir::LT::Make(index, Expr(lane));
          for (auto tail_stride : tail_strides) {
            tmp_indexs.push_back(index / Expr(tail_stride));
            index = index % Expr(tail_stride);
          }

957 958
          CHECK_EQ(tmp_indexs.size(), A->shape.size())
              << "Indexs size is not equal to Input shape!";
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
          if (check_bound) {
            return ir::Select::Make(selected, A(tmp_indexs), initial);
          } else {
            return A(tmp_indexs);
          }
        },
        UniqName(output_name + "_reshape"));
    return out;
  };
  std::vector<ir::Tensor> results;
  if (lane > max_num_threads) {
    VLOG(3) << "Do Reduce Reshape!";
    results.push_back(reduce_reshape_func());
  } else {
    if (!keep_dim) {
      for (auto& axis : second_axes) {
        axis -= first_axes.size();
      }
    }
  }
  if (first_axes.size()) {
    VLOG(3) << "Do Reduce Internal!";
981 982 983 984
    results.push_back(reduce_func(results.size() ? results.back() : A,
                                  first_axes,
                                  keep_dim_first,
                                  output_name + "_internal"));
985 986 987 988
    results.back()->WithBuffer("local");
  }
  if (second_axes.size()) {
    VLOG(3) << "Do Block Reduce!";
989 990 991 992
    auto res = block_reduce_func(results.size() ? results.back() : A,
                                 second_axes,
                                 keep_dim_second,
                                 output_name);
993 994 995 996 997 998 999 1000 1001 1002 1003
    results.push_back(res[1]);
    results.push_back(res[0]);
  }
  std::reverse(results.begin(), results.end());
  return results;
}

std::vector<ir::Tensor> TwoStepBlockReduceSum(const ir::Tensor& A,
                                              const std::vector<int>& axes,
                                              const bool keep_dim,
                                              const std::string& output_name) {
1004 1005 1006 1007 1008 1009 1010
  return TwoStepBlockReduceInternal(A,
                                    axes,
                                    keep_dim,
                                    output_name,
                                    ReduceSum,
                                    BlockReduceSumInternal,
                                    ir::Zero(A->type()));
1011 1012 1013 1014 1015 1016
}

std::vector<ir::Tensor> TwoStepBlockReduceProd(const ir::Tensor& A,
                                               const std::vector<int>& axes,
                                               const bool keep_dim,
                                               const std::string& output_name) {
1017 1018 1019 1020 1021 1022 1023
  return TwoStepBlockReduceInternal(A,
                                    axes,
                                    keep_dim,
                                    output_name,
                                    ReduceProd,
                                    BlockReduceProdInternal,
                                    lang::One(A->type()));
1024 1025 1026 1027 1028 1029
}

std::vector<ir::Tensor> TwoStepBlockReduceMax(const ir::Tensor& A,
                                              const std::vector<int>& axes,
                                              const bool keep_dim,
                                              const std::string& output_name) {
1030 1031 1032 1033 1034 1035 1036
  return TwoStepBlockReduceInternal(A,
                                    axes,
                                    keep_dim,
                                    output_name,
                                    ReduceMax,
                                    BlockReduceMaxInternal,
                                    lang::min_value(A->type()));
1037 1038 1039 1040 1041 1042
}

std::vector<ir::Tensor> TwoStepBlockReduceMin(const ir::Tensor& A,
                                              const std::vector<int>& axes,
                                              const bool keep_dim,
                                              const std::string& output_name) {
1043 1044 1045 1046 1047 1048 1049
  return TwoStepBlockReduceInternal(A,
                                    axes,
                                    keep_dim,
                                    output_name,
                                    ReduceMin,
                                    BlockReduceMinInternal,
                                    lang::max_value(A->type()));
1050 1051 1052 1053 1054 1055
}

std::vector<ir::Tensor> TwoStepBlockReduceAll(const ir::Tensor& A,
                                              const std::vector<int>& axes,
                                              const bool keep_dim,
                                              const std::string& output_name) {
1056 1057 1058 1059 1060 1061 1062
  return TwoStepBlockReduceInternal(A,
                                    axes,
                                    keep_dim,
                                    output_name,
                                    ReduceAll,
                                    BlockReduceAllInternal,
                                    Expr(true));
1063 1064 1065 1066 1067 1068
}

std::vector<ir::Tensor> TwoStepBlockReduceAny(const ir::Tensor& A,
                                              const std::vector<int>& axes,
                                              const bool keep_dim,
                                              const std::string& output_name) {
1069 1070 1071 1072 1073 1074 1075
  return TwoStepBlockReduceInternal(A,
                                    axes,
                                    keep_dim,
                                    output_name,
                                    ReduceAny,
                                    BlockReduceAnyInternal,
                                    Expr(false));
1076 1077 1078 1079 1080
}

}  // namespace pe
}  // namespace hlir
}  // namespace cinn