-
Notifications
You must be signed in to change notification settings - Fork 3
/
gen_paper_fig.py
executable file
·1605 lines (1391 loc) · 57.6 KB
/
gen_paper_fig.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
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
# -*- coding: utf-8 -*-
# so X11 would not be needed
import matplotlib
matplotlib.use('Agg')
import torch
from eevbnn.net_bin import ModelHelper, BiasRegularizer
from eevbnn.utils import default_dataset_root, ensure_dir
from eevbnn.net_tools import eval_cbd_stats
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
import copy
import argparse
import os
import re
import functools
import collections
import json
import itertools
import zlib
import weakref
from pathlib import Path
ADV2_255 = '0.00784313725490196'
ADV20_255 = '0.0784313725490196'
ADV5_255 = '0.0196078431372549'
ADV8_255 = '0.03137254901960784'
# chosen cbd config for mnist and cifar10
CHOSEN_CBD = ['3-vrf', '3-vrf']
COLOR4 = [
'#a6cee3',
'#1f78b4',
'#b2df8a',
'#33a02c',
]
g_possible_tested_cases = set()
# patch latex formatter to output cline for single rows
import pandas.io.formats.latex
class FixedClineLatexFormatter(pandas.io.formats.latex.LatexFormatter):
def _format_multirow(self, row, ilevels, i, rows):
for j in range(ilevels):
if row[j].strip():
nrow = 1
for r in rows[i + 1 :]:
if not r[j].strip():
nrow += 1
else:
break
if nrow > 1:
# overwrite non-multirow entry
row[j] = "\\multirow{{{nrow:d}}}{{*}}{{{row:s}}}".format(
nrow=nrow, row=row[j].strip()
)
if j < ilevels - 1:
# save when to end the current block with \cline
self.clinebuf.append([i + nrow - 1, j + 1])
return row
pandas.io.formats.latex.LatexFormatter = FixedClineLatexFormatter
def gen_prod_treelike(desc):
"""recursively generate product for tree-like description"""
if isinstance(desc[0], (list, tuple)):
ret = []
for k, v in desc:
assert isinstance(k, str)
for i in gen_prod_treelike(v):
ret.append([k] + i)
return ret
return [[i] for i in desc]
def fix_cline(latex):
"""use cmidrule for cline"""
return latex.replace('cline', 'cmidrule(lr)')
def add_second_row_title(latex: str, title: str) -> str:
"""add a title to the second row"""
lines = latex.split('\n')
cols = lines[3].split('&')
cols[0] = title
lines[3] = '&'.join(cols)
cols = lines[2].split('&')
cidx = 0
for i, j in list(enumerate(cols)):
j = j.strip()
cidx += 1
if (m := re.search(r'multicolumn\{([0-9]*)\}', j)) is not None:
cnext = cidx + int(m.group(1)) - 1
cols[-1] += r' \cmidrule(lr){%d-%d}' % (cidx, cnext)
cidx = cnext
lines[2] = '&'.join(cols)
return '\n'.join(lines)
class PercentValue:
__slots__ = ['vnum', 'precision', 'empty_for_zero']
def __init__(self, s, precision=0):
self.precision = precision
if isinstance(s, str):
s = s.strip()
assert s.endswith('%')
self.vnum = float(s[:-1]) / 100
else:
self.vnum = float(s)
self.empty_for_zero = False
def set_precision(self, prec):
self.precision = prec
return self
def set_empty_for_zero(self, flag=True):
self.empty_for_zero = flag
return self
def neg(self):
"""1 - self"""
return PercentValue(1 - self.vnum, self.precision)
def __repr__(self):
if self.empty_for_zero and not self.vnum:
return '0'
val = self.vnum * 100
fmt = '{{:.{}f}}\\%'.format(self.precision).format
ret = fmt(val)
if val != 0 and ret == fmt(0.0):
# handle small numbers
return r'{:.1g}\%'.format(val)
return ret
class FloatValue:
def __init__(self, s, precision):
self.precision = precision
self.vnum = float(s)
def copy(self):
return FloatValue(self.vnum, self.precision)
def set_precision(self, prec):
self.precision = prec
return self
def _format_latex_sci(self):
if self.vnum == 0:
return '0'
sci = '{:.1e}'.format(self.vnum)
k, e = sci.split('e')
assert e[0] in '+-'
if e[1] == '0':
e = e[0] + e[2:]
if e[0] == '+':
e = e[1:]
if k.endswith('.0'):
k = k[:-2]
return fr'\scinum{{ {k} }}{{ {e} }}'
def __repr__(self):
p = self.precision
if p == 'latex-sci':
return self._format_latex_sci()
if isinstance(p, str):
fmt = '{:' + p + '}'
else:
assert isinstance(p, int), f'bad precision {p}'
fmt = '{{:.{}f}}'.format(p)
ret = fmt.format(self.vnum)
if ret == fmt.format(0.0) and abs(self.vnum) > 1e-9:
return f'${self._format_latex_sci()}$'
return ret
def __add__(self, rhs):
assert isinstance(rhs, FloatValue) and rhs.precision == self.precision
return FloatValue(self.vnum + rhs.vnum, self.precision)
def __truediv__(self, rhs):
assert isinstance(rhs, FloatValue), rhs
return self.vnum / rhs.vnum
def cached_meth(fn):
"""decorator for cached class method without arguments"""
key = f'__result_cache_{fn.__name__}'
@functools.wraps(fn)
def work(self):
d: dict = self.__dict__
ret = d.get(key)
if ret is not None:
return ret
ret = fn(self)
assert ret is not None
d[key] = ret
return ret
return work
SparsityStat = collections.namedtuple(
'SparsityStat',
['layerwise', 'tot_avg', 'nr_non_zero']
)
SolverStat = collections.namedtuple(
'SolverStat',
['num', 'build_time',
'solve_time', 'solve_time_mid', 'solve_time_min', 'solve_time_max',
'solve_prob', 'robust_prob']
)
class SingleExperiment:
_args = None
_data_dir = None
_all_experiments = None
_name = None
_used_solver_stats = None
"""map from key to bool indicating whether the full set is used"""
def __init__(self, args, data_dir: Path, all_experiments):
assert isinstance(all_experiments, Experiments)
self._args = args
self._data_dir = data_dir
self._all_experiments = weakref.proxy(all_experiments)
self._name = data_dir.name
self._used_solver_stats = collections.defaultdict(bool)
def _open_log(self):
return (self._data_dir / 'log.txt').open()
@property
def name(self):
return self._name
@cached_meth
def _check_train_finish(self):
assert (self._data_dir / 'finish_mark').exists(), (
f'training of {self._data_dir} is unfinished')
return True
@property
@cached_meth
def _log_lines(self):
with self._open_log() as fin:
return fin.readlines()
def _check_format_v2(self, prefix, default_idx):
"""find value with specifid prefix in v2 format log"""
if (self._log_lines[-1].startswith('model choosing') or
self._log_lines[-2].startswith('model choosing')):
# log format v2 with model choosing
UPDATE_MAGIC = 'best model update at '
lookfor = None
logline = None
for i in self._log_lines[::-1]:
if lookfor is not None and i.startswith(lookfor):
return i
if i.startswith(UPDATE_MAGIC):
lookfor = prefix + i[len(UPDATE_MAGIC):].strip()
raise RuntimeError(f'{lookfor} not found in log')
return self._log_lines[default_idx]
@cached_meth
def sparsity(self):
self._check_train_finish()
logline = self._check_format_v2('sparsity', -2)
m = re.match(r'sparsity@[0-9]*: (.*) ; ([0-9]*)/([0-9]*)=.*', logline)
layer = list(map(PercentValue, m.group(1).split(',')))
nz, tot = map(int, [m.group(2), m.group(3)])
return SparsityStat(layer, PercentValue(nz / tot), tot - nz)
@cached_meth
def test_acc(self):
self._check_train_finish()
logline = self._check_format_v2('test', -1)
m = re.match(r'test@[0-9]*: acc=([0-9.]*%)', logline)
assert m is not None, (
f'bad logline: {logline.strip()} @ {self._data_dir}')
return PercentValue(m.group(1), precision=2)
@cached_meth
def test_loss(self):
self._check_train_finish()
logline = self._check_format_v2('test', -1)
m = re.match(r'test@[0-9]*: .* loss=([0-9.]*) ', logline)
assert m is not None, (
f'bad logline: {logline.strip()} @ {self._data_dir}')
return FloatValue(m.group(1), precision=2)
def ensemble_test_acc(self, eps):
fpath = self._data_dir / f'eval-ensemble-{eps}.json.ensemble_acc'
with fpath.open() as fin:
return PercentValue(float(fin.read()), 2)
@cached_meth
def _all_solver_raw(self):
self._check_train_finish()
check_merged_all = collections.defaultdict(dict)
all_result = {}
for jfile in self._data_dir.glob('eval-*.json'):
param_class = jfile.name.split('-')[-1][:-5] # eps
float(param_class) # ensure it is valid
if '-ensemble-' in jfile.name:
param_class = f'ensemble-{param_class}'
check_merged = check_merged_all[param_class]
jf_path = self._data_dir / f'{jfile.name}.finished'
with jfile.open() as fin:
data = json.load(fin)
all_result[jfile.name] = data
for k, v in data.items():
old = check_merged.setdefault(k, v['result'])
if old != v['result']:
assert old == 'TLE' or v['result'] == 'TLE', (
f'verify result mismatch on {jfile}: {old=} {k=} {v=}'
)
if old == 'TLE':
check_merged[k] = v['result']
if not jf_path.exists():
if self._args.add_unfinished:
print(f'WARNING: {jf_path} does not exist but still added')
else:
del all_result[jfile.name]
return all_result
def solver_stats(self, eps, name=None, *, use_subset=False,
default_name='minisatcs-verify'):
"""
:param use_subset: if True, use only the sub test set of this dataset
"""
name = name or default_name
try:
key = f'eval-{name}-{eps}.json'
data: dict = self._all_solver_raw()[key]
except KeyError:
raise RuntimeError(f'{key} not found in expr {self._data_dir}')
if use_subset:
data = {k: v for k, v in data.items()
if k in self._solver_stats_subset_ref()}
self._used_solver_stats[key] # insert the key
else:
self._used_solver_stats[key] = True
all_build_times = []
all_solve_times = []
is_solved = []
is_robust = []
result2int = {
'UNSAT': 0,
'SAT': 1,
'TLE': -1
}
for i in data.values():
all_build_times.append(i['build_time'])
all_solve_times.append(i['solve_time'])
result = result2int[i['result']]
is_solved.append(result >= 0)
is_robust.append(result == 0)
checksum = hex(
zlib.adler32(','.join(sorted(data.keys())).encode('utf-8')))
g_possible_tested_cases.add(f'{len(data)}[{checksum}]')
prec = 0
prec_num = 100
while len(data) > prec_num:
prec += 1
prec_num *= 10
return SolverStat(
len(data),
FloatValue(np.mean(all_build_times), 3),
FloatValue(np.mean(all_solve_times), 3),
FloatValue(np.median(all_solve_times), 3),
FloatValue(np.min(all_solve_times), 3),
FloatValue(np.max(all_solve_times), 3),
PercentValue(np.mean(is_solved), prec),
PercentValue(np.mean(is_robust), prec),
)
@cached_meth
def cbd_stats(self):
""":return: cbd loss, cbd avg, cbd max"""
cache_file = self._data_dir / 'cbd_stat.json'
if cache_file.exists():
with cache_file.open() as fin:
cbd_avg, cbd_max = json.load(fin)
else:
cbd_avg, cbd_max = self._eval_cbd_stats()
with cache_file.open('w') as fout:
json.dump([cbd_avg, cbd_max], fout)
m = re.search('bias_hinge_coeff=([^,]*),', self._log_lines[1])
coeff = float(m.group(1))
return (FloatValue(coeff, 'latex-sci'),
FloatValue(cbd_avg, 1),
FloatValue(cbd_max, 1))
@cached_meth
def pgd_acc(self):
"""a dict mapping from eps to pgd accuracy"""
return self._load_pgd_acc('attack.json')
@cached_meth
def pgd_acc_hardtanh(self):
return self._load_pgd_acc('attack-hardtanh.json')
@cached_meth
def _solver_stats_subset_ref(self):
if self._name.startswith('mnist'):
intersect = ('mnist-l-advnone-cbd0', '0.1')
elif self._name.startswith('cifar10'):
intersect = ('cifar10-l-advnone-cbd0', ADV2_255)
else:
raise RuntimeError('unknown expr')
other, other_eps = intersect
other = self._all_experiments[other]
other_raw = other._all_solver_raw()
return other_raw[f'eval-minisatcs-verify-{other_eps}.json']
def _load_pgd_acc(self, fname):
with (self._data_dir / fname).open() as fin:
data = json.load(fin)
assert data['pgd_steps'] == 100
return {k: PercentValue(v, 2) for k, v in data['pgd'].items()}
def _eval_cbd_stats(self):
print(f'evaluating CBD losses for {self._data_dir} ...', end=' ',
flush=True)
device = "cuda" if torch.cuda.is_available() else "cpu"
net = (ModelHelper.
create_with_load(self._data_dir / 'last.pth').
to(device).
eval())
return eval_cbd_stats(self._args, net, device)
def get_unused_solver_stat(self):
"""return a list of unaccessed solver stats"""
ret = []
for k, v in self._all_solver_raw().items():
used_as_full = self._used_solver_stats.get(k)
if used_as_full is None:
ret.append(k)
elif (not used_as_full and
len(v) > len(self._solver_stats_subset_ref())):
ret.append(f'{k} (full)')
return ret
class ValueRange:
val = (float('inf'), float('-inf'))
_sum = None
_cnt = None
def __init__(self, *, calc_avg=False):
if calc_avg:
self._sum = 0
self._cnt = 0
def update(self, *args):
a, b = self.val
for v in args:
assert isinstance(v, float)
a = min(a, v)
b = max(b, v)
if self._sum is not None:
self._sum += a
self._cnt += 1
self.val = (a, b)
@property
def average(self):
return self._sum / self._cnt
def __repr__(self):
return f'ValueRange{self.val}'
class Experiments:
args = None
out_dir: Path = None
_experiments = None
_used_experiments = None
_mcs_speedup_range = None
"""mean speedup of minisatcs compared to other solvers"""
_mcs_speedup_range_mid = None
"""median speedup of minisatcs compared to other solvers"""
_latex_defs = None
def __init__(self, args):
self.args = args
self._mcs_speedup_range = ValueRange(calc_avg=True)
self._mcs_speedup_range_mid = ValueRange()
p = Path(args.train_dir)
experiments = {}
for i in p.iterdir():
if i.is_dir():
expr = SingleExperiment(args, i, self)
experiments[expr.name] = expr
self._experiments = experiments
self.out_dir = Path(args.out_dir)
self._latex_defs = {}
self._used_experiments = set()
def __getitem__(self, key) -> SingleExperiment:
self._used_experiments.add(key)
return self._experiments[key]
def _open_outfile(self, name):
return (self.out_dir / name).open('w')
def gen_table_ensemble(self):
idx_row = [
r'\texttt{conv-small}',
r'\texttt{conv-large}',
r'ensemble',
]
idx_col = [
'Test Accuracy',
'Mean Solve Time (s)',
'Attack Success Rate',
]
data = np.empty((len(idx_row), len(idx_col)), dtype=object)
exp = self[f'mnist-l-adv0.3-cbd{CHOSEN_CBD[0]}']
exp_s = self[f'mnist-s-adv0.3']
st = [
exp_s.solver_stats('0.3'),
exp.solver_stats('0.3'),
exp.solver_stats('0.3', 'ensemble'),
]
data[:, 0] = [
exp_s.test_acc(),
exp.test_acc(),
exp.ensemble_test_acc('0.3'),
]
data[:, 1] = [i.solve_time for i in st]
data[:, 2] = [i.robust_prob.neg().set_precision(2) for i in st]
df = pd.DataFrame(data, index=idx_row, columns=idx_col)
with self._open_outfile('table-ensemble.tex') as fout:
latex: str = df.to_latex(
escape=False,
column_format='lR{9ex}R{10ex}R{8ex}')
fout.write(latex)
with self._open_outfile('table-ensemble-wide.tex') as fout:
latex: str = df.to_latex(
escape=False,
column_format='lrrr')
fout.write(latex)
def gen_fig_cmp_minisat(self):
METHODS = [
'Ours:\nMiniSatCS\n(full)', 'Ours:\nMiniSatCS\n(sub40)',
'MiniSat\nseqcnt\n(sub40)', 'MiniSat\ncardnet\n(sub40)',
'Z3\n(sub40)', 'RoundingSat\n(sub40)', 'Narodytska et al.\n(sub100)'
]
TIME_narodytska2020in = FloatValue(5.1, 3)
EPS_DISP = ['20/255', '0.3']
EPS_FILE = [ADV20_255, '0.3']
fig_h, ax_h = plt.subplots(figsize=(8, 3))
fig_v, ax_v = plt.subplots(figsize=(9.5, 5.5))
solver_test_size = None
exp = self['mnist-mlp']
colors = ['#e41a1c', '#377eb8']
NR_CMP = len(METHODS) - 1 # excluding Narodytska
xmin_min = float('inf')
for eps_i, eps in enumerate(EPS_FILE):
xmean = []
xmid = []
xmin = []
xmax = []
for meth_i, meth in enumerate(
['minisatcs', 'minisatcs',
'm22', 'm22-cardnet', 'z3', 'pb']):
solver_st = exp.solver_stats(eps, meth,
use_subset=(meth_i != 0))
xmean.append(solver_st.solve_time.vnum)
xmin.append(solver_st.solve_time_min.vnum)
xmax.append(solver_st.solve_time_max.vnum)
xmid.append(solver_st.solve_time_mid.vnum)
if not self.args.add_unfinished and meth_i != 0:
if solver_test_size is None:
solver_test_size = solver_st.num
assert solver_test_size == solver_st.num, (
solver_test_size, solver_st.num)
ycoord = np.arange(NR_CMP, dtype=np.float32)
if eps_i == 0:
ycoord -= 0.15
else:
ycoord += 0.15
xmean, xmin, xmax = map(np.array, [xmean, xmin, xmax])
range_kw = dict(marker='o', ls='', capsize=2, capthick=1,
color=colors[eps_i])
mid_kw = dict(ls='', marker='^', color=colors[eps_i],
markersize=7)
ax_h.errorbar(xmean, ycoord, xerr=[xmean - xmin, xmax - xmean],
**range_kw)
ax_h.plot(xmid, ycoord, **mid_kw)
ax_v.errorbar(ycoord, xmean, yerr=[xmean - xmin, xmax - xmean],
**range_kw)
ax_v.plot(ycoord, xmid, **mid_kw)
xmin_min = min(xmin_min, min(xmin))
ax_h.plot([TIME_narodytska2020in.vnum], [NR_CMP],
marker='o', color=colors[0])
ax_v.plot([NR_CMP], [TIME_narodytska2020in.vnum],
marker='o', color=colors[0])
xlim = (xmin_min * 0.9, 5e3)
ylim = (-0.49, 4.49)
ax_h.set_xlabel('Solve Time (seconds) in Log Scale')
ax_h.set_xscale('log')
ax_h.set_xlim(xlim)
ax_h.set_yticks(np.arange(len(METHODS)))
ax_h.set_yticklabels(METHODS)
ax_h.set_ylim(ylim)
ax_h.set_yticks(np.arange(len(METHODS)) + 0.5, minor=True)
ax_h.grid(axis='y', which='minor')
ax_h.grid(axis='x', which='major')
ax_v.set_ylabel('Solve Time (seconds) in Log Scale')
ax_v.set_yscale('log')
ax_v.set_ylim(xlim)
ax_v.set_xticks(np.arange(len(METHODS)))
ax_v.set_xticklabels(METHODS)
ax_v.set_xlim(ylim)
ax_v.set_xticks(np.arange(len(METHODS)) + 0.5, minor=True)
ax_v.grid(axis='x', which='minor')
ax_v.grid(axis='y', which='major')
for ax in ax_h, ax_v:
for c, e in zip(colors, EPS_DISP):
ax.plot([], [], color=c, ls='-', label=rf'$\epsilon={e}$')
ax.plot([], [], marker='o', ls='none', label='mean', color='black')
ax.plot([], [], marker='^', ls='none', label='median',
color='black')
ax.legend(loc='best', fancybox=True, framealpha=0.9,
borderpad=1, frameon=True, fontsize=13)
fig_h.tight_layout()
fig_h.savefig(str(self.out_dir / 'fig-cmp-minisat.pdf'),
metadata={'CreationDate': None})
fig_v.tight_layout()
fig_v.savefig(str(self.out_dir / 'fig-cmp-minisat-vert.pdf'),
metadata={'CreationDate': None})
@classmethod
def _make_refdata_xiao(cls):
npydict = lambda **kwargs: {k: np.array(v) for k, v in kwargs.items()}
small = npydict(
test_acc=[0.9868, 0.9733, 0.6112, 0.4045],
pgd_acc=[0.9513, 0.9205, 0.4992, 0.2678],
prov_acc=[0.9433, 0.8068, 0.4593, 0.2027],
prov_upper=[0.9438, 0.8170, 0.4779, 0.2274],
prov_time=[0.49, 2.78, 13.5, 22.33],
build_time=[4.98, 4.34, 52.58, 38.34],
)
large = npydict(
test_acc=[0.9895, 0.9754, 0.6141, 0.4281],
pgd_acc=[0.9658, 0.9325, 0.5061, 0.2869],
prov_acc=[0.9560, 0.5960, 0.4140, 0.1980],
prov_upper=[0.9560, 0.8370, 0.5100, 0.2520],
prov_time=[0.27, 37.45, 29.88, 20.14],
build_time=[156.74, 166.39, 335.97, 401.72],
)
def fix(x):
x['total_time'] = x['prov_time'] + x['build_time']
x['timeout'] = x['prov_upper'] - x['prov_acc']
return x
return fix(small), fix(large)
def gen_e2e_cmp_plot(self):
xiao_small, xiao_large = self._make_refdata_xiao()
fig, ax = plt.subplots()
colors = COLOR4
min_time = float('inf')
max_time = float('-inf')
def draw(time, acc, is_large, marker, color):
nonlocal min_time, max_time
min_time = min(time, min_time)
max_time = max(time, max_time)
kw = dict(edgecolors=color, linewidths=2)
if is_large:
kw['color'] = color
else:
kw['facecolors'] = 'none'
ax.scatter([time], [acc * 100], marker=marker, **kw)
for dset_i, dset in enumerate(['mnist', 'cifar10']):
if dset_i == 0:
eps_range = [('0.1',) * 3, ('0.3', ) * 3]
else:
eps_range = [(r'\frac{2}{255}', '2', ADV2_255),
(r'\frac{8}{255}', '8', ADV8_255)]
for eps_i, (eps_disp, eps_file, eps_vrf) in enumerate(eps_range):
idx = dset_i * 2 + eps_i
color = colors[idx]
draw(xiao_small['total_time'][idx],
xiao_small['prov_acc'][idx],
False, 's', color)
draw(xiao_large['total_time'][idx],
xiao_large['prov_acc'][idx],
True, 's', color)
st = self[f'{dset}-s-adv{eps_file}'].solver_stats(eps_vrf)
draw(st.solve_time.vnum, st.robust_prob.vnum, False,
'o', color)
st = (self[f'{dset}-l-adv{eps_file}-cbd{CHOSEN_CBD[dset_i]}'].
solver_stats(eps_vrf))
draw(st.solve_time.vnum, st.robust_prob.vnum, True,
'o', color)
ax.plot([], [], color=color,
label=fr'{dset.upper()} $\epsilon={eps_disp}$')
def add_legend(marker, meth):
ax.plot([], [], color='black', marker=marker, mfc='none', ls='none',
mew=2, label=f'{meth} small')
ax.plot([], [], color='black', marker=marker, ls='none',
mew=2, label=f'{meth} large')
add_legend('s', 'Xiao et al.')
add_legend('o', 'EEV')
ax.set_xlabel('Mean Verification Time (seconds) in Log Scale')
ax.set_ylabel('Verifiable Accuracy (%)')
ax.set_xscale('log')
ax.set_xlim(min_time / 2, max_time * 50)
ax.grid(which='major', axis='both')
ax.legend(loc='upper right', fancybox=True, frameon=True,
framealpha=0.8, prop={'size': 'small'})
fig.tight_layout()
fig.savefig(str(self.out_dir / 'fig-e2e-cmp.pdf'),
metadata={'CreationDate': None})
def gen_cmp_singledset(self):
self._do_gen_cmp_singledset(True)
self._do_gen_cmp_singledset(False)
self._do_gen_cmp_singledset_sep()
def _do_gen_cmp_singledset_sep(self):
fig0, ax0 = plt.subplots(figsize=(5.6, 4.3))
fig1, ax1 = plt.subplots(figsize=(5.6, 6.3))
self._plot_cmp_singledset(ax0, ax1, False, 15, 15)
ax1.set_ylim(10, 50)
fig0.suptitle('Comparing Verification Solving Time on CIFAR10\n'
r'with $\epsilon=8/255$ Timeout=120s',
fontsize=15)
fig1.suptitle('Comparing Verifiable Accuracy on CIFAR10\n'
r'with $\epsilon=8/255$ Timeout=120s',
fontsize=15)
for ext in ['png', 'pdf', 'svg']:
metadata = {}
if ext != 'svg':
metadata['CreationDate'] = None
fig0.savefig(str(self.out_dir / f'fig-cmp-singledset-sep0.{ext}'),
metadata=metadata)
fig1.savefig(str(self.out_dir / f'fig-cmp-singledset-sep1.{ext}'),
metadata=metadata)
def _do_gen_cmp_singledset(self, annot_speedup):
fig, (ax0, ax1) = plt.subplots(ncols=2, figsize=(10, 5))
postfix = self._plot_cmp_singledset(ax0, ax1, annot_speedup, 15, 14)
fig.suptitle(r'Comparing Verification Performance on CIFAR10 '
r'with $\epsilon=\frac{8}{255}$ Timeout=120s',
fontsize=15)
fig.tight_layout()
postfix()
for ext in ['png', 'pdf']:
a = ''
if annot_speedup:
a += '-annot'
fig.savefig(str(self.out_dir / f'fig-cmp-singledset{a}.{ext}'),
metadata={'CreationDate': None})
def _plot_cmp_singledset(self, ax0, ax1, annot_speedup,
fsize_tick, fsize_legend):
xiao_small, xiao_large = self._make_refdata_xiao()
eev_se = self['cifar10-s-adv8']
eev_le = self[f'cifar10-l-adv8-cbd{CHOSEN_CBD[1]}']
eev_s = eev_se.solver_stats(ADV8_255)
eev_l = eev_le.solver_stats(ADV8_255)
x_labels = [
'Small\nBNN', 'Small\nFP32 NN',
'Large\nBNN', 'Large\nFP32 NN'
]
for i in ax0, ax1:
i.set_xticks(np.arange(len(x_labels)))
i.set_xticklabels(x_labels, fontsize=fsize_tick)
xs = np.arange(len(x_labels))
def make_y(exeev, xkey, k=1, use_solver=True):
if use_solver:
eev = [eev_s, eev_l]
else:
eev = [eev_se, eev_le]
return [i * k for i in (
exeev(eev[0]), xiao_small[xkey][3],
exeev(eev[1]), xiao_large[xkey][3])]
ys = make_y(lambda x: x.solve_time.vnum, 'prov_time')
if annot_speedup:
ax0.scatter(xs[::2], ys[::2], marker='*', color='green', s=260)
ax0.scatter(xs[1::2], ys[1::2], color='black', s=100)
else:
ax0.bar(xs[::2], ys[::2], color='#0496ff', width=0.6,
label='Ours: EEV')
ax0.bar(xs[1::2], ys[1::2], color='#006ba6', width=0.6,
label='Xiao et al. 2019')
ax0.set_ylabel('Mean Solve Time (seconds) in Log Scale',
fontsize=fsize_tick)
ax0.set_yscale('log')
ax0.set_xlim(-0.5, 3.5)
ax0.set_ylim(min(ys) / 4, max(ys) * 4)
ax0.grid(which='major', axis='y')
tx0 = [None, None]
if annot_speedup:
for i in range(2):
i0 = i*2
i1 = i*2 + 1
dx = (xs[i1]-xs[i0])*0.03
dy = np.exp((np.log(ys[i1]) - np.log(ys[i0]))*0.03)
ax0.annotate(
'',
xy=(xs[i0]+dx, ys[i0]*dy), xycoords='data',
xytext=(xs[i1]-dx, ys[i1]/dy), textcoords='data',
arrowprops=dict(
arrowstyle='fancy',
)
)
tx0[i] = ax0.text(
(xs[i0]+xs[i1]) / 2 - 0.1,
np.sqrt(ys[i0]*ys[i1]) * 1.5,
f"speedup: {ys[i1]/ys[i0]:.2f}x",
ha='center', va='center',
size='large',
)
else:
ax0.set_ylim(min(ys) / 1.5, max(ys) * 5)
ax0.legend(loc='best', fancybox=True, frameon=True,
fontsize=fsize_legend, ncol=2)
colors = ['#ffeda0', '#feb24c', '#f03b20']
ys0 = make_y(lambda x: x.robust_prob.vnum, 'prov_acc', 100)
ys1 = make_y(lambda x: x.solve_prob.neg().vnum, 'timeout', 100)
ys2 = make_y(lambda x: x.test_acc().vnum, 'test_acc', 100,
use_solver=False)
ax1.bar(xs, ys2, label='Natural Test Accuracy', width=0.6,
color=colors[0])
ax1.bar(xs, ys0, label='Verfiable Accuracy', width=0.6,
color=colors[1])
ax1.bar(xs, ys1, bottom=ys0, label='Timeout', width=0.6,
color=colors[2])
ax1.set_ylabel('Accuracy (%)', fontsize=fsize_tick)
ax1.grid(which='major', axis='y')
ax1.set_ylim(0, 55)
handles, labels = ax1.get_legend_handles_labels()
_, handles, labels = zip(*sorted(zip([1, 0, 2],
handles, labels)))
ax1.legend(handles, labels,
loc='upper left', fancybox=True, frameon=True,
fontsize=fsize_legend)
def postfix():
if annot_speedup:
for i in range(2):
sp1 = ax0.transData.transform_point(np.array([
xs[i*2], ys[i*2]]))
sp2 = ax0.transData.transform_point(np.array([
xs[i*2+1], ys[i*2+1]]))
tx0[i].set_rotation(np.degrees(np.arctan2(
sp2[1] - sp1[1], sp2[0] - sp1[0])))
return postfix
def gen_table_summary(self):
xiao_data_small, xiao_data_large = self._make_refdata_xiao()
idx_row = list(itertools.product(
[
r'MNIST $\epsilon=0.1$',
r'MNIST $\epsilon=0.3$',
r'CIFAR10 $\epsilon=\frac{2}{255}$',
r'CIFAR10 $\epsilon=\frac{8}{255}$'
],
[
r'EEV S',
r'EEV L',
r'\citet{xiao2018training} S',
r'\citet{xiao2018training} L\tnote{*}',
]
))
idx_col = (
list(itertools.product(
['Mean Time (s)'],
['Build', 'Solve', 'Total'])) +
list(itertools.product(
['Accuracy'],
['Verifiable', 'Natural', 'PGD']
)) +
[('Timeout', '~')]
)
data = np.empty((len(idx_row), len(idx_col)), dtype=object)
def fill_existing(rows, source):
mkacc = lambda x: [PercentValue(i, 2) for i in x]
mktime = lambda x: [FloatValue(i, 2) for i in x]
data[rows, :] = np.array([
mktime(source['build_time']),
mktime(source['prov_time']),
mktime(source['total_time']),
mkacc(pacc := source['prov_acc']),
mkacc(source['test_acc']),
mkacc(source['pgd_acc']),
mkacc(source['prov_upper'] - pacc),
], dtype=object).T
fill_existing(np.arange(2, 16, 4), xiao_data_small)
fill_existing(np.arange(3, 16, 4), xiao_data_large)
TRAIN_EPS = {
'mnist': ['0.1', '0.3'],
'cifar10': ['2', '8'],
}
for dset_i, dset in enumerate(['mnist', 'cifar10']):
for model_i, model in enumerate('sl'):
for train_eps_i, train_eps in enumerate(TRAIN_EPS[dset]):
rbase = dset_i * 8 + train_eps_i * 4 + model_i
suffix = ''
if model_i == 1:
suffix = f'-cbd{CHOSEN_CBD[dset_i]}'
exp = self[f'{dset}-{model}-adv{train_eps}{suffix}']
if dset_i == 0:
test_eps = train_eps
else:
test_eps = [ADV2_255, ADV8_255][train_eps_i]
solver_st = exp.solver_stats(test_eps)
data[rbase, :] = [