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.

test_functional.py 22 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. import itertools
  10. from functools import partial
  11. import numpy as np
  12. import pytest
  13. from utils import opr_test
  14. import megengine.core.ops.builtin as builtin
  15. import megengine.core.tensor.dtype as dtype
  16. import megengine.functional as F
  17. from megengine import Parameter, Tensor, is_cuda_available, tensor
  18. from megengine.core._trace_option import use_symbolic_shape
  19. from megengine.core.autodiff.grad import Grad
  20. from megengine.core.tensor.utils import make_shape_tuple
  21. from megengine.distributed.helper import get_device_count_by_fork
  22. def test_where():
  23. maskv0 = np.array([[1, 0], [0, 1]], dtype=np.bool_)
  24. xv0 = np.array([[1, np.inf], [np.nan, 4]], dtype=np.float32)
  25. yv0 = np.array([[5, 6], [7, 8]], dtype=np.float32)
  26. maskv1 = np.array([[1, 0, 1], [1, 0, 0], [1, 1, 0]], dtype=np.bool_)
  27. xv1 = np.array([[1, np.inf, 2], [0, np.nan, 4], [1, 5, 7]], dtype=np.float32)
  28. yv1 = np.array([[5, 6, 9], [2, 7, 8], [2, 1, 9]], dtype=np.float32)
  29. cases = [
  30. {"input": [maskv0, xv0, yv0]},
  31. {"input": [maskv1, xv1, yv1]},
  32. ]
  33. opr_test(cases, F.where, ref_fn=np.where)
  34. maskv2 = np.array([1, 1, 1], dtype=np.bool_)
  35. xv2 = np.array([1, 3, 2], dtype=np.float32)
  36. yv2 = np.array([5, 6, 9], dtype=np.float32)
  37. maskv3 = np.array([0, 0, 0], dtype=np.bool_)
  38. xv3 = np.array([1, 3, 2], dtype=np.float32)
  39. yv3 = np.array([5, 6, 9], dtype=np.float32)
  40. cases = [
  41. {"input": [maskv2, xv2, yv2]},
  42. {"input": [maskv3, xv3, yv3]},
  43. ]
  44. opr_test(cases, F.where, ref_fn=np.where)
  45. def test_dropout():
  46. data = tensor(np.ones(10, dtype=np.float32))
  47. out = F.dropout(data, 1.0 / 3.0, training=False)
  48. assert out.numpy().sum() >= 0.0
  49. def test_matinv():
  50. shape1 = (5, 5)
  51. shape2 = (3, 9, 9)
  52. data1 = np.random.random(shape1).astype("float32")
  53. data2 = np.random.random(shape2).astype("float32")
  54. cases = [
  55. {"input": data1},
  56. {"input": data2},
  57. ]
  58. opr_test(
  59. cases,
  60. F.matinv,
  61. compare_fn=lambda x, y: np.testing.assert_allclose(x.numpy(), y, rtol=1e-5),
  62. ref_fn=np.linalg.inv,
  63. )
  64. def test_matmul():
  65. shape1 = 3
  66. shape2 = 3
  67. shape3 = (3, 5)
  68. shape4 = (5, 6)
  69. data1 = np.random.random(shape1).astype("float32")
  70. data2 = np.random.random(shape2).astype("float32")
  71. data3 = np.random.random(shape3).astype("float32")
  72. data4 = np.random.random(shape4).astype("float32")
  73. cases = [
  74. {"input": [data1, data2]},
  75. {"input": [data2, data3]},
  76. {"input": [data3, data4]},
  77. ]
  78. opr_test(cases, F.matmul, ref_fn=np.matmul)
  79. batch_size = 10
  80. shape1 = (2,)
  81. shape2 = (batch_size, 2, 3)
  82. shape3 = (batch_size, 3, 4)
  83. shape4 = (batch_size, 10, 4, 2)
  84. shape5 = (batch_size, 10, 2, 4)
  85. data1 = np.random.random(shape1).astype("float32")
  86. data2 = np.random.random(shape2).astype("float32")
  87. data3 = np.random.random(shape3).astype("float32")
  88. data4 = np.random.random(shape4).astype("float32")
  89. data5 = np.random.random(shape5).astype("float32")
  90. cases = [
  91. {"input": [data1, data2]},
  92. {"input": [data2, data3]},
  93. {"input": [data3, data4]},
  94. {"input": [data4, data5]},
  95. ]
  96. for _ in range(0, batch_size):
  97. opr_test(
  98. cases, F.matmul, ref_fn=np.matmul,
  99. )
  100. opr_test(
  101. [{"input": [data1, data4]}],
  102. F.matmul,
  103. ref_fn=lambda x, y: np.matmul(x, y.transpose(0, 1, 3, 2)),
  104. transpose_b=True,
  105. )
  106. opr_test(
  107. [{"input": [data3, data2]}],
  108. F.matmul,
  109. ref_fn=lambda x, y: np.matmul(x.transpose(0, 2, 1), y.transpose(0, 2, 1)),
  110. transpose_a=True,
  111. transpose_b=True,
  112. )
  113. def test_interpolate():
  114. def linear_interpolate():
  115. inp = tensor(np.arange(1, 3, dtype=np.float32).reshape(1, 1, 2))
  116. out = F.nn.interpolate(inp, scale_factor=2.0, mode="LINEAR")
  117. out2 = F.nn.interpolate(inp, 4, mode="LINEAR")
  118. np.testing.assert_allclose(
  119. out.numpy(), np.array([[[1.0, 1.25, 1.75, 2.0]]], dtype=np.float32)
  120. )
  121. np.testing.assert_allclose(
  122. out2.numpy(), np.array([[[1.0, 1.25, 1.75, 2.0]]], dtype=np.float32)
  123. )
  124. def many_batch_interpolate():
  125. inp = tensor(np.arange(1, 9, dtype=np.float32).reshape(2, 1, 2, 2))
  126. out = F.nn.interpolate(inp, [4, 4])
  127. out2 = F.nn.interpolate(inp, scale_factor=2.0)
  128. np.testing.assert_allclose(out.numpy(), out2.numpy())
  129. def assign_corner_interpolate():
  130. inp = tensor(np.arange(1, 5, dtype=np.float32).reshape(1, 1, 2, 2))
  131. out = F.nn.interpolate(inp, [4, 4], align_corners=True)
  132. out2 = F.nn.interpolate(inp, scale_factor=2.0, align_corners=True)
  133. np.testing.assert_allclose(out.numpy(), out2.numpy())
  134. def error_shape_linear_interpolate():
  135. inp = tensor(np.arange(1, 5, dtype=np.float32).reshape(1, 1, 2, 2))
  136. with pytest.raises(ValueError):
  137. F.nn.interpolate(inp, scale_factor=2.0, mode="LINEAR")
  138. def inappropriate_scale_linear_interpolate():
  139. inp = tensor(np.arange(1, 3, dtype=np.float32).reshape(1, 1, 2))
  140. with pytest.raises(ValueError):
  141. F.nn.interpolate(inp, scale_factor=[2.0, 3.0], mode="LINEAR")
  142. linear_interpolate()
  143. many_batch_interpolate()
  144. assign_corner_interpolate()
  145. error_shape_linear_interpolate()
  146. inappropriate_scale_linear_interpolate()
  147. def _save_to(self, name="grad"):
  148. def callback(grad):
  149. setattr(self, name, grad)
  150. return callback
  151. def _gen_roi_inp():
  152. inp_feat = np.random.randn(2, 32, 256, 256)
  153. rois = np.zeros((4, 5))
  154. rois[:, 0] = [0, 0, 1, 1]
  155. rois[:, 1:3] = np.random.rand(4, 2) * 100
  156. rois[:, 3:] = np.random.rand(4, 2) * 100 + 150
  157. inp_feat = tensor(inp_feat)
  158. rois = tensor(rois)
  159. return inp_feat, rois
  160. def test_roi_align():
  161. inp_feat, rois = _gen_roi_inp()
  162. grad = Grad().wrt(inp_feat, callback=_save_to(inp_feat))
  163. output_shape = (7, 7)
  164. out_feat = F.nn.roi_align(
  165. inp_feat,
  166. rois,
  167. output_shape=output_shape,
  168. mode="average",
  169. spatial_scale=1.0 / 4,
  170. sample_points=2,
  171. aligned=True,
  172. )
  173. assert make_shape_tuple(out_feat.shape) == (
  174. rois.shape[0],
  175. inp_feat.shape[1],
  176. *output_shape,
  177. )
  178. grad(out_feat, tensor(F.ones_like(out_feat)))
  179. assert make_shape_tuple(inp_feat.grad.shape) == make_shape_tuple(inp_feat.shape)
  180. def test_roi_pooling():
  181. inp_feat, rois = _gen_roi_inp()
  182. grad = Grad().wrt(inp_feat, callback=_save_to(inp_feat))
  183. output_shape = (7, 7)
  184. out_feat = F.nn.roi_pooling(
  185. inp_feat, rois, output_shape=output_shape, mode="max", scale=1.0 / 4,
  186. )
  187. assert make_shape_tuple(out_feat.shape) == (
  188. rois.shape[0],
  189. inp_feat.shape[1],
  190. *output_shape,
  191. )
  192. grad(out_feat, tensor(F.ones_like(out_feat)))
  193. assert make_shape_tuple(inp_feat.grad.shape) == make_shape_tuple(inp_feat.shape)
  194. def test_adaptive_avg_pool2d():
  195. inp = tensor(np.arange(0, 16, dtype=np.float32).reshape(1, 1, 4, 4))
  196. oshp = (2, 2)
  197. grad = Grad().wrt(inp, callback=_save_to(inp))
  198. outp = F.adaptive_avg_pool2d(inp, oshp,)
  199. assert make_shape_tuple(outp.shape) == (inp.shape[0], inp.shape[1], *oshp,)
  200. np.testing.assert_equal(
  201. outp.numpy(), np.array([[[[2.5, 4.5], [10.5, 12.5]]]], dtype=np.float32)
  202. )
  203. grad(outp, tensor(F.ones_like(outp)))
  204. assert make_shape_tuple(inp.grad.shape) == make_shape_tuple(inp.shape)
  205. np.testing.assert_equal(
  206. inp.grad.numpy(),
  207. np.array(
  208. [
  209. [
  210. [
  211. [0.25, 0.25, 0.25, 0.25],
  212. [0.25, 0.25, 0.25, 0.25],
  213. [0.25, 0.25, 0.25, 0.25],
  214. [0.25, 0.25, 0.25, 0.25],
  215. ]
  216. ]
  217. ],
  218. dtype=np.float32,
  219. ),
  220. )
  221. def test_adaptive_max_pool2d():
  222. inp = tensor(np.arange(0, 16, dtype=np.float32).reshape(1, 1, 4, 4))
  223. oshp = (2, 2)
  224. grad = Grad().wrt(inp, callback=_save_to(inp))
  225. outp = F.adaptive_max_pool2d(inp, oshp,)
  226. assert make_shape_tuple(outp.shape) == (inp.shape[0], inp.shape[1], *oshp,)
  227. np.testing.assert_equal(
  228. outp.numpy(), np.array([[[[5, 7], [13, 15]]]], dtype=np.float32)
  229. )
  230. grad(outp, tensor(F.ones_like(outp)))
  231. assert make_shape_tuple(inp.grad.shape) == make_shape_tuple(inp.shape)
  232. np.testing.assert_equal(
  233. inp.grad.numpy(),
  234. np.array(
  235. [
  236. [
  237. [
  238. [0.0, 0.0, 0.0, 0.0],
  239. [0.0, 1.0, 0.0, 1.0],
  240. [0.0, 0.0, 0.0, 0.0],
  241. [0.0, 1.0, 0.0, 1.0],
  242. ]
  243. ]
  244. ],
  245. dtype=np.float32,
  246. ),
  247. )
  248. def test_one_hot():
  249. def onehot_low_dimension():
  250. inp = tensor(np.arange(1, 4, dtype=np.int32))
  251. out = F.one_hot(inp, num_classes=4)
  252. np.testing.assert_allclose(
  253. out.numpy(), np.eye(4, dtype=np.int32)[np.arange(1, 4, dtype=np.int32)]
  254. )
  255. def onehot_high_dimension():
  256. arr = np.array(
  257. [[3, 2, 4, 4, 2, 4, 0, 4, 4, 1], [4, 1, 1, 3, 2, 2, 4, 2, 4, 3]],
  258. dtype=np.int32,
  259. )
  260. inp = tensor(arr)
  261. out = F.one_hot(inp, 10)
  262. np.testing.assert_allclose(out.numpy(), np.eye(10, dtype=np.int32)[arr])
  263. onehot_low_dimension()
  264. onehot_high_dimension()
  265. def test_resize():
  266. # check shape
  267. test_cases = [
  268. [(1, 1, 10, 10), (5, 5)],
  269. [(1, 3, 10, 10), (20, 20)],
  270. [(10, 1, 10, 10), (1, 1)],
  271. [(10, 10, 1, 1), (10, 10)],
  272. ]
  273. for inp_shape, target_shape in test_cases:
  274. x = tensor(np.random.randn(*inp_shape), dtype=np.float32)
  275. out = F.resize(x, target_shape, interp_mode="LINEAR")
  276. assert out.shape[0] == x.shape[0] and out.shape[1] == x.shape[1]
  277. assert out.shape[2] == target_shape[0] and out.shape[3] == target_shape[1]
  278. # check value
  279. x = tensor(np.ones((3, 3, 10, 10)), dtype=np.float32)
  280. out = F.resize(x, (15, 5), interp_mode="LINEAR")
  281. np.testing.assert_equal(out.numpy(), np.ones((3, 3, 15, 5)).astype(np.float32))
  282. np_x = np.arange(32)
  283. x = tensor(np_x).astype(np.float32).reshape(1, 1, 32, 1)
  284. out = F.resize(x, (1, 1), interp_mode="LINEAR")
  285. np.testing.assert_equal(out.item(), np_x.mean())
  286. def test_warp_perspective():
  287. inp_shape = (1, 1, 4, 4)
  288. x = tensor(np.arange(16, dtype=np.float32).reshape(inp_shape))
  289. M_shape = (1, 3, 3)
  290. # M defines a translation: dst(1, 1, h, w) = rst(1, 1, h+1, w+1)
  291. M = tensor(
  292. np.array(
  293. [[1.0, 0.0, 1.0], [0.0, 1.0, 1.0], [0.0, 0.0, 1.0]], dtype=np.float32
  294. ).reshape(M_shape)
  295. )
  296. outp = F.warp_perspective(x, M, (2, 2))
  297. np.testing.assert_equal(
  298. outp.numpy(), np.array([[[[5.0, 6.0], [9.0, 10.0]]]], dtype=np.float32)
  299. )
  300. def test_remap():
  301. inp_shape = (1, 1, 4, 4)
  302. inp = tensor(np.arange(16, dtype=np.float32).reshape(inp_shape))
  303. map_xy_shape = (1, 2, 2, 2)
  304. map_xy = tensor(
  305. np.array(
  306. [[[1.0, 0.0], [0.0, 1.0]], [[0.0, 1.0], [0.0, 1.0]]], dtype=np.float32
  307. ).reshape(map_xy_shape)
  308. )
  309. outp = F.remap(inp, map_xy)
  310. np.testing.assert_equal(
  311. outp.numpy(), np.array([[[[1.0, 4.0], [4.0, 4.0]]]], dtype=np.float32)
  312. )
  313. def test_binary_cross_entropy():
  314. data1_shape = (2, 2)
  315. label1_shape = (2, 2)
  316. data2_shape = (2, 3)
  317. label2_shape = (2, 3)
  318. def sigmoid(x):
  319. return 1 / (1 + np.exp(-x))
  320. def compare_fn(x, y):
  321. np.testing.assert_allclose(x.numpy(), y, atol=5e-4)
  322. np.random.seed(123)
  323. data1 = np.random.uniform(size=data1_shape).astype(np.float32)
  324. label1 = np.random.uniform(size=label1_shape).astype(np.float32)
  325. expect1 = np.array([0.6361], dtype=np.float32)
  326. np.random.seed(123)
  327. data2 = np.random.uniform(size=data2_shape).astype(np.float32)
  328. label2 = np.random.uniform(size=label2_shape).astype(np.float32)
  329. expect2 = np.array([0.6750], dtype=np.float32)
  330. cases = [
  331. {"input": [data1, label1], "output": expect1,},
  332. {"input": [data2, label2], "output": expect2,},
  333. ]
  334. opr_test(cases, F.nn.binary_cross_entropy, compare_fn=compare_fn)
  335. cases = [
  336. {"input": [sigmoid(data1), label1], "output": expect1,},
  337. {"input": [sigmoid(data2), label2], "output": expect2,},
  338. ]
  339. opr_test(
  340. cases,
  341. partial(F.nn.binary_cross_entropy, with_logits=False),
  342. compare_fn=compare_fn,
  343. )
  344. def test_hinge_loss():
  345. np.random.seed(123)
  346. # case with L1 norm
  347. cases = []
  348. for shape in [(2, 2), (2, 3)]:
  349. data = np.random.uniform(size=shape).astype(np.float32)
  350. label = 2 * np.random.randint(0, 1, size=shape).astype(np.float32) - 1
  351. expect = np.clip(0, np.inf, 1 - data * label).sum(axis=1).mean()
  352. cases.append({"input": [data, label], "output": expect})
  353. opr_test(cases, F.nn.hinge_loss)
  354. # cases with L2 norm
  355. cases = []
  356. for shape in [(2, 2), (2, 3)]:
  357. data = np.random.uniform(size=shape).astype(np.float32)
  358. label = 2 * np.random.randint(0, 1, size=shape).astype(np.float32) - 1
  359. expect = ((np.clip(0, np.inf, 1 - data * label) ** 2).sum(axis=1)).mean()
  360. cases.append({"input": [data, label], "output": expect})
  361. def hinge_loss_with_l2_norm(pred, label):
  362. return F.nn.hinge_loss(pred, label, "L2")
  363. opr_test(cases, hinge_loss_with_l2_norm)
  364. def test_nms():
  365. x = np.array(
  366. [
  367. [0, 0, 100, 100],
  368. [10, 10, 100, 100],
  369. [50, 50, 100, 100],
  370. [100, 100, 150, 150],
  371. ],
  372. dtype=np.float32,
  373. )
  374. inp = tensor(x)
  375. scores = tensor([0.5, 0.8, 0.9, 0.6], dtype=np.float32)
  376. result = F.nn.nms(inp, scores=scores, iou_thresh=0.5)
  377. np.testing.assert_equal(result.numpy(), np.array([2, 1, 3], dtype=np.int32))
  378. @pytest.mark.skipif(
  379. get_device_count_by_fork("gpu") > 0, reason="cuda does not support nchw int8"
  380. )
  381. def test_conv_bias():
  382. inp_scale = 1.5
  383. w_scale = 2.5
  384. outp_scale = 1.5
  385. inp_dtype = dtype.qint8(inp_scale)
  386. w_dtype = dtype.qint8(w_scale)
  387. b_dtype = dtype.qint32(inp_scale * w_scale)
  388. out_dtype = dtype.qint8(outp_scale)
  389. def run(
  390. N,
  391. IC,
  392. OC,
  393. IH,
  394. IW,
  395. KH,
  396. KW,
  397. PH,
  398. PW,
  399. SH,
  400. SW,
  401. has_bias=True,
  402. nonlinear_mode="IDENTITY",
  403. ):
  404. inp_v = np.random.normal(size=(N, IC, IH, IW))
  405. w_v = np.random.normal(size=(OC, IC, KH, KW))
  406. b_v = np.random.normal(size=(1, OC, 1, 1))
  407. inp_scale = dtype.get_scale(inp_dtype)
  408. w_scale = dtype.get_scale(w_dtype)
  409. b_scale = dtype.get_scale(b_dtype)
  410. inpv = dtype.convert_to_qint8(inp_v * inp_scale, inp_dtype)
  411. wv = dtype.convert_to_qint8(w_v * w_scale, w_dtype)
  412. bv = dtype.convert_to_qint32(b_v * b_scale, b_dtype)
  413. inp_int8 = tensor(inpv, dtype=inp_dtype)
  414. w_int8 = Parameter(wv, dtype=w_dtype)
  415. b_int32 = Parameter(bv, dtype=b_dtype)
  416. inp_fp32 = inp_int8.astype("float32")
  417. w_fp32 = w_int8.astype("float32")
  418. b_fp32 = b_int32.astype("float32")
  419. def convert_to_nchw4(var):
  420. var = F.reshape(
  421. var, (var.shape[0], var.shape[1] // 4, 4, var.shape[2], var.shape[3])
  422. )
  423. var = F.transpose(var, (0, 1, 3, 4, 2))
  424. return var
  425. def run_conv2d(inp, w, b):
  426. O = F.conv2d(
  427. inp, w, b if has_bias else None, stride=(SH, SW), padding=(PH, PW),
  428. )
  429. if nonlinear_mode == "RELU":
  430. return F.relu(O)
  431. else:
  432. return O
  433. def run_conv_bias(inp, w, b, format="NCHW"):
  434. b = b if has_bias else Parameter(np.zeros_like(b.numpy()))
  435. if format == "NCHW4":
  436. inp = convert_to_nchw4(inp)
  437. w = convert_to_nchw4(w)
  438. b = convert_to_nchw4(b)
  439. return F.quantized.conv_bias_activation(
  440. inp,
  441. w,
  442. b,
  443. stride=(SH, SW),
  444. padding=(PH, PW),
  445. dtype=out_dtype,
  446. nonlinear_mode=nonlinear_mode,
  447. )
  448. format = "NCHW4" if is_cuda_available() else "NCHW"
  449. expected = run_conv2d(inp_fp32, w_fp32, b_fp32)
  450. expected = expected.astype(out_dtype).astype("float32")
  451. result = run_conv_bias(inp_int8, w_int8, b_int32, format=format).astype(
  452. "float32"
  453. )
  454. if format == "NCHW4":
  455. result = F.transpose(result, (0, 1, 4, 2, 3))
  456. expected = F.flatten(expected)
  457. result = F.flatten(result)
  458. np.testing.assert_allclose(result.numpy(), expected.numpy(), atol=outp_scale)
  459. run(1, 4, 4, 24, 33, 1, 1, 2, 3, 1, 1, False)
  460. run(10, 12, 24, 46, 46, 1, 1, 2, 1, 3, 1, False)
  461. run(10, 36, 8, 46, 26, 2, 2, 2, 1, 1, 2, False)
  462. run(1, 4, 4, 24, 33, 1, 1, 2, 3, 1, 1)
  463. run(10, 12, 24, 46, 46, 1, 1, 2, 1, 3, 1)
  464. run(10, 36, 8, 46, 26, 2, 2, 2, 1, 1, 2)
  465. run(10, 36, 8, 46, 26, 2, 2, 2, 1, 1, 2, False, "RELU")
  466. run(10, 36, 8, 46, 26, 2, 2, 2, 1, 1, 2, True, "RELU")
  467. @pytest.mark.skipif(
  468. get_device_count_by_fork("gpu") > 0, reason="no int8 algorithm on cuda"
  469. )
  470. def test_batch_conv_bias():
  471. inp_scale = 1.5
  472. w_scale = 2.5
  473. outp_scale = 1.5
  474. inp_dtype = dtype.qint8(inp_scale)
  475. w_dtype = dtype.qint8(w_scale)
  476. b_dtype = dtype.qint32(inp_scale * w_scale)
  477. out_dtype = dtype.qint8(outp_scale)
  478. def run(
  479. N, IC, OC, IH, IW, KH, KW, PH, PW, SH, SW, has_bias=True,
  480. ):
  481. inp_v = np.random.normal(size=(N, IC, IH, IW))
  482. w_v = np.random.normal(size=(N, OC, IC, KH, KW))
  483. b_v = np.random.normal(size=(1, OC, 1, 1))
  484. inp_scale = dtype.get_scale(inp_dtype)
  485. w_scale = dtype.get_scale(w_dtype)
  486. b_scale = dtype.get_scale(b_dtype)
  487. inpv = dtype.convert_to_qint8(inp_v * inp_scale, inp_dtype)
  488. wv = dtype.convert_to_qint8(w_v * w_scale, w_dtype)
  489. bv = dtype.convert_to_qint32(b_v * b_scale, b_dtype)
  490. inp_int8 = tensor(inpv, dtype=inp_dtype)
  491. w_int8 = Parameter(wv, dtype=w_dtype)
  492. b_int32 = Parameter(bv, dtype=b_dtype)
  493. inp_fp32 = inp_int8.astype("float32")
  494. w_fp32 = w_int8.astype("float32")
  495. b_fp32 = b_int32.astype("float32")
  496. def run_batch_conv_bias(inp, w, b):
  497. b = b if has_bias else Parameter(np.zeros_like(b.numpy()))
  498. result = F.quantized.batch_conv_bias_activation(
  499. inp, w, b, stride=(SH, SW), padding=(PH, PW), dtype=out_dtype,
  500. )
  501. return result.astype("float32")
  502. expected = F.conv2d(inp_fp32, w_fp32[0], b_fp32 if has_bias else None)[0]
  503. expected = expected.astype(out_dtype).astype("float32")
  504. expected = F.flatten(expected)
  505. result = run_batch_conv_bias(inp_int8, w_int8, b_int32)
  506. result = F.flatten(result)
  507. np.testing.assert_allclose(result.numpy(), expected.numpy(), atol=outp_scale)
  508. run(1, 4, 4, 5, 5, 3, 3, 0, 0, 1, 1, True)
  509. def test_zero_stride_numpy_array():
  510. inp = np.random.randn(3, 224, 224).astype(np.float32)
  511. inp = inp[np.newaxis, :]
  512. inp = tensor(inp, dtype=np.float32)
  513. weight = tensor(np.random.randn(16, 3, 3, 3), dtype=np.float32)
  514. out = F.conv2d(inp, weight, None, (2, 2), (3, 3), (1, 1), 1)
  515. def test_conv1d():
  516. inp = tensor(np.ones((16,), dtype=np.float32).reshape(2, 2, 4))
  517. weight = tensor(np.ones((12,), dtype=np.float32).reshape(3, 2, 2))
  518. out = F.conv1d(inp, weight, None, 2, 0, 1, 1)
  519. np.testing.assert_equal(
  520. out.numpy(),
  521. np.array(
  522. [[[4, 4], [4, 4], [4, 4]], [[4, 4], [4, 4], [4, 4]]], dtype=np.float32
  523. ),
  524. )
  525. def test_condtake():
  526. x = np.array([[1, 2, 3], [4, 5, 6]])
  527. y = np.array([[True, False, True], [False, True, True]])
  528. xx = tensor(x)
  529. yy = tensor(y)
  530. val, idx = F.cond_take(yy, xx)
  531. np.testing.assert_equal(val.numpy(), x[y])
  532. np.testing.assert_equal(idx.numpy(), np.where(y.reshape(-1))[0])
  533. def test_condtake_is_same():
  534. op1 = builtin.CondTake()
  535. op2 = builtin.CondTake()
  536. assert op1 == op2
  537. def test_nms_is_same():
  538. op1 = builtin.NMSKeep(0.7, 100)
  539. op2 = builtin.NMSKeep(0.7, 100)
  540. op3 = builtin.NMSKeep(0.8, 100)
  541. op4 = builtin.NMSKeep(0.7, 200)
  542. assert op1 == op2
  543. assert op1 != op3
  544. assert op1 != op4
  545. assert op3 != op4
  546. def test_argmxx_on_inf():
  547. def run_argmax():
  548. x = F.zeros((100, 100))
  549. x[:] = -float("inf")
  550. idxs = F.argmax(x, axis=0)
  551. return idxs
  552. def run_argmin():
  553. x = F.zeros((100, 100))
  554. x[:] = float("inf")
  555. idxs = F.argmin(x, axis=0)
  556. return idxs
  557. assert all(run_argmax() >= 0)
  558. assert all(run_argmin() >= 0)

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