ngraph_engine.cc 23.4 KB
Newer Older
B
baojun 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/* Copyright (c) 2018 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 <glog/logging.h>

#include <algorithm>
#include <map>
19
#include <memory>
B
baojun 已提交
20
#include <string>
21 22
#include <unordered_set>
#include <utility>
B
baojun 已提交
23 24 25 26 27 28 29 30 31 32
#include <vector>

#include "paddle/fluid/framework/block_desc.h"
#include "paddle/fluid/framework/ddim.h"
#include "paddle/fluid/framework/feed_fetch_type.h"
#include "paddle/fluid/framework/framework.pb.h"
#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/framework/op_desc.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/var_type.h"
33
#include "paddle/fluid/operators/ngraph/ngraph_bridge.h"
B
baojun 已提交
34 35 36 37 38 39 40
#include "paddle/fluid/operators/ngraph/ngraph_engine.h"

namespace paddle {
namespace operators {

static ngraph::Shape Ddim2Shape(const framework::DDim& dims) {
  ngraph::Shape sp;
41 42 43 44
  if (dims.size() == 1 && dims[0] == 0) {
    sp.emplace_back(0);
    return sp;
  }
B
baojun 已提交
45 46 47
  for (int i = 0; i < dims.size(); ++i) {
    int k = dims[i];
    k = k == 0 ? 1 : k;
48
    sp.emplace_back(k);
B
baojun 已提交
49 50 51 52
  }
  return sp;
}

53 54 55 56 57 58 59 60 61
static framework::DDim Shape2Ddim(const ngraph::Shape& shape) {
  std::vector<int64_t> dims;
  for (size_t i = 0; i < shape.size(); ++i) {
    int64_t k = shape[i];
    dims.emplace_back(k);
  }
  return framework::make_ddim(dims);
}

B
baojun 已提交
62 63 64 65 66 67
static std::map<framework::proto::VarType::Type, ngraph::element::Type>
    pd2ng_type_map = {
        {framework::proto::VarType::FP32, ngraph::element::f32},
        {framework::proto::VarType::FP64, ngraph::element::f64},
        {framework::proto::VarType::INT32, ngraph::element::i32},
        {framework::proto::VarType::INT64, ngraph::element::i64},
68
        {framework::proto::VarType::UINT8, ngraph::element::u8},
69 70 71 72 73 74 75 76
        {framework::proto::VarType::BOOL, ngraph::element::boolean}};

static std::map<ngraph::element::Type, framework::proto::VarType::Type>
    ng2pd_type_map = {
        {ngraph::element::f32, framework::proto::VarType::FP32},
        {ngraph::element::f64, framework::proto::VarType::FP64},
        {ngraph::element::i32, framework::proto::VarType::INT32},
        {ngraph::element::i64, framework::proto::VarType::INT64},
77
        {ngraph::element::u8, framework::proto::VarType::UINT8},
78 79 80 81 82 83
        {ngraph::element::boolean, framework::proto::VarType::BOOL}};

std::vector<std::string> NgraphEngine::feed_vars = {};
std::vector<std::string> NgraphEngine::fetch_vars = {};
framework::Variable* NgraphEngine::pre_var_ptr = nullptr;
const framework::BlockDesc* NgraphEngine::p_bdesc = nullptr;
84
bool NgraphEngine::is_training = false;
85 86 87 88 89

std::unordered_map<std::string, EngineCache> NgraphEngine::engine_cache = {};
std::unordered_map<std::string,
                   std::vector<std::shared_ptr<ngraph::runtime::Tensor>>>
    NgraphEngine::t_in_cache_ = {};
B
baojun 已提交
90 91 92 93 94

std::shared_ptr<ngraph::runtime::Backend> NgraphEngine::backend_ =
    ngraph::runtime::Backend::create("CPU");

static std::vector<std::vector<int>> NgraphOpIntervals(
95 96 97
    std::vector<std::unique_ptr<framework::OperatorBase>>* ops) {
  NgraphEngine::feed_vars.clear();
  NgraphEngine::fetch_vars.clear();
B
baojun 已提交
98
  std::vector<std::vector<int>> intervals;
99 100

  int size = ops->size();
B
baojun 已提交
101
  int left = 0;
B
baojun 已提交
102
  while (left < size && ops->at(left)->Type() != framework::kFeedOpType &&
103
         ops->at(left)->Type() != "read" &&
B
baojun 已提交
104
         ops->at(left)->Type() != framework::kFetchOpType) {
B
baojun 已提交
105 106
    ++left;
  }
107

108 109
  while (left < size && (ops->at(left)->Type() == framework::kFeedOpType ||
                         ops->at(left)->Type() == "read")) {
110 111 112 113 114
    for (auto& var_name_item : ops->at(left)->Outputs()) {
      for (auto& var_name : var_name_item.second) {
        NgraphEngine::feed_vars.emplace_back(var_name);
      }
    }
B
baojun 已提交
115 116 117 118
    ++left;
  }

  int right = left;
119
  while (right < size && ops->at(right)->Type() != framework::kFetchOpType) {
B
baojun 已提交
120 121 122
    ++right;
  }

123 124 125 126 127 128 129 130 131 132
  int index = right;
  while (index < size && ops->at(index)->Type() == framework::kFetchOpType) {
    for (auto& var_name_item : ops->at(index)->Inputs()) {
      for (auto& var_name : var_name_item.second) {
        NgraphEngine::fetch_vars.emplace_back(var_name);
      }
    }
    ++index;
  }

B
baojun 已提交
133 134 135 136
  if (left == size || ops->at(left)->Type() == framework::kFetchOpType) {
    left = 0;
  }

B
baojun 已提交
137 138 139
  // (left, right - 1) represents indices between feed and fetch
  int pivot = left;
  while (pivot < right) {
140
    auto op_type = ops->at(pivot)->Type();
141
    if (!NgraphBridge::isSupported(ops->at(pivot))) {
B
baojun 已提交
142 143 144
      ++pivot;
    } else {
      int start = pivot, end = start;
145
      while (pivot < right && (NgraphBridge::isSupported(ops->at(pivot)))) {
B
baojun 已提交
146 147 148 149
        ++pivot;
        ++end;
      }
      std::vector<int> interval = {start, end};
150
      intervals.emplace_back(interval);
B
baojun 已提交
151 152 153 154 155
    }
  }  // end while
  return intervals;
}

156 157 158 159 160 161 162 163
static void SubstituteNgraphOp(
    std::vector<std::unique_ptr<framework::OperatorBase>>* ops,
    std::string engine_key, std::string block_str, std::vector<int> interval) {
  framework::OpDesc ng_op_desc(nullptr);
  ng_op_desc.SetType("ngraph_engine");
  ng_op_desc.SetAttr("interval", interval);
  ng_op_desc.SetAttr("engine_key", engine_key);
  ng_op_desc.SetAttr("graph", block_str);
164 165
  ng_op_desc.SetInput("Xs", std::vector<std::string>(0));
  ng_op_desc.SetOutput("Ys", std::vector<std::string>(0));
166 167 168 169

  ops->erase(ops->begin() + interval[0], ops->begin() + interval[1]);
  ops->insert(ops->begin() + interval[0],
              framework::OpRegistry::CreateOp(ng_op_desc));
B
baojun 已提交
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 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
std::string SerializedBlock(const std::vector<framework::OpDesc*>& op_descs) {
  framework::proto::BlockDesc block_proto;
  framework::BlockDesc block_desc(nullptr, &block_proto);
  block_desc.Proto()->set_parent_idx(-1);
  block_desc.Proto()->set_idx(0);

  for (auto* op_desc : op_descs) {
    auto* op = block_desc.AppendOp();
    *op->Proto() = *op_desc->Proto();
  }
  return block_desc.Proto()->SerializeAsString();
}

std::string GenerateEngineKey(const framework::BlockDesc& bdesc) {
  framework::proto::BlockDesc block_proto;
  framework::BlockDesc block_desc(nullptr, &block_proto);
  block_desc.Proto()->set_parent_idx(-1);
  block_desc.Proto()->set_idx(0);

  for (auto& op_desc : bdesc.AllOps()) {
    auto* op = block_desc.AppendOp();
    *op->Proto() = *op_desc->Proto();
  }
  auto engine_key = std::to_string(
      std::hash<std::string>()(block_desc.Proto()->SerializeAsString()));
  return engine_key;
}

std::string GenerateEngineKey(const std::vector<std::string>& engine_inputs,
                              const std::vector<std::string>& engine_outputs,
                              int size) {
  std::string engine_hash_key = "";
  for (auto name : engine_inputs) {
    engine_hash_key += name;
  }
  for (auto name : engine_outputs) {
    engine_hash_key += name;
  }
  engine_hash_key += std::to_string(size);
  auto engine_key = std::to_string(std::hash<std::string>()(engine_hash_key));
  return engine_key;
}

void NgraphEngine::FuseNgraphOps(
    const framework::BlockDesc& block_desc,
    std::vector<std::unique_ptr<framework::OperatorBase>>* ops) {
  NgraphEngine::p_bdesc = &block_desc;
  auto intervals = NgraphOpIntervals(ops);
  std::string engine_key =
      GenerateEngineKey(feed_vars, fetch_vars, ops->size());
  for (auto it = intervals.rbegin(); it != intervals.rend(); ++it) {
    SubstituteNgraphOp(ops, engine_key, "", *it);
B
baojun 已提交
224 225 226 227 228
  }
}

NgraphEngine::NgraphEngine(const framework::Scope& scope,
                           const platform::Place& place,
229
                           const framework::ExecutionContext& ctx)
B
baojun 已提交
230 231 232 233 234 235 236
    : scope_(scope), place_(place) {
  var_in_node_map_ = std::make_shared<
      std::unordered_map<std::string, std::shared_ptr<ngraph::Node>>>();

  var_node_map_ = std::make_shared<
      std::unordered_map<std::string, std::shared_ptr<ngraph::Node>>>();

237
  GetNgFunction(ctx);
B
baojun 已提交
238 239
}

240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
void NgraphEngine::Prepare(const framework::ExecutionContext& ctx) {
  auto interval = ctx.Attr<std::vector<int>>("interval");
  std::string serialized_graph = ctx.Attr<std::string>("graph");

  auto input_vars = ctx.Inputs("Xs");
  if (!input_vars.empty()) {
    feed_vars = input_vars;
    var_in_ = input_vars;
  }
  auto output_vars = ctx.Outputs("Ys");
  if (!output_vars.empty()) {
    var_out_ = output_vars;
  }

  framework::proto::BlockDesc block_proto;
  if (!serialized_graph.empty()) block_proto.ParseFromString(serialized_graph);
  framework::BlockDesc block_desc(nullptr, &block_proto);
  if (!serialized_graph.empty()) {
    NgraphEngine::p_bdesc = &block_desc;
  }

B
baojun 已提交
261
  bool has_fetch = false, is_full = false;
262
  for (auto& var : p_bdesc->AllVars()) {
B
baojun 已提交
263 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
    if (!(var->GetType() == framework::proto::VarType::SELECTED_ROWS ||
          var->GetType() == framework::proto::VarType::LOD_TENSOR ||
          var->GetType() == framework::proto::VarType::LOD_TENSOR_ARRAY)) {
      continue;
    }

    auto var_name = var->Name();
    if (var->Name() == framework::kEmptyVarName) {
      continue;
    }

    if (var_name != framework::kFeedOpType &&
        var_name != framework::kFetchOpType) {
      auto pd_type = var->GetDataType();
      if (pd2ng_type_map.find(pd_type) == pd2ng_type_map.end()) {
        PADDLE_THROW("Data type of var %s not found in pd2ng_type_map",
                     var_name);
      }
      var_type_map_[var_name] = pd2ng_type_map[pd_type];
    }

    if (var->Persistable()) {
      persistables_.insert(var->Name());
    }
  }

289 290 291
  std::vector<paddle::framework::OpDesc*> ops_desc;
  for (auto op_desc : p_bdesc->AllOps()) {
    ops_desc.emplace_back(op_desc);
B
baojun 已提交
292 293 294
    if (op_desc->Type() == framework::kFetchOpType) {
      has_fetch = true;
    }
B
baojun 已提交
295 296
  }

297
  for (auto op_desc : ops_desc) {
B
baojun 已提交
298
    if (op_desc->Type().find("_grad") != std::string::npos) {
299
      is_training = true;
300
      this->is_test_ = false;
B
baojun 已提交
301 302 303 304
      break;
    }
  }

305 306 307
  if (interval[0] > 0 &&
      ops_desc.at(interval[0] - 1)->Type() == framework::kFeedOpType &&
      interval[1] < static_cast<int>(ops_desc.size()) &&
B
baojun 已提交
308 309
      ops_desc.at(interval[1])->Type() == framework::kFetchOpType) {
    is_full = true;
B
baojun 已提交
310 311
  }

B
baojun 已提交
312
  if (is_full) {
313 314 315 316
    this->op_state_ = this->is_test_ ? OpState::FULL_TEST : OpState::FULL_TRAIN;
  } else {
    this->op_state_ =
        this->is_test_ ? OpState::PARTIAL_TEST : OpState::PARTIAL_TRAIN;
B
baojun 已提交
317 318
  }

319 320 321 322 323 324
  int idx = interval[0];
  while (idx < interval[1]) {
    this->fused_ops_.emplace_back(
        framework::OpRegistry::CreateOp(*(ops_desc[idx])));
    ++idx;
  }
B
baojun 已提交
325 326
  while (idx < static_cast<int>(ops_desc.size()) &&
         ops_desc.at(idx)->Type() != framework::kFetchOpType) {
327 328
    auto op_desc = ops_desc.at(idx);
    for (auto& var_name_item : op_desc->Inputs()) {
B
baojun 已提交
329
      for (auto& var_name : var_name_item.second) {
330
        this->post_op_inputs_.insert(var_name);
B
baojun 已提交
331 332
      }
    }
333
    ++idx;
B
baojun 已提交
334
  }
335

B
baojun 已提交
336 337 338 339
  if (!has_fetch) {
    op_state_ = OpState::UNKNOWN;
  }

340 341 342 343 344 345 346 347 348
  if (var_in_.empty() && var_out_.empty()) {
    BuildNgIO(ops_desc, interval);
  }
  for (size_t i = 0; i < var_in_.size(); ++i) {
    auto var_name = var_in_[i];
    if (persistables_.find(var_name) == persistables_.end()) {
      var_in_updates_.emplace_back(i);
    }
  }
B
baojun 已提交
349 350
}

351 352
void NgraphEngine::BuildNgIO(const std::vector<framework::OpDesc*>& ops_desc,
                             const std::vector<int>& interval) {
B
baojun 已提交
353 354
  std::unordered_set<std::string> inputs;
  std::unordered_set<std::string> outputs;
355 356
  for (int i = interval[0]; i < interval[1]; ++i) {
    auto op = ops_desc[i];
B
baojun 已提交
357 358 359 360 361 362
    for (auto& var_name_item : op->Inputs()) {
      for (auto& var_name : var_name_item.second) {
        inputs.insert(var_name);
        const bool is_output = outputs.find(var_name) != outputs.end();
        if (!is_output &&
            std::find(var_in_.begin(), var_in_.end(), var_name) ==
363 364
                var_in_.end() &&
            scope_.FindVar(var_name)) {
B
baojun 已提交
365
          // fill var_in here to keep lhs and rhs order
366
          this->var_in_.emplace_back(var_name);
B
baojun 已提交
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
        }
      }
    }

    for (auto& var_name_item : op->Outputs()) {
      PADDLE_ENFORCE_LE(var_name_item.second.size(), 1,
                        "op %s has more than 1 output - Not handling yet",
                        op->Type());
      for (auto& var_name : var_name_item.second) {
        outputs.insert(var_name);
      }
    }
  }

  // var_out.clear();
382 383
  for (int i = interval[0]; i < interval[1]; ++i) {
    auto op = ops_desc[i];
B
baojun 已提交
384 385 386 387 388
    for (auto& var_name_item : op->Outputs()) {
      PADDLE_ENFORCE_LE(var_name_item.second.size(), 1,
                        "op %s has more than 1 output - Not handling yet",
                        op->Type());
      for (auto& var_name : var_name_item.second) {
389
        switch (this->op_state_) {
B
baojun 已提交
390 391
          case OpState::PARTIAL_TEST:
            if (post_op_inputs_.find(var_name) != post_op_inputs_.end() ||
392 393 394
                find(fetch_vars.begin(), fetch_vars.end(), var_name) !=
                    fetch_vars.end()) {
              this->var_out_.emplace_back(var_name);
B
baojun 已提交
395 396 397
            }
            break;
          case OpState::FULL_TEST:
398 399 400
            if (find(fetch_vars.begin(), fetch_vars.end(), var_name) !=
                fetch_vars.end()) {
              this->var_out_.emplace_back(var_name);
B
baojun 已提交
401 402 403
            }
            break;
          case OpState::PARTIAL_TRAIN:
404 405
            if (find(fetch_vars.begin(), fetch_vars.end(), var_name) !=
                    fetch_vars.end() ||
B
baojun 已提交
406 407
                post_op_inputs_.find(var_name) != post_op_inputs_.end() ||
                persistables_.find(var_name) != persistables_.end()) {
408
              this->var_out_.emplace_back(var_name);
B
baojun 已提交
409 410 411
            }
            break;
          case OpState::FULL_TRAIN:
412 413
            if (find(fetch_vars.begin(), fetch_vars.end(), var_name) !=
                    fetch_vars.end() ||
B
baojun 已提交
414
                persistables_.find(var_name) != persistables_.end()) {
415
              this->var_out_.emplace_back(var_name);
B
baojun 已提交
416 417 418
            }
            break;
          default:
419
            this->var_out_.emplace_back(var_name);
B
baojun 已提交
420 421 422 423
        }
      }
    }
  }
424 425 426 427 428 429 430 431 432
  // remove output duplicates
  std::unordered_set<std::string> var_out_set;
  for (int i = static_cast<int>(var_out_.size()) - 1; i >= 0; --i) {
    std::string var_name = var_out_.at(i);
    if (var_out_set.count(var_name)) {
      var_out_.erase(var_out_.begin() + i);
    }
    var_out_set.insert(var_name);
  }
B
baojun 已提交
433 434
}

435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
void NgraphEngine::GetNgInputShape() {
  for (auto& var_name : var_in_) {
    auto* var = scope_.FindVar(var_name);
    if (var && var->IsType<framework::LoDTensor>()) {
      auto* tensor_pd = GetLoDTensorOrSelectedRowsValueFromVar(*var);
      auto sp = Ddim2Shape(tensor_pd->dims());
      auto ng_type = var_type_map_[var_name];
      auto prm = std::make_shared<ngraph::op::Parameter>(ng_type, sp, true);
      (*var_node_map_)[var_name] = prm;
      (*var_in_node_map_)[var_name] = prm;
    }
  }
}

void NgraphEngine::BuildNgNodes() {
  for (auto& op : fused_ops_) {
    for (auto& var_name_item : op->Outputs()) {
      for (auto& var_name : var_name_item.second) {
        if (var_node_map_->find(var_name) == var_node_map_->end()) {
          auto* var = scope_.FindVar(var_name);
          if (var && var->IsType<framework::LoDTensor>()) {
            auto* tensor_pd = GetLoDTensorOrSelectedRowsValueFromVar(*var);
            auto& ddim = tensor_pd->dims();
            auto ng_shape = Ddim2Shape(ddim);
            auto ng_type = var_type_map_[var_name];
            auto prm = std::make_shared<ngraph::op::Parameter>(ng_type,
                                                               ng_shape, true);
            (*var_node_map_)[var_name] = prm;
          }
        }
      }
    }
  }
  NgraphBridge ngb(var_node_map_);
  for (auto& op : fused_ops_) {
    ngb.BuildNgNode(op);
  }
}

474 475
std::shared_ptr<ngraph::Function> NgraphEngine::BuildNgFunction(
    const framework::ExecutionContext& ctx) {
476
  Prepare(ctx);
477
  GetNgInputShape();
B
baojun 已提交
478 479 480 481 482
  BuildNgNodes();
  ngraph::NodeVector func_outputs;
  ngraph::ParameterVector func_inputs;

  for (auto& vo : var_out_) {
483
    func_outputs.emplace_back(var_node_map_->at(vo));
B
baojun 已提交
484 485 486 487 488 489
  }

  for (auto& vi : var_in_) {
    std::shared_ptr<ngraph::op::Parameter> prm =
        std::dynamic_pointer_cast<ngraph::op::Parameter>(
            var_in_node_map_->at(vi));
490
    func_inputs.emplace_back(prm);
B
baojun 已提交
491 492
  }

493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
  return std::make_shared<ngraph::Function>(func_outputs, func_inputs);
}

void NgraphEngine::ClearNgCache() {
  auto it = engine_cache.begin();
  while (it != engine_cache.end()) {
    auto ng_engine = it->second;
    backend_->remove_compiled_function(ng_engine.ngraph_handle);
    ++it;
  }
  engine_cache.clear();
  auto it_tensor = t_in_cache_.begin();
  while (it_tensor != t_in_cache_.end()) {
    auto t_vec = it_tensor->second;
    for (auto t_in : t_vec) {
      t_in.reset();
    }
    ++it_tensor;
  }
  t_in_cache_.clear();
B
baojun 已提交
513 514
}

515 516 517
void NgraphEngine::GetNgFunction(const framework::ExecutionContext& ctx) {
  auto interval = ctx.Attr<std::vector<int>>("interval");
  std::string engine_key = ctx.Attr<std::string>("engine_key");
518 519

  // set to flase, to debug cache or recompile everytime.
520
  bool use_cache = true;
521 522 523 524 525 526 527 528 529 530
  if (!use_cache) ClearNgCache();

  this->func_cache_key_ = "";
  for (int i = 0; i < static_cast<int>(feed_vars.size()); ++i) {
    auto* var = scope_.FindVar(feed_vars[i]);
    if (var && var->IsType<framework::LoDTensor>()) {
      auto* tensor_pd = GetLoDTensorOrSelectedRowsValueFromVar(*var);
      auto dims = tensor_pd->dims();
      for (int j = 0; j < dims.size(); ++j) {
        func_cache_key_ += std::to_string(dims[j]);
B
baojun 已提交
531 532
      }
    }
533 534 535 536 537 538 539 540 541 542 543 544 545
  }
  func_cache_key_ += std::to_string(interval[0]) + "_" +
                     std::to_string(interval[1]) + engine_key;
  func_cache_key_ = std::to_string(std::hash<std::string>()(func_cache_key_));

  if (engine_cache.find(func_cache_key_) != engine_cache.end()) {
    if (engine_cache[func_cache_key_].persistables.size() == 0) {
      ClearNgCache();
    } else {
      auto var_name = engine_cache[func_cache_key_].persistables.begin();
      framework::Variable* var = scope_.FindVar(*var_name);
      if (var != pre_var_ptr) {
        ClearNgCache();
546
      }
547
      pre_var_ptr = var;
548
    }
549
  }
550

551 552 553 554 555 556 557
  if (engine_cache.find(func_cache_key_) == engine_cache.end()) {
    if (engine_cache.size() > 5) ClearNgCache();
    auto func = BuildNgFunction(ctx);
    // Due to optimization backend may produce results in other layouts,
    // make sure we get default layout for results.
    for (auto& r : func->get_results()) {
      r->set_needs_default_layout(true);
B
baojun 已提交
558
    }
559 560 561 562 563 564
    engine_cache[func_cache_key_].ngraph_handle = backend_->compile(func);
    engine_cache[func_cache_key_].persistables = this->persistables_;
    engine_cache[func_cache_key_].var_in_updates = this->var_in_updates_;
    engine_cache[func_cache_key_].var_in = this->var_in_;
    engine_cache[func_cache_key_].var_out = this->var_out_;
    engine_cache[func_cache_key_].is_test = this->is_test_;
B
baojun 已提交
565 566 567 568 569
  }
}

void NgraphEngine::Run(const framework::Scope& scope,
                       const platform::Place& place) const {
570
  std::shared_ptr<ngraph::runtime::Executable> ng_handle;
571 572 573 574 575 576
  const std::set<std::string>* p_persistables;
  const std::vector<size_t>* p_var_in_updates;
  const std::vector<std::string>* p_var_in;
  const std::vector<std::string>* p_var_out;
  bool is_test;

577 578 579 580 581 582 583 584
  PADDLE_ENFORCE(engine_cache.find(func_cache_key_) != engine_cache.end(),
                 "Cannot find cached data to run ngraph function");
  ng_handle = engine_cache[func_cache_key_].ngraph_handle;
  p_persistables = &(engine_cache[func_cache_key_].persistables);
  p_var_in_updates = &(engine_cache[func_cache_key_].var_in_updates);
  p_var_in = &(engine_cache[func_cache_key_].var_in);
  p_var_out = &(engine_cache[func_cache_key_].var_out);
  is_test = engine_cache[func_cache_key_].is_test;
B
baojun 已提交
585

586 587 588
  std::vector<std::shared_ptr<ngraph::runtime::Tensor>>* p_t_in;
  std::vector<std::shared_ptr<ngraph::runtime::Tensor>> t_in = {};

589 590 591
  auto m_parameters = ng_handle->get_parameters();
  auto m_results = ng_handle->get_results();
  if (is_test && t_in_cache_.find(func_cache_key_) != t_in_cache_.end()) {
592 593 594 595 596 597 598 599 600 601 602 603 604
    p_t_in = &(t_in_cache_[func_cache_key_]);
    for (size_t i = 0; i < p_var_in_updates->size(); ++i) {
      int index = p_var_in_updates->at(i);
      auto vi = p_var_in->at(index);
      auto sp = m_parameters[index]->get_shape();
      auto ng_type = m_parameters[index]->get_element_type();
      std::shared_ptr<ngraph::runtime::Tensor> ti;
      auto* var = scope.FindVar(vi);
      if (var && var->IsType<framework::LoDTensor>()) {
        auto* tensor_pd = GetMutableLoDTensorOrSelectedRowsValueFromVar(var);
        void* pd_arr = tensor_pd->mutable_data(place, ng2pd_type_map[ng_type]);
        ti = backend_->create_tensor(ng_type, sp, pd_arr);
        (*p_t_in)[index] = ti;
B
baojun 已提交
605
      } else {
606
        PADDLE_THROW("Cannot find var or tensor with var name %s", vi);
B
baojun 已提交
607
      }
608 609
    }
  } else {
610
    if (is_test) {
611
      p_t_in = &(t_in_cache_[func_cache_key_]);
B
baojun 已提交
612
    } else {
613
      p_t_in = &t_in;
B
baojun 已提交
614
    }
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632

    for (size_t i = 0; i < p_var_in->size(); ++i) {
      auto vi = p_var_in->at(i);
      auto sp = m_parameters[i]->get_shape();
      auto ng_type = m_parameters[i]->get_element_type();
      std::shared_ptr<ngraph::runtime::Tensor> ti;
      auto* var = scope.FindVar(vi);
      if (var && var->IsType<framework::LoDTensor>()) {
        auto* tensor_pd = GetMutableLoDTensorOrSelectedRowsValueFromVar(var);
        void* pd_arr = tensor_pd->mutable_data(place, ng2pd_type_map[ng_type]);
        PADDLE_ENFORCE(sp == Ddim2Shape(tensor_pd->dims()),
                       "Ensure ngraph tensor layout align with paddle tensor");
        ti = backend_->create_tensor(ng_type, sp, pd_arr);
      } else {
        PADDLE_THROW("Cannot find var or tensor with var name %s", vi);
      }
      bool is_persistable =
          (p_persistables->find(vi) != p_persistables->end()) ? true : false;
633
      if (!is_training && is_test && is_persistable) {
634 635 636
        ti->set_stale(false);
      }
      (*p_t_in).emplace_back(ti);
B
baojun 已提交
637 638 639
    }
  }

640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
  for (auto& op : fused_ops_) {
    framework::RuntimeContext ctx(op->Inputs(), op->Outputs(), scope_);
    if (op->Type() == "reshape2_grad") {
      auto xshape_name = op->Inputs().at("XShape").at(0);
      auto* xshape_var = scope_.FindVar(xshape_name);
      auto* xshape_tensor = GetLoDTensorOrSelectedRowsValueFromVar(*xshape_var);
      auto& xshape_ddim = xshape_tensor->dims();
      auto xgrad_name = op->Outputs().at(framework::GradVarName("X")).at(0);
      auto* xgrad_var = scope_.FindVar(xgrad_name);
      xgrad_var->GetMutable<framework::LoDTensor>()->Resize(xshape_ddim);
    } else {
      op->RuntimeInferShape(scope_, place_, ctx);
    }
  }

655 656 657
  std::vector<std::shared_ptr<ngraph::runtime::Tensor>> t_out = {};
  for (size_t i = 0; i < p_var_out->size(); ++i) {
    auto vo = p_var_out->at(i);
B
baojun 已提交
658 659
    auto* var = scope.FindVar(vo);
    if (var && var->IsType<framework::LoDTensor>()) {
660 661
      auto sp = m_results[i]->get_shape();
      var->GetMutable<framework::LoDTensor>()->Resize(Shape2Ddim(sp));
B
baojun 已提交
662
      auto* tensor_pd = GetMutableLoDTensorOrSelectedRowsValueFromVar(var);
663 664 665 666 667
      auto ng_type = m_results[i]->get_element_type();
      void* pd_arr = tensor_pd->mutable_data(place, ng2pd_type_map[ng_type]);
      std::shared_ptr<ngraph::runtime::Tensor> to =
          backend_->create_tensor(ng_type, sp, pd_arr);
      t_out.emplace_back(to);
B
baojun 已提交
668 669 670 671 672
    } else {
      PADDLE_THROW("Cannot find var or tensor with var name %s", vo);
    }
  }

673
  ng_handle->call(t_out, *p_t_in);
B
baojun 已提交
674 675 676
}  // NgraphEngine::Run
}  // namespace operators
}  // namespace paddle