|
| 1 | +"""Module for the SingleModelSimpleSolver.""" |
| 2 | + |
| 3 | +import torch |
| 4 | +from torch.nn.modules.loss import _Loss |
| 5 | + |
| 6 | +from pina._src.condition.domain_equation_condition import ( |
| 7 | + DomainEquationCondition, |
| 8 | +) |
| 9 | +from pina._src.condition.input_equation_condition import ( |
| 10 | + InputEquationCondition, |
| 11 | +) |
| 12 | +from pina._src.condition.input_target_condition import InputTargetCondition |
| 13 | +from pina._src.core.utils import check_consistency |
| 14 | +from pina._src.loss.loss_interface import LossInterface |
| 15 | +from pina._src.solver.solver import SingleSolverInterface |
| 16 | + |
| 17 | + |
| 18 | +class SingleModelSimpleSolver(SingleSolverInterface): |
| 19 | + """ |
| 20 | + Minimal single-model solver with explicit residual evaluation, reduction, |
| 21 | + and loss aggregation across conditions. |
| 22 | +
|
| 23 | + The solver orchestrates a uniform workflow for all conditions in the batch: |
| 24 | +
|
| 25 | + 1. evaluate the condition and obtain a non-aggregated loss tensor; |
| 26 | + 2. apply a reduction to obtain a scalar loss for that condition; |
| 27 | + 4. return the per-condition losses, which are aggregated by the inherited |
| 28 | + solver machinery through the configured weighting. |
| 29 | + """ |
| 30 | + |
| 31 | + accepted_conditions_types = ( |
| 32 | + InputTargetCondition, |
| 33 | + InputEquationCondition, |
| 34 | + DomainEquationCondition, |
| 35 | + ) |
| 36 | + |
| 37 | + def __init__( |
| 38 | + self, |
| 39 | + problem, |
| 40 | + model, |
| 41 | + optimizer=None, |
| 42 | + scheduler=None, |
| 43 | + weighting=None, |
| 44 | + loss=None, |
| 45 | + use_lt=True, |
| 46 | + ): |
| 47 | + """ |
| 48 | + Initialize the single-model simple solver. |
| 49 | +
|
| 50 | + :param AbstractProblem problem: The problem to be solved. |
| 51 | + :param torch.nn.Module model: The neural network model to be used. |
| 52 | + :param Optimizer optimizer: The optimizer to be used. |
| 53 | + :param Scheduler scheduler: Learning rate scheduler. |
| 54 | + :param WeightingInterface weighting: The weighting schema to be used. |
| 55 | + :param torch.nn.Module loss: The element-wise loss module whose |
| 56 | + reduction strategy is reused by the solver. If ``None``, |
| 57 | + :class:`torch.nn.MSELoss` is used. |
| 58 | + :param bool use_lt: If ``True``, the solver uses LabelTensors as input. |
| 59 | + """ |
| 60 | + if loss is None: |
| 61 | + loss = torch.nn.MSELoss() |
| 62 | + |
| 63 | + check_consistency(loss, (LossInterface, _Loss), subclass=False) |
| 64 | + |
| 65 | + super().__init__( |
| 66 | + model=model, |
| 67 | + problem=problem, |
| 68 | + optimizer=optimizer, |
| 69 | + scheduler=scheduler, |
| 70 | + weighting=weighting, |
| 71 | + use_lt=use_lt, |
| 72 | + ) |
| 73 | + |
| 74 | + self._loss_fn = loss |
| 75 | + self._reduction = getattr(loss, "reduction", "mean") |
| 76 | + |
| 77 | + if hasattr(self._loss_fn, "reduction"): |
| 78 | + self._loss_fn.reduction = "none" |
| 79 | + |
| 80 | + def optimization_cycle(self, batch): |
| 81 | + """ |
| 82 | + Compute one reduced loss per condition in the batch. |
| 83 | +
|
| 84 | + :param list[tuple[str, dict]] batch: A batch of data. Each element is a |
| 85 | + tuple containing a condition name and a dictionary of points. |
| 86 | + :return: The reduced losses for all conditions. |
| 87 | + :rtype: dict[str, torch.Tensor] |
| 88 | + """ |
| 89 | + condition_losses = {} |
| 90 | + |
| 91 | + for condition_name, data in batch: |
| 92 | + condition = self.problem.conditions[condition_name] |
| 93 | + condition_data = dict(data) |
| 94 | + |
| 95 | + if hasattr(condition_data.get("input"), "requires_grad_"): |
| 96 | + condition_data["input"] = condition_data[ |
| 97 | + "input" |
| 98 | + ].requires_grad_() |
| 99 | + |
| 100 | + condition_loss_tensor = condition.evaluate( |
| 101 | + condition_data, self, self._loss_fn |
| 102 | + ) |
| 103 | + condition_losses[condition_name] = self._apply_reduction( |
| 104 | + condition_loss_tensor |
| 105 | + ) |
| 106 | + |
| 107 | + return condition_losses |
| 108 | + |
| 109 | + def _apply_reduction(self, value): |
| 110 | + """ |
| 111 | + Apply the configured reduction to a non-aggregated condition tensor. |
| 112 | +
|
| 113 | + :param value: The non-aggregated tensor returned by a condition. |
| 114 | + :type value: torch.Tensor |
| 115 | + :return: The reduced scalar tensor. |
| 116 | + :rtype: torch.Tensor |
| 117 | + :raises ValueError: If the reduction is not supported. |
| 118 | + """ |
| 119 | + if self._reduction == "none": |
| 120 | + return value |
| 121 | + if self._reduction == "mean": |
| 122 | + return value.mean() |
| 123 | + if self._reduction == "sum": |
| 124 | + return value.sum() |
| 125 | + raise ValueError(f"Unsupported reduction '{self._reduction}'.") |
| 126 | + |
| 127 | + @property |
| 128 | + def loss(self): |
| 129 | + """ |
| 130 | + The underlying element-wise loss module. |
| 131 | +
|
| 132 | + :return: The stored loss module. |
| 133 | + :rtype: torch.nn.Module |
| 134 | + """ |
| 135 | + return self._loss_fn |
0 commit comments