-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathquantum_computer.py
More file actions
1916 lines (1586 loc) · 67.7 KB
/
quantum_computer.py
File metadata and controls
1916 lines (1586 loc) · 67.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
quantum_computer.py
Author: Gris Iscomeback
License: AGPL v3
Collapse-Free Quantum Computer Simulator on Classical Hardware.
The state of n qubits lives in the JOINT Hilbert space C^(2^n).
The state vector has 2^n complex amplitudes: one per computational basis state.
This is the only representation that correctly supports entanglement.
Each amplitude alpha_k (k in {0,...,2^n - 1}) is encoded as a 2D spatial
wavefunction on a (G, G) grid, using the neural physics backends as the
time-evolution engine. The joint state tensor has shape:
amplitudes: (2^n, 2, G, G)
dim 0 : computational basis index (2^n states)
dim 1 : real / imaginary channel (2 channels)
dim 2 : spatial x (G points)
dim 3 : spatial y (G points)
Single-qubit gates act via einsum on the qubit index within dim 0.
Two-qubit gates (CNOT, CZ, SWAP) permute and mix amplitude pairs in dim 0.
Measurement reads Born probabilities from norm-squared without collapsing.
Architecture (SOLID):
- IQuantumGate : gate abstraction (Interface Segregation)
- IPhysicsBackend : physics engine abstraction (Dependency Inversion)
- JointHilbertState : joint 2^n amplitude state (Single Responsibility)
- HamiltonianBackend : H(nn) spectral operator backend
- SchrodingerBackend : Schrodinger network backend
- DiracBackend : Dirac relativistic spinor backend
- QuantumCircuit : circuit builder (Open/Closed via IQuantumGate)
- QuantumComputer : top-level orchestrator (Single Responsibility)
"""
from __future__ import annotations
import logging
import math
import os
import warnings
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Sequence, Tuple
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
warnings.filterwarnings("ignore")
def _make_logger(name: str) -> logging.Logger:
"""Create a module-level logger with a consistent formatter."""
logger = logging.getLogger(name)
if not logger.handlers:
handler = logging.StreamHandler()
handler.setFormatter(
logging.Formatter("%(asctime)s | %(name)s | %(levelname)s | %(message)s")
)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
return logger
_LOG = _make_logger("QuantumComputer")
@dataclass
class SimulatorConfig:
"""
Global configuration for the quantum computer simulator.
grid_size, hidden_dim, expansion_dim, num_spectral_layers must match
the values used when training the checkpoint files.
"""
grid_size: int = 16
hidden_dim: int = 32
expansion_dim: int = 64
num_spectral_layers: int = 2
dirac_mass: float = 1.0
dirac_c: float = 1.0
gamma_representation: str = "dirac"
dt: float = 0.01
normalization_eps: float = 1e-8
potential_depth: float = 5.0
potential_width: float = 0.3
hamiltonian_checkpoint: str = "weights/latest.pth"
schrodinger_checkpoint: str = "weights/schrodinger_crystal_final.pth"
dirac_checkpoint: str = "weights/dirac_phase5_latest.pth"
device: str = "cuda" if torch.cuda.is_available() else "cpu"
random_seed: int = 42
max_qubits: int = 8
class SpectralLayer(nn.Module):
"""
Spectral convolution in frequency domain.
Learns complex kernels that modulate Fourier coefficients.
Architecture is identical to the training scripts.
"""
def __init__(self, channels: int, grid_size: int) -> None:
super().__init__()
self.channels = channels
self.grid_size = grid_size
self.kernel_real = nn.Parameter(
torch.randn(channels, channels, grid_size // 2 + 1, grid_size) * 0.1
)
self.kernel_imag = nn.Parameter(
torch.randn(channels, channels, grid_size // 2 + 1, grid_size) * 0.1
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""Apply spectral convolution via RFFT2."""
x_fft = torch.fft.rfft2(x)
_b, _c, freq_h, freq_w = x_fft.shape
kr = F.interpolate(
self.kernel_real.mean(dim=0).unsqueeze(0),
size=(freq_h, freq_w), mode="bilinear", align_corners=False,
).squeeze(0)
ki = F.interpolate(
self.kernel_imag.mean(dim=0).unsqueeze(0),
size=(freq_h, freq_w), mode="bilinear", align_corners=False,
).squeeze(0)
real_part = x_fft.real * kr - x_fft.imag * ki
imag_part = x_fft.real * ki + x_fft.imag * kr
return torch.fft.irfft2(
torch.complex(real_part, imag_part),
s=(self.grid_size, self.grid_size),
)
class HamiltonianBackboneNet(nn.Module):
"""
Hamiltonian backbone: single-channel field -> H|psi>.
Shared by all physics backends as the H operator.
"""
def __init__(self, grid_size: int, hidden_dim: int, num_spectral_layers: int) -> None:
super().__init__()
self.grid_size = grid_size
self.input_proj = nn.Conv2d(1, hidden_dim, kernel_size=1)
self.spectral_layers = nn.ModuleList(
[SpectralLayer(hidden_dim, grid_size) for _ in range(num_spectral_layers)]
)
self.output_proj = nn.Conv2d(hidden_dim, 1, kernel_size=1)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""Accepts (G,G), (1,G,G), or (B,1,G,G). Returns squeezed output."""
if x.dim() == 2:
x = x.unsqueeze(0).unsqueeze(0)
elif x.dim() == 3:
x = x.unsqueeze(1)
x = F.gelu(self.input_proj(x))
for layer in self.spectral_layers:
x = F.gelu(layer(x))
return self.output_proj(x).squeeze(1)
class SchrodingerSpectralNet(nn.Module):
"""
Schrodinger network: 2-channel [psi_real, psi_imag] -> evolved wavefunction.
"""
def __init__(self, grid_size: int, hidden_dim: int, expansion_dim: int,
num_spectral_layers: int) -> None:
super().__init__()
self.grid_size = grid_size
self.input_proj = nn.Conv2d(2, hidden_dim, kernel_size=1)
self.expansion_proj = nn.Conv2d(hidden_dim, expansion_dim, kernel_size=1)
self.spectral_layers = nn.ModuleList(
[SpectralLayer(expansion_dim, grid_size) for _ in range(num_spectral_layers)]
)
self.contraction_proj = nn.Conv2d(expansion_dim, hidden_dim, kernel_size=1)
self.output_proj = nn.Conv2d(hidden_dim, 2, kernel_size=1)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""(2,G,G) or (B,2,G,G) -> same shape."""
if x.dim() == 3:
x = x.unsqueeze(0)
x = F.gelu(self.input_proj(x))
x = F.gelu(self.expansion_proj(x))
for layer in self.spectral_layers:
x = F.gelu(layer(x))
x = F.gelu(self.contraction_proj(x))
return self.output_proj(x)
class DiracSpectralNet(nn.Module):
"""
Dirac network: 8-channel spinor [4 components x (real,imag)] -> evolved spinor.
"""
def __init__(self, grid_size: int, hidden_dim: int, expansion_dim: int,
num_spectral_layers: int) -> None:
super().__init__()
self.grid_size = grid_size
self.input_proj = nn.Conv2d(8, hidden_dim, kernel_size=1)
self.expansion_proj = nn.Conv2d(hidden_dim, expansion_dim, kernel_size=1)
self.spectral_layers = nn.ModuleList(
[SpectralLayer(expansion_dim, grid_size) for _ in range(num_spectral_layers)]
)
self.contraction_proj = nn.Conv2d(expansion_dim, hidden_dim, kernel_size=1)
self.output_proj = nn.Conv2d(hidden_dim, 8, kernel_size=1)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""(8,G,G) or (B,8,G,G) -> same shape."""
if x.dim() == 3:
x = x.unsqueeze(0)
x = F.gelu(self.input_proj(x))
x = F.gelu(self.expansion_proj(x))
for layer in self.spectral_layers:
x = F.gelu(layer(x))
x = F.gelu(self.contraction_proj(x))
return self.output_proj(x)
# ---------------------------------------------------------------------------
# Gamma matrices
# ---------------------------------------------------------------------------
class GammaMatrices:
"""Dirac gamma matrices in Dirac or Weyl representation."""
def __init__(self, representation: str = "dirac", device: str = "cpu") -> None:
self.representation = representation
self.device = device
self._init_matrices()
def _init_matrices(self) -> None:
if self.representation == "dirac":
self.gamma0 = torch.tensor(
[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, -1, 0], [0, 0, 0, -1]],
dtype=torch.complex64, device=self.device)
self.gamma1 = torch.tensor(
[[0, 0, 0, 1], [0, 0, 1, 0], [0, -1, 0, 0], [-1, 0, 0, 0]],
dtype=torch.complex64, device=self.device)
self.gamma2 = torch.tensor(
[[0, 0, 0, -1j], [0, 0, 1j, 0], [0, 1j, 0, 0], [-1j, 0, 0, 0]],
dtype=torch.complex64, device=self.device)
self.gamma3 = torch.tensor(
[[0, 0, 1, 0], [0, 0, 0, -1], [-1, 0, 0, 0], [0, 1, 0, 0]],
dtype=torch.complex64, device=self.device)
elif self.representation == "weyl":
self.gamma0 = torch.tensor(
[[0, 0, 1, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 1, 0, 0]],
dtype=torch.complex64, device=self.device)
self.gamma1 = torch.tensor(
[[0, 0, 0, 1], [0, 0, 1, 0], [0, -1, 0, 0], [-1, 0, 0, 0]],
dtype=torch.complex64, device=self.device)
self.gamma2 = torch.tensor(
[[0, 0, 0, -1j], [0, 0, 1j, 0], [0, 1j, 0, 0], [-1j, 0, 0, 0]],
dtype=torch.complex64, device=self.device)
self.gamma3 = torch.tensor(
[[0, 0, 1, 0], [0, 0, 0, -1], [-1, 0, 0, 0], [0, 1, 0, 0]],
dtype=torch.complex64, device=self.device)
else:
raise ValueError(f"Unknown gamma representation: {self.representation}")
self.gammas = [self.gamma0, self.gamma1, self.gamma2, self.gamma3]
def to(self, device: str) -> "GammaMatrices":
"""Move all matrices to device."""
self.device = device
self._init_matrices()
return self
class JointHilbertState:
"""
Joint quantum state of n qubits in the full 2^n dimensional Hilbert space.
The state is stored as a tensor of shape (2^n, 2, G, G):
- dim 0: computational basis index k in {0, ..., 2^n - 1}
bit j of k is the state of qubit j (MSB = qubit 0)
- dim 1: channel 0 = real part, channel 1 = imaginary part
- dim 2: spatial x (G grid points)
- dim 3: spatial y (G grid points)
Each amplitude alpha_k is a spatial wavefunction. The overall quantum
amplitude for basis state |k> is the complex field alpha_k(x,y).
The Born probability of measuring |k> is:
P(k) = integral |alpha_k(x,y)|^2 dx dy
= sum_{x,y} (alpha_k_real^2 + alpha_k_imag^2)
normalized so that sum_k P(k) = 1.
This representation correctly supports:
- Superposition: multiple k indices have non-zero amplitude
- Entanglement: amplitudes do not factorize across qubits
- Coherent multi-qubit gates: exact permutation and mixing of amplitudes
"""
def __init__(self, amplitudes: torch.Tensor, n_qubits: int) -> None:
expected_dim0 = 2 ** n_qubits
if amplitudes.shape[0] != expected_dim0:
raise ValueError(
f"amplitudes.shape[0]={amplitudes.shape[0]} but 2^n_qubits={expected_dim0}"
)
self.amplitudes = amplitudes
self.n_qubits = n_qubits
self.dim = expected_dim0
self.device = amplitudes.device
self.G = amplitudes.shape[-1]
def normalize_(self) -> None:
"""In-place normalization: sum_k P(k) = 1."""
probs = (self.amplitudes[:, 0] ** 2 + self.amplitudes[:, 1] ** 2).sum(dim=(-2, -1))
total = probs.sum() + 1e-12
self.amplitudes = self.amplitudes / (total ** 0.5)
def probabilities(self) -> torch.Tensor:
"""Return (2^n,) tensor of Born probabilities P(k) for each basis state."""
probs = (self.amplitudes[:, 0] ** 2 + self.amplitudes[:, 1] ** 2).sum(dim=(-2, -1))
return probs / (probs.sum() + 1e-12)
def marginal_probability_one(self, qubit: int) -> float:
"""
Marginal Born probability P(qubit_j = |1>).
Sums P(k) over all basis states k where bit j == 1.
Bit ordering: qubit 0 is the MSB of k.
"""
probs = self.probabilities()
bit_pos = self.n_qubits - 1 - qubit
mask = torch.zeros(self.dim, dtype=torch.bool, device=self.device)
for k in range(self.dim):
if (k >> bit_pos) & 1:
mask[k] = True
return float(probs[mask].sum().clamp(0.0, 1.0))
def most_probable_basis_state(self) -> int:
"""Return the index k with the highest probability."""
return int(self.probabilities().argmax().item())
def bloch_vector(self, qubit: int) -> Tuple[float, float, float]:
"""
Compute the reduced Bloch vector for qubit j by partial trace.
rho_j[0,0] = P(qubit=0), rho_j[1,1] = P(qubit=1)
rho_j[0,1] = sum_{pairs} alpha_{k0}^* alpha_{k1} (off-diagonal coherence)
bx = 2 Re(rho_j[0,1]), by = -2 Im(rho_j[0,1]), bz = P(0) - P(1)
"""
probs = self.probabilities()
bit_pos = self.n_qubits - 1 - qubit
p0 = float(sum(probs[k] for k in range(self.dim) if not ((k >> bit_pos) & 1)))
p1 = 1.0 - p0
bz = p0 - p1
re_offdiag = 0.0
im_offdiag = 0.0
for k0 in range(self.dim):
if (k0 >> bit_pos) & 1:
continue
k1 = k0 | (1 << bit_pos)
a0r = self.amplitudes[k0, 0]
a0i = self.amplitudes[k0, 1]
a1r = self.amplitudes[k1, 0]
a1i = self.amplitudes[k1, 1]
re_offdiag += float((a0r * a1r + a0i * a1i).sum())
im_offdiag += float((a0r * a1i - a0i * a1r).sum())
total_weight = float(
(self.amplitudes[:, 0] ** 2 + self.amplitudes[:, 1] ** 2).sum()
) + 1e-12
bx = 2.0 * re_offdiag / total_weight
by = -2.0 * im_offdiag / total_weight
mag = math.sqrt(bx ** 2 + by ** 2 + bz ** 2) + 1e-12
if mag > 1.0:
bx, by, bz = bx / mag, by / mag, bz / mag
return bx, by, bz
def clone(self) -> "JointHilbertState":
"""Return a deep copy."""
return JointHilbertState(self.amplitudes.clone(), self.n_qubits)
class PotentialGenerator:
"""Spatial potentials for eigenstate initialization."""
def __init__(self, config: SimulatorConfig) -> None:
self.config = config
self.G = config.grid_size
def _grid(self) -> Tuple[torch.Tensor, torch.Tensor]:
x = torch.linspace(0, 2 * math.pi, self.G)
y = torch.linspace(0, 2 * math.pi, self.G)
return torch.meshgrid(x, y, indexing="ij")
def harmonic(self) -> torch.Tensor:
"""V = k/2 * r^2."""
X, Y = self._grid()
cx, cy = math.pi, math.pi
return 0.5 * self.config.potential_depth * (
(X - cx) ** 2 + (Y - cy) ** 2
) / (math.pi ** 2)
def double_well(self) -> torch.Tensor:
"""Double-well along x."""
X, _ = self._grid()
cx = math.pi
w = self.config.potential_width * math.pi
return self.config.potential_depth * ((X - cx) ** 2 / w ** 2 - 1.0) ** 2
def coulomb(self) -> torch.Tensor:
"""Coulomb-like V ~ -1/r."""
X, Y = self._grid()
cx, cy = math.pi, math.pi
r = torch.sqrt((X - cx) ** 2 + (Y - cy) ** 2) + self.config.potential_width
return -self.config.potential_depth / r
def periodic_lattice(self) -> torch.Tensor:
"""Periodic cosine lattice."""
X, Y = self._grid()
return self.config.potential_depth * (torch.cos(2.0 * X) + torch.cos(2.0 * Y))
def mixed(self, seed: int) -> torch.Tensor:
"""Dirichlet-weighted mixture of all four potentials."""
rng = np.random.RandomState(seed)
weights = rng.dirichlet([1.0, 1.0, 1.0, 1.0])
parts = [self.harmonic(), self.double_well(), self.coulomb(), self.periodic_lattice()]
result = torch.zeros(self.G, self.G)
for w, v in zip(weights, parts):
result += float(w) * v
return result
def _solve_eigenstate(config: SimulatorConfig, potential: torch.Tensor, n: int) -> torch.Tensor:
"""
Solve the 1D marginal Hamiltonian and return the n-th eigenstate
as a normalized 2-channel (2, G, G) real tensor.
"""
G = config.grid_size
kx = torch.fft.fftfreq(G, d=1.0) * 2.0 * math.pi
h_matrix = torch.diag(-0.5 * (-(kx ** 2))) + torch.diag(potential.mean(dim=1))
try:
_, eigenvectors = torch.linalg.eigh(h_matrix.float())
except Exception:
eigenvectors = torch.eye(G)
n_clamped = min(n, G - 1)
psi_1d = eigenvectors[:, n_clamped]
psi_2d = psi_1d.unsqueeze(1).expand(-1, G).clone()
phase = torch.randn(G, G) * 0.1
psi = torch.stack([psi_2d * torch.cos(phase), psi_2d * torch.sin(phase)], dim=0)
norm = torch.sqrt((psi ** 2).sum()) + 1e-8
return psi / norm
def _build_basis_amplitude(config: SimulatorConfig, basis_idx: int) -> torch.Tensor:
"""
Build the (2, G, G) spatial wavefunction for amplitude at basis index basis_idx.
Each computational basis state gets its own spatial eigenstate profile.
The excitation level is proportional to the popcount of the basis index.
"""
pot_gen = PotentialGenerator(config)
popcount = bin(basis_idx).count("1")
potential = pot_gen.mixed(seed=basis_idx * 17 + 3)
return _solve_eigenstate(config, potential, n=popcount)
class JointStateFactory:
"""Builds JointHilbertState tensors for common initial conditions."""
def __init__(self, config: SimulatorConfig) -> None:
self.config = config
def _empty(self, n_qubits: int) -> torch.Tensor:
return torch.zeros(2 ** n_qubits, 2, self.config.grid_size, self.config.grid_size,
device=self.config.device)
def all_zeros(self, n_qubits: int) -> JointHilbertState:
"""Initialize register in |00...0>."""
amps = self._empty(n_qubits)
amps[0] = _build_basis_amplitude(self.config, 0).to(self.config.device)
state = JointHilbertState(amps, n_qubits)
state.normalize_()
return state
def basis_state(self, n_qubits: int, k: int) -> JointHilbertState:
"""Initialize register in computational basis state |k>."""
if k < 0 or k >= 2 ** n_qubits:
raise ValueError(f"k={k} out of range for {n_qubits} qubits")
amps = self._empty(n_qubits)
amps[k] = _build_basis_amplitude(self.config, k).to(self.config.device)
state = JointHilbertState(amps, n_qubits)
state.normalize_()
return state
def from_bitstring(self, bitstring: str) -> JointHilbertState:
"""Initialize in the basis state given by binary string."""
return self.basis_state(len(bitstring), int(bitstring, 2))
# ---------------------------------------------------------------------------
# Physics backends
# ---------------------------------------------------------------------------
class IPhysicsBackend(ABC):
"""Abstract physics backend for spatial wavefunction evolution."""
@abstractmethod
def evolve_amplitude(self, amp: torch.Tensor, dt: float) -> torch.Tensor:
"""Evolve a single (2, G, G) wavefunction by dt under H."""
@abstractmethod
def apply_phase(self, amp: torch.Tensor, phase_angle: float) -> torch.Tensor:
"""Apply global phase e^{i*phi} to a (2, G, G) amplitude."""
class HamiltonianBackend(IPhysicsBackend):
"""
Physics backend driven by the Hamiltonian neural network.
Performs first-order Schrodinger time evolution:
psi(t+dt) = psi(t) - i*dt*H*psi(t)
"""
def __init__(self, config: SimulatorConfig) -> None:
self.config = config
self.device = config.device
self.net: Optional[HamiltonianBackboneNet] = None
self._laplacian: Optional[torch.Tensor] = None
self._load()
self._precompute_laplacian()
def _load(self) -> None:
net = HamiltonianBackboneNet(
self.config.grid_size, self.config.hidden_dim, self.config.num_spectral_layers
).to(self.device)
path = self.config.hamiltonian_checkpoint
if os.path.exists(path):
try:
ckpt = torch.load(path, map_location=self.device, weights_only=False)
net.load_state_dict(ckpt.get("model_state_dict", ckpt), strict=False)
_LOG.info("HamiltonianBackend: loaded %s", path)
except Exception as exc:
_LOG.warning("HamiltonianBackend: load failed (%s), random init", exc)
else:
_LOG.info("HamiltonianBackend: no checkpoint at %s, random init", path)
net.eval()
for p in net.parameters():
p.requires_grad_(False)
self.net = net
def _precompute_laplacian(self) -> None:
G = self.config.grid_size
kx = torch.fft.fftfreq(G, d=1.0) * 2.0 * math.pi
ky = torch.fft.fftfreq(G, d=1.0) * 2.0 * math.pi
KX, KY = torch.meshgrid(kx, ky, indexing="ij")
self._laplacian = (-(KX ** 2 + KY ** 2)).float().to(self.device)
def _apply_h(self, field: torch.Tensor) -> torch.Tensor:
if self.net is not None:
with torch.no_grad():
result = self.net(field.to(self.device))
return result.squeeze() if result.dim() > 2 else result
fft = torch.fft.fft2(field.to(self.device))
return torch.fft.ifft2(fft * self._laplacian).real
def evolve_amplitude(self, amp: torch.Tensor, dt: float) -> torch.Tensor:
"""dpsi/dt = -i H psi => psi' = psi + dt * (-i H psi) = psi + dt*(H_i*r - H_r*i)."""
psi_r = amp[0].to(self.device)
psi_i = amp[1].to(self.device)
h_r = self._apply_h(psi_r)
h_i = self._apply_h(psi_i)
new_r = psi_r + dt * h_i
new_i = psi_i - dt * h_r
out = torch.stack([new_r, new_i], dim=0)
norm = torch.sqrt((out ** 2).sum()) + 1e-8
return out / norm
def apply_phase(self, amp: torch.Tensor, phase_angle: float) -> torch.Tensor:
c = math.cos(phase_angle)
s = math.sin(phase_angle)
return torch.stack([c * amp[0] - s * amp[1], s * amp[0] + c * amp[1]], dim=0)
class SchrodingerBackend(IPhysicsBackend):
"""
Physics backend driven by the Schrodinger network.
Uses the learned 2-channel spectral network for wavefunction propagation.
Falls back to HamiltonianBackend if checkpoint is unavailable.
"""
def __init__(self, config: SimulatorConfig, hamiltonian: HamiltonianBackend) -> None:
self.config = config
self.device = config.device
self.hamiltonian = hamiltonian
self.net: Optional[SchrodingerSpectralNet] = None
self._load()
def _load(self) -> None:
net = SchrodingerSpectralNet(
self.config.grid_size, self.config.hidden_dim,
self.config.expansion_dim, self.config.num_spectral_layers
).to(self.device)
path = self.config.schrodinger_checkpoint
if os.path.exists(path):
try:
ckpt = torch.load(path, map_location=self.device, weights_only=False)
net.load_state_dict(ckpt.get("model_state_dict", ckpt), strict=False)
_LOG.info("SchrodingerBackend: loaded %s", path)
except Exception as exc:
_LOG.warning("SchrodingerBackend: load failed (%s), using H-only", exc)
return
else:
_LOG.info("SchrodingerBackend: no checkpoint at %s, using H-only", path)
return
net.eval()
for p in net.parameters():
p.requires_grad_(False)
self.net = net
def evolve_amplitude(self, amp: torch.Tensor, dt: float) -> torch.Tensor:
if self.net is None:
return self.hamiltonian.evolve_amplitude(amp, dt)
with torch.no_grad():
out = self.net(amp.unsqueeze(0).to(self.device)).squeeze(0)
norm = torch.sqrt((out ** 2).sum()) + 1e-8
return out / norm
def apply_phase(self, amp: torch.Tensor, phase_angle: float) -> torch.Tensor:
return self.hamiltonian.apply_phase(amp, phase_angle)
class DiracBackend(IPhysicsBackend):
"""
Physics backend driven by the Dirac network.
Expands each (2,G,G) amplitude to a 4-component spinor, propagates
via the Dirac network, then projects back to (2,G,G).
"""
def __init__(self, config: SimulatorConfig, hamiltonian: HamiltonianBackend) -> None:
self.config = config
self.device = config.device
self.hamiltonian = hamiltonian
self.gamma = GammaMatrices(config.gamma_representation, config.device)
self.net: Optional[DiracSpectralNet] = None
self._load()
self._precompute_dirac()
def _load(self) -> None:
net = DiracSpectralNet(
self.config.grid_size, self.config.hidden_dim,
self.config.expansion_dim, self.config.num_spectral_layers
).to(self.device)
path = self.config.dirac_checkpoint
if os.path.exists(path):
try:
ckpt = torch.load(path, map_location=self.device, weights_only=False)
net.load_state_dict(ckpt.get("model_state_dict", ckpt), strict=False)
_LOG.info("DiracBackend: loaded %s", path)
except Exception as exc:
_LOG.warning("DiracBackend: load failed (%s), using H-only", exc)
return
else:
_LOG.info("DiracBackend: no checkpoint at %s, using H-only", path)
return
net.eval()
for p in net.parameters():
p.requires_grad_(False)
self.net = net
def _precompute_dirac(self) -> None:
G = self.config.grid_size
kx = torch.fft.fftfreq(G, d=1.0) * 2.0 * math.pi
ky = torch.fft.fftfreq(G, d=1.0) * 2.0 * math.pi
KX, KY = torch.meshgrid(kx, ky, indexing="ij")
self.kx_grid = KX.to(self.device)
self.ky_grid = KY.to(self.device)
self.alpha_x = (self.gamma.gamma0 @ self.gamma.gamma1).to(self.device)
self.alpha_y = (self.gamma.gamma0 @ self.gamma.gamma2).to(self.device)
self.beta = self.gamma.gamma0.to(self.device)
def _pack(self, amp: torch.Tensor) -> torch.Tensor:
G = self.config.grid_size
psi_c = torch.complex(amp[0].to(self.device), amp[1].to(self.device))
s = math.sqrt(0.5)
spinor = torch.zeros(4, G, G, dtype=torch.complex64, device=self.device)
spinor[0] = psi_c * s
spinor[1] = psi_c * s
spinor[2] = psi_c.conj() * s
spinor[3] = psi_c.conj() * s
return spinor
def _unpack(self, spinor: torch.Tensor) -> torch.Tensor:
particle = spinor[:2].mean(dim=0)
out = torch.stack([particle.real, particle.imag], dim=0)
norm = torch.sqrt((out ** 2).sum()) + 1e-8
return out / norm
def _analytical_dirac(self, spinor: torch.Tensor) -> torch.Tensor:
m, c = self.config.dirac_mass, self.config.dirac_c
result = torch.zeros_like(spinor)
for comp in range(4):
fft = torch.fft.fft2(spinor[comp])
px = torch.fft.ifft2(fft * self.kx_grid)
py = torch.fft.ifft2(fft * self.ky_grid)
for row in range(4):
result[row] += (
c * self.alpha_x[row, comp] * px
+ c * self.alpha_y[row, comp] * py
+ m * c ** 2 * self.beta[row, comp] * spinor[comp]
)
return result
def evolve_amplitude(self, amp: torch.Tensor, dt: float) -> torch.Tensor:
spinor = self._pack(amp)
if self.net is not None:
channels = torch.cat([spinor.real, spinor.imag], dim=0).unsqueeze(0)
with torch.no_grad():
out = self.net(channels).squeeze(0)
spinor_out = torch.complex(out[:4], out[4:])
else:
h_spinor = self._analytical_dirac(spinor)
spinor_out = spinor - 1j * dt * h_spinor
norm = torch.sqrt((spinor_out.abs() ** 2).sum()) + 1e-8
return self._unpack(spinor_out / norm)
def apply_phase(self, amp: torch.Tensor, phase_angle: float) -> torch.Tensor:
return self.hamiltonian.apply_phase(amp, phase_angle)
def _single_qubit_unitary(
state: JointHilbertState,
qubit: int,
u: torch.Tensor,
backend: IPhysicsBackend,
) -> JointHilbertState:
"""
Apply a 2x2 unitary u to qubit j in the joint Hilbert space.
For each pair of basis states (k0, k1) that differ only in bit j:
alpha_{k0}' = u[0,0]*alpha_{k0} + u[0,1]*alpha_{k1}
alpha_{k1}' = u[1,0]*alpha_{k0} + u[1,1]*alpha_{k1}
Complex scalar * (2,G,G) amplitude:
(a+ib)(psi_r + i*psi_i) = (a*psi_r - b*psi_i) + i*(a*psi_i + b*psi_r)
This is exact, preserves unitarity, and correctly creates superpositions.
"""
n = state.n_qubits
bit_pos = n - 1 - qubit
new_amps = state.amplitudes.clone()
u00r, u00i = float(u[0, 0].real), float(u[0, 0].imag)
u01r, u01i = float(u[0, 1].real), float(u[0, 1].imag)
u10r, u10i = float(u[1, 0].real), float(u[1, 0].imag)
u11r, u11i = float(u[1, 1].real), float(u[1, 1].imag)
processed = set()
for k0 in range(2 ** n):
if (k0 >> bit_pos) & 1:
continue
k1 = k0 | (1 << bit_pos)
if k0 in processed:
continue
processed.add(k0)
processed.add(k1)
a0r = state.amplitudes[k0, 0]
a0i = state.amplitudes[k0, 1]
a1r = state.amplitudes[k1, 0]
a1i = state.amplitudes[k1, 1]
new_amps[k0, 0] = u00r*a0r - u00i*a0i + u01r*a1r - u01i*a1i
new_amps[k0, 1] = u00r*a0i + u00i*a0r + u01r*a1i + u01i*a1r
new_amps[k1, 0] = u10r*a0r - u10i*a0i + u11r*a1r - u11i*a1i
new_amps[k1, 1] = u10r*a0i + u10i*a0r + u11r*a1i + u11i*a1r
return JointHilbertState(new_amps, n)
def _two_qubit_unitary(
state: JointHilbertState,
ctrl: int,
tgt: int,
u4: torch.Tensor,
) -> JointHilbertState:
"""
Apply a 4x4 unitary in the {|00>,|01>,|10>,|11>} subspace of (ctrl, tgt).
For each group of 4 basis states sharing all bits except ctrl and tgt,
apply the 4x4 unitary to the amplitude quadruplet.
Ordering within the 4x4 block: |00>=0, |01>=1, |10>=2, |11>=3
(first bit = ctrl, second bit = tgt).
This correctly implements CNOT, CZ, SWAP and any 2-qubit gate.
"""
n = state.n_qubits
ctrl_bit = n - 1 - ctrl
tgt_bit = n - 1 - tgt
new_amps = state.amplitudes.clone()
processed = set()
for base in range(2 ** n):
if (base >> ctrl_bit) & 1:
continue
if (base >> tgt_bit) & 1:
continue
k00 = base
k01 = base | (1 << tgt_bit)
k10 = base | (1 << ctrl_bit)
k11 = base | (1 << ctrl_bit) | (1 << tgt_bit)
key = (k00, k01, k10, k11)
if key in processed:
continue
processed.add(key)
indices = [k00, k01, k10, k11]
old_r = [state.amplitudes[k, 0] for k in indices]
old_i = [state.amplitudes[k, 1] for k in indices]
for row, k_out in enumerate(indices):
new_r = torch.zeros_like(old_r[0])
new_i = torch.zeros_like(old_i[0])
for col in range(4):
ur = float(u4[row, col].real)
ui = float(u4[row, col].imag)
new_r = new_r + ur * old_r[col] - ui * old_i[col]
new_i = new_i + ur * old_i[col] + ui * old_r[col]
new_amps[k_out, 0] = new_r
new_amps[k_out, 1] = new_i
# Unitary gates preserve total norm; do not normalize here.
return JointHilbertState(new_amps, n)
class IQuantumGate(ABC):
"""Abstract quantum gate operating on the joint Hilbert space."""
@property
@abstractmethod
def name(self) -> str:
"""Gate identifier."""
@abstractmethod
def apply(
self,
state: JointHilbertState,
backend: IPhysicsBackend,
targets: Sequence[int],
params: Optional[Dict[str, float]],
) -> JointHilbertState:
"""Apply gate to joint state, return new joint state."""
class HadamardGate(IQuantumGate):
"""H = [[1,1],[1,-1]] / sqrt(2)."""
@property
def name(self) -> str:
return "H"
def apply(self, state, backend, targets, params):
s = 1.0 / math.sqrt(2.0)
u = torch.tensor([[s, s], [s, -s]], dtype=torch.complex64)
for t in targets:
state = _single_qubit_unitary(state, t, u, backend)
return state
class PauliXGate(IQuantumGate):
"""X = [[0,1],[1,0]]."""
@property
def name(self) -> str:
return "X"
def apply(self, state, backend, targets, params):
u = torch.tensor([[0, 1], [1, 0]], dtype=torch.complex64)
for t in targets:
state = _single_qubit_unitary(state, t, u, backend)
return state
class PauliYGate(IQuantumGate):
"""Y = [[0,-i],[i,0]]."""
@property
def name(self) -> str:
return "Y"
def apply(self, state, backend, targets, params):
u = torch.tensor([[0, -1j], [1j, 0]], dtype=torch.complex64)
for t in targets:
state = _single_qubit_unitary(state, t, u, backend)
return state
class PauliZGate(IQuantumGate):
"""Z = [[1,0],[0,-1]]."""
@property
def name(self) -> str:
return "Z"
def apply(self, state, backend, targets, params):
u = torch.tensor([[1, 0], [0, -1]], dtype=torch.complex64)
for t in targets:
state = _single_qubit_unitary(state, t, u, backend)
return state
class SGate(IQuantumGate):
"""S = [[1,0],[0,i]]."""
@property
def name(self) -> str:
return "S"
def apply(self, state, backend, targets, params):
u = torch.tensor([[1, 0], [0, 1j]], dtype=torch.complex64)
for t in targets:
state = _single_qubit_unitary(state, t, u, backend)
return state
class TGate(IQuantumGate):
"""T = [[1,0],[0,e^{i*pi/4}]]."""
@property
def name(self) -> str:
return "T"
def apply(self, state, backend, targets, params):
phase = complex(math.cos(math.pi / 4), math.sin(math.pi / 4))
u = torch.tensor([[1, 0], [0, phase]], dtype=torch.complex64)
for t in targets:
state = _single_qubit_unitary(state, t, u, backend)
return state
class RxGate(IQuantumGate):
"""Rx(theta) = exp(-i*theta/2 * X)."""
@property
def name(self) -> str:
return "Rx"
def apply(self, state, backend, targets, params):
theta = (params or {}).get("theta", 0.0)
c, s = math.cos(theta / 2.0), math.sin(theta / 2.0)
u = torch.tensor([[c, -1j * s], [-1j * s, c]], dtype=torch.complex64)
for t in targets:
state = _single_qubit_unitary(state, t, u, backend)
return state
class RyGate(IQuantumGate):
"""Ry(theta) = exp(-i*theta/2 * Y)."""
@property
def name(self) -> str:
return "Ry"
def apply(self, state, backend, targets, params):
theta = (params or {}).get("theta", 0.0)
c, s = math.cos(theta / 2.0), math.sin(theta / 2.0)
u = torch.tensor([[c, -s], [s, c]], dtype=torch.complex64)
for t in targets:
state = _single_qubit_unitary(state, t, u, backend)
return state
class RzGate(IQuantumGate):
"""Rz(theta) = exp(-i*theta/2 * Z)."""
@property
def name(self) -> str:
return "Rz"
def apply(self, state, backend, targets, params):
theta = (params or {}).get("theta", 0.0)
e_neg = complex(math.cos(theta / 2.0), -math.sin(theta / 2.0))
e_pos = complex(math.cos(theta / 2.0), math.sin(theta / 2.0))
u = torch.tensor([[e_neg, 0], [0, e_pos]], dtype=torch.complex64)
for t in targets:
state = _single_qubit_unitary(state, t, u, backend)
return state
class CNOTGate(IQuantumGate):
"""
CNOT: |ctrl tgt> -> |ctrl, ctrl XOR tgt>.
4x4 matrix (|00>,|01>,|10>,|11>):