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

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

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