nequip.train.callbacks¶
- class nequip.train.callbacks.SoftAdapt(beta: float, interval: str, frequency: int, eps: float = 1e-08)[source]¶
Adaptively modify loss coefficients over a training run using the SoftAdapt scheme.
Note that the implementation here differs from the original
SoftAdaptscheme (which tends to 1:1:1 loss coefficient ratios), where the coefficient updates are weighted by the input loss coefficients (see PR #515).Warning
The SoftAdapt requires that all components of the loss function contribute to the loss function, i.e. that their
coeffin theMetricsManageris notNone.Warning
It is dangerous to restart training (with SoftAdapt) and use a differently configured loss function for the restart because SoftAdapt’s loaded checkpoint state will become ill-suited for the new loss function.
Example usage in config where the loss coefficients are updated every 5 epochs:
callbacks: - _target_: nequip.train.callbacks.SoftAdapt beta: 1.1 interval: epoch frequency: 5
- class nequip.train.callbacks.LossCoefficientScheduler(schedule: Dict[int, Dict[str, float]])[source]¶
Schedule loss coefficients during training.
The
LossCoefficientSchedulertakes a single argumentschedule, which is aDict[int, Dict[str, float]]where the keys are the epochs at which the loss coefficients change and the values are dictionaries mapping loss metric names (corresponding to how the loss was configured) to their coefficients.When the trainer’s epoch counter matches any of the keys (representing epochs), the loss coefficients will be changed to the values (representing the coefficients for each loss term).
The coefficients will be normalized to sum up to 1 in line with the convention of
MetricsManager.Example usage in config where there are two loss contributions:
callbacks: - _target_: nequip.train.callbacks.LossCoefficientScheduler schedule: 100: per_atom_energy_mse: 1.0 forces_mse: 5.0 200: per_atom_energy_mse: 5.0 forces_mse: 1.0
- class nequip.train.callbacks.LinearLossCoefficientScheduler(final_coeffs: Dict[str, float], transition_epochs: int, start_epoch: int = 0)[source]¶
Linearly schedule loss coefficients during training.
The
LinearLossCoefficientSchedulerlinearly interpolates loss coefficients from the current values atstart_epochto the specifiedfinal_coeffsovertransition_epochsepochs.This callback is stateful and captures the loss coefficients at
start_epochfor interpolation.Note
This callback is currently in beta testing. Please report any unexpected behavior or issues.
Example usage in config to transition to energy:force:stress = 1:1:1 over 200 epochs starting at epoch 100 (from whatever coefficients they were originally at):
callbacks: - _target_: nequip.train.callbacks.LinearLossCoefficientScheduler final_coeffs: per_atom_energy_mse: 1.0 forces_mse: 1.0 stress_mse: 1.0 start_epoch: 100 transition_epochs: 200
Multiple
LinearLossCoefficientSchedulercallbacks can be composed for multi-stage scheduling:callbacks: # First transition: current -> 1:5:1 from epoch 50-150 - _target_: nequip.train.callbacks.LinearLossCoefficientScheduler final_coeffs: per_atom_energy_mse: 1.0 forces_mse: 5.0 stress_mse: 1.0 start_epoch: 50 transition_epochs: 100 # Second transition: current -> 1:1:1 from epoch 200-400 - _target_: nequip.train.callbacks.LinearLossCoefficientScheduler final_coeffs: per_atom_energy_mse: 1.0 forces_mse: 1.0 stress_mse: 1.0 start_epoch: 200 transition_epochs: 200
Warning
When composing multiple schedulers, ensure their epoch ranges do not overlap. No safety checks are performed to validate scheduler composition. Additionally, callback execution order is not guaranteed and training protocols should not rely on specific callback execution orders.
- class nequip.train.callbacks.LossCoefficientMonitor(interval: str, frequency: int)[source]¶
Monitor and log loss coefficients during training.
Example usage in config to log loss coefficients every 5 epochs:
callbacks: - _target_: nequip.train.callbacks.LossCoefficientMonitor interval: epoch frequency: 5
- class nequip.train.callbacks.TestTimeXYZFileWriter(*args, **kwargs)[source]¶
XYZFileWriter designed for saving Test Time Predictions
Users must provide an
out_filethat does not contain an extension. The actual output file will take the form{out_file}_dataset{idx}[_epoch{epoch}].xyzwhereidxis the dataset index (would be0for a single validation set but varies depending on number of validation sets) andepochis the epoch when the file is produced.To incorporate original dataset fields in the
xyzfile to simplify analysis, users may provideoutput_fields_from_original_dataset. Such fields will have the prefixoriginal_dataset_in thexyzfile.To obtain correct chemical species information, users must provide
chemical_speciesin an order consistent with the model’stype_names.To activate the option to save to a different file every epoch, users should set
separate_file_per_epochtrue.- Parameters:
out_file (str) – path to output file (must NOT contain
.xyzor.extxyzextension)output_fields_from_original_dataset (List[str]) – values from the original dataset to save in the
out_fileextra_fields (List[str]) – extra fields to save in addition to ASE’s default fields
chemical_species (List[str]) – chemical species in the same order as model’s
type_names
Example usage in config to write predictions and original dataset
total_energyandforcesto anxyzfile:callbacks: - _target_: nequip.train.callbacks.TestTimeXYZFileWriter out_file: ${hydra:runtime.output_dir}/test output_fields_from_original_dataset: [total_energy, forces] chemical_symbols: ${chemical_symbols}
- class nequip.train.callbacks.ValTimeXYZFileWriter(separate_file_per_epoch: bool = False, every_n_epochs: int = 1, *args, **kwargs)[source]¶
XYZFileWriter designed for saving Val Time Predictions
Users must provide an
out_filethat does not contain an extension. The actual output file will take the form{out_file}_dataset{idx}[_epoch{epoch}].xyzwhereidxis the dataset index (would be0for a single validation set but varies depending on number of validation sets) andepochis the epoch when the file is produced.To incorporate original dataset fields in the
xyzfile to simplify analysis, users may provideoutput_fields_from_original_dataset. Such fields will have the prefixoriginal_dataset_in thexyzfile.To obtain correct chemical species information, users must provide
chemical_speciesin an order consistent with the model’stype_names.To activate the option to save to a different file every epoch, users should set
separate_file_per_epochtrue.- Parameters:
out_file (str) – path to output file (must NOT contain
.xyzor.extxyzextension)output_fields_from_original_dataset (List[str]) – values from the original dataset to save in the
out_fileextra_fields (List[str]) – extra fields to save in addition to ASE’s default fields
chemical_species (List[str]) – chemical species in the same order as model’s
type_namesseparate_file_per_epoch (bool) – if True, write outputs to a separate file per epoch (Useful for
Trainrun types with ValTimeXYZFileWriter)every_n_epochs (int) – if nonzero, only call on epoch multiples of this variable
Example usage in config to write predictions and original dataset
total_energyandforcesto anxyzfile:callbacks: - _target_: nequip.train.callbacks.ValTimeXYZFileWriter out_file: ${hydra:runtime.output_dir}/val output_fields_from_original_dataset: [total_energy, forces] chemical_symbols: ${chemical_symbols} separate_file_per_epoch: true every_n_epochs: 5
- class nequip.train.callbacks.WandbWatch(log_freq: int, log: str = 'gradients', log_graph: bool = False)[source]¶
Monitor and log weights and gradients during training with PyTorch Lightning’s
WandbLogger.This class provides a way to call https://docs.wandb.ai/ref/python/watch/ when using a
WandbLoggerfor monitoring weights and gradients over the course of training.
- class nequip.train.callbacks.TF32Scheduler(schedule: Dict[int, bool])[source]¶
Schedule TF32 precision during training.
The
TF32Schedulertakes a single argumentschedule, which is aDict[int, bool]where the keys are the epochs at which TF32 changes and the values are:True: Enable TF32 (faster but less precise)False: Disable TF32 (slower but more precise)
Basic example to enable TF32 for all training:
callbacks: - _target_: nequip.train.callbacks.TF32Scheduler schedule: 0: true # Enable TF32 throughout training
Dynamic scheduling example for two-stage training:
callbacks: - _target_: nequip.train.callbacks.TF32Scheduler schedule: 0: true # Start with TF32 enabled 100: false # Disable TF32 at epoch 100 200: true # Re-enable TF32 at epoch 200
Note
The schedule must start at epoch 0. The initial setting will be applied at the beginning of training.
Note
This callback is currently in beta testing. Please report any unexpected behavior or issues.
- class nequip.train.callbacks.TrainingStatsMonitor(log_freq: int = 100, log_weights: bool = True, log_gradients: bool = True, log_optimizer_states: bool = True)[source]¶
Monitor and log detailed training statistics including weights, gradients, and optimizer states.
This callback provides comprehensive logging of training dynamics to help diagnose training instabilities. It tracks weight and gradient statistics as well as internal optimizer states for Adam/AdamW optimizers.
- class nequip.train.callbacks.TorchProfilerCallback(profile_dir: str = 'profiler', chrome_trace_dir: str | None = None, wait: int = 1, warmup: int = 1, active: int = 3, repeat: int = 1, ranks: Sequence[int] | None = (0,), record_shapes: bool = True, with_stack: bool = False, with_modules: bool = False, profile_memory: bool = False, activities: Sequence[str] | None = None, summary_rows: int = 30)[source]¶
Profile training steps with
torch.profilerand export Chrome/TensorBoard traces.The callback wraps the training loop in a
torch.profiler.profilecontext driven by atorch.profiler.schedule(). Profiling starts after Lightning’s sanity-check validation, and one trace file is written per completedwait/warmup/activecycle. The trace files are named<worker>.cycle<N>.pt.trace.jsonand can either be loaded directly inchrome://tracing/ Perfetto, or pointed at by the TensorBoard profiler plugin (tensorboard --logdir <profile_dir>). To use chrome tracing, make sure to have Chrome’s developer settings enabled.The profiler samples
repeat * (wait + warmup + active)training batches in total, so make sure the run is long enough to reach the end of the first cycle – otherwise no trace is written. A warning is emitted at the start of training if the configured schedule cannot complete.Example usage in config:
callbacks: - _target_: nequip.train.callbacks.TorchProfilerCallback profile_dir: ${hydra:runtime.output_dir}/profiler wait: 5 warmup: 3 active: 5 repeat: 1
Warning
Some of these profiling options are a bit expensive. In particular, set
activesmall, and usewith_stackandprofile_memoryonly if you need to.Note
When using
compile_mode: compile, the first several batches are dominated by compilation. Setwait(and/orwarmup) large enough to skip past compilation, otherwise the trace mostly shows Dynamo/Inductor instead of the model.- Parameters:
profile_dir (str) – directory that trace files are written to
chrome_trace_dir (str) – optional additional directory to copy the traces into (default
None)wait (int) – number of batches to skip at the start of each cycle
warmup (int) – number of batches to warm the profiler up on
active (int) – number of batches recorded in each cycle
repeat (int) – number of cycles,
0means repeat foreverranks (List[int]) – global ranks that profile,
Noneprofiles every rank (default[0])record_shapes (bool) – whether to record input shapes of operators
with_stack (bool) – whether to record source information (file and line number)
with_modules (bool) – whether to record the module hierarchy of each operator
profile_memory (bool) – whether to record tensor memory allocation/free
activities (List[str]) – profiler activities, e.g.
["CPU", "CUDA"](defaultNone: CPU, if available, CUDA)summary_rows (int) – number of rows of the
key_averagessummary table written next to each trace,0disables the summary (default30)
- on_train_start(trainer: Trainer, pl_module: NequIPLightningModule) None[source]¶
Called when the train begins.
- on_train_batch_end(trainer: Trainer, pl_module: NequIPLightningModule, outputs, batch, batch_idx: int) None[source]¶
Called when the train batch ends.
Note
The value
outputs["loss"]here will be the normalized value w.r.taccumulate_grad_batchesof the loss returned fromtraining_step.
- on_train_end(trainer: Trainer, pl_module: NequIPLightningModule) None[source]¶
Called when the train ends.
- on_exception(trainer: Trainer, pl_module: NequIPLightningModule, exception: BaseException) None[source]¶
Called when any trainer execution is interrupted by an exception.