Running nx-parallel backends on Free-Threaded Python#

This notebook is a hands-on tour of the parallel backends nx-parallel can dispatch to (Loky, Threading, Dask, Multiprocessing, and Ray), run on Python 3.14’s free-threaded build (3.14t).

Why free-threaded Python matters here: on a normal (GIL-enabled) Python build, the threading backend usually can’t speed up CPU-bound graph algorithms – only one thread can execute Python bytecode at a time, so threads mostly just take turns instead of running in parallel. Free-threaded Python (PEP 703) removes that restriction, so threads can execute simultaneously on separate cores. That makes threading a genuinely useful backend!

The following tutorial notebook compares the following, and along with that showcases different ways for calling a backend function and setting configs from both NetworkX and Joblib’s config systems:

  • Sequential NetworkX : the baseline, no backend involved.

  • Loky : nx-parallel’s default: process-based.

  • Threading : thread-based, only viable as a real speedup because we’re on 3.14t.

  • Multiprocessing : joblib’s other process-based backend.

  • Dask : a distributed scheduler; useful when you want to scale past one machine later, at the cost of some setup overhead.

  • Ray : process-based like Loky and Multiprocessing.

Creating the Python environment#

Run the following commands in your terminal to create the environment for free-threaded python. This is done because this tutorial uses the Threading parallel backend and for it to give speedups free-threaded python is needed.

cd nx-parallel
uv python install 3.14t
uv python pin 3.14t

uv venv --python 3.14t
source .venv/bin/activate

uv pip install -e '.[test]'
uv pip install git+https://github.com/networkx/networkx.git@main
uv pip install git+https://github.com/joblib/joblib.git@main
uv pip install -e .
uv pip install "dask[complete]" 
# uv pip install "ray"

A couple of things worth calling out about that setup:

  • uv python install 3.14t / uv python pin 3.14t get you the free-threaded build – note the trailing t. A regular uv python install 3.14 gives you the normal GIL build, which would make the Threading section below pointless (or actively slower, since it’d be paying thread overhead with no parallelism to show for it).

  • We install NetworkX and joblib from their main branches rather than the latest release, because free-threading support in the ecosystem is moving fast and the released versions may not yet have full 3.14t support baked in.

  • Ray is deliberately commented out. As of this writing, Ray doesn’t ship free-threaded wheels – more on how we still demo it further down.

Importing libraries#

import time
import sys
import platform
import psutil
import joblib
import networkx as nx
import logging
import nx_parallel as nxp
from dask.distributed import Client, LocalCluster
import dask
# from ray.util.joblib import register_ray

Machine specs#

Every timing in this notebook is only meaningful relative to the hardware it ran on – printing the core count and RAM up front means anyone reading this later (including future-us) can sanity-check whether a given result should still hold on their machine. If you’re reading this on a 2- or 4-core machine, expect the gap between the sequential and parallel timings to be smaller than what’s shown here.

print("OS:", platform.system())
print("Machine:", platform.machine())
print("Architecture:", platform.architecture()[0])
print("Number of CPUs:", joblib.cpu_count())
print("CPU:", platform.processor())
print("RAM (GB):", round(psutil.virtual_memory().total / 1024**3, 2))
OS: Darwin
Machine: arm64
Architecture: 64bit
Number of CPUs: 8
CPU: arm
RAM (GB): 8.0

Confirming the environment is actually free-threaded#

sys._is_gil_enabled() is the ground truth here – it’s easy to think you’re on 3.14t because you ran uv python pin 3.14t, but still end up in a GIL-enabled interpreter if the wrong kernel got selected. If this prints True, stop and fix your environment before trusting any of the Threading numbers below.

print("Python:", sys.version)
print("GIL enabled:", sys._is_gil_enabled())
print("Joblib version:", joblib.__version__)
print("NetworkX version:", nx.__version__)
print("nx-parallel version:", nxp.__version__)
print("Dask version:", dask.__version__)
print("Ray version:", "Not installed" if "ray" not in sys.modules else ray.__version__)  # noqa: F821
Python: 3.14.6 free-threading build (main, Jun 23 2026, 15:54:43) [Clang 22.1.3 ]
GIL enabled: False
Joblib version: 1.6.dev0
NetworkX version: 3.7rc0.dev0
nx-parallel version: 0.5rc0.dev0
Dask version: 2026.7.1
Ray version: Not installed

Enabling NetworkX’s backend-dispatch logging#

NetworkX’s backend system decides, per call, whether to run your code natively or hand it off to a backend like nx-parallel. Turning the logger to DEBUG makes that decision visible – you’ll see lines like “Using backend ‘parallel’ for call to ‘betweenness_centrality’” in the output of the cells below, which is genuinely useful for confirming a call actually got dispatched the way you expect (and for spotting graph conversion/caching behavior, which we’ll hit in the Multiprocessing section).

