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.
Files changed (136) hide show
  1. nablaengine/__init__.py +4 -0
  2. nablaengine/_fixtures/README.md +19 -0
  3. nablaengine/_fixtures/data/mf_s0.npz +0 -0
  4. nablaengine/_fixtures/mjlab/LICENSE +27 -0
  5. nablaengine/_fixtures/mjlab/README.md +113 -0
  6. nablaengine/_fixtures/mjlab/g1_meta.json +32 -0
  7. nablaengine/_fixtures/mjlab/g1_train.mjb +0 -0
  8. nablaengine/_optional.py +30 -0
  9. nablaengine/_paths.py +38 -0
  10. nablaengine/actuators/__init__.py +169 -0
  11. nablaengine/actuators/bam.py +306 -0
  12. nablaengine/actuators/bam_params/LICENSE +202 -0
  13. nablaengine/actuators/bam_params/xl330/m6.json +19 -0
  14. nablaengine/boxbox.py +259 -0
  15. nablaengine/ccd.py +1122 -0
  16. nablaengine/checks.py +376 -0
  17. nablaengine/cuda.py +483 -0
  18. nablaengine/dist_query.py +628 -0
  19. nablaengine/dual.py +223 -0
  20. nablaengine/dyn_query.py +685 -0
  21. nablaengine/engines.py +114 -0
  22. nablaengine/envs/__init__.py +24 -0
  23. nablaengine/envs/brax.py +165 -0
  24. nablaengine/envs/convert.py +771 -0
  25. nablaengine/envs/dmc.py +523 -0
  26. nablaengine/envs/env.py +233 -0
  27. nablaengine/envs/kin.py +371 -0
  28. nablaengine/envs/ops.py +134 -0
  29. nablaengine/envs/rewards.py +57 -0
  30. nablaengine/fixtures.py +243 -0
  31. nablaengine/forest_engine/__init__.py +0 -0
  32. nablaengine/forest_engine/adjoint.py +1726 -0
  33. nablaengine/forest_engine/adjoint_contact.py +493 -0
  34. nablaengine/forest_engine/bam_hooks.py +248 -0
  35. nablaengine/forest_engine/body_params.py +1007 -0
  36. nablaengine/forest_engine/capacity_diag.py +116 -0
  37. nablaengine/forest_engine/ccd_coop.py +250 -0
  38. nablaengine/forest_engine/chol_blk.py +80 -0
  39. nablaengine/forest_engine/contact_forces.py +142 -0
  40. nablaengine/forest_engine/contact_vjp.py +462 -0
  41. nablaengine/forest_engine/convex.py +1331 -0
  42. nablaengine/forest_engine/cylinder.py +73 -0
  43. nablaengine/forest_engine/dist_device.py +923 -0
  44. nablaengine/forest_engine/dyn_device.py +696 -0
  45. nablaengine/forest_engine/ellipsoid.py +179 -0
  46. nablaengine/forest_engine/elliptic.py +272 -0
  47. nablaengine/forest_engine/equality.py +842 -0
  48. nablaengine/forest_engine/floss.py +148 -0
  49. nablaengine/forest_engine/foot_offset.py +368 -0
  50. nablaengine/forest_engine/free_gyro.py +288 -0
  51. nablaengine/forest_engine/host.py +530 -0
  52. nablaengine/forest_engine/kdof64.py +127 -0
  53. nablaengine/forest_engine/kinematics.py +320 -0
  54. nablaengine/forest_engine/margin.py +167 -0
  55. nablaengine/forest_engine/margin_convex.py +326 -0
  56. nablaengine/forest_engine/midphase.py +439 -0
  57. nablaengine/forest_engine/model_hooks.py +913 -0
  58. nablaengine/forest_engine/motor_hooks.py +50 -0
  59. nablaengine/forest_engine/muscle.py +485 -0
  60. nablaengine/forest_engine/nb128.py +118 -0
  61. nablaengine/forest_engine/nb64.py +163 -0
  62. nablaengine/forest_engine/noslip.py +1124 -0
  63. nablaengine/forest_engine/nv128.py +1944 -0
  64. nablaengine/forest_engine/object_size.py +283 -0
  65. nablaengine/forest_engine/replay_guard.py +40 -0
  66. nablaengine/forest_engine/root_spread.py +126 -0
  67. nablaengine/forest_engine/solref.py +74 -0
  68. nablaengine/forest_engine/source.py +1464 -0
  69. nablaengine/forest_engine/sparse_pattern.py +527 -0
  70. nablaengine/forest_engine/spatial.py +1045 -0
  71. nablaengine/forest_engine/step.py +3083 -0
  72. nablaengine/forest_engine/surrogate.py +498 -0
  73. nablaengine/forest_engine/tape.py +199 -0
  74. nablaengine/forest_engine/tendon.py +845 -0
  75. nablaengine/forest_engine/terrain.py +1059 -0
  76. nablaengine/forest_engine/world_forces.py +166 -0
  77. nablaengine/forest_engine/world_params.py +230 -0
  78. nablaengine/g1_engine/__init__.py +0 -0
  79. nablaengine/g1_engine/adjoint.py +1661 -0
  80. nablaengine/g1_engine/adjoint_contact.py +577 -0
  81. nablaengine/g1_engine/bam_hooks.py +596 -0
  82. nablaengine/g1_engine/condim4.py +245 -0
  83. nablaengine/g1_engine/contact_forces.py +500 -0
  84. nablaengine/g1_engine/cylccd.py +1158 -0
  85. nablaengine/g1_engine/cylinder.py +216 -0
  86. nablaengine/g1_engine/elliptic.py +565 -0
  87. nablaengine/g1_engine/exact_replay.py +61 -0
  88. nablaengine/g1_engine/host.py +358 -0
  89. nablaengine/g1_engine/kinematics.py +320 -0
  90. nablaengine/g1_engine/mesh.py +305 -0
  91. nablaengine/g1_engine/mesh_tables.py +79 -0
  92. nablaengine/g1_engine/model_hooks.py +919 -0
  93. nablaengine/g1_engine/motor_hooks.py +70 -0
  94. nablaengine/g1_engine/replay_guard.py +55 -0
  95. nablaengine/g1_engine/source.py +1107 -0
  96. nablaengine/g1_engine/sphbox.py +93 -0
  97. nablaengine/g1_engine/step.py +3716 -0
  98. nablaengine/g1_engine/tape.py +173 -0
  99. nablaengine/g1_engine/world_params.py +447 -0
  100. nablaengine/identity.py +401 -0
  101. nablaengine/jax_ffi.py +2536 -0
  102. nablaengine/model/__init__.py +1 -0
  103. nablaengine/model/capability.py +694 -0
  104. nablaengine/model/fields.py +317 -0
  105. nablaengine/model/gravcomp.py +64 -0
  106. nablaengine/model/invweight.py +145 -0
  107. nablaengine/motor.py +143 -0
  108. nablaengine/object_geometry.py +609 -0
  109. nablaengine/params.py +258 -0
  110. nablaengine/provenance.py +196 -0
  111. nablaengine/reference/__init__.py +0 -0
  112. nablaengine/reference/adjoint_groups.py +226 -0
  113. nablaengine/reference/jax64.py +690 -0
  114. nablaengine/reference/warp_physics.py +262 -0
  115. nablaengine/sensors/__init__.py +4 -0
  116. nablaengine/sensors/cameras.py +285 -0
  117. nablaengine/sensors/data/LIVOX_MID360_LICENSE +21 -0
  118. nablaengine/sensors/data/livox_mid360.npz +0 -0
  119. nablaengine/sensors/g1.py +521 -0
  120. nablaengine/sensors/jax_rays.py +364 -0
  121. nablaengine/sensors/optix_rays.py +725 -0
  122. nablaengine/sensors/raycore.py +630 -0
  123. nablaengine/sensors/raygrad.py +374 -0
  124. nablaengine/sensors/raygrad_cuda.py +191 -0
  125. nablaengine/sensors/robot_mesh.py +273 -0
  126. nablaengine/sensors/torch_rays.py +275 -0
  127. nablaengine/terrain.py +424 -0
  128. nablaengine/torch_ffi.py +1328 -0
  129. nablaengine/workdir.py +37 -0
  130. nablaengine-1.0.2.dist-info/METADATA +236 -0
  131. nablaengine-1.0.2.dist-info/RECORD +136 -0
  132. nablaengine-1.0.2.dist-info/WHEEL +5 -0
  133. nablaengine-1.0.2.dist-info/licenses/LICENSE +202 -0
  134. nablaengine-1.0.2.dist-info/licenses/NOTICE +23 -0
  135. nablaengine-1.0.2.dist-info/licenses/THIRD_PARTY_NOTICES.md +176 -0
  136. nablaengine-1.0.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,401 @@
