File size: 18,603 Bytes
be903e2 | 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 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 | // BUG1989 is pleased to support the open source community by supporting ncnn available.
//
// Copyright (C) 2019 BUG1989. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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.
#ifdef _MSC_VER
#define _CRT_SECURE_NO_DEPRECATE
#endif
#include <cstdio>
#include <cstring>
#include <map>
#include <set>
#include <vector>
// ncnn public header
#include "datareader.h"
#include "layer.h"
#include "layer_type.h"
#include "net.h"
// ncnn private header
#include "../modelwriter.h"
class DataReaderFromEmpty : public ncnn::DataReader
{
public:
virtual int scan(const char* format, void* p) const
{
return 0;
}
virtual size_t read(void* buf, size_t size) const
{
memset(buf, 0, size);
return size;
}
};
static bool read_int8scale_table(const char* filepath, std::map<std::string, ncnn::Mat>& blob_int8scale_table, std::map<std::string, ncnn::Mat>& weight_int8scale_table)
{
blob_int8scale_table.clear();
weight_int8scale_table.clear();
FILE* fp = fopen(filepath, "rb");
if (!fp)
{
fprintf(stderr, "Open %s failed.\n", filepath);
return false;
}
std::string key_str;
std::vector<float> scales;
std::vector<char> line(10240000);
char* pch = NULL;
size_t len = 0;
while (!feof(fp))
{
char* s = fgets(line.data(), (int)line.size(), fp);
if (!s)
break;
float scale = 1.f;
char key[256];
line[strcspn(line.data(), "\r\n")] = 0;
pch = strtok(line.data(), " ");
if (pch == NULL) break;
bool is_key = true;
while (pch != NULL)
{
if (is_key)
{
sscanf(pch, "%255s", key);
key_str = key;
is_key = false;
}
else
{
sscanf(pch, "%f", &scale);
scales.push_back(scale);
}
pch = strtok(NULL, " ");
}
// XYZ_param_N pattern
if (strstr(key_str.c_str(), "_param_"))
{
weight_int8scale_table[key_str] = ncnn::Mat((int)scales.size(), (void*)scales.data()).clone();
}
else
{
blob_int8scale_table[key_str] = ncnn::Mat((int)scales.size(), (void*)scales.data()).clone();
}
key_str.clear();
scales.clear();
}
fclose(fp);
return true;
}
class NetQuantize : public ModelWriter
{
public:
NetQuantize();
std::map<std::string, ncnn::Mat> blob_int8scale_table;
std::map<std::string, ncnn::Mat> weight_int8scale_table;
public:
int quantize_convolution();
int quantize_convolutiondepthwise();
int quantize_innerproduct();
int fuse_requantize();
};
NetQuantize::NetQuantize()
: ModelWriter()
{
}
int NetQuantize::quantize_convolution()
{
const int layer_count = static_cast<int>(layers.size());
for (int i = 0; i < layer_count; i++)
{
// find convolution layer
if (layers[i]->type != "Convolution")
continue;
// find convolution layer
std::map<std::string, ncnn::Mat>::iterator iter_data = blob_int8scale_table.find(layers[i]->name);
if (iter_data == blob_int8scale_table.end())
continue;
char key[256];
sprintf(key, "%s_param_0", layers[i]->name.c_str());
std::map<std::string, ncnn::Mat>::iterator iter = weight_int8scale_table.find(key);
if (iter == weight_int8scale_table.end())
{
fprintf(stderr, "this layer need to be quantized, but no scale param!\n");
return -1;
}
// Convolution - quantize weight from fp32 to int8
ncnn::Convolution* convolution = (ncnn::Convolution*)layers[i];
ncnn::Mat bottom_blob_int8_scales = iter_data->second;
ncnn::Mat weight_data_int8_scales = iter->second;
fprintf(stderr, "quantize_convolution %s\n", convolution->name.c_str());
{
const int maxk = convolution->kernel_w * convolution->kernel_h;
const int num_input = convolution->weight_data_size / convolution->num_output / maxk;
ncnn::Mat weight_data_r2 = convolution->weight_data.reshape(maxk, num_input, convolution->num_output);
ncnn::Mat weight_data_int8;
ncnn::Option opt_q = opt;
opt_q.blob_allocator = convolution->weight_data.allocator;
opt_q.use_packing_layout = false;
ncnn::quantize_to_int8(weight_data_r2, weight_data_int8, weight_data_int8_scales, opt_q);
if (weight_data_int8.empty())
return -100;
convolution->weight_data = weight_data_int8.reshape(convolution->weight_data_size);
}
convolution->int8_scale_term = 2;
convolution->weight_data_int8_scales = weight_data_int8_scales;
convolution->bottom_blob_int8_scales = bottom_blob_int8_scales;
}
return 0;
}
int NetQuantize::quantize_convolutiondepthwise()
{
const int layer_count = static_cast<int>(layers.size());
for (int i = 0; i < layer_count; i++)
{
// find convolution layer
if (layers[i]->type != "ConvolutionDepthWise")
continue;
// find convolutiondepthwise layer
std::map<std::string, ncnn::Mat>::iterator iter_data = blob_int8scale_table.find(layers[i]->name);
if (iter_data == blob_int8scale_table.end())
continue;
char key[256];
sprintf(key, "%s_param_0", layers[i]->name.c_str());
std::map<std::string, ncnn::Mat>::iterator iter = weight_int8scale_table.find(key);
if (iter == weight_int8scale_table.end())
{
fprintf(stderr, "this layer need to be quantized, but no scale param!\n");
return -1;
}
// Convolution - quantize weight from fp32 to int8
ncnn::ConvolutionDepthWise* convdw = (ncnn::ConvolutionDepthWise*)layers[i];
ncnn::Mat bottom_blob_int8_scales = iter_data->second;
ncnn::Mat weight_data_int8_scales = iter->second;
fprintf(stderr, "quantize_convolutiondepthwise %s\n", convdw->name.c_str());
{
ncnn::Mat int8_weight_data(convdw->weight_data_size, (size_t)1u);
if (int8_weight_data.empty())
return -100;
const int weight_data_size_g = convdw->weight_data_size / convdw->group;
for (int g = 0; g < convdw->group; g++)
{
ncnn::Option opt_q = opt;
opt_q.blob_allocator = int8_weight_data.allocator;
opt_q.use_packing_layout = false;
const ncnn::Mat weight_data_g = convdw->weight_data.range(weight_data_size_g * g, weight_data_size_g);
ncnn::Mat int8_weight_data_g = int8_weight_data.range(weight_data_size_g * g, weight_data_size_g);
const ncnn::Mat weight_data_int8_scales_g = weight_data_int8_scales.range(g, 1);
ncnn::quantize_to_int8(weight_data_g, int8_weight_data_g, weight_data_int8_scales_g, opt_q);
}
convdw->weight_data = int8_weight_data;
}
convdw->int8_scale_term = 1;
convdw->weight_data_int8_scales = weight_data_int8_scales;
convdw->bottom_blob_int8_scales = bottom_blob_int8_scales;
}
return 0;
}
int NetQuantize::quantize_innerproduct()
{
const int layer_count = static_cast<int>(layers.size());
for (int i = 0; i < layer_count; i++)
{
// find convolution layer
if (layers[i]->type != "InnerProduct")
continue;
// find InnerProduct layer
std::map<std::string, ncnn::Mat>::iterator iter_data = blob_int8scale_table.find(layers[i]->name);
if (iter_data == blob_int8scale_table.end())
continue;
char key[256];
sprintf(key, "%s_param_0", layers[i]->name.c_str());
std::map<std::string, ncnn::Mat>::iterator iter = weight_int8scale_table.find(key);
if (iter == weight_int8scale_table.end())
{
fprintf(stderr, "this layer need to be quantized, but no scale param!\n");
return -1;
}
// InnerProduct - quantize weight from fp32 to int8
ncnn::InnerProduct* fc = (ncnn::InnerProduct*)layers[i];
ncnn::Mat bottom_blob_int8_scales = iter_data->second;
ncnn::Mat weight_data_int8_scales = iter->second;
fprintf(stderr, "quantize_innerproduct %s\n", fc->name.c_str());
{
const int num_input = fc->weight_data_size / fc->num_output;
ncnn::Mat weight_data_r2 = fc->weight_data.reshape(num_input, fc->num_output);
ncnn::Mat weight_data_int8;
ncnn::Option opt_q = opt;
opt_q.use_packing_layout = false;
ncnn::quantize_to_int8(weight_data_r2, weight_data_int8, weight_data_int8_scales, opt_q);
if (weight_data_int8.empty())
return -100;
fc->weight_data = weight_data_int8.reshape(fc->weight_data_size);
}
fc->int8_scale_term = 2;
fc->weight_data_int8_scales = weight_data_int8_scales;
fc->bottom_blob_int8_scales = bottom_blob_int8_scales;
}
return 0;
}
int NetQuantize::fuse_requantize()
{
const size_t layer_count = layers.size();
for (size_t i = 0; i < layer_count; i++)
{
if (layers[i]->type != "Convolution" && layers[i]->type != "ConvolutionDepthWise")
continue;
// Convolution/ConvolutionDepthWise - Convolution/ConvolutionDepthWise
int top_blob_index = layers[i]->tops[0];
size_t j = i + 1;
for (; j < layer_count; j++)
{
if (layers[j]->type != "Convolution" && layers[j]->type != "ConvolutionDepthWise")
continue;
if (layers[j]->bottoms.size() != 1)
continue;
if (layers[j]->bottoms[0] == top_blob_index)
break;
}
if (j == layer_count)
continue;
// fuse requantize
fprintf(stderr, "fuse_requantize %s %s\n", layers[i]->name.c_str(), layers[j]->name.c_str());
if (layers[i]->type == "Convolution" && layers[j]->type == "Convolution")
{
ncnn::Convolution* convolution1 = (ncnn::Convolution*)layers[i];
ncnn::Convolution* convolution2 = (ncnn::Convolution*)layers[j];
if (convolution1->weight_data.elemsize != 1u || convolution2->weight_data.elemsize != 1u)
continue;
convolution1->int8_scale_term += 100;
convolution1->top_blob_int8_scales = convolution2->bottom_blob_int8_scales;
}
if (layers[i]->type == "Convolution" && layers[j]->type == "ConvolutionDepthWise")
{
ncnn::Convolution* convolution1 = (ncnn::Convolution*)layers[i];
ncnn::ConvolutionDepthWise* convolution2 = (ncnn::ConvolutionDepthWise*)layers[j];
if (convolution1->weight_data.elemsize != 1u || convolution2->weight_data.elemsize != 1u)
continue;
convolution1->int8_scale_term += 100;
convolution1->top_blob_int8_scales = convolution2->bottom_blob_int8_scales;
}
if (layers[i]->type == "ConvolutionDepthWise" && layers[j]->type == "Convolution")
{
ncnn::ConvolutionDepthWise* convolution1 = (ncnn::ConvolutionDepthWise*)layers[i];
ncnn::Convolution* convolution2 = (ncnn::Convolution*)layers[j];
if (convolution1->weight_data.elemsize != 1u || convolution2->weight_data.elemsize != 1u)
continue;
convolution1->int8_scale_term += 100;
convolution1->top_blob_int8_scales = convolution2->bottom_blob_int8_scales;
}
if (layers[i]->type == "ConvolutionDepthWise" && layers[j]->type == "ConvolutionDepthWise")
{
ncnn::ConvolutionDepthWise* convolution1 = (ncnn::ConvolutionDepthWise*)layers[i];
ncnn::ConvolutionDepthWise* convolution2 = (ncnn::ConvolutionDepthWise*)layers[j];
if (convolution1->weight_data.elemsize != 1u || convolution2->weight_data.elemsize != 1u)
continue;
convolution1->int8_scale_term += 100;
convolution1->top_blob_int8_scales = convolution2->bottom_blob_int8_scales;
}
}
for (size_t i = 0; i < layer_count; i++)
{
if (layers[i]->type != "Convolution" && layers[i]->type != "ConvolutionDepthWise")
continue;
// Convolution/ConvolutionDepthWise - Split - Convolution/ConvolutionDepthWise
int top_blob_index = layers[i]->tops[0];
size_t j = i + 1;
for (; j < layer_count; j++)
{
if (layers[j]->type != "Split")
continue;
if (layers[j]->bottoms.size() != 1)
continue;
if (layers[j]->bottoms[0] == top_blob_index)
break;
}
if (j == layer_count)
continue;
ncnn::Split* split = (ncnn::Split*)layers[j];
bool all_conv = true;
for (size_t p = 0; p < split->tops.size(); p++)
{
int split_top_blob_index = split->tops[p];
size_t k = j + 1;
for (; k < layer_count; k++)
{
if (layers[k]->type != "Convolution" && layers[k]->type != "ConvolutionDepthWise")
continue;
if (layers[k]->bottoms.size() != 1)
continue;
if (layers[k]->bottoms[0] == split_top_blob_index)
break;
}
if (k == layer_count)
{
all_conv = false;
break;
}
if (layers[k]->type == "Convolution")
{
ncnn::Convolution* convolution = (ncnn::Convolution*)layers[k];
if (convolution->weight_data.elemsize != 1u)
{
all_conv = false;
break;
}
}
if (layers[k]->type == "ConvolutionDepthWise")
{
ncnn::ConvolutionDepthWise* convolution = (ncnn::ConvolutionDepthWise*)layers[k];
if (convolution->weight_data.elemsize != 1u)
{
all_conv = false;
break;
}
}
}
if (!all_conv)
continue;
j = blobs[split->tops[0]].consumer;
// fuse requantize
fprintf(stderr, "fuse_requantize %s %s\n", layers[i]->name.c_str(), split->name.c_str());
if (layers[i]->type == "Convolution" && layers[j]->type == "Convolution")
{
ncnn::Convolution* convolution1 = (ncnn::Convolution*)layers[i];
ncnn::Convolution* convolution2 = (ncnn::Convolution*)layers[j];
if (convolution1->weight_data.elemsize != 1u || convolution2->weight_data.elemsize != 1u)
continue;
convolution1->int8_scale_term += 100;
convolution1->top_blob_int8_scales = convolution2->bottom_blob_int8_scales;
}
if (layers[i]->type == "Convolution" && layers[j]->type == "ConvolutionDepthWise")
{
ncnn::Convolution* convolution1 = (ncnn::Convolution*)layers[i];
ncnn::ConvolutionDepthWise* convolution2 = (ncnn::ConvolutionDepthWise*)layers[j];
if (convolution1->weight_data.elemsize != 1u || convolution2->weight_data.elemsize != 1u)
continue;
convolution1->int8_scale_term += 100;
convolution1->top_blob_int8_scales = convolution2->bottom_blob_int8_scales;
}
if (layers[i]->type == "ConvolutionDepthWise" && layers[j]->type == "Convolution")
{
ncnn::ConvolutionDepthWise* convolution1 = (ncnn::ConvolutionDepthWise*)layers[i];
ncnn::Convolution* convolution2 = (ncnn::Convolution*)layers[j];
if (convolution1->weight_data.elemsize != 1u || convolution2->weight_data.elemsize != 1u)
continue;
convolution1->int8_scale_term += 100;
convolution1->top_blob_int8_scales = convolution2->bottom_blob_int8_scales;
}
if (layers[i]->type == "ConvolutionDepthWise" && layers[j]->type == "ConvolutionDepthWise")
{
ncnn::ConvolutionDepthWise* convolution1 = (ncnn::ConvolutionDepthWise*)layers[i];
ncnn::ConvolutionDepthWise* convolution2 = (ncnn::ConvolutionDepthWise*)layers[j];
if (convolution1->weight_data.elemsize != 1u || convolution2->weight_data.elemsize != 1u)
continue;
convolution1->int8_scale_term += 100;
convolution1->top_blob_int8_scales = convolution2->bottom_blob_int8_scales;
}
}
return 0;
}
int main(int argc, char** argv)
{
if (argc != 6)
{
fprintf(stderr, "usage: %s [inparam] [inbin] [outparam] [outbin] [calibration table]\n", argv[0]);
return -1;
}
const char* inparam = argv[1];
const char* inbin = argv[2];
const char* outparam = argv[3];
const char* outbin = argv[4];
const char* int8scale_table_path = argv[5];
NetQuantize quantizer;
// parse the calibration scale table
if (int8scale_table_path)
{
bool s2 = read_int8scale_table(int8scale_table_path, quantizer.blob_int8scale_table, quantizer.weight_int8scale_table);
if (!s2)
{
fprintf(stderr, "read_int8scale_table failed\n");
return -1;
}
}
quantizer.load_param(inparam);
if (strcmp(inbin, "null") == 0)
{
DataReaderFromEmpty dr;
quantizer.load_model(dr);
quantizer.gen_random_weight = true;
}
else
quantizer.load_model(inbin);
quantizer.quantize_convolution();
quantizer.quantize_convolutiondepthwise();
quantizer.quantize_innerproduct();
quantizer.fuse_requantize();
quantizer.save(outparam, outbin);
return 0;
}
|