-
Notifications
You must be signed in to change notification settings - Fork 62
Add MONAI loss configuration classes #914
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
Open
txmed82
wants to merge
6
commits into
aramis-lab:dev
Choose a base branch
from
txmed82:agent/add-monai-loss-configs
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,3 +2,4 @@ | |
|
|
||
| from .configs import * | ||
| from .enum import ImplementedLoss | ||
| from .monai import * | ||
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 |
|---|---|---|
| @@ -0,0 +1,166 @@ | ||
| """Config classes for commonly used MONAI loss functions.""" | ||
|
|
||
| from typing import Callable, Optional, Union | ||
|
|
||
| import monai.losses | ||
| import torch | ||
| from pydantic import NonNegativeFloat, field_validator, model_validator | ||
|
|
||
| from clinicadl.utils.factories import get_defaults_from | ||
|
|
||
| from .configs import LossConfig | ||
| from .enum import GeneralizedDiceWeight, Reduction | ||
|
|
||
| __all__ = [ | ||
| "MonaiLossConfig", | ||
| "DiceLossConfig", | ||
| "DiceCELossConfig", | ||
| "DiceFocalLossConfig", | ||
| "GeneralizedDiceLossConfig", | ||
| "GeneralizedDiceFocalLossConfig", | ||
| "FocalLossConfig", | ||
| "TverskyLossConfig", | ||
| ] | ||
|
|
||
| DICE_MONAI_DEFAULTS = get_defaults_from(monai.losses.DiceLoss) | ||
| DICE_CE_MONAI_DEFAULTS = get_defaults_from(monai.losses.DiceCELoss) | ||
| DICE_FOCAL_MONAI_DEFAULTS = get_defaults_from(monai.losses.DiceFocalLoss) | ||
| GENERALIZED_DICE_MONAI_DEFAULTS = get_defaults_from(monai.losses.GeneralizedDiceLoss) | ||
| GENERALIZED_DICE_FOCAL_MONAI_DEFAULTS = get_defaults_from( | ||
| monai.losses.GeneralizedDiceFocalLoss | ||
| ) | ||
| FOCAL_MONAI_DEFAULTS = get_defaults_from(monai.losses.FocalLoss) | ||
| TVERSKY_MONAI_DEFAULTS = get_defaults_from(monai.losses.TverskyLoss) | ||
|
|
||
| SerializableWeight = Optional[Union[NonNegativeFloat, list[NonNegativeFloat]]] | ||
|
|
||
|
|
||
| class MonaiLossConfig(LossConfig): | ||
| """Base config class for MONAI loss functions.""" | ||
|
|
||
| @classmethod | ||
| def _get_class(cls) -> type[torch.nn.Module]: | ||
| """Returns the MONAI loss function associated to this config class.""" | ||
| return getattr(monai.losses, cls._get_name()) | ||
|
|
||
|
|
||
| class _OverlapLossConfig(MonaiLossConfig): | ||
| """Parameters shared by overlap-based MONAI losses.""" | ||
|
|
||
| include_background: bool = DICE_MONAI_DEFAULTS["include_background"] | ||
| to_onehot_y: bool = DICE_MONAI_DEFAULTS["to_onehot_y"] | ||
| sigmoid: bool = DICE_MONAI_DEFAULTS["sigmoid"] | ||
| softmax: bool = DICE_MONAI_DEFAULTS["softmax"] | ||
| other_act: Optional[Callable[[torch.Tensor], torch.Tensor]] = DICE_MONAI_DEFAULTS[ | ||
| "other_act" | ||
| ] | ||
| reduction: Reduction = DICE_MONAI_DEFAULTS["reduction"] | ||
| smooth_nr: NonNegativeFloat = DICE_MONAI_DEFAULTS["smooth_nr"] | ||
| smooth_dr: NonNegativeFloat = DICE_MONAI_DEFAULTS["smooth_dr"] | ||
| batch: bool = DICE_MONAI_DEFAULTS["batch"] | ||
|
|
||
| @model_validator(mode="after") | ||
| def validate_activation(self): | ||
| """Only one activation may be enabled at a time.""" | ||
| if sum((self.sigmoid, self.softmax, self.other_act is not None)) > 1: | ||
| raise ValueError( | ||
| "Only one of 'sigmoid', 'softmax' and 'other_act' may be set." | ||
| ) | ||
| return self | ||
|
|
||
|
|
||
| class _DiceLossConfig(_OverlapLossConfig): | ||
| """Parameters shared by Dice-based MONAI losses.""" | ||
|
|
||
| squared_pred: bool = DICE_MONAI_DEFAULTS["squared_pred"] | ||
| jaccard: bool = DICE_MONAI_DEFAULTS["jaccard"] | ||
|
|
||
|
|
||
| class DiceLossConfig(_DiceLossConfig): | ||
| """Config class for :py:class:`monai.losses.DiceLoss`.""" | ||
|
|
||
| weight: SerializableWeight = DICE_MONAI_DEFAULTS["weight"] | ||
| soft_label: bool = DICE_MONAI_DEFAULTS["soft_label"] | ||
|
|
||
|
|
||
| class DiceCELossConfig(_DiceLossConfig): | ||
| """Config class for :py:class:`monai.losses.DiceCELoss`.""" | ||
|
|
||
| weight: Optional[list[NonNegativeFloat]] = DICE_CE_MONAI_DEFAULTS["weight"] | ||
| lambda_dice: NonNegativeFloat = DICE_CE_MONAI_DEFAULTS["lambda_dice"] | ||
| lambda_ce: NonNegativeFloat = DICE_CE_MONAI_DEFAULTS["lambda_ce"] | ||
| label_smoothing: NonNegativeFloat = DICE_CE_MONAI_DEFAULTS["label_smoothing"] | ||
|
|
||
| @field_validator("label_smoothing") | ||
| @classmethod | ||
| def validate_label_smoothing(cls, value): | ||
| if value > 1: | ||
| raise ValueError("'label_smoothing' must be between 0 and 1.") | ||
| return value | ||
|
|
||
|
|
||
| class DiceFocalLossConfig(_DiceLossConfig): | ||
| """Config class for :py:class:`monai.losses.DiceFocalLoss`.""" | ||
|
|
||
| gamma: NonNegativeFloat = DICE_FOCAL_MONAI_DEFAULTS["gamma"] | ||
| weight: SerializableWeight = DICE_FOCAL_MONAI_DEFAULTS["weight"] | ||
| lambda_dice: NonNegativeFloat = DICE_FOCAL_MONAI_DEFAULTS["lambda_dice"] | ||
| lambda_focal: NonNegativeFloat = DICE_FOCAL_MONAI_DEFAULTS["lambda_focal"] | ||
| alpha: Optional[NonNegativeFloat] = DICE_FOCAL_MONAI_DEFAULTS["alpha"] | ||
|
|
||
| @field_validator("alpha") | ||
| @classmethod | ||
| def validate_alpha(cls, value): | ||
| if value is not None and value > 1: | ||
| raise ValueError("'alpha' must be between 0 and 1.") | ||
| return value | ||
|
|
||
|
|
||
| class _GeneralizedDiceLossConfig(_OverlapLossConfig): | ||
| """Parameters shared by generalized Dice MONAI losses.""" | ||
|
|
||
| w_type: GeneralizedDiceWeight = GENERALIZED_DICE_MONAI_DEFAULTS["w_type"] | ||
|
|
||
|
|
||
| class GeneralizedDiceLossConfig(_GeneralizedDiceLossConfig): | ||
| """Config class for :py:class:`monai.losses.GeneralizedDiceLoss`.""" | ||
|
|
||
| soft_label: bool = GENERALIZED_DICE_MONAI_DEFAULTS["soft_label"] | ||
|
|
||
|
|
||
| class GeneralizedDiceFocalLossConfig(_GeneralizedDiceLossConfig): | ||
| """Config class for :py:class:`monai.losses.GeneralizedDiceFocalLoss`.""" | ||
|
|
||
| gamma: NonNegativeFloat = GENERALIZED_DICE_FOCAL_MONAI_DEFAULTS["gamma"] | ||
| weight: SerializableWeight = GENERALIZED_DICE_FOCAL_MONAI_DEFAULTS["weight"] | ||
| lambda_gdl: NonNegativeFloat = GENERALIZED_DICE_FOCAL_MONAI_DEFAULTS["lambda_gdl"] | ||
| lambda_focal: NonNegativeFloat = GENERALIZED_DICE_FOCAL_MONAI_DEFAULTS[ | ||
| "lambda_focal" | ||
| ] | ||
|
|
||
|
|
||
| class FocalLossConfig(MonaiLossConfig): | ||
| """Config class for :py:class:`monai.losses.FocalLoss`.""" | ||
|
|
||
| include_background: bool = FOCAL_MONAI_DEFAULTS["include_background"] | ||
| to_onehot_y: bool = FOCAL_MONAI_DEFAULTS["to_onehot_y"] | ||
| gamma: NonNegativeFloat = FOCAL_MONAI_DEFAULTS["gamma"] | ||
| alpha: Optional[NonNegativeFloat] = FOCAL_MONAI_DEFAULTS["alpha"] | ||
| weight: SerializableWeight = FOCAL_MONAI_DEFAULTS["weight"] | ||
| reduction: Reduction = FOCAL_MONAI_DEFAULTS["reduction"] | ||
| use_softmax: bool = FOCAL_MONAI_DEFAULTS["use_softmax"] | ||
|
|
||
| @field_validator("alpha") | ||
| @classmethod | ||
| def validate_alpha(cls, value): | ||
| if value is not None and value > 1: | ||
| raise ValueError("'alpha' must be between 0 and 1.") | ||
| return value | ||
|
|
||
|
|
||
| class TverskyLossConfig(_OverlapLossConfig): | ||
| """Config class for :py:class:`monai.losses.TverskyLoss`.""" | ||
|
|
||
| alpha: NonNegativeFloat = TVERSKY_MONAI_DEFAULTS["alpha"] | ||
| beta: NonNegativeFloat = TVERSKY_MONAI_DEFAULTS["beta"] | ||
| soft_label: bool = TVERSKY_MONAI_DEFAULTS["soft_label"] |
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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Could you add a docstring to explain why this test is necessary?