Projection MPS Circuit DMRG#
The following code example illustrates how to use the state projection MPS API to perform circuit simulation using DMRG optimization, following the method described by [Ayral et al., 2023]. The full code can be found in the NVIDIA/cuQuantum repository (here).
Headers, error handling, and helper functions#
7#include <cstdlib>
8#include <cstdio>
9#include <cassert>
10#include <complex>
11#include <cmath>
12#include <vector>
13#include <limits>
14#include <iostream>
15
16#include <cuda_runtime.h>
17#include <cutensornet.h>
18#include <cublas_v2.h>
19
20#define HANDLE_CUDA_ERROR(x) \
21 { \
22 const auto err = x; \
23 if (err != cudaSuccess) \
24 { \
25 printf("CUDA error %s in line %d\n", cudaGetErrorString(err), __LINE__); \
26 fflush(stdout); \
27 std::abort(); \
28 } \
29 };
30
31#define HANDLE_CUTN_ERROR(x) \
32 { \
33 const auto err = x; \
34 if (err != CUTENSORNET_STATUS_SUCCESS) \
35 { \
36 printf("cuTensorNet error %s in line %d\n", cutensornetGetErrorString(err), __LINE__); \
37 fflush(stdout); \
38 std::abort(); \
39 } \
40 };
41
42#define HANDLE_CUBLAS_ERROR(x) \
43 { \
44 const auto err = x; \
45 if (err != CUBLAS_STATUS_SUCCESS) \
46 { \
47 printf("cuBLAS error (status code %d) in line %d\n", static_cast<int>(err), __LINE__); \
48 fflush(stdout); \
49 std::abort(); \
50 } \
51 };
52
53// Helper function to compute maximum bond extents
54std::vector<int64_t> getMaxBondExtents(const std::vector<int64_t>& stateModeExtents, int64_t maxdim = -1)
55{
56 const int32_t numQubits = stateModeExtents.size();
57 std::vector<int64_t> cumprodLeft(numQubits), cumprodRight(numQubits);
58
59 // Compute cumulative products from left and right
60 cumprodLeft[0] = stateModeExtents[0];
61 for (int32_t i = 1; i < numQubits; ++i)
62 {
63 cumprodLeft[i] = cumprodLeft[i - 1] * stateModeExtents[i];
64 }
65
66 cumprodRight[numQubits - 1] = stateModeExtents[numQubits - 1];
67 for (int32_t i = numQubits - 2; i >= 0; --i)
68 {
69 cumprodRight[i] = cumprodRight[i + 1] * stateModeExtents[i];
70 }
71
72 std::vector<int64_t> maxBondExtents(numQubits - 1);
73 for (int32_t i = 0; i < numQubits - 1; ++i)
74 {
75 int64_t minVal = std::min(cumprodLeft[i], cumprodRight[i + 1]);
76 maxBondExtents[i] = (maxdim > 0) ? std::min(minVal, maxdim) : minVal;
77 }
78
79 return maxBondExtents;
80}
81
82int main()
83{
84 static_assert(sizeof(size_t) == sizeof(int64_t), "Please build this sample on a 64-bit architecture!");
85
86 constexpr std::size_t fp64size = sizeof(double);
Define the tensor network state and quantum circuit configuration#
Let’s define a tensor network state corresponding to a 16-qubit QFT quantum circuit.
90 // Quantum state configuration
91 const int32_t numQubits = 16;
92 const std::vector<int64_t> qubitDims(numQubits, 2);
93 std::cout << "DMRG quantum circuit with " << numQubits << " qubits\n";
Initialize the cuTensorNet library handle#
97 // Initialize the cuTensorNet library
98 HANDLE_CUDA_ERROR(cudaSetDevice(0));
99 cutensornetHandle_t cutnHandle;
100 HANDLE_CUTN_ERROR(cutensornetCreate(&cutnHandle));
101 std::cout << "Initialized cuTensorNet library on GPU 0\n";
102
103 cublasHandle_t cublasHandle;
104 HANDLE_CUBLAS_ERROR(cublasCreate(&cublasHandle));
105
Define quantum gates on GPU#
108 // Define necessary quantum gate tensors in Host memory
109 const double invsq2 = 1.0 / std::sqrt(2.0);
110 const double pi = 3.14159265358979323846;
111 using GateData = std::vector<std::complex<double>>;
112
113 // CR(k) gate generator
114 auto cRGate = [&pi](int32_t k)
115 {
116 const double phi = pi / std::pow(2.0, k);
117 const GateData cr{{1.0, 0.0}, {0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0},
118 {0.0, 0.0}, {1.0, 0.0}, {0.0, 0.0}, {0.0, 0.0},
119 {0.0, 0.0}, {0.0, 0.0}, {1.0, 0.0}, {0.0, 0.0},
120 {0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0}, {std::cos(phi), std::sin(phi)}};
121 return cr;
122 };
123
124 // Hadamard gate
125 const GateData h_gateH{{invsq2, 0.0}, {invsq2, 0.0}, {invsq2, 0.0}, {-invsq2, 0.0}};
126
127 // CR(k) gates (controlled rotations)
128 std::vector<GateData> h_gateCR(numQubits);
129 for (int32_t k = 0; k < numQubits; ++k)
130 {
131 h_gateCR[k] = cRGate(k + 1);
132 }
133
134 // Copy quantum gates into Device memory
135 void* d_gateH{nullptr};
136 std::vector<void*> d_gateCR(numQubits, nullptr);
137 HANDLE_CUDA_ERROR(cudaMalloc(&d_gateH, 4 * (2 * fp64size)));
138 for (int32_t k = 0; k < numQubits; ++k)
139 {
140 HANDLE_CUDA_ERROR(cudaMalloc(&(d_gateCR[k]), 16 * (2 * fp64size)));
141 }
142
143 HANDLE_CUDA_ERROR(cudaMemcpy(d_gateH, h_gateH.data(), 4 * (2 * fp64size), cudaMemcpyHostToDevice));
144 for (int32_t k = 0; k < numQubits; ++k)
145 {
146 HANDLE_CUDA_ERROR(cudaMemcpy(d_gateCR[k], h_gateCR[k].data(), 16 * (2 * fp64size), cudaMemcpyHostToDevice));
147 }
148 std::cout << "Copied quantum gates into GPU memory\n";
Create initial quantum state and apply gates#
Here we query the available GPU memory and allocate a scratch buffer for computations, followed by creating the pure quantum state and then applying the quantum gates.
152 // Query free memory on Device and allocate a scratch buffer
153 std::size_t freeSize{0}, totalSize{0};
154 HANDLE_CUDA_ERROR(cudaMemGetInfo(&freeSize, &totalSize));
155 const std::size_t scratchSize = (freeSize - (freeSize % 4096)) / 2;
156 void* d_scratch{nullptr};
157 void *h_scratch{nullptr}; // host scratch workspace buffer (attached if the prepare call reports a need)
158 int64_t hostWorksize{0};
159 HANDLE_CUDA_ERROR(cudaMalloc(&d_scratch, scratchSize));
160 std::cout << "Allocated " << scratchSize << " bytes of scratch memory on GPU\n";
161
162 // Create the initial quantum state
163 cutensornetState_t quantumState;
164 HANDLE_CUTN_ERROR(cutensornetCreateState(cutnHandle, CUTENSORNET_STATE_PURITY_PURE, numQubits, qubitDims.data(),
165 CUDA_C_64F, &quantumState));
166 std::cout << "Created the initial quantum state\n";
167
168 // Construct the quantum circuit state (apply quantum gates)
169 int64_t id;
170 for (int32_t i = 0; i < numQubits; ++i)
171 {
172 HANDLE_CUTN_ERROR(cutensornetStateApplyTensorOperator(
173 cutnHandle, quantumState, 1, std::vector<int32_t>{{i}}.data(), d_gateH, nullptr, 1, 0, 1, &id));
174 for (int32_t j = (i + 1); j < numQubits; ++j)
175 {
176 HANDLE_CUTN_ERROR(cutensornetStateApplyTensorOperator(cutnHandle, quantumState, 2,
177 std::vector<int32_t>{{j, i}}.data(), d_gateCR[j - i],
178 nullptr, 1, 0, 1, &id));
179 }
180 }
181 std::cout << "Applied quantum gates\n";
Set up and specify the MPS representation of the output state#
Now let’s set up the MPS representation of the output state for our 16-qubit quantum circuit.
185 // Define the MPS representation and allocate memory buffers for the MPS tensors
186 const int64_t maxExtent = 8;
187 std::vector<int64_t> dimExtents(numQubits, 2);
188 std::vector<int64_t> maxBondExtents = getMaxBondExtents(dimExtents, maxExtent);
189
190 std::vector<std::vector<int64_t>> projMPSTensorExtents;
191 std::vector<const int64_t*> projMPSTensorExtentsPtr(numQubits);
192 std::vector<void*> d_projMPSTensors(numQubits, nullptr);
193 std::vector<int64_t> numElements(numQubits);
194 std::vector<void*> d_envTensorsExtract(numQubits, nullptr);
195 std::vector<void*> d_envTensorsInsert(numQubits, nullptr);
Initialize the MPS in the vacuum state#
For simplicity and reproducibility, we initialize the MPS as the vacuum state. This includes logic for the bond dimension, as we require the MPS to not have overcomplete bond dimensions.
200 for (int32_t i = 0; i < numQubits; ++i)
201 {
202 if (i == 0)
203 {
204 // left boundary MPS tensor
205 auto extent2 = std::min(maxBondExtents[i], maxExtent);
206 projMPSTensorExtents.push_back({2, extent2});
207 numElements[i] = 2 * extent2;
208 HANDLE_CUDA_ERROR(cudaMalloc(&d_projMPSTensors[i], numElements[i] * (2 * fp64size)));
209 //projMPSTensorStrides.push_back({1, 2});
210 }
211 else if (i == numQubits - 1)
212 {
213 // right boundary MPS tensor
214 auto extent1 = std::min(maxBondExtents[i - 1], maxExtent);
215 projMPSTensorExtents.push_back({extent1, 2});
216 numElements[i] = extent1 * 2;
217 HANDLE_CUDA_ERROR(cudaMalloc(&d_projMPSTensors[i], numElements[i] * (2 * fp64size)));
218 }
219 else
220 {
221 // middle MPS tensors
222 auto extent1 = std::min(maxBondExtents[i - 1], maxExtent);
223 auto extent3 = std::min(maxBondExtents[i], maxExtent);
224 projMPSTensorExtents.push_back({extent1, 2, extent3});
225 numElements[i] = extent1 * 2 * extent3;
226 HANDLE_CUDA_ERROR(cudaMalloc(&d_projMPSTensors[i], numElements[i] * (2 * fp64size)));
227 }
228 projMPSTensorExtentsPtr[i] = projMPSTensorExtents[i].data();
229
230 HANDLE_CUDA_ERROR(cudaMalloc(&d_envTensorsExtract[i], numElements[i] * (2 * fp64size)));
231 HANDLE_CUDA_ERROR(cudaMalloc(&d_envTensorsInsert[i], numElements[i] * (2 * fp64size)));
232 }
233
234 // Initialize the vacuum state
235 for (int32_t i = 0; i < numQubits; ++i)
236 {
237 std::vector<std::complex<double>> hostTensor(numElements[i]);
238 for (int64_t j = 0; j < numElements[i]; ++j)
239 {
240 hostTensor[j] = {0.0, 0.0};
241 }
242 hostTensor[0] = {1.0, 0.0};
243 HANDLE_CUDA_ERROR(
244 cudaMemcpy(d_projMPSTensors[i], hostTensor.data(), numElements[i] * (2 * fp64size), cudaMemcpyHostToDevice));
245 }
246 std::cout << "Allocated GPU memory for projection MPS tensors\n";
Define MPS representation and allocate projection MPS tensors#
Here we set up the MPS representation to be optimized by the projection MPS API and allocate GPU memory for the projection MPS tensors and environment tensors to be used over the course of the DMRG optimization.
250 // Prepare state projection MPS
251 std::vector<cutensornetState_t> states = {quantumState};
252 std::vector<cuDoubleComplex> coefficients = {{1.0, 0.0}};
253
254 // Environment specifications
255 std::vector<cutensornetMPSEnvBounds_t> envSpecs;
256 for (int32_t i = 0; i < numQubits; ++i)
257 {
258 cutensornetMPSEnvBounds_t spec;
259 spec.lowerBound = i - 1;
260 spec.upperBound = i + 1;
261 envSpecs.push_back(spec);
262 }
263
264 cutensornetMPSEnvBounds_t initialOrthoSpec;
265 initialOrthoSpec.lowerBound = -1;
266 initialOrthoSpec.upperBound = numQubits;
Create state projection MPS#
Now we create the cutensornetStateProjectionMPS_t object that will be used for DMRG optimization.
Many MPS optimization algorithms, including circuit DMRG, make use of the gauge degree of freedom of the MPS and enforce
orthogonality conditions on the MPS tensors, such that the optimized tensors constitute coefficients of the quantum state in a orthonormal basis defined by the other MPS tensors.
By default, the cutensornetStateProjectionMPSExtract API enforces these orthogonality conditions by performing orthogonalization of the MPS tensors towards the environment for which the extraction happens.
The following figure illustrates the main idea behind the state projection MPS API for the four-qubit case.
The environment network is the initial MPS (left) contracted with the circuit gates (middle) and the target MPS (right), where the tensor to be variationally optimized is removed from the network. Contracting this network results in a single-site tensor, which we will call the environment tensor. Note that we use the following convention for the indexing of the environment tensors: The single-site environment for tensor \(i\) is specified by the environment specification \((i-1, i+1)\).
270 // Create state projection MPS
271 cutensornetStateProjectionMPS_t projectionMps;
272 HANDLE_CUTN_ERROR(cutensornetCreateStateProjectionMPS(
273 cutnHandle, states.size(), states.data(), coefficients.data(), false, envSpecs.size(), envSpecs.data(),
274 CUTENSORNET_BOUNDARY_CONDITION_OPEN, numQubits, 0, projMPSTensorExtentsPtr.data(), 0,
275 d_projMPSTensors.data(), &initialOrthoSpec, &projectionMps));
276 std::cout << "Created state projection MPS\n";
277
278 // Prepare the state projection MPS computation
279 cutensornetWorkspaceDescriptor_t workDesc;
280 HANDLE_CUTN_ERROR(cutensornetCreateWorkspaceDescriptor(cutnHandle, &workDesc));
281 HANDLE_CUTN_ERROR(cutensornetStateProjectionMPSPrepare(cutnHandle, projectionMps, scratchSize, workDesc, 0x0));
282
283 int64_t worksize{0};
284 HANDLE_CUTN_ERROR(cutensornetWorkspaceGetMemorySize(cutnHandle, workDesc, CUTENSORNET_WORKSIZE_PREF_RECOMMENDED,
285 CUTENSORNET_MEMSPACE_DEVICE, CUTENSORNET_WORKSPACE_SCRATCH,
286 &worksize));
287 std::cout << "Workspace size for MPS projection = " << worksize << " bytes\n";
288
289 if (worksize <= scratchSize)
290 {
291 HANDLE_CUTN_ERROR(cutensornetWorkspaceSetMemory(cutnHandle, workDesc, CUTENSORNET_MEMSPACE_DEVICE,
292 CUTENSORNET_WORKSPACE_SCRATCH, d_scratch, worksize));
293 }
294 else
295 {
296 std::cout << "ERROR: Insufficient workspace size on Device!\n";
297
298 // Cleanup
299 HANDLE_CUTN_ERROR(cutensornetDestroyWorkspaceDescriptor(workDesc));
300 HANDLE_CUTN_ERROR(cutensornetDestroyStateProjectionMPS(projectionMps));
301 HANDLE_CUTN_ERROR(cutensornetDestroyState(quantumState));
302
303 // Free GPU buffers
304 for (int32_t i = 0; i < numQubits; i++)
305 {
306 HANDLE_CUDA_ERROR(cudaFree(d_projMPSTensors[i]));
307 HANDLE_CUDA_ERROR(cudaFree(d_envTensorsExtract[i]));
308 HANDLE_CUDA_ERROR(cudaFree(d_envTensorsInsert[i]));
309 }
310 HANDLE_CUDA_ERROR(cudaFree(d_scratch));
311 for (auto ptr : d_gateCR) HANDLE_CUDA_ERROR(cudaFree(ptr));
312 HANDLE_CUDA_ERROR(cudaFree(d_gateH));
313 std::cout << "Freed memory on GPU\n";
314
315 // Finalize the cuTensorNet library
316 HANDLE_CUTN_ERROR(cutensornetDestroy(cutnHandle));
317
318 std::abort();
319 }
320
321 // Query the host scratch workspace size and attach a host scratch buffer if one is required
322 HANDLE_CUTN_ERROR(cutensornetWorkspaceGetMemorySize(cutnHandle, workDesc, CUTENSORNET_WORKSIZE_PREF_RECOMMENDED,
323 CUTENSORNET_MEMSPACE_HOST, CUTENSORNET_WORKSPACE_SCRATCH, &hostWorksize));
324 std::cout << "Scratch Host workspace size (bytes) = " << hostWorksize << std::endl;
325 if(hostWorksize > 0) {
326 h_scratch = std::realloc(h_scratch, hostWorksize);
327 if(h_scratch == nullptr) { std::cout << "ERROR: Host scratch allocation failed!\n"; std::abort(); }
328 HANDLE_CUTN_ERROR(cutensornetWorkspaceSetMemory(cutnHandle, workDesc, CUTENSORNET_MEMSPACE_HOST,
329 CUTENSORNET_WORKSPACE_SCRATCH, h_scratch, hostWorksize));
330 }
Perform DMRG optimization#
Once the state projection MPS has been prepared, we perform DMRG optimization through forward and backward sweeps to optimize the MPS representation. For each tensor, we extract the site tensor, compute the corresponding environment tensor, and then insert the resulting tensor back into the MPS.
334 // DMRG iterations
335 const int32_t numIterations = 5;
336 std::cout << "Starting DMRG iterations\n";
337
338 for (int32_t iter = 0; iter < numIterations; ++iter)
339 {
340 std::cout << "DMRG iteration " << iter + 1 << "/" << numIterations << std::endl;
341
342 // Forward sweep
343 for (int32_t i = 0; i < numQubits; ++i)
344 {
345 // Environment bounds for site i
346 cutensornetMPSEnvBounds_t envBounds;
347 envBounds.lowerBound = i - 1;
348 envBounds.upperBound = i + 1;
349
350 // Extract site tensor
351 HANDLE_CUTN_ERROR(cutensornetStateProjectionMPSExtractTensor(
352 cutnHandle, projectionMps, &envBounds, nullptr, d_envTensorsExtract[i], workDesc, 0x0));
353
354 // Compute environment tensor
355 HANDLE_CUTN_ERROR(cutensornetStateProjectionMPSComputeTensorEnv(cutnHandle, projectionMps, &envBounds, 0, 0,
356 0, d_envTensorsInsert[i], 0,
357 0, workDesc, 0x0));
358
359 // Apply partial-fidelity scaling factor to the environment tensor
360 double f_tau_sqrt;
361 HANDLE_CUBLAS_ERROR(cublasDznrm2(cublasHandle, numElements[i],
362 static_cast<const cuDoubleComplex*>(d_envTensorsInsert[i]), 1,
363 &f_tau_sqrt));
364 HANDLE_CUDA_ERROR(cudaStreamSynchronize(0));
365
366 if (f_tau_sqrt < std::sqrt(std::numeric_limits<double>::epsilon()))
367 {
368 std::cout << "ERROR: Scaling factor is zero!\n";
369 std::abort();
370 }
371 cuDoubleComplex scaling_factor = {1.0 / f_tau_sqrt, 0.0};
372
373 HANDLE_CUBLAS_ERROR(cublasZscal(cublasHandle, numElements[i],
374 &scaling_factor,
375 static_cast<cuDoubleComplex*>(d_envTensorsInsert[i]), 1));
376
377 // Insert updated tensor
378 cutensornetMPSEnvBounds_t orthoSpec = envBounds;
379 HANDLE_CUTN_ERROR(cutensornetStateProjectionMPSInsertTensor(cutnHandle, projectionMps, &envBounds,
380 &orthoSpec, 0,
381 d_envTensorsInsert[i], workDesc, 0x0));
382 }
383
384 // Backward sweep
385 for (int32_t i = numQubits - 1; i >= 0; --i)
386 {
387 // Environment bounds for site i
388 cutensornetMPSEnvBounds_t envBounds;
389 envBounds.lowerBound = i - 1;
390 envBounds.upperBound = i + 1;
391
392 // Extract site tensor
393 HANDLE_CUTN_ERROR(cutensornetStateProjectionMPSExtractTensor(
394 cutnHandle, projectionMps, &envBounds, 0, d_envTensorsExtract[i], workDesc, 0x0));
395
396 // Compute environment tensor
397 HANDLE_CUTN_ERROR(cutensornetStateProjectionMPSComputeTensorEnv(cutnHandle, projectionMps, &envBounds, 0, 0,
398 0, d_envTensorsInsert[i], 0,
399 0, workDesc, 0x0));
400
401 // Apply partial-fidelity scaling factor to the environment tensor
402 double f_tau_sqrt;
403 HANDLE_CUBLAS_ERROR(cublasDznrm2(cublasHandle, numElements[i],
404 static_cast<const cuDoubleComplex*>(d_envTensorsInsert[i]), 1,
405 &f_tau_sqrt));
406 HANDLE_CUDA_ERROR(cudaStreamSynchronize(0));
407
408 if (f_tau_sqrt < std::sqrt(std::numeric_limits<double>::epsilon()))
409 {
410 std::cout << "ERROR: Scaling factor is zero!\n";
411 std::abort();
412 }
413 cuDoubleComplex scaling_factor = {1.0 / f_tau_sqrt, 0.0};
414
415 HANDLE_CUBLAS_ERROR(cublasZscal(cublasHandle, numElements[i],
416 &scaling_factor,
417 static_cast<cuDoubleComplex*>(d_envTensorsInsert[i]), 1));
418
419 // Insert updated tensor
420 cutensornetMPSEnvBounds_t orthoSpec = envBounds;
421 HANDLE_CUTN_ERROR(cutensornetStateProjectionMPSInsertTensor(cutnHandle, projectionMps, &envBounds,
422 &orthoSpec, 0,
423 d_envTensorsInsert[i], workDesc, 0x0));
424 }
425
426 std::cout << "Completed DMRG iteration " << iter + 1 << std::endl;
427 }
428
429 std::cout << "DMRG optimization completed\n";
Free resources#
433 // Cleanup
434 HANDLE_CUTN_ERROR(cutensornetDestroyWorkspaceDescriptor(workDesc));
435 HANDLE_CUTN_ERROR(cutensornetDestroyStateProjectionMPS(projectionMps));
436 HANDLE_CUTN_ERROR(cutensornetDestroyState(quantumState));
437
438 // Free GPU buffers
439 for (int32_t i = 0; i < numQubits; i++)
440 {
441 HANDLE_CUDA_ERROR(cudaFree(d_projMPSTensors[i]));
442 HANDLE_CUDA_ERROR(cudaFree(d_envTensorsExtract[i]));
443 HANDLE_CUDA_ERROR(cudaFree(d_envTensorsInsert[i]));
444 }
445 std::free(h_scratch);
446 HANDLE_CUDA_ERROR(cudaFree(d_scratch));
447 for (auto ptr : d_gateCR) HANDLE_CUDA_ERROR(cudaFree(ptr));
448 HANDLE_CUDA_ERROR(cudaFree(d_gateH));
449 std::cout << "Freed memory on GPU\n";
450
451 HANDLE_CUBLAS_ERROR(cublasDestroy(cublasHandle));
452
453 // Finalize the cuTensorNet library
454 HANDLE_CUTN_ERROR(cutensornetDestroy(cutnHandle));
455 std::cout << "Finalized the cuTensorNet library\n";
456
457 return 0;
458}
References#
Ayral, Thomas, Thibaud Louvet, Yiqing Zhou, Cyprien Lambert, E. Miles Stoudenmire, and Xavier Waintal. 2023. “Density-Matrix Renormalization Group Algorithm for Simulating Quantum Circuits with a Finite Fidelity.” PRX Quantum 4 (April): 020304. https://doi.org/10.1103/PRXQuantum.4.020304.