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
nablaengine/cuda.py
ADDED
|
@@ -0,0 +1,483 @@
|
|
|
1
|
+
"""nvcc and target architecture for the hand-written CUDA kernels."""
|
|
2
|
+
|
|
3
|
+
import functools
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
import shutil
|
|
7
|
+
import subprocess
|
|
8
|
+
import sys
|
|
9
|
+
import tempfile
|
|
10
|
+
import warnings
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
FRONTEND_VAR = "DK_SM120_FRONTEND"
|
|
14
|
+
LEGACY_FRONTEND_VAR = "DK_SM120_FORWARD_FRONTEND"
|
|
15
|
+
FRONTENDS = ("n7", "split", "native")
|
|
16
|
+
TEST_FORWARD_VAR = "DK_TEST_FORWARD_VIRTUAL_ARCH"
|
|
17
|
+
TEST_VAR = "DK_TEST_VIRTUAL_ARCH"
|
|
18
|
+
N7_VIRTUAL = {"sm_120": "compute_90", "sm_103": "compute_90"}
|
|
19
|
+
SM103_FRONTEND_VAR = "DK_SM103_FRONTEND"
|
|
20
|
+
SM103_FRONTENDS = ("adjoint", "n7", "native")
|
|
21
|
+
SM90_CAPS = ("SPLIT_PRE_MINB=16", "SPLIT_POST_MAXNREG=128")
|
|
22
|
+
REG_CAPS = {"sm_90": ("DK_SM90_REG_CAPS", SM90_CAPS, False),
|
|
23
|
+
"sm_90a": ("DK_SM90_REG_CAPS", SM90_CAPS, False),
|
|
24
|
+
"sm_120": ("DK_SM120_PRE_CAP", ("SPLIT_PRE_MINB=16",), True),
|
|
25
|
+
"sm_103": ("DK_SM103_REG_CAPS", SM90_CAPS, False)}
|
|
26
|
+
ADJ_CAPS = {"sm_103": ("DK_SM103_REG_CAPS", ("ADJ_MAXNREG=120",))}
|
|
27
|
+
FOREST_ADJ_CAPS = {"sm_103": ("DK_SM103_REG_CAPS", ("ADJ_MAXNREG=128",))}
|
|
28
|
+
FOREST_POST_VAR = "DK_FOREST_POST_CAP"
|
|
29
|
+
FOREST_ADJ_VAR = "DK_SM103_FOREST_ADJ_CAP"
|
|
30
|
+
CAPBOX_COOP_OFF = ("sm_90", "sm_90a")
|
|
31
|
+
CAPBOX_COOP_VAR = "DK_SM90_CAPBOX_COOP"
|
|
32
|
+
TREE_ADJ_CAPS = {"sm_90": ("ADJ_MAXNREG=168",), "sm_90a": ("ADJ_MAXNREG=168",)}
|
|
33
|
+
TREE_ADJ_VAR = "DK_SM90_ADJ_CAP"
|
|
34
|
+
FOREST_TER_CAP_VAR = "DK_SM90_FOREST_ADJ_CAP"
|
|
35
|
+
FOREST_HOLD_TARGETS = ("sm_90", "sm_90a")
|
|
36
|
+
FOREST_HESS_VAR = "DK_FOREST_HESS_UNROLL"
|
|
37
|
+
FOREST_CHOL_VAR = "DK_FOREST_CHOL_REG"
|
|
38
|
+
FOREST_WIDE_VAR = "DK_FOREST_CHOL_WIDE"
|
|
39
|
+
FOREST_CCD_COOP_VAR = "DK_FOREST_CCD_COOP"
|
|
40
|
+
FOREST_FREE_GYRO_VAR = "DK_FOREST_FREE_GYRO"
|
|
41
|
+
CAP_BOUNDS = {"SPLIT_PRE_MINB": ("SPLIT_PRE_MINB",), "SPLIT_POST_MAXNREG": ("SPLIT_POST_MAXNREG", "SPLIT_POST_MINB"),
|
|
42
|
+
"ADJ_MAXNREG": ("ADJ_MAXNREG",)}
|
|
43
|
+
MAXNREG_NVCC = (12, 4)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def nvcc():
|
|
47
|
+
"""The nvcc to build with: $NVCC, nvcc on PATH, $CUDA_HOME/bin/nvcc, a pip nvidia.cuda_nvcc package's nvcc, then
|
|
48
|
+
/usr/local/cuda/bin/nvcc (the first that exists); FileNotFoundError if none does."""
|
|
49
|
+
cands = [os.environ.get("NVCC"), shutil.which("nvcc")]
|
|
50
|
+
if os.environ.get("CUDA_HOME"):
|
|
51
|
+
cands.append(str(Path(os.environ["CUDA_HOME"]) / "bin" / "nvcc"))
|
|
52
|
+
try:
|
|
53
|
+
import nvidia.cuda_nvcc
|
|
54
|
+
cands.append(str(Path(list(nvidia.cuda_nvcc.__path__)[0]) / "bin" / "nvcc"))
|
|
55
|
+
except ImportError:
|
|
56
|
+
pass
|
|
57
|
+
cands.append("/usr/local/cuda/bin/nvcc")
|
|
58
|
+
for c in cands:
|
|
59
|
+
if c and Path(c).exists():
|
|
60
|
+
return c
|
|
61
|
+
raise FileNotFoundError(
|
|
62
|
+
"no nvcc found: set NVCC to a CUDA 12.x nvcc (or CUDA_HOME, or put nvcc on PATH). The pip wheel "
|
|
63
|
+
"nvidia-cuda-nvcc-cu12 has no nvcc (only ptxas); install a toolkit, e.g. conda's cuda-nvcc "
|
|
64
|
+
"(scripts/setup_env.sh, README.md)")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def visible_gpu():
|
|
68
|
+
"""The first visible GPU as nvidia-smi names it (index or UUID): the first entry of $CUDA_VISIBLE_DEVICES, else
|
|
69
|
+
None (nvidia-smi's GPU 0). nvidia-smi itself ignores CUDA_VISIBLE_DEVICES and numbers the GPUs in PCI order, CUDA
|
|
70
|
+
fastest first unless CUDA_DEVICE_ORDER=PCI_BUS_ID: the same GPU on a machine with one GPU type."""
|
|
71
|
+
v = os.environ.get("CUDA_VISIBLE_DEVICES", "").split(",")[0].strip()
|
|
72
|
+
return v if v and not v.startswith("-") else None
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def device_arch():
|
|
76
|
+
"""sm_XY of the first visible GPU (nvidia-smi), None without nvidia-smi or a GPU."""
|
|
77
|
+
q = ["nvidia-smi", "--query-gpu=compute_cap", "--format=csv,noheader"]
|
|
78
|
+
for cmd in ([*q, "-i", visible_gpu()] if visible_gpu() else None, q):
|
|
79
|
+
if cmd is None:
|
|
80
|
+
continue
|
|
81
|
+
try:
|
|
82
|
+
out = subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
|
|
83
|
+
universal_newlines=True).stdout.split()
|
|
84
|
+
except (OSError, subprocess.CalledProcessError):
|
|
85
|
+
continue
|
|
86
|
+
if out:
|
|
87
|
+
return "sm_" + out[0].replace(".", "")
|
|
88
|
+
return None
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def arch():
|
|
92
|
+
"""$DK_ARCH, else the first visible GPU's architecture (device_arch). A $DK_ARCH that is not the GPU's warns (once
|
|
93
|
+
per process): code built for an older target runs that target's code paths (CHOL_COMPACT follows __CUDA_ARCH__)
|
|
94
|
+
from its SASS within the same major version, else from the driver's compilation of its PTX, so the results are not
|
|
95
|
+
bitwise those of a build for the GPU; code built for a newer target does not load. No warning without a GPU (a
|
|
96
|
+
build for another machine)."""
|
|
97
|
+
if os.environ.get("DK_ARCH"):
|
|
98
|
+
a = os.environ["DK_ARCH"]
|
|
99
|
+
dev = device_arch()
|
|
100
|
+
if dev is not None and dev != a:
|
|
101
|
+
warnings.warn(f"DK_ARCH={a} but the GPU is {dev}: the CUDA code is built for {a} (unset DK_ARCH to build "
|
|
102
|
+
f"for the GPU)", RuntimeWarning, stacklevel=2)
|
|
103
|
+
return a
|
|
104
|
+
a = device_arch()
|
|
105
|
+
if a is None:
|
|
106
|
+
raise RuntimeError("no GPU found by nvidia-smi: set DK_ARCH (e.g. sm_70, sm_86, sm_87, sm_90, sm_120) to build "
|
|
107
|
+
"without one")
|
|
108
|
+
return a
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def frontend():
|
|
112
|
+
"""$DK_SM120_FRONTEND: 'n7' (the default), 'split' or 'native'. The deprecated $DK_SM120_FORWARD_FRONTEND (n7 / native)
|
|
113
|
+
is read where $DK_SM120_FRONTEND is unset, with a DeprecationWarning (n7 -> n7, native -> native)."""
|
|
114
|
+
v = (os.environ.get(FRONTEND_VAR) or "").strip().lower()
|
|
115
|
+
old = (os.environ.get(LEGACY_FRONTEND_VAR) or "").strip().lower()
|
|
116
|
+
if old:
|
|
117
|
+
_warn_legacy(old, bool(v))
|
|
118
|
+
if not v:
|
|
119
|
+
if old not in ("n7", "native"):
|
|
120
|
+
raise ValueError(f"${LEGACY_FRONTEND_VAR}={old!r}: must be n7 or native (deprecated: use ${FRONTEND_VAR})")
|
|
121
|
+
v = old
|
|
122
|
+
v = v or "n7"
|
|
123
|
+
if v not in FRONTENDS:
|
|
124
|
+
raise ValueError(f"${FRONTEND_VAR}={v!r}: must be one of {', '.join(FRONTENDS)}")
|
|
125
|
+
return v
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def sm103_frontend():
|
|
129
|
+
"""$DK_SM103_FRONTEND: 'adjoint' (the default), 'n7' or 'native' (module docstring)."""
|
|
130
|
+
v = (os.environ.get(SM103_FRONTEND_VAR) or "adjoint").strip().lower()
|
|
131
|
+
if v not in SM103_FRONTENDS:
|
|
132
|
+
raise ValueError(f"${SM103_FRONTEND_VAR}={v!r}: must be one of {', '.join(SM103_FRONTENDS)}")
|
|
133
|
+
return v
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def frontend_of(target):
|
|
137
|
+
"""The front-end switch value of a build target with NVVM 7 units (N7_VIRTUAL): $DK_SM103_FRONTEND on sm_103,
|
|
138
|
+
$DK_SM120_FRONTEND (frontend()) on sm_120."""
|
|
139
|
+
return sm103_frontend() if target == "sm_103" else frontend()
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
@functools.lru_cache(maxsize=None)
|
|
143
|
+
def _warn_legacy(old, shadowed):
|
|
144
|
+
warnings.warn(f"${LEGACY_FRONTEND_VAR} is deprecated: use ${FRONTEND_VAR} (n7 / split / native)"
|
|
145
|
+
+ (f"; ${FRONTEND_VAR} is set and wins" if shadowed else f"; {old} is taken as ${FRONTEND_VAR}={old}"),
|
|
146
|
+
DeprecationWarning, stacklevel=4)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def nvvm_version(virt, nvcc_path=None):
|
|
150
|
+
"""The front end nvcc uses for a virtual architecture (compute_XY), from the header of the PTX it makes for a tiny
|
|
151
|
+
kernel ('NVVM 7.0.1', 'NVVM 20.0.0'), or None if nvcc cannot make it."""
|
|
152
|
+
return _nvvm_version(virt, nvcc_path or nvcc())
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
@functools.lru_cache(maxsize=None)
|
|
156
|
+
def _nvvm_version(virt, nvcc_path):
|
|
157
|
+
with tempfile.TemporaryDirectory(prefix="dk_nvvm_") as d:
|
|
158
|
+
src, ptx = Path(d) / "k.cu", Path(d) / "k.ptx"
|
|
159
|
+
src.write_text("__global__ void k(float* a) { a[threadIdx.x] *= 2.f; }\n")
|
|
160
|
+
r = subprocess.run([nvcc_path, f"-arch={virt}", "-ptx", "-o", str(ptx), str(src)],
|
|
161
|
+
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
|
162
|
+
if r.returncode or not ptx.exists():
|
|
163
|
+
return None
|
|
164
|
+
m = re.search(r"Based on NVVM ([\d.]+)", ptx.read_text())
|
|
165
|
+
return f"NVVM {m.group(1)}" if m else None
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
@functools.lru_cache(maxsize=None)
|
|
169
|
+
def _n7_applies(target, nvcc_path):
|
|
170
|
+
virt = N7_VIRTUAL[target]
|
|
171
|
+
native, n7 = nvvm_version("compute_" + target[3:], nvcc_path), nvvm_version(virt, nvcc_path)
|
|
172
|
+
if n7 and n7.startswith("NVVM 7.") and not (native or "").startswith("NVVM 7."):
|
|
173
|
+
return virt
|
|
174
|
+
var = SM103_FRONTEND_VAR if target == "sm_103" else FRONTEND_VAR
|
|
175
|
+
print(f"nablaengine.cuda: {var}={frontend_of(target)} not applied on {target} (front ends: compute_{target[3:]} "
|
|
176
|
+
f"{native}, {virt} {n7}): every unit keeps the native build", file=sys.stderr)
|
|
177
|
+
return None
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
@functools.lru_cache(maxsize=None)
|
|
181
|
+
def _warn_test(var, virt):
|
|
182
|
+
warnings.warn(f"${var}={virt}: {'the forward / kinematics unit is' if var == TEST_FORWARD_VAR else 'every unit is'} "
|
|
183
|
+
f"built from {virt} PTX (a testing switch, not the default build)", RuntimeWarning, stacklevel=4)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def virtual_arch(unit=None, target=None, nvcc_path=None):
|
|
187
|
+
"""The virtual architecture whose PTX a compilation unit is built from, or None for the native build
|
|
188
|
+
(-arch=<target>). unit 'forward': the forward / kinematics unit; anything else: the adjoint units, the FFI unit and
|
|
189
|
+
test programs. sm_120 (see the module docstring): compute_90 for every unit with $DK_SM120_FRONTEND n7 (the
|
|
190
|
+
default), for the forward unit only with split, none with native (n7 / split only where the PTX headers confirm
|
|
191
|
+
it). sm_103: compute_90 for every unit but the forward one with $DK_SM103_FRONTEND adjoint (the default), every
|
|
192
|
+
unit with n7, none with native. The testing switches take precedence on any target: $DK_TEST_FORWARD_VIRTUAL_ARCH for the forward unit,
|
|
193
|
+
$DK_TEST_VIRTUAL_ARCH for every unit."""
|
|
194
|
+
target = target or arch()
|
|
195
|
+
fwd = unit == "forward"
|
|
196
|
+
for var, applies in ((TEST_FORWARD_VAR, fwd), (TEST_VAR, True)):
|
|
197
|
+
test = (os.environ.get(var) or "").strip()
|
|
198
|
+
if test and applies:
|
|
199
|
+
_warn_test(var, test)
|
|
200
|
+
return test
|
|
201
|
+
if target not in N7_VIRTUAL:
|
|
202
|
+
return None
|
|
203
|
+
mode = frontend_of(target)
|
|
204
|
+
if mode == "native" or (mode == "split" and not fwd) or (mode == "adjoint" and fwd):
|
|
205
|
+
return None
|
|
206
|
+
return _n7_applies(target, nvcc_path or nvcc())
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def forward_virtual_arch(target=None, nvcc_path=None):
|
|
210
|
+
"""virtual_arch of the forward / kinematics unit (compute_90 on sm_120 with n7 or split)."""
|
|
211
|
+
return virtual_arch("forward", target, nvcc_path)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def arch_flags(unit=None, target=None, nvcc_path=None):
|
|
215
|
+
"""nvcc's architecture flags for a compilation unit (unit 'forward': the forward / kinematics kernels; anything
|
|
216
|
+
else: the adjoint units, the FFI unit, test programs): ['-arch=<virtual>', '-code=<target>'] where virtual_arch gives
|
|
217
|
+
one (sm_120: every unit by default, see the module docstring), else ['-arch=<target>']."""
|
|
218
|
+
target = target or arch()
|
|
219
|
+
virt = virtual_arch(unit, target, nvcc_path)
|
|
220
|
+
return [f"-arch={virt}", f"-code={target}"] if virt else [f"-arch={target}"]
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def forward_tag(target=None, nvcc_path=None):
|
|
224
|
+
"""'' where the forward unit has the native flags, else 'fwd-<virtual architecture>' (names forward references:
|
|
225
|
+
the forward's bits depend only on the forward unit's flags, so sm_120's n7 and split share 'fwd-compute_90')."""
|
|
226
|
+
virt = forward_virtual_arch(target, nvcc_path)
|
|
227
|
+
return f"fwd-{virt}" if virt else ""
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def reg_caps(target=None):
|
|
231
|
+
"""The register-cap switch of the build target (REG_CAPS: $DK_SM90_REG_CAPS on sm_90 / sm_90a, $DK_SM120_PRE_CAP on
|
|
232
|
+
sm_120, $DK_SM103_REG_CAPS on sm_103): True for 1 (the default), False for 0; None for a target without caps."""
|
|
233
|
+
target = target or arch()
|
|
234
|
+
if target not in REG_CAPS:
|
|
235
|
+
return None
|
|
236
|
+
var = REG_CAPS[target][0]
|
|
237
|
+
v = (os.environ.get(var) or "1").strip()
|
|
238
|
+
if v not in ("0", "1"):
|
|
239
|
+
raise ValueError(f"${var}={v!r}: must be 1 or 0")
|
|
240
|
+
return v == "1"
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def defined_macros(options):
|
|
244
|
+
"""The macro names an nvcc option list defines (-DX, -DX=Y, -D X, --define-macro X, --define-macro=X)."""
|
|
245
|
+
out, it = set(), iter(str(a) for a in options)
|
|
246
|
+
for a in it:
|
|
247
|
+
if a in ("-D", "--define-macro"):
|
|
248
|
+
a = "-D" + next(it, "")
|
|
249
|
+
elif a.startswith("--define-macro="):
|
|
250
|
+
a = "-D" + a.split("=", 1)[1]
|
|
251
|
+
if a.startswith("-D") and len(a) > 2:
|
|
252
|
+
out.add(a[2:].split("=", 1)[0])
|
|
253
|
+
return out
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def reg_caps_defines(options=(), caps=SM90_CAPS):
|
|
257
|
+
"""The caps (e.g. ('SPLIT_PRE_MINB=16', ...)) as -D options, less each cap whose kernel the caller's nvcc options
|
|
258
|
+
already bound (defined_macros; CAP_BOUNDS)."""
|
|
259
|
+
have = defined_macros(options)
|
|
260
|
+
return [f"-D{d}" for d in caps if not have.intersection(CAP_BOUNDS[d.split("=", 1)[0]])]
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
@functools.lru_cache(maxsize=None)
|
|
264
|
+
def _maxnreg_ok(nvcc_path, var):
|
|
265
|
+
r = subprocess.run([nvcc_path, "--version"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
|
|
266
|
+
universal_newlines=True)
|
|
267
|
+
m = re.search(r"release (\d+)\.(\d+)", r.stdout)
|
|
268
|
+
rel = (int(m.group(1)), int(m.group(2))) if m else None
|
|
269
|
+
if rel and rel >= MAXNREG_NVCC:
|
|
270
|
+
return True
|
|
271
|
+
print(f"nablaengine.cuda: {var}=1 not applied (nvcc release {'.'.join(map(str, rel)) if rel else '?'}; "
|
|
272
|
+
"__maxnreg__ needs 12.4 or newer): the forward unit keeps the launch bounds of the other targets",
|
|
273
|
+
file=sys.stderr)
|
|
274
|
+
return False
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
FOREST_POST_DROP = ("sm_90", "sm_90a")
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def forest_post_cap(target=None):
|
|
281
|
+
"""$DK_FOREST_POST_CAP: True for 1 (the forest engine keeps k_post's __maxnreg__ cap), False for 0; unset: the
|
|
282
|
+
target's default, False on sm_90 / sm_90a (ptxas's lane rematerialization, module docstring), True elsewhere
|
|
283
|
+
(sm_103: bitwise the uncapped forward, B300 G1 4096 worlds k_post 1.260 -> 1.167 ms)."""
|
|
284
|
+
v = (os.environ.get(FOREST_POST_VAR) or "").strip()
|
|
285
|
+
if v not in ("", "0", "1"):
|
|
286
|
+
raise ValueError(f"${FOREST_POST_VAR}={v!r}: must be 0 or 1")
|
|
287
|
+
if v == "":
|
|
288
|
+
return (target or arch()) not in FOREST_POST_DROP
|
|
289
|
+
return v == "1"
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def unit_defines(unit=None, target=None, options=(), nvcc_path=None, forest=False):
|
|
293
|
+
"""The -D options a compilation unit gets for its build target besides the caller's nvcc options: unit 'forward'
|
|
294
|
+
(the split forward kernels' unit; see the module docstring) gets the target's register caps (REG_CAPS: sm_90 /
|
|
295
|
+
sm_90a and sm_103 ['-DSPLIT_PRE_MINB=16', '-DSPLIT_POST_MAXNREG=128'], sm_120 with the NVVM 7 forward
|
|
296
|
+
['-DSPLIT_PRE_MINB=16'])
|
|
297
|
+
where its switch is 1 (the default), each unless `options` already bound that kernel; every other unit and target:
|
|
298
|
+
none. forest: a forest-engine unit, which gets no SPLIT_POST_MAXNREG where forest_post_cap(target) is False (by
|
|
299
|
+
default on sm_90 / sm_90a: ptxas's miscompile, module docstring)."""
|
|
300
|
+
if unit != "forward":
|
|
301
|
+
return []
|
|
302
|
+
target = target or arch()
|
|
303
|
+
if not reg_caps(target):
|
|
304
|
+
return []
|
|
305
|
+
var, caps, needs_n7 = REG_CAPS[target]
|
|
306
|
+
if forest and not forest_post_cap(target):
|
|
307
|
+
caps = tuple(c for c in caps if not c.startswith("SPLIT_POST_MAXNREG="))
|
|
308
|
+
if needs_n7 and not forward_virtual_arch(target, nvcc_path):
|
|
309
|
+
return []
|
|
310
|
+
if any(c.startswith("SPLIT_POST_MAXNREG=") for c in caps) and not _maxnreg_ok(nvcc_path or nvcc(), var):
|
|
311
|
+
return []
|
|
312
|
+
return reg_caps_defines(options, caps)
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def forest_hold_defines(target=None, text="", options=()):
|
|
316
|
+
"""The -D options of a forest-engine unit (its text) on a build target of FOREST_HOLD_TARGETS (sm_90 / sm_90a),
|
|
317
|
+
decided by the target (not __CUDA_ARCH__: sm_120's and sm_103's units from compute_90 PTX see 900 too):
|
|
318
|
+
['-DDK_FOREST_HESS_UNROLL=0'] for a text with the forest hessian()'s unrolled contact-mask loops (DK_HESS_UNROLLED)
|
|
319
|
+
unless $DK_FOREST_HESS_UNROLL is set (forest_engine.step then defines it in the text, every target); and
|
|
320
|
+
['-DDK_FOREST_SM90_SMALL=1'] (chol_solve_small for NV <= 32 as before 2026-11-16 instead of chol_solve_reg) for a
|
|
321
|
+
text with CHOL_SMALL's choice unless $DK_FOREST_CHOL_REG is 1; ['-DCHOL_BCAST_WIDE=0'] (36 <= NV <= 48: the
|
|
322
|
+
previous CHOL_SOLVE instead of chol_solve_bcast_wide, and with it no NEWTON_REUSE for those sizes) for a text with
|
|
323
|
+
chol_solve_bcast_wide unless $DK_FOREST_CHOL_WIDE is 1; ['-DDK_CCD_COOP=0'] (native-CCD box-box contacts: their VJP
|
|
324
|
+
passes on the contact's lane as before, forest_engine.ccd_coop) for a text with that pass unless $DK_FOREST_CCD_COOP
|
|
325
|
+
is 1; ['-DDK_FREE_GYRO=0'] (standalone free bodies in implicitfast without MuJoCo 3.17's gyroscopic block, as
|
|
326
|
+
before, forest_engine.free_gyro) for a text with that block unless $DK_FOREST_FREE_GYRO is 1. A caller's own option
|
|
327
|
+
of the same macro wins. [] on every other target."""
|
|
328
|
+
target = target or arch()
|
|
329
|
+
if target not in FOREST_HOLD_TARGETS:
|
|
330
|
+
return []
|
|
331
|
+
out = []
|
|
332
|
+
own = lambda name: any(o == f"-D{name}" or o.startswith(f"-D{name}=") for o in options)
|
|
333
|
+
if "DK_HESS_UNROLLED" in text and not (os.environ.get(FOREST_HESS_VAR) or "").strip() \
|
|
334
|
+
and not own("DK_FOREST_HESS_UNROLL"):
|
|
335
|
+
out.append("-DDK_FOREST_HESS_UNROLL=0")
|
|
336
|
+
v = (os.environ.get(FOREST_CHOL_VAR) or "0").strip()
|
|
337
|
+
if v not in ("0", "1"):
|
|
338
|
+
raise ValueError(f"${FOREST_CHOL_VAR}={v!r}: must be 0 or 1")
|
|
339
|
+
if "DK_FOREST_SM90_SMALL" in text and v == "0" and not own("DK_FOREST_SM90_SMALL") and not own("CHOL_SMALL"):
|
|
340
|
+
out.append("-DDK_FOREST_SM90_SMALL=1")
|
|
341
|
+
w = (os.environ.get(FOREST_WIDE_VAR) or "0").strip()
|
|
342
|
+
if w not in ("0", "1"):
|
|
343
|
+
raise ValueError(f"${FOREST_WIDE_VAR}={w!r}: must be 0 or 1")
|
|
344
|
+
nv = re.search(r"^#define NV (\d+)", text, re.M)
|
|
345
|
+
if "chol_solve_bcast_wide" in text and w == "0" and not own("CHOL_BCAST_WIDE") and nv \
|
|
346
|
+
and 36 <= int(nv.group(1)) <= 48:
|
|
347
|
+
out.append("-DCHOL_BCAST_WIDE=0")
|
|
348
|
+
c = (os.environ.get(FOREST_CCD_COOP_VAR) or "0").strip()
|
|
349
|
+
if c not in ("0", "1"):
|
|
350
|
+
raise ValueError(f"${FOREST_CCD_COOP_VAR}={c!r}: must be 0 or 1")
|
|
351
|
+
if "DK_CCD_COOP" in text and c == "0" and not own("DK_CCD_COOP"):
|
|
352
|
+
out.append("-DDK_CCD_COOP=0")
|
|
353
|
+
g = (os.environ.get(FOREST_FREE_GYRO_VAR) or "0").strip()
|
|
354
|
+
if g not in ("0", "1"):
|
|
355
|
+
raise ValueError(f"${FOREST_FREE_GYRO_VAR}={g!r}: must be 0 or 1")
|
|
356
|
+
if "DK_FREE_GYRO" in text and g == "0" and not own("DK_FREE_GYRO"):
|
|
357
|
+
out.append("-DDK_FREE_GYRO=0")
|
|
358
|
+
return out
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def capbox_coop_defines(target=None, text="", options=(), forest=False):
|
|
362
|
+
"""['-DDK_CAPBOX_COOP=0'] for a tree-engine unit whose text has the cooperative box contact VJP pass (the macro
|
|
363
|
+
DK_CAPBOX_COOP in text), or a forest-engine unit of a terrain build with it (cbter_dir_vjp in text: the terrain
|
|
364
|
+
capsule-box contacts' pass), on a build target of CAPBOX_COOP_OFF (sm_90 / sm_90a) where $DK_SM90_CAPBOX_COOP is 0
|
|
365
|
+
(the default), unless `options` already define DK_CAPBOX_COOP; else [] (forest units without terrain, other
|
|
366
|
+
targets, texts without the pass, the switch at 1). Bitwise unchanged: both paths give the same gradients (module
|
|
367
|
+
docstring)."""
|
|
368
|
+
target = target or arch()
|
|
369
|
+
if target not in CAPBOX_COOP_OFF or "DK_CAPBOX_COOP" not in text or (forest and "cbter_dir_vjp(" not in text):
|
|
370
|
+
return []
|
|
371
|
+
v = (os.environ.get(CAPBOX_COOP_VAR) or "0").strip()
|
|
372
|
+
if v not in ("0", "1"):
|
|
373
|
+
raise ValueError(f"${CAPBOX_COOP_VAR}={v!r}: must be 0 or 1")
|
|
374
|
+
if v == "1" or any(o == "-DDK_CAPBOX_COOP" or o.startswith("-DDK_CAPBOX_COOP=") for o in options):
|
|
375
|
+
return []
|
|
376
|
+
return ["-DDK_CAPBOX_COOP=0"]
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def tree_adj_cap():
|
|
380
|
+
"""$DK_SM90_ADJ_CAP: None for 1 (the default: TREE_ADJ_CAPS on terrain builds), 0 for no cap, N for ADJ_MAXNREG=N on
|
|
381
|
+
every tree-engine unit that launches k_adjoint (64..255; experiments, e.g. a bitwise check of other models)."""
|
|
382
|
+
v = (os.environ.get(TREE_ADJ_VAR) or "1").strip()
|
|
383
|
+
if v == "1":
|
|
384
|
+
return None
|
|
385
|
+
if v == "0":
|
|
386
|
+
return 0
|
|
387
|
+
if v.isdigit() and 64 <= int(v) <= 255:
|
|
388
|
+
return int(v)
|
|
389
|
+
raise ValueError(f"${TREE_ADJ_VAR}={v!r}: must be 1, 0 or a register count 64..255")
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def tree_adj_cap_defines(target=None, options=(), nvcc_path=None, forest=False, terrain=False):
|
|
393
|
+
"""The tree engine's k_adjoint register cap on sm_90 / sm_90a (TREE_ADJ_CAPS: ['-DADJ_MAXNREG=168']) for a unit that
|
|
394
|
+
launches k_adjoint of a terrain build (terrain) where $DK_SM90_ADJ_CAP is 1 (the default); ['-DADJ_MAXNREG=N'] on
|
|
395
|
+
every tree-engine such unit with N. Forest units (forest): the same for a terrain build's units (the tree engine's
|
|
396
|
+
terrain VJP device code; since 2026-11-15) only where $DK_SM90_FOREST_ADJ_CAP is 1 (default 0: no cap until
|
|
397
|
+
verified on sm_90), none without terrain. None with 0, for other targets, a caller's own
|
|
398
|
+
-DADJ_MAXNREG, or an nvcc older than 12.4. The unit's text needs with_adj_bounds (g1_engine.adjoint). Register
|
|
399
|
+
allocation only (bitwise unchanged; module docstring)."""
|
|
400
|
+
target = target or arch()
|
|
401
|
+
if target not in TREE_ADJ_CAPS or (forest and not terrain):
|
|
402
|
+
return []
|
|
403
|
+
if forest:
|
|
404
|
+
v = (os.environ.get(FOREST_TER_CAP_VAR) or "0").strip()
|
|
405
|
+
if v not in ("0", "1"):
|
|
406
|
+
raise ValueError(f"${FOREST_TER_CAP_VAR}={v!r}: must be 0 or 1")
|
|
407
|
+
if v == "0":
|
|
408
|
+
return []
|
|
409
|
+
n = tree_adj_cap()
|
|
410
|
+
if n == 0 or (n is None and not terrain):
|
|
411
|
+
return []
|
|
412
|
+
caps = TREE_ADJ_CAPS[target] if n is None else (f"ADJ_MAXNREG={n}",)
|
|
413
|
+
if not _maxnreg_ok(nvcc_path or nvcc(), TREE_ADJ_VAR):
|
|
414
|
+
return []
|
|
415
|
+
return reg_caps_defines(options, caps)
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
def forest_adj_cap():
|
|
419
|
+
"""$DK_SM103_FOREST_ADJ_CAP: None for 1 (the default: FOREST_ADJ_CAPS' value where forest_adj_light), 0 for no
|
|
420
|
+
cap, N for a register cap of N on every forest model (64..255; e.g. for a timing sweep). Read only where FOREST_ADJ_CAPS has the build target and its register-cap
|
|
421
|
+
switch is 1."""
|
|
422
|
+
v = (os.environ.get(FOREST_ADJ_VAR) or "1").strip()
|
|
423
|
+
if v == "1":
|
|
424
|
+
return None
|
|
425
|
+
if v == "0":
|
|
426
|
+
return 0
|
|
427
|
+
if v.isdigit() and 64 <= int(v) <= 255:
|
|
428
|
+
return int(v)
|
|
429
|
+
raise ValueError(f"${FOREST_ADJ_VAR}={v!r}: must be 1, 0 or a register count 64..255")
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def forest_adj_light(m):
|
|
433
|
+
"""Whether the forest engine's sm_103 adjoint cap applies to model m by default (FOREST_ADJ_CAPS under
|
|
434
|
+
$DK_SM103_FOREST_ADJ_CAP=1): every contact pair between planes, spheres and capsules (no box, mesh, cylinder,
|
|
435
|
+
ellipsoid or height-field pair, whose contact VJPs and replays take k_adjoint to 236-255 registers) and the
|
|
436
|
+
pyramidal cone. ptxas 12.9 (NVVM 7 adjoint on sm_103): such models' uncapped k_adjoint stays at about 120-150
|
|
437
|
+
registers, so the cap at 128 costs a few spilled bytes for up to 16 worlds per SM (B300: G1 on the forest engine
|
|
438
|
+
backward -12.5%); with box pairs it costs 1.3-2.4 KB of spills and was slower (B300: +7.3% backward on a
|
|
439
|
+
hand scene)."""
|
|
440
|
+
import mujoco
|
|
441
|
+
light = {int(mujoco.mjtGeom.mjGEOM_PLANE), int(mujoco.mjtGeom.mjGEOM_SPHERE), int(mujoco.mjtGeom.mjGEOM_CAPSULE)}
|
|
442
|
+
if int(m.opt.cone) != int(mujoco.mjtCone.mjCONE_PYRAMIDAL):
|
|
443
|
+
return False
|
|
444
|
+
return all(int(m.geom_type[g]) in light for g in list(m.pair_geom1) + list(m.pair_geom2))
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def adjoint_defines(target=None, options=(), nvcc_path=None, forest=False, light=True):
|
|
448
|
+
"""The -D options of a unit that launches k_adjoint (the FFI library's adjoint variant units, the adjoint check
|
|
449
|
+
binary) for its build target (ADJ_CAPS: sm_103 ['-DADJ_MAXNREG=120'] where $DK_SM103_REG_CAPS is 1, the default),
|
|
450
|
+
unless `options` already bound k_adjoint; every other target: none. forest: a forest-engine unit (FOREST_ADJ_CAPS:
|
|
451
|
+
sm_103 ['-DADJ_MAXNREG=128'] where `light` (forest_adj_light of the model) and $DK_SM103_FOREST_ADJ_CAP is 1, the
|
|
452
|
+
default; none with 0; ['-DADJ_MAXNREG=N'] for every forest model with N). Register allocation only (bitwise
|
|
453
|
+
unchanged)."""
|
|
454
|
+
target = target or arch()
|
|
455
|
+
table = FOREST_ADJ_CAPS if forest else ADJ_CAPS
|
|
456
|
+
if target not in table or not reg_caps(target):
|
|
457
|
+
return []
|
|
458
|
+
var, caps = table[target]
|
|
459
|
+
if forest:
|
|
460
|
+
n = forest_adj_cap()
|
|
461
|
+
if n == 0 or (n is None and not light):
|
|
462
|
+
return []
|
|
463
|
+
if n is not None:
|
|
464
|
+
caps = (f"ADJ_MAXNREG={n}",)
|
|
465
|
+
if not _maxnreg_ok(nvcc_path or nvcc(), var):
|
|
466
|
+
return []
|
|
467
|
+
return reg_caps_defines(options, caps)
|
|
468
|
+
|
|
469
|
+
|
|
470
|
+
def compile_command(src, out, extra=(), unit=None, defines=True, target=None, nvcc_path=None):
|
|
471
|
+
"""compile_cuda's command line for build target target (default arch()): [nvcc, -O3, <arch_flags(unit)>,
|
|
472
|
+
-std=c++17, [extra], [unit_defines(unit)], -o, out, src] (also scripts/identity_gate.py's)."""
|
|
473
|
+
extra = list(extra)
|
|
474
|
+
return [nvcc_path or nvcc(), "-O3", *arch_flags(unit, target, nvcc_path), "-std=c++17", *extra,
|
|
475
|
+
*(unit_defines(unit, target, extra, nvcc_path) if defines else []), "-o", str(out), str(src)]
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
def compile_cuda(src, out, extra=(), unit=None, defines=True):
|
|
479
|
+
"""nvcc -O3 <arch_flags(unit)> -std=c++17 [extra] [unit_defines(unit)] -o out src (unit 'forward': the forward /
|
|
480
|
+
kinematics kernels' unit, which gets the target's register caps; on sm_120 every unit is built from compute_90 PTX
|
|
481
|
+
by default; default unit: the adjoint units' / test programs' flags). defines=False: without unit_defines (the
|
|
482
|
+
caller passes every -D option itself). The command is compile_command's."""
|
|
483
|
+
subprocess.run(compile_command(src, out, extra, unit, defines), check=True)
|