For more refer the Introspection and Logging section in NetworkX’s backend documentation.

nxl = logging.getLogger("networkx")
nxl.addHandler(logging.StreamHandler())
nxl.setLevel(logging.DEBUG)

nx-parallel’s configuration#

nx.config.backends.parallel is nx-parallel’s config object, exposed through NetworkX’s own configuration system. verbose=100 here turns up joblib’s own progress logging (the [Parallel(n_jobs=...)]: Done ... lines you’ll see later), separately from the NetworkX dispatch logging enabled above. See Config.md for the full set of config options and how the NetworkX and joblib config systems interact.

# Setting nx-parallel Configs (via NetworkX)

nxp_config = nx.config.backends.parallel
nxp_config.verbose = 100

Creating a test graph#

A 2000-node random graph with edge probability 0.2 gives us a dense-ish graph that’s large enough for parallelization overhead to actually pay off.

ParallelGraph wraps the plain NetworkX graph G so it can be later passed to a backend function directly (type-based dispatching).

%%time

G = nx.fast_gnp_random_graph(2000, 0.2, seed=42)
H = nxp.ParallelGraph(G)
print("created graph:", G)
created graph: Graph with 2000 nodes and 399283 edges
CPU times: user 505 ms, sys: 20.1 ms, total: 525 ms
Wall time: 530 ms

Baseline: plain NetworkX#

No backend, no parallelism.

%%time
# =================== NetworkX ================================

print("Running betweenness centrality....\n")

nx.betweenness_centrality(G, seed=42)
print("NetworkX:")
Running betweenness centrality....

NetworkX:
CPU times: user 3min 4s, sys: 1.08 s, total: 3min 5s
Wall time: 3min 7s

Loky (nx-parallel’s default backend)#

Here, we dispatch to the nx-parallel backend by adding a backend="parallel" keyword argument to a standard NetworkX function call. By default, when using nxp_config the n_jobs ia set to -1, unlike in joblib’s paralle_config where n_jobs=None by default.

%%time
# ====================== Loky (default) =============================
# using `backend=` kwarg for dispatching

nx.betweenness_centrality(G, seed=42, backend="parallel")
print("Loky (default):")
Converting input graphs from 'networkx' backend to 'parallel' backend for call to 'betweenness_centrality'
Caching converted graph (from 'networkx' to 'parallel' backend) in call to 'betweenness_centrality' for 'G' argument
Using backend 'parallel' for call to 'betweenness_centrality' with arguments: (G=<nx_parallel.interface.ParallelGraph object at 0x2ebc5a4a650>, k=None, normalized=True, weight=None, endpoints=False, seed=<random.Random object at 0x2ebb5061810>)
[Parallel(n_jobs=-1)]: Using backend LokyBackend with 8 concurrent workers.
[Parallel(n_jobs=-1)]: Done   1 tasks      | elapsed:  1.3min
[Parallel(n_jobs=-1)]: Done   2 out of   8 | elapsed:  1.3min remaining:  3.8min
[Parallel(n_jobs=-1)]: Done   3 out of   8 | elapsed:  1.3min remaining:  2.1min
[Parallel(n_jobs=-1)]: Done   4 out of   8 | elapsed:  1.3min remaining:  1.3min
[Parallel(n_jobs=-1)]: Done   5 out of   8 | elapsed:  1.3min remaining:   46.2s
[Parallel(n_jobs=-1)]: Done   6 out of   8 | elapsed:  1.3min remaining:   25.7s
[Parallel(n_jobs=-1)]: Done   8 out of   8 | elapsed:  1.3min finished
Loky (default):
CPU times: user 1.82 s, sys: 388 ms, total: 2.21 s
Wall time: 1min 17s

Threading#

We pass the ParallelGraph object H directly (type-based dispatching) and set the backend via a nxp_config context manager. NetworkX’s backend machinery checks the H.__networkx_backend__ to get the backend name and dispatch to the apt backend.

%%time
# ====================== Threading =============================
# using backend-graph-object for dispatching + networkx's config for configuring

with nxp_config(backend="threading"):
    nx.betweenness_centrality(H, seed=42)
