nablaengine 1.0.2__py3-none-any.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.
- nablaengine/__init__.py +4 -0
- nablaengine/_fixtures/README.md +19 -0
- nablaengine/_fixtures/data/mf_s0.npz +0 -0
- nablaengine/_fixtures/mjlab/LICENSE +27 -0
- nablaengine/_fixtures/mjlab/README.md +113 -0
- nablaengine/_fixtures/mjlab/g1_meta.json +32 -0
- nablaengine/_fixtures/mjlab/g1_train.mjb +0 -0
- nablaengine/_optional.py +30 -0
- nablaengine/_paths.py +38 -0
- nablaengine/actuators/__init__.py +169 -0
- nablaengine/actuators/bam.py +306 -0
- nablaengine/actuators/bam_params/LICENSE +202 -0
- nablaengine/actuators/bam_params/xl330/m6.json +19 -0
- nablaengine/boxbox.py +259 -0
- nablaengine/ccd.py +1122 -0
- nablaengine/checks.py +376 -0
- nablaengine/cuda.py +483 -0
- nablaengine/dist_query.py +628 -0
- nablaengine/dual.py +223 -0
- nablaengine/dyn_query.py +685 -0
- nablaengine/engines.py +114 -0
- nablaengine/envs/__init__.py +24 -0
- nablaengine/envs/brax.py +165 -0
- nablaengine/envs/convert.py +771 -0
- nablaengine/envs/dmc.py +523 -0
- nablaengine/envs/env.py +233 -0
- nablaengine/envs/kin.py +371 -0
- nablaengine/envs/ops.py +134 -0
- nablaengine/envs/rewards.py +57 -0
- nablaengine/fixtures.py +243 -0
- nablaengine/forest_engine/__init__.py +0 -0
- nablaengine/forest_engine/adjoint.py +1726 -0
- nablaengine/forest_engine/adjoint_contact.py +493 -0
- nablaengine/forest_engine/bam_hooks.py +248 -0
- nablaengine/forest_engine/body_params.py +1007 -0
- nablaengine/forest_engine/capacity_diag.py +116 -0
- nablaengine/forest_engine/ccd_coop.py +250 -0
- nablaengine/forest_engine/chol_blk.py +80 -0
- nablaengine/forest_engine/contact_forces.py +142 -0
- nablaengine/forest_engine/contact_vjp.py +462 -0
- nablaengine/forest_engine/convex.py +1331 -0
- nablaengine/forest_engine/cylinder.py +73 -0
- nablaengine/forest_engine/dist_device.py +923 -0
- nablaengine/forest_engine/dyn_device.py +696 -0
- nablaengine/forest_engine/ellipsoid.py +179 -0
- nablaengine/forest_engine/elliptic.py +272 -0
- nablaengine/forest_engine/equality.py +842 -0
- nablaengine/forest_engine/floss.py +148 -0
- nablaengine/forest_engine/foot_offset.py +368 -0
- nablaengine/forest_engine/free_gyro.py +288 -0
- nablaengine/forest_engine/host.py +530 -0
- nablaengine/forest_engine/kdof64.py +127 -0
- nablaengine/forest_engine/kinematics.py +320 -0
- nablaengine/forest_engine/margin.py +167 -0
- nablaengine/forest_engine/margin_convex.py +326 -0
- nablaengine/forest_engine/midphase.py +439 -0
- nablaengine/forest_engine/model_hooks.py +913 -0
- nablaengine/forest_engine/motor_hooks.py +50 -0
- nablaengine/forest_engine/muscle.py +485 -0
- nablaengine/forest_engine/nb128.py +118 -0
- nablaengine/forest_engine/nb64.py +163 -0
- nablaengine/forest_engine/noslip.py +1124 -0
- nablaengine/forest_engine/nv128.py +1944 -0
- nablaengine/forest_engine/object_size.py +283 -0
- nablaengine/forest_engine/replay_guard.py +40 -0
- nablaengine/forest_engine/root_spread.py +126 -0
- nablaengine/forest_engine/solref.py +74 -0
- nablaengine/forest_engine/source.py +1464 -0
- nablaengine/forest_engine/sparse_pattern.py +527 -0
- nablaengine/forest_engine/spatial.py +1045 -0
- nablaengine/forest_engine/step.py +3083 -0
- nablaengine/forest_engine/surrogate.py +498 -0
- nablaengine/forest_engine/tape.py +199 -0
- nablaengine/forest_engine/tendon.py +845 -0
- nablaengine/forest_engine/terrain.py +1059 -0
- nablaengine/forest_engine/world_forces.py +166 -0
- nablaengine/forest_engine/world_params.py +230 -0
- nablaengine/g1_engine/__init__.py +0 -0
- nablaengine/g1_engine/adjoint.py +1661 -0
- nablaengine/g1_engine/adjoint_contact.py +577 -0
- nablaengine/g1_engine/bam_hooks.py +596 -0
- nablaengine/g1_engine/condim4.py +245 -0
- nablaengine/g1_engine/contact_forces.py +500 -0
- nablaengine/g1_engine/cylccd.py +1158 -0
- nablaengine/g1_engine/cylinder.py +216 -0
- nablaengine/g1_engine/elliptic.py +565 -0
- nablaengine/g1_engine/exact_replay.py +61 -0
- nablaengine/g1_engine/host.py +358 -0
- nablaengine/g1_engine/kinematics.py +320 -0
- nablaengine/g1_engine/mesh.py +305 -0
- nablaengine/g1_engine/mesh_tables.py +79 -0
- nablaengine/g1_engine/model_hooks.py +919 -0
- nablaengine/g1_engine/motor_hooks.py +70 -0
- nablaengine/g1_engine/replay_guard.py +55 -0
- nablaengine/g1_engine/source.py +1107 -0
- nablaengine/g1_engine/sphbox.py +93 -0
- nablaengine/g1_engine/step.py +3716 -0
- nablaengine/g1_engine/tape.py +173 -0
- nablaengine/g1_engine/world_params.py +447 -0
- nablaengine/identity.py +401 -0
- nablaengine/jax_ffi.py +2536 -0
- nablaengine/model/__init__.py +1 -0
- nablaengine/model/capability.py +694 -0
- nablaengine/model/fields.py +317 -0
- nablaengine/model/gravcomp.py +64 -0
- nablaengine/model/invweight.py +145 -0
- nablaengine/motor.py +143 -0
- nablaengine/object_geometry.py +609 -0
- nablaengine/params.py +258 -0
- nablaengine/provenance.py +196 -0
- nablaengine/reference/__init__.py +0 -0
- nablaengine/reference/adjoint_groups.py +226 -0
- nablaengine/reference/jax64.py +690 -0
- nablaengine/reference/warp_physics.py +262 -0
- nablaengine/sensors/__init__.py +4 -0
- nablaengine/sensors/cameras.py +285 -0
- nablaengine/sensors/data/LIVOX_MID360_LICENSE +21 -0
- nablaengine/sensors/data/livox_mid360.npz +0 -0
- nablaengine/sensors/g1.py +521 -0
- nablaengine/sensors/jax_rays.py +364 -0
- nablaengine/sensors/optix_rays.py +725 -0
- nablaengine/sensors/raycore.py +630 -0
- nablaengine/sensors/raygrad.py +374 -0
- nablaengine/sensors/raygrad_cuda.py +191 -0
- nablaengine/sensors/robot_mesh.py +273 -0
- nablaengine/sensors/torch_rays.py +275 -0
- nablaengine/terrain.py +424 -0
- nablaengine/torch_ffi.py +1328 -0
- nablaengine/workdir.py +37 -0
- nablaengine-1.0.2.dist-info/METADATA +236 -0
- nablaengine-1.0.2.dist-info/RECORD +136 -0
- nablaengine-1.0.2.dist-info/WHEEL +5 -0
- nablaengine-1.0.2.dist-info/licenses/LICENSE +202 -0
- nablaengine-1.0.2.dist-info/licenses/NOTICE +23 -0
- nablaengine-1.0.2.dist-info/licenses/THIRD_PARTY_NOTICES.md +176 -0
- nablaengine-1.0.2.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
"""JAX interface of the ray library (raycore): setup() uploads the static scene (terrain, robot meshes) to the GPU
|
|
2
|
+
devices once; cast() casts batched rays inside jit (an XLA FFI call). cast(..., grad="first_order") makes the hit
|
|
3
|
+
distance differentiable (raygrad: w.r.t. the sensor pose, the robot's body poses and the object slots' poses)."""
|
|
4
|
+
import ctypes
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
|
|
9
|
+
from nablaengine.sensors import raycore, raygrad
|
|
10
|
+
from nablaengine.sensors.torch_rays import _Scene, cell_tops
|
|
11
|
+
|
|
12
|
+
_STATE = {}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _lib():
|
|
16
|
+
if "lib" not in _STATE:
|
|
17
|
+
import jax
|
|
18
|
+
from nablaengine.jax_ffi import ensure_jax_ffi
|
|
19
|
+
ensure_jax_ffi()
|
|
20
|
+
dev = jax.devices("gpu")[0]
|
|
21
|
+
arch = "sm_" + str(dev.compute_capability).replace(".", "")
|
|
22
|
+
lib = ctypes.cdll.LoadLibrary(str(raycore.build(arch, jax.ffi.include_dir())))
|
|
23
|
+
lib.dk_rays_set_scene.argtypes = [ctypes.c_int, ctypes.c_void_p]
|
|
24
|
+
assert lib.dk_scene_size() == ctypes.sizeof(_Scene), "Scene layout mismatch"
|
|
25
|
+
jax.ffi.register_ffi_target("dk_scene_rays", jax.ffi.pycapsule(lib.DkSceneRays), platform="CUDA")
|
|
26
|
+
_STATE["lib"] = lib
|
|
27
|
+
return _STATE["lib"]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def setup(terrain=None, cell=1.0, floor_z=None, robot=None, nbody=0, exclude_body=-1, devices=None, backend="software"):
|
|
31
|
+
"""Upload the static scene to the JAX GPU devices (default all): terrain (nablaengine.terrain.Terrain), an optional
|
|
32
|
+
floor plane z = floor_z, robot meshes (robot_mesh.load's dict) on nbody bodies, exclude_body (-1: none). backend:
|
|
33
|
+
"software" (raycore, the default), "optix" (an optional backend: RT cores, needs an OptiX SDK at $OPTIX_ROOT,
|
|
34
|
+
sensors/optix_rays), "auto" (OptiX where $OPTIX_ROOT is set, else software)."""
|
|
35
|
+
import jax
|
|
36
|
+
import jax.numpy as jnp
|
|
37
|
+
from nablaengine.sensors import optix_rays
|
|
38
|
+
if backend not in ("auto", "optix", "software"):
|
|
39
|
+
raise ValueError(f"backend {backend!r}")
|
|
40
|
+
use_optix = backend == "optix" or (backend == "auto" and optix_rays.available())
|
|
41
|
+
lib = _lib()
|
|
42
|
+
keep = []
|
|
43
|
+
xlib = None
|
|
44
|
+
if use_optix:
|
|
45
|
+
dev0 = jax.devices("gpu")[0]
|
|
46
|
+
arch = "sm_" + str(dev0.compute_capability).replace(".", "")
|
|
47
|
+
libp, ptx = optix_rays.build(arch, jax.ffi.include_dir())
|
|
48
|
+
xlib = ctypes.cdll.LoadLibrary(str(libp))
|
|
49
|
+
vp, ci, cu = ctypes.c_void_p, ctypes.c_int, ctypes.c_uint
|
|
50
|
+
xlib.dkx_create_on.argtypes = [ci, ctypes.c_char_p, ctypes.c_size_t, ctypes.POINTER(vp)]
|
|
51
|
+
xlib.dkx_set_geometry_on.argtypes = [ci, vp, vp, cu, vp, vp, vp, ci, vp]
|
|
52
|
+
xlib.dkx_jax_setup.argtypes = [ci, vp, vp, vp, vp, vp]
|
|
53
|
+
if "optix_target" not in _STATE:
|
|
54
|
+
jax.ffi.register_ffi_target("dk_optix_rays", jax.ffi.pycapsule(xlib.DkOptixRays), platform="CUDA")
|
|
55
|
+
_STATE["optix_target"] = True
|
|
56
|
+
ptx_code = Path(ptx).read_bytes()
|
|
57
|
+
for d in devices or [d for d in jax.devices() if d.platform == "gpu"]:
|
|
58
|
+
put = lambda x, dt: jax.device_put(jnp.asarray(np.ascontiguousarray(x).reshape(-1) if np.size(x) else
|
|
59
|
+
np.zeros(1), dt), d)
|
|
60
|
+
s = _Scene()
|
|
61
|
+
arrs = []
|
|
62
|
+
if terrain is not None:
|
|
63
|
+
pk = terrain.pack(cell)
|
|
64
|
+
ent = dict(box=(pk["boxes"], jnp.float32), hfh=(pk["hf_head"], jnp.float32),
|
|
65
|
+
hfd=(pk["hf_data"], jnp.float32), grid=(pk["grid"], jnp.float32),
|
|
66
|
+
cellz=(cell_tops(terrain, pk), jnp.float32), hfi=(pk["hf_int"], jnp.int32),
|
|
67
|
+
cstart=(pk["cell_start"], jnp.int32), citems=(pk["cell_items"], jnp.int32))
|
|
68
|
+
s.zmax = float(np.max(ent["cellz"][0]))
|
|
69
|
+
for k, (x, dt) in ent.items():
|
|
70
|
+
a = put(x, dt)
|
|
71
|
+
arrs.append(a)
|
|
72
|
+
setattr(s, k, a.unsafe_buffer_pointer())
|
|
73
|
+
s.has_floor, s.floor_z = int(floor_z is not None), float(floor_z or 0.0)
|
|
74
|
+
if robot is not None:
|
|
75
|
+
for k in ("mgeom", "mroot", "nodeb", "nodei", "tri"):
|
|
76
|
+
a = put(robot[k], jnp.int32 if k in ("mroot", "nodei") else jnp.float32)
|
|
77
|
+
arrs.append(a)
|
|
78
|
+
setattr(s, k, a.unsafe_buffer_pointer())
|
|
79
|
+
s.nmesh = len(robot["mgeom"])
|
|
80
|
+
s.nbody, s.exclude_body = int(nbody), int(exclude_body)
|
|
81
|
+
for a in arrs:
|
|
82
|
+
a.block_until_ready()
|
|
83
|
+
rc = lib.dk_rays_set_scene(int(d.local_hardware_id), ctypes.byref(s))
|
|
84
|
+
if rc:
|
|
85
|
+
raise RuntimeError(f"dk_rays_set_scene failed ({rc})")
|
|
86
|
+
if use_optix:
|
|
87
|
+
dev = int(d.local_hardware_id)
|
|
88
|
+
h = ctypes.c_void_p()
|
|
89
|
+
rc = xlib.dkx_create_on(dev, ptx_code, len(ptx_code), ctypes.byref(h))
|
|
90
|
+
if rc:
|
|
91
|
+
raise RuntimeError(f"dkx_create failed ({rc})")
|
|
92
|
+
if terrain is not None:
|
|
93
|
+
tri, el, ce = optix_rays.terrain_triangles(terrain)
|
|
94
|
+
ext = (tri.reshape(-1, 3).min(0), tri.reshape(-1, 3).max(0))
|
|
95
|
+
else:
|
|
96
|
+
tri, el, ce = np.zeros((1, 9), np.float32), np.zeros(1, np.int32), np.zeros(1, np.int32)
|
|
97
|
+
ext = (np.zeros(3), np.zeros(3))
|
|
98
|
+
first, count = (optix_rays.OptixSceneRays._mesh_ranges(robot) if robot is not None
|
|
99
|
+
else (np.zeros(1, np.int32), np.zeros(1, np.int32)))
|
|
100
|
+
xa = dict(tri=put(tri, jnp.float32), el=put(el, jnp.int32), ce=put(ce, jnp.int32),
|
|
101
|
+
first=put(first, jnp.int32), box=put(optix_rays.unit_box(), jnp.float32))
|
|
102
|
+
for a in xa.values():
|
|
103
|
+
a.block_until_ready()
|
|
104
|
+
rc = xlib.dkx_set_geometry_on(dev, h, xa["tri"].unsafe_buffer_pointer(), len(tri) if terrain is not None
|
|
105
|
+
else 0, s.tri if robot is not None else None, first.ctypes.data,
|
|
106
|
+
count.ctypes.data, len(first) if robot is not None else 0,
|
|
107
|
+
xa["box"].unsafe_buffer_pointer())
|
|
108
|
+
if rc:
|
|
109
|
+
raise RuntimeError(f"dkx_set_geometry failed ({rc})")
|
|
110
|
+
rc = xlib.dkx_jax_setup(dev, h, ctypes.byref(s), xa["el"].unsafe_buffer_pointer(),
|
|
111
|
+
xa["ce"].unsafe_buffer_pointer(), xa["first"].unsafe_buffer_pointer())
|
|
112
|
+
if rc:
|
|
113
|
+
raise RuntimeError(f"dkx_jax_setup failed ({rc})")
|
|
114
|
+
arrs += list(xa.values())
|
|
115
|
+
_STATE["extent"] = ext
|
|
116
|
+
keep.append(arrs)
|
|
117
|
+
_STATE.update(keep=keep, nmesh=int(robot is not None and len(robot["mgeom"])), nbody=int(nbody),
|
|
118
|
+
mbody=(np.asarray(robot["mgeom"])[:, 0].astype(np.int32) if robot is not None
|
|
119
|
+
else np.zeros(1, np.int32)),
|
|
120
|
+
backend="optix" if use_optix else "software")
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _shift(B, maxd):
|
|
124
|
+
lo, hi = _STATE["extent"]
|
|
125
|
+
size = (hi - lo) + 2 * float(maxd) + 4.0
|
|
126
|
+
n = int(np.ceil(B ** (1 / 3)))
|
|
127
|
+
i = np.arange(B)
|
|
128
|
+
g = np.stack([i % n, (i // n) % n, i // (n * n)], 1) - (n - 1) / 2
|
|
129
|
+
return (g * size).astype(np.float32)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def cone(dirs, off=None):
|
|
133
|
+
"""(cos, sin, offset_max): the half angle about the sensor x axis that holds every direction of dirs (N, 3), and
|
|
134
|
+
the largest offset norm of off (N, 3) (NumPy; the mesh culling's constants of a ray pattern)."""
|
|
135
|
+
cx = float(np.clip(np.min(np.asarray(dirs)[:, 0]), -1, 1))
|
|
136
|
+
om = float(np.max(np.linalg.norm(np.asarray(off), axis=1))) if off is not None and len(off) else 0.0
|
|
137
|
+
return cx, float(np.sqrt(max(0.0, 1 - cx * cx))), om
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def cast(pos, rot, off, dirs, xpos=None, xquat=None, objects=None, max_distance=10.0, cone_cs=None, robot=True,
|
|
141
|
+
exclude_body=-1, backend=None, grad="none", min_cos=raygrad.MIN_COS, impl="fused"):
|
|
142
|
+
"""dist (B, N) (-1: none), id (B, N) int32 (raycore.ID_*), normal (B, N, 3) of rays from sensor frames pos (B, 3),
|
|
143
|
+
rot (B, 3, 3) with offsets / unit directions (N, 3) in the sensor frame; xpos (B, nbody, 3) / xquat (B, nbody, 4):
|
|
144
|
+
the body poses (needed with robot meshes); objects (B, K, 15) or None. Traceable (jit); no gradient. cone_cs:
|
|
145
|
+
cone(dirs, off) when they are traced (default: computed from them, which must then be concrete). robot: False skips the
|
|
146
|
+
robot's meshes (e.g. a terrain height scan); exclude_body: a body whose meshes are skipped (-1: none). backend:
|
|
147
|
+
None (setup's), or "software" (the CUDA kernels, set up next to OptiX: better for a few rays per world, as a height
|
|
148
|
+
scan, where OptiX's per-cast IAS build dominates). grad: "none" (dist without gradient, the default) or
|
|
149
|
+
"first_order" (dist differentiable w.r.t. pos, rot, off, dirs, xpos, xquat, objects by the hit plane's first-order
|
|
150
|
+
rule, raygrad; zero for misses and for hits with |n . r| < min_cos; id and normal carry no gradient); the forward
|
|
151
|
+
outputs are the same either way. impl (first_order): "fused" (reverse mode by the fused CUDA backward,
|
|
152
|
+
raygrad_cuda; no forward mode) or "xla" (a custom JVP in XLA: forward and reverse mode; off / dirs get cotangents
|
|
153
|
+
too). Per-world rays: off / dirs (B, N, 3) (e.g. per-world camera intrinsics) with the software kernels, grad
|
|
154
|
+
"none" and cone_cs given (a cone that holds every world's rays); shared (N, 3) rays are cast as before."""
|
|
155
|
+
import jax
|
|
156
|
+
import jax.numpy as jnp
|
|
157
|
+
if np.ndim(dirs) == 3 or np.ndim(off) == 3:
|
|
158
|
+
if grad != "none":
|
|
159
|
+
raise ValueError("cast: per-world rays (B, N, 3) have no gradient (grad='none')")
|
|
160
|
+
if cone_cs is None:
|
|
161
|
+
raise ValueError("cast: per-world rays (B, N, 3) need cone_cs (a cone that holds every world's rays)")
|
|
162
|
+
if _STATE.get("backend") == "optix" and backend != "software":
|
|
163
|
+
raise ValueError("cast: per-world rays (B, N, 3) use the software kernels (backend='software')")
|
|
164
|
+
if grad == "first_order":
|
|
165
|
+
return _cast_first_order(pos, rot, off, dirs, xpos, xquat, objects, max_distance, cone_cs, robot,
|
|
166
|
+
exclude_body, backend, min_cos, impl)
|
|
167
|
+
if grad != "none":
|
|
168
|
+
raise ValueError(f"grad {grad!r}: 'none' or 'first_order'")
|
|
169
|
+
if "lib" not in _STATE:
|
|
170
|
+
raise RuntimeError("nablaengine.sensors.jax_rays: setup() first")
|
|
171
|
+
f = lambda x: jnp.asarray(x, jnp.float32)
|
|
172
|
+
pos, rot, off, dirs = f(pos), f(rot), f(off), f(dirs)
|
|
173
|
+
B, N = pos.shape[0], off.shape[-2]
|
|
174
|
+
if off.ndim != dirs.ndim:
|
|
175
|
+
off, dirs = jnp.broadcast_to(off, (B, N, 3)), jnp.broadcast_to(dirs, (B, N, 3))
|
|
176
|
+
nb = max(_STATE["nbody"], 1)
|
|
177
|
+
xpos = f(xpos) if xpos is not None else jnp.zeros((B, nb, 3), jnp.float32)
|
|
178
|
+
xquat = f(xquat) if xquat is not None else jnp.zeros((B, nb, 4), jnp.float32)
|
|
179
|
+
objects = f(objects) if objects is not None else jnp.zeros((B, 0, 15), jnp.float32)
|
|
180
|
+
ch, sh, offmax = cone_cs if cone_cs is not None else cone(np.asarray(dirs), np.asarray(off))
|
|
181
|
+
if _STATE.get("backend") == "optix" and backend != "software":
|
|
182
|
+
out = (jax.ShapeDtypeStruct((B, N), jnp.float32), jax.ShapeDtypeStruct((B, N), jnp.int32),
|
|
183
|
+
jax.ShapeDtypeStruct((B, N, 3), jnp.float32), jax.ShapeDtypeStruct((B, N), jnp.float32),
|
|
184
|
+
jax.ShapeDtypeStruct((B, N), jnp.int32), jax.ShapeDtypeStruct((B, N), jnp.int32))
|
|
185
|
+
dist, gid, nrm, _, _, _ = jax.ffi.ffi_call("dk_optix_rays", out)(
|
|
186
|
+
pos, rot.reshape(B, 3, 3), off, dirs, xpos, xquat, objects, jnp.asarray(_shift(B, max_distance)),
|
|
187
|
+
max_distance=np.float32(max_distance), robot=np.int32(bool(robot)), exclude_body=np.int32(exclude_body))
|
|
188
|
+
return jax.lax.stop_gradient(dist), gid, jax.lax.stop_gradient(nrm)
|
|
189
|
+
nm = max(_STATE["nmesh"], 1)
|
|
190
|
+
out = (jax.ShapeDtypeStruct((B, N), jnp.float32), jax.ShapeDtypeStruct((B, N), jnp.int32),
|
|
191
|
+
jax.ShapeDtypeStruct((B, N, 3), jnp.float32), jax.ShapeDtypeStruct((B, nm, 12), jnp.float32),
|
|
192
|
+
jax.ShapeDtypeStruct((B, 2), jnp.int32))
|
|
193
|
+
dist, gid, nrm, _, _ = jax.ffi.ffi_call("dk_scene_rays", out)(
|
|
194
|
+
pos, rot.reshape(B, 3, 3), off, dirs, xpos, xquat, objects, max_distance=np.float32(max_distance),
|
|
195
|
+
cone_cos=np.float32(ch), cone_sin=np.float32(sh), offset_max=np.float32(offmax), robot=np.int32(bool(robot)),
|
|
196
|
+
exclude_body=np.int32(exclude_body))
|
|
197
|
+
return jax.lax.stop_gradient(dist), gid, jax.lax.stop_gradient(nrm)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _prep(pos, rot, off, dirs, xpos, xquat, objects):
|
|
201
|
+
import jax.numpy as jnp
|
|
202
|
+
f = lambda x: jnp.asarray(x, jnp.float32)
|
|
203
|
+
pos, rot, off, dirs = f(pos), f(rot), f(off), f(dirs)
|
|
204
|
+
B = pos.shape[0]
|
|
205
|
+
nb = max(_STATE["nbody"], 1)
|
|
206
|
+
xpos = f(xpos) if xpos is not None else jnp.zeros((B, nb, 3), jnp.float32)
|
|
207
|
+
xquat = f(xquat) if xquat is not None else jnp.zeros((B, nb, 4), jnp.float32)
|
|
208
|
+
objects = f(objects) if objects is not None else jnp.zeros((B, 0, 15), jnp.float32)
|
|
209
|
+
return pos, rot.reshape(B, 3, 3), off, dirs, xpos, xquat, objects
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _vjp_lib():
|
|
213
|
+
if "vjp" not in _STATE:
|
|
214
|
+
import jax
|
|
215
|
+
from nablaengine.sensors import raygrad_cuda
|
|
216
|
+
dev = jax.devices("gpu")[0]
|
|
217
|
+
arch = "sm_" + str(dev.compute_capability).replace(".", "")
|
|
218
|
+
lib = ctypes.cdll.LoadLibrary(str(raygrad_cuda.build(arch, jax.ffi.include_dir())))
|
|
219
|
+
assert lib.dk_ray_vjp_args_size() == ctypes.sizeof(raygrad_cuda.VjpArgs), "VjpArgs layout mismatch"
|
|
220
|
+
jax.ffi.register_ffi_target("dk_ray_vjp", jax.ffi.pycapsule(lib.DkRayVjp), platform="CUDA")
|
|
221
|
+
_STATE["vjp"] = lib
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def ray_vjp(coef, pos, rot, off, dirs, xpos, xquat, objects, dist, gid, nrm, spec=None, min_cos=raygrad.MIN_COS,
|
|
225
|
+
light=(0.0, 0.0, 0.0)):
|
|
226
|
+
"""The fused backward (raygrad_cuda): cotangents (pos, rot, xpos, xquat, objects) of per-ray coefficients coef
|
|
227
|
+
(B, N, 1 | 4 | 5) on (dt, value, col, row, (-light) . n) at the cast's outputs dist, gid, nrm; spec: the image
|
|
228
|
+
sensor (raygrad.ImageSpec) for the value / image coordinates (None: dt alone)."""
|
|
229
|
+
import jax
|
|
230
|
+
import jax.numpy as jnp
|
|
231
|
+
from nablaengine.sensors import raygrad_cuda
|
|
232
|
+
_vjp_lib()
|
|
233
|
+
B, nb, K = pos.shape[0], xpos.shape[1], objects.shape[1]
|
|
234
|
+
ptype, par = raygrad_cuda.params(spec, min_cos, light)
|
|
235
|
+
S = 12 + 12 * (nb + K)
|
|
236
|
+
names = ("p0", "p1", "min_cos", "ac0", "ac1", "ac2", "aw0", "aw1", "aw2", "l0", "l1", "l2")
|
|
237
|
+
out = jax.ffi.ffi_call("dk_ray_vjp", jax.ShapeDtypeStruct((B, S), jnp.float32))(
|
|
238
|
+
pos, rot.reshape(B, 3, 3), off, dirs, xpos, xquat, objects, jnp.asarray(_STATE["mbody"], jnp.int32),
|
|
239
|
+
dist, gid, nrm, jnp.asarray(coef, jnp.float32), ptype=np.int32(ptype),
|
|
240
|
+
nmesh=np.int32(_STATE["nmesh"]), **{k: np.float32(v) for k, v in zip(names, par)})
|
|
241
|
+
bod = out[:, 12:12 + 12 * nb].reshape(B, nb, 12)
|
|
242
|
+
cq = jax.vjp(lambda q: raygrad.qmat(jnp, q), xquat)[1](bod[..., 3:].reshape(B, nb, 3, 3))[0]
|
|
243
|
+
co = jnp.concatenate([out[:, 12 + 12 * nb:].reshape(B, K, 12), jnp.zeros((B, K, 3), jnp.float32)], -1)
|
|
244
|
+
return out[:, :3], out[:, 3:12].reshape(B, 3, 3), bod[..., :3], cq, co
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _cast_first_order(pos, rot, off, dirs, xpos, xquat, objects, max_distance, cone_cs, robot, exclude_body, backend,
|
|
248
|
+
min_cos, impl="fused"):
|
|
249
|
+
import jax
|
|
250
|
+
import jax.numpy as jnp
|
|
251
|
+
pos, rot, off, dirs, xpos, xquat, objects = _prep(pos, rot, off, dirs, xpos, xquat, objects)
|
|
252
|
+
if cone_cs is None:
|
|
253
|
+
cone_cs = cone(np.asarray(dirs), np.asarray(off))
|
|
254
|
+
kw = dict(max_distance=max_distance, cone_cs=cone_cs, robot=robot, exclude_body=exclude_body, backend=backend)
|
|
255
|
+
mbody = _STATE["mbody"]
|
|
256
|
+
if impl == "fused":
|
|
257
|
+
@jax.custom_vjp
|
|
258
|
+
def runv(pos, rot, off, dirs, xpos, xquat, objects):
|
|
259
|
+
return cast(pos, rot, off, dirs, xpos, xquat, objects, **kw)
|
|
260
|
+
|
|
261
|
+
def fwd(*a):
|
|
262
|
+
out = runv(*a)
|
|
263
|
+
return out, (a, out)
|
|
264
|
+
|
|
265
|
+
def bwd(r, cts):
|
|
266
|
+
a, (dist, gid, nrm) = r
|
|
267
|
+
cp, cr, cx, cq, co = ray_vjp(cts[0][..., None], *a, dist, gid, nrm, None, min_cos)
|
|
268
|
+
return cp, cr, jnp.zeros_like(a[2]), jnp.zeros_like(a[3]), cx, cq, co
|
|
269
|
+
|
|
270
|
+
runv.defvjp(fwd, bwd)
|
|
271
|
+
return runv(pos, rot, off, dirs, xpos, xquat, objects)
|
|
272
|
+
if impl != "xla":
|
|
273
|
+
raise ValueError(f"impl {impl!r}: 'fused' or 'xla'")
|
|
274
|
+
|
|
275
|
+
@jax.custom_jvp
|
|
276
|
+
def run(pos, rot, off, dirs, xpos, xquat, objects):
|
|
277
|
+
return cast(pos, rot, off, dirs, xpos, xquat, objects, **kw)
|
|
278
|
+
|
|
279
|
+
@run.defjvp
|
|
280
|
+
def run_jvp(primals, tangents):
|
|
281
|
+
dist, gid, nrm = run(*primals)
|
|
282
|
+
res = raygrad.residuals(jnp, *primals, dist, gid, nrm, jnp.asarray(mbody), min_cos)
|
|
283
|
+
_, ddist = jax.jvp(lambda *a: raygrad.tangent_dist(jnp, *a, res), primals, tangents)
|
|
284
|
+
return (dist, gid, nrm), (ddist, np.zeros(gid.shape, jax.dtypes.float0), jnp.zeros_like(nrm))
|
|
285
|
+
|
|
286
|
+
return run(pos, rot, off, dirs, xpos, xquat, objects)
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def cast_image(spec, value_fn, sigma, pos, rot, off, dirs, xpos=None, xquat=None, objects=None, impl="fused",
|
|
290
|
+
min_cos=raygrad.MIN_COS, light=None, **cast_kw):
|
|
291
|
+
"""An image sensor's value with the smoothed gradient (raygrad: sigma in pixels / grid cells; sigma None: the
|
|
292
|
+
per-pixel value tangent alone, the RGB's "first_order"). value_fn(dist, gid, nrm, pos, rot) -> (image (B, H, W[,
|
|
293
|
+
C]), aux (not differentiable, e.g. the seg ids), m (B, H, W) the moving-value mask, kappa (B, N, C) or None: d
|
|
294
|
+
image / d ((-light) . n) per channel (the RGB), the normal the tangents use (B, N, 3)); the forward value is
|
|
295
|
+
value_fn's. impl "fused" (custom VJP, the fused backward) or "xla" (custom JVP). cast_kw: cast()'s max_distance,
|
|
296
|
+
cone_cs, robot, exclude_body, backend. Returns (image, aux)."""
|
|
297
|
+
import jax
|
|
298
|
+
import jax.numpy as jnp
|
|
299
|
+
pos, rot, off, dirs, xpos, xquat, objects = _prep(pos, rot, off, dirs, xpos, xquat, objects)
|
|
300
|
+
if cast_kw.get("cone_cs") is None:
|
|
301
|
+
cast_kw["cone_cs"] = cone(np.asarray(dirs), np.asarray(off))
|
|
302
|
+
mbody = _STATE["mbody"]
|
|
303
|
+
B, N = pos.shape[0], off.shape[0]
|
|
304
|
+
lt = tuple(float(x) for x in light) if light is not None else (0.0, 0.0, 0.0)
|
|
305
|
+
|
|
306
|
+
def forward(pos, rot, off, dirs, xpos, xquat, objects):
|
|
307
|
+
dist, gid, nrm = cast(pos, rot, off, dirs, xpos, xquat, objects, **cast_kw)
|
|
308
|
+
img, aux, m, kappa, nf = value_fn(dist, gid, nrm, pos, rot)
|
|
309
|
+
return (img, aux), (dist, gid, nf, img, m.astype(jnp.float32), kappa)
|
|
310
|
+
|
|
311
|
+
def to_img(x):
|
|
312
|
+
return x.reshape((B, spec.H, spec.W) + x.shape[2:])
|
|
313
|
+
|
|
314
|
+
if impl == "fused":
|
|
315
|
+
@jax.custom_vjp
|
|
316
|
+
def runv(*a):
|
|
317
|
+
return forward(*a)[0]
|
|
318
|
+
|
|
319
|
+
def fwd(*a):
|
|
320
|
+
out, r = forward(*a)
|
|
321
|
+
return out, (a, r)
|
|
322
|
+
|
|
323
|
+
def bwd(res, cts):
|
|
324
|
+
a, (dist, gid, nf, img, m, kappa) = res
|
|
325
|
+
c = cts[0]
|
|
326
|
+
if sigma is None:
|
|
327
|
+
cV = (m[..., None] if img.ndim == 4 else m) * c
|
|
328
|
+
cc = cr = jnp.zeros_like(m)
|
|
329
|
+
else:
|
|
330
|
+
sm = raygrad.Smoother(jnp, spec.H, spec.W, sigma)
|
|
331
|
+
cV, cc, cr = raygrad.image_transpose(sm, img, m, to_img(dist), c)
|
|
332
|
+
cV = cV.reshape((B, N) + cV.shape[3:])
|
|
333
|
+
z = jnp.zeros((B, N), jnp.float32)
|
|
334
|
+
if kappa is not None:
|
|
335
|
+
coef = jnp.stack([z, z, cc.reshape(B, N), cr.reshape(B, N), (cV * kappa).sum(-1)], -1)
|
|
336
|
+
else:
|
|
337
|
+
coef = jnp.stack([z, cV, cc.reshape(B, N), cr.reshape(B, N)], -1)
|
|
338
|
+
cp, crot, cx, cq, co = ray_vjp(coef, *a, dist, gid, nf, spec, min_cos, lt)
|
|
339
|
+
return cp, crot, jnp.zeros_like(a[2]), jnp.zeros_like(a[3]), cx, cq, co
|
|
340
|
+
|
|
341
|
+
runv.defvjp(fwd, bwd)
|
|
342
|
+
return runv(pos, rot, off, dirs, xpos, xquat, objects)
|
|
343
|
+
if impl != "xla":
|
|
344
|
+
raise ValueError(f"impl {impl!r}: 'fused' or 'xla'")
|
|
345
|
+
|
|
346
|
+
@jax.custom_jvp
|
|
347
|
+
def run(*a):
|
|
348
|
+
return forward(*a)[0]
|
|
349
|
+
|
|
350
|
+
@run.defjvp
|
|
351
|
+
def run_jvp(primals, tangents):
|
|
352
|
+
(img, aux), (dist, gid, nf, _, m, kappa) = forward(*primals)
|
|
353
|
+
res = raygrad.residuals(jnp, *primals, dist, gid, nf, jnp.asarray(mbody), min_cos)
|
|
354
|
+
_, d = jax.jvp(lambda *a: raygrad.functionals(jnp, *a, res, spec, light), primals, tangents)
|
|
355
|
+
dV = d["ndl"][..., None] * kappa if kappa is not None else d["V"]
|
|
356
|
+
dV, dc, dr = to_img(dV), to_img(d["col"]), to_img(d["row"])
|
|
357
|
+
if sigma is None:
|
|
358
|
+
dimg = (m[..., None] if img.ndim == 4 else m) * dV
|
|
359
|
+
else:
|
|
360
|
+
sm = raygrad.Smoother(jnp, spec.H, spec.W, sigma)
|
|
361
|
+
dimg = raygrad.image_tangent(sm, img, m, to_img(dist), dV, dc, dr)
|
|
362
|
+
return (img, aux), (dimg, np.zeros(aux.shape, jax.dtypes.float0))
|
|
363
|
+
|
|
364
|
+
return run(pos, rot, off, dirs, xpos, xquat, objects)
|