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.

helper.cpp 16 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. /**
  2. * \file test/src/helper.cpp
  3. *
  4. * This file is part of MegBrain, a deep learning framework developed by Megvii.
  5. *
  6. * \copyright Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  7. *
  8. */
  9. #include "./rng_seed.h"
  10. #include "megbrain/test/helper.h"
  11. #include "megbrain/utils/hash.h"
  12. #include "megbrain/utils/debug.h"
  13. #include "megbrain/utils/persistent_cache.h"
  14. #include "megbrain/comp_node_env.h"
  15. #include <atomic>
  16. #include <random>
  17. #include <cmath>
  18. #include <cstring>
  19. #include <cstdlib>
  20. #if MGB_CUDA
  21. #include <cuda.h>
  22. #include <cuda_runtime.h>
  23. #endif
  24. using namespace mgb;
  25. const dt_qint8 UniformRNGDefaultRange<dtype::QuantizedS8>::LO = dt_qint8{-128};
  26. const dt_qint8 UniformRNGDefaultRange<dtype::QuantizedS8>::HI = dt_qint8{127};
  27. bool megdnn::operator == (const TensorLayout &a, const TensorLayout &b) {
  28. if (a.ndim != b.ndim)
  29. return false;
  30. // check all shapes and strides equal, including shape-1 dims
  31. for (size_t i = 0; i < a.ndim; ++ i) {
  32. if (a[i] != b[i] || a.stride[i] != b.stride[i])
  33. return false;
  34. }
  35. return true;
  36. }
  37. uint64_t mgb::next_rand_seed() {
  38. return RNGSeedManager::inst().next_seed();
  39. }
  40. void mgb::set_rand_seed(uint64_t seed) {
  41. RNGSeedManager::inst().set_seed(seed);
  42. }
  43. RNGxorshf::RNGxorshf(uint64_t seed) {
  44. std::mt19937_64 gen(seed);
  45. s[0] = gen();
  46. s[1] = gen();
  47. }
  48. /* ========================== HostTensorGenerator ========================== */
  49. template<typename dtype>
  50. std::shared_ptr<HostTensorND> HostTensorGenerator<
  51. dtype, RandomDistribution::GAUSSIAN>::operator ()(
  52. const TensorShape &shape, CompNode cn) {
  53. if (!cn.valid())
  54. cn = CompNode::load("xpu0");
  55. std::shared_ptr<HostTensorND> ret =
  56. std::make_shared<HostTensorND>(cn, shape, dtype());
  57. auto ptr = ret->ptr<ctype>();
  58. auto mean = m_mean, std = m_std;
  59. for (size_t i = 0, it = shape.total_nr_elems(); i < it; i += 2) {
  60. ctype u1 = ctype((m_rng() + 1.0) / (m_rng.max() + 1.0)),
  61. u2 = ctype((m_rng() + 1.0) / (m_rng.max() + 1.0)),
  62. r = ctype(std * std::sqrt(-2 * std::log(u1))),
  63. theta = ctype(2 * M_PI * u2),
  64. z0 = ctype(r * std::cos(theta) + mean),
  65. z1 = ctype(r * std::sin(theta) + mean);
  66. ptr[i] = z0;
  67. ptr[std::min(i + 1, it - 1)] = z1;
  68. }
  69. return ret;
  70. }
  71. template<typename dtype>
  72. std::shared_ptr<HostTensorND> HostTensorGenerator<
  73. dtype, RandomDistribution::UNIFORM>::operator ()(
  74. const TensorShape &shape, CompNode cn) {
  75. if (!cn.valid())
  76. cn = CompNode::load("xpu0");
  77. std::shared_ptr<HostTensorND> ret =
  78. std::make_shared<HostTensorND>(cn, shape, dtype());
  79. auto ptr = ret->ptr<ctype>();
  80. double scale = (m_hi - m_lo) / (m_rng.max() + 1.0);
  81. for (size_t i = 0, it = shape.total_nr_elems(); i < it; ++ i) {
  82. ptr[i] = m_rng() * scale + m_lo;
  83. }
  84. return ret;
  85. }
  86. template<typename dtype>
  87. std::shared_ptr<HostTensorND> HostTensorGenerator<
  88. dtype, RandomDistribution::CONSTANT>::operator ()(
  89. const TensorShape &shape, CompNode cn) {
  90. if (!cn.valid())
  91. cn = CompNode::load("xpu0");
  92. std::shared_ptr<HostTensorND> ret =
  93. std::make_shared<HostTensorND>(cn, shape, dtype());
  94. auto ptr = ret->ptr<ctype>();
  95. for (size_t i = 0, it = shape.total_nr_elems(); i < it; ++ i) {
  96. ptr[i] = m_default_val;
  97. }
  98. return ret;
  99. }
  100. template<typename dtype>
  101. std::shared_ptr<HostTensorND> HostTensorGenerator<
  102. dtype, RandomDistribution::CONSECUTIVE>::operator ()(
  103. const TensorShape &shape, CompNode cn) {
  104. if (!cn.valid())
  105. cn = CompNode::load("xpu0");
  106. std::shared_ptr<HostTensorND> ret =
  107. std::make_shared<HostTensorND>(cn, shape, dtype());
  108. auto ptr = ret->ptr<ctype>();
  109. for (size_t i = 0, it = shape.total_nr_elems(); i < it; ++ i) {
  110. ptr[i] = m_val + i * m_delta;
  111. }
  112. return ret;
  113. }
  114. // explicit instantialization of HostTensorGenerator
  115. namespace mgb {
  116. template class HostTensorGenerator<
  117. dtype::Float32, RandomDistribution::GAUSSIAN>;
  118. template class HostTensorGenerator<
  119. dtype::Float32, RandomDistribution::UNIFORM>;
  120. template class HostTensorGenerator<
  121. dtype::Float32, RandomDistribution::CONSTANT>;
  122. template class HostTensorGenerator<
  123. dtype::Float32, RandomDistribution::CONSECUTIVE>;
  124. template class HostTensorGenerator<
  125. dtype::Float16, RandomDistribution::GAUSSIAN>;
  126. template class HostTensorGenerator<
  127. dtype::Int8, RandomDistribution::UNIFORM>;
  128. template class HostTensorGenerator<
  129. dtype::Int8, RandomDistribution::CONSTANT>;
  130. template class HostTensorGenerator<
  131. dtype::Int8, RandomDistribution::CONSECUTIVE>;
  132. template class HostTensorGenerator<
  133. dtype::Uint8, RandomDistribution::UNIFORM>;
  134. template class HostTensorGenerator<
  135. dtype::Uint8, RandomDistribution::CONSTANT>;
  136. template class HostTensorGenerator<
  137. dtype::Int16, RandomDistribution::UNIFORM>;
  138. template class HostTensorGenerator<
  139. dtype::Int16, RandomDistribution::CONSTANT>;
  140. template class HostTensorGenerator<
  141. dtype::Int32, RandomDistribution::UNIFORM>;
  142. template class HostTensorGenerator<
  143. dtype::Int32, RandomDistribution::CONSTANT>;
  144. std::shared_ptr<HostTensorND>
  145. HostTensorGenerator<dtype::Bool, RandomDistribution::UNIFORM>::
  146. operator()(const TensorShape& shape, CompNode cn) {
  147. if (!cn.valid())
  148. cn = CompNode::load("xpu0");
  149. auto dtype = dtype::Bool();
  150. std::shared_ptr<HostTensorND> ret =
  151. std::make_shared<HostTensorND>(cn, shape, dtype);
  152. auto ptr = ret->ptr<dt_bool>();
  153. for (size_t i = 0, it = shape.total_nr_elems(); i < it; ++i) {
  154. ptr[i] = (i % 2 == 1);
  155. }
  156. return ret;
  157. }
  158. std::shared_ptr<HostTensorND>
  159. HostTensorGenerator<dtype::QuantizedS8, RandomDistribution::UNIFORM>::
  160. operator()(const TensorShape& shape, CompNode cn) {
  161. if (!cn.valid())
  162. cn = CompNode::load("xpu0");
  163. auto dtype = dtype::QuantizedS8(m_scale);
  164. auto param = dtype.param();
  165. std::shared_ptr<HostTensorND> ret =
  166. std::make_shared<HostTensorND>(cn, shape, dtype);
  167. auto ptr = ret->ptr<dt_qint8>();
  168. double scale = (param.dequantize(m_hi) - param.dequantize(m_lo)) /
  169. (m_rng.max() + 1.0);
  170. for (size_t i = 0, it = shape.total_nr_elems(); i < it; ++i) {
  171. ptr[i] = param.quantize(m_rng() * scale + param.dequantize(m_lo));
  172. }
  173. return ret;
  174. }
  175. std::shared_ptr<HostTensorND>
  176. HostTensorGenerator<dtype::Quantized8Asymm, RandomDistribution::UNIFORM>::
  177. operator()(const TensorShape& shape, CompNode cn) {
  178. if (!cn.valid())
  179. cn = CompNode::load("xpu0");
  180. auto dtype = dtype::Quantized8Asymm(m_scale, m_zero_point);
  181. auto param = dtype.param();
  182. std::shared_ptr<HostTensorND> ret =
  183. std::make_shared<HostTensorND>(cn, shape, dtype);
  184. auto ptr = ret->ptr<dt_quint8>();
  185. double scale = (param.dequantize(m_hi) - param.dequantize(m_lo)) /
  186. (m_rng.max() + 1.0);
  187. for (size_t i = 0, it = shape.total_nr_elems(); i < it; ++i) {
  188. ptr[i] = param.quantize(m_rng() * scale + param.dequantize(m_lo));
  189. }
  190. return ret;
  191. }
  192. }
  193. ::testing::AssertionResult mgb::__assert_float_equal(
  194. const char *expr0, const char *expr1, const char * /*expr_maxerr*/,
  195. float v0, float v1, float maxerr) {
  196. float err = fabs(v0 - v1) / std::max<float>(
  197. 1, std::min(fabs(v0), fabs(v1)));
  198. if (std::isfinite(v0) && std::isfinite(v1) && err < maxerr) {
  199. return ::testing::AssertionSuccess();
  200. }
  201. return ::testing::AssertionFailure() << ssprintf(
  202. "Value of: %s\n"
  203. " Actual: %.6g\n"
  204. "Expected: %s\n"
  205. "Which is: %.6g\n"
  206. " Error: %.4e", expr1, v1, expr0, v0, err);
  207. }
  208. ::testing::AssertionResult mgb::__assert_tensor_equal(
  209. const char *expr0, const char *expr1, const char * /*expr_maxerr*/,
  210. const HostTensorND &v0, const HostTensorND &v1, float maxerr) {
  211. auto ret = debug::compare_tensor_value(v0, expr0, v1, expr1, maxerr);
  212. if (ret.valid())
  213. return ::testing::AssertionFailure() << ret.val();
  214. return ::testing::AssertionSuccess();
  215. }
  216. ::testing::AssertionResult mgb::__assert_shape_equal(const TensorShape& v0,
  217. const TensorShape& v1) {
  218. if (v0.eq_shape(v1))
  219. return ::testing::AssertionSuccess()
  220. << v0.to_string() << " == " << v1.to_string();
  221. else
  222. return ::testing::AssertionFailure()
  223. << v0.to_string() << " != " << v1.to_string();
  224. }
  225. #if WIN32
  226. #include <io.h>
  227. #include <fcntl.h>
  228. #include <direct.h>
  229. #define getcwd _getcwd
  230. namespace {
  231. auto mkdir(const char *path, int) {
  232. return _mkdir(path);
  233. }
  234. int mkstemp(char *tpl){
  235. tpl = _mktemp(tpl);
  236. mgb_assert(tpl);
  237. auto fd = _open(tpl, _O_TEMPORARY | _O_RDWR);
  238. mgb_assert(fd > 0, "failed to open %s: %s", tpl, strerror(errno));
  239. return fd;
  240. }
  241. }
  242. #else
  243. #include <unistd.h>
  244. #include <sys/stat.h>
  245. #include <sys/types.h>
  246. #endif
  247. NamedTemporaryFile::NamedTemporaryFile()
  248. {
  249. char name[256];
  250. strcpy(name, output_file("mgb-test-XXXXXX", false).c_str());
  251. m_fd = mkstemp(name);
  252. mgb_throw_if(m_fd == -1, MegBrainError,
  253. "failed to open temp file `%s': %m", name);
  254. m_fpath = name;
  255. mgb_log_debug("opened temporary file: %s", name);
  256. }
  257. NamedTemporaryFile::~NamedTemporaryFile() {
  258. #ifdef WIN32
  259. _unlink(m_fpath.c_str());
  260. #else
  261. unlink(m_fpath.c_str());
  262. #endif
  263. }
  264. #if defined(IOS)
  265. #pragma message "build test on iOS; need ios_get_mgb_output_dir() to be defined"
  266. extern "C" void ios_get_mgb_output_dir(char **dir);
  267. #endif
  268. std::string mgb::output_file(const std::string &fname, bool check_writable) {
  269. static std::string cwd;
  270. static std::mutex cwd_mtx;
  271. MGB_LOCK_GUARD(cwd_mtx);
  272. if (cwd.empty()) {
  273. #if defined(IOS)
  274. char *buf = nullptr;
  275. ios_get_mgb_output_dir(&buf);
  276. #else
  277. auto buf = getcwd(nullptr, 0);
  278. #endif
  279. mgb_assert(buf);
  280. cwd = buf;
  281. free(buf);
  282. cwd.append("/output");
  283. mgb_log("use test output dir: %s", cwd.c_str());
  284. mkdir(cwd.c_str(), 0755);
  285. }
  286. if (fname.empty())
  287. return cwd;
  288. auto ret = cwd + "/" + fname;
  289. if (check_writable) {
  290. FILE *fout = fopen(ret.c_str(), "w");
  291. mgb_assert(fout, "failed to open %s: %s", ret.c_str(), strerror(errno));
  292. fclose(fout);
  293. }
  294. return ret;
  295. }
  296. std::vector<CompNode> mgb::load_multiple_xpus(size_t num) {
  297. auto cn0 = CompNode::load("xpu0");
  298. if (CompNode::get_device_count(cn0.device_type()) < num) {
  299. cn0 = CompNode::load("cpu0");
  300. }
  301. std::vector<CompNode> ret{cn0};
  302. auto loc = cn0.locator();
  303. for (size_t i = 1; i < num; ++ i) {
  304. loc.device = i;
  305. ret.push_back(CompNode::load(loc));
  306. }
  307. return ret;
  308. }
  309. bool mgb::check_xpu_available(size_t num) {
  310. if (CompNode::get_device_count(CompNode::DeviceType::UNSPEC) < num) {
  311. mgb_log_warn("skip test case that requires %zu XPU(s)", num);
  312. return false;
  313. }
  314. return true;
  315. }
  316. bool mgb::check_gpu_available(size_t num) {
  317. if (CompNode::get_device_count(CompNode::DeviceType::CUDA) < num) {
  318. mgb_log_warn("skip test case that requires %zu GPU(s)", num);
  319. return false;
  320. }
  321. return true;
  322. }
  323. bool mgb::check_amd_gpu_available(size_t num) {
  324. if (CompNode::get_device_count(CompNode::DeviceType::ROCM) < num) {
  325. mgb_log_warn("skip test case that requires %zu AMD GPU(s)", num);
  326. return false;
  327. }
  328. return true;
  329. }
  330. bool mgb::check_cambricon_device_available(size_t num) {
  331. if (CompNode::get_device_count(CompNode::DeviceType::CAMBRICON) < num) {
  332. mgb_log_warn("skip test case that requires %zu cambricon device(s)",
  333. num);
  334. return false;
  335. }
  336. return true;
  337. }
  338. bool mgb::check_device_type_avaiable(CompNode::DeviceType device_type) {
  339. switch (device_type) {
  340. case mgb::CompNode::DeviceType::CUDA:
  341. case mgb::CompNode::DeviceType::CPU:
  342. case mgb::CompNode::DeviceType::CAMBRICON:
  343. case mgb::CompNode::DeviceType::ATLAS:
  344. case mgb::CompNode::DeviceType::MULTITHREAD:
  345. return true;
  346. default:
  347. return false;
  348. }
  349. return false;
  350. }
  351. bool mgb::check_compute_capability(int major, int minor) {
  352. #if MGB_CUDA
  353. int dev;
  354. MGB_CUDA_CHECK(cudaGetDevice(&dev));
  355. cudaDeviceProp prop;
  356. MGB_CUDA_CHECK(cudaGetDeviceProperties(&prop, dev));
  357. bool available = prop.major > major || (prop.major == major && prop.minor >= minor);
  358. if (!available) {
  359. mgb_log_warn(
  360. "This testcase is ignored due to insufficient cuda cap(got: "
  361. "%d.%d, "
  362. "expected: %d.%d)",
  363. prop.major, prop.minor, major, minor);
  364. }
  365. return available;
  366. #else
  367. MGB_MARK_USED_VAR(major);
  368. MGB_MARK_USED_VAR(minor);
  369. return false;
  370. #endif
  371. }
  372. bool mgb::check_compute_capability_eq(int major, int minor) {
  373. #if MGB_CUDA
  374. int dev;
  375. MGB_CUDA_CHECK(cudaGetDevice(&dev));
  376. cudaDeviceProp prop;
  377. MGB_CUDA_CHECK(cudaGetDeviceProperties(&prop, dev));
  378. bool available = prop.major == major && prop.minor == minor;
  379. if (!available) {
  380. mgb_log_warn(
  381. "This testcase is ignored due to insufficient cuda cap(got: "
  382. "%d.%d, "
  383. "expected: %d.%d)",
  384. prop.major, prop.minor, major, minor);
  385. }
  386. return available;
  387. #else
  388. MGB_MARK_USED_VAR(major);
  389. MGB_MARK_USED_VAR(minor);
  390. return false;
  391. #endif
  392. }
  393. void mgb::write_tensor_to_file(const HostTensorND &hv,
  394. const char *fname, char mode) {
  395. mgb_assert(hv.layout().is_contiguous());
  396. char modefull[] = {mode, 'b', '\x00'};
  397. FILE *fout = fopen(fname, modefull);
  398. mgb_assert(fout, "failed to open %s: %s", fname, strerror(errno));
  399. fprintf(fout, "%s %zu", hv.dtype().name(), hv.shape().ndim);
  400. for (size_t i = 0; i < hv.shape().ndim; ++ i) {
  401. fprintf(fout, " %zu", hv.shape(i));
  402. }
  403. fprintf(fout, "\n");
  404. auto size = hv.layout().span().dist_byte();
  405. auto wr = fwrite(hv.raw_ptr(), 1, size, fout);
  406. mgb_assert(size == wr);
  407. mgb_log("write tensor: %zu bytes (%s) to %s", size,
  408. hv.shape().to_string().c_str(), fname);
  409. fclose(fout);
  410. }
  411. cg::ComputingGraph::OutputSpecItem
  412. mgb::make_callback_copy(SymbolVar dev, HostTensorND &host, bool sync) {
  413. auto cb = [sync, &host](DeviceTensorND &d) {
  414. host.copy_from(d);
  415. if (sync) {
  416. host.sync();
  417. }
  418. };
  419. return {dev, cb};
  420. }
  421. /* ========================== PersistentCacheHook ========================== */
  422. class PersistentCacheHook::HookedImpl final : public PersistentCache {
  423. Hook m_on_get, m_on_set;
  424. public:
  425. std::shared_ptr<PersistentCache> orig_impl;
  426. HookedImpl(Hook on_get, Hook on_set)
  427. : m_on_get{std::move(on_get)}, m_on_set{std::move(on_set)} {}
  428. Maybe<Blob> get(const std::string& category, const Blob& key) override {
  429. auto ret = orig_impl->get(category, key);
  430. m_on_get(category, key.ptr, key.size, ret.valid() ? ret->ptr : 0,
  431. ret.valid() ? ret->size : 0);
  432. return ret;
  433. }
  434. void put(const std::string& category, const Blob& key,
  435. const Blob& value) override {
  436. m_on_set(category, key.ptr, key.size, value.ptr,
  437. value.size);
  438. orig_impl->put(category, key, value);
  439. }
  440. };
  441. PersistentCacheHook::Hook PersistentCacheHook::default_set_hook =
  442. [](const std::string&, const void*, size_t, const void*, size_t) {};
  443. PersistentCacheHook::PersistentCacheHook(Hook on_get, Hook on_set)
  444. : m_impl{std::make_shared<HookedImpl>(std::move(on_get),
  445. std::move(on_set))} {
  446. m_impl->orig_impl = PersistentCache::set_impl(m_impl);
  447. }
  448. PersistentCacheHook::~PersistentCacheHook() {
  449. PersistentCache::set_impl(std::move(m_impl->orig_impl));
  450. }
  451. #if !MGB_ENABLE_EXCEPTION
  452. #pragma message "some tests would be disabled because exception is disabled"
  453. #endif
  454. // vim: syntax=cpp.doxygen foldmethod=marker foldmarker=f{{{,f}}}

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