Skip to content

feat(nav): cvc::nav grid navigation kernels for GRL-SNAM realtime - #198

Merged
transfix merged 35 commits into
masterfrom
feat/cvc-nav-kernels
Aug 20, 2026
Merged

transfix merged 35 commits into
masterfrom
feat/cvc-nav-kernels

Conversation

@transfix

Copy link
Copy Markdown
Owner

What

A new cvc::nav module baking GRL-SNAM's realtime navigation hot path into libcvc — the four kernels that dominate Squad.step plus the footprint SDF, as a bit-identical C++ port of the pure-Python reference (grl_snam/planner.py + sdf_nav.py). This is Stage 3 of GRL-SNAM/docs/PERFORMANCE.md, the step that takes the tick loop from ~0.7 Hz toward the 100-agent @ 30 fps target.

New files under the existing library, exposed through the existing pycvc bindings — no new SWIG module.

  • inc/cvc/nav/grid_nav.h, src/cvc/nav/grid_nav.cpp — edt2_squared, build_sdf, inflate, line_of_sight, nearest_free, astar (8-connected, corner-cut prevention), simplify. Pure STL over raw row-major rasters, zero libcvc dependencies, so the core is threadable across agents (Stage 4).
  • bindings/pycvc/pycvc_nav.i — numpy in via PyArray_FROMANY, out via the existing zero-copy ArrayView typemap; build_sdf returns a stacked (3, H, W) float32; outputs are writable.
  • src/cvc/tests/nav_test.cpp — 17 gtests; CMake + pycvc.i wiring.

Fidelity

Bit-identical is a hard requirement (a fast twin that moves differently is worthless). The guardrails from PERFORMANCE.md are all honored:

  • float64 EDT parabola-envelope arithmetic (a float32 tie-break flips the gradient on medial axes);
  • Python heapq (f, g, node, parent) pop order reproduced by an (f, g, r, c, pk) comparator, so A* returns the byte-identical path among equal-cost ties;
  • libm hypot; the TU is compiled without -ffast-math / -ffp-contract=fast;
  • nearest_free's top-left-biased scan order copied verbatim.

Verification

  • 17/17 nav_test gtests.
  • A 300-grid parity oracle through the built pycvc — pycvc.nav_* vs the Python reference, exact array_equal across sizes 3²–96², random densities, cost fields, unreachable/degenerate cases.
  • Measured 384² speedups: EDT 55×, build_sdf 39×, A* 36×.

Follow-ups (not in this PR)

Stage 4: thread the kernels across agents + stagger sense ticks (≈150 agents at 384²/33 ms); a per-thread A* buffer pool. The GRL-SNAM consumer side (dispatch to pycvc.nav_*, inert until this ships in a published pycvc) is a separate PR.

Bake GRL-SNAM's realtime navigation hot path into libcvc as a new cvc::nav
module (PERFORMANCE.md stage 3), so the tick loop can approach the
100-agent@30fps target. New files under the existing library, exposed through
the existing pycvc bindings — no new SWIG module.

Kernels (inc/cvc/nav/grid_nav.h, src/cvc/nav/grid_nav.cpp): edt2_squared,
build_sdf, inflate, line_of_sight, nearest_free, astar (8-connected,
corner-cut prevention), simplify. Pure STL over raw row-major rasters, so the
core has no libcvc dependency and can be threaded across agents (stage 4).

Bit-identical to the Python reference (grl_snam/planner.py + sdf_nav.py) per
the PERFORMANCE.md fidelity guardrails: float64 EDT envelope arithmetic,
Python heapq (f, g, node, parent) pop order reproduced by an (f, g, r, c, pk)
comparator, libm hypot, and this TU must be built without -ffast-math /
-ffp-contract=fast.

Bindings (bindings/pycvc/pycvc_nav.i): numpy in via PyArray_FROMANY, out via
the existing zero-copy ArrayView typemap; build_sdf returns a stacked (3,H,W)
float32; outputs are writable (GRL-SNAM mutates the fields in place).

Verified: 17 gtests (nav_test) plus a 300-grid parity oracle through the built
pycvc, all exact. Measured 384^2 speedups: EDT 55x, build_sdf 39x, A* 36x.
PERFORMANCE.md stage 4: the agents are independent, so a sense tick's N
replans / SDF rebuilds fan out across cores. Adds a self-contained parallel_for
(std::thread + an atomic work counter, so uneven per-query cost self-balances)
and astar_batch / build_sdf_batch to cvc::nav. Each single-agent kernel already
allocates all working state locally, so the batch is data-race-free and every
result is byte-identical to the equivalent serial call (nav_test asserts this).

pycvc: nav_astar_batch (occ (N,H,W), starts/goals (N,2), cost (N,H,W)|None) ->
list of (Ki,2) paths; nav_build_sdf_batch -> (N,3,H,W). Both release the GIL
across the parallel compute so N agents run truly concurrently.

