/
nasbench_101.py
3069 lines (2671 loc) · 110 KB
/
nasbench_101.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
"""
NASBench-101 search space, rollout, controller, evaluator.
During the development,
referred https://github.com/automl/nas_benchmarks/blob/master/tabular_benchmarks/nas_cifar10.py
"""
import abc
import copy
import os
import re
import random
import collections
import itertools
import yaml
from typing import List
import numpy as np
import torch
from torch import nn, Tensor
import torch.nn.functional as F
import nasbench
from nasbench import api
from nasbench.lib import graph_util, config
from aw_nas import utils
from aw_nas.ops import get_op, Identity
from aw_nas.utils.exception import expect
from aw_nas.common import SearchSpace
from aw_nas.rollout.base import BaseRollout
from aw_nas.controller.base import BaseController
from aw_nas.evaluator.base import BaseEvaluator
from aw_nas.rollout.compare import CompareRollout
from aw_nas.evaluator.arch_network import ArchEmbedder
from aw_nas.utils import DenseGraphConvolution, DenseGraphFlow
from aw_nas.weights_manager.shared import SharedCell, SharedOp
from aw_nas.weights_manager.base import CandidateNet, BaseWeightsManager
INPUT = 'input'
OUTPUT = 'output'
CONV1X1 = 'conv1x1-bn-relu'
CONV3X3 = 'conv3x3-bn-relu'
MAXPOOL3X3 = 'maxpool3x3'
OUTPUT_NODE = 6
VERTICES = 7
MAX_EDGES = 9
_nasbench_cfg = config.build_config()
def parent_combinations_old(adjacency_matrix, node, n_parents=2):
"""Get all possible parent combinations for the current node."""
if node != 1:
# Parents can only be nodes which have an index that is lower than the current index,
# because of the upper triangular adjacency matrix and because the index is also a
# topological ordering in our case.
return itertools.combinations(np.argwhere(adjacency_matrix[:node, node] == 0).flatten(),
n_parents) # (e.g. (0, 1), (0, 2), (1, 2), ...
else:
return [[0]]
def parent_combinations(node, num_parents):
if node == 1 and num_parents == 1:
return [(0,)]
else:
return list(itertools.combinations(list(range(int(node))), num_parents))
def upscale_to_nasbench_format(adjacency_matrix):
"""
The search space uses only 4 intermediate nodes, rather than 5 as used in nasbench
This method adds a dummy node to the graph which is never used to be compatible with nasbench.
:param adjacency_matrix:
:return:
"""
return np.insert(
np.insert(adjacency_matrix,
5, [0, 0, 0, 0, 0, 0], axis=1),
5, [0, 0, 0, 0, 0, 0, 0], axis=0)
def _literal_np_array(arr):
if arr is None:
return None
return "np.array({})".format(np.array2string(arr, separator=",").replace("\n", " "))
class _ModelSpec(api.ModelSpec):
def __repr__(self):
return "_ModelSpec({}, {}; pruned_matrix={}, pruned_ops={})".format(
_literal_np_array(self.original_matrix),
self.original_ops,
_literal_np_array(self.matrix),
self.ops,
)
def hash_spec(self, *args, **kwargs):
return super(_ModelSpec, self).hash_spec(_nasbench_cfg["available_ops"])
class NasBench101SearchSpace(SearchSpace):
NAME = "nasbench-101"
def __init__(
self,
multi_fidelity=False,
load_nasbench=True,
compare_reduced=True,
compare_use_hash=False,
validate_spec=True,
):
super(NasBench101SearchSpace, self).__init__()
self.ops_choices = ["conv1x1-bn-relu",
"conv3x3-bn-relu", "maxpool3x3", "none"]
awnas_ops = [
"conv_bn_relu_1x1",
"conv_bn_relu_3x3",
"max_pool_3x3",
"none",
]
self.op_mapping = {k: v for k, v in zip(self.ops_choices, awnas_ops)}
self.ops_choice_to_idx = {
choice: i for i, choice in enumerate(self.ops_choices)
}
# operations: "conv3x3-bn-relu", "conv1x1-bn-relu", "maxpool3x3"
self.multi_fidelity = multi_fidelity
self.load_nasbench = load_nasbench
self.compare_reduced = compare_reduced
self.compare_use_hash = compare_use_hash
self.num_vertices = VERTICES
self.max_edges = MAX_EDGES
self.none_op_ind = self.ops_choices.index("none")
self.num_possible_edges = self.num_vertices * \
(self.num_vertices - 1) // 2
self.num_op_choices = len(self.ops_choices) # 3 + 1 (none)
self.num_ops = self.num_vertices - 2 # 5
self.idx = np.triu_indices(self.num_vertices, k=1)
self.validate_spec = validate_spec
if self.load_nasbench:
self._init_nasbench()
def __getstate__(self):
state = super(NasBench101SearchSpace, self).__getstate__().copy()
del state["nasbench"]
return state
def __setstate__(self, state):
super(NasBench101SearchSpace, self).__setstate__(state)
if self.load_nasbench:
# slow, comment this if do not need to load nasbench API when pickle load from disk
self._init_nasbench()
def pad_archs(self, archs):
return [self._pad_arch(arch) for arch in archs]
def _pad_arch(self, arch):
# padding for batchify training
adj, ops = arch
# all normalize the the reduced one
spec = self.construct_modelspec(edges=None, matrix=adj, ops=ops)
adj, ops = spec.matrix, self.op_to_idx(spec.ops)
num_v = adj.shape[0]
if num_v < VERTICES:
padded_adj = np.concatenate(
(adj[:-1], np.zeros((VERTICES - num_v, num_v), dtype=np.int8), adj[-1:])
)
padded_adj = np.concatenate(
(
padded_adj[:, :-1],
np.zeros((VERTICES, VERTICES - num_v)),
padded_adj[:, -1:],
),
axis=1,
)
padded_ops = ops + [3] * (7 - num_v)
adj, ops = padded_adj, padded_ops
return (adj, ops)
def _random_sample_ori(self):
while 1:
matrix = np.random.choice(
[0, 1], size=(self.num_vertices, self.num_vertices)
)
matrix = np.triu(matrix, 1)
ops = np.random.choice(
self.ops_choices[:-1], size=(self.num_vertices)
).tolist()
ops[0] = "input"
ops[-1] = "output"
spec = _ModelSpec(matrix=matrix, ops=ops)
if self.validate_spec and not self.nasbench.is_valid(spec):
continue
return NasBench101Rollout(
spec.original_matrix,
ops=self.op_to_idx(spec.original_ops),
search_space=self,
)
def _random_sample_me(self):
while 1:
splits = np.array(
sorted(
[0]
+ list(
np.random.randint(
0, self.max_edges + 1, size=self.num_possible_edges - 1
)
)
+ [self.max_edges]
)
)
edges = np.minimum(splits[1:] - splits[:-1], 1)
matrix = self.edges_to_matrix(edges)
ops = np.random.randint(0, self.num_op_choices, size=self.num_ops)
rollout = NasBench101Rollout(matrix, ops, search_space=self)
try:
self.nasbench._check_spec(rollout.genotype)
except api.OutOfDomainError:
# ignore out-of-domain archs (disconnected)
continue
else:
return rollout
# optional API
def genotype_from_str(self, genotype_str):
return eval(genotype_str)
return eval(re.search("(_ModelSpec\(.+);", genotype_str).group(1) + ")")
# ---- APIs ----
def random_sample(self):
m, ops = self.sample(True)
if len(ops) < len(m) - 2:
ops.append("none")
return NasBench101Rollout(m, [self.ops_choices.index(op) for op in ops], search_space=self)
return self._random_sample_ori()
def genotype(self, arch):
# return the corresponding ModelSpec
# edges, ops = arch
matrix, ops = arch
return self.construct_modelspec(edges=None, matrix=matrix, ops=ops)
def rollout_from_genotype(self, genotype):
return NasBench101Rollout(
genotype.original_matrix,
ops=self.op_to_idx(genotype.original_ops),
search_space=self,
)
def plot_arch(self, genotypes, filename, label, plot_format="pdf", **kwargs):
graph = genotypes.visualize()
graph.format = "pdf"
graph.render(filename, view=False)
return filename + ".{}".format(plot_format)
def distance(self, arch1, arch2):
pass
# ---- helpers ----
def _init_nasbench(self):
# the arch -> performances dataset
self.base_dir = os.path.join(
utils.get_awnas_dir("AWNAS_DATA", "data"), "nasbench-101"
)
if self.multi_fidelity:
self.nasbench = api.NASBench(
os.path.join(self.base_dir, "nasbench_full.tfrecord")
)
else:
self.nasbench = api.NASBench(
os.path.join(self.base_dir, "nasbench_only108.tfrecord")
)
def edges_to_matrix(self, edges):
matrix = np.zeros(
[self.num_vertices, self.num_vertices], dtype=np.int8)
matrix[self.idx] = edges
return matrix
def op_to_idx(self, ops):
return [
self.ops_choice_to_idx[op] for op in ops if op not in {"input", "output"}
]
def matrix_to_edges(self, matrix):
return matrix[self.idx]
def matrix_to_connection(self, matrix):
edges = matrix[self.idx].astype(np.bool)
node_connections = {}
concat_nodes = []
for from_, to_ in zip(self.idx[0][edges], self.idx[1][edges]):
# index of nodes starts with 1 rather than 0
if to_ < len(matrix) - 1:
node_connections.setdefault(to_, []).append(from_)
else:
if from_ >= len(matrix) - 2:
continue
concat_nodes.append(from_)
return node_connections, concat_nodes
def construct_modelspec(self, edges, matrix, ops):
if matrix is None:
assert edges is not None
matrix = self.edges_to_matrix(edges)
# expect(graph_util.num_edges(matrix) <= self.max_edges,
# "number of edges could not exceed {}".format(self.max_edges))
labeling = [self.ops_choices[op_ind] for op_ind in ops]
labeling = ["input"] + list(labeling) + ["output"]
model_spec = _ModelSpec(matrix, labeling)
return model_spec
def random_sample_arch(self):
# not uniform, and could be illegal,
# if there is not edge from the INPUT or no edge to the OUTPUT,
# Just check and reject for now
return self.random_sample().arch
def batch_rollouts(self, batch_size, shuffle=True, max_num=None):
len_ = ori_len_ = len(self.nasbench.fixed_statistics)
if max_num is not None:
len_ = min(max_num, len_)
list_ = list(self.nasbench.fixed_statistics.values())
indexes = np.arange(ori_len_)
np.random.shuffle(indexes)
ind = 0
while ind < len_:
end_ind = min(len_, ind + batch_size)
yield [
NasBench101Rollout(
list_[r_ind]["module_adjacency"],
self.op_to_idx(list_[r_ind]["module_operations"]),
search_space=self,
)
for r_ind in indexes[ind:end_ind]
]
ind = end_ind
@classmethod
def supported_rollout_types(cls):
return ["nasbench-101"]
class NasBench101OneShotSearchSpace(NasBench101SearchSpace):
# NAME = "nasbench-101-1shot"
def __init__(
self,
multi_fidelity=False,
load_nasbench=True,
compare_reduced=True,
compare_use_hash=False,
validate_spec=True,
num_cell_groups=2,
num_init_nodes=1,
cell_layout=None,
reduce_cell_groups=(1,),
num_layers=8,
):
super(NasBench101OneShotSearchSpace, self).__init__(
multi_fidelity,
load_nasbench,
compare_reduced,
compare_use_hash,
validate_spec,
)
self.num_init_nodes = num_init_nodes
self.num_cell_groups = num_cell_groups
self.reduce_cell_groups = reduce_cell_groups
self.num_layers = num_layers
if cell_layout is not None:
expect(
len(cell_layout) == self.num_layers,
"Length of `cell_layout` should equal `num_layers`",
)
expect(
np.max(cell_layout) == self.num_cell_groups - 1,
"Max of elements of `cell_layout` should equal `num_cell_groups-1`",
)
self.cell_layout = cell_layout
elif self.num_cell_groups == 2:
# by default: cell 0: normal cel, cell 1: reduce cell
self.cell_layout = [0] * self.num_layers
self.cell_layout[self.num_layers // 3] = 1
self.cell_layout[(2 * self.num_layers) // 3] = 1
else:
raise ValueError
self.loose_end = False
self.num_steps = 4
self.concat_op = "concat"
self.concat_nodes = None
self.cellwise_primitives = False
self.shared_primitives = self.ops_choices
self.num_parents = None
if self.load_nasbench:
self._init_nasbench()
def _is_valid(self, matrix):
assert self.num_parents is not None, \
"Do no use nasbench-101-1shot directly, please use nasbench-101-1shot-1, "\
"nasbench-101-1shot-2 or nasbench-101-1shot-3 search space instead."
num_node = list(matrix.sum(0))
if len(num_node) == VERTICES - 1:
num_node.insert(-2, 0)
return all([p == k for p, k in zip(self.num_parents, num_node)])
@abc.abstractmethod
def create_nasbench_adjacency_matrix(self, parents, **kwargs):
"""Based on given connectivity pattern create the corresponding adjacency matrix."""
pass
def sample(self, with_loose_ends, upscale=True):
if with_loose_ends:
adjacency_matrix_sample = self._sample_adjacency_matrix_with_loose_ends()
else:
adjacency_matrix_sample = self._sample_adjacency_matrix_without_loose_ends(
adjacency_matrix=np.zeros(
[self.num_intermediate_nodes + 2, self.num_intermediate_nodes + 2]),
node=self.num_intermediate_nodes + 1)
assert self._check_validity_of_adjacency_matrix(
adjacency_matrix_sample), 'Incorrect graph'
if upscale and self.NAME[-1] in ["1", "2"]:
adjacency_matrix_sample = upscale_to_nasbench_format(
adjacency_matrix_sample)
return adjacency_matrix_sample, random.choices(self.ops_choices[:-1], k=self.num_intermediate_nodes)
def _sample_adjacency_matrix_with_loose_ends(self):
parents_per_node = [random.sample(list(itertools.combinations(list(range(int(node))), num_parents)), 1) for
node, num_parents in self.num_parents_per_node.items()][2:]
parents = {
'0': [],
'1': [0]
}
for node, node_parent in enumerate(parents_per_node, 2):
parents[str(node)] = node_parent
adjacency_matrix = self._create_adjacency_matrix_with_loose_ends(
parents)
return adjacency_matrix
def _sample_adjacency_matrix_without_loose_ends(self, adjacency_matrix, node):
req_num_parents = self.num_parents_per_node[str(node)]
current_num_parents = np.sum(adjacency_matrix[:, node], dtype=np.int)
num_parents_left = req_num_parents - current_num_parents
sampled_parents = \
random.sample(list(parent_combinations_old(
adjacency_matrix, node, n_parents=num_parents_left)), 1)[0]
for parent in sampled_parents:
adjacency_matrix[parent, node] = 1
adjacency_matrix = self._sample_adjacency_matrix_without_loose_ends(
adjacency_matrix, parent)
return adjacency_matrix
@abc.abstractmethod
def generate_adjacency_matrix_without_loose_ends(self, **kwargs):
"""Returns every adjacency matrix in the search space without loose ends."""
pass
def convert_config_to_nasbench_format(self, config):
parents = {node: config["choice_block_{}_parents".format(node)] for node in
list(self.num_parents_per_node.keys())[1:]}
parents['0'] = []
adjacency_matrix = self.create_nasbench_adjacency_matrix_with_loose_ends(
parents)
ops = [config["choice_block_{}_op".format(node)] for node in list(
self.num_parents_per_node.keys())[1:-1]]
return adjacency_matrix, ops
def generate_search_space_without_loose_ends(self):
# Create all possible connectivity patterns
for iter, adjacency_matrix in enumerate(self.generate_adjacency_matrix_without_loose_ends()):
print(iter)
# Print graph
# Evaluate every possible combination of node ops.
n_repeats = int(np.sum(np.sum(adjacency_matrix, axis=1)[1:-1] > 0))
for combination in itertools.product([CONV1X1, CONV3X3, MAXPOOL3X3], repeat=n_repeats):
# Create node labels
# Add some op as node 6 which isn't used, here conv1x1
ops = [INPUT]
combination = list(combination)
for i in range(5):
if np.sum(adjacency_matrix, axis=1)[i + 1] > 0:
ops.append(combination.pop())
else:
ops.append(CONV1X1)
assert len(combination) == 0, 'Something is wrong'
ops.append(OUTPUT)
# Create nested list from numpy matrix
nasbench_adjacency_matrix = adjacency_matrix.astype(
np.int).tolist()
# Assemble the model spec
model_spec = api.ModelSpec(
# Adjacency matrix of the module
matrix=nasbench_adjacency_matrix,
# Operations at the vertices of the module, matches order of matrix
ops=ops)
yield adjacency_matrix, ops, model_spec
def _generate_adjacency_matrix(self, adjacency_matrix, node):
if self._check_validity_of_adjacency_matrix(adjacency_matrix):
# If graph from search space then yield.
yield adjacency_matrix
else:
req_num_parents = self.num_parents_per_node[str(node)]
current_num_parents = np.sum(
adjacency_matrix[:, node], dtype=np.int)
num_parents_left = req_num_parents - current_num_parents
for parents in parent_combinations_old(adjacency_matrix, node, n_parents=num_parents_left):
# Make copy of adjacency matrix so that when it returns to this stack
# it can continue with the unmodified adjacency matrix
adjacency_matrix_copy = copy.copy(adjacency_matrix)
for parent in parents:
adjacency_matrix_copy[parent, node] = 1
for graph in self._generate_adjacency_matrix(adjacency_matrix=adjacency_matrix_copy, node=parent):
yield graph
def _create_adjacency_matrix(self, parents, adjacency_matrix, node):
if self._check_validity_of_adjacency_matrix(adjacency_matrix):
# If graph from search space then yield.
return adjacency_matrix
else:
for parent in parents[str(node)]:
adjacency_matrix[parent, node] = 1
if parent != 0:
adjacency_matrix = self._create_adjacency_matrix(parents=parents, adjacency_matrix=adjacency_matrix,
node=parent)
return adjacency_matrix
def _create_adjacency_matrix_with_loose_ends(self, parents):
# Create the adjacency_matrix on a per node basis
adjacency_matrix = np.zeros([len(parents), len(parents)])
for node, node_parents in parents.items():
for parent in node_parents:
adjacency_matrix[parent, int(node)] = 1
return adjacency_matrix
def _check_validity_of_adjacency_matrix(self, adjacency_matrix):
"""
Checks whether a graph is a valid graph in the search space.
1. Checks that the graph is non empty
2. Checks that every node has the correct number of inputs
3. Checks that if a node has outgoing edges then it should also have incoming edges
4. Checks that input node is connected
5. Checks that the graph has no more than 9 edges
:param adjacency_matrix:
:return:
"""
# Check that the graph contains nodes
num_intermediate_nodes = sum(
np.array(np.sum(adjacency_matrix, axis=1) > 0, dtype=int)[1:-1])
if num_intermediate_nodes == 0:
return False
# Check that every node has exactly the right number of inputs
col_sums = np.sum(adjacency_matrix[:, :], axis=0)
for col_idx, col_sum in enumerate(col_sums):
# important FIX!
if col_idx > 0:
if col_sum != self.num_parents_per_node[str(col_idx)]:
return False
# Check that if a node has outputs then it should also have incoming edges (apart from zero)
col_sums = np.sum(np.sum(adjacency_matrix, axis=0) > 0)
row_sums = np.sum(np.sum(adjacency_matrix, axis=1) > 0)
if col_sums != row_sums:
return False
# Check that the input node is always connected. Otherwise the graph is disconnected.
row_sum = np.sum(adjacency_matrix, axis=1)
if row_sum[0] == 0:
return False
# Check that the graph returned has no more than 9 edges.
num_edges = np.sum(adjacency_matrix.flatten())
if num_edges > 9:
return False
return True
def get_layer_num_steps(self, layer_index):
return self.get_num_steps(self.cell_layout[layer_index])
def get_num_steps(self, cell_index):
return (
self.num_steps
if isinstance(self.num_steps, int)
else self.num_steps[cell_index]
)
def _random_sample_ori(self):
while 1:
matrix = np.random.choice(
[0, 1], size=(self.num_vertices, self.num_vertices)
)
matrix = np.triu(matrix, 1)
ops = np.random.choice(
self.ops_choices[:-1], size=(self.num_vertices)
).tolist()
ops[0] = "input"
ops[-1] = "output"
spec = _ModelSpec(matrix=matrix, ops=ops)
if (
self.validate_spec
and not self.nasbench.is_valid(spec)
and not self._is_valid(matrix)
):
continue
return NasBench101Rollout(
spec.original_matrix,
ops=self.op_to_idx(spec.original_ops),
search_space=self,
)
class NasBench101OneShot1SearchSpace(NasBench101OneShotSearchSpace):
NAME = "nasbench-101-1shot-1"
def __init__(
self,
multi_fidelity=False,
load_nasbench=True,
compare_reduced=True,
compare_use_hash=False,
validate_spec=True,
num_cell_groups=2,
num_init_nodes=1,
cell_layout=None,
reduce_cell_groups=(1,),
num_layers=8,
):
super(NasBench101OneShot1SearchSpace, self).__init__(
multi_fidelity,
load_nasbench,
compare_reduced,
compare_use_hash,
validate_spec,
num_cell_groups,
num_init_nodes,
cell_layout,
reduce_cell_groups,
num_layers,
)
self.num_parents = [0, 1, 2, 2, 2, 0, 2]
self.num_parents_per_node = {
'0': 0,
'1': 1,
'2': 2,
'3': 2,
'4': 2,
'5': 2
}
self.num_intermediate_nodes = 4
assert sum(self.num_parents) == 9, "The num of edges must equal to 9."
def create_nasbench_adjacency_matrix(self, parents, **kwargs):
adjacency_matrix = self._create_adjacency_matrix(parents, adjacency_matrix=np.zeros([6, 6]),
node=OUTPUT_NODE - 1)
# Create nasbench compatible adjacency matrix
return upscale_to_nasbench_format(adjacency_matrix)
def create_nasbench_adjacency_matrix_with_loose_ends(self, parents):
return upscale_to_nasbench_format(self._create_adjacency_matrix_with_loose_ends(parents))
def generate_adjacency_matrix_without_loose_ends(self):
for adjacency_matrix in self._generate_adjacency_matrix(adjacency_matrix=np.zeros([6, 6]),
node=OUTPUT_NODE - 1):
yield upscale_to_nasbench_format(adjacency_matrix)
def generate_with_loose_ends(self):
for _, parent_node_3, parent_node_4, output_parents in itertools.product(
*[itertools.combinations(list(range(int(node))), num_parents) for node, num_parents in
self.num_parents_per_node.items()][2:]):
parents = {
'0': [],
'1': [0],
'2': [0, 1],
'3': parent_node_3,
'4': parent_node_4,
'5': output_parents
}
adjacency_matrix = self.create_nasbench_adjacency_matrix_with_loose_ends(
parents)
yield adjacency_matrix
class NasBench101OneShot2SearchSpace(NasBench101OneShotSearchSpace):
NAME = "nasbench-101-1shot-2"
def __init__(
self,
multi_fidelity=False,
load_nasbench=True,
compare_reduced=True,
compare_use_hash=False,
validate_spec=True,
num_cell_groups=2,
num_init_nodes=1,
cell_layout=None,
reduce_cell_groups=(1,),
num_layers=8,
):
super(NasBench101OneShot2SearchSpace, self).__init__(
multi_fidelity,
load_nasbench,
compare_reduced,
compare_use_hash,
validate_spec,
num_cell_groups,
num_init_nodes,
cell_layout,
reduce_cell_groups,
num_layers,
)
self.num_parents = [0, 1, 1, 2, 2, 0, 3]
self.num_parents_per_node = {
'0': 0,
'1': 1,
'2': 1,
'3': 2,
'4': 2,
'5': 3
}
self.num_intermediate_nodes = 4
assert sum(self.num_parents) == 9, "The num of edges must equal to 9."
def create_nasbench_adjacency_matrix(self, parents, **kwargs):
adjacency_matrix = self._create_adjacency_matrix(parents, adjacency_matrix=np.zeros([6, 6]),
node=OUTPUT_NODE - 1)
# Create nasbench compatible adjacency matrix
return upscale_to_nasbench_format(adjacency_matrix)
def create_nasbench_adjacency_matrix_with_loose_ends(self, parents):
return upscale_to_nasbench_format(self._create_adjacency_matrix_with_loose_ends(parents))
def generate_adjacency_matrix_without_loose_ends(self):
for adjacency_matrix in self._generate_adjacency_matrix(adjacency_matrix=np.zeros([6, 6]),
node=OUTPUT_NODE - 1):
yield upscale_to_nasbench_format(adjacency_matrix)
def generate_with_loose_ends(self):
for parent_node_2, parent_node_3, parent_node_4, output_parents in itertools.product(
*[itertools.combinations(list(range(int(node))), num_parents) for node, num_parents in
self.num_parents_per_node.items()][2:]):
parents = {
'0': [],
'1': [0],
'2': parent_node_2,
'3': parent_node_3,
'4': parent_node_4,
'5': output_parents
}
adjacency_matrix = self.create_nasbench_adjacency_matrix_with_loose_ends(
parents)
yield adjacency_matrix
class NasBench101OneShot3SearchSpace(NasBench101OneShotSearchSpace):
NAME = "nasbench-101-1shot-3"
def __init__(
self,
multi_fidelity=False,
load_nasbench=True,
compare_reduced=True,
compare_use_hash=False,
validate_spec=True,
num_cell_groups=2,
num_init_nodes=1,
cell_layout=None,
reduce_cell_groups=(1,),
num_layers=8,
):
super(NasBench101OneShot3SearchSpace, self).__init__(
multi_fidelity,
load_nasbench,
compare_reduced,
compare_use_hash,
validate_spec,
num_cell_groups,
num_init_nodes,
cell_layout,
reduce_cell_groups,
num_layers,
)
self.num_parents = [0, 1, 1, 1, 2, 2, 2]
self.num_parents_per_node = {
'0': 0,
'1': 1,
'2': 1,
'3': 1,
'4': 2,
'5': 2,
'6': 2
}
self.num_intermediate_nodes = 5
assert sum(self.num_parents) == 9, "The num of edges must equal to 9."
def create_nasbench_adjacency_matrix(self, parents, **kwargs):
# Create nasbench compatible adjacency matrix
adjacency_matrix = self._create_adjacency_matrix(
parents, adjacency_matrix=np.zeros([7, 7]), node=OUTPUT_NODE)
return adjacency_matrix
def create_nasbench_adjacency_matrix_with_loose_ends(self, parents):
return self._create_adjacency_matrix_with_loose_ends(parents)
def generate_adjacency_matrix_without_loose_ends(self):
for adjacency_matrix in self._generate_adjacency_matrix(adjacency_matrix=np.zeros([7, 7]), node=OUTPUT_NODE):
yield adjacency_matrix
def generate_with_loose_ends(self):
for parent_node_2, parent_node_3, parent_node_4, parent_node_5, output_parents in itertools.product(
*[itertools.combinations(list(range(int(node))), num_parents) for node, num_parents in
self.num_parents_per_node.items()][2:]):
parents = {
'0': [],
'1': [0],
'2': parent_node_2,
'3': parent_node_3,
'4': parent_node_4,
'5': parent_node_5,
'6': output_parents
}
adjacency_matrix = self.create_nasbench_adjacency_matrix_with_loose_ends(
parents)
yield adjacency_matrix
class NasBench101Rollout(BaseRollout):
NAME = "nasbench-101"
supported_components = [("evaluator", "mepa"), ("trainer", "simple")]
def __init__(self, matrix, ops, search_space):
self._arch = (matrix, ops)
self.search_space = search_space
self.perf = collections.OrderedDict()
self._genotype = None
@property
def arch(self):
return self._arch
@property
def pruned_arch(self):
matrix, ops = self._arch
index = [i for i, op in enumerate(ops) if op != 3]
ops = [ops[i] for i in index]
index = [0] + [i + 1 for i in index] + [6]
matrix = matrix[index][:, index]
return matrix, ops
def set_candidate_net(self, c_net):
raise Exception("Should not be called")
def plot_arch(self, filename, label="", edge_labels=None):
return self.search_space.plot_arch(
self.genotype, filename, label=label, edge_labels=edge_labels
)
@property
def genotype(self):
if self._genotype is None:
self._genotype = self.search_space.genotype(self.pruned_arch)
return self._genotype
def __repr__(self):
return "NasBench101Rollout(matrix={arch}, perf={perf})".format(
arch=self.arch, perf=self.perf
)
def __eq__(self, other):
if self.search_space.compare_reduced:
if self.search_space.compare_use_hash:
# compare using hash, isomorphic archs would be equal
return self.genotype.hash_spec() == other.genotype.hash_spec()
else:
# compared using reduced archs
return (
np.array(self.genotype.matrix).tolist()
== np.array(other.genotype.matrix).tolist()
) and list(self.genotype.ops) == list(other.genotype.ops)
# compared using original/non-reduced archs, might be wrong
return (np.array(other.arch[0]).tolist(), list(other.arch[1])) == (
np.array(self.arch[0]).tolist(),
list(self.arch[1]),
)
class NasBench101CompareController(BaseController):
NAME = "nasbench-101-compare"
def __init__(
self,
search_space,
device,
rollout_type="compare",
mode="eval",
shuffle_indexes=True,
schedule_cfg=None,
):
super(NasBench101CompareController, self).__init__(
search_space, rollout_type, mode, schedule_cfg
)
self.shuffle_indexes = shuffle_indexes
# get the infinite iterator of the model matrix and ops
self.fixed_statistics = list(
self.search_space.nasbench.fixed_statistics.values()
)
self.num_data = len(self.fixed_statistics)
self.indexes = list(np.arange(self.num_data))
self.comp_indexes = list(np.arange(self.num_data))
self.cur_ind = 0
self.cur_comp_ind = 1
def sample(self, n=1, batch_size=None):
assert batch_size is None
rollouts = []
n_r = 0
while n_r < n:
fixed_stat = self.fixed_statistics[self.indexes[self.cur_ind]]
rollout_1 = NasBench101Rollout(
fixed_stat["module_adjacency"],
self.search_space.op_to_idx(fixed_stat["module_operations"]),
search_space=self.search_space,
)
if self.comp_indexes[self.cur_comp_ind] != self.indexes[self.cur_ind]:
fixed_stat_2 = self.fixed_statistics[
self.comp_indexes[self.cur_comp_ind]
]
rollout_2 = NasBench101Rollout(
fixed_stat_2["module_adjacency"],
self.search_space.op_to_idx(
fixed_stat_2["module_operations"]),
search_space=self.search_space,
)
rollouts.append(
CompareRollout(rollout_1=rollout_1, rollout_2=rollout_2)
)
n_r += 1
self.cur_comp_ind += 1
if self.cur_comp_ind >= self.num_data:
self.cur_comp_ind = 0
if self.shuffle_indexes:
random.shuffle(self.comp_indexes)
self.cur_ind += 1
if self.cur_ind >= self.num_data:
self.logger.info("One epoch end")
self.cur_ind = 0
if self.shuffle_indexes:
random.shuffle(self.indexes)
return rollouts
@classmethod
def supported_rollout_types(cls):
return ["compare"]
# ---- APIs that is not necessary ----
def set_device(self, device):
pass
def step(self, rollouts, optimizer, perf_name):
return 0.0
def summary(self, rollouts, log=False, log_prefix="", step=None):
pass
def save(self, path):