🔪 The Sharp Bits 🔪#
Compatible devices#
NVIDIA GPU: Heavily tested, best performance
AMD GPU: To be supported in the future
CPU: Supported but not heavily tested
Google TPU: Supported but not heavily tested
Determinants and Pfaffians of the fermionic models are computed by fermix, whose Pallas kernels run on NVIDIA GPUs. On other devices, fermix falls back to a much slower generic jax.numpy implementation and emits a FermixFallbackWarning on every call. The results are the same, so the warning can be silenced with warnings.filterwarnings("ignore", category=fermix.FermixFallbackWarning).
Caveats on Google TPU#
The default matmul and convolution precision is
bfloat16on TPU. Usejax.config.update("jax_default_matmul_precision", precision)withprecision="high"or"highest"for precision similar to GPU.Double precision is very slow on TPU. To avoid it in the SR solver, choose
solver=quantax.optimizer.lsmr().
Global system#
Quantax stores the system geometry and Hilbert space — the Sites (or Lattice) — as a process-global constant, retrieved anywhere via quantax.get_sites() and quantax.get_lattice(). This differs from most NQS packages, where the system is an ordinary object passed around explicitly.
The consequence is that only one Sites should exist per Python process. Constructing a second one does not raise an error; it merely warns and overwrites the first, which can lead to hard-to-debug behavior. This is especially easy to trigger in notebooks by re-running a cell that builds the system.
To switch to a different system, restart the Python interpreter (or the notebook kernel).
Randomness#
Quantax keeps a single global PRNG key, replicated across all devices. Set it with quantax.set_random_seed() (the default seed is 42) for reproducible runs, and draw fresh subkeys with quantax.get_subkeys().
Because get_subkeys reads and updates this global key, it is not jittable. Call it outside jitted functions and pass the resulting keys in as arguments.
Data precision#
By default, JAX
disables double precision, so
float64/complex128silently fall back tofloat32/complex64;uses TF32, a reduced-precision format, for the matmuls and convolutions of
float32inputs on supported GPUs, whenever possible.
Quantax does NOT change these defaults. Most computations work well under this setting, but be careful in the following cases.
Matrix inversion / linear solves. Several solvers in
quantax/optimizer/solver.pyswitch to FP64 (with jax.enable_x64()) or FP32 matmuls (precision='highest') locally to keep the inverse accurate.Local updates. Higher precision might be required in local updates to avoid error accumulation.
The Metropolis-Hastings test of the Metropolis samplers is done in FP64 inside the jitted update (with jax.enable_x64()): the acceptance rate \(R = |\psi(s')/\psi(s)|^n\) is computed from the wave functions cast to FP64, so the acceptance probability \(\min(1, R)\) is not limited by the overflow of \(|\psi|^n\), the \(2^{-23}\) grid of a float32 uniform random number or the rounding of \(R\) near 1. The uniform random number is assembled from two 32-bit draws, because 64-bit random bits can’t be generated inside a jitted function with x64 disabled. The sampling probability prob is computed from the wave function only at the end of the sweep, as a LogArray that doesn’t overflow, with the wave function below single precision promoted to float32.
To enable double precision globally, call jax.config.update("jax_enable_x64", True). Alternatively, call quantax.set_default_dtype(jnp.float64) to set jnp.float64 as the default data type in Quantax, which also turns on jax_enable_x64. To disable TF32, call jax.config.update("jax_default_matmul_precision", "float32").
The variational models in quantax.model deliberately ignore the Quantax default dtype and pick their own (usually float32) for efficiency, so quantax.set_default_dtype() does not change them.
To JIT or not to JIT#
jax.jit greatly accelerates JAX functions, but it imposes constraints on the jitted function and can make the code harder to read.
In Quantax, our strategy is to apply jax.jit only to functions that are likely to be the bottleneck of a simulation, and to keep the rest unjitted for flexibility. For instance, quantax.operator.Operator.expectation() is left unjitted so that it can compute the expectation of arbitrary states, while the forward pass of quantax.state.Variational — the actual bottleneck when computing expectation values — is jitted.
Wavefunction overflow#
Many-body wavefunctions often span a wide range of magnitudes, even beyond the limit of FP64. In many packages, e.g. NetKet and jVMC, the wavefunction amplitudes are expressed by \(\log \psi\) instead of \(\psi\) to avoid overflow (and underflow).
In Quantax, we don’t utilize this approach for the following reasons.
Ground-state wavefunctions are often real-valued with signs. Expressing them using \(\log \psi\) forces one to perform optimization in the complex space.
\(\log\psi\) is discontinuous at \(\psi=0\), which might cause stability issues.
Instead, Quantax keeps \(\psi\) but stores its magnitude in log space. The custom array type LogArray in quantax.utils implements this as a PyTree with two leaves: value = sign * exp(logabs), with sign being \(\pm 1\) or a complex phase and logabs the real log-magnitude. An exact zero is encoded by sign = 0 and logabs = -inf.
The sign/phase stays attached to the amplitude, so a real sign-structured wavefunction remains real and continuous at \(\psi=0\). Arithmetic is overloaded to act in the log space (e.g. multiplying two LogArrays adds the logabs, never forming the overflowing product); convert back to jax.Array with arr.value() or jnp.asarray(arr).
For details of constructing neural wavefunctions with LogArray, see tutorial build your network.
Chunk size#
max_parallel of Variational sets the maximum number of configurations evaluated per device in one forward pass, the chunk. It bounds the memory of the forward pass and fixes the batch shapes to avoid re-jitting. The three forward paths use the chunk differently.
Direct forward pass
state(s): the batch is evaluated chunk by chunk, and a batch smaller than the chunk is padded up to it, so that every batch size is lowered in the same way. Unlike sampling, a batch smaller than the chunk is padded up to it.Sampling by the Metropolis samplers: the Markov chains are swept
min(nsamples // ndevices, chunk)at a time, with the chunk of local updates (ref_chunk) for states using them, padded only when a smaller chunk does not divide the per-device sample count, so a chunk larger than the per-device sample count costs nothing.Local energy and observables (
Oloc()): the forward pass runs on the connected configurations \(s'\) (plus the samples if their \(\psi\) is still missing), rounded up to a multiple of the chunk, so everyOloccall costs at least one full chunk. For a Hamiltonian this batch is usually much larger than the chunk, and a larger chunk means fewer and larger forward passes.
Hence, max_parallel should not be set to the per-device sample count by reflex. A larger chunk is usually better for the local energy, as long as it fits in the memory. The opposite holds when many small operators with a few connected configurations per sample (e.g. single \(\sigma^x_i\), hopping or pair terms) are measured one Oloc call at a time: each call is padded to a full chunk, so pack the terms into one forward pass or measure them with a second state whose chunk is about the per-device sample count. The chunk counts input configurations: under symm, each forward pass evaluates chunk \(\times\) nsymm images, so don’t multiply the chunk by nsymm. The backward pass of the Jacobian needs the most memory per configuration and usually limits the chunk; see the formats of max_parallel in Variational. Benchmark a few chunk sizes before a large-scale simulation.
In reduced precision, e.g. TF32 or half precision, different batch sizes may give slightly different \(\psi\), so the samples and the local energy may effectively use different wavefunctions, which breaks the strict variationality of VMC. If the chains are evaluated in a batch smaller than the chunk, the Metropolis samplers don’t return the \(\psi\) of the sweep. It is then evaluated in the forward pass of the connected configurations in Oloc(), usually without an extra forward pass, and the samples are reweighted from prob. Without max_parallel, the batch size is not fixed at all, which is warned when the state is defined in reduced precision.
HPC usage#
There are 3 ways to submit JAX jobs on HPC. Here we provide the caveats in the python script and the slurm scripts on the NERSC cluster as examples. In all cases, the users only need a few lines of code to control the distributed initialization of JAX, while the Quantax API works the same way as on a single device.
Single-node, only one process#
In the single-node case, one doesn’t have to do anything special in the python script. The slurm script is given below.
#!/bin/bash -l
#SBATCH --nodes=1
#SBATCH --ntasks-per-node=1
#SBATCH --gpus-per-task=<number_of_gpus>
#SBATCH --output=gpu-out.%j
#SBATCH --error=gpu-err.%j
#SBATCH --time=<time_of_simulations>
#SBATCH --constraint=gpu
#SBATCH --qos=regular
#SBATCH --account=<account_name>
source <path_to_quantax_env>/bin/activate
srun --cpu-bind=none python -u <path_to_python_script>
Multi-node, one process per GPU#
#!/bin/bash -l
#SBATCH --nodes=<number_of_nodes>
#SBATCH --ntasks-per-node=4 # 4 GPUs / node on NERSC
#SBATCH --gpus-per-task=1
#SBATCH --gpu-bind=none
#SBATCH --mem=0
#SBATCH --output=gpu-out.%j
#SBATCH --error=gpu-err.%j
#SBATCH --time=<time_of_simulation>
#SBATCH --constraint=gpu
#SBATCH --qos=regular
#SBATCH -c 32
#SBATCH --account=<account_name>
source <path_to_quantax_env>/bin/activate
# Specific to multi-node jobs on NERSC: the nccl module supplies the Slingshot
# (aws-ofi-nccl) plugin. Use the module for jax's CUDA major and pin the pip NCCL
# to its version, e.g. pip install --no-deps nvidia-nccl-cu13==2.29.2 for jax cuda13.
module load nccl/2.29.2-cu13
# Some JAX versions fail without turning off xla_gpu_shard_autotuning
export XLA_FLAGS="--xla_gpu_shard_autotuning=false"
srun --cpu-bind=cores python -u <path_to_python_script>
One should configure the distributed initialization of JAX in the beginning of the python script.
import jax
jax.distributed.initialize()
...
Multi-node, one process per node#
#!/bin/bash -l
#SBATCH --nodes=<number_of_nodes>
#SBATCH --ntasks-per-node=1
#SBATCH --gpus-per-node=4 # 4 GPUs / node on NERSC
#SBATCH --gpu-bind=none
#SBATCH --mem=0
#SBATCH --output=gpu-out.%j
#SBATCH --error=gpu-err.%j
#SBATCH --time=<time_of_simulation>
#SBATCH --constraint=gpu
#SBATCH --qos=regular
#SBATCH -c 128
#SBATCH --account=<account_name>
source <path_to_quantax_env>/bin/activate
# Specific to multi-node jobs on NERSC: the nccl module supplies the Slingshot
# (aws-ofi-nccl) plugin. Use the module for jax's CUDA major and pin the pip NCCL
# to its version, e.g. pip install --no-deps nvidia-nccl-cu13==2.29.2 for jax cuda13.
module load nccl/2.29.2-cu13
# Some JAX versions fail without turning off xla_gpu_shard_autotuning
export XLA_FLAGS="--xla_gpu_shard_autotuning=false"
srun --cpu-bind=none python -u <path_to_python_script>
A bare jax.distributed.initialize() uses only the first GPU of each node in this case. The following code works under both multi-process layouts; check that the printed devices equals the number of allocated GPUs.
import os
import jax
# Skip JAX's CPU (gloo) collectives, unused by GPU runs: their per-rank hostname
# DNS lookup can fail transiently and kill a large multi-node job at startup.
jax.config.update("jax_cpu_collectives_implementation", None)
g = int(os.environ["SLURM_GPUS_ON_NODE"]) # GPUs of the node
t = int(os.environ.get("SLURM_NTASKS_PER_NODE", 1)) # tasks per node
lid = int(os.environ["SLURM_LOCALID"])
jax.distributed.initialize(
num_processes=int(os.environ["SLURM_NTASKS"]),
process_id=int(os.environ["SLURM_PROCID"]),
local_device_ids=list(range(lid * g // t, (lid + 1) * g // t)),
)
if jax.process_index() == 0:
print(
f"processes: {jax.process_count()}, devices: {jax.device_count()}", flush=True
)
...