Elffuss BraidHub

kikocis/ncnn public

master · 32.5 KiBRawPermalink
1// Tencent is pleased to support the open source community by making ncnn available.
2//
3// Copyright (C) 2020 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
15#include <algorithm>
16#include <assert.h>
17#include <cctype>
18#include <deque>
19#include <fstream>
20#include <iostream>
21#include <locale>
22#include <sstream>
23#include <stdio.h>
24#include <stdlib.h>
25#include <string>
26#include <unordered_map>
27#include <vector>
28#include <cstdint>
29
30#define OUTPUT_LAYER_MAP 0 //enable this to generate darknet style layer output
31
32void file_error(const char* s)
33{
34 fprintf(stderr, "Couldn't open file: %s\n", s);
35 exit(EXIT_FAILURE);
36}
37
38void fread_or_error(void* buffer, size_t size, size_t count, FILE* fp, const char* s)
39{
40 if (count != fread(buffer, size, count, fp))
41 {
42 fprintf(stderr, "Couldn't read from file: %s\n", s);
43 fclose(fp);
44 assert(0);
45 exit(EXIT_FAILURE);
46 }
47}
48
49void error(const char* s)
50{
51 perror(s);
52 assert(0);
53 exit(EXIT_FAILURE);
54}
55
56typedef struct Section
57{
58 std::string name;
59 int line_number = -1;
60 int original_layer_count;
61
62 std::unordered_map<std::string, std::string> options;
63 int w = 416, h = 416, c = 3, inputs = 256, letter_box = 0;
64 int out_w, out_h, out_c;
65 int batch_normalize = 0, filters = 1, size = 1, groups = 1, stride = 1, padding = -1, pad = 0, dilation = 1;
66 std::string activation;
67 int from, reverse;
68 std::vector<int> layers, mask, anchors;
69 int group_id = -1;
70 int classes = 0, num = 0;
71 float ignore_thresh = 0.45f, scale_x_y = 1.f;
72
73 std::vector<float> weights, bias, scales, rolling_mean, rolling_variance;
74
75 std::string layer_type, layer_name;
76 std::vector<std::string> input_blobs, output_blobs;
77 std::vector<std::string> real_output_blobs;
78 std::vector<std::string> param;
79} Section;
80
81static inline std::string& trim(std::string& s)
82{
83 s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) {
84 return !std::isspace(ch);
85 }));
86 s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) {
87 return !std::isspace(ch);
88 }).base(),
89 s.end());
90 return s;
91}
92
93typedef enum FIELD_TYPE
94{
95 INT,
96 FLOAT,
97 IARRAY,
98 FARRAY,
99 STRING,
100 UNSUPPORTED
101} FIELD_TYPE;
102
103typedef struct Section_Field
104{
105 const char* name;
106 FIELD_TYPE type;
107 size_t offset;
108} Section_Field;
109
110#define FIELD_OFFSET(c) ((size_t) & (((Section*)0)->c))
111
112int yolo_layer_count = 0;
113bool letter_box_enabled = false;
114
115std::vector<std::string> split(const std::string& s, char delimiter)
116{
117 std::vector<std::string> tokens;
118 std::string token;
119 std::istringstream tokenStream(s);
120 while (std::getline(tokenStream, token, delimiter))
121 {
122 tokens.push_back(token);
123 }
124 return tokens;
125}
126
127template<typename... Args>
128std::string format(const char* fmt, Args... args)
129{
130 size_t size = snprintf(nullptr, 0, fmt, args...);
131 std::string buf;
132 buf.reserve(size + 1);
133 buf.resize(size);
134 snprintf(&buf[0], size + 1, fmt, args...);
135 return buf;
136}
137
138void update_field(Section* section, std::string key, std::string value)
139{
140 static const Section_Field fields[] = {
141 //net
142 {"width", INT, FIELD_OFFSET(w)},
143 {"height", INT, FIELD_OFFSET(h)},
144 {"channels", INT, FIELD_OFFSET(c)},
145 {"inputs", INT, FIELD_OFFSET(inputs)},
146 {"letter_box", INT, FIELD_OFFSET(letter_box)},
147 //convolutional, upsample, maxpool
148 {"batch_normalize", INT, FIELD_OFFSET(batch_normalize)},
149 {"filters", INT, FIELD_OFFSET(filters)},
150 {"size", INT, FIELD_OFFSET(size)},
151 {"groups", INT, FIELD_OFFSET(groups)},
152 {"stride", INT, FIELD_OFFSET(stride)},
153 {"padding", INT, FIELD_OFFSET(padding)},
154 {"pad", INT, FIELD_OFFSET(pad)},
155 {"dilation", INT, FIELD_OFFSET(dilation)},
156 {"activation", STRING, FIELD_OFFSET(activation)},
157 //shortcut
158 {"from", INT, FIELD_OFFSET(from)},
159 {"reverse", INT, FIELD_OFFSET(reverse)},
160 //route
161 {"layers", IARRAY, FIELD_OFFSET(layers)},
162 {"group_id", INT, FIELD_OFFSET(group_id)},
163 //yolo
164 {"mask", IARRAY, FIELD_OFFSET(mask)},
165 {"anchors", IARRAY, FIELD_OFFSET(anchors)},
166 {"classes", INT, FIELD_OFFSET(classes)},
167 {"num", INT, FIELD_OFFSET(num)},
168 {"ignore_thresh", FLOAT, FIELD_OFFSET(ignore_thresh)},
169 {"scale_x_y", FLOAT, FIELD_OFFSET(scale_x_y)},
170 };
171
172 for (size_t i = 0; i < sizeof(fields) / sizeof(fields[0]); i++)
173 {
174 auto f = fields[i];
175 if (key != f.name)
176 continue;
177 char* addr = ((char*)section) + f.offset;
178 switch (f.type)
179 {
180 case INT:
181 *(int*)(addr) = std::stoi(value);
182 return;
183
184 case FLOAT:
185 *(float*)(addr) = std::stof(value);
186 return;
187
188 case IARRAY:
189 for (auto v : split(value, ','))
190 reinterpret_cast<std::vector<int>*>(addr)->push_back(std::stoi(v));
191 return;
192
193 case FARRAY:
194 for (auto v : split(value, ','))
195 reinterpret_cast<std::vector<float>*>(addr)->push_back(std::stof(v));
196 return;
197
198 case STRING:
199 *reinterpret_cast<std::string*>(addr) = value;
200 return;
201
202 case UNSUPPORTED:
203 printf("unsupported option: %s\n", key.c_str());
204 exit(EXIT_FAILURE);
205 }
206 }
207}
208
209void load_cfg(const char* filename, std::deque<Section*>& dnet)
210{
211 std::string line;
212 std::ifstream icfg(filename, std::ifstream::in);
213 if (!icfg.good())
214 {
215 fprintf(stderr, "Couldn't cfg open file: %s\n", filename);
216 exit(EXIT_FAILURE);
217 }
218
219 Section* section = NULL;
220 size_t pos;
221 int section_count = 0, line_count = 0;
222 while (!icfg.eof())
223 {
224 line_count++;
225 std::getline(icfg, line);
226 trim(line);
227 if (line.length() == 0 || line.at(0) == '#')
228 continue;
229 if (line.at(0) == '[' && line.at(line.length() - 1) == ']')
230 {
231 line = line.substr(1, line.length() - 2);
232 section = new Section;
233 section->name = line;
234 section->line_number = line_count;
235 section->original_layer_count = section_count++;
236 dnet.push_back(section);
237 }
238 else if ((pos = line.find_first_of('=')) != std::string::npos)
239 {
240 std::string key = line.substr(0, pos);
241 std::string value = line.substr(pos + 1, line.length() - 1);
242 section->options[trim(key)] = trim(value);
243 update_field(section, key, value);
244 }
245 }
246
247 icfg.close();
248}
249
250Section* get_original_section(std::deque<Section*>& dnet, int count, int offset)
251{
252 if (offset >= 0)
253 count = offset + 1;
254 else
255 count += offset;
256 for (auto s : dnet)
257 if (s->original_layer_count == count)
258 return s;
259 return dnet[0];
260}
261
262template<typename T>
263std::string array_to_float_string(std::vector<T> vec)
264{
265 std::string ret;
266 for (size_t i = 0; i < vec.size(); i++)
267 ret.append(format(",%f", (float)vec[i]));
268 return ret;
269}
270
271Section* get_section_by_output_blob(std::deque<Section*>& dnet, std::string blob)
272{
273 for (auto s : dnet)
274 for (auto b : s->output_blobs)
275 if (b == blob)
276 return s;
277 return NULL;
278}
279
280std::vector<Section*> get_sections_by_input_blob(std::deque<Section*>& dnet, std::string blob)
281{
282 std::vector<Section*> ret;
283 for (auto s : dnet)
284 for (auto b : s->input_blobs)
285 if (b == blob)
286 ret.push_back(s);
287 return ret;
288}
289
290void addActivationLayer(Section* s, std::deque<Section*>::iterator& it, std::deque<Section*>& dnet)
291{
292 Section* act = new Section;
293
294 if (s->activation == "relu")
295 {
296 act->layer_type = "ReLU";
297 act->param.push_back("0=0");
298 }
299 else if (s->activation == "leaky")
300 {
301 act->layer_type = "ReLU";
302 act->param.push_back("0=0.1");
303 }
304 else if (s->activation == "mish")
305 act->layer_type = "Mish";
306 else if (s->activation == "logistic")
307 act->layer_type = "Sigmoid";
308 else if (s->activation == "swish")
309 act->layer_type = "Swish";
310
311 if (s->batch_normalize)
312 act->layer_name = s->layer_name + "_bn";
313 else
314 act->layer_name = s->layer_name;
315 act->h = s->out_h;
316 act->w = s->out_w;
317 act->c = s->out_c;
318 act->out_h = s->out_h;
319 act->out_w = s->out_w;
320 act->out_c = s->out_c;
321 act->layer_name += "_" + s->activation;
322 act->input_blobs = s->real_output_blobs;
323 act->output_blobs.push_back(act->layer_name);
324
325 s->real_output_blobs = act->real_output_blobs = act->output_blobs;
326 it = dnet.insert(it + 1, act);
327}
328
329void parse_cfg(std::deque<Section*>& dnet, int merge_output)
330{
331 int input_w = 416, input_h = 416;
332 int yolo_count = 0;
333 std::vector<Section*> yolo_layers;
334
335#if OUTPUT_LAYER_MAP
336 printf(" layer filters size/strd(dil) input output\n");
337#endif
338 for (auto it = dnet.begin(); it != dnet.end(); it++)
339 {
340 auto s = *it;
341 if (s->line_number < 0)
342 continue;
343
344 auto p = get_original_section(dnet, s->original_layer_count, -1);
345
346#if OUTPUT_LAYER_MAP
347 if (s->original_layer_count > 0)
348 printf("%4d ", s->original_layer_count - 1);
349#endif
350
351 s->layer_name = format("%d_%d", s->original_layer_count - 1, s->line_number);
352 s->input_blobs = p->real_output_blobs;
353 s->output_blobs.push_back(s->layer_name);
354 s->real_output_blobs = s->output_blobs;
355
356 if (s->name == "net")
357 {
358 if (s->letter_box)
359 {
360 fprintf(stderr, "WARNING: letter_box enabled.\n");
361 letter_box_enabled = true;
362 }
363
364 s->out_h = s->h;
365 s->out_w = s->w;
366 s->out_c = s->c;
367 input_h = s->h;
368 input_w = s->w;
369
370 s->layer_type = "Input";
371 s->layer_name = "data";
372 s->input_blobs.clear();
373 s->output_blobs.clear();
374 s->output_blobs.push_back("data");
375 s->real_output_blobs = s->output_blobs;
376 s->param.push_back(format("0=%d", s->w));
377 s->param.push_back(format("1=%d", s->h));
378 s->param.push_back(format("2=%d", s->c));
379 }
380 else if (s->name == "convolutional")
381 {
382 if (s->pad)
383 s->padding = s->size / 2;
384 if (s->padding == -1)
385 s->padding = 0;
386 s->h = p->out_h;
387 s->w = p->out_w;
388 s->c = p->out_c;
389 s->out_h = (s->h + 2 * s->padding - s->size) / s->stride + 1;
390 s->out_w = (s->w + 2 * s->padding - s->size) / s->stride + 1;
391 s->out_c = s->filters;
392
393#if OUTPUT_LAYER_MAP
394 if (s->groups == 1)
395 printf("conv %5d %2d x%2d/%2d ", s->filters, s->size, s->size, s->stride);
396 else
397 printf("conv %5d/%4d %2d x%2d/%2d ", s->filters, s->groups, s->size, s->size, s->stride);
398 printf("%4d x%4d x%4d -> %4d x%4d x%4d\n", s->h, s->w, s->c, s->out_h, s->out_w, s->out_c);
399#endif
400
401 if (s->groups == 1)
402 s->layer_type = "Convolution";
403 else
404 s->layer_type = "ConvolutionDepthWise";
405 s->param.push_back(format("0=%d", s->filters)); //num_output
406 s->param.push_back(format("1=%d", s->size)); //kernel_w
407 s->param.push_back(format("2=%d", s->dilation)); //dilation_w
408 s->param.push_back(format("3=%d", s->stride)); //stride_w
409 s->param.push_back(format("4=%d", s->padding)); //pad_left
410
411 if (s->batch_normalize)
412 {
413 s->param.push_back("5=0"); //bias_term
414
415 Section* bn = new Section;
416 bn->layer_type = "BatchNorm";
417 bn->layer_name = s->layer_name + "_bn";
418 bn->h = s->out_h;
419 bn->w = s->out_w;
420 bn->c = s->out_c;
421 bn->out_h = s->out_h;
422 bn->out_w = s->out_w;
423 bn->out_c = s->out_c;
424 bn->input_blobs = s->real_output_blobs;
425 bn->output_blobs.push_back(bn->layer_name);
426 bn->param.push_back(format("0=%d", s->filters)); //channels
427 bn->param.push_back("1=.00001"); //eps
428
429 s->real_output_blobs = bn->real_output_blobs = bn->output_blobs;
430 it = dnet.insert(it + 1, bn);
431 }
432 else
433 {
434 s->param.push_back("5=1"); //bias_term
435 }
436 s->param.push_back(format("6=%d", s->c * s->size * s->size * s->filters / s->groups)); //weight_data_size
437
438 if (s->groups > 1)
439 s->param.push_back(format("7=%d", s->groups)); //stride_w
440
441 if (s->activation.size() > 0)
442 {
443 if (s->activation == "relu" || s->activation == "leaky" || s->activation == "mish" || s->activation == "logistic" || s->activation == "swish")
444 {
445 addActivationLayer(s, it, dnet);
446 }
447 else if (s->activation != "linear")
448 error(format("Unsupported convolutional activation type: %s", s->activation.c_str()).c_str());
449 }
450 }
451 else if (s->name == "shortcut")
452 {
453 auto q = get_original_section(dnet, s->original_layer_count, s->from);
454 if (p->out_h != q->out_h || p->out_w != q->out_w)
455 error("shortcut dim not match");
456
457 s->h = p->out_h;
458 s->w = p->out_w;
459 s->c = p->out_c;
460 s->out_h = s->h;
461 s->out_w = s->w;
462 s->out_c = p->out_c;
463
464#if OUTPUT_LAYER_MAP
465 printf("Shortcut Layer: %d, ", q->original_layer_count - 1);
466 printf("outputs: %4d x%4d x%4d\n", s->out_h, s->out_w, s->out_c);
467 if (p->out_c != q->out_c)
468 printf("(%4d x%4d x%4d) + (%4d x%4d x%4d)\n", p->out_h, p->out_w, p->out_c,
469 q->out_h, q->out_w, q->out_c);
470#endif
471
472 if (s->activation.size() > 0)
473 {
474 if (s->activation == "relu" || s->activation == "leaky" || s->activation == "mish" || s->activation == "logistic" || s->activation == "swish")
475 {
476 addActivationLayer(s, it, dnet);
477 }
478 else if (s->activation != "linear")
479 error(format("Unsupported convolutional activation type: %s", s->activation.c_str()).c_str());
480 }
481
482 s->layer_type = "Eltwise";
483 s->input_blobs.clear();
484 s->input_blobs.push_back(p->real_output_blobs[0]);
485 s->input_blobs.push_back(q->real_output_blobs[0]);
486
487 s->param.push_back("0=1"); //op_type=Operation_SUM
488 }
489 else if (s->name == "maxpool")
490 {
491 if (s->padding == -1)
492 s->padding = s->size - 1;
493 int pad = s->padding / 2;
494 s->h = p->out_h;
495 s->w = p->out_w;
496 s->c = p->out_c;
497 s->out_h = (s->h + s->padding - s->size) / s->stride + 1;
498 s->out_w = (s->w + s->padding - s->size) / s->stride + 1;
499 s->out_c = s->c;
500
501#if OUTPUT_LAYER_MAP
502 printf("max %2d x%2d/%2d ", s->size, s->size, s->stride);
503 printf("%4d x%4d x%4d -> %4d x%4d x%4d\n", s->h, s->w, s->c, s->out_h, s->out_w, s->out_c);
504#endif
505
506 s->layer_type = "Pooling";
507 s->param.push_back("0=0"); //pooling_type=PoolMethod_MAX
508 s->param.push_back(format("1=%d", s->size)); //kernel_w
509 s->param.push_back(format("2=%d", s->stride)); //stride_w
510 s->param.push_back("5=1"); //pad_mode=SAME_UPPER
511 s->param.push_back(format("3=%d", pad)); //pad_left
512 s->param.push_back(format("13=%d", pad)); //pad_top
513 s->param.push_back(format("14=%d", s->padding - pad)); //pad_right
514 s->param.push_back(format("15=%d", s->padding - pad)); //pad_bottom
515 }
516 else if (s->name == "avgpool")
517 {
518 if (s->padding == -1)
519 s->padding = s->size - 1;
520 s->h = p->out_h;
521 s->w = p->out_w;
522 s->c = p->out_c;
523 s->out_h = 1;
524 s->out_w = s->out_h;
525 s->out_c = s->c;
526
527#if OUTPUT_LAYER_MAP
528 printf("avg %4d x%4d x%4d -> %4d\n", s->h, s->w, s->c, s->out_c);
529#endif
530
531 s->layer_type = "Pooling";
532 s->param.push_back("0=1"); //pooling_type=PoolMethod_AVE
533 s->param.push_back("4=1"); //global_pooling
534
535 Section* r = new Section;
536 r->layer_type = "Reshape";
537 r->layer_name = s->layer_name + "_reshape";
538 r->h = s->out_h;
539 r->w = s->out_w;
540 r->c = s->out_c;
541 r->out_h = 1;
542 r->out_w = 1;
543 r->out_c = r->h * r->w * r->c;
544 r->input_blobs.push_back(s->output_blobs[0]);
545 r->output_blobs.push_back(r->layer_name);
546 r->param.push_back("0=1"); //w
547 r->param.push_back("1=1"); //h
548 r->param.push_back(format("2=%d", r->out_c)); //c
549
550 s->real_output_blobs.clear();
551 s->real_output_blobs.push_back(r->layer_name);
552
553 it = dnet.insert(it + 1, r);
554 }
555 else if (s->name == "sam")
556 {
557 auto q = get_original_section(dnet, s->original_layer_count, s->from);
558 if (p->out_w != q->out_w || p->out_h != q->out_h || p->out_c != q->out_c)
559 error("sam layer dimension not match");
560
561 s->h = q->out_h;
562 s->w = q->out_w;
563 s->c = q->out_c;
564 s->out_h = s->h;
565 s->out_w = s->w;
566 s->out_c = q->out_c;
567
568#if OUTPUT_LAYER_MAP
569 printf("scale Layer: %d\n", q->original_layer_count - 1);
570#endif
571
572 s->layer_type = "BinaryOp";
573 s->input_blobs.clear();
574 s->input_blobs.push_back(q->real_output_blobs[0]);
575 s->input_blobs.push_back(p->real_output_blobs[0]);
576 s->param.push_back("0=2"); //op_type=Operation_MUL
577 }
578 else if (s->name == "scale_channels")
579 {
580 auto q = get_original_section(dnet, s->original_layer_count, s->from);
581 if (p->out_c != q->out_c)
582 error("scale channels not match");
583
584 s->h = q->out_h;
585 s->w = q->out_w;
586 s->c = q->out_c;
587 s->out_h = s->h;
588 s->out_w = s->w;
589 s->out_c = q->out_c;
590
591#if OUTPUT_LAYER_MAP
592 printf("scale Layer: %d\n", q->original_layer_count - 1);
593#endif
594
595 if (s->activation.size() > 0 && s->activation != "linear")
596 error(format("Unsupported scale_channels activation type: %s", s->activation.c_str()).c_str());
597
598 s->layer_type = "BinaryOp";
599 s->input_blobs.clear();
600 s->input_blobs.push_back(q->real_output_blobs[0]);
601 s->input_blobs.push_back(p->real_output_blobs[0]);
602 s->param.push_back("0=2"); //op_type=Operation_MUL
603 }
604 else if (s->name == "route")
605 {
606#if OUTPUT_LAYER_MAP
607 printf("route ");
608#endif
609 s->out_c = 0;
610 s->input_blobs.clear();
611 for (int l : s->layers)
612 {
613 auto q = get_original_section(dnet, s->original_layer_count, l);
614#if OUTPUT_LAYER_MAP
615 printf("%d ", q->original_layer_count - 1);
616#endif
617 s->out_h = q->out_h;
618 s->out_w = q->out_w;
619 s->out_c += q->out_c;
620
621 for (auto blob : q->real_output_blobs)
622 s->input_blobs.push_back(blob);
623 }
624 if (s->input_blobs.size() == 1)
625 {
626 if (s->groups <= 1 || s->group_id == -1)
627 s->layer_type = "Noop";
628 else
629 {
630 s->out_c /= s->groups;
631#if OUTPUT_LAYER_MAP
632 printf("%31d/%d -> %4d x%4d x%4d", 1, s->groups, s->out_w, s->out_h, s->out_c);
633#endif
634
635 s->layer_type = "Crop";
636 s->param.push_back(format("2=%d", s->out_c * s->group_id));
637 s->param.push_back(format("3=%d", s->out_w));
638 s->param.push_back(format("4=%d", s->out_h));
639 s->param.push_back(format("5=%d", s->out_c));
640 }
641 }
642 else
643 {
644#if OUTPUT_LAYER_MAP
645 printf("%30c-> %4d x%4d x%4d", ' ', s->out_w, s->out_h, s->out_c);
646#endif
647 s->layer_type = "Concat";
648 }
649#if OUTPUT_LAYER_MAP
650 printf("\n");
651#endif
652 }
653 else if (s->name == "upsample")
654 {
655 s->h = p->out_h;
656 s->w = p->out_w;
657 s->c = p->out_c;
658 s->out_h = s->h * s->stride;
659 s->out_w = s->w * s->stride;
660 s->out_c = s->c;
661
662#if OUTPUT_LAYER_MAP
663 printf("upsample %2dx ", s->stride);
664 printf("%4d x%4d x%4d -> %4d x%4d x%4d\n", s->h, s->w, s->c, s->out_h, s->out_w, s->out_c);
665#endif
666 s->layer_type = "Interp";
667 s->param.push_back("0=1"); //resize_type=nearest
668 s->param.push_back("1=2.f"); //height_scale
669 s->param.push_back("2=2.f"); //width_scale
670 }
671 else if (s->name == "yolo")
672 {
673#if OUTPUT_LAYER_MAP
674 printf("yolo%d\n", yolo_count);
675#endif
676
677 if (s->ignore_thresh > 0.25)
678 {
679 fprintf(stderr, "WARNING: The ignore_thresh=%f of yolo%d is too high. "
680 "An alternative value 0.25 is written instead.\n",
681 s->ignore_thresh, yolo_count);
682 s->ignore_thresh = 0.25;
683 }
684
685 s->layer_type = "Yolov3DetectionOutput";
686 s->layer_name = format("yolo%d", yolo_count++);
687 s->output_blobs[0] = s->layer_name;
688 s->h = p->out_h;
689 s->w = p->out_w;
690 s->c = p->out_c;
691 s->out_h = s->h;
692 s->out_w = s->w;
693 s->out_c = s->c * (int)s->mask.size();
694 s->param.push_back(format("0=%d", s->classes)); //num_class
695 s->param.push_back(format("1=%d", s->mask.size())); //num_box
696 s->param.push_back(format("2=%f", s->ignore_thresh)); //confidence_threshold
697 s->param.push_back(format("-23304=%d%s", s->anchors.size(), array_to_float_string(s->anchors).c_str())); //biases
698 s->param.push_back(format("-23305=%d%s", s->mask.size(), array_to_float_string(s->mask).c_str())); //mask
699 s->param.push_back(format("-23306=2,%f,%f", input_w * s->scale_x_y / s->w, input_h * s->scale_x_y / s->h)); //biases_index
700
701 yolo_layer_count++;
702 yolo_layers.push_back(s);
703 }
704 else if (s->name == "dropout")
705 {
706#if OUTPUT_LAYER_MAP
707 printf("dropout\n");
708#endif
709 s->h = p->out_h;
710 s->w = p->out_w;
711 s->c = p->out_c;
712 s->out_h = s->h;
713 s->out_w = s->w;
714 s->out_c = p->out_c;
715 s->layer_type = "Noop";
716 }
717 else
718 {
719#if OUTPUT_LAYER_MAP
720 printf("%-8s (unsupported)\n", s->name.c_str());
721#endif
722 }
723 }
724
725 for (auto it = dnet.begin(); it != dnet.end(); it++)
726 {
727 auto s = *it;
728 for (size_t i = 0; i < s->input_blobs.size(); i++)
729 {
730 auto p = get_section_by_output_blob(dnet, s->input_blobs[i]);
731 if (p == NULL || p->layer_type != "Noop")
732 continue;
733 s->input_blobs[i] = p->input_blobs[0];
734 }
735 }
736
737 for (auto it = dnet.begin(); it != dnet.end();)
738 if ((*it)->layer_type == "Noop")
739 it = dnet.erase(it);
740 else
741 it++;
742
743 for (auto it = dnet.begin(); it != dnet.end(); it++)
744 {
745 auto s = *it;
746 for (std::string output_name : s->output_blobs)
747 {
748 auto q = get_sections_by_input_blob(dnet, output_name);
749 if (q.size() <= 1 || s->layer_type == "Split")
750 continue;
751 Section* p = new Section;
752 p->layer_type = "Split";
753 p->layer_name = s->layer_name + "_split";
754 p->w = s->w;
755 p->h = s->h;
756 p->c = s->c;
757 p->out_w = s->out_w;
758 p->out_h = s->out_h;
759 p->out_c = s->out_c;
760 p->input_blobs.push_back(output_name);
761 for (size_t i = 0; i < q.size(); i++)
762 {
763 std::string new_output_name = p->layer_name + "_" + std::to_string(i);
764 p->output_blobs.push_back(new_output_name);
765
766 for (size_t j = 0; j < q[i]->input_blobs.size(); j++)
767 if (q[i]->input_blobs[j] == output_name)
768 q[i]->input_blobs[j] = new_output_name;
769 }
770 it = dnet.insert(it + 1, p);
771 }
772 }
773
774 if (merge_output && yolo_layer_count > 0)
775 {
776 std::vector<int> masks;
777 std::vector<float> scale_x_y;
778
779 Section* s = new Section;
780 s->classes = yolo_layers[0]->classes;
781 s->anchors = yolo_layers[0]->anchors;
782 s->mask = yolo_layers[0]->mask;
783
784 for (auto p : yolo_layers)
785 {
786 if (s->classes != p->classes)
787 error("yolo object classes number not match, output cannot be merged.");
788
789 if (s->anchors.size() != p->anchors.size())
790 error("yolo layer anchor count not match, output cannot be merged.");
791
792 for (size_t i = 0; i < s->anchors.size(); i++)
793 if (s->anchors[i] != p->anchors[i])
794 error("yolo anchor size not match, output cannot be merged.");
795
796 if (s->ignore_thresh > p->ignore_thresh)
797 s->ignore_thresh = p->ignore_thresh;
798
799 for (int m : p->mask)
800 masks.push_back(m);
801
802 scale_x_y.push_back(input_w * p->scale_x_y / p->w);
803 s->input_blobs.push_back(p->input_blobs[0]);
804 }
805
806 for (auto it = dnet.begin(); it != dnet.end();)
807 if ((*it)->name == "yolo")
808 it = dnet.erase(it);
809 else
810 it++;
811
812 s->layer_type = "Yolov3DetectionOutput";
813 s->layer_name = "detection_out";
814 s->output_blobs.push_back("output");
815 s->param.push_back(format("0=%d", s->classes)); //num_class
816 s->param.push_back(format("1=%d", s->mask.size())); //num_box
817 s->param.push_back(format("2=%f", s->ignore_thresh)); //confidence_threshold
818 s->param.push_back(format("-23304=%d%s", s->anchors.size(), array_to_float_string(s->anchors).c_str())); //biases
819 s->param.push_back(format("-23305=%d%s", masks.size(), array_to_float_string(masks).c_str())); //mask
820 s->param.push_back(format("-23306=%d%s", scale_x_y.size(), array_to_float_string(scale_x_y).c_str())); //biases_index
821
822 dnet.push_back(s);
823 }
824}
825
826void read_to(std::vector<float>& vec, size_t size, FILE* fp)
827{
828 vec.resize(size);
829 size_t read_size = fread(&vec[0], sizeof(float), size, fp);
830 if (read_size != size)
831 error("\n Warning: Unexpected end of wights-file!\n");
832}
833
834void load_weights(const char* filename, std::deque<Section*>& dnet)
835{
836 FILE* fp = fopen(filename, "rb");
837 if (fp == NULL)
838 file_error(filename);
839
840 int major, minor, revision;
841
842 fread_or_error(&major, sizeof(int), 1, fp, filename);
843 fread_or_error(&minor, sizeof(int), 1, fp, filename);
844 fread_or_error(&revision, sizeof(int), 1, fp, filename);
845 if ((major * 10 + minor) >= 2)
846 {
847 uint64_t iseen = 0;
848 fread_or_error(&iseen, sizeof(uint64_t), 1, fp, filename);
849 }
850 else
851 {
852 uint32_t iseen = 0;
853 fread_or_error(&iseen, sizeof(uint32_t), 1, fp, filename);
854 }
855
856 for (auto s : dnet)
857 {
858 if (s->name == "convolutional")
859 {
860 read_to(s->bias, s->filters, fp);
861 if (s->batch_normalize)
862 {
863 read_to(s->scales, s->filters, fp);
864 read_to(s->rolling_mean, s->filters, fp);
865 read_to(s->rolling_variance, s->filters, fp);
866 }
867
868 if (s->layer_type == "Convolution")
869 read_to(s->weights, (size_t)(s->c) * s->filters * s->size * s->size, fp);
870 else if (s->layer_type == "ConvolutionDepthWise")
871 read_to(s->weights, s->c * s->filters * s->size * s->size / s->groups, fp);
872 }
873 }
874
875 fclose(fp);
876}
877
878int count_output_blob(std::deque<Section*>& dnet)
879{
880 int count = 0;
881 for (auto s : dnet)
882 count += (int)s->output_blobs.size();
883 return count;
884}
885
886int main(int argc, char** argv)
887{
888 if (!(argc == 3 || argc == 5 || argc == 6))
889 {
890 fprintf(stderr, "Usage: %s [darknetcfg] [darknetweights] [ncnnparam] [ncnnbin] [merge_output]\n"
891 "\t[darknetcfg] .cfg file of input darknet model.\n"
892 "\t[darknetweights] .weights file of input darknet model.\n"
893 "\t[cnnparam] .param file of output ncnn model.\n"
894 "\t[ncnnbin] .bin file of output ncnn model.\n"
895 "\t[merge_output] merge all output yolo layers into one, enabled by default.\n",
896 argv[0]);
897 return -1;
898 }
899
900 const char* darknetcfg = argv[1];
901 const char* darknetweights = argv[2];
902 const char* ncnn_param = argc >= 5 ? argv[3] : "ncnn.param";
903 const char* ncnn_bin = argc >= 5 ? argv[4] : "ncnn.bin";
904 int merge_output = argc >= 6 ? atoi(argv[5]) : 1;
905
906 std::deque<Section*> dnet;
907
908 printf("Loading cfg...\n");
909 load_cfg(darknetcfg, dnet);
910 parse_cfg(dnet, merge_output);
911
912 printf("Loading weights...\n");
913 load_weights(darknetweights, dnet);
914
915 FILE* pp = fopen(ncnn_param, "wb");
916 if (pp == NULL)
917 file_error(ncnn_param);
918
919 FILE* bp = fopen(ncnn_bin, "wb");
920 if (bp == NULL)
921 file_error(ncnn_bin);
922
923 printf("Converting model...\n");
924
925 fprintf(pp, "7767517\n");
926 fprintf(pp, "%d %d\n", (int)dnet.size(), count_output_blob(dnet));
927
928 for (auto s : dnet)
929 {
930 fprintf(pp, "%-22s %-20s %d %d", s->layer_type.c_str(), s->layer_name.c_str(), (int)s->input_blobs.size(), (int)s->output_blobs.size());
931 for (auto b : s->input_blobs)
932 fprintf(pp, " %s", b.c_str());
933 for (auto b : s->output_blobs)
934 fprintf(pp, " %s", b.c_str());
935 for (auto p : s->param)
936 fprintf(pp, " %s", p.c_str());
937 fprintf(pp, "\n");
938
939 if (s->name == "convolutional")
940 {
941 fseek(bp, 4, SEEK_CUR);
942 if (s->weights.size() > 0)
943 fwrite(&s->weights[0], sizeof(float), s->weights.size(), bp);
944 if (s->scales.size() > 0)
945 fwrite(&s->scales[0], sizeof(float), s->scales.size(), bp);
946 if (s->rolling_mean.size() > 0)
947 fwrite(&s->rolling_mean[0], sizeof(float), s->rolling_mean.size(), bp);
948 if (s->rolling_variance.size() > 0)
949 fwrite(&s->rolling_variance[0], sizeof(float), s->rolling_variance.size(), bp);
950 if (s->bias.size() > 0)
951 fwrite(&s->bias[0], sizeof(float), s->bias.size(), bp);
952 }
953 }
954 fclose(pp);
955
956 printf("%d layers, %d blobs generated.\n", (int)dnet.size(), count_output_blob(dnet));
957 printf("NOTE: The input of darknet uses: mean_vals=0 and norm_vals=1/255.f.\n");
958 if (!merge_output)
959 printf("NOTE: There are %d unmerged yolo output layer. Make sure all outputs are processed with nms.\n", yolo_layer_count);
960 if (letter_box_enabled)
961 printf("NOTE: Make sure your pre-processing and post-processing support letter_box.\n");
962 printf("NOTE: Remember to use ncnnoptimize for better performance.\n");
963
964 return 0;
965}