-
Notifications
You must be signed in to change notification settings - Fork 97
Neural Tangent Kernel integration + typo fix #505
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
+147
−0
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
07c789f
NTK + typo fixing
AleDinve 662f297
restore
AleDinve eaeab58
black code formatter + .rst docs
AleDinve 933115d
comment fix
AleDinve 4623ffd
Importing fix
AleDinve 784db71
black formatter
AleDinve e54199d
bug fix
AleDinve b3f7158
test fix
AleDinve f317bf0
black code formatter
AleDinve d71990d
test fix
AleDinve 60a0fca
black code formatter
AleDinve 1fc3ad8
text fix
AleDinve f458c73
Update ntk_weighting.py
ndem0 b6f4452
Update ntk_weighting.rst
ndem0 5784aef
update doc
dario-coscia 6a30aa7
fix renaming for test fails
dario-coscia 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 |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| NeuralTangentKernelWeighting | ||
| ============================= | ||
| .. currentmodule:: pina.loss.ntk_weighting | ||
|
|
||
| .. automodule:: pina.loss.ntk_weighting | ||
|
|
||
| .. autoclass:: NeuralTangentKernelWeighting | ||
| :members: | ||
| :show-inheritance: | ||
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,71 @@ | ||
| """Module for Neural Tangent Kernel Class""" | ||
|
|
||
| import torch | ||
| from torch.nn import Module | ||
| from .weighting_interface import WeightingInterface | ||
| from ..utils import check_consistency | ||
|
|
||
|
|
||
| class NeuralTangentKernelWeighting(WeightingInterface): | ||
| """ | ||
| A neural tangent kernel scheme for weighting different losses to | ||
| boost the convergence. | ||
|
|
||
| .. seealso:: | ||
|
|
||
| **Original reference**: Wang, Sifan, Xinling Yu, and | ||
| Paris Perdikaris. *When and why PINNs fail to train: | ||
| A neural tangent kernel perspective*. Journal of | ||
| Computational Physics 449 (2022): 110768. | ||
| DOI: `10.1016/j.jcp.2021.110768 <https://doi.org/10.1016/j.jcp.2021.110768>`_. | ||
|
|
||
|
|
||
|
|
||
| """ | ||
|
|
||
| def __init__(self, model, alpha=0.5): | ||
| """ | ||
| Initialization of the :class:`NeuralTangentKernelWeighting` class. | ||
|
|
||
| :param torch.nn.Module model: The neural network model. | ||
| :param float alpha: The alpha parameter. | ||
| """ | ||
|
|
||
| super().__init__() | ||
| check_consistency(alpha, float) | ||
| check_consistency(model, Module) | ||
| if alpha < 0 or alpha > 1: | ||
| raise ValueError("alpha should be a value between 0 and 1") | ||
| self.alpha = alpha | ||
| self.model = model | ||
| self.weights = {} | ||
| self.default_value_weights = 1 | ||
|
|
||
| def aggregate(self, losses): | ||
| """ | ||
| Weights the losses according to the Neural Tangent Kernel | ||
| algorithm. | ||
|
|
||
| :param dict(torch.Tensor) input: The dictionary of losses. | ||
| :return: The losses aggregation. It should be a scalar Tensor. | ||
| :rtype: torch.Tensor | ||
| """ | ||
| losses_norm = {} | ||
| for condition in losses: | ||
| losses[condition].backward(retain_graph=True) | ||
| grads = [] | ||
| for param in self.model.parameters(): | ||
| grads.append(param.grad.view(-1)) | ||
| grads = torch.cat(grads) | ||
| losses_norm[condition] = torch.norm(grads) | ||
| self.weights = { | ||
| condition: self.alpha | ||
| * self.weights.get(condition, self.default_value_weights) | ||
| + (1 - self.alpha) | ||
| * losses_norm[condition] | ||
| / sum(losses_norm.values()) | ||
| for condition in losses | ||
| } | ||
| return sum( | ||
|
AleDinve marked this conversation as resolved.
|
||
| self.weights[condition] * loss for condition, loss in losses.items() | ||
| ) | ||
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,65 @@ | ||
| import pytest | ||
| from pina import Trainer | ||
| from pina.solver import PINN | ||
| from pina.model import FeedForward | ||
| from pina.problem.zoo import Poisson2DSquareProblem | ||
| from pina.loss import NeuralTangentKernelWeighting | ||
|
|
||
| problem = Poisson2DSquareProblem() | ||
| condition_names = problem.conditions.keys() | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "model,alpha", | ||
| [ | ||
| ( | ||
| FeedForward( | ||
| len(problem.input_variables), len(problem.output_variables) | ||
| ), | ||
| 0.5, | ||
| ) | ||
| ], | ||
| ) | ||
| def test_constructor(model, alpha): | ||
| NeuralTangentKernelWeighting(model=model, alpha=alpha) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("model", [0.5]) | ||
| def test_wrong_constructor1(model): | ||
| with pytest.raises(ValueError): | ||
| NeuralTangentKernelWeighting(model) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "model,alpha", | ||
| [ | ||
| ( | ||
| FeedForward( | ||
| len(problem.input_variables), len(problem.output_variables) | ||
| ), | ||
| 1.2, | ||
| ) | ||
| ], | ||
| ) | ||
| def test_wrong_constructor2(model, alpha): | ||
| with pytest.raises(ValueError): | ||
| NeuralTangentKernelWeighting(model, alpha) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "model,alpha", | ||
| [ | ||
| ( | ||
| FeedForward( | ||
| len(problem.input_variables), len(problem.output_variables) | ||
| ), | ||
| 0.5, | ||
| ) | ||
| ], | ||
| ) | ||
| def test_train_aggregation(model, alpha): | ||
| weighting = NeuralTangentKernelWeighting(model=model, alpha=alpha) | ||
| problem.discretise_domain(50) | ||
| solver = PINN(problem=problem, model=model, weighting=weighting) | ||
| trainer = Trainer(solver=solver, max_epochs=5, accelerator="cpu") | ||
| trainer.train() |
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.