| 1 | // Tencent is pleased to support the open source community by making ncnn available. |
| 2 | // |
| 3 | // Copyright (C) 2022 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 "save_ncnn.h" |
| 16 | |
| 17 | namespace pnnx { |
| 18 | |
| 19 | static bool type_is_integer(int type) |
| 20 | { |
| 21 | if (type == 1) return false; |
| 22 | if (type == 2) return false; |
| 23 | if (type == 3) return false; |
| 24 | if (type == 4) return true; |
| 25 | if (type == 5) return true; |
| 26 | if (type == 6) return true; |
| 27 | if (type == 7) return true; |
| 28 | if (type == 8) return true; |
| 29 | if (type == 9) return true; |
| 30 | if (type == 10) return false; |
| 31 | if (type == 11) return false; |
| 32 | if (type == 12) return false; |
| 33 | return false; |
| 34 | } |
| 35 | |
| 36 | static const char* type_to_dtype_string(int type) |
| 37 | { |
| 38 | if (type == 1) return "torch.float"; |
| 39 | if (type == 2) return "torch.double"; |
| 40 | if (type == 3) return "torch.half"; |
| 41 | if (type == 4) return "torch.int"; |
| 42 | if (type == 5) |
| 43 | { |
| 44 | fprintf(stderr, "replace ncnn input torch.long type with torch.int\n"); |
| 45 | return "torch.int"; |
| 46 | } |
| 47 | if (type == 6) return "torch.short"; |
| 48 | if (type == 7) return "torch.int8"; |
| 49 | if (type == 8) return "torch.uint8"; |
| 50 | if (type == 9) return "torch.bool"; |
| 51 | if (type == 10) return "torch.complex64"; |
| 52 | if (type == 11) return "torch.complex128"; |
| 53 | if (type == 12) return "torch.complex32"; |
| 54 | return "null"; |
| 55 | } |
| 56 | |
| 57 | static bool string_is_positive_integer(const std::string& t) |
| 58 | { |
| 59 | for (size_t i = 0; i < t.size(); i++) |
| 60 | { |
| 61 | if (t[i] < '0' || t[i] > '9') |
| 62 | return false; |
| 63 | } |
| 64 | |
| 65 | return true; |
| 66 | } |
| 67 | |
| 68 | static unsigned short float32_to_float16(float value) |
| 69 | { |
| 70 | // 1 : 8 : 23 |
| 71 | union |
| 72 | { |
| 73 | unsigned int u; |
| 74 | float f; |
| 75 | } tmp; |
| 76 | |
| 77 | tmp.f = value; |
| 78 | |
| 79 | // 1 : 8 : 23 |
| 80 | unsigned short sign = (tmp.u & 0x80000000) >> 31; |
| 81 | unsigned short exponent = (tmp.u & 0x7F800000) >> 23; |
| 82 | unsigned int significand = tmp.u & 0x7FFFFF; |
| 83 | |
| 84 | // NCNN_LOGE("%d %d %d", sign, exponent, significand); |
| 85 | |
| 86 | // 1 : 5 : 10 |
| 87 | unsigned short fp16; |
| 88 | if (exponent == 0) |
| 89 | { |
| 90 | // zero or denormal, always underflow |
| 91 | fp16 = (sign << 15) | (0x00 << 10) | 0x00; |
| 92 | } |
| 93 | else if (exponent == 0xFF) |
| 94 | { |
| 95 | // infinity or NaN |
| 96 | fp16 = (sign << 15) | (0x1F << 10) | (significand ? 0x200 : 0x00); |
| 97 | } |
| 98 | else |
| 99 | { |
| 100 | // normalized |
| 101 | short newexp = exponent + (-127 + 15); |
| 102 | if (newexp >= 31) |
| 103 | { |
| 104 | // overflow, return infinity |
| 105 | fp16 = (sign << 15) | (0x1F << 10) | 0x00; |
| 106 | } |
| 107 | else if (newexp <= 0) |
| 108 | { |
| 109 | // Some normal fp32 cannot be expressed as normal fp16 |
| 110 | fp16 = (sign << 15) | (0x00 << 10) | 0x00; |
| 111 | } |
| 112 | else |
| 113 | { |
| 114 | // normal fp16 |
| 115 | fp16 = (sign << 15) | (newexp << 10) | (significand >> 13); |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | return fp16; |
| 120 | } |
| 121 | |
| 122 | static size_t alignSize(size_t sz, int n) |
| 123 | { |
| 124 | return (sz + n - 1) & -n; |
| 125 | } |
| 126 | |
| 127 | int save_ncnn(const Graph& g, const std::string& parampath, const std::string& binpath, const std::string& pypath, int fp16) |
| 128 | { |
| 129 | FILE* paramfp = fopen(parampath.c_str(), "wb"); |
| 130 | if (!paramfp) |
| 131 | { |
| 132 | fprintf(stderr, "fopen %s failed\n", parampath.c_str()); |
| 133 | return -1; |
| 134 | } |
| 135 | |
| 136 | FILE* binfp = fopen(binpath.c_str(), "wb"); |
| 137 | if (!binfp) |
| 138 | { |
| 139 | fprintf(stderr, "fopen %s failed\n", binpath.c_str()); |
| 140 | fclose(paramfp); |
| 141 | return -1; |
| 142 | } |
| 143 | |
| 144 | // magic |
| 145 | fprintf(paramfp, "7767517\n"); |
| 146 | |
| 147 | // op count and oprand count |
| 148 | fprintf(paramfp, "%d %d\n", (int)g.ops.size(), (int)g.operands.size()); |
| 149 | |
| 150 | for (const Operator* op : g.ops) |
| 151 | { |
| 152 | fprintf(paramfp, "%-24s %-24s %d %d", op->type.c_str(), op->name.c_str(), (int)op->inputs.size(), (int)op->outputs.size()); |
| 153 | |
| 154 | for (const Operand* oprand : op->inputs) |
| 155 | { |
| 156 | fprintf(paramfp, " %s", oprand->name.c_str()); |
| 157 | } |
| 158 | |
| 159 | for (const Operand* oprand : op->outputs) |
| 160 | { |
| 161 | fprintf(paramfp, " %s", oprand->name.c_str()); |
| 162 | } |
| 163 | |
| 164 | for (const auto& it : op->params) |
| 165 | { |
| 166 | const Parameter& param = it.second; |
| 167 | |
| 168 | if (!string_is_positive_integer(it.first)) |
| 169 | { |
| 170 | fprintf(stderr, "ignore %s %s param %s=", op->type.c_str(), op->name.c_str(), it.first.c_str()); |
| 171 | |
| 172 | if (param.type == 0) |
| 173 | { |
| 174 | fprintf(stderr, "None"); |
| 175 | } |
| 176 | if (param.type == 1) |
| 177 | { |
| 178 | if (param.b) |
| 179 | fprintf(stderr, "True"); |
| 180 | else |
| 181 | fprintf(stderr, "False"); |
| 182 | } |
| 183 | if (param.type == 2) |
| 184 | { |
| 185 | fprintf(stderr, "%d", param.i); |
| 186 | } |
| 187 | if (param.type == 3) |
| 188 | { |
| 189 | fprintf(stderr, "%e", param.f); |
| 190 | } |
| 191 | if (param.type == 4) |
| 192 | { |
| 193 | fprintf(stderr, "%s", param.s.c_str()); |
| 194 | } |
| 195 | if (param.type == 5) |
| 196 | { |
| 197 | fprintf(stderr, "("); |
| 198 | for (size_t i = 0; i < param.ai.size(); i++) |
| 199 | { |
| 200 | fprintf(stderr, "%d", param.ai[i]); |
| 201 | if (i + 1 != param.ai.size()) |
| 202 | fprintf(stderr, ","); |
| 203 | } |
| 204 | fprintf(stderr, ")"); |
| 205 | } |
| 206 | if (param.type == 6) |
| 207 | { |
| 208 | fprintf(stderr, "("); |
| 209 | for (size_t i = 0; i < param.af.size(); i++) |
| 210 | { |
| 211 | fprintf(stderr, "%e", param.af[i]); |
| 212 | if (i + 1 != param.af.size()) |
| 213 | fprintf(stderr, ","); |
| 214 | } |
| 215 | fprintf(stderr, ")"); |
| 216 | } |
| 217 | if (param.type == 7) |
| 218 | { |
| 219 | fprintf(stderr, "("); |
| 220 | for (size_t i = 0; i < param.as.size(); i++) |
| 221 | { |
| 222 | fprintf(stderr, "%s", param.as[i].c_str()); |
| 223 | if (i + 1 != param.as.size()) |
| 224 | fprintf(stderr, ","); |
| 225 | } |
| 226 | fprintf(stderr, ")"); |
| 227 | } |
| 228 | fprintf(stderr, "\n"); |
| 229 | |
| 230 | continue; |
| 231 | } |
| 232 | |
| 233 | const int idkey = std::stoi(it.first); |
| 234 | if (param.type == 2) |
| 235 | { |
| 236 | fprintf(paramfp, " %d=%d", idkey, param.i); |
| 237 | } |
| 238 | if (param.type == 3) |
| 239 | { |
| 240 | fprintf(paramfp, " %d=%e", idkey, param.f); |
| 241 | } |
| 242 | if (param.type == 5) |
| 243 | { |
| 244 | const int array_size = (int)param.ai.size(); |
| 245 | fprintf(paramfp, " %d=%d", -23300 - idkey, array_size); |
| 246 | for (size_t i = 0; i < param.ai.size(); i++) |
| 247 | { |
| 248 | fprintf(paramfp, ",%d", param.ai[i]); |
| 249 | } |
| 250 | } |
| 251 | if (param.type == 6) |
| 252 | { |
| 253 | const int array_size = (int)param.af.size(); |
| 254 | fprintf(paramfp, " %d=%d", -23300 - idkey, array_size); |
| 255 | for (size_t i = 0; i < param.af.size(); i++) |
| 256 | { |
| 257 | fprintf(paramfp, ",%e", param.af[i]); |
| 258 | } |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | bool is_type_flag_fp32 = false; |
| 263 | for (const auto& it : op->attrs) |
| 264 | { |
| 265 | // fprintf(paramfp, " @%s=", it.first.c_str()); |
| 266 | |
| 267 | const Attribute& attr = it.second; |
| 268 | |
| 269 | if (fp16 && is_type_flag_fp32) |
| 270 | { |
| 271 | // fp32 -> fp16 |
| 272 | const float* p = (const float*)attr.data.data(); |
| 273 | int len = attr.data.size() / 4; |
| 274 | std::vector<char> data_fp16(alignSize(len * 2, 4)); |
| 275 | unsigned short* p_fp16 = (unsigned short*)data_fp16.data(); |
| 276 | for (int i = 0; i < len; i++) |
| 277 | { |
| 278 | p_fp16[i] = float32_to_float16(p[i]); |
| 279 | } |
| 280 | |
| 281 | // pad size to 4bytes |
| 282 | if (len % 2 == 1) |
| 283 | { |
| 284 | // pad with fixed value for model hash consistency |
| 285 | p_fp16[len] = 0x2283; |
| 286 | } |
| 287 | |
| 288 | fwrite(data_fp16.data(), data_fp16.size(), 1, binfp); |
| 289 | |
| 290 | is_type_flag_fp32 = false; |
| 291 | continue; |
| 292 | } |
| 293 | |
| 294 | if (fp16 && attr.type == 0 && attr.data == std::vector<char> {0, 0, 0, 0}) |
| 295 | { |
| 296 | // write fp16 flag |
| 297 | unsigned int fp16_flag = 0x01306B47; |
| 298 | fwrite((const char*)&fp16_flag, sizeof(fp16_flag), 1, binfp); |
| 299 | |
| 300 | is_type_flag_fp32 = true; |
| 301 | continue; |
| 302 | } |
| 303 | |
| 304 | fwrite(attr.data.data(), attr.data.size(), 1, binfp); |
| 305 | } |
| 306 | |
| 307 | // if (op->inputnames.size() == op->inputs.size()) |
| 308 | // { |
| 309 | // for (size_t i = 0; i < op->inputs.size(); i++) |
| 310 | // { |
| 311 | // const Operand* oprand = op->inputs[i]; |
| 312 | // fprintf(paramfp, " $%s=%s", op->inputnames[i].c_str(), oprand->name.c_str()); |
| 313 | // } |
| 314 | // } |
| 315 | |
| 316 | // for (const Operand* oprand : op->outputs) |
| 317 | // { |
| 318 | // if (oprand->params.find("__batch_index") == oprand->params.end()) |
| 319 | // continue; |
| 320 | // |
| 321 | // const int batch_index = oprand->params.at("__batch_index").i; |
| 322 | // |
| 323 | // fprintf(paramfp, " #%s=%d", oprand->name.c_str(), batch_index); |
| 324 | // } |
| 325 | |
| 326 | // for (const Operand* oprand : op->outputs) |
| 327 | // { |
| 328 | // if (oprand->shape.empty()) |
| 329 | // continue; |
| 330 | // |
| 331 | // fprintf(paramfp, " #%s=", oprand->name.c_str()); |
| 332 | // |
| 333 | // fprintf(paramfp, "("); |
| 334 | // for (int64_t i = 0; i < oprand->shape.size() - 1; i++) |
| 335 | // { |
| 336 | // fprintf(paramfp, "%d,", oprand->shape[i]); |
| 337 | // } |
| 338 | // if (oprand->shape.size() > 0) |
| 339 | // fprintf(paramfp, "%d", oprand->shape[oprand->shape.size() - 1]); |
| 340 | // fprintf(paramfp, ")"); |
| 341 | // |
| 342 | // fprintf(paramfp, type_to_string(oprand->type)); |
| 343 | // } |
| 344 | |
| 345 | fprintf(paramfp, "\n"); |
| 346 | } |
| 347 | |
| 348 | fclose(paramfp); |
| 349 | fclose(binfp); |
| 350 | |
| 351 | FILE* pyfp = fopen(pypath.c_str(), "wb"); |
| 352 | if (!pyfp) |
| 353 | { |
| 354 | fprintf(stderr, "fopen %s failed\n", pypath.c_str()); |
| 355 | return -1; |
| 356 | } |
| 357 | |
| 358 | fprintf(pyfp, "import numpy as np\n"); |
| 359 | fprintf(pyfp, "import ncnn\n"); |
| 360 | fprintf(pyfp, "import torch\n"); |
| 361 | |
| 362 | fprintf(pyfp, "\n"); |
| 363 | |
| 364 | // test inference |
| 365 | { |
| 366 | fprintf(pyfp, "def test_inference():\n"); |
| 367 | fprintf(pyfp, " torch.manual_seed(0)\n"); |
| 368 | |
| 369 | for (int input_index = 0;; input_index++) |
| 370 | { |
| 371 | std::string input_name = std::string("in") + std::to_string(input_index); |
| 372 | const Operand* r = g.get_operand(input_name); |
| 373 | if (!r) |
| 374 | break; |
| 375 | |
| 376 | if (type_is_integer(r->type)) |
| 377 | { |
| 378 | fprintf(pyfp, " %s = torch.randint(10, (", input_name.c_str()); |
| 379 | for (size_t i = 0; i < r->shape.size(); i++) |
| 380 | { |
| 381 | fprintf(pyfp, "%d", r->shape[i]); |
| 382 | if (i + 1 != r->shape.size() || r->shape.size() == 1) |
| 383 | fprintf(pyfp, ", "); |
| 384 | } |
| 385 | fprintf(pyfp, "), dtype=%s)\n", type_to_dtype_string(r->type)); |
| 386 | } |
| 387 | else |
| 388 | { |
| 389 | fprintf(pyfp, " %s = torch.rand(", input_name.c_str()); |
| 390 | for (size_t i = 0; i < r->shape.size(); i++) |
| 391 | { |
| 392 | fprintf(pyfp, "%d, ", r->shape[i]); |
| 393 | } |
| 394 | fprintf(pyfp, "dtype=%s)\n", type_to_dtype_string(r->type)); |
| 395 | } |
| 396 | } |
| 397 | |
| 398 | fprintf(pyfp, " out = []\n"); |
| 399 | fprintf(pyfp, "\n"); |
| 400 | |
| 401 | fprintf(pyfp, " with ncnn.Net() as net:\n"); |
| 402 | fprintf(pyfp, " net.load_param(\"%s\")\n", parampath.c_str()); |
| 403 | fprintf(pyfp, " net.load_model(\"%s\")\n", binpath.c_str()); |
| 404 | fprintf(pyfp, "\n"); |
| 405 | fprintf(pyfp, " with net.create_extractor() as ex:\n"); |
| 406 | |
| 407 | for (int input_index = 0;; input_index++) |
| 408 | { |
| 409 | std::string input_name = std::string("in") + std::to_string(input_index); |
| 410 | const Operand* r = g.get_operand(input_name); |
| 411 | if (!r) |
| 412 | break; |
| 413 | |
| 414 | const int batch_index = r->params.at("__batch_index").i; |
| 415 | if (batch_index != 233) |
| 416 | { |
| 417 | fprintf(pyfp, " ex.input(\"%s\", ncnn.Mat(%s.squeeze(%d).numpy()).clone())\n", input_name.c_str(), input_name.c_str(), batch_index); |
| 418 | } |
| 419 | else |
| 420 | { |
| 421 | fprintf(pyfp, " ex.input(\"%s\", ncnn.Mat(%s.numpy()).clone())\n", input_name.c_str(), input_name.c_str()); |
| 422 | } |
| 423 | } |
| 424 | |
| 425 | fprintf(pyfp, "\n"); |
| 426 | |
| 427 | for (int output_index = 0;; output_index++) |
| 428 | { |
| 429 | std::string output_name = std::string("out") + std::to_string(output_index); |
| 430 | const Operand* r = g.get_operand(output_name); |
| 431 | if (!r) |
| 432 | break; |
| 433 | |
| 434 | fprintf(pyfp, " _, %s = ex.extract(\"%s\")\n", output_name.c_str(), output_name.c_str()); |
| 435 | |
| 436 | const int batch_index = r->params.at("__batch_index").i; |
| 437 | if (batch_index != 233) |
| 438 | { |
| 439 | fprintf(pyfp, " out.append(torch.from_numpy(np.array(%s)).unsqueeze(%d))\n", output_name.c_str(), batch_index); |
| 440 | } |
| 441 | else |
| 442 | { |
| 443 | fprintf(pyfp, " out.append(torch.from_numpy(np.array(%s)))\n", output_name.c_str()); |
| 444 | } |
| 445 | } |
| 446 | |
| 447 | fprintf(pyfp, "\n"); |
| 448 | |
| 449 | fprintf(pyfp, " if len(out) == 1:\n"); |
| 450 | fprintf(pyfp, " return out[0]\n"); |
| 451 | fprintf(pyfp, " else:\n"); |
| 452 | fprintf(pyfp, " return tuple(out)\n"); |
| 453 | } |
| 454 | |
| 455 | fprintf(pyfp, "\n"); |
| 456 | |
| 457 | // main |
| 458 | { |
| 459 | fprintf(pyfp, "if __name__ == \"__main__\":\n"); |
| 460 | fprintf(pyfp, " print(test_inference())\n"); |
| 461 | } |
| 462 | |
| 463 | fclose(pyfp); |
| 464 | |
| 465 | return 0; |
| 466 | } |
| 467 | |
| 468 | } // namespace pnnx |