qewton.graphs package¶
Module contents¶
Graphs Submodule¶
The graphs module provides the core infrastructure for building and executing Directed Acyclic Graphs (DAGs) in Qewton. It allows users to define modular computation pipelines where each operation is encapsulated as a Node.
Key Components¶
Graph: The main container that manages nodes, edges, and topological sorting (using Kahn’s algorithm) for execution. It supports programmatic construction through thetrackercontext manager, to avoid large amounts of manual calls tograph.connect().Node: The base class for all functional blocks. Nodes define input and output ports and can represent anything from simple math to entire subgraphs. While multiple edges can connect to a single output port, each input port can only have one incoming edge. Data loaders and constraints are also implemented as nodes, allowing them to be integrated into the graph execution.Edge: Manages the data flow (data can be of any type) between ports, including support for connections to outside the local graph context (e.g., in aGraphNode) and skip connections.GraphNode: Enables hierarchical nesting by encapsulating an entire graph within a single node.TrackingObject: Allows users to write standard Python functions that are automatically converted into graph structures. Note: This does not yet support control flow constructs like loops or conditionals.Pipelines: Predefined graph templates for common tasks (e.g., PINN training) that can be easily customized and extended.
Goals¶
Modularity: Break complex physics models into reusable, atomic components.
Implicit Construction: Allow users to build graphs using standard Python syntax and operators.
Validation: Ensure that connections between nodes are compatible before execution.
Flexibility: Support both simple sequential execution and complex, multi-input/multi-output DAGs. Can therefore cover arbitrary algorithms, e.g. for time-dependent problems, multi-physics coupling, or multi-task learning.
Hierarchical Nesting: Enable users to create subgraphs that can be reused as single nodes in larger graphs.
Independence of Backend: Does not only allow for the use of multiple deep learning frameworks, but also for non-deep learning computations, e.g. for data preprocessing or classical numerical methods.
Usage¶
from qewton.graphs import Graph
graph = Graph()
with graph.tracker():
data = dataloader() # returns a TrackingObject for its output port
prediction = model(data) # connects dataloader -> model in `graph`
graph.setup() # builds all nodes and plans the run
graph.run()
result = graph.value_of(model.output_ports[0])
Nodes can also be connected explicitly with graph.connect(from_, to_).
Places¶
A node can be part of several graphs and occur at several places of one
graph; node.copy() gives another place sharing its weights. A graph
keeps the matched configuration and the value of every port per place:
graph.config_of(port, within=(graph_node, ...)) # DataConfiguration
graph.value_of(port, within=(graph_node, ...)) # value of the last run
within names the GraphNodes leading to the port, from the outside in;
it is needed only for a node at several places.
GraphNodes¶
A graph matches and runs the inner graph of a GraphNode in place. A model
whose input sizes are left open (e.g. FCN(in_neurons=None, ...)) has no
inner graph until it is set up in a graph that infers them; its forward
declares the ports. Called on its own, a GraphNode runs its inner graph in
its own mode (set_mode).
Setup¶
Order: create nodes → connect (matches the configurations) →
graph.setup() (builds every node, matches again and plans the run) →
graph.run(). A node implements build() to create what it computes
with; setup() belongs to the library. Set the graph up again after
changing hyperparameters or setting up nodes by hand.
See REQUIREMENTS.md and DECISIONS.md.
Subpackages¶
- qewton.graphs.control_nodes package
- Module contents
- Submodules
- qewton.graphs.control_nodes.data_processing_node module
- qewton.graphs.control_nodes.graph_node module
GraphNodeGraphNode.inner_graphGraphNode.upgrade()GraphNode.update_inner_input_ports()GraphNode.update_inner_output_ports()GraphNode.inner_graphGraphNode.hyperparametersGraphNode.trainable_parametersGraphNode.forward()GraphNode.setup_graph()GraphNode.setup()GraphNode.set_mode()GraphNode.reset()GraphNode.to()GraphNode.unfreeze()GraphNode.memory_consumption
FromFunctionNodeTrackedNodeCopiedNode
- qewton.graphs.control_nodes.wrapper_node module
- qewton.graphs.pipelines package
Submodules¶
qewton.graphs.edges module¶
- class qewton.graphs.edges.Edge(from_port: Port, to_port: Port, connects_to_outside: bool = False)[source]¶
Bases:
SerializableRepresents a connection of two nodes in the graph.
- Parameters:
qewton.graphs.graphs module¶
Computation graphs (DAGs) of nodes and the tracking objects that build them from plain Python functions.
- class qewton.graphs.graphs.Graph[source]¶
Bases:
SerializableDirected acyclic graph (DAG) of interconnected nodes.
Nodes are connected port to port via
Edgeobjects. Every connection merges the data configurations of both ports (seemerge()): axes and dims that correspond become one object. A graph keeps the matched configuration and the value of every port it contains, also of the ports inside its GraphNodes, per place: a port together with the path of GraphNodes leading to it, so one node may occur at several places (seeconfig_of()andvalue_of()). The static configurations of the ports stay untouched.- sorted_incoming_edges¶
For each entry of sorted_nodes, its incoming edges keyed by the input port they end in.
- mode¶
The evaluation phase of this graph.
- Type:
- incoming_edges¶
Incoming edges of each node, including edges from outside of the graph.
- outgoing_edges¶
Outgoing edges of each node, including edges to outside of the graph.
- skip_connections¶
Edges added by
add_skip_connection().- Type:
list[Edge]
- load(serializer, data_config: dict) None[source]¶
Loads the object’s state from the serialized data. It sets the object’s attributes based on the serialized data.
- Parameters:
serializer (Deserializer) – The deserializer instance that manages the loading process.
data_config (dict) – A dictionary containing the serialized data for the object.
- config_of(port: Port, within=None) DataConfiguration | None[source]¶
The matched data configuration of port in this graph.
- Parameters:
port – A port of a node in this graph or in the inner graph of one of its GraphNodes, at any depth.
within (tuple[GraphNode, ...], optional) – The GraphNodes, from the outside in, leading to the node of port; needed only if the node occurs at several places of this graph.
- Returns:
- The configuration, or None if the node
is not part of this graph.
- Return type:
DataConfiguration or None
- value_of(port: Port, within=None) Any[source]¶
The value of port in the last run of this graph.
- Parameters:
port – A port of a node in this graph or in the inner graph of one of its GraphNodes, at any depth.
within (tuple[GraphNode, ...], optional) – The GraphNodes, from the outside in, leading to the node of port; needed only if the node occurs at several places of this graph, e.g. a node whose weights are shared by two copies (
Node.copy()).
- Returns:
The value; None if it was not computed in the last run.
- Return type:
Any
- Raises:
ValueError – If the node of port is not part of this graph, or occurs at several places and within is not given.
- all_edges() list[Edge][source]¶
Every edge of this graph, also those from and to outside and the skip connections, once each.
- classmethod from_function(func: Callable) tuple[Graph, list[list[InputPort] | InputPort], list[OutputPort | int]][source]¶
Build a graph by tracking the execution of func.
func is called once with one
TrackingObjectper parameter; every node called on them is recorded in the new graph (seetracker()).- Parameters:
func – The function to track. Its parameters become the graph inputs, its returned tracking objects the graph outputs.
- Returns:
A tuple
(graph, input_ports, output_ports)ofgraph (Graph): The constructed graph.
input_ports (list[list[InputPort] | InputPort]): For each parameter of func, the input ports it was passed to.
output_ports (list[OutputPort | int]): For each returned value, the output port producing it, or the index of the parameter if an input is returned unchanged.
- Return type:
tuple
- Raises:
ValueError – If a parameter of func is neither used nor returned.
- add_node(node: Node, check_warning=True) None[source]¶
Add a node to this graph.
Adding a node that is already part of the graph keeps its edges and data configurations.
- Parameters:
node – The node to add.
check_warning (bool, optional) – Whether to check that no node with the same node_id is already part of this graph. Default is True.
- Raises:
ValueError – If check_warning is True and a node with the same node_id already exists in this graph.
- sort()[source]¶
Sort the nodes topologically to determine the execution order.
Uses Kahn’s algorithm. Edges from outside of the graph do not count towards a node’s in-degree, since their data is already available when the graph starts.
- Raises:
ValueError – If a cycle is detected in the graph.
- connect(from_: Node | OutputPort, to_: Node | InputPort) None[source]¶
Connect two nodes or ports within the graph.
If nodes are passed, all output ports of from_ are connected to the input ports of to_ in order. Both nodes are added to the graph if needed, and the data configurations of every connected port pair are unified. Warns if the graph was already sorted.
- Parameters:
from – The source node or output port.
to – The destination node or input port.
- Raises:
ValueError – If the numbers of ports do not match or an input port is already connected.
DataConfigMismatchError – If the data configurations of the connected ports are incompatible.
- remove(obj: Node | Edge)[source]¶
Remove a node or edge from the graph.
Removing a node also removes all edges connected to it. All data configurations are matched again afterwards and the graph is marked as unsorted.
- Parameters:
obj – The node or edge to remove.
- duplicate() Graph[source]¶
Create a copy of this graph’s structure.
The copy shares the node objects but has its own edges and data configurations. It is sorted if this graph is sorted.
- Returns:
A new graph with the same nodes and connections.
- Return type:
- replace_node(old_node: Node, new_node: Node, input_port_mapping: dict[Port, Port] | None = None, output_port_mapping: dict[Port, Port] | None = None)[source]¶
Replace a node of the graph with a new node.
All edges and skip connections of old_node are transferred to new_node, the data configurations are recalculated and the graph is marked as unsorted.
- Parameters:
old_node – The node to replace.
new_node – The node that replaces old_node.
input_port_mapping – Maps input ports of old_node to input ports of new_node. None (default) matches them by order, which requires both nodes to have the same number of input ports.
output_port_mapping – Maps output ports of old_node to output ports of new_node. None (default) matches them by order, which requires both nodes to have the same number of output ports.
- Raises:
ValueError – If old_node is not part of the graph, new_node already is, or the numbers of ports do not match without a mapping.
- connect_from_outside_of_graph(from_port: Port, to_port: InputPort)[source]¶
Connect a port outside of this graph to an input port inside it.
The node of to_port is added to this graph. The created edge passes data between the ports but does not increase the in-degree of the node of to_port, so that node can be evaluated at the start of a run.
- Parameters:
from_port – The port outside of this graph that provides the data.
to_port – The input port that receives the data.
- Raises:
ValueError – If to_port is already connected.
DataConfigMismatchError – If the data configurations of the ports are incompatible. The edge is not added in this case.
- connect_to_outside_of_graph(from_port: OutputPort, to_port: Port)[source]¶
Connect an output port inside this graph to a port outside of it.
The node of from_port is added to this graph; to_port carries the value of from_port (see
value_of()).- Parameters:
from_port – The output port inside this graph that provides the data.
to_port – The port outside of this graph that receives the data.
- Raises:
DataConfigMismatchError – If the data configurations of the ports are incompatible. The edge is not added in this case.
- add_skip_connection(from_port: Port, to_port: Port)[source]¶
Add a skip connection between two ports.
The edge is not part of the topological order; to_port carries the value of from_port (see
value_of()), and their data configurations are merged.- Parameters:
from_port – The port providing the data.
to_port – The port receiving the data.
- validate() None[source]¶
Check that every required input port of every node is connected.
- Raises:
ValueError – If a required input port is not connected.
- setup(plan: bool = True)[source]¶
Sort the graph, set up all nodes for evaluation, in order, and match their configurations.
Every node receives this graph in its setup (see
setup()); aGraphAwareNodebuilds with it. ADataProcessingNodeis only set up if its data source node is part of this graph.- Parameters:
plan – Whether to match the configurations and plan the run now. False for the inner graph of a GraphNode: a graph containing the GraphNode matches it in place, and it plans itself when it is run on its own.
- evaluate(inputs: dict[Port, Any], outputs: list[Port], mode: EvaluationPhase = EvaluationPhase.ALWAYS) list[Any][source]¶
Run this graph with the given values at ports outside of it, e.g. the input ports of the GraphNode it is the inner graph of.
- Parameters:
inputs – The value of each port outside of this graph that edges lead from.
outputs – Ports whose values to return.
mode – The evaluation phase every node is set to.
- Returns:
The value of each of outputs after the run.
- Return type:
list
- run(mode: EvaluationPhase = EvaluationPhase.ALWAYS)[source]¶
Run all nodes in execution order.
Each input receives the value of its incoming edge, or its default if it has none. The values are kept in this graph, see
value_of().- Parameters:
mode – The evaluation phase every node is set to.
- run_to(last_node: Node, mode: EvaluationPhase = EvaluationPhase.ALWAYS) dict[Port, Edge][source]¶
Run only the nodes last_node depends on, in topological order.
last_node itself is not run.
- diagram(depth: int = 1, show_port_names: bool = False, show_configs: bool = False) GraphPlot[source]¶
Build a diagram of this graph’s structure.
- Parameters:
depth – How many levels of composite nodes (subclasses of
GraphNode) are expanded inline instead of drawn as a single box.show_port_names – Whether nodes with more than one input or output port also get a name label at each port.
show_configs – Whether every edge is labeled with the axes of its matched data configuration; otherwise they are shown on hover.
- Returns:
The node-link diagram of this graph.
- Return type:
- visualize(port: Port | list[Port], reference: Port | Callable | Any = None, error: str | None = 'signed', mask: Port | None = None, plot_type: type['Plot'] | None = None, max_vertex_distance: float | dict[Variable, float] = 0.05, device: Device | str | None = None, share_scale: bool = True, color_scale: ColorScale | None = None, controls: list[ControlAxis] = (), default_control: type[ControlAxis] | None = None, variables: list[Variable] | None = None, prediction_config: DataConfiguration | None = None, reference_config: DataConfiguration | None = None, mode: EvaluationPhase = EvaluationPhase.VALIDATION, **plot_kwargs) Layout[source]¶
Evaluate the graph for port and build plots of the result.
Only the nodes needed to produce a value for port are run. The plots are built with
auto_plot().Without reference, every
PointSampleron the path to port is switched to mesh mode for this run (seediscretization_mode()), so the result is drawn on a deterministic discretization of its geometry.With reference, the result is compared to reference data in a Reference / Prediction / Error layout. The model is evaluated at the points of the reference, so no interpolation is needed.
- Parameters:
port – One port, or a list of ports, to visualize.
reference –
Reference data for a single port. One of
plain data (a numpy array or a backend tensor on any device); requires reference_config. Its Variable must be the exact same instance as the one of port’s value. The model is evaluated at the points of its geometry; a list of GeometryAxes, one per factor of a product domain, is evaluated at all combinations of the factors’ points.
another port of this graph (e.g. the true-output port of a data loader), run together with port. Its Variable must equal the one of port by name, dimension and structure.
a callable, evaluated at the mesh-mode points of port.
None (default) draws port alone.
error – With reference, which error panel to add:
"signed"(prediction - reference, diverging colormap, symmetric scale),"absolute"(absolute difference, scale from 0),"relative"(difference divided by the reference, NaN where the reference is close to 0, diverging, symmetric), or None for no error panel. Ignored without reference.mask – A port of this graph, run together with port, whose value has one component per point of the plotted data, e.g. the domain mask of a data loader. Points where it is 0 or NaN are not drawn in any panel and do not train the scales. None (default) draws every point.
plot_type – Plot type passed to
auto_plot()for every plot. None (default) selects it automatically.max_vertex_distance – Maximal vertex distance of the mesh used in mesh mode. A dict sets it per geometry Variable, e.g. per factor of a space-time domain; geometries missing from it use None (the coarsest mesh). Unused with plain reference data.
device – If given, every node needed for port is moved to this device before running, and mesh-mode points are created there.
share_scale – With reference, whether the reference and prediction panels share one color scale. The error panel always has its own scale.
color_scale – The color scale of every plot, e.g.
ColorScale(vmin=0.0, vmax=1.0)for one fixed range. With reference, it is shared by the reference and prediction panels instead of the scale from share_scale; the error panel keeps its own scale. None (default) gives each plot its own.controls – Control axes for chosen dimensions, e.g.
[TimeAxis(t)]; a control on a 1D factor of a product geometry steps through that factor.default_control – Control axis class for every other dimension not drawn; None for auto_plot’s default (a slider). Every control is shared by all plots whose data has its axes or Variable (see
AutoPlots).variables – Narrows port (and reference, unless it already has exactly this combination) to the slice of these Variables of a composed FeatureAxes before plotting. With more than one Variable, all plots share one Selector to switch between them, which requires them to be scalars. None (default) uses the Variable of port as declared.
prediction_config – Used instead of the data configuration of port in this graph to build the prediction plot and to check reference against.
reference_config – Used instead of the data configuration of a port reference in this graph. Required for plain reference data.
mode – The evaluation phase every run node is set to; selects which split a data loader provides.
**plot_kwargs – Passed to
auto_plot()for every plot.
- Returns:
- The plots (with reference: reference, prediction and
error) arranged by
auto_layout(); panels in one Overlay are named by their legend entries, panels side by side by their titles. Show it withFigure(layout).show().
- Return type:
- Raises:
ValueError – If reference is given for a list of ports, plain reference data is given without reference_config, the Variables or shapes of prediction and reference do not match, mask has not one value per point of the data, error is unknown, or auto_plot raises.
- collect_trainable_parameters()[source]¶
Collect the trainable parameters of all nodes in this graph.
Nodes in state
NodeState.FIXEDcontribute no parameters.- Returns:
- The trainable parameters of all
nodes.
- Return type:
- tracker(n_tracking_vars=1)[source]¶
Context manager that builds this graph from node calls.
While active, calling a node with
TrackingObjectarguments does not compute anything but connects the node in this graph and returns tracking objects for its outputs. Non-tracking arguments become defaults of the corresponding input ports. Trackers can be nested; the innermost graph receives the connections.- Parameters:
n_tracking_vars (int, optional) – The number of tracking objects to yield. Default is 1.
- Yields:
TrackingObject or list[TrackingObject] or None –
- A single tracking
object if n_tracking_vars is 1, a list of them if it is larger, None if it is 0.
- Raises:
RuntimeError – If the graph already contains nodes.
- class qewton.graphs.graphs.SequentialGraph(*nodes: Node)[source]¶
Bases:
GraphGraph of nodes connected in a linear sequence.
Each node is connected to the next one with
Graph.connect(), so the output ports of a node must match the input ports of its successor. The given order is used as execution order.- Parameters:
*nodes – The nodes in execution order.
- class qewton.graphs.graphs.TrackingObject(last_output_port: OutputPort | None = None)[source]¶
Bases:
objectPlaceholder for a value flowing through a graph during tracking.
Inside
Graph.tracker(), calling a node with tracking objects connects the node in the tracked graph and returns new tracking objects for its output ports. Arithmetic operators (+,-,*,/,**,@, unary-,abs), indexing, item assignment and the methods of this class add the corresponding nodes fromqewton.algorithms.building_blocksin the same way and return the tracking object of the result.- Parameters:
last_output_port – The output port that produces this value. None for a graph input that is not produced by any node.
- current_graph_tracked¶
Class attribute: the graph currently being tracked, None outside of
Graph.tracker().- Type:
Graph or None
- last_output_port¶
The output port that produces this value.
- Type:
OutputPort or None
- norm(ord: float | str = 2)[source]¶
Track the norm along the last axis.
- Parameters:
ord – The order of the norm.
- dot(other)[source]¶
Track the dot product with other.
- Parameters:
other (TrackingObject) – The second factor.
- squeeze(dim)[source]¶
Track removing the dimension dim of size 1.
- Parameters:
dim (int) – The dimension to remove.
- unsqueeze(dim)[source]¶
Track adding a dimension of size 1 at position dim.
- Parameters:
dim (int) – The position of the new dimension.
- as_variable(variable)[source]¶
Track declaring that the features of this value are variable, e.g.
exact_solution(t).as_variable(U)to compare it with a model ofU. The data is unchanged; seeAsVariable.- Parameters:
variable (Variable) – The Variable of the features, of the same size as the current ones.
- gradient(with_respect_to)[source]¶
Track the gradient of this value.
- Parameters:
with_respect_to (TrackingObject) – The input to differentiate with respect to.
- normal_derivative(normals, with_respect_to)[source]¶
Track the normal derivative of this value.
- Parameters:
normals (TrackingObject) – The normal vectors.
with_respect_to (TrackingObject) – The input to differentiate with respect to.
- laplacian(with_respect_to)[source]¶
Track the Laplacian of this value.
- Parameters:
with_respect_to (TrackingObject) – The input to differentiate with respect to.
- jac(with_respect_to)[source]¶
Track the Jacobian of this value.
- Parameters:
with_respect_to (TrackingObject) – The input to differentiate with respect to.
- div(with_respect_to)[source]¶
Track the divergence of this value.
- Parameters:
with_respect_to (TrackingObject) – The input to differentiate with respect to.
- hessian(with_respect_to)[source]¶
Track the Hessian of this value.
- Parameters:
with_respect_to (TrackingObject) – The input to differentiate with respect to.
- sym_grad(with_respect_to)[source]¶
Track the symmetric gradient of this value.
- Parameters:
with_respect_to (TrackingObject) – The input to differentiate with respect to.
- rot(with_respect_to)[source]¶
Track the rotation (curl) of this value.
- Parameters:
with_respect_to (TrackingObject) – The input to differentiate with respect to.
- matrix_div(with_respect_to)[source]¶
Track the row-wise divergence of this value.
- Parameters:
with_respect_to (TrackingObject) – The input to differentiate with respect to.
qewton.graphs.nodes module¶
Nodes, the building blocks of a Graph,
and their input and output ports.
- class qewton.graphs.nodes.NO_DEFAULT(*args, **kwargs)[source]¶
Bases:
SerializableSentinel denoting that an input port has no default value.
The class itself is the sentinel; it is never instantiated.
- classmethod save(serializer: Serializer) None[source]¶
Serialize a reference to the sentinel class.
- Parameters:
serializer – The serializer that collects the data.
- classmethod construct_new_object(serializer: Deserializer, data_config: dict) Any[source]¶
Return the sentinel class itself.
- Parameters:
serializer – The deserializer managing the loading process.
data_config – The serialized data of the sentinel.
- Returns:
This class.
- Return type:
type[NO_DEFAULT]
- class qewton.graphs.nodes.Port(data_configuration: DataConfiguration, node: Node, name: str)[source]¶
Bases:
SerializableInput or output connection of a node.
Ports are connected by edges in a
Graph. Each port declares a static data configuration describing the data passing through it. A port holds no value: a graph keeps the values and the matched configurations of the ports it contains, seevalue_of()andget_data_configuration().- Parameters:
data_configuration – The static data configuration of this port.
node – The node owning this port.
name – The name of this port.
- name¶
The name of this port.
- Type:
str
- data_configuration¶
The static data configuration of this port.
- Type:
- property data_configuration: DataConfiguration¶
- get_data_configuration(graph, within=None) DataConfiguration | None[source]¶
Return the data configuration of this port inside graph.
- Parameters:
graph (Graph) – The graph whose matched configuration is returned.
within (tuple[GraphNode, ...], optional) – The GraphNodes, from the outside in, leading to the node of this port; needed only where the node occurs at several places of graph, see
config_of().
- Returns:
- The configuration of this port in
graph, or None if the owning node is not part of graph.
- Return type:
DataConfiguration or None
- update_static_data_configuration(new_config: DataConfiguration)[source]¶
Replace the static data configuration of this port.
- Parameters:
new_config – The new static data configuration.
- duplicate_with_new_owner(new_owner: Node, new_name: str | None = None) Port[source]¶
Create a port of the same type and configuration for another node.
- Parameters:
new_owner – The node owning the new port.
new_name – The name of the new port. None (default) keeps the name of this port.
- Returns:
The new port.
- Return type:
- class qewton.graphs.nodes.InputPort(data_configuration: DataConfiguration, node: Node, name: str = 'Input', default: Any = <class 'qewton.graphs.nodes.NO_DEFAULT'>)[source]¶
Bases:
PortInput port of a node.
An input port without an incoming edge holds its default value when the graph runs.
- Parameters:
data_configuration – The static data configuration of this port.
node – The node owning this port.
name – The name of this port.
default – The default value of this port.
NO_DEFAULT(default) marks the port as required.
- default¶
The default value of this port.
- Type:
Any
- is_required¶
Whether this port has no default value and must be connected.
- Type:
bool
- duplicate_with_new_owner(new_owner: Node, new_name: str | None = None) InputPort[source]¶
Create an input port with the same configuration and default for another node.
- Parameters:
new_owner – The node owning the new port.
new_name – The name of the new port. None (default) keeps the name of this port.
- Returns:
The new port.
- Return type:
- property is_required: bool¶
- class qewton.graphs.nodes.OutputPort(data_configuration: DataConfiguration, node: Node, name: str = 'Output')[source]¶
Bases:
PortOutput port of a node.
- Parameters:
data_configuration – The static data configuration of this port.
node – The node owning this port.
name – The name of this port.
- class qewton.graphs.nodes.NodeState(*values)[source]¶
Bases:
EnumState of a node.
- FIXED¶
The node has some fixed behavior that never changes.
- UNINITIALIZED¶
The node needs to be initialized before it can be used, e.g. by calling .setup().
- INITIALIZED¶
The node is ready to be used and can be trained.
- TRAINED¶
The node has been trained and is ready to be used for inference.
- FIXED = 1¶
- UNINITIALIZED = 2¶
- INITIALIZED = 3¶
- TRAINED = 4¶
- class qewton.graphs.nodes.Node(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]¶
Bases:
ABC,Serializable,Generic[TensorType]Base class for all nodes of a graph.
The input and output ports are built from the signature of
forward(): every parameter becomes an input port (a parameter default becomes the port default), every element of the return type (or of a returned tuple) an output port namedoutput_<i>. ADataConfiguration, or a callable taking the node and returning one, given viatyping.Annotatedsets the static data configuration of a port.- Parameters:
name – The name of the node. None (default) uses the class name.
state – The initial state of the node.
backend – The backend used for computations and parameters.
**kwargs – Ignored; accepted so subclasses can pass on extra arguments.
- mode¶
The current evaluation phase, see
set_mode().- Type:
- node_id¶
Unique ID of this node.
- Type:
int
- name¶
The name of the node.
- Type:
str
- output_ports¶
The output ports, in the order of the return values of
forward().- Type:
list[OutputPort]
- hyperparameters¶
The tunable hyperparameters of this node. By default all
HyperParameterinstance attributes.- Type:
list[HyperParameter]
- trainable_parameters¶
The trainable parameters of this node. Empty by default.
- Type:
- memory_consumption¶
The memory consumption of this node in bytes. 0 by default.
- Type:
int
Notes
Subclasses must implement
forward(). They may overridesetup()to create their underlying algorithm, the properties trainable_parameters, hyperparameters and memory_consumption,to(),reset(), andupdate_data_configs()if their ports depend on each other in a non-default way.- mode: EvaluationPhase¶
- property name¶
- classmethod set_tracking(set_active: bool)[source]¶
Switch graph tracking on or off for all nodes.
While tracking is active, calling a node records it in the tracked graph instead of running
forward(), seetracker().- Parameters:
set_active – Whether tracking is active.
- classmethod get_dtype(type_hint, backend: type[Backend[TensorType]])[source]¶
Resolve the dtype of a port from its type hint.
- Parameters:
type_hint (Any) – The type hint of the port.
backend – The backend of the node.
- Returns:
- type_hint if it is
Anyor a concrete type other than TensorType; otherwiseAnyfor the genericBackendand the default dtype of backend for a concrete backend.
- type_hint if it is
- Return type:
Any
- setup(graph=None) None[source]¶
Make the node ready to run: build it (
build()) unless it is built already, i.e. unless its state is other than NodeState.UNINITIALIZED.Called by
setup(). Belongs to the library: subclasses overridebuild(), not this method.- Parameters:
graph (Graph, optional) – The graph being set up; passed on to the build of nodes that need it (
GraphAwareNode).- Raises:
RuntimeError – If a size of the node is still open (see
require_known_sizes()).
- require_known_sizes() None[source]¶
Make sure no hyperparameter waits to be inferred, so that the node can be built.
- Raises:
RuntimeError – Naming the hyperparameters that are still open.
- 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.
- property output_ports: list[OutputPort]¶
- relate(*inputs: DynamicDataConfiguration)[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 ofDataConfiguration).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 raisesStructureUnknown; 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(*args, **kwargs)[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.
- property hyperparameters: list[HyperParameter]¶
- property open_hyperparameters: list[HyperParameter]¶
The hyperparameters still waiting to be inferred from the connected data (see
HyperParameter.is_open); the node can not be built before they are.
- property trainable_parameters: _TrainableParameterBase¶
- 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.
- 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.
- 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.
- set_state(new_state: NodeState)[source]¶
Set the current state of this node.
- Parameters:
new_state – The new state.
- property state¶
- 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.
- get_input_port(name: str | Variable) InputPort[source]¶
Returns the input port matching the given name.
- Parameters:
name (str | Variable) – The name we are looking for, either as a string or as a Variable, in which case the variable’s name is used.
- Raises:
ValueError – If no input port matching the given name is found or the passed variable does not have a name set.
ValueError – If no input port has this name.
- Returns:
The port with this name.
- Return type:
- get_output_port(name: str | Variable) OutputPort[source]¶
Returns the output port matching the given name.
- Parameters:
name (str | Variable) – The name we are looking for, either as a string or as a Variable, in which case the variable’s name is used.
- Raises:
ValueError – If no output port matching the given name is found or the passed variable does not have a name set.
- Returns:
The port matching the given name.
- Return type:
- copy()[source]¶
Create a node sharing this node’s operations and parameters but with its own input and output ports.
- Returns:
- The copy, see
- Return type:
- upgrade(version: int) None[source]¶
See
upgrade().Files of version 1 hold the port declarations of their time: the ports of this node annotated in
forward()are declared anew.- Parameters:
version – The format version of the file.
- 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.graphs.nodes.GraphAwareNode(name: str | None = None, state: NodeState = NodeState.FIXED, backend: type[Backend[TensorType]] = <class 'qewton.backends.base.DeepLearningBackend'>, **kwargs)[source]¶
Bases:
Node[TensorType]Base class for nodes whose build needs the owning graph.
setup()passes itself on, so the build of these nodes gets the graph, e.g. to read the configurations of their ports or to run the graph up to them.Notes
Subclasses implement
build()with the signaturebuild(self, graph), in addition toNode.forward().