From 2dd48f2ba44033ea777ea84344717b3ebd5663d5 Mon Sep 17 00:00:00 2001 From: Tassos Manganaris Date: Mon, 2 Nov 2026 16:51:01 -0500 Subject: [PATCH 1/6] Encode the goal once for goal-fixed travel-time queries MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - TravelTimeModel.encode_goal / travel_time_from_encoded_goal: T(·, q_g) from a goal encoded once. TD-NTFields keeps the goal embedding, P-NTFields [q_g, f(q_g)]; other models fall back to forward with the goal expanded. - TrainedField.towards(goal) returns a GoalField with travel_time(q) and gradient(q). MPPI plans with it. - check_method checks travel_time_from_encoded_goal against forward. On the UR5e benchmark MPPI goes from 92 to 42 ms per plan (scenarios) and from 195 to 113 ms (random pairs), with the same paths up to float32 rounding. Co-Authored-By: Claude Opus 5.5 --- README.md | 3 +++ src/ntfields/__init__.py | 3 ++- src/ntfields/base.py | 9 ++++++++ src/ntfields/field.py | 28 ++++++++++++++++++++++- src/ntfields/methods/pntfields/model.py | 14 +++++++++++- src/ntfields/methods/td_ntfields/model.py | 13 +++++++++-- src/ntfields/plan/mppi.py | 3 ++- src/ntfields/testing.py | 9 ++++++++ tests/unit/test_plan_eval.py | 15 ++++++++++++ 9 files changed, 91 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 328cc6e..0e72268 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,9 @@ print(travel_time_error(field, gt, sample_valid(problem, 500).to(device))) field = ntfields.load(field.ckpt_path, device=device) # reload later from the checkpoint ``` +For many queries against one goal, `field.towards(goal)` encodes the goal once and gives `.travel_time(q)` and +`.gradient(q)` for batches q; MPPI plans this way. + The same run from the CLI (needs the `[cli]` extra). `--method.*` sets any field of the method's config: ```bash diff --git a/src/ntfields/__init__.py b/src/ntfields/__init__.py index d8aa316..d34b102 100644 --- a/src/ntfields/__init__.py +++ b/src/ntfields/__init__.py @@ -1,7 +1,7 @@ from ntfields.api import TrainConfig, train from ntfields.base import Batch, LossOut, Method, MethodConfig, SceneCondition, TrainState, TravelTimeModel from ntfields.checkpoint import load -from ntfields.field import TrainedField +from ntfields.field import GoalField, TrainedField from ntfields.problem import Problem from ntfields.registry import available, get_method, register from ntfields.train import Epochs, TimeLimit @@ -11,6 +11,7 @@ __all__ = [ "Batch", "Epochs", + "GoalField", "LossOut", "Method", "MethodConfig", diff --git a/src/ntfields/base.py b/src/ntfields/base.py index 0e47d14..6ce677f 100644 --- a/src/ntfields/base.py +++ b/src/ntfields/base.py @@ -75,6 +75,15 @@ class TravelTimeModel(nn.Module, ABC): @abstractmethod def forward(self, q_s: Tensor, q_g: Tensor, scene: SceneCondition) -> Tensor: ... # (B,) + def encode_goal(self, q_g: Tensor, scene: SceneCondition) -> Tensor: + """What T(·, q_g) needs from one goal q_g (dim,), computed once (a (1, n) row); by default q_g itself. + Models override it, with `travel_time_from_encoded_goal`, to skip the goal's share of every query.""" + return q_g[None] + + def travel_time_from_encoded_goal(self, q: Tensor, e_g: Tensor, scene: SceneCondition) -> Tensor: + """T(q, q_g) (B,) for a batch q (B, dim) and e_g = encode_goal(q_g).""" + return self(q, e_g.expand(q.shape[0], -1), scene) + @dataclass class MethodConfig: diff --git a/src/ntfields/field.py b/src/ntfields/field.py index 554665e..e914cf8 100644 --- a/src/ntfields/field.py +++ b/src/ntfields/field.py @@ -5,11 +5,31 @@ import torch from torch import Tensor -from ntfields.base import Method, TravelTimeModel +from ntfields.base import Method, SceneCondition, TravelTimeModel from ntfields.plan import PLANNERS, PlanResult from ntfields.problem import Problem +@dataclass +class GoalField: + """T(·, q_g) for one goal, encoded once (see `TrainedField.towards`).""" + + model: TravelTimeModel + scene: SceneCondition + e_g: Tensor # the model's encode_goal(q_g) + + def travel_time(self, q: Tensor) -> Tensor: + with torch.no_grad(): + return self.model.travel_time_from_encoded_goal(q, self.e_g, self.scene) + + def gradient(self, q: Tensor) -> Tensor: + """∇_q T(q, q_g).""" + with torch.enable_grad(): + q = q.detach().requires_grad_(True) + (g,) = torch.autograd.grad(self.model.travel_time_from_encoded_goal(q, self.e_g, self.scene).sum(), q) + return g + + @dataclass class TrainedField: method: Method[Any] @@ -30,6 +50,12 @@ def gradient(self, q_s: Tensor, q_g: Tensor) -> tuple[Tensor, Tensor]: g_s, g_g = torch.autograd.grad(t.sum(), (q_s, q_g)) return g_s, g_g + def towards(self, goal: Tensor) -> GoalField: + """T(·, goal) for a goal (dim,), which is encoded once instead of once per query.""" + scene = self.problem.env.condition() + with torch.no_grad(): + return GoalField(self.model, scene, self.model.encode_goal(goal, scene)) + def plan(self, start: Tensor, goal: Tensor, planner: str | None = None) -> PlanResult: """Single query with `planner` (default: the method's default planner).""" return PLANNERS[planner or self.method.default_planner](self, start, goal) diff --git a/src/ntfields/methods/pntfields/model.py b/src/ntfields/methods/pntfields/model.py index ddfaf3d..6c5613c 100644 --- a/src/ntfields/methods/pntfields/model.py +++ b/src/ntfields/methods/pntfields/model.py @@ -94,7 +94,11 @@ def encode(self, q: Tensor) -> Tensor: def tau(self, q_s: Tensor, q_g: Tensor) -> Tensor: """τ (B,), the factor with T = ‖q_g - q_s‖ / τ.""" - f = torch.stack([self.encode(q_s), self.encode(q_g)]) + return self.tau_from_encodings(self.encode(q_s), self.encode(q_g)) + + def tau_from_encodings(self, f_s: Tensor, f_g: Tensor) -> Tensor: + """τ from the encodings f_s (B, hidden) and f_g (B or 1, hidden).""" + f = torch.stack(torch.broadcast_tensors(f_s, f_g)) x = torch.cat([torch.logsumexp(self.beta * f, 0), -torch.logsumexp(-self.beta * f, 0)], dim=-1) / self.beta for block in self.generator_blocks: x = block(x) @@ -104,6 +108,14 @@ def tau(self, q_s: Tensor, q_g: Tensor) -> Tensor: def forward(self, q_s: Tensor, q_g: Tensor, scene: SceneCondition) -> Tensor: return (q_g - q_s).norm(dim=-1) / self.tau(q_s, q_g) + def encode_goal(self, q_g: Tensor, scene: SceneCondition) -> Tensor: + """[q_g, f(q_g)] (1, dim + hidden): the numerator needs the goal itself.""" + return torch.cat([q_g[None], self.encode(q_g[None])], dim=-1) + + def travel_time_from_encoded_goal(self, q: Tensor, e_g: Tensor, scene: SceneCondition) -> Tensor: + q_g, f_g = e_g[:, : q.shape[-1]], e_g[:, q.shape[-1] :] + return (q_g - q).norm(dim=-1) / self.tau_from_encodings(self.encode(q), f_g) + def tau_jet(self, q_s: Tensor, q_g: Tensor) -> Jet: """τ (B,), and its gradient and Hessian diagonal (B, 2·dim) w.r.t. [q_s, q_g].""" a, da, la = self._encode_jet(q_s) diff --git a/src/ntfields/methods/td_ntfields/model.py b/src/ntfields/methods/td_ntfields/model.py index 542cc6b..9cc02f7 100644 --- a/src/ntfields/methods/td_ntfields/model.py +++ b/src/ntfields/methods/td_ntfields/model.py @@ -82,8 +82,17 @@ def embed(self, q: Tensor) -> Tensor: return F.instance_norm(self.final(x)[None])[0] def forward(self, q_s: Tensor, q_g: Tensor, scene: SceneCondition) -> Tensor: - e_s, e_g = self.embed(q_s), self.embed(q_g) - d = ((e_s - e_g) ** 2 + 1e-6).sqrt().view(q_s.shape[0], -1, self.group) + return self.travel_time_from_embeddings(self.embed(q_s), self.embed(q_g)) + + def encode_goal(self, q_g: Tensor, scene: SceneCondition) -> Tensor: + return self.embed(q_g[None]) + + def travel_time_from_encoded_goal(self, q: Tensor, e_g: Tensor, scene: SceneCondition) -> Tensor: + return self.travel_time_from_embeddings(self.embed(q), e_g) + + def travel_time_from_embeddings(self, e_s: Tensor, e_g: Tensor) -> Tensor: + """T from the embeddings e_s (B, hidden) and e_g (B or 1, hidden).""" + d = ((e_s - e_g) ** 2 + 1e-6).sqrt().view(e_s.shape[0], -1, self.group) t = self.temperature smooth_max = (torch.logsumexp(t * d, dim=-1) - math.log(self.group)) / t return self.out_scale * smooth_max.sum(dim=-1) diff --git a/src/ntfields/plan/mppi.py b/src/ntfields/plan/mppi.py index 5ed47a3..1d128ec 100644 --- a/src/ntfields/plan/mppi.py +++ b/src/ntfields/plan/mppi.py @@ -31,6 +31,7 @@ def mppi( first step. """ dim = start.shape[-1] + target = field.towards(goal) q, prior = start.clone(), torch.zeros_like(start) path, reached = [start], False for _ in range(max_steps): @@ -39,7 +40,7 @@ def mppi( steps = noise + prior_gain * prior steps = steps / (steps.norm(dim=2, keepdim=True).clamp(min=step) / step) ends = (q + steps.cumsum(dim=1))[:, [0, -1]].reshape(-1, dim) - cost = field.travel_time(ends, goal.expand_as(ends)).reshape(samples, 2) + cost = target.travel_time(ends).reshape(samples, 2) weight = torch.softmax(-temperature * (first_weight * cost[:, 0] + cost[:, 1]), dim=0) prior = weight @ steps[:, 0] q = q + prior diff --git a/src/ntfields/testing.py b/src/ntfields/testing.py index 9db867b..8ae5f49 100644 --- a/src/ntfields/testing.py +++ b/src/ntfields/testing.py @@ -1,6 +1,8 @@ from dataclasses import asdict from typing import Any +import torch + from ntfields.base import Method, TrainState from ntfields.checkpoint import config_from_dict from ntfields.data import sample_pairs @@ -24,6 +26,13 @@ def check_method(method_cls: type[Method[Any]], problem: Problem | None = None) assert t.shape == (64,), f"travel time must have shape (B,), got {tuple(t.shape)}" t_self = model(batch.q_s, batch.q_s, batch.scene) assert t_self.abs().max() < 1e-2 * t.abs().mean() + 1e-6, "T(q, q) must be ~0" + q_g = batch.q_g[0] + t_goal = model.travel_time_from_encoded_goal(batch.q_s, model.encode_goal(q_g, batch.scene), batch.scene) + torch.testing.assert_close( + t_goal, + model(batch.q_s, q_g.expand_as(batch.q_s), batch.scene), + msg="travel_time_from_encoded_goal must match forward", + ) out = method.loss(model, batch, TrainState(model=model, optimizer=method.optimizer(model))) assert out.total.ndim == 0 and out.total.isfinite(), "loss must be a finite scalar" diff --git a/tests/unit/test_plan_eval.py b/tests/unit/test_plan_eval.py index cb180ba..98e997f 100644 --- a/tests/unit/test_plan_eval.py +++ b/tests/unit/test_plan_eval.py @@ -6,6 +6,7 @@ from ntfields.gt import fmm_travel_time from ntfields.methods.euclidean import Euclidean, EuclideanConfig from ntfields.plan import mppi +from ntfields.registry import create from ntfields.speed import Clipped @@ -49,6 +50,20 @@ def test_planner_meets_in_free_space(): assert path_length(result.path) < 1.01 * float((goal - start).norm()) + 0.06 +def test_towards_matches_pair_queries(): + """In float64: in float32, embedding the goal alone rather than in a batch changes the rounding.""" + torch.manual_seed(0) + problem = _empty() + for name in ("euclidean", "td_ntfields", "pntfields"): + method = create(name) + field = TrainedField(method, problem, method.build_model(problem).double().eval()) + q = torch.rand(16, 2, dtype=torch.float64) - 0.5 + goal = torch.tensor([0.3, -0.2], dtype=torch.float64) + target = field.towards(goal) + torch.testing.assert_close(target.travel_time(q), field.travel_time(q, goal.expand_as(q)), msg=name) + torch.testing.assert_close(target.gradient(q), field.gradient(q, goal.expand_as(q))[0], msg=name) + + def test_mppi_reaches_goal_in_free_space(): field = _euclidean_field(_empty()) start, goal = torch.tensor([-0.6, -0.3]), torch.tensor([0.5, 0.4]) From 67c55f83ce1e41610c3132c55bd6922c0da721a8 Mon Sep 17 00:00:00 2001 From: Tassos Manganaris Date: Tue, 3 Nov 2026 12:47:44 -0500 Subject: [PATCH 2/6] Add ntfields.accel: TD-NTFields' inference form on eager and compiled backends - ntfields.inference: InferenceModel, the tensor-only functions backends build (encode_goal, travel_time, pair_travel_time and the optional gradient, pair_gradient), and autograd_inference for any model, which TrainedField.towards now uses. TravelTimeModel.inference_model returns a model's own form (None by default). - TD-NTFields' inference form, from fast-ntfields: LipschitzLinear rescales, the duplicated sin(lin1(x)) and the block gates folded into constants, instance norm written out, and gradients in forward mode. It matches autograd through the model to ~1e-15 in float64; check_method checks this for any model that has an inference form. - accelerate(field, "eager" | "compile", cuda_graphs) returns an AcceleratedField, with CUDA graphs per batch size around each function. Gradients the inference form leaves out are absent and raise. - A Field protocol for the planners, benchmark_ur5e and travel_time_error, which now take either field. - On the UR5e benchmark (RTX 3090), compile + CUDA graphs plans MPPI in 9 ms instead of 41 (scenarios) and 20 ms instead of 110 (random pairs), with the same success counts, and the bidirectional gradient planner in 1.4 ms instead of 36. Co-Authored-By: Claude Opus 5.5 --- README.md | 15 ++ src/ntfields/__init__.py | 3 +- src/ntfields/accel/__init__.py | 94 +++++++++ src/ntfields/accel/cuda_graphs.py | 41 ++++ src/ntfields/base.py | 9 + src/ntfields/eval/metrics.py | 4 +- src/ntfields/eval/ur5e.py | 6 +- src/ntfields/field.py | 49 +++-- src/ntfields/inference.py | 64 ++++++ src/ntfields/methods/td_ntfields/inference.py | 184 ++++++++++++++++++ src/ntfields/methods/td_ntfields/model.py | 21 +- src/ntfields/plan/__init__.py | 4 +- src/ntfields/plan/gradient_bidirectional.py | 4 +- src/ntfields/plan/mppi.py | 4 +- src/ntfields/testing.py | 29 ++- tests/unit/test_accel.py | 104 ++++++++++ 16 files changed, 606 insertions(+), 29 deletions(-) create mode 100644 src/ntfields/accel/__init__.py create mode 100644 src/ntfields/accel/cuda_graphs.py create mode 100644 src/ntfields/inference.py create mode 100644 src/ntfields/methods/td_ntfields/inference.py create mode 100644 tests/unit/test_accel.py diff --git a/README.md b/README.md index 0e72268..d6abeb3 100644 --- a/README.md +++ b/README.md @@ -97,6 +97,21 @@ To train on a fixed dataset instead of sampling, pass `data=` (a `PairDataset`, to `ntfields.train`. The training loop underneath, `ntfields.train.fit`, takes any `PairSource`: an object with `.batches(batch_size, scene, generator)`, asked once per epoch, so it can draw new pairs (or scenes) every epoch. +### Faster evaluation + +`field.accelerate()` evaluates the field through its model's inference form: weights folded into plain matmuls, +gradients in forward mode, compiled with torch.compile and replayed from CUDA graphs. It takes the field's place in +the planners and benchmarks (TD-NTFields only for now): + +```python +fast = field.accelerate() # "compile" (a few seconds per batch size on first use), or "eager" +result = fast.plan(starts[0].to(device), goals[0].to(device)) +print(benchmark_ur5e(fast)) +``` + +On an RTX 3090, MPPI on the UR5e benchmark drops from 41 to 9 ms per plan (scenarios) and from 110 to 20 ms (random +pairs), with the same success counts. + To build other arm scenes, use `ArmEnv.ur5e(points=..., spheres=...)`, which accepts point-cloud and sphere obstacles. diff --git a/src/ntfields/__init__.py b/src/ntfields/__init__.py index d34b102..8a760ed 100644 --- a/src/ntfields/__init__.py +++ b/src/ntfields/__init__.py @@ -1,7 +1,7 @@ from ntfields.api import TrainConfig, train from ntfields.base import Batch, LossOut, Method, MethodConfig, SceneCondition, TrainState, TravelTimeModel from ntfields.checkpoint import load -from ntfields.field import GoalField, TrainedField +from ntfields.field import Field, GoalField, TrainedField from ntfields.problem import Problem from ntfields.registry import available, get_method, register from ntfields.train import Epochs, TimeLimit @@ -11,6 +11,7 @@ __all__ = [ "Batch", "Epochs", + "Field", "GoalField", "LossOut", "Method", diff --git a/src/ntfields/accel/__init__.py b/src/ntfields/accel/__init__.py new file mode 100644 index 0000000..7d35ebf --- /dev/null +++ b/src/ntfields/accel/__init__.py @@ -0,0 +1,94 @@ +"""Faster evaluation of a trained field, through its model's inference form (`TravelTimeModel.inference_model`). + + fast = field.accelerate("compile") # or ntfields.accel.accelerate(field, ...) + fast.plan(start, goal) # planners and benchmarks take it in place of the field + t = fast.towards(goal).travel_time(q) + +Backends: +- "eager": the inference form as is (folded weights, forward-mode gradients) +- "compile": torch.compile (inductor) of each inference function, specialized per batch size (past torch._dynamo's + recompile limit, 8 sizes per function, further sizes run eagerly) + +With `cuda_graphs` (on a CUDA field), each function is also replayed from a CUDA graph per batch size, which +removes the launch overhead that dominates at planning batch sizes. + +The scene is the environment's condition when `accelerate` is called: unlike a TrainedField, an AcceleratedField does +not follow later changes to the environment (no model reads the scene yet). +""" + +from dataclasses import dataclass +from typing import Any, Literal + +import torch +from torch import Tensor + +from ntfields.accel.cuda_graphs import CudaGraphs +from ntfields.base import Method +from ntfields.field import GoalField, TrainedField +from ntfields.inference import InferenceModel +from ntfields.plan import PLANNERS, PlanResult +from ntfields.problem import Problem + +Backend = Literal["eager", "compile"] +# on the UR5e MPPI benchmark, max-autotune builds in 52 s instead of 4 s and plans at most 15% faster; CUDA graphs +# come from CudaGraphs, not inductor's modes +COMPILE_MODE = "default" + + +@dataclass +class AcceleratedField: + field: TrainedField + inference: InferenceModel + + @property + def problem(self) -> Problem: + return self.field.problem + + @property + def method(self) -> Method[Any]: + return self.field.method + + @property + def device(self) -> torch.device: + return self.field.device + + def travel_time(self, q_s: Tensor, q_g: Tensor) -> Tensor: + with torch.no_grad(): + return self.inference.pair_travel_time(q_s, q_g) + + def gradient(self, q_s: Tensor, q_g: Tensor) -> tuple[Tensor, Tensor]: + """(∇_{q_s} T, ∇_{q_g} T).""" + if self.inference.pair_gradient is None: + raise ValueError( + f"{type(self.field.model).__name__}'s inference model has no gradients; use the TrainedField's" + ) + with torch.no_grad(): + _, g_s, g_g = self.inference.pair_gradient(q_s, q_g) + return g_s, g_g + + def towards(self, goal: Tensor) -> GoalField: + """T(·, goal) for a goal (dim,), which is encoded once instead of once per query.""" + with torch.no_grad(): + return GoalField(self.inference, self.inference.encode_goal(goal[None])) + + def plan(self, start: Tensor, goal: Tensor, planner: str | None = None) -> PlanResult: + """Single query with `planner` (default: the method's default planner).""" + return PLANNERS[planner or self.method.default_planner](self, start, goal) + + +def accelerate(field: TrainedField, backend: Backend = "compile", cuda_graphs: bool = True) -> AcceleratedField: + """`field` evaluated through its model's inference form on `backend`; values and gradients match the field's + up to rounding. Gradients the inference form leaves out are absent: asking for them raises.""" + inference = field.model.inference_model(field.problem.env.condition()) + if inference is None: + raise ValueError(f"{type(field.model).__name__} ({field.method.name}) has no inference model to accelerate") + if backend == "compile": + inference = inference.map(lambda fn: torch.compile(fn, mode=COMPILE_MODE, dynamic=False)) + elif backend != "eager": + raise ValueError(f"unknown backend {backend!r}; available: eager, compile") + if cuda_graphs and field.device.type == "cuda": + inference = inference.map(CudaGraphs) + return AcceleratedField(field, inference) + + +__all__ = ["AcceleratedField", "Backend", "CudaGraphs", "accelerate"] diff --git a/src/ntfields/accel/cuda_graphs.py b/src/ntfields/accel/cuda_graphs.py new file mode 100644 index 0000000..e10f7e1 --- /dev/null +++ b/src/ntfields/accel/cuda_graphs.py @@ -0,0 +1,41 @@ +from collections.abc import Callable + +import torch +from torch import Tensor + +Outputs = Tensor | tuple[Tensor, ...] + + +class CudaGraphs: + """Replays fn from a CUDA graph captured per input shape. Inputs are copied into the graph's static buffers + (so one graph serves every goal embedding) and outputs are cloned out of them (so they outlive the next call). + fn must be a plain forward computation: no autograd and no host synchronization.""" + + def __init__(self, fn: Callable[..., Outputs]) -> None: + self.fn = fn + self._graphs: dict[tuple[object, ...], tuple[torch.cuda.CUDAGraph, tuple[Tensor, ...], Outputs]] = {} + + def __call__(self, *args: Tensor) -> Outputs: + key = tuple((a.shape, a.dtype, a.device) for a in args) + if key not in self._graphs: + self._graphs[key] = self._capture(args) + graph, inputs, out = self._graphs[key] + for buffer, arg in zip(inputs, args, strict=True): + buffer.copy_(arg) + graph.replay() + return out.clone() if isinstance(out, Tensor) else tuple(o.clone() for o in out) + + def _capture(self, args: tuple[Tensor, ...]) -> tuple[torch.cuda.CUDAGraph, tuple[Tensor, ...], Outputs]: + inputs = tuple(a.clone() for a in args) + with torch.no_grad(): + # warm up on a side stream (lazy initialization, autotuning), as torch.cuda.graph requires + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + for _ in range(3): + self.fn(*inputs) + torch.cuda.current_stream().wait_stream(stream) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + out = self.fn(*inputs) + return graph, inputs, out diff --git a/src/ntfields/base.py b/src/ntfields/base.py index 6ce677f..f668a8e 100644 --- a/src/ntfields/base.py +++ b/src/ntfields/base.py @@ -7,6 +7,7 @@ if TYPE_CHECKING: from ntfields.data.pair_sampler import Sampler + from ntfields.inference import InferenceModel from ntfields.problem import Problem from ntfields.train.callbacks import Callback @@ -84,6 +85,14 @@ def travel_time_from_encoded_goal(self, q: Tensor, e_g: Tensor, scene: SceneCond """T(q, q_g) (B,) for a batch q (B, dim) and e_g = encode_goal(q_g).""" return self(q, e_g.expand(q.shape[0], -1), scene) + def inference_model(self, scene: SceneCondition) -> "InferenceModel | None": + """The model's inference-only form, for ntfields.accel: its functions are plain forward networks, with every + training-time indirection folded away, and the gradients optional. None: the model has none. + + `scene` is fixed into the functions, which take tensors only. A scene-conditioned model would instead take + an encoded scene as an input, as the goal is (no model reads the scene yet).""" + return None + @dataclass class MethodConfig: diff --git a/src/ntfields/eval/metrics.py b/src/ntfields/eval/metrics.py index 78fb355..086f0fb 100644 --- a/src/ntfields/eval/metrics.py +++ b/src/ntfields/eval/metrics.py @@ -1,7 +1,7 @@ import torch from torch import Tensor -from ntfields.field import TrainedField +from ntfields.field import Field from ntfields.gt import GridField from ntfields.plan import PlanResult from ntfields.problem import Problem @@ -32,7 +32,7 @@ def plan_succeeded(problem: Problem, result: PlanResult) -> bool: return result.success and is_collision_free(problem, result.path) -def travel_time_error(field: TrainedField, gt: GridField, starts: Tensor) -> float: +def travel_time_error(field: Field, gt: GridField, starts: Tensor) -> float: """Mean |T_field(start, goal) - T_gt(start)| over starts with a finite ground truth.""" goals = gt.goal.to(starts).expand_as(starts) t_gt = gt.value(starts) diff --git a/src/ntfields/eval/ur5e.py b/src/ntfields/eval/ur5e.py index 292dc80..09cbfb8 100644 --- a/src/ntfields/eval/ur5e.py +++ b/src/ntfields/eval/ur5e.py @@ -3,11 +3,11 @@ import torch from ntfields.envs.arm import ArmEnv, ntrl_random_pairs, ntrl_scenarios -from ntfields.field import TrainedField +from ntfields.field import Field from ntfields.plan import mppi -def benchmark_ur5e(field: TrainedField, seeds: Sequence[int] = (2024, 1, 2)) -> dict[str, list[dict[str, int]]]: +def benchmark_ur5e(field: Field, seeds: Sequence[int] = (2024, 1, 2)) -> dict[str, list[dict[str, int]]]: """The UR5e evaluation: ntrl-demo's 5 scenarios and 50 random pairs, planned with MPPI once per seed. A plan succeeds if MPPI converges and every waypoint has a raw clearance (without the offset) above 0. @@ -15,7 +15,7 @@ def benchmark_ur5e(field: TrainedField, seeds: Sequence[int] = (2024, 1, 2)) -> """ env = field.problem.env assert isinstance(env, ArmEnv), "benchmark_ur5e needs the UR5e ArmEnv" - device = next(field.model.parameters()).device + device = field.device results: dict[str, list[dict[str, int]]] = {} for name, (starts, goals) in (("scenarios", ntrl_scenarios()), ("random", ntrl_random_pairs())): results[name] = [] diff --git a/src/ntfields/field.py b/src/ntfields/field.py index e914cf8..88742b2 100644 --- a/src/ntfields/field.py +++ b/src/ntfields/field.py @@ -1,33 +1,48 @@ from dataclasses import dataclass from pathlib import Path -from typing import Any +from typing import TYPE_CHECKING, Any, Protocol import torch from torch import Tensor -from ntfields.base import Method, SceneCondition, TravelTimeModel +from ntfields.base import Method, TravelTimeModel +from ntfields.inference import InferenceModel, autograd_inference from ntfields.plan import PLANNERS, PlanResult from ntfields.problem import Problem +if TYPE_CHECKING: + from ntfields.accel import AcceleratedField, Backend + + +class Field(Protocol): + """What planners and evaluation query: a TrainedField or an AcceleratedField.""" + + @property + def problem(self) -> Problem: ... + @property + def device(self) -> torch.device: ... + def travel_time(self, q_s: Tensor, q_g: Tensor) -> Tensor: ... + def gradient(self, q_s: Tensor, q_g: Tensor) -> tuple[Tensor, Tensor]: ... + def towards(self, goal: Tensor) -> "GoalField": ... + @dataclass class GoalField: """T(·, q_g) for one goal, encoded once (see `TrainedField.towards`).""" - model: TravelTimeModel - scene: SceneCondition - e_g: Tensor # the model's encode_goal(q_g) + inference: InferenceModel + e_g: Tensor # inference.encode_goal(q_g) def travel_time(self, q: Tensor) -> Tensor: with torch.no_grad(): - return self.model.travel_time_from_encoded_goal(q, self.e_g, self.scene) + return self.inference.travel_time(q, self.e_g) def gradient(self, q: Tensor) -> Tensor: """∇_q T(q, q_g).""" - with torch.enable_grad(): - q = q.detach().requires_grad_(True) - (g,) = torch.autograd.grad(self.model.travel_time_from_encoded_goal(q, self.e_g, self.scene).sum(), q) - return g + if self.inference.gradient is None: + raise ValueError("this inference model has no gradients; use the TrainedField's") + with torch.no_grad(): + return self.inference.gradient(q, self.e_g)[1] @dataclass @@ -37,6 +52,10 @@ class TrainedField: model: TravelTimeModel ckpt_path: Path | None = None + @property + def device(self) -> torch.device: + return next(self.model.parameters()).device + def travel_time(self, q_s: Tensor, q_g: Tensor) -> Tensor: with torch.no_grad(): return self.model(q_s, q_g, self.problem.env.condition()) @@ -52,10 +71,16 @@ def gradient(self, q_s: Tensor, q_g: Tensor) -> tuple[Tensor, Tensor]: def towards(self, goal: Tensor) -> GoalField: """T(·, goal) for a goal (dim,), which is encoded once instead of once per query.""" - scene = self.problem.env.condition() + inference = autograd_inference(self.model, self.problem.env.condition()) with torch.no_grad(): - return GoalField(self.model, scene, self.model.encode_goal(goal, scene)) + return GoalField(inference, inference.encode_goal(goal[None])) def plan(self, start: Tensor, goal: Tensor, planner: str | None = None) -> PlanResult: """Single query with `planner` (default: the method's default planner).""" return PLANNERS[planner or self.method.default_planner](self, start, goal) + + def accelerate(self, backend: "Backend" = "compile", cuda_graphs: bool = True) -> "AcceleratedField": + """This field, evaluated through its model's inference form (see `ntfields.accel.accelerate`).""" + from ntfields.accel import accelerate + + return accelerate(self, backend, cuda_graphs) diff --git a/src/ntfields/inference.py b/src/ntfields/inference.py new file mode 100644 index 0000000..16f7a98 --- /dev/null +++ b/src/ntfields/inference.py @@ -0,0 +1,64 @@ +"""Inference-time evaluation of a travel-time model, as functions of tensors only. + +A model's inference form (`TravelTimeModel.inference_model`) is what backends compile or export (ntfields.accel): +plain forward networks, so no autograd at query time. The gradients are optional: a model without forward-mode ones +leaves them out, and its accelerated field has none. `autograd_inference` builds every function from any model's own +methods, which is what TrainedField queries through. +""" + +from collections.abc import Callable +from dataclasses import dataclass +from typing import Any + +import torch +from torch import Tensor + +from ntfields.base import SceneCondition, TravelTimeModel + + +@dataclass +class InferenceModel: + encode_goal: Callable[[Tensor], Tensor] # q_g (1, dim) -> e_g (1, n) + travel_time: Callable[[Tensor, Tensor], Tensor] # q (B, dim), e_g (1, n) -> T (B,) + pair_travel_time: Callable[[Tensor, Tensor], Tensor] # q_s, q_g (B, dim) -> T (B,) + gradient: Callable[[Tensor, Tensor], tuple[Tensor, Tensor]] | None = None # q, e_g -> T, ∇_q T (B, dim) + # q_s, q_g -> T, ∇_{q_s} T, ∇_{q_g} T + pair_gradient: Callable[[Tensor, Tensor], tuple[Tensor, Tensor, Tensor]] | None = None + + def map(self, wrap: Callable[[Callable[..., Any]], Callable[..., Any]]) -> "InferenceModel": + """The same model with every function it has wrapped (e.g. compiled).""" + return InferenceModel( + wrap(self.encode_goal), + wrap(self.travel_time), + wrap(self.pair_travel_time), + None if self.gradient is None else wrap(self.gradient), + None if self.pair_gradient is None else wrap(self.pair_gradient), + ) + + +def autograd_inference(model: TravelTimeModel, scene: SceneCondition) -> InferenceModel: + """The inference functions of any model, from its forward, encode_goal and travel_time_from_encoded_goal, with + gradients by autograd.""" + + def gradient(q: Tensor, e_g: Tensor) -> tuple[Tensor, Tensor]: + with torch.enable_grad(): + q = q.detach().requires_grad_(True) + t = model.travel_time_from_encoded_goal(q, e_g, scene) + (g,) = torch.autograd.grad(t.sum(), q) + return t.detach(), g + + def pair_gradient(q_s: Tensor, q_g: Tensor) -> tuple[Tensor, Tensor, Tensor]: + with torch.enable_grad(): + q_s = q_s.detach().requires_grad_(True) + q_g = q_g.detach().requires_grad_(True) + t = model(q_s, q_g, scene) + g_s, g_g = torch.autograd.grad(t.sum(), (q_s, q_g)) + return t.detach(), g_s, g_g + + return InferenceModel( + encode_goal=lambda q_g: model.encode_goal(q_g[0], scene), + travel_time=lambda q, e_g: model.travel_time_from_encoded_goal(q, e_g, scene), + pair_travel_time=lambda q_s, q_g: model(q_s, q_g, scene), + gradient=gradient, + pair_gradient=pair_gradient, + ) diff --git a/src/ntfields/methods/td_ntfields/inference.py b/src/ntfields/methods/td_ntfields/inference.py new file mode 100644 index 0000000..64430f0 --- /dev/null +++ b/src/ntfields/methods/td_ntfields/inference.py @@ -0,0 +1,184 @@ +"""Inference-only form of TDMetricModel. + +Training-time indirections are removed so the graph is plain matmuls and pointwise ops, which every backend +(torch.compile, TensorRT, a hand-written kernel) handles well: +- each LipschitzLinear's row rescale is folded into a constant weight +- GatedBlock's duplicated sin(lin1(x)) is computed once +- the block gates' sigmoid(0.1 · gate) are folded into constants +- instance norm is written out (biased variance, eps 1e-5, no affine), as F.instance_norm computes it + +Outputs have the inputs' dtype whatever the weights': with float16 weights (`.half()`) and float32 inputs, the +matmuls and sines run in float16 and the instance norm and travel-time head in float32. + +Gradients are forward mode. The configuration has few dimensions (6 for an arm), so the embedding's full Jacobian +is pushed forward alongside the value: every activation is carried as a stack (1 + dim, B, F), row 0 the primal and +rows 1.. its derivative along each input coordinate. A dense layer is then one matmul over all 1 + dim rows, so the +launch count matches the plain forward and only the matmul height grows. +""" + +import math +from typing import cast + +import torch +import torch.nn.functional as F +from torch import Tensor, nn + +from ntfields.inference import InferenceModel +from ntfields.methods.td_ntfields.model import GatedBlock, LipschitzLinear, TDMetricModel, metric_travel_time + +INSTANCE_NORM_EPS = 1e-5 + + +def fold(model: TDMetricModel) -> InferenceModel: + embed = FoldedEmbedding(model) + return InferenceModel( + encode_goal=embed, + travel_time=GoalTravelTime(embed, model), + pair_travel_time=PairTravelTime(embed, model), + gradient=GoalTravelTimeGrad(embed, model), + pair_gradient=PairTravelTimeGrad(embed, model), + ) + + +def fold_linear(layer: LipschitzLinear) -> nn.Linear: + with torch.no_grad(): + row_norm = layer.weight.pow(2).sum(dim=1).sqrt() + scale = 1 + 1e-5 - F.softplus(1 - 1 / row_norm, beta=layer.beta) + out = nn.Linear(layer.in_features, layer.out_features, device=layer.weight.device, dtype=layer.weight.dtype) + out.weight.copy_(layer.weight * scale[:, None]) + out.bias.copy_(layer.bias) + return out.requires_grad_(False) + + +class FoldedEmbedding(nn.Module): + """e(q) of a TDMetricModel, with every constant folded: q (B, dim) -> e (B, hidden).""" + + b: Tensor + mix: Tensor + + def __init__(self, model: TDMetricModel) -> None: + super().__init__() + self.register_buffer("b", 2 * math.pi * model.fourier.b.detach().clone()) + self.gate_u = fold_linear(model.gate_u) + self.gate_v = fold_linear(model.gate_v) + blocks = cast(list[GatedBlock], list(model.blocks)) + self.lin1 = nn.ModuleList(fold_linear(b.lin1) for b in blocks) + self.lin2 = nn.ModuleList(fold_linear(b.lin2) for b in blocks) + self.lin3 = nn.ModuleList(fold_linear(b.lin3) for b in blocks) + self.register_buffer("mix", torch.stack([torch.sigmoid(0.1 * g.detach()) for g in model.block_gates])) + self.final = fold_linear(model.final) + + def blocks(self) -> list[tuple[nn.Linear, nn.Linear, nn.Linear]]: + return cast( + list[tuple[nn.Linear, nn.Linear, nn.Linear]], list(zip(self.lin1, self.lin2, self.lin3, strict=True)) + ) + + def forward(self, q: Tensor) -> Tensor: + proj = q.to(self.b.dtype) @ self.b.T + x = torch.cat([proj.sin(), proj.cos()], dim=-1) + u = self.gate_u(x).sin() + v = self.gate_v(x).sin() + uv = u - v # u·s + v·(1 - s) = v + (u - v)·s + for i, (lin1, lin2, lin3) in enumerate(self.blocks()): + x_in = x + x = v + uv * lin1(x).sin() + x = v + uv * lin2(x).sin() + w = self.mix[i] + x = (1.0 - w) * x_in + w * lin3(x).sin() + y = self.final(x).to(q.dtype) + mean = y.mean(dim=-1, keepdim=True) + var = (y - mean).pow(2).mean(dim=-1, keepdim=True) + return (y - mean) * torch.rsqrt(var + INSTANCE_NORM_EPS) + + def stacked(self, q: Tensor) -> Tensor: + """The embedding and its tangents along each coordinate of q, as one (1 + dim, B, hidden) stack.""" + proj = q.to(self.b.dtype) @ self.b.T + dproj = self.b.T[:, None, :].expand(-1, q.shape[0], -1) # d proj / d q_k = row k of b.T + c, s = proj.cos(), proj.sin() + x = torch.cat([torch.cat([s, c], dim=-1)[None], torch.cat([c * dproj, -s * dproj], dim=-1)]) + u = _sin(_linear(x, self.gate_u)) + v = _sin(_linear(x, self.gate_v)) + uv = u - v + for i, (lin1, lin2, lin3) in enumerate(self.blocks()): + x_in = x + x = v + _mul(uv, _sin(_linear(x, lin1))) + x = v + _mul(uv, _sin(_linear(x, lin2))) + w = self.mix[i] + x = (1.0 - w) * x_in + w * _sin(_linear(x, lin3)) + y = _linear(x, self.final).to(q.dtype) + # instance norm over the hidden axis: e = c·r with c = y - mean(y), r = rsqrt(mean(c²) + eps) + c = y - y.mean(dim=-1, keepdim=True) + r = torch.rsqrt((c[0] ** 2).mean(dim=-1, keepdim=True) + INSTANCE_NORM_EPS) + dvar = 2.0 * (c[:1] * c[1:]).mean(dim=-1, keepdim=True) + return torch.cat([c[:1] * r, c[1:] * r - 0.5 * r**3 * dvar * c[:1]]) + + +def _linear(s: Tensor, layer: nn.Linear) -> Tensor: + z = s @ layer.weight.T + return torch.cat([z[:1] + layer.bias, z[1:]]) + + +def _sin(s: Tensor) -> Tensor: + p = s[:1] + return torch.cat([p.sin(), p.cos() * s[1:]]) + + +def _mul(a: Tensor, b: Tensor) -> Tensor: + return torch.cat([a[:1] * b[:1], a[1:] * b[:1] + a[:1] * b[1:]]) + + +class _Metric(nn.Module): + """The travel-time head on a folded embedding.""" + + def __init__(self, embed: FoldedEmbedding, model: TDMetricModel) -> None: + super().__init__() + self.embed = embed + self.group = model.group + self.temperature = model.temperature + self.out_scale = model.out_scale + + def head(self, e_s: Tensor, e_g: Tensor) -> Tensor: + return metric_travel_time(e_s, e_g, self.group, self.temperature, self.out_scale) + + def head_grad(self, diff: Tensor) -> tuple[Tensor, Tensor]: + """T and ∂T/∂e_s from diff = e_s - e_g (B, hidden).""" + d = (diff**2 + 1e-6).sqrt() + dg = d.view(diff.shape[0], -1, self.group) + smooth_max = (torch.logsumexp(self.temperature * dg, dim=-1) - math.log(self.group)) / self.temperature + # ∂T/∂e_s = out_scale · softmax_group(t·d) · (e_s - e_g) / d + weight = torch.softmax(self.temperature * dg, dim=-1).view_as(d) + return self.out_scale * smooth_max.sum(dim=-1), self.out_scale * weight * diff / d + + +class GoalTravelTime(_Metric): + """q (B, dim), e_g (1, hidden) -> T (B,).""" + + def forward(self, q: Tensor, e_g: Tensor) -> Tensor: + return self.head(self.embed(q), e_g) + + +class GoalTravelTimeGrad(_Metric): + """q (B, dim), e_g (1, hidden) -> T (B,), ∇_q T (B, dim).""" + + def forward(self, q: Tensor, e_g: Tensor) -> tuple[Tensor, Tensor]: + s = self.embed.stacked(q) + t, dt_de = self.head_grad(s[0] - e_g) + return t, (s[1:] * dt_de).sum(dim=-1).T + + +class PairTravelTime(_Metric): + """q_s, q_g (B, dim) -> T (B,).""" + + def forward(self, q_s: Tensor, q_g: Tensor) -> Tensor: + e = self.embed(torch.cat([q_s, q_g])) + return self.head(e[: q_s.shape[0]], e[q_s.shape[0] :]) + + +class PairTravelTimeGrad(_Metric): + """q_s, q_g (B, dim) -> T (B,), ∇_{q_s} T (B, dim), ∇_{q_g} T (B, dim).""" + + def forward(self, q_s: Tensor, q_g: Tensor) -> tuple[Tensor, Tensor, Tensor]: + s = self.embed.stacked(torch.cat([q_s, q_g])) + ss, sg = s[:, : q_s.shape[0]], s[:, q_s.shape[0] :] + t, dt_de = self.head_grad(ss[0] - sg[0]) + return t, (ss[1:] * dt_de).sum(dim=-1).T, -(sg[1:] * dt_de).sum(dim=-1).T diff --git a/src/ntfields/methods/td_ntfields/model.py b/src/ntfields/methods/td_ntfields/model.py index 9cc02f7..742e569 100644 --- a/src/ntfields/methods/td_ntfields/model.py +++ b/src/ntfields/methods/td_ntfields/model.py @@ -1,4 +1,5 @@ import math +from typing import TYPE_CHECKING import torch import torch.nn.functional as F @@ -7,6 +8,9 @@ from ntfields.base import SceneCondition, TravelTimeModel from ntfields.nn import RandomFourierFeatures +if TYPE_CHECKING: + from ntfields.inference import InferenceModel + class LipschitzLinear(nn.Linear): """Linear layer whose weight rows are softly rescaled to norm <= 1 (ntrl-demo's `lip_norm`).""" @@ -92,7 +96,16 @@ def travel_time_from_encoded_goal(self, q: Tensor, e_g: Tensor, scene: SceneCond def travel_time_from_embeddings(self, e_s: Tensor, e_g: Tensor) -> Tensor: """T from the embeddings e_s (B, hidden) and e_g (B or 1, hidden).""" - d = ((e_s - e_g) ** 2 + 1e-6).sqrt().view(e_s.shape[0], -1, self.group) - t = self.temperature - smooth_max = (torch.logsumexp(t * d, dim=-1) - math.log(self.group)) / t - return self.out_scale * smooth_max.sum(dim=-1) + return metric_travel_time(e_s, e_g, self.group, self.temperature, self.out_scale) + + def inference_model(self, scene: SceneCondition) -> "InferenceModel": + from ntfields.methods.td_ntfields.inference import fold + + return fold(self) + + +def metric_travel_time(e_s: Tensor, e_g: Tensor, group: int, temperature: float, out_scale: float) -> Tensor: + """out_scale · Σ_groups smoothmax_group |e_s - e_g|, for e_s (B, hidden) and e_g (B or 1, hidden).""" + d = ((e_s - e_g) ** 2 + 1e-6).sqrt().view(e_s.shape[0], -1, group) + smooth_max = (torch.logsumexp(temperature * d, dim=-1) - math.log(group)) / temperature + return out_scale * smooth_max.sum(dim=-1) diff --git a/src/ntfields/plan/__init__.py b/src/ntfields/plan/__init__.py index 0c9a589..88f64a6 100644 --- a/src/ntfields/plan/__init__.py +++ b/src/ntfields/plan/__init__.py @@ -7,9 +7,9 @@ from ntfields.plan.mppi import mppi if TYPE_CHECKING: - from ntfields.field import TrainedField + from ntfields.field import Field -Planner = Callable[["TrainedField", Tensor, Tensor], PlanResult] +Planner = Callable[["Field", Tensor, Tensor], PlanResult] PLANNERS: dict[str, Planner] = {"gradient_bidirectional": gradient_bidirectional, "mppi": mppi} diff --git a/src/ntfields/plan/gradient_bidirectional.py b/src/ntfields/plan/gradient_bidirectional.py index a7aca16..e172f21 100644 --- a/src/ntfields/plan/gradient_bidirectional.py +++ b/src/ntfields/plan/gradient_bidirectional.py @@ -5,7 +5,7 @@ from torch import Tensor if TYPE_CHECKING: - from ntfields.field import TrainedField + from ntfields.field import Field @dataclass @@ -15,7 +15,7 @@ class PlanResult: def gradient_bidirectional( - field: "TrainedField", + field: "Field", start: Tensor, goal: Tensor, beta: float = 0.03, diff --git a/src/ntfields/plan/mppi.py b/src/ntfields/plan/mppi.py index 1d128ec..253e9df 100644 --- a/src/ntfields/plan/mppi.py +++ b/src/ntfields/plan/mppi.py @@ -6,11 +6,11 @@ from ntfields.plan.gradient_bidirectional import PlanResult if TYPE_CHECKING: - from ntfields.field import TrainedField + from ntfields.field import Field def mppi( - field: "TrainedField", + field: "Field", start: Tensor, goal: Tensor, samples: int = 50, diff --git a/src/ntfields/testing.py b/src/ntfields/testing.py index 8ae5f49..f7e0aa4 100644 --- a/src/ntfields/testing.py +++ b/src/ntfields/testing.py @@ -1,12 +1,14 @@ +import copy from dataclasses import asdict from typing import Any import torch -from ntfields.base import Method, TrainState +from ntfields.base import Batch, Method, TrainState, TravelTimeModel from ntfields.checkpoint import config_from_dict from ntfields.data import sample_pairs from ntfields.envs import load_env +from ntfields.inference import autograd_inference from ntfields.problem import Problem from ntfields.speed import Clipped @@ -33,8 +35,33 @@ def check_method(method_cls: type[Method[Any]], problem: Problem | None = None) model(batch.q_s, q_g.expand_as(batch.q_s), batch.scene), msg="travel_time_from_encoded_goal must match forward", ) + _check_inference_model(model, batch) out = method.loss(model, batch, TrainState(model=model, optimizer=method.optimizer(model))) assert out.total.ndim == 0 and out.total.isfinite(), "loss must be a finite scalar" out.total.backward() assert any(p.grad is not None and p.grad.abs().sum() > 0 for p in model.parameters()), "loss has no gradient" + + +def _check_inference_model(model: TravelTimeModel, batch: Batch) -> None: + """A model's inference form, if it has one, matches autograd through the model in the functions it provides (in + float64, where folding and forward-mode differentiation only change the rounding).""" + model = copy.deepcopy(model).double().eval() + inference = model.inference_model(batch.scene) + if inference is None: + return + reference = autograd_inference(model, batch.scene) + q_s, q_g = batch.q_s.double(), batch.q_g.double() + e_g = reference.encode_goal(q_g[:1]) + for name, args in ( + ("encode_goal", (q_g[:1],)), + ("travel_time", (q_s, e_g)), + ("gradient", (q_s, e_g)), + ("pair_travel_time", (q_s, q_g)), + ("pair_gradient", (q_s, q_g)), + ): + if getattr(inference, name) is None: + continue + with torch.no_grad(): + ours, expected = getattr(inference, name)(*args), getattr(reference, name)(*args) + torch.testing.assert_close(ours, expected, msg=f"inference_model().{name} must match autograd") diff --git a/tests/unit/test_accel.py b/tests/unit/test_accel.py new file mode 100644 index 0000000..38041a8 --- /dev/null +++ b/tests/unit/test_accel.py @@ -0,0 +1,104 @@ +from dataclasses import replace +from typing import cast + +import pytest +import torch + +from ntfields import Problem, TrainedField +from ntfields.accel import accelerate +from ntfields.envs import load_env +from ntfields.inference import autograd_inference +from ntfields.methods.td_ntfields.inference import fold +from ntfields.methods.td_ntfields.model import TDMetricModel +from ntfields.plan import mppi +from ntfields.registry import create +from ntfields.speed import Clipped + +requires_cuda = pytest.mark.skipif(not torch.cuda.is_available(), reason="needs CUDA") + + +def _td_field(dim: int = 2, dtype: torch.dtype = torch.float64, device: str = "cpu") -> TrainedField: + """A small TD-NTFields field with nonzero block gates, so every folded constant matters.""" + torch.manual_seed(0) + method = create("td_ntfields") + problem = Problem(load_env("box2d/empty"), Clipped()) + model = cast(TDMetricModel, method.build_model(problem)) + with torch.no_grad(): + for gate in model.block_gates: + gate.normal_() + return TrainedField(method, problem, model.to(dtype=dtype, device=device).eval()) + + +@pytest.mark.parametrize("name", ["encode_goal", "travel_time", "gradient", "pair_travel_time", "pair_gradient"]) +def test_td_inference_model_matches_autograd(name: str): + field = _td_field() + scene = field.problem.env.condition() + folded, reference = field.model.inference_model(scene), autograd_inference(field.model, scene) + assert folded is not None + q, y = torch.rand(32, 2, dtype=torch.float64) - 0.5, torch.rand(32, 2, dtype=torch.float64) - 0.5 + e_g = reference.encode_goal(y[:1]) + args = {"encode_goal": (y[:1],), "travel_time": (q, e_g), "gradient": (q, e_g)}.get(name, (q, y)) + with torch.no_grad(): + torch.testing.assert_close(getattr(folded, name)(*args), getattr(reference, name)(*args)) + + +def test_accelerated_field_matches_field(): + field = _td_field() + fast = accelerate(field, "eager") + q, y = torch.rand(16, 2, dtype=torch.float64) - 0.5, torch.rand(16, 2, dtype=torch.float64) - 0.5 + goal = y[0] + torch.testing.assert_close(fast.travel_time(q, y), field.travel_time(q, y)) + for ours, expected in zip(fast.gradient(q, y), field.gradient(q, y), strict=True): + torch.testing.assert_close(ours, expected) + torch.testing.assert_close(fast.towards(goal).travel_time(q), field.towards(goal).travel_time(q)) + torch.testing.assert_close(fast.towards(goal).gradient(q), field.towards(goal).gradient(q)) + + +def test_accelerated_field_plans_as_the_field(): + """Over a few steps: on an untrained field MPPI wanders, and rounding differences grow (1e-11 by step 20).""" + field = _td_field() + start, goal = torch.tensor([-0.6, -0.3], dtype=torch.float64), torch.tensor([0.5, 0.4], dtype=torch.float64) + paths = [ + mppi(f, start, goal, max_steps=15, generator=torch.Generator().manual_seed(0)).path + for f in (field, field.accelerate("eager")) + ] + torch.testing.assert_close(paths[0], paths[1]) + + +def test_gradients_are_absent_without_forward_mode_ones(monkeypatch: pytest.MonkeyPatch): + field = _td_field() + values_only = replace(fold(cast(TDMetricModel, field.model)), gradient=None, pair_gradient=None) + monkeypatch.setattr(field.model, "inference_model", lambda scene: values_only) + fast = accelerate(field, "eager") + start, goal = torch.tensor([-0.6, -0.3], dtype=torch.float64), torch.tensor([0.5, 0.4], dtype=torch.float64) + mppi(fast, start, goal, max_steps=5) # values only + with pytest.raises(ValueError, match="no gradients"): + fast.gradient(start[None], goal[None]) + with pytest.raises(ValueError, match="no gradients"): + fast.towards(goal).gradient(start[None]) + with pytest.raises(ValueError, match="no gradients"): + fast.plan(start, goal, "gradient_bidirectional") + + +def test_accelerate_needs_an_inference_model(): + problem = Problem(load_env("box2d/empty"), Clipped()) + method = create("pntfields") + with pytest.raises(ValueError, match="no inference model"): + accelerate(TrainedField(method, problem, method.build_model(problem))) + with pytest.raises(ValueError, match="unknown backend"): + accelerate(_td_field(), "tensorrt") # pyright: ignore[reportArgumentType] + + +@requires_cuda +def test_compiled_cuda_graphs_match_eager(): + field = _td_field(dtype=torch.float32, device="cuda") + eager, fast = field.accelerate("eager", cuda_graphs=False), field.accelerate("compile") + q = torch.rand(100, 2, device="cuda") - 0.5 + goals = torch.rand(2, 2, device="cuda") - 0.5 + # one graph serves every goal, and outputs are not overwritten by later replays + t = [fast.towards(g).travel_time(q) for g in goals] + for g, t_g in zip(goals, t, strict=True): + torch.testing.assert_close(t_g, eager.towards(g).travel_time(q), rtol=1e-4, atol=1e-5) + torch.testing.assert_close(fast.towards(g).gradient(q), eager.towards(g).gradient(q), rtol=1e-4, atol=1e-4) + for ours, expected in zip(fast.gradient(q, q.flip(0)), eager.gradient(q, q.flip(0)), strict=True): + torch.testing.assert_close(ours, expected, rtol=1e-4, atol=1e-4) From b64c4dc12fdda862427175af32e28c72f83bcab0 Mon Sep 17 00:00:00 2001 From: Tassos Manganaris Date: Tue, 3 Nov 2026 12:58:50 -0500 Subject: [PATCH 3/6] Add P-NTFields' inference form MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The goal is encoded once as [q_g, f(q_g)], and gradients are first-order forward-mode jets through the encoder and the generator (tau_jet without its second derivatives), then T = ‖q_g - q_s‖ / τ. At q_s = q_g the norm's derivative is taken as 0, as autograd does. All five functions match autograd to ~1e-15 in float64. - With the pntfields_arm preset on the UR5e problem (random weights, RTX 3090), compile + CUDA graphs takes MPPI from 0.58 to 0.25 ms per step and the bidirectional gradient planner from 0.67 to 0.08 ms. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- src/ntfields/methods/pntfields/inference.py | 146 ++++++++++++++++++++ src/ntfields/methods/pntfields/model.py | 10 +- tests/unit/test_accel.py | 25 +++- 4 files changed, 178 insertions(+), 5 deletions(-) create mode 100644 src/ntfields/methods/pntfields/inference.py diff --git a/README.md b/README.md index d6abeb3..f843163 100644 --- a/README.md +++ b/README.md @@ -101,7 +101,7 @@ to `ntfields.train`. The training loop underneath, `ntfields.train.fit`, takes a `field.accelerate()` evaluates the field through its model's inference form: weights folded into plain matmuls, gradients in forward mode, compiled with torch.compile and replayed from CUDA graphs. It takes the field's place in -the planners and benchmarks (TD-NTFields only for now): +the planners and benchmarks (TD-NTFields and P-NTFields): ```python fast = field.accelerate() # "compile" (a few seconds per batch size on first use), or "eager" diff --git a/src/ntfields/methods/pntfields/inference.py b/src/ntfields/methods/pntfields/inference.py new file mode 100644 index 0000000..f43cff1 --- /dev/null +++ b/src/ntfields/methods/pntfields/inference.py @@ -0,0 +1,146 @@ +"""Inference-only form of PNTFieldsModel. + +The model is already plain linear layers and softplus, so nothing is folded: the goal is encoded once as +[q_g, f(q_g)] (the numerator ‖q_g - q_s‖ needs q_g itself), and gradients are forward mode. They push first-order +jets (x, dx), dx (B, k, n) the derivatives along k input coordinates, through the encoder and the generator, as +`PNTFieldsModel.tau_jet` does without its second derivatives: k = dim for a fixed goal (its encoding is constant), +2·dim for pairs. +""" + +from typing import cast + +import torch +import torch.nn.functional as F +from torch import Tensor, nn + +from ntfields.inference import InferenceModel +from ntfields.methods.pntfields.model import PNTFieldsModel, ResidualBlock + +Jet = tuple[Tensor, Tensor] + + +def inference_model(model: PNTFieldsModel) -> InferenceModel: + return InferenceModel( + encode_goal=EncodeGoal(model), + travel_time=GoalTravelTime(model), + pair_travel_time=PairTravelTime(model), + gradient=GoalTravelTimeGrad(model), + pair_gradient=PairTravelTimeGrad(model), + ) + + +def _linear_jet(layer: nn.Linear, jet: Jet) -> Jet: + x, dx = jet + return layer(x), dx @ layer.weight.T + + +def _softplus_jet(jet: Jet, beta: float) -> Jet: + x, dx = jet + return F.softplus(x, beta=beta), dx * torch.sigmoid(beta * x)[:, None] + + +def _block_jet(block: ResidualBlock, jet: Jet) -> Jet: + h = _linear_jet(block.lin2, _softplus_jet(_linear_jet(block.lin1, jet), block.beta)) + return _softplus_jet((h[0] + jet[0], h[1] + jet[1]), block.beta) + + +class _PNTFields(nn.Module): + def __init__(self, model: PNTFieldsModel) -> None: + super().__init__() + self.model = model + self.dim = model.fourier.b.shape[1] + + def split(self, e_g: Tensor) -> tuple[Tensor, Tensor]: + """q_g (1, dim) and f(q_g) (1, hidden) from e_g = [q_g, f(q_g)].""" + return e_g[:, : self.dim], e_g[:, self.dim :] + + def encode_jet(self, q: Tensor) -> Jet: + """f(q) (B, hidden) and its derivatives along each coordinate of q (B, dim, hidden).""" + m = self.model + w = 2 * torch.pi * m.fourier.b.T # (dim, n) + p = (q @ w)[:, None] + sin, cos = p.sin(), p.cos() + jet: Jet = (torch.cat([sin, cos], -1)[:, 0], torch.cat([w * cos, -w * sin], -1)) + jet = _softplus_jet(_linear_jet(m.encoder_in, jet), m.beta) + for block in cast(list[ResidualBlock], list(m.encoder_blocks)): + jet = _block_jet(block, jet) + return _linear_jet(m.encoder_out, jet) + + def tau_jet(self, jet: Jet) -> Jet: + """τ (B,) and its derivatives (B, k) from the generator input's jet: [smooth max, smooth min] (B, 2·hidden) + and its k derivatives.""" + m = self.model + for block in cast(list[ResidualBlock], list(m.generator_blocks)): + jet = _block_jet(block, jet) + y, dy = _linear_jet(m.generator_out, _softplus_jet(_linear_jet(m.generator_hidden, jet), m.beta)) + tau = torch.sigmoid(0.1 * y) + return tau[:, 0], (dy * (0.1 * tau * (1 - tau))[:, None])[..., 0] + + def smooth_max_min(self, a: Tensor, b: Tensor) -> tuple[Tensor, Tensor]: + """The generator input [smooth max, smooth min] of the encodings a, b (B or 1, hidden), and + s = ∂max/∂a = ∂min/∂b = sigmoid(β(a - b)) (so ∂max/∂b = ∂min/∂a = 1 - s).""" + beta = self.model.beta + f = torch.stack(torch.broadcast_tensors(a, b)) + x = torch.cat([torch.logsumexp(beta * f, 0), -torch.logsumexp(-beta * f, 0)], dim=-1) / beta + return x, torch.sigmoid(beta * (a - b)) + + +def _travel_time_grads(diff: Tensor, tau: Tensor, dtau: Tensor) -> tuple[Tensor, Tensor]: + """T = ‖diff‖ / τ with diff = q_g - q_s, and ∂T/∂q_s = -diff / (‖diff‖·τ) - (T / τ)·∂τ/∂q_s for dtau = ∂τ/∂q_s. + At diff = 0 the norm's derivative is taken as 0, as autograd does.""" + r = diff.norm(dim=-1) + t = r / tau + unit = diff / torch.where(r > 0, r, 1.0)[:, None] + return t, -unit / tau[:, None] - (t / tau)[:, None] * dtau + + +class EncodeGoal(_PNTFields): + """q_g (1, dim) -> [q_g, f(q_g)] (1, dim + hidden).""" + + def forward(self, q_g: Tensor) -> Tensor: + return torch.cat([q_g, self.model.encode(q_g)], dim=-1) + + +class GoalTravelTime(_PNTFields): + """q (B, dim), e_g (1, dim + hidden) -> T (B,).""" + + def forward(self, q: Tensor, e_g: Tensor) -> Tensor: + q_g, f_g = self.split(e_g) + return (q_g - q).norm(dim=-1) / self.model.tau_from_encodings(self.model.encode(q), f_g) + + +class PairTravelTime(_PNTFields): + """q_s, q_g (B, dim) -> T (B,).""" + + def forward(self, q_s: Tensor, q_g: Tensor) -> Tensor: + f = self.model.encode(torch.cat([q_s, q_g])) + f_s, f_g = f[: q_s.shape[0]], f[q_s.shape[0] :] + return (q_g - q_s).norm(dim=-1) / self.model.tau_from_encodings(f_s, f_g) + + +class GoalTravelTimeGrad(_PNTFields): + """q (B, dim), e_g (1, dim + hidden) -> T (B,), ∇_q T (B, dim).""" + + def forward(self, q: Tensor, e_g: Tensor) -> tuple[Tensor, Tensor]: + q_g, f_g = self.split(e_g) + a, da = self.encode_jet(q) + x, s = self.smooth_max_min(a, f_g) + tau, dtau = self.tau_jet((x, torch.cat([da * s[:, None], da * (1 - s)[:, None]], -1))) + return _travel_time_grads(q_g - q, tau, dtau) + + +class PairTravelTimeGrad(_PNTFields): + """q_s, q_g (B, dim) -> T (B,), ∇_{q_s} T (B, dim), ∇_{q_g} T (B, dim).""" + + def forward(self, q_s: Tensor, q_g: Tensor) -> tuple[Tensor, Tensor, Tensor]: + a, da = self.encode_jet(q_s) + b, db = self.encode_jet(q_g) + x, s = self.smooth_max_min(a, b) + s, c = s[:, None], 1 - s[:, None] + # tangents along q_s (rows :dim) and q_g (rows dim:): max moves with s·da and c·db, min with c·da and s·db + dmax, dmin = torch.cat([da * s, db * c], 1), torch.cat([da * c, db * s], 1) + tau, dtau = self.tau_jet((x, torch.cat([dmax, dmin], -1))) + t, dt_dqs = _travel_time_grads(q_g - q_s, tau, dtau[:, : self.dim]) + # T is symmetric in its ends' roles: ∂T/∂q_g = diff / (‖diff‖·τ) - (T / τ)·∂τ/∂q_g + _, dt_dqg = _travel_time_grads(q_s - q_g, tau, dtau[:, self.dim :]) + return t, dt_dqs, dt_dqg diff --git a/src/ntfields/methods/pntfields/model.py b/src/ntfields/methods/pntfields/model.py index 6c5613c..2127341 100644 --- a/src/ntfields/methods/pntfields/model.py +++ b/src/ntfields/methods/pntfields/model.py @@ -1,5 +1,5 @@ import math -from typing import cast +from typing import TYPE_CHECKING, cast import torch import torch.nn.functional as F @@ -8,6 +8,9 @@ from ntfields.base import SceneCondition, TravelTimeModel from ntfields.nn import RandomFourierFeatures +if TYPE_CHECKING: + from ntfields.inference import InferenceModel + def _linear(in_features: int, out_features: int) -> nn.Linear: """Linear layer with the reference init: weights and biases U(±2/√fan_in).""" @@ -116,6 +119,11 @@ def travel_time_from_encoded_goal(self, q: Tensor, e_g: Tensor, scene: SceneCond q_g, f_g = e_g[:, : q.shape[-1]], e_g[:, q.shape[-1] :] return (q_g - q).norm(dim=-1) / self.tau_from_encodings(self.encode(q), f_g) + def inference_model(self, scene: SceneCondition) -> "InferenceModel": + from ntfields.methods.pntfields.inference import inference_model + + return inference_model(self) + def tau_jet(self, q_s: Tensor, q_g: Tensor) -> Jet: """τ (B,), and its gradient and Hessian diagonal (B, 2·dim) w.r.t. [q_s, q_g].""" a, da, la = self._encode_jet(q_s) diff --git a/tests/unit/test_accel.py b/tests/unit/test_accel.py index 38041a8..e442828 100644 --- a/tests/unit/test_accel.py +++ b/tests/unit/test_accel.py @@ -29,9 +29,17 @@ def _td_field(dim: int = 2, dtype: torch.dtype = torch.float64, device: str = "c return TrainedField(method, problem, model.to(dtype=dtype, device=device).eval()) +def _pntfields_field() -> TrainedField: + torch.manual_seed(0) + method = create("pntfields") + problem = Problem(load_env("box2d/empty"), Clipped()) + return TrainedField(method, problem, method.build_model(problem).double().eval()) + + +@pytest.mark.parametrize("method", ["td_ntfields", "pntfields"]) @pytest.mark.parametrize("name", ["encode_goal", "travel_time", "gradient", "pair_travel_time", "pair_gradient"]) -def test_td_inference_model_matches_autograd(name: str): - field = _td_field() +def test_inference_model_matches_autograd(method: str, name: str): + field = _td_field() if method == "td_ntfields" else _pntfields_field() scene = field.problem.env.condition() folded, reference = field.model.inference_model(scene), autograd_inference(field.model, scene) assert folded is not None @@ -42,6 +50,17 @@ def test_td_inference_model_matches_autograd(name: str): torch.testing.assert_close(getattr(folded, name)(*args), getattr(reference, name)(*args)) +def test_pntfields_pair_gradient_at_coincident_ends(): + """‖q_g - q_s‖ has no derivative at q_s = q_g; the forward-mode gradients take it as 0, as autograd does.""" + field = _pntfields_field() + scene = field.problem.env.condition() + folded, reference = field.model.inference_model(scene), autograd_inference(field.model, scene) + assert folded is not None and folded.pair_gradient is not None and reference.pair_gradient is not None + q = torch.rand(8, 2, dtype=torch.float64) - 0.5 + for ours, expected in zip(folded.pair_gradient(q, q), reference.pair_gradient(q, q), strict=True): + torch.testing.assert_close(ours, expected) + + def test_accelerated_field_matches_field(): field = _td_field() fast = accelerate(field, "eager") @@ -82,7 +101,7 @@ def test_gradients_are_absent_without_forward_mode_ones(monkeypatch: pytest.Monk def test_accelerate_needs_an_inference_model(): problem = Problem(load_env("box2d/empty"), Clipped()) - method = create("pntfields") + method = create("euclidean") with pytest.raises(ValueError, match="no inference model"): accelerate(TrainedField(method, problem, method.build_model(problem))) with pytest.raises(ValueError, match="unknown backend"): From 1f2539ba221436a4537360e7a26200956380b80e Mon Sep 17 00:00:00 2001 From: Tassos Manganaris Date: Tue, 3 Nov 2026 13:25:02 -0500 Subject: [PATCH 4/6] Add the TensorRT backend and engine export - A [tensorrt] extra (torch-tensorrt 2.14, Python 3.12+ by a marker, so the core stays on 3.11). - accelerate(field, "tensorrt", precision, batch): one engine per inference function, built on its first call with a dynamic batch, inside the CUDA graphs. fp16 applies to travel_time and pair_travel_time of models with float16-capable inference forms (TD-NTFields); encode_goal and the gradients stay fp32, and fp32 builds disable TF32. On the UR5e field at B = 1024, fp32 is within 1e-6 of the original model on T and 3e-5 on dT/dq, fp16 within 4e-3 on T. - ntfields export: serialized engines with named bindings, the original model's reference inputs and outputs, and a versioned meta.json, for runtimes outside Python. A test runs them through the bare TensorRT runtime. - On the UR5e benchmark (RTX 3090), TensorRT plans MPPI in 6.0-6.8 ms (scenarios) and 16-19 ms (random pairs), against compile's 7.7 and 19, and the gradient planner in 2.2 ms against 1.2: in Python, compile stays the default. Co-Authored-By: Claude Opus 5.5 --- README.md | 14 ++ pyproject.toml | 3 + src/ntfields/accel/__init__.py | 30 ++- src/ntfields/accel/tensorrt.py | 228 ++++++++++++++++++ src/ntfields/cli.py | 26 +- src/ntfields/field.py | 12 +- src/ntfields/inference.py | 8 +- src/ntfields/methods/td_ntfields/inference.py | 1 + tests/unit/test_accel.py | 2 +- tests/unit/test_tensorrt.py | 127 ++++++++++ uv.lock | 118 ++++++++- 11 files changed, 555 insertions(+), 14 deletions(-) create mode 100644 src/ntfields/accel/tensorrt.py create mode 100644 tests/unit/test_tensorrt.py diff --git a/README.md b/README.md index f843163..b9f59b3 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,7 @@ Implemented methods: ```bash uv sync # dev environment (all extras) pip install "ntfields[cli,gt]" # as a library: CLI (tyro) and FMM ground truth (scikit-fmm) +pip install "ntfields[tensorrt]" # TensorRT backend and engine export (Python 3.12+) ``` ## TD-NTFields on a 2D point mass @@ -112,6 +113,19 @@ print(benchmark_ur5e(fast)) On an RTX 3090, MPPI on the UR5e benchmark drops from 41 to 9 ms per plan (scenarios) and from 110 to 20 ms (random pairs), with the same success counts. +With the `[tensorrt]` extra (Python 3.12+), `field.accelerate("tensorrt", precision="fp16")` builds a TensorRT engine +per function on its first call; fp16 applies to the travel times only (TD-NTFields), the goal encoding and gradients +stay fp32. In Python it plans about as fast as `"compile"`; its main use is exporting engines for other runtimes: + +```bash +ntfields export --ckpt runs/.../ckpt.pt --out engines/ur5e --precision fp32 fp16 +``` + +This writes one `_.engine` per inference function (`encode_goal`, `travel_time`, +`pair_travel_time`, `gradient`, `pair_gradient`; `--functions` picks some), reference inputs and outputs of the +original model to check another runtime against, and a `meta.json` with every engine's binding names and shapes. +Engines load only with the TensorRT version they were built with, which `meta.json` records. + To build other arm scenes, use `ArmEnv.ur5e(points=..., spheres=...)`, which accepts point-cloud and sphere obstacles. diff --git a/pyproject.toml b/pyproject.toml index 1cf66f8..ae9dd18 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -14,6 +14,8 @@ dependencies = [ arm = ["pytorch-kinematics>=0.7"] cli = ["tyro>=0.9"] gt = ["scikit-fmm>=2024.5.29"] +# serialized engines load only with the TensorRT they were built with; no wheels for Python 3.11 +tensorrt = ["torch-tensorrt>=2.14,<2.15; python_version >= '3.12'"] [project.scripts] ntfields = "ntfields.cli:main" @@ -26,6 +28,7 @@ dev = [ "pytorch-kinematics>=0.7", "ruff>=0.14", "scikit-fmm>=2024.5.29", + "torch-tensorrt>=2.14,<2.15; python_version >= '3.12'", "tyro>=0.9", ] diff --git a/src/ntfields/accel/__init__.py b/src/ntfields/accel/__init__.py index 7d35ebf..9006c12 100644 --- a/src/ntfields/accel/__init__.py +++ b/src/ntfields/accel/__init__.py @@ -8,6 +8,8 @@ - "eager": the inference form as is (folded weights, forward-mode gradients) - "compile": torch.compile (inductor) of each inference function, specialized per batch size (past torch._dynamo's recompile limit, 8 sizes per function, further sizes run eagerly) +- "tensorrt": a TensorRT engine per inference function, built on its first call with a dynamic batch within `batch`, + in `precision` (see ntfields.accel.tensorrt; needs the [tensorrt] extra) With `cuda_graphs` (on a CUDA field), each function is also replayed from a CUDA graph per batch size, which removes the launch overhead that dominates at planning batch sizes. @@ -29,7 +31,8 @@ from ntfields.plan import PLANNERS, PlanResult from ntfields.problem import Problem -Backend = Literal["eager", "compile"] +Backend = Literal["eager", "compile", "tensorrt"] +Precision = Literal["fp32", "fp16"] # on the UR5e MPPI benchmark, max-autotune builds in 52 s instead of 4 s and plans at most 15% faster; CUDA graphs # come from CudaGraphs, not inductor's modes COMPILE_MODE = "default" @@ -76,19 +79,34 @@ def plan(self, start: Tensor, goal: Tensor, planner: str | None = None) -> PlanR return PLANNERS[planner or self.method.default_planner](self, start, goal) -def accelerate(field: TrainedField, backend: Backend = "compile", cuda_graphs: bool = True) -> AcceleratedField: +def accelerate( + field: TrainedField, + backend: Backend = "compile", + cuda_graphs: bool = True, + precision: Precision = "fp32", + batch: tuple[int, int, int] = (1, 128, 65536), +) -> AcceleratedField: """`field` evaluated through its model's inference form on `backend`; values and gradients match the field's - up to rounding. Gradients the inference form leaves out are absent: asking for them raises.""" + up to rounding (and float16 weights, for the tensorrt backend's fp16). Gradients the inference form leaves out are + absent: asking for them raises. `precision` and `batch` (min, opt, max) are the tensorrt backend's.""" inference = field.model.inference_model(field.problem.env.condition()) if inference is None: raise ValueError(f"{type(field.model).__name__} ({field.method.name}) has no inference model to accelerate") + if backend not in ("eager", "compile", "tensorrt"): + raise ValueError(f"unknown backend {backend!r}; available: eager, compile, tensorrt") + if backend != "tensorrt" and precision != "fp32": + raise ValueError(f"precision {precision!r} needs the tensorrt backend") if backend == "compile": inference = inference.map(lambda fn: torch.compile(fn, mode=COMPILE_MODE, dynamic=False)) - elif backend != "eager": - raise ValueError(f"unknown backend {backend!r}; available: eager, compile") + elif backend == "tensorrt": + if field.device.type != "cuda": + raise ValueError("the tensorrt backend needs a CUDA field") + from ntfields.accel.tensorrt import tensorrt_inference + + inference = tensorrt_inference(inference, precision, batch) if cuda_graphs and field.device.type == "cuda": inference = inference.map(CudaGraphs) return AcceleratedField(field, inference) -__all__ = ["AcceleratedField", "Backend", "CudaGraphs", "accelerate"] +__all__ = ["AcceleratedField", "Backend", "CudaGraphs", "Precision", "accelerate"] diff --git a/src/ntfields/accel/tensorrt.py b/src/ntfields/accel/tensorrt.py new file mode 100644 index 0000000..3fd4f3b --- /dev/null +++ b/src/ntfields/accel/tensorrt.py @@ -0,0 +1,228 @@ +"""TensorRT builds of a model's inference form: in-process engines for `accelerate(field, "tensorrt")`, or serialized +engines with named bindings for other runtimes (`export`). Needs the [tensorrt] extra. + +Every function is built with a dynamic batch B (min, opt, max) and float32 inputs and outputs; the bindings are +BINDINGS, with every input (B, dim) except the encoded goal e_g and encode_goal's q_g, both (1, ·): +- encode_goal: q_g (1, dim) -> e_g (1, n) +- travel_time: q (B, dim), e_g (1, n) -> t (B,) +- pair_travel_time: q_s, q_g (B, dim) -> t (B,) +- gradient: q (B, dim), e_g (1, n) -> t (B,), dt_dq (B, dim) +- pair_gradient: q_s, q_g (B, dim) -> t (B,), dt_dqs (B, dim), dt_dqg (B, dim) + +The precision sets the weights' dtype of travel_time and pair_travel_time. encode_goal and the gradients are always +built in float32: encode_goal runs once per goal, and on the UR5e field an fp16 encoded goal alone puts an error of +8e-3 on dT/dq at B = 1024, where fp32 gives 3e-5 (|dT/dq| ~ 0.3). Float32 builds disable TF32, which on the UR5e +field puts errors of 8e-4 on T and 9e-3 on dT/dq at B = 1024, against 1e-6 and 3e-5 without. fp16 puts 4e-3 on T +(|T| ~ 1.3). +""" + +import copy +import json +from collections.abc import Callable, Sequence +from pathlib import Path +from typing import Any + +try: + import tensorrt + import torch_tensorrt +except ImportError as e: + raise ImportError("the TensorRT backend needs torch-tensorrt: pip install 'ntfields[tensorrt]'") from e +import torch +from torch import Tensor, nn + +from ntfields.accel import Precision +from ntfields.field import TrainedField +from ntfields.inference import Function, InferenceModel, autograd_inference + +FORMAT_VERSION = 1 +Batch = tuple[int, int, int] # (min, opt, max) +BATCH: Batch = (1, 128, 65536) +SETTINGS: dict[str, object] = { + "min_block_size": 1, + "require_full_compilation": True, + "optimization_level": 5, + "disable_tf32": True, +} +BINDINGS: dict[Function, tuple[tuple[str, ...], tuple[str, ...]]] = { + "encode_goal": (("q_g",), ("e_g",)), + "travel_time": (("q", "e_g"), ("t",)), + "pair_travel_time": (("q_s", "q_g"), ("t",)), + "gradient": (("q", "e_g"), ("t", "dt_dq")), + "pair_gradient": (("q_s", "q_g"), ("t", "dt_dqs", "dt_dqg")), +} +FLOAT32_ONLY: tuple[Function, ...] = ("encode_goal", "gradient", "pair_gradient") + + +def tensorrt_inference( + inference: InferenceModel, precision: Precision = "fp32", batch: Batch = BATCH +) -> InferenceModel: + """`inference` with each function built into a TensorRT engine on its first call.""" + _check(inference, precision) + + def engine(name: Function) -> Callable[..., Any]: + return _LazyEngine(getattr(inference, name), name, precision, batch) + + return InferenceModel( + engine("encode_goal"), + engine("travel_time"), + engine("pair_travel_time"), + None if inference.gradient is None else engine("gradient"), + None if inference.pair_gradient is None else engine("pair_gradient"), + inference.float16_weights, + ) + + +def export( + field: TrainedField, + out: Path, + functions: Sequence[Function] | None = None, + precisions: Sequence[Precision] = ("fp32",), + batch: Batch = BATCH, + n_ref: int = 4096, +) -> None: + """Serialized engines of `field`'s inference functions (default: all it has) for other runtimes, loadable with + the same TensorRT version. Writes to `out`: + - _.engine, per precision for travel_time and pair_travel_time, and fp32 for the others + - reference/_.bin: the original model's inputs and outputs on n_ref random configurations + within the env's bounds (raw little-endian float32), to check another runtime against + - meta.json: the format version, dims, batch range, TensorRT version, the env's bounds and every engine's bindings + """ + if field.device.type != "cuda": + raise ValueError("TensorRT engines are built from a CUDA field") + scene = field.problem.env.condition() + inference = field.model.inference_model(scene) + if inference is None: + raise ValueError(f"{type(field.model).__name__} ({field.method.name}) has no inference model to export") + for precision in precisions: + _check(inference, precision) + available: list[Function] = [name for name in BINDINGS if getattr(inference, name) is not None] + names = list(functions) if functions else available + if missing := [name for name in names if name not in available]: + raise ValueError(f"{type(field.model).__name__}'s inference model has no {', '.join(missing)}") + + bounds = field.problem.env.bounds.to(field.device) + gen = torch.Generator(device=field.device).manual_seed(0) + q = bounds[:, 0] + (bounds[:, 1] - bounds[:, 0]) * torch.rand( + n_ref, len(bounds), device=field.device, generator=gen + ) + reference = autograd_inference(field.model, scene) + with torch.no_grad(): + e_g = reference.encode_goal(q[:1]) + args: dict[Function, tuple[Tensor, ...]] = { + "encode_goal": (q[:1],), + "travel_time": (q, e_g), + "pair_travel_time": (q, q.roll(1, dims=0)), + "gradient": (q, e_g), + "pair_gradient": (q, q.roll(1, dims=0)), + } + + out.mkdir(parents=True, exist_ok=True) + (out / "reference").mkdir(exist_ok=True) + engines: dict[str, Any] = {} + for name in names: + inputs, outputs = BINDINGS[name] + with torch.no_grad(): + expected = getattr(reference, name)(*args[name]) + expected = (expected,) if isinstance(expected, Tensor) else expected + for binding, tensor in zip((*inputs, *outputs), (*args[name], *expected), strict=True): + tensor.detach().float().cpu().numpy().tofile(out / "reference" / f"{name}_{binding}.bin") + built = [] + chosen: list[Precision] = ["fp32"] if name in FLOAT32_ONLY else list(dict.fromkeys(precisions)) + for precision in chosen: + module = _module(getattr(inference, name), name, precision) + exported, specs = _export(module, name, args[name], batch) + engine = torch_tensorrt.dynamo.convert_exported_program_to_serialized_trt_engine( + exported, + arg_inputs=specs, # pyright: ignore[reportArgumentType] + arg_input_binding_names=inputs, + # a pytree matching the module's output: one name for a single tensor, a tuple for a tuple + output_binding_names=outputs[0] if len(outputs) == 1 else outputs, + **SETTINGS, # type: ignore[arg-type] + ) + (out / f"{name}_{precision}.engine").write_bytes(engine) + built.append(precision) + engines[name] = { + "precisions": built, + "inputs": {b: _shape(name, b, t) for b, t in zip(inputs, args[name], strict=True)}, + "outputs": {b: _shape(name, b, t) for b, t in zip(outputs, expected, strict=True)}, + } + meta = { + "format_version": FORMAT_VERSION, + "method": field.method.name, + "ckpt": None if field.ckpt_path is None else str(field.ckpt_path.resolve()), + "dim": len(bounds), + "encoded_goal": e_g.shape[1], + "batch": batch, + "tensorrt": tensorrt.__version__, + "bounds": field.problem.env.bounds.tolist(), + "n_ref": n_ref, + "engines": engines, + } + (out / "meta.json").write_text(json.dumps(meta, indent=1)) + + +class _LazyEngine: + """A function built into an in-process TensorRT engine on its first call (from that call's shapes, with the + batch dynamic within `batch`), so functions that are never called are never built.""" + + def __init__(self, fn: Callable[..., Any], name: Function, precision: Precision, batch: Batch) -> None: + self.fn = fn + self.name: Function = name + self.precision: Precision = precision + self.batch = batch + self._engine: Callable[..., Any] | None = None + + def __call__(self, *args: Tensor) -> Any: + if self._engine is None: + module = _module(self.fn, self.name, self.precision) + exported, specs = _export(module, self.name, args, self.batch) + self._engine = torch_tensorrt.dynamo.compile(exported, arg_inputs=specs, **SETTINGS) # type: ignore[arg-type] + return self._engine(*args) + + +def _check(inference: InferenceModel, precision: Precision) -> None: + if precision not in ("fp32", "fp16"): + raise ValueError(f"unknown precision {precision!r}; available: fp32, fp16") + if precision == "fp16" and not inference.float16_weights: + raise ValueError("this inference model does not support float16 weights; use precision='fp32'") + + +def _module(fn: Callable[..., Any], name: Function, precision: Precision) -> nn.Module: + """A copy of the function's module, with float16 weights in fp16 unless the function is FLOAT32_ONLY.""" + if not isinstance(fn, nn.Module): + raise TypeError(f"TensorRT builds nn.Modules; the inference model's {name} is a {type(fn).__name__}") + dtype = torch.float16 if precision == "fp16" and name not in FLOAT32_ONLY else torch.float32 + return copy.deepcopy(fn).to(dtype).eval() + + +def _batched(name: Function, binding: str) -> bool: + return name != "encode_goal" and binding != "e_g" + + +def _shape(name: Function, binding: str, example: Tensor) -> list[int | str]: + return ["B", *example.shape[1:]] if _batched(name, binding) else list(example.shape) + + +def _export( + module: nn.Module, name: Function, args: Sequence[Tensor], batch: Batch +) -> tuple[torch.export.ExportedProgram, list[torch_tensorrt.Input]]: + """torch.export of `module`, dynamic in the batch unless min == max, and the matching TensorRT input specs.""" + batched = [_batched(name, binding) for binding in BINDINGS[name][0]] + example = tuple( + torch.zeros(batch[1], *a.shape[1:], device=a.device) if b else a.float() + for a, b in zip(args, batched, strict=True) + ) + specs = [ + torch_tensorrt.Input( + min_shape=(batch[0], *a.shape[1:]), opt_shape=(batch[1], *a.shape[1:]), max_shape=(batch[2], *a.shape[1:]) + ) + if b + else torch_tensorrt.Input(shape=tuple(a.shape)) + for a, b in zip(example, batched, strict=True) + ] + dynamic = None + if batch[0] != batch[2]: + dim = torch.export.Dim("batch", min=batch[0], max=batch[2]) + dynamic = tuple({0: dim} if b else None for b in batched) + with torch.no_grad(): + return torch.export.export(module, example, dynamic_shapes=dynamic), specs diff --git a/src/ntfields/cli.py b/src/ntfields/cli.py index 09fd374..4239d4c 100644 --- a/src/ntfields/cli.py +++ b/src/ntfields/cli.py @@ -1,6 +1,7 @@ import logging from collections.abc import Sequence from dataclasses import dataclass, field +from pathlib import Path from typing import Annotated, Any, Generic, Literal, TypeVar, Union try: @@ -9,8 +10,10 @@ raise SystemExit("the ntfields CLI needs tyro: pip install 'ntfields[cli]'") from e import ntfields +from ntfields.accel import Precision from ntfields.base import MethodConfig, SpeedModel from ntfields.envs import load_env +from ntfields.inference import Function from ntfields.registry import available, default_config, get_method from ntfields.speed import Clipped, ClippedEased, Smoothstep @@ -41,6 +44,18 @@ class Train(Generic[C]): train: ntfields.TrainConfig = field(default_factory=ntfields.TrainConfig) +@dataclass +class Export: + """Export TensorRT engines of a trained field, for runtimes outside Python (needs the [tensorrt] extra).""" + + ckpt: Path + out: Path + functions: tuple[Function, ...] = () # default: every function the model's inference form has + precision: tuple[Precision, ...] = ("fp32",) # of travel_time and pair_travel_time; the others are fp32 + batch: tuple[int, int, int] = (1, 128, 65536) # min, opt, max + device: str = "cuda" + + def main(args: Sequence[str] | None = None) -> None: logging.basicConfig(level=logging.INFO, format="%(message)s") names = available() @@ -51,9 +66,16 @@ def main(args: Sequence[str] | None = None) -> None: for name, cfg in defaults.items() ) ] - command: Train[Any] = tyro.extras.subcommand_cli_from_dict( - {"train": Train[choice]}, args=args, config=(tyro.conf.CascadeSubcommandArgs,) + command: Train[Any] | Export = tyro.extras.subcommand_cli_from_dict( + {"train": Train[choice], "export": Export}, args=args, config=(tyro.conf.CascadeSubcommandArgs,) ) + if isinstance(command, Export): + from ntfields.accel.tensorrt import export + + field_ = ntfields.load(command.ckpt, device=command.device) + export(field_, command.out, command.functions, command.precision, command.batch) + print(f"engines: {command.out}") + return name = next(n for n, cfg in defaults.items() if type(cfg) is type(command.method)) method = get_method(name)(command.method) problem = ntfields.Problem(load_env(command.env), command.speed.build()) diff --git a/src/ntfields/field.py b/src/ntfields/field.py index 88742b2..df9803f 100644 --- a/src/ntfields/field.py +++ b/src/ntfields/field.py @@ -11,7 +11,7 @@ from ntfields.problem import Problem if TYPE_CHECKING: - from ntfields.accel import AcceleratedField, Backend + from ntfields.accel import AcceleratedField, Backend, Precision class Field(Protocol): @@ -79,8 +79,14 @@ def plan(self, start: Tensor, goal: Tensor, planner: str | None = None) -> PlanR """Single query with `planner` (default: the method's default planner).""" return PLANNERS[planner or self.method.default_planner](self, start, goal) - def accelerate(self, backend: "Backend" = "compile", cuda_graphs: bool = True) -> "AcceleratedField": + def accelerate( + self, + backend: "Backend" = "compile", + cuda_graphs: bool = True, + precision: "Precision" = "fp32", + batch: tuple[int, int, int] = (1, 128, 65536), + ) -> "AcceleratedField": """This field, evaluated through its model's inference form (see `ntfields.accel.accelerate`).""" from ntfields.accel import accelerate - return accelerate(self, backend, cuda_graphs) + return accelerate(self, backend, cuda_graphs, precision, batch) diff --git a/src/ntfields/inference.py b/src/ntfields/inference.py index 16f7a98..73a32ea 100644 --- a/src/ntfields/inference.py +++ b/src/ntfields/inference.py @@ -8,13 +8,15 @@ from collections.abc import Callable from dataclasses import dataclass -from typing import Any +from typing import Any, Literal import torch from torch import Tensor from ntfields.base import SceneCondition, TravelTimeModel +Function = Literal["encode_goal", "travel_time", "pair_travel_time", "gradient", "pair_gradient"] + @dataclass class InferenceModel: @@ -24,6 +26,9 @@ class InferenceModel: gradient: Callable[[Tensor, Tensor], tuple[Tensor, Tensor]] | None = None # q, e_g -> T, ∇_q T (B, dim) # q_s, q_g -> T, ∇_{q_s} T, ∇_{q_g} T pair_gradient: Callable[[Tensor, Tensor], tuple[Tensor, Tensor, Tensor]] | None = None + # the functions are nn.Modules that also run with float16 weights (`.half()`) on float32 inputs, giving float32 + # outputs (what a TensorRT fp16 build needs) + float16_weights: bool = False def map(self, wrap: Callable[[Callable[..., Any]], Callable[..., Any]]) -> "InferenceModel": """The same model with every function it has wrapped (e.g. compiled).""" @@ -33,6 +38,7 @@ def map(self, wrap: Callable[[Callable[..., Any]], Callable[..., Any]]) -> "Infe wrap(self.pair_travel_time), None if self.gradient is None else wrap(self.gradient), None if self.pair_gradient is None else wrap(self.pair_gradient), + self.float16_weights, ) diff --git a/src/ntfields/methods/td_ntfields/inference.py b/src/ntfields/methods/td_ntfields/inference.py index 64430f0..1cd1690 100644 --- a/src/ntfields/methods/td_ntfields/inference.py +++ b/src/ntfields/methods/td_ntfields/inference.py @@ -37,6 +37,7 @@ def fold(model: TDMetricModel) -> InferenceModel: pair_travel_time=PairTravelTime(embed, model), gradient=GoalTravelTimeGrad(embed, model), pair_gradient=PairTravelTimeGrad(embed, model), + float16_weights=True, ) diff --git a/tests/unit/test_accel.py b/tests/unit/test_accel.py index e442828..1b630aa 100644 --- a/tests/unit/test_accel.py +++ b/tests/unit/test_accel.py @@ -105,7 +105,7 @@ def test_accelerate_needs_an_inference_model(): with pytest.raises(ValueError, match="no inference model"): accelerate(TrainedField(method, problem, method.build_model(problem))) with pytest.raises(ValueError, match="unknown backend"): - accelerate(_td_field(), "tensorrt") # pyright: ignore[reportArgumentType] + accelerate(_td_field(), "onnx") # pyright: ignore[reportArgumentType] @requires_cuda diff --git a/tests/unit/test_tensorrt.py b/tests/unit/test_tensorrt.py new file mode 100644 index 0000000..4e9efc6 --- /dev/null +++ b/tests/unit/test_tensorrt.py @@ -0,0 +1,127 @@ +import json +from pathlib import Path + +import numpy as np +import pytest +import torch + +from ntfields import Problem, TrainedField +from ntfields.envs import load_env +from ntfields.inference import autograd_inference +from ntfields.registry import create +from ntfields.speed import Clipped + +pytest.importorskip("torch_tensorrt") +if not torch.cuda.is_available(): + pytest.skip("TensorRT needs CUDA", allow_module_level=True) + +import tensorrt + +from ntfields.accel.tensorrt import export + +BATCH = (1, 64, 256) # a narrow range builds faster + + +def _field(name: str) -> TrainedField: + torch.manual_seed(0) + method = create(name) + problem = Problem(load_env("box2d/empty"), Clipped()) + return TrainedField(method, problem, method.build_model(problem).cuda().eval()) + + +def _queries() -> tuple[torch.Tensor, torch.Tensor]: + gen = torch.Generator(device="cuda").manual_seed(1) + return ( + torch.rand(100, 2, device="cuda", generator=gen) - 0.5, + torch.rand(100, 2, device="cuda", generator=gen) - 0.5, + ) + + +@pytest.mark.parametrize("name", ["td_ntfields", "pntfields"]) +def test_fp32_engines_match_eager(name: str): + field = _field(name) + eager, fast = field.accelerate("eager", cuda_graphs=False), field.accelerate("tensorrt", batch=BATCH) + q, y = _queries() + goal = y[0] + torch.testing.assert_close( + fast.towards(goal).travel_time(q), eager.towards(goal).travel_time(q), rtol=1e-4, atol=1e-5 + ) + torch.testing.assert_close(fast.towards(goal).gradient(q), eager.towards(goal).gradient(q), rtol=1e-4, atol=1e-4) + for ours, expected in zip(fast.gradient(q, y), eager.gradient(q, y), strict=True): + torch.testing.assert_close(ours, expected, rtol=1e-4, atol=1e-4) + + +def test_fp16_builds_only_the_travel_times_in_fp16(): + field = _field("td_ntfields") + eager = field.accelerate("eager", cuda_graphs=False) + fast = field.accelerate("tensorrt", precision="fp16", batch=BATCH) + q, y = _queries() + t, t_ref = fast.towards(y[0]).travel_time(q), eager.towards(y[0]).travel_time(q) + assert (t - t_ref).abs().max() < 1e-2 * t_ref.abs().mean() + # the goal encoding and the gradients are float32 + torch.testing.assert_close(fast.towards(y[0]).gradient(q), eager.towards(y[0]).gradient(q), rtol=1e-4, atol=1e-4) + + +def test_engines_are_built_on_first_call(): + fast = _field("td_ntfields").accelerate("tensorrt", cuda_graphs=False, batch=BATCH) + q, y = _queries() + fast.towards(y[0]).travel_time(q) + built = {name: getattr(fast.inference, name)._engine is not None for name in ("travel_time", "gradient")} + assert built == {"travel_time": True, "gradient": False} + + +def test_fp16_needs_float16_weights(): + with pytest.raises(ValueError, match="float16"): + _field("pntfields").accelerate("tensorrt", precision="fp16") + + +def test_export_rejects_what_the_model_cannot_build(tmp_path: Path): + with pytest.raises(ValueError, match="float16"): + export(_field("pntfields"), tmp_path, precisions=("fp16",)) + with pytest.raises(ValueError, match="no inference model"): + export(_field("euclidean"), tmp_path) + + +def test_exported_engines_reproduce_the_reference(tmp_path: Path): + """The engines, run through the bare TensorRT runtime as another runtime would, on the exported reference.""" + field = _field("td_ntfields") + functions = ("encode_goal", "travel_time", "gradient") + export(field, tmp_path, functions, ("fp32", "fp16"), BATCH, n_ref=200) + meta = json.loads((tmp_path / "meta.json").read_text()) + assert meta["format_version"] == 1 and meta["dim"] == 2 and list(meta["engines"]) == list(functions) + assert meta["engines"]["travel_time"]["precisions"] == ["fp32", "fp16"] + assert meta["engines"]["gradient"]["precisions"] == meta["engines"]["encode_goal"]["precisions"] == ["fp32"] + + # the reference comes from the original model + q = _load(tmp_path, "gradient", "q", ["B", 2], 200) + e_g = _load(tmp_path, "gradient", "e_g", [1, -1], 200) + reference = autograd_inference(field.model, field.problem.env.condition()) + assert reference.gradient is not None + torch.testing.assert_close(_load(tmp_path, "gradient", "dt_dq", ["B", 2], 200), reference.gradient(q, e_g)[1]) + + runtime = tensorrt.Runtime(tensorrt.Logger(tensorrt.Logger.ERROR)) # pyright: ignore[reportAttributeAccessIssue] + for name, spec in meta["engines"].items(): + for precision in spec["precisions"]: + engine = runtime.deserialize_cuda_engine((tmp_path / f"{name}_{precision}.engine").read_bytes()) + context = engine.create_execution_context() + inputs = {b: _load(tmp_path, name, b, s, 200) for b, s in spec["inputs"].items()} + expected = {b: _load(tmp_path, name, b, s, 200) for b, s in spec["outputs"].items()} + outputs = {b: torch.empty_like(t) for b, t in expected.items()} + for b, t in inputs.items(): + context.set_input_shape(b, tuple(t.shape)) + for b, t in {**inputs, **outputs}.items(): + context.set_tensor_address(b, t.data_ptr()) + stream = torch.cuda.Stream() + assert context.execute_async_v3(stream.cuda_stream) + stream.synchronize() + for b, t in outputs.items(): + # relative to the output's scale: the untrained field's gradients reach ~35 within the bounds, where + # float32 rounding alone (the eager inference form's too) is ~1e-3 + tol = 1e-2 if precision == "fp16" else 1e-4 + scale = expected[b].abs().max().item() + torch.testing.assert_close(t, expected[b], rtol=tol, atol=tol * scale, msg=f"{name}_{precision}: {b}") + + +def _load(out: Path, name: str, binding: str, shape: list[int | str], n: int) -> torch.Tensor: + data = np.fromfile(out / "reference" / f"{name}_{binding}.bin", dtype=np.float32) + return torch.from_numpy(data.reshape([n if d == "B" else int(d) for d in shape])).cuda() diff --git a/uv.lock b/uv.lock index 4bf38fd..4717385 100644 --- a/uv.lock +++ b/uv.lock @@ -300,6 +300,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/e7/05/c19819d5e3d95294a6f5947fb9b9629efb316b96de511b418c53d245aae6/cycler-0.12.1-py3-none-any.whl", hash = "sha256:85cef7cff222d8644161529808465972e51340599459b8ac3ccbac5a854e0d30", size = 8321, upload-time = "2023-10-07T05:32:16.783Z" }, ] +[[package]] +name = "dllist" +version = "2.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/b2/ce/dda13123329d55555de67b414206f14f4f80b96cb273ec59d76d5ce6b5c3/dllist-2.0.0.tar.gz", hash = "sha256:7413ba963aaa1b2b6827eadd7908e40e635b19108ab431667485eaf75c492bf4", size = 5369, upload-time = "2025-02-10T15:41:07.637Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7b/07/a212ca4cfe56fa35c8315307e37df218e5946c726a792b5c7a795b245c10/dllist-2.0.0-py3-none-any.whl", hash = "sha256:cd307b1a91bc46fae084f8c817d79be7e34951b149a2fd69004772e03573bfb3", size = 5721, upload-time = "2025-02-10T15:41:06.045Z" }, +] + [[package]] name = "docstring-parser" version = "0.18.0" @@ -998,6 +1007,9 @@ cli = [ gt = [ { name = "scikit-fmm" }, ] +tensorrt = [ + { name = "torch-tensorrt", marker = "python_full_version >= '3.12'" }, +] [package.dev-dependencies] dev = [ @@ -1007,6 +1019,7 @@ dev = [ { name = "pytorch-kinematics" }, { name = "ruff" }, { name = "scikit-fmm" }, + { name = "torch-tensorrt", marker = "python_full_version >= '3.12'" }, { name = "tyro" }, ] @@ -1017,9 +1030,10 @@ requires-dist = [ { name = "pytorch-kinematics", marker = "extra == 'arm'", specifier = ">=0.7" }, { name = "scikit-fmm", marker = "extra == 'gt'", specifier = ">=2024.5.29" }, { name = "torch", specifier = ">=2.4" }, + { name = "torch-tensorrt", marker = "python_full_version >= '3.12' and extra == 'tensorrt'", specifier = ">=2.14,<2.15" }, { name = "tyro", marker = "extra == 'cli'", specifier = ">=0.9" }, ] -provides-extras = ["arm", "cli", "gt"] +provides-extras = ["arm", "cli", "gt", "tensorrt"] [package.metadata.requires-dev] dev = [ @@ -1029,6 +1043,7 @@ dev = [ { name = "pytorch-kinematics", specifier = ">=0.7" }, { name = "ruff", specifier = ">=0.14" }, { name = "scikit-fmm", specifier = ">=2024.5.29" }, + { name = "torch-tensorrt", marker = "python_full_version >= '3.12'", specifier = ">=2.14,<2.15" }, { name = "tyro", specifier = ">=0.9" }, ] @@ -1450,6 +1465,34 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/40/9e/2b38731e0fc536806f16490e1a12d7f0dc2a1235aa8cc07bcc75416a7daa/pluggy-1.7.0-py3-none-any.whl", hash = "sha256:7dd7b0d8832ba3cb632c306926ded123429211b83641b35dc5c41ad2d34f9bec", size = 27082, upload-time = "2026-10-15T09:50:56.808Z" }, ] +[[package]] +name = "psutil" +version = "7.2.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/aa/c6/d1ddf4abb55e93cebc4f2ed8b5d6dbad109ecb8d63748dd2b20ab5e57ebe/psutil-7.2.2.tar.gz", hash = "sha256:0746f5f8d406af344fd547f1c8daa5f5c33dbc293bb8d6a16d80b4bb88f59372", size = 493740, upload-time = "2026-01-28T18:14:54.428Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/51/08/510cbdb69c25a96f4ae523f733cdc963ae654904e8db864c07585ef99875/psutil-7.2.2-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:2edccc433cbfa046b980b0df0171cd25bcaeb3a68fe9022db0979e7aa74a826b", size = 130595, upload-time = "2026-01-28T18:14:57.293Z" }, + { url = "https://files.pythonhosted.org/packages/d6/f5/97baea3fe7a5a9af7436301f85490905379b1c6f2dd51fe3ecf24b4c5fbf/psutil-7.2.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:e78c8603dcd9a04c7364f1a3e670cea95d51ee865e4efb3556a3a63adef958ea", size = 131082, upload-time = "2026-01-28T18:14:59.732Z" }, + { url = "https://files.pythonhosted.org/packages/37/d6/246513fbf9fa174af531f28412297dd05241d97a75911ac8febefa1a53c6/psutil-7.2.2-cp313-cp313t-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1a571f2330c966c62aeda00dd24620425d4b0cc86881c89861fbc04549e5dc63", size = 181476, upload-time = "2026-01-28T18:15:01.884Z" }, + { url = "https://files.pythonhosted.org/packages/b8/b5/9182c9af3836cca61696dabe4fd1304e17bc56cb62f17439e1154f225dd3/psutil-7.2.2-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:917e891983ca3c1887b4ef36447b1e0873e70c933afc831c6b6da078ba474312", size = 184062, upload-time = "2026-01-28T18:15:04.436Z" }, + { url = "https://files.pythonhosted.org/packages/16/ba/0756dca669f5a9300d0cbcbfae9a4c30e446dfc7440ffe43ded5724bfd93/psutil-7.2.2-cp313-cp313t-win_amd64.whl", hash = "sha256:ab486563df44c17f5173621c7b198955bd6b613fb87c71c161f827d3fb149a9b", size = 139893, upload-time = "2026-01-28T18:15:06.378Z" }, + { url = "https://files.pythonhosted.org/packages/1c/61/8fa0e26f33623b49949346de05ec1ddaad02ed8ba64af45f40a147dbfa97/psutil-7.2.2-cp313-cp313t-win_arm64.whl", hash = "sha256:ae0aefdd8796a7737eccea863f80f81e468a1e4cf14d926bd9b6f5f2d5f90ca9", size = 135589, upload-time = "2026-01-28T18:15:08.03Z" }, + { url = "https://files.pythonhosted.org/packages/81/69/ef179ab5ca24f32acc1dac0c247fd6a13b501fd5534dbae0e05a1c48b66d/psutil-7.2.2-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:eed63d3b4d62449571547b60578c5b2c4bcccc5387148db46e0c2313dad0ee00", size = 130664, upload-time = "2026-01-28T18:15:09.469Z" }, + { url = "https://files.pythonhosted.org/packages/7b/64/665248b557a236d3fa9efc378d60d95ef56dd0a490c2cd37dafc7660d4a9/psutil-7.2.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:7b6d09433a10592ce39b13d7be5a54fbac1d1228ed29abc880fb23df7cb694c9", size = 131087, upload-time = "2026-01-28T18:15:11.724Z" }, + { url = "https://files.pythonhosted.org/packages/d5/2e/e6782744700d6759ebce3043dcfa661fb61e2fb752b91cdeae9af12c2178/psutil-7.2.2-cp314-cp314t-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1fa4ecf83bcdf6e6c8f4449aff98eefb5d0604bf88cb883d7da3d8d2d909546a", size = 182383, upload-time = "2026-01-28T18:15:13.445Z" }, + { url = "https://files.pythonhosted.org/packages/57/49/0a41cefd10cb7505cdc04dab3eacf24c0c2cb158a998b8c7b1d27ee2c1f5/psutil-7.2.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e452c464a02e7dc7822a05d25db4cde564444a67e58539a00f929c51eddda0cf", size = 185210, upload-time = "2026-01-28T18:15:16.002Z" }, + { url = "https://files.pythonhosted.org/packages/dd/2c/ff9bfb544f283ba5f83ba725a3c5fec6d6b10b8f27ac1dc641c473dc390d/psutil-7.2.2-cp314-cp314t-win_amd64.whl", hash = "sha256:c7663d4e37f13e884d13994247449e9f8f574bc4655d509c3b95e9ec9e2b9dc1", size = 141228, upload-time = "2026-01-28T18:15:18.385Z" }, + { url = "https://files.pythonhosted.org/packages/f2/fc/f8d9c31db14fcec13748d373e668bc3bed94d9077dbc17fb0eebc073233c/psutil-7.2.2-cp314-cp314t-win_arm64.whl", hash = "sha256:11fe5a4f613759764e79c65cf11ebdf26e33d6dd34336f8a337aa2996d71c841", size = 136284, upload-time = "2026-01-28T18:15:19.912Z" }, + { url = "https://files.pythonhosted.org/packages/e7/36/5ee6e05c9bd427237b11b3937ad82bb8ad2752d72c6969314590dd0c2f6e/psutil-7.2.2-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:ed0cace939114f62738d808fdcecd4c869222507e266e574799e9c0faa17d486", size = 129090, upload-time = "2026-01-28T18:15:22.168Z" }, + { url = "https://files.pythonhosted.org/packages/80/c4/f5af4c1ca8c1eeb2e92ccca14ce8effdeec651d5ab6053c589b074eda6e1/psutil-7.2.2-cp36-abi3-macosx_11_0_arm64.whl", hash = "sha256:1a7b04c10f32cc88ab39cbf606e117fd74721c831c98a27dc04578deb0c16979", size = 129859, upload-time = "2026-01-28T18:15:23.795Z" }, + { url = "https://files.pythonhosted.org/packages/b5/70/5d8df3b09e25bce090399cf48e452d25c935ab72dad19406c77f4e828045/psutil-7.2.2-cp36-abi3-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:076a2d2f923fd4821644f5ba89f059523da90dc9014e85f8e45a5774ca5bc6f9", size = 155560, upload-time = "2026-01-28T18:15:25.976Z" }, + { url = "https://files.pythonhosted.org/packages/63/65/37648c0c158dc222aba51c089eb3bdfa238e621674dc42d48706e639204f/psutil-7.2.2-cp36-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b0726cecd84f9474419d67252add4ac0cd9811b04d61123054b9fb6f57df6e9e", size = 156997, upload-time = "2026-01-28T18:15:27.794Z" }, + { url = "https://files.pythonhosted.org/packages/8e/13/125093eadae863ce03c6ffdbae9929430d116a246ef69866dad94da3bfbc/psutil-7.2.2-cp36-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:fd04ef36b4a6d599bbdb225dd1d3f51e00105f6d48a28f006da7f9822f2606d8", size = 148972, upload-time = "2026-01-28T18:15:29.342Z" }, + { url = "https://files.pythonhosted.org/packages/04/78/0acd37ca84ce3ddffaa92ef0f571e073faa6d8ff1f0559ab1272188ea2be/psutil-7.2.2-cp36-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:b58fabe35e80b264a4e3bb23e6b96f9e45a3df7fb7eed419ac0e5947c61e47cc", size = 148266, upload-time = "2026-01-28T18:15:31.597Z" }, + { url = "https://files.pythonhosted.org/packages/b4/90/e2159492b5426be0c1fef7acba807a03511f97c5f86b3caeda6ad92351a7/psutil-7.2.2-cp37-abi3-win_amd64.whl", hash = "sha256:eb7e81434c8d223ec4a219b5fc1c47d0417b12be7ea866e24fb5ad6e84b3d988", size = 137737, upload-time = "2026-01-28T18:15:33.849Z" }, + { url = "https://files.pythonhosted.org/packages/8c/c7/7bb2e321574b10df20cbde462a94e2b71d05f9bbda251ef27d104668306a/psutil-7.2.2-cp37-abi3-win_arm64.whl", hash = "sha256:8c233660f575a5a89e6d4cb65d9f938126312bca76d8fe087b947b3a1aaac9ee", size = 134617, upload-time = "2026-01-28T18:15:36.514Z" }, +] + [[package]] name = "pygments" version = "2.21.0" @@ -1813,6 +1856,50 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/a2/09/77d55d46fd61b4a135c444fc97158ef34a095e5681d0a6c10b75bf356191/sympy-1.14.0-py3-none-any.whl", hash = "sha256:e091cc3e99d2141a0ba2847328f5479b05d94a6635cb96148ccb3f34671bd8f5", size = 6299353, upload-time = "2025-04-27T18:04:59.103Z" }, ] +[[package]] +name = "tensorrt" +version = "11.1.0.106" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "tensorrt-cu13", marker = "python_full_version >= '3.12'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/0e/af/215ec5632aa002fcc061b18f9e16f718a5e3d51d04712713f0a154e2ba07/tensorrt-11.1.0.106.tar.gz", hash = "sha256:18ee99dc9cb0b2c14d12a68e1a062a79699c05a684ae564390130a1293af059a", size = 16664, upload-time = "2026-06-16T17:26:20.666Z" } + +[[package]] +name = "tensorrt-cu13" +version = "11.1.0.106" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "tensorrt-cu13-bindings", marker = "python_full_version >= '3.12'" }, + { name = "tensorrt-cu13-libs", marker = "python_full_version >= '3.12'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/27/85/b71d95375f67b3b54450aa1b313d099e69987aaf669f47313abe2da49d5d/tensorrt_cu13-11.1.0.106.tar.gz", hash = "sha256:7511c9fa102306c5841a3a261a18a99eab3a5e4bf2e1f64a34f3331475f8e804", size = 17979, upload-time = "2026-06-16T17:26:20.17Z" } + +[[package]] +name = "tensorrt-cu13-bindings" +version = "11.1.0.106" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a4/dc/a57c98cbee7d66af75d8cefa03a7a3262430a20d886781b16c430205b5a9/tensorrt_cu13_bindings-11.1.0.106-cp311-none-manylinux_2_28_x86_64.whl", hash = "sha256:14b6073352fddc66fc859956b86a8e601f9a35ce15e8d331026a7f7947e4e683", size = 1240726, upload-time = "2026-06-16T17:28:07.464Z" }, + { url = "https://files.pythonhosted.org/packages/51/0f/167224b106cea2bd0ce86fe258e567490c04ad15a90b71cad4497a7bb5a5/tensorrt_cu13_bindings-11.1.0.106-cp311-none-manylinux_2_35_aarch64.whl", hash = "sha256:91f8c83f4c8a8e793479d5a619996073d53487dae2ea58cdffbb06744ded8b8f", size = 1227555, upload-time = "2026-06-16T17:28:56.539Z" }, + { url = "https://files.pythonhosted.org/packages/d2/5c/5e332300d111e09dbfbb85e79245716fb7967a834c86062246c362c0fb32/tensorrt_cu13_bindings-11.1.0.106-cp311-none-win_amd64.whl", hash = "sha256:32a961b9c262d2fba49b63433f855ac11921e83495c29c48b57e14ae3280bdb7", size = 886201, upload-time = "2026-06-16T17:29:09.348Z" }, + { url = "https://files.pythonhosted.org/packages/35/db/3d72889bd9ec71e981869bed490742255bc011c9d0094c73867f83776931/tensorrt_cu13_bindings-11.1.0.106-cp312-none-manylinux_2_28_x86_64.whl", hash = "sha256:c02e93843a7bbe0b1cba15fb1fa01424d240f9037326e66d21628a2f1fcf2bf2", size = 1239408, upload-time = "2026-06-16T17:29:20.619Z" }, + { url = "https://files.pythonhosted.org/packages/76/aa/3673ea48abfeb5e75ff7566a89e1dc7b8542dd22711c8ff999cef9faf796/tensorrt_cu13_bindings-11.1.0.106-cp312-none-manylinux_2_35_aarch64.whl", hash = "sha256:2b34be566802da851f9fd6cb86428431e5d14ea527405ee86d0e3d3551ea41d3", size = 1214006, upload-time = "2026-06-16T17:29:42.57Z" }, + { url = "https://files.pythonhosted.org/packages/0b/a8/549fedb7a8c0b10f03f2bf27d2d38fdb8e04b4d713cf3696b79d5f95bc86/tensorrt_cu13_bindings-11.1.0.106-cp312-none-win_amd64.whl", hash = "sha256:42864885cfc87f904ee30eb817a3aa8062608a6b5b0cb3cea72feb557d83c047", size = 885665, upload-time = "2026-06-16T17:30:04.787Z" }, + { url = "https://files.pythonhosted.org/packages/22/8c/cc33158fbf493959df03869082c734fe47c1b35e206206655b5bb4747af6/tensorrt_cu13_bindings-11.1.0.106-cp313-none-manylinux_2_28_x86_64.whl", hash = "sha256:cc0c63553a3015f1a9c6acdf9883ae636dbeb6607ace40041f4bd45487887cca", size = 1239441, upload-time = "2026-06-16T17:30:25.306Z" }, + { url = "https://files.pythonhosted.org/packages/92/7f/8d1d9c555839fce2fd28a2466af56944b386f3b351cc8ff7f2aef13491ce/tensorrt_cu13_bindings-11.1.0.106-cp313-none-manylinux_2_35_aarch64.whl", hash = "sha256:4ebbaa9dc5aab768bef1ff1427a0cf5334bbbb5e3438a156e2ba94e4559c55dc", size = 1214005, upload-time = "2026-06-16T17:30:48.112Z" }, + { url = "https://files.pythonhosted.org/packages/14/33/2591cc62739c035c4475525c7350809333802b8c9dbb80140966365e549a/tensorrt_cu13_bindings-11.1.0.106-cp313-none-win_amd64.whl", hash = "sha256:0c80f92cc018acdc7be99d19caa97fbf7773173ca3f28c1d5d90d943540b8eb0", size = 885570, upload-time = "2026-06-16T17:31:11.129Z" }, + { url = "https://files.pythonhosted.org/packages/38/06/8f7aeac937fc4a9569bfe7cdbe0fbdcaffc99cbfc1207be0a23bf5fe31d5/tensorrt_cu13_bindings-11.1.0.106-cp314-none-manylinux_2_28_x86_64.whl", hash = "sha256:04d1209c30d05c0ee22b31b0c80413ed9b8a3ca8aac3e76f46168dd2f71a88b7", size = 1242358, upload-time = "2026-06-16T17:31:31.811Z" }, + { url = "https://files.pythonhosted.org/packages/36/c1/61f6a6542a90c41c0783e4bbda36691c32f02bf122493b1847129469d8d4/tensorrt_cu13_bindings-11.1.0.106-cp314-none-manylinux_2_35_aarch64.whl", hash = "sha256:cac43a80f8dd65f75f1929f56d5e5607aaf071e5f6d092692dc303cb36382251", size = 1218636, upload-time = "2026-06-16T17:31:58.175Z" }, + { url = "https://files.pythonhosted.org/packages/5f/e7/ca3c8b37ce1a055ed5b97b5d2500545be16057fa78e761bcc77562c3084f/tensorrt_cu13_bindings-11.1.0.106-cp314-none-win_amd64.whl", hash = "sha256:d6e119194831dfe21c6f1c0ed1a58172ba53917cf423b885fc850b5fc67996cb", size = 886842, upload-time = "2026-06-16T17:32:15.854Z" }, +] + +[[package]] +name = "tensorrt-cu13-libs" +version = "11.1.0.106" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/db/f5/babf00011cdb6bbed9743cc885a39399aebc37197dbb6f8bbe7e03dab7fc/tensorrt_cu13_libs-11.1.0.106.tar.gz", hash = "sha256:6d2fe9e98847775122566c58b32691631dff8d8152b724d92447e93a23dfbefb", size = 15747, upload-time = "2026-06-16T19:40:06.288Z" } + [[package]] name = "torch" version = "2.14.1" @@ -1857,6 +1944,35 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/45/05/451a69a4287033d8f106f5c65f92c2c0c37229d81ea101d4b047caf758cc/torch-2.14.1-cp314-cp314t-win_amd64.whl", hash = "sha256:e07306caa1de2a4ac1467e11ecfc92fc44f523dd6a521145039aef46d913963c", size = 124400129, upload-time = "2026-09-30T17:54:12.306Z" }, ] +[[package]] +name = "torch-tensorrt" +version = "2.14.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "dllist", marker = "python_full_version >= '3.12'" }, + { name = "filelock", marker = "python_full_version >= '3.12'" }, + { name = "numpy", version = "2.5.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "packaging", marker = "python_full_version >= '3.12'" }, + { name = "psutil", marker = "python_full_version >= '3.12'" }, + { name = "tensorrt", marker = "python_full_version >= '3.12'" }, + { name = "torch", marker = "python_full_version >= '3.12'" }, + { name = "typing-extensions", marker = "python_full_version >= '3.12'" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/0c/9d/3c92e50602668523679a9f71dd8648fa76adbe70fc192a6d771fdee48af6/torch_tensorrt-2.14.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:d0a5c217670e8ad129cf82d2b2ba930ae50b896310b16fb90d5e1e1f235d5b94", size = 4189500, upload-time = "2026-09-23T17:26:56.78Z" }, + { url = "https://files.pythonhosted.org/packages/f2/19/c6322d714de39948a369efe9d2d9158b03a5f7a82f9a4153a200b58375ec/torch_tensorrt-2.14.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:12756addfacb326d0ff99aa9f35c1534954d73afaea8492472d95b389101d707", size = 4304958, upload-time = "2026-09-23T17:26:59.423Z" }, + { url = "https://files.pythonhosted.org/packages/a0/ce/2053673bade076739ccb8e145e8c71ba432cee42f4fd640c6ff92d0e988c/torch_tensorrt-2.14.0-cp311-cp311-win_amd64.whl", hash = "sha256:e909b56a0036fc1cbef1ef0a6e0502c51626d00c25be1e8829c0c6fba74ec72d", size = 2248474, upload-time = "2026-09-23T17:27:00.963Z" }, + { url = "https://files.pythonhosted.org/packages/d6/ff/b661b1fdf84a71005888413827971ca416bca225ae508b7b0af86d320db5/torch_tensorrt-2.14.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:15c1481225c28e0d3a300b247b4eb10b217765e617f983bf740b870267d63ece", size = 4185307, upload-time = "2026-09-23T17:27:03.809Z" }, + { url = "https://files.pythonhosted.org/packages/15/14/a9700b69d626bf6c087927f27a8992083ce509b02e4dd82596481228787c/torch_tensorrt-2.14.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:2c03ae5f26a513fd5213a4e20d857b3cff13627b916e251987ca213ac873fa57", size = 4306427, upload-time = "2026-09-23T17:27:06.131Z" }, + { url = "https://files.pythonhosted.org/packages/4d/5e/cb00646d4ea6a77d8bc98b26da117794dccd744302077a9bfcabc195eafa/torch_tensorrt-2.14.0-cp312-cp312-win_amd64.whl", hash = "sha256:70683e7ab38b96afd5ecac68c0dc918d54db055920761dd9f4b5697316bd390c", size = 2248586, upload-time = "2026-09-23T17:27:07.771Z" }, + { url = "https://files.pythonhosted.org/packages/7a/6a/e43307494e7b7e3018524906b2000bc3198e060010e34d5dbe1518f49a0e/torch_tensorrt-2.14.0-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:93cf2c4e8e467359a5d66578f07a2eca5e2439ccda53ed39b5cbe546ed156702", size = 4181767, upload-time = "2026-09-23T17:27:09.568Z" }, + { url = "https://files.pythonhosted.org/packages/df/f6/107a081f7dbec9f89cd18ddf14f64d28296cfe6781184e7e9b8a285194e3/torch_tensorrt-2.14.0-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:c0c67f6b62b8028064e2ef54bddc8ea05f1fac9f46c17fb45ad66a078cece5f1", size = 4306823, upload-time = "2026-09-23T17:27:11.284Z" }, + { url = "https://files.pythonhosted.org/packages/69/ca/6307c07774ab00ff8a837e6b66edb8149b1158568ebeca1ce5aebd1a3ce6/torch_tensorrt-2.14.0-cp313-cp313-win_amd64.whl", hash = "sha256:b2adde69b858a3df64d8cb8e908a3dabea0377bc7529b24e8dc5ff54c41652a3", size = 2249131, upload-time = "2026-09-23T17:27:12.819Z" }, + { url = "https://files.pythonhosted.org/packages/4a/82/20805ba658494b89f8cebaa95d25697a09c313bc7c438d43a459bacfb58a/torch_tensorrt-2.14.0-cp314-cp314-manylinux_2_28_aarch64.whl", hash = "sha256:7b33749c8f2918f6c214e57d34851b43077ed12d64aed20e727b8e8c924025e2", size = 4181922, upload-time = "2026-09-23T17:27:14.6Z" }, + { url = "https://files.pythonhosted.org/packages/f7/a1/253f6f2fa451e9ae179289c12bc57b6107dca5a090560b2bc8494b789964/torch_tensorrt-2.14.0-cp314-cp314-manylinux_2_28_x86_64.whl", hash = "sha256:636f7547c07a6ee105b1e9f1135f162b208f7e2e1a48a81b12f5fbf2f12add5f", size = 4306903, upload-time = "2026-09-23T17:27:16.41Z" }, + { url = "https://files.pythonhosted.org/packages/0c/0f/3e48917613f0b6a854578ed845a3a0acc24aaa444d37c41e39ef682f0555/torch_tensorrt-2.14.0-cp314-cp314-win_amd64.whl", hash = "sha256:2e9c47af74cbd0e0dfd22d37903a6dd2ac36b27ea03133f704ddccfc0bfb6965", size = 2249875, upload-time = "2026-09-23T17:27:18.124Z" }, +] + [[package]] name = "triton" version = "3.8.0" From 4bee3006c607d1defa0b8020d7d5635a0a1609e2 Mon Sep 17 00:00:00 2001 From: Tassos Manganaris Date: Mon, 16 Nov 2026 11:06:44 -0500 Subject: [PATCH 5/6] Keep TensorRT out of CPU CI Importing torch_tensorrt on CPU torch raises AssertionError, which pytest.importorskip doesn't catch, so check for CUDA first. Drop torch-tensorrt from the dev group and exclude the tensorrt extra in install-cpu.sh: the runners can't use it, and its NVIDIA stub wheel failed to build on 3.14. Co-Authored-By: Claude Opus 5.5 --- .github/install-cpu.sh | 2 +- pyproject.toml | 1 - tests/unit/test_tensorrt.py | 4 ++-- uv.lock | 2 -- 4 files changed, 3 insertions(+), 6 deletions(-) diff --git a/.github/install-cpu.sh b/.github/install-cpu.sh index d23f6c3..d81fef2 100755 --- a/.github/install-cpu.sh +++ b/.github/install-cpu.sh @@ -2,5 +2,5 @@ # Install the locked environment, but with the CPU build of the locked torch version instead of PyPI's CUDA build. set -euo pipefail torch=$(sed -n '/^name = "torch"$/{n;s/^version = "\(.*\)"$/\1/p;}' uv.lock) -uv sync --locked --all-extras --no-install-package torch +uv sync --locked --all-extras --no-extra tensorrt --no-install-package torch # TensorRT needs CUDA uv pip install "torch==$torch" --index-url https://download.pytorch.org/whl/cpu diff --git a/pyproject.toml b/pyproject.toml index ae9dd18..43fa83d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -28,7 +28,6 @@ dev = [ "pytorch-kinematics>=0.7", "ruff>=0.14", "scikit-fmm>=2024.5.29", - "torch-tensorrt>=2.14,<2.15; python_version >= '3.12'", "tyro>=0.9", ] diff --git a/tests/unit/test_tensorrt.py b/tests/unit/test_tensorrt.py index 4e9efc6..8a71e6c 100644 --- a/tests/unit/test_tensorrt.py +++ b/tests/unit/test_tensorrt.py @@ -11,9 +11,9 @@ from ntfields.registry import create from ntfields.speed import Clipped -pytest.importorskip("torch_tensorrt") -if not torch.cuda.is_available(): +if not torch.cuda.is_available(): # importing torch_tensorrt on CPU torch raises AssertionError, not ImportError pytest.skip("TensorRT needs CUDA", allow_module_level=True) +pytest.importorskip("torch_tensorrt") import tensorrt diff --git a/uv.lock b/uv.lock index 4717385..2518393 100644 --- a/uv.lock +++ b/uv.lock @@ -1019,7 +1019,6 @@ dev = [ { name = "pytorch-kinematics" }, { name = "ruff" }, { name = "scikit-fmm" }, - { name = "torch-tensorrt", marker = "python_full_version >= '3.12'" }, { name = "tyro" }, ] @@ -1043,7 +1042,6 @@ dev = [ { name = "pytorch-kinematics", specifier = ">=0.7" }, { name = "ruff", specifier = ">=0.14" }, { name = "scikit-fmm", specifier = ">=2024.5.29" }, - { name = "torch-tensorrt", marker = "python_full_version >= '3.12'", specifier = ">=2.14,<2.15" }, { name = "tyro", specifier = ">=0.9" }, ] From d832f466430b7bb3a5e5585a3cd78b23d52d387a Mon Sep 17 00:00:00 2001 From: Tassos Manganaris Date: Mon, 16 Nov 2026 11:08:48 -0500 Subject: [PATCH 6/6] Let pyright keep the tensorrt extra Only the test jobs exclude it; pyright needs torch_tensorrt to check ntfields.accel.tensorrt. Co-Authored-By: Claude Opus 5.5 --- .github/install-cpu.sh | 3 ++- .github/workflows/_tests.yml | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/install-cpu.sh b/.github/install-cpu.sh index d81fef2..02cff38 100755 --- a/.github/install-cpu.sh +++ b/.github/install-cpu.sh @@ -1,6 +1,7 @@ #!/usr/bin/env bash # Install the locked environment, but with the CPU build of the locked torch version instead of PyPI's CUDA build. +# Extra arguments go to uv sync (the test jobs pass --no-extra tensorrt). set -euo pipefail torch=$(sed -n '/^name = "torch"$/{n;s/^version = "\(.*\)"$/\1/p;}' uv.lock) -uv sync --locked --all-extras --no-extra tensorrt --no-install-package torch # TensorRT needs CUDA +uv sync --locked --all-extras "$@" --no-install-package torch uv pip install "torch==$torch" --index-url https://download.pytorch.org/whl/cpu diff --git a/.github/workflows/_tests.yml b/.github/workflows/_tests.yml index 0a649d6..7f2c13b 100644 --- a/.github/workflows/_tests.yml +++ b/.github/workflows/_tests.yml @@ -18,6 +18,6 @@ jobs: python-version: ${{ inputs.python }} enable-cache: true - name: Install (CPU torch) - run: .github/install-cpu.sh + run: .github/install-cpu.sh --no-extra tensorrt # TensorRT needs CUDA to import # tests/fidelity and tests/private need local reference checkouts (and some CUDA); run them locally - run: uv run --no-sync pytest tests/unit tests/test_end_to_end.py