|
| 1 | +"""Module for Neural Tangent Kernel Class""" |
| 2 | + |
| 3 | +import torch |
| 4 | +from torch.nn import Module |
| 5 | +from .weighting_interface import WeightingInterface |
| 6 | +from ..utils import check_consistency |
| 7 | + |
| 8 | + |
| 9 | +class NeuralTangentKernelWeighting(WeightingInterface): |
| 10 | + """ |
| 11 | + A neural tangent kernel scheme for weighting different losses to |
| 12 | + boost the convergence. |
| 13 | +
|
| 14 | + .. seealso:: |
| 15 | +
|
| 16 | + **Original reference**: Wang, Sifan, Xinling Yu, and |
| 17 | + Paris Perdikaris. *When and why PINNs fail to train: |
| 18 | + A neural tangent kernel perspective*. Journal of |
| 19 | + Computational Physics 449 (2022): 110768. |
| 20 | + DOI: `10.1016/j.jcp.2021.110768 <https://doi.org/10.1016/j.jcp.2021.110768>`_. |
| 21 | +
|
| 22 | +
|
| 23 | +
|
| 24 | + """ |
| 25 | + |
| 26 | + def __init__(self, model, alpha=0.5): |
| 27 | + """ |
| 28 | + Initialization of the :class:`NeuralTangentKernelWeighting` class. |
| 29 | +
|
| 30 | + :param torch.nn.Module model: The neural network model. |
| 31 | + :param float alpha: The alpha parameter. |
| 32 | + """ |
| 33 | + |
| 34 | + super().__init__() |
| 35 | + check_consistency(alpha, float) |
| 36 | + check_consistency(model, Module) |
| 37 | + if alpha < 0 or alpha > 1: |
| 38 | + raise ValueError("alpha should be a value between 0 and 1") |
| 39 | + self.alpha = alpha |
| 40 | + self.model = model |
| 41 | + self.weights = {} |
| 42 | + self.default_value_weights = 1 |
| 43 | + |
| 44 | + def aggregate(self, losses): |
| 45 | + """ |
| 46 | + Weights the losses according to the Neural Tangent Kernel |
| 47 | + algorithm. |
| 48 | +
|
| 49 | + :param dict(torch.Tensor) input: The dictionary of losses. |
| 50 | + :return: The losses aggregation. It should be a scalar Tensor. |
| 51 | + :rtype: torch.Tensor |
| 52 | + """ |
| 53 | + losses_norm = {} |
| 54 | + for condition in losses: |
| 55 | + losses[condition].backward(retain_graph=True) |
| 56 | + grads = [] |
| 57 | + for param in self.model.parameters(): |
| 58 | + grads.append(param.grad.view(-1)) |
| 59 | + grads = torch.cat(grads) |
| 60 | + losses_norm[condition] = torch.norm(grads) |
| 61 | + self.weights = { |
| 62 | + condition: self.alpha |
| 63 | + * self.weights.get(condition, self.default_value_weights) |
| 64 | + + (1 - self.alpha) |
| 65 | + * losses_norm[condition] |
| 66 | + / sum(losses_norm.values()) |
| 67 | + for condition in losses |
| 68 | + } |
| 69 | + return sum( |
| 70 | + self.weights[condition] * loss for condition, loss in losses.items() |
| 71 | + ) |
0 commit comments