nvalchemi.training.BaseLossFunction#
- class nvalchemi.training.BaseLossFunction(*, dtype_policy='strict')[source]#
Abstract
torch.nn.Modulebase for ALCHEMI loss functions.BaseLossFunctionimplements a template-methodforward()pipeline that orchestrates five overridable hooks:validate()— shape / dtype checks.normalize()— pre-processpredandtarget(e.g. per-atom energy division) and return aReductionContextfor downstream hooks.mask()— produce a boolean validity tensor (e.g.torch.isfinite, padding masks).compute_residual()— abstract; the only method every leaf must implement. Receivespred,target, and the validitymaskproduced by step 3.reduce()— collapse the residual tensor and validity mask into a scalar loss and populateper_sample_loss.
Loss authors subclass
BaseLossFunctionand overridecompute_residual()at a minimum. Normalization, masking, and reduction come free via the defaults, or can be overridden individually for domain-specific behaviour (e.g. per-atom energy division innormalize(), padding-aware force masking inmask(), graph-balanced force reduction inreduce()).Leaves are weightless — weighting and scheduling live on
ComposedLossFunction. Operator sugar (scalar * leaf,leaf + leaf,sum([...])) produces a composition; seeComposedLossFunctionfor semantics.- Parameters:
dtype_policy (DTypePolicy)
- requires_eval_grad#
Whether this loss term requires autograd during evaluation. Losses based on derived outputs such as forces and stress should set this to
True; direct scalar-output losses should set it toFalse.Nonemeans callers cannot infer the policy automatically.- Type:
bool | None
- dtype_policy#
How
forwardhandles prediction/target dtype mismatches before validation.strictpreserves both tensors and raises on mismatch. The other policies cast one tensor to the other’s dtype before the leaf validates shapes and dtypes.- Type:
{“strict”, “prediction_to_target”, “target_to_prediction”}
- per_sample_loss#
Detached per-graph loss tensor of shape
(B,)left as a side effect of the most recentforward()call, orNonewhen the loss does not naturally compute a per-graph view (or whenforwardhas never been called). Intended for logging and diagnostics only — gradients flow through the scalar returned byforward(), not through this attribute.- Type:
torch.Tensor | None
- align_dtypes(pred, target)[source]#
Return prediction and target tensors adjusted by
dtype_policy.strictpreserves both tensors and leaves dtype mismatches tovalidate().prediction_to_targetandtarget_to_predictioncast only when needed and preserve the source tensor otherwise.
- abstractmethod compute_residual(pred, target, valid)[source]#
Return the per-element residual tensor.
This is the only hook that must be overridden. The
validmask (frommask()) is provided so the leaf can zero out invalid positions before computing the residual (important for operations likevector_normwhere masking after the reduction would be incorrect).
- property dtype_policy: Literal['strict', 'prediction_to_target', 'target_to_prediction']#
Dtype alignment policy applied before validation.
- forward(pred, target, **kwargs)[source]#
Template-method pipeline: validate → normalize → mask → residual → reduce.
Subclasses should not override this method. Override the individual hooks instead. Extra keyword arguments (
batch,batch_idx,num_nodes_per_graph, etc.) are forwarded to every hook via**kwargs.
- mask(pred, target, ctx, **kwargs)[source]#
Return a boolean validity mask for
target.The default implementation returns an all-
Truemask matchingtarget’s shape. Override to exclude non-finite entries, padding, or any other invalid positions.- Parameters:
pred (Tensor)
target (Tensor)
ctx (ReductionContext)
kwargs (Any)
- Return type:
- normalize(pred, target, **kwargs)[source]#
Pre-process prediction and target before residual computation.
Returns a
(pred, target, ctx)triple. The default implementation is the identity —ctxis empty.Override to inject per-atom energy division, or any other pre-processing that should be available to all loss authors as a composable step.
- Parameters:
- Return type:
tuple[Tensor, Tensor, ReductionContext]
- reduce(residual, valid, ctx, **kwargs)[source]#
Collapse a residual tensor to a scalar loss.
The default implementation computes a validity-weighted mean:
(residual * valid_float).sum() / valid_float.sum(), wherevalid_floatincorporates optionalctx["weights"].Override for domain-specific reductions (graph-balanced force reduction, RMSD, etc.). Implementations should also populate
per_sample_losswith a detached(B,)tensor when a per-graph decomposition is available.- Parameters:
residual (Tensor)
valid (Tensor)
ctx (ReductionContext)
kwargs (Any)
- Return type: