summaryrefslogtreecommitdiff
path: root/compiler/tf2nnpkg/src/tf2nnpkg.cpp
blob: 548cee61f8de70b8a7a5654ace91313fed99ebc1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
/*
 * Copyright (c) 2020 Samsung Electronics Co., Ltd. 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 "filesystem.h"

#include <moco/LoggingContext.h>
#include <moco/tf/Frontend.h>
#include <exo/LoggingContext.h>
#include <exo/CircleExporter.h>

#include <nnkit/support/tftestinfo/TensorInfoParser.h>

#include <locop/FormattedGraph.h>

#include <hermes/ConsoleReporter.h>
#include <hermes/EnvConfig.h>

#include <memory>
#include <iostream>
#include <fstream>
#include <functional>
#include <stdexcept>
#include <string>
#include <vector>

namespace
{

std::unique_ptr<loco::Graph> import(const moco::ModelSignature &sig, const std::string &path)
{
  moco::tf::Frontend frontend;
  return frontend.load(sig, path.c_str(), moco::tf::Frontend::FileType::Binary);
}

} // namespace

//
// Logging Support
//
namespace
{

struct Logger final : public hermes::Source
{
  Logger(hermes::Context *ctx) { activate(ctx->sources(), ctx->bus()); }
  ~Logger() { deactivate(); }
};

struct LoggingContext
{
  static hermes::Context *get(void)
  {
    using EnvConfig = hermes::EnvConfig<hermes::EnvFormat::BooleanNumber>;

    static hermes::Context *ctx = nullptr;

    if (ctx == nullptr)
    {
      ctx = new hermes::Context;
      ctx->sinks()->append(std::make_unique<hermes::ConsoleReporter>());
      ctx->config(std::make_unique<EnvConfig>("TF2NNPKG_Log"));
    }

    return ctx;
  }
};

void print_help()
{
  std::cerr << "Usage:" << std::endl;
  std::cerr << "    tf2nnpkg --info <path/to/info>" << std::endl;
  std::cerr << "             --graphdef <path/to/pb>" << std::endl;
  std::cerr << "             -o <path/to/package/dir>" << std::endl;
}

} // namespace

#define LOGGER(name) \
  ::Logger name { ::LoggingContext::get() }

#define INFO(name) HERMES_INFO(name)

namespace
{

void internal_error(void)
{
  std::cerr << "tf2nnpkg: internal compiler error" << std::endl;

  // TODO Explain how to report a bug
}

} // namespace

namespace
{

std::string extract_modelname(std::string tf_path)
{
  auto filename = filesystem::basename(tf_path);
  // TODO Find better way
  const std::string key = ".pb";
  auto suffix_index = filename.find(key);
  assert(suffix_index != std::string::npos);
  assert(suffix_index + key.size() == filename.size());

  return filename.substr(0, suffix_index);
}

class EntryFunctor
{
public:
  EntryFunctor();

public:
  ~EntryFunctor();

public:
  int operator()(int argc, char **argv) const;
};

EntryFunctor::EntryFunctor()
{
  // NOTE Implement initialization here
}

EntryFunctor::~EntryFunctor()
{
  // NOTE Implement finialization here
}

int EntryFunctor::operator()(int argc, char **argv) const
{
  using EnvConfig = hermes::EnvConfig<hermes::EnvFormat::BooleanNumber>;

  // This line allows users to control all the moco-tf loggers via TF2NNPKG_Log_Frontend
  moco::LoggingContext::get()->config(std::make_unique<EnvConfig>("TF2NNPKG_Log_Frontend"));
  // This line allows users to control all the exo-circle loggers via TF2NNPKG_Log_Backend
  exo::LoggingContext::get()->config(std::make_unique<EnvConfig>("TF2NNPKG_Log_Backend"));

  LOGGER(l);

  // Simple argument parser (based on map)
  std::map<std::string, std::function<void(const std::string &arg)>> argparse;

  std::string arg_info;
  std::string arg_graphdef;
  std::string arg_output;

  argparse["--info"] = [&](const std::string &arg) { arg_info = arg; };
  argparse["--graphdef"] = [&](const std::string &arg) { arg_graphdef = arg; };
  argparse["-o"] = [&](const std::string &arg) { arg_output = arg; };

  // TODO We need better args parsing in future

  for (int n = 1; n < argc; n += 2)
  {
    const std::string tag{argv[n]};
    const std::string arg{argv[n + 1]};

    auto it = argparse.find(tag);
    if (it == argparse.end())
    {
      std::cerr << "Option '" << tag << "' is not supported" << std::endl;
      print_help();
      return 255;
    }

    it->second(arg);
  }
  if (arg_info.empty() || arg_graphdef.empty() || arg_output.empty())
  {
    print_help();
    return 255;
  }

  // Input paths
  std::string info_path = arg_info;
  std::string tf_path = arg_graphdef; // .pb file

  // Output paths
  std::string outdir_path = arg_output;
  std::string modelname = extract_modelname(filesystem::normalize_path(tf_path));
  std::string nnpkg_path = filesystem::join(outdir_path, modelname);
  std::string model_filename = modelname + ".circle";
  std::string metadata_path = filesystem::join(nnpkg_path, "metadata");
  std::string circle_path = filesystem::join(nnpkg_path, model_filename);
  std::string manifest_path = filesystem::join(metadata_path, "MANIFEST");

  std::cout << "Read '" << info_path << "'" << std::endl;

  moco::ModelSignature sig;
  {
    for (const auto &info : nnkit::support::tftestinfo::parse(info_path.c_str()))
    {
      switch (info->kind())
      {
        case nnkit::support::tftestinfo::ParsedTensor::Kind::Input:
          sig.add_input(moco::TensorName{info->name()});
          sig.shape(info->name(), info->shape());
          break;

        case nnkit::support::tftestinfo::ParsedTensor::Kind::Output:
          sig.add_output(moco::TensorName{info->name()});
          sig.shape(info->name(), info->shape());
          break;

        default:
          throw std::runtime_error{"Unknown kind"};
      }
    }
  }

  std::cout << "Read '" << info_path << "' - Done" << std::endl;

  std::cout << "Import from '" << tf_path << "'" << std::endl;
  auto g = import(sig, tf_path);
  std::cout << "Import from '" << tf_path << "' - Done" << std::endl;

  INFO(l) << "Import Graph" << std::endl;
  INFO(l) << locop::fmt<locop::Formatter::LinearV1>(g) << std::endl;

  if (not filesystem::is_dir(outdir_path))
  {
    std::cout << "Make output directory '" << outdir_path << "'" << std::endl;
    if (not filesystem::mkdir(outdir_path))
      throw std::runtime_error("Fail to make directory " + outdir_path);
    std::cout << "Make output directory '" << outdir_path << "' - Done" << std::endl;
  }

  if (not filesystem::is_dir(nnpkg_path))
  {
    std::cout << "Make package directory '" << nnpkg_path << "'" << std::endl;
    if (not filesystem::mkdir(nnpkg_path))
      throw std::runtime_error("Fail to make directory " + nnpkg_path);
    std::cout << "Make package directory '" << nnpkg_path << "' - Done" << std::endl;
  }

  std::cout << "Export into '" << circle_path << "'" << std::endl;
  exo::CircleExporter(g.get()).dumpToFile(circle_path.c_str());
  std::cout << "Export into '" << circle_path << "' - Done" << std::endl;

  if (not filesystem::is_dir(metadata_path))
  {
    std::cout << "Make metadata directory '" << metadata_path << "'" << std::endl;
    if (not filesystem::mkdir(metadata_path))
      throw std::runtime_error("Fail to make directory " + metadata_path);
    std::cout << "Make metadata directory '" << metadata_path << "' - Done" << std::endl;
  }

  std::cout << "Make manifest file '" << manifest_path << "'" << std::endl;
  std::ofstream manifest_file;
  manifest_file.open(manifest_path, std::ios::out | std::ios::binary);
  manifest_file << "{\n";
  manifest_file << "  \"major-version\" : \"1\",\n";
  manifest_file << "  \"minor-version\" : \"0\",\n";
  manifest_file << "  \"patch-version\" : \"0\",\n";
  manifest_file << "  \"models\" : [ \"" + model_filename + "\" ],\n";
  manifest_file << "  \"model-types\" : [ \"circle\" ]\n";
  manifest_file << "}";
  manifest_file.close();
  std::cout << "Make manifest file '" << manifest_path << "' - Done" << std::endl;

  return 0;
}

} // namespace

int main(int argc, char **argv)
{
  // TODO Add "signal" handler here

  try
  {
    EntryFunctor entry;
    return entry(argc, argv);
  }
  catch (...)
  {
    // Catch all the exception and print the default error message.
    internal_error();
  }

  // EX_SOFTWARE defined in "sysexits.h"
  return 70;
}