Advanced Guide: Multi-GPU
If multi-GPU jobs hang during communication, try calling
jztree.jax_compat.fix_jax_environment() on every process before JAX backend
initialization (including device queries or jax.distributed.initialize()).
See Known issues for usage and scope.
This is a guide on how to use the multi-GPU functionality in jz-tree. All functionality works both in cases with a single host and multiple GPUs (e.g. if you allocate 4 GPUs on a single node with 1 task) or in multi-host multi-GPU setups (e.g. 4 nodes with 4 GPUs each with 16 tasks).
However, to start with a simple interactive scenario, this guide assumes you are executing this
interactively with a single host on a multi-GPU system. For a multi-host case, the main difference
is that you’d need to execute jax.distributed.initialize() at the beginning, as we will explain later.
Let us start by importing the relevant modules and by declaring a mesh that includes all available GPUs:
import jax
import jax.numpy as jnp
from jax.sharding import PartitionSpec as P
import jztree as jz
from jztree_utils import ics
import numpy as np
mesh = jax.make_mesh((jax.device_count(),), axis_names=("gpus",), axis_types=jax.sharding.AxisType.Auto)
Particle-data and padding
As you may have noticed in the example above, for multi-GPU scenarios our particle data needs to carry
some extra information: not every GPU will have the same number of particles at the same time, and
we need to pad the arrays to allow some extra space for imbalance. Consider the following dataclass
from jztree.data.Pos:
@jax.tree_util.register_dataclass
@dataclass(kw_only=True, slots=True)
class Pos:
pos: jax.Array
num: int | jax.Array | None = None
num_total: int | None = static_field(default=None)
Beyond the position array, it carries a dynamical value num which indicates the currently filled number of particles
(which will be less than or equal to pos.shape[0]) and num_total, which statically defines the total number of
particles.
You may define your own particle data class that follows the same interface. Whenever particles
get communicated or rearranged, we use a jax.tree.map approach to adapt all fields that have the
same leading dimension as pos. To pad particles, you may use the function jztree.data.pad_particles
that adds the indicated number of particles along each pytree leaf that has the correct shape. For example,
this is the implementation of jztree_utils.ics.uniform_particles:
def uniform_particles(N, total_mass=1., seed=0, npad=0):
rank, ndev, axis_name = get_rank_info()
pos = jax.random.uniform(jax.random.PRNGKey(seed + rank), (N,3), dtype=jnp.float32)
posmass = PosMass(pos=pos, mass=total_mass/(N*ndev), num=N, num_total=ndev*N)
return pad_particles(posmass, npad)
uniform_particles.smap = shard_map_constructor(uniform_particles,
in_specs=(None, None, None, None), out_specs=P(-1), static_argnums=(0,3)
)
You can see that it uses the jztree.data.PosMass dataclass which additionally has masses, for example,
as would be required to calculate masses in FoF catalogues. The type hints in jz-tree, e.g. Pos
in jztree.tree.distr_zsort, only indicate a minimal interface, but don’t require that the
provided data is a subclass of the indicated class.
How much padding is needed, and what happens if it is too little, is described in Padding errors and internal padding below.
Distributed kNN
If a padded instance of Pos is provided, the distributed kNN can be used more or less identically to the single-GPU version. However, bringing the full neighbour list back into input order is
very communication-heavy. To avoid this, it is recommended to define a reduction function that
directly extracts the property that you need while all source particles are present in z-order.
Here is an example:
def get_mean_neighbour_rad(N, npad):
part = ics.uniform_particles(N, npad=npad)
def get_rmean(rnn, **kwargs):
return jnp.mean(rnn[:,1:], axis=-1)
rmean = jz.knn.knn(part, k=9, result="reduce", reduce_func=get_rmean)
return part, rmean
get_mean_neighbour_rad.smap = jz.jax_ext.shard_map_constructor(
get_mean_neighbour_rad, in_specs=(None, None), out_specs=(P(-1), P(-1)),
static_argnames=["N", "npad"]
)
part, rmean = get_mean_neighbour_rad.smap(mesh, jit=True)(int(1e6), npad=int(5e5))
print(part.pos.shape, rmean.shape)
print(part.pos[0,0], rmean[0,0])
(4, 1500000, 3) (4, 1500000)
[0.947667 0.9785799 0.33229148] 0.0069931187
This calculates the average distance to the 8 nearest neighbours (excluding the particle itself). For example, you could easily use this to get a local estimate of the density.
The
reduce_funcneeds to have**kwargs, because the code passes several other optional keyword arguments to this function, namelypart,rnn,inn, andorigin, so you could easily define more general reductions.
The reduce_func above reduces the materialized neighbour arrays before returning
results to their owners. For applications that can accumulate during traversal,
custom reductions additionally avoid storing full
neighbour lists and can notably reduce memory usage. The built-in KDE interface
uses this approach.
Distributed KDE
The KDE interface is experimental and may change in future versions. The following complete example can run on one host with all its visible GPUs. For multiple processes, initialize JAX distributed execution first on every process, as described below.
import jax
import jax.numpy as jnp
from jax.sharding import PartitionSpec as P
import jztree as jz
from jztree_utils import ics
from jztree.kde import KNNBandwidth
mesh = jax.make_mesh(
(jax.device_count(),), axis_names=("gpus",),
axis_types=jax.sharding.AxisType.Auto,
)
def estimate_density(cfg):
# Counts and padding here are per GPU; each rank generates different positions.
part = ics.uniform_particles(N=10000, npad=5000)
valid = jnp.arange(part.pos.shape[0]) < part.num
weights = jnp.where(valid, 1.0 / part.num_total, 0).astype(part.pos.dtype)
adaptive = jz.kde.kde(
part, KNNBandwidth(k=32), weights=weights, boxsize=1.0, cfg=cfg,
)
# A shared scalar can be closed over inside the mapped function.
fixed = jz.kde.kde(
part, bandwidth=0.1, weights=weights, boxsize=1.0, cfg=cfg,
)
return part, adaptive, fixed
estimate_density.smap = jz.jax_ext.shard_map_constructor(
estimate_density, in_specs=(None,), out_specs=(P(-1), P(-1), P(-1)),
)
run = estimate_density.smap(mesh, jit=True)
(part, adaptive, fixed), cfg = jz.run_with_fixes(
lambda cfg: run(cfg), jz.config.KNNConfig(extra_pad_fac=0.1),
)
jax.block_until_ready((adaptive, fixed))
print("positions, adaptive, fixed:", part.pos.shape, adaptive.shape, fixed.shape)
cfg.print()
The global arrays have a leading device axis: positions have shape
(ndev, capacity, dim), scalar weights and densities (ndev, capacity), and
vector weights (ndev, capacity, C). Only the first part.num rows on each
device are valid; padded rows are not density samples. Results return to input
order. The explicit weights argument supplies the masses; KDE does not infer
weights from a particle object’s mass field.
For array bandwidths, use (ndev, source_capacity) with bandwidth_at="source"
or (ndev, query_capacity) with bandwidth_at="query". Provide positive finite
radii, including padded entries. Separate queries need their own padded Pos
object and exclude_self=False. Weight arrays always follow the sources.
When calling jz.kde.kde.smap(mesh, jit=True) directly, supply a scalar bandwidth
as an array of shape (ndev,), one scalar per device. KNNBandwidth(k=32) can
be passed directly. Inside a composed map, as above, use ordinary local arrays
and a scalar bandwidth. Configurations control execution and allocation only;
they do not change bandwidth ownership or the kernel.
The example enables internal padding so automatic recovery can also handle
input-capacity failures. For memory-sensitive production runs, size the input
padding in advance and use extra_pad_fac=None; see the allocation guide below.
Distributed friends-of-friends
Distributed friends-of-friends works similarly. For example:
from dataclasses import asdict
def write_callback(rank, cata: jz.data.FofCatalogue):
cata = jz.data.squeeze_catalogue(cata)
print(f"rank: {rank} ngroups {cata.ngroups}")
np.savez(f"fof_catalogue_rank_{rank}.npz", **asdict(cata))
def write_fof_catalogue(N, npad):
rank, ndev, axis_name = jz.comm.get_rank_info()
part = ics.uniform_particles(N, npad=npad)
rlink = 0.7 * np.cbrt(1./part.num_total)
partf, cata = jz.fof.fof_and_catalogue(part, rlink=rlink)
jax.debug.callback(write_callback, rank, cata)
write_fof_catalogue.smap = jz.jax_ext.shard_map_constructor(
write_fof_catalogue, in_specs=(None, None), out_specs=None,
static_argnames=["N", "npad"]
)
write_fof_catalogue.smap(mesh, jit=True)(250000, 100000)
rank: 3 ngroups 310
rank: 1 ngroups 322
rank: 0 ngroups 337
rank: 2 ngroups 320
Note
You may notice that JIT compilation takes significantly longer than for the single-GPU version. This is because JAX’s communication routines compile relatively slowly and FoF requires many of them.
Here we have written the catalogues to disk in a host callback. Inside the host callback, the data is given as NumPy arrays and we can remove the padding in the catalogue with jztree.data.squeeze_catalogue. Every rank writes its own NumPy file.
Here you can verify that the output makes sense:
for rank in range(0,4):
cata = np.load(f"fof_catalogue_rank_{rank}.npz")
print("rank", rank, "ngr", cata["ngroups"], "largest ten:", np.sort(cata["count"])[::-1][0:10])
rank 0 ngr 337 largest ten: [61 54 46 45 43 43 43 43 42 41]
rank 1 ngr 322 largest ten: [64 61 51 47 45 45 43 41 40 40]
rank 2 ngr 320 largest ten: [64 62 55 46 46 44 41 41 40 39]
rank 3 ngr 310 largest ten: [60 52 50 47 46 44 43 43 42 41]
Of course, for an HPC code it is advisable to use a more advanced file format like HDF5 to save the data.
Multi-host execution and performance
Generally, to execute the code with multiple hosts, all you need to add before calling any other JAX function is:
import jax
jax.distributed.initialize()
Of course, you should use a .py script (rather than an .ipynb notebook) for your code, and with Slurm you may execute it as srun python myscript.py. To get good performance, it is very important that you provide a sufficient number of CPUs per task. These extra CPUs are heavily involved in communication, e.g. see this GitHub issue. For the same reason, the single-host multiple-GPU case is significantly slower than the case where you provide one task per GPU. So it is recommended to only use it to interactively develop and test code.
Here is an example Slurm script that I use for some performance measurements on 4 nodes with 4 GPUs each:
#!/bin/bash
#SBATCH --nodes=4
#SBATCH --ntasks-per-node=4
#SBATCH --cpus-per-task=8
#SBATCH --time=00:30:00
#SBATCH --gres=gpu:4
# ...
conda activate cu12.2
cd repos/jz-tree/checks/profiling
srun python multi_gpu.py
Of course, the setup may vary notably, depending on your cluster.
Padding errors and internal padding
There are separate capacities for particle imbalance, local geometry and communication. Increasing one is not a substitute for increasing another:
Capacity |
Setting |
What it holds |
|---|---|---|
Input particles |
Caller-supplied padding, or |
Particles owned locally after redistribution |
Local tree |
|
Local tree nodes |
Received nodes |
|
Nodes requested from other ranks |
Received particles |
|
Particles requested from other ranks |
Node interactions |
|
Candidate node interactions for traversal |
Packed radius-query output |
|
Neighbour indices returned by |
For kNN and FoF, the local-node factor defaults to 1.1; communication-node and
communication-particle factors default to 1.5 and 1.25. Communication capacities
are multiples of the local node and particle array sizes, respectively. They
are separate buffers, not percentages of extra input padding. QueryBallConfig
inherits these factors. KDE and reductions do not allocate packed neighbour
outputs, so alloc_fac_neighbours does not apply to them.
Start with the defaults and inspect failed checks rather than increasing every
factor. jz.run_with_fixes returns both the result and the adjusted configuration,
as in the KDE example above. Reuse that configuration on subsequent calls;
perform recovery and compilation before timing. A setting that fits uniform
particles may be insufficient for a clustered distribution or a larger search.
How much padding is needed depends on how well the particles are balanced between the ranks,
e.g. during the domain decomposition of jztree.tree.distr_zsort or when ranks request
particles from each other. If it is too little, the computation stops with an error whose
suggested fix is "padding" (see the error handling guide): a factor by
which the particle arrays per rank need to grow. Since the padding is part of your input data,
jz.apply_fix cannot fix it in a configuration by default. It raises a ValueError that states
the required length per rank, and you need to pad the inputs more (e.g. with
jztree.data.pad_particles).
Alternatively, the top-level functions can pad their inputs internally. Set extra_pad_fac on
their configuration (KNNConfig, QueryBallConfig, FofConfig): cfg.extra_pad_fac = 0.1 pads every input by
10% of its length per rank, and jz.apply_fix and jz.run_with_fixes then increase it
automatically if the padding is too small. kNN outputs in input order keep the input length,
while z-ordered or FoF-ordered outputs have the padded length.
Internal padding is convenient, but it copies the particle data into larger arrays inside the computation. It is therefore not recommended when memory usage is a concern, e.g. for large runs close to the GPU memory limit. Pad the input arrays when you create them instead, which needs no extra copy.
Opt-in fatal error handling
Failed allocation checks of jz-tree do not need this: they raise the same catchable error on all ranks (see the error handling guide). The following is meant for errors that only some ranks see, e.g. exceptions in your own code or crashes.
--kill-on-bad-exit=1 tells srun to terminate peer tasks when a rank exits
nonzero. A caught Python exception, or a process stuck in JAX shutdown, is not
an exit. For a distributed application where an escaping exception is fatal:
import jax
from jztree.distributed import configure_distributed_fail_fast, fatal_distributed_errors
with fatal_distributed_errors(failure_dir="existing-log-directory"):
configure_distributed_fail_fast()
jax.distributed.initialize()
result = run_tree_analysis()
jax.block_until_ready(result)
Launch all ranks using srun --kill-on-bad-exit=1 .... The context writes the
traceback to stderr and optionally a fatal-PID-UUID.json record, then exits this
rank with status 1 using os._exit. It deliberately bypasses finalizers and
atexit handlers; cleanup must not depend on another rank reaching a collective.
Checkpoint important results during normal execution. The context does not
install global exception handlers or change low-level tree kernels. Exceptions
caught inside the context remain recoverable; successful execution is unchanged.
Asynchronous device errors must be synchronized inside the context.
For this repository’s pytest suite, explicitly add --distributed-fail-fast.
This handles collection failures, pytest-internal errors and interrupts. Failed tests are
recorded and the run continues: failed allocation checks raise the same error on every
rank, and the tests compare their results after the last communication, so all ranks move on
to the next test together. Crashes still stop the job through --kill-on-bad-exit=1.
Expected failures and skips are not fatal. Failure records go beside the requested
JUnit XML; final JUnit XML may be absent because pytest teardown is bypassed.
Missing peer reports must be marked incomplete, not successful. The plugin uses
public pytest hooks rather than manually finalizing pytest’s internal XML writer.
Neither approach can handle a runtime that never returns an exception to Python, and reporting to a blocked filesystem can also hang. Always retain an external step/job timeout. This feature requires a peer-terminating launcher; it does not send signals to other ranks itself. JAX heartbeat timeouts alone do not establish that a live but blocked process has failed.
configure_distributed_fail_fast() explicitly disables JAX’s cooperative
preemption service before initialization. Otherwise that service can intercept
Slurm’s SIGTERM and leave peers waiting for heartbeat failure. This policy trades
cooperative preemption/checkpoint notifications for prompt launcher termination;
use it only for jobs where fatal termination is intended. Calling it after
distributed initialization is an error. The pytest option applies this policy
before initialization; default pytest and library execution do not.