warp-lang 1.0.1__py3-none-manylinux2014_aarch64.whl → 1.1.0__py3-none-manylinux2014_aarch64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of warp-lang might be problematic. Click here for more details.

Files changed (346) hide show
  1. warp/__init__.py +108 -97
  2. warp/__init__.pyi +1 -1
  3. warp/bin/warp-clang.so +0 -0
  4. warp/bin/warp.so +0 -0
  5. warp/build.py +115 -113
  6. warp/build_dll.py +383 -375
  7. warp/builtins.py +3425 -3354
  8. warp/codegen.py +2878 -2792
  9. warp/config.py +40 -36
  10. warp/constants.py +45 -45
  11. warp/context.py +5194 -5102
  12. warp/dlpack.py +442 -442
  13. warp/examples/__init__.py +16 -16
  14. warp/examples/assets/bear.usd +0 -0
  15. warp/examples/assets/bunny.usd +0 -0
  16. warp/examples/assets/cartpole.urdf +110 -110
  17. warp/examples/assets/crazyflie.usd +0 -0
  18. warp/examples/assets/cube.usd +0 -0
  19. warp/examples/assets/nv_ant.xml +92 -92
  20. warp/examples/assets/nv_humanoid.xml +183 -183
  21. warp/examples/assets/quadruped.urdf +267 -267
  22. warp/examples/assets/rocks.nvdb +0 -0
  23. warp/examples/assets/rocks.usd +0 -0
  24. warp/examples/assets/sphere.usd +0 -0
  25. warp/examples/benchmarks/benchmark_api.py +383 -383
  26. warp/examples/benchmarks/benchmark_cloth.py +278 -279
  27. warp/examples/benchmarks/benchmark_cloth_cupy.py +88 -88
  28. warp/examples/benchmarks/benchmark_cloth_jax.py +97 -100
  29. warp/examples/benchmarks/benchmark_cloth_numba.py +146 -142
  30. warp/examples/benchmarks/benchmark_cloth_numpy.py +77 -77
  31. warp/examples/benchmarks/benchmark_cloth_pytorch.py +86 -86
  32. warp/examples/benchmarks/benchmark_cloth_taichi.py +112 -112
  33. warp/examples/benchmarks/benchmark_cloth_warp.py +146 -146
  34. warp/examples/benchmarks/benchmark_launches.py +295 -295
  35. warp/examples/browse.py +29 -28
  36. warp/examples/core/example_dem.py +234 -221
  37. warp/examples/core/example_fluid.py +293 -267
  38. warp/examples/core/example_graph_capture.py +144 -129
  39. warp/examples/core/example_marching_cubes.py +188 -176
  40. warp/examples/core/example_mesh.py +174 -154
  41. warp/examples/core/example_mesh_intersect.py +205 -193
  42. warp/examples/core/example_nvdb.py +176 -169
  43. warp/examples/core/example_raycast.py +105 -89
  44. warp/examples/core/example_raymarch.py +199 -178
  45. warp/examples/core/example_render_opengl.py +185 -141
  46. warp/examples/core/example_sph.py +405 -389
  47. warp/examples/core/example_torch.py +222 -181
  48. warp/examples/core/example_wave.py +263 -249
  49. warp/examples/fem/bsr_utils.py +378 -380
  50. warp/examples/fem/example_apic_fluid.py +407 -391
  51. warp/examples/fem/example_convection_diffusion.py +182 -168
  52. warp/examples/fem/example_convection_diffusion_dg.py +219 -209
  53. warp/examples/fem/example_convection_diffusion_dg0.py +204 -194
  54. warp/examples/fem/example_deformed_geometry.py +177 -159
  55. warp/examples/fem/example_diffusion.py +201 -173
  56. warp/examples/fem/example_diffusion_3d.py +177 -152
  57. warp/examples/fem/example_diffusion_mgpu.py +221 -214
  58. warp/examples/fem/example_mixed_elasticity.py +244 -222
  59. warp/examples/fem/example_navier_stokes.py +259 -243
  60. warp/examples/fem/example_stokes.py +220 -192
  61. warp/examples/fem/example_stokes_transfer.py +265 -249
  62. warp/examples/fem/mesh_utils.py +133 -109
  63. warp/examples/fem/plot_utils.py +292 -287
  64. warp/examples/optim/example_bounce.py +260 -248
  65. warp/examples/optim/example_cloth_throw.py +222 -210
  66. warp/examples/optim/example_diffray.py +566 -535
  67. warp/examples/optim/example_drone.py +864 -835
  68. warp/examples/optim/example_inverse_kinematics.py +176 -169
  69. warp/examples/optim/example_inverse_kinematics_torch.py +185 -170
  70. warp/examples/optim/example_spring_cage.py +239 -234
  71. warp/examples/optim/example_trajectory.py +223 -201
  72. warp/examples/optim/example_walker.py +306 -292
  73. warp/examples/sim/example_cartpole.py +139 -128
  74. warp/examples/sim/example_cloth.py +196 -184
  75. warp/examples/sim/example_granular.py +124 -113
  76. warp/examples/sim/example_granular_collision_sdf.py +197 -185
  77. warp/examples/sim/example_jacobian_ik.py +236 -213
  78. warp/examples/sim/example_particle_chain.py +118 -106
  79. warp/examples/sim/example_quadruped.py +193 -179
  80. warp/examples/sim/example_rigid_chain.py +197 -189
  81. warp/examples/sim/example_rigid_contact.py +189 -176
  82. warp/examples/sim/example_rigid_force.py +127 -126
  83. warp/examples/sim/example_rigid_gyroscopic.py +109 -97
  84. warp/examples/sim/example_rigid_soft_contact.py +134 -124
  85. warp/examples/sim/example_soft_body.py +190 -178
  86. warp/fabric.py +337 -335
  87. warp/fem/__init__.py +60 -27
  88. warp/fem/cache.py +401 -388
  89. warp/fem/dirichlet.py +178 -179
  90. warp/fem/domain.py +262 -263
  91. warp/fem/field/__init__.py +100 -101
  92. warp/fem/field/field.py +148 -149
  93. warp/fem/field/nodal_field.py +298 -299
  94. warp/fem/field/restriction.py +22 -21
  95. warp/fem/field/test.py +180 -181
  96. warp/fem/field/trial.py +183 -183
  97. warp/fem/geometry/__init__.py +15 -19
  98. warp/fem/geometry/closest_point.py +69 -70
  99. warp/fem/geometry/deformed_geometry.py +270 -271
  100. warp/fem/geometry/element.py +744 -744
  101. warp/fem/geometry/geometry.py +184 -186
  102. warp/fem/geometry/grid_2d.py +380 -373
  103. warp/fem/geometry/grid_3d.py +441 -435
  104. warp/fem/geometry/hexmesh.py +953 -953
  105. warp/fem/geometry/partition.py +374 -376
  106. warp/fem/geometry/quadmesh_2d.py +532 -532
  107. warp/fem/geometry/tetmesh.py +840 -840
  108. warp/fem/geometry/trimesh_2d.py +577 -577
  109. warp/fem/integrate.py +1630 -1615
  110. warp/fem/operator.py +190 -191
  111. warp/fem/polynomial.py +214 -213
  112. warp/fem/quadrature/__init__.py +2 -2
  113. warp/fem/quadrature/pic_quadrature.py +243 -245
  114. warp/fem/quadrature/quadrature.py +295 -294
  115. warp/fem/space/__init__.py +294 -292
  116. warp/fem/space/basis_space.py +488 -489
  117. warp/fem/space/collocated_function_space.py +100 -105
  118. warp/fem/space/dof_mapper.py +236 -236
  119. warp/fem/space/function_space.py +148 -145
  120. warp/fem/space/grid_2d_function_space.py +267 -267
  121. warp/fem/space/grid_3d_function_space.py +305 -306
  122. warp/fem/space/hexmesh_function_space.py +350 -352
  123. warp/fem/space/partition.py +350 -350
  124. warp/fem/space/quadmesh_2d_function_space.py +368 -369
  125. warp/fem/space/restriction.py +158 -160
  126. warp/fem/space/shape/__init__.py +13 -15
  127. warp/fem/space/shape/cube_shape_function.py +738 -738
  128. warp/fem/space/shape/shape_function.py +102 -103
  129. warp/fem/space/shape/square_shape_function.py +611 -611
  130. warp/fem/space/shape/tet_shape_function.py +565 -567
  131. warp/fem/space/shape/triangle_shape_function.py +429 -429
  132. warp/fem/space/tetmesh_function_space.py +294 -292
  133. warp/fem/space/topology.py +297 -295
  134. warp/fem/space/trimesh_2d_function_space.py +223 -221
  135. warp/fem/types.py +77 -77
  136. warp/fem/utils.py +495 -495
  137. warp/jax.py +166 -141
  138. warp/jax_experimental.py +341 -339
  139. warp/native/array.h +1072 -1025
  140. warp/native/builtin.h +1560 -1560
  141. warp/native/bvh.cpp +398 -398
  142. warp/native/bvh.cu +525 -525
  143. warp/native/bvh.h +429 -429
  144. warp/native/clang/clang.cpp +495 -464
  145. warp/native/crt.cpp +31 -31
  146. warp/native/crt.h +334 -334
  147. warp/native/cuda_crt.h +1049 -1049
  148. warp/native/cuda_util.cpp +549 -540
  149. warp/native/cuda_util.h +288 -203
  150. warp/native/cutlass_gemm.cpp +34 -34
  151. warp/native/cutlass_gemm.cu +372 -372
  152. warp/native/error.cpp +66 -66
  153. warp/native/error.h +27 -27
  154. warp/native/fabric.h +228 -228
  155. warp/native/hashgrid.cpp +301 -278
  156. warp/native/hashgrid.cu +78 -77
  157. warp/native/hashgrid.h +227 -227
  158. warp/native/initializer_array.h +32 -32
  159. warp/native/intersect.h +1204 -1204
  160. warp/native/intersect_adj.h +365 -365
  161. warp/native/intersect_tri.h +322 -322
  162. warp/native/marching.cpp +2 -2
  163. warp/native/marching.cu +497 -497
  164. warp/native/marching.h +2 -2
  165. warp/native/mat.h +1498 -1498
  166. warp/native/matnn.h +333 -333
  167. warp/native/mesh.cpp +203 -203
  168. warp/native/mesh.cu +293 -293
  169. warp/native/mesh.h +1887 -1887
  170. warp/native/nanovdb/NanoVDB.h +4782 -4782
  171. warp/native/nanovdb/PNanoVDB.h +2553 -2553
  172. warp/native/nanovdb/PNanoVDBWrite.h +294 -294
  173. warp/native/noise.h +850 -850
  174. warp/native/quat.h +1084 -1084
  175. warp/native/rand.h +299 -299
  176. warp/native/range.h +108 -108
  177. warp/native/reduce.cpp +156 -156
  178. warp/native/reduce.cu +348 -348
  179. warp/native/runlength_encode.cpp +61 -61
  180. warp/native/runlength_encode.cu +46 -46
  181. warp/native/scan.cpp +30 -30
  182. warp/native/scan.cu +36 -36
  183. warp/native/scan.h +7 -7
  184. warp/native/solid_angle.h +442 -442
  185. warp/native/sort.cpp +94 -94
  186. warp/native/sort.cu +97 -97
  187. warp/native/sort.h +14 -14
  188. warp/native/sparse.cpp +337 -337
  189. warp/native/sparse.cu +544 -544
  190. warp/native/spatial.h +630 -630
  191. warp/native/svd.h +562 -562
  192. warp/native/temp_buffer.h +30 -30
  193. warp/native/vec.h +1132 -1132
  194. warp/native/volume.cpp +297 -297
  195. warp/native/volume.cu +32 -32
  196. warp/native/volume.h +538 -538
  197. warp/native/volume_builder.cu +425 -425
  198. warp/native/volume_builder.h +19 -19
  199. warp/native/warp.cpp +1057 -1052
  200. warp/native/warp.cu +2943 -2828
  201. warp/native/warp.h +313 -305
  202. warp/optim/__init__.py +9 -9
  203. warp/optim/adam.py +120 -120
  204. warp/optim/linear.py +1104 -939
  205. warp/optim/sgd.py +104 -92
  206. warp/render/__init__.py +10 -10
  207. warp/render/render_opengl.py +3217 -3204
  208. warp/render/render_usd.py +768 -749
  209. warp/render/utils.py +152 -150
  210. warp/sim/__init__.py +52 -59
  211. warp/sim/articulation.py +685 -685
  212. warp/sim/collide.py +1594 -1590
  213. warp/sim/import_mjcf.py +489 -481
  214. warp/sim/import_snu.py +220 -221
  215. warp/sim/import_urdf.py +536 -516
  216. warp/sim/import_usd.py +887 -881
  217. warp/sim/inertia.py +316 -317
  218. warp/sim/integrator.py +234 -233
  219. warp/sim/integrator_euler.py +1956 -1956
  220. warp/sim/integrator_featherstone.py +1910 -1991
  221. warp/sim/integrator_xpbd.py +3294 -3312
  222. warp/sim/model.py +4473 -4314
  223. warp/sim/particles.py +113 -112
  224. warp/sim/render.py +417 -403
  225. warp/sim/utils.py +413 -410
  226. warp/sparse.py +1227 -1227
  227. warp/stubs.py +2109 -2469
  228. warp/tape.py +1162 -225
  229. warp/tests/__init__.py +1 -1
  230. warp/tests/__main__.py +4 -4
  231. warp/tests/assets/torus.usda +105 -105
  232. warp/tests/aux_test_class_kernel.py +26 -26
  233. warp/tests/aux_test_compile_consts_dummy.py +10 -10
  234. warp/tests/aux_test_conditional_unequal_types_kernels.py +21 -21
  235. warp/tests/aux_test_dependent.py +22 -22
  236. warp/tests/aux_test_grad_customs.py +23 -23
  237. warp/tests/aux_test_reference.py +11 -11
  238. warp/tests/aux_test_reference_reference.py +10 -10
  239. warp/tests/aux_test_square.py +17 -17
  240. warp/tests/aux_test_unresolved_func.py +14 -14
  241. warp/tests/aux_test_unresolved_symbol.py +14 -14
  242. warp/tests/disabled_kinematics.py +239 -239
  243. warp/tests/run_coverage_serial.py +31 -31
  244. warp/tests/test_adam.py +157 -157
  245. warp/tests/test_arithmetic.py +1124 -1124
  246. warp/tests/test_array.py +2417 -2326
  247. warp/tests/test_array_reduce.py +150 -150
  248. warp/tests/test_async.py +668 -656
  249. warp/tests/test_atomic.py +141 -141
  250. warp/tests/test_bool.py +204 -149
  251. warp/tests/test_builtins_resolution.py +1292 -1292
  252. warp/tests/test_bvh.py +164 -171
  253. warp/tests/test_closest_point_edge_edge.py +228 -228
  254. warp/tests/test_codegen.py +566 -553
  255. warp/tests/test_compile_consts.py +97 -101
  256. warp/tests/test_conditional.py +246 -246
  257. warp/tests/test_copy.py +232 -215
  258. warp/tests/test_ctypes.py +632 -632
  259. warp/tests/test_dense.py +67 -67
  260. warp/tests/test_devices.py +91 -98
  261. warp/tests/test_dlpack.py +530 -529
  262. warp/tests/test_examples.py +400 -378
  263. warp/tests/test_fabricarray.py +955 -955
  264. warp/tests/test_fast_math.py +62 -54
  265. warp/tests/test_fem.py +1277 -1278
  266. warp/tests/test_fp16.py +130 -130
  267. warp/tests/test_func.py +338 -337
  268. warp/tests/test_generics.py +571 -571
  269. warp/tests/test_grad.py +746 -640
  270. warp/tests/test_grad_customs.py +333 -336
  271. warp/tests/test_hash_grid.py +210 -164
  272. warp/tests/test_import.py +39 -39
  273. warp/tests/test_indexedarray.py +1134 -1134
  274. warp/tests/test_intersect.py +67 -67
  275. warp/tests/test_jax.py +307 -307
  276. warp/tests/test_large.py +167 -164
  277. warp/tests/test_launch.py +354 -354
  278. warp/tests/test_lerp.py +261 -261
  279. warp/tests/test_linear_solvers.py +191 -171
  280. warp/tests/test_lvalue.py +421 -493
  281. warp/tests/test_marching_cubes.py +65 -65
  282. warp/tests/test_mat.py +1801 -1827
  283. warp/tests/test_mat_lite.py +115 -115
  284. warp/tests/test_mat_scalar_ops.py +2907 -2889
  285. warp/tests/test_math.py +126 -193
  286. warp/tests/test_matmul.py +500 -499
  287. warp/tests/test_matmul_lite.py +410 -410
  288. warp/tests/test_mempool.py +188 -190
  289. warp/tests/test_mesh.py +284 -324
  290. warp/tests/test_mesh_query_aabb.py +228 -241
  291. warp/tests/test_mesh_query_point.py +692 -702
  292. warp/tests/test_mesh_query_ray.py +292 -303
  293. warp/tests/test_mlp.py +276 -276
  294. warp/tests/test_model.py +110 -110
  295. warp/tests/test_modules_lite.py +39 -39
  296. warp/tests/test_multigpu.py +163 -163
  297. warp/tests/test_noise.py +248 -248
  298. warp/tests/test_operators.py +250 -250
  299. warp/tests/test_options.py +123 -125
  300. warp/tests/test_peer.py +133 -137
  301. warp/tests/test_pinned.py +78 -78
  302. warp/tests/test_print.py +54 -54
  303. warp/tests/test_quat.py +2086 -2086
  304. warp/tests/test_rand.py +288 -288
  305. warp/tests/test_reload.py +217 -217
  306. warp/tests/test_rounding.py +179 -179
  307. warp/tests/test_runlength_encode.py +190 -190
  308. warp/tests/test_sim_grad.py +243 -0
  309. warp/tests/test_sim_kinematics.py +91 -97
  310. warp/tests/test_smoothstep.py +168 -168
  311. warp/tests/test_snippet.py +305 -266
  312. warp/tests/test_sparse.py +468 -460
  313. warp/tests/test_spatial.py +2148 -2148
  314. warp/tests/test_streams.py +486 -473
  315. warp/tests/test_struct.py +710 -675
  316. warp/tests/test_tape.py +173 -148
  317. warp/tests/test_torch.py +743 -743
  318. warp/tests/test_transient_module.py +87 -87
  319. warp/tests/test_types.py +556 -659
  320. warp/tests/test_utils.py +490 -499
  321. warp/tests/test_vec.py +1264 -1268
  322. warp/tests/test_vec_lite.py +73 -73
  323. warp/tests/test_vec_scalar_ops.py +2099 -2099
  324. warp/tests/test_verify_fp.py +94 -94
  325. warp/tests/test_volume.py +737 -736
  326. warp/tests/test_volume_write.py +255 -265
  327. warp/tests/unittest_serial.py +37 -37
  328. warp/tests/unittest_suites.py +363 -359
  329. warp/tests/unittest_utils.py +603 -578
  330. warp/tests/unused_test_misc.py +71 -71
  331. warp/tests/walkthrough_debug.py +85 -85
  332. warp/thirdparty/appdirs.py +598 -598
  333. warp/thirdparty/dlpack.py +143 -143
  334. warp/thirdparty/unittest_parallel.py +566 -561
  335. warp/torch.py +321 -295
  336. warp/types.py +4504 -4450
  337. warp/utils.py +1008 -821
  338. {warp_lang-1.0.1.dist-info → warp_lang-1.1.0.dist-info}/LICENSE.md +126 -126
  339. {warp_lang-1.0.1.dist-info → warp_lang-1.1.0.dist-info}/METADATA +338 -400
  340. warp_lang-1.1.0.dist-info/RECORD +352 -0
  341. warp/examples/assets/cube.usda +0 -42
  342. warp/examples/assets/sphere.usda +0 -56
  343. warp/examples/assets/torus.usda +0 -105
  344. warp_lang-1.0.1.dist-info/RECORD +0 -352
  345. {warp_lang-1.0.1.dist-info → warp_lang-1.1.0.dist-info}/WHEEL +0 -0
  346. {warp_lang-1.0.1.dist-info → warp_lang-1.1.0.dist-info}/top_level.txt +0 -0
