-
Notifications
You must be signed in to change notification settings - Fork 12
Refactor and generalize loss.py
#635
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
63be717
Refactor the loss.
jwa7 6aa8d47
Merge branch 'main' into generic_loss
jwa7 5ff1585
Change trainer checkpoint version
ppegolo 9463a36
Merge branch 'main' into generic_loss
ppegolo a4faa4c
Update trainer chekpoints
ppegolo ab696de
Add checkpoint file for soap-bpnn
ppegolo 1bf88e3
Restore arch defaults for the loss section
ppegolo 52b693a
Add checkpoint file for nanopet
ppegolo 2a15fce
Merge branch 'main' into generic_loss
ppegolo 66c3a90
Update the changelog
ppegolo d6fbb29
add pet checkpoint file
ppegolo File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,123 @@ | ||
.. _loss-functions: | ||
|
||
Loss functions | ||
============== | ||
|
||
``metatrain`` supports a variety of loss functions, which can be configured | ||
in the ``loss`` subsection of the ``training`` section for each ``architecture`` | ||
in the options file. The loss functions are designed to be flexible and can be | ||
tailored to the specific needs of the dataset and the targets being predicted. | ||
|
||
The ``loss`` subsection describes the loss functions to be used. The most basic | ||
configuration is | ||
|
||
.. code-block:: yaml | ||
|
||
loss: mse | ||
|
||
which sets the loss function to mean squared error (MSE) for all targets. | ||
When training a potential energy surface on energy, forces, and virial, | ||
for example, this configuration is internally expanded to | ||
|
||
.. code-block:: yaml | ||
|
||
loss: | ||
energy: | ||
type: mse | ||
weight: 1.0 | ||
reduction: mean | ||
forces: | ||
type: mse | ||
weight: 1.0 | ||
reduction: mean | ||
virial: | ||
type: mse | ||
weight: 1.0 | ||
reduction: mean | ||
|
||
This internal, more detailed configuration can be used in the options file | ||
to specify different loss functions for each target, or to override default | ||
values for the parameters. The parameters accepted by each loss function are | ||
|
||
1. ``type``. This controls the type of loss to be used. The default value is ``mse``, | ||
and other standard options are ``mae`` and ``huber``, which implement the equivalent | ||
PyTorch loss functions | ||
`MSELoss <https://docs.pytorch.org/docs/stable/generated/torch.nn.MSELoss.html>`_, | ||
`L1Loss <https://docs.pytorch.org/docs/stable/generated/torch.nn.L1Loss.html>`_, | ||
and | ||
`HuberLoss <https://docs.pytorch.org/docs/stable/generated/torch.nn.HuberLoss.html>`_, | ||
respectively. | ||
There are also "masked" versions of these losses, which are useful when using | ||
padded targets with values that should be masked before computing the loss. The | ||
masked losses are named ``masked_mse``, ``masked_mae``, and ``masked_huber``. | ||
|
||
2. ``weight``. This controls the weighting of different contributions to the loss | ||
(e.g., energy, forces, virial, etc.). The default value of 1.0 for all targets | ||
works well for most datasets, but can be adjusted if required. | ||
|
||
3. ``reduction``. This controls how the overall loss is computed across batches. | ||
The default for this is to use the ``mean`` of the batch losses. The ``sum`` | ||
function is also supported. | ||
|
||
Some losses, like ``huber``, require additional parameters to be specified. Below is | ||
a table summarizing losses that require or allow additional parameters: | ||
|
||
.. list-table:: Loss Functions and Parameters | ||
:header-rows: 1 | ||
:widths: 20 30 50 | ||
|
||
* - Loss Type | ||
- Description | ||
- Additional Parameters | ||
* - ``mse`` | ||
- Mean squared error | ||
- N/A | ||
* - ``mae`` | ||
- Mean absolute error | ||
- N/A | ||
* - ``mse_masked`` | ||
- Masked mean squared error | ||
- N/A | ||
* - ``mae_masked`` | ||
- Masked mean absolute error | ||
- N/A | ||
* - ``huber`` | ||
- Huber loss | ||
- ``delta``: Threshold at which to switch from squared error to absolute error. | ||
|
||
|
||
Masked loss functions | ||
--------------------- | ||
|
||
Masked loss functions are particularly useful when dealing with datasets that contain | ||
padded targets. In such cases, the loss function can be configured to ignore the padded | ||
values during the loss computation. This is done by using the ``masked_`` prefix in | ||
the loss type. For example, if the target contains padded values, you can use | ||
``masked_mse`` or ``masked_mae`` to ensure that the loss is computed only on the | ||
valid (non-padded) values. The values of the masks must be passed as ``extra_data`` | ||
in the training set, and the loss function will automatically apply the mask to | ||
the target values. An example configuration for a masked loss is as follows: | ||
|
||
.. code-block:: yaml | ||
|
||
loss: | ||
energy: | ||
type: masked_mse | ||
weight: 1.0 | ||
reduction: sum | ||
forces: | ||
type: masked_mae | ||
weight: 0.1 | ||
reduction: sum | ||
jwa7 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
... | ||
|
||
training_set: | ||
systems: | ||
... | ||
targets: | ||
mtt::my_target: | ||
... | ||
... | ||
extra_data: | ||
mtt::my_target_mask: | ||
read_from: my_target_mask.mts |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
jwa7 marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -13,6 +13,7 @@ module. | |
architecture-life-cycle | ||
new-architecture | ||
dataset-information | ||
new-loss | ||
cli/index | ||
utils/index | ||
changelog |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
.. _adding-new-loss: | ||
|
||
Adding a new loss function | ||
========================== | ||
|
||
This page describes the required classes and files necessary for adding a new | ||
loss function to ``metatrain``. Defining a new loss can be useful in case some extra | ||
data has to be used to compute the loss. | ||
|
||
Loss functions in ``metatrain`` are implemented as subclasses of | ||
:py:class:`metatrain.utils.loss.LossInterface`. This interface defines the | ||
jwa7 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
required method :py:meth:`compute`, which takes the model predictions and | ||
the ground truth values as input and returns the computed loss value. The | ||
:py:meth:`compute` method accepts an additional argument ``extra_data`` on top of | ||
``predictions`` and ``targets``, that can be used to pass any extra information needed | ||
for the loss computation. | ||
|
||
.. code-block:: python | ||
|
||
from typing import Dict, Optional | ||
import torch | ||
from metatrain.utils.loss import LossInterface | ||
from metatensor.torch import TensorMap | ||
|
||
class NewLoss(LossInterface): | ||
def __init__( | ||
self, | ||
name: str, | ||
gradient: Optional[str], | ||
weight: float, | ||
reduction: str, | ||
) -> None: | ||
... | ||
|
||
def compute( | ||
self, | ||
predictions: Dict[str, TensorMap], | ||
targets: Dict[str, TensorMap], | ||
extra_data: Dict[str, TensorMap] | ||
) -> torch.Tensor: | ||
... | ||
|
||
|
||
Examples of loss functions already implemented in ``metatrain`` are | ||
:py:class:`metatrain.utils.loss.TensorMapMSELoss` and | ||
:py:class:`metatrain.utils.loss.TensorMapMAELoss`. They both inherit from the | ||
:py:class:`metatrain.utils.loss.BaseTensorMapLoss` class, which implements pointwise | ||
losses for :py:class:`metatensor.torch.TensorMap` objects. | ||
|
||
|
||
Loss weight scheduling | ||
---------------------- | ||
|
||
Currently, only one loss weight scheduler is implemented in ``metatrain``, which is | ||
:py:class:`metatrain.utils.loss.EMAScheduler`. This class is used to schedule the weight | ||
of a loss function based on the Exponential Moving Average (EMA) of the loss value. | ||
The EMA scheduler is useful to adapt the loss weight during training, allowing for a | ||
more dynamic adjustment of the loss contribution based on the training progress. | ||
New schedulers can be implemented by inheriting from the | ||
:py:class:`metatrain.utils.loss.WeightScheduler` abstract class, which defines the | ||
:py:meth:`initialize` and :py:meth:`update` methods that need to be implemented. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
# ===== Model checkpoint updates ===== | ||
|
||
# ... | ||
|
||
# ===== Trainer checkpoint updates ===== | ||
|
||
|
||
def trainer_update_v1_v2(checkpoint): | ||
old_loss_hypers = checkpoint["train_hypers"]["loss"].copy() | ||
jwa7 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
dataset_info = checkpoint["model_data"]["dataset_info"] | ||
new_loss_hypers = {} | ||
jwa7 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
for target_name in dataset_info.targets.keys(): | ||
new_loss_hypers[target_name] = { | ||
"type": old_loss_hypers["type"], | ||
"weight": old_loss_hypers["weights"].get(target_name, 1.0), | ||
"reduction": old_loss_hypers["reduction"], | ||
"sliding_factor": old_loss_hypers.get("sliding_factor", None), | ||
} | ||
checkpoint["train_hypers"]["loss"] = new_loss_hypers |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -31,7 +31,4 @@ architecture: | |
log_mae: false | ||
log_separate_blocks: false | ||
best_model_metric: rmse_prod | ||
loss: | ||
type: mse | ||
weights: {} | ||
reduction: mean | ||
Comment on lines
-34
to
-37
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is it necessary to remove the defaults here? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. And what is the new default? Is it documented? |
||
loss: mse |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.