Skip to content

nav: an external force in the material training rollouts (material_ext) - #734

Merged
transfix merged 5 commits into
masterfrom
feat/material-ext
Oct 20, 2026
Merged

transfix merged 5 commits into
masterfrom
feat/material-ext

Conversation

@transfix

@transfix transfix commented Oct 19, 2026 •

Copy link
Copy Markdown
Owner

The deployed drive steers the material policy and an external force together: drive_step_material_ext with an ext_force, a hook through which a caller supplies its own force. The material trainer, though, trained the material heads with no such force present. This PR adds that force to the material training rollouts, so the heads learn in the presence of the force they face at deploy.

material_ext (material.h)

It joins each rollout as the deployed drive adds ext_force:

rollout where F_ext goes
surrogate (integrate_surrogate_material) ftot + F_ext. A point mass, so steer has nothing to act on
bicycle / dynamic (integrate_bicycle_material, integrate_dynamic_material) added last to F = F_bar + F_goal + F_mat. With steer, also to the steering bias (F_rep + F_mat + F_ext) . left
  • Null is unchanged. A null channel gives the rollout without one, bit for bit, because the adds are conditional.
  • Mass. The bicycle divides by mass and the deployed drive does not, so the two agree at the default mass = 1.

Sources. Exactly one of:

  • Force patches: K per agent, (B,K,2,Hp,Wp), on the rollout patch's grid and sampled bilinearly at the current position. patch_of_step picks the patch per step.
    • This form suits a force that depends only on the agent's own position, such as fixed sources switching on and off.
    • J is the patch's own gradient.
  • Per-step values F, with an optional J.
  • A C++ callback with hold, the shape of bike_ext_fn.

The VJPs.

  • They chain J^T dL/dF_ext into the position adjoint. A held window's sum goes in at the step it was sampled.
  • They return dL/dF_ext per step (g_fext).
  • detail/material_ext.h holds the per-step sampler and the reverse's window.

The trainer.

  • material_batch::ext carries the force through material_loss and material_loss_and_grad.
  • L_multi leaves the force out, as it leaves out the material forces.
  • With a force, the surrogate runs on the CPU. There is no device twin of the channel yet.

pycvc. Optional trailing arguments ext_patch / ext_patch_of_step / ext_F / ext_J / ext_steer on:

  • nav_integrate_surrogate_material;
  • nav_integrate_bicycle_material and its _vjp (want_g_fext=1 returns g_fext);
  • nav_material_trainer_step and _loss.

They are all checked with the GIL held.

Verified locally (Windows, the cvcpkg prefix)

check result
Null or zero force, all three integrators bit-identical forward and reverse
Coefficient gradients through a scheduled force patch vs finite differences worst relative 2.2e-3 / 1.1e-2 / 1.7e-2 (surrogate / bicycle / dynamic)
The same through a callback held for 2 steps 9.2e-4 / 1.6e-2
dL/dF_ext per step 2.6e-4 / 2.5e-5 / 3.0e-5
A callback giving the patch's values and J the patch, bit for bit
Full loss-to-weights gradient with the force (nav_material_train_test) directional 2.2e-4 surrogate, 7.0e-4 bicycle
pycvc: rollouts vs material_ext_golden.json; trainer with a force patch 4e-9; a zero patch leaves the loss bit-identical; training with the force descends (37.68 → 17.29 in 20 steps); malformed arrays refused
material / drive / geometry ctest subset 355/355

The per-coefficient finite-difference check counts only coefficients with |g| ≥ 1e-2. At these 3–4 step horizons, a coefficient near 5e-3 has forward and backward differences 10–16% apart, with or without the force.

The golden src/cvc/tests/data/material_ext_golden.json (NavMaterialExt.Golden) holds GRL-SNAM's torch twins to the three integrators with the force on: inputs, outputs, coefficient gradients and dL/dF_ext.

Also fixed: sim_world.h's set_ext_force comment said the ext force had no effect on the material path, but step() fuses them through drive_step_material_ext.

Follow-ups

  • The GRL-SNAM side: the torch twins of the surrogate and bicycle with the channel, the MaterialTrainer pass-through, and parity tests against this golden on CPU and CUDA. That PR follows.
  • A torch twin of the dynamic material integrator.
  • A device twin of the channel for the CUDA surrogate.

