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.3 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. schema::FinishMetaGraphBuffer(builder, offset);
  29. int size = builder.GetSize();
  30. auto content = builder.GetBufferPointer();
  31. if (content == nullptr) {
  32. MS_LOG(ERROR) << "GetBufferPointer nullptr";
  33. return RET_ERROR;
  34. }
  35. if (access((outputPath + ".ms").c_str(), F_OK) == 0) {
  36. chmod((outputPath + ".ms").c_str(), S_IWUSR);
  37. }
  38. std::ofstream output(outputPath + ".ms", std::ofstream::binary);
  39. if (!output.is_open()) {
  40. MS_LOG(ERROR) << "Can not open output file: " << outputPath << ".ms";
  41. return RET_ERROR;
  42. }
  43. output.write((const char *)content, size);
  44. output.close();
  45. chmod((outputPath + ".ms").c_str(), S_IRUSR);
  46. return RET_OK;
  47. }
  48. schema::MetaGraphT *Storage::Load(const std::string &inputPath) {
  49. size_t size = 0;
  50. auto buf = ReadFile(inputPath.c_str(), &size);
  51. if (buf == nullptr) {
  52. MS_LOG(ERROR) << "the file buffer is nullptr";
  53. return nullptr;
  54. }
  55. flatbuffers::Verifier verify((const uint8_t *)buf, size);
  56. if (!schema::VerifyMetaGraphBuffer(verify)) {
  57. MS_LOG(ERROR) << "the buffer is invalid and fail to create meta graph";
  58. return nullptr;
  59. }
  60. auto graphDefT = schema::UnPackMetaGraph(buf);
  61. return graphDefT.release();
  62. }
  63. } // namespace lite
  64. } // namespace mindspore