-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathutils.py
More file actions
1594 lines (1434 loc) · 67.3 KB
/
utils.py
File metadata and controls
1594 lines (1434 loc) · 67.3 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
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
import torch
import torchvision
import torchvision.transforms as transforms
import numpy as np
import orientations
import wandb
import common
import os
import policies
import shapely
import math
import subprocess
import pathlib
from torch.utils.data import Subset
import pickle
from shapely.geometry import Polygon
from torch_geometric.data import Data
from omegaconf import OmegaConf
from PIL import Image, ImageDraw
from pathlib import Path
from collections import OrderedDict
import re
import guidance
import csv
import time
import moviepy.editor
import plotly.graph_objects as go
import matplotlib.pyplot as plt
@torch.no_grad()
def validate(x_val, model, cond=None):
model.eval()
t = torch.randint(1, model.max_diffusion_steps + 1, [x_val.shape[0]], device = x_val.device)
if cond is None:
loss, model_metrics = model.loss(x_val, t)
else:
loss, model_metrics = model.loss(x_val, cond, t)
logs = {
"loss": loss.cpu().item()
}
logs.update(model_metrics)
model.train()
return logs
@torch.no_grad()
def display_predictions(x_val, y_val, model, logger, prefix = "val", text_labels = None):
model.eval()
log_probs = model(x_val)
probs = torch.nn.functional.softmax(log_probs, dim=-1)
predictions = log_probs.argmax(dim=-1)
for image, pred, label, prob, logit in zip(
torch.movedim(x_val, 1, -1).cpu().numpy(),
predictions.cpu().numpy(),
y_val.cpu().numpy(),
probs.cpu().numpy(),
log_probs.cpu().numpy(),
):
log_image = wandb.Image(image)
logs = {
"examples": {
"image": log_image,
"prediction": text_labels[pred] if text_labels else pred,
"ground truth": text_labels[label] if text_labels else label,
"pred prob": prob[pred],
"truth prob": prob[label],
"logit histogram": logit,
},
}
logger.add(logs, prefix = prefix)
model.train()
@torch.no_grad()
def display_samples(batch_size, model, logger, intermediate_every = 200, prefix = "val"):
model.eval()
samples, intermediates = model.reverse_samples(batch_size, intermediate_every = intermediate_every)
intermediate_stats = compute_intermediate_stats(intermediates)
intermediates = torch.cat(intermediates, dim = -1) # concat along width
for idx, (image, intermediate_image) in enumerate(zip(
torch.movedim(samples, 1, -1).cpu().numpy(),
torch.movedim(intermediates, 1, -1).cpu().numpy()
)):
log_image = wandb.Image(image)
log_intermediate = wandb.Image(intermediate_image)
logs = {
"reverse_examples": {
"sample": log_image,
"intermediates": log_intermediate,
},
}
for stat_name, stat in intermediate_stats.items():
logs["reverse_examples"][stat_name] = stat[idx]
logger.add(logs, prefix = prefix)
model.train()
@torch.no_grad()
def display_forward_samples(x_val, model, logger, intermediate_every = 200, prefix = "val"):
model.eval()
intermediates = model.forward_samples(x_val, intermediate_every = intermediate_every)
intermediate_stats = compute_intermediate_stats(intermediates)
intermediates = torch.cat(intermediates, dim = -1) # concat along width
for idx, (image, intermediate_image) in enumerate(zip(
torch.movedim(x_val, 1, -1).cpu().numpy(),
torch.movedim(intermediates, 1, -1).cpu().numpy(),
)):
log_image = wandb.Image(image)
log_intermediate = wandb.Image(intermediate_image)
logs = {
"forward_examples": {
"image": log_image,
"intermediates": log_intermediate,
},
}
for stat_name, stat in intermediate_stats.items():
logs["forward_examples"][stat_name] = stat[idx]
logger.add(logs, prefix = prefix)
model.train()
@torch.no_grad()
def display_graph_samples(batch_size, x_val, cond_val, model, logger, intermediate_every = 200, prefix = "val", eval_function = None, policy = "open_loop"):
model.eval()
# samples, intermediates = model.reverse_samples(batch_size, x_val, cond_val, intermediate_every = intermediate_every)
masks = None
info = {}
if policy == "open_loop":
samples, intermediates, _ = policies.open_loop(batch_size, model, x_val, cond_val, intermediate_every = intermediate_every)
elif policy == "open_loop_clustered":
samples, intermediates = policies.open_loop_clustered(batch_size, model, x_val, cond_val, intermediate_every = intermediate_every)
elif policy == "open_loop_multi":
samples, intermediates = policies.open_loop_multi(
model, x_val, cond_val, num_attempts = 8, score_fn = lambda x: check_legality(x, x_val[0], cond_val.x, cond_val.is_ports, True)
)
elif policy == "iterative":
samples, intermediates, masks, info = policies.iterative(
model, x_val, cond_val, score_fn = lambda x, mask: check_legality(x, x_val[0], cond_val.x, mask, True) > 0.99
)
else:
raise NotImplementedError
if masks is None:
intermediate_images = [generate_batch_visualizations(inter, cond_val) for inter in intermediates]
else:
intermediate_images = [generate_batch_visualizations(inter, cond_val, mask) for inter, mask in zip(intermediates, masks)]
intermediate_images = torch.cat(intermediate_images, dim = -1) # concat along width
sample_images = generate_batch_visualizations(samples, cond_val)
# should be a list of dicts, each dict corresponds to one sample
eval_metrics = eval_function(samples, x_val, cond_val) if eval_function is not None else [{}] * batch_size
for idx, (image, intermediate_image) in enumerate(zip(
torch.movedim(sample_images, 1, -1).cpu().numpy(),
torch.movedim(intermediate_images, 1, -1).cpu().numpy()
)):
log_image = wandb.Image(image)
log_intermediate = wandb.Image(intermediate_image)
logs = {
"reverse_examples": {
"sample": log_image,
"intermediates": log_intermediate,
**eval_metrics[idx],
**info,
},
}
logger.add(logs, prefix = prefix)
model.train()
return eval_metrics
@torch.no_grad()
def display_forward_graph_samples(x_val, cond_val, model, logger, intermediate_every = 200, prefix = "val"):
model.eval()
intermediates = model.forward_samples(x_val, cond_val, intermediate_every = intermediate_every)
intermediate_stats = compute_intermediate_stats(intermediates)
intermediate_images = [generate_batch_visualizations(inter, cond_val) for inter in intermediates]
intermediate_images = torch.cat(intermediate_images, dim = -1) # concat along width
x_images = generate_batch_visualizations(x_val, cond_val)
for idx, (image, intermediate_image) in enumerate(zip(
torch.movedim(x_images, 1, -1).cpu().numpy(),
torch.movedim(intermediate_images, 1, -1).cpu().numpy(),
)):
log_image = wandb.Image(image)
log_intermediate = wandb.Image(intermediate_image)
logs = {
"forward_examples": {
"image": log_image,
"intermediates": log_intermediate,
},
}
for stat_name, stat in intermediate_stats.items():
logs["forward_examples"][stat_name] = stat[idx]
logger.add(logs, prefix = prefix)
model.train()
@torch.no_grad()
def generate_report(num_samples, dataloader, model, logger, policy = "iterative", intermediate_every = 200):
metrics = common.Metrics()
for _ in range(num_samples):
x_eval, cond_eval = dataloader.get_batch("val")
x_eval = x_eval[:1]
sample_metrics = display_graph_samples(1, x_eval, cond_eval, model, logger, prefix = "eval", eval_function = eval_samples, policy = policy, intermediate_every = intermediate_every)
for sample_metric in sample_metrics:
metrics.add(sample_metric)
cond_eval.to(device = "cpu")
# compile metrics and compute stats
logger.add(metrics.result(), prefix = "eval")
@torch.no_grad()
def save_outputs(
x_in,
cond,
model,
save_folder,
output_number_offset=0,
policy="open_loop",
policy_kwargs = {},
preprocess_fn=None,
postprocess_fn=None,
legalization_fn=None,
):
"""
x_in and cond are both assumed to be on CPU
x_in has shape (V, 2)
preprocess_fn: x_in, cond -> x_in, cond
postprocess_fn: sample, cond -> sample
Returns:
- metrics: Dict
- sample: (V, 2) tensor
- cond: Data object
All outputs are after preprocessing, and before postprocessing. tensors are on cpu
"""
idx = cond.file_idx if "file_idx" in cond else output_number_offset
x_in = torch.unsqueeze(x_in, dim=0).to(model.device)
original_device = cond.x.device
cond.to(model.device)
metrics = {}
metrics_special = {} # For things that should not be aggregated like plots, images, etc.
# user-defined preprocess function
t0 = time.time()
x_preprocessed, cond_preprocessed = preprocess_fn(x_in, cond) if preprocess_fn is not None else (x_in, cond)
t1 = time.time()
if cond_preprocessed.num_nodes == 0:
# handle edge case with 0 nodes after preprocessing
sample = torch.zeros_like(x_preprocessed)
else:
if policy == "open_loop":
sample, _, policy_metrics_special = policies.open_loop(1, model, x_preprocessed, cond_preprocessed, intermediate_every = 0, save_videos = policy_kwargs["save_videos"])
metrics_special.update(policy_metrics_special)
elif policy == "open_loop_clustered":
sample, _ = policies.open_loop_clustered(1, model, x_preprocessed, cond_preprocessed, intermediate_every = 0)
elif policy == "iterative_clustering":
sample, policy_metrics, policy_metrics_special = policies.iterative_clustering(1, model, x_preprocessed, cond_preprocessed, **policy_kwargs)
metrics.update(policy_metrics)
metrics_special.update(policy_metrics_special)
elif policy == "random":
sample = policies.random(1, x_preprocessed, cond_preprocessed)
else:
raise NotImplementedError
t2 = time.time()
# save image too
image = visualize_placement(sample[0], cond_preprocessed, plot_pins=True, plot_edges=False, img_size=(2048, 2048))
# legalization
if legalization_fn is not None:
sample, legalization_metrics, legalization_metrics_special = legalization_fn(sample, cond_preprocessed)
metrics.update(legalization_metrics)
metrics_special.update(legalization_metrics_special)
image_legalized = visualize_placement(sample[0], cond_preprocessed, plot_pins=True, plot_edges=False, img_size=(2048, 2048))
else:
image_legalized = image
debug_plot_img(image_legalized, os.path.join(save_folder, f"placed{idx}"))
# user-defined postprocess function
sample_unprocessed = sample.detach().clone()
sample, cond_postprocessed = postprocess_fn(sample, cond_preprocessed)
sample = sample.squeeze(dim=0).detach().to(device = cond.x.device)
sample = postprocess_placement(sample, cond_postprocessed).cpu().numpy() # mandatory post-processing
save_file = os.path.join(save_folder, f"sample{idx}.pkl")
with open(save_file, 'wb') as f:
pickle.dump(sample, f)
t3 = time.time()
# evaluate sample and generate sampling metrics
hpwl_normalized, hpwl_rescaled = hpwl_fast(sample_unprocessed[0], cond_preprocessed, normalized_hpwl=False)
macro_hpwl_normalized, macro_hpwl_rescaled = macro_hpwl(sample_unprocessed[0], cond_preprocessed, normalized_hpwl=False)
legality = check_legality_new(sample_unprocessed[0], x_in[0], cond_preprocessed, cond_preprocessed.is_ports, score=True)
if "is_macros" in cond:
macro_legality = check_legality_new(sample_unprocessed[0], x_in[0], cond_preprocessed, (~cond_preprocessed.is_macros) | cond_preprocessed.is_ports, score=True)
else:
macro_legality = 0.0
original_hpwl_normalized = hpwl_fast(x_preprocessed, cond_preprocessed, normalized_hpwl=True)
t4 = time.time()
cond.to(original_device)
metrics.update({
"idx": idx,
"hpwl_normalized": hpwl_normalized,
"hpwl_rescaled": hpwl_rescaled,
"macro_hpwl_normalized": macro_hpwl_normalized,
"macro_hpwl_rescaled": macro_hpwl_rescaled,
"legality_2": legality,
"macro_legality": macro_legality,
"original_hpwl_normalized": original_hpwl_normalized,
"hpwl_ratio": hpwl_normalized/max(1e-12, original_hpwl_normalized),
"model_time": t2-t1,
"generation_time": t3-t0,
"eval_time": t4-t3,
"model_vertices": cond_preprocessed.num_nodes, # number of vertices that model input has
"model_edges": cond_preprocessed.num_edges, # number of edges that model input has
})
return metrics, metrics_special, image, image_legalized
def compute_intermediate_stats(intermediates):
# input: intermediates is a list, each is (B, C, H, W)
# outputs: dict of stats, each value is torch tensor with shape (B, T)
stats_to_compute = {"mean": torch.mean, "std": torch.std}
stats = {}
for stat_name, stat_fn in stats_to_compute.items():
stat_list = [stat_fn(image.view(image.shape[0], -1), dim=1) for image in intermediates]
stat = torch.cat(stat_list, -1)
stats[stat_name] = stat
return stats
def eval_samples(samples, x_val, cond_val, use_new_legality_fn = True):
# evaluates generated samples
# returns a list (length B) of dicts, each dict corresponds to one sample
# samples and x_val are (B, V, F)
eval_metrics = []
cond_ports = cond_val.is_ports
for idx, (sample, x) in enumerate(zip(samples, x_val)):
V, F = sample.shape
sample_hpwl = hpwl(sample, cond_val)
original_hpwl = hpwl(x, cond_val)
current_metrics = {
"num_vertices": V,
"num_edges": cond_val.edge_index.shape[1],
# "legality_score": check_legality(sample, x, cond_val, cond_ports, score=True), # Deprecated! don't use this
# "is_legal": check_legality(sample, x, cond_val, cond_ports, score=False),
"gen_hpwl": sample_hpwl,
"original_hpwl": original_hpwl,
"hpwl_ratio": sample_hpwl/original_hpwl if original_hpwl!=0 else 0,
}
if use_new_legality_fn:
current_metrics["legality_score_2"] = check_legality_new(sample, x, cond_val, cond_ports, score=True)
eval_metrics.append(current_metrics)
return eval_metrics
def load_graph_data(dataset_name, augment = False, train_data_limit = None, val_data_limit = None):
dataset_sizes = { # name: (train size, val size, chip width, chip height, scale)
}
dataset_path = os.path.join(os.path.dirname(__file__), f'../datasets/graph/{dataset_name}')
if os.path.exists(dataset_path):
if dataset_name in dataset_sizes:
TRAIN_SIZE, VAL_SIZE, chip_width, chip_height, scale = dataset_sizes[dataset_name]
else:
return load_graph_data_with_config(dataset_name, train_data_limit=train_data_limit, val_data_limit=val_data_limit)
if train_data_limit is None or train_data_limit == "none":
train_data_limit = TRAIN_SIZE
if val_data_limit is None or val_data_limit == "none":
val_data_limit = VAL_SIZE
assert train_data_limit <= TRAIN_SIZE and val_data_limit <= VAL_SIZE, "data limits invalid"
train_set = []
val_set = []
missing_data = 0
for i in range(TRAIN_SIZE + VAL_SIZE):
if not (i<train_data_limit or (i>=TRAIN_SIZE and i-TRAIN_SIZE<val_data_limit)):
continue
cond_path = os.path.join(dataset_path, f"graph{i}.pickle")
x_path = os.path.join(dataset_path, f"output{i}.pickle")
if not (os.path.exists(cond_path) and os.path.exists(dataset_path)):
missing_data += 1
if missing_data <= 5:
print(f"WARNING: {i} of dataset not found in {dataset_path}")
if missing_data == 5:
print(f"Suppressing missing data warnings...")
continue
cond = load_and_parse_graph(cond_path)
x = open_pickle(x_path)
x, cond = preprocess_graph(x, cond, (chip_width, chip_height), scale)
if i<TRAIN_SIZE:
train_set.append((x, cond))
else:
val_set.append((x, cond))
if missing_data > 0:
print(f"WARNING: total of {missing_data} samples not found. Continuing...")
else:
try:
return load_synthetic_graph_data(dataset_name, train_data_limit, val_data_limit)
except NotImplementedError:
raise
return train_set, val_set
def load_graph_data_with_config(dataset_name, train_data_limit = None, val_data_limit = None, override_placement_path = None, placement_format = "output*.pickle"):
# loads data in a way that maintains link with original files
# Algorithm:
# load and parse config
# sort all files (graphXX and outputXX) in increasing order of number XX
# the first TRAIN_SIZE examples are in the training set, next VAL_SIZE are in test set
# generate a list of filenames along with placement and netlist
dataset_path = os.path.join(os.path.dirname(__file__), f'../datasets/graph/{dataset_name}')
placement_path = dataset_path if override_placement_path is None else override_placement_path
if os.path.exists(dataset_path):
config = get_dataset_config(dataset_name)
TRAIN_SIZE = config.train_samples
VAL_SIZE = config.val_samples
scale = config.scale
if train_data_limit is None or train_data_limit == "none":
train_data_limit = TRAIN_SIZE
if val_data_limit is None or val_data_limit == "none":
val_data_limit = VAL_SIZE
assert train_data_limit <= TRAIN_SIZE and val_data_limit <= VAL_SIZE, "data limits invalid"
graph_files = {int(re.search('\d+', p.name).group()):str(p) for p in Path(dataset_path).rglob("graph*.pickle")}
placement_files = {int(re.search('\d+', p.name).group()):str(p) for p in Path(placement_path).rglob(placement_format)}
idx_list = list(graph_files.keys())
idx_list.sort()
intersect_list = list(graph_files.keys() & placement_files.keys())
if len(intersect_list) != len(idx_list):
print(f"WARNING: some graph files have no corresponding placements. {len(intersect_list)} of {len(idx_list)} placements found.")
assert TRAIN_SIZE + VAL_SIZE <= len(idx_list), "not enough valid data files found for TRAIN_SIZE and VAL_SIZE specified"
train_idx = idx_list[:train_data_limit]
val_idx = idx_list[TRAIN_SIZE:TRAIN_SIZE + val_data_limit]
train_set = []
val_set = []
for train_i in train_idx:
cond_path = graph_files[train_i]
x_path = placement_files.get(train_i, None)
cond = load_and_parse_graph(cond_path)
if x_path is not None:
x = open_pickle(x_path)
else:
x = torch.zeros_like(cond.x)
if "chip_size" in cond:
if len(cond.chip_size) == 4: # chip_size is [x_start, y_start, x_end, y_end]
chip_size = (cond.chip_size[2] - cond.chip_size[0], cond.chip_size[3] - cond.chip_size[1])
chip_offset = (cond.chip_size[0], cond.chip_size[1])
else:
chip_size = (cond.chip_size[0], cond.chip_size[1])
chip_offset = (0, 0)
else:
chip_size = (config.chip_width, config.chip_height)
chip_offset = (0, 0)
x, cond = preprocess_graph(x, cond, chip_size, scale, chip_offset=chip_offset)
cond.file_idx = train_i
train_set.append((x, cond))
for val_i in val_idx:
cond_path = graph_files[val_i]
x_path = placement_files.get(val_i, None)
cond = load_and_parse_graph(cond_path)
if x_path is not None:
x = open_pickle(x_path)
else:
x = torch.zeros_like(cond.x)
if "chip_size" in cond:
if len(cond.chip_size) == 4: # chip_size is [x_start, y_start, x_end, y_end]
chip_size = (cond.chip_size[2] - cond.chip_size[0], cond.chip_size[3] - cond.chip_size[1])
chip_offset = (cond.chip_size[0], cond.chip_size[1])
else:
chip_size = (cond.chip_size[0], cond.chip_size[1])
chip_offset = (0, 0)
else:
chip_size = (config.chip_width, config.chip_height)
chip_offset = (0, 0)
x, cond = preprocess_graph(x, cond, chip_size, scale, chip_offset=chip_offset)
cond.file_idx = val_i
if dataset_name == "ispd2005": # TODO fix special case
cond.is_ports = torch.zeros_like(cond.is_ports)
val_set.append((x, cond))
else:
try:
return load_synthetic_graph_data(dataset_name, train_data_limit, val_data_limit)
except NotImplementedError:
raise
return train_set, val_set
def get_dataset_config(dataset_name):
# raises error if file is not found
dataset_path = os.path.join(os.path.dirname(__file__), f'../datasets/graph/{dataset_name}')
if os.path.exists(dataset_path):
config_path = os.path.join(dataset_path, "config.yaml")
config = OmegaConf.load(config_path)
return config
else:
raise FileNotFoundError
def load_synthetic_graph_data(dataset_name, train_data_limit = None, val_data_limit = None):
dataset_path = os.path.join(os.path.dirname(__file__), '../data-gen/outputs', dataset_name)
NEEDS_CENTERING = False
# load dataset config
config_path = list(Path(dataset_path).glob("config.yaml"))
assert len(config_path) > 0, f"config path not found in {dataset_path}"
dataset_config = OmegaConf.load(config_path[0])
if ("num_train_samples" in dataset_config and "num_val_samples" in dataset_config):
TRAIN_SIZE = dataset_config.num_train_samples
VAL_SIZE = dataset_config.num_val_samples
data_files = {int(re.search('\d+', p.name).group()):str(p) for p in Path(dataset_path).rglob("*.pickle")}
data_files = OrderedDict(sorted(data_files.items()))
if train_data_limit is None or train_data_limit == "none":
train_data_limit = TRAIN_SIZE
if val_data_limit is None or val_data_limit == "none":
val_data_limit = VAL_SIZE
assert train_data_limit <= TRAIN_SIZE and val_data_limit <= VAL_SIZE, "data limits invalid"
train_set = []
val_set = []
for _, data_file in data_files.items():
x = open_pickle(data_file)
new_len = len(x)
train_len = min(train_data_limit-len(train_set), new_len)
val_len = min(val_data_limit-len(val_set), new_len-train_len)
train_samples = x[:train_len]
val_samples = x[train_len:train_len+val_len]
train_samples = [preprocess_synthetic_graph(x, cond, NEEDS_CENTERING) for x, cond in train_samples]
val_samples = [preprocess_synthetic_graph(x, cond, NEEDS_CENTERING) for x, cond in val_samples]
train_set.extend(train_samples)
val_set.extend(val_samples)
if len(train_set) == train_data_limit and len(val_set) == val_data_limit:
break
else:
# dataset is a mixture of other datasets
data_mix = dataset_config.mixture
train_set = []
val_set = []
if train_data_limit is None or train_data_limit == "none":
train_data_limit = int(1e16)
else:
print("WARNING: mixture train set will truncate without shuffling, because train_data_limit is defined")
if val_data_limit is None or val_data_limit == "none":
val_data_limit = int(1e16)
else:
print("WARNING: mixture val set will truncate without shuffling, because val_data_limit is defined")
for k, v in data_mix.items(): # be careful of recursion
train_samples, val_samples = load_synthetic_graph_data(
k,
train_data_limit = v.num_train_samples,
val_data_limit = v.num_val_samples,
)
train_set.extend(train_samples)
val_set.extend(val_samples)
if len(train_set) >= train_data_limit and len(val_set) >= val_data_limit:
break
train_set = train_set[:train_data_limit]
val_set = val_set[:val_data_limit]
return train_set, val_set
def load_samples(samples_dir):
"""
Loads placements for generated samples, as well as the graphs
Then preprocesses them, and outputs the preprocessed placements and graphs
"""
# load graphs used to generate samples
samples_config_path = str(list(pathlib.Path(samples_dir).rglob("config.yaml"))[0])
cfg = OmegaConf.load(samples_config_path)
_, val_set = load_graph_data_with_config(
cfg.task,
train_data_limit = cfg.train_data_limit,
val_data_limit = cfg.val_data_limit,
override_placement_path = samples_dir,
placement_format = "sample*.pkl",
)
return val_set
def preprocess_synthetic_graph(x, cond, needs_centering=False):
"""
Preprocesses synthetic data.
Terminal positions are measured relative to center of instance, and normalized to canvas size
"""
if needs_centering:
x = x + cond.x/2
u_shape = cond.x[cond.edge_index[0,:]]
v_shape = cond.x[cond.edge_index[1,:]]
cond.edge_attr[:,:2] = cond.edge_attr[:,:2] - u_shape/2
cond.edge_attr[:,2:4] = cond.edge_attr[:,2:4] - v_shape/2
assert (cond.edge_index.shape[1] % 2 == 0) and (cond.edge_attr.shape[0] % 2 == 0), "graph edges must be undirected"
return x, cond
def preprocess_graph(x, cond, chip_size, scale = 1, chip_offset = (0, 0)):
# x: numpy float64 array with shape (V, 2) describing 2D position on canvas
# cond.x: torch float32 tensor (V, 2) describing instance sizes
# cond.edge_attr: torch float64 tensor (E, 4)
# chip_size: tuple of length 2; size of canvas in um
# chip_size: tuple of length 2; bottom left corner coordinates in um
chip_size = torch.tensor(chip_size, dtype = torch.float32).view(1, 2)
chip_offset = torch.tensor(chip_offset, dtype = torch.float32).view(1, 2)
# normalizes input data
cond.x = 2 * (cond.x / chip_size)
cond.edge_attr = cond.edge_attr.float()
# scale edge_attr with canvas size
cond.edge_attr[:,:2] = 2 * (cond.edge_attr[:,:2] / chip_size)
cond.edge_attr[:,2:4] = 2 * (cond.edge_attr[:,2:4] / chip_size)
# normalize placement data TODO fix torch.tensor warnings
x = (torch.tensor(x, dtype=torch.float32) - chip_offset)/scale
x = 2 * (x / chip_size) - 1
# use center of instance as coordinate point and reference for terminal
x = x + cond.x/2
u_shape = cond.x[cond.edge_index[0,:]]
v_shape = cond.x[cond.edge_index[1,:]]
cond.edge_attr[:,:2] = cond.edge_attr[:,:2] - u_shape/2
cond.edge_attr[:,2:4] = cond.edge_attr[:,2:4] - v_shape/2
return x, cond
def postprocess_placement(x, cond, chip_size=None, process_graph=False):
"""
Assumes x is (V, 2), placement is 2D coordinates, with no rotations
chip_size must be tensor
Note: if process_graph=True, postprocessing is done in-place
"""
if chip_size is None:
if "chip_size" in cond:
cond_chip_size = torch.tensor(cond.chip_size, dtype = torch.float32) if not isinstance(cond.chip_size, torch.Tensor) else cond.chip_size
if len(cond.chip_size) == 2:
chip_size = cond_chip_size
chip_offset = torch.zeros_like(chip_size)
elif len(cond.chip_size) == 4:
chip_size = cond_chip_size[2:] - cond_chip_size[:2]
chip_offset = cond_chip_size[:2]
else:
return x # no normalization to be done
else:
chip_size = chip_size if isinstance(chip_size, torch.Tensor) else torch.tensor(chip_size)
scale = chip_size.view(1, 2).to(device = x.device)
chip_offset = chip_offset.to(device = x.device)
x = x - cond.x/2
x = scale * (x+1)/2
x = x + chip_offset
if not process_graph:
return x
else:
# use bottom left as reference for terminal coordinates
u_shape = cond.x[cond.edge_index[0,:]]
v_shape = cond.x[cond.edge_index[1,:]]
cond.edge_attr[:,:2] = cond.edge_attr[:,:2] + u_shape/2
cond.edge_attr[:,2:4] = cond.edge_attr[:,2:4] + v_shape/2
# un-normalize terminal coordinates
cond.edge_attr[:,:2] = (cond.edge_attr[:,:2] * scale)/2
cond.edge_attr[:,2:4] = (cond.edge_attr[:,2:4] * scale)/2
# un-normalize object sizes
cond.x = (cond.x * scale)/2
return x, cond
def edge_dropout(x, cond, dropout_probability):
_, E = cond.edge_index.shape
E = E//2 # forward and reverse edges are included in edge_index. we only want forward edges
num_remaining_edges = round((1-dropout_probability) * E)
if num_remaining_edges > 0:
new_edge_ids = torch.multinomial(torch.ones([E], device=cond.edge_index.device), num_remaining_edges) # sample without replacement
else:
new_edge_ids = torch.tensor([0], dtype=torch.int64) # need at least one edge
new_edge_ids = torch.cat([new_edge_ids, new_edge_ids + E])
output_cond = Data(
x = cond.x,
edge_index = cond.edge_index[:, new_edge_ids],
edge_attr = cond.edge_attr[new_edge_ids, :],
)
if "edge_pin_id" in cond:
output_cond.edge_pin_id = cond.edge_pin_id[new_edge_ids, :]
# (shallow) copy over other attributes in cond
for k in cond.keys():
if not k in output_cond:
output_cond[k] = cond[k]
return x, output_cond
def generate_batch_visualizations(x, cond, mask = None):
# x has shape (B, V, 2)
# cond is data object, cond.x contains width and heights of nodes
# mask is shared across batch dimension, has shape (V)
B, V, F = x.shape
image_list = []
for i in range(B):
img = torch.tensor(visualize_placement(x[i], cond, mask = cond.is_ports if mask is None else mask)).movedim(-1, -3) # images should be C, H, W
C, H, W = img.shape
img_padded = torch.zeros((C, H+2, W+2), dtype=img.dtype, device=img.device)
img_padded[:, 1:-1, 1:-1] = img
image_list.append(img_padded)
return torch.stack(image_list, dim=0)
class DataLoader:
def __init__(
self,
train_dataset,
val_dataset,
train_batch_size,
val_batch_size,
train_device = "cuda",
num_workers = 8,
pin_memory = False,
):
self.device = train_device
self.train_batch_size = train_batch_size
self.val_batch_size = val_batch_size
self.train_set = train_dataset
self.val_set = val_dataset
self.train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=train_batch_size, shuffle=True, num_workers=num_workers, pin_memory=pin_memory, pin_memory_device=train_device if pin_memory else '')
self.val_loader = torch.utils.data.DataLoader(val_dataset, batch_size=val_batch_size, shuffle=True, num_workers=num_workers, pin_memory=pin_memory, pin_memory_device=train_device if pin_memory else '')
self._get_train_batch = self._train_gen()
self._get_val_batch = self._val_gen()
self._display_x = None
self._display_y = None
def get_batch(self, split):
assert split in ("train", "val"), "split argument has to be one of 'train' or 'val'"
x, y = next(self._get_train_batch) if split == "train" else next(self._get_val_batch)
return x.to(self.device), y.to(self.device)
def get_display_batch(self, num_images):
assert num_images <= self.val_batch_size, "num images must be smaller than batch size"
if (self._display_x is None) or (self._display_y is None):
x, y = self.get_batch("val")
self._display_x = x[:num_images]
self._display_y = y[:num_images]
return self._display_x, self._display_y
def _train_gen(self):
while True:
for data in self.train_loader:
yield data
def _val_gen(self):
while True:
for data in self.val_loader:
yield data
def get_train_size(self):
return len(self.train_set)
def get_val_size(self):
return len(self.val_set)
class GraphDataLoader:
def __init__(
self,
train_dataset,
val_dataset,
train_batch_size,
val_batch_size,
train_device = "cuda",
preprocess_fn = None,
train_shuffle = True,
val_shuffle = True,
num_workers = 8,
pin_memory = False,
):
self.device = train_device
self.train_batch_size = train_batch_size
self.val_batch_size = val_batch_size
self.train_set = train_dataset
self.val_set = val_dataset
self._display_x = {}
self._display_y = {}
self.preprocess_fn = preprocess_fn
self.is_shuffle = {"train": train_shuffle, "val": val_shuffle}
self.current_idx = {"train": 0, "val": 0} # For non-shuffle
def get_batch(self, split):
assert split in ("train", "val"), "split argument has to be one of 'train' or 'val'"
dataset = self.train_set if split=="train" else self.val_set
batch_size = self.train_batch_size if split=="train" else self.val_batch_size
if self.is_shuffle[split]:
idx = torch.randint(0, len(dataset), [1]) # TODO support larger batch sizes
else:
idx = self.current_idx[split]
self.current_idx[split] = (self.current_idx[split] + 1) % len(dataset)
x, y = dataset[idx]
output = self.prepare_output(x.to(self.device).view(1, *x.shape).expand(batch_size, *x.shape), y.to(self.device))
return output
def get_display_batch(self, display_batch_size, split="val"):
batch_size = self.val_batch_size if split == "val" else self.train_batch_size
assert display_batch_size <= batch_size, "num images must be smaller than batch size"
if (self._display_x.get(split, None) is None) or (self._display_y.get(split, None) is None):
x, y = self.get_batch(split)
# self._display_x[split] = x[:display_batch_size]
# self._display_y[split] = y
# return self._display_x[split], self._display_y[split]
output = self.prepare_output(x[:display_batch_size], y)
return output # TODO return deterministically
def reset_idx(self, split):
assert split in ("train", "val"), "split argument has to be one of 'train' or 'val'"
self.current_idx[split] = 0
def get_train_size(self):
return len(self.train_set)
def get_val_size(self):
return len(self.val_set)
def prepare_output(self, x, y):
if self.preprocess_fn is None:
return x, y
else:
return self.preprocess_fn(x, y)
def open_pickle(path):
with open(path, "rb") as f:
return pickle.load(f)
def load_and_parse_graph(path):
"""Loads Data object from pickle file"""
graph = open_pickle(path) # networkx graph or pytorch geometric
assert isinstance(graph, Data), "Pickle file must contain pytorch-geometric Data object; networkx is deprecated"
assert (graph.edge_index.shape[1] % 2 == 0) and (len(graph.edge_attr) % 2 == 0), "graph edges must be undirected"
# enforce 1D tensor for some keys
for key in ["is_macros", "is_ports"]:
if key in graph and len(graph[key].shape) > 1:
graph[key] = torch.flatten(graph[key]).bool() # TODO remove autoconversions to avoid bugs
return graph
def hsv_to_rgb(h, s, v):
"""
Converts HSV (Hue, Saturation, Value) color space to RGB (Red, Green, Blue).
h: float [0, 1] - Hue
s: float [0, 1] - Saturation
v: float [0, 1] - Value
Returns: tuple (r, g, b) representing RGB values in the range [0, 255]
"""
h_i = int(h * 6)
f = h * 6 - h_i
p = v * (1 - s)
q = v * (1 - f * s)
t = v * (1 - (1 - f) * s)
if h_i == 0:
r, g, b = v, t, p
elif h_i == 1:
r, g, b = q, v, p
elif h_i == 2:
r, g, b = p, v, t
elif h_i == 3:
r, g, b = p, q, v
elif h_i == 4:
r, g, b = t, p, v
else:
r, g, b = v, p, q
return int(r * 255), int(g * 255), int(b * 255)
def visualize(x, cond, mask = None):
"""
Visualizes the X with node attributes, returning an numpy image (H, W, C)
x,y are floats normalized to canvas size (from -1 to 1)
attr are also normalized to canvas size
Inputs:
x: can be (V, 2) for 2D coordinate placement or (V, 2+3) floats for 2D plus orientation placement
cond: pyG data object with instance sizes in 'x' field (V, 2)
"""
width, height = 128, 128
background_color = "white"
image = Image.new("RGB", (width, height), background_color)
draw = ImageDraw.Draw(image)
assert len(x.shape) == 2, "x has to have 2 axes with shape (V, 2) or (V, 2+3)"
if x.shape[1] == 5:
# 2D + orientation placement
cond = orientations.to_fixed(x[:,2:], cond)
attr = cond.x.cpu()
x = x[:,:2].cpu()
h_step = 1 / len(x)
for i, (pos, shape) in enumerate(zip(x, attr)):
# NOTE assumes coordinates are center of instance
left = pos[0] - shape[0]/2
top = pos[1] + shape[1]/2
right = pos[0] + shape[0]/2
bottom = pos[1] - shape[1]/2
inbounds = (left>=-1) and (top<=1) and (right<=1) and (bottom>=-1)
left = (0.5 + left/2) * width
right = (0.5 + right/2) * width
top = (0.5 - top/2) * height
bottom = (0.5 - bottom/2) * height
color = hsv_to_rgb(i * h_step, 1 if (mask is None or not mask[i]) else 0.2, 0.9 if inbounds else 0.5)
draw.rectangle([left, top, right, bottom], fill=color, width=0)
return np.array(image)
def visualize_placement(x, cond, plot_pins = False, plot_edges = False, img_size = (256, 256), mask = None):
"""
Visualizes the X with node attributes, returning an numpy image
All coordinates are normalized w.r.t canvas size
x is (V, 2) tensor with 2D coordinates describing placement of center of instances
cond is pytorch geometric Data object with the following:
- x is (V, 2) tensor with sizes of instances
- edge_index (2, E)
- edge_attr (E, 4) tensor describing pin locations, measured relative to center of instance
- mask is mask override
"""
width, height = img_size
background_color = "white"
base_image = Image.new("RGBA", (width, height), background_color)
assert len(x.shape) == 2, "x has to have 2 axes with shape (V, 2) or (V, 2+3)"
if x.shape[1] == 5:
# 2D + orientation placement
cond = orientations.to_fixed(x[:,2:], cond)
x = x[:,:2]
def canvas_to_pixel_coord(x):
# x is (B, 2) tensor representing normalized 2D coordinates in canvas space
output = torch.zeros_like(x)
output[:,0] = (0.5 + x[:,0]/2) * width
output[:,1] = (0.5 - x[:,1]/2) * height
return output
V, _ = x.shape
mask = cond.is_ports if "is_ports" in cond and mask is None else mask
h_step = 0.2 / max(V, 1) if "is_macros" in cond else 1.0 / max(V, 1)
h_offsets = {"macro": .0, "port": 0.35, "sc": 0.55}
left_bottom = x - cond.x/2
right_top = x + cond.x/2
inbounds = torch.logical_and(left_bottom >= -1, right_top <= 1)
inbounds = torch.logical_and(inbounds[:,0], inbounds[:,1])
left_bottom_px = canvas_to_pixel_coord(left_bottom)
right_top_px = canvas_to_pixel_coord(right_top)
for i in range(V):
image = Image.new("RGBA", base_image.size, (255, 255, 255, 0))
draw = ImageDraw.Draw(image)
if "is_macros" in cond:
if cond.is_macros[i]:
h_offset = h_offsets["macro"]
elif mask is None or not mask[i]:
h_offset = h_offsets["sc"]
else:
h_offset = h_offsets["port"]
else:
h_offset = 0.0
color = hsv_to_rgb(
i * h_step + h_offset,
1 if (mask is None or not mask[i]) else 0.2,
0.9 if inbounds[i] else 0.5,
)
draw.rectangle([left_bottom_px[i,0], right_top_px[i,1], right_top_px[i,0], left_bottom_px[i,1]], fill=(*color, 160), width=0)
base_image = Image.alpha_composite(base_image, image)
draw = ImageDraw.Draw(base_image)
# get pin positions
if plot_edges or plot_pins:
unique_edges = cond.edge_attr.shape[0]//2
u_pos = cond.edge_attr[:unique_edges,:2] + x[cond.edge_index[0,:unique_edges]]
v_pos = cond.edge_attr[:unique_edges,2:4] + x[cond.edge_index[1,:unique_edges]]
u_pos = canvas_to_pixel_coord(u_pos)
v_pos = canvas_to_pixel_coord(v_pos)
# plot edges
if plot_edges:
for i in range(unique_edges):
draw.line([tuple(u_pos[i].detach().cpu().numpy()), tuple(v_pos[i].detach().cpu().numpy())], fill="gray")
# plot pin positions
if plot_pins:
draw.point([(row[0], row[1]) for row in u_pos.detach().cpu().numpy()], fill="black")
draw.point([(row[0], row[1]) for row in v_pos.detach().cpu().numpy()], fill="yellow")
return np.array(base_image)[:,:,:3]
def save_cfg(cfg, path):
with open(path, "w") as f:
OmegaConf.save(config=cfg, f=f)
def load_cfg(path):
with open(path, "r") as f:
return OmegaConf.load(f)
def visualize_ignore_ports(x, cond, mask):
"""
Visualizes the X with node attributes, returning an numpy image
x,y are floats normalized to canvas size (from -1 to 1)
attr are also normalized to canvas size
"""
width, height = 1024, 1024
background_color = "black"
image = Image.new("RGB", (width, height), background_color)
draw = ImageDraw.Draw(image)
assert len(x.shape) == 2, "x has to have 2 axes with shape (V, 2) or (V, 2+3)"
if x.shape[1] == 5:
# 2D + orientation placement