qewton.algorithms.building_blocks package

Module contents

Submodules

qewton.algorithms.building_blocks.activation_functions module

class qewton.algorithms.building_blocks.activation_functions.AdaptiveActivation(activation_function: ~qewton.graphs.nodes.Node[~qewton.backends.base.TensorType], initial_slope=1.0, name: str = 'AdaptiveActivation', backend: type[~qewton.backends.base.DeepLearningBackend[~qewton.backends.base.TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: GraphNode[TensorType]

An adaptive activation function node that applies a specified activation function with learnable slope and shift parameters.

Parameters:
  • activation_function (Node[TensorType]) – The activation function to be applied.

  • initial_slope (float or TensorType) – Initial value for the slope parameter. Defaults to 1.0.

  • name (str) – Name of the node. Defaults to “AdaptiveActivation”.

  • backend (type[DeepLearningBackend[TensorType]]) – The deep learning backend to use. Defaults to DEFAULT_DL_BACKEND.

ellipsis_axes = <qewton.config.axes.EllipsisAxes object>
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.

forward(x: Annotated[TensorType, ..., Number, ()]) → Annotated[TensorType, ..., Number, ()][source]

Evaluate the inner graph on the inputs.

Subclasses override this method only to declare the data configurations of their ports with typing.Annotated; the body stays return super().forward(...). Inside a graph, the steps of the inner graph run in place of this node instead.

Parameters:
  • *args – The values of the input ports, in order.

  • **kwargs – The values of input ports by name.

Returns:

The value of the output port, or a tuple for several.

Return type:

Any

Raises:

RuntimeError – If the node is not built and waits for sizes to be inferred from connected data.

class qewton.algorithms.building_blocks.activation_functions.ReLU(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Rectified Linear Unit (ReLU) activation function.

Applies the ReLU activation function element-wise to the input tensor. Returns max(0, x) for each element, effectively zeroing out negative values.

ellipsis_axes = <qewton.config.axes.EllipsisAxes object>
forward(x: Annotated[TensorType, ..., Number, ()]) → Annotated[TensorType, ..., Number, ()][source]

Forward pass of ReLU activation.

Parameters:

x – Input tensor of any shape.

Returns:

Output tensor with same shape and dtype as input.

Return type:

TensorType

class qewton.algorithms.building_blocks.activation_functions.Tanh(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Hyperbolic Tangent (Tanh) activation function.

Applies the tanh activation function element-wise to the input tensor. Maps input values to the range [-1, 1], providing a smooth, differentiable activation.

ellipsis_axes = <qewton.config.axes.EllipsisAxes object>
forward(x: Annotated[TensorType, ..., Number, ()]) → Annotated[TensorType, ..., Number, ()][source]

Forward pass of Tanh activation.

Parameters:

x – Input tensor of any shape.

Returns:

Output tensor with values in range [-1, 1],

same shape and dtype as input.

Return type:

TensorType

class qewton.algorithms.building_blocks.activation_functions.Sigmoid(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Sigmoid activation function.

Applies the sigmoid activation function element-wise to the input tensor. Maps input values to the range (0, 1), providing a smooth probability-like output.

ellipsis_axes

Configuration for tensor axes handling.

Type:

EllipsisAxes

Examples

>>> sigmoid = Sigmoid(backend)
>>> x = backend.library.array([[-2, 0], [2, 4]])
>>> output = sigmoid.forward(x)
>>> # output: approximately [[0.12, 0.5], [0.88, 0.98]]
ellipsis_axes = <qewton.config.axes.EllipsisAxes object>
forward(x: Annotated[TensorType, ..., Number, ()]) → Annotated[TensorType, ..., Number, ()][source]

Forward pass of Sigmoid activation.

Parameters:

x – Input tensor of any shape.

Returns:

Output tensor with values in range (0, 1),

same shape and dtype as input.

Return type:

TensorType

class qewton.algorithms.building_blocks.activation_functions.GELU(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Gaussian Error Linear Unit (GELU) activation function.

Applies the GELU activation function element-wise to the input tensor. Weights input values according to the cumulative distribution function of a standard Gaussian distribution, providing a smooth nonlinear output.

ellipsis_axes

Configuration for tensor axes handling.

Type:

EllipsisAxes

Examples

>>> gelu = GELU(backend)
>>> x = backend.library.array([[-2, 0], [2, 4]])
>>> output = gelu.forward(x)
>>> # output: approximately [[-0.05, 0], [1.95, 4.0]]
ellipsis_axes = <qewton.config.axes.EllipsisAxes object>
forward(x: Annotated[TensorType, ..., Number, ()]) → Annotated[TensorType, ..., Number, ()][source]

Forward pass of GELU activation.

Parameters:

x – Input tensor of any shape.

Returns:

Output tensor with the same shape and dtype as the input.

Return type:

TensorType

class qewton.algorithms.building_blocks.activation_functions.SoftPlus(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Softplus activation function.

Applies the softplus activation function element-wise to the input tensor. Maps input values to the range (0, ∞), providing a smooth approximation of ReLU.

ellipsis_axes

Configuration for tensor axes handling.

Type:

EllipsisAxes

ellipsis_axes = <qewton.config.axes.EllipsisAxes object>
forward(x: Annotated[TensorType, ..., Number, ()]) → Annotated[TensorType, ..., Number, ()][source]

Forward pass of Softplus activation.

Parameters:

x – Input tensor of any shape.

Returns:

Output tensor with values in range (0, ∞),

same shape and dtype as input.

Return type:

TensorType

qewton.algorithms.building_blocks.array_operations module

class qewton.algorithms.building_blocks.array_operations.SetItem(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Set item node that assigns values to specific indices of an input tensor. Has variable input ports for tensor and indices, and one output port. The value may be a tensor or a Python number, e.g. x[:, :1] = 1.0.

data_axis = <qewton.config.axes.EllipsisAxes object>
forward(inp: Annotated[TensorType, ...], key: Annotated[Any, ...], value: Annotated[TensorType | float, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.array_operations.Slice(slice_config: int | slice | ~qewton.config.variables.Variable | tuple[slice | list[int] | ~types.EllipsisType | int | ~typing.Any, ...], name=None, backend: type[~qewton.backends.base.DeepLearningBackend[~qewton.backends.base.TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: Node[TensorType]

Slice node that extracts a portion of the input tensor based on slice configuration. Supports integer indices, slices, variables, and ellipsis notation. Has one input port and one output port.

backend: type[DeepLearningBackend[TensorType]]
forward(inp: Annotated[Any, ...]) → Annotated[Any, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

relate(inp: DynamicDataConfiguration) → DataConfiguration | None[source]

Slicing a Variable keeps every axis but the features, which become the Variable; other slices leave the output open.

class qewton.algorithms.building_blocks.array_operations.SplitVariables(split_into: list[~qewton.config.variables.Variable], name=None, backend: type[~qewton.backends.base.DeepLearningBackend[~qewton.backends.base.TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: Node[TensorType]

Splits an input tensor’s feature axis into one output port per Variable in split_into.

The caller decides the exact pieces upfront - this used to auto-derive them from whatever named entries its own input happened to have, which forced always splitting down to the finest granularity available before anything downstream could ask for less. A caller that knows every downstream consumer in advance (e.g. PINNPipeline) can instead split only as finely as actually needed - a variable nothing ever asks to subdivide can be named whole in split_into and passed through with a single piece.

Parameters:

split_into (list[Variable]) – The pieces to split the input’s feature axis into, in order. Each must be a contiguous run of the eventual input’s own feature Variable - not necessarily a single leaf, e.g. an auto-expanded 3D variable can be its own whole piece.

backend: type[DeepLearningBackend[TensorType]]
forward(inp: Annotated[TensorType, ...])[source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.array_operations.ConcatVariables(in_variables, concat_dim: int = -1, name=None, backend: type[DeepLearningBackend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: Node[TensorType]

Concatenate variables node that combines multiple input tensors with different variables along a dimension. Assumes the feature axes are all the last axes. Has multiple input ports (one per variable) and one output port.

backend: type[DeepLearningBackend[TensorType]]
check_unique_var_keys()[source]
forward(*inp)[source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.array_operations.AsVariable(variable: Variable, name=None, backend: type[DeepLearningBackend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: Node[TensorType]

Declares that the features of its input are variable, e.g. that an exact solution computed from t is a value of u, to compare it with the output of a model of u.

Merging configurations never changes their Variables, so data of t can not be connected where u is expected; this node passes the data on unchanged under the new Variable. The input may have any Variable (or none) with the same feature size as variable.

Parameters:

variable (Variable) – The Variable of the output’s features.

backend: type[DeepLearningBackend[TensorType]]
forward(inp: Annotated[TensorType, ...])[source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.array_operations.ConcatNode(concat_dim: int, num_of_input_ports: int = 2, backend=<class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: Node[TensorType]

Concatenate node that combines multiple input tensors along a specified dimension. Has multiple input ports and one output port.

backend: type[DeepLearningBackend[TensorType]]
forward(*inp) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

relate(*inputs: DynamicDataConfiguration) → DataConfiguration[source]

The configuration of each output, from those of the inputs at one place of a graph, for relations the annotations of forward() can not express: an operation that changes dims by their index (e.g. return x.squeeze(self.dim), see the shape operations of DataConfiguration).

The inputs are declared by the annotations and already merged with what is connected, as known so far (resolved, see Matching); they belong to the matching of the graph, so what shape operations fix goes there. The returned configurations are merged with the annotated ones of the outputs. A shape operation that needs more of the inputs’ structure than is known raises StructureUnknown; the graph calls relate again once the inputs change.

Parameters:

*inputs – The configurations of the input ports, in order.

Returns:

The configuration of the

output, a tuple for several outputs, or None if the annotations say everything (default).

Return type:

DataConfiguration or tuple or None

class qewton.algorithms.building_blocks.array_operations.Narrow(dim=None, start=0, length=None, backend=<class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: Node[TensorType]

Narrow node that returns a narrowed view of the input tensor along a specified dimension. Has one input port and one output port.

backend: type[DeepLearningBackend[TensorType]]
forward(x: Annotated[TensorType, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

relate(x: DynamicDataConfiguration) → DataConfiguration | None[source]

The configuration of each output, from those of the inputs at one place of a graph, for relations the annotations of forward() can not express: an operation that changes dims by their index (e.g. return x.squeeze(self.dim), see the shape operations of DataConfiguration).

The inputs are declared by the annotations and already merged with what is connected, as known so far (resolved, see Matching); they belong to the matching of the graph, so what shape operations fix goes there. The returned configurations are merged with the annotated ones of the outputs. A shape operation that needs more of the inputs’ structure than is known raises StructureUnknown; the graph calls relate again once the inputs change.

Parameters:

*inputs – The configurations of the input ports, in order.

Returns:

The configuration of the

output, a tuple for several outputs, or None if the annotations say everything (default).

Return type:

DataConfiguration or tuple or None

class qewton.algorithms.building_blocks.array_operations.Squeeze(dim: int, name=None, backend: type[DeepLearningBackend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: Node[TensorType]

Squeeze node that removes a single dimension of size 1 from the input tensor. Has one input port and one output port.

backend: type[DeepLearningBackend[TensorType]]
forward(inp: Annotated[TensorType, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

relate(inp: DynamicDataConfiguration) → DataConfiguration[source]

The configuration of each output, from those of the inputs at one place of a graph, for relations the annotations of forward() can not express: an operation that changes dims by their index (e.g. return x.squeeze(self.dim), see the shape operations of DataConfiguration).

The inputs are declared by the annotations and already merged with what is connected, as known so far (resolved, see Matching); they belong to the matching of the graph, so what shape operations fix goes there. The returned configurations are merged with the annotated ones of the outputs. A shape operation that needs more of the inputs’ structure than is known raises StructureUnknown; the graph calls relate again once the inputs change.

Parameters:

*inputs – The configurations of the input ports, in order.

Returns:

The configuration of the

output, a tuple for several outputs, or None if the annotations say everything (default).

Return type:

DataConfiguration or tuple or None

class qewton.algorithms.building_blocks.array_operations.Unsqueeze(dim: int, name=None, backend: type[DeepLearningBackend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: Node[TensorType]

Unsqueeze node that adds a new dimension of size 1 at the specified position. Has one input port and one output port.

backend: type[DeepLearningBackend[TensorType]]
forward(inp: Annotated[TensorType, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

relate(inp: DynamicDataConfiguration) → DataConfiguration[source]

The configuration of each output, from those of the inputs at one place of a graph, for relations the annotations of forward() can not express: an operation that changes dims by their index (e.g. return x.squeeze(self.dim), see the shape operations of DataConfiguration).

The inputs are declared by the annotations and already merged with what is connected, as known so far (resolved, see Matching); they belong to the matching of the graph, so what shape operations fix goes there. The returned configurations are merged with the annotated ones of the outputs. A shape operation that needs more of the inputs’ structure than is known raises StructureUnknown; the graph calls relate again once the inputs change.

Parameters:

*inputs – The configurations of the input ports, in order.

Returns:

The configuration of the

output, a tuple for several outputs, or None if the annotations say everything (default).

Return type:

DataConfiguration or tuple or None

class qewton.algorithms.building_blocks.array_operations.Reshape(new_shape: tuple[int, ...], name=None, backend: type[~qewton.backends.base.DeepLearningBackend[~qewton.backends.base.TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: Node[TensorType]

Reshape node that changes the shape of the input tensor to a specified new shape. Has one input port and one output port.

backend: type[DeepLearningBackend[TensorType]]
forward(inp: Annotated[TensorType, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

relate(inp: DynamicDataConfiguration) → DataConfiguration[source]

The configuration of each output, from those of the inputs at one place of a graph, for relations the annotations of forward() can not express: an operation that changes dims by their index (e.g. return x.squeeze(self.dim), see the shape operations of DataConfiguration).

The inputs are declared by the annotations and already merged with what is connected, as known so far (resolved, see Matching); they belong to the matching of the graph, so what shape operations fix goes there. The returned configurations are merged with the annotated ones of the outputs. A shape operation that needs more of the inputs’ structure than is known raises StructureUnknown; the graph calls relate again once the inputs change.

Parameters:

*inputs – The configurations of the input ports, in order.

Returns:

The configuration of the

output, a tuple for several outputs, or None if the annotations say everything (default).

Return type:

DataConfiguration or tuple or None

class qewton.algorithms.building_blocks.array_operations.ReshapeAtDim(dim: int, new_shape: tuple[int, ...], name=None, backend: type[~qewton.backends.base.DeepLearningBackend[~qewton.backends.base.TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: Node[TensorType]

Reshape at dimension node that reshapes a portion of the input tensor at a specified dimension. Has one input port and one output port.

backend: type[DeepLearningBackend[TensorType]]
forward(inp: Annotated[TensorType, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

relate(inp: DynamicDataConfiguration) → DataConfiguration[source]

The configuration of each output, from those of the inputs at one place of a graph, for relations the annotations of forward() can not express: an operation that changes dims by their index (e.g. return x.squeeze(self.dim), see the shape operations of DataConfiguration).

The inputs are declared by the annotations and already merged with what is connected, as known so far (resolved, see Matching); they belong to the matching of the graph, so what shape operations fix goes there. The returned configurations are merged with the annotated ones of the outputs. A shape operation that needs more of the inputs’ structure than is known raises StructureUnknown; the graph calls relate again once the inputs change.

Parameters:

*inputs – The configurations of the input ports, in order.

Returns:

The configuration of the

output, a tuple for several outputs, or None if the annotations say everything (default).

Return type:

DataConfiguration or tuple or None

class qewton.algorithms.building_blocks.array_operations.Flatten(start_dim: int = 0, end_dim: int = -1, name=None, backend: type[DeepLearningBackend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: Node[TensorType]

Flatten node that flattens the input tensor between specified dimensions. Has one input port and one output port.

backend: type[DeepLearningBackend[TensorType]]
forward(inp: Annotated[TensorType, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

relate(inp: DynamicDataConfiguration) → DataConfiguration[source]

The configuration of each output, from those of the inputs at one place of a graph, for relations the annotations of forward() can not express: an operation that changes dims by their index (e.g. return x.squeeze(self.dim), see the shape operations of DataConfiguration).

The inputs are declared by the annotations and already merged with what is connected, as known so far (resolved, see Matching); they belong to the matching of the graph, so what shape operations fix goes there. The returned configurations are merged with the annotated ones of the outputs. A shape operation that needs more of the inputs’ structure than is known raises StructureUnknown; the graph calls relate again once the inputs change.

Parameters:

*inputs – The configurations of the input ports, in order.

Returns:

The configuration of the

output, a tuple for several outputs, or None if the annotations say everything (default).

Return type:

DataConfiguration or tuple or None

class qewton.algorithms.building_blocks.array_operations.Unflatten(axis: int, sizes: tuple[int, ...] | None=None, name=None, backend: type[DeepLearningBackend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: Node[TensorType]

Unflatten node that reshapes a single dimension into multiple dimensions. Has one input port and one output port.

backend: type[DeepLearningBackend[TensorType]]
forward(inp: ~typing.Annotated[~qewton.backends.base.TensorType, ...], size: ~typing.Annotated[int | tuple[int, ...] | None, <qewton.config.axes.FeatureAxes object at 0x7c052e7bc770>] = None) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

relate(inp: DynamicDataConfiguration, size: DynamicDataConfiguration) → DataConfiguration | None[source]

The configuration of each output, from those of the inputs at one place of a graph, for relations the annotations of forward() can not express: an operation that changes dims by their index (e.g. return x.squeeze(self.dim), see the shape operations of DataConfiguration).

The inputs are declared by the annotations and already merged with what is connected, as known so far (resolved, see Matching); they belong to the matching of the graph, so what shape operations fix goes there. The returned configurations are merged with the annotated ones of the outputs. A shape operation that needs more of the inputs’ structure than is known raises StructureUnknown; the graph calls relate again once the inputs change.

Parameters:

*inputs – The configurations of the input ports, in order.

Returns:

The configuration of the

output, a tuple for several outputs, or None if the annotations say everything (default).

Return type:

DataConfiguration or tuple or None

class qewton.algorithms.building_blocks.array_operations.Repeat(repeats: int, dim: int, name=None, backend: type[DeepLearningBackend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: Node[TensorType]

backend: type[DeepLearningBackend[TensorType]]
forward(inp: Annotated[TensorType, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.array_operations.UnflattenLike(start_dim: int, end_dim: int | None = None, axis: int = -1, name: str | None = None, backend: type[DeepLearningBackend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: Node[TensorType]

Unflattens an axis of a tensor into a part of the shape of another one.

The axis axis of the input is split into the shape like.shape[start_dim:end_dim]. This is the inverse of Flatten(start_dim, end_dim) when the shape to restore is only known at runtime, taken from the tensor that was flattened.

Parameters:
  • start_dim (int) – Index of the first axis of like whose shape is restored.

  • end_dim (int | None, optional) – Index after the last axis of like whose shape is restored; None for all up to the end. Defaults to None.

  • axis (int, optional) – The axis of the input that is split. Defaults to -1, the last one.

  • name (str | None, optional) – Name of the node. Defaults to “UnflattenLikeNode”.

  • backend (type[DeepLearningBackend[TensorType]], optional) – The backend used for the computations. Defaults to DEFAULT_DL_BACKEND.

backend: type[DeepLearningBackend[TensorType]]
forward(inp: Annotated[TensorType, ...], like: Annotated[TensorType, ...]) → Annotated[TensorType, ...][source]

Splits the axis axis of inp into a part of the shape of like.

Parameters:
  • inp (TensorType) – Tensor whose axis is split, e.g. the flattened spatial axes. Its size must be the product of the restored shape.

  • like (TensorType) – Tensor that provides the shape to restore.

Returns:

inp with the axis replaced by

like.shape[start_dim:end_dim].

Return type:

TensorType

class qewton.algorithms.building_blocks.array_operations.GetShapeNode(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Get shape node that returns the shape tuple of the input tensor. Has one input port and one output port.

forward(x: Annotated[TensorType, ...]) → Annotated[tuple[int, ...], ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

qewton.algorithms.building_blocks.channel_mlp module

Channel-wise multi-layer perceptron.

class qewton.algorithms.building_blocks.channel_mlp.ChannelMLP(in_channels: int | HyperParameter, out_channels: int | HyperParameter | None = None, hidden_channels: int | HyperParameter | None = None, n_layers: int | HyperParameter = 2, non_linearity: type[Node] | HyperParameter = <class 'qewton.algorithms.building_blocks.activation_functions.GELU'>, name: str = 'channel_mlp', backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: GraphNode, Generic[TensorType]

A multi-layer perceptron applied to the channels of an input.

For an input of shape (batch, in_channels, x_1, …, x_n) the same MLP is applied to the channels at every position (a stack of 1x1 convolutions).

in_channels, out_channels, hidden_channels, n_layers, non_linearity

(HyperParameter): The arguments of the same name, each stored as a hyperparameter.

Parameters:
  • in_channels (int | HyperParameter) – Number of input channels.

  • out_channels (int | HyperParameter | None, optional) – Number of output channels. Defaults to in_channels.

  • hidden_channels (int | HyperParameter | None, optional) – Number of channels between the layers. Defaults to in_channels.

  • n_layers (int | HyperParameter, optional) – Number of linear layers. The non-linearity is applied between the layers, not after the last one. With a single layer the MLP is just one linear map from in_channels to out_channels. Defaults to 2.

  • non_linearity (type[Node] | HyperParameter, optional) – The non-linearity between the layers. Defaults to GELU.

  • name (str, optional) – Name of the node. Defaults to “channel_mlp”.

  • backend (type[Backend[TensorType]], optional) – The backend used for the computations. Defaults to DEFAULT_DL_BACKEND.

Raises:
  • ValueError – If a number of channels or layers is not positive.

  • TypeError – If non_linearity is not a node class.

property hyperparameters: list[HyperParameter]

Collects and returns all hyperparameters from the nodes within the encapsulated graph.

Returns:

A list of all hyperparameters found in the inner graph.

Return type:

list[HyperParameter]

build() → None[source]

Builds the network for the current hyperparameter values, with newly initialized weights.

forward(x: TensorType) → TensorType[source]

Applies the MLP to the channels at every position.

Parameters:

x (TensorType) – Input of shape (batch, in_channels, *spatial_dims).

Returns:

Output of shape (batch, out_channels, *spatial_dims).

Return type:

TensorType

qewton.algorithms.building_blocks.conv module

class qewton.algorithms.building_blocks.conv.FunctionalConv(dim: ~typing.Literal[1, 2, 3], stride: int | tuple[int, ...] = 1, padding: int | tuple[int, ...] = 0, dilation: int | tuple[int, ...] = 1, groups: int = 1, name: str = 'FunctionalConvolution', state: ~qewton.graphs.nodes.NodeState = NodeState.FIXED, backend: type[~qewton.backends.base.DeepLearningBackend[~qewton.backends.base.TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: Node[TensorType]

A functional convolution layer, using the same arguments as the convolution node.

upgrade(version: int) → None[source]

See upgrade(); the axes of files of version 1 relate the sizes differently, so they are declared anew.

Parameters:

version – The format version of the file.

x_data_config()[source]
weight_data_config()[source]
bias_data_config()[source]
out_data_config()[source]
forward(x: ~typing.Annotated[~qewton.backends.base.TensorType, <function FunctionalConv.x_data_config at 0x7c052e6f9b20>], weight: ~typing.Annotated[~qewton.backends.base.TensorType, <function FunctionalConv.weight_data_config at 0x7c052e6f8fe0>], bias: ~typing.Annotated[~qewton.backends.base.TensorType, <function FunctionalConv.bias_data_config at 0x7c052e6f9bc0>] = None) → out_data_config at 0x7c052e6fb7e0>][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

load(serializer: Deserializer, data_config: dict) → None[source]

Load the node state and give it a node ID unique in this session.

Parameters:
  • serializer – The deserializer managing the loading process.

  • data_config – The serialized data of this node.

class qewton.algorithms.building_blocks.conv.Conv(in_channels: int | HyperParameter, out_channels: int | HyperParameter, kernel_size: int | tuple[int | ~qewton.optim.parameters.hyperparameter_base.HyperParameter, ...] | ~qewton.optim.parameters.hyperparameter_base.HyperParameter, bias: bool = True, stride: int | tuple[int, ...]=1, padding: int | tuple[int, ...]=0, dilation: int | tuple[int, ...]=1, groups: int = 1, name: str = 'Convolution', backend: type[DeepLearningBackend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: GraphNode, Generic[TensorType]

A node implementing a convolution operation. The dimension of the convolution is automatically determined from the specified kernel size.

Parameters:
  • in_channels (int | HyperParameter) – The number of input channels.

  • out_channels (int | HyperParameter) – The number of output channels.

  • kernel_size (int | tuple[int | HyperParameter, ...] | HyperParameter) – The size of the convolution kernel. The dimension of the convolution is determined by the length of the tuple (or set to 1 in case of an integer).

  • bias (bool, optional) – If a bias should be included. Defaults to True.

  • stride (int | tuple[int, ...], optional) – Controls the stride for the cross-correlation. Defaults to 1.

  • padding (int | tuple[int, ...], optional) – The amount of padding applied to each axis of the input. Defaults to 0.

  • dilation (int | tuple[int, ...], optional) – The spacing between kernel points. Defaults to 1, so direct neighbors are taken.

  • groups (int, optional) – The connections between inputs and outputs. Both input and output channels are divided into groups, and convolutions are applied separately to each group. The output is the concatenation of all the groups. Defaults to 1.

  • backend (type[DeepLearningBackend[TensorType]], optional) – Defaults to DEFAULT_DL_BACKEND.

forward(x)[source]

Evaluate the inner graph on the inputs.

Subclasses override this method only to declare the data configurations of their ports with typing.Annotated; the body stays return super().forward(...). Inside a graph, the steps of the inner graph run in place of this node instead.

Parameters:
  • *args – The values of the input ports, in order.

  • **kwargs – The values of input ports by name.

Returns:

The value of the output port, or a tuple for several.

Return type:

Any

Raises:

RuntimeError – If the node is not built and waits for sizes to be inferred from connected data.

class qewton.algorithms.building_blocks.conv.Conv1D(in_channels: int | ~qewton.optim.parameters.hyperparameter_base.HyperParameter, out_channels: int | ~qewton.optim.parameters.hyperparameter_base.HyperParameter, kernel_size: int | ~qewton.optim.parameters.hyperparameter_base.HyperParameter | tuple[int | ~qewton.optim.parameters.hyperparameter_base.HyperParameter], bias: bool = True, stride: int | tuple[int] = 1, padding: int | tuple[int] = 0, dilation: int | tuple[int] = 1, groups: int = 1, backend: type[~qewton.backends.base.DeepLearningBackend[~qewton.backends.base.TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Conv[TensorType]

class qewton.algorithms.building_blocks.conv.Conv2D(in_channels: int | ~qewton.optim.parameters.hyperparameter_base.HyperParameter, out_channels: int | ~qewton.optim.parameters.hyperparameter_base.HyperParameter, kernel_size: int | ~qewton.optim.parameters.hyperparameter_base.HyperParameter | tuple[int | ~qewton.optim.parameters.hyperparameter_base.HyperParameter, int | ~qewton.optim.parameters.hyperparameter_base.HyperParameter], bias: bool = True, stride: int | tuple[int, int] = 1, padding: int | tuple[int, int] = 0, dilation: int | tuple[int, int] = 1, groups: int = 1, backend: type[~qewton.backends.base.DeepLearningBackend[~qewton.backends.base.TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Conv[TensorType]

class qewton.algorithms.building_blocks.conv.Conv3D(in_channels: int | ~qewton.optim.parameters.hyperparameter_base.HyperParameter, out_channels: int | ~qewton.optim.parameters.hyperparameter_base.HyperParameter, kernel_size: int | ~qewton.optim.parameters.hyperparameter_base.HyperParameter | tuple[int | ~qewton.optim.parameters.hyperparameter_base.HyperParameter, int | ~qewton.optim.parameters.hyperparameter_base.HyperParameter, int | ~qewton.optim.parameters.hyperparameter_base.HyperParameter], bias: bool = True, stride: int | tuple[int, int, int] = 1, padding: int | tuple[int, int, int] = 0, dilation: int | tuple[int, int, int] = 1, groups: int = 1, backend: type[~qewton.backends.base.DeepLearningBackend[~qewton.backends.base.TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Conv[TensorType]

class qewton.algorithms.building_blocks.conv.DoubleConv(in_channels: int | HyperParameter, out_channels: int | HyperParameter, kernel_size: int | tuple[int, ...] | ~qewton.optim.parameters.hyperparameter_base.HyperParameter, activation: type[Node] | HyperParameter = <class 'qewton.algorithms.building_blocks.activation_functions.ReLU'>, bias: bool | HyperParameter = True, stride: int | ~qewton.optim.parameters.hyperparameter_base.HyperParameter | tuple[int, ...]=1, padding: int | ~qewton.optim.parameters.hyperparameter_base.HyperParameter | tuple[int, ...]=0, dilation: int | ~qewton.optim.parameters.hyperparameter_base.HyperParameter | tuple[int, ...]=1, groups: int = 1, name='DoubleConv', backend: type[DeepLearningBackend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: GraphNode, Generic[TensorType]

A node implementing two convolution operations in sequence. The dimension of the convolution is automatically determined from the specified kernel size.

Parameters:
  • in_channels (int | HyperParameter) – The number of input channels.

  • out_channels (int | HyperParameter) – The number of output channels.

  • kernel_size (int | tuple[int | HyperParameter, ...] | HyperParameter) – The size of the convolution kernel. The dimension of the convolution is determined by the length of the tuple (or set to 1 in case of an integer).

  • activation – type[Node] | HyperParameter = ReLU,

  • bias (bool, optional) – If a bias should be included. Defaults to True.

  • stride (int | tuple[int, ...], optional) – Controls the stride for the cross-correlation. Defaults to 1.

  • padding (int | tuple[int, ...], optional) – The amount of padding applied to each axis of the input. Defaults to 0.

  • dilation (int | tuple[int, ...], optional) – The spacing between kernel points. Defaults to 1, so direct neighbors are taken.

  • groups (int, optional) – The connections between inputs and outputs. Both input and output channels are divided into groups, and convolutions are applied separately to each group. The output is the concatenation of all the groups. Defaults to 1.

  • backend (type[DeepLearningBackend[TensorType]], optional) – Defaults to DEFAULT_DL_BACKEND.

reset()[source]

Make this node and every node of its inner graph unbuilt (see Node.reset()).

property hyperparameters: list[HyperParameter]

Collects and returns all hyperparameters from the nodes within the encapsulated graph.

Returns:

A list of all hyperparameters found in the inner graph.

Return type:

list[HyperParameter]

build() → None[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.

forward(x)[source]

Evaluate the inner graph on the inputs.

Subclasses override this method only to declare the data configurations of their ports with typing.Annotated; the body stays return super().forward(...). Inside a graph, the steps of the inner graph run in place of this node instead.

Parameters:
  • *args – The values of the input ports, in order.

  • **kwargs – The values of input ports by name.

Returns:

The value of the output port, or a tuple for several.

Return type:

Any

Raises:

RuntimeError – If the node is not built and waits for sizes to be inferred from connected data.

class qewton.algorithms.building_blocks.conv.Flattened1dConv(in_channels: int | HyperParameter, out_channels: int | HyperParameter, kernel_size: int, bias: bool = False, backend: type[DeepLearningBackend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, name: str = 'flattened_1d_conv')[source]

Bases: GraphNode[TensorType]

A 1D convolution for inputs of shape (batch, channels, x_1, …, x_n).

All spatial dimensions are flattened into one, the 1D convolution is applied to the flattened input, and the spatial dimensions are restored. Only kernel_size=1 is supported, which applies the same linear map to the channels at every position of the domain.

The flattening and restoring are nodes of the inner graph (instead of reshapes in forward), so they are also executed when this node is a part of another graph, and the parameters of the convolution are visible to that graph.

conv

The convolution applied to the flattened input.

Type:

Conv1D

Parameters:
  • in_channels (int | HyperParameter) – Number of input channels.

  • out_channels (int | HyperParameter) – Number of output channels.

  • kernel_size (int) – Size of the convolution kernel. Only 1 is supported, since a larger kernel changes the length of the flattened axis.

  • bias (bool, optional) – If the convolution has a bias. Defaults to False.

  • backend (type[DeepLearningBackend[TensorType]], optional) – The backend used for the computations. Defaults to DEFAULT_DL_BACKEND.

  • name (str, optional) – Name of the node. Defaults to “flattened_1d_conv”.

Note

Weight and bias are initialized like torch.nn.Conv1d, i.e. uniformly in [-1/sqrt(in_channels), 1/sqrt(in_channels)].

Raises:

ValueError – If kernel_size is not 1.

FIRST_SPATIAL_AXIS = 2
x_data_config() → DataConfiguration[source]
out_data_config() → DataConfiguration[source]
forward(x: ~typing.Annotated[~qewton.backends.base.TensorType, <function Flattened1dConv.x_data_config at 0x7c052e52c400>]) → out_data_config at 0x7c052e52c4a0>][source]

Applies the convolution along the flattened spatial axes.

Parameters:

x (TensorType) – Input of shape (batch, in_channels, x_1, …, x_n).

Returns:

Output of shape (batch, out_channels, x_1, …, x_n).

Return type:

TensorType

class qewton.algorithms.building_blocks.conv.PoolingNode(kernel_size: tuple[int, ...], name: str | None = None, state: ~qewton.graphs.nodes.NodeState = NodeState.FIXED, backend: type[~qewton.backends.base.DeepLearningBackend[~qewton.backends.base.TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: Node[TensorType]

Helper node to combine some syntax that appears in every pooling node.

backend: type[DeepLearningBackend[TensorType]]
upgrade(version: int) → None[source]

See upgrade(); the axes of files of version 1 relate the sizes differently, so they are declared anew.

Parameters:

version – The format version of the file.

in_data_config()[source]
out_data_config()[source]
class qewton.algorithms.building_blocks.conv.MaxPool1D(kernel_size: int | tuple[int, ...], stride: int | tuple[int, ...] | None = None, padding: int | tuple[int, ...] = 0, dilation: int | tuple[int, ...] = 1, name: str | None = 'MaxPooling', backend: type[~qewton.backends.base.DeepLearningBackend[~qewton.backends.base.TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: PoolingNode[TensorType]

A pooling node, which reduces the size of the input by taking the maximum value in each kernel window.

Parameters:
  • kernel_size (int | tuple[int, ...]) – The size of the pooling kernel.

  • stride (int | tuple[int, ...] | None, optional) – Stride for pooling. Defaults to None.

  • padding (int | tuple[int, ...], optional) – Additionally padding at the boundary. Defaults to 0.

  • dilation (int | tuple[int, ...], optional) – Dilation for the pooling window. Defaults to 1.

in_data_config()[source]
out_data_config()[source]
forward(x: ~typing.Annotated[~qewton.backends.base.TensorType, <function MaxPool1D.in_data_config at 0x7c052e52cae0>]) → out_data_config at 0x7c052e52cb80>][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.conv.MaxPool2D(kernel_size: int | tuple[int, ...], stride: int | tuple[int, ...] | None = None, padding: int | tuple[int, ...] = 0, dilation: int | tuple[int, ...] = 1, name: str | None = 'MaxPooling', backend: type[~qewton.backends.base.DeepLearningBackend[~qewton.backends.base.TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: MaxPool1D[TensorType]

in_data_config()[source]
out_data_config()[source]
forward(x: ~typing.Annotated[~qewton.backends.base.TensorType, <function MaxPool2D.in_data_config at 0x7c052e52ce00>]) → out_data_config at 0x7c052e52cea0>][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.conv.MaxPool3D(kernel_size: int | tuple[int, ...], stride: int | tuple[int, ...] | None = None, padding: int | tuple[int, ...] = 0, dilation: int | tuple[int, ...] = 1, name: str | None = 'MaxPooling', backend: type[~qewton.backends.base.DeepLearningBackend[~qewton.backends.base.TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: MaxPool1D[TensorType]

in_data_config()[source]
out_data_config()[source]
forward(x: ~typing.Annotated[~qewton.backends.base.TensorType, <function MaxPool3D.in_data_config at 0x7c052e52d120>]) → out_data_config at 0x7c052e52d1c0>][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.conv.AvgPool1D(kernel_size: int | tuple[int, ...], stride: int | tuple[int, ...] | None = None, padding: int | tuple[int, ...] = 0, count_include_pad: bool = True, name: str | None = 'AvgPooling', backend: type[~qewton.backends.base.DeepLearningBackend[~qewton.backends.base.TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: PoolingNode[TensorType]

A pooling node, which reduces the size of the input by taking the average value in the kernel window.

Parameters:
  • kernel_size (int | tuple[int, ...]) – The size of the pooling kernel.

  • stride (int | tuple[int, ...] | None, optional) – Stride for pooling. Defaults to None.

  • padding (int | tuple[int, ...], optional) – Additionally padding at the boundary. Defaults to 0.

  • dilation (int | tuple[int, ...], optional) – Dilation for the pooling window. Defaults to 1.

  • count_include_pad (bool, optional) – Whether to include the padding in the average calculation. Defaults to True.

upgrade(version: int) → None[source]

See upgrade(); files of version 1 have no dilation yet.

Parameters:

version – The format version of the file.

in_data_config()[source]
out_data_config()[source]
forward(x: ~typing.Annotated[~qewton.backends.base.TensorType, <function AvgPool1D.in_data_config at 0x7c052e52d4e0>]) → out_data_config at 0x7c052e52d580>][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.conv.AvgPool2D(kernel_size: int | tuple[int, ...], stride: int | tuple[int, ...] | None = None, padding: int | tuple[int, ...] = 0, count_include_pad: bool = True, name: str | None = 'AvgPooling', backend: type[~qewton.backends.base.DeepLearningBackend[~qewton.backends.base.TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: AvgPool1D[TensorType]

in_data_config()[source]
out_data_config()[source]
forward(x: ~typing.Annotated[~qewton.backends.base.TensorType, <function AvgPool2D.in_data_config at 0x7c052e52d760>]) → out_data_config at 0x7c052e52d800>][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.conv.AvgPool3D(kernel_size: int | tuple[int, ...], stride: int | tuple[int, ...] | None = None, padding: int | tuple[int, ...] = 0, count_include_pad: bool = True, name: str | None = 'AvgPooling', backend: type[~qewton.backends.base.DeepLearningBackend[~qewton.backends.base.TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: AvgPool1D[TensorType]

in_data_config()[source]
out_data_config()[source]
forward(x: ~typing.Annotated[~qewton.backends.base.TensorType, <function AvgPool3D.in_data_config at 0x7c052e52da80>]) → out_data_config at 0x7c052e52db20>][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.conv.Interpolate(size: int | tuple[int] | tuple[int, int] | tuple[int, int, int] | None=None, scale_factor: int | tuple[int] | tuple[int, int] | tuple[int, int, int] | None=None, interpolate_mode: Literal['nearest', 'linear', 'bilinear', 'bicubic', 'trilinear']='nearest', align_corners: bool | None = None, name: str = 'InterpolateNode', backend: type[DeepLearningBackend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: Node[TensorType]

A node that interpolates a given tensor to a new shape. Expected inputs are 3-D, 4-D or 5-D in shape. E.g (batch, feature, width, [height, depth]), where the last to axis are optional.

Parameters:
  • size (int | tuple[int...] | None, optional) – The output spatial size. Defaults to None.

  • scale_factor (int | tuple[int...] | None, optional) – A multiplier for the spatial size. The scale_factor has to fit the the number of spatial dimensions. Defaults to None. Either size or the scale_factor need to be provided.

  • &quot;nearest&quot; (interpolate_mode (Literal[) –

    &quot;bilinear&quot;, &quot;bicubic&quot;,

    &quot;trilinear&quot; ], optional):

    The type of interpolation scheme to use. Defaults to “nearest”.

  • &quot;linear&quot; –

    &quot;bilinear&quot;, &quot;bicubic&quot;,

    &quot;trilinear&quot; ], optional):

    The type of interpolation scheme to use. Defaults to “nearest”.

:param&quot;bilinear&quot;, &quot;bicubic&quot;,

&quot;trilinear&quot; ], optional):

The type of interpolation scheme to use. Defaults to “nearest”.

Parameters:
  • align_corners (bool, optional) – If the pixel data should be aligned along corners. Defaults to False.

  • name (str, optional) – Name of the node. Defaults to “InterpolateNode”.

  • backend (type[DeepLearningBackend[TensorType]], optional) – Defaults to DEFAULT_DL_BACKEND.

backend: DeepLearningBackend
in_data_config()[source]
out_data_config()[source]
forward(x: ~typing.Annotated[~qewton.backends.base.TensorType, <function Interpolate.in_data_config at 0x7c052e52dd00>], size: ~typing.Annotated[int | tuple[int] | tuple[int, int] | tuple[int, int, int] | None, <qewton.config.axes.FeatureAxes object at 0x7c052e6aa1e0>] = None) → out_data_config at 0x7c052e52dda0>][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.conv.FunctionalBatchNorm(dim: ~typing.Literal[1, 2, 3], momentum: float = 0.1, eps: float = 1e-05, name: str = 'FunctionalBatchNorm', backend: type[~qewton.backends.base.DeepLearningBackend[~qewton.backends.base.TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: Node[TensorType]

A node implementing a batch normalization operation for 1D data.

Parameters:
  • dim (Literal[1, 2, 3]) – The dimension of the input data.

  • momentum (float, optional) – The momentum used to update the running bias. Defaults to 0.1.

  • eps (float, optional) – A tolerance added to the variance normalization. Defaults to 1e-5.

  • name (str, optional) – Name of the node. Defaults to “BatchNorm1D”.

  • backend (type[DeepLearningBackend[TensorType]], optional) – Defaults to DEFAULT_DL_BACKEND.

set_mode(new_mode: EvaluationPhase)[source]

Set the current evaluation phase.

Some nodes behave differently depending on the phase, e.g. dropout is disabled during validation.

Parameters:

new_mode – The new evaluation phase.

data_config()[source]
parameter_data_config()[source]
forward(x: ~typing.Annotated[~qewton.backends.base.TensorType, <function FunctionalBatchNorm.data_config at 0x7c052e52e0c0>], running_mean: ~typing.Annotated[~qewton.backends.base.TensorType, <function FunctionalBatchNorm.parameter_data_config at 0x7c052e52e160>], running_var: ~typing.Annotated[~qewton.backends.base.TensorType, <function FunctionalBatchNorm.parameter_data_config at 0x7c052e52e160>], weight: ~typing.Annotated[~qewton.backends.base.TensorType, <function FunctionalBatchNorm.parameter_data_config at 0x7c052e52e160>] = None, bias: ~typing.Annotated[~qewton.backends.base.TensorType, <function FunctionalBatchNorm.parameter_data_config at 0x7c052e52e160>] = None) → data_config at 0x7c052e52e0c0>][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

load(serializer: Deserializer, data_config: dict) → None[source]

Load the node state and give it a node ID unique in this session.

Parameters:
  • serializer – The deserializer managing the loading process.

  • data_config – The serialized data of this node.

class qewton.algorithms.building_blocks.conv.BatchNorm(num_features: int | ~qewton.optim.parameters.hyperparameter_base.HyperParameter, dim: ~typing.Literal[1, 2, 3], weight: bool = False, bias: bool = False, momentum: float = 0.1, eps: float = 1e-05, name: str = 'BatchNorm', backend: type[~qewton.backends.base.DeepLearningBackend[~qewton.backends.base.TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: GraphNode, Generic[TensorType]

A node implementing a batch normalization operation for 1D data.

Parameters:
  • num_features (int | HyperParameter) – The number of features in the input data.

  • dim (Literal[1, 2, 3]) – The dimension of the input data.

  • weight (bool, optional) – If a trainable weight should be added. Defaults to False.

  • bias (bool, optional) – If a trainable bias should be added. Defaults to False.

  • momentum (float, optional) – The momentum used to update the running bias. Defaults to 0.1.

  • eps (float, optional) – A tolerance added to the variance normalization. Defaults to 1e-5.

  • name (str, optional) – Name of the node. Defaults to “BatchNorm”.

  • backend (type[DeepLearningBackend[TensorType]], optional) – Defaults to DEFAULT_DL_BACKEND.

reset()[source]

Make this node and every node of its inner graph unbuilt (see Node.reset()).

build() → None[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.

forward(x)[source]

Evaluate the inner graph on the inputs.

Subclasses override this method only to declare the data configurations of their ports with typing.Annotated; the body stays return super().forward(...). Inside a graph, the steps of the inner graph run in place of this node instead.

Parameters:
  • *args – The values of the input ports, in order.

  • **kwargs – The values of input ports by name.

Returns:

The value of the output port, or a tuple for several.

Return type:

Any

Raises:

RuntimeError – If the node is not built and waits for sizes to be inferred from connected data.

class qewton.algorithms.building_blocks.conv.BatchNorm1D(num_features: int, weight: bool = False, bias: bool = False, momentum: float = 0.1, eps: float = 1e-05, name: str = 'BatchNorm1D', backend: type[DeepLearningBackend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: BatchNorm[TensorType]

A node implementing a batch normalization operation for 1D data.

Parameters:
  • num_features (int| HyperParameter) – The number of features in the input data.

  • weight (bool, optional) – If a trainable weight should be added. Defaults to False.

  • bias (bool, optional) – If a trainable bias should be added. Defaults to False.

  • momentum (float, optional) – The momentum used to update the running bias. Defaults to 0.1.

  • eps (float, optional) – A tolerance added to the variance normalization. Defaults to 1e-5.

  • name (str, optional) – Name of the node. Defaults to “BatchNorm1D”.

  • backend (type[DeepLearningBackend[TensorType]], optional) – Defaults to DEFAULT_DL_BACKEND.

class qewton.algorithms.building_blocks.conv.BatchNorm2D(num_features: int, weight: bool = False, bias: bool = False, momentum: float = 0.1, eps: float = 1e-05, name: str = 'BatchNorm2D', backend: type[DeepLearningBackend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: BatchNorm[TensorType]

A node implementing a batch normalization operation for 2D data.

Parameters:
  • num_features (int | HyperParameter) – The number of features in the input data.

  • weight (bool, optional) – If a trainable weight should be added. Defaults to False.

  • bias (bool, optional) – If a trainable bias should be added. Defaults to False.

  • momentum (float, optional) – The momentum used to update the running bias. Defaults to 0.1.

  • eps (float, optional) – A tolerance added to the variance normalization. Defaults to 1e-5.

  • name (str, optional) – Name of the node. Defaults to “BatchNorm2D”.

  • backend (type[DeepLearningBackend[TensorType]], optional) – Defaults to DEFAULT_DL_BACKEND.

class qewton.algorithms.building_blocks.conv.BatchNorm3D(num_features: int, weight: bool = False, bias: bool = False, momentum: float = 0.1, eps: float = 1e-05, name: str = 'BatchNorm3D', backend: type[DeepLearningBackend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: BatchNorm[TensorType]

A node implementing a batch normalization operation for 3D data.

Parameters:
  • num_features (int | HyperParameter) – The number of features in the input data.

  • weight (bool, optional) – If a trainable weight should be added. Defaults to False.

  • bias (bool, optional) – If a trainable bias should be added. Defaults to False.

  • momentum (float, optional) – The momentum used to update the running bias. Defaults to 0.1.

  • eps (float, optional) – A tolerance added to the variance normalization. Defaults to 1e-5.

  • name (str, optional) – Name of the node. Defaults to “BatchNorm3D”.

  • backend (type[DeepLearningBackend[TensorType]], optional) – Defaults to DEFAULT_DL_BACKEND.

qewton.algorithms.building_blocks.creation module

class qewton.algorithms.building_blocks.creation.Identity(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

A node that just returns the provided input. Helpful to track some operations and and inputs.

ell_axis = <qewton.config.axes.EllipsisAxes object>
forward(x: Annotated[TensorType, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.creation.Zeros(shape: int | tuple[int, ...], name: str | None = None, state: ~qewton.graphs.nodes.NodeState = NodeState.FIXED, backend: type[~qewton.backends.base.Backend[~qewton.backends.base.TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: Node[TensorType]

forward() → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.creation.ZerosLike(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

ellipsis_dims = <qewton.config.axes.EllipsisAxes object>
forward(x: Annotated[TensorType, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.creation.Ones(shape: int | tuple[int, ...], name: str | None = None, state: ~qewton.graphs.nodes.NodeState = NodeState.FIXED, backend: type[~qewton.backends.base.Backend[~qewton.backends.base.TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: Node[TensorType]

forward() → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.creation.OnesLike(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

ellipsis_dims = <qewton.config.axes.EllipsisAxes object>
forward(x: Annotated[TensorType, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

qewton.algorithms.building_blocks.derivatives module

class qewton.algorithms.building_blocks.derivatives.GradientTracking(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

ell_axes = <qewton.config.axes.EllipsisAxes object>
forward(inp: Annotated[TensorType, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.derivatives.Gradient(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

ell_axes = <qewton.config.axes.EllipsisAxes object>
x_dim = <qewton.config.axes.AxesDim object>
forward(u: Annotated[TensorType, ..., FeatureAxes([1])], x: Annotated[TensorType, ..., FeatureAxes([None])]) → Annotated[TensorType, ..., FeatureAxes([None])][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.derivatives.Laplacian(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Computes the laplacian (sum of second derivatives) of a scalar output with respect to the input variable.

ell_axes = <qewton.config.axes.EllipsisAxes object>
forward(u: Annotated[TensorType, ..., FeatureAxes([1])], x: Annotated[TensorType, ..., FeatureAxes([None])]) → Annotated[TensorType, ..., FeatureAxes([1])][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.derivatives.NormalDerivative(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Computes the normal derivative (gradient · normals) of a scalar output.

ell_axes = <qewton.config.axes.EllipsisAxes object>
x_dim = <qewton.config.axes.AxesDim object>
u_dim = <qewton.config.axes.AxesDim object>
forward(u: Annotated[TensorType, ..., FeatureAxes([1])], normals: Annotated[TensorType, ..., FeatureAxes([None])], x: Annotated[TensorType, ..., FeatureAxes([None])]) → Annotated[TensorType, ..., FeatureAxes([1])][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.derivatives.Divergence(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Computes the divergence of a vector field (model output) with respect to spatial variables.

ell_axes = <qewton.config.axes.EllipsisAxes object>
x_dim = <qewton.config.axes.AxesDim object>
forward(u: Annotated[TensorType, ..., FeatureAxes([None])], x: Annotated[TensorType, ..., FeatureAxes([None])]) → Annotated[TensorType, ..., FeatureAxes([1])][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.derivatives.Jacobian(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Computes the Jacobian matrix of a vector output with respect to input variables.

ell_axes = <qewton.config.axes.EllipsisAxes object>
x_dim = <qewton.config.axes.AxesDim object>
forward(u: Annotated[TensorType, ..., FeatureAxes([None])], x: Annotated[TensorType, ..., FeatureAxes([None])]) → Annotated[TensorType, ..., FeatureAxes([None, None])][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.derivatives.Partial(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Computes n-th order partial derivatives recursively with respect to multiple variables.

ell_axes = <qewton.config.axes.EllipsisAxes object>
x_dim = <qewton.config.axes.AxesDim object>
forward(u: Annotated[TensorType, ..., FeatureAxes([1])], x: Annotated[TensorType, ..., FeatureAxes([None])]) → Annotated[TensorType, ..., FeatureAxes([None])][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.derivatives.Hessian(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Computes the Hessian matrix (second partial derivatives) of a scalar output.

ell_axes = <qewton.config.axes.EllipsisAxes object>
x_dim = <qewton.config.axes.AxesDim object>
forward(u: Annotated[TensorType, ..., FeatureAxes([1])], x: Annotated[TensorType, ..., FeatureAxes([None])]) → Annotated[TensorType, ..., FeatureAxes([None, None])][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.derivatives.MatrixDivergence(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Computes the row-wise divergence of a matrix-valued field.

The output is a vector containing the divergence of each row of the matrix field with respect to the spatial input.

ell_axes = <qewton.config.axes.EllipsisAxes object>
u_dim = <qewton.config.axes.AxesDim object>
x_dim = <qewton.config.axes.AxesDim object>
forward(u: Annotated[TensorType, ..., FeatureAxes([None, None])], x: Annotated[TensorType, ..., FeatureAxes([None])]) → Annotated[TensorType, ..., FeatureAxes([None])][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.derivatives.Rotation(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Computes the curl/rotation of a 3D vector field.

ell_axes = <qewton.config.axes.EllipsisAxes object>
x_dim = <qewton.config.axes.AxesDim object>
forward(u: Annotated[TensorType, ..., FeatureAxes([3])], x: Annotated[TensorType, ..., FeatureAxes([3])]) → Annotated[TensorType, ..., FeatureAxes([3])][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.derivatives.SymmetricGradient(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Computes the symmetric gradient 0.5 * (∇u + (∇u)^T).

ell_axes = <qewton.config.axes.EllipsisAxes object>
u_dim = <qewton.config.axes.AxesDim object>
x_dim = <qewton.config.axes.AxesDim object>
forward(u: Annotated[TensorType, ..., FeatureAxes([None])], x: Annotated[TensorType, ..., FeatureAxes([None])]) → Annotated[TensorType, ..., FeatureAxes([None, None])][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

qewton.algorithms.building_blocks.embeddings module

Positional embeddings.

class qewton.algorithms.building_blocks.embeddings.GridEmbeddingND(in_channels: int, dim: int = 2, grid_boundaries: tuple[tuple[float, float], ...] | None = None, name: str = 'grid_embedding', backend: type[~qewton.backends.base.Backend[~qewton.backends.base.TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: Node[TensorType]

Positional embedding that appends the coordinates of a regular grid as channels.

An input of shape (batch, in_channels, x_1, …, x_dim) is mapped to (batch, in_channels + dim, x_1, …, x_dim). The coordinates along dimension i are linspace(start, stop, x_i + 1)[:-1], i.e. the right boundary is excluded (periodic domain).

out_channels

Number of channels of the output, in_channels + dim.

Type:

int

Parameters:
  • in_channels (int) – Number of channels of the input.

  • dim (int, optional) – Number of spatial dimensions. Defaults to 2.

  • grid_boundaries (tuple[tuple[float, float], ...] | None, optional) – The (start, stop) of the grid along every dimension. Defaults to the unit cube, ((0, 1),) * dim.

  • name (str, optional) – Name of the node. Defaults to “grid_embedding”.

  • backend (type[Backend[TensorType]], optional) – The backend used for the computations. Defaults to DEFAULT_DL_BACKEND.

Raises:

ValueError – If grid_boundaries does not have one entry per dimension, or if the input of forward has a different number of dimensions or channels.

property out_channels: int

the input channels plus one per dimension.

Type:

Number of output channels

x_data_config() → DataConfiguration[source]
out_data_config() → DataConfiguration[source]
forward(data: ~typing.Annotated[~qewton.backends.base.TensorType, <function GridEmbeddingND.x_data_config at 0x7c052e51e840>]) → out_data_config at 0x7c052e51e8e0>][source]

Appends the grid coordinates to the channels of the input.

Parameters:

data (TensorType) – Input of shape (batch, in_channels, x_1, …, x_dim).

Returns:

Tensor of shape (batch, in_channels + dim, x_1, …, x_dim)

with the coordinates in the last dim channels.

Return type:

TensorType

qewton.algorithms.building_blocks.fno_block module

Fourier layer of Fourier Neural Operators.

class qewton.algorithms.building_blocks.fno_block.FNOBlock(in_channels: int | HyperParameter, out_channels: int | HyperParameter, n_modes: tuple[int, ...] | ~qewton.optim.parameters.hyperparameter_base.HyperParameter, use_channel_mlp: bool | HyperParameter = True, channel_mlp_expansion: float | HyperParameter = 0.5, non_linearity: type[Node] | HyperParameter | None = <class 'qewton.algorithms.building_blocks.activation_functions.GELU'>, fno_skip: Literal['soft-gating', 'linear', 'identity'] | ~qewton.optim.parameters.hyperparameter_base.HyperParameter | None='linear', channel_mlp_skip: Literal['soft-gating', 'linear', 'identity'] | ~qewton.optim.parameters.hyperparameter_base.HyperParameter | None='soft-gating', conv_bias: bool | HyperParameter = True, init_std: float | Literal['auto'] | HyperParameter = 'auto', fft_norm: Literal['forward', 'backward', 'ortho'] | ~qewton.optim.parameters.hyperparameter_base.HyperParameter='forward', name: str = 'fno_block', backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: GraphNode, Generic[TensorType]

A single Fourier layer.

Computes:

x = non_linearity(conv(x) + fno_skip(x))
if use_channel_mlp:
    x = channel_mlp(x) + channel_mlp_skip(x)
x = non_linearity(x)

where the skip connections are applied to the input of the block. If non_linearity is None, no non-linearity is applied, as in the last layer of an FNO. As in neuraloperator, the second non-linearity is applied also without a channel MLP. The channel MLP always uses GELU between its two layers.

All arguments but name and backend can be hyperparameters. The network is rebuilt for their current values when the node is built (build), with newly initialized weights.

in_channels, out_channels, n_modes, use_channel_mlp, channel_mlp_expansion,

non_linearity, fno_skip, channel_mlp_skip, conv_bias, init_std, fft_norm (HyperParameter): The arguments of the same name, each stored as a hyperparameter.

batch_axes, geo_axes, channel_dim_in, channel_dim_out

Shape information of the data configurations.

input_node

Distributes the input to the parallel branches.

Type:

Identity

conv

The spectral convolution.

Type:

SpectralConv

fno_skip_connection

Skip connection around the spectral convolution.

Type:

Node | None

fno_non_linearity

Non-linearity after the spectral convolution.

Type:

Node | None

channel_mlp

The channel MLP.

Type:

ChannelMLP | None

channel_mlp_skip_connection

Skip connection around the channel MLP.

Type:

Node | None

post_non_linearity

Non-linearity after the channel MLP, or after the spectral convolution if there is no channel MLP.

Type:

Node | None

Parameters:
  • in_channels (int | HyperParameter) – Number of input channels.

  • out_channels (int | HyperParameter) – Number of output channels.

  • n_modes (tuple[int, ...] | HyperParameter) – Number of Fourier modes kept in every spatial dimension.

  • use_channel_mlp (bool | HyperParameter, optional) – If a channel MLP follows the spectral convolution. Defaults to True.

  • channel_mlp_expansion (float | HyperParameter, optional) – The channel MLP has round(out_channels * channel_mlp_expansion) hidden channels. Defaults to 0.5.

  • non_linearity (type[Node] | HyperParameter | None, optional) – Non-linearity applied after the spectral convolution and after the channel MLP; None applies none. Defaults to GELU.

  • fno_skip (SkipType | HyperParameter | None, optional) – Skip connection around the spectral convolution; None for no skip connection. “soft-gating” and “identity” require in_channels == out_channels, also for channel_mlp_skip. Defaults to “linear”.

  • channel_mlp_skip (SkipType | HyperParameter | None, optional) – Skip connection around the channel MLP; None for no skip connection. Ignored (and not checked) if use_channel_mlp is False. Defaults to “soft-gating”.

  • conv_bias (bool | HyperParameter, optional) – If the spectral convolution has a bias. Defaults to True.

  • init_std (float | Literal["auto"] | HyperParameter, optional) – Standard deviation to initialize the spectral convolution. Defaults to “auto”.

  • fft_norm (FFTNorm | HyperParameter, optional) – Normalization of the FFT of the spectral convolution. Defaults to “forward”.

  • name (str, optional) – Name of the node. Defaults to “fno_block”.

  • backend (type[Backend[TensorType]], optional) – The backend used for the computations. Defaults to DEFAULT_DL_BACKEND.

Raises:
  • TypeError – If non_linearity is neither None nor a node class.

  • ValueError – If the channel MLP would have no hidden channels, if fno_skip or channel_mlp_skip is “soft-gating” or “identity” and the number of input and output channels differ, or if the spectral convolution gets invalid arguments (see SpectralConv).

property hyperparameters: list[HyperParameter]

Collects and returns all hyperparameters from the nodes within the encapsulated graph.

Returns:

A list of all hyperparameters found in the inner graph.

Return type:

list[HyperParameter]

build() → None[source]

Builds the network for the current hyperparameter values, with newly initialized weights.

x_data_config() → DataConfiguration[source]
out_data_config() → DataConfiguration[source]
forward(x: ~typing.Annotated[~qewton.backends.base.TensorType, <function FNOBlock.x_data_config at 0x7c052e51fa60>]) → out_data_config at 0x7c052e51fb00>][source]

Applies the Fourier layer.

Parameters:

x (TensorType) – Input of shape (batch, in_channels, *spatial_dims).

Returns:

Output of shape (batch, out_channels, *spatial_dims).

Return type:

TensorType

qewton.algorithms.building_blocks.geometry module

class qewton.algorithms.building_blocks.geometry.MeshInterpolationNode(mesh_geometry: MeshGeometry, field_variable: Variable, target_geometry: DiscreteGeometry, name: str | None = None, backend: type[ComputingBackend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: Node[TensorType]

Interpolates a per-vertex mesh field onto the points of a target geometry, linearly (barycentric) within the simplex containing each point, e.g. onto a rectilinear GridGeometry, a point set or the vertices of another mesh. Points outside the mesh, and points a GridGeometry’s point_filter excludes, are NaN.

The source mesh geometry and target geometry are structural constants, fixed at construction time - like PointSampler.geometry, not something that varies per forward pass. Only the per-vertex field VALUES flow through the graph dynamically (e.g. a trained solution evaluated at each mesh vertex), so the output DataConfiguration is fully known here and built manually - the same pattern PointSampler/ConcatVariables use for ports whose config depends on constructor parameters rather than forward()’s type hints.

Parameters:
  • mesh_geometry (MeshGeometry) – The source volumetric mesh.

  • field_variable (Variable) – The per-vertex field variable expected on the input port, and carried through unchanged to the output.

  • target_geometry (DiscreteGeometry) – Where to interpolate to - any geometry with discretization_points, of shape (*target_geometry.shape, mesh_geometry.variable.dim).

to(device)[source]

Move the source mesh and the target geometry to device.

Parameters:

device (Device | str) – The target device.

forward(field)[source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

qewton.algorithms.building_blocks.linear module

class qewton.algorithms.building_blocks.linear.FunctionalLinear(name='functional_linear', bias=True, backend: type[DeepLearningBackend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: GraphNode, Generic[TensorType]

ell_ax = <qewton.config.axes.EllipsisAxes object>
dim_1 = <qewton.config.axes.AxesDim object>
dim_2 = <qewton.config.axes.AxesDim object>
forward(x: Annotated[TensorType, ..., FeatureAxes([None])], weight: Annotated[TensorType, ..., FeatureAxes([None, None])], bias: Annotated[TensorType, ..., FeatureAxes([None])] = None) → Annotated[TensorType, ..., FeatureAxes([None])][source]

Evaluate the inner graph on the inputs.

Subclasses override this method only to declare the data configurations of their ports with typing.Annotated; the body stays return super().forward(...). Inside a graph, the steps of the inner graph run in place of this node instead.

Parameters:
  • *args – The values of the input ports, in order.

  • **kwargs – The values of input ports by name.

Returns:

The value of the output port, or a tuple for several.

Return type:

Any

Raises:

RuntimeError – If the node is not built and waits for sizes to be inferred from connected data.

class qewton.algorithms.building_blocks.linear.Linear(in_neurons: int | HyperParameter, out_neurons: int | HyperParameter, bias=True, name='linear', backend: type[DeepLearningBackend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: GraphNode, Generic[TensorType]

A node representing an linear deep learning layer

Parameters:
  • in_neurons (int | HyperParameter) – The number of input neurons.

  • out_neurons (int | HyperParameter) – The number of output neurons.

  • bias (bool) – Whether to include a bias term. Defaults to True.

  • name (str) – Name of the node. Defaults to “linear”.

  • backend (type[DeepLearningBackend[TensorType]]) – The deep learning backend to use. Defaults to DEFAULT_DL_BACKEND.

ellipsis_axes: EllipsisAxes
x_data_config()[source]
out_data_config()[source]
forward(x: ~typing.Annotated[~qewton.backends.base.TensorType, <function Linear.x_data_config at 0x7c052e6b3d80>]) → out_data_config at 0x7c052e6b3e20>][source]

Evaluate the inner graph on the inputs.

Subclasses override this method only to declare the data configurations of their ports with typing.Annotated; the body stays return super().forward(...). Inside a graph, the steps of the inner graph run in place of this node instead.

Parameters:
  • *args – The values of the input ports, in order.

  • **kwargs – The values of input ports by name.

Returns:

The value of the output port, or a tuple for several.

Return type:

Any

Raises:

RuntimeError – If the node is not built and waits for sizes to be inferred from connected data.

class qewton.algorithms.building_blocks.linear.Quadratic(in_neurons: int | HyperParameter, out_neurons: int | HyperParameter, bias=True, name='quadratic', backend: type[DeepLearningBackend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: Linear[TensorType]

A node representing an quadratic deep learning layer of the form W_1*x (*) W_2*x + W_1*x + b. Here (*) means the hadamard product of two vectors (element-wise multiplication). W_1, W_2 are weight matrices and b is a bias vector.

qewton.algorithms.building_blocks.math module

class qewton.algorithms.building_blocks.math.BroadcastingNode(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

A node computing element by element from two inputs that broadcast against each other: where one has size 1, the other’s size is taken. Subclasses declare each port with an ellipsis of its own; an input may also be a Python scalar, which the backends convert themselves.

relate(x: DynamicDataConfiguration, y: DynamicDataConfiguration) → DataConfiguration[source]

The configuration of each output, from those of the inputs at one place of a graph, for relations the annotations of forward() can not express: an operation that changes dims by their index (e.g. return x.squeeze(self.dim), see the shape operations of DataConfiguration).

The inputs are declared by the annotations and already merged with what is connected, as known so far (resolved, see Matching); they belong to the matching of the graph, so what shape operations fix goes there. The returned configurations are merged with the annotated ones of the outputs. A shape operation that needs more of the inputs’ structure than is known raises StructureUnknown; the graph calls relate again once the inputs change.

Parameters:

*inputs – The configurations of the input ports, in order.

Returns:

The configuration of the

output, a tuple for several outputs, or None if the annotations say everything (default).

Return type:

DataConfiguration or tuple or None

class qewton.algorithms.building_blocks.math.Add(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: BroadcastingNode[TensorType]

A summation node that adds two input tensors together. Has two input ports and one output port.

forward(x: Annotated[TensorType | float, ...], y: Annotated[TensorType | float, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.math.Subtract(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: BroadcastingNode[TensorType]

A subtraction node that subtracts the second input from the first input tensor. Has two input ports and one output port.

forward(x: Annotated[TensorType | float, ...], y: Annotated[TensorType | float, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.math.Multiply(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: BroadcastingNode[TensorType]

Element-wise multiplication of two input tensors. Has two input ports and one output port.

forward(x: Annotated[TensorType | float, ...], y: Annotated[TensorType | float, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.math.Divide(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: BroadcastingNode[TensorType]

Element-wise division of the first input by the second input tensor. Has two input ports and one output port.

forward(x: Annotated[TensorType | float, ...], y: Annotated[TensorType | float, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.math.Mod(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: BroadcastingNode[TensorType]

Element-wise modulo (remainder) operation on two input tensors. Has two input ports and one output port.

forward(x: Annotated[TensorType | float, ...], y: Annotated[TensorType | float, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.math.Negative(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Negation node that returns the negative of the input tensor. Has one input port and one output port.

ellipsis_dims = <qewton.config.axes.EllipsisAxes object>
forward(x: Annotated[TensorType, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.math.Square(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Element-wise squaring of the input tensor. Has one input port and one output port.

ellipsis_dims = <qewton.config.axes.EllipsisAxes object>
forward(x: Annotated[TensorType, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.math.Sqrt(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Element-wise square root of the input tensor. Has one input port and one output port.

ellipsis_dims = <qewton.config.axes.EllipsisAxes object>
forward(x: Annotated[TensorType, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.math.Power(power: float | None = None, name=None, backend: type[DeepLearningBackend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: BroadcastingNode[TensorType]

Element-wise exponentiation node that raises the first input to the power of the second input. Has two input ports and one output port.

forward(x: Annotated[TensorType | float, ...], y: Annotated[TensorType | float, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.math.Exp(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Element-wise exponential (e^x) of the input tensor. Has one input port and one output port.

ellipsis_dims = <qewton.config.axes.EllipsisAxes object>
forward(x: Annotated[TensorType, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.math.Log(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Element-wise natural logarithm of the input tensor. Has one input port and one output port.

ellipsis_dims = <qewton.config.axes.EllipsisAxes object>
forward(x: Annotated[TensorType, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.math.Log2(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Element-wise base-2 logarithm of the input tensor. Has one input port and one output port.

ellipsis_dims = <qewton.config.axes.EllipsisAxes object>
forward(x: Annotated[TensorType, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.math.Log10(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Element-wise base-10 logarithm of the input tensor. Has one input port and one output port.

ellipsis_dims = <qewton.config.axes.EllipsisAxes object>
forward(x: Annotated[TensorType, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.math.Sin(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Element-wise sine of the input tensor. Has one input port and one output port.

ellipsis_dims = <qewton.config.axes.EllipsisAxes object>
forward(x: Annotated[TensorType, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.math.Cos(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Element-wise cosine of the input tensor. Has one input port and one output port.

ellipsis_dims = <qewton.config.axes.EllipsisAxes object>
forward(x: Annotated[TensorType, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.math.Tan(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Element-wise tangent of the input tensor. Has one input port and one output port.

ellipsis_dims = <qewton.config.axes.EllipsisAxes object>
forward(x: Annotated[TensorType, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.math.ArcSin(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Element-wise inverse sine (arcsine) of the input tensor. Has one input port and one output port.

ellipsis_dims = <qewton.config.axes.EllipsisAxes object>
forward(x: Annotated[TensorType, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.math.ArcCos(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Element-wise inverse cosine (arccosine) of the input tensor. Has one input port and one output port.

ellipsis_dims = <qewton.config.axes.EllipsisAxes object>
forward(x: Annotated[TensorType, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.math.ArcTan(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Element-wise inverse tangent (arctangent) of the input tensor. Has one input port and one output port.

ellipsis_dims = <qewton.config.axes.EllipsisAxes object>
forward(x: Annotated[TensorType, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.math.Abs(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Element-wise absolute value of the input tensor. Has one input port and one output port.

ellipsis_dims = <qewton.config.axes.EllipsisAxes object>
forward(x: Annotated[TensorType, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.math.Floor(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Element-wise floor operation on the input tensor (rounds down). Has one input port and one output port.

ellipsis_dims = <qewton.config.axes.EllipsisAxes object>
forward(x: Annotated[TensorType, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.math.Ceil(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Element-wise ceiling operation on the input tensor (rounds up). Has one input port and one output port.

ellipsis_dims = <qewton.config.axes.EllipsisAxes object>
forward(x: Annotated[TensorType, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.math.Maximum(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: BroadcastingNode[TensorType]

Element-wise maximum of two input tensors. Has two input ports and one output port.

forward(x: Annotated[TensorType | float, ...], y: Annotated[TensorType | float, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.math.Minimum(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: BroadcastingNode[TensorType]

Element-wise minimum of two input tensors. Has two input ports and one output port.

forward(x: Annotated[TensorType | float, ...], y: Annotated[TensorType | float, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.math.MatMul(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Matrix multiplication node that multiplies two tensors along their matrix dimensions. Supports batch dimensions and ellipsis dimensions. Has two input ports and one output port.

ell_ax = <qewton.config.axes.EllipsisAxes object>
dim_1 = <qewton.config.axes.AxesDim object>
dim_ellipsis = <qewton.config.axes.EllipsisDim object>
dim_2 = <qewton.config.axes.AxesDim object>
forward(x: Annotated[TensorType, ..., FeatureAxes([..., None])], y: Annotated[TensorType, ..., FeatureAxes([None, None])]) → Annotated[TensorType, ..., FeatureAxes([..., None])][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.math.SVD(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Singular Value Decomposition node that decomposes an input matrix into U, S, V components. Has one input port and three output ports (U, S, V).

dim_1 = <qewton.config.axes.AxesDim object>
dim_2 = <qewton.config.axes.AxesDim object>
min_dim = <qewton.config.axes.MinimumDim object>
ell_ax = <qewton.config.axes.EllipsisAxes object>
forward(x: Annotated[TensorType, ..., FeatureAxes([None, None])]) → tuple[Annotated[TensorType, ..., FeatureAxes([None, None])], Annotated[TensorType, ..., FeatureAxes([MinimumDim])], Annotated[TensorType, ..., FeatureAxes([None, None])]][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.math.Dot(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Dot product node that computes the inner product of two vectors. Has two input ports and one output port.

dim_1 = <qewton.config.axes.AxesDim object>
forward(x: Annotated[TensorType, ..., FeatureAxes([None])], y: Annotated[TensorType, ..., FeatureAxes([None])]) → Annotated[TensorType, ..., FeatureAxes([1])][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

relate(x: DynamicDataConfiguration, y: DynamicDataConfiguration) → DataConfiguration[source]

The configuration of each output, from those of the inputs at one place of a graph, for relations the annotations of forward() can not express: an operation that changes dims by their index (e.g. return x.squeeze(self.dim), see the shape operations of DataConfiguration).

The inputs are declared by the annotations and already merged with what is connected, as known so far (resolved, see Matching); they belong to the matching of the graph, so what shape operations fix goes there. The returned configurations are merged with the annotated ones of the outputs. A shape operation that needs more of the inputs’ structure than is known raises StructureUnknown; the graph calls relate again once the inputs change.

Parameters:

*inputs – The configurations of the input ports, in order.

Returns:

The configuration of the

output, a tuple for several outputs, or None if the annotations say everything (default).

Return type:

DataConfiguration or tuple or None

class qewton.algorithms.building_blocks.math.Norm(ord: float | str = 2, name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Norm node that computes the p-norm of the input tensor along the last axis. Always keeps the last dimension (keepdims=True). Has one input port and one output port.

dim_1 = <qewton.config.axes.AxesDim object>
ell_ax = <qewton.config.axes.EllipsisAxes object>
forward(x: Annotated[TensorType, ..., FeatureAxes([None])]) → Annotated[TensorType, ..., FeatureAxes([1])][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.math.Inner(keepdims: bool = False, name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]

Bases: Node[TensorType]

Inner product node that computes the element-wise product sum along the last axis. Supports keepdims option to retain dimension after reduction. Has two input ports and one output port.

dim_1 = <qewton.config.axes.AxesDim object>
ell_ax = <qewton.config.axes.EllipsisAxes object>
forward(x: Annotated[TensorType, ..., FeatureAxes([None])], y: Annotated[TensorType, ..., FeatureAxes([None])]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

relate(x: DynamicDataConfiguration, y: DynamicDataConfiguration) → DataConfiguration[source]

The configuration of each output, from those of the inputs at one place of a graph, for relations the annotations of forward() can not express: an operation that changes dims by their index (e.g. return x.squeeze(self.dim), see the shape operations of DataConfiguration).

The inputs are declared by the annotations and already merged with what is connected, as known so far (resolved, see Matching); they belong to the matching of the graph, so what shape operations fix goes there. The returned configurations are merged with the annotated ones of the outputs. A shape operation that needs more of the inputs’ structure than is known raises StructureUnknown; the graph calls relate again once the inputs change.

Parameters:

*inputs – The configurations of the input ports, in order.

Returns:

The configuration of the

output, a tuple for several outputs, or None if the annotations say everything (default).

Return type:

DataConfiguration or tuple or None

class qewton.algorithms.building_blocks.math.ReductionNode(name=None, axis: None | int | tuple[int, ...]=None, keepdims=False, backend: type[DeepLearningBackend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: Node[TensorType]

Base class for reduction operations (Mean, Sum, Std) that reduce tensor dimensions. Supports axis specification and keepdims option.

relate(x: DynamicDataConfiguration) → DataConfiguration[source]

Without keepdims the reduced dims are dropped, with keepdims they have size 1; without an axis every dim is reduced.

class qewton.algorithms.building_blocks.math.Mean(name=None, axis: None | int | tuple[int, ...]=None, keepdims=False, backend: type[DeepLearningBackend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: ReductionNode[TensorType]

Mean reduction node that computes the average of input tensor along the specified axis. Has one input port and one output port.

forward(x: Annotated[TensorType, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.math.Sum(name=None, axis: None | int | tuple[int, ...]=None, keepdims=False, backend: type[DeepLearningBackend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: ReductionNode[TensorType]

Sum reduction node that computes the total of input tensor elements along the specified axis. Has one input port and one output port.

forward(x: Annotated[TensorType, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.math.Std(name=None, axis: None | int | tuple[int, ...]=None, keepdims=False, backend: type[DeepLearningBackend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: ReductionNode[TensorType]

Standard deviation reduction node that computes the standard deviation along the specified axis. Has one input port and one output port.

forward(x: Annotated[TensorType, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

class qewton.algorithms.building_blocks.math.Transpose(perm: list | None = None, backend=<class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: Node[TensorType]

Transpose node that permutes the dimensions of the input tensor. Has one input port and one output port.

relate(x: DynamicDataConfiguration) → DataConfiguration[source]

The configuration of each output, from those of the inputs at one place of a graph, for relations the annotations of forward() can not express: an operation that changes dims by their index (e.g. return x.squeeze(self.dim), see the shape operations of DataConfiguration).

The inputs are declared by the annotations and already merged with what is connected, as known so far (resolved, see Matching); they belong to the matching of the graph, so what shape operations fix goes there. The returned configurations are merged with the annotated ones of the outputs. A shape operation that needs more of the inputs’ structure than is known raises StructureUnknown; the graph calls relate again once the inputs change.

Parameters:

*inputs – The configurations of the input ports, in order.

Returns:

The configuration of the

output, a tuple for several outputs, or None if the annotations say everything (default).

Return type:

DataConfiguration or tuple or None

forward(x: Annotated[TensorType, ...]) → Annotated[TensorType, ...][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

qewton.algorithms.building_blocks.norms module

class qewton.algorithms.building_blocks.norms.MSN(backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: GraphNode

qewton.algorithms.building_blocks.parameters module

class qewton.algorithms.building_blocks.parameters.ParameterNode(shape: tuple[int | ~qewton.optim.parameters.hyperparameter_base.HyperParameter, ...], initial_value=None, name: str = 'ParameterNode', backend: type[~qewton.backends.base.DeepLearningBackend] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: Node[TensorType]

build() → None[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.

set_trainable_parameter(new_value: TrainableParameters) → None[source]
output_config()[source]
run() → None[source]
forward() → output_config at 0x7c052e6b00e0>][source]

Compute the outputs of this node from its inputs.

The signature and type hints define the ports of the node.

Raises:

NotImplementedError – Always; subclasses must implement this method.

reset()[source]

Make the node unbuilt, so that the next setup() builds it again (e.g. for other hyperparameter values); a FIXED node stays as it is.

fix_node_state() → None[source]

Set the state to FIXED, so the node is neither trained nor recreated.

An uninitialized node is not fixed; a UserWarning is issued instead.

set_state(new_state: NodeState)[source]

Set the current state of this node.

Parameters:

new_state – The new state.

property trainable_parameters
property memory_consumption: int
to(device)[source]

Move the data stored in this node to device.

Does nothing by default.

Parameters:

device (Device or str) – The target device, e.g. a CPU or GPU.

qewton.algorithms.building_blocks.skip_connections module

Skip connections of Fourier Neural Operator blocks.

qewton.algorithms.building_blocks.skip_connections.SkipType

The kinds of skip connections available in skip_connection.

alias of Literal[‘soft-gating’, ‘linear’, ‘identity’]

class qewton.algorithms.building_blocks.skip_connections.SoftGating(in_features: int, out_features: int | None = None, n_dim: int = 2, bias: bool = False, name: str = 'soft_gating', backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: GraphNode, Generic[TensorType]

Soft-gating skip connection.

Weights every channel of the input with a learned scalar, x * w (+ b), where w (and b) have the shape (1, channels, 1, …, 1). Both the weight and the bias are initialized with ones.

weight

The learned per-channel scale.

Type:

ParameterNode

bias

The learned per-channel offset, or None if the gating has no bias.

Type:

ParameterNode | None

Parameters:
  • in_features (int) – Number of channels of the input.

  • out_features (int | None, optional) – Number of channels of the output. Only there for compatibility with the other skip connections; it has to be None or equal to in_features. Defaults to None.

  • n_dim (int, optional) – Number of spatial dimensions of the input (excluding batch and channels). Defaults to 2.

  • bias (bool, optional) – If a learned bias should be added. Defaults to False.

  • name (str, optional) – Name of the node. Defaults to “soft_gating”.

  • backend (type[Backend[TensorType]], optional) – The backend used for the computations. Defaults to DEFAULT_DL_BACKEND.

forward(x: Annotated[TensorType, ...]) → Annotated[TensorType, ...][source]

Scales (and shifts) every channel of the input.

The weight is broadcast over batch and space, which the data configuration cannot express, so the input and output configuration is left flexible.

Parameters:

x (TensorType) – Input of shape (batch, in_features, *spatial_dims).

Returns:

The gated input, same shape as x.

Return type:

TensorType

qewton.algorithms.building_blocks.skip_connections.skip_connection(in_features: int, out_features: int, n_dim: int = 2, bias: bool = False, skip_type: Literal['soft-gating', 'linear', 'identity']='soft-gating', backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>) → Node[source]

Builds a skip connection node.

Parameters:
  • in_features (int) – Number of channels of the input.

  • out_features (int) – Number of channels of the output.

  • n_dim (int, optional) – Number of spatial dimensions of the input. Only used by the soft-gating. Defaults to 2.

  • bias (bool, optional) – If the soft-gating or the linear skip should have a bias. Not used by the identity. Defaults to False.

  • skip_type (SkipType, optional) – “soft-gating” for a learned scale per channel, “linear” for a 1x1 convolution, or “identity”. Defaults to “soft-gating”.

  • backend (type[Backend[TensorType]], optional) – The backend used for the computations. Defaults to DEFAULT_DL_BACKEND.

Returns:

The skip connection, with a single input and a single output port.

Return type:

Node

Raises:

ValueError – If skip_type is unknown, or if the soft-gating or the identity is requested with in_features != out_features.

qewton.algorithms.building_blocks.spectral_convolution module

Spectral convolution of Fourier Neural Operators.

qewton.algorithms.building_blocks.spectral_convolution.FFTNorm

The normalization modes of the fast Fourier transform.

alias of Literal[‘forward’, ‘backward’, ‘ortho’]

class qewton.algorithms.building_blocks.spectral_convolution.FunctionalSpectralConv(n_dim: int, name: str = 'functional_spectral_conv', backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: Node[TensorType]

Functional spectral convolution of real-valued data.

The number of modes kept per spatial dimension is inferred from weight.shape[2:]. Because of the redundancy of the real FFT, the last dimension of the weight has to hold n_modes[-1] // 2 + 1 modes (see SpectralConv). If the input has fewer frequencies than the weight has modes, the weight is cropped to the available ones.

input, weight, bias, fft_norm

The inputs of the node.

Type:

InputPort

output

The output of the node.

Type:

OutputPort

batch_axes, geo_axes, feature_axes_x, feature_axes_weight, feature_axes_bias,

channel_dim_out: Shape information of the data configurations.

Parameters:
  • n_dim (int) – Number of spatial dimensions of the input.

  • name (str, optional) – Name of the node. Defaults to “functional_spectral_conv”.

  • backend (type[Backend[TensorType]], optional) – The backend used for the computations. Defaults to DEFAULT_DL_BACKEND.

x_data_config() → DataConfiguration[source]
weight_data_config() → DataConfiguration[source]
bias_data_config() → DataConfiguration[source]
out_data_config() → DataConfiguration[source]
forward(x: ~typing.Annotated[~qewton.backends.base.TensorType, <function FunctionalSpectralConv.x_data_config at 0x7c052e51f100>], weight: ~typing.Annotated[~qewton.backends.base.TensorType, <function FunctionalSpectralConv.weight_data_config at 0x7c052e51f1a0>], bias: ~typing.Annotated[~qewton.backends.base.TensorType | None, <function FunctionalSpectralConv.bias_data_config at 0x7c052e51f240>] = None, fft_norm: ~typing.Annotated[~typing.Literal['forward', 'backward', 'ortho'] | None, ...] = 'forward') → out_data_config at 0x7c052e51f2e0>][source]

Applies the spectral convolution.

Parameters:
  • x (TensorType) – Input of shape (batch, in_channels, *spatial_dims).

  • weight (TensorType) – Complex-valued Fourier weight of shape (in_channels, out_channels, *kept_modes), where kept_modes already has the halving of the last dimension applied.

  • bias (TensorType | None, optional) – Real-valued bias of shape (out_channels, 1, …, 1), broadcast over batch and space. Defaults to None.

  • fft_norm (FFTNorm | None, optional) – Normalization of the forward and the inverse FFT. Defaults to “forward”.

Returns:

Output of shape (batch, out_channels, *spatial_dims).

Return type:

TensorType

class qewton.algorithms.building_blocks.spectral_convolution.SpectralConv(in_channels: int, out_channels: int, n_modes: tuple[int, ...], bias: bool = True, init_std: float | ~typing.Literal['auto'] = 'auto', fft_norm: ~typing.Literal['forward', 'backward', 'ortho'] | None = 'forward', name: str = 'spectral_conv', backend: type[~qewton.backends.base.Backend[~qewton.backends.base.TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>)[source]

Bases: GraphNode[TensorType]

Spectral convolution layer of a Fourier Neural Operator.

Owns a complex-valued Fourier weight (with the mode count of the last spatial dimension halved because of the redundancy of the real FFT) and an optional real-valued bias per output channel. The computation is delegated to FunctionalSpectralConv.

kept_modes

Shape of the weight along the spatial dimensions, i.e. n_modes with the last entry halved.

Type:

tuple[int, …]

weight

The complex Fourier weight of shape (in_channels, out_channels, *kept_modes).

Type:

ParameterNode

bias

The bias of shape (out_channels, 1, …, 1), or None if the layer has no bias.

Type:

ParameterNode | None

Parameters:
  • in_channels (int) – Number of input channels.

  • out_channels (int) – Number of output channels.

  • n_modes (tuple[int, ...]) – Number of modes to keep in every spatial dimension.

  • bias (bool, optional) – If a bias should be added. Defaults to True.

  • init_std (float | Literal["auto"], optional) – Standard deviation of the normal distribution used to initialize weight and bias. “auto” uses sqrt(2 / (in_channels + out_channels)). Defaults to “auto”.

  • fft_norm (FFTNorm | None, optional) – Normalization of the forward and the inverse FFT. Defaults to “forward”.

  • name (str, optional) – Name of the node. Defaults to “spectral_conv”.

  • backend (type[Backend[TensorType]], optional) – The backend used for the computations. Defaults to DEFAULT_DL_BACKEND.

Raises:

ValueError – If a number of channels or modes is not positive, init_std is negative, or fft_norm is unknown.

forward(x: TensorType) → TensorType[source]

Applies the spectral convolution.

Parameters:

x (TensorType) – Input of shape (batch, in_channels, *spatial_dims).

Returns:

Output of shape (batch, out_channels, *spatial_dims).

Return type:

TensorType