tenkai 0.1.0__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.
tenkai/__init__.py ADDED
@@ -0,0 +1,35 @@
1
+ """Robot-specialized CUDA code generation and motion planning."""
2
+
3
+ from tenkai import sdf
4
+ from tenkai.cuda import (
5
+ Options,
6
+ generate_centers_kernel,
7
+ generate_collision_function,
8
+ generate_collision_kernel,
9
+ generate_fk_kernel,
10
+ generate_rrt_sources,
11
+ )
12
+ from tenkai.modeling import JointInfo, JointKind, KinematicModel, SelfCollisionRules, Sphere
13
+ from tenkai.rrt import Planner, RRTBuild, RRTConfig, RRTResult, build_rrt
14
+ from tenkai.shortcut import ShortcutConfig
15
+
16
+ __all__ = [
17
+ "sdf",
18
+ "JointInfo",
19
+ "JointKind",
20
+ "KinematicModel",
21
+ "Sphere",
22
+ "SelfCollisionRules",
23
+ "Options",
24
+ "generate_centers_kernel",
25
+ "generate_collision_function",
26
+ "generate_collision_kernel",
27
+ "generate_fk_kernel",
28
+ "generate_rrt_sources",
29
+ "Planner",
30
+ "RRTBuild",
31
+ "RRTConfig",
32
+ "RRTResult",
33
+ "build_rrt",
34
+ "ShortcutConfig",
35
+ ]
tenkai/build.py ADDED
@@ -0,0 +1,306 @@
1
+ """GPU compiler discovery and caching of compiled libraries."""
2
+
3
+ import fcntl
4
+ import hashlib
5
+ import json
6
+ import logging
7
+ import os
8
+ import re
9
+ import shutil
10
+ import subprocess
11
+ import time
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+ from tempfile import TemporaryDirectory
15
+ from typing import Literal, NotRequired, TypedDict
16
+
17
+ from tenkai.cuda import TEMPLATES
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+ type Backend = Literal["cuda", "hip"]
22
+
23
+
24
+ def target_arch(backend: Backend, arch: str | None) -> str:
25
+ if backend not in ("cuda", "hip"):
26
+ raise ValueError("backend must be cuda or hip")
27
+ if arch is None:
28
+ return "gfx1201" if backend == "hip" else "compute_75"
29
+
30
+ pattern = r"gfx[0-9a-f]+" if backend == "hip" else r"compute_[0-9]+"
31
+ if re.fullmatch(pattern, arch) is None:
32
+ example = "gfx1201" if backend == "hip" else "compute_75"
33
+ raise ValueError(f"invalid {backend} arch; expected an architecture such as {example}")
34
+
35
+ return arch
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class CompileOptions:
40
+ backend: Backend = "cuda"
41
+ arch: str | None = None
42
+ max_registers: int | None = None
43
+
44
+ def __post_init__(self) -> None:
45
+ target_arch(self.backend, self.arch)
46
+ registers = self.max_registers or 0
47
+ if registers != 0 and not 32 <= registers <= 255:
48
+ raise ValueError("max_registers must be 0 or between 32 and 255")
49
+ if self.backend == "hip" and registers:
50
+ raise ValueError("max_registers is only supported by the CUDA backend")
51
+
52
+
53
+ class BuildInfo(TypedDict):
54
+ nvcc: NotRequired[str]
55
+ hipcc: NotRequired[str]
56
+ backend: NotRequired[Backend]
57
+ compile_command: list[str]
58
+ max_registers: int | None
59
+
60
+
61
+ @dataclass
62
+ class Compilation:
63
+ library: Path
64
+ toolchain: BuildInfo
65
+ compiler_name: str
66
+ seconds: float
67
+ cache_hit: bool
68
+
69
+
70
+ @dataclass
71
+ class _CompileCommand:
72
+ compiler: list[str]
73
+ directory: Path
74
+ source: Path
75
+ output: Path
76
+ max_registers: int | None
77
+
78
+ def arguments(
79
+ self,
80
+ *,
81
+ output: str | Path | None = None,
82
+ path_roots: tuple[tuple[Path, Path], ...] = (),
83
+ ) -> list[str]:
84
+ arguments = [*self.compiler, "-I", str(self.directory), str(self.source)]
85
+ for index, argument in enumerate(arguments):
86
+ path = Path(argument)
87
+ for root, replacement in path_roots:
88
+ if path.is_relative_to(root):
89
+ arguments[index] = (replacement / path.relative_to(root)).as_posix()
90
+ break
91
+
92
+ arguments.extend(["-o", str(self.output if output is None else output)])
93
+ if self.max_registers:
94
+ arguments.append("--maxrregcount=" + str(self.max_registers))
95
+ return arguments
96
+
97
+
98
+ def _source_digest(directory: Path, backend: Backend) -> str:
99
+ files = [
100
+ (path.relative_to(directory).as_posix(), path)
101
+ for path in directory.rglob("*")
102
+ if path.is_file() and path.suffix in {".cu", ".cuh", ".h", ".hpp"}
103
+ ]
104
+ if backend == "hip":
105
+ for name in ("amd_hip_compat.h", "cuda_runtime.h"):
106
+ files.append(("hip/" + name, TEMPLATES / name))
107
+
108
+ contents = [
109
+ (name, hashlib.sha256(path.read_bytes()).hexdigest()) for name, path in sorted(files)
110
+ ]
111
+ return hashlib.sha256(json.dumps(contents).encode()).hexdigest()
112
+
113
+
114
+ def _library_cache_path(sources: str, command: _CompileCommand, version: str) -> Path:
115
+ normalized_command = command.arguments(
116
+ output="<output>",
117
+ path_roots=((TEMPLATES, Path("<templates>")), (command.directory, Path("."))),
118
+ )
119
+
120
+ host_version = ""
121
+ if "-ccbin" in command.compiler:
122
+ host = command.compiler[command.compiler.index("-ccbin") + 1]
123
+ host_version = subprocess.check_output([host, "--version"], text=True)
124
+
125
+ environment = {
126
+ name: os.environ.get(name)
127
+ for name in (
128
+ "NVCC_PREPEND_FLAGS",
129
+ "NVCC_APPEND_FLAGS",
130
+ "HIPCC_COMPILE_FLAGS_APPEND",
131
+ "HIPCC_LINK_FLAGS_APPEND",
132
+ "CPATH",
133
+ "CPLUS_INCLUDE_PATH",
134
+ "LIBRARY_PATH",
135
+ )
136
+ }
137
+ inputs = [
138
+ sources,
139
+ normalized_command,
140
+ version,
141
+ host_version,
142
+ environment,
143
+ ]
144
+ key = hashlib.sha256(json.dumps(inputs, sort_keys=True).encode()).hexdigest()
145
+ root = Path(os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache")
146
+ return root / "tenkai" / (key + ".so")
147
+
148
+
149
+ def _export_sources(directory: Path, output: Path) -> None:
150
+ if directory != output:
151
+ for path in list(directory.rglob("*")):
152
+ if not path.is_file():
153
+ continue
154
+ # A nested output directory must not be copied into itself.
155
+ if output.is_relative_to(directory) and path.is_relative_to(output):
156
+ continue
157
+ destination = output / path.relative_to(directory)
158
+ destination.parent.mkdir(parents=True, exist_ok=True)
159
+ shutil.copyfile(path, destination)
160
+
161
+
162
+ def compile_library(
163
+ directory: Path,
164
+ source: str | Path,
165
+ library: Path,
166
+ *,
167
+ options: CompileOptions = CompileOptions(),
168
+ cache: bool = True,
169
+ ) -> Compilation:
170
+ """Compile sources and preserve them beside the output library.
171
+
172
+ source is relative to directory; library is the requested output path.
173
+ Only native source/header contents and compiler settings determine reuse;
174
+ model metadata is excluded.
175
+ The returned command can be rerun from the output directory after temporary
176
+ sources are removed.
177
+ """
178
+ directory = directory.resolve()
179
+ source = (directory / source).resolve()
180
+ if not source.is_relative_to(directory):
181
+ raise ValueError("source must be within the generated source directory")
182
+ library = library.absolute()
183
+ compiler, version = compiler_command(options.backend, options.arch)
184
+ compiler_name = "hipcc" if options.backend == "hip" else "nvcc"
185
+ compiler.extend(["-O3", "-shared"])
186
+ if options.backend == "cuda":
187
+ compiler.append("-Xcompiler")
188
+ compiler.append("-fPIC")
189
+ command = _CompileCommand(compiler, directory, source, library, options.max_registers)
190
+
191
+ library.parent.mkdir(parents=True, exist_ok=True)
192
+ cached = None
193
+ if cache:
194
+ sources = _source_digest(directory, options.backend)
195
+ cached = _library_cache_path(sources, command, version)
196
+ _export_sources(directory, library.parent)
197
+ exported_command = command.arguments(path_roots=((directory, library.parent),))
198
+ seconds, hit = _compile_or_restore(command, compiler_name, cached)
199
+
200
+ info = BuildInfo(
201
+ backend=options.backend,
202
+ compile_command=exported_command,
203
+ max_registers=options.max_registers or None,
204
+ )
205
+ if options.backend == "hip":
206
+ info["hipcc"] = version
207
+ else:
208
+ info["nvcc"] = version
209
+ return Compilation(library, info, compiler_name, seconds, hit)
210
+
211
+
212
+ def _compile_or_restore(
213
+ command: _CompileCommand, compiler_name: str, cached: Path | None
214
+ ) -> tuple[float, bool]:
215
+ if cached is not None:
216
+ cached.parent.mkdir(parents=True, exist_ok=True)
217
+ with cached.with_suffix(".lock").open("a") as lock:
218
+ fcntl.flock(lock, fcntl.LOCK_EX)
219
+ return _build_library(command, compiler_name, cached)
220
+ return _build_library(command, compiler_name, cached)
221
+
222
+
223
+ def _build_library(
224
+ command: _CompileCommand, compiler_name: str, cached: Path | None
225
+ ) -> tuple[float, bool]:
226
+ log_path = command.output.parent / "compile.log"
227
+ target = command.output.resolve()
228
+ with TemporaryDirectory(prefix=".tenkai-", dir=target.parent) as temporary:
229
+ built = Path(temporary) / command.output.name
230
+ if cached is not None and cached.is_file():
231
+ shutil.copyfile(cached, built)
232
+ log_path.write_text("Compilation cache hit.\n")
233
+ seconds, hit = 0.0, True
234
+ logger.info("Reusing cached GPU kernel: %s", cached)
235
+ else:
236
+ logger.info("Compiling GPU kernel with %s (cache disabled).", compiler_name)
237
+ seconds = _run_compiler(command, compiler_name, built, log_path)
238
+ hit = False
239
+ if cached is not None:
240
+ with TemporaryDirectory(prefix=".tenkai-", dir=cached.parent) as staging:
241
+ stored = Path(staging) / command.output.name
242
+ shutil.copyfile(built, stored)
243
+ stored.replace(cached)
244
+ logger.info("Compilation finished in %.2f s.", seconds)
245
+
246
+ built.replace(target)
247
+ return seconds, hit
248
+
249
+
250
+ def _run_compiler(
251
+ command: _CompileCommand, compiler_name: str, output: Path, log_path: Path
252
+ ) -> float:
253
+ invocation = command.arguments(output=output)
254
+ with log_path.open("w") as log:
255
+ begin = time.perf_counter()
256
+ result = subprocess.run(
257
+ invocation, cwd=command.directory, stdout=log, stderr=subprocess.STDOUT
258
+ )
259
+ seconds = time.perf_counter() - begin
260
+ if result.returncode:
261
+ raise RuntimeError(f"{compiler_name} failed; see {log_path}\n{log_path.read_text()}")
262
+ return seconds
263
+
264
+
265
+ def compiler_command(backend: Backend = "cuda", arch: str | None = None) -> tuple[list[str], str]:
266
+ arch = target_arch(backend, arch)
267
+ if backend == "cuda":
268
+ nvcc, host, version = toolchain()
269
+ return [nvcc, "-ccbin", host, "-std=c++14", "-arch=" + arch, "-code=" + arch], version
270
+
271
+ hipcc = shutil.which(os.environ.get("HIPCC", "hipcc"))
272
+ if hipcc is None:
273
+ raise RuntimeError("hipcc not found; install ROCm or set HIPCC")
274
+
275
+ version = subprocess.check_output([hipcc, "--version"], text=True)
276
+ command = [
277
+ hipcc,
278
+ "-x",
279
+ "hip",
280
+ "-std=c++14",
281
+ "--offload-arch=" + arch,
282
+ "-I",
283
+ str(TEMPLATES),
284
+ "-include",
285
+ str(TEMPLATES / "amd_hip_compat.h"),
286
+ ]
287
+ return command, version
288
+
289
+
290
+ def toolchain() -> tuple[str, str, str]:
291
+ nvcc = shutil.which(os.environ.get("NVCC", "nvcc"))
292
+ if nvcc is None:
293
+ raise RuntimeError("nvcc not found; install the CUDA toolkit or set NVCC")
294
+
295
+ version = subprocess.check_output([nvcc, "--version"], text=True)
296
+ release = re.search(r"release (\d+)\.", version)
297
+
298
+ compiler = os.environ.get("CXX")
299
+ # CUDA 10 rejects the newer default GCC shipped on the original benchmark host.
300
+ if compiler is None:
301
+ compiler = "g++-8" if release and int(release[1]) == 10 else "c++"
302
+ compiler = shutil.which(compiler)
303
+ if compiler is None:
304
+ raise RuntimeError("CUDA host compiler not found; set CXX to a compiler supported by nvcc")
305
+
306
+ return nvcc, compiler, version
tenkai/cli.py ADDED
@@ -0,0 +1,65 @@
1
+ import json
2
+ import sys
3
+ from collections.abc import Sequence
4
+ from pathlib import Path
5
+ from typing import Annotated
6
+
7
+ import tyro
8
+
9
+ from tenkai.compiler import generate
10
+ from tenkai.cuda import Options
11
+ from tenkai.dag import Optimization
12
+
13
+ SCHEDULING = tyro.conf.create_mutex_group(required=False, title="scheduling")
14
+
15
+
16
+ def main(
17
+ urdf: Path,
18
+ spheres: Path,
19
+ output: tyro.conf.Positional[Path],
20
+ optimization: Optimization = "algebraic",
21
+ all_kernels: bool = False,
22
+ scheduling: Annotated[bool, SCHEDULING] = False,
23
+ no_scheduling: Annotated[bool, SCHEDULING] = False,
24
+ live_budget: Annotated[int | None, SCHEDULING] = None,
25
+ sphere_batch_size: int = 8,
26
+ ground: bool = True,
27
+ ) -> None:
28
+ """Generate CUDA source from a URDF model and collision sphere configuration.
29
+
30
+ Args:
31
+ scheduling: Schedule with a live budget of 64.
32
+ no_scheduling: Disable scheduling (the default).
33
+ live_budget: Schedule with a nonnegative live-value budget.
34
+ sphere_batch_size: Compile-time maximum robot spheres on one link sharing
35
+ an obstacle traversal. Must be positive.
36
+ ground: Require exactly one Ground in every environment.
37
+ """
38
+ if scheduling:
39
+ live_budget = 64
40
+ elif no_scheduling:
41
+ live_budget = None
42
+ try:
43
+ options = Options(
44
+ optimization=optimization,
45
+ live_budget=live_budget,
46
+ sphere_batch_size=sphere_batch_size,
47
+ ground=ground,
48
+ )
49
+ except ValueError as error:
50
+ print(error, file=sys.stderr)
51
+ raise SystemExit(2) from error
52
+ generation = generate(urdf, spheres, output, options, all_kernels)
53
+ print(json.dumps(generation.timings))
54
+
55
+
56
+ def cli(argv: Sequence[str] | None = None) -> None:
57
+ tyro.cli(
58
+ main,
59
+ args=argv,
60
+ config=(tyro.conf.DisallowNone, tyro.conf.FlagCreatePairsOff),
61
+ )
62
+
63
+
64
+ if __name__ == "__main__":
65
+ cli()
tenkai/compiler.py ADDED
@@ -0,0 +1,146 @@
1
+ """Compile a robot model into CUDA source files."""
2
+
3
+ import json
4
+ import math
5
+ import time
6
+ from collections.abc import Set
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+ from typing import Literal, TypedDict
10
+
11
+ from tenkai.cuda import (
12
+ Options,
13
+ generate_centers_kernel,
14
+ generate_collision_function,
15
+ generate_collision_kernel,
16
+ generate_fk_kernel,
17
+ generate_rrt_sources,
18
+ )
19
+ from tenkai.dag import Optimization
20
+ from tenkai.modeling import KinematicModel, read_config
21
+ from tenkai.sdf import SpecializationType, geometry_type_mask
22
+
23
+
24
+ class ControlJoint(TypedDict):
25
+ name: str
26
+ index: int
27
+ lower: float
28
+ upper: float
29
+
30
+
31
+ class ModelMetadata(TypedDict):
32
+ input_joint_names: list[str]
33
+ control_joints: list[ControlJoint]
34
+ sphere_count: int
35
+ scalar: str
36
+ math: Literal["f32-sfu"]
37
+ optimization: Optimization
38
+ live_budget: int | None
39
+ sphere_batch_size: int
40
+ ground: bool
41
+ self_collision_pair_count: int
42
+ external_sphere_count: int
43
+
44
+
45
+ @dataclass
46
+ class Generation:
47
+ model: ModelMetadata
48
+ timings: dict[str, float]
49
+
50
+
51
+ def control_joints(kin: KinematicModel, names: list[str]) -> list[ControlJoint]:
52
+ bounds: list[ControlJoint] = []
53
+ joint_indices = {joint.name: index for index, joint in enumerate(kin.joints)}
54
+ for name in names:
55
+ if name not in joint_indices:
56
+ raise ValueError("control is not a movable joint: " + name)
57
+
58
+ index = joint_indices[name]
59
+ joint = kin.joints[index]
60
+ if joint.kind == "continuous":
61
+ lower, upper = -math.tau, math.tau
62
+ else:
63
+ lower, upper = joint.lower, joint.upper
64
+ if not math.isfinite(lower) or not math.isfinite(upper) or lower >= upper:
65
+ raise ValueError("invalid sampling bounds for " + name)
66
+
67
+ bounds.append(ControlJoint(name=name, index=index, lower=lower, upper=upper))
68
+
69
+ return bounds
70
+
71
+
72
+ def generate(
73
+ urdf_path: Path,
74
+ yaml_path: Path,
75
+ output: Path,
76
+ options: Options = Options(),
77
+ all_kernels: bool = False,
78
+ *,
79
+ specialize_types: Set[SpecializationType] | None = None,
80
+ ) -> Generation:
81
+ """Write generated sources and model.json to output."""
82
+ geometry_type_mask(specialize_types)
83
+ total = time.perf_counter()
84
+ start = total
85
+ timings: dict[str, float] = {}
86
+
87
+ kin = KinematicModel.from_urdf(urdf_path.read_text())
88
+ timings["kinematics"] = time.perf_counter() - start
89
+
90
+ start = time.perf_counter()
91
+ source = yaml_path.read_text()
92
+ config = read_config(source)
93
+ spheres = config.resolve(kin)
94
+ rules = config.resolve_rules(kin, spheres)
95
+ bounds = control_joints(kin, config.control_joint_names)
96
+ controls = [joint["index"] for joint in bounds]
97
+ timings["spheres_and_controls"] = time.perf_counter() - start
98
+
99
+ files: dict[str, str] = {}
100
+ start = time.perf_counter()
101
+ files["collision.cuh"] = generate_collision_kernel(kin, spheres, options, rules=rules)
102
+ timings["collision_codegen"] = time.perf_counter() - start
103
+
104
+ start = time.perf_counter()
105
+ if controls:
106
+ files.update(
107
+ generate_rrt_sources(
108
+ kin, spheres, controls, options, rules=rules, specialize_types=specialize_types
109
+ )
110
+ )
111
+ timings["rrt_codegen"] = time.perf_counter() - start
112
+
113
+ if all_kernels:
114
+ start = time.perf_counter()
115
+ files["fk.cuh"] = generate_fk_kernel(kin, len(kin.poses) - 1, options)
116
+ files["centers.cuh"] = generate_centers_kernel(kin, spheres, options)
117
+ files["collision_function.cuh"] = generate_collision_function(
118
+ kin, spheres, options, rules=rules
119
+ )
120
+ timings["auxiliary_codegen"] = time.perf_counter() - start
121
+
122
+ start = time.perf_counter()
123
+ output.mkdir(parents=True, exist_ok=True)
124
+ for name, contents in files.items():
125
+ path = output / name
126
+ path.parent.mkdir(parents=True, exist_ok=True)
127
+ path.write_text(contents)
128
+
129
+ model = ModelMetadata(
130
+ input_joint_names=kin.joint_names,
131
+ control_joints=bounds,
132
+ sphere_count=len(spheres),
133
+ scalar="float",
134
+ math="f32-sfu",
135
+ optimization=options.optimization,
136
+ live_budget=options.live_budget,
137
+ sphere_batch_size=options.sphere_batch_size,
138
+ ground=options.ground,
139
+ self_collision_pair_count=len(rules.self_pairs),
140
+ external_sphere_count=sum(s.link_index not in rules.self_only_links for s in spheres),
141
+ )
142
+ (output / "model.json").write_text(json.dumps(model, indent=2, sort_keys=True, allow_nan=False))
143
+
144
+ timings["write_outputs"] = time.perf_counter() - start
145
+ timings["total"] = time.perf_counter() - total
146
+ return Generation(model, timings)