-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinput_python.txt
More file actions
7523 lines (5942 loc) · 259 KB
/
Copy pathinput_python.txt
File metadata and controls
7523 lines (5942 loc) · 259 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
================================================================================
implementation/python/ -- PyTorch tensor-ops quantum simulator (Python 3.12+)
================================================================================
================================================================================
FILE: implementation/python/README.md
================================================================================
# implementation/python -- PyTorch state-vector quantum simulator
A pure-Python state-vector quantum-circuit simulator using PyTorch for
tensor ops and device-agnostic GPU acceleration. Sibling of
`implementation/c` (MPI) and `implementation/go` (goroutines), covering
the same thesis claims via a third parallelism model: tensor ops on
whatever device PyTorch can reach (NVIDIA CUDA, AMD ROCm, Apple Metal /
MPS), with a CPU fallback.
## Status
**Feature-complete.** The implementation covers the same thesis claims
as `/c` and `/go`:
- `qubit.Qreg` — state-vector register with construction, accessors,
the qubit-axis helper, memory preflight, and a CPU measurement RNG.
- `qubit.standart` — `gcd_u64`, `mod_pow`, `continued_fraction`,
`is_power_of_two`, `ilog2_u32`. Python builtins (`math.gcd`, `pow`,
`fractions.Fraction.limit_denominator`) wrapped with
`qubit:`-prefixed validation.
- Single-qubit gates — `apply_u` (the `tensordot` + `movedim`
workhorse) plus the named gates `apply_h`, `apply_x`, `apply_y`,
`apply_z`, `apply_s`, `apply_t`, `apply_phase`, `apply_rx`,
`apply_ry`, `apply_rz`.
- Controlled gates — `apply_cu` (4x4 block-diagonal workhorse via
permute + matmul + inverse-permute) plus `apply_cnot`, `apply_cz`,
`apply_controlled_phase`, `apply_swap` (the 3-CNOT identity).
- Multi-controlled gates — `apply_multi_controlled_z` for phase-flip
diffusion and `apply_multi_controlled_x` (generalised Toffoli),
both vectorized mask/gather/scatter; no per-amplitude loops.
- Measurement — `measure_qubit` (single-qubit projective with collapse
and renormalise), `measure_all` (sample full basis from `|amp|^2`),
`sample_distribution` (snapshot + restore so the original isn't
mutated), `clone` (independent amp + RNG state), `dump` (structured
list of non-zero amplitudes).
- QFT — `apply_qft` (forward, includes final bit-reversal swaps so
output is in natural binary order) and `apply_qft_inverse` (true
inverse via reversed loop order and negated phase angles, not three
forward applications). Sub-register support via `start=` / `n=`.
- Grover — `apply_grover(q, n_qubits, oracle, user=None,
iterations=None)`. The oracle is a `Callable[[Qreg, Any], None]`
that phase-flips marked basis states; the default iteration count
is the optimum for one marked item (`floor(pi/4 * sqrt(N))`).
- Shor — `apply_modular_exp` (vectorized permutation via
`torch.gather` with a CPU-built index tensor), `apply_shor_period`
(period-finding circuit), `shor_factor(N, max_attempts=20,
seed=None)` (end-to-end factoring, bit-for-bit reproducible when
seeded). v1 covers Shor-15 (13-qubit register: `n=4` target +
`t=2n+1=9` counting) and Shor-21 (16-qubit register: `n=5` + `t=11`,
gated by `RUN_SHOR_21=1` to keep the default test loop fast).
- `qubit-demo` CLI — `--algo {bell,qft,grover,shor}` for quick
algorithm-level smoke tests. Installed via `[project.scripts]`.
Function-style (`apply_h(q, 0)`) and method-style (`q.apply_h(0)`)
call shapes are both first-class for every gate, measurement op, QFT,
Grover, and Shor primitive.
**Tests:** the exact collected count is device-dependent because the
device-parametrised tests in `tests/conftest.py` expand once per
available backend. On the author's CPU + MPS host the count is
**414 default + 1 gated Shor-21 = 415 total**; on CPU-only CI runners
the MPS rows drop and the collected count is lower. All green on
every available device under `ruff check`, `mypy --strict`, and
pytest.
## Quickstart
The Makefile targets assume [`uv`](https://docs.astral.sh/uv/) is on
your path (it manages the venv and dev-tool installation). Without
`uv`, the same workflow runs through `pip install -e .[dev]` and your
preferred environment manager.
```bash
cd implementation/python
make sync # creates .venv, installs torch + dev tools
make test # ~0.5s on Apple Silicon
make check # lint + typecheck + test (the full PR gate)
make demo # default: bell
make demo ALGO=qft # QFT|0> = uniform
make demo ALGO=grover # Grover marks |1111>
make demo ALGO=shor # factor 15
RUN_SHOR_21=1 uv run pytest tests/test_shor.py -q # 16-qubit gated test
```
The CLI also runs directly: `uv run qubit-demo --algo shor`.
On many-core CPU-only hosts, PyTorch's default thread fan-out can be
counterproductive for the small tensor kernels these tests exercise.
If the gated Shor-21 path is slow or hangs, cap the thread count:
```bash
OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 \
RUN_SHOR_21=1 uv run pytest tests/test_shor.py -q
```
Apple Silicon / MPS does not need this.
## Key design choices
- **Device-agnostic via `torch.device`.** `Qreg(n_qubits)` auto-detects
`cuda` > `mps` > `cpu`. Override with `Qreg(n_qubits, device='cpu')`.
- **Tensor-native gates.** State is a flat `(2**n,)` complex tensor;
gate code reshapes into the `(2,) * n` view and `einsum`/`tensordot`
the unitary against the target axis. No per-amplitude loops.
- **Dtype policy.** `complex128` on CPU / CUDA / ROCm; `complex64` on
MPS (the MPS backend lacks `float64`, so `complex128` is impossible
there). Explicit `Qreg(..., device='mps', dtype=torch.complex128)`
raises `ValueError` with a guidance message; the simulator never
silently downgrades.
- **Qubit 0 is LSB.** Matches `/c` and `/go`. The tensor axis for
qubit `q` is `n_qubits - 1 - q`, centralised in `qubit/_axis.py`.
- **CPU measurement RNG.** Even when `_amp` lives on GPU, the
measurement RNG is a CPU `torch.Generator` — MPS-generator quirks
are real and measurement is a readout boundary anyway. Seeded tests
are bit-identical across CPU / CUDA / MPS.
- **No `destroy()` / `close()` / context manager.** Python's GC
reclaims PyTorch tensors when the `Qreg` goes out of scope. No
`with` block, no manual cleanup.
## API at a glance
```python
import math, torch
from qubit import Qreg, apply_h, apply_x, qubit_axis, shor_factor
# Auto-detect device + dtype.
q = Qreg(n_qubits=4)
print(q.device, q.dtype, q.n_qubits)
# Or explicit:
q = Qreg(4, device='cpu', seed=42, dtype=torch.complex128)
# Seeded measurement-RNG is reproducible across same-seed Qregs.
q.init_basis(5) # |0101>
print(q.prob_of(5)) # 1.0
print(q.norm()) # 1.0
# Gates: both function-style and method-style work.
q.apply_h(0) # method-style
apply_x(q, 1) # function-style
print(q.norm()) # still 1.0 (unitary)
# Custom unitary via apply_u (the workhorse every named gate dispatches to).
inv2 = 1.0 / math.sqrt(2.0)
h = torch.tensor(
[[inv2 + 0j, inv2 + 0j], [inv2 + 0j, -inv2 + 0j]],
dtype=q.dtype, device=q.device,
)
q.apply_u(2, h)
# Defensive CPU clone for inspection / cross-implementation comparison:
amps = q.amplitudes_copy() # 1-D CPU tensor, len 16
# Qubit-to-axis helper (used internally by every gate):
assert qubit_axis(0, 4) == 3 # qubit 0 is the LSB / rightmost axis
assert qubit_axis(3, 4) == 0 # qubit 3 is the MSB / leftmost axis
# End-to-end Shor.
result = shor_factor(15, seed=42)
print(result) # ShorFactorResult(p=3, q=5, attempts=1)
```
## Scope and known limitations
- **`shor_factor` does not detect prime powers** (`N = p**k` for prime
`p`, `k >= 2`). Such inputs make every quantum attempt fail the
factor-derivation check; the function exhausts `max_attempts` and
reports failure. The classical pre-check (`round(N**(1/k))**k ==
N`) belongs in the caller. Even `N` is handled here (short-
circuits without a quantum step). Matches `/c` and `/go` scope.
- **Shor-25 and beyond are not a v1 performance target.** At 25
qubits the modexp permutation tensor is 256 MiB (int64) on CPU
before transfer, and the gather output adds another 512 MiB. The
arithmetic is correct, but the memory cost is significant.
Shor-15 (13-qubit register: `n=4` + `t=9`) and Shor-21 (16-qubit
register: `n=5` + `t=11`) are the supported algorithm targets;
both run in well under a second on CPU.
- **MPS dtype is `complex64`, not `complex128`.** The MPS backend
lacks `float64`. `apply_modular_exp`'s permutation tensor and the
resulting gather output are unaffected (both int64 / complex64),
but precision-sensitive computations (e.g., very deep gate
sequences) accumulate rounding faster than on CPU/CUDA.
`amp_tol_for` and `prob_tol_for` return looser tolerances when
the register's dtype is `complex64`.
- **No CUDA testing in CI.** GitHub-hosted runners don't have GPUs.
The device-parametrised tests run CPU-only on CI; MPS coverage
comes from local runs on Apple Silicon.
## Layout
```
qubit/
__init__.py # public API re-exports
_axis.py # qubit_axis (LSB-first convention lives here)
_device.py # default_device, default_dtype, validate_dtype_device
_memory.py # estimate_state_bytes, estimate_peak_bytes, preflight
_assert.py # qubit:-prefixed ValueError/TypeError helpers
_view.py # state_view + validate_matrix (gate helpers)
qreg.py # Qreg class + method wrappers for every gate
standart.py # arithmetic helpers (gcd, mod_pow, continued_fraction, ...)
gates_single.py # apply_u + apply_h/x/y/z/s/t/phase/rx/ry/rz
gates_controlled.py # apply_cu + cnot/cz/controlled_phase/swap
gates_multi.py # apply_multi_controlled_z + apply_multi_controlled_x
measure.py # measure_qubit / measure_all / sample_distribution / clone / dump
qft.py # apply_qft + apply_qft_inverse (with bit-reversal swaps)
grover.py # apply_grover (uniform prep + oracle/diffusion iterations)
shor.py # apply_modular_exp + apply_shor_period + shor_factor
cli.py # qubit-demo CLI (argparse, exit codes, top-level catch)
tests/
conftest.py # device fixture (parametrises over available devices)
test_assert.py
test_axis.py
test_device.py
test_memory.py
test_qreg.py
test_standart.py
test_gates_single.py
test_gates_controlled.py
test_gates_multi.py
test_measure.py
test_qft.py
test_grover.py
test_shor.py
test_cli.py
test_import.py
pyproject.toml
Makefile
README.md
assessment.md # thesis-claim coverage map
```
The underscore-prefixed modules are package-private; external callers
should import only from `qubit` (the top-level `__init__.py`
re-exports the public surface).
The misspelled `standart.py` filename is deliberate parity with `/c`'s
2004 spelling and the `/go` sibling. The function names inside use
modern snake_case (`gcd_u64`, `mod_pow`, `continued_fraction`,
`is_power_of_two`, `ilog2_u32`); the `_u64` / `_u32` suffixes are
preserved as visual cues even though Python ints have no width limit.
## Cross-implementation parity
| Claim | This implementation | Sibling locations |
|---|---|---|
| LSB-first basis indexing | `qubit/_axis.py::qubit_axis` | `/go gates_single.go`, `/c parallel.c` |
| Tensor-native gates | `qubit/_view.py::state_view`, `gates_single.apply_u` | `/go parallelOverPairs`, `/c apply_u` |
| ModularExp via permutation | `qubit/shor.py::_build_modexp_perm` | `/go shor.go::_build_modexp_permutation`, `/c shor.c::apply_modular_exp` |
| QFT with bit-reversal swaps | `qubit/qft.py::apply_qft` | `/go qft.go::ApplyQFT`, `/c qft.c::apply_qft` |
| Continued-fraction recovery | `qubit/standart.py::continued_fraction` | `/go standart.go::ContinuedFraction`, `/c standart.c::continued_fraction` |
| Factor N=15 reliably | `tests/test_shor.py::test_shor_factor_15_*` | `/go shor_test.go`, `/c tests/test_shor.c` |
| Shor-21 gated by env var | `tests/test_shor.py::test_shor_period_a2_mod21_gated` | `/go shor_test.go::TestShorPeriodA2Mod21`, `/c tests/test_shor.c` |
See [`assessment.md`](./assessment.md) for the detailed file:line map.
## Sibling implementations
- [/c](../c) — MPI / OpenMPI 5.x. 26-qubit registers tested at NP=1..8.
- [/go](../go) — goroutines / per-call WaitGroup. 70 tests, race-clean.
================================================================================
FILE: implementation/python/assessment.md
================================================================================
# implementation/python — coverage of thesis claims
Updated at the end of Phase 9. File:line references point to the
canonical implementation site for each claim. Sibling implementations:
[`/c`](../c/assessment.md) (MPI) and [`/go`](../go/assessment.md)
(goroutines) cover the same claims via different parallelism models.
## §8 (sparse-gate strategy, 2026 thesis)
| Claim | Status | Location |
|---|---|---|
| Object-level in-place single-qubit gate, O(2^n) work | ✓ | `qubit/gates_single.py::apply_u` |
| State vector as a flat `(2^n,)` PyTorch tensor | ✓ | `qubit/qreg.py::Qreg._amp` |
| Tensor-native dispatch via `tensordot` + `movedim` | ✓ | `qubit/gates_single.py::apply_u` |
| Controlled gates via 4x4 block-diagonal CU | ✓ | `qubit/gates_controlled.py::apply_cu` |
| ModularExp as object-level in-place permutation via `torch.gather` | ✓ | `qubit/shor.py::apply_modular_exp` |
| qreg API per §12 | ✓ | `qubit/qreg.py::Qreg` |
**"In-place" caveat.** Object-level in-place: the `Qreg` instance is
reused across gate calls and the underlying tensor is reassigned. PyTorch
typically allocates a fresh output tensor for `tensordot`, `matmul`, and
`gather`, so transient peak memory is 2x to 4x the state-vector size
during a single gate (see `_memory.estimate_peak_bytes`). The sparse-gate
work is still O(2^n) per gate; we never materialise a 2^n x 2^n operator.
**Parallelism model.** Instead of MPI ranks (`/c`) or goroutines
(`/go`), this implementation routes work through PyTorch's tensor ops
on whatever device is available (NVIDIA CUDA, AMD ROCm, Apple Metal /
MPS, or CPU fallback). The "parallel dispatch" is PyTorch's kernel
scheduler; the simulator never has a `parallelOverPairs`-style
abstraction of its own.
## §9 (2026 QFT)
| Claim | Status | Location |
|---|---|---|
| QFT forward + inverse | ✓ | `qubit/qft.py::apply_qft` / `apply_qft_inverse` |
| Includes final bit-reversal swaps (natural binary order) | ✓ | `qubit/qft.py::apply_qft` final swap loop |
| Inverse is a TRUE inverse, not three forward applications | ✓ | `qubit/qft.py::apply_qft_inverse` (reverses loop order, negates phases) |
| Period detection on known periodic input | ✓ (tested) | `tests/test_qft.py::test_qft_on_basis_state_matches_analytic` |
| Round-trip exhaustively across basis states for n=1..4 | ✓ (tested) | `tests/test_qft.py::test_qft_then_qft_inverse_round_trip` |
## §10 (2026 Grover)
| Claim | Status | Location |
|---|---|---|
| Phase-oracle callback API | ✓ | `qubit/grover.py::apply_grover` (oracle: `Callable[[Qreg, Any], None]`) |
| H^n → oracle / diffusion loop | ✓ | `qubit/grover.py::apply_grover` |
| Diffusion via H X MCZ X H sandwich | ✓ | `qubit/grover.py::apply_grover` |
| Default iteration count = floor(π/4·√N) | ✓ | `qubit/grover.py::apply_grover` |
| Over-iteration drops probability (rotation reverses past π/2) | ✓ (tested) | `tests/test_grover.py::test_grover_over_iteration_drops_probability` |
| Multiple marked items (4 of 16 in 1 iter → P=1.0) | ✓ (tested) | `tests/test_grover.py::test_grover_four_marked_in_16_one_iteration` |
| n_qubits=1 degenerate case supported | ✓ (tested) | `tests/test_grover.py::test_grover_n_qubits_one_does_not_amplify_but_runs` |
## §11 (2026 Shor)
| Claim | Status | Location |
|---|---|---|
| `apply_modular_exp` with y >= N pass-through | ✓ | `qubit/shor.py::apply_modular_exp` |
| `apply_shor_period` (period-finding subroutine) | ✓ | `qubit/shor.py::apply_shor_period` |
| `shor_factor` (end-to-end with retry loop) | ✓ | `qubit/shor.py::shor_factor` |
| Continued-fraction post-processing | ✓ | `qubit/standart.py::continued_fraction` |
| Factor N=15 reliably with seed | ✓ (tested) | `tests/test_shor.py::test_shor_factor_15_seeded` |
| Even N short-circuit (no quantum step) | ✓ (tested) | `tests/test_shor.py::test_shor_factor_even_N_short_circuits` |
| Shor-21 period of 2 mod 21 (gated) | ✓ (gated) | `tests/test_shor.py::test_shor_period_a2_mod21_gated` |
| Reproducibility under seed | ✓ (tested) | `tests/test_shor.py::test_shor_factor_seeded_is_deterministic` |
**Scope caveat.** `shor_factor` does NOT detect prime powers
(`N = p**k` for prime `p`, `k >= 2`). Such inputs make every quantum
attempt fail the factor-derivation check; the function exhausts
`max_attempts` and reports failure. The classical pre-check belongs
in the caller. Matches `/c` and `/go` scope. Documented inline at
`qubit/shor.py::shor_factor` docstring.
## §12 (qreg API)
Every entry in spec §6 is implemented in `qubit/qreg.py` + the
adjacent gate / measurement / algorithm files. Python-specific
deviations from the abstract API:
- **No `Destroy()` / `close()` / context manager.** Python's GC
reclaims PyTorch tensors when the `Qreg` goes out of scope.
- **Method wrappers for every state-mutating function.** `q.apply_h(0)`
reads more naturally for method-chaining; `apply_h(q, 0)` matches
the lower-level function signature. Both are public.
- **Amplitude slice is unexported (`_amp`).** Accessors are
`amplitude(i)`, `amplitudes_copy()`, `prob_of(basis)`, `norm()`.
- **Functional options at construction.** `Qreg(n, *, device=None,
seed=None, dtype=None, check_memory=True)`. `None` triggers
auto-detection per the device/dtype policy.
- **Programmer-error panics use `ValueError` / `TypeError` with the
`qubit:` prefix.** Same uniform-exception policy across the package;
no `panic`-vs-`error` split as in `/go`. Library code never calls
`sys.exit`; the CLI (`qubit/cli.py`) catches at the top level and
exits non-zero.
## Out of scope for v1
- Distributed execution across machines (would re-introduce MPI's
problem space; outside the GPU-tensor-ops premise).
- Density matrices / mixed states.
- Noise models.
- Prime-power detection in `shor_factor` (classical pre-check; matches
`/c` and `/go`).
- Shor-25 and beyond as a routine target (the modexp permutation
tensor at 25 qubits is 256 MiB on CPU before transfer; the gather
output is another 512 MiB. The arithmetic is correct, but the
memory cost is significant. Shor-15 and Shor-21 are the supported
algorithm targets.)
## Test matrix
`uv run pytest -q` covers **414 active tests** in well under a second on
Apple Silicon (`make check` adds `ruff` and `mypy --strict`). The
gated Shor-21 test brings the total to **415** via `RUN_SHOR_21=1`
and runs the 16-qubit
period-finding circuit with fixed `a=2`; the only stochasticity is
the QFT-readout measurement, so the test asserts the recovered
period divides 6 (the true order of 2 mod 21).
Device coverage on this Apple Silicon host: CPU + MPS via the
parametrised `device` fixture in `tests/conftest.py`. CI runs Linux
CPU-only.
## CLI
The `qubit-demo` console script is exposed via
`[project.scripts] qubit-demo = "qubit.cli:main"` in `pyproject.toml`.
It mirrors the demos in `/c`'s `cmd/qubit` and `/go`'s
`cmd/qubit/main.go`:
```bash
uv run qubit-demo --algo bell
uv run qubit-demo --algo qft
uv run qubit-demo --algo grover
uv run qubit-demo --algo shor
```
All four demos are seeded where applicable so successive runs produce
identical output. Demo errors print to stderr with a `qubit-demo:`
prefix and the process exits non-zero.
================================================================================
FILE: implementation/python/Makefile
================================================================================
# ---------------------------------------------------------------------------
# Makefile for implementation/python -- PyTorch state-vector quantum simulator.
#
# Targets:
# make sync uv sync --group dev (install/refresh .venv)
# make test uv run pytest (full test suite)
# make test-cpu PYTORCH_DISABLE_MPS=1 ... (force CPU even on Apple Silicon)
# make lint uv run ruff check .
# make format uv run ruff format .
# make typecheck uv run mypy qubit tests
# make check lint + typecheck + test (the standard PR gate)
# make demo ALGO=bell|qft|grover|shor
# uv run qubit-demo --algo $(ALGO)
# make clean rm -rf .venv .pytest_cache .ruff_cache .mypy_cache
#
# The implementation/python module is managed by `uv`; the Makefile is a
# thin convenience wrapper. Most one-off operations can use `uv run <tool>`
# directly.
# ---------------------------------------------------------------------------
ALGO ?= bell
.PHONY: sync test test-cpu lint format typecheck check demo clean
sync:
uv sync --group dev
test:
uv run pytest
test-cpu:
PYTORCH_DISABLE_MPS=1 CUDA_VISIBLE_DEVICES= uv run pytest
lint:
uv run ruff check .
format:
uv run ruff format .
typecheck:
uv run mypy qubit tests
check: lint typecheck test
demo:
uv run qubit-demo --algo $(ALGO)
clean:
rm -rf .venv .pytest_cache .ruff_cache .mypy_cache build dist *.egg-info
================================================================================
FILE: implementation/python/pyproject.toml
================================================================================
[project]
name = "qubit"
version = "0.1.0"
description = "PyTorch state-vector quantum simulator (sparse-gate sibling of /c MPI and /go goroutines)"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"torch>=2.4",
]
[project.scripts]
qubit-demo = "qubit.cli:main"
[dependency-groups]
dev = [
"pytest>=8.0",
"ruff>=0.6",
"mypy>=1.11",
]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[tool.hatch.build.targets.wheel]
packages = ["qubit"]
# ---- ruff -----------------------------------------------------------------
[tool.ruff]
target-version = "py312"
line-length = 100
[tool.ruff.lint]
select = [
"E", # pycodestyle errors
"F", # pyflakes
"I", # isort
"N", # pep8-naming
"UP", # pyupgrade
"B", # flake8-bugbear
"W", # pycodestyle warnings
]
[tool.ruff.lint.per-file-ignores]
# Package initialisation installs a narrow PyTorch optional-NumPy warning
# filter before importing torch-backed modules.
"qubit/__init__.py" = ["E402"]
# Tests touch the private _amp/_n/_gen fields by design (same-package
# inspection of internal state). Allow underscore-prefix access there.
# Also allow uppercase N in test names and local variables -- Shor's
# algorithm uses uppercase N (the modulus) everywhere in math
# literature, and keeping the convention in tests makes the math-to-
# code traceability obvious.
"tests/*" = ["SLF001", "N802", "N803", "N806"]
# Shor's algorithm uses uppercase `N` (the modulus) universally in
# the math literature; keeping the convention in code makes the
# math-to-code traceability obvious. Same for qreg.py's Shor method
# wrappers which thread `N` through to qubit.shor.
"qubit/shor.py" = ["N803"]
"qubit/qreg.py" = ["N803"]
# ---- mypy -----------------------------------------------------------------
[tool.mypy]
python_version = "3.12"
strict = true
warn_unused_ignores = true
ignore_missing_imports = false
[[tool.mypy.overrides]]
# PyTorch's type stubs are partial; some return types come back as Any.
# Allow that without burning the strict-mode budget elsewhere.
module = "torch.*"
ignore_missing_imports = true
follow_imports = "skip"
[[tool.mypy.overrides]]
# Tests are less strict about Any everywhere.
module = "tests.*"
disallow_untyped_decorators = false
disallow_any_explicit = false
# ---- pytest ---------------------------------------------------------------
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = ["-ra", "--strict-markers"]
================================================================================
FILE: implementation/python/qubit/__init__.py
================================================================================
"""qubit: PyTorch state-vector quantum-circuit simulator.
Sibling of ``implementation/c`` (MPI) and ``implementation/go``
(goroutines). The PyTorch backend gives device-agnostic GPU support:
the same code runs on NVIDIA CUDA, AMD ROCm, Apple Metal (MPS), and CPU.
Through Phase 8 this ships: the data model (:class:`Qreg` construction,
accessors, the qubit-axis helper), the ``standart`` arithmetic helpers
(gcd, mod_pow, continued_fraction, is_power_of_two, ilog2_u32), the
single-qubit gate primitives (``apply_u`` plus the standard named
gates), the controlled and multi-controlled gates (``apply_cu`` /
``apply_cnot`` / ``apply_cz`` / ``apply_controlled_phase`` /
``apply_swap`` / ``apply_multi_controlled_z`` /
``apply_multi_controlled_x``), the measurement primitives
(``measure_qubit`` / ``measure_all`` / ``sample_distribution`` /
``clone`` / ``dump``), the Quantum Fourier Transform
(``apply_qft`` / ``apply_qft_inverse``), Grover's amplitude
amplification (``apply_grover``), and Shor's algorithm
(``apply_modular_exp`` / ``apply_shor_period`` / ``shor_factor``), and
the ``qubit-demo`` CLI (``qubit.cli``).
Public API surface:
* :class:`Qreg` -- the state-vector register class with methods for
every gate (``q.apply_h(0)``).
* Function-style gate equivalents (``apply_h(q, 0)``) re-exported from
:mod:`qubit.gates_single`. Both shapes are first-class.
* :func:`qubit_axis` -- the LSB-first qubit-to-tensor-axis helper.
* Arithmetic helpers from :mod:`qubit.standart`:
:func:`gcd_u64`, :func:`mod_pow`, :func:`continued_fraction`,
:func:`is_power_of_two`, :func:`ilog2_u32`.
* Numerical-tolerance constants ``AMP_TOL_C64`` / ``AMP_TOL_C128`` /
``PROB_TOL_C64`` / ``PROB_TOL_C128`` plus the dtype-keyed helpers
``amp_tol_for`` and ``prob_tol_for`` for test-side use.
"""
from __future__ import annotations
import warnings
# PyTorch warns when its optional NumPy bridge cannot initialize. The
# simulator does not use NumPy, so suppress only this known optional-bridge
# warning while leaving all other PyTorch warnings visible.
warnings.filterwarnings(
"ignore",
message=r"Failed to initialize NumPy: No module named 'numpy'.*",
category=UserWarning,
)
from ._axis import qubit_axis
from .gates_controlled import (
apply_cnot,
apply_controlled_phase,
apply_cu,
apply_cz,
apply_swap,
)
from .gates_multi import (
apply_multi_controlled_x,
apply_multi_controlled_z,
)
from .gates_single import (
apply_h,
apply_phase,
apply_rx,
apply_ry,
apply_rz,
apply_s,
apply_t,
apply_u,
apply_x,
apply_y,
apply_z,
)
from .grover import apply_grover
from .measure import (
clone,
dump,
measure_all,
measure_qubit,
sample_distribution,
)
from .qft import (
apply_qft,
apply_qft_inverse,
)
from .qreg import (
AMP_TOL_C64,
AMP_TOL_C128,
PROB_TOL_C64,
PROB_TOL_C128,
Qreg,
amp_tol_for,
prob_tol_for,
)
from .shor import (
ShorFactorResult,
ShorPeriodResult,
apply_modular_exp,
apply_shor_period,
shor_factor,
)
from .standart import (
continued_fraction,
gcd_u64,
ilog2_u32,
is_power_of_two,
mod_pow,
)
__all__ = [
"AMP_TOL_C128",
"AMP_TOL_C64",
"PROB_TOL_C128",
"PROB_TOL_C64",
"Qreg",
"ShorFactorResult",
"ShorPeriodResult",
"amp_tol_for",
"apply_cnot",
"apply_controlled_phase",
"apply_cu",
"apply_cz",
"apply_grover",
"apply_h",
"apply_modular_exp",
"apply_multi_controlled_x",
"apply_multi_controlled_z",
"apply_phase",
"apply_qft",
"apply_qft_inverse",
"apply_rx",
"apply_ry",
"apply_rz",
"apply_s",
"apply_shor_period",
"apply_swap",
"apply_t",
"apply_u",
"apply_x",
"apply_y",
"apply_z",
"clone",
"continued_fraction",
"dump",
"gcd_u64",
"ilog2_u32",
"is_power_of_two",
"measure_all",
"measure_qubit",
"mod_pow",
"prob_tol_for",
"qubit_axis",
"sample_distribution",
"shor_factor",
]
================================================================================
FILE: implementation/python/qubit/_assert.py
================================================================================
"""Programmer-error validation helpers.
Every exception raised by the `qubit` package carries a ``"qubit: "``
prefix so callers can identify simulator-originated errors at a glance
without inspecting tracebacks. Construction-time and gate preconditions
both flow through these helpers; the CLI catches at the top level.
"""
from __future__ import annotations
def raise_value(cond: bool, fmt: str, *args: object) -> None:
"""Raise ``ValueError`` with ``"qubit: " + fmt % args`` if ``cond`` is False.
Used at the top of every public method for programmer-error
preconditions (out-of-range qubit indices, control == target, etc.).
Construction-time input validation (bad ``n_qubits``) goes through the
same helper. There is no separate ``panic`` vs ``error`` split as in
/go; Python's exception model is uniform across both layers.
"""
if not cond:
raise ValueError("qubit: " + fmt % args)
def raise_type(cond: bool, fmt: str, *args: object) -> None:
"""Raise ``TypeError`` with ``"qubit: " + fmt % args`` if ``cond`` is False.
Reserved for type-shape failures (caller passed a non-tensor where a
tensor was expected, etc.). Value-domain failures use
:func:`raise_value` so the exception class signals which axis of the
contract was violated.
"""
if not cond:
raise TypeError("qubit: " + fmt % args)
================================================================================
FILE: implementation/python/qubit/_axis.py
================================================================================
"""Qubit-to-tensor-axis mapping.
The flat amplitude vector ``q._amp`` is indexed by basis state with the
same convention as ``/c`` and ``/go``: **qubit 0 is the least significant
bit** of the basis index. For a 3-qubit register, the state
``|q2 q1 q0>`` corresponds to ``amp[4*q2 + 2*q1 + q0]``.
When a gate function reshapes the flat vector to the n-D view
``(2,) * n_qubits`` for einsum/tensordot, the tensor axis corresponding
to qubit ``q`` is :func:`qubit_axis` ``= n_qubits - 1 - q`` (so qubit 0
lives on the rightmost / fastest-varying axis). This module is the single
home of that conversion; gates call it instead of recomputing
``n - 1 - q`` ad hoc, so a silent endian flip cannot be introduced one
gate at a time.
"""
from __future__ import annotations
from ._assert import raise_value
def qubit_axis(target: int, n_qubits: int) -> int:
"""Return the tensor-axis index corresponding to qubit ``target``.
For the ``(2,) * n`` reshape view of a flat ``2**n``-amplitude state
vector, qubit 0 lives on axis ``n - 1`` (LSB, fastest-varying),
qubit 1 on axis ``n - 2``, ..., qubit ``n - 1`` on axis 0 (MSB).
Raises :class:`ValueError` if ``target`` is not in ``[0, n_qubits)``.
"""
raise_value(
0 <= target < n_qubits,
"qubit_axis: target=%d out of [0, %d)",
target,
n_qubits,
)
return n_qubits - 1 - target
================================================================================
FILE: implementation/python/qubit/_device.py
================================================================================
"""Device selection and dtype policy.
The simulator is device-agnostic: the same source runs on NVIDIA CUDA,
AMD ROCm (uses the CUDA API surface), Apple Metal (MPS), and CPU. The
caller picks a device at :class:`Qreg` construction; this module handles
the default-detection (cuda > mps > cpu) and enforces the one
hardware-driven dtype constraint:
* PyTorch's MPS backend does not support ``float64``, and therefore
cannot support ``complex128`` (whose real/imag components are
float64). Calling ``Qreg(..., device='mps', dtype=torch.complex128)``
must raise rather than silently downgrade. Auto-detect picks the
right dtype per device when ``dtype=None``.
"""
from __future__ import annotations
import torch
from ._assert import raise_value
def default_device() -> torch.device:
"""Pick the best available device: cuda > mps > cpu."""
if torch.cuda.is_available():
return torch.device("cuda")
if torch.backends.mps.is_available():
return torch.device("mps")
return torch.device("cpu")
def default_dtype(device: torch.device) -> torch.dtype:
"""Highest-precision complex dtype the device supports.
MPS lacks float64, so its complex peak is complex64. Everywhere else
(CPU, CUDA, ROCm) defaults to complex128 for parity with /c and /go.
"""
if device.type == "mps":
return torch.complex64
return torch.complex128
def validate_dtype_device(device: torch.device, dtype: torch.dtype) -> None:
"""Raise ValueError if (device, dtype) is unsupportable.
Currently the only banned combination is MPS + complex128. The error
message tells the caller exactly which two options they have:
move to CPU for double precision, or accept complex64 on MPS.
"""
raise_value(
dtype in (torch.complex64, torch.complex128),
"validate_dtype_device: dtype=%s must be complex64 or complex128",
dtype,
)
if device.type == "mps" and dtype == torch.complex128:
raise ValueError(
"qubit: MPS backend does not support complex128 "
"(requires float64, which MPS lacks). "
"Use device='cpu' for double precision, "
"or dtype=torch.complex64 to stay on MPS."
)
def coerce_device(device: torch.device | str | None) -> torch.device:
"""Normalise the caller's ``device`` argument to a ``torch.device``.
``None`` triggers :func:`default_device`; strings (``"cpu"``,
``"cuda:0"``, ``"mps"``) are passed through ``torch.device(...)``.
A ready-made ``torch.device`` is returned unchanged.
"""
if device is None:
return default_device()
if isinstance(device, str):
return torch.device(device)
return device
================================================================================
FILE: implementation/python/qubit/_memory.py
================================================================================
"""Memory preflight helpers.
PyTorch will happily attempt ``torch.zeros(2**40, dtype=complex128)`` and
fail with a low-level runtime error (especially unfriendly on MPS, where
device memory is shared with the host OS). We estimate the peak working
set for a requested operation before allocating and reject obviously-
impossible requests with a clear ``MemoryError``.
Two layers of check:
1. A **sanity ceiling** (1 TiB) applied regardless of device. Catches
``n_qubits >= 36`` requests that cannot fit any consumer hardware.
2. A **device-specific free-memory check** when PyTorch exposes one
(currently CUDA only via ``torch.cuda.mem_get_info``). MPS and CPU
have no portable free-memory query in stable PyTorch, so the check
becomes a no-op on those devices and the sanity ceiling is the only
gate.
Power users can opt out by passing ``check_memory=False`` to
:class:`Qreg`. The preflight is best-effort and not a substitute for
catching ``RuntimeError`` from allocation; it just narrows the cliff.
"""
from __future__ import annotations
from typing import Literal
import torch
# Bytes per amplitude for each supported complex dtype.
_DTYPE_BYTES: dict[torch.dtype, int] = {
torch.complex64: 8,
torch.complex128: 16,
}
# Sanity ceiling applied regardless of device. 1 TiB is bigger than any
# consumer GPU (NVIDIA H100 = 80 GiB, M3 Ultra = 192 GiB), so any state
# tensor that exceeds this is unambiguously a bug in the caller's
# parameters rather than a legitimate hardware target.
_SANITY_CEILING: int = 1 << 40 # 1 TiB
# Op tags used by estimate_peak_bytes. State is the baseline (one tensor);
# single_gate / controlled_gate / qft are upper bounds on the transient
# tensors PyTorch allocates during a gate (tensordot / matmul intermediates
# plus an output state vector); modexp allocates a second state tensor and
# an int64 permutation tensor (per spec §5.5).
_Op = Literal["state", "modexp", "qft", "single_gate", "controlled_gate"]
def dtype_bytes(dtype: torch.dtype) -> int:
"""Bytes per amplitude for ``dtype``. Raises on unsupported dtypes."""
try:
return _DTYPE_BYTES[dtype]
except KeyError as exc:
raise ValueError(
f"qubit: dtype_bytes: unsupported dtype {dtype} "
"(expected torch.complex64 or torch.complex128)"
) from exc
def estimate_state_bytes(n_qubits: int, dtype: torch.dtype) -> int:
"""Bytes for a single state-vector tensor of ``2**n_qubits`` amplitudes."""
if n_qubits < 1:
raise ValueError(
f"qubit: estimate_state_bytes: n_qubits={n_qubits} must be >= 1"
)
return (1 << n_qubits) * dtype_bytes(dtype)
def estimate_peak_bytes(
n_qubits: int, dtype: torch.dtype, op: _Op = "state"
) -> int:
"""Peak working-set bytes for ``op`` at the given size and dtype.
* ``"state"`` -- one state vector. Baseline; matches
:func:`estimate_state_bytes`.
* ``"single_gate"`` -- ``2 * state``. A single-qubit gate via
:func:`qubit.gates_single.apply_u` runs ``tensordot`` + ``movedim``,
which allocates a fresh output state vector alongside the source.
* ``"controlled_gate"`` -- ``4 * state``. Controlled-U via permute +
reshape + matmul + reshape + inverse-permute can hold the source,
the permuted view, a 2x2-block matmul output, and the unpermuted
result transiently.
* ``"qft"`` -- ``4 * state``. The QFT decomposes into Hadamards,
controlled-phase gates, and SWAPs; the controlled-phase steps
drive the peak. Treated as an upper bound on a single QFT gate;
a long QFT sequence releases each transient before the next.
* ``"modexp"`` -- ``2 * state + 2 * int64_permutation``. ModularExp
allocates a fresh state vector from the gather and holds both a
CPU-side and a device-side copy of the permutation index tensor
transiently (the CPU copy is alive until ``.to(device)`` returns).
"""
state = estimate_state_bytes(n_qubits, dtype)
if op == "state":
return state
if op == "single_gate":
return 2 * state
if op == "controlled_gate":
return 4 * state
if op == "qft":
return 4 * state
if op == "modexp":
perm = (1 << n_qubits) * 8 # int64
return 2 * state + 2 * perm
raise ValueError(f"qubit: estimate_peak_bytes: unknown op={op!r}")
def free_bytes(device: torch.device) -> int | None:
"""Best-effort free memory in bytes for ``device``.
Returns ``None`` if PyTorch does not expose a free-memory query for
the device kind. Currently CUDA exposes one via
``torch.cuda.mem_get_info``; MPS and CPU do not have a portable