op_translator.cc 17.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "paddle/fluid/translator/op_translator.h"

#include <algorithm>
18
#include <cctype>
19 20 21 22 23 24
#include <numeric>
#include <string>
#include <tuple>
#include <unordered_map>
#include <vector>

25
#include "paddle/fluid/dialect/pd_interface.h"
26
#include "paddle/fluid/framework/op_desc.h"
27
#include "paddle/fluid/translator/attribute_translator.h"
28
#include "paddle/fluid/translator/op_compat_info.h"
29 30
#include "paddle/fluid/translator/program_translator.h"
#include "paddle/fluid/translator/type_translator.h"
31 32 33
#include "paddle/ir/core/builtin_op.h"
#include "paddle/ir/core/builtin_type.h"
#include "paddle/ir/core/ir_context.h"
34
#include "paddle/ir/core/operation.h"
35
#include "paddle/ir/core/value.h"
36 37 38 39 40 41 42 43 44 45 46 47 48
#include "paddle/phi/core/enforce.h"

namespace paddle {
namespace translator {

namespace {

using ResultIdx = size_t;
using OpDesc = paddle::framework::OpDesc;
using BlockDesc = paddle::framework::BlockDesc;
using VarDesc = paddle::framework::VarDesc;
using OpOutputTypeList = std::vector<ir::Type>;
using OpOutputMapping = std::unordered_map<std::string, ResultIdx>;
49 50 51 52 53 54
using OpInputInfo = paddle::dialect::OpInputInfo;
using OpInputInfoList = std::vector<paddle::dialect::OpInputInfo>;
using OpAttributeInfo = paddle::dialect::OpAttributeInfo;
using OpAttributeInfoList = std::vector<paddle::dialect::OpAttributeInfo>;
using OpOutputInfo = paddle::dialect::OpOutputInfo;
using OpOutputInfoList = std::vector<paddle::dialect::OpOutputInfo>;
55 56 57

static const char kTargetDialectPrefix[] = "pd.";

58 59 60 61
static const std::unordered_set<std::string> special_inplace_ops = {
    "batch_norm",
};

62 63
inline bool IsInplace(const OpDesc& op_desc) {
  bool inplace = false;
64 65 66
  if (special_inplace_ops.count(op_desc.Type())) {
    return inplace;
  }
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
  auto input_names = op_desc.InputArgumentNames();
  auto output_names = op_desc.OutputArgumentNames();

  std::vector<std::string> name_intersection;
  std::set_intersection(input_names.begin(),
                        input_names.end(),
                        output_names.begin(),
                        output_names.end(),
                        std::back_inserter(name_intersection));

  if (name_intersection.size() > 0) {
    std::string redundant_variables = std::accumulate(
        std::next(name_intersection.begin()),
        name_intersection.end(),
        name_intersection[0],
        [](std::string a, std::string b) { return a + "," + b; });
    VLOG(4) << "Following variables occur both in inputs and outputs: "
            << redundant_variables;
    return true;
  }

  return inplace;
}

91 92 93 94 95
inline std::string OpNamecompatibleMapping(std::string op_name) {
  auto& op_normalizer = OpNameNormalizer::instance();
  return op_normalizer[op_name];
}

96
inline ir::OpInfo LoopkUpOpInfo(ir::IrContext* ctx, const OpDesc& op_desc) {
97 98
  std::string target_op_name =
      kTargetDialectPrefix + OpNamecompatibleMapping(op_desc.Type());
99 100 101
  if (IsInplace(op_desc)) {
    target_op_name += "_";
  }
102 103
  VLOG(6) << "[op name normalizing: " << op_desc.Type() << " to "
          << target_op_name;
104 105 106 107 108 109 110 111 112 113 114
  auto op_info = ctx->GetRegisteredOpInfo(target_op_name);
  if (!op_info) {
    PADDLE_THROW(platform::errors::PreconditionNotMet(
        "Op %d should have corresponding OpInfo %d",
        op_desc.Type(),
        target_op_name));
  }

  return op_info;
}

115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
inline ir::Operation* InsertSliceOperationForTarget(
    ir::IrContext* ctx,
    TranslationContext* param_map,
    ir::Program* program,
    const VariableDefiningInfo& defining_info,
    const std::string& arg_name) {
  std::string slice_op_name(ir::SliceOp::name());
  ir::OpInfo op_info = ctx->GetRegisteredOpInfo(slice_op_name);
  std::unordered_map<std::string, ir::Attribute> op_attribute_map = {
      {"index", ir::Int32_tAttribute::get(ctx, defining_info.idx_in_vector)},
  };
  ir::VectorType src_vec_type =
      defining_info.value.type().dyn_cast<ir::VectorType>();
  ir::Operation* operation =
      ir::Operation::create({defining_info.value},
                            op_attribute_map,
131
                            {src_vec_type[defining_info.idx_in_vector]},
132
                            op_info);
133
  program->block()->push_back(operation);
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
  ir::OpResult target_op_result = operation->GetResultByIndex(0);
  (*param_map)[arg_name] = VariableDefiningInfo(target_op_result);
  return operation;
}

inline ir::Operation* InsertCombineOperationForTarget(
    ir::IrContext* ctx,
    TranslationContext* param_map,
    ir::Program* program,
    const std::vector<std::string>& args) {
  std::string combine_op_name(ir::CombineOp::name());
  ir::OpInfo op_info = ctx->GetRegisteredOpInfo(combine_op_name);

  std::vector<ir::OpResult> src_values;
  std::vector<ir::Type> types_in_vec;
149
  for (const auto& arg_name : args) {
150 151 152 153 154 155
    auto defining_info = param_map->at(arg_name);
    src_values.push_back(defining_info.value);
    types_in_vec.push_back(defining_info.value.type());
  }
  ir::Type target_vec_type = ir::VectorType::get(ctx, types_in_vec);
  ir::Operation* operation =
156
      ir::Operation::create(src_values, {}, {target_vec_type}, op_info);
157
  program->block()->push_back(operation);
158 159 160
  return operation;
}

161 162 163 164 165 166 167 168 169 170 171 172
inline ir::Operation* InsertConstantOperationForOptionalArg(
    ir::IrContext* ctx, ir::Program* program) {
  std::string constant_op_name(ir::ConstantOp::name());
  ir::OpInfo op_info = ctx->GetRegisteredOpInfo(constant_op_name);

  ir::Type null_type = ir::Type(nullptr);
  ir::Operation* operation =
      ir::Operation::create({}, {}, {null_type}, op_info);
  program->block()->push_back(operation);
  return operation;
}

173
inline std::vector<ir::OpResult> GenerateOperationInput(
174 175 176
    ir::IrContext* ctx,
    TranslationContext* param_map,
    ir::Program* program,
177 178 179
    const OpDesc& op_desc,
    const std::string& normalized_op_name,
    const OpInputInfoList& input_infos) {
180 181
  // scan all inputs to see if any of them is generated as a vector<Tensor>
  // so need an additional `SliceOp` to take it out.
182 183 184
  for (const auto& n : op_desc.Inputs()) {
    auto& name = n.first;
    auto& args = n.second;
185

186 187 188 189 190
    for (const auto& arg_name : args) {
      PADDLE_ENFORCE_NE(
          param_map->count(arg_name),
          0,
          platform::errors::PreconditionNotMet(
191
              "arg %s.%s as input should be exists before prasing %s",
192
              name,
193 194
              arg_name,
              op_desc.Type()));
195 196 197 198 199 200 201 202
      auto defining_info = (*param_map)[arg_name];
      if (defining_info.generated_by_vector) {
        InsertSliceOperationForTarget(
            ctx, param_map, program, defining_info, arg_name);
      }
    }
  }

203 204
  std::vector<ir::OpResult> op_inputs;
  auto& op_normalizer = OpNameNormalizer::instance();
205

206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
  for (const auto& info : input_infos) {
    std::string legacy_input_name =
        op_normalizer.GetLegacyArgName(op_desc.Type(), info.name);

    // return empty OpResult if this arg is optional and not shown in OpDesc
    // TODO(lyk): HasInput doesnot consider variadic attribute
    if (!op_desc.HasInput(legacy_input_name)) {
      PADDLE_ENFORCE(info.optional,
                     platform::errors::PreconditionNotMet(
                         "Op %s arg %s should be optional if it can be empty",
                         op_desc.Type(),
                         legacy_input_name));
      op_inputs.push_back(ir::OpResult(nullptr));
      continue;
    }

    const auto& legacy_input_vars = op_desc.Input(legacy_input_name, true);
    bool is_vector = (info.type_name.find("VectorType") != std::string::npos);

    // if src type is Tensor
    if (!is_vector) {
      auto defining_info = (*param_map)[legacy_input_vars[0]];
      op_inputs.push_back(defining_info.value);
229 230 231 232

      // if src type is Vector<Tesnor> , need an additional `CombineOp` to
      // assemble them.
    } else {
233 234
      auto* combine_op = InsertCombineOperationForTarget(
          ctx, param_map, program, legacy_input_vars);
235
      op_inputs.push_back(combine_op->GetResultByIndex(0));
236 237
    }
  }
238

239 240 241 242
  return op_inputs;
}

inline std::tuple<OpOutputTypeList, OpOutputMapping> GenerateOperationOutput(
243 244 245
    ir::IrContext* ctx,
    const OpDesc& op_desc,
    const OpOutputInfoList& output_infos) {
246 247 248 249
  OpOutputMapping arg_to_idx;
  OpOutputTypeList op_output_types = {};

  auto& type_translator = TypeTranslator::instance();
250
  auto& op_normalizer = OpNameNormalizer::instance();
251 252 253

  const BlockDesc* block = op_desc.Block();

254
  for (const auto& info : output_infos) {
255
    size_t cur_output_idx = op_output_types.size();
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
    std::string legacy_output_name =
        op_normalizer.GetLegacyArgName(op_desc.Type(), info.name);

    // return empty type if this arg is optional and not shown in OpDesc
    // TODO(lyk): HasOutput doesnot consider variadic attribute
    if (!op_desc.HasOutput(legacy_output_name)) {
      VLOG(10) << "[output translating]"
               << "[" << op_desc.Type() << "] optional " << info.name << " :"
               << info.type_name << " " << legacy_output_name;
      PADDLE_ENFORCE(info.optional,
                     platform::errors::PreconditionNotMet(
                         "Op %s arg %s should be optional if it can be empty",
                         op_desc.Type(),
                         legacy_output_name));
      op_output_types.push_back(ir::Type(nullptr));
      continue;
    }
273

274 275 276 277 278 279 280 281 282 283 284 285
    const auto& legacy_output_vars = op_desc.Output(legacy_output_name);
    bool is_vector = (info.type_name.find("VectorType") != std::string::npos);

    // if src type is Tensor
    if (!is_vector) {
      VLOG(10) << "[output translating]"
               << "[" << op_desc.Type() << "]" << info.name << " :"
               << info.type_name << " " << legacy_output_name;
      if (legacy_output_vars.size() == 0) {
        op_output_types.push_back(ir::Type(nullptr));
        continue;
      }
286

287 288 289 290 291
      auto& var_name = legacy_output_vars[0];
      VarDesc* var = block->FindVarRecursive(var_name);
      VLOG(10) << "[output translating]"
               << "[" << op_desc.Type() << "]" << info.name << " " << var_name
               << " " << var->GetType();
292

293 294 295 296
      ir::Type translated_var_type = type_translator[var->GetType()](ctx, *var);

      arg_to_idx[var_name] = cur_output_idx;
      op_output_types.push_back(translated_var_type);
297 298 299

      // if src type is Vector<Tesnor>
    } else {
300 301 302
      VLOG(10) << "[output translating]"
               << "[" << op_desc.Type() << "]" << info.name << " :"
               << info.type_name << " " << legacy_output_name;
303
      std::vector<ir::Type> types;
304 305
      for (const auto& var_name : legacy_output_vars) {
        VarDesc* var = block->FindVarRecursive(var_name);
306
        VLOG(10) << "[output translating]"
307
                 << "[" << op_desc.Type() << "]" << info.name << " " << var_name
308 309 310 311
                 << " " << var->GetType();
        ir::Type translated_var_type =
            type_translator[var->GetType()](ctx, *var);
        types.push_back(translated_var_type);
312
        arg_to_idx[var_name] = cur_output_idx;
313 314 315
      }
      ir::Type vec_type = ir::VectorType::get(ctx, types);
      op_output_types.push_back(vec_type);
316 317 318 319 320
    }
  }
  return {op_output_types, arg_to_idx};
}

321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
inline ir::AttributeMap TranslateOpAttribute(
    std::string normalized_op_name,
    const OpAttributeInfoList& op_attr_infos,
    const OpDesc& op_desc) {
  auto& attribute_translator = AttributeTranslator::instance();
  auto& op_normalizer = OpNameNormalizer::instance();
  ir::AttributeMap attribute_map = {};

  for (const auto& info : op_attr_infos) {
    auto legacy_attr_name =
        op_normalizer.GetLegacyAttrName(op_desc.Type(), info.name);

    paddle::framework::Attribute legacy_attr;
    if (op_desc.HasAttr(legacy_attr_name)) {
      legacy_attr = op_desc.GetAttr(legacy_attr_name);
    }
    VLOG(10) << "attribute in " << op_desc.Type()
             << " name: " << legacy_attr_name << " " << legacy_attr.index();
    ir::Attribute new_attr = attribute_translator(info.type_name, legacy_attr);
    attribute_map[info.name] = new_attr;
    if (!new_attr) {
      VLOG(0) << "empty attribute in " << op_desc.Type()
              << " name: " << info.name;
    } else {
      VLOG(10) << "new attribute in " << op_desc.Type()
               << " name: " << info.name << " " << new_attr.storage();
    }
  }

  return attribute_map;
}

353 354 355 356 357 358 359 360 361
inline void RecordOpResultMapping(TranslationContext* param_map,
                                  const OpDesc& op_desc,
                                  ir::Operation* operation,
                                  const OpOutputMapping& arg_to_idx) {
  for (const auto& n : op_desc.Outputs()) {
    auto& name = n.first;
    VLOG(10) << "[output recording]"
             << "[" << op_desc.Type() << "]" << name;
    auto& args = n.second;
362
    size_t idx_in_vector = 0;
363 364 365 366 367
    for (const auto& arg_name : args) {
      auto idx = arg_to_idx.at(arg_name);
      VLOG(10) << "[output recording]"
               << "[" << op_desc.Type() << "]" << arg_name << " " << idx;

368 369 370 371 372
      ir::OpResult value = operation->GetResultByIndex(idx);
      bool generated_by_vector = value.type().isa<ir::VectorType>();
      (*param_map)[arg_name] = VariableDefiningInfo(
          value, generated_by_vector, generated_by_vector ? idx_in_vector : -1);
      idx_in_vector++;
373 374 375 376 377 378 379 380
    }
  }
}

ir::Operation* GeneralOpHandler(ir::IrContext* ctx,
                                TranslationContext* param_map,
                                ir::Program* program,
                                const OpDesc& op_desc) {
381 382 383 384 385 386 387 388 389 390 391 392
  auto op_info = LoopkUpOpInfo(ctx, op_desc);
  auto* op_info_concept =
      op_info.GetInterfaceImpl<paddle::dialect::GetOpInfoInterface>();

  OpInputInfoList input_infos;
  OpAttributeInfoList attr_infos;
  OpOutputInfoList output_infos;
  std::tie(input_infos, attr_infos, output_infos, std::ignore) =
      op_info_concept->get_op_info_();

  auto op_inputs = GenerateOperationInput(
      ctx, param_map, program, op_desc, op_info.name(), input_infos);
393 394

  OpOutputMapping arg_to_idx;
395 396 397 398 399 400 401 402
  OpOutputTypeList op_output_types;
  std::tie(op_output_types, arg_to_idx) =
      GenerateOperationOutput(ctx, op_desc, output_infos);

  auto attribute_map =
      TranslateOpAttribute(op_info.name(), attr_infos, op_desc);
  VLOG(4) << "[general op][" << op_desc.Type() << "] preparation end.";

403
  ir::Operation* operation =
404 405
      ir::Operation::create(op_inputs, attribute_map, op_output_types, op_info);
  VLOG(4) << "[general op][" << op_desc.Type() << "] opearation creation end.";
406
  program->block()->push_back(operation);
407 408

  VLOG(4) << "[general op][" << op_desc.Type() << "] opearation insertion end.";
409 410 411 412 413 414 415 416 417
  RecordOpResultMapping(param_map, op_desc, operation, arg_to_idx);

  return operation;
}

ir::Operation* FeedOpHandler(ir::IrContext* ctx,
                             TranslationContext* param_map,
                             ir::Program* program,
                             const OpDesc& op_desc) {
418 419 420 421 422 423 424 425 426 427 428
  auto op_info = LoopkUpOpInfo(ctx, op_desc);

  auto* op_info_concept =
      op_info.GetInterfaceImpl<paddle::dialect::GetOpInfoInterface>();
  OpInputInfoList input_infos;
  OpAttributeInfoList attr_infos;
  OpOutputInfoList output_infos;
  std::tie(input_infos, attr_infos, output_infos, std::ignore) =
      op_info_concept->get_op_info_();

  std::vector<ir::OpResult> op_inputs;
429 430

  OpOutputMapping arg_to_idx;
431 432 433 434 435 436 437
  OpOutputTypeList op_output_types;
  std::tie(op_output_types, arg_to_idx) =
      GenerateOperationOutput(ctx, op_desc, output_infos);
  ir::AttributeMap attribute_map = {
      {"name", ir::StrAttribute::get(ctx, op_desc.OutputArgumentNames()[0])},
  };

438
  ir::Operation* operation =
439
      ir::Operation::create(op_inputs, attribute_map, op_output_types, op_info);
440
  program->block()->push_back(operation);
441 442 443 444 445 446 447 448 449 450
  RecordOpResultMapping(param_map, op_desc, operation, arg_to_idx);

  return operation;
}

ir::Operation* FetchOpHandler(ir::IrContext* ctx,
                              TranslationContext* param_map,
                              ir::Program* program,
                              const OpDesc& op_desc) {
  auto op_info = LoopkUpOpInfo(ctx, op_desc);
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467

  auto* op_info_concept =
      op_info.GetInterfaceImpl<paddle::dialect::GetOpInfoInterface>();
  OpInputInfoList input_infos;
  OpAttributeInfoList attr_infos;
  OpOutputInfoList output_infos;
  std::tie(input_infos, attr_infos, output_infos, std::ignore) =
      op_info_concept->get_op_info_();

  auto op_inputs = GenerateOperationInput(
      ctx, param_map, program, op_desc, op_info.name(), input_infos);

  OpOutputTypeList op_output_types;
  ir::AttributeMap attribute_map = {
      {"name", ir::StrAttribute::get(ctx, op_desc.InputArgumentNames()[0])},
  };

468
  ir::Operation* operation =
469
      ir::Operation::create(op_inputs, attribute_map, op_output_types, op_info);
470
  program->block()->push_back(operation);
471 472 473 474 475 476 477 478 479 480 481 482

  return operation;
}
}  // namespace

OpTranslator::OpTranslator() : general_handler(GeneralOpHandler) {
  special_handlers["feed"] = FeedOpHandler;
  special_handlers["fetch_v2"] = FetchOpHandler;
}

}  // namespace translator
}  // namespace paddle