program.cc 2.3 KB
Newer Older
S
superjomn 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// 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/fluid/lite/core/program.h"
S
Superjomn 已提交
16 17 18 19 20
#include "paddle/fluid/lite/core/optimizer.h"

namespace paddle {
namespace lite {

S
Superjomn 已提交
21
void RuntimeProgram::PersistModel(const std::string &dir,
S
Superjomn 已提交
22 23
                                  const framework::proto::ProgramDesc &desc) {
  // Persist model.
S
Superjomn 已提交
24
  const std::string model_path = dir + "/__model__";
S
Superjomn 已提交
25 26
  std::ofstream model_ostream(model_path, std::ios_base::binary);
  CHECK(model_ostream.is_open());
S
Superjomn 已提交
27
  const std::string pb_str = SerializeProgram(desc);
S
Superjomn 已提交
28
  model_ostream.write(pb_str.c_str(), pb_str.size());
S
Superjomn 已提交
29
  model_ostream.close();
S
Superjomn 已提交
30 31 32 33

  // Persist params.
  framework::proto::ProgramDesc latest_program;
  latest_program.ParseFromString(pb_str);
S
Superjomn 已提交
34
  SaveParams(dir, latest_program);
S
Superjomn 已提交
35 36
}

S
Superjomn 已提交
37
std::string RuntimeProgram::SerializeProgram(
S
Superjomn 已提交
38 39 40 41
    const framework::proto::ProgramDesc &desc) {
  auto program_dummy = desc;
  program_dummy.mutable_blocks(0)->clear_ops();
  for (auto &node : instructions_) {
Y
Yan Chunwei 已提交
42 43 44
    pb::OpDesc pb_desc;
    TransformOpDescCppToPb(*node.op()->op_info(), &pb_desc);
    pb_desc.SetAttr(kKernelTypeAttr, node.kernel()->SerializedKernelType());
S
Superjomn 已提交
45
    // append new opdesc
Y
Yan Chunwei 已提交
46
    *program_dummy.mutable_blocks(0)->add_ops() = *pb_desc.Proto();
S
Superjomn 已提交
47 48 49 50
  }
  return program_dummy.SerializeAsString();
}

S
Superjomn 已提交
51 52 53
void RuntimeProgram::SaveParams(const std::string &dir,
                                const framework::proto::ProgramDesc &desc) {
  CHECK(exec_scope_);
S
Superjomn 已提交
54
  for (auto &item : desc.blocks(0).vars()) {
S
Superjomn 已提交
55
    const std::string path = dir + "/" + item.name();
S
Superjomn 已提交
56 57
    if (item.name() == "feed" || item.name() == "fetch") continue;
    if (item.persistable()) {
S
Superjomn 已提交
58 59 60
      std::ofstream file(path, std::ios::binary);
      SerializeTensor(file, *exec_scope_, item.name());
      file.close();
S
Superjomn 已提交
61 62 63 64 65 66
    }
  }
}

}  // namespace lite
}  // namespace paddle