print("Threading:")
Using backend 'parallel' for call to 'betweenness_centrality' with arguments: (G=<nx_parallel.interface.ParallelGraph object at 0x2ebc8771b10>, k=None, normalized=True, weight=None, endpoints=False, seed=<random.Random object at 0x2ebb5063c10>)
[Parallel(n_jobs=-1)]: Using backend ThreadingBackend with 8 concurrent workers.
[Parallel(n_jobs=-1)]: Done   1 tasks      | elapsed:  1.4min
[Parallel(n_jobs=-1)]: Done   2 out of   8 | elapsed:  1.4min remaining:  4.2min
[Parallel(n_jobs=-1)]: Done   3 out of   8 | elapsed:  1.4min remaining:  2.3min
[Parallel(n_jobs=-1)]: Done   4 out of   8 | elapsed:  1.4min remaining:  1.4min
[Parallel(n_jobs=-1)]: Done   5 out of   8 | elapsed:  1.4min remaining:   50.6s
[Parallel(n_jobs=-1)]: Done   6 out of   8 | elapsed:  1.4min remaining:   28.2s
[Parallel(n_jobs=-1)]: Done   8 out of   8 | elapsed:  1.4min finished
Threading:
CPU times: user 10min 1s, sys: 4.69 s, total: 10min 6s
Wall time: 1min 24s

Multiprocessing#

Unlike the cells above, this one deactivates the default NetworkX’s config system – we set nxp_config.active = False so nx-parallel stops managing joblib for us, and then we configure joblib’s parallel_config context manager directly. This is the pattern you’d reach for if you’re integrating nx-parallel into a codebase that already manages its own joblib configuration elsewhere. verbose=100 here means you’ll see joblib’s own per-task progress log (Done 1 tasks..., etc.).

Also, note we are using n_jobs=5 (and not n_jobs=-1 like for all other parallel backends) here for demonstration purposes. So, you can try it with n_jobs=-1 to get the maximum performance improvements.

Note that we use time.time() instead of %time because with %time the time taken by for new created processes doesn’t get accounted.

# ====================== Multiprocessing =============================
# Using joblib's parallel_config for configuring

t1 = time.time()
nxp_config.active = False
with joblib.parallel_config(n_jobs=5, backend="multiprocessing", verbose=100):
    nx.betweenness_centrality(G, seed=42, backend="parallel")
t2 = time.time()

print()
print("Multiprocessing:", t2 - t1, "seconds")
Converting input graphs from 'networkx' backend to 'parallel' backend for call to 'betweenness_centrality'
/Users/kavitajuneja/Desktop/nx-parallel/.venv/lib/python3.14t/site-packages/networkx/utils/backends.py:1386: UserWarning: Note: conversions to backend graphs are saved to cache (`G.__networkx_cache__` on the original graph) by default.

This warning means the cached graph is being used for the 'parallel' backend in the call to betweenness_centrality.

For the cache to be consistent (i.e., correct), the input graph must not have been manually mutated since the cached graph was created. Examples of manually mutating the graph data structures resulting in an inconsistent cache include:

    >>> G[u][v][key] = val

and

    >>> for u, v, d in G.edges(data=True):
    ...     d[key] = val

Using methods such as `G.add_edge(u, v, weight=val)` will correctly clear the cache to keep it consistent. You may also use `G.__networkx_cache__.clear()` to manually clear the cache, or set `G.__networkx_cache__` to None to disable caching for G. Enable or disable caching globally via `nx.config.cache_converted_graphs` config.

