qewton.constraints package

Module contents

Constraints Submodule

The constraints module defines the objectives and metrics used to guide and log the optimization process. Constraints are specialized nodes that evaluate model outputs against specific criteria, such as ground truth data or physical laws. Enables flexible combination of different types of constraints (e.g., data-fitting losses, physics-based residuals, or monitoring metrics) within the same graph.

Integration

During training, the GraphBasedTrainer scans the graph for Constraint nodes. It uses their evaluated_in_mode to seperate training and validation execution. Constraints which should be optimized need to be passed to the Trainer as objectives.

Submodules

qewton.constraints.base module

class qewton.constraints.base.ConstraintObjective(*values)[source]

Bases: Enum

MINIMIZE = 'minimize'
MAXIMIZE = 'maximize'
class qewton.constraints.base.Constraint(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]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: 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.

Parameters:
  • 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.

weight: HyperParameter
activation_condition: ConstraintWeightFunction | None
objective: ConstraintObjective
property loss_port: OutputPort

The output port in which the current loss value will be written.

Returns:

The output port in which the current loss value

will be written.

Return type:

OutputPort

get_loss(graph, add_weight: bool = True, training_iteration: int = 0) → TensorType[source]

Return the loss value of this constraint in the last run of graph, multiplied by the weight if add_weight is True.

Parameters:
  • 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:

The current loss value of this constraint.

Return type:

Number

property hyperparameters: list[HyperParameter]

Return a list of all hyperparameters of this constraint.

set_evaluation_mode(new_mode: EvaluationPhase)[source]

Set the evaluation mode of this constraint. This determines in which phase this constraint will be evaluated.

Parameters:

new_mode (EvaluationPhase) – The new evaluation mode for this constraint.

qewton.constraints.metric_constraint module

class qewton.constraints.metric_constraint.MetricConstraint(input_config: DataConfiguration = ..., target_config: DataConfiguration = ..., name='MetricConstraint', relative: bool | BooleanHyperparameter = False, evaluated_in_mode: EvaluationPhase = EvaluationPhase.ALWAYS, weight: float | ContinuousHyperparameter = 1, backend=<class 'qewton.backends.base.DeepLearningBackend'>, epsilon=1e-06, **kwargs)[source]

Bases: Constraint

A metric constraint is a constraint that computes a metric between two inputs, e.g. the MSE between the output of the model and some target data. The metric can be computed in a relative way, i.e. the MSE is divided by the variance of the target data, to make it scale invariant.

Parameters:
  • input_config (DataConfiguration, optional) – The expected data of the first input (the prediction). Defaults to DataConfiguration.empty().

  • target_config (DataConfiguration, optional) – The expected data of the second input (the target), which may also be a Python number. Defaults to DataConfiguration.empty().

  • name (str, optional) – A name of the constraint. Defaults to “MetricConstraint”.

  • relative (bool | BooleanHyperparameter, optional) – If a relative loss should be computed. Defaults to False.

  • epsilon (_type_, optional) – A small tolerance added to the relative loss to avoid dividing by zero. Defaults to 1e-8.

relate(prediction: DynamicDataConfiguration, target: DynamicDataConfiguration) → None[source]

A target with dims has the configuration of the prediction: the same dims and Variables. A target without dims, e.g. the 0.0 in constraint(residual, 0.0), is compared with every value.

property hyperparameters: list[HyperParameter]

Return a list of all hyperparameters of this constraint.

class qewton.constraints.metric_constraint.MSEConstraint(name='MSEConstraint', relative: bool | BooleanHyperparameter = False, evaluated_in_mode: EvaluationPhase = EvaluationPhase.ALWAYS, weight: float | ContinuousHyperparameter = 1, activation_condition: ConstraintWeightFunction | None = None, backend=<class 'qewton.backends.base.DeepLearningBackend'>, epsilon=1e-08)[source]

Bases: MetricConstraint, GraphNode

A constraint that computes the mean squared error between two inputs

build()[source]

Create what the node computes with, e.g. the weights or the inner graph of a network, from the current hyperparameter values.

Called by setup() for a node that is not built yet; a tuner makes a node unbuilt again (reset()) before trying other hyperparameter values. Does nothing by default.

qewton.constraints.pinn_constraint module

Physics-informed constraint defined by a residual function.