Measured on a 16-core/32-thread box, 256 agents at 384^2, worst-case full-grid
replans: 2450 ms serial -> 255 ms threaded (9.6x). Real ticks stagger sensing
and skip ~87% of replans (route_valid), so effective per-tick load is far
lower — this is the mechanism for the 100-1000 agent target.
The changed lines wrapped at ~80 cols with Allman braces; the repo's
.clang-format uses 100 cols and attached braces. git-clang-format applied,
verified clean against the merge-base. Whitespace only — nav_test still 20/20.
Replace astar's per-call vector(ncells) allocation + O(ncells) fill of the
came/g_best arrays with a thread_local scratch reused across searches via a
generation stamp: a cell belongs to the current search iff its stamp == gen, so
a new search is just ++gen (O(1)) instead of clearing the arrays. Each worker in
astar_batch reuses one buffer across the queries it runs.

Bit-identical: the values and comparisons are unchanged, only how 'unvisited' /
'g_best = +inf' is represented. Verified by the 400-trial standalone oracle, the
threaded batch==serial check, and the nav_test A* suite.
Add cvc::nav::inflate_batch (parallel_for over N occupancy planes) + the
nav_inflate_batch GIL-releasing binding, mirroring astar_batch / build_sdf_batch.
Each plane is byte-identical to the serial inflate. The 384^2 Squad profiler had
nav_inflate as the top per-tick cost (~19%) because every rebuilding agent
dilated its own belief; a Squad can now batch all of them in one threaded call.

gtest InflateBatchIsByteIdenticalToSerial + the standalone batch==serial check.
Add cvc::nav::neighbors_within_radius — for each of N 2-D points, every other
point within a radius — backed by CGAL's Kd_tree + Fuzzy_sphere (epsilon 0, so
exact: squared distance <= radius^2). libcvc already links CGAL, so no new
dependency; the inexact Simple_cartesian<double> kernel avoids GMP/MPFR. Kept in
its own spatial.cpp so grid_nav.cpp stays dependency-free STL; the header
signature is plain STL (CSR neighbour lists). nav_neighbors binding returns
per-point index arrays, GIL released across the query.

This is the specialized structure for the crowd N-body query (which peers are
within an agent's sensor range) — robust to clustering where a uniform grid
degrades. gtest NeighborsWithinRadiusMatchesBruteForce; verified 0 mismatches vs
brute force at r=3/15/60.
The fourth and last per-agent kernel: cvc::nav::sense_batch, a bit-identical
batched port of grl_snam BeliefGrid.sense. N agents ray-cast the truth grid
(+ optional per-agent peer / shared mover box blockers) and fold the result
into K log-odds belief planes selected per agent by an agent_map, so shared /
clustered / private belief are one data parameter (K = 1 / groups / N).

Threads across PLANES (disjoint memory ⇒ race-free); agents mapped to one plane
fold sequentially in ascending index — exactly what N serial BeliefGrid.sense
calls do (each adds its delta then clamps, the next reads the clamped result),
so it is byte-identical in every mode with parallelism = the plane count.
Load-bearing for that: float64 cos/sin/hypot (system libm, == numpy), std::rint
half-to-even, a march-and-break DDA reproducing the vectorized first-stop /
free / occ masks, and log-odds accumulated f32-store/f64-add of the double
constant (the np.add.at-onto-float32 semantics) free-before-occ. Same
no-fast-math / no-fp-contract TU rule as the other kernels.

pycvc nav_sense_batch mutates the (M,H,W) logodds/last_visible/ever_seen and
(M,) version IN PLACE (borrowed + validated, never PyArray_FROMANY'd — a
coerce-copy would silently swallow the writes), returns flips (N,), releases
the GIL across the compute.

gtests: determinism across thread counts (the race gate), per-plane ==
per-group serial, OOB no-op, peer-box occlude+deposit. The byte-for-byte parity
vs N BeliefGrid.sense lives in GRL-SNAM tests/test_nav_sense_parity.py.
…ical)

sense_batch threaded across belief PLANES, so shared mode (M=1, K=1) ran the
whole cost on one worker — the raycast is ~99% of a sense tick and the fold ~1%.
But the raycast reads only `truth` + the agent's own boxes, so it is order-free:
it can run for every agent in parallel. Only the log-odds fold is order-dependent
(each agent adds its per-cell delta then clamps, and the next reads the clamped
value), so it stays serial per plane in ascending index.

Split accordingly: Phase A raycasts all N agents in parallel into per-agent
(touched cells, free/occ counts); Phase B folds per plane, agents sequential in
ascending index — exactly the order N serial BeliefGrid.sense calls fold in.
Byte-identical: the raycast is plane-independent (same touched cells + counts
whenever it runs) and the fold order is unchanged. The five NavSense gtests
(incl. DeterministicAcrossThreadCounts + Private/Clustered-equal-serial) and the
six test_nav_sense_parity pytests stay green.

