Source code for qewton.constraints.base
from enum import Enum
from qewton.backends import TensorType, Backend, DEFAULT_DL_BACKEND
from qewton.optim.base import EvaluationPhase
from qewton.optim.parameters.hyperparameter_base import HyperParameter
from qewton.graphs.nodes import Node, OutputPort
from qewton.constraints.weight_functions import ConstraintWeightFunction
[docs]
class ConstraintObjective(Enum):
MINIMIZE = "minimize"
MAXIMIZE = "maximize"
[docs]
class Constraint(Node):
"""A constraint represents a condition/loss/metric that should be fulfilled or
monitored. A constraint can be optimized during training or just be tracked
for validation/testing. Constraints can be used to implement problem specific
regularization, e.g. physics informed losses, symmetries, data constraints etc.
A constraint usually has one output port that represents the value of
the constraint, which can be used to compute the loss for optimization
or just for monitoring. The constraint can have any number of input ports,
which can be used to feed in the necessary data for computing the constraint.
Args:
weight (float | HyperParameter, optional): An additional weight for
this constraint. Defaults to 1.0.
activation_condition (ConstraintWeightFunction, optional): A callable that
takes the current training iteration and returns a float (preferably
between 0 and 1) that represents whether this constraint should be
active or not. Defaults to None, which means the constraint is
always active.
objective (ConstraintObjective, optional): Wether to minimize of maximize
this constraint. Defaults to ConstraintObjective.MINIMIZE.
evaluated_in_mode (EvaluationPhase, optional): When this constraint should
be evaluated. Defaults to EvaluationPhase.ALWAYS.
name (str, optional): A name for this constraint. Defaults to "Constraint".
backend (type[Backend[TensorType]], optional): What backend to use.
Defaults to DEFAULT_DL_BACKEND.
"""
def __init__(
self,
weight: float | HyperParameter = 1.0,
activation_condition: ConstraintWeightFunction | None = None,
objective: ConstraintObjective = ConstraintObjective.MINIMIZE,
evaluated_in_mode: EvaluationPhase = EvaluationPhase.ALWAYS,
name="Constraint",
backend: type[Backend[TensorType]] = DEFAULT_DL_BACKEND,
**kwargs,
):
self.weight: HyperParameter = HyperParameter.from_value(weight, "Weight")
self.activation_condition: ConstraintWeightFunction | None = activation_condition
self.objective: ConstraintObjective = objective
self.evaluated_in_mode = evaluated_in_mode
super().__init__(name=name, backend=backend, **kwargs)
@property
def loss_port(self) -> OutputPort:
"""The output port in which the current loss value will be written.
Returns:
OutputPort: The output port in which the current loss value
will be written.
"""
return self.output_ports[0]
[docs]
def get_loss(
self, graph, add_weight: bool = True, training_iteration: int = 0
) -> TensorType:
"""Return the loss value of this constraint in the last run of
`graph`, multiplied by the weight if add_weight is True.
Args:
graph (Graph): The graph this constraint was evaluated in.
add_weight (bool, optional): If to add the weight. Defaults to True.
training_iteration (int, optional): The current training iteration,
for the activation condition. Defaults to 0.
Raises:
ValueError: If the loss value is not computed yet.
Returns:
Number: The current loss value of this constraint.
"""
loss = graph.value_of(self.loss_port)
if loss is None:
raise ValueError(
"Loss value is not computed yet. Make sure to run the forward pass of the\
graph before getting the loss."
)
weight = self.weight.value if add_weight else 1
if add_weight and self.activation_condition is not None:
weight *= self.activation_condition(training_iteration)
return loss * weight
@property
def hyperparameters(self) -> list[HyperParameter]:
"""Return a list of all hyperparameters of this constraint."""
if self.activation_condition is not None:
return (
[self.weight]
+ self.activation_condition.hyperparameters
+ super().hyperparameters
)
return [self.weight] + super().hyperparameters
[docs]
def set_evaluation_mode(self, new_mode: EvaluationPhase):
"""Set the evaluation mode of this constraint. This determines in which
phase this constraint will be evaluated.
Args:
new_mode (EvaluationPhase): The new evaluation mode for this constraint.
"""
self.evaluated_in_mode = new_mode