pd_op_to_kernel_pass.cc 12.4 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
// 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 <iostream>

#include "paddle/fluid/ir/pass/pd_op_to_kernel_pass.h"

#include "paddle/fluid/ir/dialect/kernel_attribute.h"
#include "paddle/fluid/ir/dialect/kernel_dialect.h"
#include "paddle/fluid/ir/dialect/kernel_op.h"
#include "paddle/fluid/ir/dialect/kernel_type.h"
23
#include "paddle/fluid/ir/dialect/op_yaml_info_util.h"
24
#include "paddle/fluid/ir/dialect/pd_attribute.h"
H
hong 已提交
25
#include "paddle/fluid/ir/dialect/pd_dialect.h"
26 27
#include "paddle/fluid/ir/dialect/utils.h"
#include "paddle/fluid/ir/interface/op_yaml_info.h"
H
hong 已提交
28
#include "paddle/phi/api/lib/data_transform.h"
29 30 31 32 33 34 35
#include "paddle/phi/api/lib/kernel_dispatch.h"
#include "paddle/phi/common/place.h"
#include "paddle/phi/core/compat/convert_utils.h"
#include "paddle/phi/core/kernel_factory.h"
namespace paddle {
namespace dialect {

H
hong 已提交
36 37
const int init_on_gpu_threashold = 1000;

38 39 40 41
phi::KernelKey GetKernelKey(
    ir::Operation* op,
    const phi::Place& place,
    const std::unordered_map<ir::Value, ir::OpResult>& map_value_pair) {
H
hong 已提交
42 43 44
  if (op->name() == "pd.feed") {
    return {phi::Backend::CPU, phi::DataLayout::ANY, phi::DataType::FLOAT32};
  }
H
hong 已提交
45 46 47 48
  phi::Backend kernel_backend = phi::Backend::UNDEFINED;
  phi::DataLayout kernel_layout = phi::DataLayout::UNDEFINED;
  phi::DataType kernel_data_type = phi::DataType::UNDEFINED;

49 50
  paddle::dialect::OpYamlInfoInterface op_info_interface =
      op->dyn_cast<paddle::dialect::OpYamlInfoInterface>();
H
hong 已提交
51 52 53
  std::vector<paddle::dialect::OpInputInfo> input_info;
  if (op_info_interface) {
    auto op_info_res = op_info_interface.GetOpInfo();
54

H
hong 已提交
55
    input_info = std::get<0>(op_info_res);
56

H
hong 已提交
57 58 59 60 61 62 63
    // only suppurt non vector input for now
    std::map<std::string, int> input_map;
    int index = 0;
    int tensor_input_number = 0;
    for (auto& t : input_info) {
      // todo filter attribute tensor
      input_map[t.name] = index++;
H
hong 已提交
64

H
hong 已提交
65 66 67
      if (!t.is_mutable_attribute) {
        tensor_input_number += 1;
      }
H
hong 已提交
68
    }
69

H
hong 已提交
70 71 72 73 74 75 76
    std::map<std::string, std::string> attr_type_map;
    auto attr_info = std::get<1>(op_info_res);
    for (auto& t : attr_info) {
      VLOG(6) << t.name << "\t" << t.type_name;
      attr_type_map[t.name] = t.type_name;
    }
    auto runtime_info = std::get<3>(op_info_res);
77

H
hong 已提交
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
    auto attr_map = op->attributes();
    auto data_type_info = runtime_info.kernel_key_dtype;
    if (data_type_info.size() > 0 && data_type_info[0] != "") {
      // only support single input and attribute
      auto slot_name = data_type_info[0];
      if (input_map.count(slot_name)) {
        // parse from input
        int in_index = input_map.at(slot_name);

        dialect::DenseTensorType type =
            op->operand(in_index)
                .type()
                .dyn_cast<paddle::dialect::DenseTensorType>();
        kernel_data_type = TransToPhiDataType(type.dtype());
      } else {
        PADDLE_ENFORCE_EQ(attr_type_map.count(slot_name),
                          true,
                          phi::errors::PreconditionNotMet(
                              "[%s] MUST in attr map", slot_name));
        kernel_data_type = attr_map.at(slot_name)
                               .dyn_cast<paddle::dialect::DataTypeAttribute>()
                               .data();
      }
    }
102

H
hong 已提交
103 104 105
    // parse all the input tensor
    if (tensor_input_number == 0 || op->name() == "pd.full_") {
      // all the information have to get from attribute and context
H
hong 已提交
106 107 108 109

      if (op->name() == "pd.uniform") {
        // try to process uniform, use shape to determin backend
        // TODO(phlrain): shuold support other initilize op
110
        auto define_op = op->operand(0).GetDefiningOp();
H
hong 已提交
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
        if (define_op->name() == "pd.full_int_array") {
          auto shape = define_op->attributes()
                           .at("value")
                           .dyn_cast<dialect::IntArrayAttribute>()
                           .data()
                           .GetData();

          size_t numel = 1;
          for (auto& s : shape) {
            numel *= s;
          }
          if (numel > init_on_gpu_threashold) {
            kernel_backend = phi::Backend::GPU;
          }
        }
      }

      if (kernel_backend == phi::Backend::UNDEFINED) {
        kernel_backend = paddle::experimental::ParseBackend(place);
      }
131 132 133
    }
  }

H
hong 已提交
134
  if (op->num_operands() > 0) {
135 136
    paddle::experimental::detail::KernelKeyParser kernel_key_parser;

H
hong 已提交
137
    for (size_t i = 0; i < op->num_operands(); ++i) {
138
      // todo filter attribute tensor
H
hong 已提交
139
      if ((input_info.size() > i) && input_info[i].is_mutable_attribute) {
H
hong 已提交
140 141
        continue;
      }
142
      auto input_tmp = op->operand(i);
143
      auto new_input_tmp = map_value_pair.at(input_tmp);
H
hong 已提交
144

H
hong 已提交
145 146 147 148 149 150 151 152
      auto input_type = new_input_tmp.type();
      dialect::AllocatedDenseTensorType type;
      if (input_type.isa<dialect::AllocatedDenseTensorType>()) {
        type = input_type.dyn_cast<dialect::AllocatedDenseTensorType>();
      } else if (input_type.isa<ir::VectorType>()) {
        type = input_type.dyn_cast<ir::VectorType>()[0]
                   .dyn_cast<dialect::AllocatedDenseTensorType>();
      }
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194

      // fake tensor here
      auto ptr = new phi::Allocation(nullptr, 0, type.place());

      std::shared_ptr<phi::Allocation> holder(ptr);

      auto dtype = TransToPhiDataType(type.dtype());

      phi::DenseTensorMeta meta(
          dtype, type.dims(), type.data_layout(), type.lod(), type.offset());

      phi::DenseTensor fake_tensor(holder, meta);

      kernel_key_parser.AssignKernelKeySet(fake_tensor);
    }

    auto kernel_key_set = kernel_key_parser.key_set;

    auto kernel_key = kernel_key_set.GetHighestPriorityKernelKey();

    if (kernel_backend == phi::Backend::UNDEFINED) {
      kernel_backend = kernel_key.backend();
    }
    if (kernel_layout == phi::DataLayout::UNDEFINED) {
      kernel_layout = kernel_key.layout();
    }
    if (kernel_data_type == phi::DataType::UNDEFINED) {
      kernel_data_type = kernel_key.dtype();
    }
  }

  phi::KernelKey res(kernel_backend, kernel_layout, kernel_data_type);
  return res;
}

std::unique_ptr<ir::Program> PdOpLowerToKernelPass(ir::Program* prog) {
  auto program = std::make_unique<ir::Program>(ir::IrContext::Instance());

  auto block = prog->block();
  phi::Place cpu_place(phi::AllocationType::CPU);

  ir::IrContext* ctx = ir::IrContext::Instance();
H
hong 已提交
195
  ctx->GetOrRegisterDialect<paddle::dialect::PaddleDialect>();
196 197 198 199 200 201 202 203 204 205
  ctx->GetOrRegisterDialect<paddle::dialect::PaddleKernelDialect>();

  std::unordered_map<ir::Operation*, ir::Operation*> map_op_pair;
  std::unordered_map<ir::Value, ir::OpResult> map_value_pair;

  std::string op1_name = paddle::dialect::PhiKernelOp::name();

  ir::OpInfo op1_info = ctx->GetRegisteredOpInfo(op1_name);

  for (auto it = block->begin(); it != block->end(); ++it) {
H
hong 已提交
206
    VLOG(6) << "op name " << (*it)->name();
207
    auto kernel_key = GetKernelKey(*it, cpu_place, map_value_pair);
H
hong 已提交
208
    VLOG(6) << "kernel type " << kernel_key;
209 210 211 212 213
    // create new Op

    // only for single output
    // need update new kernel key layout and data tyep

214 215
    std::vector<ir::Type> op_output_types;
    if ((*it)->num_results() > 0) {
H
hong 已提交
216 217 218
      for (size_t i = 0; i < (*it)->num_results(); ++i) {
        auto result_type = (*it)->result(i).type();
        if (result_type.isa<dialect::DenseTensorType>()) {
H
hong 已提交
219 220 221 222
          auto allocated_dense_tensor_dtype =
              paddle::dialect::AllocatedDenseTensorType::get(
                  ctx,
                  phi::TransToPhiPlace(kernel_key.backend()),
H
hong 已提交
223
                  result_type.dyn_cast<dialect::DenseTensorType>());
H
hong 已提交
224
          op_output_types.push_back(allocated_dense_tensor_dtype);
H
hong 已提交
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
        } else if (result_type.isa<ir::VectorType>()) {
          auto pos1 = result_type.dyn_cast<ir::VectorType>().data()[0];

          if (pos1.isa<dialect::DenseTensorType>()) {
            auto allocated_dense_tensor_dtype =
                paddle::dialect::AllocatedDenseTensorType::get(
                    ctx,
                    phi::TransToPhiPlace(kernel_key.backend()),
                    pos1.dyn_cast<dialect::DenseTensorType>());
            op_output_types.push_back(allocated_dense_tensor_dtype);
          } else {
            PADDLE_THROW(phi::errors::Unimplemented(
                "only support dense tensor in vector type for now"));
          }

          ir::Type t1 = ir::VectorType::get(ctx, op_output_types);
          op_output_types.clear();
          op_output_types.push_back(t1);
H
hong 已提交
243 244
        }
      }
245
    }
H
hong 已提交
246

247 248
    // constuct input
    std::vector<ir::OpResult> vec_inputs;
H
hong 已提交
249

250 251
    paddle::dialect::OpYamlInfoInterface op_info_interface =
        (*it)->dyn_cast<paddle::dialect::OpYamlInfoInterface>();
H
hong 已提交
252
    std::string kernel_fn_str;
H
hong 已提交
253
    std::vector<paddle::dialect::OpInputInfo> input_info;
H
hong 已提交
254 255 256 257
    if (op_info_interface) {
      auto op_info_res = op_info_interface.GetOpInfo();
      auto runtime_info = std::get<3>(op_info_res);
      kernel_fn_str = runtime_info.kernel_func[0];
H
hong 已提交
258 259 260 261 262
      input_info = std::get<0>(op_info_res);
    }

    if ((*it)->num_operands() > 0) {
      for (size_t i = 0; i < (*it)->num_operands(); ++i) {
263
        auto cur_in = (*it)->operand(i);
H
hong 已提交
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
        auto new_in = map_value_pair.at(cur_in);

        auto new_in_type = new_in.type();

        auto& kernel = phi::KernelFactory::Instance().SelectKernelWithGPUDNN(
            kernel_fn_str, kernel_key);

        if (kernel.IsValid()) {
          if (new_in_type.isa<dialect::AllocatedDenseTensorType>()) {
            // allocated type
            auto place =
                new_in_type.dyn_cast<dialect::AllocatedDenseTensorType>()
                    .place();

            if ((i < input_info.size()) &&
                (!input_info[i].is_mutable_attribute) &&
                (place != phi::TransToPhiPlace(kernel_key.backend()))) {
              if (paddle::experimental::NeedTransformPlace(
                      place, kernel.InputAt(i).backend, {})) {
                VLOG(6) << "need trans from " << place << " to "
                        << kernel_key.backend();
                // build memcopy op
                auto copy_kernel_key = kernel_key;
                copy_kernel_key.set_backend(phi::Backend::GPU);
                std::unordered_map<std::string, ir::Attribute> op1_attribute{
                    {"op_name", ir::StrAttribute::get(ctx, "pd.memcpy_h2d")},
                    {"kernel_name", ir::StrAttribute::get(ctx, "memcpy_h2d")},
                    {"kernel_key",
                     dialect::KernelAttribute::get(ctx, copy_kernel_key)},
                    {"dst_place_type", ir::Int32Attribute::get(ctx, 1)}};

                ir::Operation* op1 = ir::Operation::Create(
                    {new_in}, op1_attribute, {new_in_type}, op1_info);

                program->block()->push_back(op1);

                new_in = op1->result(0);
              }
            }
          } else if (new_in_type.isa<ir::VectorType>()) {
            // [ todo need update here, support combine data transfomer]
          } else {
            PADDLE_THROW(phi::errors::Unimplemented(
                "only support allocated dense tensor type for now"));
          }
        }
        vec_inputs.push_back(new_in);
      }
H
hong 已提交
312
    }
313 314 315

    std::unordered_map<std::string, ir::Attribute> op1_attribute{
        {"op_name", ir::StrAttribute::get(ctx, (*it)->name())},
H
hong 已提交
316
        {"kernel_name", ir::StrAttribute::get(ctx, kernel_fn_str)},
317 318 319 320 321 322 323 324 325
        {"kernel_key", dialect::KernelAttribute::get(ctx, kernel_key)}};

    auto op_attr_map = (*it)->attributes();

    for (auto it1 = op_attr_map.begin(); it1 != op_attr_map.end(); ++it1) {
      op1_attribute.emplace(it1->first, it1->second);
    }

    ir::Operation* op1 = ir::Operation::Create(
326
        vec_inputs, op1_attribute, op_output_types, op1_info);
327 328

    map_op_pair[*it] = op1;
329 330 331

    // only deal with single output
    if ((*it)->num_results() > 0) {
H
hong 已提交
332 333 334
      for (size_t i = 0; i < (*it)->num_results(); ++i) {
        map_value_pair[(*it)->result(i)] = op1->result(i);
      }
335
    }
336 337 338 339 340 341 342 343 344

    program->block()->push_back(op1);
  }

  return program;
}

}  // namespace dialect
}  // namespace paddle