Skip to content

material_train_torch: the torch material trainer, held to libcvc's native one - #125

Merged
transfix merged 5 commits into
mainfrom
material-torch-trainer
Oct 20, 2026
Merged

transfix merged 5 commits into
mainfrom
material-torch-trainer

Conversation

@transfix

@transfix transfix commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Stacks on #124 (feat/material-ext, the external force in the material rollouts). Base is feat/material-ext; retarget to main once #124 merges.

What

grl_snam/material_train_torch.py: MaterialTrainerTorch, the torch twin of MaterialTrainer (libcvc's material_loss_and_grad + material_adam). With it, the material stage trains on both paths, the C++ trainer and a torch one, with CUDA on either.

  • API. The same constructor arguments, step(batch, lr, num_threads, ext), loss(batch, frozen_eta, num_threads, ext), save(path) and 17-array batch as MaterialTrainer. It also has integrator= (surrogate / bicycle), device= (or the use_cuda request) and dtype= (float32 / float64). For parity work, loss_parts() returns the terms named as libcvc's material_loss_parts, and loss_and_grad() returns the per-tensor gradients.
  • External force. ext= takes every MaterialExt source: patch, patch schedule, per-step F/J, and a callable (torch only).
  • Weights. .cvcnm in and out through matnet_export (load_cvcnm / save_cvcnm), so the same file runs on both trainers.
  • Dynamic integrator. integrator="dynamic" raises NotImplementedError: it has no torch twin yet.
  • Rollout change. integrate_surrogate_material gains k_sharp (default 5.0, the value it hard-coded before), so the trainer's k_sharp reaches the surrogate as it already reaches the bicycle.

The loss is material_train.cpp's compute_loss, term by term. Where a literal torch reading would differ, it follows the native:

  • dropout off, and the transformer's math path;
  • TF32 off on CUDA (with it, the risk encoder's gradients drift by 1e-4);
  • config scalars rounded to float32;
  • double reductions;
  • the lreg clamp's pass-through seed;
  • geom_rollout.cpp's L_multi: explicit Euler, the trainer's mass, multi_start_fracs's draw, seed + k at step k.

Held to the native trainer

Golden. The golden is libcvc's NavMaterialTrain.TorchTrainerGolden, from libcvc #734 commit 6001a840. It covers 3 Adam steps on B 16 / N 3 / P 16 / 13x13, with a scheduled two-patch external force. It is ~3 MB and not committed: tests/test_material_train_torch.py reads it from GRL_SNAM_MATERIAL_TRAIN_GOLDEN and skips cleanly when that is unset. Measured on CPU and CUDA (RTX 4070), float32 and float64:

quantity tolerance measured
step-0 L and each term (eta frozen at the native's) 1e-5 rel <= 5e-7
step-0 weight gradients, per tensor 1e-4 of the tensor's max <= 1e-6
L and eta at steps 0-2 and after step 3 1e-5 rel <= 2e-7
weights after 3 Adam steps 1e-6 on 99.99%, 2.5e-5 every entry 1.3e-7 / 3.5e-6

The native's model and rollouts are float32 and only its reductions are double, so the golden holds at the float tier for either torch dtype. The double assembly is checked separately: the terms add up to L to 1e-12 on both sides.

One exclusion: the attention key bias (in_proj_bias[64:128]). Its gradient is identically zero, because softmax ignores a shift shared by every key. So both sides' gradients there are roundoff (~1e-8), and Adam turns that roundoff into steps of up to lr. The test checks those entries for exactly that.

Live native trainer. When a pycvc with the trainer binding is installed, the tests also run a native trainer against the torch one, on configurations the golden does not cover. Against libcvc #734's pycvc (6001a840), the same weights and batch (B 16), 3 Adam steps at lr 1e-3:

configuration loss, step 0 loss over 3 steps L_multi alone weights, 99.99th pct weights, max
legacy 1.2e-8 9.6e-8 3.6e-9 1.8e-7 1.2e-5
sampled multi-start 1.2e-8 9.6e-8 8.8e-9 1.8e-7 1.2e-5
sampled semi-implicit 1.2e-8 9.6e-8 1.0e-8 1.8e-7 1.2e-5
bicycle 1.0e-10 6.9e-10 9.0e-9 1.2e-7 4.8e-6
surrogate + ext 8.7e-8 8.7e-8 3.6e-9 1.8e-7 7.8e-7
bicycle + ext 9.5e-11 4.2e-10 9.0e-9 9.2e-8 4.8e-6

Losses are relative. "L_multi alone" compares the torch term with the native's loss(w_multi=1) - loss(w_multi=0). The ext cases use the golden's force recipe: two patches per agent, the odd agents switching at step 1. The weight maxima of 1.2e-5 are single entries whose gradient is ~1e-7 of their tensor's, where Adam's normalization amplifies float32 rounding. With this pycvc the whole file passes, as does test_material_ext_parity.py: 49 passed, nothing skipped.

Always (CI):

  • a float64 central-difference gradcheck of the full loss -> weights chain: directional to 1e-5, every tensor's largest entry to 1e-4. It runs with ext, on the bicycle, and with sampled and semi-implicit multi-starts;
  • the pass-through's semantics: loss does not train, step returns the pre-update loss, step k draws with seed + k, the low 32 bits of the seed, and ext=None equals a zero force;
  • semi-implicit L_multi equals surrogate_robust.multi_start_penalty;
  • determinism;
  • the .cvcnm round trip;
  • CUDA against CPU (skipped without a GPU).

Docs: the P5 section of CVCNAV_MATERIAL_PORT_ROADMAP.md (a new "torch trainer, held to the native one" subsection) and the parity table in MATERIAL_NAV.md.

Not covered

  • No torch twin of the dynamic integrator (NotImplementedError).
  • CI runs only the self-consistency half until the golden or a trainer-capable pycvc is in its closure.

…, 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 (cvcdbg's RF/comm 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.
…tive one

MaterialTrainerTorch is the torch twin of MaterialTrainer (libcvc's material_loss_and_grad and
material_adam). It takes the same arguments and batch, has the same step / loss / save, and takes
the same external force ext= (patch, a patch schedule, per-step F and J, or a callable). It trains
CoefEnergyNetMaterial through the torch rollout twins (surrogate or bicycle) with autograd, on the
CPU or CUDA, in float32 or float64. Weights load from and save to .cvcnm through matnet_export, so
one file runs on both trainers. The dynamic integrator has no torch twin yet and raises
NotImplementedError.

The loss is material_train.cpp's compute_loss, term by term. Where a literal torch reading would
differ, it follows the native: no dropout and the transformer's math path, TF32 off on CUDA, config
scalars rounded to float32, reductions in double, the lreg clamp's pass-through gradient, and
geom_rollout.cpp's L_multi (explicit Euler, the trainer's mass, multi_start_fracs's draw,
seed + k at step k). The optimizer is material_adam: global-norm clip, then bias-corrected Adam.

integrate_surrogate_material gains k_sharp (default 5.0, the value it hard-coded), so the trainer's
k_sharp reaches the surrogate as it reaches the bicycle.

tests/test_material_train_torch.py holds it to libcvc's NavMaterialTrain.TorchTrainerGolden
(#734, 6001a840), read from GRL_SNAM_MATERIAL_TRAIN_GOLDEN; the ~3 MB golden is not committed and
the tests skip without it. On CPU and CUDA, in float32 and float64, the step-0 terms agree to
<= 5e-7 relative, each tensor's gradient to <= 1e-6 of its largest entry, the losses over 3 Adam
steps to <= 2e-7, and the weights after them to 1.3e-7 at the 99.99th percentile (3.5e-6 max).
The attention key bias is excluded: its gradient is identically zero and Adam amplifies the
roundoff. With a pycvc trainer binding installed, the file also runs a live native trainer on the
bicycle and on sampled and semi-implicit multi-starts. Always: a float64 gradcheck of the full
chain, the pass-through's semantics, determinism, the .cvcnm round trip and CUDA against the CPU.
…ycvc

With #734's pycvc (6001a840) the two live cases with an external force run too, so the bicycle
with ext now has a native reference. All six configurations: loss <= 1e-7 relative over 3 steps,
L_multi alone <= 1e-8, weights <= 1.9e-7 at the 99.99th percentile and 1.2e-5 max.
…lden in CI

libcvc #734's TorchTrainerGoldenSmall writes the native trainer's golden at the narrowest widths (d_tok 16, 2 heads, 1 layer, d_risk 16; a batch of 4), 0.8 MB, committed under tests/fixtures/material_train_golden_small. The golden tests run on it always and on the full golden when GRL_SNAM_MATERIAL_TRAIN_GOLDEN is set. CoefEnergyNetMaterial takes nhead and num_layers (defaults unchanged), load_cvcnm builds the file's widths, and write_matnet writes the model's.
# Conflicts:
#	grl_snam/material_ext.py
#	grl_snam/material_nav.py
#	grl_snam/material_train_native.py
@transfix
transfix changed the base branch from feat/material-ext to main October 20, 2026 15:51
@transfix transfix closed this Oct 20, 2026
@transfix transfix reopened this Oct 20, 2026
@transfix
transfix merged commit 89b7ead into main Oct 20, 2026
5 checks passed
transfix added a commit that referenced this pull request Nov 7, 2026
* release: 0.3.0

95 commits since v0.2.1 (PRs #66 to #158), with new features, so the
pre-1.0 minor version goes up. The main changes:

- Ariadne hosts: GRL-SNAM's demos run as Python hosts of Ariadne documents
  (#147, #149, #153). `grl-snam ariadne cars` runs libcvc's multi-car
  template (#155), and fleet and live take its settings, worlds, plants,
  panels and log (#157). These need pycvc-gl 3.7.12.
- Vehicle plants: capture, the demos, the fog-of-war stories and training
  run on kinematic, dynamic and Jolt plants (#119, #130, #143, #145, #154).
- Torch twins of libcvc, held to its goldens: the material rollout (#118),
  terrain (#120), dyn_bike and dyn4 (#121, #123, #134-#136), the external
  force (#122, #124), the material trainer (#125), belief material
  (#128, #129, #131), U_nav (#133), and the port-Hamiltonian form, its
  energy books, wheel spin and compliant contact (#138, #139, #146).
- The vehicle-plant port-Hamiltonian whitepaper (#137 to #158).
- Training and evaluation: the base scorecard and selection (#82-#98),
  `grl-snam coef-train` (#102), the learned lam head and .cvcnav v2
  (#94, #105), and the 2026-10 audit fixes (#113).
- Data: grl-snam-weights, plus the Austin scene and Humvee as runtime
  dependencies, so `grl-snam demo` runs from a bare install (#72-#77).
- The research core moves under grl_snam/ (#103). The world clock is
  shared with libcvc's (#116, #117).

The version lives in pyproject.toml. The three cvcpkg columns mirror it in
upstream_version and in the package.files dist-info path. cvc_revision goes
back to 1 for the new upstream version. The publish job asks the server for
the next revision in any case.

* material_train_native: pass semi_implicit=False explicitly (libcvc #981)

libcvc #981 (in 3.7.12) changed nav_material_trainer_create's
ms_semi_implicit default from 0 to 1. MaterialTrainer left the L_multi
sampling args out for the legacy single start, so on pycvc-gl 3.7.12
semi_implicit=False quietly ran semi-implicit Euler. #159's CI was the
first run on 3.7.12, and four tests failed on cp311, cp312 and cp313:

- test_sampled_multi_start_args: "semi_implicit did not reach the
  rollout", because the default and semi_implicit=True were now the same
  rollout;
- test_live_native_trainer_agrees[legacy] and [legacy+ext], and
  test_live_native_trainer_agrees_on_the_belief_net[surrogate]: the
  explicit torch trainer and the native one differed by 1.3e-3 to 1.5e-3
  (tolerance 1e-5).

Now a binding that takes the args always gets them, so the integrator is
the one asked for on any pycvc. An older binding still gets the legacy
start through the old signature. GRL-SNAM's default stays explicit Euler.

tests/test_material_train_native_args.py checks both bindings. Its new
case fails without this change.
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