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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2021 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, test_trace=False)
  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, test_trace=False)
  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. # FIXME: remove test_trace=False in the future
  98. opr_test(
  99. cases, F.matmul, test_trace=False, ref_fn=np.matmul,
  100. )
  101. # FIXME: remove test_trace=False in the future
  102. opr_test(
  103. [{"input": [data1, data4]}],
  104. F.matmul,
  105. ref_fn=lambda x, y: np.matmul(x, y.transpose(0, 1, 3, 2)),
  106. test_trace=False,
  107. transpose_b=True,
  108. )
  109. opr_test(
  110. [{"input": [data3, data2]}],
  111. F.matmul,
  112. ref_fn=lambda x, y: np.matmul(x.transpose(0, 2, 1), y.transpose(0, 2, 1)),
  113. transpose_a=True,
  114. transpose_b=True,
  115. )
  116. def test_interpolate():
  117. def linear_interpolate():
  118. inp = tensor(np.arange(1, 3, dtype=np.float32).reshape(1, 1, 2))
  119. out = F.nn.interpolate(inp, scale_factor=2.0, mode="LINEAR")
  120. out2 = F.nn.interpolate(inp, 4, mode="LINEAR")
  121. np.testing.assert_allclose(
  122. out.numpy(), np.array([[[1.0, 1.25, 1.75, 2.0]]], dtype=np.float32)
  123. )
  124. np.testing.assert_allclose(
  125. out2.numpy(), np.array([[[1.0, 1.25, 1.75, 2.0]]], dtype=np.float32)
  126. )
  127. def many_batch_interpolate():
  128. inp = tensor(np.arange(1, 9, dtype=np.float32).reshape(2, 1, 2, 2))
  129. out = F.nn.interpolate(inp, [4, 4])
  130. out2 = F.nn.interpolate(inp, scale_factor=2.0)
  131. np.testing.assert_allclose(out.numpy(), out2.numpy())
  132. def assign_corner_interpolate():
  133. inp = tensor(np.arange(1, 5, dtype=np.float32).reshape(1, 1, 2, 2))
  134. out = F.nn.interpolate(inp, [4, 4], align_corners=True)
  135. out2 = F.nn.interpolate(inp, scale_factor=2.0, align_corners=True)
  136. np.testing.assert_allclose(out.numpy(), out2.numpy())
  137. def error_shape_linear_interpolate():
  138. inp = tensor(np.arange(1, 5, dtype=np.float32).reshape(1, 1, 2, 2))
  139. with pytest.raises(ValueError):
  140. F.nn.interpolate(inp, scale_factor=2.0, mode="LINEAR")
  141. def inappropriate_scale_linear_interpolate():
  142. inp = tensor(np.arange(1, 3, dtype=np.float32).reshape(1, 1, 2))
  143. with pytest.raises(ValueError):
  144. F.nn.interpolate(inp, scale_factor=[2.0, 3.0], mode="LINEAR")
  145. linear_interpolate()
  146. many_batch_interpolate()
  147. assign_corner_interpolate()
  148. error_shape_linear_interpolate()
  149. inappropriate_scale_linear_interpolate()
  150. def _save_to(self, name="grad"):
  151. def callback(grad):
  152. setattr(self, name, grad)
  153. return callback
  154. def _gen_roi_inp():
  155. inp_feat = np.random.randn(2, 32, 256, 256)
  156. rois = np.zeros((4, 5))
  157. rois[:, 0] = [0, 0, 1, 1]
  158. rois[:, 1:3] = np.random.rand(4, 2) * 100
  159. rois[:, 3:] = np.random.rand(4, 2) * 100 + 150
  160. inp_feat = tensor(inp_feat)
  161. rois = tensor(rois)
  162. return inp_feat, rois
  163. def test_roi_align():
  164. inp_feat, rois = _gen_roi_inp()
  165. grad = Grad().wrt(inp_feat, callback=_save_to(inp_feat))
  166. output_shape = (7, 7)
  167. out_feat = F.nn.roi_align(
  168. inp_feat,
  169. rois,
  170. output_shape=output_shape,
  171. mode="average",
  172. spatial_scale=1.0 / 4,
  173. sample_points=2,
  174. aligned=True,
  175. )
  176. assert make_shape_tuple(out_feat.shape) == (
  177. rois.shape[0],
  178. inp_feat.shape[1],
  179. *output_shape,
  180. )
  181. grad(out_feat, tensor(F.ones_like(out_feat)))
  182. assert make_shape_tuple(inp_feat.grad.shape) == make_shape_tuple(inp_feat.shape)
  183. def test_roi_pooling():
  184. inp_feat, rois = _gen_roi_inp()
  185. grad = Grad().wrt(inp_feat, callback=_save_to(inp_feat))
  186. output_shape = (7, 7)
  187. out_feat = F.nn.roi_pooling(
  188. inp_feat, rois, output_shape=output_shape, mode="max", scale=1.0 / 4,
  189. )
  190. assert make_shape_tuple(out_feat.shape) == (
  191. rois.shape[0],
  192. inp_feat.shape[1],
  193. *output_shape,
  194. )
  195. grad(out_feat, tensor(F.ones_like(out_feat)))
  196. assert make_shape_tuple(inp_feat.grad.shape) == make_shape_tuple(inp_feat.shape)
  197. def test_adaptive_avg_pool2d():
  198. inp = tensor(np.arange(0, 16, dtype=np.float32).reshape(1, 1, 4, 4))
  199. oshp = (2, 2)
  200. grad = Grad().wrt(inp, callback=_save_to(inp))
  201. outp = F.adaptive_avg_pool2d(inp, oshp,)
  202. assert make_shape_tuple(outp.shape) == (inp.shape[0], inp.shape[1], *oshp,)
  203. np.testing.assert_equal(
  204. outp.numpy(), np.array([[[[2.5, 4.5], [10.5, 12.5]]]], dtype=np.float32)
  205. )
  206. grad(outp, tensor(F.ones_like(outp)))
  207. assert make_shape_tuple(inp.grad.shape) == make_shape_tuple(inp.shape)
  208. np.testing.assert_equal(
  209. inp.grad.numpy(),
  210. np.array(
  211. [
  212. [
  213. [
  214. [0.25, 0.25, 0.25, 0.25],
  215. [0.25, 0.25, 0.25, 0.25],
  216. [0.25, 0.25, 0.25, 0.25],
  217. [0.25, 0.25, 0.25, 0.25],
  218. ]
  219. ]
  220. ],
  221. dtype=np.float32,
  222. ),
  223. )
  224. def test_adaptive_max_pool2d():
  225. inp = tensor(np.arange(0, 16, dtype=np.float32).reshape(1, 1, 4, 4))
  226. oshp = (2, 2)
  227. grad = Grad().wrt(inp, callback=_save_to(inp))
  228. outp = F.adaptive_max_pool2d(inp, oshp,)
  229. assert make_shape_tuple(outp.shape) == (inp.shape[0], inp.shape[1], *oshp,)
  230. np.testing.assert_equal(
  231. outp.numpy(), np.array([[[[5, 7], [13, 15]]]], dtype=np.float32)
  232. )
  233. grad(outp, tensor(F.ones_like(outp)))
  234. assert make_shape_tuple(inp.grad.shape) == make_shape_tuple(inp.shape)
  235. np.testing.assert_equal(
  236. inp.grad.numpy(),
  237. np.array(
  238. [
  239. [
  240. [
  241. [0.0, 0.0, 0.0, 0.0],
  242. [0.0, 1.0, 0.0, 1.0],
  243. [0.0, 0.0, 0.0, 0.0],
  244. [0.0, 1.0, 0.0, 1.0],
  245. ]
  246. ]
  247. ],
  248. dtype=np.float32,
  249. ),
  250. )
  251. def test_one_hot():
  252. def onehot_low_dimension():
  253. inp = tensor(np.arange(1, 4, dtype=np.int32))
  254. out = F.one_hot(inp, num_classes=4)
  255. np.testing.assert_allclose(
  256. out.numpy(), np.eye(4, dtype=np.int32)[np.arange(1, 4, dtype=np.int32)]
  257. )
  258. def onehot_high_dimension():
  259. arr = np.array(
  260. [[3, 2, 4, 4, 2, 4, 0, 4, 4, 1], [4, 1, 1, 3, 2, 2, 4, 2, 4, 3]],
  261. dtype=np.int32,
  262. )
  263. inp = tensor(arr)
  264. out = F.one_hot(inp, 10)
  265. np.testing.assert_allclose(out.numpy(), np.eye(10, dtype=np.int32)[arr])
  266. onehot_low_dimension()
  267. onehot_high_dimension()
  268. def test_resize():
  269. # check shape
  270. test_cases = [
  271. [(1, 1, 10, 10), (5, 5)],
  272. [(1, 3, 10, 10), (20, 20)],
  273. [(10, 1, 10, 10), (1, 1)],
  274. [(10, 10, 1, 1), (10, 10)],
  275. ]
  276. for inp_shape, target_shape in test_cases:
  277. x = tensor(np.random.randn(*inp_shape), dtype=np.float32)
  278. out = F.resize(x, target_shape, interp_mode="LINEAR")
  279. assert out.shape[0] == x.shape[0] and out.shape[1] == x.shape[1]
  280. assert out.shape[2] == target_shape[0] and out.shape[3] == target_shape[1]
  281. # check value
  282. x = tensor(np.ones((3, 3, 10, 10)), dtype=np.float32)
  283. out = F.resize(x, (15, 5), interp_mode="LINEAR")
  284. np.testing.assert_equal(out.numpy(), np.ones((3, 3, 15, 5)).astype(np.float32))
  285. np_x = np.arange(32)
  286. x = tensor(np_x).astype(np.float32).reshape(1, 1, 32, 1)
  287. out = F.resize(x, (1, 1), interp_mode="LINEAR")
  288. np.testing.assert_equal(out.item(), np_x.mean())
  289. def test_warp_perspective():
  290. inp_shape = (1, 1, 4, 4)
  291. x = tensor(np.arange(16, dtype=np.float32).reshape(inp_shape))
  292. M_shape = (1, 3, 3)
  293. # M defines a translation: dst(1, 1, h, w) = rst(1, 1, h+1, w+1)
  294. M = tensor(
  295. np.array(
  296. [[1.0, 0.0, 1.0], [0.0, 1.0, 1.0], [0.0, 0.0, 1.0]], dtype=np.float32
  297. ).reshape(M_shape)
  298. )
  299. outp = F.warp_perspective(x, M, (2, 2))
  300. np.testing.assert_equal(
  301. outp.numpy(), np.array([[[[5.0, 6.0], [9.0, 10.0]]]], dtype=np.float32)
  302. )
  303. def test_warp_affine():
  304. inp_shape = (1, 3, 3, 3)
  305. x = tensor(np.arange(27, dtype=np.float32).reshape(inp_shape))
  306. weightv = [[[1.26666667, 0.6, -83.33333333], [-0.33333333, 1, 66.66666667]]]
  307. outp = F.warp_affine(x, tensor(weightv), (2, 2), border_mode="WRAP")
  308. res = np.array(
  309. [
  310. [
  311. [[7.875, 8.875, 9.875], [8.90625, 9.90625, 10.90625]],
  312. [[18.75, 19.75, 20.75], [14.90625, 15.90625, 16.90625]],
  313. ]
  314. ],
  315. dtype=np.float32,
  316. )
  317. if not is_cuda_available():
  318. np.testing.assert_almost_equal(outp.numpy(), res, 5)
  319. def test_remap():
  320. inp_shape = (1, 1, 4, 4)
  321. inp = tensor(np.arange(16, dtype=np.float32).reshape(inp_shape))
  322. map_xy_shape = (1, 2, 2, 2)
  323. map_xy = tensor(
  324. np.array(
  325. [[[1.0, 0.0], [0.0, 1.0]], [[0.0, 1.0], [0.0, 1.0]]], dtype=np.float32
  326. ).reshape(map_xy_shape)
  327. )
  328. outp = F.remap(inp, map_xy)
  329. np.testing.assert_equal(
  330. outp.numpy(), np.array([[[[1.0, 4.0], [4.0, 4.0]]]], dtype=np.float32)
  331. )
  332. def test_binary_cross_entropy():
  333. data1_shape = (2, 2)
  334. label1_shape = (2, 2)
  335. data2_shape = (2, 3)
  336. label2_shape = (2, 3)
  337. def sigmoid(x):
  338. return 1 / (1 + np.exp(-x))
  339. def compare_fn(x, y):
  340. np.testing.assert_allclose(x.numpy(), y, atol=5e-4)
  341. np.random.seed(123)
  342. data1 = np.random.uniform(size=data1_shape).astype(np.float32)
  343. label1 = np.random.uniform(size=label1_shape).astype(np.float32)
  344. expect1 = np.array([0.6361], dtype=np.float32)
  345. np.random.seed(123)
  346. data2 = np.random.uniform(size=data2_shape).astype(np.float32)
  347. label2 = np.random.uniform(size=label2_shape).astype(np.float32)
  348. expect2 = np.array([0.6750], dtype=np.float32)
  349. cases = [
  350. {"input": [data1, label1], "output": expect1,},
  351. {"input": [data2, label2], "output": expect2,},
  352. ]
  353. opr_test(cases, F.nn.binary_cross_entropy, compare_fn=compare_fn)
  354. cases = [
  355. {"input": [sigmoid(data1), label1], "output": expect1,},
  356. {"input": [sigmoid(data2), label2], "output": expect2,},
  357. ]
  358. opr_test(
  359. cases,
  360. partial(F.nn.binary_cross_entropy, with_logits=False),
  361. compare_fn=compare_fn,
  362. )
  363. def test_hinge_loss():
  364. np.random.seed(123)
  365. # case with L1 norm
  366. cases = []
  367. for shape in [(2, 2), (2, 3)]:
  368. data = np.random.uniform(size=shape).astype(np.float32)
  369. label = 2 * np.random.randint(0, 1, size=shape).astype(np.float32) - 1
  370. expect = np.clip(0, np.inf, 1 - data * label).sum(axis=1).mean()
  371. cases.append({"input": [data, label], "output": expect})
  372. opr_test(cases, F.nn.hinge_loss)
  373. # cases with L2 norm
  374. cases = []
  375. for shape in [(2, 2), (2, 3)]:
  376. data = np.random.uniform(size=shape).astype(np.float32)
  377. label = 2 * np.random.randint(0, 1, size=shape).astype(np.float32) - 1
  378. expect = ((np.clip(0, np.inf, 1 - data * label) ** 2).sum(axis=1)).mean()
  379. cases.append({"input": [data, label], "output": expect})
  380. def hinge_loss_with_l2_norm(pred, label):
  381. return F.nn.hinge_loss(pred, label, "L2")
  382. opr_test(cases, hinge_loss_with_l2_norm)
  383. def test_nms():
  384. x = np.array(
  385. [
  386. [0, 0, 100, 100],
  387. [10, 10, 100, 100],
  388. [50, 50, 100, 100],
  389. [100, 100, 150, 150],
  390. ],
  391. dtype=np.float32,
  392. )
  393. inp = tensor(x)
  394. scores = tensor([0.5, 0.8, 0.9, 0.6], dtype=np.float32)
  395. result = F.nn.nms(inp, scores=scores, iou_thresh=0.5)
  396. np.testing.assert_equal(result.numpy(), np.array([2, 1, 3], dtype=np.int32))
  397. @pytest.mark.skipif(
  398. get_device_count_by_fork("gpu") > 0, reason="cuda does not support nchw int8"
  399. )
  400. def test_conv_bias():
  401. inp_scale = 1.5
  402. w_scale = 2.5
  403. outp_scale = 1.5
  404. inp_dtype = dtype.qint8(inp_scale)
  405. w_dtype = dtype.qint8(w_scale)
  406. b_dtype = dtype.qint32(inp_scale * w_scale)
  407. out_dtype = dtype.qint8(outp_scale)
  408. def run(
  409. N,
  410. IC,
  411. OC,
  412. IH,
  413. IW,
  414. KH,
  415. KW,
  416. PH,
  417. PW,
  418. SH,
  419. SW,
  420. has_bias=True,
  421. nonlinear_mode="IDENTITY",
  422. ):
  423. inp_v = np.random.normal(size=(N, IC, IH, IW))
  424. w_v = np.random.normal(size=(OC, IC, KH, KW))
  425. b_v = np.random.normal(size=(1, OC, 1, 1))
  426. inp_scale = dtype.get_scale(inp_dtype)
  427. w_scale = dtype.get_scale(w_dtype)
  428. b_scale = dtype.get_scale(b_dtype)
  429. inpv = dtype.convert_to_qint8(inp_v * inp_scale, inp_dtype)
  430. wv = dtype.convert_to_qint8(w_v * w_scale, w_dtype)
  431. bv = dtype.convert_to_qint32(b_v * b_scale, b_dtype)
  432. inp_int8 = tensor(inpv, dtype=inp_dtype)
  433. w_int8 = Parameter(wv, dtype=w_dtype)
  434. b_int32 = Parameter(bv, dtype=b_dtype)
  435. inp_fp32 = inp_int8.astype("float32")
  436. w_fp32 = w_int8.astype("float32")
  437. b_fp32 = b_int32.astype("float32")
  438. def convert_to_nchw4(var):
  439. var = F.reshape(
  440. var, (var.shape[0], var.shape[1] // 4, 4, var.shape[2], var.shape[3])
  441. )
  442. var = F.transpose(var, (0, 1, 3, 4, 2))
  443. return var
  444. def run_conv2d(inp, w, b):
  445. O = F.conv2d(
  446. inp, w, b if has_bias else None, stride=(SH, SW), padding=(PH, PW),
  447. )
  448. if nonlinear_mode == "RELU":
  449. return F.relu(O)
  450. else:
  451. return O
  452. def run_conv_bias(inp, w, b, format="NCHW"):
  453. b = b if has_bias else Parameter(np.zeros_like(b.numpy()))
  454. if format == "NCHW4":
  455. inp = convert_to_nchw4(inp)
  456. w = convert_to_nchw4(w)
  457. b = convert_to_nchw4(b)
  458. return F.quantized.conv_bias_activation(
  459. inp,
  460. w,
  461. b,
  462. stride=(SH, SW),
  463. padding=(PH, PW),
  464. dtype=out_dtype,
  465. nonlinear_mode=nonlinear_mode,
  466. )
  467. format = "NCHW4" if is_cuda_available() else "NCHW"
  468. expected = run_conv2d(inp_fp32, w_fp32, b_fp32)
  469. expected = expected.astype(out_dtype).astype("float32")
  470. result = run_conv_bias(inp_int8, w_int8, b_int32, format=format).astype(
  471. "float32"
  472. )
  473. if format == "NCHW4":
  474. result = F.transpose(result, (0, 1, 4, 2, 3))
  475. expected = F.flatten(expected)
  476. result = F.flatten(result)
  477. np.testing.assert_allclose(result.numpy(), expected.numpy(), atol=outp_scale)
  478. run(1, 4, 4, 24, 33, 1, 1, 2, 3, 1, 1, False)
  479. run(10, 12, 24, 46, 46, 1, 1, 2, 1, 3, 1, False)
  480. run(10, 36, 8, 46, 26, 2, 2, 2, 1, 1, 2, False)
  481. run(1, 4, 4, 24, 33, 1, 1, 2, 3, 1, 1)
  482. run(10, 12, 24, 46, 46, 1, 1, 2, 1, 3, 1)
  483. run(10, 36, 8, 46, 26, 2, 2, 2, 1, 1, 2)
  484. run(10, 36, 8, 46, 26, 2, 2, 2, 1, 1, 2, False, "RELU")
  485. run(10, 36, 8, 46, 26, 2, 2, 2, 1, 1, 2, True, "RELU")
  486. @pytest.mark.skipif(
  487. get_device_count_by_fork("gpu") > 0, reason="no int8 algorithm on cuda"
  488. )
  489. def test_batch_conv_bias():
  490. inp_scale = 1.5
  491. w_scale = 2.5
  492. outp_scale = 1.5
  493. inp_dtype = dtype.qint8(inp_scale)
  494. w_dtype = dtype.qint8(w_scale)
  495. b_dtype = dtype.qint32(inp_scale * w_scale)
  496. out_dtype = dtype.qint8(outp_scale)
  497. def run(
  498. N, IC, OC, IH, IW, KH, KW, PH, PW, SH, SW, has_bias=True,
  499. ):
  500. inp_v = np.random.normal(size=(N, IC, IH, IW))
  501. w_v = np.random.normal(size=(N, OC, IC, KH, KW))
  502. b_v = np.random.normal(size=(1, OC, 1, 1))
  503. inp_scale = dtype.get_scale(inp_dtype)
  504. w_scale = dtype.get_scale(w_dtype)
  505. b_scale = dtype.get_scale(b_dtype)
  506. inpv = dtype.convert_to_qint8(inp_v * inp_scale, inp_dtype)
  507. wv = dtype.convert_to_qint8(w_v * w_scale, w_dtype)
  508. bv = dtype.convert_to_qint32(b_v * b_scale, b_dtype)
  509. inp_int8 = tensor(inpv, dtype=inp_dtype)
  510. w_int8 = Parameter(wv, dtype=w_dtype)
  511. b_int32 = Parameter(bv, dtype=b_dtype)
  512. inp_fp32 = inp_int8.astype("float32")
  513. w_fp32 = w_int8.astype("float32")
  514. b_fp32 = b_int32.astype("float32")
  515. def run_batch_conv_bias(inp, w, b):
  516. b = b if has_bias else Parameter(np.zeros_like(b.numpy()))
  517. result = F.quantized.batch_conv_bias_activation(
  518. inp, w, b, stride=(SH, SW), padding=(PH, PW), dtype=out_dtype,
  519. )
  520. return result.astype("float32")
  521. expected = F.conv2d(inp_fp32, w_fp32[0], b_fp32 if has_bias else None)[0]
  522. expected = expected.astype(out_dtype).astype("float32")
  523. expected = F.flatten(expected)
  524. result = run_batch_conv_bias(inp_int8, w_int8, b_int32)
  525. result = F.flatten(result)
  526. np.testing.assert_allclose(result.numpy(), expected.numpy(), atol=outp_scale)
  527. run(1, 4, 4, 5, 5, 3, 3, 0, 0, 1, 1, True)
  528. def test_zero_stride_numpy_array():
  529. inp = np.random.randn(3, 224, 224).astype(np.float32)
  530. inp = inp[np.newaxis, :]
  531. inp = tensor(inp, dtype=np.float32)
  532. weight = tensor(np.random.randn(16, 3, 3, 3), dtype=np.float32)
  533. out = F.conv2d(inp, weight, None, (2, 2), (3, 3), (1, 1), 1)
  534. def test_conv1d():
  535. inp = tensor(np.ones((16,), dtype=np.float32).reshape(2, 2, 4))
  536. weight = tensor(np.ones((12,), dtype=np.float32).reshape(3, 2, 2))
  537. out = F.conv1d(inp, weight, None, 2, 0, 1, 1)
  538. np.testing.assert_equal(
  539. out.numpy(),
  540. np.array(
  541. [[[4, 4], [4, 4], [4, 4]], [[4, 4], [4, 4], [4, 4]]], dtype=np.float32
  542. ),
  543. )
  544. def test_condtake():
  545. x = np.array([[1, 2, 3], [4, 5, 6]])
  546. y = np.array([[True, False, True], [False, True, True]])
  547. xx = tensor(x)
  548. yy = tensor(y)
  549. val, idx = F.cond_take(yy, xx)
  550. np.testing.assert_equal(val.numpy(), x[y])
  551. np.testing.assert_equal(idx.numpy(), np.where(y.reshape(-1))[0])
  552. def test_condtake_is_same():
  553. op1 = builtin.CondTake()
  554. op2 = builtin.CondTake()
  555. assert op1 == op2
  556. def test_nms_is_same():
  557. op1 = builtin.NMSKeep(0.7, 100)
  558. op2 = builtin.NMSKeep(0.7, 100)
  559. op3 = builtin.NMSKeep(0.8, 100)
  560. op4 = builtin.NMSKeep(0.7, 200)
  561. assert op1 == op2
  562. assert op1 != op3
  563. assert op1 != op4
  564. assert op3 != op4
  565. def test_argmxx_on_inf():
  566. def run_argmax():
  567. x = F.zeros((100, 100))
  568. x[:] = -float("inf")
  569. idxs = F.argmax(x, axis=0)
  570. return idxs
  571. def run_argmin():
  572. x = F.zeros((100, 100))
  573. x[:] = float("inf")
  574. idxs = F.argmin(x, axis=0)
  575. return idxs
  576. assert all(run_argmax() >= 0)
  577. assert all(run_argmin() >= 0)
  578. def test_cvt_color():
  579. def rgb2gray(rgb):
  580. return np.dot(rgb[..., :3], [0.299, 0.587, 0.114])
  581. inp = np.random.randn(3, 3, 3, 3).astype(np.float32)
  582. out = np.expand_dims(rgb2gray(inp), 3).astype(np.float32)
  583. x = tensor(inp)
  584. y = F.img_proc.cvt_color(x, mode="RGB2GRAY")
  585. np.testing.assert_allclose(y.numpy(), out, atol=1e-5)

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