load_combine_op.cc 6.3 KB
Newer Older
1
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14

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 <fstream>
15
#include "paddle/fluid/framework/data_type.h"
16
#include "paddle/fluid/framework/data_type_transform.h"
Y
Yi Wang 已提交
17 18
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/platform/device_context.h"
19 20 21 22

namespace paddle {
namespace operators {

23
class LoadCombineOp : public framework::OperatorWithKernel {
24
 public:
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext *ctx) const override {}

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext &ctx) const override {
    framework::OpKernelType kt = framework::OpKernelType(
        framework::proto::VarType::FP32, platform::CPUPlace());
    return kt;
  }
};

class LoadCombineOpProtoMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddOutput(
        "Out",
        "(vector) The output LoDTensors that will be read from the input file.")
        .AsDuplicable();
    AddAttr<bool>(
        "load_as_fp16",
        "(boolean, default false)"
        "If true, the tensor will be first loaded and then "
        "converted to float16 data type. Otherwise, the tensor will be "
        "directly loaded without data type conversion.")
        .SetDefault(false);
    AddAttr<std::string>("file_path",
                         "(string) "
                         "LoDTensors will be loaded from \"file_path\".")
        .AddCustomChecker(
            [](const std::string &path) { return !path.empty(); });
    AddAttr<bool>("model_from_memory",
                  "(boolean, default false)"
                  "If true, file_path is in memory, and LoDTensors will be "
                  "loaded directly from memory")
        .SetDefault(false);
    AddComment(R"DOC(
LoadCombine Operator.

LoadCombine operator loads LoDTensor variables from a file, which could be
loaded in memory already. The file should contain one or more LoDTensors
serialized using the SaveCombine operator. The
LoadCombine operator applies a deserialization strategy to appropriately load
the LodTensors, and this strategy complements the serialization strategy used
in the SaveCombine operator. Hence, the LoadCombine operator is tightly coupled
with the SaveCombine operator, and can only deserialize one or more LoDTensors
that were saved using the SaveCombine operator.

)DOC");
  }
};

template <typename DeviceContext, typename T>
class LoadCombineOpKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext &ctx) const override {
    auto place = ctx.GetPlace();
    auto filename = ctx.Attr<std::string>("file_path");
    auto load_as_fp16 = ctx.Attr<bool>("load_as_fp16");
    auto model_from_memory = ctx.Attr<bool>("model_from_memory");
    auto &out_var_names = ctx.Outputs("Out");

88 89 90
    PADDLE_ENFORCE_GT(
        static_cast<int>(out_var_names.size()), 0,
        "The number of output variables should be greater than 0.");
T
Tao Luo 已提交
91
    if (!model_from_memory) {
92
      std::ifstream fin(filename, std::ios::binary);
T
Tao Luo 已提交
93 94
      PADDLE_ENFORCE(static_cast<bool>(fin),
                     "Cannot open file %s for load_combine op", filename);
95
      LoadParamsFromBuffer(ctx, place, &fin, load_as_fp16, out_var_names);
T
Tao Luo 已提交
96 97
    } else {
      PADDLE_ENFORCE(!filename.empty(), "Cannot load file from memory");
P
peizhilin 已提交
98
      std::stringstream fin(filename, std::ios::in | std::ios::binary);
99
      LoadParamsFromBuffer(ctx, place, &fin, load_as_fp16, out_var_names);
T
Tao Luo 已提交
100 101
    }
  }
102

T
Tao Luo 已提交
103
  void LoadParamsFromBuffer(
104
      const framework::ExecutionContext &context, const platform::Place &place,
T
Tao Luo 已提交
105 106
      std::istream *buffer, bool load_as_fp16,
      const std::vector<std::string> &out_var_names) const {
107 108
    platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance();
    auto &dev_ctx = *pool.Get(place);
109
    auto out_vars = context.MultiOutputVar("Out");
110 111

    for (size_t i = 0; i < out_var_names.size(); i++) {
112 113
      PADDLE_ENFORCE(out_vars[i] != nullptr,
                     "Output variable %s cannot be found", out_var_names[i]);
114

115
      auto *tensor = out_vars[i]->GetMutable<framework::LoDTensor>();
D
dzhwinter 已提交
116

117
      // Error checking
118
      PADDLE_ENFORCE(static_cast<bool>(*buffer), "Cannot read more");
D
dzhwinter 已提交
119

120
      // Get data from fin to tensor
T
Tao Luo 已提交
121
      DeserializeFromStream(*buffer, tensor, dev_ctx);
D
dzhwinter 已提交
122

Y
Yu Yang 已提交
123
      auto in_dtype = tensor->type();
124 125 126 127 128 129 130 131 132 133 134 135 136 137
      auto out_dtype =
          load_as_fp16 ? framework::proto::VarType::FP16 : in_dtype;

      if (in_dtype != out_dtype) {
        // convert to float16 tensor
        auto in_kernel_type = framework::OpKernelType(in_dtype, place);
        auto out_kernel_type = framework::OpKernelType(out_dtype, place);
        framework::LoDTensor fp16_tensor;
        // copy LoD info to the new tensor
        fp16_tensor.set_lod(tensor->lod());
        framework::TransDataType(in_kernel_type, out_kernel_type, *tensor,
                                 &fp16_tensor);

        // reset output tensor
138 139
        out_vars[i]->Clear();
        tensor = out_vars[i]->GetMutable<framework::LoDTensor>();
140 141
        tensor->set_lod(fp16_tensor.lod());
        tensor->ShareDataWith(fp16_tensor);
142 143
      }
    }
144 145 146 147
    buffer->peek();
    PADDLE_ENFORCE(buffer->eof(),
                   "You are not allowed to load partial data via "
                   "load_combine_op, use load_op instead.");
148 149 150 151 152
  }
};

}  // namespace operators
}  // namespace paddle
153

154 155 156 157
namespace ops = paddle::operators;

REGISTER_OPERATOR(load_combine, ops::LoadCombineOp,
                  ops::LoadCombineOpProtoMaker);
158 159 160 161 162 163 164

REGISTER_OP_CPU_KERNEL(
    load_combine,
    ops::LoadCombineOpKernel<paddle::platform::CPUDeviceContext, float>,
    ops::LoadCombineOpKernel<paddle::platform::CPUDeviceContext, double>,
    ops::LoadCombineOpKernel<paddle::platform::CPUDeviceContext, int>,
    ops::LoadCombineOpKernel<paddle::platform::CPUDeviceContext, int64_t>);