Skip to content
Edit this page View source of this page

MeanFlux

A PyTorch library for mean field games of supply chains. It solves for the equilibrium inventory of every tier of a supply network on the GPU, and reports shortage risk as a differentiable function of the model.

PyPI Python License CI Docs

Pre-alpha

The numerical core is being built, and no equilibrium solver is released yet. This site describes the development version on GitHub. Version 0.0.1 on PyPI only reserves the name.

Overview

Each tier of a multi-echelon supply chain holds a large population of firms that manage their own inventory. In a mean field game every firm optimises against the distribution of all the others, and the equilibrium is a pair of a value function \(u\) and an inventory density \(m\) that solves a Hamilton-Jacobi-Bellman equation backward in time and a Fokker-Planck equation forward in time12,

\[ \begin{aligned} -\partial_t u - \nu \, \partial_{xx} u + H(x, \partial_x u) &= f(x, m), \\ \partial_t m - \nu \, \partial_{xx} m - \partial_x \big( m \, \partial_p H(x, \partial_x u) \big) &= 0 . \end{aligned} \]

MeanFlux discretises this system with monotone finite differences3, which keep mass and positivity exactly, and solves it for every node of a supply network and every scenario of a batch at once. Shortage risk, such as the probability of a stockout, is then an integral of \(m\). The derivations are in Mathematical formulations.

In action

Goods move from every supplier to its customers and orders move back. The demand sits at the leaves, and each node is sized by the total demand it serves, computed level by level with SupplyNetwork.sum_customers. Hover a node for its data.

Every implicit time step solves one tridiagonal system per node and scenario. After k levels of parallel cyclic reduction the system splits into 2k interleaved systems, which the Thomas algorithm sweeps in parallel (highlighted rows). The chart counts the work of one solve of 192 systems on 401 points. Each level halves the sequential steps and adds arithmetic, and solve_tridiagonal picks the number of levels from the batch and the device.

Every figure on this site is drawn in the browser from data that python -m tools.figures computes with MeanFlux when the site is built.

Core components

  • Supply network


    SupplyNetwork stores a tree of suppliers and customers as index tensors, built from a supplier list, from edges, or as a serial or distribution network. sum_customers adds a quantity of the customers of every node, with the same bits on every run.

    meanflux.core

  • Grids


    Grid and TimeGrid describe the uniform state and time grids of the schemes. They hold Python numbers only and build their points on any device.

    meanflux.core

  • Tridiagonal solver


    solve_tridiagonal solves batches of tridiagonal systems by a hybrid of parallel cyclic reduction and the Thomas algorithm, in place, with rules for reverse mode, forward mode and torch.func.vmap.

    meanflux.numerics

  • Working precision


    working_dtype raises half-precision inputs to float32 for the computation and rounds only the result back.

    meanflux.core

Why MeanFlux

  • GPU-first


    Every routine is batched over leading dimensions and never synchronises the device with the host. The tests pin the number of synchronisations and of tensor operations of each routine.

  • Native PyTorch


    A class that holds tensors is a torch.nn.Module, so one .to(device) moves a whole model. Functions compose with torch.func, and torch is the only runtime dependency.

  • Differentiable


    The linear solves have reverse- and forward-mode rules that cost one extra solve each. Gradients through the equilibrium itself, by implicit differentiation, are the next step.

  • Verified numerics


    Every routine is tested against a closed form or a dense reference, with property-based tests and gradcheck, at full line coverage, on Linux, macOS and Windows and Python 3.11 to 3.14.

  • Guarded speed


    Continuous integration times every pull request against its base commit in alternating runs, and repeated runs give bitwise equal results.

Install

MeanFlux needs Python 3.11 or newer and PyTorch 2.2 or newer. Until the first release, install it from a clone of the repository.

git clone https://github.com/navidsharifi/meanflux.git
cd meanflux
python -m venv .venv
.venv\Scripts\Activate.ps1
git clone https://github.com/navidsharifi/meanflux.git
cd meanflux
python -m venv .venv
source .venv/bin/activate

Then install the PyTorch build for your hardware, as the PyTorch selector lists it, and MeanFlux itself.

pip install torch --index-url https://download.pytorch.org/whl/cu132
pip install -e .
pip install torch --index-url https://download.pytorch.org/whl/cpu
pip install -e .

Contributors add the development and documentation tools with pip install -e ".[dev,docs]".

Quick start

The example builds a distribution network, totals the demand that each node serves, and solves the linear systems of one implicit diffusion step for 64 scenarios and every node at once.

import torch
from meanflux import Grid, SupplyNetwork, TimeGrid
from meanflux.numerics import solve_tridiagonal

device = "cuda" if torch.cuda.is_available() else "cpu"

# A factory, two warehouses and six retailers. Demand sits at the retailers.
network = SupplyNetwork.distribution([2, 3], device=device)
demand = torch.tensor([0, 0, 0, 2.0, 1.5, 1.0, 2.5, 1.0, 2.0], device=device)
total = demand
for _ in range(len(network.level_sizes) - 1):
    total = demand + network.sum_customers(total)  # 10.0 at the factory

# One implicit step of the heat equation, 64 scenarios x 9 nodes x 401 points.
grid = Grid(lower=-20.0, upper=60.0, size=401)
time_grid = TimeGrid(horizon=4.0, steps=400)
coupling = 0.5 * time_grid.step_size / grid.spacing**2
off = torch.full((64, network.num_nodes, grid.size), -coupling, device=device)
rhs = torch.rand(64, network.num_nodes, grid.size, device=device)
solution = solve_tridiagonal(off, 1.0 - 2.0 * off, off, rhs)  # (64, 9, 401)

Imports

The main classes are re-exported from the package root, and functions stay in their subpackage, as torch.linalg.solve does.

from meanflux import Grid, SupplyNetwork, TimeGrid
from meanflux.core import working_dtype
from meanflux.numerics import solve_tridiagonal

An algorithm will run through solver.solve(problem). The package root holds no workflow function.

Versioning

MeanFlux follows Semantic Versioning. During 0.x a minor release may change the public API and a patch release does not. A name is public when it is listed in the __all__ of meanflux or of one of its subpackages.

Citing

The citation metadata is in CITATION.cff, which the "Cite this repository" button of GitHub turns into APA or BibTeX.

Contributing

The development workflow, the design rules and the pull request checklist are in CONTRIBUTING.md.


  1. J.-M. Lasry and P.-L. Lions (2007). Mean field games. Japanese Journal of Mathematics, 2(1), 229-260. ↩

  2. M. Huang, R. P. Malhamé and P. E. Caines (2006). Large population stochastic dynamic games. Communications in Information and Systems, 6(3), 221-252. ↩

  3. Y. Achdou and I. Capuzzo-Dolcetta (2010). Mean field games: numerical methods. SIAM Journal on Numerical Analysis, 48(3), 1136-1162. ↩