parallel_do_op.cc 8.6 KB
Newer Older
Y
Yang Yang 已提交
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 <vector>
Y
Yang Yang 已提交
16

Y
Yang Yang 已提交
17 18 19 20 21 22 23 24 25
#include "paddle/framework/executor.h"
#include "paddle/framework/op_registry.h"

namespace paddle {
namespace operators {

constexpr char kInputs[] = "inputs";
constexpr char kParameters[] = "parameters";
constexpr char kPlaces[] = "places";
Y
Yang Yang 已提交
26

Y
Yang Yang 已提交
27
constexpr char kOutputs[] = "outputs";
Y
Yang Yang 已提交
28 29 30
constexpr char kParallelScopes[] = "parallel_scopes";

constexpr char kParallelBlock[] = "sub_block";
Y
Yang Yang 已提交
31

Y
Yang Yang 已提交
32 33
// using ParallelScopeVar = std::vector<framework::Scope *>;
using LoDTensor = framework::LoDTensor;
Y
Yang Yang 已提交
34 35
using OperatorBase = framework::OperatorBase;

Y
Yang Yang 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
void SplitTensorAndMoveTensorToScopes(
    const framework::Scope &scope,
    const std::vector<framework::Scope *> &sub_scopes,
    const std::vector<platform::Place> &places,
    const std::vector<std::string> &names) {
  for (auto &argu : names) {
    auto *var = scope.FindVar(argu);
    const auto &tensor = var->Get<LoDTensor>();
    auto lod_tensors = tensor.SplitLoDTensor(places);

    for (auto &lod : lod_tensors) {
      LOG(INFO) << lod.dims();
    }

    for (int i = 0; i < sub_scopes.size(); ++i) {
      *sub_scopes[i]->Var(argu)->GetMutable<LoDTensor>() = lod_tensors[i];
    }
  }
}

class ParallelDoOp : public framework::OperatorBase {
Y
Yang Yang 已提交
57 58 59 60 61 62 63 64 65
 public:
  ParallelDoOp(const std::string &type,
               const framework::VariableNameMap &inputs,
               const framework::VariableNameMap &outputs,
               const framework::AttributeMap &attrs)
      : OperatorBase(type, inputs, outputs, attrs) {}

  void Run(const framework::Scope &scope,
           const platform::DeviceContext &dev_ctx) const override {
Y
Yang Yang 已提交
66 67
    auto *block = Attr<framework::BlockDescBind *>(kParallelBlock);
    auto *program = block->Program();
Y
Yang Yang 已提交
68

Y
Yang Yang 已提交
69 70 71 72
    // TODO(tonyyang-svail): get places from input
    std::vector<platform::Place> places;
    places.emplace_back(platform::CPUPlace());
    places.emplace_back(platform::CPUPlace());
Y
Yang Yang 已提交
73

Y
Yang Yang 已提交
74 75 76
    auto &sub_scopes = *scope.FindVar(Output(kParallelScopes))
                            ->GetMutable<std::vector<framework::Scope *>>();
    //    std::vector<framework::Scope *> sub_scopes;
Y
Yang Yang 已提交
77 78
    for (int place_idx = 0; place_idx < places.size(); ++place_idx) {
      sub_scopes.push_back(&scope.NewScope());
Y
Yang Yang 已提交
79 80 81 82 83 84 85
    }

    SplitTensorAndMoveTensorToScopes(scope, sub_scopes, places,
                                     Inputs(kInputs));

    for (int place_idx = 0; place_idx < places.size(); ++place_idx) {
      VLOG(3) << "Run " << place_idx;
Y
Yang Yang 已提交
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112

      auto &place = places[place_idx];
      auto *cur_scope = sub_scopes[place_idx];

      // copy parameter
      if (dev_ctx.GetPlace() != place) {
        PADDLE_THROW("Not Implemented");
      }

      // execute
      auto executor = framework::Executor(place);
      executor.Run(*program, cur_scope, block->ID(),
                   false /*create_local_scope*/);
    }

    // merge output
    for (auto &o_name : Outputs(kOutputs)) {
      std::vector<const framework::LoDTensor *> lod_tensors;
      for (auto *sub_scope : sub_scopes) {
        lod_tensors.push_back(&sub_scope->FindVar(o_name)->Get<LoDTensor>());
      }

      auto *lod_tensor_to_be_merged =
          scope.FindVar(o_name)->GetMutable<LoDTensor>();
      lod_tensor_to_be_merged->MergeLoDTensor(lod_tensors, dev_ctx.GetPlace());
    }
  }
Y
Yang Yang 已提交
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
};

class ParallelDoOpProtoMaker : public framework::OpProtoAndCheckerMaker {
 public:
  ParallelDoOpProtoMaker(framework::OpProto *proto,
                         framework::OpAttrChecker *op_checker)
      : OpProtoAndCheckerMaker(proto, op_checker) {
    AddInput(kInputs, "").AsDuplicable();
    AddInput(kParameters, "").AsDuplicable();
    AddInput(kPlaces, "");
    AddOutput(kOutputs, "").AsDuplicable();
    AddOutput(kParallelScopes, "");
    AddAttr<framework::BlockDescBind *>(kParallelBlock, "");
    AddComment(R"DOC(
ParallelDo Operator.
)DOC");
  }
};

Y
Yang Yang 已提交
132 133 134 135 136 137 138 139 140
class ParallelDoGradOp : public OperatorBase {
 public:
  ParallelDoGradOp(const std::string &type,
                   const framework::VariableNameMap &inputs,
                   const framework::VariableNameMap &outputs,
                   const framework::AttributeMap &attrs)
      : OperatorBase(type, inputs, outputs, attrs) {}