class qewton.constraints.pinn_constraint.PINNConstraint(residual, reduction=None, name: str | None = None, weight: float | HyperParameter = 1, activation_condition: ConstraintWeightFunction | None = None, track_residual: bool = True, objective: ConstraintObjective = ConstraintObjective.MINIMIZE, evaluated_in_mode: EvaluationPhase = EvaluationPhase.ALWAYS, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: Constraint, GraphNode

Physics-informed constraint defined by a residual function.

The residual function computes the residual of the PDE from its inputs; a reduction function then reduces it to a single value, by default the mean squared norm. Both are wrapped as nodes in the internal graph of this GraphNode.

The arguments of the residual function are annotated with variables. Each annotated argument becomes an input port named after the argument, expecting data with that variable as feature axis:

def residual(x: Variable("x"), u: Variable("u")):
    return u.gradient(x) - f(x)
Parameters:
  • residual (callable or Node) – The residual function, or a node computing the residual. Must have a single output.

  • reduction (callable or Node, optional) – Reduces the residual to a single value. Must have a single input and a single output. Defaults to MSN.

  • name – The name under which the loss is recorded. Defaults to the name of the residual function, or "PINNConstraint" for a lambda or a node.

  • weight – A weight the loss is multiplied with.

  • activation_condition – Maps the training iteration to an additional weight factor. If None, the constraint is always active.

  • track_residual – If True, the residual function is traced into a graph (FromFunctionNode); otherwise it is called directly as an opaque function (FunctionWrappingNode). Ignored if residual is a node.

  • objective – Whether the constraint is minimized or maximized.

  • evaluated_in_mode – The evaluation phase in which the constraint is evaluated.

  • backend – The backend used for computations.

Raises:

AssertionError – If the residual has more than one output, or the reduction does not have exactly one input and one output.

residual_node

The node computing the residual.

Type:

Node

reduction_node

The node reducing the residual to the loss.

Type:

Node

track_residual

Whether the residual function is traced.

Type:

bool

qewton.constraints.weight_functions module

class qewton.constraints.weight_functions.ConstraintWeightFunction[source]

Bases: object

Base class for constraint weight functions.

property hyperparameters: list[HyperParameter]

Returns a list of hyperparameters for this weight function.

Returns:

A list of hyperparameters for this weight function.

class qewton.constraints.weight_functions.LinearRampWeight(start_iteration: int | HyperParameter, full_iteration: int | HyperParameter, initial_weight: float | HyperParameter = 0.0, target_weight: float | HyperParameter = 1.0)[source]

Bases: ConstraintWeightFunction

Linearly ramps the constraint weight from initial_weight to target_weight between start_iteration and full_iteration.

For iteration <= start_iteration the returned weight is initial_weight. For iteration >= full_iteration the returned weight is target_weight.

Parameters:
  • start_iteration (int | HyperParameter) – The iteration at which the ramp starts.

  • full_iteration (int | HyperParameter) – The iteration at which the ramp ends and the target weight is reached.

  • initial_weight (float | HyperParameter, optional) – The weight at the start of the ramp. Defaults to 0.0.

  • target_weight (float | HyperParameter, optional) – The weight at the end of the ramp. Defaults to 1.0.

class qewton.constraints.weight_functions.StepWeight(activate_iteration: int | HyperParameter, inactive_weight: float | HyperParameter = 0.0, active_weight: float | HyperParameter = 1.0)[source]

Bases: ConstraintWeightFunction

Keeps a low weight until activate_iteration and then jumps up.

This is useful when a constraint should only become active after some warm-up iterations.

Parameters:
  • activate_iteration (int | HyperParameter) – The iteration at which the weight jumps up.

  • inactive_weight (float | HyperParameter, optional) – The weight before the activation iteration. Defaults to 0.0.

  • active_weight (float | HyperParameter, optional) – The weight after the activation iteration. Defaults to 1.0.

class qewton.constraints.weight_functions.CosineRampWeight(start_iteration: int | HyperParameter, full_iteration: int | HyperParameter, initial_weight: float | HyperParameter = 0.0, target_weight: float | HyperParameter = 1.0)[source]

Bases: ConstraintWeightFunction

Smoothly ramps weight from initial_weight to target_weight.

Uses a half-cosine schedule between start_iteration and full_iteration to avoid abrupt optimization changes.

Parameters:
  • start_iteration (int | HyperParameter) – The iteration at which the ramp starts.

  • full_iteration (int | HyperParameter) – The iteration at which the ramp ends and the target weight is reached.

  • initial_weight (float | HyperParameter, optional) – The weight at the start of the ramp. Defaults to 0.0.

  • target_weight (float | HyperParameter, optional) – The weight at the end of the ramp. Defaults to 1.0.