| 1 | // Tencent is pleased to support the open source community by making ncnn available. |
| 2 | // |
| 3 | // Copyright (C) 2024 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 "load_torchscript.h" |
| 16 | |
| 17 | #if _WIN32 |
| 18 | #include <windows.h> |
| 19 | #else |
| 20 | #include <dlfcn.h> |
| 21 | #endif |
| 22 | |
| 23 | #include <torch/script.h> |
| 24 | #include <torch/csrc/api/include/torch/version.h> |
| 25 | #ifdef PNNX_TORCHVISION |
| 26 | namespace vision { |
| 27 | int64_t cuda_version(); |
| 28 | } // namespace vision |
| 29 | #endif |
| 30 | |
| 31 | #include "pass_level0.h" |
| 32 | #include "pass_level1.h" |
| 33 | |
| 34 | namespace pnnx { |
| 35 | |
| 36 | static int get_at_tensor_type(const at::ScalarType& st) |
| 37 | { |
| 38 | if (st == c10::ScalarType::Float) return 1; |
| 39 | if (st == c10::ScalarType::Double) return 2; |
| 40 | if (st == c10::ScalarType::Half) return 3; |
| 41 | if (st == c10::ScalarType::Int) return 4; |
| 42 | if (st == c10::ScalarType::QInt32) return 4; |
| 43 | if (st == c10::ScalarType::Long) return 5; |
| 44 | if (st == c10::ScalarType::Short) return 6; |
| 45 | if (st == c10::ScalarType::Char) return 7; |
| 46 | if (st == c10::ScalarType::QInt8) return 7; |
| 47 | if (st == c10::ScalarType::Byte) return 8; |
| 48 | if (st == c10::ScalarType::QUInt8) return 8; |
| 49 | if (st == c10::ScalarType::Bool) return 9; |
| 50 | if (st == c10::ScalarType::ComplexFloat) return 10; |
| 51 | if (st == c10::ScalarType::ComplexDouble) return 11; |
| 52 | if (st == c10::ScalarType::ComplexHalf) return 12; |
| 53 | if (st == c10::ScalarType::BFloat16) return 13; |
| 54 | return 0; // unknown type |
| 55 | } |
| 56 | |
| 57 | static size_t type_to_elemsize(int type) |
| 58 | { |
| 59 | if (type == 1) return 4; |
| 60 | if (type == 2) return 8; |
| 61 | if (type == 3) return 2; |
| 62 | if (type == 4) return 4; |
| 63 | if (type == 5) return 8; |
| 64 | if (type == 6) return 2; |
| 65 | if (type == 7) return 1; |
| 66 | if (type == 8) return 1; |
| 67 | if (type == 9) return 1; |
| 68 | if (type == 10) return 8; |
| 69 | if (type == 11) return 16; |
| 70 | if (type == 12) return 4; |
| 71 | if (type == 13) return 2; |
| 72 | return 0; // null |
| 73 | } |
| 74 | |
| 75 | Parameter::Parameter(const torch::jit::Node* value_node) |
| 76 | { |
| 77 | type = 0; |
| 78 | |
| 79 | if (value_node->kind() == c10::prim::Constant) |
| 80 | { |
| 81 | if (value_node->output()->type()->kind() == c10::TypeKind::NoneType) |
| 82 | { |
| 83 | type = 0; |
| 84 | return; |
| 85 | } |
| 86 | |
| 87 | if (!value_node->hasAttribute(torch::jit::attr::value)) |
| 88 | { |
| 89 | fprintf(stderr, "no attribute value\n"); |
| 90 | value_node->dump(); |
| 91 | return; |
| 92 | } |
| 93 | |
| 94 | switch (value_node->output()->type()->kind()) |
| 95 | { |
| 96 | case c10::TypeKind::NoneType: |
| 97 | { |
| 98 | type = 0; |
| 99 | break; |
| 100 | } |
| 101 | case c10::TypeKind::BoolType: |
| 102 | { |
| 103 | type = 1; |
| 104 | b = value_node->i(torch::jit::attr::value); |
| 105 | break; |
| 106 | } |
| 107 | case c10::TypeKind::IntType: |
| 108 | { |
| 109 | type = 2; |
| 110 | int64_t i64 = value_node->i(torch::jit::attr::value); |
| 111 | if (i64 == std::numeric_limits<int64_t>::max()) i64 = INT_MAX; |
| 112 | if (i64 == std::numeric_limits<int64_t>::min()) i64 = INT_MIN; |
| 113 | i = (int)i64; |
| 114 | break; |
| 115 | } |
| 116 | case c10::TypeKind::FloatType: |
| 117 | { |
| 118 | type = 3; |
| 119 | f = (float)value_node->f(torch::jit::attr::value); |
| 120 | break; |
| 121 | } |
| 122 | case c10::TypeKind::StringType: |
| 123 | { |
| 124 | type = 4; |
| 125 | s = value_node->s(torch::jit::attr::value); |
| 126 | break; |
| 127 | } |
| 128 | case c10::TypeKind::DeviceObjType: |
| 129 | { |
| 130 | type = 4; |
| 131 | s = value_node->s(torch::jit::attr::value); |
| 132 | break; |
| 133 | } |
| 134 | #if TORCH_VERSION_MAJOR >= 2 || (TORCH_VERSION_MAJOR >= 1 && TORCH_VERSION_MINOR >= 9) |
| 135 | case c10::TypeKind::ComplexType: |
| 136 | { |
| 137 | type = 10; |
| 138 | c = std::complex<float>(value_node->c(torch::jit::attr::value)); |
| 139 | break; |
| 140 | } |
| 141 | #endif |
| 142 | case c10::TypeKind::TensorType: |
| 143 | { |
| 144 | at::Tensor t = value_node->t(torch::jit::attr::value); |
| 145 | |
| 146 | if (t.dim() == 0 && t.numel() == 1) |
| 147 | { |
| 148 | if (t.scalar_type() == c10::ScalarType::Long) |
| 149 | { |
| 150 | type = 2; |
| 151 | int64_t i64 = t.item<int64_t>(); |
| 152 | if (i64 == std::numeric_limits<int64_t>::max()) i64 = INT_MAX; |
| 153 | if (i64 == std::numeric_limits<int64_t>::min()) i64 = INT_MIN; |
| 154 | i = (int)i64; |
| 155 | } |
| 156 | else if (t.scalar_type() == c10::ScalarType::Int) |
| 157 | { |
| 158 | type = 2; |
| 159 | i = t.item<int>(); |
| 160 | } |
| 161 | else if (t.scalar_type() == c10::ScalarType::Double) |
| 162 | { |
| 163 | type = 3; |
| 164 | f = (float)t.item<double>(); |
| 165 | } |
| 166 | else if (t.scalar_type() == c10::ScalarType::Float) |
| 167 | { |
| 168 | type = 3; |
| 169 | f = t.item<float>(); |
| 170 | } |
| 171 | else if (t.scalar_type() == c10::ScalarType::ComplexDouble) |
| 172 | { |
| 173 | type = 10; |
| 174 | c = std::complex<float>(t.item<c10::complex<double> >()); |
| 175 | } |
| 176 | else if (t.scalar_type() == c10::ScalarType::ComplexFloat) |
| 177 | { |
| 178 | type = 10; |
| 179 | c = std::complex<float>(t.item<c10::complex<float> >()); |
| 180 | } |
| 181 | else |
| 182 | { |
| 183 | fprintf(stderr, "unknown Parameter value kind %s of TensorType, t.dim = 0\n", value_node->kind().toDisplayString()); |
| 184 | } |
| 185 | } |
| 186 | else |
| 187 | { |
| 188 | // constant tensor will become pnnx attribute node later |
| 189 | type = 8; |
| 190 | } |
| 191 | |
| 192 | break; |
| 193 | } |
| 194 | case c10::TypeKind::ListType: |
| 195 | { |
| 196 | switch (value_node->output()->type()->containedTypes()[0]->kind()) |
| 197 | { |
| 198 | case c10::TypeKind::IntType: |
| 199 | { |
| 200 | type = 5; |
| 201 | std::vector<int64_t> i64s = value_node->ival(torch::jit::attr::value).toIntVector(); |
| 202 | for (auto i64 : i64s) |
| 203 | { |
| 204 | if (i64 == std::numeric_limits<int64_t>::max()) i64 = INT_MAX; |
| 205 | if (i64 == std::numeric_limits<int64_t>::min()) i64 = INT_MIN; |
| 206 | ai.push_back(i64); |
| 207 | } |
| 208 | break; |
| 209 | } |
| 210 | case c10::TypeKind::FloatType: |
| 211 | { |
| 212 | type = 6; |
| 213 | std::vector<double> fs = value_node->ival(torch::jit::attr::value).toDoubleVector(); |
| 214 | for (auto f : fs) |
| 215 | { |
| 216 | af.push_back((float)f); |
| 217 | } |
| 218 | break; |
| 219 | } |
| 220 | default: |
| 221 | { |
| 222 | fprintf(stderr, "unknown Parameter value list element kind %s\n", c10::typeKindToString(value_node->output()->type()->containedTypes()[0]->kind())); |
| 223 | break; |
| 224 | } |
| 225 | } |
| 226 | break; |
| 227 | } |
| 228 | default: |
| 229 | { |
| 230 | fprintf(stderr, "unknown Parameter value kind %s\n", c10::typeKindToString(value_node->output()->type()->kind())); |
| 231 | break; |
| 232 | } |
| 233 | } |
| 234 | } |
| 235 | else if (value_node->kind() == c10::prim::ListConstruct) |
| 236 | { |
| 237 | switch (value_node->output()->type()->cast<c10::ListType>()->getElementType()->kind()) |
| 238 | { |
| 239 | case c10::TypeKind::IntType: |
| 240 | { |
| 241 | type = 5; |
| 242 | for (const auto& x : value_node->inputs()) |
| 243 | { |
| 244 | if (!x->node()->hasAttribute(torch::jit::attr::value)) |
| 245 | { |
| 246 | fprintf(stderr, "no attribute value in int list\n"); |
| 247 | ai.push_back(0); |
| 248 | continue; |
| 249 | } |
| 250 | |
| 251 | ai.push_back((int)x->node()->i(torch::jit::attr::value)); |
| 252 | } |
| 253 | break; |
| 254 | } |
| 255 | case c10::TypeKind::FloatType: |
| 256 | { |
| 257 | type = 6; |
| 258 | for (const auto& x : value_node->inputs()) |
| 259 | { |
| 260 | if (!x->node()->hasAttribute(torch::jit::attr::value)) |
| 261 | { |
| 262 | fprintf(stderr, "no attribute value in float list\n"); |
| 263 | af.push_back(0.f); |
| 264 | continue; |
| 265 | } |
| 266 | |
| 267 | af.push_back((float)x->node()->f(torch::jit::attr::value)); |
| 268 | } |
| 269 | break; |
| 270 | } |
| 271 | case c10::TypeKind::StringType: |
| 272 | { |
| 273 | type = 7; |
| 274 | for (const auto& x : value_node->inputs()) |
| 275 | { |
| 276 | if (!x->node()->hasAttribute(torch::jit::attr::value)) |
| 277 | { |
| 278 | fprintf(stderr, "no attribute value in string list\n"); |
| 279 | as.push_back(""); |
| 280 | continue; |
| 281 | } |
| 282 | |
| 283 | as.push_back(x->node()->s(torch::jit::attr::value)); |
| 284 | } |
| 285 | break; |
| 286 | } |
| 287 | #if TORCH_VERSION_MAJOR >= 2 || (TORCH_VERSION_MAJOR >= 1 && TORCH_VERSION_MINOR >= 9) |
| 288 | case c10::TypeKind::ComplexType: |
| 289 | { |
| 290 | type = 11; |
| 291 | for (const auto& x : value_node->inputs()) |
| 292 | { |
| 293 | if (!x->node()->hasAttribute(torch::jit::attr::value)) |
| 294 | { |
| 295 | fprintf(stderr, "no attribute value in complex list\n"); |
| 296 | ac.push_back(std::complex<float>(0.f, 0.f)); |
| 297 | continue; |
| 298 | } |
| 299 | |
| 300 | ac.push_back(std::complex<float>(x->node()->c(torch::jit::attr::value))); |
| 301 | } |
| 302 | break; |
| 303 | } |
| 304 | #endif |
| 305 | default: |
| 306 | { |
| 307 | fprintf(stderr, "unknown Parameter value list element kind %s\n", c10::typeKindToString(value_node->output()->type()->cast<c10::ListType>()->getElementType()->kind())); |
| 308 | break; |
| 309 | } |
| 310 | } |
| 311 | } |
| 312 | else |
| 313 | { |
| 314 | fprintf(stderr, "unknown Parameter value_node kind %s\n", value_node->kind().toDisplayString()); |
| 315 | } |
| 316 | } |
| 317 | |
| 318 | Parameter::Parameter(const torch::jit::Value* value) |
| 319 | : Parameter(value->node()) |
| 320 | { |
| 321 | } |
| 322 | |
| 323 | Attribute::Attribute(const at::Tensor& t) |
| 324 | { |
| 325 | type = get_at_tensor_type(t.scalar_type()); |
| 326 | |
| 327 | const int ndim = (int)t.dim(); |
| 328 | |
| 329 | if (ndim == 0) |
| 330 | { |
| 331 | shape = {1}; |
| 332 | |
| 333 | data.resize(type_to_elemsize(type)); |
| 334 | |
| 335 | if (t.scalar_type() == c10::ScalarType::Long) |
| 336 | { |
| 337 | int64_t i = t.item<int64_t>(); |
| 338 | memcpy((void*)data.data(), (const void*)&i, data.size()); |
| 339 | } |
| 340 | else if (t.scalar_type() == c10::ScalarType::Int) |
| 341 | { |
| 342 | int i = t.item<int>(); |
| 343 | memcpy((void*)data.data(), (const void*)&i, data.size()); |
| 344 | } |
| 345 | else if (t.scalar_type() == c10::ScalarType::Double) |
| 346 | { |
| 347 | double f = t.item<double>(); |
| 348 | memcpy((void*)data.data(), (const void*)&f, data.size()); |
| 349 | } |
| 350 | else if (t.scalar_type() == c10::ScalarType::Float) |
| 351 | { |
| 352 | float f = t.item<float>(); |
| 353 | memcpy((void*)data.data(), (const void*)&f, data.size()); |
| 354 | } |
| 355 | else |
| 356 | { |
| 357 | fprintf(stderr, "unknown Attribute tensor scalar type %d\n", type); |
| 358 | } |
| 359 | |
| 360 | return; |
| 361 | } |
| 362 | |
| 363 | shape.resize(ndim); |
| 364 | for (int i = 0; i < ndim; i++) |
| 365 | shape[i] = t.size(i); |
| 366 | |
| 367 | if (shape.size() > 0) |
| 368 | { |
| 369 | data.resize(elemcount() * type_to_elemsize(type)); |
| 370 | memcpy((void*)data.data(), (const void*)t.cpu().contiguous().data_ptr(), data.size()); |
| 371 | } |
| 372 | } |
| 373 | |
| 374 | Operand* Graph::new_operand(const torch::jit::Value* v) |
| 375 | { |
| 376 | // Operand* r = new Operand; |
| 377 | // r->name = v->debugName(); |
| 378 | |
| 379 | Operand* r = new_operand(v->debugName()); |
| 380 | |
| 381 | r->type = -1; |
| 382 | |
| 383 | auto pt = v->type()->cast<c10::TensorType>(); |
| 384 | if (pt) |
| 385 | { |
| 386 | if (pt->scalarType().has_value() && pt->dim().has_value()) |
| 387 | { |
| 388 | r->type = get_at_tensor_type(pt->scalarType().value()); |
| 389 | const int ndim = (int)pt->dim().value(); |
| 390 | r->shape.resize(ndim); |
| 391 | for (int i = 0; i < ndim; i++) |
| 392 | { |
| 393 | if (pt->sizes()[i].has_value()) |
| 394 | r->shape[i] = (int)pt->sizes()[i].value(); |
| 395 | else |
| 396 | r->shape[i] = -1; |
| 397 | } |
| 398 | } |
| 399 | } |
| 400 | |
| 401 | // operands.push_back(r); |
| 402 | return r; |
| 403 | } |
| 404 | |
| 405 | static c10::ScalarType input_type_to_c10_ScalarType(const std::string& t) |
| 406 | { |
| 407 | if (t == "c64") return torch::kComplexFloat; |
| 408 | if (t == "c32") return torch::kComplexHalf; |
| 409 | if (t == "c128") return torch::kComplexDouble; |
| 410 | if (t == "bf16") return torch::kBFloat16; |
| 411 | if (t == "f32") return torch::kFloat32; |
| 412 | if (t == "f16") return torch::kFloat16; |
| 413 | if (t == "f64") return torch::kFloat64; |
| 414 | if (t == "i32") return torch::kInt32; |
| 415 | if (t == "i16") return torch::kInt16; |
| 416 | if (t == "i64") return torch::kInt64; |
| 417 | if (t == "i8") return torch::kInt8; |
| 418 | if (t == "u8") return torch::kUInt8; |
| 419 | |
| 420 | fprintf(stderr, "unsupported type %s fallback to f32\n", t.c_str()); |
| 421 | return torch::kFloat32; |
| 422 | } |
| 423 | |
| 424 | const torch::jit::Node* find_node_by_kind(const std::shared_ptr<torch::jit::Graph>& graph, const std::string& kind) |
| 425 | { |
| 426 | for (const auto& n : graph->nodes()) |
| 427 | { |
| 428 | if (n->kind().toDisplayString() == kind) |
| 429 | return n; |
| 430 | } |
| 431 | |
| 432 | return 0; |
| 433 | } |
| 434 | |
| 435 | int load_torchscript(const std::string& ptpath, Graph& pnnx_graph, |
| 436 | const std::string& device, |
| 437 | const std::vector<std::vector<int64_t> >& input_shapes, |
| 438 | const std::vector<std::string>& input_types, |
| 439 | const std::vector<std::vector<int64_t> >& input_shapes2, |
| 440 | const std::vector<std::string>& input_types2, |
| 441 | const std::vector<std::string>& customop_modules, |
| 442 | const std::vector<std::string>& module_operators, |
| 443 | const std::string& foldable_constants_zippath, |
| 444 | std::set<std::string>& foldable_constants) |
| 445 | { |
| 446 | #ifdef PNNX_TORCHVISION |
| 447 | // call some vision api to register vision ops :P |
| 448 | (void)vision::cuda_version(); |
| 449 | #endif |
| 450 | |
| 451 | for (auto m : customop_modules) |
| 452 | { |
| 453 | fprintf(stderr, "load custom module %s\n", m.c_str()); |
| 454 | #if _WIN32 |
| 455 | HMODULE handle = LoadLibraryExA(m.c_str(), NULL, LOAD_WITH_ALTERED_SEARCH_PATH); |
| 456 | if (!handle) |
| 457 | { |
| 458 | fprintf(stderr, "LoadLibraryExA %s failed %d\n", m.c_str(), GetLastError()); |
| 459 | } |
| 460 | #else |
| 461 | void* handle = dlopen(m.c_str(), RTLD_LAZY); |
| 462 | if (!handle) |
| 463 | { |
| 464 | fprintf(stderr, "dlopen %s failed %s\n", m.c_str(), dlerror()); |
| 465 | } |
| 466 | #endif |
| 467 | } |
| 468 | |
| 469 | std::vector<at::Tensor> input_tensors; |
| 470 | for (size_t i = 0; i < input_shapes.size(); i++) |
| 471 | { |
| 472 | const std::vector<int64_t>& shape = input_shapes[i]; |
| 473 | const std::string& type = input_types[i]; |
| 474 | |
| 475 | at::Tensor t = torch::ones(shape, input_type_to_c10_ScalarType(type)); |
| 476 | if (device == "gpu") |
| 477 | t = t.cuda(); |
| 478 | |
| 479 | input_tensors.push_back(t); |
| 480 | } |
| 481 | |
| 482 | std::vector<at::Tensor> input_tensors2; |
| 483 | for (size_t i = 0; i < input_shapes2.size(); i++) |
| 484 | { |
| 485 | const std::vector<int64_t>& shape = input_shapes2[i]; |
| 486 | const std::string& type = input_types2[i]; |
| 487 | |
| 488 | at::Tensor t = torch::ones(shape, input_type_to_c10_ScalarType(type)); |
| 489 | if (device == "gpu") |
| 490 | t = t.cuda(); |
| 491 | |
| 492 | input_tensors2.push_back(t); |
| 493 | } |
| 494 | |
| 495 | torch::jit::Module mod; |
| 496 | |
| 497 | try |
| 498 | { |
| 499 | mod = torch::jit::load(ptpath, (device == "gpu") ? c10::kCUDA : c10::kCPU); |
| 500 | } |
| 501 | catch (const c10::Error& e) |
| 502 | { |
| 503 | fprintf(stderr, "Load torchscript failed: %s\n", e.what()); |
| 504 | |
| 505 | fprintf(stderr, "Please export model to torchscript as follows\n"); |
| 506 | fprintf(stderr, "------------------------------------------\n"); |
| 507 | fprintf(stderr, "import torch\n"); |
| 508 | fprintf(stderr, "import torchvision.models as models\n\n"); |
| 509 | fprintf(stderr, "net = models.resnet18(pretrained=True)\n"); |
| 510 | fprintf(stderr, "net = net.eval()\n\n"); |
| 511 | fprintf(stderr, "x = torch.rand(1, 3, 224, 224)\n"); |
| 512 | fprintf(stderr, "mod = torch.jit.trace(net, x)\n"); |
| 513 | fprintf(stderr, "mod.save(\"resnet18.pt\")\n"); |
| 514 | fprintf(stderr, "------------------------------------------\n"); |
| 515 | |
| 516 | return -1; |
| 517 | } |
| 518 | |
| 519 | mod.eval(); |
| 520 | |
| 521 | // mod.dump(true, false, false); |
| 522 | // mod.dump(true, true, true); |
| 523 | |
| 524 | auto method = mod.find_method("forward"); |
| 525 | if (!method) |
| 526 | { |
| 527 | auto methods = mod.get_methods(); |
| 528 | if (methods.empty()) |
| 529 | { |
| 530 | fprintf(stderr, "No method in torchscript\n"); |
| 531 | return -1; |
| 532 | } |
| 533 | |
| 534 | method = methods[0]; |
| 535 | fprintf(stderr, "Use method %s as the entrypoint instead of forward\n", method->name().c_str()); |
| 536 | } |
| 537 | |
| 538 | auto g = method->graph(); |
| 539 | |
| 540 | // g->dump(); |
| 541 | |
| 542 | fprintf(stderr, "############# pass_level0\n"); |
| 543 | |
| 544 | pnnx::pass_level0(mod, g, input_tensors, input_tensors2, module_operators, ptpath, device, foldable_constants, foldable_constants_zippath); |
| 545 | |
| 546 | // g->dump(); |
| 547 | |
| 548 | fprintf(stderr, "############# pass_level1\n"); |
| 549 | |
| 550 | pnnx::pass_level1(mod, g, module_operators, pnnx_graph); |
| 551 | |
| 552 | return 0; |
| 553 | } |
| 554 | |
| 555 | } // namespace pnnx |