1
+ """Identity of the engine's build units: the hashes and comparisons behind the G1 identity gate
2
+ (scripts/identity_gate.py and its manifest)."""
3
+
4
+ import functools
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import re
9
+ import shlex
10
+ import shutil
11
+ import subprocess
12
+ from dataclasses import dataclass, field
13
+ from pathlib import Path
14
+
15
+ import numpy as np
16
+
17
+ SCHEMA = "dk-identity/1"
18
+ LEVELS = (0, 1, 2)
19
+ MANGLE = (re.compile(r"_INTERNAL_[0-9a-f]{8}_[0-9]+_[A-Za-z0-9_]+?_cu_[0-9a-f]{8}"),
20
+ re.compile(r"_GLOBAL__N__[0-9a-f]{8}_[0-9]+_[A-Za-z0-9_]+?_cu_[0-9a-f]{8}"))
21
+ SASS_HEADER = ("Fatbin", "code for", "arch =", "code version", "host =", "compile_size", "identifier", "producer")
22
+ NVCC_PLACEHOLDER = "nvcc"
23
+
24
+
25
+ def sha256(x):
26
+ """sha256 hex digest of a str (UTF-8), bytes or array (its raw bytes, C order)."""
27
+ if isinstance(x, np.ndarray):
28
+ x = np.ascontiguousarray(x).view(np.uint8).tobytes()
29
+ elif isinstance(x, str):
30
+ x = x.encode()
31
+ return hashlib.sha256(x).hexdigest()
32
+
33
+
34
+ def normalize_symbols(text, module_ids=()):
35
+ """The text with the unit's module ids (nvcc's -keep <file>.module_id) replaced by <MODULE>, then any internal-linkage
36
+ path hash left (MANGLE) by <INTERNAL> / <ANON>."""
37
+ for mid in sorted({m for m in module_ids if m}, key=len, reverse=True):
38
+ text = text.replace(mid, "<MODULE>")
39
+ return MANGLE[1].sub("<ANON>", MANGLE[0].sub("<INTERNAL>", text))
40
+
41
+
42
+ def normalize_preprocessed(text):
43
+ """Preprocessed source: trailing white space dropped, runs of blank lines collapsed (-P leaves blank lines where
44
+ directives were)."""
45
+ lines = [x.rstrip() for x in text.split("\n")]
46
+ return "\n".join(x for x in lines if x)
47
+
48
+
49
+ def normalize_ptx(text, module_ids=()):
50
+ """PTX without its comment lines (the compiler build and version header; the toolchain is recorded separately)."""
51
+ return normalize_symbols("\n".join(x for x in text.split("\n") if not x.lstrip().startswith("//")), module_ids)
52
+
53
+
54
+ def normalize_sass(text, module_ids=()):
55
+ """cuobjdump -sass output without its header lines (file, architecture, ELF identification), white space collapsed."""
56
+ out = []
57
+ for line in normalize_symbols(text, module_ids).split("\n"):
58
+ s = line.strip()
59
+ if not s or s.startswith(SASS_HEADER):
60
+ continue
61
+ out.append(re.sub(r"\s+", " ", s))
62
+ return "\n".join(out)
63
+
64
+
65
+ def normalize_host(text, module_ids=()):
66
+ """cudafe++'s host translation or stub file as the host compiler sees it: the #if 0 blocks dropped (cudafe++ keeps
67
+ the bodies of device functions and kernels there, so device-only code does not count as host code), then every
68
+ other preprocessor line (line markers, the #include of the stub and the fatbin, which carry temporary file names)."""
69
+ out, skip = [], 0
70
+ for line in text.split("\n"):
71
+ s = line.strip()
72
+ if s.startswith("#"):
73
+ d = s[1:].strip()
74
+ if skip:
75
+ if re.match(r"if(def|ndef)?\b", d):
76
+ skip += 1
77
+ elif re.match(r"endif\b", d) or (skip == 1 and re.match(r"(else|elif)\b", d)):
78
+ skip -= 1
79
+ elif re.match(r"if\s+0\s*$", d):
80
+ skip = 1
81
+ continue
82
+ if not skip:
83
+ out.append(line.rstrip())
84
+ return normalize_symbols("\n".join(out), module_ids)
85
+
86
+
87
+ def resource_usage(text, module_ids=()):
88
+ """{kernel / function: {REG, STACK, SHARED, LOCAL, ...}} from cuobjdump -res-usage (names normalized)."""
89
+ out, name = {}, None
90
+ for line in normalize_symbols(text, module_ids).split("\n"):
91
+ m = re.match(r"\s*Function (\S+?):?\s*$", line)
92
+ if m:
93
+ name = m.group(1)
94
+ continue
95
+ if name and "REG:" in line:
96
+ out[name] = {k: int(v) for k, v in re.findall(r"([A-Z]+(?:\[\d+\])?):(\d+)", line)}
97
+ name = None
98
+ return dict(sorted(out.items()))
99
+
100
+
101
+ def _run(cmd, cwd=None, check=True, env=None):
102
+ r = subprocess.run([str(c) for c in cmd], cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
103
+ universal_newlines=True, env=env)
104
+ if check and r.returncode:
105
+ raise RuntimeError(f"command failed ({r.returncode}): {' '.join(map(str, cmd))}\n{r.stdout[-4000:]}")
106
+ return r.stdout
107
+
108
+
109
+ def find_tool(name, env_var=None):
110
+ """A CUDA binary tool (cuobjdump, nvdisasm): ${env_var or NAME.upper()}, next to nvcc, on PATH, or a conda package
111
+ cache (cuda-<name>-12*: $CONDA_PKGS_DIRS, $CONDA_EXE's installation, ~/miniconda3, ~/miniforge3, ~/anaconda3);
112
+ None if none exists."""
113
+ from nablaengine import cuda
114
+ cands = [os.environ.get(env_var or name.upper())]
115
+ try:
116
+ cands.append(str(Path(cuda.nvcc()).parent / name))
117
+ except FileNotFoundError:
118
+ pass
119
+ cands.append(shutil.which(name))
120
+ pkgs = [Path(p) for p in os.environ.get("CONDA_PKGS_DIRS", "").split(",") if p]
121
+ if os.environ.get("CONDA_EXE"):
122
+ pkgs.append(Path(os.environ["CONDA_EXE"]).resolve().parents[1] / "pkgs")
123
+ pkgs += [Path.home() / d / "pkgs" for d in ("miniconda3", "miniforge3", "anaconda3")]
124
+ cands += [str(p) for d in pkgs for p in sorted(d.glob(f"cuda-{name}-12*/bin/{name}"))]
125
+ return next((c for c in cands if c and Path(c).is_file()), None)
126
+
127
+
128
+ @functools.lru_cache(maxsize=None)
129
+ def tool_version(path):
130
+ """'<release> (<build>)' of a CUDA tool's --version (e.g. '12.4.131 (cuda_12.4.r12.4/compiler.34097967_0)'), or of
131
+ the host compiler's first --version line; None if it does not run."""
132
+ try:
133
+ out = _run([path, "--version"])
134
+ except (OSError, RuntimeError):
135
+ return None
136
+ rel = re.search(r"\bV(\d+\.\d+\.\d+)", out)
137
+ build = re.search(r"Build (\S+)", out)
138
+ if rel:
139
+ return rel.group(1) + (f" ({build.group(1)})" if build else "")
140
+ return out.strip().split("\n")[0] or None
141
+
142
+
143
+ def release(version):
144
+ """'12.4.131' of tool_version's '12.4.131 (...)'."""
145
+ return (version or "").split(" ")[0] or None
146
+
147
+
148
+ @functools.lru_cache(maxsize=None)
149
+ def nvcc_gpu_codes(nvcc_path):
150
+ """The real architectures nvcc can target (nvcc --list-gpu-code)."""
151
+ return frozenset(_run([nvcc_path, "--list-gpu-code"]).split())
152
+
153
+
154
+ @functools.lru_cache(maxsize=None)
155
+ def ptxas_supports(ptxas_path, arch):
156
+ """Whether this ptxas assembles for arch (a tiny PTX for that architecture's virtual architecture)."""
157
+ import tempfile
158
+ with tempfile.TemporaryDirectory(prefix="dk_ptxas_") as d:
159
+ ptx = Path(d) / "k.ptx"
160
+ ver = "8.7" if int(arch[3:].rstrip("af")) >= 100 else "7.0"
161
+ ptx.write_text(f".version {ver}\n.target {arch}\n.address_size 64\n.visible .entry k() {{ ret; }}\n")
162
+ r = subprocess.run([ptxas_path, f"-arch={arch}", "-m64", str(ptx), "-o", str(Path(d) / "k.cubin")],
163
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
164
+ return r.returncode == 0
165
+
166
+
167
+ def find_ptxas(arch, nvcc_path):
168
+ """A ptxas that assembles for arch: $PTXAS, the pip package nvidia.cuda_nvcc's (the JAX stack's ptxas), next to
169
+ nvcc; None if none does."""
170
+ cands = [os.environ.get("PTXAS")]
171
+ try:
172
+ import nvidia.cuda_nvcc
173
+ cands.append(str(Path(list(nvidia.cuda_nvcc.__path__)[0]) / "bin" / "ptxas"))
174
+ except ImportError:
175
+ pass
176
+ cands.append(str(Path(nvcc_path).parent / "ptxas"))
177
+ return next((c for c in cands if c and Path(c).is_file() and ptxas_supports(c, arch)), None)
178
+
179
+
180
+ def host_compiler(nvcc_path):
181
+ """The host compiler nvcc runs (its -dryrun's first gcc / g++ / clang command), as a path or name."""
182
+ import tempfile
183
+ with tempfile.TemporaryDirectory(prefix="dk_hc_") as d:
184
+ (Path(d) / "k.cu").write_text("int main() { return 0; }\n")
185
+ out = _run([nvcc_path, "-dryrun", "-c", "-o", "k.o", "k.cu"], cwd=d, check=False)
186
+ for line in out.split("\n"):
187
+ if line.startswith("#$ "):
188
+ args = shlex.split(line[3:])
189
+ if args and Path(args[0]).name.startswith(("gcc", "g++", "cc", "c++", "clang")):
190
+ return args[0]
191
+ return None
192
+
193
+
194
+ @dataclass
195
+ class Unit:
196
+ """One nvcc translation unit of a production build. command: nvcc's arguments after the nvcc path, with "{src}" and
197
+ "{out}" for the source and output paths (the build function's own command, e.g. [..., "-c", "-o", "{out}",
198
+ "{src}"]); include: {placeholder: directory} for -I options whose directory is machine-specific (written as
199
+ "-I{placeholder}" in command)."""
200
+ name: str
201
+ file: str
202
+ source: str
203
+ command: list
204
+ defines: list
205
+ consts: object = None
206
+ include: dict = field(default_factory=dict)
207
+
208
+ def args(self, src, out, command=None):
209
+ """command (default: the unit's) with the paths filled in."""
210
+ rep = {"{src}": str(src), "{out}": str(out)}
211
+ rep.update({f"-I{{{k}}}": f"-I{v}" for k, v in self.include.items()})
212
+ return [rep.get(a, a) for a in (self.command if command is None else command)]
213
+
214
+
215
+ def arch_of(command):
216
+ """(virtual architecture, real architecture) of an nvcc command: -arch=sm_XY gives (compute_XY, sm_XY),
217
+ -arch=compute_XY -code=sm_ZW (compute_XY, sm_ZW)."""
218
+ a = next(x.split("=", 1)[1] for x in command if x.startswith("-arch="))
219
+ code = next((x.split("=", 1)[1] for x in command if x.startswith("-code=")), None)
220
+ if a.startswith("sm_"):
221
+ return "compute_" + a[3:], code or a
222
+ return a, code or a
223
+
224
+
225
+ def level0(unit):
226
+ """L0: the unit as generated, without a compiler run."""
227
+ out = dict(source=sha256(unit.source), defines=sha256(json.dumps(unit.defines)),
228
+ command=sha256(json.dumps(unit.command)), source_bytes=len(unit.source.encode()))
229
+ if unit.consts is not None:
230
+ c = np.ascontiguousarray(unit.consts, np.float32)
231
+ out.update(consts=sha256(c), consts_count=int(c.size))
232
+ return out
233
+
234
+
235
+ def _strip(args, drop_code):
236
+ out, it = [], iter(args)
237
+ for a in it:
238
+ if a == "-o":
239
+ next(it, None)
240
+ continue
241
+ if a in ("-c", "{src}") or (drop_code and a.startswith("-code=")):
242
+ continue
243
+ out.append(a)
244
+ return out
245
+
246
+
247
+ class Toolchain:
248
+ """The compilers and tools of this machine for one real architecture (see the module docstring)."""
249
+
250
+ def __init__(self, nvcc_path=None, cuobjdump=None):
251
+ from nablaengine import cuda
252
+ self.nvcc = nvcc_path or cuda.nvcc()
253
+ self.cuobjdump = cuobjdump or find_tool("cuobjdump")
254
+ self.host = host_compiler(self.nvcc)
255
+
256
+ def route(self, real):
257
+ """'nvcc' if nvcc targets real itself, 'ptxas' if it needs the separate ptxas, None if neither can."""
258
+ if real in nvcc_gpu_codes(self.nvcc):
259
+ return "nvcc"
260
+ return "ptxas" if find_ptxas(real, self.nvcc) else None
261
+
262
+ def record(self, real):
263
+ """{nvcc, host, ptxas (route ptxas only), cuobjdump}: tool versions, the manifest's toolchain key."""
264
+ rec = dict(nvcc=tool_version(self.nvcc), host=tool_version(self.host) if self.host else None)
265
+ if self.route(real) == "ptxas":
266
+ rec["ptxas"] = tool_version(find_ptxas(real, self.nvcc))
267
+ rec["cuobjdump"] = tool_version(self.cuobjdump) if self.cuobjdump else None
268
+ return rec
269
+
270
+ def key(self, real):
271
+ """The manifest key of this toolchain for real: '<arch> nvcc <release>[ ptxas <release>] host <...> cuobjdump
272
+ <release>'."""
273
+ r = self.record(real)
274
+ parts = [real, f"nvcc {release(r['nvcc'])}"] + ([f"ptxas {release(r['ptxas'])}"] if r.get("ptxas") else [])
275
+ host = re.search(r"(\d+\.\d+(\.\d+)?)", r["host"] or "")
276
+ hc = Path(self.host).name.split("-")[0] if self.host else "?"
277
+ parts += [f"{hc} {host.group(1) if host else '?'}", f"cuobjdump {release(r['cuobjdump'])}"]
278
+ return " ".join(parts)
279
+
280
+ def level1(self, unit, work):
281
+ """L1 of the unit (work: an empty directory, kept by the caller): the device and the host pass."""
282
+ virt, real = arch_of(unit.command)
283
+ drop_code = self.route(real) != "nvcc"
284
+ src = Path(work) / unit.file
285
+ src.write_text(unit.source)
286
+ base = unit.args(src.name, "unit.o", _strip(unit.command, drop_code))
287
+ pp = Path(work) / "device.ii"
288
+ _run([self.nvcc, *base, "-E", "-Xcompiler", "-P", "-o", pp.name, src.name], cwd=work)
289
+ out = dict(virtual=virt, device=sha256(normalize_preprocessed(pp.read_text())))
290
+ host = self._host_preprocess(base, src.name, work)
291
+ if host is None:
292
+ raise RuntimeError(f"{unit.name}: no host preprocessing step in nvcc -dryrun ({self.nvcc})")
293
+ out["host"] = sha256(normalize_preprocessed(host))
294
+ return out
295
+
296
+ def _host_preprocess(self, base, src, work):
297
+ dry = _run([self.nvcc, "-dryrun", *base, "-c", "-o", "unit_dry.o", src], cwd=work)
298
+ for line in dry.split("\n"):
299
+ if not line.startswith("#$ "):
300
+ continue
301
+ args = shlex.split(line[3:])
302
+ if (not args or "-E" not in args or any(a.startswith("-D__CUDA_ARCH__=") for a in args)
303
+ or not Path(args[0]).name.startswith(("gcc", "g++", "cc", "c++", "clang"))):
304
+ continue
305
+ if "-o" in args:
306
+ i = args.index("-o")
307
+ args[i + 1] = "host.ii"
308
+ else:
309
+ args += ["-o", "host.ii"]
310
+ _run([*args[:1], "-P", *args[1:]], cwd=work)
311
+ return (Path(work) / "host.ii").read_text()
312
+ return None
313
+
314
+ def level2(self, unit, work):
315
+ """L2 of the unit (work: an empty directory, kept by the caller): one compile with the production command plus
316
+ -keep, then the PTX, SASS, resource usage and host translation."""
317
+ virt, real = arch_of(unit.command)
318
+ route = self.route(real)
319
+ if route is None:
320
+ raise RuntimeError(f"{unit.name}: neither nvcc ({self.nvcc}) nor a ptxas ($PTXAS) targets {real}")
321
+ if self.cuobjdump is None:
322
+ raise RuntimeError("no cuobjdump: set CUOBJDUMP (a CUDA 12.8+ cuobjdump also reads sm_120)")
323
+ src = Path(work) / unit.file
324
+ src.write_text(unit.source)
325
+ keep = Path(work) / "keep"
326
+ keep.mkdir()
327
+ args = unit.args(src.name, "unit.out")
328
+ if route == "ptxas":
329
+ args = [a for a in args if not a.startswith("-code=")]
330
+ if any(a.startswith(("-Xptxas", "--ptxas-options", "-maxrregcount")) for a in args):
331
+ raise RuntimeError(f"{unit.name}: ptxas options in the command; the separate ptxas route does not "
332
+ "forward them")
333
+ _run([self.nvcc, *args, "-keep", "-keep-dir", "keep"], cwd=work)
334
+ stem = Path(unit.file).stem
335
+ mids = [p.read_text().strip() for p in keep.glob(f"{stem}.module_id")]
336
+ ptx = keep / f"{stem}.ptx"
337
+ if not ptx.exists():
338
+ raise RuntimeError(f"{unit.name}: no {ptx.name} in nvcc's -keep output")
339
+ if route == "ptxas":
340
+ cubin = keep / f"{stem}.{real}.ptxas.cubin"
341
+ _run([find_ptxas(real, self.nvcc), f"-arch={real}", "-m64", ptx, "-o", cubin])
342
+ else:
343
+ cubin = keep / f"{stem}.{real}.cubin"
344
+ if not cubin.exists():
345
+ raise RuntimeError(f"{unit.name}: no {cubin.name} in nvcc's -keep output")
346
+ sass = normalize_sass(_run([self.cuobjdump, "-sass", cubin]), mids)
347
+ if "Function" not in sass:
348
+ raise RuntimeError(f"{unit.name}: cuobjdump ({self.cuobjdump}) printed no SASS for {real}")
349
+ host = []
350
+ for suffix in (".cudafe1.cpp", ".cudafe1.stub.c"):
351
+ p = keep / f"{stem}{suffix}"
352
+ host.append(normalize_host(p.read_text(errors="replace"), mids) if p.exists() else "")
353
+ return dict(route=route, ptx_virtual=virt, ptx=sha256(normalize_ptx(ptx.read_text(), mids)),
354
+ sass=sha256(sass), sass_lines=sass.count("\n") + 1,
355
+ resources=resource_usage(_run([self.cuobjdump, "-res-usage", cubin]), mids),
356
+ host=sha256("\n//--\n".join(host)))
357
+
358
+
359
+ def options(command):
360
+ """An nvcc command line (a manifest entry's "command" string or an argument list) without its -D options: the
361
+ options that also act after preprocessing (code generation, ptxas, the host compiler)."""
362
+ args = command.split() if isinstance(command, str) else [str(a) for a in command]
363
+ return [a for a in args if not a.startswith("-D")]
364
+
365
+
366
+ def clearing_level(old, new):
367
+ """The first level at which a unit whose L0 differs between a manifest entry and a recomputed one may still be
368
+ identical (module docstring): 0 if L0 is identical; None if the packed constants differ (the units are uploaded
369
+ with them at run time, no compiler output contains them: the G1 runs other numbers whatever L1 and L2 say); 2 if
370
+ the nvcc options other than -D differ (e.g. -fmad=false, -Xptxas, -maxrregcount: they act on code generation
371
+ after preprocessing, so an identical L1 does not show an identical build); else 1 (the source or the -D options
372
+ differ: an identical preprocessed source shows a change the G1 build compiles out)."""
373
+ diff = compare(old, new).get(0, [])
374
+ if not diff:
375
+ return 0
376
+ if {"consts", "consts_count"} & set(diff):
377
+ return None
378
+ if options(old.get("command", "")) != options(new.get("command", "")):
379
+ return 2
380
+ return 1
381
+
382
+
383
+ def compare(old, new):
384
+ """Differences between a manifest unit entry and a recomputed one, per level: {0: [field, ...], 1: [...], 2: [...]}
385
+ (a level absent from either side is not compared). L2's resource usage counts as part of the SASS."""
386
+ diff = {}
387
+ for lv in LEVELS:
388
+ a, b = old.get(f"L{lv}"), new.get(f"L{lv}")
389
+ if a is None or b is None:
390
+ continue
391
+ keys = sorted(set(a) | set(b))
392
+ diff[lv] = [k for k in keys if a.get(k) != b.get(k)]
393
+ return diff
394
+
395
+
396
+ def manifest_skeleton(about, model):
397
+ return dict(schema=SCHEMA, about=about, model=model, normalization=dict(
398
+ module_id="nvcc -keep's <file>.module_id replaced by <MODULE> in PTX, SASS, resource names and host code",
399
+ mangle=[p.pattern for p in MANGLE], sass_header_dropped=list(SASS_HEADER),
400
+ ptx="comment lines dropped", host="#if 0 blocks (device code bodies) and preprocessor lines dropped",
401
+ preprocessed="trailing white space and blank lines dropped"), targets={})