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 46 kB

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

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