Using the MPI cuTensorNet Calculator
Goal
Write and run a distributed quantum chemistry calculation using Qrunch’s MpiCutensornetTensorNetworkContractionCalculator to parallelize tensor network contractions across multiple nodes.
Prerequisites
A Qrunch MPI Docker/Apptainer/Enroot image (see Building an Image)
Access to an HPC cluster or multi-node environment with MPI support
Basic understanding of MPI concepts (rank, communicator, root process)
Python script that uses the
MpiCutensornetTensorNetworkContractionCalculatorInput files (molecule configuration, license file) accessible to all nodes
Overview
The MPI cuTensorNet calculator uses a root-worker architecture to distribute tensor network contractions across multiple nodes:
Root node (rank 0): Executes your main Qrunch calculation logic (problem setup, VQE iterations, result collection)
Worker nodes (ranks 1, 2, …): Wait in
serve_forever()to receive and execute contraction tasks sent by the root
All nodes create the same MpiCutensornetTensorNetworkContractionCalculator instance. When the root calls contract() on a tensor network (inside estimator or sampler operations), the calculator automatically:
Slices the contraction into independent tasks
Distributes tasks across all MPI ranks via MPI communication
Gathers results back to the root node
This architecture lets you write standard Qrunch code on the root while transparently parallelizing the computationally expensive tensor contractions.
Complete Example Script
Below is a complete example that runs a VQE calculation with distributed tensor network contractions. The script structure follows the root-worker pattern: the root rank (0) executes the chemistry calculation, while all other ranks serve as workers.
We’ll break down each section after the full listing.
1"""Script for running a simple mpi calculation with qrunch."""
2
3from __future__ import annotations
4
5from pathlib import Path
6from typing import TYPE_CHECKING
7
8# snippet-start: import-mpi
9from mpi4py import MPI # this line initializes MPI
10
11# snippet-end: import-mpi
12import qrunch as qc
13from qrunch.common.kfy_logging import LOGGER_ESSENTIAL, logger
14from qrunch.third_party.cuquantum_import.tensornet import OptimizerOptions, SlicerOptions
15from qrunch.tools.mpi import mpi_main
16
17if TYPE_CHECKING:
18 from qrunch.type_defs import MpiCutensornetTensorNetworkContractionCalculator
19
20
21def run_calculation(
22 rank: int,
23 contraction_calculator: MpiCutensornetTensorNetworkContractionCalculator,
24) -> None:
25 """Run main calculation on the root rank."""
26 logger.info(f"Building problem on rank {rank}.")
27
28 max_iterations = 10
29 number_of_orbitals = 10
30 number_of_alpha_electrons = number_of_orbitals // 2
31
32 number_of_shots = 10_000
33
34 # snippet-start: file-paths
35 molecule_path = Path("/workspace/input/molecule.xyz")
36 output_dir = Path("/workspace/data")
37 output_dir.mkdir(parents=True, exist_ok=True)
38 # snippet-end: file-paths
39
40 # snippet-start: problem-setup
41 molecular_configuration = qc.build_molecular_configuration(
42 molecule=molecule_path,
43 basis_set="sto-3g",
44 charge=0,
45 spin_difference=0,
46 )
47
48 problem_builder = (
49 qc
50 .problem_builder_creator()
51 .ground_state()
52 .standard()
53 .choose_repulsion_integral_builder()
54 .resolution_of_the_identity()
55 .add_problem_modifier()
56 .active_space(
57 number_of_active_spatial_orbitals=number_of_orbitals,
58 number_of_active_alpha_electrons=number_of_alpha_electrons,
59 )
60 .add_problem_modifier()
61 .to_dense_integrals()
62 .choose_data_persister_manager()
63 .file_persister(directory=output_dir)
64 .create()
65 )
66
67 logger.log(LOGGER_ESSENTIAL, f"Building problem on rank {rank}.")
68 problem = problem_builder.build_restricted(molecular_configuration)
69 logger.log(LOGGER_ESSENTIAL, f"Finished building problem on rank {rank}.")
70 # snippet-end: problem-setup
71
72 logger.info(f"Setting up calculator on rank {rank}.")
73
74 # snippet-start: calculator-setup
75 estimator = (
76 qc
77 .estimator_creator()
78 .tensor_network()
79 .choose_estimator_algorithm()
80 .custom_contraction_calculator(contraction_calculator)
81 .create()
82 )
83 sampler = (
84 qc
85 .sampler_creator()
86 .tensor_network()
87 .choose_sampler_algorithm()
88 .custom_contraction_calculator(contraction_calculator)
89 .create()
90 )
91
92 options = qc.options.IterativeVqeOptions(max_iterations=max_iterations)
93 calculator = (
94 qc
95 .calculator_creator()
96 .vqe()
97 .iterative()
98 .beast()
99 .with_options(options)
100 .choose_data_persister_manager()
101 .file_persister(directory=output_dir)
102 .with_estimator(estimator)
103 .with_total_estimator_shots(None)
104 .with_gate_selector_sampler(sampler)
105 .with_gate_selector_shots(number_of_shots)
106 .create()
107 )
108 # snippet-end: calculator-setup
109
110 # snippet-start: calculation
111 logger.log(LOGGER_ESSENTIAL, f"Starting calculation on rank {rank}.")
112 total_estimated_energy = calculator.calculate(problem)
113
114 logger.log(LOGGER_ESSENTIAL, f"Found energy {total_estimated_energy} on rank {rank}.")
115 # snippet-end: calculation
116
117
118# snippet-start: mpi-error-handling
119@mpi_main
120def main() -> None:
121 """Prepare shared calculation similarly on all non-root nodes and run on root node."""
122 # snippet-end: mpi-error-handling
123
124 # snippet-start: logger-license-setup
125 qc.setup_logger(qc.LOGGER_ESSENTIAL)
126 qc.register_license_file("/workspace/input/license.txt")
127 # snippet-end: logger-license-setup
128
129 # snippet-start: mpi-setup
130 root = 0
131 comm = MPI.COMM_WORLD
132
133 rank = comm.Get_rank()
134 size = comm.Get_size()
135 # snippet-end: mpi-setup
136
137 logger.log(LOGGER_ESSENTIAL, f"Log from rank {rank} of {size} with root {root}.")
138
139 # snippet-start: contraction-calculator
140 contraction_calculator = (
141 qc
142 .mpi_creator()
143 .contraction_calculator()
144 .with_root(root)
145 .with_comm(comm)
146 .choose_contraction_path_finder()
147 .none() # None allows for MPI path finding with cuTensorNet
148 .with_options(
149 qc.options.MpiCutensornetTensorNetworkContractionCalculatorOptions(
150 optimizer_options=OptimizerOptions(
151 samples=8,
152 threads=10, # set to the core count of a task
153 slicing=SlicerOptions(
154 min_slices=size,
155 slice_factor=2,
156 ),
157 ),
158 storage_data_type="float32",
159 compute_data_type="float32",
160 ),
161 )
162 .create()
163 )
164 # snippet-end: contraction-calculator
165
166 # snippet-start: root-worker-split
167 if rank == root:
168 try:
169 logger.info(f"`run_calculation` on rank {rank} (root).")
170 run_calculation(
171 rank=rank,
172 contraction_calculator=contraction_calculator,
173 )
174 finally:
175 contraction_calculator.shutdown()
176 else:
177 logger.info(f"`serve_forever` on rank {rank}.")
178 contraction_calculator.serve_forever()
179 # snippet-end: root-worker-split
180
181
182if __name__ == "__main__":
183 main()
Running the Script
Execute your MPI script with mpirun and the Qrunch MPI container:
mpirun -n 4 apptainer exec qrunch-mpi.sif python /path/to/your_script.py
The -n 4 flag launches 4 MPI processes: rank 0 (root) runs the calculation, ranks 1-3 (workers) execute distributed contractions.
For detailed instructions on running with Slurm, mounting data, GPU access, and HPC cluster configuration, see Running MPI Calculations.
Code Walkthrough
MPI Initialization
1from mpi4py import MPI # this line initializes MPI
2
Critical: This import must occur at module level before any MPI operations. Importing mpi4py.MPI automatically initializes the MPI environment.
The Qrunch MPI image includes OpenMPI. If you encounter MPI compatibility issues between the container and your host system, contact the Qrunch support team.
The run_calculation Function (Root Rank Only)
This function contains the main calculation logic and only runs on rank 0. Worker ranks never enter this function.
File Paths
1 molecule_path = Path("/workspace/input/molecule.xyz")
2 output_dir = Path("/workspace/data")
3 output_dir.mkdir(parents=True, exist_ok=True)
This example assumes /workspace is mounted into the container with input files in /workspace/input/. Adjust these paths to match your cluster’s storage setup.
Problem Setup (Standard Qrunch Code)
1 molecular_configuration = qc.build_molecular_configuration(
2 molecule=molecule_path,
3 basis_set="sto-3g",
4 charge=0,
5 spin_difference=0,
6 )
7
8 problem_builder = (
9 qc
10 .problem_builder_creator()
11 .ground_state()
12 .standard()
13 .choose_repulsion_integral_builder()
14 .resolution_of_the_identity()
15 .add_problem_modifier()
16 .active_space(
17 number_of_active_spatial_orbitals=number_of_orbitals,
18 number_of_active_alpha_electrons=number_of_alpha_electrons,
19 )
20 .add_problem_modifier()
21 .to_dense_integrals()
22 .choose_data_persister_manager()
23 .file_persister(directory=output_dir)
24 .create()
25 )
26
27 logger.log(LOGGER_ESSENTIAL, f"Building problem on rank {rank}.")
28 problem = problem_builder.build_restricted(molecular_configuration)
29 logger.log(LOGGER_ESSENTIAL, f"Finished building problem on rank {rank}.")
Problem construction uses standard Qrunch builders—no MPI-specific changes needed. Only the root rank builds the problem; worker ranks remain idle in serve_forever() during this phase.
Calculator Setup with MPI Contraction Calculator
1 estimator = (
2 qc
3 .estimator_creator()
4 .tensor_network()
5 .choose_estimator_algorithm()
6 .custom_contraction_calculator(contraction_calculator)
7 .create()
8 )
9 sampler = (
10 qc
11 .sampler_creator()
12 .tensor_network()
13 .choose_sampler_algorithm()
14 .custom_contraction_calculator(contraction_calculator)
15 .create()
16 )
17
18 options = qc.options.IterativeVqeOptions(max_iterations=max_iterations)
19 calculator = (
20 qc
21 .calculator_creator()
22 .vqe()
23 .iterative()
24 .beast()
25 .with_options(options)
26 .choose_data_persister_manager()
27 .file_persister(directory=output_dir)
28 .with_estimator(estimator)
29 .with_total_estimator_shots(None)
30 .with_gate_selector_sampler(sampler)
31 .with_gate_selector_shots(number_of_shots)
32 .create()
33 )
Key point: Pass the MPI contraction calculator to both the estimator and sampler via .custom_contraction_calculator(). This is the only MPI-specific change needed in the calculation setup. The rest follows standard Qrunch patterns.
Running the Calculation
1 logger.log(LOGGER_ESSENTIAL, f"Starting calculation on rank {rank}.")
2 total_estimated_energy = calculator.calculate(problem)
3
4 logger.log(LOGGER_ESSENTIAL, f"Found energy {total_estimated_energy} on rank {rank}.")
Execute the calculation as usual. When the VQE calculator needs expectation values or samples, the MPI estimator/sampler automatically distributes tensor contractions to all worker ranks. The root rank collects results and continues the VQE optimization loop.
The main Function (All Ranks)
This function runs on every MPI rank and orchestrates the root-worker split.
License and Logging Setup
1 qc.setup_logger(qc.LOGGER_ESSENTIAL)
2 qc.register_license_file("/workspace/input/license.txt")
Both the logger and license must be configured on all ranks. Ensure the license file is accessible from all nodes (via shared filesystem or local copies).
Note
If you encounter license registration errors, register only on the root rank and add a barrier:
if rank == root:
qc.register_license_file("/workspace/input/license.txt")
comm.Barrier() # Wait for root to finish before workers proceed
This avoids conflicts on systems where ranks share memory.
MPI Communicator and Rank Information
1 root = 0
2 comm = MPI.COMM_WORLD
3
4 rank = comm.Get_rank()
5 size = comm.Get_size()
comm: The MPI communicator (COMM_WORLDincludes all launched processes)rank: This process’s unique ID (0, 1, 2, …)size: Total number of MPI processesroot = 0: Convention to use rank 0 as the root node
Contraction Calculator Configuration (All Ranks)
1 contraction_calculator = (
2 qc
3 .mpi_creator()
4 .contraction_calculator()
5 .with_root(root)
6 .with_comm(comm)
7 .choose_contraction_path_finder()
8 .none() # None allows for MPI path finding with cuTensorNet
9 .with_options(
10 qc.options.MpiCutensornetTensorNetworkContractionCalculatorOptions(
11 optimizer_options=OptimizerOptions(
12 samples=8,
13 threads=10, # set to the core count of a task
14 slicing=SlicerOptions(
15 min_slices=size,
16 slice_factor=2,
17 ),
18 ),
19 storage_data_type="float32",
20 compute_data_type="float32",
21 ),
22 )
23 .create()
24 )
All ranks create the same calculator instance with identical options. Key configuration:
samplesNumber of contraction path optimization trials (default: 8). Higher values (32-128) find better paths but take longer. Since actual contraction time typically dominates path-finding time, investing more samples often pays off.
threadsCPU threads per MPI process. Set to match your allocation (e.g., if your job requests 10 cores per task, use
threads=10).min_slicesMinimum slices for parallelization. Set to
size(number of MPI ranks) to ensure enough work for all processes.slice_factorFactor by which to increase the total number of slices at each slicing round (default: 2). The slicer iteratively increases slices by this factor until reaching
min_slices.storage_data_type/compute_data_typeUse
"float32"for 2× memory savings with minimal accuracy loss in most chemistry calculations. Use"float64"if you need full precision.
Note
The with_root(), with_comm(), and choose_contraction_path_finder() builder methods are optional. If omitted, they default to None. For most MPI calculations, you should configure with_options() but can omit the others to use sensible defaults.
Minimal example:
contraction_calculator = (
qc
.mpi_creator()
.contraction_calculator()
.with_options(qc.options.MpiCutensornetTensorNetworkContractionCalculatorOptions(...))
.create()
)
Root-Worker Split
1 if rank == root:
2 try:
3 logger.info(f"`run_calculation` on rank {rank} (root).")
4 run_calculation(
5 rank=rank,
6 contraction_calculator=contraction_calculator,
7 )
8 finally:
9 contraction_calculator.shutdown()
10 else:
11 logger.info(f"`serve_forever` on rank {rank}.")
12 contraction_calculator.serve_forever()
Root rank (0): Executes the calculation logic in run_calculation(). The finally block ensures shutdown() is called even if the calculation fails, which signals workers to exit.
Worker ranks (1, 2, …): Call serve_forever() to enter an infinite loop waiting for contraction tasks from the root. They remain blocked here until the root calls shutdown().
Error Handling with mpi_main
Import mpi_main from qrunch.tools.mpi and decorate the entry point:
1@mpi_main
2def main() -> None:
3 """Prepare shared calculation similarly on all non-root nodes and run on root node."""
The mpi_main wrapper calls comm.Abort(1) if any rank raises an exception, terminating all MPI processes so other ranks do not hang in serve_forever(). In every other case, including a propagating KeyboardInterrupt, it calls MPI.Finalize() to clean up MPI resources.
Troubleshooting
MPI version compatibility issues
The Qrunch MPI image uses OpenMPI. If you encounter MPI initialization or communication errors, verify that your host system provides a compatible MPI environment. If you require assistance with MPI compatibility or an alternative MPI implementation, you may contact Qrunch to discuss available support options.
Worker processes hang or don’t exit
Always call contraction_calculator.shutdown() on the root rank in a finally block. Without shutdown, workers remain blocked in serve_forever() even after the calculation completes.
License file not found on worker nodes
The license must be accessible from all MPI ranks. Use a shared filesystem (e.g., /workspace mounted on all nodes) or copy the license to each node’s local storage.
CUDA/GPU errors
Ensure all nodes have compatible NVIDIA GPUs with CUDA 12.x drivers. Test GPU visibility inside the container:
mpirun -n 4 apptainer exec qrunch-mpi.sif nvidia-smi
Import errors or missing dependencies
Verify you’re using the correct Qrunch MPI image with CUDA and MPI support. Standard Qrunch wheels do not include MpiCutensornetTensorNetworkContractionCalculator support.
See Also
Building an Image - Build Docker/Apptainer images with MPI support
Running MPI Calculations - Run MPI jobs with mpirun or Slurm on HPC clusters
MpiCutensornetTensorNetworkContractionCalculator- Calculator API documentationMpiCutensornetTensorNetworkContractionCalculatorOptions- Options API documentation