tensor_array_read_write_op.cc 7.7 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Y
Yu Yang 已提交
2

L
Luo Tao 已提交
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
Y
Yu Yang 已提交
6

L
Luo Tao 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
Y
Yu Yang 已提交
8

L
Luo Tao 已提交
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. */
Y
Yi Wang 已提交
14 15
#include "paddle/fluid/operators/array_operator.h"
#include "paddle/fluid/operators/detail/safe_ref.h"
Y
Yu Yang 已提交
16 17 18
namespace paddle {
namespace operators {

Y
Yang Yu 已提交
19
class WriteToArrayOp : public ArrayOp {
Y
Yu Yang 已提交
20 21 22 23 24
 public:
  WriteToArrayOp(const std::string &type,
                 const framework::VariableNameMap &inputs,
                 const framework::VariableNameMap &outputs,
                 const framework::AttributeMap &attrs)
Y
Yang Yu 已提交
25
      : ArrayOp(type, inputs, outputs, attrs) {}
Y
Yu Yang 已提交
26

27 28 29
 private:
  void RunImpl(const framework::Scope &scope,
               const platform::Place &place) const override {
Y
Yu Yang 已提交
30
    auto *x = scope.FindVar(Input("X"));
31
    if (x == nullptr) return;
Y
Yu Yang 已提交
32
    auto &x_tensor = x->Get<framework::LoDTensor>();
D
dzhwinter 已提交
33
    size_t offset = GetOffset(scope, place);
Y
Yu Yang 已提交
34 35 36
    auto *out =
        scope.FindVar(Output("Out"))->GetMutable<framework::LoDTensorArray>();
    if (offset >= out->size()) {
M
minqiyang 已提交
37 38
      VLOG(10) << "Resize " << Output("Out") << " from " << out->size()
               << " to " << offset + 1;
Y
Yu Yang 已提交
39 40
      out->resize(offset + 1);
    }
41 42
    auto *out_tensor = &out->at(offset);
    out_tensor->set_lod(x_tensor.lod());
43
    if (x_tensor.memory_size() > 0) {
Y
Yang Yu 已提交
44 45 46
      platform::DeviceContextPool &pool =
          platform::DeviceContextPool::Instance();
      auto &dev_ctx = *pool.Get(place);
D
dzhwinter 已提交
47

Y
Yi Wang 已提交
48
      TensorCopy(x_tensor, place, dev_ctx, out_tensor);
49
    } else {
M
minqiyang 已提交
50 51 52
      VLOG(10) << "WARNING: The input tensor 'x_tensor' holds no memory, so "
                  "nothing has been written to output array["
               << offset << "].";
53
    }
Y
Yu Yang 已提交
54 55 56 57 58
  }
};

class WriteToArrayOpProtoMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
59
  void Make() override {
Y
Yu Yang 已提交
60 61 62 63 64 65
    AddInput("X", "(LoDTensor) the tensor will be written to tensor array");
    AddInput(
        "I",
        "(Tensor) the subscript index in tensor array. The number of element "
        "should be 1");
    AddOutput("Out", "(TensorArray) the tensor array will be written");
66 67
    AddComment(R"DOC(
WriteToArray Operator.
Y
Yu Yang 已提交
68

69 70 71
This operator writes a LoDTensor to a LoDTensor array.

Assume $T$ is LoDTensor, $i$ is the subscript of the array, and $A$ is the array. The
Y
Yu Yang 已提交
72 73
equation is

74 75
$$A[i] = T$$

Y
Yu Yang 已提交
76 77 78 79 80 81 82 83 84 85
)DOC");
  }
};

class WriteToArrayInferShape : public framework::InferShapeBase {
 public:
  void operator()(framework::InferShapeContext *context) const override {
    PADDLE_ENFORCE(context->HasInput("I"), "Must set the subscript index");
    PADDLE_ENFORCE_EQ(framework::product(context->GetInputDim("I")), 1,
                      "The number of element of subscript index must be 1");
86 87 88
    if (!context->HasInput("X")) {
      return;
    }
Y
Yu Yang 已提交
89 90 91 92 93 94 95 96 97 98 99 100 101 102
    PADDLE_ENFORCE(context->HasOutput("Out"), NotHasOutError());
    context->SetOutputDim("Out", context->GetInputDim("X"));
  }

 protected:
  virtual const char *NotHasXError() const { return "Must set the lod tensor"; }

  virtual const char *NotHasOutError() const {
    return "Must set the lod tensor array";
  }
};

class WriteToArrayInferVarType : public framework::VarTypeInference {
 public:
M
minqiyang 已提交
103 104 105
  void operator()(framework::InferVarTypeContext *ctx) const override {
    auto x_name = ctx->Input("X")[0];
    auto out_name = ctx->Output("Out")[0];
M
minqiyang 已提交
106
    VLOG(10) << "Set Variable " << out_name << " as LOD_TENSOR_ARRAY";
M
minqiyang 已提交
107 108 109
    ctx->SetType(out_name, framework::proto::VarType::LOD_TENSOR_ARRAY);
    if (ctx->HasVar(x_name)) {
      ctx->SetDataType(out_name, ctx->GetDataType(x_name));
110
    }
Y
Yu Yang 已提交
111 112 113
  }
};

Y
Yang Yu 已提交
114
class ReadFromArrayOp : public ArrayOp {
Y
Yu Yang 已提交
115 116 117 118 119
 public:
  ReadFromArrayOp(const std::string &type,
                  const framework::VariableNameMap &inputs,
                  const framework::VariableNameMap &outputs,
                  const framework::AttributeMap &attrs)
Y
Yang Yu 已提交
120
      : ArrayOp(type, inputs, outputs, attrs) {}
121 122 123 124

