jVMC 2.0: A modular and scalable library for neural quantum states
Analyze & explore related research in Conceptio
Connect this record directly into your research workflow or AI agent. Explore citations across open repositories, query full text, and export structured proof bundles.
SciPost Physics Codebases
Submission
jVMC 2.0: A modular and scalable library for neural quantum states Massimo Solinas1⋆ , Sven Benjamin Kožić1,2 , Wladislaw Krinitsin1,2 , Jonas B. Rigo1 , Noe Salmeron1 and Markus Schmitt1,2
arXiv:2611.41541v1 [quant-ph] 30 Nov 2026
1 University of Regensburg, 93053 Regensburg, Germany 2 Forschungszentrum Jülich GmbH, Peter Grünberg Institute, Quantum Control (PGI-8), 52425 Jülich, Germany ⋆ massimo.solinas@physik.uni-regensburg.de
Abstract We present jVMC 2.0, the second generation of the JAX-based jVMC library for variational Monte Carlo with neural quantum states. This new version was rebuilt from the ground up for large-scale simulations: samples, network evaluations and Jacobian products are sharded across multiple GPUs and nodes, and memory-efficient distributed linear algebra allows models with large numbers of parameters. A modular design around networks, samplers, operators, objective functions, solvers, time integrators and optimizers makes the library easy to extend, and it now supports continuous-space systems, fermions, symmetry projections, autoregressive and transformer architectures, and mixed-precision arithmetic. After benchmarking its scaling across devices, we showcase exemplary applications: ground states of the frustrated J1 –J2 model with mixed precision and of electrons in a two-dimensional quantum dot, and quench dynamics in the two-dimensional transverse-field Ising model on lattices of up to 10 × 10 sites. Copyright attribution to authors. This work is a submission to SciPost Physics Codebases. License information to appear upon publication. Publication information to appear upon publication.
Received Date Accepted Date Published Date
Contents 1 Introduction 1.1 How to Install jVMC 2.0 1.2 Migrating from jVMC 1.x and using AI coding agents 1.3 The Variational Monte Carlo Framework
2 4 4 5
2 Codebase Design and Features 2.1 Defining the Neural Quantum State 2.1.1 Network 2.1.2 NQS 2.1.3 Symmetrizing the Network 2.2 Sampling Configurations 2.2.1 Exact Sampler 2.2.2 MC Sampler
6 7 7 8 9 12 12 13 1
SciPost Physics Codebases
Submission
2.2.3 Proposer 2.2.4 Autoregressive Networks Constructing Observables 2.3.1 Discrete Operators 2.3.2 Continuous Operators 2.3.3 Obtaining Statistics Objective Function The Stepper The Optimizer 2.6.1 Ground State Search Optimizers 2.6.2 Real Time Evolution 2.6.3 Solvers Using Multiple GPUs 2.7.1 Sharded Decorator
14 15 16 16 18 19 20 22 23 24 25 26 27 28
3 Benchmarks 3.1 Parallelism on multiple GPUs 3.2 Batching 3.3 Parallelized Monte Carlo sampling 3.4 Distributed matrix inversion with JAXMg 3.5 Comparison with NetKet
30 30 30 31 32 32
4 Examples 4.1 The J1 –J2 Model Using Mixed Precision 4.2 Continuous Space: Electrons in a Quantum Dot 4.3 Unitary Dynamics
36 36 38 40
5 Conclusion
42
A Gradient of the Objective Function
43
B Memory-Efficient Distributed Jacobian Products
45
References
46
2.3
2.4 2.5 2.6
2.7
1
Introduction
The efficient simulation of quantum many-body systems remains one of the central challenges of computational physics, with implications ranging from condensed-matter physics and quantum chemistry to materials science and the development of quantum technologies. The fundamental obstacle is the exponential growth of the Hilbert space with the number of degrees of freedom: storing and manipulating the full wavefunction quickly becomes impossible, and full state methods remain limited to a few tens of spins even on the largest supercomputers [1,2]. Progress therefore relies on approximate methods that exploit the structure of physically relevant states, combined with algorithms that make efficient use of modern computing hardware. Over the past decades, the community has developed a variety of such methods, each with its own domain of applicability. Quantum Monte Carlo (QMC) techniques [3–5] estimate observables by stochastic sampling and yield numerically exact results for large, unfrustrated 2
SciPost Physics Codebases
Submission
bosonic and spin systems. For fermionic and frustrated systems, however, they suffer from the sign problem, whose cost grows exponentially with system size and inverse temperature [6], and an analogous phase problem prevents their direct application to real-time dynamics. Tensornetwork methods [7–9], do not suffer from the sign problem and provide quasi-exact results in one dimension, where low-energy states obey an area law of entanglement [10]. Their efficiency, however, relies on bounded entanglement so that their cost grows exponentially with the width of two-dimensional systems and with time in out-of-equilibrium dynamics. Dynamical mean-field theory (DMFT) [11, 12] instead maps the lattice problem onto a self-consistent quantum impurity model and has become a powerful tool for strongly correlated materials [13]. Its central approximation, however, neglects non-local correlations, which can only be partially restored by cluster extensions at a substantially higher computational cost [14]. A complementary route is offered by variational Monte Carlo (VMC) [4], in which the wavefunction is represented by a parametrized ansatz and expectation values are estimated by stochastic sampling. VMC does not suffer from the sign problem and applies equally to bosons, fermions and frustrated systems, in any dimension and both in and out of equilibrium. Its accuracy, however, is limited by the bias of the chosen ansatz. Neural quantum states [15] render VMC a systematically controlled numerical method by using artificial neural networks as variational ansätze [16–18]. The universal approximation property of neural networks [19] and their ability to efficiently encode large amounts of entanglement [20–22] make them compact yet highly expressive representations of the wavefunction, while their optimization directly benefits from GPU acceleration. NQS have been used both to find ground states, typically via stochastic reconfiguration [23], excited states [24, 25] and to simulate unitary evolution through the time-dependent variational principle [15, 26]. Over the years, the employed architectures have evolved from restricted Boltzmann machines [15] to convolutional [27], autoregressive [28, 29] and transformer-based networks [30]. The approach has proven successful for a broad range of systems, from frustrated spin models [27, 30–32] and fermionic lattice models [33, 34] to electronic structure in continuous space [35–38]. State-of-the-art NQS simulations now routinely employ networks with 105 –106 parameters and require a comparable number of samples per optimization step [31, 39]. At this scale, both the evaluation of the network on large batches of configurations and the solution of the dense linear systems arising in stochastic reconfiguration and the time-dependent variational principle easily exceed the memory and compute budget of a single GPU, making the distribution of the workload over multiple accelerators and compute nodes an essential requirement. At the same time, the development of efficient architectures and optimization schemes tailored to NQS remains an extremely active field of research [40–43]. Providing a common, welltested and scalable code base that implements the core building blocks of the framework is therefore a fundamental task, both to ensure reproducibility and to lower the barrier for new methodological developments. With this work we continue this effort by presenting version 2.0 of jVMC [44], an open-source Python library built on JAX [45] and Flax [46] that implements the core components of variational Monte Carlo tailored to NQS. jVMC 2.0 retains the guiding philosophy of the first version, namely an easy-to-use and highly performant interface designed to be easily customized, modified and extended. However, the library has been almost completely rewritten: its components are now decoupled behind clean and uniform interfaces, so that each of them can be inspected, replaced or extended independently without touching the rest of the code. Beyond this restructuring, jVMC 2.0 introduces new functionalities including new architectures, new integrators, new samplers, compatibility with continuous VMC and new optimization tricks such as mixed precision schemes [47]. Most importantly, jVMC 2.0 provides a straightforward way of running simulations on multiple devices and compute nodes relying on JAX sharding mechanism. Sampling and network evaluations can be
3
SciPost Physics Codebases
Submission
distributed across all available accelerators with no change to user code, while the dense linear algebra routines required by most of the optimization schemes can be now distributed over multiple GPUs through JAXMg [48], removing the single-device memory bottleneck for large networks. This paper is organized as follows. In Sec. 1.3 we briefly review the variational Monte Carlo framework and its use for ground-state search and time evolution. Sec. 2 describes the structure of the library and its main modules, and shows how users can build custom functionality on top of the existing components; Sec. 2.7 explains how simulations are distributed across multiple devices and nodes. With the codebase in place, we turn to applications: in Sec. 3 we benchmark the performance of the library, and in Sec. 4 we apply it to representative problems in both ground-state search and unitary dynamics. We conclude in Sec. 5; technical details on the gradient of the objective function and on memory-efficient distributed Jacobian products are given in the appendices.
1.1
How to Install jVMC 2.0
Since jVMC is built on JAX, it supports the same platforms, namely Linux and macOS, while GPU acceleration is only available on Linux. jVMC can be easily installed with pip install jVMC
For GPU support, the CUDA version must be specified: pip install "jVMC[cuda12]"
# or "jVMC[cuda13]"
This installs the corresponding CUDA-enabled build of JAX together with the CUDA libraries, as well as JAXMg for distributed linear algebra across multiple GPUs. On computing clusters, where CUDA is usually provided through environment modules, we recommend using the system installation instead. After loading the relevant modules, jVMC can be installed with the -local variant: module load cuda pip install "jVMC[cuda12-local]"
# cluster-specific # or "jVMC[cuda13-local]"
In this way JAX uses the CUDA libraries that the cluster provides, matched to the local drivers. This avoids version conflicts with a second, pip-installed copy of CUDA.
1.2
Migrating from jVMC 1.x and using AI coding agents
Since jVMC 2.0 is a near-complete rewrite, scripts written for version 1.x do not run without changes: the interface now follows PEP 8 naming, MPI has been replaced by JAX sharding, and components such as solvers, steppers and objective functions are now separate objects. To ease the transition, the repository contains a migration guide (MIGRATION.md, also part of the online documentation). It shows a version-1.x script next to its version-2.0 equivalent, maps the old names to the new ones module by module, and lists the changes in behavior that do not raise errors. AI coding assistants are increasingly used to write simulation code. Since such models are trained on publicly available code, they are likely to reproduce the interface of jVMC 1.x. We therefore distribute, in the folder skills/jvmc of the repository, an agent skill: a set of Markdown files in the open Agent Skills format, which compatible agents load when a task involves the library. The skill describes the structure of a jVMC calculation, gives complete examples of ground-state searches and real-time evolution, lists common pitfalls and maps the version-1.x names to the current ones. 4
SciPost Physics Codebases
Submission
operator / function
proposer
model
objective ℓ(θ)
sampler s ∼ pθ
NQS ψθ (s)
samples s1 , . . . , sNs VMC loop
evaluate ℓ(θ), ∇θ ℓ
update NQS θ ← θ + δθ
step
Optimizer
optimizer-specific
solver
stepper
linear system for θ̇
θ(t) → θ(t + δt)
Figure 1: Schematic of the VMC optimization loop in jVMC. The user specifies three components (top): an objective ℓ(θ ), built from an operator or a generic function; a sampler, which draws configurations s ∼ pθ using a chosen proposer; and the model, a neural quantum state ψθ (s). Each iteration of the loop, handled by the optimizer (dashed region), proceeds as follows. A set of samples s1 , . . . , sNs is drawn from the current model and used to estimate the objective ℓ(θ ) and its gradient ∇θ ℓ. An optimizer-specific step then computes the parameter update δθ , and the network is updated as θ ← θ + δθ before new samples are drawn. For natural-gradient and time-dependent schemes, the step relies on two further interchangeable components (bottom): a solver for the linear system determining θ̇ , and a stepper that integrates θ (t) → θ (t + δt).
1.3
The Variational Monte Carlo Framework
NQS build on the well-established VMC framework. Its starting point is the observation that the quantum expectation value of an observable Ô can be rewritten as a classical expectation value over the Born distribution in a given basis {|s〉}: Ôψθ (s) 〈ψθ | Ô |ψθ 〉 |ψ (s)|2 = E pθ := E pθ [Oloc (s)] , pθ (s) = θ , (1) 〈ψθ | ψθ 〉 ψθ (s) N where N represents the normalization of the distribution, and we defined the local observables Oloc . With this basis, VMC rests on three ingredients: (i) a compact representation ψθ (s) = 〈s| ψθ 〉 of the wave function amplitudes, depending on a set of variational parameters θ whose number scales polynomially with system size, which circumvents the exponential size of the Hilbert space; (ii) Monte Carlo sampling from pθ , which replaces Eq. (1) by a sample mean over Ns configurations, so that the wavefunction only has to be evaluated on typical configurations that appear in the sample; (iii) a variational principle that prescribes how θ is updated to approach a target state, such as the ground state, an excited state, or the time-evolved state under unitary dynamics. What distinguishes NQS from earlier VMC approaches is the choice of the ansatz. Traditional VMC relies on physically motivated wavefunctions, such as Jastrow or Gutzwiller-projected states, with few parameters. These encode strong prior knowledge and are cheap to optimize, but they introduce a systematic bias whenever that prior does not capture the physics of the target state. NQS replace them with generic, highly expressive artificial neural network. This 5
SciPost Physics Codebases
Submission
reduces the systematic bias of the ansatz at the cost of a typically much larger parameter space and a more demanding stochastic optimization, which becomes tractable by borrowing architectures, automatic differentiation, and hardware acceleration from modern machine learning. From this perspective, VMC with NQS can be viewed as an unsupervised learning problem in which the training data, the configurations s, are not given in advance but are generated at every iteration by the model itself. Once a network (the model), a procedure for generating configurations (the sampler), and an objective function are specified, VMC reduces to an optimization loop: configurations are sampled, used to estimate the value and the gradient of the objective, and these estimates are used to update the variational parameters. This loop is shown schematically in Fig. 1.
2
Codebase Design and Features
As outlined in the introduction, a VMC codebase rests on three core ingredients: a network architecture that represents the wavefunction, a procedure for drawing configurations from the associated probability distribution, and a means of defining operators and evaluating their quantum expectation values. Building on these three components, one can implement different algorithms that drive the optimization of the network towards the desired wavefunction, what we refer to as the optimizer. This structure translates in code in defining a series of core modules, that together define an optimization task, as illustrated in this simple example: 1
import jVMC
2 3 4 5 6 7 8 9
# Problem and numerical hyperparameters L = 10 # number of sites n_samples = 2**12 # samples drawn at every step n_chains = 2**10 # parallel Markov chains batch_size = n_samples # configurations evaluated at once steps = 100 # number of optimization steps learning_rate = 1e-3 # time step of the integrator
10 11 12
# 1. Network: log-amplitude of a single configuration net = jVMC.nets.RBM()
13 14 15
# 2. NQS: vectorized evaluation of the network and its gradients psi = jVMC.vqs.NQS(net, L, batch_size)
16 17 18 19 20 21
# 3. Sampler: the way to generate new samples proposer = jVMC.propose.SpinFlip() sampler = jVMC.sampler.MCSampler( psi, proposer, num_chains=n_chains, num_samples=n_samples )
22 23 24
# 4. Operator: observable to be used in the objective function H = sum(jVMC.operator.discrete.SigmaX(i) for i in range(L))
25 26 27
# 5. Objective function: expectation value of the operator loss = jVMC.objective_function.Observable(H)
28 29 30
# 6. Stepper: time integrator for the parameters stepper = jVMC.stepper.Euler(learning_rate)
6
SciPost Physics Codebases
Submission
31 32 33
# 7. Solver: linear system solver used in the update solver = jVMC.solver.Pinv()
34 35 36
# 8. Optimizer: orchestrates the VMC loop opt = jVMC.optimizer.MinSR(sampler, psi, solver=solver)
37 38 39
# Run the optimization out = opt.ground_state_search(steps, loss, stepper)
In what follows, we describe each of these building blocks of our codebase in detail, outlining both how they are implemented and, more importantly, how they can be extended to develop and experiment with new custom methods.
2.1
Defining the Neural Quantum State
The central object of jVMC is the neural quantum state, which provides the variational ansatz for VMC. For a given configuration s, it encodes the logarithmic amplitude log〈s|ψθ 〉, where θ denotes the set of variational parameters. Note that working in log-space is the standard choice in VMC frameworks, since unnormalized amplitudes can vary over many orders of magnitude and would otherwise lead to numerical instabilities during optimization. The first step for the user is therefore to define the underlying network, which we refer to as NET, that maps a configuration s to log〈s|ψθ 〉. 2.1.1
Network
Our library relies on Flax [46], which allows neural networks to be defined in a straightforward way on top of JAX [45]. Any custom network can be implemented using either the Flax nn or nnx API. Since Flax is gradually transitioning from nn to nnx, the NQS class is compatible with networks defined in either framework: under the hood, an nnx model is automatically converted into an equivalent nn module. The only requirement imposed on the user is that the network’s __call__ method be defined for a single input configuration of shape (sample_shape,); the NQS class then automatically vectorizes this computation over arbitrary batches of configurations using jax.vmap. This design choice keeps the definition of new network architectures as simple as possible. In addition, the NET can optionally implement two further methods, sample and eval_ratio. The former is discussed in Sec. 2.2.4, while the latter defines a function that, given two configurations s and s′ , directly returns their amplitude ratio, NET.eval_ratio : (s, s′ ) 7−→
ψθ (s′ ) . ψθ (s)
(2)
This functionality is useful whenever an analytical expression for the ratio is available, since evaluating it directly is computationally cheaper than calling the model on the two configurations separately. When the user wishes to represent the real and imaginary parts of the amplitude with two separate networks, these can be passed to the TwoNets wrapper, available as jVMC.nets.two_nets_wrapper, before being handed to the NQS class. This wrapper guarantees that the combined output is consistently complex-valued, and that extracting the real part of the amplitude only triggers evaluation of the network responsible for it. Finally, jVMC provides a collection of pre-implemented network architectures (see jVMC.nets) that users can readily employ in their VMC calculations. These range from 7
SciPost Physics Codebases
Submission
restricted Boltzmann machines [15] and convolutional networks [27] to autoregressive models, namely recurrent networks with GRU/LSTM cells in one and two dimensions [29] and RWKV-type architectures [49], which allow exact sampling, as well as Vision Transformers [30] and a hidden-fermion Pfaffian extension for fermionic systems. All networks are standard Flax modules, so they can be freely combined with or replaced by user-defined architectures. 2.1.2
NQS
Once the network has been defined, it can be handed to the NQS class, which wraps it and exposes a simple interface to inspect and overwrite the variational parameters θ , either in their native dictionary/pytree structure, as used internally by Flax (NQS.parameters), or as a single flat array (NQS.parameters_flat). Since the network can be defined with either real or complex parameters, the NQS class adopts the convention that the flat representation is always a real-valued array. For a network with Np complex parameters, this array has length 2Np and collects their real and imaginary parts, NQS.parameters_flat = (Re θ , Im θ ) ∈ R2Np ,
(3)
while for real parameters it simply coincides with θ ∈ RNp . In other words, the NQS class always treats the network as a function of real variational parameters, and complex parameters are handled by doubling their number. The class is responsible for the following functionalities: • Defining the Batch Size: During initialization, the user specifies the batch_size, i.e., the number of input configurations that the NQS processes simultaneously when evaluating the network or its gradients. This parameter is essential to control the tradeoff between execution time and memory, and has to be tuned looking at the number of samples produced by the Sampler class (see Sec. 2.2). Setting batch_size equal to the total number of samples Ns maximizes throughput, since all evaluations are then performed in a single vectorized call. On the other hand, reducing it trades some speed for a smaller memory footprint, which becomes necessary whenever the full batch of network evaluations and gradients would otherwise exceed the available memory (see Sec. 3.2). N
s • Evaluation: Given a set of configurations S = {si }i=1 , the class returns the log-amplitude of the configurations,
NQS.__call__ : S 7−→ log ψθ (S) ∈ I,
(4)
where I denotes either R or C, depending on the chosen parametrization. The user can decide to define a net whose output can represent either the log-amplitude directly or the bare amplitude. In the latter case, the user must indicate this when initializing the NQS class by setting the flag logarithmic to False, so that the logarithm is then applied internally. N
s • Gradient: Given a set of configurations S = {si }i=1 , the class computes the Jacobian matrix of logarithmic derivatives Γ , with elements
∂ log ψθ (si ) , ∂ θk
(5)
NQS.gradients : S 7−→ Γ .
(6)
Γi,k = Γk (si ) = through the method
Consistently with the parameter convention above, the derivatives are always taken with respect to the real parameters stored in NQS.parameters_flat. Hence Γ has shape 8
SciPost Physics Codebases
Submission
Ns × Np for real parameters and Ns × 2Np for complex parameters θk = ak + i bk , in which case ∂ log ψθ (s) ∂ log ψθ (s) Γ (s) = , = Γ (a) , Γ (b) . (7) ∂a ∂b Note that Γ is in general complex even when θ is real, since log ψθ is complex-valued. How Γ is evaluated depends on the analytic structure of the network, which the NQS class determines automatically: – Real parameters. If log ψθ is real, Γ is obtained by a single automatic differentiation. Otherwise, the real and imaginary parts of log ψθ are differentiated separately and recombined as Γk = ∂θk Re log ψθ + i ∂θk Im log ψθ . – Complex parameters, non-holomorphic network. The same procedure is applied, now differentiating with respect to both ak and bk , yielding the 2Np columns of Γ . – Complex parameters, holomorphic network. If log ψθ is holomorphic in θ , the Cauchy– Riemann conditions imply Γ (b) = iΓ (a) , so that the Jacobian follows from a single differentiation of the real part of log ψθ . Holomorphicity is probed numerically on a sample input configuration by gauging the validity of the Cauchy–Riemann conditions. • Lazy gradient: Since materializing the full Jacobian Γ becomes memory-intensive for large Ns or Np , the NQS class also provides the lazy_gradients method. Instead of computing Γ at once, it returns a reusable generator that yields it in consecutive blocks of batch_size rows, so that only an array of shape batch_size × Np is held in memory at any time. This is essential for objective functions that accumulate statistics over many configurations (see Sec. 2.4). • Mixed Precision: the NQS class can be provided with three additional parameters at initialization, sampler_dtype, eval_dtype, and grad_dtype, which together enable mixed-precision VMC. As their names suggest, sampler_dtype controls the dtype used for the network parameters (and hence for all internal operations) when the network is called for sampling purposes, either directly by the NQS or by the Sampler; eval_dtype controls the dtype used when evaluating the network via NQS.__call__; and grad_dtype controls the dtype used when computing gradients via NQS.gradients. In all three cases, the output of the network is subsequently cast to a fixed output dtype, given by the global variable DT_OUT_REAL or DT_OUT_CPX, depending on whether the network output is realor complex-valued. This design decouples the precision used internally, in the computationally expensive network evaluations, from the precision used to accumulate and report statistics, giving the user fine-grained control over a mixed-precision optimization scheme. Section 4.1 presents a ground-state search using mixed precision. If the user does not specify these three parameters explicitly, they default to the global variable DT_PARAMS_REAL (or DT_PARAMS_CPX, for complex-valued parameters). For this mechanism to function correctly, the network must be defined so that it can accept parameters of varying dtype. In Flax, this is achieved simply by not hard-coding a dtype argument in the network’s layers: specifying a fixed dtype forces all computations inside that layer to that dtype, whereas omitting it lets JAX infer the dtype directly from the parameters passed at call time, which is what allows the NQS class to switch precision on the fly. 2.1.3
Symmetrizing the Network
Symmetries of the Hamiltonian can be imposed on an NQS either through the network architecture or by projecting its amplitudes onto a symmetry sector. In the first approach, the 9
SciPost Physics Codebases
Submission
internal features transform equivariantly under the chosen symmetry, and an invariant output is obtained by pooling these features. For example, the ViterittiViT architecture uses translation-invariant attention and a sum over patch features to make its backbone invariant under translations by complete patches [39]. An invariant scalar output belongs to the trivial symmetry sector, whereas a nontrivial character requires an appropriately transforming output or an additional projection [50]. For a finite symmetry group G with unitary operators T̂g and characters χ g , the symmetry projector is dχ X ∗ P̂χ = χ T̂g , (8) |G| g∈G g which produces an unnormalized projected state with wavefunction amplitudes |ψθ ,χ 〉 = P̂χ |ψθ 〉 =
dχ X |G| g∈G
ψθ ,χ (s) = 〈s|ψθ ,χ 〉 =
χ g∗ T̂g |ψθ 〉 ,
dχ X |G| g∈G
(9) χ g∗ η g (s)ψθ (g −1 s),
where η g (s) = 〈s| T̂g |g −1 s〉 includes any phase or sign associated with the transformation [50]. For permutations of spin or bosonic occupations, this factor is unity and the permutation sign of the state g −1 s for fermions. The SymmetryProjector class represents the transformed configurations by permutations of site indices, optionally combined with local occupation transformations, and stores the scalar coefficients χ g∗ in its character field. The default averaging mode, symmetry_average="exp", evaluates the logarithm of the weighted amplitude sum in Eq. (9) using a numerically stabilized exponential average. Thus, the projection acts on amplitudes even though the underlying network returns their logarithms. This construction also applies to one-dimensional sectors of non-Abelian groups, although only Abelian symmetries are currently available. The lattice constructors provide periodic translations with a specified lattice momentum, the square point group D4 , the rectangular point group D2 , reflection of a chain, global spin inversion, and particle–hole transformations for the supported particle types. Spatial permutations can use the built-in direct or snake site ordering, or a user-supplied site enumeration. The point-group constructors select the fully symmetric sector by default. The overloaded multiplication applies a projector to a network according to * : ( P̂χ , NET) 7−→ NETχ ,
NETχ (s) = log ψθ ,χ (s).
(10)
The returned network is wrapped by ProjectedOrbitNet and can be passed to NQS. The same operation composes two projectors, * : ( P̂1 , P̂2 ) 7−→ P̂1 P̂2 .
(11)
This product represents simultaneous projection onto the two sectors when the projectors commute. For example, zero momentum is compatible with the full square point group, giving 1 2
import jVMC from jVMC.symmetry import lattice_symmetries as sym
3 4 5 6 7 8
Lx = Ly = 4 raw_net = jVMC.nets.RBM(num_hidden=4, bias=True) D4 = sym.square_d4_symmetry(Lx, Ly, particle_type="spin") T_square = sym.square_translation_symmetry( Lx, Ly, particle_type="spin", q=(0, 0)
10
SciPost Physics Codebases
9 10 11
Submission
) net = (D4 * T_square) * raw_net psi = jVMC.vqs.NQS(net, Lx * Ly, batch_size=16, seed=7)
Custom projectors are defined by supplying the index permutations and scalar weights for the desired sector, together with any required local occupation transformations. As an example, consider spins on the eight vertices of a cube. Quarter-turn rotations about one of its three fourfold (tetrad) axes generate the group C4 = {e, R, R2 , R3 }. Number the vertices cyclically as 0, 1, 2, 3 on one face and 4, 5, 6, 7 on the opposite face, with the same orientation about the chosen axis. The nontrivial sector with χ(R) = i is selected by the conjugate character weights (1, −i, −1, i): 1
import numpy as np
2 3 4 5 6 7 8 9 10 11 12 13
cube_faces = np.arange(8).reshape(2, 4) c4_permutations = tuple( tuple(np.roll(cube_faces, -r, axis=1).ravel()) for r in range(4) ) C4 = jVMC.symmetry.SymmetryProjector( Lx=4, Ly=2, particle_type="spin", perm=c4_permutations, character=(1, -1j, -1, 1j), name="cube_C4" ) net_c4 = C4 * raw_net
Here, Lx=4 and Ly=2 enumerate four vertices on each of two faces. The permutations specify the rotation of the cube, each row of perm produces R−r s for evaluating Eq. (9). For a nonzero projection, the resulting state has eigenvalue i under the quarter-turn operator R̂. More generally, the supplied operations and weights must form a consistent representation of the chosen symmetry group. For fermions, permuting the occupations also permutes the creation operators defining the Fock basis, and the resulting occupation-dependent parity must be included in η g (s). Selecting particle_type="spinless_fermion" or "spinful_fermion" in the constructors enables these signs in the library’s fixed Fock ordering. Spinful configurations contain one integer per site, with 0, 1, 2, 3 denoting empty, spin-up, spin-down, and double occupation, respectively. The implementation also includes the local fermionic phases required by spin inversion and particle–hole transformations. Besides coherent amplitude projection, ProjectedOrbitNet provides two nonlinear averages: "log" averages logarithmic amplitudes directly, while "sep" averages the probabilities and the phases separately, using a circular mean for the latter. Both modes ignore the scalar projector weights and fermionic signs, so they do not implement Eq. (9) for nontrivial characters or sign factors. For networks evaluated with MCMC, "exp" is therefore the appropriate choice for such sectors. The average can also be supplied as a callable taking the logarithmic amplitudes and their weights and returning one logarithmic amplitude. Table 1 summarizes the symmetry and network restrictions of these choices. If the underlying network provides autoregressive sampling, the wrapper accepts only "sep" or a custom callable, and rejects nontrivial characters and additional phase or sign factors. The built-in "sep" mode assumes the pure-state convention log_prob_factor=0.5 and preserves direct sampling by combining a sample from the original network with a uniformly chosen symmetry transformation [29]. The resulting probability is the average of the transformed Born probabilities; coherent projection generally produces a different distribution. A custom average must preserve consistency with this sampling rule.
11
SciPost Physics Codebases
Submission
Table 1: Averaging choices in ProjectedOrbitNet. Average
Symmetry restriction
"exp"
All supported characters and sign factors. No direct-sampling interface.
"log"
Unit weights for the intended symmetry No direct-sampling interface. sector; all supplied weights are ignored.
"sep"
Unit weights for the intended symmetry With or without direct sampling; disector; all supplied weights are ignored. rect sampling assumes log_prob_factor = 0.5.
callable
Determined by the callable; direct- With or without direct sampling; for disampling networks still require unit rect sampling, the squared modulus of the weights. amplitude must reproduce the wrapper’s probability mixture.
2.2
Network restriction
Sampling Configurations
The second core ingredient of the VMC framework is the Sampler, an object responsible for generating configurations to be fed to the NQS and for computing expectation values of user-specified observables. These two responsibilities are captured by the AbstractSampler base class, which requires only an NQS instance for initialization. The class stores the most recently generated configurations S (the samples), together with their log-amplitudes and their associated probabilities (the weights). Since the class already holds all the ingredients required to compute quantum expectation values, its call method can be used directly for this purpose, AbstractSampler.__call__ : Ô 7−→
〈ψθ |Ô|ψθ 〉 . 〈ψθ |ψθ 〉
(12)
The result is returned as a SampledObs object (see Sec. 2.3.3). From this general interface, two different kinds of samplers are provided to the user: the ExactSampler and the AbstractMCSampler. 2.2.1
Exact Sampler
The ExactSampler is designed to enumerate and generate the complete basis of a discrete Hilbert space Hd . It is initialized by providing the local Hilbert space dimension l_dim and the parameter log_prob_factor, which controls the normalization convention used for the returned probabilities, as detailed below. The class infers the total number of sites N from the sample shape and efficiently constructs the basis, S = [s1 , s2 , . . . , s M ] ,
M = l_dimN .
(13)
This is done through the cached property ExactSampler.basis. The sample method then simply returns these configurations together with their amplitudes and probabilities, _ _ |ψθ (S)|1/log prob factor ExactSampler.sample : 7−→ S, log ψθ (S), , (14) N P 1 where N = s∈S |ψθ (s)| log_prob_factor is a normalization constant ensuring that the returned probabilities sum to one.
12
SciPost Physics Codebases
2.2.2
Submission
MC Sampler
The AbstractMCSampler implements a more elaborate interface, whose purpose is to draw configurations from the probability distribution |ψ (s)|µ pµ,θ (s) = P θ , µ s |ψθ (s)|
µ ∈ (0, 2].
(15)
This is achieved by means of a Markov Chain Monte Carlo (MCMC) or auto-regressive sampling (which we discuss in Sec. 2.2.4) if the network itself can generate samples. In the former case, given a configuration s, a new configuration s′ is proposed and accepted with the Metropolis– Hastings acceptance probability, ′
α(s, s ) = min 1,
pµ,θ (s′ ) pµ,θ (s)
′
C(s, s ) ,
(16)
where C(s, s′ ) = T (s′ → s)/T (s → s′ ) denotes the proposal ratio, i.e., the probability of proposing the reverse transition from s′ to s divided by the probability of proposing the forward transition from s to s′ , under whichever proposal distribution has been chosen by the user (see Sec. 2.2.3). Accordingly, when initializing the AbstractMCSampler, the user must specify the desired number of samples and the number of independent Markov chains to run. Generation of the independent chains is efficiently parallelized; if the code is run on multiple devices, this parallelization is automatically distributed across them (see Sec. 2.7). Internally, the class adjusts the requested numbers of samples and chains so that the number of chains is always divisible by the number of available devices. To ensure proper decorrelation between successive samples, the user can tune the number of sweep steps, i.e., the number of Monte Carlo proposal/acceptance moves performed between two configurations that are actually retained as samples. Discarding these intermediate configurations reduces the autocorrelation inherent to any MCMC chain. If this parameter is not specified at initialization, it is inferred automatically from the sample shape. Separately, to ensure that the chains have reached the stationary distribution pµ,θ before any configuration is used to estimate expectation values, the user can also set the number of thermalization sweeps, i.e., the number of initial sweeps that are performed and discarded before any sample is collected. This burn-in step is necessary because the chains are typically initialized from an arbitrary starting configuration, and some number of moves is required before the chain’s state becomes representative of the target distribution. As for the ExactSampler, the class exposes a sample method that returns the sampled configurations, their log-amplitudes, and their associated weights, _ _ |ψθ (S)|1/log prob factor−µ AbstractMCSampler.sample : num_samples 7−→ S, log ψθ (S), , N (17) P _ _ where N = s∈S |ψθ (s)|1/log prob factor−µ . The parameters log_prob_factor and µ can thus be tuned jointly to implement different importance-sampling schemes. Indeed, since the chain samples from pµ,θ rather than the target distribution directly, each configuration _ _ is re-weighted by the ratio between the desired probability, |ψθ (s)|1/log prob factor , and the µ sampling probability, |ψθ (s)| , up to normalization. By default, µ is set to 2, corresponding to sampling directly from the Born distribution |ψθ |2 , and log_prob_factor is set to 1/2. With this choice the importance-sampling exponent 1/log_prob_factor − µ vanishes, so every sampled configuration is assigned equal weight, exactly as expected when sampling directly from the target distribution. 13
SciPost Physics Codebases
Submission
Two samplers that inherit from this abstract class are provided: MCSampler and MCSamplerCont. The two differ simply in the type of samples they produce, discrete for the former and continuous for the latter. The CutoffSampler, introduced in Ref. [51], extends the MCSampler class and alleviates the estimation bias of the conventional approach of sampling from the Born distribution [52]. It does so by assigning a nonzero probability to every configuration in the Hilbert space, controlled by the cutoff parameter ε. 2.2.3
Proposer
As anticipated, the AbstractMCSampler relies on a proposer, a function that, given a single configuration s, proposes a new configuration s′ together with the associated proposal ratio. This is implemented by the AbstractProposer interface, AbstractProposer.__call__ : s 7−→ s′ , log C(s, s′ ) . (18) Note that, for numerical stability, the proposer returns the logarithm of the proposal ratio C(s, s′ ) entering the acceptance probability of Eq. 16, consistently with the convention adopted for the log-amplitudes discussed above. In addition, a proposer may optionally implement a custom thermalization routine, invoked exclusively during the thermalization sweeps, which allows proposer-specific hyperparameters (such as a step size or a flip probability) to be adaptively tuned, typically by targeting a prescribed acceptance rate. Our library provides the following proposer classes, ready to be used in combination with MCSampler: • SpinFlip: s′ is obtained from s by flipping a single spin, chosen uniformly at random among all sites. • SpinFlipZ2: as in SpinFlip, s′ is obtained by flipping a single, randomly chosen spin. In addition, on average once every 30 proposal steps, all spins are flipped simultaneously, so that global spin-inversion (Z2 ) symmetry is enforced in the sampling process. • SpinFlipZeroMag: s′ is obtained from s while ensuring that the proposed configuration remains in the zero-magnetization sector, i.e., the sum of all spins in every configuration must vanish. In order to enforce this constraint, a spin-exchange move is proposed rather than a single spin flip. One up spin and one down spin are each selected uniformly at random among the occupied sites and their values are swapped. On the other hand, we provide two different proposers tailored to continuous-variable VMC, to be used in combination with MCSamplerCont: • RWM: implements the random walk Metropolis algorithm [53]. Given a configuration s representing the positions of all particles in real space, s′ is obtained by displacing every particle according to s′ = s + δs, δs ∼ N (0, Σ2 ), (19) where N (0, Σ2 ) denotes a normal distribution with zero mean and variance Σ2 , sampled independently for every coordinate of s. The step size Σ is tuned during thermalization so that the Metropolis–Hastings acceptance rate, given by the average of Eq. 16 over all produced samples, remains close to a target value.
• MALA: implements the Metropolis-adjusted Langevin algorithm [54]. As in the previous case, the positions of all particles are displaced, but the proposal now also incorporates a drift term along the gradient of the log-amplitude, p s′ = s + τ ∇µRe (log ψθ (s)) + 2τ ξ, ξ ∼ N (0, 1) (20) 14
SciPost Physics Codebases
Submission
where the gradient is taken with respect to the configuration s. By biasing proposals towards regions of higher probability density, this drift term typically improves sampling efficiency compared to the undirected random walk of RWM. As in the previous case, the step size τ can be tuned during thermalization to target a prescribed acceptance rate. Users can readily implement new proposal rules by defining classes that inherit from AbstractProposer, taking care that the call method remains compatible with jax.jit. 2.2.4
Autoregressive Networks
Autoregressive networks represent the Born distribution as a product of normalized conditional probabilities [29]. For an ordered configuration s = (s1 , . . . , sN ), the distribution and the corresponding pure-state amplitude satisfy pθ (s) =
N Y
pθ (si | s<i ),
X
pθ (si | s<i ) = 1,
si i=1 1 log ψθ (s) = 2 log pθ (s) + iϕθ (s),
(21)
where s<i = (s1 , . . . , si−1 ) and ϕθ (s) is the phase of the wavefunction. Drawing the local states successively from these conditionals produces independent configurations at fixed parameters, avoiding MCMC thermalization and autocorrelation between successive samples. jVMC provides autoregressive models in the form of RWKVCPM in one dimension and RWKV2D in two dimensions. For RWKV2D, causal connections can follow a rectangular grid or a supplied graph. The RWKV, or Receptance Weighted Key Value architecture, retains efficient recurrent sampling and admits parallel evaluation across sites for a known configuration, with a computational cost that grows linearly with sequence length at fixed network width and depth, compared with the quadratic cost of full self-attention [49,55]. As for other networks, a custom autoregressive model must provide a sampling method, NET.__call__ : s 7−→ log ψθ (s), NET.sample : k 7−→ s ∼ pθ ,
(22)
where k is a random key and the sampled configuration has the physical shape specified when constructing NQS. Both methods must be compatible with JAX transformations and use the same parameters and conditional probabilities. The NQS class handles batching and distribution over devices. Initialization follows the interface of Sec. 2.1.2: the model is passed to NQS together with the configuration shape, evaluation batch size, and an optional seed for parameter initialization. The presence of a sampling method identifies the network as a generator, and MCSampler then uses direct sampling without a proposal rule. For example, the following model generates eight-site configurations using two-site patches: 1
import jVMC
2 3 4 5 6 7 8 9 10 11
net_ar = jVMC.nets.RWKVCPM( L=8, patch_size=2, hidden_size=8, embedding_size=8, num_layers=1, log_prob_factor=0.5 ) psi_ar = jVMC.vqs.NQS(net_ar, 8, batch_size=16, seed=31) sampler_ar = jVMC.sampler.MCSampler( psi_ar, update_proposer=None, key=32, num_samples=64 ) samples_ar, log_psi_ar, weights_ar = sampler_ar.sample()
15
SciPost Physics Codebases
Submission
The returned arrays contain the configurations, their logarithmic amplitudes, and uniform weights w i = 1/Ns for estimating expectation values from Born-distributed samples. For pure states, log_prob_factor is 0.5. A fixed particle number or magnetization can be imposed by masking conditional choices incompatible with the target sector and renormalizing the remaining probabilities [29]. These masks must be used consistently in amplitude evaluation and sampling. The implementation provides ParticleConservingAutoregressive for RWKVCPM, and the fixed_n_up option for binary RWKV2D models; the available constraints depend on the chosen model. Site patching is likewise implemented inside the network: grouping b sites with local Hilbert-space dimension d gives d b possible patch configurations at each sampling step, which are decoded into physical site values before being returned. Symmetry averaging must preserve consistency with direct sampling and is subject to the restrictions described in Sec. 2.1.3.
2.3
Constructing Observables
As computing quantum expectation values in VMC reduces to averaging local observables, as described in Sec. 1.3, a generic observable object is simply an object that, given a configuration s and the NQS, must be able to produce the corresponding local observable. This is precisely what the general AbstractOperator interface provides, AbstractOperator.get_O_loc : (s, NQS, ξ) 7−→ Oloc (s, ξ).
(23)
Since an operator may itself depend on additional parameters, such as time, we collectively denote the set of these parameters by ξ. From this common abstract interface, two different kinds of operators branch off, as the computation of the local observable is fundamentally different in the two cases: discrete and continuous operators. 2.3.1
Discrete Operators
For a generic discrete operator Ô, the local observables can be written as: X Oloc (s) = exp log ψθ (s′ ) − log ψθ (s) 〈s| Ô |s′ 〉 .
(24)
s′
Notice that, the amplitudes are subtracted in log-space and only exponentiated afterward, to avoid the numerical instabilities that would otherwise arise from evaluating ψθ (s′ )/ψθ (s) directly when amplitudes vary over many orders of magnitude. Efficiently evaluating Eq. 24 therefore requires a method to identify, for a given configuration s, the set of all configurations s′ connected to it, defined as Cs = s′ : M (s, s′ ) := 〈s|Ô|s′ 〉 ̸= 0 . (25) There exists an important class of operators for which such an algorithm is particularly simple: those that map every configuration s to exactly one connected configuration s′ in the same basis, rather than to a set of several connected configurations. These are the so-called branch-free operators. In jVMC they serve as elementary building blocks: products of branch-free operators are again branch-free, and general operators are constructed as sums of such terms. As a concrete example, we construct the operator y Ô(t) = σ̂0z σ̂0x + 2σ̂1 + cos(t) σ̂0z σ̂1z , (26) and inspect its matrix representation, evaluated at a given value of t, by calling the .to_dense() method: 16
SciPost Physics Codebases
1 2
Submission
f_t = lambda t, **kwargs: jnp.cos(t) O = SigmaZ(0) * (SigmaX(0) + 2 * SigmaY(1)) + f_t * SigmaZ(0) * SigmaZ(1)
3 4
O.to_dense(basis, t=0.25 * jnp.pi) matrix([[ 0.70710678+0.j, 0. -2.j, 1. +0.j, 0.+0.j], [ 0. +2.j, -0.70710678+0.j, 0. +0.j, 1. +0.j], [-1. +0.j, 0. +0.j,-0.70710678+0.j, 0. +2.j], [ 0. +0.j, -1. +0.j, 0. -2.j, 0.70710678+0.j]])
This example also illustrates a key design feature of jVMC operators: they support ordinary algebraic composition, sums, products, and multiplication by (possibly parameter-dependent) scalar coefficients, via operator overloading, so that Hamiltonians and other observables can be assembled directly from elementary building blocks, in a syntax that closely mirrors their mathematical expression. Time (or, more generally, ξ) dependent coefficients, such as f_t above, are simply passed as callables that return the coefficient as a function of the relevant parameter. The connected configurations Cs and the associated matrix elements M (s, s′ ) can be obtained directly by calling O.get_conn_elements on a set of configurations S and a given value of t. This lower-level method is what get_O_loc internally relies on, combining its output with the network amplitudes according to Eq 24. Importantly, get_conn_elements is fully compatible with jax.jit, so that varying t, or any other parameter on which the operator depends, does not trigger recompilation. Moreover, discrete operators can also be converted to a sparse matrix representation via the .to_sparse() method, in direct analogy to .to_dense() introduced above. This is particularly useful for small to moderately sized systems, where the full Hamiltonian (or any other observable of interest) can still be represented explicitly and diagonalized using standard sparse eigensolvers, e.g., to obtain exact reference energies against which the variational results can be benchmarked. Our library provides a range of predefined elementary operators, covering the most common building blocks used in many-body Hamiltonians: • Spin-1/2 operators: SigmaX, SigmaY, SigmaZ (the Pauli matrices), and SigmaPlus, SigmaMinus (the raising and lowering operators σ̂± = (σ̂ x ± i σ̂ y )/2). • Fermionic operators: Creation, Annihilation, and Number (ĉ † , ĉ, and n̂, respectively). These can be instantiated as either spinful or spinless. Unlike bare spin operators, they incorporate the appropriate Jordan–Wigner string in their matrix elements, ensuring that the correct fermionic anticommutation relations are respected once the operators are mapped onto the chosen encoding. Beyond these predefined building blocks, users can straightforwardly define custom operators. As an example, we show the explicit definition of σ̂ y : 1
from jVMC.operator.discrete.branch_free import Operator
2 3 4 5 6 7
class SigmaY(Operator): def __init__(self, idx): super().__init__( l_dim=2, idx=idx, diag=False, fermionic=False, spin=None )
8
17
SciPost Physics Codebases
Submission
@property def mat_els(self): return np.array([1j, -1j], dtype=global_defs.DT_OPERATORS_CPX)
9 10 11 12
@property def map(self): return np.array([1, 0], dtype=jnp.int32)
13 14 15
In particular, the user must specify: the local Hilbert space dimension on which the operator acts, via l_dim; whether the operator is diagonal, via diag (enabling further internal optimizations); whether it is fermionic, via fermionic; and, if it is spinful, its spin quantum number, via spin. Since the operator is branch-free, it then suffices to specify, for each of the l_dim possible values of the local degree of freedom, the single value it is mapped to, through the map property, together with the corresponding matrix element, through the mat_els property. In the example above, this recovers exactly the action of the Pauli matrix σ̂ y on a spin-1/2 degree of freedom: an input value of 0 is mapped to 1 with matrix element 〈1|σ̂ y |0〉 = i, and an input value of 1 is mapped to 0 with matrix element 〈0|σ̂ y |1〉 = −i. 2.3.2
Continuous Operators
Continuous operators differ fundamentally from discrete ones, as they do not require finding the set of connected configurations for a given configuration s. Indeed, the quantum expectation value of a continuous operator Ô can be rewritten as Z Z 2 (Ôψθ )(x) 〈ψθ |Ô|ψθ 〉 = d x |ψθ (x)| := d x |ψθ (x)|2 Oloc (x), (27) ψθ (x) which has exactly the same structure as the discrete case discussed above: an average of a local observable Oloc (s) over configurations sampled from |ψθ (s)|2 , only now x denotes a continuous (e.g., real-space) configuration rather than a discrete one. Choosing the real-space basis, the local observable of a diagonal operator is simply given by the operator evaluated at the particle positions x; no reference to the wavefunction is required at all, since a diagonal operator acts on |x〉 as a multiplication by a scalar function of x alone. For a non-diagonal operator, by contrast, one must instead specify how the operator acts on the amplitude itself, since (Ôψθ )(x) is no longer simply proportional to ψθ (x). As a concrete example, consider the kinetic operator T̂ , whose local value is given by P ( T̂ ψθ )(x) 1 X 2 =− ∇i log ψθ (x) + (∇i log ψθ (x))2 , ψθ (x) 2m i=1
(28)
where i labels the particle, P is the total number of particles, m is the particle mass, and all gradients and Laplacians are taken with respect to the particles’ positions (we set ħ h = 1). This 2 2 2 expression follows from the identity ∇ ψθ /ψθ = ∇ log ψθ + (∇ log ψθ ) . jVMC currently provides the following continuous operators: • Diagonal operators: PotentialOperator, CoulombInteraction, ParticleDensity, and Monopole. • Non-diagonal operators: TotalKineticOperator. As for discrete operators, users can straightforwardly define custom continuous operators. As an example, we show the explicit definition of the potential operator:
18
SciPost Physics Codebases
1
Submission
from jVMC.operator.continuous.base import Operator
2 3 4 5 6 7 8
class PotentialOperator(Operator): def __init__(self, geometry, potential): super().__init__(geometry, is_diagonal=True) if not callable(potential): raise ValueError('The property potential has to be a function.') self._potential = potential
9
@property def potential(self): return self._potential
10 11 12 13
def _get_O_loc(self, s, apply_fun, parameters, kwargs): return self.potential(s)
14 15
Here, geometry is a class used by continuous operator to encode the physical setting they act on, and potential is any user-supplied callable implementing the (diagonal) potential energy as a function of the configuration x (for more information see the example in Sec. 4.2). Importantly, the class inherits from the generic Operator base class, so that the user only has to implement _get_O_loc for a single configuration x. Internally, the library takes care of vectorizing this computation over an entire batch of configurations, exactly as done for the NET in Sec. 2.1.1. Note that _get_O_loc receives not the NQS object itself, but rather the network’s raw apply_fun and its parameters directly: this gives non-diagonal operators, such as TotalKineticOperator, direct access to the underlying function being differentiated, which is what is actually needed to construct the automatic-differentiation calls (gradients, Laplacians) entering their local value, without incurring the additional overhead of going through the full NQS wrapper. 2.3.3
Obtaining Statistics
Once the local observables have been gathered through the get_O_loc method, jVMC provides a simple class to compute statistics over them: SampledObs. This class is initialized with a set of observations and their associated weights, such as those returned by the sampler (see Sec. 2.2). Beyond simple statistics such as the mean, variance, and covariance, the class can also compute the autocorrelation time via the fast Fourier transform and the Gelman–Rubin statistic [56], both of which are standard diagnostics for assessing the quality and convergence of an MCMC estimate. Since the sampler already holds all the ingredients needed to construct these observations, namely the samples and their weights, it can be used directly to obtain the expectation value of an observable Ô, returned as a fully populated SampledObs instance, AbstractSampler.__call__ : Ô 7−→ SampledObs (Oloc (S)) .
(29)
Thus, all the statistics of the resulting estimator are all immediately available as methods of the returned object, without any additional bookkeeping on the user’s side. As an example, we compute the magnetization along the x axis for a randomly initialized RBM: 1 2
M_x_op = sum(SigmaX(n) for n in range(L)) / L M_x = sampler(M_x_op)
3 4 5 6
print('Magnetization:', M_x) print('Autocorrelation time:', M_x.get_autocorrelation_time(n_chains)) print('Gelman-Rubin statistic:', M_x.get_R_hat(n_chains))
19
SciPost Physics Codebases
Submission
Magnetization: 6.7405e-01+0.0000e+00j ± 4.0622e-03 (Var = 6.7589e-02) Autocorrelation time: 8.3453e-01 ± 2.0593e-01 (Var = 1.6962e-01) Gelman-Rubin statistic: 1.0003317267261622
Together with SampledObs, our library provides a closely related object: LazySampledObs. Rather than taking as input a fully materialized set of observations, as SampledObs does, LazySampledObs is built to accept a reusable generator of observations, which it consumes one batch at a time, accumulating the running statistics incrementally as each new batch becomes available. This design pairs naturally with NQS.lazy_gradients (see Sec. 2.1.2): the generator returned by lazy_gradients can be fed directly into LazySampledObs, so that statistics over the parameter gradients are computed and correctly accumulated batch by batch, without ever materializing the full Jacobian in memory. This is particularly valuable for large networks, where the number of parameters is such that even a single instance of this array would no longer fit in VRAM. As we discuss later, this mechanism is a key ingredient in the efficient implementation of the optimizer (see Sec. 2.6), which relies extensively on gradient statistics of exactly this form.
2.4
Objective Function
Before introducing the algorithms that jVMC provides to optimize the NQS towards a target state, we define the loss function L and how its gradient with respect to the variational parameters θ is computed. All objective functions implemented in jVMC share a common structure: L is the expectation value of a local loss ℓθ (s) over the Born distribution, estimated as a weighted sum over the configurations si and weights w i held by a sampler, X L(θ ) = Es∼pθ [ℓθ (s)] ≈ w i ℓθ (si ). (30) i
The local loss may be complex-valued, but its expectation value is required to be real for all θ , so that L is a well-defined loss. Since complex parameters are always represented as pairs of real parameters (Re θk , Im θk ) (see Sec. 2.1.2), θk denotes a real parameter throughout. The gradient of Eq. (30) reads (see Appendix A) ∂k L = 2 Cov p (Re(Γk ), ℓ) + E p [∂k ℓ] . (31) The first term stems from the dependence of the sampling distribution on θ , the second from the explicit dependence of the local loss. As will become clear in Sec. 2.6, it is convenient to recast Eq. (31) as ∂k L = 2 Re (Fk ) , (32) in terms of the complex force vector 1 Fk = Cov p Γk∗ , ℓ + R k , 2
R k = E p [∂k Re(ℓ)] − 2 E p [Im(Γk ) Im(ℓ)] ∈ R.
(33)
The covariance is the standard VMC force, while R k collects all remaining contributions; it vanishes whenever ℓ is the local estimator of a θ -independent Hermitian operator. The common interface for all loss functions is the AbstractObjectiveFunction, which exposes two methods: __call__, which evaluates the local losses ℓθ (si ) on the configurations currently held by a sampler and returns them as a SampledObs, and value_and_grad, which additionally computes the Jacobian and the force vector, AbstractObjectiveFunction.value_and_grad : AbstractSampler 7−→ (ℓθ (S), Γ , F ) .
(34) 20
SciPost Physics Codebases
Submission
The computation of F can be skipped via the boolean flag compute_grad. At construction, the flag batched_jacobian determines whether Γ is returned as a SampledObs or as a LazySampledObs (see Sec. 2.3.3); the latter is preferable whenever the full Jacobian does not fit in memory. The objective functions provided by jVMC differ only in the choice of ℓθ , which determines the form of R k : • Observable: L = 〈Ô〉 is the quantum expectation value of a Hermitian operator Ô (Sec. 2.3), and the local loss is the local observable Oloc (s) introduced in Sec. 1.3. In this case R k = 0 (see Appendix A), and the force vector takes the standard form Fk = Cov p Γk∗ , Oloc . (35) • Estimator: the local loss is an arbitrary user-defined, real-valued function of the configuration and the parameters, ℓθ (s) = f (s, θ ) ∈ R, (36) without any operator structure. Since Im(ℓ) = 0, Eq. (33) gives R k = E p ∂θk f , so both terms of Eq. (31) contribute and 1 Fk = Cov p Γk∗ , f + E p ∂θk f , 2
(37)
where ∂θk f is obtained via automatic differentiation. Regularization terms such as f = λ∥θ ∥2 are a special case: since f does not depend on s, the covariance vanishes identically and Fk = λθk . • ParametricObservable: L = 〈Ô(θ )〉 is the quantum expectation value of an operator Ô(θ ) that is Hermitian for all θ and whose matrix elements depend explicitly on the variational parameters, in addition to the implicit dependence through ψθ : ℓθ (s) = Oloc (s; θ ) =
X s′
Oss′ (θ )
ψθ (s′ ) . ψθ (s)
(38)
The implicit dependence is treated exactly as for Observable, while the explicit one yields R k = E p (∂θk Ô)loc (see Appendix A), so that 1 Fk = Cov p Γk∗ , Oloc + E p (∂θk Ô)loc , 2
(∂θk Ô)loc (s) =
X s′
∂θk Oss′ (θ )
ψθ (s′ ) . (39) ψθ (s)
Since ∂θk Ô is itself Hermitian, its expectation value is real. The derivatives ∂θk Oss′ (θ ) are obtained by automatic differentiation of a user-supplied function encoding the explicit parameter dependence of the matrix elements. • Infidelity: L = I is the infidelity between the trial state |ψθ 〉, sampled by the primary sampler, and a reference state |χ〉, sampled independently by a second, dedicated reference_sampler. Optionally, a unitary operator Ô can be applied to the reference state, so that 〈ψ |Ô|χ〉〈χ|Ô† |ψθ 〉 I =1− θ . (40) 〈ψθ |ψθ 〉 〈χ|χ〉 This construction is particularly useful when |χ〉 is a previously optimized state and Ô an evolution operator, in which case minimizing I implements projected time-dependent 21
SciPost Physics Codebases
Submission
VMC (ptVMC) [57]. The infidelity is estimated by combining two local ratios, each sampled from only one of the two distributions, ψ
Iloc (s) =
(Ôχ)(s) , s ∼ |ψθ |2 , ψθ (s)
χ
Iloc (s) =
(Ô† ψθ )(s) , s ∼ |χ|2 , χ(s)
(41)
whose expectation values are 〈ψθ |Ô|χ〉/〈ψθ |ψθ 〉 and 〈χ|Ô† |ψθ 〉/〈χ|χ〉, respectively. The local loss is ψ χ ℓθ (s) = 1 − Iloc (s) 〈Iloc 〉χ . (42) This is precisely the local estimator of the θ -independent Hermitian operator Ĥχ = 1 − Ô|χ〉〈χ|Ô† /〈χ|χ〉,
(43)
i.e. I = 〈Ĥχ 〉. Therefore, as for Observable, R k = 0 and the force vector reduces to a single covariance, ψ χ Fk = Cov p Γk∗ , ℓ = − Cov p Γk∗ , Iloc 〈Iloc 〉χ . (44) It has been shown that the signal-to-noise ratio of the infidelity estimator vanishes as I → 0, which makes them unreliable indicators of convergence [57]. To mitigate this, Infidelity supports two control-variate variance-reduction schemes, selected via the control_variate flag [57]. In one of the examples provided in jVMC, we show how to use this objective function to construct a simple ptVMC optimization loop. Note that the same objective can be used for non-unitary Ô. In that case, the properly normalized infidelity is obtained by multiplying the fidelity term above by c=
〈χ|χ〉 〈χ|Ô† Ô|χ〉
,
(45)
which does not depend on the variational parameters θ . The two objectives therefore share the same minimizer, and their gradients differ only by the constant factor c. All the estimators above remain valid, since Ô|χ〉〈χ|Ô† is Hermitian for any Ô. As in the previous cases, users are free to define custom objective functions by implementing classes that inherit from AbstractObjectiveFunction, simply providing a __call__ and a value_and_grad method with the signatures defined above. This architectural choice gives the user full freedom to go beyond the objective functions provided out of the box, for example by adding regularization terms to an existing loss. Crucially, since AbstractObjectiveFunction sits at the same level of abstraction as Observable, Estimator, and ParametricObservable, any such custom objective function integrates seamlessly with the rest of the library, in particular with the optimizers discussed next (see Sec. 2.6), without requiring any changes downstream.
2.5
The Stepper
As it will become clear in Sec. 2.6, different ground-state search and (real- or imaginary-)time dynamics algorithms require solving a first-order differential equation for the set of variational parameters, of the form dθ = f (t, θ ), (46) dt where the specific functional form of f is determined by the chosen algorithm. Our library therefore provides a collection of different time integrators, which we refer to as steppers. These are divided into two groups: 22
SciPost Physics Codebases
Submission
• Simple steppers: Euler and Heun, which advance the solution using a fixed, userspecified time step d t. • Adaptive steppers: AdaptiveHeun, RK23, and RK45, which instead adjust the time step d t dynamically over the course of the integration. Adaptive steppers work by computing, at every integration step, two candidate solutions of different accuracy, θ1 and θ2 , and measuring the distance between them under a chosen metric M. If this distance exceeds a prescribed tolerance, meaning ∥θ1 − θ2 ∥M > atol + rtol ∥θ ∥M ,
(47)
the time step is rejected and reduced, and two new candidate solutions are recomputed with the smaller step. This process repeats until either the tolerance is satisfied or, if provided, a minimum allowed time step is reached. The three adaptive steppers differ in how the two candidate solutions θ1 , θ2 are obtained. For AdaptiveHeun, the higher-accuracy solution is obtained by performing two consecutive half-sized Heun steps in place of a single full step, so that estimating the error requires solving the underlying differential equation twice, at a correspondingly higher computational cost. RK23 and RK45, by contrast, are embedded Runge– Kutta pairs, the Bogacki–Shampine and Dormand–Prince schemes respectively, in which a single set of intermediate stage evaluations of f is reused to construct two solutions of different order (second and third order for RK23; fourth and fifth order for RK45) via two different linear combinations of the same stages. The higher-order solution of the pair is then the one actually propagated forward. While users can implement custom norms for M, our library already provides two: a simple root-mean-square norm, and a norm that uses the quantum geometric tensor S as its metric, so that the distance between the two solutions is evaluated directly in the Hilbert space (see Sec.2.6.1).
2.6
The Optimizer
The optimizer class is responsible for taking all the key modules defined so far and orchestrating them into a complete, runnable training algorithm. Our library defines the general structure of an optimizer through the AbstractOptimizer class. Given the current set of parameters θ , this class implements a full VMC loop, producing an updated set of parameters θ ′ as output. This is done through three steps: (1) the sampler is used to draw a new set of configurations S; (2) these configurations are passed to the chosen objective function via its value_and_grad method (see Sec. 2.4); and (3) the resulting output is passed to AbstractOptimizer.get_update(), which returns θ ′ . While this three-step structure is entirely general, the specific rule used to turn the objective function’s output into a parameter update is algorithm-dependent, and must therefore be implemented separately by each concrete optimizer, by overriding get_update. This three-step procedure is precisely what computes f (t, θ ) in the differential equation of Sec. 2.5, and a single stepper call may require evaluating f several times within one integration step. Each such evaluation would require drawing an entirely new set of configurations from the distribution pθ associated with that intermediate θ , at significant additional computational cost. To avoid this, AbstractOptimizer provides the option to draw new configurations only once, at the very first stage of a stepper call, and to reuse this same set of configurations for all subsequent intermediate stages, correcting for the fact that they were drawn from a different distribution than the current one via importance sampling, as proposed in Ref. [32]. This simple technique reduces the computational cost of otherwise expensive multi-stage time integrators, and it moreover reduces the statistical noise entering the error estimate of Eq. 47, allowing for a more reliable dynamical refinement of the time step. Whether this scheme is used can be decided at initialization through the flag resample_stepper. 23
SciPost Physics Codebases
Submission
This general interface also implements two convenience utilities, ground_state_search and time_evolution, both of which simply repeat the VMC loop described above: for a fixed number of iterations N in the former case, or until a target time t max is reached in the latter. Both methods can additionally take, as optional arguments, a list of observables and a list of callbacks; when provided, the corresponding quantum expectation values are computed and stored at every iteration, and the given callbacks are invoked, allowing the user to monitor, log, or otherwise intervene in the optimization as it progresses. As with the other core components of the library, this class is designed so that users can easily implement custom optimizers by inheriting from AbstractOptimizer and implementing only get_update, making it straightforward to develop and experiment with new optimization algorithms. Our library already implements several optimizers tailored to ground-state search and to dynamics, which we discuss in what follows. Importantly, all the optimizers provided in jVMC are compatible with the LazySampledObs interface (see Sec 2.3.3), so that if required the algorithms never materialize the full Jacobian to construct quantities such as the quantum geometric tensor or the tangent kernel. 2.6.1
Ground State Search Optimizers
The ground state of a Hamiltonian can be approximated using the variational principle, which guarantees that the quantum expectation value of the Hamiltonian over any trial wavefunction |ψθ 〉 is always greater than or equal to the true ground-state energy E0 , Eθ =
〈ψθ |Ĥ|ψθ 〉 ≥ E0 . 〈ψθ |ψθ 〉
(48)
As a consequence, minimizing the left-hand side of Eq. 48 with respect to the parameters θ provides a way to approximate the ground state of the system. Since this optimization problem is in general non-convex, several strategies can be adopted in practice to reliably converge to a good approximation of the ground state. Our library implements a simple Adam optimizer, which drives the optimization towards the ground state through an adaptive variant of stochastic gradient descent (SGD) [58], using the gradient ∇θ Eθ obtained from the Observable objective function introduced in Sec. 2.4. Since plain SGD ignores both the geometry of the variational manifold and the gauge redundancy typically present in overparametrized networks (multiple values of θ can represent the same physical state |ψθ 〉), jVMC also provides stochastic reconfiguration (SR) as an optimization scheme [4, 23]. SR can be understood as a natural-gradient method [59]. Rather than measuring the step size in parameter space, it measures it through the Fubini– Study distance between the normalized states |ψθ 〉 and |ψθ +δθ 〉, which to second order reads P δθ k Re[Skl ] δθl with the quantum geometric tensor (QGT) defined as kl Skl = Cov p Γk∗ , Γl . (49) Minimizing the linearized loss at fixed step length yields the update θ → θ + η δθ , with δθ the solution of Re[S] δθ = −Re[F ], (50) where F is the force vector of Eq. (33) and the factor 12 relating Re[F ] to ∇θ L has been absorbed into the learning rate η. As gauge redundancies manifest themselves as (near-)zero eigenvalues of Re[S], before solving Eq. (50) this has to be regularized. A standard approach is to shift and rescale the diagonal of the QGT S → S + λ1 I + λ2 diag(S), 24
(51)
SciPost Physics Codebases
Submission
where diag(S) denotes the matrix that agrees with S on the diagonal and vanishes elsewhere. The two regularization strengths can be provided to the SR class at initialization, as diagonal_shift and diagonal_scale respectively, either as fixed scalars or as functions of the current optimization step, allowing for e.g. an annealed regularization schedule. Since the QGT has shape Np × Np , solving Eq. 50 directly can become computationally prohibitive as the network size increases. In this regime, the MinSR optimizer can be used instead: it targets the same update as SR, but exploits the push-through identity to recast the solution of Eq. 50 as the inversion of an Ns × Ns matrix, the neural tangent kernel [31, 39]. As for the QGT, the tangent kernel can be regularized in exactly the same manner, again via the diagonal_shift and diagonal_scale parameters. Both SR and MinSR can be combined with any objective function provided in jVMC, but they are geometrically motivated only when L depends on θ solely through |ψθ 〉. 2.6.2
Real Time Evolution
The time-dependent Schrödinger equation can be approximately solved within VMC by means of time-dependent VMC (tVMC): the parameters of the network are promoted to time-dependent quantities θ (t), chosen at every instant so that the family of variational states |ψθ (t) 〉 follows the exact solution as closely as possible. While |ψθ (t) 〉 is constrained by construction to the variational manifold defined by the network, the exact time-evolved state will in general leave this manifold at every infinitesimal time step. All tVMC schemes therefore rest on the same idea, the time-dependent variational principle (TDVP): the Schrödinger equation is projected onto the tangent space of the manifold at the current point θ (t) [60]. The tangent space is spanned by the vectors |Vk 〉 = ∂θk − 〈∂θk 〉 |ψθ 〉 (52) so that 〈s|Vk 〉 = Γk (s) − 〈Γk 〉 ψθ (s), where the mean is subtracted to remove changes of norm and global phase. As mentioned above restricting the time derivative to the manifold, leaves a residual X |R〉 = θ̇k |Vk 〉 + i Ĥ − Eθ |ψθ 〉. (53) k
The TDVP requires that |R〉 has no component along the vectors |Vk 〉 spanning the tangent space: X 〈Vk |R〉 = Skk′ θ̇k′ + i Fk = 0, (54) k′
with the quantum geometric tensor S and the force vector F , the same Monte Carlo estimators that enter Eq. 50, now keeping both real and imaginary parts. If the network is holomorphic, the tangent space is a complex vector space and the full complex condition 〈Vk |R〉 = 0 can then be imposed, leading to the Dirac–Frenkel form S θ̇ = −i F.
(55)
If the network is not holomorphic, the tangent space is only a real vector space, therefore not closed under multiplication by i. This leads to an additional degree of freedom: the test vectors can be chosen as either |Vk 〉 or i|Vk 〉, leading to different implementations of the same variational principle. • McLachlan form: the test vectors are chosen as |Vk 〉, so that Re[S] θ̇ = Re[−i F ]. It can be shown that this formulation is not symplectic. 25
(56)
SciPost Physics Codebases
Submission
• Lagrangian form: the test vectors are chosen as i |Vk 〉, so that Im[S] θ̇ = Im[−i F ].
(57)
Our library implements all three variants of the same variational principle within a single TDVP class. When the network is holomorphic, the class automatically uses the Dirac–Frenkel
form. When the network is not holomorphic, the user selects between the McLachlan and the Lagrangian form via the boolean flag make_real, which determines whether the real or the imaginary part of S and −i F is used to construct the linear system solved at each time step. tVMC generally requires a more delicate numerical treatment than ground state search. In ground-state search only the final, converged state matters: transient inaccuracies in S or F along the optimization path slow down convergence but do not bias the state eventually reached, in much the same way that noisy gradients still converge on average in ordinary stochastic gradient descent. In dynamics, by contrast, every intermediate step directly determines the trajectory being traced out, and errors in S and F at a given step propagate forward and accumulate over the subsequent evolution, exactly as for the right-hand side of any numerically integrated ODE. This leads to two practical considerations. First, S and F must be resolved with considerably higher statistical accuracy than is typically required for ground-state search, which in practice means using a substantially larger number of samples NS at every step. Second, the naive diagonal regularization of Sec. 2.6, harmless for ground-state search since it only reshapes the descent path towards the same fixed point, can introduce a substantial bias in the dynamics. Shifting and rescaling S changes the metric defining the tangent-space projection itself, and therefore changes which state on the manifold is actually being tracked at every step, rather than merely how quickly it is reached. Consequently, more elaborate regularization schemes, tailored specifically to the linear systems arising in tVMC, are required; we discuss the solvers implemented in our library for this purpose in Sec. 2.6.3. 2.6.3
Solvers
As explained in Sec. 2.6, most optimizers require the solution of a linear system of the form Ax = b at every iteration. Our library abstracts this step behind a common AbstractSolver interface AbstractSolver.__call__ : (A, b) 7−→ (x, info), (58) where info is a dictionary of solver-specific diagnostics (e.g. the residual of the solve, or the condition number of A) that can be logged at every step via the callback mechanism of AbstractOptimizer (Sec. 2.6). Since A is always either the QGT or the tangent kernel, both Hermitian positive semi-definite matrices by construction (Sec. 2.6), our library provides the following solvers, all of which exploit this structure: • Pinv: computes a truncated Moore–Penrose pseudoinverse of A via its eigendecomposition A = V diag(λ) V † (exploiting Hermiticity, rather than a general SVD), and solves the system as x = V diag(λ−1 ) V † b, without ever explicitly assembling the pseudoinverse matrix itself. Eigenvalues satisfying |λi /λmax | ≤ pinv_cutoff are treated as zero and dropped, using a hard cutoff fixed at initialization. • PinvSNR: extends Pinv with two complementary, smooth (rather than hard) regularization filters, applied to the inverse eigenvalues, following the general pseudoinverse regularization scheme of [26, 61]. The first replaces the fixed hard cutoff of Pinv with a smooth cutoff function of |λi /λmax |. This avoids the discontinuous jumps in the resulting update over the course of the optimization, a concern that matters most in dynamics. 26
SciPost Physics Codebases
Submission
Moreover, rather than being fixed, the cutoff itself is searched adaptively at every single linear solve: starting from a loose value, it is decreased until either the residual of the solve falls below a target tolerance pinv_tol, or a minimum allowed cutoff pinv_cutoff is reached, whichever comes first. Note that this differs from Pinv’s use of the same parameter name: for Pinv, pinv_cutoff is the (fixed) cutoff itself, whereas for PinvSNR it is only the floor of an adaptively determined cutoff. The second filter is activated by setting snr_tol to a nonzero value at initialization. It further suppresses update directions along eigenvectors of A whose associated component of the force vector b cannot be statistically resolved from sampling noise, based on the signalto-noise ratio (SNR) of b projected onto the eigenbasis of A [26]. Computing this SNR requires the densely materialized, per-sample log-derivative Jacobian (i.e. a SampledObs rather than a LazySampledObs, obtained by setting batched_jacobian=False on the objective function, see Sec. 2.4) together with the per-sample local estimator entering b. For the same reason, SNR regularization is only meaningful for SR and TDVP, whose linear system is formulated directly in the p-dimensional parameter space spanned by the per-sample Jacobian; MinSR, which instead operates in the Ns -dimensional sample-space eigenbasis of the tangent kernel, must therefore be used with snr_tol = 0. • CG: an iterative conjugate-gradient solver, wrapping jax.scipy.sparse.linalg.cg. Unlike Pinv and PinvSNR, which require A to be diagonalized and therefore explicitly materialized as a dense matrix, CG only ever needs A through matrix-vector products, and can therefore also be used with a purely functional, matrix-free representation of A. All solvers that require diagonalizing A additionally support three diagonalization backends. These can be selected via diagonalization_mode: "device", using jax.numpy.linalg.eigh on a single device; "host", using numpy.linalg.eigh on the CPU; and "distributed", which diagonalizes A jointly across all available devices using JAXMg [48]. The distributed mode allows matrices considerably larger than what a single device could otherwise handle to be diagonalized, without ever materializing the full matrix on every device simultaneously, thereby avoiding out-of-memory errors that would otherwise limit the size of the QGT, or of the tangent kernel, that can be inverted. We demonstrate in the benchmarking section below, that the parallelization moreover yields speedup compared to single device runtime for large problem sizes.
2.7
Using Multiple GPUs
As outlined throughout the previous sections, jVMC is designed from the ground up to run efficiently across multiple GPUs, possibly spread across different nodes. Concretely, this means that: samples are generated using independent Markov chains distributed in parallel across all available devices (Sec. 2.2); every network evaluation and gradient computation, whether triggered directly by the NQS or internally by an operator’s local-value computation (Sec. 2.1.2, Sec. 2.3), is likewise carried out in parallel across devices; the diagonalization of the QGT or the tangent kernel, required by SR, TDVP, and MinSR, is parallelized across devices via JAXMg (Sec. 2.6.3); and, even when a finite batch_size restricts how many configurations are processed at once, each individual batch is itself sharded so that it lives across multiple devices rather than being placed on a single one. Correspondingly, the QGT and the tangent kernel are both built and stored distributed across devices, so that no single device ever holds the full matrix (see Appendix B). This is achieved by building on the sharding mechanism natively provided by JAX. A one-dimensional device mesh, with a single axis named "devices", is constructed once at import time from all globally visible devices. Throughout the library, arrays of shape (Ns , ...) 27
SciPost Physics Codebases
Submission
consistently follow the convention of being distributed along this leading axis, so that the samples living on a given device are also the ones processed on that same device at every subsequent stage of the computation, without requiring data movement between devices in between. For this scheme to divide evenly, quantities such as the number of samples or the number of Markov chains must be divisible by the number of devices. The library handles this automatically by increasing the number of samples or Markov chains if necessary. For the specific case of matrix diagonalization via JAXMg (Sec. 2.6.3), a second, twodimensional device mesh, with axes labeled "row" and "col", is constructed separately from the one-dimensional mesh used elsewhere, with devices arranged in as close to a square grid as possible. This reflects the fact that efficient distributed diagonalization algorithms typically require a genuinely two-dimensional partitioning of the matrix being diagonalized, rather than the one-dimensional, sample-indexed sharding used for the rest of the pipeline. Beyond sharding across the devices of a single process, jVMC also supports running across multiple processes, for instance to scale a computation across several nodes of a cluster, each contributing its own set of GPUs. By default, the library assumes a single-process setting. Multiprocess execution is enabled by setting the global flag global_defs.JVMC_USE_DISTRIBUTED to True before importing the library. In this case, jVMC calls jax.distributed.initialize() at start-up, which establishes the communication between processes and merges their devices into a single, globally addressable mesh spanning all nodes. On most common cluster environments, such as SLURM, JAX detects the process layout automatically, so this default call is sufficient and no further configuration is needed. On systems where this automatic detection is not available, the user must instead call jax.distributed.initialize() themselves, with a custom configuration, before importing jVMC. The flag global_defs.JVMC_USE_DISTRIBUTED must still be set to True in this case, so that the library operates in multi-process mode. On a SLURM environment, when using multiple nodes, one process per device should be used. JAXMg requires one process per device also on a single node. 2.7.1
Sharded Decorator
The parallelization of per-configuration computations is centralized in a single reusable building block, the sharded decorator. It turns a plain method acting on one batch of configurations into a function that is vectorized and distributed across the device mesh. The decorator first vectorizes the method over the configurations, and then distributes it in one of two ways. With automatic_sharding=True, the vectorized method is simply compiled with jax.jit, and JAX’s sharding propagation places the computation according to the sharding of the inputs. Otherwise, it is distributed explicitly with jax.shard_map, using user-specified in_specs and out_specs that fix how each argument and the output are partitioned across the mesh. The first option requires no additional information, while the second gives precise control over the partitioning. In addition, the decorator handles batching transparently whenever a batch_size smaller than the number of samples is requested: the configurations are padded to the next multiple of batch_size, split into batches, and each batch is sharded across the devices before being passed to the distributed function, without any communication between devices. When constructed with yield_iter=True, rather than eagerly evaluating and concatenating all batches, the decorator instead returns a lazily evaluated, reusable generator over per-batch results. This is precisely the mechanism underlying NQS.lazy_gradients and its use throughout LazySampledObs (Sec. 2.1.2, Sec. 2.3.3), allowing gradients (or any other per-configuration quantity) to be both distributed across devices and streamed batch by batch, without ever materializing the full result on any single device at once. Users can further control how this decorator is constructed by setting the global flag global_defs.JVMC_BATCH_LOOP to either "python" or "compiled" before importing the library. The flag determines how 28
SciPost Physics Codebases
Submission
(a) 16
(b) Ideal Measured
Objective function and gradient 68.93 s
1 GPU 72.4 s
Objective function and gradient 4.70 s
16 GPUs 5.2 s
Speedup
8
Sampling 2.50 s Solve 1.00 s
4
2
1 1
2
4
8
Sampling 0.23 s Solve 0.22 s
16
Number of GPUs
Figure 2: (a) Speedup of a TDVP step as a function of the number of GPUs used, and (b) breakdown of the time spent in the three main parts of the algorithm. The system is a transverse-field Ising chain with N = 100 spins, and the variational state is a RNN with Np = 2082 parameters. The number of samples is Ns = 219 and the batch size is Nb = 210 . The GPUs are NVIDIA A100 80GB. the loop over batches is executed, and the two options trade runtime performance against recompilation cost. In the "python" mode, the loop is a plain Python for loop that repeatedly calls a single jit-compiled function. In the "compiled" mode, the loop itself is expressed in JAX and compiled together with the batched computation. Compiling the loop generally yields better performance, since the compiler can fuse operations across iterations. However, it requires recompilation every time the shape of the input changes, i.e., whenever the number of samples changes. Besides the compilation time, this has a second, less obvious cost: JAX caches every compiled executable, and for large networks these executables are themselves big. Repeatedly changing the number of samples therefore accumulates a growing set of cached programs, which can by itself exhaust memory and cause out-of-memory errors, even when a single evaluation would comfortably fit. The Python loop avoids both problems: the inner compiled function is always called on inputs of fixed shape (batch_size, ...), regardless of the total number of configurations, so recompilation, and the accompanying growth of the cache, is only triggered when batch_size itself is changed. The "compiled" mode is therefore preferable when the number of samples is fixed throughout a run, while the "python" mode is better when this number varies between calls. When imported, the library defaults to "python". Because this machinery is exposed as a simple decorator, adding a new sharded, batched method to a custom NQS, Operator, or objective function (Sec. 2.1.2, Sec. 2.3, Sec. 2.4) requires no explicit knowledge of shard_map or manual batching logic on the user’s part.
29
SciPost Physics Codebases
Submission
Objective function and gradient
Solve
(a)
(b)
200
50
100
Peak device memory [GB]
Speedup over batch size 8
Sampling
60 40 30 20 10 6 4 3 2 1
40 30 20 10 0
23
25
27
29
211
213
215
Batch size
23
25
27
29
211
213
215
Batch size
Figure 3: (a) Speedup as the batch size is increased for the three main parts of the algorithm, and (b) the corresponding memory usage for a single TDVP step. The system is a transverse-field Ising chain with N = 50 spins, and the variational state is a RWKV with Np = 32768 parameters. The number of samples is Ns = 212 and the GPUs are NVIDIA A100 80GB.
3
Benchmarks
3.1
Parallelism on multiple GPUs
We benchmark the parallelization capabilities of the library across accelerators with a single step of the TDVP algorithm. Fig. 2(a) shows an example of an observed speedup when increasing the number of GPUs from 1 to 16. Each node contains only 4 GPUs, but the parallelization is seamless across nodes thanks to the JAX sharding mechanism. Fig. 2(b) shows the breakdown of the time spent in three parts of the algorithm: the sampling, the computation of the energy and its gradient, and solving the linear system. The first two parts can be fully parallelized across GPUs, while the last part contains the inversion of the quantum geometric tensor, which cannot be sped up in the same way. Note that the inversion can be parallelized with JAXMg, as explained in Sec. 2.7, and can provide a speedup in certain cases. Its main goal, however, is to reduce the memory footprint of the inversion. This example, however, does not use JAXMg, as the number of parameters is small enough that the inversion of the QGT is not a memory bottleneck. Nevertheless, the solve step in Fig. 2(b) still becomes faster with more GPUs, from 1.00 s to 0.22 s, because it also includes the construction of the QGT from the Jacobian, which is distributed across devices like the rest of the computation. In this example, most of the time is spent on computing the energy and its gradient. This is due to the large system size: each sample has 100 connected elements, making the local energy computation expensive. This computation, however, is embarrassingly parallel, and therefore well suited for GPU parallelization.
3.2
Batching
The batch size must be carefully chosen to balance the memory usage and the speed of the computation. Fig. 3(a) shows an example of the speedup for a single TDVP step as a function of the batch size, broken down into the three main parts of the algorithm: sampling, computing the 30
Submission
(a)
(b)
10 100
Time of one TDVP step [s]
Speedup of the sampling over 10 chains
SciPost Physics Codebases
6 4 3 2
1 GPU 2 GPUs 4 GPUs
1
jaxmg off, 16 GPUs jaxmg on, 16 GPUs
10
1
0.1 10
100
103
1000
Number of Markov chains
104
Number of parameters
Figure 4: (a) Speedup in the sampling time as the number of Monte Carlo chains is increased. The system is a transverse-field Ising chain with N = 50 spins, and the variational state is a complex CNN with Np = 3268 parameters. The number of samples is Ns = 212 , and the GPUs are NVIDIA A100 80GB. The sampling consists of single-spin-flip Metropolis updates with sweeps of 50 proposals and 20 thermalization sweeps. The speedup is computed with respect to 10 chains for each curve. (b) Comparison of the execution time of a single TDVP step with and without JAXMg. The curves stop when the simulation runs out of memory. The system is a transverse-field Ising chain with N = 50 spins, and the variational state is a RNN. The number of samples is Ns = 212 and the batch size is Nb = 210 . The GPUs are NVIDIA A100 80GB. energy and its gradient, and solving the linear system. The first two parts benefit the most from increasing the batch size, with a speedup spanning two orders of magnitude. Notice, however, that the speedup plateaus as the batch size approaches the total number of samples used, while the memory usage in Fig. 3(b) increases sharply. There is therefore a sweet spot, dependent on the problem, where memory usage can be lowered without sacrificing performance. The cost of solving the linear system, on the other hand, is often dominated by the inversion of the QGT, which is independent of the batch size, so no speedup is observed.
3.3
Parallelized Monte Carlo sampling
Monte Carlo sampling can be parallelized by running multiple Markov chains in parallel, with the chains themselves parallelized across GPUs. Fig. 4(a) shows an example of the speedup in sampling time as a function of the number of Markov chains used, on one or more GPUs. At first, increasing the number of chains leads, as expected, to a speedup. At some point, however, the speedup saturates, and then reverses. This happens as the GPU’s computing resources become saturated by the parallel network evaluations. Furthermore, each chain has a fixed number of thermalization sweeps, meaning that adding more chains increases the total number of sweeps, leading to a slowdown. Adding more GPUs provides more computational resources and allows more chains to run in parallel before reaching saturation. The optimal number of chains is therefore problem dependent, and should be chosen carefully to maximize the speedup.
31
SciPost Physics Codebases
3.4
Submission
Distributed matrix inversion with JAXMg
JAXMg allows the inversion of the QGT to be distributed across multiple GPUs, allowing the use of larger networks for TDVP, or more samples for MinSR. As an example, Fig. 4(b) shows the total time of a single TDVP step on 16 GPUs with and without JAXMg. Without JAXMg, the inversion is performed on one GPU, and the maximum number of parameters reached before running out of memory is Np = 40862, while with JAXMg, the maximum number of parameters reached is Np = 79886. Fig. 4(b) also shows that the distributed inversion is slower than the single GPU inversion for small matrices, but becomes faster for larger matrices as the memory usage approaches saturation. JAXMg decomposes the matrix into tiles whose size can be controlled with the tile size parameter TA. By default, we fix this parameter at TA = 256. More information about the tiling can be found in Ref. [48].
3.5
Comparison with NetKet
NetKet [50] is another widely used open-source Python package implementing VMC with NQS, and it is therefore natural to benchmark the two codebases against each other. Before doing so, we note two points. First, both libraries are built on JAX and rely on just-in-time compiled functions, so we expect comparable performance and memory usage for sampling, expectation values and gradients, as confirmed by the benchmarks below. Second, both libraries support multi-GPU and multi-node execution through JAX sharding and handle the distribution of data internally, so that little knowledge of the device layout is required from the user. One may therefore ask why two libraries with overlapping functionality should be maintained. We see two reasons. First, independent implementations of the same methods provide a direct test of reproducibility, which is particularly valuable in a field where results and computational performance can depend sensitively on implementation details. Second, and more importantly, the two packages follow different design philosophies. NetKet aims at broad coverage of models, Hilbert spaces, operators and algorithms within a general and extensible framework. jVMC instead deliberately keeps its core minimal. It implements a small set of essential building blocks and keeps the path from a high-level call to the underlying JAX operations short and explicit. Since VMC with NQS is still a rapidly evolving field, with few established guidelines on which methods work reliably, we consider this an advantage for method development. New algorithms can be implemented with little code, without navigating extensive abstraction layers, and on the same footing as the built-in functionality. We benchmark the two libraries in three settings, using a restricted Boltzmann machine (RBM) as the variational state. 1. We compare the execution time for sampling and for estimating the expectation value of an observable. As observable we take the Hamiltonian of the one-dimensional transversefield Ising model with N = 80 spins, Ĥ = −
N −1 X
σ̂zi σ̂zi+1 −
i=1
N X
σ̂ix .
(59)
i=1
The results are shown in Tab. 2, and as expected the two libraries share very similar execution time for both tasks. 2. We measure the peak memory usage and the execution time of a single SR step as a function of the number of samples, again for the Hamiltonian in Eq. (59). In both libraries the linear system is solved with the Moore–Penrose pseudoinverse. For NetKet we use 32
SciPost Physics Codebases
Submission
60 40 30 20
jVMC, batched Jacobian out of memory
(a)
(b) batch size
Peak device memory [GB]
jVMC, full Jacobian NetKet, VMC SR
10 6 4 3 2 1
2
(c)
(d)
Time [s]
1 0.6 0.4 0.3 0.2
0.1 210
212
214
216
218
220 210
Number of samples
212
214
216
218
220
Number of parameters
Figure 5: Peak device memory and time of one optimization step in jVMC and NetKet on a single NVIDIA GH200 GPU. (a, c) SR at a fixed number of parameters, Np = 6400, as a function of the number of samples Ns . (b, d) MinSR at a fixed number of samples, Ns = 4096, as a function of Np . The variational state is a RBM for the transverse-field Ising chain with N = 80 spins, in double precision, with 80 hidden units in (a, c) and 16 to 16384 hidden units in (b, d). Both libraries use the same parameters, the same uniformly distributed samples and the same linear solver: an eigendecompositionbased pseudo-inverse with diagonal shift 10−3 and relative eigenvalue cutoff 10−14 . NetKet runs its VMC_SR driver, with the neural tangent kernel for MinSR. jVMC builds the Jacobian either in full or in batches of 214 samples in (a, c) (dashed line) and 210 samples in (b, d); the other series process all samples at once. A step comprises the local energies, the Jacobian, the matrix S (SR) or the neural tangent kernel (MinSR) and the solution of the linear system; sampling is excluded so that the same set of samples can be used in both libraries. Times are obtained after one compilation and one warm-up step. The two libraries give the same parameter update to within a relative difference of 5 × 10−12 .
33
SciPost Physics Codebases
Submission
jVMC NetKet, IsingJax NetKet, LocalOperatorJax
Sampling [ms]
〈Ĥ〉 [ms]
49.4 46.6 46.6
5.19 4.07 7.53
Table 2: Execution time of the two stages of a Monte Carlo estimate of 〈Ĥ〉 in jVMC and NetKet on a single NVIDIA GH200 GPU, for the transverse-field Ising chain of Eq. (59) with N = 80 spins. The variational state is a RBM with 80 hidden units in double precision; both libraries use identical network parameters. Sampling: 4096 samples from 1024 Markov chains, single-spin-flip Metropolis updates with sweeps of 80 proposals and 20 thermalization sweeps. Estimate of 〈Ĥ〉: the full estimate on these samples, including matrix elements, network evaluations, mean and statistical error, with a chunk size of 4096 network evaluations. The two NetKet rows differ only in the operator implementation and share the same sampler. QGTJacobianDense. For jVMC we run the benchmark twice, once with the full Jacobian
and once with the batched Jacobian. The results are shown in Fig. 5 (a,c). With the full Jacobian, the two libraries show very similar memory usage and execution time. With the batched Jacobian, the peak memory saturates as the number of samples grows, at the cost of a modest increase in execution time. This makes the batched Jacobian essential for avoiding out-of-memory errors at large sample sizes. To our knowledge, NetKet offers no equivalent option that bounds the memory of the Jacobian while still producing the dense matrix required by direct linear solvers. Its matrix-free alternative avoids storing the Jacobian, but it is designed for iterative solvers. 3. We repeat the experiment for MinSR, now varying the number of variational parameters at a fixed number of samples. The results are shown in Fig. 5 (b,d). Again, the two libraries perform very similarly. Since the batched Jacobian is split along the sample axis, each batch still contains all parameters, so its memory grows with the number of parameters and no plateau appears in this case. Nevertheless, the batched Jacobian requires less memory than the full one and runs successfully at parameter counts where both the full-Jacobian implementation of jVMC and NetKet run out of memory. As a final note, unlike jVMC, the current version of NetKet (3.22.4) does not keep the quantum geometric tensor sharded across devices: every device computes the full Np × Np contribution of its own samples, and these are all-reduced into a complete copy of S on each device. The same holds for the tangent kernel of MinSR: NetKet redistributes the Jacobian along the parameter axis, which splits the computation of T across devices, but T is again all-reduced into a full Ns × Ns copy on every device. A distributed solver such as JAXMg therefore cannot reduce the memory per device in NetKet, whereas jVMC builds both matrices block by block with reduce-scatter operations, so that neither is ever stored in full on a single device (see Appendix B).
34
SciPost Physics Codebases
Identity
D4
Submission
D4 + T b) Ground-state accuracy
10
2 Energy variance σH /J12
Time [s]
a) Time and batch size
1
Batch size
0.1 210 212 214 64/64
32/64
32/32
16/64
0.08
0.07
16/32
0.0007
Precision (network / VMC)
64/64
0.00075
0.0008
Relative energy error (E − E0 )/|E0 | 32/64
32/32
16/64
16/32
c) Process fractions
Step wall time [%]
100 75 50 25 0
64/64
32/64
32/32
16/64
16/32
Precision (network / VMC) Sampling
Objective
Solve
Other
Figure 6: Mixed-precision ground-state search for the periodic 6 × 6 J1 –J2 model at J2 /J1 = 0.5, with Np = 10 032 ViT parameters. Precision labels give the network and VMC bit widths, respectively, and T denotes lattice translations. (a) Step times and evaluation batch sizes for three choices of symmetry. Each time is the median over three updates following one warm-up update and includes sampling, objective evaluation, and the solve. Whiskers span the observed minimum and maximum, and the lower bars give batch sizes on a separate logarithmic scale. (b) Relative energy error and energy variance after 10 000 updates with D4 + T symmetry. We use the rounded exact-diagonalization energy E0 = −18.13716 J1 and estimate σ2H from the sample variance of the complex local energy. Horizontal error bars give one Monte Carlo standard error of the energy divided by |E0 |. Vertical error bars give one standard error of the variance from 4 000 whole-chain bootstrap resamples stratified by ensemble. (c) Fractions of step wall time spent on sampling, objective evaluation, the solve, and other work, obtained from mean process times over the same three updates as in (a). The solve includes construction of the tangent kernel and right-hand side, the linear solve, and projection of the solution back into parameter space.
35
SciPost Physics Codebases
Submission
4
Examples
4.1
The J1 –J2 Model Using Mixed Precision
As a first example, we use the mixed-precision interface of Sec. 2.1.2 to approximate the ground state of the spin-1/2 J1 –J2 Heisenberg model on the square lattice, X X Ĥ = J1 Ŝi · Ŝ j + J2 Ŝi · Ŝ j , (60) 〈i, j〉
〈〈i, j〉〉
where 〈i, j〉 and 〈〈i, j〉〉 denote nearest- and next-nearest-neighbour pairs, respectively. At J2 /J1 = 0.5 the two antiferromagnetic couplings compete strongly, the model is highly frustrated, which makes it one of the standard benchmarks for NQS. We consider a 6 × 6 lattice with periodic boundary conditions, for which the reference energy can be found using exact z diagonalization. We restrict the search to the sector of zero total magnetization, Stot = 0, which contains the ground state. This constraint is enforced during sampling by the SpinFlipZeroMag proposer (Sec. 2.2.3). Our ansatz follows the vision transformer (ViT) of Viteritti et al. [62], whose attention weights depend on the relative displacement of the patches. We divide the lattice into four 3 × 3 patches, embed each patch in a vector of dimension 12, and use six transformer layers with four attention heads each, giving 10 032 real parameters. In the modified readout we apply layer normalization to the sum of the patch embeddings and separately normalize the real and imaginary inputs to the complex log cosh function. We work in the Marshall basis, in which the nearest-neighbor spin-exchange matrix elements acquire a minus sign. The ViT is fully compatible with any abelian symmetry, which here is the square point group D4 and translation. We impose only the latter on the network through symmetry projector of Sec. 2.1.3. The cost of a VMC step is dominated by network evaluations: the forward passes during sampling, the amplitudes of all configurations connected by Ĥ that enter the local energies, and the Jacobian Γ . These operations tolerate reduced precision well. By contrast, the accumulation of Monte Carlo statistics might be sensitive to round-off errors. jVMC sets the two precisions independently, through arguments of NQS: sampler_dtype, eval_dtype and grad_dtype. These fix the arithmetic inside the network, while the global output data types fix the precision of everything downstream (Sec. 2.1.2). For instance, a run with a complex network in FP32 and the remaining VMC operations in FP32 is set up as 1 2 3
import os os.environ["JVMC_DT_OUT_REAL"] = "f32" os.environ["JVMC_DT_OUT_CPX"] = "c64"
4 5 6 7
import jax.numpy as jnp import jVMC from jVMC.operator.discrete import SigmaZ, SigmaPlus, SigmaMinus
8 9 10 11 12 13 14 15 16 17 18 19
L = 6 net = jVMC.nets.ViterittiViT( Lx=L, Ly=L, patch_size=3, layers=6, embed_dim=12, heads=4, phase_scale=1.0, param_dtype=jnp.float32, compute_dtype=jnp.float32, ) psi = jVMC.vqs.NQS( net, (L, L), batch_size=16, seed=1234, sampler_dtype=jnp.float32,
36
SciPost Physics Codebases
20 21 22 23 24 25 26 27 28 29 30
Submission
eval_dtype=jnp.float32, grad_dtype=jnp.float32 ) chains = 8 checkerboard = jnp.indices((L, L)).sum(axis=0) % 2 sampler = jVMC.sampler.MCSampler( psi, jVMC.propose.SpinFlipZeroMag(), key=4321, init_state=jnp.tile(checkerboard, (chains, 1, 1)), num_chains=chains, num_samples=32, sweep_steps=L*L, thermalization_sweeps=2, )
31 32 33 34 35 36 37 38 39 40 41 42 43
# Periodic Heisenberg bonds in the Marshall basis H = 0 bonds = [(1, 0, 1.0), (0, 1, 1.0), (1, 1, 0.5), (1, -1, 0.5)] for y in range(L): for x in range(L): i = y * L + x for dx, dy, J in bonds: j = ((y + dy) % L) * L + (x + dx) % L sign = -1 if (dx + dy) % 2 else 1 H += (J / 4) * SigmaZ(i) * SigmaZ(j) H += (sign * J / 2) * SigmaPlus(i) * SigmaMinus(j) H += (sign * J / 2) * SigmaMinus(i) * SigmaPlus(j)
44 45 46 47 48 49
energy = jVMC.objective_function.Observable(H) opt = jVMC.optimizer.MinSR(sampler, psi, diagonal_shift=1e-3) stepper = jVMC.stepper.Euler(0.01) history = opt.ground_state_search(3, energy, stepper) print(float(history["energy"]["mean"][-1]))
For this example we compare each network precision (FP64, FP32, or FP16) with FP64 VMC arithmetic and also test FP32 and FP16 networks with FP32 VMC arithmetic. Each update uses 2 000 samples drawn from 2 000 Markov chains with 144 proposals per sweep. We optimize the parameters with SPRING [63] at zero momentum (µ = 0), using a diagonal shift λ = 10−3 and unit weight for the projector onto the constant mode of the tangent kernel. We use a constant learning rate η = 0.05 and bound the Euclidean norm of each parameter step by 0.5. We assess runtime and accuracy for the various precision combinations on a single NVIDIA GeForce RTX 5090. First we evaluate the runtime for three symmetry settings: no projection, projection onto the D4 point group, and D4 combined with lattice translations. Lowering the precision also reduces the memory required per configuration, so for every precision pair and symmetry setting we select the evaluation batch size independently, while the gradient batch always contains all 2 000 samples. The timings in Fig. 6(a) therefore combine the cheaper arithmetic with the larger batches it allows, which reflects how mixed precision is used in practice. Reduced precision lowers the step time for every symmetry setting. For example, with D4 and translations, FP16/FP32 is 14.4 times faster than FP64/FP64. This large factor partly reflects the limited double-precision throughput of consumer GPUs. Fig. 6(c) shows how the step time is distributed among sampling, objective evaluation and the linear solve. To assess how reduced precision affects the final variational state, we train each precision pair for 10 000 updates on a single NVIDIA A100 80 GB, with both D4 and lattice-translation symmetry enforced. The cumulative training time decreases from 27.8 h for FP64/FP64 to 15.5 h for FP16/FP32. Figure 6(b) shows the energy and variance of each final state, measured independently of training from 107 fresh configurations. For each state, we initialize two independent ensembles of 1 000 chains, discard 512 thermalization sweeps, and retain 5 000
37
SciPost Physics Codebases
Energy
22.20 22.15
VMC FCI, Ec = 5 FCI, Ec = 6 FCI, Ec = 7 FCI, Ec = 8 FCI, Ec = 9
100
Energy variance
22.25
Submission
10−1 10−2
20
22.10
40
60
80
100
Steps 22.05 22.00 20
40
60
80
100
Steps
Figure 7: Ground-state search for N = 6 electrons in the quantum dot of Eq. 61 with ω = 1. Main panel: variational energy 〈H〉 as a function of the optimization step for the ansatz in Eq. 63, compared with the FCI reference with increasing number of basis functions (dashed lines). The orbital basis includes all Fock–Darwin states up to the cutoff energy Ec = 6ω; the Jastrow factor and the backflow transformation use Ec = 4ω. In total, the ansatz has 827 complex variational parameters. Inset: energy variance σ2 = 〈H 2 〉 − 〈H〉2 , which vanishes for an exact eigenstate, as a function of the optimization step. configurations per chain. We evaluate the local energies at the configured precision and accumulate the estimator statistics in double precision. Across the five precision pairs, the relative energy error ranges from 0.686 × 10−3 for FP64/FP64 to 0.807 × 10−3 for FP16/FP32.
4.2
Continuous Space: Electrons in a Quantum Dot
The same variational workflow applies beyond lattice models. We illustrate it with the groundstate search for N interacting spin-polarized electrons confined in a two-dimensional harmonic trap, a standard model of semiconductor quantum dots [64]. In effective atomic units, ħ h = m∗ = e2 /4πϵ = 1, the Hamiltonian reads X N X 1 2 ω2 2 1 H= − ∇i + ri + , 2 2 |ri − r j | i=1 i< j
(61)
where ri ∈ R2 is the position of the i-th electron, ri = |ri |, and ω sets the confinement strength. We consider N = 6 electrons at ω = 1. This system is small enough that full configuration interaction (FCI) gives a reference energy, and its strong correlation still makes it a nontrivial test. The Hamiltonian is assembled from predefined operators: 1 2 3
N = 6 n_dim = 2 omega = 1.0
4 5
geometry = jVMC.geometry.HyperRectangle(N, n_dim, PBC=False, extent=(6., 6.))
38
SciPost Physics Codebases
6 7 8
9 10
Submission
hamiltonian = ( op.TotalKineticOperator(geometry) + op.PotentialOperator(geometry, lambda x: 0.5 * omega ** 2 * jnp.sum(x ** 2) ) + op.CoulombInteraction(geometry) )
We here introduce the geometry object which is mainly needed to define the boundary condition of the problem, and therefore how to compute the distance between particles, and how to initialize the Markov chains. A natural single-particle basis for this problem is given by the eigenstates of the noninteracting Hamiltonian, the Fock–Darwin orbitals v t |m| |m| p 2 ω n! ωr L n ωr 2 e−ωr /2 e imθ , ϕα (r, θ ) = α ≡ (n, m), (62) π (n + |m|)! with radial quantum number n ∈ N, angular momentum m ∈ Z, generalized Laguerre polynomials L n|m| , and single-particle energies εα = ω (2n + |m| + 1). Our ansatz is a variant of the one proposed in Ref. [65]. It combines a single Slater determinant of backflow orbitals with a two-body Jastrow factor and a cusp-enforcing Jastrow term. By writing x := {r1 , r2 , ..., rN }, we have ψ(x) = det ϕ̃kBF ri ; {r j } j̸=i e J(x)+Jcusp (x) . (63) Both the orbitals and the Jastrow factor are expanded in the basis of Eq. 62. The N occupied orbitals are constructed as linear combinations of the basis functions with complex variational parameters Ci, j , X ϕ̃k (r) =
α
Cαk ϕα (r),
k = 1, . . . , N .
(64)
On the other hand, the backflow makes each single particle orbital depend on the positions of all electrons, through the transformation: X X 1 (k) ϕβ (r j ) , (65) ϕ̃kBF ri ; {r j } j̸=i = ϕ̃k (ri ) 1 + ϕα (ri ) Bαβ N − 1 j̸=i α,β (k)
with Bi, j complex variational parameters. As the environment of electron i enters only through a permutation-invariant average over the other electrons, exchanging two electrons still exchanges two rows of the matrix, so that the determinant stays antisymmetric. Similarly, the two-body Jastrow factor is constructed as: 1 XX J(x) = ϕα (ri ) Aαβ ϕβ (r j ) (66) 2 i̸= j α,β where A is a symmetric matrix of variational parameters. Finally, Jcusp enforces Kato’s cusp condition [66], which smooth basis expansions cannot reproduce. In two dimensions this condition fixes the slope of the Jastrow factor at electron coalescence: Jcusp (x) = −
1X b2 , 3 i< j b + |ri − r j |
(67)
where b is a single complex variational parameter. Once the model is defined, we pick as proposer RWM and we pair it with the MCSamplerCont. Then the workflow remains identical to the discrete case. 39
SciPost Physics Codebases
1 2
Submission
E_c_det, E_c_jastrow, E_c_bf = 6, 4, 4 n_samples = 2**11
3 4 5 6 7 8 9 10 11 12 13 14 15 16
net = SlaterJastrowBackflow( n_particles=N, orbitals=HOOrbitals(E_c_det, omega), jastrow=OrbitalJastrow(HOOrbitals(E_c_jastrow, omega)), cusp=ElectronCusp(), backflow=OrbitalBackflow(HOOrbitals(E_c_bf, omega)), ) psi = jVMC.vqs.NQS(net, sample_shape=n_dim * N, batch_size=n_samples, seed=123) proposer = jVMC.propose.RWM(geometry) sampler = jVMC.sampler.MCSamplerCont( psi, proposer, key=123, num_chains=n_samples // 4, num_samples=n_samples, sweep_steps=2 * N, thermalization_sweeps=5 )
17 18 19
print('Number of parameters:', psi.num_parameters) print('Holomorphic:', psi.holomorphic) Number of parameters: 827 Holomorphic: True
Figure 7 shows the variational energy mean and variance during the optimization compared with the FCI reference. The final VMC energy agrees with the FCI value within a relative error of 2 · 10−4 . Note that FCI is variational only within its truncated basis and converges slowly for this system because of the electron-electron cusp. The complete example, with the used architecture and the FCI code, can be found in the folder of examples of jVMC.
4.3
Unitary Dynamics
As a benchmark for real-time evolution with the TDVP, we consider the two-dimensional transverse-field Ising model on an L × L square lattice with periodic boundary conditions, Ĥ = −J
X
σ̂zi σ̂zj − h
N X
σ̂ix ,
(68)
i=1
〈i, j〉
where J > 0, 〈i, j〉 runs over nearest-neighbour pairs and N = L 2 . In the ground state, the model undergoes a quantum phase transition between a ferromagnetic and a paramagnetic phase at hc /J = 3.04438 [68]. We prepare the system in the x-polarized product state |Ψ0 〉 = |→→ · · · →〉, which is the ground state of Ĥ for h → ∞, and suddenly quench the field to the critical value h = hc . Entanglement grows quickly after such a quench, which makes the dynamics hard for tensor-network methods in two dimensions. It therefore serves as a standard test for NQS [26, 67]. We follow the evolution up to hc t = 6 on lattices of size 6 × 6, 8 × 8 and 10 × 10. For 6 × 6 we compare with exact numerical results, while for the larger lattices we compare with the NQS simulations of Ref. [26], based on convolutional networks, and of Ref. [67], based on convolutional transformers. As variational ansatz we use a convolutional residual network (ResNet) with real parameters and a complex output, which encodes the modulus and the phase of the amplitude. It consists of two residual blocks of two convolutional layers each, with nC filters of size 4 × 4 and GELU activations. Circular padding makes every layer equivariant under lattice translations, and 40
(E − E0 )/|E0 | [10−3 ]
SciPost Physics Codebases
Submission
6×6
5
8×8
10 × 10
0
TDVP error r2
−5
10−2 10−4 10−6
magnetization X
1.0 jVMC-2.0, nC = 10 exact
jVMC-2.0, nC = 16 jVMC-2.0, nC = 20 CNN (Chen et al.) CNN (Schmitt et al.)
0.9
jVMC-2.0, nC = 16 CNN (Schmitt et al.)
0.8 0
1
2
3
time hc t
4
5
6
0
1
2
3
time hc t
4
5
6
0
1
2
3
4
5
6
time hc t
Figure 8: Time evolution after a quench to the critical point of the two-dimensional transverse-field Ising model on 6 × 6 (left), 8 × 8 (middle) and 10 × 10 (right) lattices. Top: energy relative to the initial energy E0 , exhibiting statistical fluctuations. Middle: TDVP error r 2 , rising rapidly after hc t ≈ 1. Bottom: magnetization X , compared with the exact reference for 6 × 6 and with the NQS results of Chen et al. [67] and Schmitt et al. [26] for the larger lattices. summing the output Qoverx the lattice makes the amplitude translation invariant. The global spin-flip symmetry i σ̂i , which commutes with Ĥ and leaves |Ψ0 〉 invariant, is imposed by projection with the spin_flip_symmetry projector (Sec. 2.1.3). Since the filters do not depend on L, the number of parameters is set by nC alone: 4 990, 12 592 and 19 580 for nC = 10, 16 and 20. We use nC = 10 for 6 × 6, nC = 16 and 20 for 8 × 8, and nC = 16 for 10 × 10. Expectation values are estimated with NMC Markov-chain Monte Carlo samples from 100 chains with single spin-flip updates and 25 thermalization sweeps, where NMC = 8 × 104 for 6 × 6, and NMC = 3 × 105 for the larger lattices. Because the network has real parameters but a complex output, it is not holomorphic, and we integrate the McLachlan form of the TDVP, Eq. (56). As previously discussed, diagonal regularization biases the dynamics. We therefore solve the linear system with a plain pseudoinverse of the quantum geometric tensor, with relative eigenvalue cutoff 10−8 , no diagonal shift and no signal-to-noise regularization. The equation of motion is integrated with an adaptive stepper whose error is measured in the norm induced by the quantum geometric tensor (Sec. 2.5), starting from J δt = 10−3 with a maximal step of J δt = 0.05. In particular, we use a second-order adaptive Heun scheme with tolerance 10−4 for 6 × 6, and RK45 with absolute tolerance 10−6 for the larger lattices. ThePthree rows of Fig. 8 show the energy, the TDVP error r 2 and the mean magnetization X = N1 i 〈σix 〉, each column corresponding to one system size. The energy is plotted relative to its initial value E0 = −hc N , which is conserved under the exact dynamics, so that the deviations
41
SciPost Physics Codebases
Submission
show the drift and the statistical fluctuations of the simulation. To monitor the quality of the time evolution, we use the TDVP error r 2 introduced in Ref. [26], quantifying the squared distance between the exact infinitesimal time step and its projection onto the variational manifold, normalized by the norm of the exact step, r2 = 1 +
θ̇ † S θ̇ − 2 Re[ θ̇ † (−i F )] , Var(H)
(69)
where θ̇ is the TDVP update, S the quantum geometric tensor and F the force vector, so that r 2 = 0 corresponds to an exactly representable step and r 2 = 1 to no overlap at all. Since all quantities entering the TDVP error have already been computed for the TDVP step itself, r 2 is obtained from the same Monte Carlo samples at negligible extra cost; the TDVP optimizer therefore computes it by default and records it in the per-step metadata. Note however that r 2 measures the error of a single step and carries the statistical noise of the estimators; as such, it does not necessarily accumulate the error along the trajectory, but can be understood as its upper bound. In our quench example, the TDVP error rises rapidly after hc t ≈ 1 and saturates at a similar level for all system sizes, while the magnetization agrees well with the exact reference for 6 × 6 and with the NQS studies of Refs. [26, 67] for 8 × 8 and 10 × 10, with the two network widths giving nearly indistinguishable results for 8 × 8.
5
Conclusion
We have presented jVMC 2.0, a redesigned version of the jVMC library for variational Monte Carlo with neural quantum states. The library is organized around a small number of core modules (variational states, samplers, operators, objective functions, optimizers, steppers and solvers), each defined by a minimal abstract interface, so that new components can be combined freely with the existing ones. Building on JAX’s sharding mechanism, samples, network evaluations, Jacobians and Jacobian products, such as the QGT and the tangent kernel, are distributed across multiple GPUs and nodes, and the linear systems at the core of SR, MinSR and the TDVP can be solved with distributed, memory-efficient linear algebra thanks to JAXMg. The support of simulations with mixed floating point precision enables most efficient exploitation of available GPU capacities. Besides lattice models of spins and fermions, the library now covers particles in continuous space, symmetry projections, autoregressive and transformer architectures, and mixed-precision arithmetic. Our benchmarks show close to linear scaling with the number of GPUs and performance competitive with existing libraries. The examples, ranging from the frustrated J1 –J2 model and a two-dimensional quantum dot to quench dynamics in the two-dimensional transverse-field Ising model, illustrate how these components are used together in realistic applications. The aim of jVMC 2.0 is not to provide every variant of VMC with neural quantum states ready-made. Instead, it offers a solid and performant foundation on which new ideas can be implemented and tested with little effort, and scaled to many devices without additional work. A new network, objective function or optimizer only has to implement the corresponding interface, and it then inherits the distribution across devices, batching and memory management of the rest of the library. The projected time evolution in the examples of the repository is a case in point: it is assembled entirely from existing building blocks, namely the infidelity objective function and the ground-state optimizers. As for the previous version, the library will continue to be maintained and developed: we will keep it up to date with the evolving JAX ecosystem, review contributions from the community, and add new features over time. Planned additions include restoring the support 42
SciPost Physics Codebases
Submission
for positive operator-valued measures (POVMs), which enabled the simulation of open quantum systems in the first version of jVMC; a dedicated optimizer for projected tVMC (ptVMC); an implementation of t-NQS [69]; and variants of SR and MinSR, such as SPRING [63].
Code and Data Availability The jVMC library is open source (MIT license) and available at https://github.com/CoQuS/jvmc. All scripts and data needed to reproduce the results presented here are available at https: //github.com/msolinas28/jvmc-2.0-data.
Acknowledgements This work was supported via the Helmholtz Initiative and Networking Fund, grant no. VHNG-1711, the DFG Research Unit FOR5919 “Machine Learning for Complex Quantum States”, grant no. 550495627, and the DFG CRC 1277. Some of the computations were performed on the ADA HPC cluster at the Max Planck Computing and Data Facility. The authors gratefully acknowledge the scientific support and HPC resources provided by the Erlangen National High Performance Computing Center (NHR@FAU) of the Friedrich-Alexander-Universität ErlangenNürnberg (FAU) under the NHR project v166da. NHR funding is provided by federal and Bavarian state authorities. The authors thank the Gauss Centre for Supercomputing e.V. (GCS) for providing computing time on the Supercomputer JUPITER at the Jülich Supercomputing Centre. JUPITER is supported by the EuroHPC JU and GCS through funding by the European Commission, the German Federal Ministry of Research, Technology and Space, and the Ministry of Culture and Science of the State of North Rhine-Westphalia.
A
Gradient of the Objective Function
Here we provide the derivation for Eq. 32. We start from the general loss function
L(θ ) =
X
pi (θ ) ℓi (θ ) ∈ R,
i
|ψθ (si )|2 pi (θ ) = P , 2 j |ψθ (s j )|
(A.1)
where the sum runs over all configurations si and θ are real parameters (in jVMC the parameters are always treated as real). Here ℓi (θ ) = ℓθ (si ) is a general, in principle complex-valued, differentiable function of θ whose expectation value over p is real for all θ . We further define the logarithmic derivatives Γi,k = ∂θk log ψθ (si ), (A.2) which are complex in general. Using |ψθ (si )|2 = exp (2 Re[log ψθ (si )]) and the fact that, for realP θ , ∂k Re[ · ] = Re[∂k · ], we 2 have ∂k log |ψθ (si )| = 2 Re(Γi,k ). The normalization then gives ∂k log j |ψθ (s j )|2 = 2 E p [Re(Γk )], so that ∂k pi = 2pi Re(Γi,k ) − E p [Re(Γk )] . (A.3) The derivative of the loss therefore reads ∂k L = 2 E p Re(Γk ) − E p [Re(Γk )] ℓ(θ ) + E p [∂k ℓ(θ )] .
43
(A.4)
SciPost Physics Codebases
Submission
Since E p [ℓ(θ )] is a constant with respect to the sampling and E p Re(Γk ) − E p [Re(Γk )] = 0, we can subtract E p [ℓ(θ )] from ℓ(θ ) in the first term, which turns it into a covariance: ∂k L = 2 Cov p (Re(Γk ), ℓ(θ )) + E p [∂k ℓ(θ )] .
(A.5)
Because Re(Γk ) is real, the right-hand side splits term by term into a real and an imaginary part. The imaginary part is 2 Cov p (Re(Γk ), Im(ℓ)) + E p [∂k Im(ℓ)] = ∂k Im L,
(A.6)
which vanishes identically because L(θ ) is a function of with real domain and image. Note that its two contributions cancel each other but are not individually zero. We are thus left with ∂k L = 2 Cov p (Re(Γk ), Re(ℓ)) + E p [∂k Re(ℓ)] . To connect to the standard VMC formulation, we use Re Cov p Γk∗ , ℓ = Cov p (Re(Γk ), Re(ℓ)) + Cov p (Im(Γk ), Im(ℓ)) = = Cov p (Re(Γk ), Re(ℓ)) + E p [Im(Γk ) Im(ℓ)] ,
(A.7)
(A.8) (A.9)
where in the second step we used ImE p [ℓ] = E p [Im(ℓ)] = 0. The gradient can then be written as ∂k L = 2 Re (Fk ) , (A.10) with the force vector 1 Fk = Cov p Γk∗ , ℓ + R k , 2
R k = E p [∂k Re(ℓ)] − 2 E p [Im(Γk ) Im(ℓ)] ∈ R.
(A.11)
As a consistency check, consider the case where ℓ is the local estimator of a Hermitian operator Ô, i.e. ℓ(s) = (Ôψθ )(s)/ψθ (s). Then ∂k ℓ(s) =
(Ô ∂k ψθ )(s) − ℓ(s) Γk (s). ψθ (s)
We can use the Hermiticity of Ô to rewrite the first term as Ô ∂k ψθ 〈ψθ |Ô|∂k ψθ 〉 〈Ôψθ |∂k ψθ 〉 Ep = = ψθ 〈ψθ |ψθ 〉 〈ψθ |ψθ 〉 ∗ X (Ôψθ )(s) ∂k ψθ (s) = p(s) = E p [ℓ∗ Γk ] , ψ (s) ψ (s) θ θ s
(A.12)
(A.13) (A.14)
so that E p [∂k ℓ] = E p [(ℓ∗ − ℓ) Γk ] = −2i E p [Im(ℓ) Γk ] .
(A.15)
Taking the real part yields E p [∂k Re(ℓ)] = 2 E p [Im(Γk ) Im(ℓ)], hence R k = 0, and we recover the standard VMC force Fk = Cov p Γk∗ , ℓ . On the other hand, if the operator depends explicitly on the parameters, Ô = Ô(θ ) Hermitian for P all θ , the derivative of the local loss acquires the additional term ′ (∂θk Ô)loc (s) = contributions cancel against s′ ∂θk Oss′ (θ ) ψθ (s )/ψθ (s). The remaining the second term of R k as before, so that R k = Re E p (∂θk Ô)loc = E p (∂θk Ô)loc , where the last equality holds because ∂θk Ô is Hermitian.
44
SciPost Physics Codebases
Submission
Step 1 Γ̃c
P (d) 0 1 4 5
0 1 2 3 4 5 6 7
S̃ Σ
Σ
0 1 4 5
0 1 2 3 4 5 6 7
Step 2 2 3 6 7
0 1 2 3 4 5 6 7
Σ
2 3 6 7
Σ
Device 0
0 1 2 3 4 5 6 7
Device 1
Figure 9: Construction of S̃ for Nd = 2 devices, Ns = 6 samples and Ñp = 8 padded parameters, so that each device holds a slab of 4 rows of S̃, split into blocks of B = 2 rows. In each step, every device multiplies the selected columns of its local rows of Γ̃ c (outlined) with all of its local rows, obtaining the local product P (d) , whose rows are labeled by their index in S̃. The local products are then summed over devices (Σ) and scattered, so that the upper half of every P (d) contributes to the rows of device 0 and the lower half to the rows of device 1, filling one block of each slab.
B
Memory-Efficient Distributed Jacobian Products
In this section we outline how the QGT is built so that it remains distributed across the Nd devices throughout the whole construction. The main building block is the Jacobian of the log-amplitude, Γi,k =
∂ log ψθ (si ), ∂ θk
with shape (Ns , Np ).
(B.1)
We can then define the centered Jacobian 1 c Γi,k = p (Γi,k − E [Γk ]), Ns
(B.2)
so that the QGT reads S = (Γ c )† Γ c ,
with shape (Np , Np ).
(B.3)
The Jacobian returned by NQS.gradients() is distributed over the sample axis: device d holds a shard Γ c,(d) of Ns /Nd rows, so that Eq. (B.3) is a sum of local products, X S= (Γ c,(d) )† Γ c,(d) (B.4) d
45
SciPost Physics Codebases
Submission
We therefore need a way of obtaining the QGT with two constraints in mind: (i) S has to be distributed over its first axis, with each device holding a contiguous slab of Np /Nd rows, and (ii) no device has to ever hold an array larger than (Np /Nd ) × Np , i.e. the size of its own slab. The naive approach, in which each device computes its full local product and the results are then summed and scattered, violates (ii), since every local product has shape (Np , Np ). To satisfy both requirements, we first pad the Jacobian with zero columns so that the number of parameters is divisible by Nd2 . We call the padded matrix Γ̃ c , with shape (Ns , Ñp ). We then split the slab of each device into Nd blocks of B = Ñp /Nd2 rows, and denote by Rd, j the rows of the j-th block of device d: Ñp Rd, j = d + jB + b : b = 0, . . . , B − 1 . (B.5) Nd The algorithm proceeds in Nd sequential steps, where the j-th steps reads: 1. Select the columns C j = R0, j ∪ R1, j ∪ · · · ∪ RNd −1, j of Γ̃ c , i.e. the j-th block of every slab, ordered by device. These are Ñp /Nd columns in total. 2. Each device d multiplies its selected columns with its whole shard, (d)
Pj
† c,(d) = Γ̃:,C Γ̃ c,(d) , j
with shape (Ñp /Nd , Ñp ),
(B.6)
which is the contribution of its local samples to the rows C j of S̃. (d)
3. The matrices P j
are summed over devices and scattered along their first axis, so that P (d ′ ) device d receives the d-th group of B rows of d ′ P j . Because of the ordering chosen in point (1), these are exactly the rows Rd, j of S̃, i.e. the j-th block of the slab of device d, which is written in place. No further communication between devices is needed.
After Nd steps every device holds its full slab of S̃, and the largest array ever held by a device (d) is P j , which has the same shape as the slab itself. Finally, since the product in point (2) is a sum over samples, it can equivalently be accumulated over batches of samples to further reduce the memory footprint, without changing the rest of the algorithm, which is exactly what happens under the hood when the Jacobian is given as LazySampledObs. We give an example of this algorithm in Fig. 9. The tangent kernel used in MinSR, T = Γ̃ c (Γ̃ c )† with shape (Ns , Ns ), is constructed with the same approach and one additional step. Since the product now sums over the parameters rather than over the samples, the Jacobian is first redistributed with an all-to-all communication, so that each device holds all Ns samples but only Ñp /Nd parameters, with the parameters padded to a multiple of Nd . The local product on each device is then a partial sum over its own parameters, and the algorithm described above applies with the roles of samples and parameters exchanged.
References [1] A. Weiße and H. Fehske, Exact diagonalization techniques, In Computational many-particle physics, pp. 529–544. Springer (2008). [2] A. Szabo and N. S. Ostlund, Modern quantum chemistry: introduction to advanced electronic structure theory, Courier Corporation (2012). 46
SciPost Physics Codebases
Submission
[3] W. M. Foulkes, L. Mitas, R. Needs and G. Rajagopal, Quantum monte carlo simulations of solids, Reviews of Modern Physics 73(1), 33 (2001). [4] F. Becca and S. Sorella, Quantum Monte Carlo approaches for correlated systems, Cambridge University Press (2017). [5] F. Assaad and H. Evertz, World-line and determinantal quantum monte carlo methods for spins, phonons and electrons, In Computational many-particle physics, pp. 277–356. Springer (2008). [6] M. Troyer and U.-J. Wiese, Computational complexity and fundamental limitations to fermionic quantum monte carlo simulations, Physical review letters 94(17), 170201 (2005). [7] S. R. White, Density matrix formulation for quantum renormalization groups, Physical Review Letters 69, 2863 (1992), doi:10.1103/PhysRevLett.69.2863. [8] U. Schollwöck, The density-matrix renormalization group in the age of matrix product states, Annals of Physics 326, 96 (2011), doi:10.1016/j.aop.2010.09.012. [9] R. Orús, A practical introduction to tensor networks: Matrix product states and projected entangled pair states, Annals of Physics 349, 117 (2014), doi:10.1016/j.aop.2014.06.013. [10] J. Eisert, M. Cramer and M. B. Plenio, Colloquium: Area laws for the entanglement entropy, Reviews of Modern Physics 82, 277 (2010), doi:10.1103/RevModPhys.82.277. [11] W. Metzner and D. Vollhardt, Correlated lattice fermions in d = ∞ dimensions, Physical Review Letters 62, 324 (1989), doi:10.1103/PhysRevLett.62.324. [12] A. Georges, G. Kotliar, W. Krauth and M. J. Rozenberg, Dynamical mean-field theory of strongly correlated fermion systems and the limit of infinite dimensions, Reviews of Modern Physics 68, 13 (1996), doi:10.1103/RevModPhys.68.13. [13] G. Kotliar, S. Y. Savrasov, K. Haule, V. S. Oudovenko, O. Parcollet and C. A. Marianetti, Electronic structure calculations with dynamical mean-field theory, Reviews of Modern Physics 78, 865 (2006), doi:10.1103/RevModPhys.78.865. [14] T. Maier, M. Jarrell, T. Pruschke and M. H. Hettler, Quantum cluster theories, Reviews of Modern Physics 77, 1027 (2005), doi:10.1103/RevModPhys.77.1027. [15] G. Carleo and M. Troyer, Solving the quantum many-body problem with artificial neural networks, Science 355(6325), 602 (2017). [16] M. Medvidović and J. R. Moreno, Neural-network quantum states for many-body physics, The European Physical Journal Plus 139(7), 1 (2024). [17] J. B. Rigo, B. J. Wurst, R. Nutakki, M. Schmitt and D. Kennes, Neural quantum states in condensed matter: advances, best practices, and prospects, arXiv preprint arXiv:2608.21291 (2026). [18] H. Lange, A. Van de Walle, A. Abedinnia and A. Bohrdt, From architectures to applications: A review of neural quantum states, Quantum Science and Technology 9(4), 040501 (2024). [19] K. Hornik, Approximation capabilities of multilayer feedforward networks, Neural networks 4(2), 251 (1991).
47
SciPost Physics Codebases
Submission
[20] D.-L. Deng, X. Li and S. Das Sarma, Quantum entanglement in neural network states, Physical Review X 7, 021021 (2017), doi:10.1103/PhysRevX.7.021021. [21] Y. Levine, O. Sharir, N. Cohen and A. Shashua, Quantum entanglement in deep learning architectures, Physical review letters 122(6), 065301 (2019). [22] O. Sharir, A. Shashua and G. Carleo, Neural tensor contractions and the expressive power of deep neural quantum states, Physical Review B 106(20), 205136 (2022). [23] S. Sorella, Green function monte carlo with stochastic reconfiguration, Physical review letters 80(20), 4558 (1998). [24] M. Medvidović, A. Orfi, J. Carrasquilla and D. Sels, Adiabatic transport of neural network quantum states, PRX Intelligence 1(1), 013020 (2026). [25] D. Pfau, S. Axelrod, H. Sutterud, I. Von Glehn and J. S. Spencer, Accurate computation of quantum excited states with neural networks, Science 385(6711), eadn0137 (2024). [26] M. Schmitt and M. Heyl, Quantum many-body dynamics in two dimensions with artificial neural networks, Physical Review Letters 125(10), 100503 (2020). [27] K. Choo, T. Neupert and G. Carleo, Two-dimensional frustrated J1 − J2 model studied with neural network quantum states, Physical Review B 100, 125124 (2019), doi:10.1103/PhysRevB.100.125124. [28] O. Sharir, Y. Levine, N. Wies, G. Carleo and A. Shashua, Deep autoregressive models for the efficient variational simulation of many-body quantum systems, Physical Review Letters 124, 020503 (2020), doi:10.1103/PhysRevLett.124.020503. [29] M. Hibat-Allah, M. Ganahl, L. E. Hayward, R. G. Melko and J. Carrasquilla, Recurrent neural network wave functions, Physical Review Research 2, 023358 (2020), doi:10.1103/PhysRevResearch.2.023358. [30] L. L. Viteritti, R. Rende and F. Becca, Transformer variational wave functions for frustrated quantum spin systems, Physical Review Letters 130, 236401 (2023), doi:10.1103/PhysRevLett.130.236401. [31] A. Chen and M. Heyl, Empowering deep neural quantum states through efficient optimization, Nature Physics 20(9), 1476 (2024). [32] R. Wiersema, Numerical simulation of d-wave’s quantum advantage experiment with time-dependent variational monte carlo, arXiv preprint arXiv:2609.01719 (2026). [33] A. Chen, Z.-Q. Wan, A. Sengupta, A. Georges and C. Roth, Neural network–augmented pfaffian wave-functions for scalable simulations of interacting fermions, Proceedings of the National Academy of Sciences 123(35), e2535288123 (2026). [34] H. Lange, A. Chen, A. Georges, F. Grusdt, A. Bohrdt and C. Roth, Simulating superconductivity in mixed-dimensional t ∥ - j∥ - j⊥ bilayers with neural quantum states, arXiv preprint arXiv:2602.10091 (2026). [35] D. Pfau, J. S. Spencer, A. G. D. G. Matthews and W. M. C. Foulkes, Ab initio solution of the many-electron Schrödinger equation with deep neural networks, Physical Review Research 2, 033429 (2020), doi:10.1103/PhysRevResearch.2.033429.
48
SciPost Physics Codebases
Submission
[36] J. Hermann, Z. Schätzle and F. Noé, Deep-neural-network solution of the electronic Schrödinger equation, Nature Chemistry 12, 891 (2020), doi:10.1038/s41557-0200544-y. [37] I. von Glehn, J. S. Spencer and D. Pfau, A self-attention ansatz for ab-initio quantum chemistry, arXiv preprint arXiv:2211.13672 (2022). [38] W. Fu, Z. Li, Y. Qian, R. Li, W. Ren and J. Chen, Towards stable and accurate electron dynamics via neural network based time-dependent variational monte carlo, arXiv preprint arXiv:2606.05850 (2026). [39] R. Rende, L. L. Viteritti, L. Bardone, F. Becca and S. Goldt, A simple linear algebra identity to optimize large-scale neural network quantum states, Communications Physics 7(1), 260 (2024). [40] M. S. Moss, A. Orfi, C. Roth, A. M. Sengupta, A. Georges, D. Sels, A. Dawid and A. Valenti, Double descent: When do neural quantum states generalize?, arXiv preprint arXiv:2508.00068 (2025). [41] A. D. King, A. Nocera, M. M. Rams, J. Dziarmaga, R. Wiersema, W. Bernoudy, J. Raymond, N. Kaushal, N. Heinsdorf, R. Harris et al., Beyond-classical computation in quantum simulation, Science 388(6743), 199 (2025). [42] J. A. Duque, S. G. Heredia, V. Hernandes, E. Greplová, T. Spriggs, A. Courville and A. Dawid, One more time: Revisiting neural quantum states from a reinforcement learning perspective, arXiv preprint arXiv:2607.02292 (2026). [43] W. Krinitsin, J. B. Rigo, M. Abedi and M. Schmitt, Geometric inflation of deviations challenges neural quantum states in dynamics of quantum ising models, arXiv preprint arXiv:2609.07645 (2026). [44] M. Schmitt and M. Reh, jvmc: Versatile and performant variational monte carlo leveraging automated differentiation and gpu acceleration, arXiv preprint arXiv:2108.03409 (2021). [45] J. Bradbury, R. Frostig, P. Hawkins, M. J. Johnson, Y. Katariya, C. Leary, D. Maclaurin, G. Necula, A. Paszke, J. VanderPlas, S. Wanderman-Milne and Q. Zhang, JAX: composable transformations of Python+NumPy programs (2018). [46] J. Heek, A. Levskaya, A. Oliver, M. Ritter, B. Rondepierre, A. Steiner and M. van Zee, Flax: A neural network library and ecosystem for JAX (2024). [47] M. Solinas, A. Valenti, N. Bou-Rabee and R. Wiersema, Neural quantum states in mixed precision, In Forty-third International Conference on Machine Learning (2026). [48] R. Wiersema, Jaxmg: A multi-gpu linear solver in jax, arXiv preprint arXiv:2601.14466 (2026). [49] B. Peng, E. Alcaide, Q. Anthony, A. Albalak, S. Arcadinho, S. Biderman, H. Cao, X. Cheng, M. Chung, M. Grella et al., Rwkv: Reinventing rnns for the transformer era, arXiv preprint arXiv:2305.13048 (2023). [50] F. Vicentini, D. Hofmann, A. Szabó, D. Wu, C. Roth, C. Giuliani, G. Pescia, J. Nys, V. VargasCalderón, N. Astrakhantsev et al., Netket 3: Machine learning toolbox for many-body quantum systems, arXiv preprint arXiv:2112.10526 (2021).
49
SciPost Physics Codebases
Submission
[51] W. Krinitsin and M. Schmitt, Time-dependent variational Monte Carlo without bias (2026), 2605.03930. [52] A. Sinibaldi, C. Giuliani, G. Carleo and F. Vicentini, Unbiasing time-dependent Variational Monte Carlo by projected quantum evolution, Quantum 7, 1131 (2023), doi:10.22331/q2023-10-10-1131. [53] N. Metropolis, A. W. Rosenbluth, M. N. Rosenbluth, A. H. Teller and E. Teller, Equation of state calculations by fast computing machines, The journal of chemical physics 21(6), 1087 (1953). [54] P. J. Rossky, J. D. Doll and H. L. Friedman, Brownian dynamics as smart monte carlo simulation, The Journal of Chemical Physics 69(10), 4628 (1978). [55] J. B. Rigo and M. Schmitt, Operator lanczos approach enabling neural quantum states as real-frequency impurity solvers, arXiv preprint arXiv:2512.08624 (2025). [56] D. Vats and C. Knudson, Revisiting the gelman–rubin diagnostic, Statistical Science 36(4), 518 (2021). [57] L. Gravina, V. Savona and F. Vicentini, Neural projected quantum dynamics: a systematic study, Quantum 9, 1803 (2025). [58] D. P. Kingma and J. Ba, Adam: A method for stochastic optimization, arXiv preprint arXiv:1412.6980 (2014). [59] S.-I. Amari and S. C. Douglas, Why natural gradient?, In Proceedings of the 1998 IEEE International Conference on Acoustics, Speech and Signal Processing, ICASSP’98 (Cat. No. 98CH36181), vol. 2, pp. 1213–1216. IEEE (1998). [60] L. Hackl, T. Guaita, T. Shi, J. Haegeman, E. Demler and J. I. Cirac, Geometry of variational methods: dynamics of closed quantum systems, SciPost Physics 9(4), 048 (2020). [61] M. Medvidović and D. Sels, Variational quantum dynamics of two-dimensional rotor models, PRX Quantum 4(4), 040302 (2023). [62] L. L. Viteritti, R. Rende, A. Parola, S. Goldt and F. Becca, Transformer wave function for two dimensional frustrated magnets: Emergence of a spin-liquid phase in the shastry–sutherland model, Phys. Rev. B 111, 134411 (2025), doi:10.1103/PhysRevB.111.134411. [63] G. Goldshlager, N. Abrahamsen and L. Lin, A kaczmarz-inspired approach to accelerate the optimization of neural network wavefunctions, Journal of Computational Physics 516, 113351 (2024). [64] E. Anisimovas and A. Matulis, Energy spectra of few-electron quantum dots, Journal of Physics: Condensed Matter 10(3), 601 (1998). [65] J. Nys, G. Pescia, A. Sinibaldi and G. Carleo, Ab-initio variational wave functions for the time-dependent many-electron schrödinger equation, Nature communications 15(1), 9404 (2024). [66] R. T. Pack and W. B. Brown, Cusp conditions for molecular wavefunctions, The Journal of Chemical Physics 45(2), 556 (1966). [67] A. Chen, V. D. Naik and M. Heyl, Convolutional transformer wave functions, doi:10.48550/arXiv.2503.10462 (2025), 2503.10462. 50
SciPost Physics Codebases
Submission
[68] H. W. J. Blöte and Y. Deng, Cluster Monte Carlo simulation of the transverse Ising model, Physical Review E 66(6), 066110 (2002), doi:10.1103/PhysRevE.66.066110. [69] A. Van de Walle, M. Schmitt and A. Bohrdt, Many-body dynamics with explicitly timedependent neural quantum states, Machine Learning: Science and Technology 6(4), 045011 (2025), doi:10.1088/2632-2153/ae0f39.
51
Related documents
- Verifiable Sampling for Delegated Generative Quantum Machine Learning#1297563
- Particle Monte Carlo Tree Search#1393808
- PyGFMC: GPU-accelerated Green's Function Monte Carlo#1817333
- Perfect Born Sampling of Symmetric Thermal Tensor Network for Quantum Lattice Models#1130400
- Hamiltonian Monte Carlo for (Physics) Dummies#1536061
Retrieved via Conceptio: every document is proof-bundled with source, license, and retrieval metadata.
Read the Docs → · View CLI source on GitHub · Conceptio Open Knowledge Archive