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

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

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