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

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

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

Contributors (1)