executor.cc 2.3 KB
Newer Older
Q
qijun 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

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/framework/executor.h"
Q
qijun 已提交
16
#include <memory>
Y
Yang Yang 已提交
17
#include <vector>
Q
qijun 已提交
18
#include "paddle/framework/op_registry.h"
Q
qijun 已提交
19
#include "paddle/framework/scope.h"
Q
qijun 已提交
20 21 22 23

namespace paddle {
namespace framework {

Q
qijun 已提交
24
Executor::Executor(const std::vector<platform::Place>& places) {
Q
qijun 已提交
25
  device_contexts_.resize(places.size());
Q
qijun 已提交
26
  for (size_t i = 0; i < places.size(); i++) {
Q
qijun 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39
    if (platform::is_cpu_place(places[i])) {
      device_contexts_[i] = platform::DeviceContextManager::Get()
                                ->GetDeviceContext<platform::CPUPlace>(
                                    boost::get<platform::CPUPlace>(places[i]));
    } else {
#ifndef PADDLE_ONLY_CPU
      device_contexts_[i] = platform::DeviceContextManager::Get()
                                ->GetDeviceContext<platform::GPUPlace>(
                                    boost::get<platform::GPUPlace>(places[i]));
#else
      PADDLE_THROW("'GPUPlace' is not supported in CPU only device.");
#endif
    }
Q
qijun 已提交
40 41 42
  }
}

Q
qijun 已提交
43 44
void Executor::Run(const ProgramDesc& pdesc, Scope* scope,
                   std::vector<Tensor>* outputs) {
Q
qijun 已提交
45
  // operators running
Y
Yang Yang 已提交
46 47 48
  // TODO(tonyyang-svail):
  //    - only runs the first block
  //    - only runs on the first device
Q
qijun 已提交
49 50
  Scope& local_scope = scope->NewScope();

Y
Yang Yang 已提交
51
  auto& block = pdesc.blocks(0);
Q
qijun 已提交
52
  auto& device_context = device_contexts_[0];
Y
Yang Yang 已提交
53 54

  for (auto& var : block.vars()) {
Q
qijun 已提交
55
    local_scope.NewVar(var.name());
Y
Yang Yang 已提交
56 57 58 59 60
  }

  // std::vector<op_ptr> ops;
  for (auto& op_desc : block.ops()) {
    auto op = framework::OpRegistry::CreateOp(op_desc);
Q
qijun 已提交
61 62
    // InferShape is now doing inside Run method.
    op->Run(local_scope, *device_context);
Y
Yang Yang 已提交
63 64 65
  }

  // TODO(tonyyang-svail): need to test gpu device
Q
qijun 已提交
66 67
  for (auto device_context : device_contexts_) {
    device_context->Wait();
Q
qijun 已提交
68
  }
Q
qijun 已提交
69 70 71 72
}

}  // namespace framework
}  // namespace paddle