To disable this warning:

    >>> nx.config.warnings_to_ignore.add("cache")

  warnings.warn(
Using cached converted graph (from 'networkx' to 'parallel' backend) in call to 'betweenness_centrality' for 'G' argument
Using backend 'parallel' for call to 'betweenness_centrality' with arguments: (G=<nx_parallel.interface.ParallelGraph object at 0x2ebc5a4a650>, k=None, normalized=True, weight=None, endpoints=False, seed=<random.Random object at 0x2ebb5064810>)
[Parallel(n_jobs=5)]: Using backend MultiprocessingBackend with 5 concurrent workers.
[Parallel(n_jobs=5)]: Done   1 tasks      | elapsed:  1.5min
[Parallel(n_jobs=5)]: Done   2 out of   5 | elapsed:  1.5min remaining:  2.3min
[Parallel(n_jobs=5)]: Done   3 out of   5 | elapsed:  1.5min remaining:  1.0min
[Parallel(n_jobs=5)]: Done   5 out of   5 | elapsed:  1.5min finished

Multiprocessing: 92.44938230514526 seconds

Worth pausing on the warning above. When we ran NetworkX with the Loky backend above, NetowrkX cached the converted graph object for the parallel backend (G.__networkx_cache__), so this warning is telling us that the same cached graph is being used. That’s a nice performance win, but it comes with a sharp edge: if you mutate G directly (e.g. G[u][v][key] = val) instead of through NetworkX’s own mutation methods (G.add_edge(...)), the cache goes stale and you can silently get results computed on outdated graph data. If you’re ever unsure, G.__networkx_cache__.clear() resets it, or set nx.config.cache_converted_graphs = False to disable caching globally.

Note that for nx-parallel backend the graph conversion isn’t a very costly opteration, because ParallelGraph is just a wrapper around nx.Graph class. But, this conversion can be very expensive for other networkx backends like nx-cugraph– so this caching is very useful for such backends.

Dask#

LocalCluster creates a local Dask scheduler and workers – this is the same API you’d use to eventually point at a real multi-machine cluster, which is Dask’s main advantage over the other backends here: it’s the only one that scales beyond a single machine. The dashboard link printed below is worth opening and exploring while the cell below runs; it shows task scheduling in real time. Note we time this one manually with time.time() rather than %%time, because otherwise only the time taken for creating the client is included in the output.

Also, note that passing a nx.Graph() in a nx-parallel function call also works! Because there isn’t much difference between nx.Graph and nxp.ParallelGraph but it is not recommended as it might not be the case in the future.

# ====================== Dask =============================
# Using nxp_config for configuring

nxp_config.active = True  # re-activating networkx's config

t1 = time.time()

cluster = LocalCluster(n_workers=8)
client = Client(cluster)
print(client.dashboard_link)

with nxp_config(backend="dask"):
    nxp.betweenness_centrality(G, seed=42)

t2 = time.time()

print("Dask:", t2 - t1, "seconds")
http://127.0.0.1:8787/status
[Parallel(n_jobs=-1)]: Using backend DaskDistributedBackend with 8 concurrent workers.
[Parallel(n_jobs=-1)]: Done   1 tasks      | elapsed:  1.9min
[Parallel(n_jobs=-1)]: Done   2 out of   8 | elapsed:  2.0min remaining:  5.9min
[Parallel(n_jobs=-1)]: Done   3 out of   8 | elapsed:  2.0min remaining:  3.3min
[Parallel(n_jobs=-1)]: Done   4 out of   8 | elapsed:  2.0min remaining:  2.0min
[Parallel(n_jobs=-1)]: Done   5 out of   8 | elapsed:  2.0min remaining:  1.2min
[Parallel(n_jobs=-1)]: Done   6 out of   8 | elapsed:  2.0min remaining:   39.3s
[Parallel(n_jobs=-1)]: Done   8 out of   8 | elapsed:  2.0min finished
Dask: 120.23676109313965 seconds

Ray (runs in an another, GIL python environment)#

Ray doesn’t currently ship wheels for the free-threaded ABI (cp314t), and its C extensions haven’t been ported yet – so import ray simply isn’t installable in this 3.14t kernel as of today (this is the same reason the uv pip install "ray" line at the top is commented out).

Rather than dropping Ray from the notebook entirely, we run its demo in a separate Python environment and pull the output back into this notebook with IPython’s %%script cell magic – so you still get the Ray comparison in the same notebook, without needing this kernel to import a package it’s incompatible with.

One-time setup, outside this notebook:

# a normal (GIL-enabled) Python, separate from the .venv used for this notebook
uv venv .venv-ray --python 3.13
source .venv-ray/bin/activate
uv pip install ray networkx nx-parallel

Then point the %%script magic below at that environment’s interpreter.

%%script .venv-ray/bin/python
# ====================== Ray (run in a separate, standard-GIL env) ============
# Everything in this cell executes in the .venv-ray interpreter above, not in
# this notebook's 3.14t kernel.

import time
import networkx as nx
import nx_parallel as nxp
from ray.util.joblib import register_ray

G = nx.fast_gnp_random_graph(2000, 0.2, seed=42)
H = nxp.ParallelGraph(G)

t1 = time.time()

register_ray()

with nx.config.backends.parallel(backend="ray", verbose=100):
    nxp.betweenness_centrality(H, seed=42)

t2 = time.time()

print("Ray:", t2 - t1, "seconds")
2026-08-16 05:14:11,360	INFO ray_backend.py:74 -- Starting local ray cluster
2026-08-16 05:14:13,604	INFO worker.py:2024 -- Started a local Ray instance.
2026-08-16 05:14:14,595	WARNING pool.py:602 -- The 'context' argument is not supported using ray. Please refer to the documentation for how to control ray initialization.
[Parallel(n_jobs=-1)]: Using backend RayBackend with 8 concurrent workers.
[Parallel(n_jobs=-1)]: Done   1 tasks      | elapsed:  1.3min
[Parallel(n_jobs=-1)]: Done   2 out of   8 | elapsed:  1.3min remaining:  3.8min
[Parallel(n_jobs=-1)]: Done   3 out of   8 | elapsed:  1.3min remaining:  2.1min
[Parallel(n_jobs=-1)]: Done   4 out of   8 | elapsed:  1.3min remaining:  1.3min
[Parallel(n_jobs=-1)]: Done   5 out of   8 | elapsed:  1.3min remaining:   45.7s
[Parallel(n_jobs=-1)]: Done   6 out of   8 | elapsed:  1.3min remaining:   25.4s
[Parallel(n_jobs=-1)]: Done   8 out of   8 | elapsed:  1.3min finished
Ray: 77.24285411834717 seconds