|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# |
| 3 | +# SPDX-License-Identifier: MIT |
| 4 | + |
| 5 | +import math |
| 6 | +import argparse |
| 7 | + |
| 8 | +import torch |
| 9 | +from torch import nn |
| 10 | +from torchquantum.plugin.cuquantum import * |
| 11 | +from torchquantum.operator.standard_gates import * |
| 12 | + |
| 13 | + |
| 14 | + |
| 15 | + |
| 16 | + |
| 17 | +class MAXCUT(nn.Module): |
| 18 | + def __init__(self, n_wires, input_graph, n_layers): |
| 19 | + super().__init__() |
| 20 | + self.n_wires = n_wires |
| 21 | + self.input_graph = input_graph |
| 22 | + self.n_layers = n_layers |
| 23 | + |
| 24 | + self.circuit = ParameterizedQuantumCircuit(n_wires=n_wires, n_input_params=0, n_trainable_params=2 * n_layers) |
| 25 | + self.circuit.set_trainable_params(torch.randn(2 * n_layers)) |
| 26 | + |
| 27 | + for wire in range(self.n_wires): |
| 28 | + self.circuit.append_gate(Hadamard, wires=wire) |
| 29 | + |
| 30 | + for l in range(self.n_layers): |
| 31 | + # mixer layer |
| 32 | + for i in range(self.n_wires): |
| 33 | + self.circuit.append_gate(RX, wires=i, trainable_idx=l) |
| 34 | + |
| 35 | + # entangler layer |
| 36 | + for edge in self.input_graph: |
| 37 | + self.circuit.append_gate(CNOT, wires=[edge[0], edge[1]]) |
| 38 | + self.circuit.append_gate(RZ, wires=edge[1], trainable_idx=n_layers + l) |
| 39 | + self.circuit.append_gate(CNOT, wires=[edge[0], edge[1]]) |
| 40 | + |
| 41 | + |
| 42 | + hamiltonian = {} |
| 43 | + for edge in self.input_graph: |
| 44 | + pauli_string = "" |
| 45 | + for wire in range(self.n_wires): |
| 46 | + if wire in edge: |
| 47 | + pauli_string += "Z" |
| 48 | + else: |
| 49 | + pauli_string += "I" |
| 50 | + hamiltonian[pauli_string] = 0.5 |
| 51 | + |
| 52 | + backend = CuTensorNetworkBackend(TNConfig(num_hyper_samples=10)) |
| 53 | + self.energy = QuantumExpectation(self.circuit, backend, [hamiltonian]) |
| 54 | + self.sampling = QuantumSampling(self.circuit, backend, 100) |
| 55 | + |
| 56 | + def forward(self): |
| 57 | + start_time = torch.cuda.Event(enable_timing=True) |
| 58 | + end_time = torch.cuda.Event(enable_timing=True) |
| 59 | + |
| 60 | + start_time.record() |
| 61 | + output = self.energy() - len(self.input_graph) / 2 |
| 62 | + end_time.record() |
| 63 | + |
| 64 | + torch.cuda.synchronize() |
| 65 | + elapsed_time = start_time.elapsed_time(end_time) |
| 66 | + print(f"Forward pass took {elapsed_time:.2f} ms") |
| 67 | + |
| 68 | + return output |
| 69 | + |
| 70 | + |
| 71 | +def optimize(model, n_steps=100, lr=0.1): |
| 72 | + optimizer = torch.optim.Adam(model.parameters(), lr=lr) |
| 73 | + print(f"The initial parameters are:\n{next(model.parameters()).data.tolist()}") |
| 74 | + print("") |
| 75 | + for step in range(n_steps): |
| 76 | + optimizer.zero_grad() |
| 77 | + loss = model() |
| 78 | + start_time = torch.cuda.Event(enable_timing=True) |
| 79 | + end_time = torch.cuda.Event(enable_timing=True) |
| 80 | + |
| 81 | + start_time.record() |
| 82 | + loss.backward() |
| 83 | + end_time.record() |
| 84 | + |
| 85 | + torch.cuda.synchronize() |
| 86 | + elapsed_time = start_time.elapsed_time(end_time) |
| 87 | + print(f"Backward pass took {elapsed_time:.2f} ms") |
| 88 | + |
| 89 | + optimizer.step() |
| 90 | + |
| 91 | + print(f"Step: {step}, Cost Objective: {loss.item()}") |
| 92 | + |
| 93 | + print("") |
| 94 | + print(f"The optimal parameters are:\n{next(model.parameters()).data.tolist()}") |
| 95 | + print("") |
| 96 | + |
| 97 | +def main(): |
| 98 | + parser = argparse.ArgumentParser() |
| 99 | + parser.add_argument("--n_wires", type=int, default=4, help="number of wires") |
| 100 | + parser.add_argument("--n_layers", type=int, default=4, help="number of layers") |
| 101 | + parser.add_argument("--steps", type=int, default=100, help="number of steps") |
| 102 | + parser.add_argument("--lr", type=float, default=0.01, help="learning rate") |
| 103 | + parser.add_argument("--seed", type=int, default=0, help="random seed") |
| 104 | + args = parser.parse_args() |
| 105 | + |
| 106 | + torch.manual_seed(args.seed) |
| 107 | + |
| 108 | + # create a fully connected graph |
| 109 | + input_graph = [] |
| 110 | + for i in range(args.n_wires): |
| 111 | + for j in range(i): |
| 112 | + input_graph.append((i, j)) |
| 113 | + |
| 114 | + print(f"Cost Objective Minimum (Analytic Reference Result): {math.floor(args.n_wires**2 // 4)}") |
| 115 | + |
| 116 | + model = MAXCUT(n_wires=args.n_wires, input_graph=input_graph, n_layers=args.n_layers) |
| 117 | + optimize(model, n_steps=args.steps, lr=args.lr) |
| 118 | + samples = model.sampling() |
| 119 | + |
| 120 | + print(f"Sampling Results: {samples}") |
| 121 | + |
| 122 | + |
| 123 | +if __name__ == "__main__": |
| 124 | + main() |
0 commit comments