Steady-state (384^2, 32c, sense_every=4, nsub=1): shared 144->44 ms @1024,
291->88 ms @2048 (~3.3x); clustered/8 53->42 ms; private (N-EDT-bound) unchanged.
The scaling plateaus ~8 threads (the per-agent stores + the full-grid gen-stamped
scratch are memory-bandwidth-bound) — a windowed scratch + flat arena is the next
lever; noted for follow-up.
Move the std::thread+atomic dynamically-scheduled parallel-for out of
grid_nav.cpp's anonymous namespace into cvc::nav::detail so the torch-free drive
TUs (drive.cpp, later drive.cu's host launcher) share one implementation with
the existing SDF/A*/inflate/sense kernels. Pure refactor — the full nav_test
stays byte-green. Ships via the recursive inc/cvc install. First step of the
cvc::nav torch-free port (docs/CVCNAV_CPP_PORT_ROADMAP.md).
build_sdf's normal pass calls grad1d along each axis; on a single-row or
single-column grid that axis has length 1, where np.gradient itself errors
(edge_order=1 needs >=2 samples). The old code fell through to the i==0 branch
and read a[stride] — one row/column past the buffer — a heap OOB read whose
garbage flipped the unit normals. That is the NavSdf.SignAndScaleAcrossAWall
flake (a 1x5 grid): deterministic compute, but intermittently failing because
the out-of-bounds value depended on heap layout. Return 0 for a degenerate axis
(its gradient is zero). Found under ASan.
cvc::nav::sdf_sample (drive.h/.cpp) is a libtorch-free transcription of
SDFField.sample / BatchedSDFField.sample: torch grid_sample bilinear
(align_corners=True, padding_mode="border") of a [M,3,H,W] field_stack at [N,2]
normalized positions -> phi[N] + unit outward normal[N,2], with a map_id gather
so shared / clustered / private are one sampler (agent i reads plane map_id[i];
null => plane 0). Threaded across agents via detail/parallel.h. Built without
-ffast-math/-ffp-contract so the float32 op order tracks torch; SoA + branch-
light so a drive.cu can share the math and the .cvcnav weights later.

Contract is FLOAT-EQUIVALENT (<=~1 ULP), but matching torch's op order makes it
BIT-EXACT on this platform: the pytest fuzz (GRL-SNAM test_sdf_sample_parity)
reports phi/normal max|Δ|=0 vs torch across shared/private/clustered. pycvc
binding nav_sdf_sample (GIL-released, returns (phi, normal)) + a hand-checkable
NavDrive gtest (constant-field gather + border clamp + renorm + thread
determinism).

Also completes the NavSdf flake fix (8b99910): the wall-center cell sits on the
SDF minimum where the gradient is exactly (0,0), so its normal is zero, not unit
— the assertion now expects 0 there (the old unit-magnitude check only passed by
reading the OOB garbage this fixed).
cvc::nav::coef_mlp (coef_mlp.h/.cpp) is a libtorch-free forward of GRL-SNAM's
CoefMLP: a 5->64->64->3 SiLU MLP whose output is softplus(net + log(expm1(bias)))
-> (alpha, beta, gamma). Weights load from a versioned little-endian `.cvcnav`
blob (magic/format/flags/in/out/num_layers/arch_hash + a dense per-layer stack +
the raw out_bias, with log(expm1) folded once at load); an arch_hash pins the
architecture so a hidden-size change is rejected, not loaded silently wrong.
Per-agent matmul threaded via detail/parallel.h; built without -ffast-math so the
float32 op order tracks torch. pycvc nav_coef_mlp_forward (load + forward, GIL
released) exercises it.

Float-equivalent to CoefMLP.forward at ~1e-6 (max|Δ|=9.5e-7, rtol contract 1e-4)
including a softplus-linear-tail row — see the GRL-SNAM test_coef_mlp_parity +
coef_export.py exporter. The same blob will feed a future CUDA forward. Canonical
install path: $PREFIX/share/cvc/nav/coef_mlp.cvcnav (wired in a later phase).
The two float-equivalent numeric pieces of the drive, in C++:
- cvc::nav::coef_feats: [phi, |goal-o|, gdir_x, gdir_y, gdir.normal] per agent,
  sampling the field (unit normal) at each position (map_id gather).
- cvc::nav::bicycle_rollout: one drive tick of nsub substeps, a faithful
  transcription of sdf_nav.bicycle_rollout (pure-pursuit steering + adaptive
  lookahead, IPC wall barrier, corner / directional-stopping / creep / reverse
  governors, forward-only speed clamp), re-sampling the field each substep for
  the barrier; al/be/ga fixed per agent. drive.cpp refactored to a shared
  sample_unit (phi + unit normal) so the sampler and drive agree by construction.

Built without -ffast-math so the float32 op order tracks torch and the carrot
FSM's later threshold decisions stay stable. Float-equivalent at float32 epsilon:
coef_feats ~1e-7, bicycle o/th/sp ~5e-7 over nsub in {1,2,4}, minclr exact — see
GRL-SNAM test_bicycle_parity (per-substep + a 30-step bounded trajectory +
clustered map_id). SoA + branch-light so a drive.cu shares the math. pycvc
nav_coef_feats / nav_bicycle_rollout (GIL released). Carrot FSM rides with the
SoA sim_world (P6).
cvc::nav::drive_step fuses the whole per-agent drive tick — sample -> coef_feats
-> coef_mlp -> bicycle_rollout(nsub) — into one call given each agent's carrot;
the unit a CUDA kernel mirrors as a single launch. pycvc nav_drive_step (loads a
.cvcnav policy + runs it, GIL released). Float-equivalent to the torch Swarm
drive end-to-end (GRL-SNAM test_drive_step_parity, nsub {1,2}) and deterministic
across thread counts. Assembles the P1-P3 pieces; the carrot FSM rides with the
SoA sim_world (P6).
cvc::nav to_occupancy / composite_occupancy / world_to_cell, a bit-identical port
of grl_snam/belief.py's planning-raster path. This is the one new BIT surface
between the raw belief and the (already bit-identical) EDT/build_sdf, so it is
delicate: the probability is a float32 sigmoid (1/(1+expf(-lo))) compared to the
threshold exactly as numpy does (the float32 p widened to double). Verified
byte-identical to BeliefGrid.to_occupancy / composite_occupancy on a realistically
evolved belief for both unknown-space policies (0 cells flipped) AND that the
resulting occupancy feeds a byte-identical build_sdf field. pycvc
nav_composite_occupancy (GIL released). Completes the map path for the pure-C++
sim_world (P6).
cvc::nav::carrot_step: the steering-carrot state machine (swarm.py._plan_carrot)
as per-agent SoA updates — stall accounting (closing test + the 39-tick
displacement ring), seek->wall entry, carrot placement, wall exit, parked brake.
Validated vs _plan_carrot: the discrete state (stall/mode/turn/we_valid/
hist_count) is EXACT, the carrot float-equivalent (~5e-7).

cvc::nav::sim_world: the owning aggregate that runs the whole shared-belief swarm
with zero torch and zero Python — it holds the belief planes, the SDF field, the
coef_mlp policy and the SoA agent columns, and step() ties together the ported
pieces (sense_batch -> composite_occupancy -> build_sdf -> carrot_step ->
drive_step -> reached/park). Live retarget / add_obstacle for the threading
layer. This is what a renderer / game engine embeds. pycvc exposes it as an
opaque capsule handle (nav_sim_world_create/step/snapshot/retarget) + nav_carrot_step.

Behavioral gate (GRL-SNAM test_sim_world_parity): from an identical init + the
same .cvcnav policy, the C++ trajectories track the torch Swarm (frozen sense:
sub-5cm over 80 ticks, IDENTICAL reach-set) and the live sense/rebuild path runs
and progresses. Shared belief (M=1), the thousands-of-agents deployment path.
cvc::nav::sim_thread advances a sim_world on a dedicated std::thread at a fixed
rate and publishes an immutable Snapshot each tick by an atomic shared_ptr swap
(a renderer reads it lock-free and never blocks the sim); live-scene edits flow
back through a command queue drained top-of-tick. Because the worker runs ONLY
cvc::nav kernels it never touches the GIL, so it advances genuinely concurrently
with Python — even a tight Python read loop can't starve it (the failure mode of
the Python SimThread). pycvc exposes it as a capsule that keeps its sim_world
alive and joins the worker on destroy (create/start/stop/read/retarget/pause/
set_rate/ticks). GRL-SNAM test_sim_thread: concurrent non-tearing reads, a live
retarget the agent reacts to, pause/resume, clean stop.
The GPU deployment path for the drive — a device transcription of drive.cpp
(bilinear sample + coef_mlp + bicycle rollout, one thread per agent) plus a
sample kernel. cvc::nav::drive_step_cuda / sdf_sample_cuda; coef_mlp::export_flat
uploads the policy weights; pycvc nav_drive_step_cuda (present always, raises if
built without CUDA).

