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.

mgblar.cpp 44 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216
  1. /**
  2. * \file sdk/load-and-run/src/mgblar.cpp
  3. * MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  4. *
  5. * Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
  6. *
  7. * Unless required by applicable law or agreed to in writing,
  8. * software distributed under the License is distributed on an
  9. * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. */
  11. #include "./mgblar.h"
  12. #include "./infile_persistent_cache.h"
  13. #include "./json_loader.h"
  14. #include "./npy.h"
  15. #include "megbrain/utils/debug.h"
  16. #include "megbrain/serialization/serializer.h"
  17. #include "megbrain/serialization/extern_c_opr.h"
  18. #include "megbrain/plugin/opr_io_dump.h"
  19. #include "megbrain/plugin/profiler.h"
  20. #include "megbrain/plugin/num_range_checker.h"
  21. #include "megbrain/plugin/cpu_dispatch_checker.h"
  22. #include "megbrain/plugin/var_value_checker.h"
  23. #include "megbrain/opr/io.h"
  24. #include "megbrain/opr/utility.h"
  25. #include "megbrain/gopt/inference.h"
  26. #include "megbrain/comp_node_env.h"
  27. #include "megbrain/system.h"
  28. #include "megbrain/version.h"
  29. #include "megdnn/version.h"
  30. #include <cstdlib>
  31. #include <cstring>
  32. #include <cerrno>
  33. #include <cstdio>
  34. #include <cctype>
  35. #include <numeric>
  36. #include <sstream>
  37. #if defined(_WIN32)
  38. #include <io.h>
  39. #define F_OK 0
  40. #define access(a, b) _access(a, b)
  41. #elif __linux__ || __unix__ || __APPLE__
  42. #include <unistd.h>
  43. #include <dlfcn.h>
  44. #endif
  45. #if MGB_ENABLE_TENSOR_RT
  46. #include "megbrain/tensorrt/tensorrt_engine_cache.h"
  47. #endif
  48. using namespace mgb;
  49. namespace {
  50. const char* OPTIONS_DESC =
  51. R"__usage__(
  52. --cpu|--cpu-default
  53. )__usage__"
  54. R"__usage__(
  55. Require to compute on CPU or OpenCL. By default CUDA is used if available,
  56. and CPU is used if CUDA is not available. Use --cpu-default to compute on
  57. CPU and dispatch all tasks in the caller thread.
  58. --multithread|--multithread-default <nr_thread>
  59. Use --multithread to compute on CPU with multi threads.
  60. Use --multithread-default to compute on CPU with multi threads and
  61. the caller thread is main thread of the multi thread pool, follow by
  62. thread number
  63. --multi-thread-core-ids
  64. The multi thread affinity core set, separated with ',', the number of digital
  65. will be the thread number. for example:--multi-thread-core-ids "0,1,2,3", the
  66. number thread if 4,the main thread binding the last core '3',
  67. for best performance, the main thread should binding to the fast core.
  68. --profile|--profile-host <output>
  69. Write profiling result to given file. The output file is in JSON format and
  70. can be processed by scripts in MegHair/utils/debug.
  71. Note:
  72. For some backends (like opencl), special options need to be enabled for
  73. profiling device time, which may cause additional overhead and make it
  74. hard to profile host time. Use --profile-host to focus on host time
  75. profiling.
  76. --input [ filepath | string]
  77. Set up inputs for megbrain model. for example: --data image.ppm --data
  78. param.json --data bbox:bbox.npy@batchid:b.npy --data rect:[0,0,227,227];
  79. batchid:0,1,2,3. --io-dump or --bin-io-dump
  80. should be enabled at the same time.
  81. --io-dump <output> | --bin-io-dump <output dir>
  82. Dump input/output values of all internal variables to output file or
  83. directory, in text or binary format. The binary file can be parsed by
  84. `megbrain.plugin.load_tensor_binary`.
  85. --bin-out-dump <output dir>
  86. Dump output tensor values in binary format to given directory.
  87. --iter <num>
  88. Number of iterations to run for each testcase.
  89. --warmup-iter <num>
  90. Number of warm-up iterations, which are not included in the time statistics.
  91. --range <value>
  92. Enable tensor value range check. Exception would be raised if the absolute
  93. value of any element of any variable does not fit in given range. This can
  94. be used to debug NaN values.
  95. --check-dispatch
  96. Enable CPU dispatch checker, which prints a warning message if on operator
  97. does not the dispatch function. This is used to find potential bugs in
  98. MegDNN.
  99. --check-var-value <switch_interval[:start_i dx]>
  100. Enable VarValueChecker plugin. Refer to its doc for more details.
  101. --no-sanity-check
  102. Disable var sanity check on the first run. Var sanity check is enabled on
  103. the first-time execution by default, and can be used to find some potential
  104. memory access errors in the operator implementation.
  105. --disable-mem-opt
  106. Disable memory optimizations. This is used to check whether memory
  107. optimization is the cause for unexpected behavior.
  108. --fake-first
  109. Enable fake exec for the first run. In fake exec mode, some initialization
  110. job would be done, but no actual computing is performed. This can be used in
  111. an SDK right after loading the model to reduce execution latency in the real
  112. fist-time computing. It requires input shapes to be correctly setup.
  113. --const-shape
  114. Set `GraphLoadConfig::const_var_shape` to true before loading the graph.
  115. This can be used to reduce memory usage since some static inference data
  116. structures can be omitted.
  117. --share-param-mem
  118. Share the memory used by model params with model storage. This can be used
  119. to reduce memory usage when computing on CPU.
  120. --record-comp-seq | --record-comp-seq2
  121. Record the computing sequence, in level 1 or 2. It reduces overhead of API
  122. calls of some asynchronous computing devices, especially for OpenCL. In
  123. level 2 the computing graph can be destructed to reduce memory usage. Read
  124. the doc of `ComputingGraph::Options::comp_node_seq_record_level` for more
  125. details.
  126. )__usage__"
  127. #if MGB_ENABLE_FASTRUN
  128. R"__usage__(
  129. --fast-run
  130. Enable fast-run mode. Operators with multiple algorithms would be profiled
  131. on the real device with actual input shapes.
  132. See `mgb::gopt::enable_opr_algo_profiling_inplace` for more details.
  133. )__usage__"
  134. #endif
  135. R"__usage__(
  136. --fast-run-algo-policy <path>
  137. It will read the cache file before profile, and save new fastrun in cache file.
  138. --wait-gdb
  139. Print PID and wait for a line from stdin before starting execution. Useful
  140. for waiting for gdb attach.
  141. --c-opr-lib <path>
  142. Load external operator library. It must implement `mgb_c_opr_init` as the
  143. entry point.
  144. --thread <num>
  145. Number of threads to run concurrently. All threads perform the same work of
  146. loading and executing models. This is used for test thread safety, not for
  147. speed up on multiple cores.
  148. --disable-assert-throw
  149. Do not throw exception in case AssertEqual fails. Note that the exit code
  150. would also be zero if this option is enabled. This should only be used for
  151. debug.
  152. --copy-to-host
  153. Whether copy output from device to host.
  154. This is used for checking the performance in real scenarios including output copy.
  155. --workspace-limit <num>
  156. set workspace_limit for execution strategy for oprs with multiple algorithms.
  157. The default is SIZE_MAX(bytes).
  158. --verbose
  159. Increase verbosity for megbrain log.
  160. )__usage__"
  161. #if MGB_ENABLE_TENSOR_RT
  162. R"__usage__(
  163. --tensorrt
  164. Execute supported operators with TensorRT. Can only be used on Nvidia GPUs,
  165. i.e. comp node is xpu or gpu.
  166. --tensorrt-cache <path>
  167. Set the TensorRT engine cache path for serialized prebuilt ICudaEngine
  168. )__usage__"
  169. #endif
  170. R"__usage__(
  171. --enable-jit
  172. Execute supported operators with JIT(now only support NVRTC). Can only be used on Nvidia GPUs.
  173. )__usage__"
  174. R"__usage__(
  175. --winograd-transform
  176. Execute opr replace, replace weights by winograd transform. Currently support on conv bias opr.
  177. )__usage__"
  178. R"__usage__(
  179. --enable-chwn4
  180. Execute operators with kernels implemented in MegDNN with CHWN4 tensor format. Can only be used
  181. on Nvidia GPUs, whose compute capability is above 6.1.
  182. )__usage__"
  183. ;
  184. struct DataParser {
  185. struct Brace {
  186. std::weak_ptr<Brace> parent;
  187. std::vector<std::shared_ptr<Brace>> chidren;
  188. };
  189. void feed(const std::string& path) {
  190. std::string blob_name = "data", blob_string = path;
  191. size_t sep = path.find(":");
  192. if (sep != std::string::npos) {
  193. blob_name = path.substr(0, sep);
  194. blob_string = path.substr(sep + 1);
  195. }
  196. auto endWith = [blob_string](std::string suffix) -> bool {
  197. return blob_string.rfind(suffix) ==
  198. (blob_string.length() - suffix.length());
  199. };
  200. if (endWith(".ppm") || endWith(".pgm")) {
  201. parse_image(blob_name, blob_string);
  202. } else if (endWith(".json")) {
  203. parse_json(blob_string);
  204. } else if (endWith(".npy")) {
  205. parse_npy(blob_name, blob_string);
  206. } else {
  207. parse_string(blob_name, blob_string);
  208. }
  209. }
  210. std::map<std::string, HostTensorND> inputs;
  211. private:
  212. void parse_json(const std::string& path) {
  213. JsonLoader json;
  214. std::shared_ptr<JsonLoader::Value> root = json.load(path.c_str());
  215. mgb_assert(root != nullptr, "parse json %s fail", path.c_str());
  216. // parse json to data map
  217. const std::string SHAPE = "shape", TYPE = "type", RAW = "raw";
  218. for (auto& item : root->objects()) {
  219. auto&& value = *item.second;
  220. auto&& shape = value[SHAPE];
  221. mgb_assert(shape->is_array());
  222. auto&& type = value[TYPE];
  223. mgb_assert(type->is_str());
  224. auto&& raw = value[RAW];
  225. mgb_assert(raw->is_array());
  226. megdnn::SmallVector<size_t> data_shape;
  227. for (auto&& shape_ptr : shape->array()) {
  228. data_shape.append(
  229. {static_cast<size_t>(std::round(shape_ptr->number()))});
  230. }
  231. // get type
  232. const std::map<std::string, megdnn::DType> type_map = {
  233. {"float32", dtype::Float32()}, {"float", dtype::Float32()},
  234. {"int32", dtype::Int32()}, {"int", dtype::Int32()},
  235. {"int8", dtype::Int8()}, {"uint8", dtype::Uint8()}};
  236. const std::string& type_str = type->str();
  237. mgb_assert(type_map.find(type_str) != type_map.end(),
  238. "unknown json data type for --data");
  239. DType datatype = type_map.at(type_str);
  240. HostTensorND hv;
  241. hv.comp_node(mgb::CompNode::default_cpu(), true)
  242. .dtype(datatype)
  243. .resize(data_shape);
  244. dt_byte* raw_ptr = hv.raw_ptr();
  245. size_t elem_size = datatype.size();
  246. // get raw
  247. const size_t array_size = raw->len();
  248. for (size_t idx = 0; idx < array_size; ++idx) {
  249. double tmp = (*raw)[idx]->number();
  250. switch (datatype.enumv()) {
  251. case megdnn::DTypeEnum::Int32: {
  252. int32_t ival = std::round(tmp);
  253. memcpy(raw_ptr + idx * elem_size, &ival, elem_size);
  254. } break;
  255. case megdnn::DTypeEnum::Uint8:
  256. case megdnn::DTypeEnum::Int8: {
  257. int8_t cval = std::round(tmp);
  258. memcpy(raw_ptr + idx, &cval, sizeof(int8_t));
  259. } break;
  260. case megdnn::DTypeEnum::Float32: {
  261. float fval = tmp;
  262. memcpy(raw_ptr + idx * elem_size, &fval, elem_size);
  263. } break;
  264. default:
  265. break;
  266. }
  267. }
  268. inputs.insert(std::make_pair(item.first, std::move(hv)));
  269. }
  270. }
  271. void parse_image(const std::string& name, const std::string& path) {
  272. // load ppm/pgm
  273. std::ifstream fin;
  274. fin.open(path, std::ifstream::binary | std::ifstream::in);
  275. mgb_assert(fin.is_open(), "open file %s failed for --input",
  276. path.c_str());
  277. size_t w = 0, h = 0, channel = 0;
  278. char buf[128] = {0};
  279. fin.getline(buf, 128);
  280. if ('5' == buf[1]) {
  281. channel = 1;
  282. } else if ('6' == buf[1]) {
  283. channel = 3;
  284. } else {
  285. mgb_assert(0, "not a formal ppm/pgm");
  286. }
  287. while (fin.getline(buf, 128)) {
  288. // skip OCV comment, check
  289. // https://github.com/opencv/opencv/pull/17006
  290. if (buf[0] == '#') {
  291. continue;
  292. }
  293. break;
  294. }
  295. std::stringstream ss;
  296. ss << std::string(buf);
  297. ss >> w;
  298. ss >> h;
  299. mgb_assert(w > 0 and h > 0);
  300. HostTensorND hv;
  301. hv.comp_node(mgb::CompNode::default_cpu(), true)
  302. .dtype(dtype::Uint8())
  303. .resize({1, h, w, channel});
  304. fin.read((char*)(hv.raw_ptr()), hv.layout().total_nr_elems());
  305. fin.close();
  306. inputs.insert(std::make_pair(name, std::move(hv)));
  307. }
  308. void parse_npy(const std::string& name, const std::string& path) {
  309. std::string type_str;
  310. std::vector<npy::ndarray_len_t> stl_shape;
  311. std::vector<int8_t> raw;
  312. npy::LoadArrayFromNumpy(path, type_str, stl_shape, raw);
  313. megdnn::SmallVector<size_t> shape;
  314. for (auto val : stl_shape) {
  315. shape.append({static_cast<size_t>(val)});
  316. }
  317. const std::map<std::string, megdnn::DType> type_map = {
  318. {"f4", dtype::Float32()},
  319. {"i4", dtype::Int32()},
  320. {"i1", dtype::Int8()},
  321. {"u1", dtype::Uint8()}};
  322. megdnn::DType hv_type;
  323. for (auto& item : type_map) {
  324. if (type_str.find(item.first) != std::string::npos) {
  325. hv_type = item.second;
  326. break;
  327. }
  328. }
  329. HostTensorND hv;
  330. hv.comp_node(mgb::CompNode::default_cpu(), true)
  331. .dtype(hv_type)
  332. .resize(shape);
  333. dt_byte* raw_ptr = hv.raw_ptr();
  334. memcpy(raw_ptr, raw.data(), raw.size());
  335. inputs.insert(std::make_pair(name, std::move(hv)));
  336. }
  337. void parse_string(const std::string name, const std::string& str) {
  338. // data type
  339. megdnn::DType data_type = dtype::Int32();
  340. if (str.find(".") != std::string::npos or
  341. str.find(".") != std::string::npos) {
  342. data_type = dtype::Float32();
  343. }
  344. // shape
  345. size_t number_cnt = 0;
  346. std::shared_ptr<Brace> brace_root = std::make_shared<Brace>();
  347. std::shared_ptr<Brace> cur = brace_root;
  348. for (size_t i = 0; i < str.size(); ++i) {
  349. char c = str[i];
  350. if (c == '[') {
  351. std::shared_ptr<Brace> child = std::make_shared<Brace>();
  352. child->parent = cur;
  353. cur->chidren.emplace_back(child);
  354. cur = child;
  355. } else if (c == ']') {
  356. cur = cur->parent.lock();
  357. } else if (c == ',') {
  358. number_cnt++;
  359. }
  360. continue;
  361. }
  362. ++number_cnt;
  363. mgb_assert(cur == brace_root, "braces not closed for --input");
  364. megdnn::SmallVector<size_t> shape;
  365. cur = brace_root;
  366. while (not cur->chidren.empty()) {
  367. shape.append({cur->chidren.size()});
  368. number_cnt /= cur->chidren.size();
  369. cur = cur->chidren[0];
  370. }
  371. mgb_assert(number_cnt > 0);
  372. shape.append({number_cnt});
  373. // data
  374. std::string json_arr;
  375. for (size_t i = 0; i < str.size(); ++i) {
  376. char c = str[i];
  377. if (c != '[' and c != ']') {
  378. json_arr += c;
  379. }
  380. }
  381. json_arr = "[" + json_arr + "]";
  382. // reuse json parser to resolve raw data
  383. JsonLoader json;
  384. std::shared_ptr<JsonLoader::Value> json_root =
  385. json.load(json_arr.data(), json_arr.size());
  386. mgb_assert(json_root != nullptr, "parse json fail in parse_string");
  387. HostTensorND hv;
  388. hv.comp_node(mgb::CompNode::default_cpu(), true)
  389. .dtype(data_type)
  390. .resize(shape);
  391. dt_byte* raw_ptr = hv.raw_ptr();
  392. const size_t array_len = json_root->len();
  393. const size_t elem_size = data_type.size();
  394. for (size_t idx = 0; idx < array_len; ++idx) {
  395. double tmp = json_root->array()[idx]->number();
  396. switch (data_type.enumv()) {
  397. case megdnn::DTypeEnum::Int32: {
  398. int32_t ival = std::round(tmp);
  399. memcpy(raw_ptr + idx * elem_size, &ival, elem_size);
  400. } break;
  401. case megdnn::DTypeEnum::Float32: {
  402. float fval = tmp;
  403. memcpy(raw_ptr + idx * elem_size, &fval, elem_size);
  404. } break;
  405. default:
  406. break;
  407. }
  408. }
  409. inputs.insert(std::make_pair(name, std::move(hv)));
  410. };
  411. };
  412. struct Args {
  413. int args_parse_ret = 0;
  414. std::string model_path;
  415. bool disable_assert_throw = false;
  416. bool share_param_mem = false;
  417. #if MGB_ENABLE_FASTRUN
  418. bool use_fast_run = false;
  419. #endif
  420. std::string fast_run_cache_path;
  421. bool copy_to_host = false;
  422. int nr_run = 10;
  423. int nr_warmup = 1;
  424. int nr_thread = 1;
  425. int multithread_number = 1;
  426. size_t workspace_limit = SIZE_MAX;
  427. std::vector<std::string> data_files;
  428. serialization::GraphLoader::LoadResult load_ret;
  429. #if MGB_ENABLE_JSON
  430. std::unique_ptr<GraphProfiler> profiler;
  431. #endif
  432. std::string profiler_output;
  433. std::string bin_out_dump;
  434. std::unique_ptr<OprIODumpBase> iodump;
  435. std::unique_ptr<NumRangeChecker> num_range_checker;
  436. std::unique_ptr<CPUDispatchChecker> cpu_dispatch_checker;
  437. std::unique_ptr<VarValueChecker> var_value_checker;
  438. serialization::GraphLoader::LoadConfig load_config;
  439. thin_function<void(size_t)> affinity_cb;
  440. static Args from_argv(int argc, char **argv);
  441. };
  442. uint32_t read_nr_test(serialization::InputFile &fin) {
  443. char magic[8];
  444. fin.read(magic, sizeof(magic));
  445. if (strncmp(magic, "mgbtest0", 8)) {
  446. fin.rewind();
  447. return 0;
  448. }
  449. uint32_t ret;
  450. fin.read(&ret, sizeof(ret));
  451. return ret;
  452. }
  453. size_t get_file_size(FILE *fptr) {
  454. fseek(fptr, 0, SEEK_END);
  455. size_t size = ftell(fptr);
  456. fseek(fptr, 0, SEEK_SET);
  457. return size;
  458. }
  459. /**
  460. * \brief dump output tensor.
  461. *
  462. * graph would be destructed if comp_node_seq_record_level == 2; so we should
  463. * store graph info before graph_compile().
  464. */
  465. class OutputDumper {
  466. struct DumpInfo {
  467. HostTensorND hv = {};
  468. std::string var_info;
  469. std::string owner_inputs_info;
  470. size_t id;
  471. };
  472. SmallVector<DumpInfo> m_infos;
  473. size_t m_run_id = 0;
  474. size_t m_bind_id = 0;
  475. const Args& m_env;
  476. public:
  477. OutputDumper(const Args& env) : m_env{env} {
  478. for (auto&& i : m_env.load_ret.output_var_list) {
  479. auto&& var = i.node();
  480. DumpInfo info;
  481. info.var_info = cg::dump_var_info({var});
  482. info.owner_inputs_info =
  483. cg::dump_var_info(var->owner_opr()->input());
  484. info.id = var->id();
  485. m_infos.push_back(info);
  486. }
  487. }
  488. ComputingGraph::Callback bind() {
  489. auto& info = m_infos.at(m_bind_id++);
  490. ComputingGraph::Callback cb = [&info](const DeviceTensorND& dv) {
  491. info.hv.copy_from(dv);
  492. };
  493. return cb;
  494. }
  495. void write_to_file() {
  496. if (!m_env.bin_out_dump.empty()) {
  497. for (auto&& info : m_infos) {
  498. auto value = debug::dump_tensor(
  499. info.hv, ssprintf("var=%s owner_opr_inputs=%s",
  500. info.var_info.c_str(),
  501. info.owner_inputs_info.c_str()));
  502. debug::write_to_file(
  503. ssprintf("%s/run%zu-var%zd", m_env.bin_out_dump.c_str(),
  504. m_run_id, info.id)
  505. .c_str(),
  506. value);
  507. }
  508. }
  509. m_run_id ++;
  510. }
  511. };
  512. void run_test_st(Args &env) {
  513. std::unique_ptr<serialization::InputFile> inp_file;
  514. if (env.share_param_mem) {
  515. FILE *fin = fopen(env.model_path.c_str(), "rb");
  516. mgb_assert(fin, "failed to open %s: %s", env.model_path.c_str(),
  517. strerror(errno));
  518. auto size = get_file_size(fin);
  519. void *ptr = malloc(size);
  520. std::shared_ptr<void> buf{ptr, free};
  521. auto nr = fread(buf.get(), 1, size, fin);
  522. mgb_assert(nr == size);
  523. fclose(fin);
  524. inp_file = serialization::InputFile::make_mem_proxy(buf, size);
  525. } else {
  526. inp_file = serialization::InputFile::make_fs(
  527. env.model_path.c_str());
  528. }
  529. auto nr_test = read_nr_test(*inp_file);
  530. auto format =
  531. serialization::GraphLoader::identify_graph_dump_format(*inp_file);
  532. if (!format.valid()) {
  533. printf("invalid model: unknown model format, please make sure input "
  534. "file is generated by GraphDumper\n");
  535. return;
  536. }
  537. auto loader =
  538. serialization::GraphLoader::make(std::move(inp_file), format.val());
  539. RealTimer timer;
  540. env.load_ret = loader->load(env.load_config, false);
  541. // graph is no longer needed; reset so memory can be reclaimed
  542. env.load_config.comp_graph.reset();
  543. printf("load model: %.3fms\n", timer.get_msecs_reset());
  544. // compile function to compute all outputs
  545. ComputingGraph::OutputSpec out_spec;
  546. std::string output_names;
  547. OutputDumper output_dumper(env);
  548. for (auto&& i : env.load_ret.output_var_list) {
  549. if (&i != env.load_ret.output_var_list.data()) {
  550. output_names += " ";
  551. }
  552. output_names.append(i.node()->name() + i.shape().to_string());
  553. ComputingGraph::Callback cb;
  554. if (!env.bin_out_dump.empty()) {
  555. cb = output_dumper.bind();
  556. } else if (env.copy_to_host) {
  557. HostTensorND val;
  558. cb = [val](const DeviceTensorND& dv) mutable {
  559. val.copy_from(dv);
  560. };
  561. }
  562. out_spec.emplace_back(i, std::move(cb));
  563. }
  564. if (env.disable_assert_throw) {
  565. auto on_opr = [](cg::OperatorNodeBase* opr) {
  566. if (opr->same_type<opr::AssertEqual>()) {
  567. opr->cast_final<opr::AssertEqual>().disable_throw_on_error();
  568. }
  569. };
  570. cg::DepOprIter iter{on_opr};
  571. for (auto&& i : out_spec) {
  572. iter.add(i.first.node()->owner_opr());
  573. }
  574. }
  575. SymbolVarArray vars;
  576. for (auto i : out_spec) {
  577. vars.push_back(i.first);
  578. }
  579. mgb::gopt::set_opr_algo_workspace_limit_inplace(vars, env.workspace_limit);
  580. #if MGB_ENABLE_FASTRUN
  581. if (env.use_fast_run)
  582. mgb::gopt::enable_opr_algo_profiling_inplace(vars);
  583. #endif
  584. if (!env.fast_run_cache_path.empty()) {
  585. #if MGB_ENABLE_FASTRUN
  586. if (!access(env.fast_run_cache_path.c_str(), F_OK)) {
  587. #else
  588. mgb_assert(access(env.fast_run_cache_path.c_str(), F_OK) == 0,
  589. "fast-run cache file can't be accessed");
  590. #endif
  591. FILE* fin = fopen(env.fast_run_cache_path.c_str(), "rb");
  592. auto flen = get_file_size(fin);
  593. std::unique_ptr<uint8_t[]> buf{new uint8_t[flen]};
  594. size_t ret = fread(buf.get(), flen, 1, fin);
  595. MGB_MARK_USED_VAR(ret);
  596. mgb_assert(ret == 1, "read 1 block (got %zu), and block size %zu.",
  597. ret, flen);
  598. fclose(fin);
  599. PersistentCache::set_impl(
  600. std::make_shared<InFilePersistentCache>(buf.get(), flen));
  601. #if MGB_ENABLE_FASTRUN
  602. } else {
  603. mgb_assert(env.use_fast_run, "fast-run should be enabled");
  604. PersistentCache::set_impl(
  605. std::make_shared<InFilePersistentCache>());
  606. }
  607. if (!env.use_fast_run)
  608. #endif
  609. mgb::gopt::enable_opr_use_profiling_cache_inplace(vars);
  610. }
  611. auto func = env.load_ret.graph_compile(out_spec);
  612. auto warmup = [&]() {
  613. printf("=== prepare: %.3fms; going to warmup\n",
  614. timer.get_msecs_reset());
  615. for (int run = 0; run < env.nr_warmup; ++run) {
  616. func->execute().wait();
  617. printf("warmup %d: %.3fms\n", run, timer.get_msecs_reset());
  618. }
  619. };
  620. if (nr_test) {
  621. // run testcase, generated by dump_with_testcase.py
  622. std::vector<std::pair<std::string, HostTensorND*>> inp_tensors;
  623. for (auto &&i: env.load_ret.tensor_map) {
  624. inp_tensors.emplace_back(i.first, i.second.get());
  625. }
  626. std::sort(inp_tensors.begin(), inp_tensors.end());
  627. printf("=== going to run %u testcases; output vars: %s\n", nr_test,
  628. output_names.c_str());
  629. double tot_time = 0;
  630. for (uint32_t i = 0; i < nr_test; ++ i) {
  631. loader = serialization::GraphLoader::make(
  632. loader->reset_file(), loader->format());
  633. auto testcase = loader->load(env.load_config, false);
  634. mgb_assert(testcase.output_var_list.size() == inp_tensors.size());
  635. for (size_t i = 0; i < inp_tensors.size(); ++ i) {
  636. auto &&opr = testcase.output_var_list[i].node()->owner_opr()->
  637. cast_final_safe<opr::SharedDeviceTensor>();
  638. inp_tensors[i].second->copy_from(
  639. HostTensorND::make_proxy(*opr.dev_data()));
  640. }
  641. if (!i) {
  642. warmup();
  643. }
  644. timer.reset();
  645. printf("=== going to run test #%u for %d times\n", i, env.nr_run);
  646. if (!env.nr_run) {
  647. continue;
  648. }
  649. double time_sqrsum = 0, time_sum = 0,
  650. min_time = std::numeric_limits<double>::max(), max_time = 0;
  651. for (int run = 0; run < env.nr_run; ++ run) {
  652. mgb_log_debug("load_and_run: before running iter %d", run);
  653. timer.reset();
  654. func->execute();
  655. mgb_log_debug("load_and_run: before waiting iter %d", run);
  656. auto exec_time = timer.get_msecs();
  657. func->wait();
  658. output_dumper.write_to_file();
  659. auto cur = timer.get_msecs();
  660. printf("iter %d/%d: %.3fms (exec=%.3f,device=%.3f)\n", run,
  661. env.nr_run, cur, exec_time,
  662. func->get_prev_exec_time() * 1e3);
  663. time_sum += cur;
  664. time_sqrsum += cur * cur;
  665. fflush(stdout);
  666. if (cur < min_time) {
  667. min_time = cur;
  668. }
  669. if (cur > max_time) {
  670. max_time = cur;
  671. }
  672. }
  673. tot_time += time_sum;
  674. printf("=== finished test #%u: time=%.3fms avg_time=%.3fms "
  675. "sd=%.3fms minmax=%.3f,%.3f\n\n",
  676. i, time_sum, time_sum / env.nr_run,
  677. std::sqrt((time_sqrsum * env.nr_run - time_sum * time_sum) /
  678. (env.nr_run * (env.nr_run - 1))),
  679. min_time, max_time);
  680. }
  681. printf("=== total time: %.3fms\n", tot_time);
  682. } else if (not env.data_files.empty()) {
  683. auto& tensormap = env.load_ret.tensor_map;
  684. DataParser parser;
  685. for (auto path : env.data_files) {
  686. parser.feed(path);
  687. }
  688. auto inputs = parser.inputs;
  689. for (auto& i : inputs) {
  690. if (tensormap.find(i.first) == tensormap.end()) {
  691. continue;
  692. }
  693. auto& in = tensormap.find(i.first)->second;
  694. in->copy_from(i.second);
  695. }
  696. timer.reset();
  697. func->execute();
  698. auto exec_time = timer.get_msecs();
  699. func->wait();
  700. output_dumper.write_to_file();
  701. auto cur = timer.get_msecs();
  702. printf("%.3fms %.3fms (device=%.3f)\n", cur, exec_time,
  703. func->get_prev_exec_time() * 1e3);
  704. } else {
  705. // run speed test for a raw mgb graph
  706. mgb_assert(env.load_ret.tensor_map.empty(),
  707. "model should not require input values; input vars should be "
  708. "replaced by SharedDeviceTensor "
  709. "(i.e. megskull.opr.ParamProvider)");
  710. warmup();
  711. timer.reset();
  712. printf("=== going to run for %d times; output vars: %s\n",
  713. env.nr_run, output_names.c_str());
  714. for (int i = 0; i < env.nr_run; ++ i) {
  715. mgb_log_debug("load_and_run: before benchmark iter %d", i);
  716. auto start = timer.get_msecs();
  717. func->execute().wait();
  718. output_dumper.write_to_file();
  719. printf("=== finished run #%d: time=%.3fms\n", i,
  720. timer.get_msecs() - start);
  721. fflush(stdout);
  722. }
  723. printf("avg time: %.3fms\n", timer.get_msecs() / env.nr_run);
  724. }
  725. #if MGB_ENABLE_JSON
  726. if (env.profiler) {
  727. env.profiler->to_json_full(func.get())->writeto_fpath(
  728. env.profiler_output);
  729. mgb_log("profiling result written to %s", env.profiler_output.c_str());
  730. }
  731. #endif
  732. #if MGB_ENABLE_FASTRUN
  733. if (!env.fast_run_cache_path.empty()) {
  734. static_cast<InFilePersistentCache&>(PersistentCache::inst())
  735. .dump_cache(env.fast_run_cache_path.c_str());
  736. }
  737. #endif
  738. #if MGB_ENABLE_TENSOR_RT
  739. if (TensorRTEngineCache::enable_engine_cache()) {
  740. TensorRTEngineCache::inst().dump_cache();
  741. }
  742. #endif
  743. }
  744. } // anonymous namespace
  745. int mgb_load_and_run_main(int argc, char** argv) {
  746. {
  747. auto v0 = get_version();
  748. auto v1 = megdnn::get_version();
  749. printf("mgb load-and-run: using MegBrain "
  750. "%d.%d.%d(%d) and MegDNN %d.%d.%d\n",
  751. v0.major, v0.minor, v0.patch, v0.is_dev, v1.major, v1.minor,
  752. v1.patch);
  753. }
  754. auto env = Args::from_argv(argc, argv);
  755. if (env.args_parse_ret != 0) {
  756. return env.args_parse_ret;
  757. }
  758. if (env.nr_thread == 1) {
  759. run_test_st(env);
  760. } else {
  761. #if MGB_HAVE_THREAD
  762. mgb_log_warn("use %d threads", env.nr_thread);
  763. std::vector<std::thread> threads;
  764. auto run = [argc, argv]() {
  765. auto env = Args::from_argv(argc, argv);
  766. run_test_st(env);
  767. };
  768. for (int i = 0; i < env.nr_thread; ++i) {
  769. threads.emplace_back(run);
  770. }
  771. for (auto&& i : threads) {
  772. i.join();
  773. }
  774. #else
  775. mgb_log_error("%d threads requested, but load-and-run was compiled "
  776. "without thread support.");
  777. #endif
  778. }
  779. return 0;
  780. }
  781. Args Args::from_argv(int argc, char **argv) {
  782. Args ret;
  783. if (argc < 2) {
  784. printf("usage: %s <model file> [options...]\nWhere options are:%s",
  785. argv[0], OPTIONS_DESC);
  786. ret.args_parse_ret = -1;
  787. return ret;
  788. }
  789. set_log_level(LogLevel::WARN);
  790. ret.model_path = argv[1];
  791. ret.load_config.comp_graph = ComputingGraph::make();
  792. auto &&graph_opt = ret.load_config.comp_graph->options();
  793. graph_opt.graph_opt_level = 0;
  794. for (int i = 2; i < argc; ++ i) {
  795. if (!strcmp(argv[i], "--cpu")) {
  796. mgb_log_warn("use cpu mode");
  797. ret.load_config.comp_node_mapper = [](CompNode::Locator &loc) {
  798. loc.type = CompNode::DeviceType::CPU;
  799. };
  800. continue;
  801. }
  802. if (!strcmp(argv[i], "--cpu-default")) {
  803. mgb_log_warn("use cpu:default mode");
  804. ret.load_config.comp_node_mapper = [](CompNode::Locator &loc) {
  805. loc.type = CompNode::DeviceType::CPU;
  806. loc.device = CompNode::Locator::DEVICE_CPU_DEFAULT;
  807. };
  808. continue;
  809. }
  810. if (!strcmp(argv[i], "--multithread")) {
  811. mgb_log_warn("use multithread mode");
  812. ++ i;
  813. ret.multithread_number = std::stoi(argv[i]);
  814. ret.load_config.comp_node_mapper =
  815. [nr_threads =
  816. ret.multithread_number](CompNode::Locator& loc) {
  817. loc.type = CompNode::DeviceType::MULTITHREAD;
  818. loc.device = 0;
  819. loc.stream = nr_threads;
  820. };
  821. continue;
  822. }
  823. if (!strcmp(argv[i], "--multithread-default")) {
  824. mgb_log_warn("use multithread:default mode");
  825. ++i;
  826. ret.multithread_number = std::stoi(argv[i]);
  827. ret.load_config.comp_node_mapper = [nr_threads =
  828. ret.multithread_number](
  829. CompNode::Locator& loc) {
  830. loc.type = CompNode::DeviceType::MULTITHREAD;
  831. loc.device = CompNode::Locator::DEVICE_MULTITHREAD_DEFAULT;
  832. loc.nr_threads = nr_threads;
  833. };
  834. continue;
  835. }
  836. if (!strcmp(argv[i], "--multi-thread-core-ids")) {
  837. ++i;
  838. std::string core_id_string = argv[i];
  839. std::stringstream input_stringstream(core_id_string);
  840. std::string id;
  841. size_t nr_threads = 0;
  842. std::vector<int> core_ids;
  843. mgb_log_warn("multi thread core ids: %s", core_id_string.c_str());
  844. while(getline(input_stringstream, id, ',')) {
  845. nr_threads++;
  846. core_ids.push_back(atoi(id.c_str()));
  847. }
  848. mgb_assert(ret.multithread_number > 0 &&
  849. ret.load_config.comp_node_mapper,
  850. "the core id should set behind the --multithread param");
  851. mgb_assert(static_cast<size_t>(ret.multithread_number) ==
  852. core_ids.size(),
  853. "the core id should equal to the multi thread number");
  854. auto affinity_cb = [core_ids](int thread_id) {
  855. mgb::sys::set_cpu_affinity({core_ids[thread_id]});
  856. };
  857. CompNode::Locator loc;
  858. ret.load_config.comp_node_mapper(loc);
  859. mgb_assert(loc.type == CompNode::DeviceType::MULTITHREAD,
  860. "core id only set on multithread compnode");
  861. auto cn = CompNode::load(loc);
  862. CompNodeEnv::from_comp_node(cn).cpu_env().set_affinity(affinity_cb);
  863. continue;
  864. }
  865. #if MGB_ENABLE_TENSOR_RT
  866. if (!strcmp(argv[i], "--tensorrt")) {
  867. mgb_log_warn("use tensorrt mode");
  868. graph_opt.graph_opt.tensorrt = true;
  869. continue;
  870. }
  871. if (!strcmp(argv[i], "--tensorrt-cache")) {
  872. ++i;
  873. mgb_assert(i < argc, "value not given for --tensorrt-cache");
  874. char* tensorrt_cache_path = argv[i];
  875. mgb_log_warn("use tensorrt cache: %s", tensorrt_cache_path);
  876. TensorRTEngineCache::enable_engine_cache(true);
  877. TensorRTEngineCache::set_impl(
  878. std::make_shared<TensorRTEngineCacheIO>(
  879. tensorrt_cache_path));
  880. continue;
  881. }
  882. #endif
  883. #define cb(_layout) \
  884. if (!strcmp(argv[i], "--enable-" #_layout)) { \
  885. mgb_log_warn("enable " #_layout " optimization"); \
  886. graph_opt.graph_opt.enable_##_layout(); \
  887. continue; \
  888. }
  889. cb(nchw4);
  890. cb(chwn4);
  891. cb(nchw44);
  892. cb(nchw88);
  893. cb(nchw32);
  894. cb(nhwcd4);
  895. #undef cb
  896. if (!strcmp(argv[i], "--enable-nchw44-dot")) {
  897. mgb_log_warn("enable-nchw44-dot optimization");
  898. graph_opt.graph_opt.enable_nchw44_dot();
  899. continue;
  900. }
  901. if (!strcmp(argv[i], "--enable-fuse-conv-bias-nonlinearity")) {
  902. mgb_log_warn("enable fuse-conv-bias-nonlinearity optimization");
  903. graph_opt.graph_opt.enable_fuse_conv_bias_nonlinearity();
  904. continue;
  905. }
  906. if (!strcmp(argv[i], "--enable-fuse-conv-bias-with-z")) {
  907. mgb_log_warn("enable fuse_conv_bias_with_z optimization");
  908. graph_opt.graph_opt.enable_fuse_conv_bias_with_z();
  909. continue;
  910. }
  911. #if MGB_ENABLE_JSON
  912. if (!strcmp(argv[i], "--profile") ||
  913. !strcmp(argv[i], "--profile-host")) {
  914. if (!strcmp(argv[i], "--profile")) {
  915. mgb_log_warn("enable profiling");
  916. } else {
  917. mgb_log_warn("enable profiling for host");
  918. }
  919. ++i;
  920. mgb_assert(i < argc, "output file not given for --profile");
  921. ret.profiler = std::make_unique<GraphProfiler>(
  922. ret.load_config.comp_graph.get());
  923. ret.profiler_output = argv[i];
  924. continue;
  925. }
  926. #endif
  927. if (!strcmp(argv[i], "--input")) {
  928. ++i;
  929. mgb_assert(i < argc, "input file not given for --input");
  930. size_t start = 0;
  931. std::string cmd = argv[i];
  932. while (true) {
  933. auto end = cmd.find(";", start);
  934. if (end == std::string::npos) {
  935. ret.data_files.emplace_back(cmd.substr(start));
  936. break;
  937. }
  938. std::string substr = cmd.substr(start, end);
  939. ret.data_files.emplace_back(substr);
  940. start = end + 1;
  941. }
  942. continue;
  943. }
  944. if (!strcmp(argv[i], "--io-dump")) {
  945. mgb_log_warn("enable opr io dump");
  946. ++ i;
  947. mgb_assert(i < argc, "output file not given for --io-dump");
  948. auto iodump = std::make_unique<TextOprIODump>(
  949. ret.load_config.comp_graph.get(), argv[i]);
  950. iodump->print_addr(false);
  951. ret.iodump = std::move(iodump);
  952. continue;
  953. }
  954. if (!strcmp(argv[i], "--bin-io-dump")) {
  955. mgb_log_warn("enable opr binary io dump");
  956. ++ i;
  957. mgb_assert(i < argc,
  958. "output directory not given for --bin-io-dump");
  959. ret.iodump = std::make_unique<BinaryOprIODump>(
  960. ret.load_config.comp_graph.get(), argv[i]);
  961. continue;
  962. }
  963. if (!strcmp(argv[i], "--bin-out-dump")) {
  964. ++ i;
  965. mgb_assert(i < argc,
  966. "output directory not given for --bin-out-dump");
  967. ret.bin_out_dump = argv[i];
  968. continue;
  969. }
  970. if (!strcmp(argv[i], "--iter")) {
  971. ++ i;
  972. mgb_assert(i < argc, "value not given for --iter");
  973. ret.nr_run = std::stoi(argv[i]);
  974. mgb_assert(ret.nr_run >= 0);
  975. continue;
  976. }
  977. if (!strcmp(argv[i], "--warmup-iter")) {
  978. ++ i;
  979. mgb_assert(i < argc, "value not given for --warmup-iter");
  980. ret.nr_warmup = std::stoi(argv[i]);
  981. mgb_assert(ret.nr_warmup >= 0);
  982. continue;
  983. }
  984. if (!strcmp(argv[i], "--range")) {
  985. ++ i;
  986. mgb_assert(i < argc, "value not given for --range");
  987. auto range = std::atof(argv[i]);
  988. mgb_assert(range > 0);
  989. ret.num_range_checker = std::make_unique<NumRangeChecker>(
  990. ret.load_config.comp_graph.get(), range);
  991. continue;
  992. }
  993. if (!strcmp(argv[i], "--check-dispatch")) {
  994. ret.cpu_dispatch_checker =
  995. std::make_unique<CPUDispatchChecker>(
  996. ret.load_config.comp_graph.get());
  997. continue;
  998. }
  999. if (!strcmp(argv[i], "--disable-mem-opt")) {
  1000. graph_opt.seq_opt.enable_mem_reuse_alloc = false;
  1001. graph_opt.seq_opt.enable_mem_plan_opt = false;
  1002. continue;
  1003. }
  1004. if (!strcmp(argv[i], "--copy-to-host")) {
  1005. ret.copy_to_host = true;
  1006. continue;
  1007. }
  1008. if (!strcmp(argv[i], "--verbose")) {
  1009. graph_opt.log_level = 2;
  1010. set_log_level(LogLevel::DEBUG);
  1011. continue;
  1012. }
  1013. if (!strcmp(argv[i], "--check-var-value")) {
  1014. ++ i;
  1015. mgb_assert(i < argc, "value not given for --check-var-value");
  1016. std::string arg(argv[i]);
  1017. auto sep = arg.find(':');
  1018. size_t switch_interval, start = 0;
  1019. if (sep != std::string::npos) {
  1020. switch_interval = std::stoul(arg.substr(0, sep));
  1021. start = std::stoul(arg.substr(sep + 1));
  1022. } else {
  1023. switch_interval = std::stoul(arg);
  1024. }
  1025. ret.var_value_checker = std::make_unique<VarValueChecker>(
  1026. ret.load_config.comp_graph.get(), switch_interval, start);
  1027. continue;
  1028. }
  1029. if (!strcmp(argv[i], "--no-sanity-check")) {
  1030. graph_opt.var_sanity_check_first_run = false;
  1031. continue;
  1032. }
  1033. if (!strcmp(argv[i], "--fake-first")) {
  1034. graph_opt.fake_next_exec = true;
  1035. continue;
  1036. }
  1037. if (!strcmp(argv[i], "--record-comp-seq")) {
  1038. graph_opt.comp_node_seq_record_level = 1;
  1039. continue;
  1040. }
  1041. if (!strcmp(argv[i], "--record-comp-seq2")) {
  1042. graph_opt.comp_node_seq_record_level = 2;
  1043. continue;
  1044. }
  1045. #if MGB_ENABLE_FASTRUN
  1046. if (!strcmp(argv[i], "--fast-run")) {
  1047. ret.use_fast_run = true;
  1048. continue;
  1049. }
  1050. #endif
  1051. if (!strcmp(argv[i], "--fast-run-algo-policy")) {
  1052. ++i;
  1053. ret.fast_run_cache_path = argv[i];
  1054. continue;
  1055. }
  1056. if (!strcmp(argv[i], "--const-shape")) {
  1057. ret.load_config.const_var_shape = true;
  1058. continue;
  1059. }
  1060. if (!strcmp(argv[i], "--share-param-mem")) {
  1061. ret.share_param_mem = true;
  1062. continue;
  1063. }
  1064. if (!strcmp(argv[i], "--disable-assert-throw")) {
  1065. ret.disable_assert_throw = true;
  1066. continue;
  1067. }
  1068. if (!strcmp(argv[i], "--workspace-limit")) {
  1069. ++i;
  1070. ret.workspace_limit = std::stoll(argv[i]);
  1071. continue;
  1072. }
  1073. #if __linux__ || __unix__
  1074. if (!strcmp(argv[i], "--wait-gdb")) {
  1075. printf("wait for gdb attach (pid=%d): ", getpid());
  1076. getchar();
  1077. continue;
  1078. }
  1079. if (!strcmp(argv[i], "--c-opr-lib")) {
  1080. ++ i;
  1081. mgb_assert(i < argc, "value not given for --c-opr-lib");
  1082. auto handle = dlopen(argv[i], RTLD_LAZY);
  1083. mgb_assert(handle, "failed to open c opr lib %s: %s",
  1084. argv[i], dlerror());
  1085. const char* entry = "mgb_c_opr_init";
  1086. auto func = dlsym(handle, entry);
  1087. mgb_assert(func, "can not resolve %s: %s", entry, dlerror());
  1088. typedef void (*entry_f_t)(void*);
  1089. reinterpret_cast<entry_f_t>(func)(
  1090. reinterpret_cast<void*>(
  1091. &mgb_get_extern_c_opr_api_versioned));
  1092. printf("loaded C opr library: %s\n", argv[i]);
  1093. continue;
  1094. }
  1095. #endif
  1096. if (!strcmp(argv[i], "--thread")) {
  1097. ++ i;
  1098. mgb_assert(i < argc, "value not given for --thread");
  1099. ret.nr_thread = std::stoi(argv[i]);
  1100. continue;
  1101. }
  1102. if (!strcmp(argv[i], "--enable-jit")) {
  1103. graph_opt.graph_opt.jit = 1;
  1104. continue;
  1105. }
  1106. if (!strcmp(argv[i], "--winograd-transform")) {
  1107. mgb_log_warn("enable winograd transform");
  1108. graph_opt.graph_opt.weight_winograd_transform = true;
  1109. continue;
  1110. }
  1111. fprintf(stderr, "invalid arg: %s\n", argv[i]);
  1112. ret.args_parse_ret = -1;
  1113. return ret;
  1114. }
  1115. return ret;
  1116. }
  1117. // vim: syntax=cpp.doxygen foldmethod=marker foldmarker=f{{{,f}}}

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台