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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032
  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. import platform
  11. from functools import partial
  12. import numpy as np
  13. import pytest
  14. from utils import opr_test
  15. import megengine.amp as amp
  16. import megengine.core.ops.builtin as builtin
  17. import megengine.core.tensor.dtype as dtype
  18. import megengine.functional as F
  19. from megengine import Parameter, Tensor, is_cuda_available, tensor
  20. from megengine.core._trace_option import use_symbolic_shape
  21. from megengine.core.autodiff.grad import Grad
  22. from megengine.core.tensor.utils import make_shape_tuple
  23. from megengine.device import get_device_count
  24. def test_where():
  25. maskv0 = np.array([[1, 0], [0, 1]], dtype=np.bool_)
  26. xv0 = np.array([[1, np.inf], [np.nan, 4]], dtype=np.float32)
  27. yv0 = np.array([[5, 6], [7, 8]], dtype=np.float32)
  28. maskv1 = np.array([[1, 0, 1], [1, 0, 0], [1, 1, 0]], dtype=np.bool_)
  29. xv1 = np.array([[1, np.inf, 2], [0, np.nan, 4], [1, 5, 7]], dtype=np.float32)
  30. yv1 = np.array([[5, 6, 9], [2, 7, 8], [2, 1, 9]], dtype=np.float32)
  31. cases = [
  32. {"input": [maskv0, xv0, yv0]},
  33. {"input": [maskv1, xv1, yv1]},
  34. ]
  35. opr_test(cases, F.where, ref_fn=np.where, test_trace=False)
  36. maskv2 = np.array([1, 1, 1], dtype=np.bool_)
  37. xv2 = np.array([1, 3, 2], dtype=np.float32)
  38. yv2 = np.array([5, 6, 9], dtype=np.float32)
  39. maskv3 = np.array([0, 0, 0], dtype=np.bool_)
  40. xv3 = np.array([1, 3, 2], dtype=np.float32)
  41. yv3 = np.array([5, 6, 9], dtype=np.float32)
  42. cases = [
  43. {"input": [maskv2, xv2, yv2]},
  44. {"input": [maskv3, xv3, yv3]},
  45. ]
  46. opr_test(cases, F.where, ref_fn=np.where, test_trace=False)
  47. def test_dropout():
  48. data = tensor(np.ones(10, dtype=np.float32))
  49. out = F.dropout(data, 1.0 / 3.0, training=False)
  50. assert out.numpy().sum() >= 0.0
  51. def test_matinv():
  52. shape1 = (5, 5)
  53. shape2 = (3, 9, 9)
  54. data1 = np.random.random(shape1).astype("float32")
  55. data2 = np.random.random(shape2).astype("float32")
  56. # make matrix diagonally dominant for numerical stability
  57. data1 += (np.eye(shape1[0]) * shape1[0]).astype("float32")
  58. data2 += np.broadcast_to((np.eye(shape2[1]) * shape2[1]).astype("float32"), shape2)
  59. cases = [
  60. {"input": data1},
  61. {"input": data2},
  62. ]
  63. opr_test(
  64. cases,
  65. F.matinv,
  66. compare_fn=lambda x, y: np.testing.assert_allclose(x.numpy(), y, rtol=1e-4),
  67. ref_fn=np.linalg.inv,
  68. )
  69. def test_matmul():
  70. shape1 = 3
  71. shape2 = 3
  72. shape3 = (3, 5)
  73. shape4 = (5, 6)
  74. data1 = np.random.random(shape1).astype("float32")
  75. data2 = np.random.random(shape2).astype("float32")
  76. data3 = np.random.random(shape3).astype("float32")
  77. data4 = np.random.random(shape4).astype("float32")
  78. cases = [
  79. {"input": [data1, data2]},
  80. {"input": [data2, data3]},
  81. {"input": [data3, data4]},
  82. ]
  83. opr_test(cases, F.matmul, ref_fn=np.matmul)
  84. batch_size = 10
  85. shape1 = (2,)
  86. shape2 = (batch_size, 2, 3)
  87. shape3 = (batch_size, 3, 4)
  88. shape4 = (batch_size, 10, 4, 2)
  89. shape5 = (batch_size, 10, 2, 4)
  90. data1 = np.random.random(shape1).astype("float32")
  91. data2 = np.random.random(shape2).astype("float32")
  92. data3 = np.random.random(shape3).astype("float32")
  93. data4 = np.random.random(shape4).astype("float32")
  94. data5 = np.random.random(shape5).astype("float32")
  95. cases = [
  96. {"input": [data1, data2]},
  97. {"input": [data2, data3]},
  98. {"input": [data3, data4]},
  99. {"input": [data4, data5]},
  100. ]
  101. opr_test(cases, F.matmul, ref_fn=np.matmul)
  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. transpose_b=True,
  107. )
  108. opr_test(
  109. [{"input": [data3, data2]}],
  110. F.matmul,
  111. ref_fn=lambda x, y: np.matmul(x.transpose(0, 2, 1), y.transpose(0, 2, 1)),
  112. transpose_a=True,
  113. transpose_b=True,
  114. )
  115. def test_interpolate():
  116. def linear_interpolate():
  117. inp = tensor(np.arange(1, 3, dtype=np.float32).reshape(1, 1, 2))
  118. out = F.vision.interpolate(inp, scale_factor=2.0, mode="linear")
  119. out2 = F.vision.interpolate(inp, 4, mode="linear")
  120. np.testing.assert_allclose(
  121. out.numpy(), np.array([[[1.0, 1.25, 1.75, 2.0]]], dtype=np.float32)
  122. )
  123. np.testing.assert_allclose(
  124. out2.numpy(), np.array([[[1.0, 1.25, 1.75, 2.0]]], dtype=np.float32)
  125. )
  126. def many_batch_interpolate():
  127. inp = tensor(np.arange(1, 9, dtype=np.float32).reshape(2, 1, 2, 2))
  128. out = F.vision.interpolate(inp, [4, 4])
  129. out2 = F.vision.interpolate(inp, scale_factor=2.0)
  130. np.testing.assert_allclose(out.numpy(), out2.numpy())
  131. def assign_corner_interpolate():
  132. inp = tensor(np.arange(1, 5, dtype=np.float32).reshape(1, 1, 2, 2))
  133. out = F.vision.interpolate(inp, [4, 4], align_corners=True)
  134. out2 = F.vision.interpolate(inp, scale_factor=2.0, align_corners=True)
  135. np.testing.assert_allclose(out.numpy(), out2.numpy())
  136. def error_shape_linear_interpolate():
  137. inp = tensor(np.arange(1, 5, dtype=np.float32).reshape(1, 1, 2, 2))
  138. with pytest.raises(ValueError):
  139. F.vision.interpolate(inp, scale_factor=2.0, mode="linear")
  140. def inappropriate_scale_linear_interpolate():
  141. inp = tensor(np.arange(1, 3, dtype=np.float32).reshape(1, 1, 2))
  142. with pytest.raises(ValueError):
  143. F.vision.interpolate(inp, scale_factor=[2.0, 3.0], mode="linear")
  144. linear_interpolate()
  145. many_batch_interpolate()
  146. assign_corner_interpolate()
  147. error_shape_linear_interpolate()
  148. inappropriate_scale_linear_interpolate()
  149. def _save_to(self, name="grad"):
  150. def callback(grad):
  151. setattr(self, name, grad)
  152. return callback
  153. def _gen_roi_inp():
  154. inp_feat = np.random.randn(2, 32, 256, 256)
  155. rois = np.zeros((4, 5))
  156. rois[:, 0] = [0, 0, 1, 1]
  157. rois[:, 1:3] = np.random.rand(4, 2) * 100
  158. rois[:, 3:] = np.random.rand(4, 2) * 100 + 150
  159. inp_feat = tensor(inp_feat)
  160. rois = tensor(rois)
  161. return inp_feat, rois
  162. def test_roi_align():
  163. inp_feat, rois = _gen_roi_inp()
  164. grad = Grad().wrt(inp_feat, callback=_save_to(inp_feat))
  165. output_shape = (7, 7)
  166. out_feat = F.vision.roi_align(
  167. inp_feat,
  168. rois,
  169. output_shape=output_shape,
  170. mode="average",
  171. spatial_scale=1.0 / 4,
  172. sample_points=2,
  173. aligned=True,
  174. )
  175. assert make_shape_tuple(out_feat.shape) == (
  176. rois.shape[0],
  177. inp_feat.shape[1],
  178. *output_shape,
  179. )
  180. grad(out_feat, tensor(F.ones_like(out_feat)))
  181. assert make_shape_tuple(inp_feat.grad.shape) == make_shape_tuple(inp_feat.shape)
  182. def _gen_correlation(random=True, constant=1, image_shape=(2, 1, 160, 160)):
  183. if random:
  184. inp_feat1 = np.random.randn(
  185. image_shape[0], image_shape[1], image_shape[2], image_shape[3]
  186. )
  187. inp_feat2 = np.random.randn(
  188. image_shape[0], image_shape[1], image_shape[2], image_shape[3]
  189. )
  190. else:
  191. inp_feat1 = np.ones(image_shape) * constant
  192. inp_feat2 = np.ones(image_shape) * constant
  193. return tensor(inp_feat1), tensor(inp_feat2)
  194. def test_correlation():
  195. ##test case 0 check the grad shape
  196. data1, data2 = _gen_correlation()
  197. grad = Grad().wrt(data1, callback=_save_to(data1))
  198. out_feat = F.vision.correlation(
  199. data1,
  200. data2,
  201. kernel_size=5,
  202. max_displacement=4,
  203. stride1=2,
  204. stride2=2,
  205. pad_size=2,
  206. is_multiply=True,
  207. )
  208. grad(out_feat, tensor(F.ones_like(out_feat)))
  209. assert make_shape_tuple(data1.grad.shape) == make_shape_tuple(data1.shape)
  210. ##test case 1 from https://github.com/NVIDIA/flownet2-pytorch/issues/194
  211. data1, data2 = _gen_correlation(random=False, image_shape=(1, 1, 3, 3))
  212. out_feat = F.vision.correlation(
  213. data1,
  214. data2,
  215. kernel_size=3,
  216. max_displacement=0,
  217. stride1=1,
  218. stride2=1,
  219. pad_size=0,
  220. is_multiply=True,
  221. )
  222. assert abs(out_feat.sum() - 1) < 1e-9
  223. ##test case 2 check same image subduction
  224. data1, data2 = _gen_correlation(random=False, image_shape=(1, 1, 3, 3))
  225. out_feat = F.vision.correlation(
  226. data1,
  227. data2,
  228. kernel_size=3,
  229. max_displacement=0,
  230. stride1=1,
  231. stride2=1,
  232. pad_size=0,
  233. is_multiply=False,
  234. )
  235. assert out_feat.sum() < 1e-9
  236. ##test case 3 check same image subduction
  237. data1, data2 = _gen_correlation(random=False, image_shape=(1, 1, 3, 3))
  238. out_feat = F.vision.correlation(
  239. data1,
  240. data2,
  241. kernel_size=3,
  242. max_displacement=0,
  243. stride1=1,
  244. stride2=1,
  245. pad_size=0,
  246. is_multiply=False,
  247. )
  248. assert out_feat.sum() < 1e-9
  249. ##test case 4 check correlation
  250. data1, _ = _gen_correlation(
  251. random=False, image_shape=(1, 1, 220, 220), constant=2.0
  252. )
  253. _, data2 = _gen_correlation(
  254. random=False, image_shape=(1, 1, 220, 220), constant=1.0
  255. )
  256. out_feat = F.vision.correlation(
  257. data1,
  258. data2,
  259. kernel_size=3,
  260. max_displacement=2,
  261. stride1=1,
  262. stride2=2,
  263. pad_size=0,
  264. is_multiply=False,
  265. )
  266. assert abs(out_feat.mean() - 1) < 1e-9
  267. def test_roi_pooling():
  268. inp_feat, rois = _gen_roi_inp()
  269. grad = Grad().wrt(inp_feat, callback=_save_to(inp_feat))
  270. output_shape = (7, 7)
  271. out_feat = F.vision.roi_pooling(
  272. inp_feat, rois, output_shape=output_shape, mode="max", scale=1.0 / 4,
  273. )
  274. assert make_shape_tuple(out_feat.shape) == (
  275. rois.shape[0],
  276. inp_feat.shape[1],
  277. *output_shape,
  278. )
  279. grad(out_feat, tensor(F.ones_like(out_feat)))
  280. assert make_shape_tuple(inp_feat.grad.shape) == make_shape_tuple(inp_feat.shape)
  281. def test_adaptive_avg_pool2d():
  282. inp = tensor(np.arange(0, 16, dtype=np.float32).reshape(1, 1, 4, 4))
  283. oshp = (2, 2)
  284. grad = Grad().wrt(inp, callback=_save_to(inp))
  285. outp = F.adaptive_avg_pool2d(inp, oshp,)
  286. assert make_shape_tuple(outp.shape) == (inp.shape[0], inp.shape[1], *oshp,)
  287. np.testing.assert_equal(
  288. outp.numpy(), np.array([[[[2.5, 4.5], [10.5, 12.5]]]], dtype=np.float32)
  289. )
  290. grad(outp, tensor(F.ones_like(outp)))
  291. assert make_shape_tuple(inp.grad.shape) == make_shape_tuple(inp.shape)
  292. np.testing.assert_equal(
  293. inp.grad.numpy(),
  294. np.array(
  295. [
  296. [
  297. [
  298. [0.25, 0.25, 0.25, 0.25],
  299. [0.25, 0.25, 0.25, 0.25],
  300. [0.25, 0.25, 0.25, 0.25],
  301. [0.25, 0.25, 0.25, 0.25],
  302. ]
  303. ]
  304. ],
  305. dtype=np.float32,
  306. ),
  307. )
  308. def test_adaptive_max_pool2d():
  309. inp = tensor(np.arange(0, 16, dtype=np.float32).reshape(1, 1, 4, 4))
  310. oshp = (2, 2)
  311. grad = Grad().wrt(inp, callback=_save_to(inp))
  312. outp = F.adaptive_max_pool2d(inp, oshp,)
  313. assert make_shape_tuple(outp.shape) == (inp.shape[0], inp.shape[1], *oshp,)
  314. np.testing.assert_equal(
  315. outp.numpy(), np.array([[[[5, 7], [13, 15]]]], dtype=np.float32)
  316. )
  317. grad(outp, tensor(F.ones_like(outp)))
  318. assert make_shape_tuple(inp.grad.shape) == make_shape_tuple(inp.shape)
  319. np.testing.assert_equal(
  320. inp.grad.numpy(),
  321. np.array(
  322. [
  323. [
  324. [
  325. [0.0, 0.0, 0.0, 0.0],
  326. [0.0, 1.0, 0.0, 1.0],
  327. [0.0, 0.0, 0.0, 0.0],
  328. [0.0, 1.0, 0.0, 1.0],
  329. ]
  330. ]
  331. ],
  332. dtype=np.float32,
  333. ),
  334. )
  335. def test_one_hot():
  336. def onehot_low_dimension():
  337. inp = tensor(np.arange(1, 4, dtype=np.int32))
  338. out = F.one_hot(inp, num_classes=4)
  339. np.testing.assert_allclose(
  340. out.numpy(), np.eye(4, dtype=np.int32)[np.arange(1, 4, dtype=np.int32)]
  341. )
  342. def onehot_high_dimension():
  343. arr = np.array(
  344. [[3, 2, 4, 4, 2, 4, 0, 4, 4, 1], [4, 1, 1, 3, 2, 2, 4, 2, 4, 3]],
  345. dtype=np.int32,
  346. )
  347. inp = tensor(arr)
  348. out = F.one_hot(inp, 10)
  349. np.testing.assert_allclose(out.numpy(), np.eye(10, dtype=np.int32)[arr])
  350. onehot_low_dimension()
  351. onehot_high_dimension()
  352. def test_interpolate_fastpath():
  353. # check shape
  354. test_cases = [
  355. [(1, 1, 10, 10), (5, 5)],
  356. [(1, 3, 10, 10), (20, 20)],
  357. [(10, 1, 10, 10), (1, 1)],
  358. # [(10, 10, 1, 1), (10, 10)], # FIXME, it causes random CI failure
  359. ]
  360. for inp_shape, target_shape in test_cases:
  361. x = tensor(np.random.randn(*inp_shape), dtype=np.float32)
  362. out = F.vision.interpolate(x, target_shape, mode="bilinear")
  363. assert out.shape[0] == x.shape[0] and out.shape[1] == x.shape[1]
  364. assert out.shape[2] == target_shape[0] and out.shape[3] == target_shape[1]
  365. # check value
  366. x = tensor(np.ones((3, 3, 10, 10)), dtype=np.float32)
  367. out = F.vision.interpolate(x, (15, 5), mode="bilinear")
  368. np.testing.assert_equal(out.numpy(), np.ones((3, 3, 15, 5)).astype(np.float32))
  369. np_x = np.arange(32)
  370. x = tensor(np_x).astype(np.float32).reshape(1, 1, 32, 1)
  371. out = F.vision.interpolate(x, (1, 1), mode="bilinear")
  372. np.testing.assert_equal(out.item(), np_x.mean())
  373. @pytest.mark.parametrize("dt", [np.float32, np.int8, np.uint8, np.float16])
  374. def test_warp_perspective(dt):
  375. inp_shape = (1, 1, 4, 4)
  376. x = tensor(np.arange(16, dtype=dt).reshape(inp_shape))
  377. M_shape = (1, 3, 3)
  378. # M defines a translation: dst(1, 1, h, w) = rst(1, 1, h+1, w+1)
  379. M = tensor(
  380. np.array(
  381. [[1.0, 0.0, 1.0], [0.0, 1.0, 1.0], [0.0, 0.0, 1.0]], dtype=np.float32
  382. ).reshape(M_shape)
  383. )
  384. outp = F.vision.warp_perspective(x, M, (2, 2))
  385. np.testing.assert_equal(outp.numpy(), np.array([[[[5, 6], [9, 10]]]], dtype=dt))
  386. @pytest.mark.parametrize("dt", [np.float32, np.int8, np.uint8, np.float16])
  387. def test_warp_perspective_mat_idx(dt):
  388. inp_shape = (2, 1, 4, 4)
  389. x = tensor(np.arange(32, dtype=dt).reshape(inp_shape))
  390. M_shape = (1, 3, 3)
  391. # M defines a translation: dst(1, 1, h, w) = rst(1, 1, h+1, w+1)
  392. M = tensor(
  393. np.array(
  394. [[1.0, 0.0, 1.0], [0.0, 1.0, 1.0], [0.0, 0.0, 1.0]], dtype=np.float32
  395. ).reshape(M_shape)
  396. )
  397. M = F.concat([M,] * 4, 0)
  398. outp = F.vision.warp_perspective(x, M, (2, 2), mat_idx=[0, 1, 1, 0])
  399. np.testing.assert_equal(
  400. outp.numpy(),
  401. np.array(
  402. [
  403. [[[5, 6], [9, 10]]],
  404. [[[21, 22], [25, 26]]],
  405. [[[21, 22], [25, 26]]],
  406. [[[5, 6], [9, 10]]],
  407. ],
  408. dtype=dt,
  409. ),
  410. )
  411. def test_warp_affine():
  412. inp_shape = (1, 3, 3, 3)
  413. x = tensor(np.arange(27, dtype=np.float32).reshape(inp_shape))
  414. weightv = [[[1.26666667, 0.6, -83.33333333], [-0.33333333, 1, 66.66666667]]]
  415. outp = F.vision.warp_affine(x, tensor(weightv), (2, 2), border_mode="wrap")
  416. res = np.array(
  417. [
  418. [
  419. [[7.875, 8.875, 9.875], [8.90625, 9.90625, 10.90625]],
  420. [[18.75, 19.75, 20.75], [14.90625, 15.90625, 16.90625]],
  421. ]
  422. ],
  423. dtype=np.float32,
  424. )
  425. if not is_cuda_available():
  426. np.testing.assert_almost_equal(outp.numpy(), res, 5)
  427. def test_remap():
  428. inp_shape = (1, 1, 4, 4)
  429. inp = tensor(np.arange(16, dtype=np.float32).reshape(inp_shape))
  430. map_xy_shape = (1, 2, 2, 2)
  431. map_xy = tensor(
  432. np.array(
  433. [[[1.0, 0.0], [0.0, 1.0]], [[0.0, 1.0], [0.0, 1.0]]], dtype=np.float32
  434. ).reshape(map_xy_shape)
  435. )
  436. outp = F.vision.remap(inp, map_xy)
  437. np.testing.assert_equal(
  438. outp.numpy(), np.array([[[[1.0, 4.0], [4.0, 4.0]]]], dtype=np.float32)
  439. )
  440. def test_binary_cross_entropy():
  441. data1_shape = (2, 2)
  442. label1_shape = (2, 2)
  443. data2_shape = (2, 3)
  444. label2_shape = (2, 3)
  445. def sigmoid(x):
  446. return 1 / (1 + np.exp(-x))
  447. def compare_fn(x, y):
  448. np.testing.assert_allclose(x.numpy(), y, atol=5e-4)
  449. np.random.seed(123)
  450. data1 = np.random.uniform(size=data1_shape).astype(np.float32)
  451. label1 = np.random.uniform(size=label1_shape).astype(np.float32)
  452. expect1 = np.array([0.6361], dtype=np.float32)
  453. np.random.seed(123)
  454. data2 = np.random.uniform(size=data2_shape).astype(np.float32)
  455. label2 = np.random.uniform(size=label2_shape).astype(np.float32)
  456. expect2 = np.array([0.6750], dtype=np.float32)
  457. cases = [
  458. {"input": [data1, label1], "output": expect1,},
  459. {"input": [data2, label2], "output": expect2,},
  460. ]
  461. opr_test(cases, F.nn.binary_cross_entropy, compare_fn=compare_fn)
  462. cases = [
  463. {"input": [sigmoid(data1), label1], "output": expect1,},
  464. {"input": [sigmoid(data2), label2], "output": expect2,},
  465. ]
  466. opr_test(
  467. cases,
  468. partial(F.nn.binary_cross_entropy, with_logits=False),
  469. compare_fn=compare_fn,
  470. )
  471. def test_hinge_loss():
  472. np.random.seed(123)
  473. # case with L1 norm
  474. cases = []
  475. for shape in [(2, 2), (2, 3)]:
  476. data = np.random.uniform(size=shape).astype(np.float32)
  477. label = 2 * np.random.randint(0, 1, size=shape).astype(np.float32) - 1
  478. expect = np.clip(0, np.inf, 1 - data * label).sum(axis=1).mean()
  479. cases.append({"input": [data, label], "output": expect})
  480. opr_test(cases, F.nn.hinge_loss)
  481. # cases with L2 norm
  482. cases = []
  483. for shape in [(2, 2), (2, 3)]:
  484. data = np.random.uniform(size=shape).astype(np.float32)
  485. label = 2 * np.random.randint(0, 1, size=shape).astype(np.float32) - 1
  486. expect = ((np.clip(0, np.inf, 1 - data * label) ** 2).sum(axis=1)).mean()
  487. cases.append({"input": [data, label], "output": expect})
  488. def hinge_loss_with_l2_norm(pred, label):
  489. return F.nn.hinge_loss(pred, label, "L2")
  490. opr_test(cases, hinge_loss_with_l2_norm)
  491. def test_nms():
  492. x = np.array(
  493. [
  494. [0, 0, 100, 100],
  495. [10, 10, 100, 100],
  496. [50, 50, 100, 100],
  497. [100, 100, 150, 150],
  498. ],
  499. dtype=np.float32,
  500. )
  501. inp = tensor(x)
  502. scores = tensor([0.5, 0.8, 0.9, 0.6], dtype=np.float32)
  503. result = F.vision.nms(inp, scores=scores, iou_thresh=0.5)
  504. np.testing.assert_equal(result.numpy(), np.array([2, 1, 3], dtype=np.int32))
  505. @pytest.mark.skipif(
  506. get_device_count("gpu") > 0, reason="cuda does not support nchw int8"
  507. )
  508. def test_conv_bias():
  509. inp_scale = 1.5
  510. w_scale = 2.5
  511. outp_scale = 1.5
  512. inp_dtype = dtype.qint8(inp_scale)
  513. w_dtype = dtype.qint8(w_scale)
  514. b_dtype = dtype.qint32(inp_scale * w_scale)
  515. out_dtype = dtype.qint8(outp_scale)
  516. def run(
  517. N,
  518. IC,
  519. OC,
  520. IH,
  521. IW,
  522. KH,
  523. KW,
  524. PH,
  525. PW,
  526. SH,
  527. SW,
  528. has_bias=True,
  529. nonlinear_mode="identity",
  530. ):
  531. inp_v = np.random.normal(size=(N, IC, IH, IW))
  532. w_v = np.random.normal(size=(OC, IC, KH, KW))
  533. b_v = np.random.normal(size=(1, OC, 1, 1))
  534. inp_scale = dtype.get_scale(inp_dtype)
  535. w_scale = dtype.get_scale(w_dtype)
  536. b_scale = dtype.get_scale(b_dtype)
  537. inpv = dtype.convert_to_qint8(inp_v * inp_scale, inp_dtype)
  538. wv = dtype.convert_to_qint8(w_v * w_scale, w_dtype)
  539. bv = dtype.convert_to_qint32(b_v * b_scale, b_dtype)
  540. inp_int8 = tensor(inpv, dtype=inp_dtype)
  541. w_int8 = Parameter(wv, dtype=w_dtype)
  542. b_int32 = Parameter(bv, dtype=b_dtype)
  543. inp_fp32 = inp_int8.astype("float32")
  544. w_fp32 = w_int8.astype("float32")
  545. b_fp32 = b_int32.astype("float32")
  546. def convert_to_nchw4(var):
  547. var = F.reshape(
  548. var, (var.shape[0], var.shape[1] // 4, 4, var.shape[2], var.shape[3])
  549. )
  550. var = F.transpose(var, (0, 1, 3, 4, 2))
  551. return var
  552. def run_conv2d(inp, w, b):
  553. O = F.conv2d(
  554. inp, w, b if has_bias else None, stride=(SH, SW), padding=(PH, PW),
  555. )
  556. if nonlinear_mode == "relu":
  557. return F.relu(O)
  558. else:
  559. return O
  560. def run_conv_bias(inp, w, b, format="NCHW"):
  561. b = b if has_bias else Parameter(np.zeros_like(b.numpy()))
  562. if format == "NCHW4":
  563. inp = convert_to_nchw4(inp)
  564. w = convert_to_nchw4(w)
  565. b = convert_to_nchw4(b)
  566. return F.quantized.conv_bias_activation(
  567. inp,
  568. w,
  569. b,
  570. stride=(SH, SW),
  571. padding=(PH, PW),
  572. dtype=out_dtype,
  573. nonlinear_mode=nonlinear_mode,
  574. )
  575. format = "NCHW4" if is_cuda_available() else "NCHW"
  576. expected = run_conv2d(inp_fp32, w_fp32, b_fp32)
  577. expected = expected.astype(out_dtype).astype("float32")
  578. result = run_conv_bias(inp_int8, w_int8, b_int32, format=format).astype(
  579. "float32"
  580. )
  581. if format == "NCHW4":
  582. result = F.transpose(result, (0, 1, 4, 2, 3))
  583. expected = F.flatten(expected)
  584. result = F.flatten(result)
  585. np.testing.assert_allclose(result.numpy(), expected.numpy(), atol=outp_scale)
  586. run(1, 4, 4, 24, 33, 1, 1, 2, 3, 1, 1, False)
  587. run(10, 12, 24, 46, 46, 1, 1, 2, 1, 3, 1, False)
  588. run(10, 36, 8, 46, 26, 2, 2, 2, 1, 1, 2, False)
  589. run(1, 4, 4, 24, 33, 1, 1, 2, 3, 1, 1)
  590. run(10, 12, 24, 46, 46, 1, 1, 2, 1, 3, 1)
  591. run(10, 36, 8, 46, 26, 2, 2, 2, 1, 1, 2)
  592. run(10, 36, 8, 46, 26, 2, 2, 2, 1, 1, 2, False, "relu")
  593. run(10, 36, 8, 46, 26, 2, 2, 2, 1, 1, 2, True, "relu")
  594. @pytest.mark.skipif(get_device_count("gpu") > 0, reason="no int8 algorithm on cuda")
  595. def test_batch_conv_bias():
  596. inp_scale = 1.5
  597. w_scale = 2.5
  598. outp_scale = 1.5
  599. inp_dtype = dtype.qint8(inp_scale)
  600. w_dtype = dtype.qint8(w_scale)
  601. b_dtype = dtype.qint32(inp_scale * w_scale)
  602. out_dtype = dtype.qint8(outp_scale)
  603. def run(
  604. N, IC, OC, IH, IW, KH, KW, PH, PW, SH, SW, has_bias=True,
  605. ):
  606. inp_v = np.random.normal(size=(N, IC, IH, IW))
  607. w_v = np.random.normal(size=(N, OC, IC, KH, KW))
  608. b_v = np.random.normal(size=(1, OC, 1, 1))
  609. inp_scale = dtype.get_scale(inp_dtype)
  610. w_scale = dtype.get_scale(w_dtype)
  611. b_scale = dtype.get_scale(b_dtype)
  612. inpv = dtype.convert_to_qint8(inp_v * inp_scale, inp_dtype)
  613. wv = dtype.convert_to_qint8(w_v * w_scale, w_dtype)
  614. bv = dtype.convert_to_qint32(b_v * b_scale, b_dtype)
  615. inp_int8 = tensor(inpv, dtype=inp_dtype)
  616. w_int8 = Parameter(wv, dtype=w_dtype)
  617. b_int32 = Parameter(bv, dtype=b_dtype)
  618. inp_fp32 = inp_int8.astype("float32")
  619. w_fp32 = w_int8.astype("float32")
  620. b_fp32 = b_int32.astype("float32")
  621. def run_batch_conv_bias(inp, w, b):
  622. b = b if has_bias else Parameter(np.zeros_like(b.numpy()))
  623. result = F.quantized.batch_conv_bias_activation(
  624. inp, w, b, stride=(SH, SW), padding=(PH, PW), dtype=out_dtype,
  625. )
  626. return result.astype("float32")
  627. expected = F.conv2d(inp_fp32, w_fp32[0], b_fp32 if has_bias else None)[0]
  628. expected = expected.astype(out_dtype).astype("float32")
  629. expected = F.flatten(expected)
  630. result = run_batch_conv_bias(inp_int8, w_int8, b_int32)
  631. result = F.flatten(result)
  632. np.testing.assert_allclose(result.numpy(), expected.numpy(), atol=outp_scale)
  633. run(1, 4, 4, 5, 5, 3, 3, 0, 0, 1, 1, True)
  634. def test_conv2d_io16c32():
  635. amp.enabled = True
  636. inp = tensor(np.random.randn(1, 3, 224, 224), dtype=np.float32)
  637. weight = tensor(np.random.randn(64, 3, 7, 7), dtype=np.float32)
  638. out = F.conv2d(inp, weight, None, (2, 2), (3, 3), (1, 1), 1)
  639. amp.enabled = False
  640. expected = F.conv2d(
  641. inp.astype("float16"),
  642. weight.astype("float16"),
  643. None,
  644. (2, 2),
  645. (3, 3),
  646. (1, 1),
  647. 1,
  648. compute_mode="float32",
  649. )
  650. assert out.dtype == np.float16
  651. assert expected.dtype == np.float16
  652. np.testing.assert_allclose(out.numpy(), expected.numpy())
  653. def test_conv2d_zero_stride_numpy_array():
  654. inp = np.random.randn(3, 224, 224).astype(np.float32)
  655. inp = inp[np.newaxis, :]
  656. inp = tensor(inp, dtype=np.float32)
  657. weight = tensor(np.random.randn(16, 3, 3, 3), dtype=np.float32)
  658. out = F.conv2d(inp, weight, None, (2, 2), (3, 3), (1, 1), 1)
  659. def test_conv3d_zero_stride_numpy_array():
  660. inp = np.random.randn(3, 224, 224, 224).astype(np.float32)
  661. inp = inp[np.newaxis, :]
  662. inp = tensor(inp, dtype=np.float32)
  663. weight = tensor(np.random.randn(16, 3, 3, 3, 3), dtype=np.float32)
  664. out = F.conv3d(inp, weight, None, (2, 2, 2), (3, 3, 3), (1, 1, 1), 1)
  665. out.numpy()
  666. def test_conv1d():
  667. inp = tensor(np.ones((2, 2, 4), dtype=np.float32))
  668. weight = tensor(np.ones((3, 2, 2), dtype=np.float32))
  669. out = F.conv1d(inp, weight, None, 2, 0, 1, 1)
  670. np.testing.assert_equal(
  671. out.numpy(),
  672. np.array(
  673. [[[4, 4], [4, 4], [4, 4]], [[4, 4], [4, 4], [4, 4]]], dtype=np.float32
  674. ),
  675. )
  676. def test_batchnorm2d_io16c32():
  677. amp.enabled = True
  678. inp = tensor(np.random.randn(1, 3, 224, 224), dtype=np.float32)
  679. weight = tensor(np.ones((1, 3, 1, 1)), dtype=np.float32)
  680. bias = tensor(np.zeros((1, 3, 1, 1)), dtype=np.float32)
  681. out = F.batch_norm(inp, weight=weight, bias=bias, training=True, inplace=False)
  682. amp.enabled = False
  683. expected = F.batch_norm(
  684. inp.astype("float16"),
  685. weight=weight,
  686. bias=bias,
  687. training=True,
  688. inplace=False,
  689. compute_mode="float32",
  690. )
  691. assert out.dtype == np.float16
  692. assert expected.dtype == np.float16
  693. np.testing.assert_allclose(out.numpy(), expected.numpy())
  694. def test_conv3d():
  695. inp = tensor(np.ones((2, 2, 4, 4, 4), dtype=np.float32))
  696. weight = tensor(np.ones((3, 2, 2, 2, 2), dtype=np.float32))
  697. out = F.conv3d(inp, weight, None, 2, 0, 1, 1)
  698. print(out.numpy().shape)
  699. np.testing.assert_equal(
  700. out.numpy(), np.ones((2, 3, 2, 2, 2), dtype=np.float32) * 16
  701. )
  702. def test_condtake():
  703. x = np.array([[1, 2, 3], [4, 5, 6]])
  704. y = np.array([[True, False, True], [False, True, True]])
  705. xx = tensor(x)
  706. yy = tensor(y)
  707. val, idx = F.cond_take(yy, xx)
  708. np.testing.assert_equal(val.numpy(), x[y])
  709. np.testing.assert_equal(idx.numpy(), np.where(y.reshape(-1))[0])
  710. def test_condtake_is_same():
  711. op1 = builtin.CondTake()
  712. op2 = builtin.CondTake()
  713. assert op1 == op2
  714. def test_nms_is_same():
  715. op1 = builtin.NMSKeep(0.7, 100)
  716. op2 = builtin.NMSKeep(0.7, 100)
  717. op3 = builtin.NMSKeep(0.8, 100)
  718. op4 = builtin.NMSKeep(0.7, 200)
  719. assert op1 == op2
  720. assert op1 != op3
  721. assert op1 != op4
  722. assert op3 != op4
  723. def test_argmxx_on_inf():
  724. def run_argmax():
  725. x = F.zeros((100, 100))
  726. x[:] = -float("inf")
  727. idxs = F.argmax(x, axis=0)
  728. return idxs
  729. def run_argmin():
  730. x = F.zeros((100, 100))
  731. x[:] = float("inf")
  732. idxs = F.argmin(x, axis=0)
  733. return idxs
  734. assert all(run_argmax() >= 0)
  735. assert all(run_argmin() >= 0)
  736. def test_deformable_psroi_pooling():
  737. inp = np.random.random((1, 256, 64, 64)).astype("float32")
  738. rois = np.random.random((1, 5)).astype("float32")
  739. trans = np.random.random((24, 2, 7, 7)).astype("float32")
  740. pooled_h = 7
  741. pooled_w = 7
  742. sample_per_part = 4
  743. no_trans = False
  744. part_size = 7
  745. spatial_scale = 1.0 / 64
  746. trans_std = 0.1
  747. y = F.deformable_psroi_pooling(
  748. tensor(inp),
  749. tensor(rois),
  750. tensor(trans),
  751. no_trans,
  752. part_size,
  753. pooled_h,
  754. pooled_w,
  755. sample_per_part,
  756. spatial_scale,
  757. trans_std,
  758. )
  759. def test_cvt_color():
  760. def rgb2gray(rgb):
  761. return np.dot(rgb[..., :3], [0.299, 0.587, 0.114])
  762. inp = np.random.randn(3, 3, 3, 3).astype(np.float32)
  763. out = np.expand_dims(rgb2gray(inp), 3).astype(np.float32)
  764. x = tensor(inp)
  765. y = F.vision.cvt_color(x, mode="RGB2GRAY")
  766. np.testing.assert_allclose(y.numpy(), out, atol=1e-5)
  767. @pytest.mark.parametrize("val", [2, [2,], [2, 3]])
  768. def test_ones(val):
  769. shp = tensor(val)
  770. np_shp = np.array(val)
  771. np.testing.assert_equal(F.ones(shp), np.ones(np_shp))
  772. def test_assert_equal():
  773. shape = (2, 3, 4, 5)
  774. x = F.ones(shape, dtype=np.float32)
  775. y = F.zeros(shape, dtype=np.float32) + 1.00001
  776. z = F.utils._assert_equal(x, y)
  777. def test_assert_not_equal():
  778. shape = (2, 3, 4, 5)
  779. x = F.ones(shape, dtype=np.float32)
  780. y = F.zeros(shape, dtype=np.float32) + 1.1
  781. with pytest.raises(RuntimeError):
  782. z = F.utils._assert_equal(x, y)
  783. def test_neg_axis():
  784. x = tensor(np.random.normal(0, 1, (32, 5)))
  785. y = F.argmax(x, axis=-1)
  786. yy = F.argmax(x, axis=1)
  787. np.testing.assert_equal(y.numpy(), yy.numpy())
  788. y = F.argmax(x, axis=(-1, -2))
  789. yy = F.argmax(x, axis=(0, 1))
  790. np.testing.assert_equal(y.numpy(), yy.numpy())
  791. y = F.argmin(x, axis=(-1, -2))
  792. yy = F.argmin(x, axis=(0, 1))
  793. np.testing.assert_equal(y.numpy(), yy.numpy())
  794. def test_sliding_window():
  795. N, C, H, W = 2, 3, 7, 8
  796. inp = np.random.normal(size=(N, C, H, W))
  797. ph, pw = 1, 2
  798. sh, sw = 2, 1
  799. wh, ww = 3, 2
  800. dh, dw = 1, 3
  801. s = lambda i, p, s, d, w: (i + p * 2 - (w - 1) * d - 1) // s + 1
  802. inp_pad = np.zeros((N, C, H + ph * 2, W + pw * 2))
  803. inp_pad[:, :, ph : H + ph, pw : W + pw] = inp
  804. gt_out = np.empty(
  805. (N, C, s(H, ph, sh, dh, wh), s(W, pw, sw, dw, ww), wh, ww), dtype=np.float32
  806. )
  807. for n, c, oh, ow in itertools.product(*map(range, gt_out.shape[:4])):
  808. ih, iw = oh * sh, ow * sw
  809. gt_out[n, c, oh, ow, :] = inp_pad[
  810. n, c, ih : ih + (wh - 1) * dh + 1 : dh, iw : iw + (ww - 1) * dw + 1 : dw
  811. ]
  812. out = F.sliding_window(
  813. tensor(inp), (wh, ww), padding=(ph, pw), stride=(sh, sw), dilation=(dh, dw)
  814. )
  815. np.testing.assert_equal(gt_out, out.numpy())
  816. def test_sliding_window_transpose():
  817. N, C, H, W = 2, 3, 7, 8
  818. ph, pw = 1, 2
  819. sh, sw = 2, 1
  820. wh, ww = 3, 2
  821. dh, dw = 1, 3
  822. s = lambda i, p, s, d, w: (i + p * 2 - (w - 1) * d - 1) // s + 1
  823. inp = np.random.normal(
  824. size=(N, C, s(H, ph, sh, dh, wh), s(W, pw, sw, dw, ww), wh, ww)
  825. ).astype(np.float32)
  826. gt_out = np.zeros((N, C, H, W), dtype=np.float32)
  827. for n, c in itertools.product(*map(range, inp.shape[:2])):
  828. oh = 0
  829. for ih in range(-ph, H + ph - dh * (wh - 1), sh):
  830. ow = 0
  831. for iw in range(-pw, W + pw - dw * (ww - 1), sw):
  832. for kh, kw in itertools.product(*map(range, inp.shape[-2:])):
  833. ih2 = ih + dh * kh
  834. iw2 = iw + dw * kw
  835. if ih2 >= 0 and ih2 < H and iw2 >= 0 and iw2 < W:
  836. gt_out[n, c, ih2, iw2] += inp[n, c, oh, ow, kh, kw]
  837. ow += 1
  838. oh += 1
  839. out = F.sliding_window_transpose(
  840. tensor(inp),
  841. (H, W),
  842. (wh, ww),
  843. padding=(ph, pw),
  844. stride=(sh, sw),
  845. dilation=(dh, dw),
  846. )
  847. np.testing.assert_equal(gt_out, out.numpy())

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