warp-lang 1.9.1__py3-none-win_amd64.whl → 1.10.0__py3-none-win_amd64.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 +301 -287
  2. warp/__init__.pyi +882 -305
  3. warp/_src/__init__.py +14 -0
  4. warp/_src/autograd.py +1077 -0
  5. warp/_src/build.py +620 -0
  6. warp/_src/build_dll.py +642 -0
  7. warp/{builtins.py → _src/builtins.py} +1435 -379
  8. warp/_src/codegen.py +4361 -0
  9. warp/{config.py → _src/config.py} +178 -169
  10. warp/_src/constants.py +59 -0
  11. warp/_src/context.py +8352 -0
  12. warp/_src/dlpack.py +464 -0
  13. warp/_src/fabric.py +362 -0
  14. warp/_src/fem/__init__.py +14 -0
  15. warp/_src/fem/adaptivity.py +510 -0
  16. warp/_src/fem/cache.py +689 -0
  17. warp/_src/fem/dirichlet.py +190 -0
  18. warp/{fem → _src/fem}/domain.py +42 -30
  19. warp/_src/fem/field/__init__.py +131 -0
  20. warp/_src/fem/field/field.py +703 -0
  21. warp/{fem → _src/fem}/field/nodal_field.py +32 -15
  22. warp/{fem → _src/fem}/field/restriction.py +3 -1
  23. warp/{fem → _src/fem}/field/virtual.py +55 -27
  24. warp/_src/fem/geometry/__init__.py +32 -0
  25. warp/{fem → _src/fem}/geometry/adaptive_nanogrid.py +79 -163
  26. warp/_src/fem/geometry/closest_point.py +99 -0
  27. warp/{fem → _src/fem}/geometry/deformed_geometry.py +16 -22
  28. warp/{fem → _src/fem}/geometry/element.py +34 -10
  29. warp/{fem → _src/fem}/geometry/geometry.py +50 -20
  30. warp/{fem → _src/fem}/geometry/grid_2d.py +14 -23
  31. warp/{fem → _src/fem}/geometry/grid_3d.py +14 -23
  32. warp/{fem → _src/fem}/geometry/hexmesh.py +42 -63
  33. warp/{fem → _src/fem}/geometry/nanogrid.py +256 -247
  34. warp/{fem → _src/fem}/geometry/partition.py +123 -63
  35. warp/{fem → _src/fem}/geometry/quadmesh.py +28 -45
  36. warp/{fem → _src/fem}/geometry/tetmesh.py +42 -63
  37. warp/{fem → _src/fem}/geometry/trimesh.py +28 -45
  38. warp/{fem → _src/fem}/integrate.py +166 -158
  39. warp/_src/fem/linalg.py +385 -0
  40. warp/_src/fem/operator.py +398 -0
  41. warp/_src/fem/polynomial.py +231 -0
  42. warp/{fem → _src/fem}/quadrature/pic_quadrature.py +17 -20
  43. warp/{fem → _src/fem}/quadrature/quadrature.py +97 -47
  44. warp/_src/fem/space/__init__.py +248 -0
  45. warp/{fem → _src/fem}/space/basis_function_space.py +22 -11
  46. warp/_src/fem/space/basis_space.py +681 -0
  47. warp/{fem → _src/fem}/space/dof_mapper.py +5 -3
  48. warp/{fem → _src/fem}/space/function_space.py +16 -13
  49. warp/{fem → _src/fem}/space/grid_2d_function_space.py +6 -7
  50. warp/{fem → _src/fem}/space/grid_3d_function_space.py +6 -4
  51. warp/{fem → _src/fem}/space/hexmesh_function_space.py +6 -10
  52. warp/{fem → _src/fem}/space/nanogrid_function_space.py +5 -9
  53. warp/{fem → _src/fem}/space/partition.py +119 -60
  54. warp/{fem → _src/fem}/space/quadmesh_function_space.py +6 -10
  55. warp/{fem → _src/fem}/space/restriction.py +68 -33
  56. warp/_src/fem/space/shape/__init__.py +152 -0
  57. warp/{fem → _src/fem}/space/shape/cube_shape_function.py +11 -9
  58. warp/{fem → _src/fem}/space/shape/shape_function.py +10 -9
  59. warp/{fem → _src/fem}/space/shape/square_shape_function.py +8 -6
  60. warp/{fem → _src/fem}/space/shape/tet_shape_function.py +5 -3
  61. warp/{fem → _src/fem}/space/shape/triangle_shape_function.py +5 -3
  62. warp/{fem → _src/fem}/space/tetmesh_function_space.py +5 -9
  63. warp/_src/fem/space/topology.py +461 -0
  64. warp/{fem → _src/fem}/space/trimesh_function_space.py +5 -9
  65. warp/_src/fem/types.py +114 -0
  66. warp/_src/fem/utils.py +488 -0
  67. warp/_src/jax.py +188 -0
  68. warp/_src/jax_experimental/__init__.py +14 -0
  69. warp/_src/jax_experimental/custom_call.py +389 -0
  70. warp/_src/jax_experimental/ffi.py +1286 -0
  71. warp/_src/jax_experimental/xla_ffi.py +658 -0
  72. warp/_src/marching_cubes.py +710 -0
  73. warp/_src/math.py +416 -0
  74. warp/_src/optim/__init__.py +14 -0
  75. warp/_src/optim/adam.py +165 -0
  76. warp/_src/optim/linear.py +1608 -0
  77. warp/_src/optim/sgd.py +114 -0
  78. warp/_src/paddle.py +408 -0
  79. warp/_src/render/__init__.py +14 -0
  80. warp/_src/render/imgui_manager.py +291 -0
  81. warp/_src/render/render_opengl.py +3638 -0
  82. warp/_src/render/render_usd.py +939 -0
  83. warp/_src/render/utils.py +162 -0
  84. warp/_src/sparse.py +2718 -0
  85. warp/_src/tape.py +1208 -0
  86. warp/{thirdparty → _src/thirdparty}/unittest_parallel.py +9 -2
  87. warp/_src/torch.py +393 -0
  88. warp/_src/types.py +5888 -0
  89. warp/_src/utils.py +1695 -0
  90. warp/autograd.py +12 -1054
  91. warp/bin/warp-clang.dll +0 -0
  92. warp/bin/warp.dll +0 -0
  93. warp/build.py +8 -588
  94. warp/build_dll.py +6 -721
  95. warp/codegen.py +6 -4251
  96. warp/constants.py +6 -39
  97. warp/context.py +12 -8062
  98. warp/dlpack.py +6 -444
  99. warp/examples/distributed/example_jacobi_mpi.py +4 -5
  100. warp/examples/fem/example_adaptive_grid.py +1 -1
  101. warp/examples/fem/example_apic_fluid.py +1 -1
  102. warp/examples/fem/example_burgers.py +8 -8
  103. warp/examples/fem/example_diffusion.py +1 -1
  104. warp/examples/fem/example_distortion_energy.py +1 -1
  105. warp/examples/fem/example_mixed_elasticity.py +2 -2
  106. warp/examples/fem/example_navier_stokes.py +1 -1
  107. warp/examples/fem/example_nonconforming_contact.py +7 -7
  108. warp/examples/fem/example_stokes.py +1 -1
  109. warp/examples/fem/example_stokes_transfer.py +1 -1
  110. warp/examples/fem/utils.py +2 -2
  111. warp/examples/interop/example_jax_callable.py +1 -1
  112. warp/examples/interop/example_jax_ffi_callback.py +1 -1
  113. warp/examples/interop/example_jax_kernel.py +1 -1
  114. warp/examples/tile/example_tile_mcgp.py +191 -0
  115. warp/fabric.py +6 -337
  116. warp/fem/__init__.py +159 -97
  117. warp/fem/adaptivity.py +7 -489
  118. warp/fem/cache.py +9 -648
  119. warp/fem/dirichlet.py +6 -184
  120. warp/fem/field/__init__.py +8 -109
  121. warp/fem/field/field.py +7 -652
  122. warp/fem/geometry/__init__.py +7 -18
  123. warp/fem/geometry/closest_point.py +11 -77
  124. warp/fem/linalg.py +18 -366
  125. warp/fem/operator.py +11 -369
  126. warp/fem/polynomial.py +9 -209
  127. warp/fem/space/__init__.py +5 -211
  128. warp/fem/space/basis_space.py +6 -662
  129. warp/fem/space/shape/__init__.py +41 -118
  130. warp/fem/space/topology.py +6 -437
  131. warp/fem/types.py +6 -81
  132. warp/fem/utils.py +11 -444
  133. warp/jax.py +8 -165
  134. warp/jax_experimental/__init__.py +14 -1
  135. warp/jax_experimental/custom_call.py +8 -365
  136. warp/jax_experimental/ffi.py +17 -873
  137. warp/jax_experimental/xla_ffi.py +5 -605
  138. warp/marching_cubes.py +5 -689
  139. warp/math.py +16 -393
  140. warp/native/array.h +385 -37
  141. warp/native/builtin.h +314 -37
  142. warp/native/bvh.cpp +43 -9
  143. warp/native/bvh.cu +62 -27
  144. warp/native/bvh.h +310 -309
  145. warp/native/clang/clang.cpp +102 -97
  146. warp/native/coloring.cpp +0 -1
  147. warp/native/crt.h +208 -0
  148. warp/native/exports.h +156 -0
  149. warp/native/hashgrid.cu +2 -0
  150. warp/native/intersect.h +24 -1
  151. warp/native/intersect_tri.h +44 -35
  152. warp/native/mat.h +1456 -276
  153. warp/native/mesh.cpp +4 -4
  154. warp/native/mesh.cu +4 -2
  155. warp/native/mesh.h +176 -61
  156. warp/native/quat.h +0 -52
  157. warp/native/scan.cu +2 -0
  158. warp/native/sparse.cu +7 -3
  159. warp/native/spatial.h +12 -0
  160. warp/native/tile.h +681 -89
  161. warp/native/tile_radix_sort.h +3 -3
  162. warp/native/tile_reduce.h +394 -46
  163. warp/native/tile_scan.h +4 -4
  164. warp/native/vec.h +469 -0
  165. warp/native/version.h +23 -0
  166. warp/native/volume.cpp +1 -1
  167. warp/native/volume.cu +1 -0
  168. warp/native/volume.h +1 -1
  169. warp/native/volume_builder.cu +2 -0
  170. warp/native/warp.cpp +57 -29
  171. warp/native/warp.cu +521 -250
  172. warp/native/warp.h +11 -8
  173. warp/optim/__init__.py +6 -3
  174. warp/optim/adam.py +6 -145
  175. warp/optim/linear.py +14 -1585
  176. warp/optim/sgd.py +6 -94
  177. warp/paddle.py +6 -388
  178. warp/render/__init__.py +8 -4
  179. warp/render/imgui_manager.py +7 -267
  180. warp/render/render_opengl.py +6 -3618
  181. warp/render/render_usd.py +6 -919
  182. warp/render/utils.py +6 -142
  183. warp/sparse.py +37 -2563
  184. warp/tape.py +6 -1188
  185. warp/tests/__main__.py +1 -1
  186. warp/tests/cuda/test_async.py +4 -4
  187. warp/tests/cuda/test_conditional_captures.py +1 -1
  188. warp/tests/cuda/test_multigpu.py +1 -1
  189. warp/tests/cuda/test_streams.py +58 -1
  190. warp/tests/geometry/test_bvh.py +157 -22
  191. warp/tests/geometry/test_marching_cubes.py +0 -1
  192. warp/tests/geometry/test_mesh.py +5 -3
  193. warp/tests/geometry/test_mesh_query_aabb.py +5 -12
  194. warp/tests/geometry/test_mesh_query_point.py +5 -2
  195. warp/tests/geometry/test_mesh_query_ray.py +15 -3
  196. warp/tests/geometry/test_volume_write.py +5 -5
  197. warp/tests/interop/test_dlpack.py +18 -17
  198. warp/tests/interop/test_jax.py +772 -49
  199. warp/tests/interop/test_paddle.py +1 -1
  200. warp/tests/test_adam.py +0 -1
  201. warp/tests/test_arithmetic.py +9 -9
  202. warp/tests/test_array.py +578 -100
  203. warp/tests/test_array_reduce.py +3 -3
  204. warp/tests/test_atomic.py +12 -8
  205. warp/tests/test_atomic_bitwise.py +209 -0
  206. warp/tests/test_atomic_cas.py +4 -4
  207. warp/tests/test_bool.py +2 -2
  208. warp/tests/test_builtins_resolution.py +5 -571
  209. warp/tests/test_codegen.py +33 -14
  210. warp/tests/test_conditional.py +1 -1
  211. warp/tests/test_context.py +6 -6
  212. warp/tests/test_copy.py +242 -161
  213. warp/tests/test_ctypes.py +3 -3
  214. warp/tests/test_devices.py +24 -2
  215. warp/tests/test_examples.py +16 -84
  216. warp/tests/test_fabricarray.py +35 -35
  217. warp/tests/test_fast_math.py +0 -2
  218. warp/tests/test_fem.py +56 -10
  219. warp/tests/test_fixedarray.py +3 -3
  220. warp/tests/test_func.py +8 -5
  221. warp/tests/test_generics.py +1 -1
  222. warp/tests/test_indexedarray.py +24 -24
  223. warp/tests/test_intersect.py +39 -9
  224. warp/tests/test_large.py +1 -1
  225. warp/tests/test_lerp.py +3 -1
  226. warp/tests/test_linear_solvers.py +1 -1
  227. warp/tests/test_map.py +35 -4
  228. warp/tests/test_mat.py +52 -62
  229. warp/tests/test_mat_constructors.py +4 -5
  230. warp/tests/test_mat_lite.py +1 -1
  231. warp/tests/test_mat_scalar_ops.py +121 -121
  232. warp/tests/test_math.py +34 -0
  233. warp/tests/test_module_aot.py +4 -4
  234. warp/tests/test_modules_lite.py +28 -2
  235. warp/tests/test_print.py +11 -11
  236. warp/tests/test_quat.py +93 -58
  237. warp/tests/test_runlength_encode.py +1 -1
  238. warp/tests/test_scalar_ops.py +38 -10
  239. warp/tests/test_smoothstep.py +1 -1
  240. warp/tests/test_sparse.py +126 -15
  241. warp/tests/test_spatial.py +105 -87
  242. warp/tests/test_special_values.py +6 -6
  243. warp/tests/test_static.py +7 -7
  244. warp/tests/test_struct.py +13 -2
  245. warp/tests/test_triangle_closest_point.py +48 -1
  246. warp/tests/test_types.py +27 -15
  247. warp/tests/test_utils.py +52 -52
  248. warp/tests/test_vec.py +29 -29
  249. warp/tests/test_vec_constructors.py +5 -5
  250. warp/tests/test_vec_scalar_ops.py +97 -97
  251. warp/tests/test_version.py +75 -0
  252. warp/tests/tile/test_tile.py +178 -0
  253. warp/tests/tile/test_tile_atomic_bitwise.py +403 -0
  254. warp/tests/tile/test_tile_cholesky.py +7 -4
  255. warp/tests/tile/test_tile_load.py +26 -2
  256. warp/tests/tile/test_tile_mathdx.py +3 -3
  257. warp/tests/tile/test_tile_matmul.py +1 -1
  258. warp/tests/tile/test_tile_mlp.py +2 -4
  259. warp/tests/tile/test_tile_reduce.py +214 -13
  260. warp/tests/unittest_suites.py +6 -14
  261. warp/tests/unittest_utils.py +10 -9
  262. warp/tests/walkthrough_debug.py +3 -1
  263. warp/torch.py +6 -373
  264. warp/types.py +29 -5764
  265. warp/utils.py +10 -1659
  266. {warp_lang-1.9.1.dist-info → warp_lang-1.10.0.dist-info}/METADATA +46 -99
  267. warp_lang-1.10.0.dist-info/RECORD +468 -0
  268. warp_lang-1.10.0.dist-info/licenses/licenses/Gaia-LICENSE.txt +6 -0
  269. warp_lang-1.10.0.dist-info/licenses/licenses/appdirs-LICENSE.txt +22 -0
  270. warp_lang-1.10.0.dist-info/licenses/licenses/asset_pixel_jpg-LICENSE.txt +3 -0
  271. warp_lang-1.10.0.dist-info/licenses/licenses/cuda-LICENSE.txt +1582 -0
  272. warp_lang-1.10.0.dist-info/licenses/licenses/dlpack-LICENSE.txt +201 -0
  273. warp_lang-1.10.0.dist-info/licenses/licenses/fp16-LICENSE.txt +28 -0
  274. warp_lang-1.10.0.dist-info/licenses/licenses/libmathdx-LICENSE.txt +220 -0
  275. warp_lang-1.10.0.dist-info/licenses/licenses/llvm-LICENSE.txt +279 -0
  276. warp_lang-1.10.0.dist-info/licenses/licenses/moller-LICENSE.txt +16 -0
  277. warp_lang-1.10.0.dist-info/licenses/licenses/nanovdb-LICENSE.txt +2 -0
  278. warp_lang-1.10.0.dist-info/licenses/licenses/nvrtc-LICENSE.txt +1592 -0
  279. warp_lang-1.10.0.dist-info/licenses/licenses/svd-LICENSE.txt +23 -0
  280. warp_lang-1.10.0.dist-info/licenses/licenses/unittest_parallel-LICENSE.txt +21 -0
  281. warp_lang-1.10.0.dist-info/licenses/licenses/usd-LICENSE.txt +213 -0
  282. warp_lang-1.10.0.dist-info/licenses/licenses/windingnumber-LICENSE.txt +21 -0
  283. warp/examples/assets/cartpole.urdf +0 -110
  284. warp/examples/assets/crazyflie.usd +0 -0
  285. warp/examples/assets/nv_ant.xml +0 -92
  286. warp/examples/assets/nv_humanoid.xml +0 -183
  287. warp/examples/assets/quadruped.urdf +0 -268
  288. warp/examples/optim/example_bounce.py +0 -266
  289. warp/examples/optim/example_cloth_throw.py +0 -228
  290. warp/examples/optim/example_drone.py +0 -870
  291. warp/examples/optim/example_inverse_kinematics.py +0 -182
  292. warp/examples/optim/example_inverse_kinematics_torch.py +0 -191
  293. warp/examples/optim/example_softbody_properties.py +0 -400
  294. warp/examples/optim/example_spring_cage.py +0 -245
  295. warp/examples/optim/example_trajectory.py +0 -227
  296. warp/examples/sim/example_cartpole.py +0 -143
  297. warp/examples/sim/example_cloth.py +0 -225
  298. warp/examples/sim/example_cloth_self_contact.py +0 -316
  299. warp/examples/sim/example_granular.py +0 -130
  300. warp/examples/sim/example_granular_collision_sdf.py +0 -202
  301. warp/examples/sim/example_jacobian_ik.py +0 -244
  302. warp/examples/sim/example_particle_chain.py +0 -124
  303. warp/examples/sim/example_quadruped.py +0 -203
  304. warp/examples/sim/example_rigid_chain.py +0 -203
  305. warp/examples/sim/example_rigid_contact.py +0 -195
  306. warp/examples/sim/example_rigid_force.py +0 -133
  307. warp/examples/sim/example_rigid_gyroscopic.py +0 -115
  308. warp/examples/sim/example_rigid_soft_contact.py +0 -140
  309. warp/examples/sim/example_soft_body.py +0 -196
  310. warp/examples/tile/example_tile_walker.py +0 -327
  311. warp/sim/__init__.py +0 -74
  312. warp/sim/articulation.py +0 -793
  313. warp/sim/collide.py +0 -2570
  314. warp/sim/graph_coloring.py +0 -307
  315. warp/sim/import_mjcf.py +0 -791
  316. warp/sim/import_snu.py +0 -227
  317. warp/sim/import_urdf.py +0 -579
  318. warp/sim/import_usd.py +0 -898
  319. warp/sim/inertia.py +0 -357
  320. warp/sim/integrator.py +0 -245
  321. warp/sim/integrator_euler.py +0 -2000
  322. warp/sim/integrator_featherstone.py +0 -2101
  323. warp/sim/integrator_vbd.py +0 -2487
  324. warp/sim/integrator_xpbd.py +0 -3295
  325. warp/sim/model.py +0 -4821
  326. warp/sim/particles.py +0 -121
  327. warp/sim/render.py +0 -431
  328. warp/sim/utils.py +0 -431
  329. warp/tests/sim/disabled_kinematics.py +0 -244
  330. warp/tests/sim/test_cloth.py +0 -863
  331. warp/tests/sim/test_collision.py +0 -743
  332. warp/tests/sim/test_coloring.py +0 -347
  333. warp/tests/sim/test_inertia.py +0 -161
  334. warp/tests/sim/test_model.py +0 -226
  335. warp/tests/sim/test_sim_grad.py +0 -287
  336. warp/tests/sim/test_sim_grad_bounce_linear.py +0 -212
  337. warp/tests/sim/test_sim_kinematics.py +0 -98
  338. warp/thirdparty/__init__.py +0 -0
  339. warp_lang-1.9.1.dist-info/RECORD +0 -456
  340. /warp/{fem → _src/fem}/quadrature/__init__.py +0 -0
  341. /warp/{tests/sim → _src/thirdparty}/__init__.py +0 -0
  342. /warp/{thirdparty → _src/thirdparty}/appdirs.py +0 -0
  343. /warp/{thirdparty → _src/thirdparty}/dlpack.py +0 -0
  344. {warp_lang-1.9.1.dist-info → warp_lang-1.10.0.dist-info}/WHEEL +0 -0
  345. {warp_lang-1.9.1.dist-info → warp_lang-1.10.0.dist-info}/licenses/LICENSE.md +0 -0
  346. {warp_lang-1.9.1.dist-info → warp_lang-1.10.0.dist-info}/top_level.txt +0 -0
