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.

load_torchscript.cpp 24 kB

11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  1. // Copyright 2024 Tencent
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. #include "load_torchscript.h"
  4. #if _WIN32
  5. #include <windows.h>
  6. #else
  7. #include <dlfcn.h>
  8. #endif
  9. #include <torch/script.h>
  10. #include <torch/csrc/api/include/torch/version.h>
  11. #include <torch/csrc/jit/serialization/import_read.h>
  12. #ifdef PNNX_TORCHVISION
  13. namespace vision {
  14. int64_t cuda_version();
  15. } // namespace vision
  16. #endif
  17. #include "pass_level0.h"
  18. #include "pass_level1.h"
  19. #include "pass_level1/fuse_module_pass.h"
  20. namespace pnnx {
  21. static int get_at_tensor_type(const at::ScalarType& st)
  22. {
  23. if (st == c10::ScalarType::Float) return 1;
  24. if (st == c10::ScalarType::Double) return 2;
  25. if (st == c10::ScalarType::Half) return 3;
  26. if (st == c10::ScalarType::Int) return 4;
  27. if (st == c10::ScalarType::QInt32) return 4;
  28. if (st == c10::ScalarType::Long) return 5;
  29. if (st == c10::ScalarType::Short) return 6;
  30. if (st == c10::ScalarType::Char) return 7;
  31. if (st == c10::ScalarType::QInt8) return 7;
  32. if (st == c10::ScalarType::Byte) return 8;
  33. if (st == c10::ScalarType::QUInt8) return 8;
  34. if (st == c10::ScalarType::Bool) return 9;
  35. if (st == c10::ScalarType::ComplexFloat) return 10;
  36. if (st == c10::ScalarType::ComplexDouble) return 11;
  37. if (st == c10::ScalarType::ComplexHalf) return 12;
  38. if (st == c10::ScalarType::BFloat16) return 13;
  39. return 0; // unknown type
  40. }
  41. static size_t type_to_elemsize(int type)
  42. {
  43. if (type == 1) return 4;
  44. if (type == 2) return 8;
  45. if (type == 3) return 2;
  46. if (type == 4) return 4;
  47. if (type == 5) return 8;
  48. if (type == 6) return 2;
  49. if (type == 7) return 1;
  50. if (type == 8) return 1;
  51. if (type == 9) return 1;
  52. if (type == 10) return 8;
  53. if (type == 11) return 16;
  54. if (type == 12) return 4;
  55. if (type == 13) return 2;
  56. return 0; // null
  57. }
  58. Parameter::Parameter(const torch::jit::Node* value_node)
  59. {
  60. type = 0;
  61. if (value_node->kind() == c10::prim::Constant)
  62. {
  63. if (value_node->output()->type()->kind() == c10::TypeKind::NoneType)
  64. {
  65. type = 0;
  66. return;
  67. }
  68. if (!value_node->hasAttribute(torch::jit::attr::value))
  69. {
  70. fprintf(stderr, "no attribute value\n");
  71. value_node->dump();
  72. return;
  73. }
  74. switch (value_node->output()->type()->kind())
  75. {
  76. case c10::TypeKind::NoneType:
  77. {
  78. type = 0;
  79. break;
  80. }
  81. case c10::TypeKind::BoolType:
  82. {
  83. type = 1;
  84. b = value_node->i(torch::jit::attr::value);
  85. break;
  86. }
  87. case c10::TypeKind::IntType:
  88. {
  89. type = 2;
  90. int64_t i64 = value_node->i(torch::jit::attr::value);
  91. if (i64 == std::numeric_limits<int64_t>::max()) i64 = INT_MAX;
  92. if (i64 == std::numeric_limits<int64_t>::min()) i64 = INT_MIN;
  93. i = (int)i64;
  94. break;
  95. }
  96. case c10::TypeKind::FloatType:
  97. {
  98. type = 3;
  99. f = (float)value_node->f(torch::jit::attr::value);
  100. break;
  101. }
  102. case c10::TypeKind::StringType:
  103. {
  104. type = 4;
  105. s = value_node->s(torch::jit::attr::value);
  106. break;
  107. }
  108. case c10::TypeKind::DeviceObjType:
  109. {
  110. type = 4;
  111. s = value_node->s(torch::jit::attr::value);
  112. break;
  113. }
  114. #if TORCH_VERSION_MAJOR >= 2 || (TORCH_VERSION_MAJOR >= 1 && TORCH_VERSION_MINOR >= 9)
  115. case c10::TypeKind::ComplexType:
  116. {
  117. type = 10;
  118. c = std::complex<float>(value_node->c(torch::jit::attr::value));
  119. break;
  120. }
  121. #endif
  122. case c10::TypeKind::TensorType:
  123. {
  124. at::Tensor t = value_node->t(torch::jit::attr::value);
  125. if (t.dim() == 0 && t.numel() == 1)
  126. {
  127. if (t.scalar_type() == c10::ScalarType::Long)
  128. {
  129. type = 2;
  130. int64_t i64 = t.item<int64_t>();
  131. if (i64 == std::numeric_limits<int64_t>::max()) i64 = INT_MAX;
  132. if (i64 == std::numeric_limits<int64_t>::min()) i64 = INT_MIN;
  133. i = (int)i64;
  134. }
  135. else if (t.scalar_type() == c10::ScalarType::Int)
  136. {
  137. type = 2;
  138. i = t.item<int>();
  139. }
  140. else if (t.scalar_type() == c10::ScalarType::Double)
  141. {
  142. type = 3;
  143. f = (float)t.item<double>();
  144. }
  145. else if (t.scalar_type() == c10::ScalarType::Float)
  146. {
  147. type = 3;
  148. f = t.item<float>();
  149. }
  150. else if (t.scalar_type() == c10::ScalarType::ComplexDouble)
  151. {
  152. type = 10;
  153. c = std::complex<float>(t.item<c10::complex<double> >());
  154. }
  155. else if (t.scalar_type() == c10::ScalarType::ComplexFloat)
  156. {
  157. type = 10;
  158. c = std::complex<float>(t.item<c10::complex<float> >());
  159. }
  160. else
  161. {
  162. fprintf(stderr, "unknown Parameter value kind %s of TensorType, t.dim = 0\n", value_node->kind().toDisplayString());
  163. }
  164. }
  165. else
  166. {
  167. // constant tensor will become pnnx attribute node later
  168. type = 8;
  169. }
  170. break;
  171. }
  172. case c10::TypeKind::ListType:
  173. {
  174. switch (value_node->output()->type()->containedTypes()[0]->kind())
  175. {
  176. case c10::TypeKind::IntType:
  177. {
  178. type = 5;
  179. std::vector<int64_t> i64s = value_node->ival(torch::jit::attr::value).toIntVector();
  180. for (auto i64 : i64s)
  181. {
  182. if (i64 == std::numeric_limits<int64_t>::max()) i64 = INT_MAX;
  183. if (i64 == std::numeric_limits<int64_t>::min()) i64 = INT_MIN;
  184. ai.push_back(i64);
  185. }
  186. break;
  187. }
  188. case c10::TypeKind::FloatType:
  189. {
  190. type = 6;
  191. std::vector<double> fs = value_node->ival(torch::jit::attr::value).toDoubleVector();
  192. for (auto f : fs)
  193. {
  194. af.push_back((float)f);
  195. }
  196. break;
  197. }
  198. default:
  199. {
  200. fprintf(stderr, "unknown Parameter value list element kind %s\n", c10::typeKindToString(value_node->output()->type()->containedTypes()[0]->kind()));
  201. break;
  202. }
  203. }
  204. break;
  205. }
  206. default:
  207. {
  208. fprintf(stderr, "unknown Parameter value kind %s\n", c10::typeKindToString(value_node->output()->type()->kind()));
  209. break;
  210. }
  211. }
  212. }
  213. else if (value_node->kind() == c10::prim::ListConstruct)
  214. {
  215. switch (value_node->output()->type()->cast<c10::ListType>()->getElementType()->kind())
  216. {
  217. case c10::TypeKind::IntType:
  218. {
  219. type = 5;
  220. for (const auto& x : value_node->inputs())
  221. {
  222. if (!x->node()->hasAttribute(torch::jit::attr::value))
  223. {
  224. fprintf(stderr, "no attribute value in int list\n");
  225. ai.push_back(0);
  226. continue;
  227. }
  228. ai.push_back((int)x->node()->i(torch::jit::attr::value));
  229. }
  230. break;
  231. }
  232. case c10::TypeKind::FloatType:
  233. {
  234. type = 6;
  235. for (const auto& x : value_node->inputs())
  236. {
  237. if (!x->node()->hasAttribute(torch::jit::attr::value))
  238. {
  239. fprintf(stderr, "no attribute value in float list\n");
  240. af.push_back(0.f);
  241. continue;
  242. }
  243. af.push_back((float)x->node()->f(torch::jit::attr::value));
  244. }
  245. break;
  246. }
  247. case c10::TypeKind::StringType:
  248. {
  249. type = 7;
  250. for (const auto& x : value_node->inputs())
  251. {
  252. if (!x->node()->hasAttribute(torch::jit::attr::value))
  253. {
  254. fprintf(stderr, "no attribute value in string list\n");
  255. as.push_back("");
  256. continue;
  257. }
  258. as.push_back(x->node()->s(torch::jit::attr::value));
  259. }
  260. break;
  261. }
  262. #if TORCH_VERSION_MAJOR >= 2 || (TORCH_VERSION_MAJOR >= 1 && TORCH_VERSION_MINOR >= 9)
  263. case c10::TypeKind::ComplexType:
  264. {
  265. type = 11;
  266. for (const auto& x : value_node->inputs())
  267. {
  268. if (!x->node()->hasAttribute(torch::jit::attr::value))
  269. {
  270. fprintf(stderr, "no attribute value in complex list\n");
  271. ac.push_back(std::complex<float>(0.f, 0.f));
  272. continue;
  273. }
  274. ac.push_back(std::complex<float>(x->node()->c(torch::jit::attr::value)));
  275. }
  276. break;
  277. }
  278. #endif
  279. default:
  280. {
  281. fprintf(stderr, "unknown Parameter value list element kind %s\n", c10::typeKindToString(value_node->output()->type()->cast<c10::ListType>()->getElementType()->kind()));
  282. break;
  283. }
  284. }
  285. }
  286. else
  287. {
  288. fprintf(stderr, "unknown Parameter value_node kind %s\n", value_node->kind().toDisplayString());
  289. }
  290. }
  291. Parameter::Parameter(const torch::jit::Value* value)
  292. : Parameter(value->node())
  293. {
  294. }
  295. Attribute::Attribute(const at::Tensor& t)
  296. {
  297. type = get_at_tensor_type(t.scalar_type());
  298. const int ndim = (int)t.dim();
  299. if (ndim == 0)
  300. {
  301. shape = {1};
  302. data.resize(type_to_elemsize(type));
  303. if (t.scalar_type() == c10::ScalarType::Long)
  304. {
  305. int64_t i = t.item<int64_t>();
  306. memcpy((void*)data.data(), (const void*)&i, data.size());
  307. }
  308. else if (t.scalar_type() == c10::ScalarType::Int)
  309. {
  310. int i = t.item<int>();
  311. memcpy((void*)data.data(), (const void*)&i, data.size());
  312. }
  313. else if (t.scalar_type() == c10::ScalarType::Double)
  314. {
  315. double f = t.item<double>();
  316. memcpy((void*)data.data(), (const void*)&f, data.size());
  317. }
  318. else if (t.scalar_type() == c10::ScalarType::Float)
  319. {
  320. float f = t.item<float>();
  321. memcpy((void*)data.data(), (const void*)&f, data.size());
  322. }
  323. else
  324. {
  325. fprintf(stderr, "unknown Attribute tensor scalar type %d\n", type);
  326. }
  327. return;
  328. }
  329. shape.resize(ndim);
  330. for (int i = 0; i < ndim; i++)
  331. shape[i] = t.size(i);
  332. if (shape.size() > 0)
  333. {
  334. data.resize(elemcount() * type_to_elemsize(type));
  335. memcpy((void*)data.data(), (const void*)t.cpu().contiguous().data_ptr(), data.size());
  336. }
  337. }
  338. Attribute::Attribute(const TorchTensorProxy& t)
  339. : Attribute(t.t())
  340. {
  341. }
  342. Operand* Graph::new_operand(const torch::jit::Value* v)
  343. {
  344. // Operand* r = new Operand;
  345. // r->name = v->debugName();
  346. Operand* r = new_operand(v->debugName());
  347. r->type = -1;
  348. auto pt = v->type()->cast<c10::TensorType>();
  349. if (pt)
  350. {
  351. if (pt->scalarType().has_value() && pt->dim().has_value())
  352. {
  353. r->type = get_at_tensor_type(pt->scalarType().value());
  354. const int ndim = (int)pt->dim().value();
  355. r->shape.resize(ndim);
  356. for (int i = 0; i < ndim; i++)
  357. {
  358. if (pt->sizes()[i].has_value())
  359. r->shape[i] = (int)pt->sizes()[i].value();
  360. else
  361. r->shape[i] = -1;
  362. }
  363. }
  364. }
  365. // operands.push_back(r);
  366. return r;
  367. }
  368. static c10::ScalarType input_type_to_c10_ScalarType(const std::string& t)
  369. {
  370. if (t == "c64") return torch::kComplexFloat;
  371. if (t == "c32") return torch::kComplexHalf;
  372. if (t == "c128") return torch::kComplexDouble;
  373. if (t == "bf16") return torch::kBFloat16;
  374. if (t == "f32") return torch::kFloat32;
  375. if (t == "f16") return torch::kFloat16;
  376. if (t == "f64") return torch::kFloat64;
  377. if (t == "i32") return torch::kInt32;
  378. if (t == "i16") return torch::kInt16;
  379. if (t == "i64") return torch::kInt64;
  380. if (t == "i8") return torch::kInt8;
  381. if (t == "u8") return torch::kUInt8;
  382. fprintf(stderr, "unsupported type %s fallback to f32\n", t.c_str());
  383. return torch::kFloat32;
  384. }
  385. static const char* get_at_tensor_type_str(const at::ScalarType& st)
  386. {
  387. if (st == c10::ScalarType::Float) return "f32";
  388. if (st == c10::ScalarType::Double) return "f64";
  389. if (st == c10::ScalarType::Half) return "f16";
  390. if (st == c10::ScalarType::Int) return "i32";
  391. if (st == c10::ScalarType::Long) return "i64";
  392. if (st == c10::ScalarType::Short) return "i16";
  393. if (st == c10::ScalarType::Char) return "i8";
  394. if (st == c10::ScalarType::Byte) return "u8";
  395. if (st == c10::ScalarType::ComplexFloat) return "c64";
  396. if (st == c10::ScalarType::ComplexDouble) return "c128";
  397. if (st == c10::ScalarType::ComplexHalf) return "c32";
  398. if (st == c10::ScalarType::BFloat16) return "bf16";
  399. // unknown
  400. fprintf(stderr, "unsupported tensor elem data type %d\n", (int)st);
  401. return "";
  402. }
  403. static void print_shape_list(const std::vector<std::vector<int64_t> >& shapes, const std::vector<std::string>& types)
  404. {
  405. for (size_t i = 0; i < shapes.size(); i++)
  406. {
  407. const std::vector<int64_t>& s = shapes[i];
  408. const std::string& t = types[i];
  409. fprintf(stderr, "[");
  410. for (size_t j = 0; j < s.size(); j++)
  411. {
  412. fprintf(stderr, "%ld", s[j]);
  413. if (j != s.size() - 1)
  414. fprintf(stderr, ",");
  415. }
  416. fprintf(stderr, "]");
  417. fprintf(stderr, "%s", t.c_str());
  418. if (i != shapes.size() - 1)
  419. fprintf(stderr, ",");
  420. }
  421. }
  422. static void append_input(std::vector<std::vector<int64_t> >& input_shapes, std::vector<std::string>& input_types, const torch::jit::IValue& v)
  423. {
  424. if (v.isTensor())
  425. {
  426. const auto& tensor = v.toTensor();
  427. input_shapes.push_back(tensor.sizes().vec());
  428. input_types.push_back(get_at_tensor_type_str(tensor.scalar_type()));
  429. }
  430. else if (v.isList())
  431. {
  432. for (const auto& v2 : v.toList())
  433. append_input(input_shapes, input_types, v2);
  434. }
  435. else if (v.isTuple())
  436. {
  437. for (const auto& v2 : v.toTuple()->elements())
  438. append_input(input_shapes, input_types, v2);
  439. }
  440. else if (v.isGenericDict())
  441. {
  442. for (const auto& kv2 : v.toGenericDict())
  443. append_input(input_shapes, input_types, kv2.value());
  444. }
  445. else
  446. {
  447. fprintf(stderr, "unsupported traced input type %s\n", v.tagKind().c_str());
  448. }
  449. }
  450. static void get_traced_input_shape(const std::string& ptpath, std::vector<std::vector<int64_t> >& input_shapes, std::vector<std::string>& input_types)
  451. {
  452. try
  453. {
  454. // read traced_inputs.pkl
  455. caffe2::serialize::PyTorchStreamReader reader(ptpath);
  456. auto v = torch::jit::readArchiveAndTensors("traced_inputs", "", "traced_inputs/", c10::nullopt, c10::nullopt, c10::nullopt, reader);
  457. if (!v.isGenericDict())
  458. return;
  459. for (const auto& entry : v.toGenericDict())
  460. {
  461. if (entry.key() != "forward")
  462. continue;
  463. append_input(input_shapes, input_types, entry.value());
  464. break;
  465. }
  466. }
  467. catch (...)
  468. {
  469. // no traced_inputs.pkl pass
  470. }
  471. }
  472. static bool check_input_shape(const std::vector<std::vector<int64_t> >& traced_input_shapes, const std::vector<std::string>& traced_input_types, const std::vector<std::vector<int64_t> >& input_shapes, const std::vector<std::string>& input_types)
  473. {
  474. if (input_shapes.size() != traced_input_shapes.size())
  475. {
  476. fprintf(stderr, "input_shape expect %d tensors but got %d\n", (int)traced_input_shapes.size(), (int)input_shapes.size());
  477. return false;
  478. }
  479. for (size_t i = 0; i < traced_input_shapes.size(); i++)
  480. {
  481. bool matched = true;
  482. if (input_shapes[i].size() != traced_input_shapes[i].size())
  483. {
  484. matched = false;
  485. }
  486. else
  487. {
  488. for (size_t j = 0; j < traced_input_shapes[i].size(); j++)
  489. {
  490. if (input_shapes[i][j] != traced_input_shapes[i][j])
  491. matched = false;
  492. }
  493. }
  494. if (input_types[i] != traced_input_types[i])
  495. matched = false;
  496. if (!matched)
  497. {
  498. fprintf(stderr, "input_shapes[%d] expect [", (int)i);
  499. for (size_t j = 0; j < traced_input_shapes[i].size(); j++)
  500. {
  501. fprintf(stderr, "%ld", traced_input_shapes[i][j]);
  502. if (j + 1 != traced_input_shapes[i].size())
  503. fprintf(stderr, ",");
  504. }
  505. fprintf(stderr, "]%s but got ", traced_input_types[i].c_str());
  506. if (input_shapes.empty())
  507. {
  508. fprintf(stderr, "nothing\n");
  509. }
  510. else
  511. {
  512. fprintf(stderr, "[");
  513. for (size_t j = 0; j < input_shapes[i].size(); j++)
  514. {
  515. fprintf(stderr, "%ld", input_shapes[i][j]);
  516. if (j + 1 != input_shapes[i].size())
  517. fprintf(stderr, ",");
  518. }
  519. fprintf(stderr, "]%s\n", input_types[i].c_str());
  520. }
  521. return false;
  522. }
  523. }
  524. return true;
  525. }
  526. int load_torchscript(const std::string& ptpath, Graph& pnnx_graph,
  527. const std::string& device,
  528. const std::vector<std::vector<int64_t> >& input_shapes,
  529. const std::vector<std::string>& input_types,
  530. const std::vector<std::vector<char> >& input_contents,
  531. const std::vector<std::vector<int64_t> >& input_shapes2,
  532. const std::vector<std::string>& input_types2,
  533. const std::vector<std::vector<char> >& input_contents2,
  534. const std::vector<std::string>& customop_modules,
  535. const std::vector<std::string>& module_operators,
  536. const std::string& foldable_constants_zippath,
  537. std::set<std::string>& foldable_constants)
  538. {
  539. // get input shape from traced torchscript
  540. std::vector<std::vector<int64_t> > traced_input_shapes;
  541. std::vector<std::string> traced_input_types;
  542. get_traced_input_shape(ptpath, traced_input_shapes, traced_input_types);
  543. if (!traced_input_shapes.empty())
  544. {
  545. fprintf(stderr, "get inputshape from traced inputs\n");
  546. fprintf(stderr, "inputshape = ");
  547. print_shape_list(traced_input_shapes, traced_input_types);
  548. fprintf(stderr, "\n");
  549. if (!input_shapes.empty())
  550. {
  551. // input shape sanity check
  552. if (!check_input_shape(traced_input_shapes, traced_input_types, input_shapes, input_types))
  553. {
  554. return -1;
  555. }
  556. }
  557. // traced torchscript always has static input shapes
  558. // if (!input_shapes2.empty() && !check_input_shape(ptpath, input_shapes2, input_types2))
  559. // {
  560. // return -1;
  561. // }
  562. }
  563. else
  564. {
  565. traced_input_shapes = input_shapes;
  566. traced_input_types = input_types;
  567. }
  568. #ifdef PNNX_TORCHVISION
  569. // call some vision api to register vision ops :P
  570. (void)vision::cuda_version();
  571. #endif
  572. for (auto m : customop_modules)
  573. {
  574. fprintf(stderr, "load custom module %s\n", m.c_str());
  575. #if _WIN32
  576. HMODULE handle = LoadLibraryExA(m.c_str(), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
  577. if (!handle)
  578. {
  579. fprintf(stderr, "LoadLibraryExA %s failed %d\n", m.c_str(), GetLastError());
  580. }
  581. #else
  582. void* handle = dlopen(m.c_str(), RTLD_LAZY);
  583. if (!handle)
  584. {
  585. fprintf(stderr, "dlopen %s failed %s\n", m.c_str(), dlerror());
  586. }
  587. #endif
  588. }
  589. std::vector<at::Tensor> input_tensors;
  590. if (input_contents.size() != 0)
  591. {
  592. for (size_t i = 0; i < traced_input_shapes.size(); i++)
  593. {
  594. const std::vector<int64_t>& shape = traced_input_shapes[i];
  595. const std::string& type = traced_input_types[i];
  596. at::TensorOptions options(input_type_to_c10_ScalarType(type));
  597. at::IntArrayRef shape2(shape);
  598. at::Tensor t = torch::from_blob((void*)input_contents[i].data(), shape2, options);
  599. if (device == "gpu")
  600. t = t.cuda();
  601. input_tensors.push_back(t);
  602. }
  603. }
  604. else
  605. {
  606. for (size_t i = 0; i < traced_input_shapes.size(); i++)
  607. {
  608. const std::vector<int64_t>& shape = traced_input_shapes[i];
  609. const std::string& type = traced_input_types[i];
  610. at::Tensor t = torch::ones(shape, input_type_to_c10_ScalarType(type));
  611. if (device == "gpu")
  612. t = t.cuda();
  613. input_tensors.push_back(t);
  614. }
  615. }
  616. std::vector<at::Tensor> input_tensors2;
  617. if (input_contents2.size() != 0)
  618. {
  619. for (size_t i = 0; i < input_shapes2.size(); i++)
  620. {
  621. const std::vector<int64_t>& shape = input_shapes2[i];
  622. const std::string& type = input_types2[i];
  623. at::TensorOptions options(input_type_to_c10_ScalarType(type));
  624. at::IntArrayRef shape2(shape);
  625. at::Tensor t = torch::from_blob((void*)input_contents2[i].data(), shape2, options);
  626. if (device == "gpu")
  627. t = t.cuda();
  628. input_tensors2.push_back(t);
  629. }
  630. }
  631. else if(input_shapes2.size() != 0)
  632. {
  633. for (size_t i = 0; i < input_shapes2.size(); i++)
  634. {
  635. const std::vector<int64_t>& shape = input_shapes2[i];
  636. const std::string& type = input_types2[i];
  637. at::Tensor t = torch::ones(shape, input_type_to_c10_ScalarType(type));
  638. if (device == "gpu")
  639. t = t.cuda();
  640. input_tensors2.push_back(t);
  641. }
  642. }
  643. torch::jit::Module mod;
  644. try
  645. {
  646. mod = torch::jit::load(ptpath, (device == "gpu") ? c10::kCUDA : c10::kCPU);
  647. }
  648. catch (const c10::Error& e)
  649. {
  650. fprintf(stderr, "Load torchscript failed: %s\n", e.what());
  651. fprintf(stderr, "Please export model to torchscript as follows\n");
  652. fprintf(stderr, "------------------------------------------\n");
  653. fprintf(stderr, "import torch\n");
  654. fprintf(stderr, "import torchvision.models as models\n\n");
  655. fprintf(stderr, "net = models.resnet18(pretrained=True)\n");
  656. fprintf(stderr, "net = net.eval()\n\n");
  657. fprintf(stderr, "x = torch.rand(1, 3, 224, 224)\n");
  658. fprintf(stderr, "mod = torch.jit.trace(net, x)\n");
  659. fprintf(stderr, "mod.save(\"resnet18.pt\")\n");
  660. fprintf(stderr, "------------------------------------------\n");
  661. return -1;
  662. }
  663. mod.eval();
  664. // mod.dump(true, false, false);
  665. // mod.dump(true, true, true);
  666. auto method = mod.find_method("forward");
  667. if (!method)
  668. {
  669. auto methods = mod.get_methods();
  670. if (methods.empty())
  671. {
  672. fprintf(stderr, "No method in torchscript\n");
  673. return -1;
  674. }
  675. method = methods[0];
  676. fprintf(stderr, "Use method %s as the entrypoint instead of forward\n", method->name().c_str());
  677. }
  678. auto g = method->graph();
  679. // g->dump();
  680. fprintf(stderr, "############# pass_level0\n");
  681. pnnx::pass_level0(mod, g, input_tensors, input_tensors2, module_operators, ptpath, device, foldable_constants, foldable_constants_zippath);
  682. // g->dump();
  683. fprintf(stderr, "############# pass_level1\n");
  684. pnnx::pass_level1(mod, g, module_operators, pnnx_graph);
  685. return 0;
  686. }
  687. } // namespace pnnx