Second commit: the loss's terms and a torch-trainer golden

material_loss_parts. material_loss and material_loss_and_grad take an optional material_loss_parts. It holds L, each unweighted term (traj, vel, fric, clear, nav, lreg, multi) and the CVaR eta. TheLossPartsAddUpToTheLoss checks that the terms add up to the loss on both entry points.

TorchTrainerGolden. It runs the native trainer for 3 Adam steps on the fixture batch with a scheduled force patch. With CVC_MATERIAL_TRAIN_GOLDEN_DIR set, it writes the golden that GRL-SNAM's torch material trainer is held to:

  • the config, batch and force, as JSON;
  • the weights before and after, as .cvcnm;
  • step 0's weight gradients, as float32;
  • each step's loss terms.

The golden is about 2.5 MB, so it is not committed. Measured: the loss goes 42.95 → 25.87 over the 3 steps. All 10 tests in nav_material_train_test pass locally.

The deployed drive steers the material policy and an external force together
(drive_step_material_ext with an ext_force: cvcdbg's RF/comm force), but the material trainer
trained the material heads with no such force present. material_ext (material.h) puts it in every
material training rollout, joined as the deployed drive joins it:
- the surrogate adds it to ftot (a point mass: steer has nothing to act on);
- the bicycle and the dynamic vehicle add it last to F = F_bar + F_goal + F_mat, and with steer to
  the steering bias (F_rep + F_mat + F_ext) . left;
- a null channel is the rollout without one, bit for bit (conditional adds).

Sources, exactly one: K force patches per agent on the rollout patch's grid with a per-step
schedule (a force that depends only on the agent's position, e.g. fixed radios and jammers
switching on and off; J is the patch's gradient), per-step values with an optional J, or a C++
callback with hold. The VJPs chain J^T dL/dF_ext into the position adjoint (a held window's sum at
its sampled step) and return dL/dF_ext per step. detail/material_ext.h holds the per-step sampler
and the reverse's window. material_batch::ext carries it through material_loss /
material_loss_and_grad; L_multi leaves it out; with it the surrogate runs on the CPU.

pycvc: optional trailing ext_patch / ext_patch_of_step / ext_F / ext_J / ext_steer on
nav_integrate_surrogate_material, nav_integrate_bicycle_material(_vjp) (want_g_fext returns g_fext)
and nav_material_trainer_step / _loss, checked with the GIL held.

Tests: nav_material_ext_test (null and zero force bit-identical on all three integrators; the
coefficient gradients through a scheduled force patch and through a held callback against finite
differences; dL/dF_ext; a callback giving the patch is the patch; steer; malformed channels;
NavMaterialExt.Golden writes tests/data/material_ext_golden.json for GRL-SNAM's torch twins),
nav_material_train_test's full chain with an external force (surrogate and bicycle), and
test_pycvc_nav_train's test_external_force (the bindings reproduce the golden to 4e-9).

Also: sim_world.h's set_ext_force comment said the ext force had no effect on the material path;
step() fuses them through drive_step_material_ext.
…r a torch twin trainer

material_loss and material_loss_and_grad take an optional material_loss_parts: L, each unweighted
term (traj, vel, fric, clear, nav, lreg, multi) and the CVaR eta, for a twin trainer's parity and
for logging. TheLossPartsAddUpToTheLoss checks they sum to L on both entry points.

TorchTrainerGolden runs the native trainer for 3 Adam steps on the fixture batch with a scheduled
external force patch, and with CVC_MATERIAL_TRAIN_GOLDEN_DIR set writes the golden GRL-SNAM's torch
material trainer is held to: the config, batch and force (JSON), the weights before and after
(.cvcnm), step 0's weight gradients (float32) and each step's loss terms. Not committed (2.5 MB).
Comments and docs only: ext_force is a hook for a caller's own force, and the golden is for a torch twin of the loss; no downstream user is named.
…ittable downstream

build_test_model takes the header's widths (d_tok, nhead, num_layers, d_risk); the table at the default widths is the fixed one (TestModelTableAtDefaultWidths), so every existing test and golden is unchanged. The golden test is now a helper: TorchTrainerGolden as before (loss 42.952275 -> 25.870981, eta 33.5428), and TorchTrainerGoldenSmall at d_tok 16, 2 heads, 1 layer, d_risk 16 on a batch of 4 with a 9x9 rollout patch: 59,542 parameters, about 0.8 MB written, small enough for a torch twin's CI to commit.
transfix added a commit to CVC-Lab/GRL-SNAM that referenced this pull request Oct 20, 2026
…, with parity to libcvc (#124)

* material_ext: the external force in the material rollouts and trainer, with parity to libcvc

The torch twin of libcvc's material_ext (transfix/libcvc#734): the deployed drive steers the
material policy and an external force together (an ext_force, a hook for a caller's own force), and the material
training rollouts now take the same force.

- grl_snam/material_ext.py: MaterialExt (force patches on the rollout patch's grid with a per-step
  schedule; per-step values whose J reaches the gradient through a zero-valued term; or a callable
  with hold) and ExtForce, the per-step sampler.
- material_nav.integrate_surrogate_material and material_bike.integrate_bicycle_material take
  ext=: the force joins the surrogate's force sum, and the bicycle's F (last) and, with steer, its
  steering bias, as libcvc adds it. ext=None is unchanged.
- nav_native: ext= on the material rollout wrappers (and want_g_fext on the bicycle VJP),
  HAS_MATERIAL_EXT (probed: new trailing args), material_ext_args.
- MaterialTrainer.step / .loss take ext= and pass it to the native trainer.
- material_bike: its steering constants are created on the rollout's device (CUDA failed).

tests/test_material_ext_parity.py holds the twins to libcvc's material_ext_golden.json
(NavMaterialExt.Golden): forward 1e-7, coefficient gradients 4e-7 and dL/dF_ext, CPU and CUDA
(RTX 4070, float64); a zero force is the rollout without one; with a pycvc that has the channel,
its bindings match the golden and the trainer takes the force.

* material_ext: word the external-force docstrings by capability

The docstrings describe ext_force as a hook for a caller's own force, without naming a downstream user.
# Conflicts:
#	docs/NAV_MATERIAL.md
@transfix
transfix merged commit f7930c0 into master Oct 20, 2026
20 of 24 checks passed
transfix added a commit that referenced this pull request Oct 20, 2026
…e rollouts are (#750)

NavMaterialExt.ACallbackGivingThePatchIsThePatch has failed on recipe / macos-latest / Release
since #734. For the dynamic vehicle, the outputs, the coefficient gradients and dL/dF_ext of the
patch source and of a callback giving the same patch came out 1-2 ulp apart.

Both sources sample with the same inline functions (detail/material_rollout.h's
patch_sample_channel and patch_sample_channel_grad), but in different TUs. The rollouts' TU,
material_bike_rollout.cpp, is built with -ffp-contract=off. The test's TU, where patch_callback
is, was built with the compiler's default. On aarch64 that turns the sampler's bilinear sum into
3 FMAs and each Jacobian sum into 1, so the callback's F and J were not the patch's. x86-64 with
no -march has no FMA and MSVC does not contract, so Linux and Windows were exact. macOS Debug
inlines nothing, so most likely both sides called one copy of the sampler there.

The design promises bit for bit here (#734 and docs/NAV_MATERIAL.md's table), and the library
side already is. So the test TU is now built as the rollouts are, with -ffp-contract=off
(/fp:precise on MSVC), as tests/CMakeLists.txt already does for det_math.cpp. No tolerance.

How this was checked (there is no macOS here):
- clang 18 on the test TU with its own flags: by default, 3 fmuladd in patch_sample_channel and 2
  in patch_sample_channel_grad; none with -ffp-contract=off. Compiled for arm64-apple-macosx,
  the callback has 6 fmadd by default and none with the flag.
- On Linux, a copy of the test whose callback does those FMAs with std::fma fails the same three
  assertions, for the dynamic vehicle only, by 1-2 ulp. One gradient pair is the macOS log's
  exactly (-0.126325145 vs -0.12632513). The surrogate's and the bicycle's callback F and J are an
  ulp off at many samples too, but those ulps round away where F_ext joins larger sums.
- Linux Release and Debug: nav_material_ext_test passes (11/11).
@transfix
transfix deleted the feat/material-ext branch October 29, 2026 20:52
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