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.

tensorflow2ncnn.cpp 13 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. // Tencent is pleased to support the open source community by making ncnn available.
  2. //
  3. // Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
  4. //
  5. // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
  6. // in compliance with the License. You may obtain a copy of the License at
  7. //
  8. // https://opensource.org/licenses/BSD-3-Clause
  9. //
  10. // Unless required by applicable law or agreed to in writing, software distributed
  11. // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  12. // CONDITIONS OF ANY KIND, either express or implied. See the License for the
  13. // specific language governing permissions and limitations under the License.
  14. #include <stdio.h>
  15. #include <limits.h>
  16. #include <iostream>
  17. #include <fstream>
  18. #include <set>
  19. #include <limits>
  20. #include <algorithm>
  21. #include <google/protobuf/io/coded_stream.h>
  22. #include <google/protobuf/io/zero_copy_stream_impl.h>
  23. #include <google/protobuf/text_format.h>
  24. #include <google/protobuf/message.h>
  25. #include "graph.pb.h"
  26. static bool read_proto_from_binary(const char* filepath, google::protobuf::Message* message)
  27. {
  28. std::ifstream fs(filepath, std::ifstream::in | std::ifstream::binary);
  29. if (!fs.is_open())
  30. {
  31. fprintf(stderr, "open failed %s\n", filepath);
  32. return false;
  33. }
  34. google::protobuf::io::IstreamInputStream input(&fs);
  35. google::protobuf::io::CodedInputStream codedstr(&input);
  36. codedstr.SetTotalBytesLimit(INT_MAX, INT_MAX / 2);
  37. bool success = message->ParseFromCodedStream(&codedstr);
  38. fs.close();
  39. return success;
  40. }
  41. static const tensorflow::TensorProto& find_tensor_proto(const std::map<std::string, tensorflow::TensorProto>& weights, const tensorflow::NodeDef& node)
  42. {
  43. for (int j=0; j<node.input_size(); j++)
  44. {
  45. const std::string& input_name = node.input(j);
  46. const std::map<std::string, tensorflow::TensorProto>::const_iterator it = weights.find(input_name);
  47. if (it != weights.end())
  48. {
  49. const tensorflow::TensorProto& tensor = it->second;
  50. return tensor;
  51. }
  52. }
  53. static tensorflow::TensorProto null_tensor = tensorflow::TensorProto();
  54. return null_tensor;
  55. }
  56. int main(int argc, char** argv)
  57. {
  58. const char* tensorflowpb = argv[1];
  59. const char* ncnn_prototxt = argc >= 4 ? argv[2] : "ncnn.proto";
  60. const char* ncnn_modelbin = argc >= 4 ? argv[3] : "ncnn.bin";
  61. tensorflow::GraphDef graph;
  62. // load
  63. bool s1 = read_proto_from_binary(tensorflowpb, &graph);
  64. if (!s1)
  65. {
  66. fprintf(stderr, "read_proto_from_binary failed\n");
  67. return -1;
  68. }
  69. FILE* pp = stderr;//fopen(ncnn_prototxt, "wb");
  70. FILE* bp = stderr;//fopen(ncnn_modelbin, "wb");
  71. int node_count = graph.node_size();
  72. // fprintf(stderr, "node_count = %d\n\n", node_count);
  73. // node reference
  74. std::map<std::string, int> node_reference;
  75. // mapping for Const and Const-Identity
  76. std::map<std::string, tensorflow::TensorProto> weights;
  77. // global definition line
  78. // [layer count] [blob count]
  79. std::set<std::string> blob_names;
  80. for (int i=0; i<node_count; i++)
  81. {
  82. const tensorflow::NodeDef& node = graph.node(i);
  83. const std::string& output_name = node.name();
  84. if (node.op() == "Const")
  85. {
  86. const google::protobuf::Map<std::string, tensorflow::AttrValue>& attr = node.attr();
  87. const google::protobuf::Map<std::string, tensorflow::AttrValue>::const_iterator it = attr.find("value");
  88. if (it != attr.end())
  89. {
  90. const tensorflow::TensorProto& tensor = it->second.tensor();
  91. weights[output_name] = tensor;
  92. }
  93. continue;
  94. }
  95. else if (node.op() == "Identity")
  96. {
  97. const std::string& input_name = node.input(0);
  98. weights[output_name] = weights[input_name];
  99. continue;
  100. }
  101. else if (node.op() == "NoOp")
  102. {
  103. weights[output_name] = tensorflow::TensorProto();
  104. continue;
  105. }
  106. // input
  107. for (int j=0; j<node.input_size(); j++)
  108. {
  109. const std::string& input_name = node.input(j);
  110. // fprintf(stderr, "%s\n", input_name.c_str());
  111. if (weights.find(input_name) != weights.end())
  112. {
  113. continue;
  114. }
  115. blob_names.insert(input_name);
  116. if (node_reference.find(input_name) == node_reference.end())
  117. {
  118. node_reference[input_name] = 1;
  119. }
  120. else
  121. {
  122. node_reference[input_name] = node_reference[input_name] + 1;
  123. }
  124. }
  125. // output
  126. // fprintf(stderr, "%s\n", output_name.c_str());
  127. blob_names.insert(output_name);
  128. }
  129. // remove node_reference entry with reference equals to one
  130. int splitncnn_blob_count = 0;
  131. std::map<std::string, int>::iterator it = node_reference.begin();
  132. while (it != node_reference.end())
  133. {
  134. if (it->second == 1)
  135. {
  136. node_reference.erase(it++);
  137. }
  138. else
  139. {
  140. splitncnn_blob_count += it->second;
  141. // fprintf(stderr, "%s %d\n", it->first.c_str(), it->second);
  142. ++it;
  143. }
  144. }
  145. fprintf(pp, "%lu %lu\n", node_count + node_reference.size() - weights.size(), blob_names.size() + splitncnn_blob_count);
  146. int internal_split = 0;
  147. for (int i=0; i<node_count; i++)
  148. {
  149. const tensorflow::NodeDef& node = graph.node(i);
  150. // layer definition line, repeated
  151. // [type] [name] [bottom blob count] [top blob count] [bottom blobs] [top blobs] [layer specific params]
  152. // fprintf(pp, "%-16s %-16s %d %d", layer.type().c_str(), layer.name().c_str(), node.input_size(), layer.top_size());
  153. if (node.op() == "Add")
  154. {
  155. fprintf(pp, "%-16s", "Eltwise");
  156. }
  157. else if (node.op() == "BiasAdd")
  158. {
  159. fprintf(pp, "%-16s", "Eltwise");
  160. }
  161. else if (node.op() == "Const")
  162. {
  163. continue;
  164. }
  165. else if (node.op() == "Conv2D")
  166. {
  167. fprintf(pp, "%-16s", "Convolution");
  168. }
  169. else if (node.op() == "Identity")
  170. {
  171. continue;
  172. }
  173. else if (node.op() == "MatMul")
  174. {
  175. fprintf(pp, "%-16s", "InnerProduct");
  176. }
  177. else if (node.op() == "Max")
  178. {
  179. fprintf(pp, "%-16s", "Eltwise");
  180. }
  181. else if (node.op() == "MaxPool")
  182. {
  183. fprintf(pp, "%-16s", "Pooling");
  184. }
  185. else if (node.op() == "Mul")
  186. {
  187. fprintf(pp, "%-16s", "Eltwise");
  188. }
  189. else if (node.op() == "NoOp")
  190. {
  191. continue;
  192. }
  193. else if (node.op() == "Placeholder")
  194. {
  195. fprintf(pp, "%-16s", "Input");
  196. }
  197. else if (node.op() == "Relu")
  198. {
  199. fprintf(pp, "%-16s", "ReLU");
  200. }
  201. else
  202. {
  203. fprintf(pp, "%-16s", node.op().c_str());
  204. }
  205. int input_size = node.input_size();
  206. for (int j=0; j<node.input_size(); j++)
  207. {
  208. const std::string& input_name = node.input(j);
  209. if (weights.find(input_name) != weights.end())
  210. {
  211. input_size--;
  212. }
  213. }
  214. fprintf(pp, " %-16s %d 1", node.name().c_str(), input_size);
  215. for (int j=0; j<node.input_size(); j++)
  216. {
  217. std::string input_name = node.input(j);
  218. if (weights.find(input_name) != weights.end())
  219. {
  220. continue;
  221. }
  222. if (node_reference.find(input_name) != node_reference.end())
  223. {
  224. int refidx = node_reference[input_name] - 1;
  225. node_reference[input_name] = refidx;
  226. char splitsuffix[256];
  227. sprintf(splitsuffix, "_splitncnn_%d", refidx);
  228. input_name = input_name + splitsuffix;
  229. }
  230. fprintf(pp, " %s", input_name.c_str());
  231. }
  232. fprintf(pp, " %s\n", node.name().c_str());
  233. if (node.op() == "Add")
  234. {
  235. }
  236. else if (node.op() == "BiasAdd")
  237. {
  238. }
  239. else if (node.op() == "Const")
  240. {
  241. }
  242. else if (node.op() == "Conv2D")
  243. {
  244. // weights
  245. const tensorflow::TensorProto& tensor = find_tensor_proto(weights, node);
  246. fprintf(stderr, "[ ");
  247. const tensorflow::TensorShapeProto& shape = tensor.tensor_shape();
  248. for (int d = 0; d<shape.dim_size(); d++)
  249. fprintf(stderr, "%d ", shape.dim(d).size());
  250. fprintf(stderr, "]\n");
  251. if (!tensor.tensor_content().empty())
  252. {
  253. switch (tensor.dtype())
  254. {
  255. case 1: // float
  256. {
  257. const float *data = reinterpret_cast<const float*>(tensor.tensor_content().c_str());
  258. int size = tensor.tensor_content().size() / sizeof(float);
  259. fprintf(stderr, " size = %d\n", size);
  260. break;
  261. }
  262. case 3: // int32
  263. {
  264. const int *data = reinterpret_cast<const int*>(tensor.tensor_content().c_str());
  265. int size = tensor.tensor_content().size() / sizeof(int);
  266. fprintf(stderr, " size = %d\n", size);
  267. break;
  268. }
  269. default:
  270. fprintf(stderr, "Tensor type is not supported\n");
  271. break;
  272. }
  273. }
  274. }
  275. else if (node.op() == "Identity")
  276. {
  277. }
  278. else if (node.op() == "MatMul")
  279. {
  280. // weights
  281. const tensorflow::TensorProto& tensor = find_tensor_proto(weights, node);
  282. fprintf(stderr, "[ ");
  283. const tensorflow::TensorShapeProto& shape = tensor.tensor_shape();
  284. for (int d = 0; d<shape.dim_size(); d++)
  285. fprintf(stderr, "%d ", shape.dim(d).size());
  286. fprintf(stderr, "]\n");
  287. if (!tensor.tensor_content().empty())
  288. {
  289. switch (tensor.dtype())
  290. {
  291. case 1: // float
  292. {
  293. const float *data = reinterpret_cast<const float*>(tensor.tensor_content().c_str());
  294. int size = tensor.tensor_content().size() / sizeof(float);
  295. fprintf(stderr, " size = %d\n", size);
  296. break;
  297. }
  298. case 3: // int32
  299. {
  300. const int *data = reinterpret_cast<const int*>(tensor.tensor_content().c_str());
  301. int size = tensor.tensor_content().size() / sizeof(int);
  302. fprintf(stderr, " size = %d\n", size);
  303. break;
  304. }
  305. default:
  306. fprintf(stderr, "Tensor type is not supported\n");
  307. break;
  308. }
  309. }
  310. }
  311. else if (node.op() == "Max")
  312. {
  313. }
  314. else if (node.op() == "MaxPool")
  315. {
  316. }
  317. else if (node.op() == "Mul")
  318. {
  319. }
  320. else if (node.op() == "NoOp")
  321. {
  322. }
  323. else if (node.op() == "Placeholder")
  324. {
  325. }
  326. else if (node.op() == "Relu")
  327. {
  328. }
  329. else
  330. {
  331. const google::protobuf::Map<std::string, tensorflow::AttrValue>& attr = node.attr();
  332. google::protobuf::Map<std::string, tensorflow::AttrValue>::const_iterator it = attr.begin();
  333. for (; it != attr.end(); it++)
  334. {
  335. std::cerr << it->first << std::endl;
  336. std::cerr << it->second.type() << std::endl;
  337. }
  338. }
  339. std::string output_name = node.name();
  340. if (node_reference.find(output_name) != node_reference.end())
  341. {
  342. int refcount = node_reference[output_name];
  343. if (refcount > 1)
  344. {
  345. char splitname[256];
  346. sprintf(splitname, "splitncnn_%d", internal_split);
  347. fprintf(pp, "%-16s %-16s %d %d", "Split", splitname, 1, refcount);
  348. fprintf(pp, " %s", output_name.c_str());
  349. for (int j=0; j<refcount; j++)
  350. {
  351. fprintf(pp, " %s_splitncnn_%d", output_name.c_str(), j);
  352. }
  353. fprintf(pp, "\n");
  354. internal_split++;
  355. }
  356. }
  357. }
  358. fclose(pp);
  359. fclose(bp);
  360. return 0;
  361. }