hachem.wtf
aboutsummaryrefslogtreecommitdiff
path: root/README.md
blob: cd103aa7ae4bf71d46ffe92a1c18eccd133786f6 (plain)
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
# $\psi$

psi is a quantum circuit simulator that runs on your cpu.

## gates

all the usual clifford gates are there: h, x, y, z and s on one qubit, cnot, cz and swap on two, and toffoli (ccnot) and fredkin (cswap) on three. past the clifford set you get t, the daggered versions of s and t, $\sqrt{X}$ and its inverse, rotations $R_x(\theta)$, $R_y(\theta)$ and $R_z(\theta)$, the phase gate $P(\theta)$, the general unitaries $U_1$, $U_2$ and $U_3$, and controlled versions of the three rotations and the phase gate. each one is a function named after the gate, so `psi_apply_h`, `psi_apply_cnot`, `psi_apply_sdg`, `psi_apply_crz` and so on.

if what you need isn't in there, you can make your own gate, either straight from a unitary matrix or by chaining some of the built-in gates (h, x, y, z, s, t, cnot, cz, swap, ccnot and cswap) into a composite.

you can add measurements with `psi_measure` or `psi_measure_all`. they show up when you print or draw the circuit, but the simulator doesn't collapse the state on them yet.

## running circuits

how a circuit gets computed is up to you. a `struct PsiRuntimeConfig` has four switches you can flip in any combination.

`batched` groups runs of single-qubit gates on the same qubit and multiplies them into one matrix, which usually cuts the number of kernels by 30 to 50 percent. `structure_aware` goes further. it works out which gates are diagonal or controlled, figures out what commutes with what, reorders and fuses until nothing else will merge, and groups what's left into layers that can run side by side. `simd` picks avx-512, avx2 with fma, or neon depending on what your cpu supports, and falls back to plain scalar code if there's nothing. that check happens at runtime. `parallel` splits the state vector across threads, but only once the circuit has at least `parallel_threshold` qubits (8 by default), so small circuits stay on one thread.

if you'd rather not set flags by hand, `enum PsiRuntime` has presets. `PSI_RUNTIME_BASIC` does direct simulation, `PSI_RUNTIME_BATCHED` adds batching, `PSI_RUNTIME_SIMD` is batching plus simd, and `PSI_RUNTIME_STRUCTURE_AWARE` is structure-aware plus simd. each one has an `_MT` twin that turns threading on. `psi_optimal_runtime_config()` gives you structure-aware, simd and threads together, and plain `psi_compute_circuit` uses the basic runtime.

threading uses pthreads on macos and linux. windows doesn't have a threading backend yet, so parallel runtimes just run on one thread there.

## noise

for noise you move from a state vector to a density matrix and apply kraus channels to it. the built-in channels are depolarising, bit flip, phase flip and bit-phase flip, which each take an error probability, plus amplitude damping for $T_1$ energy loss, generalised amplitude damping for the finite-temperature version of that, and phase damping for $T_2$ dephasing. they're all named `psi_<name>_channel`. if none of those fit, you can put together your own from kraus operators with `psi_new_kraus_operator` and `psi_new_noise_channel`. once noise is applied you can read off the trace, purity, measurement probabilities, and fidelity against a pure state.

## looking at circuits

`psi_print_circuit` writes out the list of operations and, if the circuit has been computed, its non-zero amplitudes. for an actual picture, `psi_render_circuit_horizontal` and `psi_render_circuit_vertical` draw the circuit in ascii and hand you back a string that you `free()` yourself. matrices and vectors have their own printers too, `psi_print_matrix` and `psi_print_vector`.

## building

you'll need a c17 compiler (clang or gcc), [premake5](https://premake.github.io/) and make.

```bash
premake5 gmake
make config=release
```

that leaves `libpsi.a` and the `tester` binary in `bin/release-macosx/`, or whichever folder matches your configuration and platform. the configurations are debug, release and dist. on windows, run `premake5 vs2022` to get a visual studio solution instead. `premake5 clean` wipes everything the build produced.

to use psi from your own code, add `include/` to your include path, include `psi.h`, and link against `libpsi.a` and libm (and pthreads on linux):

```bash
cc -std=c17 -Iinclude main.c bin/release-macosx/libpsi.a -lm -o main
```

## a quick example

here's a three-qubit ghz state, computed with the fastest settings available:

