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

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

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