warp/tests/test_mat.py CHANGED
@@ -1,1827 +1,1801 @@
1
- # Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
2
- # NVIDIA CORPORATION and its licensors retain all intellectual property
3
- # and proprietary rights in and to this software, related documentation
4
- # and any modifications thereto. Any use, reproduction, disclosure or
5
- # distribution of this software and related documentation without an express
6
- # license agreement from NVIDIA CORPORATION is strictly prohibited.
7
-
8
- import unittest
9
-
10
- import numpy as np
11
-
12
- import warp as wp
13
- from warp.tests.unittest_utils import *
14
-
15
- wp.init()
16
-
17
- np_signed_int_types = [
18
- np.int8,
19
- np.int16,
20
- np.int32,
21
- np.int64,
22
- np.byte,
23
- ]
24
-
25
- np_float_types = [np.float16, np.float32, np.float64]
26
-
27
-
28
- def randvals(rng, shape, dtype):
29
- if dtype in np_float_types:
30
- return rng.standard_normal(size=shape).astype(dtype)
31
- elif dtype in [np.int8, np.uint8, np.byte, np.ubyte]:
32
- return rng.integers(1, high=3, size=shape, dtype=dtype)
33
- return rng.integers(1, high=5, size=shape, dtype=dtype)
34
-
35
-
36
- kernel_cache = dict()
37
-
38
-
39
- def getkernel(func, suffix=""):
40
- key = func.__name__ + "_" + suffix
41
- if key not in kernel_cache:
42
- kernel_cache[key] = wp.Kernel(func=func, key=key)
43
- return kernel_cache[key]
44
-
45
-
46
- def get_select_kernel(dtype):
47
- def output_select_kernel_fn(
48
- input: wp.array(dtype=dtype),
49
- index: int,
50
- out: wp.array(dtype=dtype),
51
- ):
52
- out[0] = input[index]
53
-
54
- return getkernel(output_select_kernel_fn, suffix=dtype.__name__)
55
-
56
- wp.launch(kernel, dim=1, inputs=[])
57
-
58
-
59
- def test_anon_constructor_error_shape_keyword_missing(test, device):
60
- @wp.kernel
61
- def kernel():
62
- wp.matrix(1.0, 2.0, 3.0)
63
-
64
- with test.assertRaisesRegex(
65
- RuntimeError,
66
- r"shape keyword must be specified when calling matrix\(\) function$",
67
- ):
68
- wp.launch(
69
- kernel,
70
- dim=1,
71
- inputs=[],
72
- device=device,
73
- )
74
-
75
-
76
- def test_anon_constructor_error_dtype_keyword_missing(test, device):
77
- @wp.kernel
78
- def kernel():
79
- wp.matrix(shape=(3, 3))
80
-
81
- with test.assertRaisesRegex(
82
- RuntimeError,
83
- r"matrix\(\) must have dtype as a keyword argument if it has no " r"positional arguments$",
84
- ):
85
- wp.launch(
86
- kernel,
87
- dim=1,
88
- inputs=[],
89
- device=device,
90
- )
91
-
92
-
93
- def test_anon_constructor_error_shape_mismatch(test, device):
94
- @wp.kernel
95
- def kernel():
96
- wp.matrix(
97
- wp.matrix(shape=(1, 2), dtype=float),
98
- shape=(3, 4),
99
- dtype=float,
100
- )
101
-
102
- with test.assertRaisesRegex(
103
- RuntimeError,
104
- r"Incompatible matrix sizes for casting copy constructor, " r"\(3, 4\) vs \(1, 2\)$",
105
- ):
106
- wp.launch(
107
- kernel,
108
- dim=1,
109
- inputs=[],
110
- device=device,
111
- )
112
-
113
-
114
- def test_anon_constructor_error_invalid_arg_count(test, device):
115
- @wp.kernel
116
- def kernel():
117
- wp.matrix(1.0, 2.0, 3.0, shape=(2, 2), dtype=float)
118
-
119
- with test.assertRaisesRegex(
120
- RuntimeError,
121
- r"Wrong number of arguments for matrix\(\) function, must initialize "
122
- r"with either a scalar value, or m\*n values$",
123
- ):
124
- wp.launch(
125
- kernel,
126
- dim=1,
127
- inputs=[],
128
- device=device,
129
- )
130
-
131
-
132
- def test_tpl_constructor_error_incompatible_sizes(test, device):
133
- @wp.kernel
134
- def kernel():
135
- wp.mat33(wp.mat22(1.0, 2.0, 3.0, 4.0))
136
-
137
- with test.assertRaisesRegex(
138
- RuntimeError,
139
- r"Incompatible matrix sizes for casting copy constructor, " r"\(3, 3\) vs \(2, 2\)$",
140
- ):
141
- wp.launch(
142
- kernel,
143
- dim=1,
144
- inputs=[],
145
- device=device,
146
- )
147
-
148
-
149
- def test_tpl_constructor_error_invalid_scalar_type(test, device):
150
- @wp.kernel
151
- def kernel():
152
- wp.mat22(1, 2, 3, 4)
153
-
154
- with test.assertRaisesRegex(
155
- RuntimeError,
156
- r"Wrong scalar type for mat 2,2,<class 'warp.types.float32'> constructor$",
157
- ):
158
- wp.launch(
159
- kernel,
160
- dim=1,
161
- inputs=[],
162
- device=device,
163
- )
164
-
165
-
166
- def test_tpl_constructor_error_invalid_vector_count(test, device):
167
- @wp.kernel
168
- def kernel():
169
- wp.mat22(wp.vec3(1.0, 2.0, 3.0))
170
-
171
- with test.assertRaisesRegex(
172
- RuntimeError,
173
- r"Wrong number of vectors when attempting to construct a matrix " r"with column vectors$",
174
- ):
175
- wp.launch(
176
- kernel,
177
- dim=1,
178
- inputs=[],
179
- device=device,
180
- )
181
-
182
-
183
- def test_tpl_constructor_error_invalid_vector_shape(test, device):
184
- @wp.kernel
185
- def kernel():
186
- wp.mat22(wp.vec3(1.0, 2.0, 3.0), wp.vec3(4.0, 5.0, 6.0))
187
-
188
- with test.assertRaisesRegex(
189
- RuntimeError,
190
- r"Wrong vector row count when attempting to construct a matrix " r"with column vectors$",
191
- ):
192
- wp.launch(
193
- kernel,
194
- dim=1,
195
- inputs=[],
196
- device=device,
197
- )
198
-
199
-
200
- def test_tpl_constructor_error_invalid_arg_count(test, device):
201
- @wp.kernel
202
- def kernel():
203
- wp.mat22(1.0, 2.0, 3.0)
204
-
205
- with test.assertRaisesRegex(
206
- RuntimeError,
207
- r"Wrong number of scalars when attempting to construct a matrix " r"from a list of components$",
208
- ):
209
- wp.launch(
210
- kernel,
211
- dim=1,
212
- inputs=[],
213
- device=device,
214
- )
215
-
216
-
217
- def test_tpl_ops_with_anon(test, device):
218
- mat22f = wp.mat((2, 2), dtype=float)
219
-
220
- m = wp.mat22f(1.0, 2.0, 3.0, 4.0)
221
- m += mat22f(2.0, 3.0, 4.0, 5.0)
222
- m -= mat22f(3.0, 4.0, 5.0, 6.0)
223
- test.assertSequenceEqual(m, ((0.0, 1.0), (2.0, 3.0)))
224
-
225
- m = mat22f(1.0, 2.0, 3.0, 4.0)
226
- m += wp.mat22f(2.0, 3.0, 4.0, 5.0)
227
- m -= wp.mat22f(3.0, 4.0, 5.0, 6.0)
228
- test.assertSequenceEqual(m, ((0.0, 1.0), (2.0, 3.0)))
229
-
230
-
231
- def test_py_arithmetic_ops(test, device, dtype):
232
- wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
233
-
234
- def make_mat(*args):
235
- if wptype in wp.types.int_types:
236
- # Cast to the correct integer type to simulate wrapping.
237
- return tuple(tuple(wptype._type_(x).value for x in row) for row in args)
238
-
239
- return args
240
-
241
- def make_vec(*args):
242
- if wptype in wp.types.int_types:
243
- # Cast to the correct integer type to simulate wrapping.
244
- return tuple(wptype._type_(x).value for x in args)
245
-
246
- return args
247
-
248
- mat_cls = wp.mat((3, 3), wptype)
249
- vec_cls = wp.vec(3, wptype)
250
-
251
- m = mat_cls(((-1, 2, 3), (4, -5, 6), (7, 8, -9)))
252
- test.assertSequenceEqual(+m, make_mat((-1, 2, 3), (4, -5, 6), (7, 8, -9)))
253
- test.assertSequenceEqual(-m, make_mat((1, -2, -3), (-4, 5, -6), (-7, -8, 9)))
254
- test.assertSequenceEqual(m + mat_cls((5, 5, 5) * 3), make_mat((4, 7, 8), (9, 0, 11), (12, 13, -4)))
255
- test.assertSequenceEqual(m - mat_cls((5, 5, 5) * 3), make_mat((-6, -3, -2), (-1, -10, 1), (2, 3, -14)))
256
- test.assertSequenceEqual(m * vec_cls(5, 5, 5), make_vec(20, 25, 30))
257
- test.assertSequenceEqual(m @ vec_cls(5, 5, 5), make_vec(20, 25, 30))
258
- test.assertSequenceEqual(vec_cls(5, 5, 5) * m, make_vec(50, 25, 0))
259
- test.assertSequenceEqual(vec_cls(5, 5, 5) @ m, make_vec(50, 25, 0))
260
-
261
- m = mat_cls(((2, 4, 6), (8, 10, 12), (14, 16, 18)))
262
- test.assertSequenceEqual(m * wptype(2), make_mat((4, 8, 12), (16, 20, 24), (28, 32, 36)))
263
- test.assertSequenceEqual(wptype(2) * m, make_mat((4, 8, 12), (16, 20, 24), (28, 32, 36)))
264
- test.assertSequenceEqual(m / wptype(2), make_mat((1, 2, 3), (4, 5, 6), (7, 8, 9)))
265
- test.assertSequenceEqual(wptype(5040) / m, make_mat((2520, 1260, 840), (630, 504, 420), (360, 315, 280)))
266
- test.assertSequenceEqual(m * vec_cls(5, 5, 5), make_vec(60, 150, 240))
267
- test.assertSequenceEqual(m @ vec_cls(5, 5, 5), make_vec(60, 150, 240))
268
- test.assertSequenceEqual(vec_cls(5, 5, 5) * m, make_vec(120, 150, 180))
269
- test.assertSequenceEqual(vec_cls(5, 5, 5) @ m, make_vec(120, 150, 180))
270
-
271
-
272
- def test_quat_constructor(test, device, dtype, register_kernels=False):
273
- rng = np.random.default_rng(123)
274
-
275
- tol = {
276
- np.float16: 1.0e-3,
277
- np.float32: 1.0e-6,
278
- np.float64: 1.0e-8,
279
- }.get(dtype, 0)
280
-
281
- wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
282
- mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
283
- vec4 = wp.types.vector(length=4, dtype=wptype)
284
- vec3 = wp.types.vector(length=3, dtype=wptype)
285
- quat = wp.types.quaternion(dtype=wptype)
286
-
287
- output_select_kernel = get_select_kernel(wptype)
288
-
289
- def check_mat_quat_constructor(
290
- p: wp.array(dtype=vec3),
291
- r: wp.array(dtype=quat),
292
- s: wp.array(dtype=vec3),
293
- outcomponents: wp.array(dtype=wptype),
294
- outcomponents_alt: wp.array(dtype=wptype),
295
- ):
296
- m = mat44(p[0], r[0], s[0])
297
-
298
- R = wp.transpose(wp.quat_to_matrix(r[0]))
299
- c0 = s[0][0] * R[0]
300
- c1 = s[0][1] * R[1]
301
- c2 = s[0][2] * R[2]
302
- m_alt = mat44(
303
- vec4(c0[0], c0[1], c0[2], wptype(0.0)),
304
- vec4(c1[0], c1[1], c1[2], wptype(0.0)),
305
- vec4(c2[0], c2[1], c2[2], wptype(0.0)),
306
- vec4(p[0][0], p[0][1], p[0][2], wptype(1.0)),
307
- )
308
-
309
- idx = 0
310
- for i in range(4):
311
- for j in range(4):
312
- outcomponents[idx] = m[i, j]
313
- outcomponents_alt[idx] = m_alt[i, j]
314
- idx = idx + 1
315
-
316
- kernel = getkernel(check_mat_quat_constructor, suffix=dtype.__name__)
317
-
318
- if register_kernels:
319
- return
320
-
321
- # translation:
322
- p = wp.array(rng.standard_normal(size=(1, 3)).astype(dtype), dtype=vec3, requires_grad=True, device=device)
323
-
324
- # generate a normalized quaternion for the rotation:
325
- r = rng.standard_normal(size=(1, 4))
326
- r /= np.linalg.norm(r)
327
- r = wp.array(r.astype(dtype), dtype=quat, requires_grad=True, device=device)
328
-
329
- # scale:
330
- s = wp.array(rng.standard_normal(size=(1, 3)).astype(dtype), dtype=vec3, requires_grad=True, device=device)
331
-
332
- # just going to generate the matrix using the constructor, then
333
- # more manually, and make sure the values/gradients are the same:
334
- outcomponents = wp.zeros(4 * 4, dtype=wptype, requires_grad=True, device=device)
335
- outcomponents_alt = wp.zeros(4 * 4, dtype=wptype, requires_grad=True, device=device)
336
- wp.launch(kernel, dim=1, inputs=[p, r, s], outputs=[outcomponents, outcomponents_alt], device=device)
337
- assert_np_equal(outcomponents.numpy(), outcomponents_alt.numpy(), tol=1.0e-6)
338
-
339
- idx = 0
340
- out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
341
- out_alt = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
342
- for i in range(4):
343
- for j in range(4):
344
- tape = wp.Tape()
345
- with tape:
346
- wp.launch(kernel, dim=1, inputs=[p, r, s], outputs=[outcomponents, outcomponents_alt], device=device)
347
- wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
348
- wp.launch(
349
- output_select_kernel, dim=1, inputs=[outcomponents_alt, idx], outputs=[out_alt], device=device
350
- )
351
-
352
- tape.backward(loss=out)
353
- p_grad = 1.0 * tape.gradients[p].numpy()[0]
354
- r_grad = 1.0 * tape.gradients[r].numpy()[0]
355
- s_grad = 1.0 * tape.gradients[s].numpy()[0]
356
- tape.zero()
357
-
358
- tape.backward(loss=out_alt)
359
- p_grad_alt = 1.0 * tape.gradients[p].numpy()[0]
360
- r_grad_alt = 1.0 * tape.gradients[r].numpy()[0]
361
- s_grad_alt = 1.0 * tape.gradients[s].numpy()[0]
362
- tape.zero()
363
-
364
- assert_np_equal(p_grad, p_grad_alt, tol=tol)
365
- assert_np_equal(r_grad, r_grad_alt, tol=tol)
366
- assert_np_equal(s_grad, s_grad_alt, tol=tol)
367
-
368
- idx = idx + 1
369
-
370
-
371
- def test_negation(test, device, dtype, register_kernels=False):
372
- rng = np.random.default_rng(123)
373
-
374
- tol = {
375
- np.float16: 1.0e-2,
376
- np.float32: 1.0e-6,
377
- np.float64: 1.0e-8,
378
- }.get(dtype, 0)
379
-
380
- wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
381
- mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
382
- mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
383
- mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
384
- mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
385
-
386
- output_select_kernel = get_select_kernel(wptype)
387
-
388
- def check_mat_negation(
389
- m2: wp.array(dtype=mat22),
390
- m3: wp.array(dtype=mat33),
391
- m4: wp.array(dtype=mat44),
392
- m5: wp.array(dtype=mat55),
393
- outcomponents: wp.array(dtype=wptype),
394
- ):
395
- mat2 = -m2[0]
396
- mat3 = -m3[0]
397
- mat4 = -m4[0]
398
- mat5 = -m5[0]
399
-
400
- # multiply outputs by 2 so we've got something to backpropagate:
401
- idx = 0
402
- for i in range(2):
403
- for j in range(2):
404
- outcomponents[idx] = wptype(2) * mat2[i, j]
405
- idx = idx + 1
406
-
407
- for i in range(3):
408
- for j in range(3):
409
- outcomponents[idx] = wptype(2) * mat3[i, j]
410
- idx = idx + 1
411
-
412
- for i in range(4):
413
- for j in range(4):
414
- outcomponents[idx] = wptype(2) * mat4[i, j]
415
- idx = idx + 1
416
-
417
- for i in range(5):
418
- for j in range(5):
419
- outcomponents[idx] = wptype(2) * mat5[i, j]
420
- idx = idx + 1
421
-
422
- kernel = getkernel(check_mat_negation, suffix=dtype.__name__)
423
-
424
- if register_kernels:
425
- return
426
-
427
- m2 = wp.array(randvals(rng, [1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
428
- m3 = wp.array(randvals(rng, [1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
429
- m4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
430
- m5 = wp.array(randvals(rng, [1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
431
- outcomponents = wp.zeros(2 * 2 + 3 * 3 + 4 * 4 + 5 * 5, dtype=wptype, requires_grad=True, device=device)
432
-
433
- wp.launch(kernel, dim=1, inputs=[m2, m3, m4, m5], outputs=[outcomponents], device=device)
434
-
435
- assert_np_equal(outcomponents.numpy()[:4], -2 * m2.numpy().reshape(-1), tol=tol)
436
- assert_np_equal(outcomponents.numpy()[4:13], -2 * m3.numpy().reshape(-1), tol=tol)
437
- assert_np_equal(outcomponents.numpy()[13:29], -2 * m4.numpy().reshape(-1), tol=tol)
438
- assert_np_equal(outcomponents.numpy()[29:54], -2 * m5.numpy().reshape(-1), tol=tol)
439
-
440
- if dtype in np_float_types:
441
- idx = 0
442
- out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
443
- for dim, input in [(2, m2), (3, m3), (4, m4), (5, m5)]:
444
- for i in range(dim):
445
- for j in range(dim):
446
- tape = wp.Tape()
447
- with tape:
448
- wp.launch(kernel, dim=1, inputs=[m2, m3, m4, m5], outputs=[outcomponents], device=device)
449
- wp.launch(
450
- output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device
451
- )
452
- tape.backward(loss=out)
453
- expectedresult = np.zeros((dim, dim), dtype=dtype)
454
- expectedresult[i, j] = -2
455
- assert_np_equal(tape.gradients[input].numpy()[0], expectedresult)
456
- tape.zero()
457
- idx = idx + 1
458
-
459
-
460
- def test_subtraction(test, device, dtype, register_kernels=False):
461
- rng = np.random.default_rng(123)
462
-
463
- tol = {
464
- np.float16: 5.0e-3,
465
- np.float32: 1.0e-6,
466
- np.float64: 1.0e-8,
467
- }.get(dtype, 0)
468
-
469
- wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
470
- mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
471
- mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
472
- mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
473
- mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
474
-
475
- output_select_kernel = get_select_kernel(wptype)
476
-
477
- def check_mat_sub(
478
- s2: wp.array(dtype=mat22),
479
- s3: wp.array(dtype=mat33),
480
- s4: wp.array(dtype=mat44),
481
- s5: wp.array(dtype=mat55),
482
- v2: wp.array(dtype=mat22),
483
- v3: wp.array(dtype=mat33),
484
- v4: wp.array(dtype=mat44),
485
- v5: wp.array(dtype=mat55),
486
- outcomponents: wp.array(dtype=wptype),
487
- ):
488
- v2result = v2[0] - s2[0]
489
- v3result = v3[0] - s3[0]
490
- v4result = v4[0] - s4[0]
491
- v5result = v5[0] - s5[0]
492
-
493
- # multiply outputs by 2 so we've got something to backpropagate:
494
- idx = 0
495
- for i in range(2):
496
- for j in range(2):
497
- outcomponents[idx] = wptype(2) * v2result[i, j]
498
- idx = idx + 1
499
-
500
- for i in range(3):
501
- for j in range(3):
502
- outcomponents[idx] = wptype(2) * v3result[i, j]
503
- idx = idx + 1
504
-
505
- for i in range(4):
506
- for j in range(4):
507
- outcomponents[idx] = wptype(2) * v4result[i, j]
508
- idx = idx + 1
509
-
510
- for i in range(5):
511
- for j in range(5):
512
- outcomponents[idx] = wptype(2) * v5result[i, j]
513
- idx = idx + 1
514
-
515
- kernel = getkernel(check_mat_sub, suffix=dtype.__name__)
516
-
517
- if register_kernels:
518
- return
519
-
520
- s2 = wp.array(randvals(rng, [1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
521
- s3 = wp.array(randvals(rng, [1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
522
- s4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
523
- s5 = wp.array(randvals(rng, [1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
524
- v2 = wp.array(randvals(rng, [1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
525
- v3 = wp.array(randvals(rng, [1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
526
- v4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
527
- v5 = wp.array(randvals(rng, [1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
528
- outcomponents = wp.zeros(2 * 2 + 3 * 3 + 4 * 4 + 5 * 5, dtype=wptype, requires_grad=True, device=device)
529
-
530
- wp.launch(
531
- kernel,
532
- dim=1,
533
- inputs=[
534
- s2,
535
- s3,
536
- s4,
537
- s5,
538
- v2,
539
- v3,
540
- v4,
541
- v5,
542
- ],
543
- outputs=[outcomponents],
544
- device=device,
545
- )
546
-
547
- assert_np_equal(outcomponents.numpy()[:4], 2 * (v2.numpy() - s2.numpy()).reshape(-1), tol=tol)
548
- assert_np_equal(outcomponents.numpy()[4:13], 2 * (v3.numpy() - s3.numpy()).reshape(-1), tol=tol)
549
- assert_np_equal(outcomponents.numpy()[13:29], 2 * (v4.numpy() - s4.numpy()).reshape(-1), tol=tol)
550
- assert_np_equal(outcomponents.numpy()[29:54], 2 * (v5.numpy() - s5.numpy()).reshape(-1), tol=10 * tol)
551
-
552
- if dtype in np_float_types:
553
- idx = 0
554
- out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
555
- for dim, in1, in2 in [(2, s2, v2), (3, s3, v3), (4, s4, v4), (5, s5, v5)]:
556
- for i in range(dim):
557
- for j in range(dim):
558
- tape = wp.Tape()
559
- with tape:
560
- wp.launch(
561
- kernel,
562
- dim=1,
563
- inputs=[
564
- s2,
565
- s3,
566
- s4,
567
- s5,
568
- v2,
569
- v3,
570
- v4,
571
- v5,
572
- ],
573
- outputs=[outcomponents],
574
- device=device,
575
- )
576
- wp.launch(
577
- output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device
578
- )
579
- tape.backward(loss=out)
580
- expectedresult = np.zeros((dim, dim), dtype=dtype)
581
- expectedresult[i, j] = 2
582
- assert_np_equal(tape.gradients[in2].numpy()[0], expectedresult, tol=10 * tol)
583
- expectedresult[i, j] = -2
584
- assert_np_equal(tape.gradients[in1].numpy()[0], expectedresult, tol=10 * tol)
585
- tape.zero()
586
-
587
- idx = idx + 1
588
-
589
-
590
- def test_determinant(test, device, dtype, register_kernels=False):
591
- rng = np.random.default_rng(123)
592
-
593
- tol = {
594
- np.float16: 5.0e-3,
595
- np.float32: 1.0e-6,
596
- np.float64: 1.0e-8,
597
- }.get(dtype, 0)
598
-
599
- wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
600
- mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
601
- mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
602
- mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
603
-
604
- def check_mat_det(
605
- v2: wp.array(dtype=mat22),
606
- v3: wp.array(dtype=mat33),
607
- v4: wp.array(dtype=mat44),
608
- det2: wp.array(dtype=wptype),
609
- det3: wp.array(dtype=wptype),
610
- det4: wp.array(dtype=wptype),
611
- ):
612
- # multiply outputs by 2 so we've got something to backpropagate:
613
- det2[0] = wptype(2) * wp.determinant(v2[0])
614
- det3[0] = wptype(2) * wp.determinant(v3[0])
615
- det4[0] = wptype(2) * wp.determinant(v4[0])
616
-
617
- kernel = getkernel(check_mat_det, suffix=dtype.__name__)
618
- if register_kernels:
619
- return
620
-
621
- v2 = wp.array(randvals(rng, [1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
622
- v3 = wp.array(randvals(rng, [1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
623
- v4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
624
- det2 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
625
- det3 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
626
- det4 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
627
-
628
- tape = wp.Tape()
629
- with tape:
630
- wp.launch(
631
- kernel,
632
- dim=1,
633
- inputs=[
634
- v2,
635
- v3,
636
- v4,
637
- ],
638
- outputs=[
639
- det2,
640
- det3,
641
- det4,
642
- ],
643
- device=device,
644
- )
645
-
646
- if dtype in np_float_types:
647
- assert_np_equal(det2.numpy()[0], 2 * np.linalg.det(v2.numpy()[0].astype(np.float64)), tol=100 * tol)
648
- assert_np_equal(det3.numpy()[0], 2 * np.linalg.det(v3.numpy()[0].astype(np.float64)), tol=100 * tol)
649
- assert_np_equal(det4.numpy()[0], 2 * np.linalg.det(v4.numpy()[0].astype(np.float64)), tol=420 * tol)
650
- else:
651
- assert_np_equal(det2.numpy()[0], 2 * np.around(np.linalg.det(v2.numpy()[0])).astype(int))
652
- assert_np_equal(det3.numpy()[0], 2 * np.around(np.linalg.det(v3.numpy()[0])).astype(int))
653
- assert_np_equal(det4.numpy()[0], 2 * np.around(np.linalg.det(v4.numpy()[0])).astype(int))
654
-
655
- if dtype in np_float_types:
656
- # determinant derivative formula is annoying so finite differences?
657
- tape.backward(loss=det2)
658
- v2grads = 1.0 * tape.gradients[v2].numpy()[0]
659
- tape.zero()
660
-
661
- tape.backward(loss=det3)
662
- v3grads = 1.0 * tape.gradients[v3].numpy()[0]
663
- tape.zero()
664
-
665
- tape.backward(loss=det4)
666
- v4grads = 1.0 * tape.gradients[v4].numpy()[0]
667
- tape.zero()
668
-
669
- # finite differences are also annoying hence the large tolerance...
670
- # absolute nightmare in float16 too innit...
671
- dx = 0.01 if dtype == np.float16 else 0.0001
672
- fdtol = 2.0e-1 if dtype == np.float16 else 2.0e-3
673
- for i in range(2):
674
- for j in range(2):
675
- v2test = v2.numpy()
676
- v2test[0, i, j] += dx
677
- wp.launch(
678
- kernel,
679
- dim=1,
680
- inputs=[
681
- wp.array(v2test, dtype=v2.dtype, requires_grad=True, device=device),
682
- v3,
683
- v4,
684
- ],
685
- outputs=[
686
- det2,
687
- det3,
688
- det4,
689
- ],
690
- device=device,
691
- )
692
- dplus = det2.numpy()[0]
693
- v2test[0, i, j] -= 2.0 * dx
694
- wp.launch(
695
- kernel,
696
- dim=1,
697
- inputs=[
698
- wp.array(v2test, dtype=v2.dtype, requires_grad=True, device=device),
699
- v3,
700
- v4,
701
- ],
702
- outputs=[
703
- det2,
704
- det3,
705
- det4,
706
- ],
707
- device=device,
708
- )
709
- dminus = det2.numpy()[0]
710
- assert_np_equal((dplus - dminus) / (2.0 * dx * dplus), v2grads[i, j] / dplus, tol=fdtol)
711
-
712
- for i in range(3):
713
- for j in range(3):
714
- v3test = v3.numpy()
715
- v3test[0, i, j] += dx
716
- wp.launch(
717
- kernel,
718
- dim=1,
719
- inputs=[
720
- v2,
721
- wp.array(v3test, dtype=v3.dtype, requires_grad=True, device=device),
722
- v4,
723
- ],
724
- outputs=[
725
- det2,
726
- det3,
727
- det4,
728
- ],
729
- device=device,
730
- )
731
- dplus = det3.numpy()[0]
732
- v3test[0, i, j] -= 2.0 * dx
733
- wp.launch(
734
- kernel,
735
- dim=1,
736
- inputs=[
737
- v2,
738
- wp.array(v3test, dtype=v3.dtype, requires_grad=True, device=device),
739
- v4,
740
- ],
741
- outputs=[
742
- det2,
743
- det3,
744
- det4,
745
- ],
746
- device=device,
747
- )
748
- dminus = det3.numpy()[0]
749
- assert_np_equal((dplus - dminus) / (2.0 * dx * dplus), v3grads[i, j] / dplus, tol=fdtol)
750
-
751
- for i in range(4):
752
- for j in range(4):
753
- v4test = v4.numpy()
754
- v4test[0, i, j] += dx
755
- wp.launch(
756
- kernel,
757
- dim=1,
758
- inputs=[
759
- v2,
760
- v3,
761
- wp.array(v4test, dtype=v4.dtype, requires_grad=True, device=device),
762
- ],
763
- outputs=[
764
- det2,
765
- det3,
766
- det4,
767
- ],
768
- device=device,
769
- )
770
- dplus = det4.numpy()[0]
771
- v4test[0, i, j] -= 2.0 * dx
772
- wp.launch(
773
- kernel,
774
- dim=1,
775
- inputs=[
776
- v2,
777
- v3,
778
- wp.array(v4test, dtype=v4.dtype, requires_grad=True, device=device),
779
- ],
780
- outputs=[
781
- det2,
782
- det3,
783
- det4,
784
- ],
785
- device=device,
786
- )
787
- dminus = det4.numpy()[0]
788
- assert_np_equal((dplus - dminus) / (2.0 * dx * dplus), v4grads[i, j] / dplus, tol=fdtol)
789
-
790
-
791
- # Unused. Why?
792
- # def test_get_diag(test, device, dtype, register_kernels=False):
793
- # tol = {
794
- # np.float16: 1.0e-3,
795
- # np.float32: 1.0e-6,
796
- # np.float64: 1.0e-8,
797
- # }.get(dtype, 0)
798
- #
799
- # wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
800
- # mat55 = wp.types.vector(shape=(5, 5), dtype=wptype)
801
- #
802
- # output_select_kernel = get_select_kernel(wptype)
803
- #
804
- # def check_mat_diag(
805
- # m55: wp.array(dtype=mat55),
806
- # outcomponents: wp.array(dtype=wptype),
807
- # ):
808
- # # multiply outputs by 2 so we've got something to backpropagate:
809
- # vec5result = wptype(2) * wp.get_diag(m55[0])
810
- #
811
- # idx = 0
812
- # for i in range(5):
813
- # outcomponents[idx] = vec5result[i]
814
- # idx = idx + 1
815
- #
816
- # kernel = getkernel(check_mat_diag, suffix=dtype.__name__)
817
- #
818
- # if register_kernels:
819
- # return
820
- #
821
- # m55 = wp.array(randvals((1, 5, 5), dtype), dtype=mat55, requires_grad=True, device=device)
822
- # outcomponents = wp.zeros(5, dtype=wptype, requires_grad=True, device=device)
823
- # out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
824
- #
825
- # wp.launch(kernel, dim=1, inputs=[m55], outputs=[outcomponents], device=device)
826
- #
827
- # assert_np_equal(outcomponents.numpy(), 2 * np.diag(m55.numpy()[0]), tol=tol)
828
- #
829
- # if dtype in np_float_types:
830
- # idx = 0
831
- # for i in range(5):
832
- # tape = wp.Tape()
833
- # with tape:
834
- # wp.launch(kernel, dim=1, inputs=[m55], outputs=[outcomponents], device=device)
835
- # wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
836
- # tape.backward(loss=out)
837
- # expectedresult = np.zeros((5, 5), dtype=dtype)
838
- # expectedresult[i, i] = 2
839
- # assert_np_equal(tape.gradients[m55].numpy()[0], expectedresult, tol=10 * tol)
840
- # tape.zero()
841
- #
842
- # idx = idx + 1
843
-
844
-
845
- def test_inverse(test, device, dtype, register_kernels=False):
846
- rng = np.random.default_rng(123)
847
-
848
- tol = {
849
- np.float16: 5.0e-2,
850
- np.float32: 1.0e-5,
851
- np.float64: 1.0e-8,
852
- }.get(dtype, 0)
853
-
854
- wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
855
- mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
856
- mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
857
- mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
858
-
859
- output_select_kernel = get_select_kernel(wptype)
860
-
861
- def check_mat_inverse(
862
- m2: wp.array(dtype=mat22),
863
- m3: wp.array(dtype=mat33),
864
- m4: wp.array(dtype=mat44),
865
- outcomponents: wp.array(dtype=wptype),
866
- ):
867
- m2result = wp.inverse(m2[0])
868
- m3result = wp.inverse(m3[0])
869
- m4result = wp.inverse(m4[0])
870
-
871
- # multiply outputs by 2 so we've got something to backpropagate:
872
- idx = 0
873
- for i in range(2):
874
- for j in range(2):
875
- outcomponents[idx] = wptype(2) * m2result[i, j]
876
- idx = idx + 1
877
-
878
- for i in range(3):
879
- for j in range(3):
880
- outcomponents[idx] = wptype(2) * m3result[i, j]
881
- idx = idx + 1
882
-
883
- for i in range(4):
884
- for j in range(4):
885
- outcomponents[idx] = wptype(2) * m4result[i, j]
886
- idx = idx + 1
887
-
888
- kernel = getkernel(check_mat_inverse, suffix=dtype.__name__)
889
-
890
- if register_kernels:
891
- return
892
-
893
- m2 = wp.array(
894
- 2 * (randvals(rng, [1, 2, 2], dtype) + 0.2 * np.eye(2)), dtype=mat22, requires_grad=True, device=device
895
- )
896
- m3 = wp.array(
897
- 2 * (randvals(rng, [1, 3, 3], dtype) + 0.2 * np.eye(3)), dtype=mat33, requires_grad=True, device=device
898
- )
899
- m4 = wp.array(
900
- 2 * (randvals(rng, [1, 4, 4], dtype) + 0.2 * np.eye(4)), dtype=mat44, requires_grad=True, device=device
901
- )
902
-
903
- outcomponents = wp.zeros(2 * 2 + 3 * 3 + 4 * 4, dtype=wptype, requires_grad=True, device=device)
904
- out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
905
-
906
- wp.launch(kernel, dim=1, inputs=[m2, m3, m4], outputs=[outcomponents], device=device)
907
-
908
- assert_np_equal(outcomponents.numpy()[:4], 2 * np.linalg.inv(m2.numpy()[0].astype(np.float64)), tol=tol)
909
- assert_np_equal(outcomponents.numpy()[4:13], 2 * np.linalg.inv(m3.numpy()[0].astype(np.float64)), tol=5 * tol)
910
- assert_np_equal(outcomponents.numpy()[13:], 2 * np.linalg.inv(m4.numpy()[0].astype(np.float64)), tol=5 * tol)
911
-
912
- if dtype in np_float_types:
913
- # check gradients:
914
- idx = 0
915
- out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
916
- for dim, input in [(2, m2), (3, m3), (4, m4)]:
917
- minv = np.linalg.inv(input.numpy()[0].astype(np.float64))
918
- for i in range(dim):
919
- for j in range(dim):
920
- tape = wp.Tape()
921
- with tape:
922
- wp.launch(kernel, dim=1, inputs=[m2, m3, m4], outputs=[outcomponents], device=device)
923
- wp.launch(
924
- output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device
925
- )
926
- tape.backward(loss=out)
927
- d = np.zeros((dim, dim))
928
- d[j, i] = 2
929
- assert_np_equal(
930
- tape.gradients[input].numpy()[0], -np.matmul(minv, np.matmul(d, minv)).T, tol=10 * tol
931
- )
932
- tape.zero()
933
-
934
- idx = idx + 1
935
-
936
- # let's check 2x2 using different formulae just for (in)sanity's sake:
937
- m = m2.numpy()[0]
938
-
939
- det = m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]
940
- expected = 2 * np.array([[m[1, 1], -m[0, 1]], [-m[1, 0], m[0, 0]]], dtype=dtype) / det
941
- assert_np_equal(expected, outcomponents.numpy()[:4], tol=tol)
942
-
943
- # 0,0 component is this:
944
- # 2 * m[1,1] / (m[0,0]*m[1,1] - m[1,0] * m[0,1])
945
- assert_np_equal(2 * m[1, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]), outcomponents.numpy()[0], tol=tol)
946
-
947
- tape = wp.Tape()
948
- with tape:
949
- wp.launch(kernel, dim=1, inputs=[m2, m3, m4], outputs=[outcomponents], device=device)
950
- wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, 0], outputs=[out], device=device)
951
-
952
- if dtype in np_float_types:
953
- tape.backward(loss=out)
954
- g = tape.gradients[m2].numpy()[0]
955
- assert_np_equal(-2 * m[1, 1] * m[1, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 0], tol=tol)
956
- assert_np_equal(2 * m[1, 1] * m[0, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 0], tol=tol)
957
- assert_np_equal(-2 * m[0, 1] * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 1], tol=tol)
958
- assert_np_equal(2 * m[1, 1] * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 1], tol=tol)
959
- tape.zero()
960
-
961
- # 0,1 component is this:
962
- # -2 * m[0,1] / (m[0,0]*m[1,1] - m[1,0] * m[0,1])
963
- assert_np_equal(-2 * m[0, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]), outcomponents.numpy()[1], tol=tol)
964
-
965
- tape = wp.Tape()
966
- with tape:
967
- wp.launch(kernel, dim=1, inputs=[m2, m3, m4], outputs=[outcomponents], device=device)
968
- wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, 1], outputs=[out], device=device)
969
- if dtype in np_float_types:
970
- tape.backward(loss=out)
971
- g = tape.gradients[m2].numpy()[0]
972
- assert_np_equal(2 * m[0, 1] * m[1, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 0], tol=tol)
973
- assert_np_equal(-2 * m[0, 1] * m[0, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 0], tol=tol)
974
- assert_np_equal(2 * m[0, 0] * m[0, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 1], tol=tol)
975
- assert_np_equal(-2 * m[1, 1] * m[0, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 1], tol=tol)
976
- tape.zero()
977
-
978
- # 1,0 component is this:
979
- # -2 * m[1,0] / (m[0,0]*m[1,1] - m[1,0] * m[0,1])
980
- assert_np_equal(-2 * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]), outcomponents.numpy()[2], tol=tol)
981
-
982
- tape = wp.Tape()
983
- with tape:
984
- wp.launch(kernel, dim=1, inputs=[m2, m3, m4], outputs=[outcomponents], device=device)
985
- wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, 2], outputs=[out], device=device)
986
-
987
- if dtype in np_float_types:
988
- tape.backward(loss=out)
989
- g = tape.gradients[m2].numpy()[0]
990
- assert_np_equal(2 * m[1, 1] * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 0], tol=tol)
991
- assert_np_equal(-2 * m[0, 0] * m[1, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 0], tol=tol)
992
- assert_np_equal(2 * m[0, 0] * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 1], tol=tol)
993
- assert_np_equal(-2 * m[1, 0] * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 1], tol=tol)
994
- tape.zero()
995
-
996
- # 1,1 component is this:
997
- # 2 * m[0,0] / (m[0,0]*m[1,1] - m[1,0] * m[0,1])
998
- assert_np_equal(2 * m[0, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]), outcomponents.numpy()[3], tol=tol)
999
-
1000
- tape = wp.Tape()
1001
- with tape:
1002
- wp.launch(kernel, dim=1, inputs=[m2, m3, m4], outputs=[outcomponents], device=device)
1003
- wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, 3], outputs=[out], device=device)
1004
-
1005
- if dtype in np_float_types:
1006
- tape.backward(loss=out)
1007
- g = tape.gradients[m2].numpy()[0]
1008
- assert_np_equal(-2 * m[0, 1] * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 0], tol=tol)
1009
- assert_np_equal(2 * m[0, 0] * m[0, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 0], tol=tol)
1010
- assert_np_equal(2 * m[0, 0] * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 1], tol=tol)
1011
- assert_np_equal(-2 * m[0, 0] * m[0, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 1], tol=tol)
1012
- tape.zero()
1013
-
1014
-
1015
- def test_svd(test, device, dtype, register_kernels=False):
1016
- rng = np.random.default_rng(123)
1017
-
1018
- tol = {
1019
- np.float16: 1.0e-3,
1020
- np.float32: 1.0e-6,
1021
- np.float64: 1.0e-6,
1022
- }.get(dtype, 0)
1023
-
1024
- wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
1025
- vec3 = wp.types.vector(length=3, dtype=wptype)
1026
- mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
1027
-
1028
- def check_mat_svd(
1029
- m3: wp.array(dtype=mat33),
1030
- Uout: wp.array(dtype=mat33),
1031
- sigmaout: wp.array(dtype=vec3),
1032
- Vout: wp.array(dtype=mat33),
1033
- outcomponents: wp.array(dtype=wptype),
1034
- ):
1035
- U = mat33()
1036
- sigma = vec3()
1037
- V = mat33()
1038
-
1039
- wp.svd3(m3[0], U, sigma, V)
1040
-
1041
- Uout[0] = U
1042
- sigmaout[0] = sigma
1043
- Vout[0] = V
1044
-
1045
- # multiply outputs by 2 so we've got something to backpropagate:
1046
- idx = 0
1047
- for i in range(3):
1048
- for j in range(3):
1049
- outcomponents[idx] = wptype(2) * U[i, j]
1050
- idx = idx + 1
1051
-
1052
- for i in range(3):
1053
- outcomponents[idx] = wptype(2) * sigma[i]
1054
- idx = idx + 1
1055
-
1056
- for i in range(3):
1057
- for j in range(3):
1058
- outcomponents[idx] = wptype(2) * V[i, j]
1059
- idx = idx + 1
1060
-
1061
- kernel = getkernel(check_mat_svd, suffix=dtype.__name__)
1062
-
1063
- output_select_kernel = get_select_kernel(wptype)
1064
-
1065
- if register_kernels:
1066
- return
1067
-
1068
- m3 = wp.array(randvals(rng, [1, 3, 3], dtype) + np.eye(3), dtype=mat33, requires_grad=True, device=device)
1069
-
1070
- outcomponents = wp.zeros(2 * 3 * 3 + 3, dtype=wptype, requires_grad=True, device=device)
1071
- Uout = wp.zeros(1, dtype=mat33, requires_grad=True, device=device)
1072
- sigmaout = wp.zeros(1, dtype=vec3, requires_grad=True, device=device)
1073
- Vout = wp.zeros(1, dtype=mat33, requires_grad=True, device=device)
1074
-
1075
- wp.launch(kernel, dim=1, inputs=[m3], outputs=[Uout, sigmaout, Vout, outcomponents], device=device)
1076
-
1077
- Uout_np = Uout.numpy()[0].astype(np.float64)
1078
- sigmaout_np = np.diag(sigmaout.numpy()[0].astype(np.float64))
1079
- Vout_np = Vout.numpy()[0].astype(np.float64)
1080
-
1081
- assert_np_equal(
1082
- np.matmul(Uout_np, np.matmul(sigmaout_np, Vout_np.T)), m3.numpy()[0].astype(np.float64), tol=30 * tol
1083
- )
1084
-
1085
- if dtype == np.float16:
1086
- # I'm not even going to bother testing the gradients for float16
1087
- # because the rounding errors are terrible...
1088
- return
1089
-
1090
- # check gradients:
1091
- out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
1092
- idx = 0
1093
- for idx in range(3 * 3 + 3 + 3 * 3):
1094
- tape = wp.Tape()
1095
- with tape:
1096
- wp.launch(kernel, dim=1, inputs=[m3], outputs=[Uout, sigmaout, Vout, outcomponents], device=device)
1097
- wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1098
- tape.backward(out)
1099
- m3grads = 1.0 * tape.gradients[m3].numpy()[0]
1100
-
1101
- tape.zero()
1102
-
1103
- dx = 0.0001
1104
- fdtol = 5.0e-4 if dtype == np.float64 else 2.0e-2
1105
- for ii in range(3):
1106
- for jj in range(3):
1107
- m3test = 1.0 * m3.numpy()
1108
- m3test[0, ii, jj] += dx
1109
- wp.launch(
1110
- kernel,
1111
- dim=1,
1112
- inputs=[wp.array(m3test, dtype=mat33, device=device)],
1113
- outputs=[Uout, sigmaout, Vout, outcomponents],
1114
- device=device,
1115
- )
1116
- wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1117
- plusval = out.numpy()[0]
1118
-
1119
- m3test = 1.0 * m3.numpy()
1120
- m3test[0, ii, jj] -= dx
1121
- wp.launch(
1122
- kernel,
1123
- dim=1,
1124
- inputs=[wp.array(m3test, dtype=mat33, device=device)],
1125
- outputs=[Uout, sigmaout, Vout, outcomponents],
1126
- device=device,
1127
- )
1128
- wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1129
- minusval = out.numpy()[0]
1130
-
1131
- assert_np_equal((plusval - minusval) / (2 * dx), m3grads[ii, jj], tol=fdtol)
1132
-
1133
-
1134
- def test_qr(test, device, dtype, register_kernels=False):
1135
- rng = np.random.default_rng(123)
1136
-
1137
- tol = {
1138
- np.float16: 2.0e-3,
1139
- np.float32: 1.0e-6,
1140
- np.float64: 1.0e-6,
1141
- }.get(dtype, 0)
1142
-
1143
- wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
1144
- mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
1145
-
1146
- def check_mat_qr(
1147
- m3: wp.array(dtype=mat33),
1148
- Qout: wp.array(dtype=mat33),
1149
- Rout: wp.array(dtype=mat33),
1150
- outcomponents: wp.array(dtype=wptype),
1151
- ):
1152
- Q = mat33()
1153
- R = mat33()
1154
-
1155
- wp.qr3(m3[0], Q, R)
1156
-
1157
- Qout[0] = Q
1158
- Rout[0] = R
1159
-
1160
- # multiply outputs by 2 so we've got something to backpropagate:
1161
- idx = 0
1162
- for i in range(3):
1163
- for j in range(3):
1164
- outcomponents[idx] = wptype(2) * Q[i, j]
1165
- idx = idx + 1
1166
-
1167
- for i in range(3):
1168
- for j in range(3):
1169
- outcomponents[idx] = wptype(2) * R[i, j]
1170
- idx = idx + 1
1171
-
1172
- kernel = getkernel(check_mat_qr, suffix=dtype.__name__)
1173
- output_select_kernel = get_select_kernel(wptype)
1174
-
1175
- if register_kernels:
1176
- return
1177
-
1178
- m3 = wp.array(0.5 * (randvals(rng, [1, 3, 3], dtype) + np.eye(3)), dtype=mat33, requires_grad=True, device=device)
1179
-
1180
- outcomponents = wp.zeros(2 * 3 * 3, dtype=wptype, requires_grad=True, device=device)
1181
- Qout = wp.zeros(1, dtype=mat33, requires_grad=True, device=device)
1182
- Rout = wp.zeros(1, dtype=mat33, requires_grad=True, device=device)
1183
-
1184
- wp.launch(kernel, dim=1, inputs=[m3], outputs=[Qout, Rout, outcomponents], device=device)
1185
-
1186
- Qout_np = Qout.numpy()[0].astype(np.float64)
1187
- Rout_np = Rout.numpy()[0].astype(np.float64)
1188
-
1189
- # check it's actually a q and an r:
1190
- assert_np_equal(np.matmul(Qout_np.T, Qout_np), np.eye(3, dtype=np.float64), tol=tol)
1191
- assert_np_equal(Rout_np[1, [0]], np.zeros(1, dtype=np.float64), tol=tol)
1192
- assert_np_equal(Rout_np[2, [0, 1]], np.zeros(2, dtype=np.float64), tol=tol)
1193
-
1194
- # check it's a factorization:
1195
- assert_np_equal(np.matmul(Qout_np, Rout_np), m3.numpy()[0].astype(np.float64), tol=30 * tol)
1196
-
1197
- if dtype == np.float16:
1198
- # I'm not even going to bother testing the gradients for float16
1199
- # because the rounding errors are terrible...
1200
- return
1201
-
1202
- # check gradients:
1203
- out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
1204
- idx = 0
1205
- for idx in range(len(outcomponents)):
1206
- tape = wp.Tape()
1207
- with tape:
1208
- wp.launch(kernel, dim=1, inputs=[m3], outputs=[Qout, Rout, outcomponents], device=device)
1209
- wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1210
- tape.backward(out)
1211
- m3grads = 1.0 * tape.gradients[m3].numpy()[0]
1212
-
1213
- tape.zero()
1214
-
1215
- dx = 0.0001
1216
- fdtol = 5.0e-4 if dtype == np.float64 else 2.0e-2
1217
- for ii in range(3):
1218
- for jj in range(3):
1219
- m3test = 1.0 * m3.numpy()
1220
- m3test[0, ii, jj] += dx
1221
- wp.launch(
1222
- kernel,
1223
- dim=1,
1224
- inputs=[wp.array(m3test, dtype=mat33, device=device)],
1225
- outputs=[Qout, Rout, outcomponents],
1226
- device=device,
1227
- )
1228
- wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1229
- plusval = out.numpy()[0]
1230
-
1231
- m3test = 1.0 * m3.numpy()
1232
- m3test[0, ii, jj] -= dx
1233
- wp.launch(
1234
- kernel,
1235
- dim=1,
1236
- inputs=[wp.array(m3test, dtype=mat33, device=device)],
1237
- outputs=[Qout, Rout, outcomponents],
1238
- device=device,
1239
- )
1240
- wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1241
- minusval = out.numpy()[0]
1242
-
1243
- assert_np_equal((plusval - minusval) / (2 * dx), m3grads[ii, jj], tol=fdtol)
1244
-
1245
-
1246
- def test_eig(test, device, dtype, register_kernels=False):
1247
- rng = np.random.default_rng(123)
1248
-
1249
- tol = {
1250
- np.float16: 4.0e-2,
1251
- np.float32: 1.0e-5,
1252
- np.float64: 1.0e-5,
1253
- }.get(dtype, 0)
1254
-
1255
- wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
1256
- vec3 = wp.types.vector(length=3, dtype=wptype)
1257
- mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
1258
-
1259
- def check_mat_eig(
1260
- m3: wp.array(dtype=mat33),
1261
- Qout: wp.array(dtype=mat33),
1262
- dout: wp.array(dtype=vec3),
1263
- outcomponents: wp.array(dtype=wptype),
1264
- ):
1265
- Q = mat33()
1266
- d = vec3()
1267
-
1268
- wp.eig3(m3[0] + wp.transpose(m3[0]), Q, d)
1269
-
1270
- Qout[0] = Q
1271
- dout[0] = d
1272
-
1273
- # multiply outputs by 2 so we've got something to backpropagate:
1274
- idx = 0
1275
- for i in range(3):
1276
- for j in range(3):
1277
- outcomponents[idx] = wptype(2) * Q[i, j]
1278
- idx = idx + 1
1279
-
1280
- for i in range(3):
1281
- outcomponents[idx] = wptype(2) * d[i]
1282
- idx = idx + 1
1283
-
1284
- kernel = getkernel(check_mat_eig, suffix=dtype.__name__)
1285
- output_select_kernel = get_select_kernel(wptype)
1286
-
1287
- if register_kernels:
1288
- return
1289
-
1290
- m3_np = randvals(rng, [1, 3, 3], dtype) + np.eye(3, dtype=dtype)
1291
- m3 = wp.array(m3_np, dtype=mat33, requires_grad=True, device=device)
1292
-
1293
- outcomponents = wp.zeros(3 * 3 + 3, dtype=wptype, requires_grad=True, device=device)
1294
- Qout = wp.zeros(1, dtype=mat33, requires_grad=True, device=device)
1295
- dout = wp.zeros(1, dtype=vec3, requires_grad=True, device=device)
1296
-
1297
- wp.launch(kernel, dim=1, inputs=[m3], outputs=[Qout, dout, outcomponents], device=device)
1298
-
1299
- Qout_np = Qout.numpy()[0].astype(np.float64)
1300
- dout_np = dout.numpy()[0].astype(np.float64)
1301
- Dout_np = np.diag(dout_np)
1302
-
1303
- # check Q is orthogonal:
1304
- assert_np_equal(np.matmul(Qout_np.T, Qout_np), np.eye(3), tol=tol)
1305
-
1306
- # check Q contains eigenvectors:
1307
- assert_np_equal(np.matmul(Qout_np, np.matmul(Dout_np, Qout_np.T)), (m3_np[0] + m3_np[0].transpose()), tol=tol)
1308
-
1309
- if dtype == np.float16:
1310
- # I'm not even going to bother testing the gradients for float16
1311
- # because the rounding errors are terrible...
1312
- return
1313
-
1314
- # check gradients:
1315
- out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
1316
- idx = 0
1317
- for idx in range(len(outcomponents)):
1318
- tape = wp.Tape()
1319
- with tape:
1320
- wp.launch(kernel, dim=1, inputs=[m3], outputs=[Qout, dout, outcomponents], device=device)
1321
- wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1322
- tape.backward(out)
1323
- m3grads = 1.0 * tape.gradients[m3].numpy()[0]
1324
-
1325
- tape.zero()
1326
-
1327
- dx = 0.0001
1328
- fdtol = 5.0e-4 if dtype == np.float64 else 2.0e-2
1329
- for ii in range(3):
1330
- for jj in range(3):
1331
- m3test = 1.0 * m3.numpy()
1332
- m3test[0, ii, jj] += dx
1333
- wp.launch(
1334
- kernel,
1335
- dim=1,
1336
- inputs=[wp.array(m3test, dtype=mat33, device=device)],
1337
- outputs=[Qout, dout, outcomponents],
1338
- device=device,
1339
- )
1340
- wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1341
- plusval = out.numpy()[0]
1342
-
1343
- m3test = 1.0 * m3.numpy()
1344
- m3test[0, ii, jj] -= dx
1345
- wp.launch(
1346
- kernel,
1347
- dim=1,
1348
- inputs=[wp.array(m3test, dtype=mat33, device=device)],
1349
- outputs=[Qout, dout, outcomponents],
1350
- device=device,
1351
- )
1352
- wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1353
- minusval = out.numpy()[0]
1354
-
1355
- assert_np_equal((plusval - minusval) / (2 * dx), m3grads[ii, jj], tol=fdtol)
1356
-
1357
-
1358
- def test_skew(test, device, dtype, register_kernels=False):
1359
- rng = np.random.default_rng(123)
1360
-
1361
- tol = {
1362
- np.float16: 1.0e-3,
1363
- np.float32: 1.0e-6,
1364
- np.float64: 1.0e-8,
1365
- }.get(dtype, 0)
1366
-
1367
- wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
1368
- vec3 = wp.types.vector(length=3, dtype=wptype)
1369
-
1370
- output_select_kernel = get_select_kernel(wptype)
1371
-
1372
- def check_mat_skew(
1373
- v3: wp.array(dtype=vec3),
1374
- outcomponents: wp.array(dtype=wptype),
1375
- ):
1376
- m3result = wp.skew(v3[0])
1377
-
1378
- # multiply outputs by 2 so we've got something to backpropagate:
1379
- idx = 0
1380
- for i in range(3):
1381
- for j in range(3):
1382
- outcomponents[idx] = wptype(2) * m3result[i, j]
1383
- idx = idx + 1
1384
-
1385
- kernel = getkernel(check_mat_skew, suffix=dtype.__name__)
1386
-
1387
- if register_kernels:
1388
- return
1389
-
1390
- v3 = wp.array(randvals(rng, [1, 3], dtype), dtype=vec3, requires_grad=True, device=device)
1391
-
1392
- outcomponents = wp.zeros(3 * 3, dtype=wptype, requires_grad=True, device=device)
1393
- out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
1394
-
1395
- wp.launch(kernel, dim=1, inputs=[v3], outputs=[outcomponents], device=device)
1396
-
1397
- # make sure it gives you a cross product matrix:
1398
- crossprodmat = outcomponents.numpy().reshape(3, 3)
1399
- v = np.array([1, 0, 0])
1400
- assert_np_equal(
1401
- np.matmul(crossprodmat, np.array([1, 0, 0])).reshape(-1),
1402
- 2 * np.cross(v3.numpy()[0], np.array([1, 0, 0])),
1403
- tol=tol,
1404
- )
1405
- assert_np_equal(
1406
- np.matmul(crossprodmat, np.array([0, 1, 0])).reshape(-1),
1407
- 2 * np.cross(v3.numpy()[0], np.array([0, 1, 0])),
1408
- tol=tol,
1409
- )
1410
- assert_np_equal(
1411
- np.matmul(crossprodmat, np.array([0, 0, 1])).reshape(-1),
1412
- 2 * np.cross(v3.numpy()[0], np.array([0, 0, 1])),
1413
- tol=tol,
1414
- )
1415
-
1416
- # check it another way:
1417
- x0 = v3.numpy()[0, 0]
1418
- x1 = v3.numpy()[0, 1]
1419
- x2 = v3.numpy()[0, 2]
1420
- crossprodmat_expected = np.array(
1421
- [
1422
- [0, -x2, x1],
1423
- [x2, 0, -x0],
1424
- [-x1, x0, 0],
1425
- ],
1426
- dtype=dtype,
1427
- )
1428
- assert_np_equal(crossprodmat, 2 * crossprodmat_expected, tol=tol)
1429
-
1430
- if dtype in np_float_types:
1431
- idx = 0
1432
- out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
1433
-
1434
- for i in range(3):
1435
- for j in range(3):
1436
- tape = wp.Tape()
1437
- with tape:
1438
- wp.launch(kernel, dim=1, inputs=[v3], outputs=[outcomponents], device=device)
1439
- wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1440
- tape.backward(loss=out)
1441
- if i == j:
1442
- assert_np_equal(tape.gradients[v3].numpy()[0], np.zeros(3))
1443
- elif [i, j] == [0, 1]:
1444
- assert_np_equal(tape.gradients[v3].numpy()[0], np.array([0, 0, -2]))
1445
- elif [i, j] == [1, 0]:
1446
- assert_np_equal(tape.gradients[v3].numpy()[0], np.array([0, 0, 2]))
1447
- elif [i, j] == [0, 2]:
1448
- assert_np_equal(tape.gradients[v3].numpy()[0], np.array([0, 2, 0]))
1449
- elif [i, j] == [2, 0]:
1450
- assert_np_equal(tape.gradients[v3].numpy()[0], np.array([0, -2, 0]))
1451
- elif [i, j] == [1, 2]:
1452
- assert_np_equal(tape.gradients[v3].numpy()[0], np.array([-2, 0, 0]))
1453
- elif [i, j] == [2, 1]:
1454
- assert_np_equal(tape.gradients[v3].numpy()[0], np.array([2, 0, 0]))
1455
- tape.zero()
1456
-
1457
- idx = idx + 1
1458
-
1459
-
1460
- def test_transform_point(test, device, dtype, register_kernels=False):
1461
- rng = np.random.default_rng(123)
1462
-
1463
- tol = {
1464
- np.float16: 5.0e-3,
1465
- np.float32: 1.0e-6,
1466
- np.float64: 1.0e-8,
1467
- }.get(dtype, 0)
1468
-
1469
- wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
1470
- vec3 = wp.types.vector(length=3, dtype=wptype)
1471
- mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
1472
-
1473
- output_select_kernel = get_select_kernel(wptype)
1474
-
1475
- def check_mat_transform_point(
1476
- v3: wp.array(dtype=vec3),
1477
- m4: wp.array(dtype=mat44),
1478
- outcomponents: wp.array(dtype=wptype),
1479
- ):
1480
- # multiply outputs by 2 so we've got something to backpropagate:
1481
- presult = wptype(2) * wp.transform_point(m4[0], v3[0])
1482
-
1483
- outcomponents[0] = presult[0]
1484
- outcomponents[1] = presult[1]
1485
- outcomponents[2] = presult[2]
1486
-
1487
- kernel = getkernel(check_mat_transform_point, suffix=dtype.__name__)
1488
-
1489
- if register_kernels:
1490
- return
1491
-
1492
- v3 = wp.array(randvals(rng, [1, 3], dtype), dtype=vec3, requires_grad=True, device=device)
1493
- m4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
1494
-
1495
- outcomponents = wp.zeros(3, dtype=wptype, requires_grad=True, device=device)
1496
- out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
1497
-
1498
- wp.launch(kernel, dim=1, inputs=[v3, m4], outputs=[outcomponents], device=device)
1499
-
1500
- v3homog = np.ones(4, dtype=dtype)
1501
- v3homog[:3] = v3.numpy()[0]
1502
- assert_np_equal(outcomponents.numpy(), 2 * np.matmul(m4.numpy()[0], v3homog)[:3], tol=10 * tol)
1503
-
1504
- if dtype in np_float_types:
1505
- for j in range(3):
1506
- tape = wp.Tape()
1507
- with tape:
1508
- wp.launch(kernel, dim=1, inputs=[v3, m4], outputs=[outcomponents], device=device)
1509
- wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, j], outputs=[out], device=device)
1510
- tape.backward(loss=out)
1511
-
1512
- assert_np_equal(2 * m4.numpy()[0, j, :3], tape.gradients[v3].numpy(), tol=tol)
1513
- expected = np.zeros((4, 4), dtype=dtype)
1514
- expected[j, :3] = 2 * v3.numpy()
1515
- expected[j, 3] = 2
1516
- assert_np_equal(tape.gradients[m4].numpy(), expected, tol=tol)
1517
-
1518
- tape.zero()
1519
-
1520
-
1521
- def test_transform_vector(test, device, dtype, register_kernels=False):
1522
- rng = np.random.default_rng(123)
1523
-
1524
- tol = {
1525
- np.float16: 5.0e-3,
1526
- np.float32: 1.0e-6,
1527
- np.float64: 1.0e-8,
1528
- }.get(dtype, 0)
1529
-
1530
- wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
1531
- vec3 = wp.types.vector(length=3, dtype=wptype)
1532
- mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
1533
-
1534
- output_select_kernel = get_select_kernel(wptype)
1535
-
1536
- def check_mat_transform_vector(
1537
- v3: wp.array(dtype=vec3),
1538
- m4: wp.array(dtype=mat44),
1539
- outcomponents: wp.array(dtype=wptype),
1540
- ):
1541
- # multiply outputs by 2 so we've got something to backpropagate:
1542
- presult = wptype(2) * wp.transform_vector(m4[0], v3[0])
1543
-
1544
- outcomponents[0] = presult[0]
1545
- outcomponents[1] = presult[1]
1546
- outcomponents[2] = presult[2]
1547
-
1548
- kernel = getkernel(check_mat_transform_vector, suffix=dtype.__name__)
1549
-
1550
- if register_kernels:
1551
- return
1552
-
1553
- v3 = wp.array(randvals(rng, [1, 3], dtype), dtype=vec3, requires_grad=True, device=device)
1554
- m4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
1555
-
1556
- outcomponents = wp.zeros(3, dtype=wptype, requires_grad=True, device=device)
1557
- out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
1558
-
1559
- wp.launch(kernel, dim=1, inputs=[v3, m4], outputs=[outcomponents], device=device)
1560
-
1561
- v3homog = np.zeros(4, dtype=dtype)
1562
- v3homog[:3] = v3.numpy()[0]
1563
- assert_np_equal(outcomponents.numpy(), 2 * np.matmul(m4.numpy()[0], v3homog)[:3], tol=10 * tol)
1564
-
1565
- if dtype in np_float_types:
1566
- for j in range(3):
1567
- tape = wp.Tape()
1568
- with tape:
1569
- wp.launch(kernel, dim=1, inputs=[v3, m4], outputs=[outcomponents], device=device)
1570
- wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, j], outputs=[out], device=device)
1571
- tape.backward(loss=out)
1572
-
1573
- assert_np_equal(2 * m4.numpy()[0, j, :3], tape.gradients[v3].numpy(), tol=tol)
1574
- expected = np.zeros((4, 4), dtype=dtype)
1575
- expected[j, :3] = 2 * v3.numpy()
1576
- assert_np_equal(tape.gradients[m4].numpy(), expected, tol=tol)
1577
-
1578
- tape.zero()
1579
-
1580
-
1581
- # Test matrix constructors using explicit type (float16)
1582
- # note that these tests are specifically not using generics / closure
1583
- # args to create kernels dynamically (like the rest of this file)
1584
- # as those use different code paths to resolve arg types which
1585
- # has lead to regressions.
1586
- @wp.kernel
1587
- def test_constructors_explicit_precision():
1588
- # construction for custom matrix types
1589
- eye = wp.identity(dtype=wp.float16, n=2)
1590
- zeros = wp.matrix(shape=(2, 2), dtype=wp.float16)
1591
- custom = wp.matrix(wp.float16(0.0), wp.float16(1.0), wp.float16(2.0), wp.float16(3.0), shape=(2, 2))
1592
-
1593
- for i in range(2):
1594
- for j in range(2):
1595
- if i == j:
1596
- wp.expect_eq(eye[i, j], wp.float16(1.0))
1597
- else:
1598
- wp.expect_eq(eye[i, j], wp.float16(0.0))
1599
-
1600
- wp.expect_eq(zeros[i, j], wp.float16(0.0))
1601
- wp.expect_eq(custom[i, j], wp.float16(i) * wp.float16(2.0) + wp.float16(j))
1602
-
1603
-
1604
- mat32d = wp.mat(shape=(3, 2), dtype=wp.float64)
1605
-
1606
-
1607
- @wp.kernel
1608
- def test_matrix_constructor_value_func():
1609
- a = wp.mat22()
1610
- b = wp.matrix(a, shape=(2, 2))
1611
- c = mat32d()
1612
- d = mat32d(c, shape=(3, 2))
1613
- e = mat32d(wp.float64(1.0), wp.float64(2.0), wp.float64(1.0), wp.float64(2.0), wp.float64(1.0), wp.float64(2.0))
1614
- f = mat32d(
1615
- wp.vec3d(wp.float64(1.0), wp.float64(2.0), wp.float64(3.0)),
1616
- wp.vec3d(wp.float64(1.0), wp.float64(2.0), wp.float64(3.0)),
1617
- )
1618
-
1619
-
1620
- # Same as above but with a default (float/int) type
1621
- # which tests some different code paths that
1622
- # need to ensure types are correctly canonicalized
1623
- # during codegen
1624
- @wp.kernel
1625
- def test_constructors_default_precision():
1626
- # construction for default (float) matrix types
1627
- eye = wp.identity(dtype=float, n=2)
1628
- zeros = wp.matrix(shape=(2, 2), dtype=float)
1629
- custom = wp.matrix(0.0, 1.0, 2.0, 3.0, shape=(2, 2))
1630
-
1631
- for i in range(2):
1632
- for j in range(2):
1633
- if i == j:
1634
- wp.expect_eq(eye[i, j], 1.0)
1635
- else:
1636
- wp.expect_eq(eye[i, j], 0.0)
1637
-
1638
- wp.expect_eq(zeros[i, j], 0.0)
1639
- wp.expect_eq(custom[i, j], float(i) * 2.0 + float(j))
1640
-
1641
-
1642
- @wp.kernel
1643
- def test_matrix_mutation(expected: wp.types.matrix(shape=(10, 3), dtype=float)):
1644
- m = wp.matrix(shape=(10, 3), dtype=float)
1645
-
1646
- # test direct element indexing
1647
- m[0, 0] = 1.0
1648
- m[0, 1] = 2.0
1649
- m[0, 2] = 3.0
1650
-
1651
- # The nested indexing (matrix->vector->scalar) below does not
1652
- # currently modify m because m[0] returns row vector by
1653
- # value rather than reference, this is different from NumPy
1654
- # which always returns by ref. Not clear how we can support
1655
- # this as well as auto-diff.
1656
-
1657
- # m[0][1] = 2.0
1658
- # m[0][2] = 3.0
1659
-
1660
- # test setting rows
1661
- for i in range(1, 10):
1662
- m[i] = m[i - 1] + wp.vec3(1.0, 2.0, 3.0)
1663
-
1664
- wp.expect_eq(m, expected)
1665
-
1666
-
1667
- CONSTANT_SHAPE_ROWS = wp.constant(10)
1668
- CONSTANT_SHAPE_COLS = wp.constant(10)
1669
-
1670
-
1671
- # tests that we can use global constants in shape keyword argument
1672
- # for matrix constructor
1673
- @wp.kernel
1674
- def test_constructors_constant_shape():
1675
- m = wp.matrix(shape=(CONSTANT_SHAPE_ROWS, CONSTANT_SHAPE_COLS), dtype=float)
1676
-
1677
- for i in range(CONSTANT_SHAPE_ROWS):
1678
- for j in range(CONSTANT_SHAPE_COLS):
1679
- m[i, j] = float(i * j)
1680
-
1681
-
1682
- devices = get_test_devices()
1683
-
1684
-
1685
- class TestMat(unittest.TestCase):
1686
- pass
1687
-
1688
-
1689
- add_kernel_test(TestMat, test_constructors_explicit_precision, dim=1, devices=devices)
1690
- add_kernel_test(TestMat, test_constructors_default_precision, dim=1, devices=devices)
1691
- add_kernel_test(TestMat, test_constructors_constant_shape, dim=1, devices=devices)
1692
- add_kernel_test(TestMat, test_matrix_constructor_value_func, dim=1, devices=devices)
1693
-
1694
- mat103 = wp.types.matrix(shape=(10, 3), dtype=float)
1695
- add_kernel_test(
1696
- TestMat,
1697
- test_matrix_mutation,
1698
- dim=1,
1699
- inputs=[
1700
- mat103(
1701
- 1.0,
1702
- 2.0,
1703
- 3.0,
1704
- 2.0,
1705
- 4.0,
1706
- 6.0,
1707
- 3.0,
1708
- 6.0,
1709
- 9.0,
1710
- 4.0,
1711
- 8.0,
1712
- 12.0,
1713
- 5.0,
1714
- 10.0,
1715
- 15.0,
1716
- 6.0,
1717
- 12.0,
1718
- 18.0,
1719
- 7.0,
1720
- 14.0,
1721
- 21.0,
1722
- 8.0,
1723
- 16.0,
1724
- 24.0,
1725
- 9.0,
1726
- 18.0,
1727
- 27.0,
1728
- 10.0,
1729
- 20.0,
1730
- 30.0,
1731
- )
1732
- ],
1733
- devices=devices,
1734
- )
1735
-
1736
- for dtype in np_signed_int_types + np_float_types:
1737
- add_function_test_register_kernel(
1738
- TestMat, f"test_negation_{dtype.__name__}", test_negation, devices=devices, dtype=dtype
1739
- )
1740
- add_function_test_register_kernel(
1741
- TestMat, f"test_subtraction_{dtype.__name__}", test_subtraction, devices=devices, dtype=dtype
1742
- )
1743
-
1744
- add_function_test(
1745
- TestMat,
1746
- "test_anon_constructor_error_shape_keyword_missing",
1747
- test_anon_constructor_error_shape_keyword_missing,
1748
- devices=devices,
1749
- )
1750
- add_function_test(
1751
- TestMat,
1752
- "test_anon_constructor_error_dtype_keyword_missing",
1753
- test_anon_constructor_error_dtype_keyword_missing,
1754
- devices=devices,
1755
- )
1756
- add_function_test(
1757
- TestMat,
1758
- "test_anon_constructor_error_shape_mismatch",
1759
- test_anon_constructor_error_shape_mismatch,
1760
- devices=devices,
1761
- )
1762
- add_function_test(
1763
- TestMat,
1764
- "test_anon_constructor_error_invalid_arg_count",
1765
- test_anon_constructor_error_invalid_arg_count,
1766
- devices=devices,
1767
- )
1768
- add_function_test(
1769
- TestMat,
1770
- "test_tpl_constructor_error_incompatible_sizes",
1771
- test_tpl_constructor_error_incompatible_sizes,
1772
- devices=devices,
1773
- )
1774
- add_function_test(
1775
- TestMat,
1776
- "test_tpl_constructor_error_invalid_scalar_type",
1777
- test_tpl_constructor_error_invalid_scalar_type,
1778
- devices=devices,
1779
- )
1780
- add_function_test(
1781
- TestMat,
1782
- "test_tpl_constructor_error_invalid_vector_count",
1783
- test_tpl_constructor_error_invalid_vector_count,
1784
- devices=devices,
1785
- )
1786
- add_function_test(
1787
- TestMat,
1788
- "test_tpl_constructor_error_invalid_vector_shape",
1789
- test_tpl_constructor_error_invalid_vector_shape,
1790
- devices=devices,
1791
- )
1792
- add_function_test(
1793
- TestMat,
1794
- "test_tpl_constructor_error_invalid_arg_count",
1795
- test_tpl_constructor_error_invalid_arg_count,
1796
- devices=devices,
1797
- )
1798
- add_function_test(TestMat, "test_tpl_ops_with_anon", test_tpl_ops_with_anon)
1799
-
1800
- for dtype in np_float_types:
1801
- add_function_test(
1802
- TestMat, f"test_py_arithmetic_ops_{dtype.__name__}", test_py_arithmetic_ops, devices=None, dtype=dtype
1803
- )
1804
- add_function_test_register_kernel(
1805
- TestMat, f"test_quat_constructor_{dtype.__name__}", test_quat_constructor, devices=devices, dtype=dtype
1806
- )
1807
- add_function_test_register_kernel(
1808
- TestMat, f"test_inverse_{dtype.__name__}", test_inverse, devices=devices, dtype=dtype
1809
- )
1810
- add_function_test_register_kernel(TestMat, f"test_svd_{dtype.__name__}", test_svd, devices=devices, dtype=dtype)
1811
- add_function_test_register_kernel(TestMat, f"test_qr_{dtype.__name__}", test_qr, devices=devices, dtype=dtype)
1812
- add_function_test_register_kernel(TestMat, f"test_eig_{dtype.__name__}", test_eig, devices=devices, dtype=dtype)
1813
- add_function_test_register_kernel(
1814
- TestMat, f"test_transform_point_{dtype.__name__}", test_transform_point, devices=devices, dtype=dtype
1815
- )
1816
- add_function_test_register_kernel(
1817
- TestMat, f"test_transform_vector_{dtype.__name__}", test_transform_vector, devices=devices, dtype=dtype
1818
- )
1819
- add_function_test_register_kernel(
1820
- TestMat, f"test_determinant_{dtype.__name__}", test_determinant, devices=devices, dtype=dtype
1821
- )
1822
- add_function_test_register_kernel(TestMat, f"test_skew_{dtype.__name__}", test_skew, devices=devices, dtype=dtype)
1823
-
1824
-
1825
- if __name__ == "__main__":
1826
- wp.build.clear_kernel_cache()
1827
- unittest.main(verbosity=2, failfast=True)
1
+ # Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
2
+ # NVIDIA CORPORATION and its licensors retain all intellectual property
3
+ # and proprietary rights in and to this software, related documentation
4
+ # and any modifications thereto. Any use, reproduction, disclosure or
5
+ # distribution of this software and related documentation without an express
6
+ # license agreement from NVIDIA CORPORATION is strictly prohibited.
7
+
8
+ import unittest
9
+
10
+ import numpy as np
11
+
12
+ import warp as wp
13
+ from warp.tests.unittest_utils import *
14
+
15
+ wp.init()
16
+
17
+ np_signed_int_types = [
18
+ np.int8,
19
+ np.int16,
20
+ np.int32,
21
+ np.int64,
22
+ np.byte,
23
+ ]
24
+
25
+ np_float_types = [np.float16, np.float32, np.float64]
26
+
27
+
28
+ def randvals(rng, shape, dtype):
29
+ if dtype in np_float_types:
30
+ return rng.standard_normal(size=shape).astype(dtype)
31
+ elif dtype in [np.int8, np.uint8, np.byte, np.ubyte]:
32
+ return rng.integers(1, high=3, size=shape, dtype=dtype)
33
+ return rng.integers(1, high=5, size=shape, dtype=dtype)
34
+
35
+
36
+ kernel_cache = {}
37
+
38
+
39
+ def getkernel(func, suffix=""):
40
+ key = func.__name__ + "_" + suffix
41
+ if key not in kernel_cache:
42
+ kernel_cache[key] = wp.Kernel(func=func, key=key)
43
+ return kernel_cache[key]
44
+
45
+
46
+ def get_select_kernel(dtype):
47
+ def output_select_kernel_fn(
48
+ input: wp.array(dtype=dtype),
49
+ index: int,
50
+ out: wp.array(dtype=dtype),
51
+ ):
52
+ out[0] = input[index]
53
+
54
+ return getkernel(output_select_kernel_fn, suffix=dtype.__name__)
55
+
56
+
57
+ def test_anon_constructor_error_shape_keyword_missing(test, device):
58
+ @wp.kernel
59
+ def kernel():
60
+ wp.matrix(1.0, 2.0, 3.0)
61
+
62
+ with test.assertRaisesRegex(
63
+ RuntimeError,
64
+ r"shape keyword must be specified when calling matrix\(\) function$",
65
+ ):
66
+ wp.launch(
67
+ kernel,
68
+ dim=1,
69
+ inputs=[],
70
+ device=device,
71
+ )
72
+
73
+
74
+ def test_anon_constructor_error_dtype_keyword_missing(test, device):
75
+ @wp.kernel
76
+ def kernel():
77
+ wp.matrix(shape=(3, 3))
78
+
79
+ with test.assertRaisesRegex(
80
+ RuntimeError,
81
+ r"matrix\(\) must have dtype as a keyword argument if it has no " r"positional arguments$",
82
+ ):
83
+ wp.launch(
84
+ kernel,
85
+ dim=1,
86
+ inputs=[],
87
+ device=device,
88
+ )
89
+
90
+
91
+ def test_anon_constructor_error_shape_mismatch(test, device):
92
+ @wp.kernel
93
+ def kernel():
94
+ wp.matrix(
95
+ wp.matrix(shape=(1, 2), dtype=float),
96
+ shape=(3, 4),
97
+ dtype=float,
98
+ )
99
+
100
+ with test.assertRaisesRegex(
101
+ RuntimeError,
102
+ r"Incompatible matrix sizes for casting copy constructor, " r"\(3, 4\) vs \(1, 2\)$",
103
+ ):
104
+ wp.launch(
105
+ kernel,
106
+ dim=1,
107
+ inputs=[],
108
+ device=device,
109
+ )
110
+
111
+
112
+ def test_anon_constructor_error_invalid_arg_count(test, device):
113
+ @wp.kernel
114
+ def kernel():
115
+ wp.matrix(1.0, 2.0, 3.0, shape=(2, 2), dtype=float)
116
+
117
+ with test.assertRaisesRegex(
118
+ RuntimeError,
119
+ r"Wrong number of arguments for matrix\(\) function, must initialize "
120
+ r"with either a scalar value, or m\*n values$",
121
+ ):
122
+ wp.launch(
123
+ kernel,
124
+ dim=1,
125
+ inputs=[],
126
+ device=device,
127
+ )
128
+
129
+
130
+ def test_tpl_constructor_error_incompatible_sizes(test, device):
131
+ @wp.kernel
132
+ def kernel():
133
+ wp.mat33(wp.mat22(1.0, 2.0, 3.0, 4.0))
134
+
135
+ with test.assertRaisesRegex(
136
+ RuntimeError,
137
+ r"Incompatible matrix sizes for casting copy constructor, " r"\(3, 3\) vs \(2, 2\)$",
138
+ ):
139
+ wp.launch(
140
+ kernel,
141
+ dim=1,
142
+ inputs=[],
143
+ device=device,
144
+ )
145
+
146
+
147
+ def test_tpl_constructor_error_invalid_scalar_type(test, device):
148
+ @wp.kernel
149
+ def kernel():
150
+ wp.mat22(1, 2, 3, 4)
151
+
152
+ with test.assertRaisesRegex(
153
+ RuntimeError,
154
+ r"Wrong scalar type for mat 2,2,<class 'warp.types.float32'> constructor$",
155
+ ):
156
+ wp.launch(
157
+ kernel,
158
+ dim=1,
159
+ inputs=[],
160
+ device=device,
161
+ )
162
+
163
+
164
+ def test_tpl_constructor_error_invalid_vector_count(test, device):
165
+ @wp.kernel
166
+ def kernel():
167
+ wp.mat22(wp.vec3(1.0, 2.0, 3.0))
168
+
169
+ with test.assertRaisesRegex(
170
+ RuntimeError,
171
+ r"Wrong number of vectors when attempting to construct a matrix " r"with column vectors$",
172
+ ):
173
+ wp.launch(
174
+ kernel,
175
+ dim=1,
176
+ inputs=[],
177
+ device=device,
178
+ )
179
+
180
+
181
+ def test_tpl_constructor_error_invalid_vector_shape(test, device):
182
+ @wp.kernel
183
+ def kernel():
184
+ wp.mat22(wp.vec3(1.0, 2.0, 3.0), wp.vec3(4.0, 5.0, 6.0))
185
+
186
+ with test.assertRaisesRegex(
187
+ RuntimeError,
188
+ r"Wrong vector row count when attempting to construct a matrix " r"with column vectors$",
189
+ ):
190
+ wp.launch(
191
+ kernel,
192
+ dim=1,
193
+ inputs=[],
194
+ device=device,
195
+ )
196
+
197
+
198
+ def test_tpl_constructor_error_invalid_arg_count(test, device):
199
+ @wp.kernel
200
+ def kernel():
201
+ wp.mat22(1.0, 2.0, 3.0)
202
+
203
+ with test.assertRaisesRegex(
204
+ RuntimeError,
205
+ r"Wrong number of scalars when attempting to construct a matrix " r"from a list of components$",
206
+ ):
207
+ wp.launch(
208
+ kernel,
209
+ dim=1,
210
+ inputs=[],
211
+ device=device,
212
+ )
213
+
214
+
215
+ def test_py_arithmetic_ops(test, device, dtype):
216
+ wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
217
+
218
+ def make_mat(*args):
219
+ if wptype in wp.types.int_types:
220
+ # Cast to the correct integer type to simulate wrapping.
221
+ return tuple(tuple(wptype._type_(x).value for x in row) for row in args)
222
+
223
+ return args
224
+
225
+ def make_vec(*args):
226
+ if wptype in wp.types.int_types:
227
+ # Cast to the correct integer type to simulate wrapping.
228
+ return tuple(wptype._type_(x).value for x in args)
229
+
230
+ return args
231
+
232
+ mat_cls = wp.mat((3, 3), wptype)
233
+ vec_cls = wp.vec(3, wptype)
234
+
235
+ m = mat_cls(((-1, 2, 3), (4, -5, 6), (7, 8, -9)))
236
+ test.assertSequenceEqual(+m, make_mat((-1, 2, 3), (4, -5, 6), (7, 8, -9)))
237
+ test.assertSequenceEqual(-m, make_mat((1, -2, -3), (-4, 5, -6), (-7, -8, 9)))
238
+ test.assertSequenceEqual(m + mat_cls((5, 5, 5) * 3), make_mat((4, 7, 8), (9, 0, 11), (12, 13, -4)))
239
+ test.assertSequenceEqual(m - mat_cls((5, 5, 5) * 3), make_mat((-6, -3, -2), (-1, -10, 1), (2, 3, -14)))
240
+ test.assertSequenceEqual(m * vec_cls(5, 5, 5), make_vec(20, 25, 30))
241
+ test.assertSequenceEqual(m @ vec_cls(5, 5, 5), make_vec(20, 25, 30))
242
+ test.assertSequenceEqual(vec_cls(5, 5, 5) * m, make_vec(50, 25, 0))
243
+ test.assertSequenceEqual(vec_cls(5, 5, 5) @ m, make_vec(50, 25, 0))
244
+
245
+ m = mat_cls(((2, 4, 6), (8, 10, 12), (14, 16, 18)))
246
+ test.assertSequenceEqual(m * wptype(2), make_mat((4, 8, 12), (16, 20, 24), (28, 32, 36)))
247
+ test.assertSequenceEqual(wptype(2) * m, make_mat((4, 8, 12), (16, 20, 24), (28, 32, 36)))
248
+ test.assertSequenceEqual(m / wptype(2), make_mat((1, 2, 3), (4, 5, 6), (7, 8, 9)))
249
+ test.assertSequenceEqual(wptype(5040) / m, make_mat((2520, 1260, 840), (630, 504, 420), (360, 315, 280)))
250
+ test.assertSequenceEqual(m * vec_cls(5, 5, 5), make_vec(60, 150, 240))
251
+ test.assertSequenceEqual(m @ vec_cls(5, 5, 5), make_vec(60, 150, 240))
252
+ test.assertSequenceEqual(vec_cls(5, 5, 5) * m, make_vec(120, 150, 180))
253
+ test.assertSequenceEqual(vec_cls(5, 5, 5) @ m, make_vec(120, 150, 180))
254
+
255
+
256
+ def test_quat_constructor(test, device, dtype, register_kernels=False):
257
+ rng = np.random.default_rng(123)
258
+
259
+ tol = {
260
+ np.float16: 1.0e-3,
261
+ np.float32: 1.0e-6,
262
+ np.float64: 1.0e-8,
263
+ }.get(dtype, 0)
264
+
265
+ wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
266
+ mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
267
+ vec4 = wp.types.vector(length=4, dtype=wptype)
268
+ vec3 = wp.types.vector(length=3, dtype=wptype)
269
+ quat = wp.types.quaternion(dtype=wptype)
270
+
271
+ output_select_kernel = get_select_kernel(wptype)
272
+
273
+ def check_mat_quat_constructor(
274
+ p: wp.array(dtype=vec3),
275
+ r: wp.array(dtype=quat),
276
+ s: wp.array(dtype=vec3),
277
+ outcomponents: wp.array(dtype=wptype),
278
+ outcomponents_alt: wp.array(dtype=wptype),
279
+ ):
280
+ m = mat44(p[0], r[0], s[0])
281
+
282
+ R = wp.transpose(wp.quat_to_matrix(r[0]))
283
+ c0 = s[0][0] * R[0]
284
+ c1 = s[0][1] * R[1]
285
+ c2 = s[0][2] * R[2]
286
+ m_alt = mat44(
287
+ vec4(c0[0], c0[1], c0[2], wptype(0.0)),
288
+ vec4(c1[0], c1[1], c1[2], wptype(0.0)),
289
+ vec4(c2[0], c2[1], c2[2], wptype(0.0)),
290
+ vec4(p[0][0], p[0][1], p[0][2], wptype(1.0)),
291
+ )
292
+
293
+ idx = 0
294
+ for i in range(4):
295
+ for j in range(4):
296
+ outcomponents[idx] = m[i, j]
297
+ outcomponents_alt[idx] = m_alt[i, j]
298
+ idx = idx + 1
299
+
300
+ kernel = getkernel(check_mat_quat_constructor, suffix=dtype.__name__)
301
+
302
+ if register_kernels:
303
+ return
304
+
305
+ # translation:
306
+ p = wp.array(rng.standard_normal(size=(1, 3)).astype(dtype), dtype=vec3, requires_grad=True, device=device)
307
+
308
+ # generate a normalized quaternion for the rotation:
309
+ r = rng.standard_normal(size=(1, 4))
310
+ r /= np.linalg.norm(r)
311
+ r = wp.array(r.astype(dtype), dtype=quat, requires_grad=True, device=device)
312
+
313
+ # scale:
314
+ s = wp.array(rng.standard_normal(size=(1, 3)).astype(dtype), dtype=vec3, requires_grad=True, device=device)
315
+
316
+ # just going to generate the matrix using the constructor, then
317
+ # more manually, and make sure the values/gradients are the same:
318
+ outcomponents = wp.zeros(4 * 4, dtype=wptype, requires_grad=True, device=device)
319
+ outcomponents_alt = wp.zeros(4 * 4, dtype=wptype, requires_grad=True, device=device)
320
+ wp.launch(kernel, dim=1, inputs=[p, r, s], outputs=[outcomponents, outcomponents_alt], device=device)
321
+ assert_np_equal(outcomponents.numpy(), outcomponents_alt.numpy(), tol=1.0e-6)
322
+
323
+ idx = 0
324
+ out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
325
+ out_alt = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
326
+ for _i in range(4):
327
+ for _j in range(4):
328
+ tape = wp.Tape()
329
+ with tape:
330
+ wp.launch(kernel, dim=1, inputs=[p, r, s], outputs=[outcomponents, outcomponents_alt], device=device)
331
+ wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
332
+ wp.launch(
333
+ output_select_kernel, dim=1, inputs=[outcomponents_alt, idx], outputs=[out_alt], device=device
334
+ )
335
+
336
+ tape.backward(loss=out)
337
+ p_grad = 1.0 * tape.gradients[p].numpy()[0]
338
+ r_grad = 1.0 * tape.gradients[r].numpy()[0]
339
+ s_grad = 1.0 * tape.gradients[s].numpy()[0]
340
+ tape.zero()
341
+
342
+ tape.backward(loss=out_alt)
343
+ p_grad_alt = 1.0 * tape.gradients[p].numpy()[0]
344
+ r_grad_alt = 1.0 * tape.gradients[r].numpy()[0]
345
+ s_grad_alt = 1.0 * tape.gradients[s].numpy()[0]
346
+ tape.zero()
347
+
348
+ assert_np_equal(p_grad, p_grad_alt, tol=tol)
349
+ assert_np_equal(r_grad, r_grad_alt, tol=tol)
350
+ assert_np_equal(s_grad, s_grad_alt, tol=tol)
351
+
352
+ idx = idx + 1
353
+
354
+
355
+ def test_negation(test, device, dtype, register_kernels=False):
356
+ rng = np.random.default_rng(123)
357
+
358
+ tol = {
359
+ np.float16: 1.0e-2,
360
+ np.float32: 1.0e-6,
361
+ np.float64: 1.0e-8,
362
+ }.get(dtype, 0)
363
+
364
+ wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
365
+ mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
366
+ mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
367
+ mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
368
+ mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
369
+
370
+ output_select_kernel = get_select_kernel(wptype)
371
+
372
+ def check_mat_negation(
373
+ m2: wp.array(dtype=mat22),
374
+ m3: wp.array(dtype=mat33),
375
+ m4: wp.array(dtype=mat44),
376
+ m5: wp.array(dtype=mat55),
377
+ outcomponents: wp.array(dtype=wptype),
378
+ ):
379
+ mat2 = -m2[0]
380
+ mat3 = -m3[0]
381
+ mat4 = -m4[0]
382
+ mat5 = -m5[0]
383
+
384
+ # multiply outputs by 2 so we've got something to backpropagate:
385
+ idx = 0
386
+ for i in range(2):
387
+ for j in range(2):
388
+ outcomponents[idx] = wptype(2) * mat2[i, j]
389
+ idx = idx + 1
390
+
391
+ for i in range(3):
392
+ for j in range(3):
393
+ outcomponents[idx] = wptype(2) * mat3[i, j]
394
+ idx = idx + 1
395
+
396
+ for i in range(4):
397
+ for j in range(4):
398
+ outcomponents[idx] = wptype(2) * mat4[i, j]
399
+ idx = idx + 1
400
+
401
+ for i in range(5):
402
+ for j in range(5):
403
+ outcomponents[idx] = wptype(2) * mat5[i, j]
404
+ idx = idx + 1
405
+
406
+ kernel = getkernel(check_mat_negation, suffix=dtype.__name__)
407
+
408
+ if register_kernels:
409
+ return
410
+
411
+ m2 = wp.array(randvals(rng, [1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
412
+ m3 = wp.array(randvals(rng, [1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
413
+ m4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
414
+ m5 = wp.array(randvals(rng, [1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
415
+ outcomponents = wp.zeros(2 * 2 + 3 * 3 + 4 * 4 + 5 * 5, dtype=wptype, requires_grad=True, device=device)
416
+
417
+ wp.launch(kernel, dim=1, inputs=[m2, m3, m4, m5], outputs=[outcomponents], device=device)
418
+
419
+ assert_np_equal(outcomponents.numpy()[:4], -2 * m2.numpy().reshape(-1), tol=tol)
420
+ assert_np_equal(outcomponents.numpy()[4:13], -2 * m3.numpy().reshape(-1), tol=tol)
421
+ assert_np_equal(outcomponents.numpy()[13:29], -2 * m4.numpy().reshape(-1), tol=tol)
422
+ assert_np_equal(outcomponents.numpy()[29:54], -2 * m5.numpy().reshape(-1), tol=tol)
423
+
424
+ if dtype in np_float_types:
425
+ idx = 0
426
+ out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
427
+ for dim, input in [(2, m2), (3, m3), (4, m4), (5, m5)]:
428
+ for i in range(dim):
429
+ for j in range(dim):
430
+ tape = wp.Tape()
431
+ with tape:
432
+ wp.launch(kernel, dim=1, inputs=[m2, m3, m4, m5], outputs=[outcomponents], device=device)
433
+ wp.launch(
434
+ output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device
435
+ )
436
+ tape.backward(loss=out)
437
+ expectedresult = np.zeros((dim, dim), dtype=dtype)
438
+ expectedresult[i, j] = -2
439
+ assert_np_equal(tape.gradients[input].numpy()[0], expectedresult)
440
+ tape.zero()
441
+ idx = idx + 1
442
+
443
+
444
+ def test_subtraction(test, device, dtype, register_kernels=False):
445
+ rng = np.random.default_rng(123)
446
+
447
+ tol = {
448
+ np.float16: 5.0e-3,
449
+ np.float32: 1.0e-6,
450
+ np.float64: 1.0e-8,
451
+ }.get(dtype, 0)
452
+
453
+ wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
454
+ mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
455
+ mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
456
+ mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
457
+ mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
458
+
459
+ output_select_kernel = get_select_kernel(wptype)
460
+
461
+ def check_mat_sub(
462
+ s2: wp.array(dtype=mat22),
463
+ s3: wp.array(dtype=mat33),
464
+ s4: wp.array(dtype=mat44),
465
+ s5: wp.array(dtype=mat55),
466
+ v2: wp.array(dtype=mat22),
467
+ v3: wp.array(dtype=mat33),
468
+ v4: wp.array(dtype=mat44),
469
+ v5: wp.array(dtype=mat55),
470
+ outcomponents: wp.array(dtype=wptype),
471
+ ):
472
+ v2result = v2[0] - s2[0]
473
+ v3result = v3[0] - s3[0]
474
+ v4result = v4[0] - s4[0]
475
+ v5result = v5[0] - s5[0]
476
+
477
+ # multiply outputs by 2 so we've got something to backpropagate:
478
+ idx = 0
479
+ for i in range(2):
480
+ for j in range(2):
481
+ outcomponents[idx] = wptype(2) * v2result[i, j]
482
+ idx = idx + 1
483
+
484
+ for i in range(3):
485
+ for j in range(3):
486
+ outcomponents[idx] = wptype(2) * v3result[i, j]
487
+ idx = idx + 1
488
+
489
+ for i in range(4):
490
+ for j in range(4):
491
+ outcomponents[idx] = wptype(2) * v4result[i, j]
492
+ idx = idx + 1
493
+
494
+ for i in range(5):
495
+ for j in range(5):
496
+ outcomponents[idx] = wptype(2) * v5result[i, j]
497
+ idx = idx + 1
498
+
499
+ kernel = getkernel(check_mat_sub, suffix=dtype.__name__)
500
+
501
+ if register_kernels:
502
+ return
503
+
504
+ s2 = wp.array(randvals(rng, [1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
505
+ s3 = wp.array(randvals(rng, [1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
506
+ s4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
507
+ s5 = wp.array(randvals(rng, [1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
508
+ v2 = wp.array(randvals(rng, [1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
509
+ v3 = wp.array(randvals(rng, [1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
510
+ v4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
511
+ v5 = wp.array(randvals(rng, [1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
512
+ outcomponents = wp.zeros(2 * 2 + 3 * 3 + 4 * 4 + 5 * 5, dtype=wptype, requires_grad=True, device=device)
513
+
514
+ wp.launch(
515
+ kernel,
516
+ dim=1,
517
+ inputs=[
518
+ s2,
519
+ s3,
520
+ s4,
521
+ s5,
522
+ v2,
523
+ v3,
524
+ v4,
525
+ v5,
526
+ ],
527
+ outputs=[outcomponents],
528
+ device=device,
529
+ )
530
+
531
+ assert_np_equal(outcomponents.numpy()[:4], 2 * (v2.numpy() - s2.numpy()).reshape(-1), tol=tol)
532
+ assert_np_equal(outcomponents.numpy()[4:13], 2 * (v3.numpy() - s3.numpy()).reshape(-1), tol=tol)
533
+ assert_np_equal(outcomponents.numpy()[13:29], 2 * (v4.numpy() - s4.numpy()).reshape(-1), tol=tol)
534
+ assert_np_equal(outcomponents.numpy()[29:54], 2 * (v5.numpy() - s5.numpy()).reshape(-1), tol=10 * tol)
535
+
536
+ if dtype in np_float_types:
537
+ idx = 0
538
+ out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
539
+ for dim, in1, in2 in [(2, s2, v2), (3, s3, v3), (4, s4, v4), (5, s5, v5)]:
540
+ for i in range(dim):
541
+ for j in range(dim):
542
+ tape = wp.Tape()
543
+ with tape:
544
+ wp.launch(
545
+ kernel,
546
+ dim=1,
547
+ inputs=[
548
+ s2,
549
+ s3,
550
+ s4,
551
+ s5,
552
+ v2,
553
+ v3,
554
+ v4,
555
+ v5,
556
+ ],
557
+ outputs=[outcomponents],
558
+ device=device,
559
+ )
560
+ wp.launch(
561
+ output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device
562
+ )
563
+ tape.backward(loss=out)
564
+ expectedresult = np.zeros((dim, dim), dtype=dtype)
565
+ expectedresult[i, j] = 2
566
+ assert_np_equal(tape.gradients[in2].numpy()[0], expectedresult, tol=10 * tol)
567
+ expectedresult[i, j] = -2
568
+ assert_np_equal(tape.gradients[in1].numpy()[0], expectedresult, tol=10 * tol)
569
+ tape.zero()
570
+
571
+ idx = idx + 1
572
+
573
+
574
+ def test_determinant(test, device, dtype, register_kernels=False):
575
+ rng = np.random.default_rng(123)
576
+
577
+ tol = {
578
+ np.float16: 5.0e-3,
579
+ np.float32: 1.0e-6,
580
+ np.float64: 1.0e-8,
581
+ }.get(dtype, 0)
582
+
583
+ wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
584
+ mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
585
+ mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
586
+ mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
587
+
588
+ def check_mat_det(
589
+ v2: wp.array(dtype=mat22),
590
+ v3: wp.array(dtype=mat33),
591
+ v4: wp.array(dtype=mat44),
592
+ det2: wp.array(dtype=wptype),
593
+ det3: wp.array(dtype=wptype),
594
+ det4: wp.array(dtype=wptype),
595
+ ):
596
+ # multiply outputs by 2 so we've got something to backpropagate:
597
+ det2[0] = wptype(2) * wp.determinant(v2[0])
598
+ det3[0] = wptype(2) * wp.determinant(v3[0])
599
+ det4[0] = wptype(2) * wp.determinant(v4[0])
600
+
601
+ kernel = getkernel(check_mat_det, suffix=dtype.__name__)
602
+ if register_kernels:
603
+ return
604
+
605
+ v2 = wp.array(randvals(rng, [1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
606
+ v3 = wp.array(randvals(rng, [1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
607
+ v4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
608
+ det2 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
609
+ det3 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
610
+ det4 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
611
+
612
+ tape = wp.Tape()
613
+ with tape:
614
+ wp.launch(
615
+ kernel,
616
+ dim=1,
617
+ inputs=[
618
+ v2,
619
+ v3,
620
+ v4,
621
+ ],
622
+ outputs=[
623
+ det2,
624
+ det3,
625
+ det4,
626
+ ],
627
+ device=device,
628
+ )
629
+
630
+ if dtype in np_float_types:
631
+ assert_np_equal(det2.numpy()[0], 2 * np.linalg.det(v2.numpy()[0].astype(np.float64)), tol=100 * tol)
632
+ assert_np_equal(det3.numpy()[0], 2 * np.linalg.det(v3.numpy()[0].astype(np.float64)), tol=100 * tol)
633
+ assert_np_equal(det4.numpy()[0], 2 * np.linalg.det(v4.numpy()[0].astype(np.float64)), tol=420 * tol)
634
+ else:
635
+ assert_np_equal(det2.numpy()[0], 2 * np.around(np.linalg.det(v2.numpy()[0])).astype(int))
636
+ assert_np_equal(det3.numpy()[0], 2 * np.around(np.linalg.det(v3.numpy()[0])).astype(int))
637
+ assert_np_equal(det4.numpy()[0], 2 * np.around(np.linalg.det(v4.numpy()[0])).astype(int))
638
+
639
+ if dtype in np_float_types:
640
+ # determinant derivative formula is annoying so finite differences?
641
+ tape.backward(loss=det2)
642
+ v2grads = 1.0 * tape.gradients[v2].numpy()[0]
643
+ tape.zero()
644
+
645
+ tape.backward(loss=det3)
646
+ v3grads = 1.0 * tape.gradients[v3].numpy()[0]
647
+ tape.zero()
648
+
649
+ tape.backward(loss=det4)
650
+ v4grads = 1.0 * tape.gradients[v4].numpy()[0]
651
+ tape.zero()
652
+
653
+ # finite differences are also annoying hence the large tolerance...
654
+ # absolute nightmare in float16 too innit...
655
+ dx = 0.01 if dtype == np.float16 else 0.0001
656
+ fdtol = 2.0e-1 if dtype == np.float16 else 2.0e-3
657
+ for i in range(2):
658
+ for j in range(2):
659
+ v2test = v2.numpy()
660
+ v2test[0, i, j] += dx
661
+ wp.launch(
662
+ kernel,
663
+ dim=1,
664
+ inputs=[
665
+ wp.array(v2test, dtype=v2.dtype, requires_grad=True, device=device),
666
+ v3,
667
+ v4,
668
+ ],
669
+ outputs=[
670
+ det2,
671
+ det3,
672
+ det4,
673
+ ],
674
+ device=device,
675
+ )
676
+ dplus = det2.numpy()[0]
677
+ v2test[0, i, j] -= 2.0 * dx
678
+ wp.launch(
679
+ kernel,
680
+ dim=1,
681
+ inputs=[
682
+ wp.array(v2test, dtype=v2.dtype, requires_grad=True, device=device),
683
+ v3,
684
+ v4,
685
+ ],
686
+ outputs=[
687
+ det2,
688
+ det3,
689
+ det4,
690
+ ],
691
+ device=device,
692
+ )
693
+ dminus = det2.numpy()[0]
694
+ assert_np_equal((dplus - dminus) / (2.0 * dx * dplus), v2grads[i, j] / dplus, tol=fdtol)
695
+
696
+ for i in range(3):
697
+ for j in range(3):
698
+ v3test = v3.numpy()
699
+ v3test[0, i, j] += dx
700
+ wp.launch(
701
+ kernel,
702
+ dim=1,
703
+ inputs=[
704
+ v2,
705
+ wp.array(v3test, dtype=v3.dtype, requires_grad=True, device=device),
706
+ v4,
707
+ ],
708
+ outputs=[
709
+ det2,
710
+ det3,
711
+ det4,
712
+ ],
713
+ device=device,
714
+ )
715
+ dplus = det3.numpy()[0]
716
+ v3test[0, i, j] -= 2.0 * dx
717
+ wp.launch(
718
+ kernel,
719
+ dim=1,
720
+ inputs=[
721
+ v2,
722
+ wp.array(v3test, dtype=v3.dtype, requires_grad=True, device=device),
723
+ v4,
724
+ ],
725
+ outputs=[
726
+ det2,
727
+ det3,
728
+ det4,
729
+ ],
730
+ device=device,
731
+ )
732
+ dminus = det3.numpy()[0]
733
+ assert_np_equal((dplus - dminus) / (2.0 * dx * dplus), v3grads[i, j] / dplus, tol=fdtol)
734
+
735
+ for i in range(4):
736
+ for j in range(4):
737
+ v4test = v4.numpy()
738
+ v4test[0, i, j] += dx
739
+ wp.launch(
740
+ kernel,
741
+ dim=1,
742
+ inputs=[
743
+ v2,
744
+ v3,
745
+ wp.array(v4test, dtype=v4.dtype, requires_grad=True, device=device),
746
+ ],
747
+ outputs=[
748
+ det2,
749
+ det3,
750
+ det4,
751
+ ],
752
+ device=device,
753
+ )
754
+ dplus = det4.numpy()[0]
755
+ v4test[0, i, j] -= 2.0 * dx
756
+ wp.launch(
757
+ kernel,
758
+ dim=1,
759
+ inputs=[
760
+ v2,
761
+ v3,
762
+ wp.array(v4test, dtype=v4.dtype, requires_grad=True, device=device),
763
+ ],
764
+ outputs=[
765
+ det2,
766
+ det3,
767
+ det4,
768
+ ],
769
+ device=device,
770
+ )
771
+ dminus = det4.numpy()[0]
772
+ assert_np_equal((dplus - dminus) / (2.0 * dx * dplus), v4grads[i, j] / dplus, tol=fdtol)
773
+
774
+
775
+ # Unused. Why?
776
+ # def test_get_diag(test, device, dtype, register_kernels=False):
777
+ # tol = {
778
+ # np.float16: 1.0e-3,
779
+ # np.float32: 1.0e-6,
780
+ # np.float64: 1.0e-8,
781
+ # }.get(dtype, 0)
782
+ #
783
+ # wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
784
+ # mat55 = wp.types.vector(shape=(5, 5), dtype=wptype)
785
+ #
786
+ # output_select_kernel = get_select_kernel(wptype)
787
+ #
788
+ # def check_mat_diag(
789
+ # m55: wp.array(dtype=mat55),
790
+ # outcomponents: wp.array(dtype=wptype),
791
+ # ):
792
+ # # multiply outputs by 2 so we've got something to backpropagate:
793
+ # vec5result = wptype(2) * wp.get_diag(m55[0])
794
+ #
795
+ # idx = 0
796
+ # for i in range(5):
797
+ # outcomponents[idx] = vec5result[i]
798
+ # idx = idx + 1
799
+ #
800
+ # kernel = getkernel(check_mat_diag, suffix=dtype.__name__)
801
+ #
802
+ # if register_kernels:
803
+ # return
804
+ #
805
+ # m55 = wp.array(randvals((1, 5, 5), dtype), dtype=mat55, requires_grad=True, device=device)
806
+ # outcomponents = wp.zeros(5, dtype=wptype, requires_grad=True, device=device)
807
+ # out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
808
+ #
809
+ # wp.launch(kernel, dim=1, inputs=[m55], outputs=[outcomponents], device=device)
810
+ #
811
+ # assert_np_equal(outcomponents.numpy(), 2 * np.diag(m55.numpy()[0]), tol=tol)
812
+ #
813
+ # if dtype in np_float_types:
814
+ # idx = 0
815
+ # for i in range(5):
816
+ # tape = wp.Tape()
817
+ # with tape:
818
+ # wp.launch(kernel, dim=1, inputs=[m55], outputs=[outcomponents], device=device)
819
+ # wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
820
+ # tape.backward(loss=out)
821
+ # expectedresult = np.zeros((5, 5), dtype=dtype)
822
+ # expectedresult[i, i] = 2
823
+ # assert_np_equal(tape.gradients[m55].numpy()[0], expectedresult, tol=10 * tol)
824
+ # tape.zero()
825
+ #
826
+ # idx = idx + 1
827
+
828
+
829
+ def test_inverse(test, device, dtype, register_kernels=False):
830
+ rng = np.random.default_rng(123)
831
+
832
+ tol = {
833
+ np.float16: 5.0e-2,
834
+ np.float32: 1.0e-5,
835
+ np.float64: 1.0e-8,
836
+ }.get(dtype, 0)
837
+
838
+ wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
839
+ mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
840
+ mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
841
+ mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
842
+
843
+ output_select_kernel = get_select_kernel(wptype)
844
+
845
+ def check_mat_inverse(
846
+ m2: wp.array(dtype=mat22),
847
+ m3: wp.array(dtype=mat33),
848
+ m4: wp.array(dtype=mat44),
849
+ outcomponents: wp.array(dtype=wptype),
850
+ ):
851
+ m2result = wp.inverse(m2[0])
852
+ m3result = wp.inverse(m3[0])
853
+ m4result = wp.inverse(m4[0])
854
+
855
+ # multiply outputs by 2 so we've got something to backpropagate:
856
+ idx = 0
857
+ for i in range(2):
858
+ for j in range(2):
859
+ outcomponents[idx] = wptype(2) * m2result[i, j]
860
+ idx = idx + 1
861
+
862
+ for i in range(3):
863
+ for j in range(3):
864
+ outcomponents[idx] = wptype(2) * m3result[i, j]
865
+ idx = idx + 1
866
+
867
+ for i in range(4):
868
+ for j in range(4):
869
+ outcomponents[idx] = wptype(2) * m4result[i, j]
870
+ idx = idx + 1
871
+
872
+ kernel = getkernel(check_mat_inverse, suffix=dtype.__name__)
873
+
874
+ if register_kernels:
875
+ return
876
+
877
+ m2 = wp.array(
878
+ 2 * (randvals(rng, [1, 2, 2], dtype) + 0.2 * np.eye(2)), dtype=mat22, requires_grad=True, device=device
879
+ )
880
+ m3 = wp.array(
881
+ 2 * (randvals(rng, [1, 3, 3], dtype) + 0.2 * np.eye(3)), dtype=mat33, requires_grad=True, device=device
882
+ )
883
+ m4 = wp.array(
884
+ 2 * (randvals(rng, [1, 4, 4], dtype) + 0.2 * np.eye(4)), dtype=mat44, requires_grad=True, device=device
885
+ )
886
+
887
+ outcomponents = wp.zeros(2 * 2 + 3 * 3 + 4 * 4, dtype=wptype, requires_grad=True, device=device)
888
+ out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
889
+
890
+ wp.launch(kernel, dim=1, inputs=[m2, m3, m4], outputs=[outcomponents], device=device)
891
+
892
+ assert_np_equal(outcomponents.numpy()[:4], 2 * np.linalg.inv(m2.numpy()[0].astype(np.float64)), tol=tol)
893
+ assert_np_equal(outcomponents.numpy()[4:13], 2 * np.linalg.inv(m3.numpy()[0].astype(np.float64)), tol=5 * tol)
894
+ assert_np_equal(outcomponents.numpy()[13:], 2 * np.linalg.inv(m4.numpy()[0].astype(np.float64)), tol=5 * tol)
895
+
896
+ if dtype in np_float_types:
897
+ # check gradients:
898
+ idx = 0
899
+ out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
900
+ for dim, input in [(2, m2), (3, m3), (4, m4)]:
901
+ minv = np.linalg.inv(input.numpy()[0].astype(np.float64))
902
+ for i in range(dim):
903
+ for j in range(dim):
904
+ tape = wp.Tape()
905
+ with tape:
906
+ wp.launch(kernel, dim=1, inputs=[m2, m3, m4], outputs=[outcomponents], device=device)
907
+ wp.launch(
908
+ output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device
909
+ )
910
+ tape.backward(loss=out)
911
+ d = np.zeros((dim, dim))
912
+ d[j, i] = 2
913
+ assert_np_equal(
914
+ tape.gradients[input].numpy()[0], -np.matmul(minv, np.matmul(d, minv)).T, tol=10 * tol
915
+ )
916
+ tape.zero()
917
+
918
+ idx = idx + 1
919
+
920
+ # let's check 2x2 using different formulae just for (in)sanity's sake:
921
+ m = m2.numpy()[0]
922
+
923
+ det = m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]
924
+ expected = 2 * np.array([[m[1, 1], -m[0, 1]], [-m[1, 0], m[0, 0]]], dtype=dtype) / det
925
+ assert_np_equal(expected, outcomponents.numpy()[:4], tol=tol)
926
+
927
+ # 0,0 component is this:
928
+ # 2 * m[1,1] / (m[0,0]*m[1,1] - m[1,0] * m[0,1])
929
+ assert_np_equal(2 * m[1, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]), outcomponents.numpy()[0], tol=tol)
930
+
931
+ tape = wp.Tape()
932
+ with tape:
933
+ wp.launch(kernel, dim=1, inputs=[m2, m3, m4], outputs=[outcomponents], device=device)
934
+ wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, 0], outputs=[out], device=device)
935
+
936
+ if dtype in np_float_types:
937
+ tape.backward(loss=out)
938
+ g = tape.gradients[m2].numpy()[0]
939
+ assert_np_equal(-2 * m[1, 1] * m[1, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 0], tol=tol)
940
+ assert_np_equal(2 * m[1, 1] * m[0, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 0], tol=tol)
941
+ assert_np_equal(-2 * m[0, 1] * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 1], tol=tol)
942
+ assert_np_equal(2 * m[1, 1] * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 1], tol=tol)
943
+ tape.zero()
944
+
945
+ # 0,1 component is this:
946
+ # -2 * m[0,1] / (m[0,0]*m[1,1] - m[1,0] * m[0,1])
947
+ assert_np_equal(-2 * m[0, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]), outcomponents.numpy()[1], tol=tol)
948
+
949
+ tape = wp.Tape()
950
+ with tape:
951
+ wp.launch(kernel, dim=1, inputs=[m2, m3, m4], outputs=[outcomponents], device=device)
952
+ wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, 1], outputs=[out], device=device)
953
+ if dtype in np_float_types:
954
+ tape.backward(loss=out)
955
+ g = tape.gradients[m2].numpy()[0]
956
+ assert_np_equal(2 * m[0, 1] * m[1, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 0], tol=tol)
957
+ assert_np_equal(-2 * m[0, 1] * m[0, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 0], tol=tol)
958
+ assert_np_equal(2 * m[0, 0] * m[0, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 1], tol=tol)
959
+ assert_np_equal(-2 * m[1, 1] * m[0, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 1], tol=tol)
960
+ tape.zero()
961
+
962
+ # 1,0 component is this:
963
+ # -2 * m[1,0] / (m[0,0]*m[1,1] - m[1,0] * m[0,1])
964
+ assert_np_equal(-2 * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]), outcomponents.numpy()[2], tol=tol)
965
+
966
+ tape = wp.Tape()
967
+ with tape:
968
+ wp.launch(kernel, dim=1, inputs=[m2, m3, m4], outputs=[outcomponents], device=device)
969
+ wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, 2], outputs=[out], device=device)
970
+
971
+ if dtype in np_float_types:
972
+ tape.backward(loss=out)
973
+ g = tape.gradients[m2].numpy()[0]
974
+ assert_np_equal(2 * m[1, 1] * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 0], tol=tol)
975
+ assert_np_equal(-2 * m[0, 0] * m[1, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 0], tol=tol)
976
+ assert_np_equal(2 * m[0, 0] * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 1], tol=tol)
977
+ assert_np_equal(-2 * m[1, 0] * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 1], tol=tol)
978
+ tape.zero()
979
+
980
+ # 1,1 component is this:
981
+ # 2 * m[0,0] / (m[0,0]*m[1,1] - m[1,0] * m[0,1])
982
+ assert_np_equal(2 * m[0, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]), outcomponents.numpy()[3], tol=tol)
983
+
984
+ tape = wp.Tape()
985
+ with tape:
986
+ wp.launch(kernel, dim=1, inputs=[m2, m3, m4], outputs=[outcomponents], device=device)
987
+ wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, 3], outputs=[out], device=device)
988
+
989
+ if dtype in np_float_types:
990
+ tape.backward(loss=out)
991
+ g = tape.gradients[m2].numpy()[0]
992
+ assert_np_equal(-2 * m[0, 1] * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 0], tol=tol)
993
+ assert_np_equal(2 * m[0, 0] * m[0, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 0], tol=tol)
994
+ assert_np_equal(2 * m[0, 0] * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 1], tol=tol)
995
+ assert_np_equal(-2 * m[0, 0] * m[0, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 1], tol=tol)
996
+ tape.zero()
997
+
998
+
999
+ def test_svd(test, device, dtype, register_kernels=False):
1000
+ rng = np.random.default_rng(123)
1001
+
1002
+ tol = {
1003
+ np.float16: 1.0e-3,
1004
+ np.float32: 1.0e-6,
1005
+ np.float64: 1.0e-6,
1006
+ }.get(dtype, 0)
1007
+
1008
+ wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
1009
+ vec3 = wp.types.vector(length=3, dtype=wptype)
1010
+ mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
1011
+
1012
+ def check_mat_svd(
1013
+ m3: wp.array(dtype=mat33),
1014
+ Uout: wp.array(dtype=mat33),
1015
+ sigmaout: wp.array(dtype=vec3),
1016
+ Vout: wp.array(dtype=mat33),
1017
+ outcomponents: wp.array(dtype=wptype),
1018
+ ):
1019
+ U = mat33()
1020
+ sigma = vec3()
1021
+ V = mat33()
1022
+
1023
+ wp.svd3(m3[0], U, sigma, V)
1024
+
1025
+ Uout[0] = U
1026
+ sigmaout[0] = sigma
1027
+ Vout[0] = V
1028
+
1029
+ # multiply outputs by 2 so we've got something to backpropagate:
1030
+ idx = 0
1031
+ for i in range(3):
1032
+ for j in range(3):
1033
+ outcomponents[idx] = wptype(2) * U[i, j]
1034
+ idx = idx + 1
1035
+
1036
+ for i in range(3):
1037
+ outcomponents[idx] = wptype(2) * sigma[i]
1038
+ idx = idx + 1
1039
+
1040
+ for i in range(3):
1041
+ for j in range(3):
1042
+ outcomponents[idx] = wptype(2) * V[i, j]
1043
+ idx = idx + 1
1044
+
1045
+ kernel = getkernel(check_mat_svd, suffix=dtype.__name__)
1046
+
1047
+ output_select_kernel = get_select_kernel(wptype)
1048
+
1049
+ if register_kernels:
1050
+ return
1051
+
1052
+ m3 = wp.array(randvals(rng, [1, 3, 3], dtype) + np.eye(3), dtype=mat33, requires_grad=True, device=device)
1053
+
1054
+ outcomponents = wp.zeros(2 * 3 * 3 + 3, dtype=wptype, requires_grad=True, device=device)
1055
+ Uout = wp.zeros(1, dtype=mat33, requires_grad=True, device=device)
1056
+ sigmaout = wp.zeros(1, dtype=vec3, requires_grad=True, device=device)
1057
+ Vout = wp.zeros(1, dtype=mat33, requires_grad=True, device=device)
1058
+
1059
+ wp.launch(kernel, dim=1, inputs=[m3], outputs=[Uout, sigmaout, Vout, outcomponents], device=device)
1060
+
1061
+ Uout_np = Uout.numpy()[0].astype(np.float64)
1062
+ sigmaout_np = np.diag(sigmaout.numpy()[0].astype(np.float64))
1063
+ Vout_np = Vout.numpy()[0].astype(np.float64)
1064
+
1065
+ assert_np_equal(
1066
+ np.matmul(Uout_np, np.matmul(sigmaout_np, Vout_np.T)), m3.numpy()[0].astype(np.float64), tol=30 * tol
1067
+ )
1068
+
1069
+ if dtype == np.float16:
1070
+ # I'm not even going to bother testing the gradients for float16
1071
+ # because the rounding errors are terrible...
1072
+ return
1073
+
1074
+ # check gradients:
1075
+ out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
1076
+ idx = 0
1077
+ for idx in range(3 * 3 + 3 + 3 * 3):
1078
+ tape = wp.Tape()
1079
+ with tape:
1080
+ wp.launch(kernel, dim=1, inputs=[m3], outputs=[Uout, sigmaout, Vout, outcomponents], device=device)
1081
+ wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1082
+ tape.backward(out)
1083
+ m3grads = 1.0 * tape.gradients[m3].numpy()[0]
1084
+
1085
+ tape.zero()
1086
+
1087
+ dx = 0.0001
1088
+ fdtol = 5.0e-4 if dtype == np.float64 else 2.0e-2
1089
+ for ii in range(3):
1090
+ for jj in range(3):
1091
+ m3test = 1.0 * m3.numpy()
1092
+ m3test[0, ii, jj] += dx
1093
+ wp.launch(
1094
+ kernel,
1095
+ dim=1,
1096
+ inputs=[wp.array(m3test, dtype=mat33, device=device)],
1097
+ outputs=[Uout, sigmaout, Vout, outcomponents],
1098
+ device=device,
1099
+ )
1100
+ wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1101
+ plusval = out.numpy()[0]
1102
+
1103
+ m3test = 1.0 * m3.numpy()
1104
+ m3test[0, ii, jj] -= dx
1105
+ wp.launch(
1106
+ kernel,
1107
+ dim=1,
1108
+ inputs=[wp.array(m3test, dtype=mat33, device=device)],
1109
+ outputs=[Uout, sigmaout, Vout, outcomponents],
1110
+ device=device,
1111
+ )
1112
+ wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1113
+ minusval = out.numpy()[0]
1114
+
1115
+ assert_np_equal((plusval - minusval) / (2 * dx), m3grads[ii, jj], tol=fdtol)
1116
+
1117
+
1118
+ def test_qr(test, device, dtype, register_kernels=False):
1119
+ rng = np.random.default_rng(123)
1120
+
1121
+ tol = {
1122
+ np.float16: 2.0e-3,
1123
+ np.float32: 1.0e-6,
1124
+ np.float64: 1.0e-6,
1125
+ }.get(dtype, 0)
1126
+
1127
+ wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
1128
+ mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
1129
+
1130
+ def check_mat_qr(
1131
+ m3: wp.array(dtype=mat33),
1132
+ Qout: wp.array(dtype=mat33),
1133
+ Rout: wp.array(dtype=mat33),
1134
+ outcomponents: wp.array(dtype=wptype),
1135
+ ):
1136
+ Q = mat33()
1137
+ R = mat33()
1138
+
1139
+ wp.qr3(m3[0], Q, R)
1140
+
1141
+ Qout[0] = Q
1142
+ Rout[0] = R
1143
+
1144
+ # multiply outputs by 2 so we've got something to backpropagate:
1145
+ idx = 0
1146
+ for i in range(3):
1147
+ for j in range(3):
1148
+ outcomponents[idx] = wptype(2) * Q[i, j]
1149
+ idx = idx + 1
1150
+
1151
+ for i in range(3):
1152
+ for j in range(3):
1153
+ outcomponents[idx] = wptype(2) * R[i, j]
1154
+ idx = idx + 1
1155
+
1156
+ kernel = getkernel(check_mat_qr, suffix=dtype.__name__)
1157
+ output_select_kernel = get_select_kernel(wptype)
1158
+
1159
+ if register_kernels:
1160
+ return
1161
+
1162
+ m3 = wp.array(0.5 * (randvals(rng, [1, 3, 3], dtype) + np.eye(3)), dtype=mat33, requires_grad=True, device=device)
1163
+
1164
+ outcomponents = wp.zeros(2 * 3 * 3, dtype=wptype, requires_grad=True, device=device)
1165
+ Qout = wp.zeros(1, dtype=mat33, requires_grad=True, device=device)
1166
+ Rout = wp.zeros(1, dtype=mat33, requires_grad=True, device=device)
1167
+
1168
+ wp.launch(kernel, dim=1, inputs=[m3], outputs=[Qout, Rout, outcomponents], device=device)
1169
+
1170
+ Qout_np = Qout.numpy()[0].astype(np.float64)
1171
+ Rout_np = Rout.numpy()[0].astype(np.float64)
1172
+
1173
+ # check it's actually a q and an r:
1174
+ assert_np_equal(np.matmul(Qout_np.T, Qout_np), np.eye(3, dtype=np.float64), tol=tol)
1175
+ assert_np_equal(Rout_np[1, [0]], np.zeros(1, dtype=np.float64), tol=tol)
1176
+ assert_np_equal(Rout_np[2, [0, 1]], np.zeros(2, dtype=np.float64), tol=tol)
1177
+
1178
+ # check it's a factorization:
1179
+ assert_np_equal(np.matmul(Qout_np, Rout_np), m3.numpy()[0].astype(np.float64), tol=30 * tol)
1180
+
1181
+ if dtype == np.float16:
1182
+ # I'm not even going to bother testing the gradients for float16
1183
+ # because the rounding errors are terrible...
1184
+ return
1185
+
1186
+ # check gradients:
1187
+ out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
1188
+ idx = 0
1189
+ for idx in range(len(outcomponents)):
1190
+ tape = wp.Tape()
1191
+ with tape:
1192
+ wp.launch(kernel, dim=1, inputs=[m3], outputs=[Qout, Rout, outcomponents], device=device)
1193
+ wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1194
+ tape.backward(out)
1195
+ m3grads = 1.0 * tape.gradients[m3].numpy()[0]
1196
+
1197
+ tape.zero()
1198
+
1199
+ dx = 0.0001
1200
+ fdtol = 5.0e-4 if dtype == np.float64 else 2.0e-2
1201
+ for ii in range(3):
1202
+ for jj in range(3):
1203
+ m3test = 1.0 * m3.numpy()
1204
+ m3test[0, ii, jj] += dx
1205
+ wp.launch(
1206
+ kernel,
1207
+ dim=1,
1208
+ inputs=[wp.array(m3test, dtype=mat33, device=device)],
1209
+ outputs=[Qout, Rout, outcomponents],
1210
+ device=device,
1211
+ )
1212
+ wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1213
+ plusval = out.numpy()[0]
1214
+
1215
+ m3test = 1.0 * m3.numpy()
1216
+ m3test[0, ii, jj] -= dx
1217
+ wp.launch(
1218
+ kernel,
1219
+ dim=1,
1220
+ inputs=[wp.array(m3test, dtype=mat33, device=device)],
1221
+ outputs=[Qout, Rout, outcomponents],
1222
+ device=device,
1223
+ )
1224
+ wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1225
+ minusval = out.numpy()[0]
1226
+
1227
+ assert_np_equal((plusval - minusval) / (2 * dx), m3grads[ii, jj], tol=fdtol)
1228
+
1229
+
1230
+ def test_eig(test, device, dtype, register_kernels=False):
1231
+ rng = np.random.default_rng(123)
1232
+
1233
+ tol = {
1234
+ np.float16: 4.0e-2,
1235
+ np.float32: 1.0e-5,
1236
+ np.float64: 1.0e-5,
1237
+ }.get(dtype, 0)
1238
+
1239
+ wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
1240
+ vec3 = wp.types.vector(length=3, dtype=wptype)
1241
+ mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
1242
+
1243
+ def check_mat_eig(
1244
+ m3: wp.array(dtype=mat33),
1245
+ Qout: wp.array(dtype=mat33),
1246
+ dout: wp.array(dtype=vec3),
1247
+ outcomponents: wp.array(dtype=wptype),
1248
+ ):
1249
+ Q = mat33()
1250
+ d = vec3()
1251
+
1252
+ wp.eig3(m3[0] + wp.transpose(m3[0]), Q, d)
1253
+
1254
+ Qout[0] = Q
1255
+ dout[0] = d
1256
+
1257
+ # multiply outputs by 2 so we've got something to backpropagate:
1258
+ idx = 0
1259
+ for i in range(3):
1260
+ for j in range(3):
1261
+ outcomponents[idx] = wptype(2) * Q[i, j]
1262
+ idx = idx + 1
1263
+
1264
+ for i in range(3):
1265
+ outcomponents[idx] = wptype(2) * d[i]
1266
+ idx = idx + 1
1267
+
1268
+ kernel = getkernel(check_mat_eig, suffix=dtype.__name__)
1269
+ output_select_kernel = get_select_kernel(wptype)
1270
+
1271
+ if register_kernels:
1272
+ return
1273
+
1274
+ m3_np = randvals(rng, [1, 3, 3], dtype) + np.eye(3, dtype=dtype)
1275
+ m3 = wp.array(m3_np, dtype=mat33, requires_grad=True, device=device)
1276
+
1277
+ outcomponents = wp.zeros(3 * 3 + 3, dtype=wptype, requires_grad=True, device=device)
1278
+ Qout = wp.zeros(1, dtype=mat33, requires_grad=True, device=device)
1279
+ dout = wp.zeros(1, dtype=vec3, requires_grad=True, device=device)
1280
+
1281
+ wp.launch(kernel, dim=1, inputs=[m3], outputs=[Qout, dout, outcomponents], device=device)
1282
+
1283
+ Qout_np = Qout.numpy()[0].astype(np.float64)
1284
+ dout_np = dout.numpy()[0].astype(np.float64)
1285
+ Dout_np = np.diag(dout_np)
1286
+
1287
+ # check Q is orthogonal:
1288
+ assert_np_equal(np.matmul(Qout_np.T, Qout_np), np.eye(3), tol=tol)
1289
+
1290
+ # check Q contains eigenvectors:
1291
+ assert_np_equal(np.matmul(Qout_np, np.matmul(Dout_np, Qout_np.T)), (m3_np[0] + m3_np[0].transpose()), tol=tol)
1292
+
1293
+ if dtype == np.float16:
1294
+ # I'm not even going to bother testing the gradients for float16
1295
+ # because the rounding errors are terrible...
1296
+ return
1297
+
1298
+ # check gradients:
1299
+ out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
1300
+ idx = 0
1301
+ for idx in range(len(outcomponents)):
1302
+ tape = wp.Tape()
1303
+ with tape:
1304
+ wp.launch(kernel, dim=1, inputs=[m3], outputs=[Qout, dout, outcomponents], device=device)
1305
+ wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1306
+ tape.backward(out)
1307
+ m3grads = 1.0 * tape.gradients[m3].numpy()[0]
1308
+
1309
+ tape.zero()
1310
+
1311
+ dx = 0.0001
1312
+ fdtol = 5.0e-4 if dtype == np.float64 else 2.0e-2
1313
+ for ii in range(3):
1314
+ for jj in range(3):
1315
+ m3test = 1.0 * m3.numpy()
1316
+ m3test[0, ii, jj] += dx
1317
+ wp.launch(
1318
+ kernel,
1319
+ dim=1,
1320
+ inputs=[wp.array(m3test, dtype=mat33, device=device)],
1321
+ outputs=[Qout, dout, outcomponents],
1322
+ device=device,
1323
+ )
1324
+ wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1325
+ plusval = out.numpy()[0]
1326
+
1327
+ m3test = 1.0 * m3.numpy()
1328
+ m3test[0, ii, jj] -= dx
1329
+ wp.launch(
1330
+ kernel,
1331
+ dim=1,
1332
+ inputs=[wp.array(m3test, dtype=mat33, device=device)],
1333
+ outputs=[Qout, dout, outcomponents],
1334
+ device=device,
1335
+ )
1336
+ wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1337
+ minusval = out.numpy()[0]
1338
+
1339
+ assert_np_equal((plusval - minusval) / (2 * dx), m3grads[ii, jj], tol=fdtol)
1340
+
1341
+
1342
+ def test_skew(test, device, dtype, register_kernels=False):
1343
+ rng = np.random.default_rng(123)
1344
+
1345
+ tol = {
1346
+ np.float16: 1.0e-3,
1347
+ np.float32: 1.0e-6,
1348
+ np.float64: 1.0e-8,
1349
+ }.get(dtype, 0)
1350
+
1351
+ wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
1352
+ vec3 = wp.types.vector(length=3, dtype=wptype)
1353
+
1354
+ output_select_kernel = get_select_kernel(wptype)
1355
+
1356
+ def check_mat_skew(
1357
+ v3: wp.array(dtype=vec3),
1358
+ outcomponents: wp.array(dtype=wptype),
1359
+ ):
1360
+ m3result = wp.skew(v3[0])
1361
+
1362
+ # multiply outputs by 2 so we've got something to backpropagate:
1363
+ idx = 0
1364
+ for i in range(3):
1365
+ for j in range(3):
1366
+ outcomponents[idx] = wptype(2) * m3result[i, j]
1367
+ idx = idx + 1
1368
+
1369
+ kernel = getkernel(check_mat_skew, suffix=dtype.__name__)
1370
+
1371
+ if register_kernels:
1372
+ return
1373
+
1374
+ v3 = wp.array(randvals(rng, [1, 3], dtype), dtype=vec3, requires_grad=True, device=device)
1375
+
1376
+ outcomponents = wp.zeros(3 * 3, dtype=wptype, requires_grad=True, device=device)
1377
+ out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
1378
+
1379
+ wp.launch(kernel, dim=1, inputs=[v3], outputs=[outcomponents], device=device)
1380
+
1381
+ # make sure it gives you a cross product matrix:
1382
+ crossprodmat = outcomponents.numpy().reshape(3, 3)
1383
+ v = np.array([1, 0, 0])
1384
+ assert_np_equal(
1385
+ np.matmul(crossprodmat, np.array([1, 0, 0])).reshape(-1),
1386
+ 2 * np.cross(v3.numpy()[0], np.array([1, 0, 0])),
1387
+ tol=tol,
1388
+ )
1389
+ assert_np_equal(
1390
+ np.matmul(crossprodmat, np.array([0, 1, 0])).reshape(-1),
1391
+ 2 * np.cross(v3.numpy()[0], np.array([0, 1, 0])),
1392
+ tol=tol,
1393
+ )
1394
+ assert_np_equal(
1395
+ np.matmul(crossprodmat, np.array([0, 0, 1])).reshape(-1),
1396
+ 2 * np.cross(v3.numpy()[0], np.array([0, 0, 1])),
1397
+ tol=tol,
1398
+ )
1399
+
1400
+ # check it another way:
1401
+ x0 = v3.numpy()[0, 0]
1402
+ x1 = v3.numpy()[0, 1]
1403
+ x2 = v3.numpy()[0, 2]
1404
+ crossprodmat_expected = np.array(
1405
+ [
1406
+ [0, -x2, x1],
1407
+ [x2, 0, -x0],
1408
+ [-x1, x0, 0],
1409
+ ],
1410
+ dtype=dtype,
1411
+ )
1412
+ assert_np_equal(crossprodmat, 2 * crossprodmat_expected, tol=tol)
1413
+
1414
+ if dtype in np_float_types:
1415
+ idx = 0
1416
+ out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
1417
+
1418
+ for i in range(3):
1419
+ for j in range(3):
1420
+ tape = wp.Tape()
1421
+ with tape:
1422
+ wp.launch(kernel, dim=1, inputs=[v3], outputs=[outcomponents], device=device)
1423
+ wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1424
+ tape.backward(loss=out)
1425
+ if i == j:
1426
+ assert_np_equal(tape.gradients[v3].numpy()[0], np.zeros(3))
1427
+ elif [i, j] == [0, 1]:
1428
+ assert_np_equal(tape.gradients[v3].numpy()[0], np.array([0, 0, -2]))
1429
+ elif [i, j] == [1, 0]:
1430
+ assert_np_equal(tape.gradients[v3].numpy()[0], np.array([0, 0, 2]))
1431
+ elif [i, j] == [0, 2]:
1432
+ assert_np_equal(tape.gradients[v3].numpy()[0], np.array([0, 2, 0]))
1433
+ elif [i, j] == [2, 0]:
1434
+ assert_np_equal(tape.gradients[v3].numpy()[0], np.array([0, -2, 0]))
1435
+ elif [i, j] == [1, 2]:
1436
+ assert_np_equal(tape.gradients[v3].numpy()[0], np.array([-2, 0, 0]))
1437
+ elif [i, j] == [2, 1]:
1438
+ assert_np_equal(tape.gradients[v3].numpy()[0], np.array([2, 0, 0]))
1439
+ tape.zero()
1440
+
1441
+ idx = idx + 1
1442
+
1443
+
1444
+ def test_transform_point(test, device, dtype, register_kernels=False):
1445
+ rng = np.random.default_rng(123)
1446
+
1447
+ tol = {
1448
+ np.float16: 5.0e-3,
1449
+ np.float32: 1.0e-6,
1450
+ np.float64: 1.0e-8,
1451
+ }.get(dtype, 0)
1452
+
1453
+ wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
1454
+ vec3 = wp.types.vector(length=3, dtype=wptype)
1455
+ mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
1456
+
1457
+ output_select_kernel = get_select_kernel(wptype)
1458
+
1459
+ def check_mat_transform_point(
1460
+ v3: wp.array(dtype=vec3),
1461
+ m4: wp.array(dtype=mat44),
1462
+ outcomponents: wp.array(dtype=wptype),
1463
+ ):
1464
+ # multiply outputs by 2 so we've got something to backpropagate:
1465
+ presult = wptype(2) * wp.transform_point(m4[0], v3[0])
1466
+
1467
+ outcomponents[0] = presult[0]
1468
+ outcomponents[1] = presult[1]
1469
+ outcomponents[2] = presult[2]
1470
+
1471
+ kernel = getkernel(check_mat_transform_point, suffix=dtype.__name__)
1472
+
1473
+ if register_kernels:
1474
+ return
1475
+
1476
+ v3 = wp.array(randvals(rng, [1, 3], dtype), dtype=vec3, requires_grad=True, device=device)
1477
+ m4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
1478
+
1479
+ outcomponents = wp.zeros(3, dtype=wptype, requires_grad=True, device=device)
1480
+ out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
1481
+
1482
+ wp.launch(kernel, dim=1, inputs=[v3, m4], outputs=[outcomponents], device=device)
1483
+
1484
+ v3homog = np.ones(4, dtype=dtype)
1485
+ v3homog[:3] = v3.numpy()[0]
1486
+ assert_np_equal(outcomponents.numpy(), 2 * np.matmul(m4.numpy()[0], v3homog)[:3], tol=10 * tol)
1487
+
1488
+ if dtype in np_float_types:
1489
+ for j in range(3):
1490
+ tape = wp.Tape()
1491
+ with tape:
1492
+ wp.launch(kernel, dim=1, inputs=[v3, m4], outputs=[outcomponents], device=device)
1493
+ wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, j], outputs=[out], device=device)
1494
+ tape.backward(loss=out)
1495
+
1496
+ assert_np_equal(2 * m4.numpy()[0, j, :3], tape.gradients[v3].numpy(), tol=tol)
1497
+ expected = np.zeros((4, 4), dtype=dtype)
1498
+ expected[j, :3] = 2 * v3.numpy()
1499
+ expected[j, 3] = 2
1500
+ assert_np_equal(tape.gradients[m4].numpy(), expected, tol=tol)
1501
+
1502
+ tape.zero()
1503
+
1504
+
1505
+ def test_transform_vector(test, device, dtype, register_kernels=False):
1506
+ rng = np.random.default_rng(123)
1507
+
1508
+ tol = {
1509
+ np.float16: 5.0e-3,
1510
+ np.float32: 1.0e-6,
1511
+ np.float64: 1.0e-8,
1512
+ }.get(dtype, 0)
1513
+
1514
+ wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
1515
+ vec3 = wp.types.vector(length=3, dtype=wptype)
1516
+ mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
1517
+
1518
+ output_select_kernel = get_select_kernel(wptype)
1519
+
1520
+ def check_mat_transform_vector(
1521
+ v3: wp.array(dtype=vec3),
1522
+ m4: wp.array(dtype=mat44),
1523
+ outcomponents: wp.array(dtype=wptype),
1524
+ ):
1525
+ # multiply outputs by 2 so we've got something to backpropagate:
1526
+ presult = wptype(2) * wp.transform_vector(m4[0], v3[0])
1527
+
1528
+ outcomponents[0] = presult[0]
1529
+ outcomponents[1] = presult[1]
1530
+ outcomponents[2] = presult[2]
1531
+
1532
+ kernel = getkernel(check_mat_transform_vector, suffix=dtype.__name__)
1533
+
1534
+ if register_kernels:
1535
+ return
1536
+
1537
+ v3 = wp.array(randvals(rng, [1, 3], dtype), dtype=vec3, requires_grad=True, device=device)
1538
+ m4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
1539
+
1540
+ outcomponents = wp.zeros(3, dtype=wptype, requires_grad=True, device=device)
1541
+ out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
1542
+
1543
+ wp.launch(kernel, dim=1, inputs=[v3, m4], outputs=[outcomponents], device=device)
1544
+
1545
+ v3homog = np.zeros(4, dtype=dtype)
1546
+ v3homog[:3] = v3.numpy()[0]
1547
+ assert_np_equal(outcomponents.numpy(), 2 * np.matmul(m4.numpy()[0], v3homog)[:3], tol=10 * tol)
1548
+
1549
+ if dtype in np_float_types:
1550
+ for j in range(3):
1551
+ tape = wp.Tape()
1552
+ with tape:
1553
+ wp.launch(kernel, dim=1, inputs=[v3, m4], outputs=[outcomponents], device=device)
1554
+ wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, j], outputs=[out], device=device)
1555
+ tape.backward(loss=out)
1556
+
1557
+ assert_np_equal(2 * m4.numpy()[0, j, :3], tape.gradients[v3].numpy(), tol=tol)
1558
+ expected = np.zeros((4, 4), dtype=dtype)
1559
+ expected[j, :3] = 2 * v3.numpy()
1560
+ assert_np_equal(tape.gradients[m4].numpy(), expected, tol=tol)
1561
+
1562
+ tape.zero()
1563
+
1564
+
1565
+ # Test matrix constructors using explicit type (float16)
1566
+ # note that these tests are specifically not using generics / closure
1567
+ # args to create kernels dynamically (like the rest of this file)
1568
+ # as those use different code paths to resolve arg types which
1569
+ # has lead to regressions.
1570
+ @wp.kernel
1571
+ def test_constructors_explicit_precision():
1572
+ # construction for custom matrix types
1573
+ eye = wp.identity(dtype=wp.float16, n=2)
1574
+ zeros = wp.matrix(shape=(2, 2), dtype=wp.float16)
1575
+ custom = wp.matrix(wp.float16(0.0), wp.float16(1.0), wp.float16(2.0), wp.float16(3.0), shape=(2, 2))
1576
+
1577
+ for i in range(2):
1578
+ for j in range(2):
1579
+ if i == j:
1580
+ wp.expect_eq(eye[i, j], wp.float16(1.0))
1581
+ else:
1582
+ wp.expect_eq(eye[i, j], wp.float16(0.0))
1583
+
1584
+ wp.expect_eq(zeros[i, j], wp.float16(0.0))
1585
+ wp.expect_eq(custom[i, j], wp.float16(i) * wp.float16(2.0) + wp.float16(j))
1586
+
1587
+
1588
+ mat32d = wp.mat(shape=(3, 2), dtype=wp.float64)
1589
+
1590
+
1591
+ @wp.kernel
1592
+ def test_matrix_constructor_value_func():
1593
+ a = wp.mat22()
1594
+ b = wp.matrix(a, shape=(2, 2))
1595
+ c = mat32d()
1596
+ d = mat32d(c, shape=(3, 2))
1597
+ e = mat32d(wp.float64(1.0), wp.float64(2.0), wp.float64(1.0), wp.float64(2.0), wp.float64(1.0), wp.float64(2.0))
1598
+ f = mat32d(
1599
+ wp.vec3d(wp.float64(1.0), wp.float64(2.0), wp.float64(3.0)),
1600
+ wp.vec3d(wp.float64(1.0), wp.float64(2.0), wp.float64(3.0)),
1601
+ )
1602
+
1603
+
1604
+ # Same as above but with a default (float/int) type
1605
+ # which tests some different code paths that
1606
+ # need to ensure types are correctly canonicalized
1607
+ # during codegen
1608
+ @wp.kernel
1609
+ def test_constructors_default_precision():
1610
+ # construction for default (float) matrix types
1611
+ eye = wp.identity(dtype=float, n=2)
1612
+ zeros = wp.matrix(shape=(2, 2), dtype=float)
1613
+ custom = wp.matrix(0.0, 1.0, 2.0, 3.0, shape=(2, 2))
1614
+
1615
+ for i in range(2):
1616
+ for j in range(2):
1617
+ if i == j:
1618
+ wp.expect_eq(eye[i, j], 1.0)
1619
+ else:
1620
+ wp.expect_eq(eye[i, j], 0.0)
1621
+
1622
+ wp.expect_eq(zeros[i, j], 0.0)
1623
+ wp.expect_eq(custom[i, j], float(i) * 2.0 + float(j))
1624
+
1625
+
1626
+ @wp.kernel
1627
+ def test_matrix_mutation(expected: wp.types.matrix(shape=(10, 3), dtype=float)):
1628
+ m = wp.matrix(shape=(10, 3), dtype=float)
1629
+
1630
+ # test direct element indexing
1631
+ m[0, 0] = 1.0
1632
+ m[0, 1] = 2.0
1633
+ m[0, 2] = 3.0
1634
+
1635
+ # The nested indexing (matrix->vector->scalar) below does not
1636
+ # currently modify m because m[0] returns row vector by
1637
+ # value rather than reference, this is different from NumPy
1638
+ # which always returns by ref. Not clear how we can support
1639
+ # this as well as auto-diff.
1640
+
1641
+ # m[0][1] = 2.0
1642
+ # m[0][2] = 3.0
1643
+
1644
+ # test setting rows
1645
+ for i in range(1, 10):
1646
+ m[i] = m[i - 1] + wp.vec3(1.0, 2.0, 3.0)
1647
+
1648
+ wp.expect_eq(m, expected)
1649
+
1650
+
1651
+ CONSTANT_SHAPE_ROWS = wp.constant(10)
1652
+ CONSTANT_SHAPE_COLS = wp.constant(10)
1653
+
1654
+
1655
+ # tests that we can use global constants in shape keyword argument
1656
+ # for matrix constructor
1657
+ @wp.kernel
1658
+ def test_constructors_constant_shape():
1659
+ m = wp.matrix(shape=(CONSTANT_SHAPE_ROWS, CONSTANT_SHAPE_COLS), dtype=float)
1660
+
1661
+ for i in range(CONSTANT_SHAPE_ROWS):
1662
+ for j in range(CONSTANT_SHAPE_COLS):
1663
+ m[i, j] = float(i * j)
1664
+
1665
+
1666
+ devices = get_test_devices()
1667
+
1668
+
1669
+ class TestMat(unittest.TestCase):
1670
+ def test_tpl_ops_with_anon(self):
1671
+ mat22f = wp.mat((2, 2), dtype=float)
1672
+
1673
+ m = wp.mat22f(1.0, 2.0, 3.0, 4.0)
1674
+ m += mat22f(2.0, 3.0, 4.0, 5.0)
1675
+ m -= mat22f(3.0, 4.0, 5.0, 6.0)
1676
+ self.assertSequenceEqual(m, ((0.0, 1.0), (2.0, 3.0)))
1677
+
1678
+ m = mat22f(1.0, 2.0, 3.0, 4.0)
1679
+ m += wp.mat22f(2.0, 3.0, 4.0, 5.0)
1680
+ m -= wp.mat22f(3.0, 4.0, 5.0, 6.0)
1681
+ self.assertSequenceEqual(m, ((0.0, 1.0), (2.0, 3.0)))
1682
+
1683
+
1684
+ add_kernel_test(TestMat, test_constructors_explicit_precision, dim=1, devices=devices)
1685
+ add_kernel_test(TestMat, test_constructors_default_precision, dim=1, devices=devices)
1686
+ add_kernel_test(TestMat, test_constructors_constant_shape, dim=1, devices=devices)
1687
+ add_kernel_test(TestMat, test_matrix_constructor_value_func, dim=1, devices=devices)
1688
+
1689
+ mat103 = wp.types.matrix(shape=(10, 3), dtype=float)
1690
+ add_kernel_test(
1691
+ TestMat,
1692
+ test_matrix_mutation,
1693
+ dim=1,
1694
+ inputs=[
1695
+ mat103(
1696
+ 1.0, 2.0, 3.0,
1697
+ 2.0, 4.0, 6.0,
1698
+ 3.0, 6.0, 9.0,
1699
+ 4.0, 8.0, 12.0,
1700
+ 5.0, 10.0, 15.0,
1701
+ 6.0, 12.0, 18.0,
1702
+ 7.0, 14.0, 21.0,
1703
+ 8.0, 16.0, 24.0,
1704
+ 9.0, 18.0, 27.0,
1705
+ 10.0, 20.0, 30.0,
1706
+ )
1707
+ ],
1708
+ devices=devices,
1709
+ ) # fmt: skip
1710
+
1711
+ for dtype in np_signed_int_types + np_float_types:
1712
+ add_function_test_register_kernel(
1713
+ TestMat, f"test_negation_{dtype.__name__}", test_negation, devices=devices, dtype=dtype
1714
+ )
1715
+ add_function_test_register_kernel(
1716
+ TestMat, f"test_subtraction_{dtype.__name__}", test_subtraction, devices=devices, dtype=dtype
1717
+ )
1718
+
1719
+ add_function_test(
1720
+ TestMat,
1721
+ "test_anon_constructor_error_shape_keyword_missing",
1722
+ test_anon_constructor_error_shape_keyword_missing,
1723
+ devices=devices,
1724
+ )
1725
+ add_function_test(
1726
+ TestMat,
1727
+ "test_anon_constructor_error_dtype_keyword_missing",
1728
+ test_anon_constructor_error_dtype_keyword_missing,
1729
+ devices=devices,
1730
+ )
1731
+ add_function_test(
1732
+ TestMat,
1733
+ "test_anon_constructor_error_shape_mismatch",
1734
+ test_anon_constructor_error_shape_mismatch,
1735
+ devices=devices,
1736
+ )
1737
+ add_function_test(
1738
+ TestMat,
1739
+ "test_anon_constructor_error_invalid_arg_count",
1740
+ test_anon_constructor_error_invalid_arg_count,
1741
+ devices=devices,
1742
+ )
1743
+ add_function_test(
1744
+ TestMat,
1745
+ "test_tpl_constructor_error_incompatible_sizes",
1746
+ test_tpl_constructor_error_incompatible_sizes,
1747
+ devices=devices,
1748
+ )
1749
+ add_function_test(
1750
+ TestMat,
1751
+ "test_tpl_constructor_error_invalid_scalar_type",
1752
+ test_tpl_constructor_error_invalid_scalar_type,
1753
+ devices=devices,
1754
+ )
1755
+ add_function_test(
1756
+ TestMat,
1757
+ "test_tpl_constructor_error_invalid_vector_count",
1758
+ test_tpl_constructor_error_invalid_vector_count,
1759
+ devices=devices,
1760
+ )
1761
+ add_function_test(
1762
+ TestMat,
1763
+ "test_tpl_constructor_error_invalid_vector_shape",
1764
+ test_tpl_constructor_error_invalid_vector_shape,
1765
+ devices=devices,
1766
+ )
1767
+ add_function_test(
1768
+ TestMat,
1769
+ "test_tpl_constructor_error_invalid_arg_count",
1770
+ test_tpl_constructor_error_invalid_arg_count,
1771
+ devices=devices,
1772
+ )
1773
+
1774
+ for dtype in np_float_types:
1775
+ add_function_test(
1776
+ TestMat, f"test_py_arithmetic_ops_{dtype.__name__}", test_py_arithmetic_ops, devices=None, dtype=dtype
1777
+ )
1778
+ add_function_test_register_kernel(
1779
+ TestMat, f"test_quat_constructor_{dtype.__name__}", test_quat_constructor, devices=devices, dtype=dtype
1780
+ )
1781
+ add_function_test_register_kernel(
1782
+ TestMat, f"test_inverse_{dtype.__name__}", test_inverse, devices=devices, dtype=dtype
1783
+ )
1784
+ add_function_test_register_kernel(TestMat, f"test_svd_{dtype.__name__}", test_svd, devices=devices, dtype=dtype)
1785
+ add_function_test_register_kernel(TestMat, f"test_qr_{dtype.__name__}", test_qr, devices=devices, dtype=dtype)
1786
+ add_function_test_register_kernel(TestMat, f"test_eig_{dtype.__name__}", test_eig, devices=devices, dtype=dtype)
1787
+ add_function_test_register_kernel(
1788
+ TestMat, f"test_transform_point_{dtype.__name__}", test_transform_point, devices=devices, dtype=dtype
1789
+ )
1790
+ add_function_test_register_kernel(
1791
+ TestMat, f"test_transform_vector_{dtype.__name__}", test_transform_vector, devices=devices, dtype=dtype
1792
+ )
1793
+ add_function_test_register_kernel(
1794
+ TestMat, f"test_determinant_{dtype.__name__}", test_determinant, devices=devices, dtype=dtype
1795
+ )
1796
+ add_function_test_register_kernel(TestMat, f"test_skew_{dtype.__name__}", test_skew, devices=devices, dtype=dtype)
1797
+
1798
+
1799
+ if __name__ == "__main__":
1800
+ wp.build.clear_kernel_cache()
1801
+ unittest.main(verbosity=2, failfast=True)