Fixes the verified prerequisite bug: SetupCUDA.cmake applied --use_fast_math
TARGET-WIDE, which maps expf/sinf to approximate intrinsics via __CUDA_FAST_MATH__
(unfixable per source) and would silently break float-equivalence for any nav .cu.
Now voxels_kernels.cu opts into fast-math per source (it has no fidelity
contract); nav/drive.cu is built precise (-fmad=false, --prec-div/sqrt=true,
--ftz=false).

Validated on a GTX 1650 (sm_75): the GPU drive is float-equivalent to the torch
reference AND the CPU drive at ~5e-7 over nsub {1,2} (GRL-SNAM
test_cuda_drive_parity, auto-skipped without a device). Manual bilinear (hardware
texture filtering's 9-bit weights are ~1e-3, outside the contract). Per-call
alloc/copy launcher; the fused device-resident sim_world.cu + throughput tuning
is the next step on a bigger GPU box.
…ts path, example

Make the whole swarm trivially runnable from pure C++ (the path to dropping
navigating agents into a cvcGL scene / lsystem_forest), no Python, no libtorch,
no weights file required to get started:

- coef_mlp::default_biased(): the shipped 5->64->64->3 topology with zero linear
  weights, so net(feat)==0 and the coefficients are the constant CoefMLP bias
  basin (alpha,beta,gamma)=(1,3,4) — a working default policy with no .cvcnav.
- sim_world::from_occupancy(cfg, occ, model, n, seed): build a swarm from one
  occupancy grid, auto-scattering starts/goals on free cells — a scene app wires
  agents in a few lines and reads sim_world::snapshot() into GeometryNodes.
- coef_mlp::default_weights_path(): resolve a trained policy in order — the
  CVC_NAV_WEIGHTS env var, the baked $PREFIX/share/cvc/nav/coef_mlp.cvcnav
  (CVC_NAV_DATADIR in config.h), then a path relative to the loaded libcvc (for a
  relocated / cvcpkg install, via dladdr). Optional install(FILES) of a supplied
  CVC_NAV_WEIGHTS_FILE to the canonical location.
- examples/nav_swarm_demo.cpp (CVC_BUILD_NAV_EXAMPLE): the copy-paste template;
  compiles standalone against -lcvc and runs 2000 agents with zero deps.

NavSimWorld gtests prove the pure-C++ runtime end-to-end (agents move + reach,
finite poses; default_biased gives the basis coefficients). Full nav_test green,
0/6 flake (the grad1d length-1-axis OOB fix, 8b99910, is in).
share/cvc/nav/coef_mlp.cvcnav — a deterministic reference navigation policy (the
bias-basin CoefMLP every parity test validates; ~57% reach on the city story).
A default build installs it to $PREFIX/share/cvc/nav/coef_mlp.cvcnav (the default
CVC_NAV_WEIGHTS_FILE), so a pure-C++ host resolves it via
coef_mlp::default_weights_path() with zero configuration; override with a trained
policy via -DCVC_NAV_WEIGHTS_FILE=... (retrain via grl_snam/tools/coef_train.py).

nav_swarm_demo now prefers the installed policy and falls back to
coef_mlp::default_biased(). A NavSimWorld gtest loads the shipped file and drives
a swarm with it (guarded by CVC_NAV_SHIPPED_WEIGHTS).
The GPU twin of sim_world for the static-map shared-belief deployment path
(drop thousands of navigating agents into a cvcGL / lsystem_forest scene). Where
sim_world's drive_step_cuda re-uploads the field + weights + agent columns every
call, sim_world_cuda keeps ALL of it resident on the GPU across ticks — the
shared SDF field, the .cvcnav policy weights, and every SoA agent column (pose
AND the full carrot-FSM state). step() launches sample -> carrot FSM -> fused
drive -> reached/park with zero host round-trips; only snapshot() copies
device->host, and only the pose-sized columns a renderer needs.

Adds two kernels to drive.cu (reusing its device math and the same .cvcnav
weights): a per-agent transcription of carrot_step, and the reached/park loop,
plus a 1-thread retarget kernel. The field is built once on the host (one EDT)
and uploaded; after that the world never leaves the GPU. No atomics — fully
deterministic. Requires CVC_ENABLE_CUDA + a device (guard with available()).

Refactors the free-cell agent scatter out of sim_world::from_occupancy into a
shared static scatter_free() so the CPU and CUDA factories scatter identically.

Validated on a GTX 1650 (NavSimWorldCuda.TracesCpuSimWorld) against the CPU
sim_world with an identical scene + identical agents: after ONE tick GPU == CPU
to the bit (systematic-bug gate), the median agent stays bit-tight over a
250-tick roll, the bulk stays sub-half-metre, and the reach count matches. The
few agents that peel off far past that horizon straddle an FSM threshold where a
~1e-6 float difference flips a branch onto a different-but-valid path — the
documented mode-flip chaos, gated by horizon, not drift. 32 gtest green.
The training twin of the inference port: coef_train.py brought into cvc::nav as
pure C++, no libtorch and no Python. There is no dataset and no labels — the
gradient comes from a differentiable rollout over a scene's SDF ("did the agent
reach its goal without hitting a wall") straight into the coefficient net.

- Differentiable forward: coef_feats -> CoefMLP -> the point-mass sdf_rollout
  surrogate (sdf_nav.py), the smooth training proxy for the deployment bicycle.
- Reverse-mode gradient by hand-written adjoints: the bilinear-sample position
  VJP, the MLP backward (Linear/SiLU/softplus), the IPC-barrier derivative and
  the rollout chain, with truncated BPTT (detach every `window`).
- Adam + global-norm gradient clip; the whole training loop in C++.
- Scene source: city_scene() ports the Python STORIES["city"] (city_blocks rects
  -> shrunk -> rasterize), occupancy_scene() takes ANY caller occupancy (e.g. a
  rasterized lsystem_forest); both draw reachable start/goal pairs from the
  largest 8-connected free component (flood fill).
- coef_mlp::from_layers bakes a frozen policy from the trained params;
  coef_mlp::save writes the versioned .cvcnav (byte-identical to
  coef_export.write_coef_mlp), so a policy trained in pure C++ persists to the
  same file torch / the CPU / the CUDA forward all read.

Correctness is torch-INDEPENDENT: a finite-difference GRADCHECK
(nav_coef_train_test) confirms the analytic gradient matches numerically —
gradient-direction dir_rel 2.2e-4, per-param worst 2.8e-3. End-to-end, a policy
trained on the city scene DRIVES the bicycle sim_world and improves reach
62.1% -> 64.8% (above the 62.9% hand-tuned basin).

Note: this is a REFINEMENT of the (1,3,4) basin the net is centered on, not
from-scratch learning — the surrogate has no turning limits, so the default lr
is 2e-4 (coef_train.py's never-run 1e-3 drives the goal-spring past what the
bicycle can execute and collapses reach to ~0). Weights export unchanged. 5 new
gtests; 32 nav_test still green.
The GPU trainer: one thread per agent runs the differentiable window forward +
hand-written backward (a device transcription of coef_train.cpp), accumulating
the per-param gradient with atomicAdd. Checkpoint/recompute keeps storage tiny —
only (o_t, v_t) per step is saved; the MLP and samples are recomputed in the
backward (the net is tiny). Built without --use_fast_math (-fmad=false, IEEE
div/sqrt) so the device forward tracks the CPU trainer.

train_coef_mlp_cuda runs the whole self-supervised loop with the loss+gradient
on the GPU and Adam / init / scene sampling / .cvcnav bake on the host (reusing
coef_trainer). loss_and_grad_cuda is exposed for the parity test and drives the
loop. train_cuda_available() gates it.

Validated on a GTX 1650 (nav_coef_train_test, CVC_ENABLE_CUDA): the CUDA loss and
gradient match the gradcheck-proven CPU trainer on the same params/scene/batch to
4.2e-7 (cosine 1.000000, identical loss) — the device backward reproduces the CPU
adjoints essentially bit-exact — and a policy trained end-to-end ON THE GPU drives
the bicycle sim_world at ~65% reach (basin 62.9%). 7 coef_train gtests green.
A runnable capstone for the torch-free trainer: trains the CoefMLP on a scene
(the Python "city" by default; swap in occupancy_scene() for any rasterized map)
and writes the versioned .cvcnav the pure-C++ swarm drives with — using the CUDA
trainer when the build has CUDA + a device, else the CPU trainer. This is the
retrain-on-the-deployment-box path: no Python, no libtorch anywhere.

Behind -DCVC_BUILD_NAV_EXAMPLE=ON (with nav_swarm_demo). Verified: trains on the
GPU and writes a valid .cvcnav.
train_coef_mlp_cuda now keeps the field, params, Adam moments (m, u) and all
per-window scratch resident on the GPU across the ENTIRE run. Per outer step only
the fresh agent batch (o, goal) is uploaded; each window runs the forward/backward
kernel, then an in-place device Adam (adam_kernel) driven by a single-float D2H of
the grad-clip norm (grad_sqnorm_kernel) — the gradient itself never leaves the
device. Pose continuation is a pointer swap. Only the final trained params come
back to bake the coef_mlp. The per-call loss_and_grad_cuda (re-uploads each
window) stays for the CUDA-vs-CPU gradient parity test.

Verified on GTX 1650: the resident loop trains a policy that drives the bicycle
sim_world at ~65% reach (basin 62.9%); the per-call gradient still matches the CPU
trainer to 4.3e-7.
Adds train_config::rollout {surrogate, bicycle} — train the CoefMLP by
differentiating EITHER the smooth point-mass surrogate (sdf_rollout, the default)
OR the full deployment kinematic-bicycle integrator. Everything but the
integrator (coef_feats -> CoefMLP -> loss) is identical.

The differentiable primitives — the bilinear-sample position VJP, the IPC-barrier
derivative, and BOTH rollout steps' forward + reverse-mode adjoints — now live in
detail/diff_rollout.h as __host__ __device__ (CVC_HD), shared verbatim by the CPU
trainer (coef_train.cpp) and the CUDA kernel (coef_train.cu). So the bicycle
adjoint (a ~250-line reverse pass through atan2/tan/tanh + the corner/stop/creep/
reverse governors) is written ONCE and both paths inherit it correct — the CPU
finite-difference gradcheck validates the device backward by construction.

coef_train.cu is refactored onto the header (deleting its duplicated sampler) and
train_kernel gains the bicycle branch, so the device-resident loop trains either
integrator on the GPU.

Validated (nav_coef_train_test, GTX 1650): surrogate gradcheck dir_rel 2.2e-4;
bicycle gradcheck dir_rel 1.7e-2 (the branchy integrator is looser; a standalone
per-op FD pins bike_step_bwd to p99 1.4e-2); CUDA bicycle loss+grad match the CPU
to 1.4e-7 (cos 1.000000). The surrogate refines the basin and improves reach
(~62->65%); the bicycle chases the goal directly (the carrot FSM is a
non-differentiable deployment wrapper) so it holds the tuned basin rather than
beating it, and its governor landscape needs a much smaller lr (~1e-5 vs 2e-4) —
so the surrogate stays the recommended default. 10 coef_train gtests green.

Bumps the libcvc project version 3.2.4 -> 3.3.0 (the torch-free trainer feature).
Documents the self-supervised policy trainer added in 3.3.0: quick start (CPU +
device-resident CUDA), the surrogate-vs-bicycle rollout switch and when to use
each, the scene source (city_scene / occupancy_scene), .cvcnav export, the
hyperparameters, how the hand-written differentiable rollout works, and the
finite-difference gradcheck that validates it. Linked from the README doc index.
Exposes cvc::nav::coef_train to Python: nav_train_coef_mlp(occ, geometry, veh,
hyperparams, rollout, use_cuda, out_path) builds an occupancy_scene, runs the
CPU or device-resident CUDA trainer (guarded by CVC_USING_CUDA + a device), and
writes the versioned .cvcnav. The CPU path releases the GIL during training.
This is the native trainer GRL-SNAM dispatches to behind GRL_SNAM_TRAIN_BACKEND;
the torch coef_train.py stays canonical.
… audit)

