Core¶
meanflux.core holds the mathematical objects and the policies that every
model and solver shares. The classes are also available from the package
root, for example from meanflux import Grid.
Grids¶
grid
¶
Uniform grids for the state and the time variable.
The finite-difference schemes in MeanFlux discretise the state \(x\) on a bounded interval and the time \(t\) on \([0, T]\), both with uniform spacing, as in the scheme of Achdou and Capuzzo-Dolcetta (2010).
A grid describes geometry only. It stores Python numbers and no tensor, so
it has no device and no dtype that could disagree with those of the model
parameters, it compares by value, and it can be used as a dictionary key.
The grid points are built on demand by Grid.points and TimeGrid.times,
which take dtype and device like the factory functions of PyTorch.
References
Y. Achdou and I. Capuzzo-Dolcetta (2010). Mean field games: numerical methods. SIAM Journal on Numerical Analysis, 48(3), 1136-1162.
Grid
dataclass
¶
Uniform grid on a bounded interval of the state variable.
The grid has \(N_x\) points
so both ends of the interval are grid points.
Attributes:
| Name | Type | Description |
|---|---|---|
lower |
float
|
Left end \(x_{\min}\) of the interval. |
upper |
float
|
Right end \(x_{\max}\) of the interval. |
size |
int
|
Number of grid points \(N_x\), at least 2. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If a bound is not finite, |
Example
import torch from meanflux import Grid grid = Grid(lower=-1.0, upper=1.0, size=5) grid.spacing 0.5 grid.points(dtype=torch.float64) tensor([-1.0000, -0.5000, 0.0000, 0.5000, 1.0000], dtype=torch.float64)
spacing
property
¶
Distance \(h\) between two neighbouring grid points.
__post_init__()
¶
Validate the fields and store the bounds as floats.
points(*, dtype=None, device=None)
¶
Return the grid points as a tensor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dtype
|
dtype | None
|
Floating-point dtype of the result. Defaults to the default dtype of PyTorch. |
None
|
device
|
device | str | None
|
Device of the result. Defaults to the default device of PyTorch. |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
The points \(x_0, \dots, x_{N_x - 1}\), shape |
Tensor
|
and the last entry equal |
TimeGrid
dataclass
¶
Uniform grid on the time interval \([0, T]\).
The grid has \(N_t\) steps of size \(\Delta t = T / N_t\) and the \(N_t + 1\) time points \(t_n = n \, \Delta t\) for \(n = 0, \dots, N_t\).
Attributes:
| Name | Type | Description |
|---|---|---|
horizon |
float
|
Final time \(T\). |
steps |
int
|
Number of time steps \(N_t\), at least 1. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If |
Example
from meanflux import TimeGrid time_grid = TimeGrid(horizon=2.0, steps=4) time_grid.step_size 0.5 time_grid.size 5 time_grid.times() tensor([0.0000, 0.5000, 1.0000, 1.5000, 2.0000])
size
property
¶
Number of time points, \(N_t + 1\).
step_size
property
¶
Length \(\Delta t\) of one time step.
__post_init__()
¶
Validate the fields and store the horizon as a float.
times(*, dtype=None, device=None)
¶
Return the time points as a tensor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dtype
|
dtype | None
|
Floating-point dtype of the result. Defaults to the default dtype of PyTorch. |
None
|
device
|
device | str | None
|
Device of the result. Defaults to the default device of PyTorch. |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
The times \(t_0, \dots, t_{N_t}\), shape |
Tensor
|
and the last entry equal 0 and |
Supply network¶
SupplyNetwork is a torch.nn.Module. Its edges are an index tensor that
moves with .to(), together with any problem that holds the network.
Goods move from every supplier to its customers and
orders move back. Each node is sized by the total demand of the leaves it
serves, computed level by level with sum_customers.
network
¶
Supply networks of a multi-echelon supply chain.
A supply network is a directed tree on the nodes \(0, \dots, V - 1\). An edge \((v, w)\) means that node \(v\) supplies node \(w\). Every node except the root has exactly one supplier \(s(w)\), a node \(v\) has a set of customers \(C(v)\), and the leaves face external demand. The serial system of Clark and Scarf (1960) is the tree in which every node has at most one customer.
The topology is given as Python integers and checked on the host when the
network is built, in \(O(V)\) time and once. Tensors are rejected as input,
because reading their values would synchronise the device with the host.
On the device the network holds index tensors only, edge_index and the
table behind SupplyNetwork.sum_customers, which a solver uses without
reading them back. The topology is shared by every
scenario of a batch. Scenarios differ in the coefficients of the problem,
not in the network.
References
A. J. Clark and H. Scarf (1960). Optimal policies for a multi-echelon inventory problem. Management Science, 6(4), 475-490.
SupplyNetwork
¶
Bases: Module
Directed tree of supply relations between the nodes of a supply chain.
Node \(w\) is supplied by node supplier[w], and the root, which has no
supplier, is marked by None. Nodes keep the labels given here, so
index \(v\) of every per-node tensor of shape (*batch, V) refers to the
same node.
The level of a node is its distance from the root, which has level 0.
The edges are stored in edge_index, sorted by the level of the
customer and then by its label. The edges into the nodes of one level
therefore form one contiguous block of columns, whose bounds follow
from level_sizes without reading the device.
The network is a torch.nn.Module so that edge_index moves with
.to() together with the problem that holds the network. It is a
non-persistent buffer. The topology is defined by the constructor
arguments, as the shape of torch.nn.Linear is defined by
in_features and out_features, so state_dict() holds no entry for
it, and loading a state dictionary cannot change the topology. The
network defines no forward. Its one computation, sum_customers,
adds a quantity of the customers of every node.
Attributes:
| Name | Type | Description |
|---|---|---|
edge_index |
Tensor
|
Edges of the tree, shape |
Example
from meanflux import SupplyNetwork network = SupplyNetwork.serial(3) network SupplyNetwork(num_nodes=3, root=0, num_levels=3) network.supplier (None, 0, 1) network.edge_index tensor([[0, 1], [1, 2]])
level_sizes
property
¶
Number of nodes at each level, from the root (level 0) downwards.
The edges into the nodes of level \(k \ge 1\) are
edge_index[:, sum(level_sizes[1:k]) : sum(level_sizes[1 : k + 1])].
num_nodes
property
¶
Number of nodes \(V\).
root
property
¶
Label of the root, the only node without a supplier.
supplier
property
¶
Supplier of each node, None for the root.
__init__(supplier, *, device=None)
¶
Build the network from the supplier of every node.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
supplier
|
Sequence[int | None]
|
Supplier of each node, |
required |
device
|
device | str | None
|
Device of |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If an entry of |
ValueError
|
If |
distribution(branching, *, device=None)
classmethod
¶
Build a distribution network in which each level branches evenly.
Every node at level \(k\) supplies branching[k] customers, so the
network has len(branching) + 1 levels. Nodes are labelled level by
level, and the customers of a node get consecutive labels. An empty
branching gives a single node.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
branching
|
Sequence[int]
|
Number of customers of each node of a level, as Python integers of at least 1, from the root downwards. |
required |
device
|
device | str | None
|
Device of |
None
|
Returns:
| Type | Description |
|---|---|
Self
|
The distribution network. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If an entry of |
ValueError
|
If an entry of |
Example
from meanflux import SupplyNetwork network = SupplyNetwork.distribution([2, 2]) network.level_sizes (1, 2, 4) network.supplier (None, 0, 0, 1, 1, 2, 2)
extra_repr()
¶
Return the size of the network for the module representation.
from_edges(edges, *, device=None)
classmethod
¶
Build the network from its edges.
A tree with \(E\) edges has \(V = E + 1\) nodes, so the nodes must be labelled \(0, \dots, E\). The edges may come in any order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edges
|
Iterable[tuple[int, int]]
|
Pairs |
required |
device
|
device | str | None
|
Device of |
None
|
Returns:
| Type | Description |
|---|---|
Self
|
The network with these edges. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If a node label is not a Python integer. |
ValueError
|
If a label is out of range, a node has two suppliers, or the edges do not form a tree. |
Example
from meanflux import SupplyNetwork SupplyNetwork.from_edges([(2, 0), (2, 1)]).supplier (2, 2, None)
serial(num_nodes, *, device=None)
classmethod
¶
Build a serial network, in which node \(v\) supplies node \(v + 1\).
Node 0 is the root and node num_nodes - 1 is the only leaf.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_nodes
|
int
|
Number of nodes, at least 1. |
required |
device
|
device | str | None
|
Device of |
None
|
Returns:
| Type | Description |
|---|---|
Self
|
The serial network. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If |
sum_customers(values)
¶
Sum a per-node quantity over the customers of every node.
Entry \(v\) of the result is \(\sum_{w \in C(v)} \text{values}_w\), and zero for a node without customers. This is how a quantity of the customers, such as their orders, reaches their supplier.
The sum is deterministic. It gathers the customers of each node
into a padded table and adds them in the order of their labels, so
two runs give the same bits on every device. A scatter-add over
edge_index (torch.Tensor.index_add) computes the same sum, but
PyTorch documents it as possibly nondeterministic on a CUDA device.
The table holds one entry per node with customers and per customer
slot, so the sum needs (*batch, I * D) numbers of working memory,
where \(I\) is the number of nodes that have customers and \(D\) the
largest number of customers of a node. For the serial and the
distribution networks this equals the number of edges.
The routine never synchronises the device with the host. It is
differentiable to any order, and half-precision values are summed
in float32, see meanflux.core.working_dtype.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
Tensor
|
Per-node values of shape |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
The sums, with the shape and the dtype of |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If the last dimension of |
Example
import torch from meanflux import SupplyNetwork network = SupplyNetwork.distribution([2]) network.sum_customers(torch.tensor([1.0, 2.0, 4.0])) tensor([6., 0., 0.])
Precision¶
precision
¶
Working precision shared by every numerical routine.
working_dtype(*tensors)
¶
Return the dtype a numerical routine over tensors computes in.
This is the type promotion of the dtypes of the inputs, raised to at
least torch.float32. Half-precision inputs (torch.float16,
torch.bfloat16) are therefore solved in float32 and only the result is
rounded back, the policy torch.autocast applies to reductions such as
cumsum and logsumexp. Elimination and long sums lose every
significant digit of an 8-bit (bfloat16) or 11-bit (float16)
significand, while computing them in float32 leaves the final rounding
to the input dtype as the only visible error. Float32 and float64
inputs are computed in their own precision, so the cast is a no-op that
copies nothing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*tensors
|
Tensor
|
Floating-point tensors entering the computation. |
()
|
Returns:
| Type | Description |
|---|---|
dtype
|
The promoted dtype of |
Example
import torch from meanflux.core import working_dtype working_dtype(torch.ones(2, dtype=torch.bfloat16)) torch.float32 working_dtype(torch.ones(2), torch.ones(2, dtype=torch.float64)) torch.float64