-
Notifications
You must be signed in to change notification settings - Fork 5
/
strategize.py
executable file
·347 lines (271 loc) · 10.9 KB
/
strategize.py
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
u"""
Find BKZ reduction strategies using timing experiments.
.. moduleauthor:: Martin R. Albrecht <fplll-devel@googlegroups.com>
.. moduleauthor:: Léo Ducas <fplll-devel@googlegroups.com>
.. moduleauthor:: Marc Stevens <fplll-devel@googlegroups.com>
"""
# We use multiprocessing to parallelize
from __future__ import absolute_import
from multiprocessing import Queue, Pipe, Process, active_children
from fpylll import IntegerMatrix, GSO, FPLLL, BKZ
from fpylll.tools.bkz_stats import BKZTreeTracer
from fpylll.fplll.bkz_param import Strategy, dump_strategies_json
from strategizer.bkz import CallbackBKZ
from strategizer.bkz import CallbackBKZParam as Param
from strategizer.config import logging, git_revision
from strategizer.util import chunk_iterator
from strategizer.strategizers import (
PruningStrategizer,
OneTourPreprocStrategizerFactory,
TwoTourPreprocStrategizerFactory,
FourTourPreprocStrategizerFactory,
ProgressivePreprocStrategizerFactory,
)
logger = logging.getLogger(__name__)
def find_best(state, fudge=1.01):
"""
Given an ordered tuple of tuples, return the minimal one, where
minimal is determined by first entry.
:param state:
:param fudge:
.. note :: The fudge factor means that we have a bias towards earlier entries.
"""
best = state[0]
for s in state:
if best[0] > fudge * s[0]:
best = s
return best
def worker_process(seed, params, queue=None):
"""
This function is called to collect statistics.
:param A: basis
:param params: BKZ parameters
:param queue: queue used for communication
"""
FPLLL.set_random_seed(seed)
FPLLL.set_threads(params["threads"])
A = IntegerMatrix.random(params.block_size, "qary", q=33554393, k=params.block_size // 2, int_type="long")
M = GSO.Mat(A)
bkz = CallbackBKZ(M) # suppresses initial LLL call
tracer = BKZTreeTracer(bkz, start_clocks=True)
with tracer.context(("tour", 0)):
bkz.svp_reduction(0, params.block_size, params, tracer)
M.update_gso()
tracer.exit()
try:
# close connection
params.strategies[params.block_size].connection.send(None)
except AttributeError:
pass
if queue:
queue.put(tracer.trace)
else:
return tracer.trace
def callback_roundtrip(alive, k, connections, data):
"""
Send ``data`` on ``connections`` for processes ids in ``alive``, ``k`` at a time.
:param alive:
:param k:
:param connections:
:param data:
"""
callback = [None] * len(connections)
for chunk in chunk_iterator(alive, k):
for i in chunk:
connections[i].send(data)
for i in chunk:
try:
callback[i] = connections[i].recv()
except EOFError:
callback[i] = None
connections[i].close()
return callback
def discover_strategy(block_size, Strategizer, strategies, jobs=1, nsamples=50, threads=1):
"""Discover a strategy using ``Strategizer``
:param block_size: block size to try
:param Strategizer: strategizer to use
:param strategies: strategies for smaller block sizes
:param jobs: number of jobs to run in parallel
:param nsamples: number of lattice bases to consider
:param threads: number of threads to use per job
"""
connections = []
processes = []
k = jobs
m = nsamples
strategizer = Strategizer(block_size)
# everybody is alive in the beginning
alive = range(m)
return_queue = Queue()
for i in range(m):
manager, worker = Pipe()
connections.append((manager, worker))
strategies_ = list(strategies)
strategies_.append(Strategizer.Strategy(block_size, worker))
# note: success probability, rerandomisation density etc. can be adapted here
param = Param(block_size=block_size, strategies=strategies_, flags=BKZ.GH_BND)
param["threads"] = threads
process = Process(target=worker_process, args=(2 ** 16 * block_size + i, param, return_queue))
processes.append(process)
callback = [None] * m
for chunk in chunk_iterator(alive, k):
for i in chunk:
process = processes[i]
process.start()
manager, worker = connections[i]
worker.close()
connections[i] = manager
# wait for `k` responses
for i in chunk:
callback[i] = connections[i].recv()
assert all(callback) # everybody wants preprocessing parameters
preproc_params = strategizer(callback)
callback = callback_roundtrip(alive, k, connections, preproc_params)
assert all(callback) # everybody wants pruning parameters
pruning_params = strategizer(callback)
callback = callback_roundtrip(alive, k, connections, pruning_params)
assert not any(callback) # no more questions
strategy = Strategy(
block_size=block_size, preprocessing_block_sizes=preproc_params, pruning_parameters=pruning_params
)
active_children()
stats = []
for i in range(m):
stats.append(return_queue.get())
return strategy, tuple(stats), tuple(strategizer.queries)
def strategize(
max_block_size,
existing_strategies=None,
min_block_size=3,
jobs=1,
threads=1,
nsamples=50,
pruner_method="hybrid",
StrategizerFactory=ProgressivePreprocStrategizerFactory,
dump_filename=None,
):
"""
*one* preprocessing block size + pruning.
:param max_block_size: maximum block size to consider
:param strategizers: strategizers to use
:param existing_strategies: extend these previously computed strategies
:param min_block_size: start at this block size
:param jobs: run this many jobs in parallel
:param threads: number of FPLLL threads to use per job
:param nsamples: start using this many samples
:param dump_filename: write strategies to this filename
"""
if dump_filename is None:
dump_filename = "default-strategies-%s.json" % git_revision
if existing_strategies is not None:
strategies = existing_strategies
times = [None] * len(strategies)
else:
strategies = []
times = []
for i in range(len(strategies), min_block_size):
strategies.append(Strategy(i, [], []))
times.append(None)
strategizer = PruningStrategizer
for block_size in range(min_block_size, max_block_size + 1):
logger.info("= block size: %3d, samples: %3d =", block_size, nsamples)
state = []
try:
p = max(strategies[-1].preprocessing_block_sizes[-1], 2)
except (IndexError,):
p = 2
prev_best_total_time = None
while p < block_size:
if p >= 4:
strategizer_p = type("PreprocStrategizer-%d" % p, (strategizer, StrategizerFactory(p)), {})
else:
strategizer_p = strategizer
strategy, stats, queries = discover_strategy(
block_size, strategizer_p, strategies, jobs=jobs, nsamples=nsamples, threads=threads,
)
stats = [stat for stat in stats if stat is not None]
total_time = [float(stat.data["cputime"]) for stat in stats]
total_walltime = [float(stat.data["walltime"]) for stat in stats]
svp_time = [float(stat.find("enumeration").data["cputime"]) for stat in stats]
preproc_time = [float(stat.find("preprocessing").data["cputime"]) for stat in stats]
total_time = sum(total_time) / len(total_time)
total_walltime = sum(total_walltime) / len(total_walltime)
svp_time = sum(svp_time) / len(svp_time)
preproc_time = sum(preproc_time) / len(preproc_time)
state.append((total_time, total_walltime, strategy, stats, strategizer, queries))
logger.info(
"t: %10.4fs, w: %10.4fs, p: %10.4fs, s: %10.4fs, %s",
total_time,
total_walltime,
preproc_time,
svp_time,
strategy,
)
if prev_best_total_time and 1.3 * prev_best_total_time < total_time:
break
p += 2
if not prev_best_total_time or prev_best_total_time > total_time:
prev_best_total_time = total_time
best = find_best(state)
total_time, total_walltime, strategy, stats, strategizer, queries = best
strategies.append(strategy)
dump_strategies_json(dump_filename, strategies)
times.append((total_time, stats, queries))
logger.info("")
logger.info(
"block size: %3d, cpu: %10.4fs, wall: %10.4fs, strategy: %s",
block_size,
total_time,
total_walltime,
strategy,
)
logger.info("")
if total_time > 0.1 and nsamples > max(2 * jobs, 8):
nsamples //= 2
return strategies, times
StrategizerFactoryDictionnary = {
"ProgressivePreproc": ProgressivePreprocStrategizerFactory,
"OneTourPreproc": OneTourPreprocStrategizerFactory,
"TwoTourPreproc": TwoTourPreprocStrategizerFactory,
"FourTourPreproc": FourTourPreprocStrategizerFactory,
}
if __name__ == "__main__":
import argparse
import logging
import os
parser = argparse.ArgumentParser(description="Preprocessing Search")
parser.add_argument("-j", "--jobs", help="number of jobs to run in parallel", type=int, default=1)
parser.add_argument("-t", "--threads", help="number of FPLLL threads to use per job", type=int, default=1)
parser.add_argument("-s", "--samples", help="number of samples to try", type=int, default=16)
parser.add_argument("-l", "--min-block-size", help="minimal block size to consider", type=int, default=3)
parser.add_argument("-u", "--max-block-size", help="minimal block size to consider", type=int, default=50)
parser.add_argument("-f", "--filename", help="json file to store strategies to", type=str, default=None)
parser.add_argument(
"-S",
"--strategizer",
help="Strategizer : {ProgressivePreproc,OneTourPreproc,TwoTourPreproc,FourTourPreproc}",
type=str,
default="OneTourPreproc",
)
args = parser.parse_args()
log_name = os.path.join("default-strategies-%s.log" % (git_revision))
if args.filename:
if not args.filename.endswith(".json"):
raise ValueError("filename should be a json file")
log_name = args.filename.replace(".json", ".log")
extra = logging.FileHandler(log_name)
extra.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(name)s: %(message)s")
extra.setFormatter(formatter)
logging.getLogger("").addHandler(extra)
strategize(
jobs=args.jobs,
threads=args.threads,
nsamples=args.samples,
min_block_size=args.min_block_size,
max_block_size=args.max_block_size,
StrategizerFactory=StrategizerFactoryDictionnary[args.strategizer],
dump_filename=args.filename,
)