warp/_src/utils.py ADDED
@@ -0,0 +1,1695 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from __future__ import annotations
17
+
18
+ import cProfile
19
+ import ctypes
20
+ import os
21
+ import sys
22
+ import time
23
+ import warnings
24
+ from types import ModuleType
25
+ from typing import Any, Callable
26
+
27
+ import numpy as np
28
+
29
+ import warp as wp
30
+ import warp._src.context
31
+ import warp._src.types
32
+ from warp._src.context import Devicelike
33
+ from warp._src.types import Array, DType, type_repr, types_equal
34
+
35
+ _wp_module_name_ = "warp.utils"
36
+
37
+ warnings_seen = set()
38
+
39
+
40
+ def warp_showwarning(message, category, filename, lineno, file=None, line=None):
41
+ """Version of warnings.showwarning that always prints to sys.stdout."""
42
+
43
+ if warp.config.verbose_warnings:
44
+ s = f"Warp {category.__name__}: {message} ({filename}:{lineno})\n"
45
+
46
+ if line is None:
47
+ try:
48
+ import linecache
49
+
50
+ line = linecache.getline(filename, lineno)
51
+ except Exception:
52
+ # When a warning is logged during Python shutdown, linecache
53
+ # and the import machinery don't work anymore
54
+ line = None
55
+ linecache = None
56
+
57
+ if line:
58
+ line = line.strip()
59
+ s += f" {line}\n"
60
+ else:
61
+ # simple warning
62
+ s = f"Warp {category.__name__}: {message}\n"
63
+
64
+ sys.stdout.write(s)
65
+
66
+
67
+ def warn(message, category=None, stacklevel=1, once=False):
68
+ if (category, message) in warnings_seen:
69
+ return
70
+
71
+ with warnings.catch_warnings():
72
+ warnings.simplefilter("default") # Change the filter in this process
73
+ warnings.showwarning = warp_showwarning
74
+ warnings.warn(
75
+ message,
76
+ category,
77
+ stacklevel=stacklevel + 1, # Increment stacklevel by 1 since we are in a wrapper
78
+ )
79
+
80
+ if category is DeprecationWarning or once:
81
+ warnings_seen.add((category, message))
82
+
83
+
84
+ # expand a 7-vec to a tuple of arrays
85
+ def transform_expand(t):
86
+ return wp.transform(np.array(t[0:3]), np.array(t[3:7]))
87
+
88
+
89
+ @wp.func
90
+ def quat_between_vectors(a: wp.vec3, b: wp.vec3) -> wp.quat:
91
+ """
92
+ Compute the quaternion that rotates vector a to vector b
93
+ """
94
+ a = wp.normalize(a)
95
+ b = wp.normalize(b)
96
+ c = wp.cross(a, b)
97
+ d = wp.dot(a, b)
98
+ q = wp.quat(c[0], c[1], c[2], 1.0 + d)
99
+ return wp.normalize(q)
100
+
101
+
102
+ def array_scan(in_array, out_array, inclusive=True):
103
+ """Perform a scan (prefix sum) operation on an array.
104
+
105
+ This function computes the inclusive or exclusive scan of the input array and stores the result in the output array.
106
+ The scan operation computes a running sum of elements in the array.
107
+
108
+ Args:
109
+ in_array (wp.array): Input array to scan. Must be of type int32 or float32.
110
+ out_array (wp.array): Output array to store scan results. Must match input array type and size.
111
+ inclusive (bool, optional): If True, performs an inclusive scan (includes current element in sum).
112
+ If False, performs an exclusive scan (excludes current element). Defaults to True.
113
+
114
+ Raises:
115
+ RuntimeError: If array storage devices don't match, if storage size is insufficient, or if data types are unsupported.
116
+ """
117
+
118
+ if in_array.device != out_array.device:
119
+ raise RuntimeError(f"In and out array storage devices do not match ({in_array.device} vs {out_array.device})")
120
+
121
+ if in_array.size != out_array.size:
122
+ raise RuntimeError(f"In and out array storage sizes do not match ({in_array.size} vs {out_array.size})")
123
+
124
+ if not types_equal(in_array.dtype, out_array.dtype):
125
+ raise RuntimeError(
126
+ f"In and out array data types do not match ({type_repr(in_array.dtype)} vs {type_repr(out_array.dtype)})"
127
+ )
128
+
129
+ if in_array.size == 0:
130
+ return
131
+
132
+ from warp._src.context import runtime
133
+
134
+ if in_array.device.is_cpu:
135
+ if in_array.dtype == wp.int32:
136
+ runtime.core.wp_array_scan_int_host(in_array.ptr, out_array.ptr, in_array.size, inclusive)
137
+ elif in_array.dtype == wp.float32:
138
+ runtime.core.wp_array_scan_float_host(in_array.ptr, out_array.ptr, in_array.size, inclusive)
139
+ else:
140
+ raise RuntimeError(f"Unsupported data type: {type_repr(in_array.dtype)}")
141
+ elif in_array.device.is_cuda:
142
+ if in_array.dtype == wp.int32:
143
+ runtime.core.wp_array_scan_int_device(in_array.ptr, out_array.ptr, in_array.size, inclusive)
144
+ elif in_array.dtype == wp.float32:
145
+ runtime.core.wp_array_scan_float_device(in_array.ptr, out_array.ptr, in_array.size, inclusive)
146
+ else:
147
+ raise RuntimeError(f"Unsupported data type: {type_repr(in_array.dtype)}")
148
+
149
+
150
+ def radix_sort_pairs(keys, values, count: int):
151
+ """Sort key-value pairs using radix sort.
152
+
153
+ This function sorts pairs of arrays based on the keys array, maintaining the key-value
154
+ relationship. The sort is stable and operates in linear time.
155
+ The `keys` and `values` arrays must be large enough to accommodate 2*`count` elements.
156
+
157
+ Args:
158
+ keys (wp.array): Array of keys to sort. Must be of type int32, float32, or int64.
159
+ values (wp.array): Array of values to sort along with keys. Must be of type int32.
160
+ count (int): Number of elements to sort.
161
+
162
+ Raises:
163
+ RuntimeError: If array storage devices don't match, if storage size is insufficient, or if data types are unsupported.
164
+ """
165
+ if keys.device != values.device:
166
+ raise RuntimeError(f"Keys and values array storage devices do not match ({keys.device} vs {values.device})")
167
+
168
+ if count == 0:
169
+ return
170
+
171
+ if keys.size < 2 * count or values.size < 2 * count:
172
+ raise RuntimeError("Keys and values array storage must be large enough to contain 2*count elements")
173
+
174
+ from warp._src.context import runtime
175
+
176
+ if keys.device.is_cpu:
177
+ if keys.dtype == wp.int32 and values.dtype == wp.int32:
178
+ runtime.core.wp_radix_sort_pairs_int_host(keys.ptr, values.ptr, count)
179
+ elif keys.dtype == wp.float32 and values.dtype == wp.int32:
180
+ runtime.core.wp_radix_sort_pairs_float_host(keys.ptr, values.ptr, count)
181
+ elif keys.dtype == wp.int64 and values.dtype == wp.int32:
182
+ runtime.core.wp_radix_sort_pairs_int64_host(keys.ptr, values.ptr, count)
183
+ else:
184
+ raise RuntimeError(
185
+ f"Unsupported keys and values data types: {type_repr(keys.dtype)}, {type_repr(values.dtype)}"
186
+ )
187
+ elif keys.device.is_cuda:
188
+ if keys.dtype == wp.int32 and values.dtype == wp.int32:
189
+ runtime.core.wp_radix_sort_pairs_int_device(keys.ptr, values.ptr, count)
190
+ elif keys.dtype == wp.float32 and values.dtype == wp.int32:
191
+ runtime.core.wp_radix_sort_pairs_float_device(keys.ptr, values.ptr, count)
192
+ elif keys.dtype == wp.int64 and values.dtype == wp.int32:
193
+ runtime.core.wp_radix_sort_pairs_int64_device(keys.ptr, values.ptr, count)
194
+ else:
195
+ raise RuntimeError(
196
+ f"Unsupported keys and values data types: {type_repr(keys.dtype)}, {type_repr(values.dtype)}"
197
+ )
198
+
199
+
200
+ def segmented_sort_pairs(
201
+ keys,
202
+ values,
203
+ count: int,
204
+ segment_start_indices: wp.array(dtype=wp.int32),
205
+ segment_end_indices: wp.array(dtype=wp.int32) = None,
206
+ ):
207
+ """Sort key-value pairs within segments.
208
+
209
+ This function performs a segmented sort of key-value pairs, where the sorting is done independently within each segment.
210
+ The segments are defined by their start and optionally end indices.
211
+ The `keys` and `values` arrays must be large enough to accommodate 2*`count` elements.
212
+
213
+ Args:
214
+ keys: Array of keys to sort. Must be of type int32 or float32.
215
+ values: Array of values to sort along with keys. Must be of type int32.
216
+ count: Number of elements to sort.
217
+ segment_start_indices: Array containing start index of each segment. Must be of type int32.
218
+ If segment_end_indices is None, this array must have length at least num_segments + 1,
219
+ and segment_end_indices will be inferred as segment_start_indices[1:].
220
+ If segment_end_indices is provided, this array must have length at least num_segments.
221
+ segment_end_indices: Optional array containing end index of each segment. Must be of type int32 if provided.
222
+ If None, segment_end_indices will be inferred from segment_start_indices[1:].
223
+ If provided, must have length at least num_segments.
224
+
225
+ Raises:
226
+ RuntimeError: If array storage devices don't match, if storage size is insufficient,
227
+ if segment_start_indices is not of type int32, or if data types are unsupported.
228
+ """
229
+ if keys.device != values.device:
230
+ raise RuntimeError(f"Array storage devices do not match ({keys.device} vs {values.device})")
231
+
232
+ if count == 0:
233
+ return
234
+
235
+ if keys.size < 2 * count or values.size < 2 * count:
236
+ raise RuntimeError("Array storage must be large enough to contain 2*count elements")
237
+
238
+ from warp._src.context import runtime
239
+
240
+ if segment_start_indices.dtype != wp.int32:
241
+ raise RuntimeError("segment_start_indices array must be of type int32")
242
+
243
+ # Handle case where segment_end_indices is not provided
244
+ if segment_end_indices is None:
245
+ num_segments = max(0, segment_start_indices.size - 1)
246
+
247
+ segment_end_indices = segment_start_indices[1:]
248
+ segment_end_indices_ptr = segment_end_indices.ptr
249
+ segment_start_indices_ptr = segment_start_indices.ptr
250
+ else:
251
+ if segment_end_indices.dtype != wp.int32:
252
+ raise RuntimeError("segment_end_indices array must be of type int32")
253
+
254
+ num_segments = segment_start_indices.size
255
+
256
+ segment_end_indices_ptr = segment_end_indices.ptr
257
+ segment_start_indices_ptr = segment_start_indices.ptr
258
+
259
+ if keys.device.is_cpu:
260
+ if keys.dtype == wp.int32 and values.dtype == wp.int32:
261
+ runtime.core.wp_segmented_sort_pairs_int_host(
262
+ keys.ptr,
263
+ values.ptr,
264
+ count,
265
+ segment_start_indices_ptr,
266
+ segment_end_indices_ptr,
267
+ num_segments,
268
+ )
269
+ elif keys.dtype == wp.float32 and values.dtype == wp.int32:
270
+ runtime.core.wp_segmented_sort_pairs_float_host(
271
+ keys.ptr,
272
+ values.ptr,
273
+ count,
274
+ segment_start_indices_ptr,
275
+ segment_end_indices_ptr,
276
+ num_segments,
277
+ )
278
+ else:
279
+ raise RuntimeError(f"Unsupported data type: {type_repr(keys.dtype)}")
280
+ elif keys.device.is_cuda:
281
+ if keys.dtype == wp.int32 and values.dtype == wp.int32:
282
+ runtime.core.wp_segmented_sort_pairs_int_device(
283
+ keys.ptr,
284
+ values.ptr,
285
+ count,
286
+ segment_start_indices_ptr,
287
+ segment_end_indices_ptr,
288
+ num_segments,
289
+ )
290
+ elif keys.dtype == wp.float32 and values.dtype == wp.int32:
291
+ runtime.core.wp_segmented_sort_pairs_float_device(
292
+ keys.ptr,
293
+ values.ptr,
294
+ count,
295
+ segment_start_indices_ptr,
296
+ segment_end_indices_ptr,
297
+ num_segments,
298
+ )
299
+ else:
300
+ raise RuntimeError(f"Unsupported data type: {type_repr(keys.dtype)}")
301
+
302
+
303
+ def runlength_encode(values, run_values, run_lengths, run_count=None, value_count=None):
304
+ """Perform run-length encoding on an array.
305
+
306
+ This function compresses an array by replacing consecutive identical values with a single value
307
+ and its count. For example, [1,1,1,2,2,3] becomes values=[1,2,3] and lengths=[3,2,1].
308
+
309
+ Args:
310
+ values (wp.array): Input array to encode. Must be of type int32.
311
+ run_values (wp.array): Output array to store unique values. Must be at least value_count in size.
312
+ run_lengths (wp.array): Output array to store run lengths. Must be at least value_count in size.
313
+ run_count (wp.array, optional): Optional output array to store the number of runs.
314
+ If None, returns the count as an integer.
315
+ value_count (int, optional): Number of values to process. If None, processes entire array.
316
+
317
+ Returns:
318
+ int or wp.array: Number of runs if run_count is None, otherwise returns run_count array.
319
+
320
+ Raises:
321
+ RuntimeError: If array storage devices don't match, if storage size is insufficient, or if data types are unsupported.
322
+ """
323
+ if run_values.device != values.device or run_lengths.device != values.device:
324
+ raise RuntimeError("run_values, run_lengths and values storage devices do not match")
325
+
326
+ if value_count is None:
327
+ value_count = values.size
328
+
329
+ if run_values.size < value_count or run_lengths.size < value_count:
330
+ raise RuntimeError(f"Output array storage sizes must be at least equal to value_count ({value_count})")
331
+
332
+ if not types_equal(values.dtype, run_values.dtype):
333
+ raise RuntimeError(
334
+ f"values and run_values data types do not match ({type_repr(values.dtype)} vs {type_repr(run_values.dtype)})"
335
+ )
336
+
337
+ if run_lengths.dtype != wp.int32:
338
+ raise RuntimeError("run_lengths array must be of type int32")
339
+
340
+ # User can provide a device output array for storing the number of runs
341
+ # For convenience, if no such array is provided, number of runs is returned on host
342
+ if run_count is None:
343
+ if value_count == 0:
344
+ return 0
345
+ run_count = wp.empty(shape=(1,), dtype=int, device=values.device)
346
+ host_return = True
347
+ else:
348
+ if run_count.device != values.device:
349
+ raise RuntimeError("run_count storage device does not match other arrays")
350
+ if run_count.dtype != wp.int32:
351
+ raise RuntimeError("run_count array must be of type int32")
352
+ if value_count == 0:
353
+ run_count.zero_()
354
+ return run_count
355
+ host_return = False
356
+
357
+ from warp._src.context import runtime
358
+
359
+ if values.device.is_cpu:
360
+ if values.dtype == wp.int32:
361
+ runtime.core.wp_runlength_encode_int_host(
362
+ values.ptr, run_values.ptr, run_lengths.ptr, run_count.ptr, value_count
363
+ )
364
+ else:
365
+ raise RuntimeError(f"Unsupported data type: {type_repr(values.dtype)}")
366
+ elif values.device.is_cuda:
367
+ if values.dtype == wp.int32:
368
+ runtime.core.wp_runlength_encode_int_device(
369
+ values.ptr, run_values.ptr, run_lengths.ptr, run_count.ptr, value_count
370
+ )
371
+ else:
372
+ raise RuntimeError(f"Unsupported data type: {type_repr(values.dtype)}")
373
+
374
+ if host_return:
375
+ return int(run_count.numpy()[0])
376
+ return run_count
377
+
378
+
379
+ def array_sum(values, out=None, value_count=None, axis=None):
380
+ """Compute the sum of array elements.
381
+
382
+ This function computes the sum of array elements, optionally along a specified axis.
383
+ The operation can be performed on the entire array or along a specific dimension.
384
+
385
+ Args:
386
+ values (wp.array): Input array to sum. Must be of type float32 or float64.
387
+ out (wp.array, optional): Output array to store results. If None, a new array is created.
388
+ value_count (int, optional): Number of elements to process. If None, processes entire array.
389
+ axis (int, optional): Axis along which to compute sum. If None, computes sum of all elements.
390
+
391
+ Returns:
392
+ wp.array or float: The sum result. Returns a float if axis is None and out is None,
393
+ otherwise returns the output array.
394
+
395
+ Raises:
396
+ RuntimeError: If output array storage device or data type is incompatible with input array.
397
+ """
398
+ if value_count is None:
399
+ if axis is None:
400
+ value_count = values.size
401
+ else:
402
+ value_count = values.shape[axis]
403
+
404
+ if axis is None:
405
+ output_shape = (1,)
406
+ else:
407
+
408
+ def output_dim(ax, dim):
409
+ return 1 if ax == axis else dim
410
+
411
+ output_shape = tuple(output_dim(ax, dim) for ax, dim in enumerate(values.shape))
412
+
413
+ type_size = wp._src.types.type_size(values.dtype)
414
+ scalar_type = wp._src.types.type_scalar_type(values.dtype)
415
+
416
+ # User can provide a device output array for storing the number of runs
417
+ # For convenience, if no such array is provided, number of runs is returned on host
418
+ if out is None:
419
+ host_return = True
420
+ out = wp.empty(shape=output_shape, dtype=values.dtype, device=values.device)
421
+ else:
422
+ host_return = False
423
+ if out.device != values.device:
424
+ raise RuntimeError("out storage device should match values array")
425
+ if out.dtype != values.dtype:
426
+ raise RuntimeError(f"out array should have type {values.dtype.__name__}")
427
+ if out.shape != output_shape:
428
+ raise RuntimeError(f"out array should have shape {output_shape}")
429
+
430
+ if value_count == 0:
431
+ out.zero_()
432
+ if axis is None and host_return:
433
+ return out.numpy()[0]
434
+ return out
435
+
436
+ from warp._src.context import runtime
437
+
438
+ if values.device.is_cpu:
439
+ if scalar_type == wp.float32:
440
+ native_func = runtime.core.wp_array_sum_float_host
441
+ elif scalar_type == wp.float64:
442
+ native_func = runtime.core.wp_array_sum_double_host
443
+ else:
444
+ raise RuntimeError(f"Unsupported data type: {type_repr(values.dtype)}")
445
+ elif values.device.is_cuda:
446
+ if scalar_type == wp.float32:
447
+ native_func = runtime.core.wp_array_sum_float_device
448
+ elif scalar_type == wp.float64:
449
+ native_func = runtime.core.wp_array_sum_double_device
450
+ else:
451
+ raise RuntimeError(f"Unsupported data type: {type_repr(values.dtype)}")
452
+
453
+ if axis is None:
454
+ stride = wp._src.types.type_size_in_bytes(values.dtype)
455
+ native_func(values.ptr, out.ptr, value_count, stride, type_size)
456
+
457
+ if host_return:
458
+ return out.numpy()[0]
459
+ return out
460
+
461
+ stride = values.strides[axis]
462
+ for idx in np.ndindex(output_shape):
463
+ out_offset = sum(i * s for i, s in zip(idx, out.strides))
464
+ val_offset = sum(i * s for i, s in zip(idx, values.strides))
465
+
466
+ native_func(
467
+ values.ptr + val_offset,
468
+ out.ptr + out_offset,
469
+ value_count,
470
+ stride,
471
+ type_size,
472
+ )
473
+
474
+ return out
475
+
476
+
477
+ def array_inner(a, b, out=None, count=None, axis=None):
478
+ """Compute the inner product of two arrays.
479
+
480
+ This function computes the dot product between two arrays, optionally along a specified axis.
481
+ The operation can be performed on the entire arrays or along a specific dimension.
482
+
483
+ Args:
484
+ a (wp.array): First input array.
485
+ b (wp.array): Second input array. Must match shape and type of a.
486
+ out (wp.array, optional): Output array to store results. If None, a new array is created.
487
+ count (int, optional): Number of elements to process. If None, processes entire arrays.
488
+ axis (int, optional): Axis along which to compute inner product. If None, computes on flattened arrays.
489
+
490
+ Returns:
491
+ wp.array or float: The inner product result. Returns a float if axis is None and out is None,
492
+ otherwise returns the output array.
493
+
494
+ Raises:
495
+ RuntimeError: If array storage devices, sizes, or data types are incompatible.
496
+ """
497
+ if a.size != b.size:
498
+ raise RuntimeError(f"A and b array storage sizes do not match ({a.size} vs {b.size})")
499
+
500
+ if a.device != b.device:
501
+ raise RuntimeError(f"A and b array storage devices do not match ({a.device} vs {b.device})")
502
+
503
+ if not types_equal(a.dtype, b.dtype):
504
+ raise RuntimeError(f"A and b array data types do not match ({type_repr(a.dtype)} vs {type_repr(b.dtype)})")
505
+
506
+ if count is None:
507
+ if axis is None:
508
+ count = a.size
509
+ else:
510
+ count = a.shape[axis]
511
+
512
+ if axis is None:
513
+ output_shape = (1,)
514
+ else:
515
+
516
+ def output_dim(ax, dim):
517
+ return 1 if ax == axis else dim
518
+
519
+ output_shape = tuple(output_dim(ax, dim) for ax, dim in enumerate(a.shape))
520
+
521
+ type_size = wp._src.types.type_size(a.dtype)
522
+ scalar_type = wp._src.types.type_scalar_type(a.dtype)
523
+
524
+ # User can provide a device output array for storing the number of runs
525
+ # For convenience, if no such array is provided, number of runs is returned on host
526
+ if out is None:
527
+ host_return = True
528
+ out = wp.empty(shape=output_shape, dtype=scalar_type, device=a.device)
529
+ else:
530
+ host_return = False
531
+ if out.device != a.device:
532
+ raise RuntimeError("out storage device should match values array")
533
+ if out.dtype != scalar_type:
534
+ raise RuntimeError(f"out array should have type {scalar_type.__name__}")
535
+ if out.shape != output_shape:
536
+ raise RuntimeError(f"out array should have shape {output_shape}")
537
+
538
+ if count == 0:
539
+ if axis is None and host_return:
540
+ return 0.0
541
+ out.zero_()
542
+ return out
543
+
544
+ from warp._src.context import runtime
545
+
546
+ if a.device.is_cpu:
547
+ if scalar_type == wp.float32:
548
+ native_func = runtime.core.wp_array_inner_float_host
549
+ elif scalar_type == wp.float64:
550
+ native_func = runtime.core.wp_array_inner_double_host
551
+ else:
552
+ raise RuntimeError(f"Unsupported data type: {type_repr(a.dtype)}")
553
+ elif a.device.is_cuda:
554
+ if scalar_type == wp.float32:
555
+ native_func = runtime.core.wp_array_inner_float_device
556
+ elif scalar_type == wp.float64:
557
+ native_func = runtime.core.wp_array_inner_double_device
558
+ else:
559
+ raise RuntimeError(f"Unsupported data type: {type_repr(a.dtype)}")
560
+
561
+ if axis is None:
562
+ stride_a = wp._src.types.type_size_in_bytes(a.dtype)
563
+ stride_b = wp._src.types.type_size_in_bytes(b.dtype)
564
+ native_func(a.ptr, b.ptr, out.ptr, count, stride_a, stride_b, type_size)
565
+
566
+ if host_return:
567
+ return out.numpy()[0]
568
+ return out
569
+
570
+ stride_a = a.strides[axis]
571
+ stride_b = b.strides[axis]
572
+
573
+ for idx in np.ndindex(output_shape):
574
+ out_offset = sum(i * s for i, s in zip(idx, out.strides))
575
+ a_offset = sum(i * s for i, s in zip(idx, a.strides))
576
+ b_offset = sum(i * s for i, s in zip(idx, b.strides))
577
+
578
+ native_func(
579
+ a.ptr + a_offset,
580
+ b.ptr + b_offset,
581
+ out.ptr + out_offset,
582
+ count,
583
+ stride_a,
584
+ stride_b,
585
+ type_size,
586
+ )
587
+
588
+ return out
589
+
590
+
591
+ @wp.kernel
592
+ def _array_cast_kernel(
593
+ dest: Any,
594
+ src: Any,
595
+ ):
596
+ i = wp.tid()
597
+ dest[i] = dest.dtype(src[i])
598
+
599
+
600
+ def array_cast(in_array, out_array, count=None):
601
+ """Cast elements from one array to another array with a different data type.
602
+
603
+ This function performs element-wise casting from the input array to the output array.
604
+ The arrays must have the same number of dimensions and data type shapes. If they don't match,
605
+ the arrays will be flattened and casting will be performed at the scalar level.
606
+
607
+ Args:
608
+ in_array (wp.array): Input array to cast from.
609
+ out_array (wp.array): Output array to cast to. Must have the same device as in_array.
610
+ count (int, optional): Number of elements to process. If None, processes entire array.
611
+ For multi-dimensional arrays, partial casting is not supported.
612
+
613
+ Raises:
614
+ RuntimeError: If arrays have different devices or if attempting partial casting
615
+ on multi-dimensional arrays.
616
+
617
+ Note:
618
+ If the input and output arrays have the same data type, this function will
619
+ simply copy the data without any conversion.
620
+ """
621
+ if in_array.device != out_array.device:
622
+ raise RuntimeError(f"Array storage devices do not match ({in_array.device} vs {out_array.device})")
623
+
624
+ in_array_data_shape = getattr(in_array.dtype, "_shape_", ())
625
+ out_array_data_shape = getattr(out_array.dtype, "_shape_", ())
626
+
627
+ if in_array.ndim != out_array.ndim or in_array_data_shape != out_array_data_shape:
628
+ # Number of dimensions or data type shape do not match.
629
+ # Flatten arrays and do cast at the scalar level
630
+ in_array = in_array.flatten()
631
+ out_array = out_array.flatten()
632
+
633
+ in_array_data_length = warp._src.types.type_size(in_array.dtype)
634
+ out_array_data_length = warp._src.types.type_size(out_array.dtype)
635
+ in_array_scalar_type = wp._src.types.type_scalar_type(in_array.dtype)
636
+ out_array_scalar_type = wp._src.types.type_scalar_type(out_array.dtype)
637
+
638
+ in_array = wp.array(
639
+ data=None,
640
+ ptr=in_array.ptr,
641
+ capacity=in_array.capacity,
642
+ device=in_array.device,
643
+ dtype=in_array_scalar_type,
644
+ shape=in_array.shape[0] * in_array_data_length,
645
+ )
646
+
647
+ out_array = wp.array(
648
+ data=None,
649
+ ptr=out_array.ptr,
650
+ capacity=out_array.capacity,
651
+ device=out_array.device,
652
+ dtype=out_array_scalar_type,
653
+ shape=out_array.shape[0] * out_array_data_length,
654
+ )
655
+
656
+ if count is not None:
657
+ count *= in_array_data_length
658
+
659
+ if count is None:
660
+ count = in_array.size
661
+
662
+ if in_array.ndim == 1:
663
+ dim = count
664
+ elif count < in_array.size:
665
+ raise RuntimeError("Partial cast is not supported for arrays with more than one dimension")
666
+ else:
667
+ dim = in_array.shape
668
+
669
+ if in_array.dtype == out_array.dtype:
670
+ # Same data type, can simply copy
671
+ wp.copy(dest=out_array, src=in_array, count=count)
672
+ else:
673
+ wp.launch(kernel=_array_cast_kernel, dim=dim, inputs=[out_array, in_array], device=out_array.device)
674
+
675
+
676
+ def create_warp_function(func: Callable) -> tuple[wp.Function, warp._src.context.Module]:
677
+ """Create a Warp function from a Python function.
678
+
679
+ Args:
680
+ func (Callable): A Python function to be converted to a Warp function.
681
+
682
+ Returns:
683
+ wp.Function: A Warp function created from the input function.
684
+ """
685
+
686
+ from .codegen import Adjoint, get_full_arg_spec
687
+
688
+ def unique_name(code: str):
689
+ return "func_" + hex(hash(code))[-8:]
690
+
691
+ # Create a Warp function from the input function
692
+ source = None
693
+ argspec = get_full_arg_spec(func)
694
+ key = getattr(func, "__name__", None)
695
+ if key is None:
696
+ source, _ = Adjoint.extract_function_source(func)
697
+ key = unique_name(source)
698
+ elif key == "<lambda>":
699
+ body = Adjoint.extract_lambda_source(func, only_body=True)
700
+ if body is None:
701
+ raise ValueError("Could not extract lambda source code")
702
+ key = unique_name(body)
703
+ source = f"def {key}({', '.join(argspec.args)}):\n return {body}"
704
+ else:
705
+ # use the qualname of the function as the key
706
+ key = getattr(func, "__qualname__", key)
707
+ key = key.replace(".", "_").replace(" ", "_").replace("<", "").replace(">", "_")
708
+
709
+ module = warp._src.context.get_module(f"map_{key}")
710
+ func = wp.Function(
711
+ func,
712
+ namespace="",
713
+ module=module,
714
+ key=key,
715
+ source=source,
716
+ overloaded_annotations=dict.fromkeys(argspec.args, Any),
717
+ )
718
+ return func, module
719
+
720
+
721
+ def broadcast_shapes(shapes: list[tuple[int]]) -> tuple[int]:
722
+ """Broadcast a list of shapes to a common shape.
723
+
724
+ Following the broadcasting rules of NumPy, two shapes are compatible when:
725
+ starting from the trailing dimension,
726
+ 1. the two dimensions are equal, or
727
+ 2. one of the dimensions is 1.
728
+
729
+ Example:
730
+ >>> broadcast_shapes([(3, 1, 4), (5, 4)])
731
+ (3, 5, 4)
732
+
733
+ Returns:
734
+ tuple[int]: The broadcasted shape.
735
+
736
+ Raises:
737
+ ValueError: If the shapes are not broadcastable.
738
+ """
739
+ ref = shapes[0]
740
+ for shape in shapes[1:]:
741
+ broad = []
742
+ for j in range(1, max(len(ref), len(shape)) + 1):
743
+ if j <= len(ref) and j <= len(shape):
744
+ s = shape[-j]
745
+ r = ref[-j]
746
+ if s == r:
747
+ broad.append(s)
748
+ elif s == 1 or r == 1:
749
+ broad.append(max(s, r))
750
+ else:
751
+ raise ValueError(f"Shapes {ref} and {shape} are not broadcastable")
752
+ elif j <= len(ref):
753
+ broad.append(ref[-j])
754
+ else:
755
+ broad.append(shape[-j])
756
+ ref = tuple(reversed(broad))
757
+ return ref
758
+
759
+
760
+ def map(
761
+ func: Callable | wp.Function,
762
+ *inputs: Array[DType] | Any,
763
+ out: Array[DType] | list[Array[DType]] | None = None,
764
+ return_kernel: bool = False,
765
+ block_dim=256,
766
+ device: Devicelike = None,
767
+ ) -> Array[DType] | list[Array[DType]] | wp.Kernel:
768
+ """
769
+ Map a function over the elements of one or more arrays.
770
+
771
+ You can use a Warp function, a regular Python function, or a lambda expression to map it to a set of arrays.
772
+
773
+ .. testcode::
774
+
775
+ a = wp.array([1, 2, 3], dtype=wp.float32)
776
+ b = wp.array([4, 5, 6], dtype=wp.float32)
777
+ c = wp.array([7, 8, 9], dtype=wp.float32)
778
+ result = wp.map(lambda x, y, z: x + 2.0 * y - z, a, b, c)
779
+ print(result)
780
+
781
+ .. testoutput::
782
+
783
+ [2. 4. 6.]
784
+
785
+ Clamp values in an array in place:
786
+
787
+ .. testcode::
788
+
789
+ xs = wp.array([-1.0, 0.0, 1.0], dtype=wp.float32)
790
+ wp.map(wp.clamp, xs, -0.5, 0.5, out=xs)
791
+ print(xs)
792
+
793
+ .. testoutput::
794
+
795
+ [-0.5 0. 0.5]
796
+
797
+ Note that only one of the inputs must be a Warp array. For example, it is possible
798
+ vectorize the function :func:`warp.transform_point` over a collection of points
799
+ with a given input transform as follows:
800
+
801
+ .. code-block:: python
802
+
803
+ tf = wp.transform((1.0, 2.0, 3.0), wp.quat_rpy(0.2, -0.6, 0.1))
804
+ points = wp.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], dtype=wp.vec3)
805
+ transformed = wp.map(wp.transform_point, tf, points)
806
+
807
+ Besides regular Warp arrays, other array types, such as the ``indexedarray``, are supported as well:
808
+
809
+ .. testcode::
810
+
811
+ arr = wp.array(data=np.arange(10, dtype=np.float32))
812
+ indices = wp.array([1, 3, 5, 7, 9], dtype=int)
813
+ iarr = wp.indexedarray1d(arr, [indices])
814
+ out = wp.map(lambda x: x * 10.0, iarr)
815
+ print(out)
816
+
817
+ .. testoutput::
818
+
819
+ [10. 30. 50. 70. 90.]
820
+
821
+ If multiple arrays are provided, the
822
+ `NumPy broadcasting rules <https://numpy.org/doc/stable/user/basics.broadcasting.html>`_
823
+ are applied to determine the shape of the output array.
824
+ Two shapes are compatible when:
825
+ starting from the trailing dimension,
826
+
827
+ 1. the two dimensions are equal, or
828
+ 2. one of the dimensions is 1.
829
+
830
+ For example, given arrays of shapes ``(3, 1, 4)`` and ``(5, 4)``, the broadcasted
831
+ shape is ``(3, 5, 4)``.
832
+
833
+ If no array(s) are provided to the ``out`` argument, the output array(s) are created automatically.
834
+ The data type(s) of the output array(s) are determined by the type of the return value(s) of
835
+ the function. The ``requires_grad`` flag for an automatically created output array is set to ``True``
836
+ if any of the input arrays have it set to ``True`` and the respective output array's ``dtype`` is a type that
837
+ supports differentiation.
838
+
839
+ Args:
840
+ func (Callable | Function): The function to map over the arrays.
841
+ *inputs (array | Any): The input arrays or values to pass to the function.
842
+ out (array | list[array] | None): Optional output array(s) to store the result(s). If None, the output array(s) will be created automatically.
843
+ return_kernel (bool): If True, only return the generated kernel without performing the mapping operation.
844
+ block_dim (int): The block dimension for the kernel launch.
845
+ device (Devicelike): The device on which to run the kernel.
846
+
847
+ Returns:
848
+ array | list[array] | Kernel:
849
+ The resulting array(s) of the mapping. If ``return_kernel`` is True, only returns the kernel used for mapping.
850
+ """
851
+
852
+ import builtins
853
+
854
+ from .codegen import Adjoint, Struct, StructInstance
855
+ from .types import (
856
+ is_array,
857
+ type_is_matrix,
858
+ type_is_quaternion,
859
+ type_is_transformation,
860
+ type_is_vector,
861
+ type_repr,
862
+ type_to_warp,
863
+ types_equal,
864
+ )
865
+
866
+ # mapping from struct name to its Python definition
867
+ referenced_modules: dict[str, ModuleType] = {}
868
+
869
+ def type_to_code(wp_type) -> str:
870
+ """Returns the string representation of a given Warp type."""
871
+ if is_array(wp_type):
872
+ return f"warp.array(ndim={wp_type.ndim}, dtype={type_to_code(wp_type.dtype)})"
873
+ if isinstance(wp_type, Struct):
874
+ key = f"{wp_type.__module__}.{wp_type.key}"
875
+ module = sys.modules.get(wp_type.__module__, None)
876
+ if module is not None:
877
+ referenced_modules[wp_type.__module__] = module
878
+ return key
879
+ if type_is_transformation(wp_type):
880
+ return f"warp._src.types.transformation(dtype={type_to_code(wp_type._wp_scalar_type_)})"
881
+ if type_is_quaternion(wp_type):
882
+ return f"warp._src.types.quaternion(dtype={type_to_code(wp_type._wp_scalar_type_)})"
883
+ if type_is_vector(wp_type):
884
+ return (
885
+ f"warp._src.types.vector(length={wp_type._shape_[0]}, dtype={type_to_code(wp_type._wp_scalar_type_)})"
886
+ )
887
+ if type_is_matrix(wp_type):
888
+ return f"warp._src.types.matrix(shape=({wp_type._shape_[0]}, {wp_type._shape_[1]}), dtype={type_to_code(wp_type._wp_scalar_type_)})"
889
+ if wp_type == builtins.bool:
890
+ return "bool"
891
+ if wp_type == builtins.float:
892
+ return "float"
893
+ if wp_type == builtins.int:
894
+ return "int"
895
+
896
+ name = getattr(wp_type, "__name__", None)
897
+ if name is None:
898
+ return type_repr(wp_type)
899
+ name = getattr(wp_type, "__qualname__", name)
900
+ module = getattr(wp_type, "__module__", None)
901
+ if module is not None:
902
+ referenced_modules[wp_type.__module__] = module
903
+ return wp_type.__module__ + "." + name
904
+
905
+ def get_warp_type(value):
906
+ dtype = type(value)
907
+ if issubclass(dtype, StructInstance):
908
+ # a struct
909
+ return value._cls
910
+ return type_to_warp(dtype)
911
+
912
+ # gather the arrays in the inputs
913
+ array_shapes = [a.shape for a in inputs if is_array(a)]
914
+ if len(array_shapes) == 0:
915
+ raise ValueError("map requires at least one warp.array input")
916
+ # broadcast the shapes of the arrays
917
+ out_shape = broadcast_shapes(array_shapes)
918
+
919
+ module = None
920
+ out_dtypes = None
921
+ if isinstance(func, wp.Function):
922
+ func_name = func.key
923
+ wp_func = func
924
+ else:
925
+ # check if op is a callable function
926
+ if not callable(func):
927
+ raise TypeError("func must be a callable function or a warp.Function")
928
+ wp_func, module = create_warp_function(func)
929
+ func_name = wp_func.key
930
+ if module is None:
931
+ module = warp._src.context.get_module(f"map_{func_name}")
932
+
933
+ arg_names = list(wp_func.input_types.keys())
934
+
935
+ if len(inputs) != len(arg_names):
936
+ raise TypeError(
937
+ f"Number of input arguments ({len(inputs)}) does not match expected number of function arguments ({len(arg_names)})"
938
+ )
939
+
940
+ # determine output dtype
941
+ arg_types = {}
942
+ arg_values = {}
943
+ for i, arg_name in enumerate(arg_names):
944
+ if is_array(inputs[i]):
945
+ # we will pass an element of the array to the function
946
+ arg_types[arg_name] = inputs[i].dtype
947
+ if device is None:
948
+ device = inputs[i].device
949
+ else:
950
+ # we pass the input value directly to the function
951
+ arg_types[arg_name] = get_warp_type(inputs[i])
952
+ func_or_none = wp_func.get_overload(list(arg_types.values()), {})
953
+ if func_or_none is None:
954
+ raise TypeError(
955
+ f"Function {func_name} does not support the provided argument types {', '.join(type_repr(t) for t in arg_types.values())}"
956
+ )
957
+ func = func_or_none
958
+
959
+ if func.value_type is not None:
960
+ out_dtype = func.value_type
961
+ elif func.value_func is not None:
962
+ out_dtype = func.value_func(arg_types, arg_values)
963
+ else:
964
+ func.build(None)
965
+ out_dtype = func.value_func(arg_types, arg_values)
966
+
967
+ if out_dtype is None:
968
+ raise TypeError("The provided function must return a value")
969
+
970
+ if isinstance(out_dtype, tuple) or isinstance(out_dtype, list):
971
+ out_dtypes = out_dtype
972
+ else:
973
+ out_dtypes = (out_dtype,)
974
+
975
+ if out is None:
976
+ requires_grad = any(getattr(a, "requires_grad", False) for a in inputs if is_array(a))
977
+ outputs = []
978
+ for dtype in out_dtypes:
979
+ rg = requires_grad and Adjoint.is_differentiable_value_type(dtype)
980
+ outputs.append(wp.empty(out_shape, dtype=dtype, requires_grad=rg, device=device))
981
+ elif len(out_dtypes) == 1 and is_array(out):
982
+ if not types_equal(out.dtype, out_dtypes[0]):
983
+ raise TypeError(
984
+ f"Output array dtype {type_repr(out.dtype)} does not match expected dtype {type_repr(out_dtypes[0])}"
985
+ )
986
+ if out.shape != out_shape:
987
+ raise TypeError(f"Output array shape {out.shape} does not match expected shape {out_shape}")
988
+ outputs = [out]
989
+ elif len(out_dtypes) > 1:
990
+ if isinstance(out, tuple) or isinstance(out, list):
991
+ if len(out) != len(out_dtypes):
992
+ raise TypeError(
993
+ f"Number of provided output arrays ({len(out)}) does not match expected number of function outputs ({len(out_dtypes)})"
994
+ )
995
+ for i, a in enumerate(out):
996
+ if not types_equal(a.dtype, out_dtypes[i]):
997
+ raise TypeError(
998
+ f"Output array {i} dtype {type_repr(a.dtype)} does not match expected dtype {type_repr(out_dtypes[i])}"
999
+ )
1000
+ if a.shape != out_shape:
1001
+ raise TypeError(f"Output array {i} shape {a.shape} does not match expected shape {out_shape}")
1002
+ outputs = list(out)
1003
+ else:
1004
+ raise TypeError(
1005
+ f"Invalid output provided, expected {len(out_dtypes)} Warp arrays with shape {out_shape} and dtypes ({', '.join(type_repr(t) for t in out_dtypes)})"
1006
+ )
1007
+
1008
+ # create code for a kernel
1009
+ code = """def map_kernel({kernel_args}):
1010
+ {tids} = wp.tid()
1011
+ {load_args}
1012
+ """
1013
+ if len(outputs) == 1:
1014
+ code += "__out_0[{tids}] = {func_name}({arg_names})"
1015
+ else:
1016
+ code += ", ".join(f"__o_{i}" for i in range(len(outputs)))
1017
+ code += " = {func_name}({arg_names})\n"
1018
+ for i in range(len(outputs)):
1019
+ code += f" __out_{i}" + "[{tids}]" + f" = __o_{i}\n"
1020
+
1021
+ tids = [f"__tid_{i}" for i in range(len(out_shape))]
1022
+
1023
+ load_args = []
1024
+ kernel_args = []
1025
+ for arg_name, input in zip(arg_names, inputs):
1026
+ if is_array(input):
1027
+ arr_name = f"{arg_name}_array"
1028
+ array_type_name = type(input).__name__
1029
+ kernel_args.append(
1030
+ f"{arr_name}: wp.{array_type_name}(dtype={type_to_code(input.dtype)}, ndim={input.ndim})"
1031
+ )
1032
+ shape = input.shape
1033
+ indices = []
1034
+ for i in range(1, len(shape) + 1):
1035
+ if shape[-i] == 1:
1036
+ indices.append("0")
1037
+ else:
1038
+ indices.append(tids[-i])
1039
+
1040
+ load_args.append(f"{arg_name} = {arr_name}[{', '.join(reversed(indices))}]")
1041
+ else:
1042
+ kernel_args.append(f"{arg_name}: {type_to_code(type(input))}")
1043
+ for i, o in enumerate(outputs):
1044
+ array_type_name = type(o).__name__
1045
+ kernel_args.append(f"__out_{i}: wp.{array_type_name}(dtype={type_to_code(o.dtype)}, ndim={o.ndim})")
1046
+ code = code.format(
1047
+ func_name=func_name,
1048
+ kernel_args=", ".join(kernel_args),
1049
+ arg_names=", ".join(arg_names),
1050
+ tids=", ".join(tids),
1051
+ load_args="\n ".join(load_args),
1052
+ )
1053
+ namespace = {}
1054
+ namespace.update({"wp": wp, "warp": wp, func_name: wp_func, "Any": Any})
1055
+ namespace.update(referenced_modules)
1056
+ exec(code, namespace)
1057
+
1058
+ kernel = wp.Kernel(namespace["map_kernel"], key="map_kernel", source=code, module=module)
1059
+ if return_kernel:
1060
+ return kernel
1061
+
1062
+ wp.launch(
1063
+ kernel,
1064
+ dim=out_shape,
1065
+ inputs=inputs,
1066
+ outputs=outputs,
1067
+ block_dim=block_dim,
1068
+ device=device,
1069
+ )
1070
+
1071
+ if len(outputs) == 1:
1072
+ o = outputs[0]
1073
+ else:
1074
+ o = outputs
1075
+
1076
+ return o
1077
+
1078
+
1079
+ # code snippet for invoking cProfile
1080
+ # cp = cProfile.Profile()
1081
+ # cp.enable()
1082
+ # for i in range(1000):
1083
+ # self.state = self.integrator.forward(self.model, self.state, self.sim_dt)
1084
+
1085
+ # cp.disable()
1086
+ # cp.print_stats(sort='tottime')
1087
+ # exit(0)
1088
+
1089
+
1090
+ # helper kernels for initializing NVDB volumes from a dense array
1091
+ @wp.kernel
1092
+ def copy_dense_volume_to_nano_vdb_v(volume: wp.uint64, values: wp.array(dtype=wp.vec3, ndim=3)):
1093
+ i, j, k = wp.tid()
1094
+ wp.volume_store_v(volume, i, j, k, values[i, j, k])
1095
+
1096
+
1097
+ @wp.kernel
1098
+ def copy_dense_volume_to_nano_vdb_f(volume: wp.uint64, values: wp.array(dtype=wp.float32, ndim=3)):
1099
+ i, j, k = wp.tid()
1100
+ wp.volume_store_f(volume, i, j, k, values[i, j, k])
1101
+
1102
+
1103
+ @wp.kernel
1104
+ def copy_dense_volume_to_nano_vdb_i(volume: wp.uint64, values: wp.array(dtype=wp.int32, ndim=3)):
1105
+ i, j, k = wp.tid()
1106
+ wp.volume_store_i(volume, i, j, k, values[i, j, k])
1107
+
1108
+
1109
+ # represent an edge between v0, v1 with connected faces f0, f1, and opposite vertex o0, and o1
1110
+ # winding is such that first tri can be reconstructed as {v0, v1, o0}, and second tri as { v1, v0, o1 }
1111
+ class MeshEdge:
1112
+ def __init__(self, v0, v1, o0, o1, f0, f1):
1113
+ self.v0 = v0 # vertex 0
1114
+ self.v1 = v1 # vertex 1
1115
+ self.o0 = o0 # opposite vertex 1
1116
+ self.o1 = o1 # opposite vertex 2
1117
+ self.f0 = f0 # index of tri1
1118
+ self.f1 = f1 # index of tri2
1119
+
1120
+
1121
+ class MeshAdjacency:
1122
+ def __init__(self, indices, num_tris):
1123
+ # map edges (v0, v1) to faces (f0, f1)
1124
+ self.edges = {}
1125
+ self.indices = indices
1126
+
1127
+ for index, tri in enumerate(indices):
1128
+ self.add_edge(tri[0], tri[1], tri[2], index)
1129
+ self.add_edge(tri[1], tri[2], tri[0], index)
1130
+ self.add_edge(tri[2], tri[0], tri[1], index)
1131
+
1132
+ def add_edge(self, i0, i1, o, f): # index1, index2, index3, index of triangle
1133
+ key = (min(i0, i1), max(i0, i1))
1134
+ edge = None
1135
+
1136
+ if key in self.edges:
1137
+ edge = self.edges[key]
1138
+
1139
+ if edge.f1 != -1:
1140
+ print("Detected non-manifold edge")
1141
+ return
1142
+ else:
1143
+ # update other side of the edge
1144
+ edge.o1 = o
1145
+ edge.f1 = f
1146
+ else:
1147
+ # create new edge with opposite yet to be filled
1148
+ edge = MeshEdge(i0, i1, o, -1, f, -1)
1149
+
1150
+ self.edges[key] = edge
1151
+
1152
+
1153
+ def mem_report(): # pragma: no cover
1154
+ def _mem_report(tensors, mem_type):
1155
+ """Print the selected tensors of type
1156
+ There are two major storage types in our major concern:
1157
+ - GPU: tensors transferred to CUDA devices
1158
+ - CPU: tensors remaining on the system memory (usually unimportant)
1159
+ Args:
1160
+ - tensors: the tensors of specified type
1161
+ - mem_type: 'CPU' or 'GPU' in current implementation"""
1162
+ total_numel = 0
1163
+ total_mem = 0
1164
+ visited_data = []
1165
+ for tensor in tensors:
1166
+ if tensor.is_sparse:
1167
+ continue
1168
+ # a data_ptr indicates a memory block allocated
1169
+ data_ptr = tensor.storage().data_ptr()
1170
+ if data_ptr in visited_data:
1171
+ continue
1172
+ visited_data.append(data_ptr)
1173
+
1174
+ numel = tensor.storage().size()
1175
+ total_numel += numel
1176
+ element_size = tensor.storage().element_size()
1177
+ mem = numel * element_size / 1024 / 1024 # 32bit=4Byte, MByte
1178
+ total_mem += mem
1179
+ print(f"Type: {mem_type:<4} | Total Tensors: {total_numel:>8} | Used Memory: {total_mem:>8.2f} MB")
1180
+
1181
+ import gc
1182
+
1183
+ import torch
1184
+
1185
+ gc.collect()
1186
+
1187
+ LEN = 65
1188
+ objects = gc.get_objects()
1189
+ # print('%s\t%s\t\t\t%s' %('Element type', 'Size', 'Used MEM(MBytes)') )
1190
+ tensors = [obj for obj in objects if torch.is_tensor(obj)]
1191
+ cuda_tensors = [t for t in tensors if t.is_cuda]
1192
+ host_tensors = [t for t in tensors if not t.is_cuda]
1193
+ _mem_report(cuda_tensors, "GPU")
1194
+ _mem_report(host_tensors, "CPU")
1195
+ print("=" * LEN)
1196
+
1197
+
1198
+ class ScopedDevice:
1199
+ """A context manager to temporarily change the current default device.
1200
+
1201
+ For CUDA devices, this context manager makes the device's CUDA context
1202
+ current and restores the previous CUDA context on exit. This is handy when
1203
+ running Warp scripts as part of a bigger pipeline because it avoids any side
1204
+ effects of changing the CUDA context in the enclosed code.
1205
+
1206
+ Attributes:
1207
+ device (Device): The device that will temporarily become the default
1208
+ device within the context.
1209
+ saved_device (Device): The previous default device. This is restored as
1210
+ the default device on exiting the context.
1211
+ """
1212
+
1213
+ def __init__(self, device: Devicelike):
1214
+ """Initializes the context manager with a device.
1215
+
1216
+ Args:
1217
+ device: The device that will temporarily become the default device
1218
+ within the context.
1219
+ """
1220
+ self.device = wp.get_device(device)
1221
+
1222
+ def __enter__(self):
1223
+ # save the previous default device
1224
+ self.saved_device = self.device.runtime.default_device
1225
+
1226
+ # make this the default device
1227
+ self.device.runtime.default_device = self.device
1228
+
1229
+ # make it the current CUDA device so that device alias "cuda" will evaluate to this device
1230
+ self.device.context_guard.__enter__()
1231
+
1232
+ return self.device
1233
+
1234
+ def __exit__(self, exc_type, exc_value, traceback):
1235
+ # restore original CUDA context
1236
+ self.device.context_guard.__exit__(exc_type, exc_value, traceback)
1237
+
1238
+ # restore original target device
1239
+ self.device.runtime.default_device = self.saved_device
1240
+
1241
+
1242
+ class ScopedStream:
1243
+ """A context manager to temporarily change the current stream on a device.
1244
+
1245
+ Attributes:
1246
+ stream (Stream or None): The stream that will temporarily become the device's
1247
+ default stream within the context.
1248
+ saved_stream (Stream): The device's previous current stream. This is
1249
+ restored as the device's current stream on exiting the context.
1250
+ sync_enter (bool): Whether to synchronize this context's stream with
1251
+ the device's previous current stream on entering the context.
1252
+ sync_exit (bool): Whether to synchronize the device's previous current
1253
+ with this context's stream on exiting the context.
1254
+ device (Device): The device associated with the stream.
1255
+ """
1256
+
1257
+ def __init__(self, stream: wp.Stream | None, sync_enter: bool = True, sync_exit: bool = False):
1258
+ """Initializes the context manager with a stream and synchronization options.
1259
+
1260
+ Args:
1261
+ stream: The stream that will temporarily become the device's
1262
+ default stream within the context.
1263
+ sync_enter (bool): Whether to synchronize this context's stream with
1264
+ the device's previous current stream on entering the context.
1265
+ sync_exit (bool): Whether to synchronize the device's previous current
1266
+ with this context's stream on exiting the context.
1267
+ """
1268
+
1269
+ self.stream = stream
1270
+ self.sync_enter = sync_enter
1271
+ self.sync_exit = sync_exit
1272
+ if stream is not None:
1273
+ self.device = stream.device
1274
+ self.device_scope = ScopedDevice(self.device)
1275
+
1276
+ def __enter__(self):
1277
+ if self.stream is not None:
1278
+ self.device_scope.__enter__()
1279
+ self.saved_stream = self.device.stream
1280
+ self.device.set_stream(self.stream, self.sync_enter)
1281
+
1282
+ return self.stream
1283
+
1284
+ def __exit__(self, exc_type, exc_value, traceback):
1285
+ if self.stream is not None:
1286
+ self.device.set_stream(self.saved_stream, self.sync_exit)
1287
+ self.device_scope.__exit__(exc_type, exc_value, traceback)
1288
+
1289
+
1290
+ TIMING_KERNEL = 1
1291
+ TIMING_KERNEL_BUILTIN = 2
1292
+ TIMING_MEMCPY = 4
1293
+ TIMING_MEMSET = 8
1294
+ TIMING_GRAPH = 16
1295
+ TIMING_ALL = 0xFFFFFFFF
1296
+
1297
+
1298
+ # timer utils
1299
+ class ScopedTimer:
1300
+ indent = -1
1301
+
1302
+ enabled = True
1303
+
1304
+ def __init__(
1305
+ self,
1306
+ name: str,
1307
+ active: bool = True,
1308
+ print: bool = True,
1309
+ detailed: bool = False,
1310
+ dict: dict[str, list[float]] | None = None,
1311
+ use_nvtx: bool = False,
1312
+ color: int | str = "rapids",
1313
+ synchronize: bool = False,
1314
+ cuda_filter: int = 0,
1315
+ report_func: Callable[[list[TimingResult], str], None] | None = None,
1316
+ skip_tape: bool = False,
1317
+ ):
1318
+ """Context manager object for a timer
1319
+
1320
+ Parameters:
1321
+ name: Name of timer
1322
+ active: Enables this timer
1323
+ print: At context manager exit, print elapsed time to ``sys.stdout``
1324
+ detailed: Collects additional profiling data using cProfile and calls ``print_stats()`` at context exit
1325
+ dict: A dictionary of lists to which the elapsed time will be appended using ``name`` as a key
1326
+ use_nvtx: If true, timing functionality is replaced by an NVTX range
1327
+ color: ARGB value (e.g. 0x00FFFF) or color name (e.g. 'cyan') associated with the NVTX range
1328
+ synchronize: Synchronize the CPU thread with any outstanding CUDA work to return accurate GPU timings
1329
+ cuda_filter: Filter flags for CUDA activity timing, e.g. ``warp.TIMING_KERNEL`` or ``warp.TIMING_ALL``
1330
+ report_func: A callback function to print the activity report.
1331
+ If ``None``, :func:`wp.timing_print() <timing_print>` will be used.
1332
+ skip_tape: If true, the timer will not be recorded in the tape
1333
+
1334
+ Attributes:
1335
+ extra_msg (str): Can be set to a string that will be added to the printout at context exit.
1336
+ elapsed (float): The duration of the ``with`` block used with this object
1337
+ timing_results (list[TimingResult]): The list of activity timing results, if collection was requested using ``cuda_filter``
1338
+ """
1339
+ self.name = name
1340
+ self.active = active and self.enabled
1341
+ self.print = print
1342
+ self.detailed = detailed
1343
+ self.dict = dict
1344
+ self.use_nvtx = use_nvtx
1345
+ self.color = color
1346
+ self.synchronize = synchronize
1347
+ self.skip_tape = skip_tape
1348
+ self.elapsed = 0.0
1349
+ self.cuda_filter = cuda_filter
1350
+ self.report_func = report_func or wp.timing_print
1351
+ self.extra_msg = "" # Can be used to add to the message printed at manager exit
1352
+
1353
+ if self.dict is not None:
1354
+ if name not in self.dict:
1355
+ self.dict[name] = []
1356
+
1357
+ def __enter__(self):
1358
+ if not self.skip_tape and warp._src.context.runtime is not None and warp._src.context.runtime.tape is not None:
1359
+ warp._src.context.runtime.tape.record_scope_begin(self.name)
1360
+ if self.active:
1361
+ if self.synchronize:
1362
+ wp.synchronize()
1363
+
1364
+ if self.cuda_filter:
1365
+ # begin CUDA activity collection, synchronizing if needed
1366
+ timing_begin(self.cuda_filter, synchronize=not self.synchronize)
1367
+
1368
+ if self.detailed:
1369
+ self.cp = cProfile.Profile()
1370
+ self.cp.clear()
1371
+ self.cp.enable()
1372
+
1373
+ if self.use_nvtx:
1374
+ import nvtx
1375
+
1376
+ self.nvtx_range_id = nvtx.start_range(self.name, color=self.color)
1377
+
1378
+ if self.print:
1379
+ ScopedTimer.indent += 1
1380
+
1381
+ if warp.config.verbose:
1382
+ indent = " " * ScopedTimer.indent
1383
+ print(f"{indent}{self.name} ...", flush=True)
1384
+
1385
+ self.start = time.perf_counter_ns()
1386
+
1387
+ return self
1388
+
1389
+ def __exit__(self, exc_type, exc_value, traceback):
1390
+ if not self.skip_tape and warp._src.context.runtime is not None and warp._src.context.runtime.tape is not None:
1391
+ warp._src.context.runtime.tape.record_scope_end()
1392
+ if self.active:
1393
+ if self.synchronize:
1394
+ wp.synchronize()
1395
+
1396
+ self.elapsed = (time.perf_counter_ns() - self.start) / 1000000.0
1397
+
1398
+ if self.use_nvtx:
1399
+ import nvtx
1400
+
1401
+ nvtx.end_range(self.nvtx_range_id)
1402
+
1403
+ if self.detailed:
1404
+ self.cp.disable()
1405
+ self.cp.print_stats(sort="tottime")
1406
+
1407
+ if self.cuda_filter:
1408
+ # end CUDA activity collection, synchronizing if needed
1409
+ self.timing_results = timing_end(synchronize=not self.synchronize)
1410
+ else:
1411
+ self.timing_results = []
1412
+
1413
+ if self.dict is not None:
1414
+ self.dict[self.name].append(self.elapsed)
1415
+
1416
+ if self.print:
1417
+ indent = " " * ScopedTimer.indent
1418
+
1419
+ if self.timing_results:
1420
+ self.report_func(self.timing_results, indent=indent)
1421
+ print()
1422
+
1423
+ if self.extra_msg:
1424
+ print(f"{indent}{self.name} took {self.elapsed:.2f} ms {self.extra_msg}")
1425
+ else:
1426
+ print(f"{indent}{self.name} took {self.elapsed:.2f} ms")
1427
+
1428
+ ScopedTimer.indent -= 1
1429
+
1430
+
1431
+ # Allow temporarily enabling/disabling mempool allocators
1432
+ class ScopedMempool:
1433
+ def __init__(self, device: Devicelike, enable: bool):
1434
+ self.device = wp.get_device(device)
1435
+ self.enable = enable
1436
+
1437
+ def __enter__(self):
1438
+ self.saved_setting = wp.is_mempool_enabled(self.device)
1439
+ wp.set_mempool_enabled(self.device, self.enable)
1440
+
1441
+ def __exit__(self, exc_type, exc_value, traceback):
1442
+ wp.set_mempool_enabled(self.device, self.saved_setting)
1443
+
1444
+
1445
+ # Allow temporarily enabling/disabling mempool access
1446
+ class ScopedMempoolAccess:
1447
+ def __init__(self, target_device: Devicelike, peer_device: Devicelike, enable: bool):
1448
+ self.target_device = target_device
1449
+ self.peer_device = peer_device
1450
+ self.enable = enable
1451
+
1452
+ def __enter__(self):
1453
+ self.saved_setting = wp.is_mempool_access_enabled(self.target_device, self.peer_device)
1454
+ wp.set_mempool_access_enabled(self.target_device, self.peer_device, self.enable)
1455
+
1456
+ def __exit__(self, exc_type, exc_value, traceback):
1457
+ wp.set_mempool_access_enabled(self.target_device, self.peer_device, self.saved_setting)
1458
+
1459
+
1460
+ # Allow temporarily enabling/disabling peer access
1461
+ class ScopedPeerAccess:
1462
+ def __init__(self, target_device: Devicelike, peer_device: Devicelike, enable: bool):
1463
+ self.target_device = target_device
1464
+ self.peer_device = peer_device
1465
+ self.enable = enable
1466
+
1467
+ def __enter__(self):
1468
+ self.saved_setting = wp.is_peer_access_enabled(self.target_device, self.peer_device)
1469
+ wp.set_peer_access_enabled(self.target_device, self.peer_device, self.enable)
1470
+
1471
+ def __exit__(self, exc_type, exc_value, traceback):
1472
+ wp.set_peer_access_enabled(self.target_device, self.peer_device, self.saved_setting)
1473
+
1474
+
1475
+ class ScopedCapture:
1476
+ def __init__(self, device: Devicelike = None, stream=None, force_module_load=None, external=False):
1477
+ self.device = device
1478
+ self.stream = stream
1479
+ self.force_module_load = force_module_load
1480
+ self.external = external
1481
+ self.active = False
1482
+ self.graph = None
1483
+
1484
+ def __enter__(self):
1485
+ try:
1486
+ wp.capture_begin(
1487
+ device=self.device, stream=self.stream, force_module_load=self.force_module_load, external=self.external
1488
+ )
1489
+ self.active = True
1490
+ return self
1491
+ except:
1492
+ raise
1493
+
1494
+ def __exit__(self, exc_type, exc_value, traceback):
1495
+ if self.active:
1496
+ try:
1497
+ self.graph = wp.capture_end(device=self.device, stream=self.stream)
1498
+ except Exception:
1499
+ # Only report this exception if __exit__() was reached without an exception,
1500
+ # otherwise re-raise the original exception.
1501
+ if exc_type is None:
1502
+ raise
1503
+ finally:
1504
+ self.active = False
1505
+
1506
+
1507
+ def check_p2p():
1508
+ """Check if the machine is configured properly for peer-to-peer transfers.
1509
+
1510
+ Returns:
1511
+ A Boolean indicating whether the machine is configured properly for peer-to-peer transfers.
1512
+ On Linux, this function attempts to determine if IOMMU is enabled and will return `False` if IOMMU is detected.
1513
+ On other operating systems, it always return `True`.
1514
+ """
1515
+
1516
+ # HACK: allow disabling P2P tests using an environment variable
1517
+ disable_p2p_tests = os.getenv("WARP_DISABLE_P2P_TESTS", default="0")
1518
+ if int(disable_p2p_tests):
1519
+ return False
1520
+
1521
+ if sys.platform == "linux":
1522
+ # IOMMU enablement can affect peer-to-peer transfers.
1523
+ # On modern Linux, there should be IOMMU-related entries in the /sys file system.
1524
+ # This should be more reliable than checking kernel logs like dmesg.
1525
+ if os.path.isdir("/sys/class/iommu") and os.listdir("/sys/class/iommu"):
1526
+ return False
1527
+ if os.path.isdir("/sys/kernel/iommu_groups") and os.listdir("/sys/kernel/iommu_groups"):
1528
+ return False
1529
+
1530
+ return True
1531
+
1532
+
1533
+ class timing_result_t(ctypes.Structure):
1534
+ """CUDA timing struct for fetching values from C++"""
1535
+
1536
+ _fields_ = (
1537
+ ("context", ctypes.c_void_p),
1538
+ ("name", ctypes.c_char_p),
1539
+ ("filter", ctypes.c_int),
1540
+ ("elapsed", ctypes.c_float),
1541
+ )
1542
+
1543
+
1544
+ class TimingResult:
1545
+ """Timing result for a single activity."""
1546
+
1547
+ def __init__(self, device, name, filter, elapsed):
1548
+ self.device: warp._src.context.Device = device
1549
+ """The device where the activity was recorded."""
1550
+
1551
+ self.name: str = name
1552
+ """The activity name."""
1553
+
1554
+ self.filter: int = filter
1555
+ """The type of activity (e.g., ``warp.TIMING_KERNEL``)."""
1556
+
1557
+ self.elapsed: float = elapsed
1558
+ """The elapsed time in milliseconds."""
1559
+
1560
+
1561
+ def timing_begin(cuda_filter: int = TIMING_ALL, synchronize: bool = True) -> None:
1562
+ """Begin detailed activity timing.
1563
+
1564
+ Parameters:
1565
+ cuda_filter: Filter flags for CUDA activity timing, e.g. ``warp.TIMING_KERNEL`` or ``warp.TIMING_ALL``
1566
+ synchronize: Whether to synchronize all CUDA devices before timing starts
1567
+ """
1568
+
1569
+ if synchronize:
1570
+ warp.synchronize()
1571
+
1572
+ warp._src.context.runtime.core.wp_cuda_timing_begin(cuda_filter)
1573
+
1574
+
1575
+ def timing_end(synchronize: bool = True) -> list[TimingResult]:
1576
+ """End detailed activity timing.
1577
+
1578
+ Parameters:
1579
+ synchronize: Whether to synchronize all CUDA devices before timing ends
1580
+
1581
+ Returns:
1582
+ A list of :class:`TimingResult` objects for all recorded activities.
1583
+ """
1584
+
1585
+ if synchronize:
1586
+ warp.synchronize()
1587
+
1588
+ # get result count
1589
+ count = warp._src.context.runtime.core.wp_cuda_timing_get_result_count()
1590
+
1591
+ # get result array from C++
1592
+ result_buffer = (timing_result_t * count)()
1593
+ warp._src.context.runtime.core.wp_cuda_timing_end(ctypes.byref(result_buffer), count)
1594
+
1595
+ # prepare Python result list
1596
+ results = []
1597
+ for r in result_buffer:
1598
+ device = warp._src.context.runtime.context_map.get(r.context)
1599
+ filter = r.filter
1600
+ elapsed = r.elapsed
1601
+
1602
+ name = r.name.decode()
1603
+ if filter == TIMING_KERNEL:
1604
+ if name.endswith("forward"):
1605
+ # strip trailing "_cuda_kernel_forward"
1606
+ name = f"forward kernel {name[:-20]}"
1607
+ else:
1608
+ # strip trailing "_cuda_kernel_backward"
1609
+ name = f"backward kernel {name[:-21]}"
1610
+ elif filter == TIMING_KERNEL_BUILTIN:
1611
+ if name.startswith("wp::"):
1612
+ name = f"builtin kernel {name[4:]}"
1613
+ else:
1614
+ name = f"builtin kernel {name}"
1615
+
1616
+ results.append(TimingResult(device, name, filter, elapsed))
1617
+
1618
+ return results
1619
+
1620
+
1621
+ def timing_print(results: list[TimingResult], indent: str = "") -> None:
1622
+ """Print timing results.
1623
+
1624
+ Parameters:
1625
+ results: List of :class:`TimingResult` objects to print.
1626
+ indent: Optional indentation to prepend to all output lines.
1627
+ """
1628
+
1629
+ if not results:
1630
+ print("No activity")
1631
+ return
1632
+
1633
+ class Aggregate:
1634
+ def __init__(self, count=0, elapsed=0):
1635
+ self.count = count
1636
+ self.elapsed = elapsed
1637
+
1638
+ device_totals = {}
1639
+ activity_totals = {}
1640
+
1641
+ max_name_len = len("Activity")
1642
+ for r in results:
1643
+ name_len = len(r.name)
1644
+ max_name_len = max(max_name_len, name_len)
1645
+
1646
+ activity_width = max_name_len + 1
1647
+ activity_dashes = "-" * activity_width
1648
+
1649
+ print(f"{indent}CUDA timeline:")
1650
+ print(f"{indent}----------------+---------+{activity_dashes}")
1651
+ print(f"{indent}Time | Device | Activity")
1652
+ print(f"{indent}----------------+---------+{activity_dashes}")
1653
+ for r in results:
1654
+ device_agg = device_totals.get(r.device.alias)
1655
+ if device_agg is None:
1656
+ device_totals[r.device.alias] = Aggregate(count=1, elapsed=r.elapsed)
1657
+ else:
1658
+ device_agg.count += 1
1659
+ device_agg.elapsed += r.elapsed
1660
+
1661
+ activity_agg = activity_totals.get(r.name)
1662
+ if activity_agg is None:
1663
+ activity_totals[r.name] = Aggregate(count=1, elapsed=r.elapsed)
1664
+ else:
1665
+ activity_agg.count += 1
1666
+ activity_agg.elapsed += r.elapsed
1667
+
1668
+ print(f"{indent}{r.elapsed:12.6f} ms | {r.device.alias:7s} | {r.name}")
1669
+
1670
+ print()
1671
+ print(f"{indent}CUDA activity summary:")
1672
+ print(f"{indent}----------------+---------+{activity_dashes}")
1673
+ print(f"{indent}Total time | Count | Activity")
1674
+ print(f"{indent}----------------+---------+{activity_dashes}")
1675
+ for name, agg in activity_totals.items():
1676
+ print(f"{indent}{agg.elapsed:12.6f} ms | {agg.count:7d} | {name}")
1677
+
1678
+ print()
1679
+ print(f"{indent}CUDA device summary:")
1680
+ print(f"{indent}----------------+---------+{activity_dashes}")
1681
+ print(f"{indent}Total time | Count | Device")
1682
+ print(f"{indent}----------------+---------+{activity_dashes}")
1683
+ for device, agg in device_totals.items():
1684
+ print(f"{indent}{agg.elapsed:12.6f} ms | {agg.count:7d} | {device}")
1685
+
1686
+
1687
+ def get_deprecated_api(module, namespace, attr_name):
1688
+ # if not attr_name.startswith("__"):
1689
+ # module_name = module.__name__.split(".")[-1]
1690
+ # warn(
1691
+ # f"The symbol `{namespace}.{module_name}.{attr_name}` is internal and will be removed from the public API.",
1692
+ # DeprecationWarning,
1693
+ # )
1694
+
1695
+ return getattr(module, attr_name)