cond_op.cc 8.7 KB
Newer Older
Z
cond op  
zchen0211 已提交
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/operators/cond_op.h"
Z
zchen0211 已提交
16 17 18

#include "paddle/operators/gather.h"
#include "paddle/operators/scatter.h"
Z
cond op  
zchen0211 已提交
19 20 21 22

namespace paddle {
namespace operators {

Z
zchen0211 已提交
23 24 25
using Scope = framework::Scope;
using Variable = framework::Variable;
using Tensor = framework::Tensor;
Z
zchen0211 已提交
26
using LoDTensor = framework::LoDTensor;
Z
zchen0211 已提交
27 28
using DDim = framework::DDim;

29
framework::Scope& CondOp::AddSubScope(const Scope& scope) const {
Z
zchen0211 已提交
30
  auto sub_scopes_var = scope.FindVar("SubScopes");
31 32
  PADDLE_ENFORCE_NOT_NULL(sub_scopes_var,
                          "Output(SubScopes) of CondOp should not be null.");
Z
zchen0211 已提交
33 34 35
  auto sub_scopes = sub_scopes_var->GetMutable<std::vector<Scope*>>();
  auto& sub_scope = scope.NewScope();
  sub_scopes->push_back(&sub_scope);
36
  return sub_scope;
Z
zchen0211 已提交
37 38
}

39 40 41 42 43 44 45 46 47
std::vector<framework::Scope*>& CondOp::GetSubScopes(
    const framework::Scope& scope) const {
  auto sub_scopes_var = scope.FindVar("SubScopes");
  PADDLE_ENFORCE_NOT_NULL(sub_scopes_var,
                          "Output(SubScopes) of CondOp should not be null.");
  return *sub_scopes_var->GetMutable<std::vector<framework::Scope*>>();
}

LoDTensor& CondOp::AddIndexTensor(const Scope& scope) const {
Z
zchen0211 已提交
48
  auto index_tensors_var = scope.FindVar("IndexTensors");
49 50
  PADDLE_ENFORCE_NOT_NULL(index_tensors_var,
                          "Output(IndexTensors) of CondOp should not be null.");
Z
zchen0211 已提交
51 52 53
  auto& index_tensors =
      *index_tensors_var->GetMutable<std::vector<LoDTensor>>();
  index_tensors.push_back(LoDTensor());
54
  return index_tensors.back();
Z
zchen0211 已提交
55 56
}

57 58
std::vector<framework::LoDTensor>& CondOp::GetIndexTensors(
    const framework::Scope& scope) const {
Z
zchen0211 已提交
59
  auto* index_tensors_var = scope.FindVar("IndexTensors");
60 61
  PADDLE_ENFORCE_NOT_NULL(index_tensors_var,
                          "Output(IndexTensors) of CondOp should not be null.");
62 63
  return *index_tensors_var->GetMutable<std::vector<framework::LoDTensor>>();
}
Z
zchen0211 已提交
64

65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
void CondOp::PrepareDataForSubnet(
    const framework::Scope& scope,
    const platform::DeviceContext& dev_ctx) const {
  PADDLE_ENFORCE(!Inputs("Xs").empty(), "Inputs(Xs) of CondOp can't be empty.");

  for (int i = 0; i < BRANCH_NUM; ++i) {
    // Create two sub scopes for true and false branches
    //   sub_scopes[0] for the true branch
    //   sub_scopes[1] for the false branch
    AddSubScope(scope);
    // Create two tensors for true and false indices:
    //   index_tensors[0] for the true branch
    //   index_tensors[1] for the false branch
    AddIndexTensor(scope);
  }

  Variable* cond_var = scope.FindVar(Input("Cond"));
82 83
  PADDLE_ENFORCE_NOT_NULL(cond_var,
                          "Input(Cond) of CondOp should not be null.");
Z
zchen0211 已提交
84
  const LoDTensor* cond = cond_var->GetMutable<LoDTensor>();
Z
zchen0211 已提交
85

86 87 88 89 90
  // get the true/false index at runtime according to cond tensor
  // index_vectors[0]: vector<int>, contains all index for cond[i] == true
  // index_vectors[1]: vector<int>, contains all index for cond[i] == false
  std::vector<std::vector<int>> index_vectors;
  index_vectors.resize(BRANCH_NUM);
Z
zchen0211 已提交
91 92 93 94

  const int* cond_data = cond->data<int>();
  for (int i = 0; i < cond->dims()[0]; ++i) {
    if (cond_data[i])
95
      index_vectors[TRUE_BRANCH].push_back(i);
Z
zchen0211 已提交
96
    else
97
      index_vectors[FALSE_BRANCH].push_back(i);
Z
zchen0211 已提交
98 99
  }

100 101 102 103 104 105 106 107
  // put index_vectors[0] and index_vectors[1] into two tensors:
  // index_tensors[0] and index_tensors[1]
  std::vector<framework::LoDTensor>& index_tensors = GetIndexTensors(scope);
  std::vector<framework::Scope*>& sub_scopes = GetSubScopes(scope);

  for (int i = 0; i < BRANCH_NUM; ++i) {
    DDim dim = {static_cast<int64_t>(index_vectors[i].size())};
    int* index_tensor_data_ptr =
Z
zchen0211 已提交
108
        index_tensors[i].mutable_data<int>(dim, platform::CPUPlace());
109 110
    memcpy(index_tensor_data_ptr, index_vectors[i].data(),
           dim[0] * sizeof(int));
Z
zchen0211 已提交
111 112
  }

113 114 115 116 117
  // create input in subscopes according to index_vectors
  for (auto& input : Inputs("Xs")) {
    Variable* var_parent = scope.FindVar(input);
    PADDLE_ENFORCE_NOT_NULL(var_parent);
    const auto* tensor_parent = &var_parent->Get<LoDTensor>();
Z
zchen0211 已提交
118

119 120 121 122
    for (int i = 0; i < BRANCH_NUM; ++i) {
      Variable* var_child = sub_scopes[i]->FindVar(input);
      PADDLE_ENFORCE_NOT_NULL(var_child);
      auto* tensor_child = var_child->GetMutable<LoDTensor>();
Z
zchen0211 已提交
123 124

      // Resize child
125 126
      DDim dim = tensor_parent->dims();
      dim[0] = index_tensors[i].dims()[0];
Z
zchen0211 已提交
127 128
      tensor_child->mutable_data<float>(dim, platform::CPUPlace());

129
      CPUGather<float>(dev_ctx, *tensor_parent, index_tensors[i], tensor_child);
Z
zchen0211 已提交
130 131 132
    }
  }

133 134 135 136 137 138 139
  // create output_tensors in subscope for sub_net
  for (int i = 0; i < BRANCH_NUM; ++i) {
    for (auto& output : (*sub_net_op_[i]).Outputs()) {
      for (auto& var_name : output.second) {
        sub_scopes[i]->NewVar(var_name);
      }
    }
Z
zchen0211 已提交
140
  }
141
}
Z
zchen0211 已提交
142

143 144 145 146 147 148 149
void CondOp::MergeDataFromSubnet(const framework::Scope& scope,
                                 const platform::DeviceContext& dev_ctx) const {
  std::vector<framework::Scope*>& sub_scopes = GetSubScopes(scope);
  const std::vector<framework::LoDTensor>& index_tensors =
      GetIndexTensors(scope);

  // Infer the output dim, out_dim[0] = true_dim[0] + false_dim[0]
150 151
  PADDLE_ENFORCE(!Outputs("Outs").empty(),
                 "Outputs(Outs) of CondOp can't be empty.");
152 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
  for (auto& output : Outputs("Outs")) {
    const LoDTensor* tensor_t_out =
        &sub_scopes[TRUE_BRANCH]->FindVar(output)->Get<LoDTensor>();
    PADDLE_ENFORCE_NOT_NULL(tensor_t_out, "True output should not be NULL");
    const LoDTensor* tensor_f_out =
        &sub_scopes[FALSE_BRANCH]->FindVar(output)->Get<LoDTensor>();
    PADDLE_ENFORCE_NOT_NULL(tensor_f_out, "False output should not be NULL");

    auto* var_out = scope.FindVar(output);
    PADDLE_ENFORCE_NOT_NULL(var_out, "Output not found");
    LoDTensor* tensor_out = var_out->GetMutable<LoDTensor>();
    PADDLE_ENFORCE_NOT_NULL(tensor_t_out,
                            "True output tensor should not be NULL");

    DDim true_dim = tensor_t_out->dims();
    DDim false_dim = tensor_f_out->dims();
    true_dim[0] = 0;
    false_dim[0] = 0;
    PADDLE_ENFORCE_EQ(true_dim, false_dim,
                      "Outputs not of the same shape except the first dim");

    DDim out_dim = tensor_t_out->dims();
    out_dim[0] = tensor_t_out->dims()[0] + tensor_f_out->dims()[0];
    tensor_out->Resize(out_dim);
    tensor_out->mutable_data<float>(platform::CPUPlace());
  }
Z
zchen0211 已提交
178

179 180 181 182 183 184 185 186 187 188 189
  // merge output results:
  // output_tensor = true_output_tensor + false_output_tensor
  for (auto& output : Outputs("Outs")) {
    Variable* var_parent = scope.FindVar(output);
    PADDLE_ENFORCE_NOT_NULL(var_parent);
    auto* tensor_parent = var_parent->GetMutable<LoDTensor>();

    for (int i = 0; i < BRANCH_NUM; ++i) {
      Variable* var_child = sub_scopes[i]->FindVar(output);
      PADDLE_ENFORCE_NOT_NULL(var_child);
      auto* tensor_child = &var_child->Get<LoDTensor>();
190
      ScatterAssign<float>(dev_ctx, *tensor_child, index_tensors[i],
Z
zchen0211 已提交
191 192 193 194 195
                           tensor_parent);
    }
  }
}

196 197 198 199 200 201 202 203 204 205
void CondOp::Run(const Scope& scope,
                 const platform::DeviceContext& dev_ctx) const {
  PrepareDataForSubnet(scope, dev_ctx);
  std::vector<framework::Scope*>& sub_scopes = GetSubScopes(scope);
  for (int i = 0; i < BRANCH_NUM; ++i) {
    sub_net_op_[i]->Run(*sub_scopes[i], dev_ctx);
  }
  MergeDataFromSubnet(scope, dev_ctx);
}

Z
zchen0211 已提交
206
class CondOpProtoAndCheckerMaker : public framework::OpProtoAndCheckerMaker {
Z
cond op  
zchen0211 已提交
207
 public:
Z
zchen0211 已提交
208 209
  CondOpProtoAndCheckerMaker(framework::OpProto* proto,
                             framework::OpAttrChecker* op_checker)
Z
cond op  
zchen0211 已提交
210 211 212 213 214 215 216 217 218 219
      : OpProtoAndCheckerMaker(proto, op_checker) {
    AddInput("Cond", "The condition, which is a bool vector");
    AddInput("Xs", "Inputs of Subnets").AsDuplicable();
    AddOutput("Outs", "Outputs of Cond_Op after merge").AsDuplicable();

    AddOutput("SubScopes", "sub scopes for true and false branches");
    AddOutput("IndexTensors", "Index Tensors contains indices for true/false");

    AddComment(R"DOC(
Sample dependent Cond Operator:
Z
zchen0211 已提交
220
Given Cond[i] as a 1/0 vector to indicate true/false
Q
Qiao Longfei 已提交
221
The equation is:
Z
zchen0211 已提交
222
Out[i] = subnet_t[i], if Cond[i] == true
Z
cond op  
zchen0211 已提交
223 224 225 226 227 228 229 230
Out[i] = subnet_t[i], if Cond[i] == false
)DOC");
  }
};

}  // namespace operators
}  // namespace paddle

Z
zchen0211 已提交
231
REGISTER_OP_WITHOUT_GRADIENT(cond, paddle::operators::CondOp,
Z
cond op  
zchen0211 已提交
232
                             paddle::operators::CondOpProtoAndCheckerMaker);