npx skills add ...
npx skills add nvidia/nvalchemi-toolkit --skill nvalchemi-loss-api
How to use built-in loss functions and implement custom losses using the BaseLossFunction template-method pattern — residual types, per-atom normalization, masking, and graph-balanced reductions. Use when choosing or weighting energy, force, or stress objectives for training or fine-tuning, masking atoms or graphs out of the loss, or writing a custom loss term.
npx skills add nvidia/nvalchemi-toolkit --skill nvalchemi-loss-api
Loss functions are torch.nn.Module subclasses rooted at BaseLossFunction.
Each leaf consumes (pred, target, **kwargs) and returns a scalar.
ComposedLossFunction routes keyed prediction/target mappings to leaves,
applies per-component weights (float or LossWeightSchedule), and returns
a ComposedLossOutput TypedDict.
Choose losses by the training signal you want:
EnergyMSELoss: default for smooth energy regression when larger errors should
dominate early training; combine with per_atom=True when system sizes vary.EnergyMAELoss: more robust to outlier energies and often useful for reporting
or late-stage fitting when median absolute accuracy matters.EnergyHuberLoss: compromise between MSE and MAE; use when energy labels have
occasional noisy outliers but small residuals should remain smooth.ForceMSELoss: default force objective; component-wise squared residuals give
strong gradients for geometry-sensitive fitting.ForceL2NormLoss: use when vector direction/magnitude per atom is the desired
error signal rather than independent xyz components.ForceHuberLoss: robust force fitting when some force labels are noisy or
contain rare large residuals.StressMSELoss / StressHuberLoss: add only when stress labels are reliable
and the model is configured to produce stresses.Composition sugar:
Graph metadata: losses that need graph structure (per_atom=True,
normalize_by_atom_count=True, or padded layouts) accept batch=
(pulls batch_idx, num_graphs, num_nodes_per_graph automatically)
or explicit kwargs.
BaseLossFunction.forward orchestrates five hooks:
Minimum implementation: override compute_residual only. Defaults
handle shape validation, all-True masking, and validity-weighted mean reduction.
Override normalize to divide by atom counts and pass weights via
ReductionContext["weights"]. The base reduce picks up weights
automatically.
Override mask to exclude non-finite targets, padding, or other invalid entries.
Return a boolean tensor broadcast-compatible with pred/target.
For padded force layouts (B, V_max, 3), combine a node mask with nonfinite check:
The valid tensor flows into compute_residual as the third argument.
Zero invalid entries with torch.where(valid, ..., torch.zeros_like(...)).
Override reduce for graph-balanced or other non-mean reductions.
Populate self.per_sample_loss with a detached (B,) tensor for diagnostics.
ForceMSELoss and ForceL2NormLoss use plum-dispatch to handle both
dense (V, 3) and padded (B, V_max, 3) layouts without if/else on
ndim. Their mask and reduce hooks delegate to @overload/@dispatch
helper methods — one overload per layout. See these implementations in
nvalchemi/training/losses/terms.py as the reference pattern for
multi-layout losses.
target_key and prediction_key on any loss that participates
in ComposedLossFunction — these route tensors from the prediction/target
mappings.**kwargs in hooks that receive them — ComposedLossFunction
forwards metadata kwargs to every component.compute_residual must zero invalid entries using the valid mask
argument — the base reduce handles weighting but not masking.ReductionContext is a dict subclass (not TypedDict) for
torch.compile compatibility. Conventional key: "weights" for
atom-count weights consumed by the base reduce.| File | Contents |
|---|---|
nvalchemi/training/losses/composition.py | BaseLossFunction, ComposedLossFunction, ReductionContext |
nvalchemi/training/losses/terms.py | All 8 built-in leaf losses |
nvalchemi/training/losses/reductions.py | per_graph_sum, per_graph_mean, frobenius_mse |
nvalchemi/training/losses/schedules.py | ConstantWeight, LinearWeight, CosineWeight, PiecewiseWeight |
nvalchemi/training/losses/base.py | LossWeightSchedule protocol, re-exports |
test/training/test_losses.py | Comprehensive tests for all loss terms |
docs/userguide/losses.md | Full user guide with examples |