```c
#include <stdio.h>

#include "psi.h"

int main(void)
{
    struct PsiQuantumCircuit circuit = psi_new_quantum_circuit(3);

    // build a ghz state
    psi_apply_h(&circuit, 0);
    psi_apply_cnot(&circuit, 0, 1);
    psi_apply_cnot(&circuit, 0, 2);

    // execute with optimal settings
    psi_compute_circuit_with_config(&circuit, psi_optimal_runtime_config());

    psi_print_circuit(&circuit, stdout);

    psi_free_quantum_circuit(&circuit);
    return 0;
}
```

which prints

```
QuantumCircuit (3 qubits, 0 classical)
Operations:
  0: H on [0]
  1: CNOT on [0, 1]
  2: CNOT on [0, 2]
State:
  |000⟩: ¹⁄√2
  |111⟩: ¹⁄√2
```

## more examples

picking your own runtime looks like this. you start from an empty config, switch on what you want, and read the probabilities back afterwards:

```c
struct PsiQuantumCircuit circuit = psi_new_quantum_circuit(8);
// ... add gates ...

// combine features as needed
struct PsiRuntimeConfig config = psi_new_runtime_config();
config.structure_aware = true;
config.simd = true;
config.parallel = true;

const struct PsiVector* state = psi_compute_circuit_with_config(&circuit, config);

// or use a predefined runtime
// psi_compute_circuit_with(&circuit, PSI_RUNTIME_SIMD_MT);

double probabilities[1 << 8];
psi_circuit_probabilities(&circuit, probabilities);
```

parametric gates take their angles as extra arguments:

```c
const double pi = 3.14159265358979323846;

psi_apply_rx(&circuit, 0, pi / 4.0);      // rotation around x
psi_apply_ry(&circuit, 0, pi / 3.0);      // rotation around y
psi_apply_rz(&circuit, 1, pi / 2.0);      // rotation around z
psi_apply_crz(&circuit, 0, 1, pi / 4.0);  // controlled-rz
```

custom gates come from either a list of operations or a row-major matrix, and get applied to whichever qubits you hand them:

```c
// from operations
struct PsiCompositeGateOp bell_ops[] = {
    { PSI_OP_H, { 0 }, 1 },
    { PSI_OP_CNOT, { 0, 1 }, 2 },
};
struct PsiCustomGate bell = psi_new_custom_gate_from_composite("BELL", 2, bell_ops, 2);

// from a unitary matrix
struct PsiCustomGate sqrt_x = psi_new_custom_gate_from_matrix(
        "SQRT_X", psi_matrix(2, 2, psi_new_complex(0.5, 0.5), psi_new_complex(0.5, -0.5),
                             psi_new_complex(0.5, -0.5), psi_new_complex(0.5, 0.5)));

size_t bell_targets[] = { 0, 1 };
psi_apply_custom(&circuit, bell, bell_targets, 2);

size_t sqrt_x_targets[] = { 2 };
psi_apply_custom(&circuit, sqrt_x, sqrt_x_targets, 1);
```

and for noise, you turn a computed state into a density matrix and work on that:

```c
struct PsiQuantumCircuit circuit = psi_new_quantum_circuit(1);
psi_apply_h(&circuit, 0);
const struct PsiVector* state = psi_compute_circuit(&circuit);

// create a density matrix from the circuit state
struct PsiDensityMatrix dm = psi_new_density_matrix_from_state(state->data, state->size);

// apply noise to qubit 0
struct PsiNoiseChannel noise = psi_depolarising_channel(0.05);
psi_apply_noise_channel(&dm, noise, 0);

// check properties
printf("purity: %f\n", psi_purity_density_matrix(dm));  // 1.0 = pure, < 1.0 = mixed
printf("fidelity: %f\n", psi_fidelity_density_matrix(dm, state->data));

psi_free_noise_channel(&noise);
psi_free_density_matrix(&dm);
psi_free_quantum_circuit(&circuit);
```

## who frees what

everything is a plain struct passed around by value, and anything you create with a `psi_new_` function has a `psi_free_` partner that takes a pointer to it. noise channels and density matrices are yours to free.

the state vector you get back from `psi_compute_circuit` and friends is the exception. it belongs to the circuit, so don't free it. it's cached until you add another gate, and it stays valid until you reset or free the circuit.

custom gates need a bit of care. `psi_new_custom_gate_from_matrix` takes over the matrix you pass in, and `psi_apply_custom` takes over the gate, which then gets freed along with the circuit. so make a fresh custom gate every time you apply one rather than reusing the same one.

## caveats

psi is still under active development, so expect the api to keep moving. the avx2 and avx-512 paths also haven't been run on real x86 hardware yet. so far only the neon path has.

## license

psi is licensed under the apache license, version 2.0, so you're free to use, modify and distribute it as long as you keep the attribution. contributions, improvements and research collaborations are all welcome. the full terms are in [LICENSE](LICENSE).