Two correctness/safety fixes surfaced by a pre-demo readiness audit:

- CoefMLP width guard. build_from_bytes / from_layers now reject any layer wider
  than coef_mlp::kMaxWidth (256, the CPU forward's stack-array cap) instead of
  silently overflowing; drive_step_cuda rejects any layer wider than 64 (the
  device d_mlp's a[64]/b[64] cap) before launching. A hidden>64 policy previously
  loaded + ran on CPU but corrupted device memory on the GPU — a config-dependent
  memory-safety bug that widening the net for a demo would trigger. New gtest
  NavSimWorld.CoefMlpRejectsTooWideLayer.
- add_obstacle: documented that it stamps the DYNAMIC layer, which is only
  composited on a sense tick — so it is inert under freeze_sense=true (the static
  deployment path); the (centered-blob) footprint faithfully matches the Python
  Swarm.add_obstacle. No behavior change, just an honest header note.

32 nav_test + 10 coef_train gtests green.
The pre-demo audit flagged two shipped-but-untested paths that a realtime demo
relies on:

- NavSimThread.RunsLockFreeAndTakesCommands — the off-render-thread runtime: a
  worker advances a sim_world at a fixed rate and publishes immutable snapshots;
  the test spins thousands of lock-free read()s (each a whole, internally
  consistent frame — never torn), fires a queued retarget, and asserts pause
  halts progress + resume restarts it + stop() is idempotent. Stable over repeated
  runs.
- NavSimWorld.LiveSensingRebuildsTheField — the freeze_sense=false path every
  other sim_world test skips: a prior belief with a phantom wall the world lacks,
  agents that sense it away, and an assertion that the belief update
  re-composites the occupancy and REBUILDS the field (field_version increases)
  while agents drive.

35 nav_test green.
Extends the pure-C++ sim_world beyond shared belief: it now holds M belief planes
(shared M=1 / clustered K groups / private M=N), each agent sensing into and
sampling from its own plane via a per-agent map_id — the C++ counterpart of the
Python Swarm's belief_mode, and what the fog-of-war / city-squad demos need. The
kernels already supported it (sense_batch takes K planes + agent_map; sdf_sample
and drive_step take map_id), so the change is the M-plane belief/occupancy/SDF
bookkeeping + per-plane rebuild here.

- ctor gains (map_id, n_planes); from_occupancy gains a belief_mode {shared,
  clustered, private} (+ clusters), with k-means-lite cluster assignment.
- log-odds / last_visible / ever_seen / version / dyn_stamp / occ / field are now
  [M,...]; step() senses all agents into their planes in one sense_batch(K=M) and
  rebuilds only the planes whose surface changed; add_obstacle marks every plane.

Tests: PrivateBelief/ClusteredBelief MatchesSharedWhenPlanesIdentical (with frozen
identical planes, grouped drives BIT-IDENTICALLY to shared — validates the M-plane
sample/drive wiring), PrivateBeliefPlanesAreIsolated (a phantom wall one agent
senses away diverges ITS plane only — proves per-agent isolation), and
FromOccupancyBeliefModesDrive (the factory wires each mode + drives). The last
caught a densify bug (clustered plane count was 1+K, map_id mislabeled 1..K) —
fixed. 39 nav_test + 10 coef_train green.
The device-resident GPU twin was shared-belief only (one field plane). Give
it the same M-plane grouped/private belief the CPU sim_world has, via a
per-agent map_id: the device field becomes [M,3,H,W], every agent samples/drives
on plane map_id[i], and the ctor gains (map_id, n_planes) with `occ` laid out as
[n_planes*rows*cols] (one known map per plane). map_id == nullptr keeps the
shared single-map path unchanged.

- d_sample_unit / d_bicycle take a `plane` and offset into the [M,3,H,W] block.
- sample_kernel / drive_kernel take the per-agent map_id (null -> plane 0), so
  the transient sdf_sample_cuda / drive_step_cuda paths are byte-identical.
- ctor builds one EDT per plane on the host and uploads d_field + d_map_id;
  planes() reports M. from_occupancy stays the shared single-map factory
  (grouped needs genuinely different per-plane maps -> use the ctor).

This is the GPU analog of CPU sim_world's grouped belief under freeze_sense, but
capable of genuinely different per-group maps (no on-device sensing; live
fog-of-war stays on the CPU sim_world).

Tests (nav_test, skip without a device):
- GroupedIdenticalPlanesMatchShared: M=3 identical planes trace the shared M=1
  world bit-for-bit (maxdiff==0) — the plane-offset math gate.
- GroupedDifferentPlanesRouteApart: two agents, same start+goal, different
  map_id; plane 0 walled / plane 1 open -> open agent ends 3.8 vs 201 from goal,
  197 apart — per-agent belief selects its own map.
…ORING.md

The README had drifted badly: version history stopped at 3.1.0 (we are at
3.3.0), the whole cvc::nav / cvcGL / world_clock / image / model / state_exec
subsystems were undocumented, and the test counts were wildly stale and
internally inconsistent (badge 546, body 577, true total 2,240 across 86 suites,
with a dozen off-by-N per-suite claims).

- Overview + Features: add cvc::nav reactive swarm navigation, the cvcGL scene
  graph + cvc::image / cvc::model assets, and cvc::world_clock.
- Core APIs: new "Reactive Swarm Navigation" section with a from_occupancy ->
  step -> snapshot example (verified against the headers) + trainer pointer.
- Testing: replace the stale/contradictory counts with the verified 2,240 cases
  across 86 suites and a families breakdown; soften unverifiable per-file
  coverage figures to a pointer to docs/TESTING.md; fix the CUDA-count and
  "Known Issues" stray stale lines.
- Supported File Formats: add assimp mesh formats (OBJ/glTF/GLB/FBX/DAE/PLY) and
  cvc::image formats (PNG/JPEG/WebP); drop the stale "OBJ via SDF (experimental)".
- Project Structure: refresh the module tree; Version History: add 3.1.1..3.3.0;
  fix the Table of Contents "Usage Example" -> "Core APIs" anchor.

Remove PROCEDURAL_GEOMETRY_REFACTORING.md: a one-off refactor work-log (stale
absolute paths, a finished volrover3 dialog change), referenced nowhere.
…ows CI)

nav_test.cpp and nav_coef_train_test.cpp use std::sort/copy/fill/max but relied
on transitive includes; libstdc++/libc++ pull <algorithm> in, MSVC does not.
It only surfaced in the CUDA-enabled Windows build (CI/CD package-windows) —
the whole NavSimWorldCuda block is under #ifdef CVC_ENABLE_CUDA, so the
no-CUDA recipe-first Windows build never compiled the offending std::sort and
stayed green. Add the explicit <algorithm> include to both test TUs.

  nav_test.cpp(1153): error C2039/C3861: 'sort' is not a member of 'std'
The PRE_TEST + 120s discovery-timeout override was guarded by if(APPLE); Windows
kept POST_BUILD discovery with the 5s default. This PR's added CUDA translation
units (drive.cu / coef_train.cu) saturate the Windows runner during build-time
test discovery, so unrelated state-test exes (state_write_policy_test,
state_brick_manifest_test) finish listing their cases but are killed before they
exit within 5s -> "Process terminated due to timeout" fails the package-windows
build. Mirror the macOS remedy on Windows but keep POST_BUILD (Windows relies on
its build-time DLL-PATH setup for discovery) and just raise the timeout to 120s.

Green on 04fcbda (pre-CUDA-additions); the exes exit promptly on an unloaded
runner, so this is a load-induced timeout, not a per-test hang.
@transfix
transfix merged commit 59e3f69 into master Aug 20, 2026
12 checks passed
@transfix
transfix deleted the feat/cvc-nav-kernels branch August 20, 2026 07:02
transfix added a commit that referenced this pull request Aug 21, 2026
The cvcgl-examples recipe has been in the tree since #204 but was never
wired into publish-cvcpkg.yml, so the example commands never reached the
catalog: the workflow only knew about libcvc, libcvc-cuda, cvcgl and the
pycvc columns.

Add a linux release step alongside cvcgl, plus a cvcgl_examples output on
compute-revisions so the revision is chosen the same way as every other
package (`cvcpkg next-revision`).  Nothing links the examples, so unlike
cvcgl this runs only in the pyver-311 column rather than in every column.

The step invokes the recipe's own build.sh instead of repeating its cmake
in YAML.  Duplicating it would leave two sources of truth for flags like
the -DCGAL_Boost_USE_STATIC_LIBS=OFF workaround (#207) -- and a recipe
drifting from what CI actually runs is exactly how one passes `cvcpkg
validate` while being broken.  build.sh takes its prefixes from a single
CVC_DEPS_PREFIX, and CMAKE_PREFIX_PATH is a list, so the three prefixes
this job spreads its dependencies across are handed over as one
semicolon-separated value (verified: cvc + Boost both resolve from a
multi-prefix list passed through build.sh's quoting).

The nav demos need cvc::nav, which exists only in libcvc >= the nav
kernels (#198) -- newer than the published bundle.  That resolves itself
here because the job builds and installs libcvc from this tree into
$STAGE before this step runs; publishing the examples from anywhere else
needs a libcvc republish first.

The recipe's `platform: wasm` entry (the browser build under
share/cvcgl-examples/web/) is deliberately NOT wired up: it needs emsdk,
the wasm dependency closure, and a rendering-enabled wasm vtk on the
catalog.  Left as a TODO in the step.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant