You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

storage.cc 2.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /**
  2. * Copyright 2020 Huawei Technologies Co., Ltd
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "tools/common/storage.h"
  17. #include <sys/stat.h>
  18. #include <unistd.h>
  19. #include "flatbuffers/flatbuffers.h"
  20. #include "src/common/log_adapter.h"
  21. #include "src/common/file_utils.h"
  22. namespace mindspore {
  23. namespace lite {
  24. int Storage::Save(const schema::MetaGraphT &graph, const std::string &outputPath) {
  25. flatbuffers::FlatBufferBuilder builder(1024);
  26. auto offset = schema::MetaGraph::Pack(builder, &graph);
  27. builder.Finish(offset);
  28. int size = builder.GetSize();
  29. auto content = builder.GetBufferPointer();
  30. if (content == nullptr) {
  31. MS_LOG(ERROR) << "GetBufferPointer nullptr";
  32. return RET_ERROR;
  33. }
  34. if (access((outputPath + ".ms").c_str(), F_OK) == 0) {
  35. chmod((outputPath + ".ms").c_str(), S_IWUSR);
  36. }
  37. std::ofstream output(outputPath + ".ms", std::ofstream::binary);
  38. if (!output.is_open()) {
  39. MS_LOG(ERROR) << "Can not open output file: " << outputPath << ".ms";
  40. return RET_ERROR;
  41. }
  42. output.write((const char *)content, size);
  43. output.close();
  44. chmod((outputPath + ".ms").c_str(), S_IRUSR);
  45. return RET_OK;
  46. }
  47. schema::MetaGraphT *Storage::Load(const std::string &inputPath) {
  48. size_t size;
  49. auto buf = ReadFile(inputPath.c_str(), &size);
  50. if (buf == nullptr) {
  51. MS_LOG(ERROR) << "the file buffer is nullptr";
  52. return nullptr;
  53. }
  54. flatbuffers::Verifier verify((const uint8_t *)buf, size);
  55. if (false == schema::VerifyMetaGraphBuffer(verify)) {
  56. MS_LOG(ERROR) << "the buffer is invalid and fail to create meta graph";
  57. return nullptr;
  58. }
  59. auto graphDefT = schema::UnPackMetaGraph(buf);
  60. return graphDefT.release();
  61. }
  62. } // namespace lite
  63. } // namespace mindspore