-
Notifications
You must be signed in to change notification settings - Fork 103
Expand file tree
/
Copy pathgf2_multiplication_test.py
More file actions
342 lines (265 loc) · 12.1 KB
/
gf2_multiplication_test.py
File metadata and controls
342 lines (265 loc) · 12.1 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
# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import itertools
import numpy as np
import pytest
from galois import GF, Poly
import qualtran.testing as qlt_testing
from qualtran import QGF
from qualtran.bloqs.gf_arithmetic.gf2_multiplication import (
_gf2_multiplication_symbolic,
_gf16_multiplication,
BinaryPolynomialMultiplication,
GF2MulK,
GF2Multiplication,
GF2MulViaKaratsuba,
GF2ShiftRight,
MultiplyPolyByOnePlusXk,
SynthesizeLRCircuit,
)
from qualtran.resource_counting import get_cost_value, QECGatesCost
from qualtran.resource_counting.generalizers import ignore_alloc_free, ignore_split_join
from qualtran.testing import assert_consistent_classical_action
def test_gf16_multiplication(bloq_autotester):
bloq_autotester(_gf16_multiplication)
def test_gf2_multiplication_symbolic(bloq_autotester):
bloq_autotester(_gf2_multiplication_symbolic)
@pytest.mark.parametrize('m', [2, 4, 6, 8])
def test_synthesize_lr_circuit(m: int):
matrix = GF2Multiplication(m).reduction_matrix_q
bloq = SynthesizeLRCircuit(matrix)
bloq_adj = bloq.adjoint()
QGFM, GFM = QGF(2, m), GF(2**m)
for i in GFM.elements:
bloq_out = bloq.call_classically(q=np.array(QGFM.to_bits(i)))[0]
bloq_adj_out = bloq_adj.call_classically(q=bloq_out)[0]
assert isinstance(bloq_adj_out, np.ndarray)
assert i == QGFM.from_bits([*bloq_adj_out])
@pytest.mark.slow
@pytest.mark.parametrize('m', [3, 4, 5])
def test_synthesize_lr_circuit_slow(m):
matrix = GF2Multiplication(m).reduction_matrix_q
bloq = SynthesizeLRCircuit(matrix)
bloq_adj = bloq.adjoint()
QGFM, GFM = QGF(2, m), GF(2**m)
for i in GFM.elements:
bloq_out = bloq.call_classically(q=np.array(QGFM.to_bits(i)))[0]
bloq_adj_out = bloq_adj.call_classically(q=bloq_out)[0]
assert isinstance(bloq_adj_out, np.ndarray)
assert i == QGFM.from_bits([*bloq_adj_out])
def test_gf2_plus_equal_prod_classical_sim_quick():
m = 2
bloq = GF2Multiplication(m, plus_equal_prod=True)
GFM = GF(2**m)
assert_consistent_classical_action(bloq, x=GFM.elements, y=GFM.elements, result=GFM.elements)
@pytest.mark.slow
def test_gf2_plus_equal_prod_classical_sim():
m = 3
bloq = GF2Multiplication(m, plus_equal_prod=True)
GFM = GF(2**m)
assert_consistent_classical_action(bloq, x=GFM.elements, y=GFM.elements, result=GFM.elements)
def test_gf2_multiplication_classical_sim_quick():
m = 2
bloq = GF2Multiplication(m, plus_equal_prod=False)
GFM = GF(2**m)
assert_consistent_classical_action(bloq, x=GFM.elements, y=GFM.elements)
@pytest.mark.slow
@pytest.mark.parametrize('m', [3, 4, 5])
def test_gf2_multiplication_classical_sim(m):
bloq = GF2Multiplication(m, plus_equal_prod=False)
GFM = GF(2**m)
assert_consistent_classical_action(bloq, x=GFM.elements, y=GFM.elements)
@pytest.mark.parametrize('m_x', [Poly.Degrees([2, 1, 0]), Poly.Degrees([3, 1, 0])])
def test_multiply_by_constant_mod_classical_action(m_x):
n = len(m_x.coeffs) - 1
gf = GF(2, n, irreducible_poly=m_x)
QGFM = QGF(2, n)
elements = [Poly(tuple(QGFM.to_bits(i))) for i in gf.elements[1:]]
for f_x in elements:
blq = GF2MulK.from_polynomials(f_x, m_x)
cblq = blq.decompose_bloq()
for g in gf.elements[1:]:
assert blq.call_classically(g=g) == cblq.call_classically(g=g)
@pytest.mark.parametrize(
['m_x', 'f_x', 'cnot_count'],
[
[Poly.Degrees([3, 1, 0]), Poly.Degrees([2, 0]), 2],
[Poly.Degrees([3, 1, 0]), Poly.Degrees([2, 1, 0]), 5],
[Poly.Degrees([2, 1, 0]), Poly.Degrees([1]), 1],
[Poly.Degrees([2, 1, 0]), Poly.Degrees([0]), 0],
],
)
def test_multiply_by_constant_mod_cost(m_x, f_x, cnot_count):
blq = GF2MulK.from_polynomials(f_x, m_x)
cost = get_cost_value(blq, QECGatesCost())
assert cost.total_t_count() == 0
assert cost.clifford == cnot_count
@pytest.mark.parametrize('m_x', [Poly.Degrees([2, 1, 0]), Poly.Degrees([3, 1, 0])])
def test_multiply_by_constant_mod_decomposition(m_x):
n = len(m_x.coeffs) - 1
gf = GF(2, n, irreducible_poly=m_x)
QGFM = QGF(2, n)
elements = [Poly(tuple(QGFM.to_bits(i))) for i in gf.elements[1:]]
for f_x in elements:
blq = GF2MulK.from_polynomials(f_x, m_x)
qlt_testing.assert_valid_bloq_decomposition(blq)
@pytest.mark.parametrize('m_x', [Poly.Degrees([2, 1, 0]), Poly.Degrees([3, 1, 0])])
def test_multiply_by_constant_mod_counts(m_x):
n = len(m_x.coeffs) - 1
gf = GF(2, n, irreducible_poly=m_x)
QGFM = QGF(2, n)
elements = [Poly(tuple(QGFM.to_bits(i))) for i in gf.elements[1:]]
for f_x in elements:
blq = GF2MulK.from_polynomials(f_x, m_x)
qlt_testing.assert_equivalent_bloq_counts(blq, generalizer=ignore_split_join)
def test_invalid_GF2MulK_args_raises():
gf = GF(2, 3)
x = GF(2, 4)(1)
with pytest.raises(AssertionError):
_ = GF2MulK(x, gf) # type: ignore[arg-type]
@pytest.mark.notebook
def test_notebook():
qlt_testing.execute_notebook('gf2_multiplication')
@pytest.mark.parametrize(['n', 'k'], [(n, k) for n in range(1, 6) for k in range(1, n + 2)])
def test_multiply_by_xk_decomposition(n, k):
blq = MultiplyPolyByOnePlusXk(n, k)
qlt_testing.assert_valid_bloq_decomposition(blq)
@pytest.mark.parametrize(['n', 'k'], [(n, k) for n in range(1, 6) for k in range(1, n + 2)])
def test_multiply_by_xk_bloq_counts(n, k):
blq = MultiplyPolyByOnePlusXk(n, k)
qlt_testing.assert_equivalent_bloq_counts(blq)
@pytest.mark.parametrize(['n', 'k'], [(n, k) for n in range(1, 4) for k in range(1, n + 2)])
def test_multiply_by_xk_classical_action(n, k):
blq = MultiplyPolyByOnePlusXk(n, k)
fg_polys = tuple(itertools.product(range(2), repeat=n))[1:]
h_polys = [*itertools.product(range(2), repeat=blq.signature[-1].shape[0])]
qlt_testing.assert_consistent_classical_action(blq, f=fg_polys, g=fg_polys, h=h_polys)
@pytest.mark.slow
@pytest.mark.parametrize(['n', 'k'], [(n, k) for n in range(4, 6) for k in range(1, n + 2)])
def test_multiply_by_xk_classical_action_slow(n, k):
blq = MultiplyPolyByOnePlusXk(n, k)
fg_polys = tuple(itertools.product(range(2), repeat=n))[1:]
h_polys = [*itertools.product(range(2), repeat=blq.signature[-1].shape[0])]
h_polys = [
h_polys[i] for i in np.random.choice(len(h_polys), min(len(h_polys), 20), replace=False)
]
qlt_testing.assert_consistent_classical_action(blq, f=fg_polys, g=fg_polys, h=h_polys)
@pytest.mark.parametrize('n', range(1, 10))
def test_binary_mult_decomposition(n):
blq = BinaryPolynomialMultiplication(n)
qlt_testing.assert_valid_bloq_decomposition(blq)
@pytest.mark.parametrize('n', range(1, 10))
def test_binary_mult_bloq_counts(n):
blq = BinaryPolynomialMultiplication(n)
qlt_testing.assert_equivalent_bloq_counts(
blq, generalizer=(ignore_split_join, ignore_alloc_free)
)
@pytest.mark.parametrize('n', range(1, 4))
def test_binary_mult_classical_action(n):
blq = BinaryPolynomialMultiplication(n)
fg_polys = tuple(itertools.product(range(2), repeat=n))[1:]
h_polys = [[0] * blq.signature[-1].shape[0]]
qlt_testing.assert_consistent_classical_action(blq, f=fg_polys, g=fg_polys, h=h_polys)
# @pytest.mark.slow
@pytest.mark.parametrize('n', range(4, 7))
def test_binary_mult_classical_action_slow(n):
blq = BinaryPolynomialMultiplication(n)
fg_polys = tuple(itertools.product(range(2), repeat=n))[1:]
h_polys = [[0] * blq.signature[-1].shape[0]]
qlt_testing.assert_consistent_classical_action(blq, f=fg_polys, g=fg_polys, h=h_polys)
@pytest.mark.parametrize('log_n', [*range(10 + 1)])
def test_binary_mult_toffoli_cost(log_n):
# Toffoli cost is n^log2(3), when n = 2^k we get (2^k)^log2(3) = 3^k
# CNOT count is is upper bounded by (10 + 1/3) n^log2(3)
n = 2**log_n
blq = BinaryPolynomialMultiplication(n)
cost = get_cost_value(blq, QECGatesCost())
assert cost.clifford < (10 + 1 / 3) * 3**log_n
counts = cost.total_t_and_ccz_count()
assert counts['n_t'] == 0
assert counts['n_ccz'] == 3**log_n
@pytest.mark.parametrize('m_x', [[1, 0], [2, 1, 0], [3, 1, 0], [5, 2, 0], [8, 4, 3, 1, 0]]) # x + 1
@pytest.mark.parametrize('k', range(1, 5))
def test_GF2ShiftRight_decomposition(m_x, k):
blq = GF2ShiftRight(m_x, k)
qlt_testing.assert_valid_bloq_decomposition(blq)
@pytest.mark.parametrize('m_x', [[1, 0], [2, 1, 0], [3, 1, 0], [5, 2, 0], [8, 4, 3, 1, 0]]) # x + 1
@pytest.mark.parametrize('k', range(1, 5))
def test_GF2ShiftRight_bloq_counts(m_x, k):
blq = GF2ShiftRight(m_x, k)
qlt_testing.assert_equivalent_bloq_counts(blq, generalizer=ignore_split_join)
@pytest.mark.parametrize('m_x', [[1, 0], [2, 1, 0], [3, 1, 0], [5, 2, 0], [8, 4, 3, 1, 0]]) # x + 1
@pytest.mark.parametrize('k', range(1, 5))
def test_GF2ShiftRight_complexity(m_x, k):
blq = GF2ShiftRight(m_x, k)
cost = get_cost_value(blq, QECGatesCost())
clifford = k * (len(m_x) - 2) if len(m_x) > 2 else 0
assert cost.clifford == clifford
assert cost.total_t_count() == 0
@pytest.mark.parametrize('m_x', [[1, 0], [2, 1, 0], [3, 1, 0], [5, 2, 0], [8, 4, 3, 1, 0]]) # x + 1
@pytest.mark.parametrize('k', range(1, 5))
def test_GF2ShiftRight_classical_action(m_x, k):
blq = GF2ShiftRight(m_x, k)
qlt_testing.assert_consistent_classical_action(blq, f=blq.gf.elements)
@pytest.mark.parametrize('m_x', [[2, 1, 0], [3, 1, 0], [5, 2, 0], [8, 4, 3, 1, 0]])
def test_gf2mulmod_decomposition(m_x):
blq = GF2MulViaKaratsuba(m_x)
qlt_testing.assert_valid_bloq_decomposition(blq)
@pytest.mark.parametrize('m_x', [[2, 1, 0], [3, 1, 0], [5, 2, 0], [8, 4, 3, 1, 0]])
def test_gf2mulmod_bloq_counts(m_x):
blq = GF2MulViaKaratsuba(m_x)
qlt_testing.assert_equivalent_bloq_counts(
blq, generalizer=(ignore_split_join, ignore_alloc_free)
)
@pytest.mark.parametrize('m_x', [[2, 1, 0], [8, 4, 3, 1, 0]])
def test_gf2mulmod_complexity(m_x):
blq = GF2MulViaKaratsuba(m_x)
cost = get_cost_value(blq, QECGatesCost())
# The toffoli cost is n^log2(3) .. when n = 2^k we get toffoli cost = 3^k
n = max(m_x)
k = n.bit_length() - 1
assert cost.total_toffoli_only() == 3**k
@pytest.mark.parametrize('m_x', [[2, 1, 0], [3, 1, 0], [5, 2, 0]])
def test_gf2mulmod_classical_action(m_x):
blq = GF2MulViaKaratsuba(m_x)
qlt_testing.assert_consistent_classical_action(blq, x=blq.gf.elements, y=blq.gf.elements)
@pytest.mark.slow
def test_gf2mulmod_classical_action_slow():
m_x = [8, 4, 3, 1, 0]
blq = GF2MulViaKaratsuba(m_x)
xs = blq.gf.elements[np.random.choice(2**8, 10)]
ys = blq.gf.elements[np.random.choice(2**8, 10)]
qlt_testing.assert_consistent_classical_action(blq, x=xs, y=ys)
@pytest.mark.parametrize('m_x', [[2, 1, 0], [3, 1, 0], [5, 2, 0]])
def test_gf2mulmod_classical_action_adjoint(m_x):
blq = GF2MulViaKaratsuba(m_x)
adjoint = blq.adjoint()
for i, j in np.random.random_integers(0, len(blq.gf.elements) - 1, (10, 2)):
f = blq.gf.elements[i]
g = blq.gf.elements[j]
a, b, c = blq.call_classically(x=f, y=g)
a, b = adjoint.call_classically(x=a, y=b, result=c)
assert a == f and b == g
@pytest.mark.parametrize('m_x', [[2, 1, 0], [8, 4, 3, 1, 0], [16, 5, 3, 1, 0]])
def test_gf2mulmod_classical_complexity(m_x):
blq = GF2MulViaKaratsuba(m_x)
cost = get_cost_value(blq, QECGatesCost()).total_t_and_ccz_count()
assert cost['n_t'] == 0
# The toffoli cost is n^log2(3) ... for n = 2^k we get toffli count = 3^k
n = max(m_x)
k = n.bit_length() - 1
assert cost['n_ccz'] == 3**k
def test_gf2mul_invalid_input_raises():
with pytest.raises(ValueError):
_ = GF2MulViaKaratsuba([0, 1]) # type: ignore[arg-type]