net_builder.cc 46.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
// 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/frontend/net_builder.h"

#include <string>
#include <utility>
#include <vector>

21
#include "glog/logging.h"
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
#include "paddle/cinn/frontend/syntax.h"
#include "paddle/cinn/hlir/pe/broadcast.h"
#include "paddle/cinn/runtime/flags.h"
#include "paddle/cinn/utils/functional.h"
#include "paddle/cinn/utils/profiler.h"

namespace cinn {
namespace frontend {

using common::Context;
using common::Type;
using hlir::framework::Operator;
using utils::AttributeMap;
using utils::ShapeType;

NetBuilder::NetBuilder(const std::string& name) : name_(name) {}

Program NetBuilder::Build(bool in_reverse) {
  utils::RecordEvent("NetBuilder::Build", utils::EventType::kProgram);
  std::vector<Instruction> instrs;
  if (in_reverse) {
    instrs.reserve(instrs_.size());
    for (auto it = instrs_.rbegin(); it != instrs_.rend(); it++) {
      instrs.emplace_back(*it);
    }
  } else {
    instrs = std::move(instrs_);
  }

  Program program{std::move(instrs), std::move(inputs_)};
  program.Validate();
  return program;
}

void NetBuilder::InferShape(Instruction instr) const {
57 58 59 60
  using ShapeFunc = std::function<std::vector<ShapeType>(
      const std::vector<ShapeType>&, const AttributeMap&)>;
  using TypeFunc = std::function<std::vector<Type>(const std::vector<Type>&,
                                                   const AttributeMap&)>;
61 62 63 64 65 66
  const auto& op_infershape = Operator::GetAttrs<ShapeFunc>("infershape");
  const auto& op_inferdtype = Operator::GetAttrs<TypeFunc>("inferdtype");

  size_t size = instr->inputs.size();
  std::vector<ShapeType> in_shapes(size);
  std::vector<Type> in_types(size);
67 68 69 70 71 72 73 74 75
  std::transform(instr->inputs.begin(),
                 instr->inputs.end(),
                 in_shapes.begin(),
                 [](const Variable& var) { return var->shape; });
  std::transform(instr->inputs.begin(),
                 instr->inputs.end(),
                 in_types.begin(),
                 [](const Variable& var) { return var->type; });
  auto key = Operator::Get(instr->op_type);
76
  auto out_shapes = op_infershape[key](in_shapes, instr->attrs);
77
  auto out_types = op_inferdtype[key](in_types, instr->attrs);
78

79
  auto& outs = instr->outputs;
80 81 82 83 84 85 86
  size_t origin_out_num = outs.size();
  outs.resize(out_shapes.size());
  for (size_t i = origin_out_num; i < outs.size(); i++) {
    outs[i] = Variable();
  }
  for (size_t i = 0; i < outs.size(); i++) {
    outs[i]->shape = out_shapes[i];
87
    outs[i]->type = out_types[i];
88 89 90
  }
}

91 92 93 94
const std::vector<Variable>& NetBuilder::CustomInstr(
    const std::string& type,
    const std::vector<Variable>& inputs,
    const AttributeMap& attrs) {
95 96 97 98 99 100 101 102 103 104
  Instruction instr(type, inputs);
  for (auto& kv : attrs) {
    instr.SetAttr(kv.first, kv.second);
  }
  utils::RecordEvent("NetBuilder." + type, utils::EventType::kProgram);
  InferShape(instr);
  AppendInstruction(instr);
  return instr.GetOutputs();
}

105 106 107 108 109 110
Variable NetBuilder::BinaryOp(const std::string& op_type,
                              const Variable& lhs,
                              const Variable& rhs,
                              int axis) {
  CHECK_EQ(lhs->type, rhs->type)
      << "The inputs type of op " << op_type << " should be equal!";
111 112 113
  return CustomInstr(op_type, {lhs, rhs}, {{"axis", axis}}).front();
}

114 115
Variable NetBuilder::UnaryOp(const std::string& op_type,
                             const Variable& operand) {
116 117 118
  return CustomInstr(op_type, {operand}, {}).front();
}

119 120 121 122
Variable NetBuilder::Reduce(const std::string& op_type,
                            const Variable& x,
                            const std::vector<int>& dim,
                            bool keep_dim) {
123
  // TODO(thisjiang): move the reduce simplify to frontend pass
124 125
  auto product = std::accumulate(
      x->shape.begin(), x->shape.end(), 1, std::multiplies<int>());
126 127 128 129
  if (product == 1) {
    if (keep_dim) {
      return Identity(x);
    } else {
130 131 132 133
      CHECK_GE(x->shape.size(), dim.size())
          << "The inputs rank should be greater than or equal to axes.";
      int new_rank =
          x->shape.size() == dim.size() ? 1 : x->shape.size() - dim.size();
134 135 136 137 138 139 140 141 142 143 144
      std::vector<int> new_shape(new_rank, 1);
      return Reshape(x, new_shape);
    }
  }
  // Convert the negative dim to a positive number
  std::vector<int> reduce_dim(dim.begin(), dim.end());
  for (int i = 0; i < dim.size(); i++) {
    if (reduce_dim[i] < 0) {
      reduce_dim[i] = x->shape.size() + reduce_dim[i];
    }
  }
145 146 147
  return CustomInstr(
             op_type, {x}, {{"dim", reduce_dim}, {"keep_dim", keep_dim}})
      .front();
148 149
}

150 151 152 153
#define NETBUILDER_UNARY_OP_DEF(func_name__, op_type__)       \
  Variable NetBuilder::func_name__(const Variable& operand) { \
    return UnaryOp(#op_type__, operand);                      \
  }
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 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
NETBUILDER_UNARY_OP_DEF(Sqrt, sqrt)
NETBUILDER_UNARY_OP_DEF(Tanh, tanh)
NETBUILDER_UNARY_OP_DEF(Relu, relu)
NETBUILDER_UNARY_OP_DEF(Gelu, gelu)
NETBUILDER_UNARY_OP_DEF(Sigmoid, sigmoid)
NETBUILDER_UNARY_OP_DEF(Identity, identity)
NETBUILDER_UNARY_OP_DEF(Exp, exp)
NETBUILDER_UNARY_OP_DEF(Erf, erf)
NETBUILDER_UNARY_OP_DEF(Rsqrt, rsqrt)
NETBUILDER_UNARY_OP_DEF(Log, log)
NETBUILDER_UNARY_OP_DEF(Log2, log2)
NETBUILDER_UNARY_OP_DEF(Log10, log10)
NETBUILDER_UNARY_OP_DEF(Floor, floor)
NETBUILDER_UNARY_OP_DEF(Ceil, ceil)
NETBUILDER_UNARY_OP_DEF(Round, round)
NETBUILDER_UNARY_OP_DEF(Trunc, trunc)
NETBUILDER_UNARY_OP_DEF(Sin, sin)
NETBUILDER_UNARY_OP_DEF(Cos, cos)
NETBUILDER_UNARY_OP_DEF(Tan, tan)
NETBUILDER_UNARY_OP_DEF(Sinh, sinh)
NETBUILDER_UNARY_OP_DEF(Cosh, cosh)
NETBUILDER_UNARY_OP_DEF(Asin, asin)
NETBUILDER_UNARY_OP_DEF(Acos, acos)
NETBUILDER_UNARY_OP_DEF(Atan, atan)
NETBUILDER_UNARY_OP_DEF(Asinh, asinh)
NETBUILDER_UNARY_OP_DEF(Acosh, acosh)
NETBUILDER_UNARY_OP_DEF(Atanh, atanh)
NETBUILDER_UNARY_OP_DEF(IsNan, isnan)
NETBUILDER_UNARY_OP_DEF(IsFinite, isfinite)
NETBUILDER_UNARY_OP_DEF(IsInf, isinf)
NETBUILDER_UNARY_OP_DEF(LogicalNot, logical_not)
NETBUILDER_UNARY_OP_DEF(BitwiseNot, bitwise_not)
NETBUILDER_UNARY_OP_DEF(Negative, negative)
NETBUILDER_UNARY_OP_DEF(Sign, sign)
NETBUILDER_UNARY_OP_DEF(Abs, abs)
NETBUILDER_UNARY_OP_DEF(Cbrt, cbrt)
NETBUILDER_UNARY_OP_DEF(Clz, clz)
NETBUILDER_UNARY_OP_DEF(Popc, popc)
NETBUILDER_UNARY_OP_DEF(Reciprocal, reciprocal)

#undef NETBUILDER_UNARY_OP_DEF

196 197 198 199
#define NETBUILDER_BINARY_OP_DEF(func_name__, op_type__)    \
  Variable NetBuilder::func_name__(                         \
      const Variable& lhs, const Variable& rhs, int axis) { \
    return BinaryOp(#op_type__, lhs, rhs, axis);            \
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
  }
NETBUILDER_BINARY_OP_DEF(Add, elementwise_add)
NETBUILDER_BINARY_OP_DEF(ElementwiseAdd, elementwise_add)
NETBUILDER_BINARY_OP_DEF(Atan2, atan2)
NETBUILDER_BINARY_OP_DEF(Multiply, elementwise_mul)
NETBUILDER_BINARY_OP_DEF(ElementwiseMul, elementwise_mul)
NETBUILDER_BINARY_OP_DEF(Divide, divide)
NETBUILDER_BINARY_OP_DEF(Subtract, subtract)
NETBUILDER_BINARY_OP_DEF(FloorDivide, floor_divide)
NETBUILDER_BINARY_OP_DEF(Mod, mod)
NETBUILDER_BINARY_OP_DEF(Remainder, remainder)
NETBUILDER_BINARY_OP_DEF(Max, max)
NETBUILDER_BINARY_OP_DEF(Min, min)
NETBUILDER_BINARY_OP_DEF(Pow, pow)
NETBUILDER_BINARY_OP_DEF(LogicalAnd, logical_and)
NETBUILDER_BINARY_OP_DEF(LogicalOr, logical_or)
NETBUILDER_BINARY_OP_DEF(LogicalXor, logical_xor)
NETBUILDER_BINARY_OP_DEF(BitwiseAnd, bitwise_and)
NETBUILDER_BINARY_OP_DEF(BitwiseOr, bitwise_or)
NETBUILDER_BINARY_OP_DEF(BitwiseXor, bitwise_xor)
NETBUILDER_BINARY_OP_DEF(LeftShift, left_shift)
NETBUILDER_BINARY_OP_DEF(RightShift, right_shift)
NETBUILDER_BINARY_OP_DEF(GreaterThan, greater_than);
NETBUILDER_BINARY_OP_DEF(LessThan, less_than);
NETBUILDER_BINARY_OP_DEF(Equal, equal);
NETBUILDER_BINARY_OP_DEF(NotEqual, not_equal);
NETBUILDER_BINARY_OP_DEF(GreaterEqual, greater_equal);
NETBUILDER_BINARY_OP_DEF(LessEqual, less_equal);
NETBUILDER_BINARY_OP_DEF(LogicalRightShift, logical_right_shift);

#undef NETBUILDER_BINARY_OP_DEF

232 233 234 235 236 237 238 239 240 241
#define NETBUILDER_REDUCE_OP_DEF(func_name__, op_type__)               \
  Variable NetBuilder::func_name__(                                    \
      const Variable& x, const std::vector<int>& dim, bool keep_dim) { \
    std::vector<int> axes = dim;                                       \
    if (axes.size() == 0) {                                            \
      for (int idx = 0; idx < x->shape.size(); ++idx) {                \
        axes.push_back(idx);                                           \
      }                                                                \
    }                                                                  \
    return Reduce(#op_type__, x, axes, keep_dim);                      \
242 243 244 245 246 247 248 249 250 251 252
  }

NETBUILDER_REDUCE_OP_DEF(ReduceSum, reduce_sum)
NETBUILDER_REDUCE_OP_DEF(ReduceProd, reduce_prod)
NETBUILDER_REDUCE_OP_DEF(ReduceMax, reduce_max)
NETBUILDER_REDUCE_OP_DEF(ReduceMin, reduce_min)
NETBUILDER_REDUCE_OP_DEF(ReduceAll, reduce_all)
NETBUILDER_REDUCE_OP_DEF(ReduceAny, reduce_any)

#undef NETBUILDER_REDUCE_OP_DEF

253 254 255
Placeholder NetBuilder::CreateInput(const Type& type,
                                    const std::vector<int>& shape,
                                    const std::string& id_hint) {
M
Minner Wang 已提交
256 257
  std::string id = id_hint.empty() ? Context::Global().NewName("placeholder")
                                   : cinn::utils::TransValidVarName(id_hint);
258
  inputs_.emplace_back(id);
259 260
  auto& var = inputs_.back();
  var->type = type;
261 262 263 264 265
  var->shape = shape;
  return Placeholder(var);
}

Placeholder NetBuilder::CreateInput(const Variable& var) {
266 267
  VLOG_IF(4, var->shape.empty())
      << "The input's shape is empty, Create 0D-Tensor for " << var->id;
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
  CHECK(!var->type.is_unk()) << "The input's type is not set yet";
  inputs_.push_back(var);
  return Placeholder(var);
}

Variable NetBuilder::FillConstant(const std::vector<int>& shape,
                                  const std::string& str_value,
                                  const std::string& name,
                                  const std::string& dtype,
                                  bool force_cpu) {
  const auto& type = common::Str2Type(dtype);

  utils::Attribute value;
  if (type.is_float()) {
    value = std::stod(str_value);
  } else if (type.is_int() || type.is_uint()) {
    value = static_cast<int64_t>(std::stoll(str_value));
  } else if (type.is_bool()) {
    value = !cinn::runtime::CheckStringFlagFalse(str_value);
  } else {
288 289
    LOG(FATAL) << "FillConstant only support int/float/bool, but here "
               << dtype;
290
  }
291 292 293 294 295 296 297
  auto out = CustomInstr("fill_constant",
                         {},
                         {{"shape", shape},
                          {"value", value},
                          {"dtype", dtype},
                          {"force_cpu", force_cpu}})
                 .front();
298 299 300 301 302 303
  if (!name.empty()) {
    out.set_id(cinn::utils::TransValidVarName(name));
  }
  return out;
}

304 305 306 307 308 309
std::vector<Variable> NetBuilder::Split(const Variable& operand,
                                        const std::vector<int>& num_or_sections,
                                        int axis) {
  return CustomInstr("split",
                     {operand},
                     {{"num_or_sections", num_or_sections}, {"axis", axis}});
310 311 312
}

Variable NetBuilder::Concat(const std::vector<Variable>& input_vars, int axis) {
313 314
  CHECK(!input_vars.empty())
      << "The inputs of concat op should not be empty! Please check.";
315 316 317
  return CustomInstr("concat", input_vars, {{"axis", axis}}).front();
}

318 319
Variable NetBuilder::BroadcastTo(const Variable& operand,
                                 const std::vector<int>& out_shape) {
320
  auto x_shape_size = operand->shape.size();
321 322 323 324 325
  if (x_shape_size == 0) {
    VLOG(4) << "0D-Tensor " << operand->id << " broadcast to shape ("
            << cinn::utils::Join(out_shape, ",") << ")";
    return BroadcastTo(operand, out_shape, {0});
  }
326
  auto y_shape_size = out_shape.size();
327 328 329 330 331 332 333 334
  CHECK_LE(x_shape_size, y_shape_size)
      << "The broadcast_p's input shape dimension should less than the "
         "output's, "
      << "but here (" << x_shape_size << " > " << y_shape_size << ").";

  VLOG(4) << "Try broadcast " << operand->id << " from shape ("
          << cinn::utils::Join(operand->shape, ",") << ") to shape ("
          << cinn::utils::Join(out_shape, ",") << ")";
335 336 337 338 339 340

  std::vector<int> broadcast_axes(x_shape_size, 0);
  if (x_shape_size > 1) {
    for (int i = 1; i <= x_shape_size; ++i) {
      CHECK((out_shape[y_shape_size - i] == operand->shape[x_shape_size - i]) ||
            (operand->shape[x_shape_size - i] == 1))
341 342
          << "We cannot broadcast from shape ("
          << cinn::utils::Join(operand->shape, ",") << ") to shape ("
343 344 345 346
          << cinn::utils::Join(out_shape, ",") << ")";
      broadcast_axes[x_shape_size - i] = y_shape_size - i;
    }
  } else {
347
    int axis = -1;
348 349 350 351 352
    auto x_shape = operand->shape.at(0);
    if (x_shape == 1) {
      // Can broadcast directly, default axis 0
      axis = 0;
    } else {
353 354
      // The broadcast axes is the index of the shape in out_shape when the
      // input dimension is 1
355 356 357 358 359 360
      for (int i = 0; i < y_shape_size; ++i) {
        if (out_shape[i] == x_shape) {
          axis = i;
          break;
        }
      }
361 362 363 364 365 366
      CHECK_NE(axis, -1) << "When we broadcast a 1-dimension shape, the number "
                            "should contained in the out_shape. "
                         << "We cannot broadcast from shape ("
                         << cinn::utils::Join(operand->shape, ",")
                         << ") to shape (" << cinn::utils::Join(out_shape, ",")
                         << ")";
367 368 369 370 371 372 373 374 375 376
    }
    broadcast_axes[0] = axis;
  }

  return BroadcastTo(operand, out_shape, broadcast_axes);
}

Variable NetBuilder::BroadcastTo(const Variable& operand,
                                 const std::vector<int>& out_shape,
                                 const std::vector<int>& broadcast_axes) {
377 378 379 380 381
  return CustomInstr(
             "broadcast_to",
             {operand},
             {{"out_shape", out_shape}, {"broadcast_axes", broadcast_axes}})
      .front();
382 383
}

384 385
Variable NetBuilder::Reshape(const Variable& operand,
                             const std::vector<int>& shape) {
386 387 388
  return CustomInstr("reshape", {operand}, {{"shape", shape}}).front();
}

389 390 391 392 393 394 395
Variable NetBuilder::Transpose(const Variable& operand,
                               const std::vector<int>& axis) {
  return CustomInstr(
             "transpose",
             {operand},
             {{"axis", utils::GetPositiveAxes(axis, operand->shape.size())}})
      .front();
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
}

Variable NetBuilder::Slice(const Variable& operand,
                           const std::vector<int>& axes,
                           const std::vector<int>& starts,
                           const std::vector<int>& ends,
                           const std::vector<int>& infer_flags,
                           const std::vector<int>& strides,
                           const std::vector<int>& decrease_axis) {
  return CustomInstr("slice",
                     {operand},
                     {{"axes", axes},
                      {"starts", starts},
                      {"ends", ends},
                      {"infer_flags", infer_flags},
                      {"strides", strides},
                      {"decrease_axis", decrease_axis}})
      .front();
}

Variable NetBuilder::SliceAssign(const Variable& input,
                                 const Variable& assign,
                                 const std::vector<int>& axes,
                                 const std::vector<int>& starts,
                                 const std::vector<int>& ends,
                                 const std::vector<int>& strides) {
  return CustomInstr("slice_assign",
                     {input, assign},
424 425 426 427
                     {{"axes", axes},
                      {"starts", starts},
                      {"ends", ends},
                      {"strides", strides}})
428 429 430
      .front();
}

431 432 433 434 435 436 437
Variable NetBuilder::Reverse(const Variable& operand,
                             const std::vector<int>& axis) {
  return CustomInstr(
             "reverse",
             {operand},
             {{"axis", utils::GetPositiveAxes(axis, operand->shape.size())}})
      .front();
438 439
}

440 441 442 443 444
Variable NetBuilder::Select(const Variable& condition,
                            const Variable& true_value,
                            const Variable& false_value) {
  return CustomInstr("select", {condition, true_value, false_value}, {})
      .front();
445 446
}

447 448 449
Variable NetBuilder::Gather(const Variable& operand,
                            const Variable& index,
                            int axis) {
450 451 452 453
  size_t x_ndim = operand->shape.size();
  if (axis < 0) {
    axis += static_cast<int>(x_ndim);
  }
454 455
  CHECK_LT(axis, x_ndim) << "Axis must be in [" << -x_ndim << ", " << x_ndim - 1
                         << ").";
456
  Variable transformed_index = index;
457 458
  // If we got 1-D Tensor, the first step is reshape, in order to keep
  // operand.rank == index.rank
459 460 461
  if (index->shape.size() == 1) {
    std::vector<int> index_reshape(x_ndim, 1);
    index_reshape[axis] = index->shape[0];
462
    transformed_index = Reshape(index, index_reshape);
463 464
  }
  // Then we need to broadcast transformed index
465
  auto broadcast_shape = operand->shape;
466
  broadcast_shape[axis] = transformed_index->shape[axis];
467 468 469
  transformed_index = BroadcastTo(transformed_index, broadcast_shape);
  return CustomInstr("gather", {operand, transformed_index}, {{"axis", axis}})
      .front();
470 471
}

472 473 474 475 476 477 478
Variable NetBuilder::ScatterAssign(const Variable& operand,
                                   const Variable& updates,
                                   const Variable& index,
                                   int axis) {
  return CustomInstr(
             "scatter_assign", {operand, updates, index}, {{"axis", axis}})
      .front();
479 480
}

481 482 483 484 485 486
Variable NetBuilder::ScatterAdd(const Variable& operand,
                                const Variable& updates,
                                const Variable& index,
                                int axis) {
  return CustomInstr("scatter_add", {operand, updates, index}, {{"axis", axis}})
      .front();
487 488
}

489 490 491 492 493 494 495 496 497
Variable NetBuilder::IsClose(const Variable& x,
                             const Variable& y,
                             float rtol,
                             float atol,
                             bool equal_nan) {
  return CustomInstr("isclose",
                     {x, y},
                     {{"rtol", rtol}, {"atol", atol}, {"equal_nan", equal_nan}})
      .front();
498 499
}

500 501 502 503 504
Variable NetBuilder::Mul(const Variable& a,
                         const Variable& b,
                         int x_num_col_dims,
                         int y_num_col_dims,
                         bool is_infer) {
505 506
  return CustomInstr("mul",
                     {a, b},
507 508 509
                     {{"x_num_col_dims", x_num_col_dims},
                      {"y_num_col_dims", y_num_col_dims},
                      {"is_infer", is_infer}})
510 511 512
      .front();
}

513 514
const std::vector<Variable>& NetBuilder::ElementwiseAddGrad(
    const Variable& dout, const Variable& x, const Variable& y, int axis) {
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
  return CustomInstr("elementwise_add_grad", {dout, x, y}, {{"axis", axis}});
}

Variable NetBuilder::Relu6(const Variable& a, float threshold) {
  return CustomInstr("relu6", {a}, {{"threshold", threshold}}).front();
}

Variable NetBuilder::ReluGrad(const Variable& lhs, const Variable& rhs) {
  return CustomInstr("relu_grad", {lhs, rhs}, {}).front();
}

Variable NetBuilder::GatherNd(const Variable& x, const Variable& index) {
  return CustomInstr("gather_nd", {x, index}, {}).front();
}

Variable NetBuilder::Cast(const Variable& operand, const std::string& dtype) {
  return CustomInstr("cast", {operand}, {{"dtype", dtype}}).front();
}

534 535
Variable NetBuilder::BitcastConvert(const Variable& operand,
                                    const std::string& dtype) {
536
  std::string input_data_type = common::Type2Str(operand->type);
537 538 539 540
  return CustomInstr("bitcast_convert",
                     {operand},
                     {{"dtype", dtype}, {"input_data_type", input_data_type}})
      .front();
541 542 543 544 545 546 547 548
}

Variable NetBuilder::OneHot(const Variable& indices,
                            const Variable& on_value,
                            const Variable& off_value,
                            const int depth,
                            const int axis,
                            const std::string& dtype) {
549 550 551
  return CustomInstr("one_hot",
                     {indices, on_value, off_value},
                     {{"depth", depth}, {"axis", axis}, {"dtype", dtype}})
552 553 554
      .front();
}

555 556
Variable NetBuilder::Squeeze(const Variable& operand,
                             const std::vector<int>& axes) {
557 558 559
  return CustomInstr("squeeze", {operand}, {{"axes", axes}}).front();
}

560 561
Variable NetBuilder::ExpandDims(const Variable& operand,
                                const cinn::utils::ShapeType& axes) {
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
  return CustomInstr("expand_dims", {operand}, {{"axes", axes}}).front();
}

Variable NetBuilder::Conv(const Variable& lhs,
                          const Variable& rhs,
                          const std::vector<int>& strides,
                          const std::vector<int>& paddings,
                          const std::vector<int>& dilations,
                          int groups,
                          const std::string& conv_type,
                          const std::string& data_format,
                          const std::string& padding_algorithm,
                          const std::vector<int>& output_shape) {
  return CustomInstr("conv2d",
                     {lhs, rhs},
                     {{"stride", strides},
                      {"padding", paddings},
                      {"dilation", dilations},
                      {"groups", groups},
                      {"conv_type", conv_type},
                      {"data_format", data_format},
                      {"padding_algorithm", padding_algorithm},
                      {"output_shape", output_shape}})
      .front();
}

588 589 590 591 592
std::vector<Variable> NetBuilder::ArgSort(const Variable& operand,
                                          const int& axis,
                                          const bool& is_ascend) {
  return CustomInstr(
      "argsort", {operand}, {{"axis", axis}, {"is_ascend", is_ascend}});
593 594
}

595 596 597 598 599 600
Variable NetBuilder::Sort(const Variable& operand,
                          const int& axis,
                          const bool& is_ascend) {
  return CustomInstr(
             "sort", {operand}, {{"axis", axis}, {"is_ascend", is_ascend}})
      .front();
601 602
}

603 604 605 606 607
Variable NetBuilder::Argmax(const Variable& x,
                            const int& axis,
                            const bool& keep_dim) {
  return CustomInstr("argmax", {x}, {{"axis", axis}, {"keep_dim", keep_dim}})
      .front();
608 609
}

610 611 612 613 614
Variable NetBuilder::Argmin(const Variable& x,
                            const int& axis,
                            const bool& keep_dim) {
  return CustomInstr("argmin", {x}, {{"axis", axis}, {"keep_dim", keep_dim}})
      .front();
615 616
}

617 618 619 620 621 622
Variable NetBuilder::LookupTable(const Variable& table,
                                 const Variable& ids,
                                 int64_t padding_idx) {
  return CustomInstr(
             "lookup_table", {table, ids}, {{"padding_idx", padding_idx}})
      .front();
623 624 625 626 627 628 629 630 631 632
}

Variable NetBuilder::Conv2d(const Variable& a,
                            const Variable& b,
                            const std::vector<int>& strides,
                            const std::vector<int>& paddings,
                            const std::vector<int>& dilations,
                            int groups,
                            const std::string& data_format,
                            const std::string& padding_algorithm) {
633 634 635 636 637 638 639 640 641 642
  return Conv(a,
              b,
              strides,
              paddings,
              dilations,
              groups,
              "forward",
              data_format,
              padding_algorithm,
              {});
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
}

Variable NetBuilder::DepthwiseConv2d(const Variable& a,
                                     const Variable& b,
                                     const std::vector<int>& strides,
                                     const std::vector<int>& paddings,
                                     const std::vector<int>& dilations,
                                     int groups,
                                     const std::string& data_format,
                                     const std::string& padding_algorithm) {
  return CustomInstr("depthwise_conv2d",
                     {a, b},
                     {{"stride", strides},
                      {"padding", paddings},
                      {"dilation", dilations},
                      {"groups", groups},
                      {"data_format", data_format},
                      {"padding_algorithm", padding_algorithm}})
      .front();
}

std::vector<int> UpdatePool2dKernelSize(const std::vector<int>& x_shape,
                                        const std::vector<int>& ksize,
                                        const bool global_pooling,
                                        const std::string& data_format) {
  std::vector<int> new_ksize{ksize};
  // Setting h/w_axis according to data_format
  int height_axis = -1;
671
  int width_axis = -1;
672 673
  if (data_format == "NCHW") {
    height_axis = 2;
674
    width_axis = 3;
675 676
  } else if (data_format == "NHWC") {
    height_axis = 1;
677
    width_axis = 2;
678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
  } else {
    LOG(FATAL) << "Unsupport data_format: " << data_format;
  }
  if (global_pooling) {
    new_ksize[0] = x_shape[height_axis];
    new_ksize[1] = x_shape[width_axis];
  }
  return new_ksize;
}

std::vector<int> UpdatePool2dPaddings(const std::vector<int>& paddings,
                                      const std::vector<int>& x_shape,
                                      const std::vector<int>& ksize,
                                      const std::vector<int>& stride,
                                      const bool global_pooling,
                                      const bool adaptive,
                                      const std::string& padding_algorithm,
                                      const std::string& data_format) {
  std::vector<int> new_paddings{paddings};
  if (paddings.size() == 2) {
    new_paddings.insert(new_paddings.end(), paddings.begin(), paddings.end());
  }
700 701
  CHECK_EQ(new_paddings.size(), 4)
      << "Padding size must be 2 or 4, but got: " << paddings.size();
702 703
  // Setting h/w_axis according to data_format
  int height_axis = -1;
704
  int width_axis = -1;
705 706
  if (data_format == "NCHW") {
    height_axis = 2;
707
    width_axis = 3;
708 709
  } else if (data_format == "NHWC") {
    height_axis = 1;
710
    width_axis = 2;
711 712 713 714
  } else {
    LOG(FATAL) << "Unsupport data_format: " << data_format;
  }
  // When padding_algorithm is VALID, set paddings to [0, 0, 0, 0].
715 716 717 718 719
  // When padding_algorithm is SAME, the calculation formula of padding is as
  // follows: output_h/w = ceil(input_h/w / stride_h/w) padding_sum_h/w =
  // (output_h/w - 1) * stride_h/w + kernel_h/w - input_h/w padding_top/left =
  // padding_sum_h/w / 2; padding_bottom/right = padding_sum_h/w -
  // padding_top/left
720 721 722 723 724
  if (padding_algorithm == "VALID") {
    new_paddings = {0, 0, 0, 0};
  } else if (padding_algorithm == "SAME") {
    int out_size_h = (x_shape[height_axis] + stride[0] - 1) / stride[0];
    int out_size_w = (x_shape[width_axis] + stride[1] - 1) / stride[1];
725 726 727 728 729
    int pad_sum_h = std::max(
        (out_size_h - 1) * stride[0] + ksize[0] - x_shape[height_axis], 0);
    int pad_sum_w = std::max(
        (out_size_w - 1) * stride[1] + ksize[1] - x_shape[width_axis], 0);
    int pad_top = pad_sum_h / 2;
730
    int pad_bottom = pad_sum_h - pad_top;
731 732 733
    int pad_left = pad_sum_w / 2;
    int pad_right = pad_sum_w - pad_left;
    new_paddings = {pad_top, pad_left, pad_bottom, pad_right};
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
  }
  // When global_pooling or adaptive is true, set paddings to [0, 0, 0, 0].
  if (global_pooling || adaptive) {
    new_paddings = {0, 0, 0, 0};
  }
  return new_paddings;
}

Variable NetBuilder::Pool2d(const Variable& a,
                            const std::string& pooling_type,
                            const std::vector<int>& ksize,
                            const std::vector<int>& strides,
                            const std::vector<int>& paddings,
                            bool ceil_mode,
                            bool exclusive,
                            bool global_pooling,
                            const std::string& data_format,
                            bool adaptive,
                            const std::string& padding_algorithm) {
  // Check input dim
754 755 756
  CHECK_EQ(a->shape.size(), 4)
      << "Input's dim must be 4, but " << a->id << "'s shape is ["
      << cinn::utils::Join(a->shape, ", ") << "].";
757 758
  // Transform pool_type
  std::string pool_type;
759 760 761 762 763 764
  std::transform(pooling_type.begin(),
                 pooling_type.end(),
                 std::back_inserter(pool_type),
                 [](unsigned char c) { return std::tolower(c); });
  CHECK(pool_type == "avg" || pool_type == "max")
      << "Pool_type must be avg or max, but got: " << pool_type;
765 766 767 768 769
  // Transform ksize
  std::vector<int> input_ksize{ksize};
  if (input_ksize.size() == 1) {
    input_ksize.insert(input_ksize.end(), ksize.begin(), ksize.end());
  }
770 771
  CHECK_EQ(input_ksize.size(), 2)
      << "Kernel_size length must be 1 or 2, but got: " << ksize.size();
772 773 774 775 776
  // Transform stride
  std::vector<int> new_strides{strides};
  if (new_strides.size() == 1) {
    new_strides.insert(new_strides.end(), strides.begin(), strides.end());
  }
777 778 779 780
  CHECK_EQ(new_strides.size(), 2)
      << "Stride length must be 1 or 2, but got: " << strides.size();
  CHECK(new_strides[0] > 0 && new_strides[1] > 0)
      << "the value of kernel size for pool2d should greater than 0.";
781 782 783 784 785 786 787 788
  // Transform data_format
  std::string new_data_format{data_format};
  if (new_data_format == "AnyLayout") {
    new_data_format.assign("NCHW");
  }
  CHECK(new_data_format == "NCHW" || new_data_format == "NHWC")
      << "Data_format must be AnyLayout/NCHW/NHWC, but got: " << data_format;
  // Check padding_algorithm
789 790 791 792
  CHECK(padding_algorithm == "EXPLICIT" || padding_algorithm == "SAME" ||
        padding_algorithm == "VALID")
      << "Padding_algorithm must be EXPLICIT/SAME/VALID, but got: "
      << padding_algorithm;
793 794 795 796 797 798 799 800 801 802
  utils::AttributeMap attrs = {{"pool_type", pool_type},
                               {"origin_kernel_size", input_ksize},
                               {"stride_size", new_strides},
                               {"origin_padding_size", paddings},
                               {"ceil_mode", ceil_mode},
                               {"exclusive", exclusive},
                               {"origin_global_pooling", global_pooling},
                               {"data_format", new_data_format},
                               {"origin_adaptive", adaptive},
                               {"padding_algorithm", padding_algorithm}};
803 804 805 806 807 808
  // In avg_pool2d, if global_pooling = false, adaptive = true and ksize is [1,
  // 1], we turn off adaptive and use global pooling instead
  if (pooling_type == "avg" && !global_pooling && adaptive &&
      input_ksize[0] == 1 && input_ksize[1] == 1) {
    VLOG(4) << "In avg_pool2d, got global_pooling = false, adaptive = true, "
               "ksize = [1, 1], turn off adaptive and "
809
               "trans to global_pooling";
810
    adaptive = false;
811 812 813
    global_pooling = true;
  }
  // Transform paddings
814 815 816 817 818 819 820 821
  auto new_paddings = UpdatePool2dPaddings(paddings,
                                           a->shape,
                                           input_ksize,
                                           new_strides,
                                           global_pooling,
                                           adaptive,
                                           padding_algorithm,
                                           new_data_format);
822
  // Update kernel_size
823 824 825 826 827
  auto new_ksize = UpdatePool2dKernelSize(
      a->shape, input_ksize, global_pooling, new_data_format);
  attrs["kernel_size"] = new_ksize;
  attrs["padding_size"] = new_paddings;
  attrs["adaptive"] = adaptive;
828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
  attrs["global_pooling"] = global_pooling;
  return CustomInstr("pool2d", {a}, attrs).front();
}

Variable NetBuilder::Pool2dGrad(const Variable& x,
                                const Variable& y,
                                const Variable& dy,
                                const std::string& pooling_type,
                                const std::vector<int>& ksize,
                                const std::vector<int>& strides,
                                const std::vector<int>& paddings,
                                bool ceil_mode,
                                bool exclusive,
                                bool global_pooling,
                                const std::string& data_format,
                                bool adaptive,
                                const std::string& padding_algorithm) {
  // Transform pool_type
  std::string pool_type;
847 848 849 850 851 852
  std::transform(pooling_type.begin(),
                 pooling_type.end(),
                 std::back_inserter(pool_type),
                 [](unsigned char c) { return std::tolower(c); });
  CHECK(pool_type == "avg" || pool_type == "max")
      << "Pool_type must be avg or max, but got: " << pool_type;
853 854 855 856 857
  // Transform ksize
  std::vector<int> input_ksize{ksize};
  if (input_ksize.size() == 1) {
    input_ksize.insert(input_ksize.end(), ksize.begin(), ksize.end());
  }
858 859
  CHECK_EQ(input_ksize.size(), 2)
      << "Kernel_size length must be 1 or 2, but got: " << ksize.size();
860 861 862 863 864
  // Transform stride
  std::vector<int> new_strides{strides};
  if (new_strides.size() == 1) {
    new_strides.insert(new_strides.end(), strides.begin(), strides.end());
  }
865 866 867 868
  CHECK_EQ(new_strides.size(), 2)
      << "Stride length must be 1 or 2, but got: " << strides.size();
  CHECK(new_strides[0] > 0 && new_strides[1] > 0)
      << "the value of kernel size for pool2d should greater than 0.";
869 870 871 872 873 874 875 876
  // Transform data_format
  std::string new_data_format{data_format};
  if (new_data_format == "AnyLayout") {
    new_data_format.assign("NCHW");
  }
  CHECK(new_data_format == "NCHW" || new_data_format == "NHWC")
      << "Data_format must be AnyLayout/NCHW/NHWC, but got: " << data_format;
  // Check padding_algorithm
877 878 879 880 881 882 883 884 885 886
  CHECK(padding_algorithm == "EXPLICIT" || padding_algorithm == "SAME" ||
        padding_algorithm == "VALID")
      << "Padding_algorithm must be EXPLICIT/SAME/VALID, but got: "
      << padding_algorithm;
  // In avg_pool2d, if global_pooling = false, adaptive = true and ksize is [1,
  // 1], we turn off adaptive and use global pooling instead
  if (pooling_type == "avg" && !global_pooling && adaptive &&
      input_ksize[0] == 1 && input_ksize[1] == 1) {
    VLOG(4) << "In avg_pool2d, got global_pooling = false, adaptive = true, "
               "ksize = [1, 1], turn off adaptive and "
887
               "trans to global_pooling";
888
    adaptive = false;
889 890 891
    global_pooling = true;
  }
  // Transform paddings
892 893 894 895 896 897 898 899
  auto new_paddings = UpdatePool2dPaddings(paddings,
                                           x->shape,
                                           input_ksize,
                                           new_strides,
                                           global_pooling,
                                           adaptive,
                                           padding_algorithm,
                                           new_data_format);
900
  // Update kernel_size
901 902
  auto new_ksize = UpdatePool2dKernelSize(
      x->shape, input_ksize, global_pooling, new_data_format);
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
  return CustomInstr("pool2d_grad",
                     {x, y, dy},
                     {{"pool_type", pool_type},
                      {"kernel_size", new_ksize},
                      {"stride_size", new_strides},
                      {"padding_size", new_paddings},
                      {"ceil_mode", ceil_mode},
                      {"exclusive", exclusive},
                      {"global_pooling", global_pooling},
                      {"data_format", new_data_format},
                      {"adaptive", adaptive},
                      {"padding_algorithm", padding_algorithm}})
      .front();
}

Variable NetBuilder::Repeat(const Variable& x, int repeats, int axis) {
919 920
  return CustomInstr("repeat", {x}, {{"repeats", repeats}, {"axis", axis}})
      .front();
921 922
}

923 924 925 926 927
Variable NetBuilder::Resize(const Variable& x,
                            const std::vector<int>& out_shape,
                            const std::string& mode) {
  return CustomInstr("resize", {x}, {{"out_shape", out_shape}, {"mode", mode}})
      .front();
928 929 930 931 932 933 934 935 936 937 938 939 940 941
}

std::vector<Variable> NetBuilder::BatchNorm(const Variable& a,
                                            const Variable& scale,
                                            const Variable& bias,
                                            const Variable& mean,
                                            const Variable& variance,
                                            float epsilon,
                                            float momentum,
                                            const std::string& data_layout,
                                            bool is_test) {
  std::string op_type = is_test ? "batch_norm" : "batch_norm_train";
  return CustomInstr(op_type,
                     {a, scale, bias, mean, variance},
942 943 944
                     {{"epsilon", epsilon},
                      {"momentum", momentum},
                      {"data_layout", data_layout}});
945 946 947
}

// batch norm grad, output(grad_x, grad_scale, grad_bias)
948 949 950 951 952 953 954 955
std::vector<Variable> NetBuilder::BatchNormGrad(
    const Variable& dy,
    const Variable& x,
    const Variable& scale,
    const Variable& save_mean,
    const Variable& save_variance,
    const float epsilon,
    const std::string& data_layout) {
956 957 958 959 960
  return CustomInstr("batch_norm_grad",
                     {dy, x, scale, save_mean, save_variance},
                     {{"epsilon", epsilon}, {"data_layout", data_layout}});
}

961 962 963 964 965 966 967 968 969 970
Variable NetBuilder::Scale(const Variable& a,
                           float scale,
                           float bias,
                           bool bias_after_scale) {
  return CustomInstr("scale",
                     {a},
                     {{"scale", scale},
                      {"bias", bias},
                      {"bias_after_scale", bias_after_scale}})
      .front();
971 972 973 974 975 976
}

Variable NetBuilder::Softmax(const Variable& a,
                             const std::vector<int>& axes,
                             const std::string& mode,
                             const std::string& data_format) {
977 978 979 980 981
  return CustomInstr(
             "softmax",
             {a},
             {{"axes", axes}, {"mode", mode}, {"data_format", data_format}})
      .front();
982 983
}

984 985 986 987 988 989 990
Variable NetBuilder::DropoutInfer(const Variable& a,
                                  float dropout_prob,
                                  const std::string& dropout_implementation) {
  return CustomInstr("dropout_infer",
                     {a},
                     {{"dropout_prob", dropout_prob},
                      {"dropout_implementation", dropout_implementation}})
991 992 993 994 995 996 997
      .front();
}

Variable NetBuilder::Sum(const std::vector<Variable>& inputs) {
  return CustomInstr("sum", inputs, {}).front();
}

998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
Variable NetBuilder::Arange(const float start,
                            const float stop,
                            const float step,
                            const std::string& dtype) {
  return CustomInstr("arange",
                     {},
                     {{"start", start},
                      {"stop", stop},
                      {"step", step},
                      {"dtype", dtype}})
      .front();
1009 1010
}

1011 1012 1013 1014 1015 1016 1017
Variable NetBuilder::Flip(const Variable& operand,
                          const std::vector<int>& axes) {
  return CustomInstr(
             "reverse",
             {operand},
             {{"axis", utils::GetPositiveAxes(axes, operand->shape.size())}})
      .front();
1018 1019
}

1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
Variable NetBuilder::Matmul(const Variable& x,
                            const Variable& y,
                            bool trans_x,
                            bool trans_y,
                            float alpha) {
  return CustomInstr(
             "matmul",
             {x, y},
             {{"trans_a", trans_x}, {"trans_b", trans_y}, {"alpha", alpha}})
      .front();
1030 1031
}

1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
Variable NetBuilder::GaussianRandom(const std::vector<int>& shape,
                                    float mean,
                                    float std,
                                    int seed,
                                    const std::string& dtype) {
  return CustomInstr("gaussian_random",
                     {},
                     {{"shape", shape},
                      {"mean", mean},
                      {"std", std},
                      {"seed", seed},
                      {"dtype", dtype}})
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
      .front();
}

Variable NetBuilder::UniformRandom(const std::vector<int>& shape,
                                   float min,
                                   float max,
                                   int seed,
                                   const std::string& dtype,
                                   int diag_num,
                                   int diag_step,
                                   float diag_val) {
1055 1056 1057 1058 1059 1060 1061 1062
  auto uniform_out = CustomInstr("uniform_random",
                                 {},
                                 {{"shape", shape},
                                  {"min", min},
                                  {"max", max},
                                  {"seed", seed},
                                  {"dtype", dtype}})
                         .front();
1063 1064 1065
  if (min == 0.0f && max == 1.0f) {
    return uniform_out;
  }
1066 1067
  auto uniform_range =
      FillConstant(shape, max - min, UniqName("uniform_range"), dtype);
1068
  auto uniform_mul_out = Multiply(uniform_out, uniform_range);
1069 1070
  auto uniform_min = FillConstant(shape, min, UniqName("uniform_min"), dtype);
  auto uniform_res = Add(uniform_mul_out, uniform_min);
1071
  if (diag_num > 0) {
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
    int numel =
        std::accumulate(shape.begin(), shape.end(), 1, std::multiplies<int>());
    CHECK_GT(numel, (diag_num - 1) * (diag_step + 1))
        << "(diag_num - 1) * (diag_step + 1) should smaller than numel!";
    auto diag_index = Arange(0.0f,
                             static_cast<float>(diag_num * (diag_step + 1)),
                             static_cast<float>(diag_step + 1),
                             "int32");
    auto diag_val_tensor =
        FillConstant(diag_index->shape, diag_val, "diag_val", dtype);
1082
    auto uniform_flatten = Reshape(uniform_res, {-1});
1083 1084 1085
    auto uniform_scatter =
        ScatterAssign(uniform_flatten, diag_val_tensor, diag_index);
    uniform_res = Reshape(uniform_scatter, shape);
1086 1087 1088 1089
  }
  return uniform_res;
}

1090 1091 1092 1093 1094
Variable NetBuilder::RandInt(const std::vector<int>& shape,
                             int min,
                             int max,
                             int seed,
                             const std::string& dtype) {
1095 1096
  CHECK_GT(max, min) << "max: " << max << "should greater than"
                     << "min: " << min;
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
  auto randint_out =
      CustomInstr(
          "randint", {}, {{"shape", shape}, {"seed", seed}, {"dtype", dtype}})
          .front();
  randint_out = Cast(randint_out, dtype);
  auto randint_range =
      FillConstant(shape, max - min, UniqName("randint_range"), dtype);
  auto randint_mod = Mod(randint_out, randint_range);
  auto randint_min = FillConstant(shape, min, UniqName("randint_min"), dtype);
  auto randint_ret = Add(randint_mod, randint_min);
1107 1108 1109 1110 1111 1112 1113
  return randint_ret;
}

Variable NetBuilder::Cholesky(const Variable& x, bool upper) {
  auto cholesky_out = CustomInstr("cholesky", {x}, {{"upper", upper}}).front();
  // Set upper/lower triangle of matrices to 0
  auto x_ndim = x->shape.size();
1114 1115
  CHECK_GE(x_ndim, 2)
      << "The input matrix x shape size should >= 2! Please check again.";
1116
  CHECK_EQ(x->shape[x_ndim - 1], x->shape[x_ndim - 2])
1117 1118 1119 1120 1121
      << "The input matrix x's last 2 dimensions must be the same! Please "
         "check again.";
  int m = x->shape[x_ndim - 1];
  auto m_tensor = FillConstant({m * m}, m);
  auto index = Arange(0.0f, static_cast<float>(m * m), 1.0f, "int32");
1122 1123
  auto index_row = Mod(index, m_tensor);
  auto index_col = FloorDivide(index, m_tensor);
1124 1125 1126
  auto mask = upper ? GreaterEqual(index_row, index_col)
                    : LessEqual(index_row, index_col);
  auto mask_mat = Reshape(mask, {m, m});
1127
  auto mask_full = BroadcastTo(mask_mat, x->shape);
1128 1129
  auto zeros = FillConstant(x->shape, 0.0f, "zeros", common::Type2Str(x->type));
  auto out = Select(mask_full, cholesky_out, zeros);
1130 1131 1132
  return out;
}

1133 1134 1135 1136 1137 1138
Variable NetBuilder::TriangularSolve(const Variable& input1,
                                     const Variable& input2,
                                     bool left_side,
                                     bool upper,
                                     bool transpose_a,
                                     bool unit_diagonal) {
1139 1140 1141 1142 1143
  // broadcast
  std::vector<Variable> inputs{input1, input2};
  {
    auto a_ndim = input1->shape.size();
    auto b_ndim = input2->shape.size();
1144 1145 1146 1147 1148 1149 1150 1151
    CHECK_GE(a_ndim, 2)
        << "The input matrix A shape size should >= 2! Please check again.";
    CHECK_GE(b_ndim, 2)
        << "The input matrix B shape size should >= 2! Please check again.";
    std::vector<int> input1_shape_cut(input1->shape.begin(),
                                      input1->shape.end() - 2);
    std::vector<int> input2_shape_cut(input2->shape.begin(),
                                      input2->shape.end() - 2);
1152
    std::vector<int> common_shape;
1153 1154
    hlir::pe::GetBroadcastOutShape(
        input1_shape_cut, input2_shape_cut, &common_shape);
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177

    // broadcast input1
    std::vector<int> input1_shape(common_shape.begin(), common_shape.end());
    input1_shape.push_back(input1->shape[a_ndim - 2]);
    input1_shape.push_back(input1->shape[a_ndim - 1]);
    inputs[0] = BroadcastTo(input1, input1_shape);

    // broadcast input2
    std::vector<int> input2_shape(common_shape.begin(), common_shape.end());
    input2_shape.push_back(input2->shape[b_ndim - 2]);
    input2_shape.push_back(input2->shape[b_ndim - 1]);
    inputs[1] = BroadcastTo(input2, input2_shape);
  }

  return CustomInstr("triangular_solve",
                     inputs,
                     {{"left_side", left_side},
                      {"upper", upper},
                      {"transpose_a", transpose_a},
                      {"unit_diagonal", unit_diagonal}})
      .front();
}

1178 1179 1180 1181 1182 1183
std::vector<Variable> NetBuilder::TopK(const Variable& x,
                                       int k,
                                       int axis,
                                       bool largest) {
  return CustomInstr(
      "top_k", {x}, {{"k", k}, {"axis", axis}, {"largest", largest}});
1184 1185 1186 1187
}

}  // namespace frontend
}  // namespace cinn