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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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-2020 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. // explicit instantialization of HostTensorGenerator
  101. namespace mgb {
  102. template class HostTensorGenerator<
  103. dtype::Float32, RandomDistribution::GAUSSIAN>;
  104. template class HostTensorGenerator<
  105. dtype::Float32, RandomDistribution::UNIFORM>;
  106. template class HostTensorGenerator<
  107. dtype::Float32, RandomDistribution::CONSTANT>;
  108. template class HostTensorGenerator<
  109. dtype::Float16, RandomDistribution::GAUSSIAN>;
  110. template class HostTensorGenerator<
  111. dtype::Int8, RandomDistribution::UNIFORM>;
  112. template class HostTensorGenerator<
  113. dtype::Int8, RandomDistribution::CONSTANT>;
  114. template class HostTensorGenerator<
  115. dtype::Uint8, RandomDistribution::UNIFORM>;
  116. template class HostTensorGenerator<
  117. dtype::Uint8, RandomDistribution::CONSTANT>;
  118. template class HostTensorGenerator<
  119. dtype::Int16, RandomDistribution::UNIFORM>;
  120. template class HostTensorGenerator<
  121. dtype::Int16, RandomDistribution::CONSTANT>;
  122. template class HostTensorGenerator<
  123. dtype::Int32, RandomDistribution::UNIFORM>;
  124. template class HostTensorGenerator<
  125. dtype::Int32, RandomDistribution::CONSTANT>;
  126. std::shared_ptr<HostTensorND>
  127. HostTensorGenerator<dtype::Bool, RandomDistribution::UNIFORM>::
  128. operator()(const TensorShape& shape, CompNode cn) {
  129. if (!cn.valid())
  130. cn = CompNode::load("xpu0");
  131. auto dtype = dtype::Bool();
  132. std::shared_ptr<HostTensorND> ret =
  133. std::make_shared<HostTensorND>(cn, shape, dtype);
  134. auto ptr = ret->ptr<dt_bool>();
  135. for (size_t i = 0, it = shape.total_nr_elems(); i < it; ++i) {
  136. ptr[i] = (i % 2 == 1);
  137. }
  138. return ret;
  139. }
  140. std::shared_ptr<HostTensorND>
  141. HostTensorGenerator<dtype::QuantizedS8, RandomDistribution::UNIFORM>::
  142. operator()(const TensorShape& shape, CompNode cn) {
  143. if (!cn.valid())
  144. cn = CompNode::load("xpu0");
  145. auto dtype = dtype::QuantizedS8(m_scale);
  146. auto param = dtype.param();
  147. std::shared_ptr<HostTensorND> ret =
  148. std::make_shared<HostTensorND>(cn, shape, dtype);
  149. auto ptr = ret->ptr<dt_qint8>();
  150. double scale = (param.dequantize(m_hi) - param.dequantize(m_lo)) /
  151. (m_rng.max() + 1.0);
  152. for (size_t i = 0, it = shape.total_nr_elems(); i < it; ++i) {
  153. ptr[i] = param.quantize(m_rng() * scale + param.dequantize(m_lo));
  154. }
  155. return ret;
  156. }
  157. }
  158. ::testing::AssertionResult mgb::__assert_float_equal(
  159. const char *expr0, const char *expr1, const char * /*expr_maxerr*/,
  160. float v0, float v1, float maxerr) {
  161. float err = fabs(v0 - v1) / std::max<float>(
  162. 1, std::min(fabs(v0), fabs(v1)));
  163. if (std::isfinite(v0) && std::isfinite(v1) && err < maxerr) {
  164. return ::testing::AssertionSuccess();
  165. }
  166. return ::testing::AssertionFailure() << ssprintf(
  167. "Value of: %s\n"
  168. " Actual: %.6g\n"
  169. "Expected: %s\n"
  170. "Which is: %.6g\n"
  171. " Error: %.4e", expr1, v1, expr0, v0, err);
  172. }
  173. ::testing::AssertionResult mgb::__assert_tensor_equal(
  174. const char *expr0, const char *expr1, const char * /*expr_maxerr*/,
  175. const HostTensorND &v0, const HostTensorND &v1, float maxerr) {
  176. auto ret = debug::compare_tensor_value(v0, expr0, v1, expr1, maxerr);
  177. if (ret.valid())
  178. return ::testing::AssertionFailure() << ret.val();
  179. return ::testing::AssertionSuccess();
  180. }
  181. ::testing::AssertionResult mgb::__assert_shape_equal(const TensorShape& v0,
  182. const TensorShape& v1) {
  183. if (v0.eq_shape(v1))
  184. return ::testing::AssertionSuccess()
  185. << v0.to_string() << " == " << v1.to_string();
  186. else
  187. return ::testing::AssertionFailure()
  188. << v0.to_string() << " != " << v1.to_string();
  189. }
  190. #if WIN32
  191. #include <io.h>
  192. #include <fcntl.h>
  193. #include <direct.h>
  194. #define getcwd _getcwd
  195. namespace {
  196. auto mkdir(const char *path, int) {
  197. return _mkdir(path);
  198. }
  199. int mkstemp(char *tpl){
  200. tpl = _mktemp(tpl);
  201. mgb_assert(tpl);
  202. auto fd = _open(tpl, _O_TEMPORARY | _O_RDWR);
  203. mgb_assert(fd > 0, "failed to open %s: %s", tpl, strerror(errno));
  204. return fd;
  205. }
  206. }
  207. #else
  208. #include <unistd.h>
  209. #include <sys/stat.h>
  210. #include <sys/types.h>
  211. #endif
  212. NamedTemporaryFile::NamedTemporaryFile()
  213. {
  214. char name[256];
  215. strcpy(name, output_file("mgb-test-XXXXXX", false).c_str());
  216. m_fd = mkstemp(name);
  217. mgb_throw_if(m_fd == -1, MegBrainError,
  218. "failed to open temp file `%s': %m", name);
  219. m_fpath = name;
  220. mgb_log_debug("opened temporary file: %s", name);
  221. }
  222. NamedTemporaryFile::~NamedTemporaryFile() {
  223. #ifdef WIN32
  224. _unlink(m_fpath.c_str());
  225. #else
  226. unlink(m_fpath.c_str());
  227. #endif
  228. }
  229. #if defined(IOS)
  230. #pragma message "build test on iOS; need ios_get_mgb_output_dir() to be defined"
  231. extern "C" void ios_get_mgb_output_dir(char **dir);
  232. #endif
  233. std::string mgb::output_file(const std::string &fname, bool check_writable) {
  234. static std::string cwd;
  235. static std::mutex cwd_mtx;
  236. MGB_LOCK_GUARD(cwd_mtx);
  237. if (cwd.empty()) {
  238. #if defined(IOS)
  239. char *buf = nullptr;
  240. ios_get_mgb_output_dir(&buf);
  241. #else
  242. auto buf = getcwd(nullptr, 0);
  243. #endif
  244. mgb_assert(buf);
  245. cwd = buf;
  246. free(buf);
  247. cwd.append("/output");
  248. mgb_log("use test output dir: %s", cwd.c_str());
  249. mkdir(cwd.c_str(), 0755);
  250. }
  251. if (fname.empty())
  252. return cwd;
  253. auto ret = cwd + "/" + fname;
  254. if (check_writable) {
  255. FILE *fout = fopen(ret.c_str(), "w");
  256. mgb_assert(fout, "failed to open %s: %s", ret.c_str(), strerror(errno));
  257. fclose(fout);
  258. }
  259. return ret;
  260. }
  261. std::vector<CompNode> mgb::load_multiple_xpus(size_t num) {
  262. auto cn0 = CompNode::load("xpu0");
  263. if (CompNode::get_device_count(cn0.device_type()) < num) {
  264. cn0 = CompNode::load("cpu0");
  265. }
  266. std::vector<CompNode> ret{cn0};
  267. auto loc = cn0.locator();
  268. for (size_t i = 1; i < num; ++ i) {
  269. loc.device = i;
  270. ret.push_back(CompNode::load(loc));
  271. }
  272. return ret;
  273. }
  274. bool mgb::check_gpu_available(size_t num) {
  275. if (CompNode::get_device_count(CompNode::DeviceType::CUDA) < num) {
  276. mgb_log_warn("skip test case that requires %zu GPU(s)", num);
  277. return false;
  278. }
  279. return true;
  280. }
  281. bool mgb::check_compute_capability(int major, int minor) {
  282. #if MGB_CUDA
  283. int dev;
  284. MGB_CUDA_CHECK(cudaGetDevice(&dev));
  285. cudaDeviceProp prop;
  286. MGB_CUDA_CHECK(cudaGetDeviceProperties(&prop, dev));
  287. return prop.major > major || (prop.major == major && prop.minor >= minor);
  288. #else
  289. MGB_MARK_USED_VAR(major);
  290. MGB_MARK_USED_VAR(minor);
  291. return false;
  292. #endif
  293. }
  294. void mgb::write_tensor_to_file(const HostTensorND &hv,
  295. const char *fname, char mode) {
  296. mgb_assert(hv.layout().is_contiguous());
  297. char modefull[] = {mode, 'b', '\x00'};
  298. FILE *fout = fopen(fname, modefull);
  299. mgb_assert(fout, "failed to open %s: %s", fname, strerror(errno));
  300. fprintf(fout, "%s %zu", hv.dtype().name(), hv.shape().ndim);
  301. for (size_t i = 0; i < hv.shape().ndim; ++ i) {
  302. fprintf(fout, " %zu", hv.shape(i));
  303. }
  304. fprintf(fout, "\n");
  305. auto size = hv.layout().span().dist_byte();
  306. auto wr = fwrite(hv.raw_ptr(), 1, size, fout);
  307. mgb_assert(size == wr);
  308. mgb_log("write tensor: %zu bytes (%s) to %s", size,
  309. hv.shape().to_string().c_str(), fname);
  310. fclose(fout);
  311. }
  312. cg::ComputingGraph::OutputSpecItem
  313. mgb::make_callback_copy(SymbolVar dev, HostTensorND &host, bool sync) {
  314. auto cb = [sync, &host](DeviceTensorND &d) {
  315. host.copy_from(d);
  316. if (sync) {
  317. host.sync();
  318. }
  319. };
  320. return {dev, cb};
  321. }
  322. /* ========================== PersistentCacheHook ========================== */
  323. class PersistentCacheHook::HookedImpl final : public PersistentCache {
  324. GetHook m_on_get;
  325. public:
  326. std::shared_ptr<PersistentCache> orig_impl;
  327. HookedImpl(GetHook on_get) : m_on_get{std::move(on_get)} {}
  328. Maybe<Blob> get(const std::string& category, const Blob& key) override {
  329. auto ret = orig_impl->get(category, key);
  330. m_on_get(category, key.ptr, key.size, ret.valid() ? ret->ptr : 0,
  331. ret.valid() ? ret->size : 0);
  332. return ret;
  333. }
  334. void put(const std::string& category, const Blob& key,
  335. const Blob& value) override {
  336. orig_impl->put(category, key, value);
  337. }
  338. };
  339. PersistentCacheHook::PersistentCacheHook(GetHook on_get)
  340. : m_impl{std::make_shared<HookedImpl>(std::move(on_get))} {
  341. m_impl->orig_impl = PersistentCache::set_impl(m_impl);
  342. }
  343. PersistentCacheHook::~PersistentCacheHook() {
  344. PersistentCache::set_impl(std::move(m_impl->orig_impl));
  345. }
  346. #if !MGB_ENABLE_EXCEPTION
  347. #pragma message "some tests would be disabled because exception is disabled"
  348. #endif
  349. // vim: syntax=cpp.doxygen foldmethod=marker foldmarker=f{{{,f}}}

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