 private:
  void RunImpl(const framework::Scope &scope,
               const platform::Place &place) const override {
Y
Yu Yang 已提交
125 126 127 128 129
    auto *x = scope.FindVar(Input("X"));
    PADDLE_ENFORCE(x != nullptr, "X must be set");
    auto &x_array = x->Get<framework::LoDTensorArray>();
    auto *out = scope.FindVar(Output("Out"));
    PADDLE_ENFORCE(out != nullptr, "Out must be set");
D
dzhwinter 已提交
130
    size_t offset = GetOffset(scope, place);
131
    if (offset < x_array.size()) {
Y
Refine  
Yang Yu 已提交
132
      auto *out_tensor = out->GetMutable<framework::LoDTensor>();
Y
Yang Yu 已提交
133 134 135
      platform::DeviceContextPool &pool =
          platform::DeviceContextPool::Instance();
      auto &dev_ctx = *pool.Get(place);
Y
Yi Wang 已提交
136
      framework::TensorCopy(x_array[offset], place, dev_ctx, out_tensor);
137 138
      out_tensor->set_lod(x_array[offset].lod());
    } else {
M
minqiyang 已提交
139
      VLOG(10) << "offset " << offset << " >= " << x_array.size();
140
    }
Y
Yu Yang 已提交
141 142 143 144 145
  }
};

class ReadFromArrayProtoMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
146
  void Make() override {
Y
Yu Yang 已提交
147 148 149 150 151
    AddInput("X", "(TensorArray) the array will be read from.");
    AddInput("I",
             "(Tensor) the subscript index in tensor array. The number of "
             "element should be 1");
    AddOutput("Out", "(LoDTensor) the tensor will be read from.");
152 153
    AddComment(R"DOC(
ReadFromArray Operator.
Y
Yu Yang 已提交
154

155 156 157
Read a LoDTensor from a LoDTensor Array.

Assume $T$ is LoDTensor, $i$ is the subscript of the array, and $A$ is the array. The
Y
Yu Yang 已提交
158 159
equation is

160 161
$$T = A[i]$$

Y
Yu Yang 已提交
162 163 164 165 166
)DOC");
  }
};

class ReadFromArrayInferShape : public WriteToArrayInferShape {
C
chengduo 已提交
167 168 169 170 171 172 173 174 175 176 177 178 179
 public:
  void operator()(framework::InferShapeContext *context) const override {
    WriteToArrayInferShape::operator()(context);
    if (!context->HasInput("X")) {
      return;
    }

    // FIXME: just for compile time.
    if (!context->IsRuntime()) {
      context->ShareLoD("X", /*->*/ "Out");
    }
  }

Y
Yu Yang 已提交
180 181 182 183 184 185 186 187 188 189 190 191 192 193
 protected:
  const char *NotHasXError() const override {
    return "The input array X must be set";
  }
  const char *NotHasOutError() const override {
    return "The output tensor out must be set";
  }
};

class WriteToArrayGradMaker : public framework::SingleGradOpDescMaker {
 public:
  using framework::SingleGradOpDescMaker::SingleGradOpDescMaker;

 protected:
Y
Yu Yang 已提交
194 195
  std::unique_ptr<framework::OpDesc> Apply() const override {
    auto *grad_op = new framework::OpDesc();
Y
Yu Yang 已提交
196 197 198 199 200
    grad_op->SetType("read_from_array");
    grad_op->SetInput("I", Input("I"));
    grad_op->SetInput("X", OutputGrad("Out"));
    grad_op->SetOutput("Out", InputGrad("X"));
    grad_op->SetAttrMap(Attrs());
Y
Yu Yang 已提交
201
    return std::unique_ptr<framework::OpDesc>(grad_op);
Y
Yu Yang 已提交
202 203 204 205 206 207 208 209
  }
};

class ReadFromArrayGradMaker : public framework::SingleGradOpDescMaker {
 public:
  using framework::SingleGradOpDescMaker::SingleGradOpDescMaker;

 protected:
Y
Yu Yang 已提交
210 211
  std::unique_ptr<framework::OpDesc> Apply() const override {
    auto *grad_op = new framework::OpDesc();
Y
Yu Yang 已提交
212 213 214 215 216
    grad_op->SetType("write_to_array");
    grad_op->SetInput("I", Input("I"));
    grad_op->SetInput("X", OutputGrad("Out"));
    grad_op->SetOutput("Out", InputGrad("X"));
    grad_op->SetAttrMap(Attrs());
Y
Yu Yang 已提交
217
    return std::unique_ptr<framework::OpDesc>(grad_op);
Y
Yu Yang 已提交
218 219 220 221 222 223 224 225 226 227 228 229 230
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OPERATOR(write_to_array, ops::WriteToArrayOp,
                  ops::WriteToArrayInferShape, ops::WriteToArrayOpProtoMaker,
                  ops::WriteToArrayGradMaker, ops::WriteToArrayInferVarType);
REGISTER_OPERATOR(read_from_array, ops::ReadFromArrayOp,
                  ops::ReadFromArrayInferShape, ops::ReadFromArrayProtoMaker,
                  ops::ReadFromArrayGradMaker);