Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/install-cpu.sh
Original file line number Diff line number Diff line change
@@ -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-install-package torch
uv sync --locked --all-extras "$@" --no-install-package torch
uv pip install "torch==$torch" --index-url https://download.pytorch.org/whl/cpu
2 changes: 1 addition & 1 deletion .github/workflows/_tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
32 changes: 32 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -55,6 +56,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
Expand Down Expand Up @@ -94,6 +98,34 @@ 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 and P-NTFields):

```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.

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 `<function>_<precision>.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.

Expand Down
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
4 changes: 3 additions & 1 deletion src/ntfields/__init__.py
Original file line number Diff line number Diff line change
@@ -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 Field, GoalField, TrainedField
from ntfields.problem import Problem
from ntfields.registry import available, get_method, register
from ntfields.train import Epochs, TimeLimit
Expand All @@ -11,6 +11,8 @@
__all__ = [
"Batch",
"Epochs",
"Field",
"GoalField",
"LossOut",
"Method",
"MethodConfig",
Expand Down
112 changes: 112 additions & 0 deletions src/ntfields/accel/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
"""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)
- "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.

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", "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"


@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,
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 (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 == "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", "Precision", "accelerate"]
41 changes: 41 additions & 0 deletions src/ntfields/accel/cuda_graphs.py
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading