fetch_op.cc 2.3 KB
Newer Older
Q
qijun 已提交
1 2
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

Y
Yu Yang 已提交
3 4 5
   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
Q
qijun 已提交
6

Y
Yu Yang 已提交
7
   http://www.apache.org/licenses/LICENSE-2.0
Q
qijun 已提交
8

Y
Yu Yang 已提交
9 10 11 12 13
   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. */
Q
qijun 已提交
14

Y
Yu Yang 已提交
15 16
#include "paddle/framework/feed_fetch_type.h"
#include "paddle/framework/op_registry.h"
Q
qijun 已提交
17 18 19 20

namespace paddle {
namespace operators {

Y
Yu Yang 已提交
21
class FetchOp : public framework::OperatorBase {
Q
qijun 已提交
22
 public:
Y
Yu Yang 已提交
23 24 25 26
  FetchOp(const std::string &type, const framework::VariableNameMap &inputs,
          const framework::VariableNameMap &outputs,
          const framework::AttributeMap &attrs)
      : OperatorBase(type, inputs, outputs, attrs) {}
Q
qijun 已提交
27

Y
Yu Yang 已提交
28 29 30 31 32 33 34
  void Run(const framework::Scope &scope,
           const platform::DeviceContext &dev_ctx) const override {
    auto fetch_var_name = Input("Input");
    auto *fetch_var = scope.FindVar(fetch_var_name);
    PADDLE_ENFORCE(fetch_var != nullptr,
                   "Cannot find fetch variable in scope, fetch_var_name is %s",
                   fetch_var_name);
Q
qijun 已提交
35

Y
Yu Yang 已提交
36 37 38 39 40
    auto out_name = this->Output("Out");
    auto *out_var = scope.FindVar(out_name);
    PADDLE_ENFORCE(out_var != nullptr,
                   "Cannot find out_var in scope, out_var_name is %s",
                   out_name);
Q
qijun 已提交
41

Y
Yu Yang 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54
    auto col = static_cast<size_t>(Attr<int>("col"));

    auto *fetch_list = out_var->GetMutable<framework::FeedFetchList>();
    auto &src_item = fetch_var->Get<framework::FeedFetchType>();

    if (col >= fetch_list->size()) {
      fetch_list->resize(col + 1);
    }
    auto &dst_item = fetch_list->at(col);

    // FIXME(yuyang18): Should we assume the fetch operator always generate
    // CPU outputs?
    dst_item.CopyFromTensor(src_item, platform::CPUPlace(), dev_ctx);
Q
qijun 已提交
55 56 57 58 59 60
  }
};

}  // namespace operators
}  // namespace paddle

Y
Yu Yang 已提交
61 62 63 64
// We do not need to register OpInfoMaker,
// since fetch operator will not be used by end users directly
REGISTER_OPERATOR(fetch, paddle::operators::FetchOp,
                  paddle::framework::EmptyGradOpMaker);