  void Run(const framework::Scope &scope,
Y
Yang Yang 已提交
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
           const platform::DeviceContext &dev_ctx) const override {
    auto *block = Attr<framework::BlockDescBind *>(kParallelBlock);
    auto *program = block->Program();

    auto &sub_scopes = scope.FindVar(Input(kParallelScopes))
                           ->Get<std::vector<framework::Scope *>>();

    // TODO(tonyyang-svail): get places from input
    std::vector<platform::Place> places;
    places.emplace_back(platform::CPUPlace());
    places.emplace_back(platform::CPUPlace());

    // feed output@grad
    SplitTensorAndMoveTensorToScopes(scope, sub_scopes, places,
                                     Inputs(framework::GradVarName(kOutputs)));

    for (auto &s : Inputs(framework::GradVarName(kOutputs))) {
      LOG(INFO) << s;
Y
Yang Yang 已提交
159
      LOG(INFO) << scope.FindVar(s)->Get<LoDTensor>();
Y
Yang Yang 已提交
160
      for (auto *sub_scope : sub_scopes) {
Y
Yang Yang 已提交
161
        LOG(INFO) << sub_scope->FindVar(s)->Get<LoDTensor>();
Y
Yang Yang 已提交
162 163
      }
    }
Y
Yang Yang 已提交
164

Y
Yang Yang 已提交
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
    // exe run
    for (int place_idx = 0; place_idx < places.size(); ++place_idx) {
      VLOG(3) << "Run " << place_idx;

      auto &place = places[place_idx];
      auto *cur_scope = sub_scopes[place_idx];

      // copy parameter
      if (dev_ctx.GetPlace() != place) {
        PADDLE_THROW("Not Implemented");
      }

      // execute
      auto executor = framework::Executor(place);
      executor.Run(*program, cur_scope, block->ID(),
                   false /*create_local_scope*/);
    }

    // merge grad
  }
Y
Yang Yang 已提交
185 186
};

Y
Yang Yang 已提交
187 188 189 190 191 192 193
class ParallelDoGradOpDescMaker : public framework::SingleGradOpDescMaker {
 public:
  using framework::SingleGradOpDescMaker::SingleGradOpDescMaker;

 protected:
  virtual std::unique_ptr<framework::OpDescBind> Apply() const {
    auto *grad = new framework::OpDescBind();
Y
Yang Yang 已提交
194
    grad->SetType("parallel_do_grad");
Y
Yang Yang 已提交
195
    for (auto &input_param : this->InputNames()) {
Y
Yang Yang 已提交
196
      LOG(INFO) << input_param;
Y
Yang Yang 已提交
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
      grad->SetInput(input_param, this->Input(input_param));
      grad->SetOutput(framework::GradVarName(input_param),
                      this->InputGrad(input_param));
    }

    for (auto &output_param : this->OutputNames()) {
      if (output_param == kParallelScopes) {
        grad->SetInput(output_param, this->Output(output_param));
        grad->SetInput(framework::GradVarName(output_param),
                       this->Output(output_param));
      } else {
        grad->SetInput(output_param, this->Output(output_param));
        grad->SetInput(framework::GradVarName(output_param),
                       this->OutputGrad(output_param));
      }
    }
    grad->SetAttrMap(this->Attrs());
    grad->SetBlockAttr(kParallelBlock, *grad_block_[0]);

    return std::unique_ptr<framework::OpDescBind>(grad);
  }
};

class ParallelDoGradOpShapeInference : public framework::InferShapeBase {
 public:
  void operator()(framework::InferShapeContext *ctx) const override {
Y
Yang Yang 已提交
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
    std::vector<std::string> input{kParameters, kInputs};
    std::vector<std::string> output{kOutputs};
    for (auto &s : input) {
      PADDLE_ENFORCE(ctx->HasInputs(s));
      PADDLE_ENFORCE(ctx->HasOutputs(framework::GradVarName(s)),
                     "Cannot find the gradient variable %s",
                     framework::GradVarName(s));
    }
    for (auto &s : output) {
      PADDLE_ENFORCE(ctx->HasInputs(s));
    }
    for (auto &s : input) {
      ctx->SetOutputsDim(framework::GradVarName(s), ctx->GetInputsDim(s));
    }
    if (ctx->HasInputs(kParameters)) {
      PADDLE_ENFORCE(ctx->HasOutputs(framework::GradVarName(kParameters)));
      ctx->SetOutputsDim(framework::GradVarName(kParameters),
                         ctx->GetInputsDim(kParameters));
    }
Y
Yang Yang 已提交
242 243 244 245 246 247 248 249 250 251 252
  }
};

}  // namespace operators
}  // namespace paddle

REGISTER_OPERATOR(parallel_do, paddle::operators::ParallelDoOp,
                  paddle::operators::ParallelDoOpProtoMaker,
                  paddle::operators::ParallelDoGradOpDescMaker);
REGISTER_OPERATOR(parallel_do_grad, paddle::operators::ParallelDoGradOp,
                  paddle::operators::ParallelDoGradOpShapeInference);