|
| 1 | +import argparse |
| 2 | +import torch |
| 3 | +import torch.nn as nn |
| 4 | +import torch.optim as optim |
| 5 | +import torchquantum as tq |
| 6 | + |
| 7 | +class Generator(nn.Module): |
| 8 | + def __init__(self, n_qubits: int, latent_dim: int): |
| 9 | + super().__init__() |
| 10 | + self.n_qubits = n_qubits |
| 11 | + self.latent_dim = latent_dim |
| 12 | + |
| 13 | + # Quantum encoder |
| 14 | + self.encoder = tq.GeneralEncoder([ |
| 15 | + {'input_idx': [i], 'func': 'rx', 'wires': [i]} |
| 16 | + for i in range(self.n_qubits) |
| 17 | + ]) |
| 18 | + |
| 19 | + # RX gates |
| 20 | + self.rxs = nn.ModuleList([ |
| 21 | + tq.RX(has_params=True, trainable=True) for _ in range(self.n_qubits) |
| 22 | + ]) |
| 23 | + |
| 24 | + def forward(self, x): |
| 25 | + qdev = tq.QuantumDevice(n_wires=self.n_qubits, bsz=x.shape[0], device=x.device) |
| 26 | + self.encoder(qdev, x) |
| 27 | + |
| 28 | + for i in range(self.n_qubits): |
| 29 | + self.rxs[i](qdev, wires=i) |
| 30 | + |
| 31 | + return tq.measure(qdev) |
| 32 | + |
| 33 | +class Discriminator(nn.Module): |
| 34 | + def __init__(self, n_qubits: int): |
| 35 | + super().__init__() |
| 36 | + self.n_qubits = n_qubits |
| 37 | + |
| 38 | + # Quantum encoder |
| 39 | + self.encoder = tq.GeneralEncoder([ |
| 40 | + {'input_idx': [i], 'func': 'rx', 'wires': [i]} |
| 41 | + for i in range(self.n_qubits) |
| 42 | + ]) |
| 43 | + |
| 44 | + # RX gates |
| 45 | + self.rxs = nn.ModuleList([ |
| 46 | + tq.RX(has_params=True, trainable=True) for _ in range(self.n_qubits) |
| 47 | + ]) |
| 48 | + |
| 49 | + # Quantum measurement |
| 50 | + self.measure = tq.MeasureAll(tq.PauliZ) |
| 51 | + |
| 52 | + def forward(self, x): |
| 53 | + qdev = tq.QuantumDevice(n_wires=self.n_qubits, bsz=x.shape[0], device=x.device) |
| 54 | + self.encoder(qdev, x) |
| 55 | + |
| 56 | + for i in range(self.n_qubits): |
| 57 | + self.rxs[i](qdev, wires=i) |
| 58 | + |
| 59 | + return self.measure(qdev) |
| 60 | + |
| 61 | +class QGAN(nn.Module): |
| 62 | + def __init__(self, n_qubits: int, latent_dim: int): |
| 63 | + super().__init__() |
| 64 | + self.generator = Generator(n_qubits, latent_dim) |
| 65 | + self.discriminator = Discriminator(n_qubits) |
| 66 | + |
| 67 | + def forward(self, z): |
| 68 | + fake_data = self.generator(z) |
| 69 | + fake_output = self.discriminator(fake_data) |
| 70 | + return fake_output |
| 71 | + |
| 72 | +def main(n_qubits, latent_dim): |
| 73 | + model = QGAN(n_qubits, latent_dim) |
| 74 | + print(model) |
| 75 | + |
| 76 | +if __name__ == "__main__": |
| 77 | + parser = argparse.ArgumentParser(description="Quantum Generative Adversarial Network (QGAN) Example") |
| 78 | + parser.add_argument('n_qubits', type=int, help='Number of qubits') |
| 79 | + parser.add_argument('latent_dim', type=int, help='Dimension of the latent space') |
| 80 | + |
| 81 | + args = parser.parse_args() |
| 82 | + |
| 83 | + main(args.n_qubits, args.latent_dim) |
| 84 | + |
0 commit comments