forked from TILOS-AI-Institute/MacroPlacement
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathplc_client_os.py
More file actions
3337 lines (2768 loc) · 125 KB
/
Copy pathplc_client_os.py
File metadata and controls
3337 lines (2768 loc) · 125 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
"""Open-Sourced PlacementCost client class."""
from ast import Assert
import os, io
import re
import math
from typing import Text, Tuple, overload
from absl import logging
from collections import namedtuple
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import numpy as np
import traceback, sys
import random
"""plc_client_os docstrings.
Open-sourced effort for plc_client and Google's API, plc_wrapper_main. This module
is used to initialize a PlacementCost object that computes the meta-information and
proxy cost function for RL agent's reward signal at the end of each placement.
Example:
For testing, please refer to plc_client_os_test.py for more information.
Todo:
* Add Documentation
* Clean up
* location information update not correctly after restore placement
* test if cell < 5, congestion cost computation
"""
Block = namedtuple('Block', 'x_max y_max x_min y_min')
class PlacementCost(object):
def __init__(self,
netlist_file: Text,
macro_macro_x_spacing: float = 0.0,
macro_macro_y_spacing: float = 0.0) -> None:
"""
Creates a PlacementCost object.
"""
self.netlist_file = netlist_file
self.macro_macro_x_spacing = macro_macro_x_spacing
self.macro_macro_y_spacing = macro_macro_y_spacing
# Update flags
self.FLAG_UPDATE_WIRELENGTH = True
self.FLAG_UPDATE_DENSITY = True
self.FLAG_UPDATE_CONGESTION = True
self.FLAG_UPDATE_MACRO_ADJ = True
self.FLAG_UPDATE_MACRO_AND_CLUSTERED_PORT_ADJ = True
self.FLAG_UPDATE_NODE_MASK = True
# Check netlist existance
assert os.path.isfile(self.netlist_file)
# [Experimental] Net Data Structure
# nets[driver] => [list of sinks]
self.nets = {}
# Set meta information
self.init_plc = None
self.project_name = "circuit_training"
self.block_name = netlist_file.rsplit('/', -1)[-2]
self.hroutes_per_micron = 0.0
self.vroutes_per_micron = 0.0
self.smooth_range = 0.0
self.overlap_thres = 0.0
self.hrouting_alloc = 0.0
self.vrouting_alloc = 0.0
self.macro_horizontal_routing_allocation = 0.0
self.macro_vertical_routing_allocation = 0.0
self.canvas_boundary_check = True
# net information
self.net_cnt = 0
# All modules look-up table
self.modules = []
self.modules_w_pins = []
# modules to index look-up table
self.indices_to_mod_name = {}
self.mod_name_to_indices = {}
# indices storage
self.port_indices = []
self.hard_macro_indices = []
self.hard_macro_pin_indices = []
self.soft_macro_indices = []
self.soft_macro_pin_indices = []
# macro to pins look-up table: [MACRO_NAME] => [PIN_NAME]
self.hard_macros_to_inpins = {}
self.soft_macros_to_inpins = {}
# Placed macro
self.placed_macro = []
# not used
self.use_incremental_cost = False
# blockage
self.blockages = []
# read netlist
self.__read_protobuf()
# default canvas width/height based on cell area
self.width = math.sqrt(self.get_area()/0.6)
self.height = math.sqrt(self.get_area()/0.6)
# default gridding
self.grid_col = 10
self.grid_row = 10
# initialize congestion map
self.V_routing_cong = [0] * (self.grid_col * self.grid_row)
self.H_routing_cong = [0] * (self.grid_col * self.grid_row)
self.V_macro_routing_cong = [0] * (self.grid_col * self.grid_row)
self.H_macro_routing_cong = [0] * (self.grid_col * self.grid_row)
# initial grid mask, flatten before output
self.node_mask = np.array([1] * (self.grid_col * self.grid_row))\
.reshape(self.grid_row, self.grid_col)
# store module/component count
self.ports_cnt = len(self.port_indices)
self.hard_macro_cnt = len(self.hard_macro_indices)
self.hard_macro_pins_cnt = len(self.hard_macro_pin_indices)
self.soft_macros_cnt = len(self.soft_macro_indices)
self.soft_macro_pins_cnt = len(self.soft_macro_pin_indices)
self.module_cnt = self.hard_macro_cnt + self.soft_macros_cnt + self.ports_cnt
# assert module and pin count are correct
assert (len(self.modules)) == self.module_cnt
assert (len(self.modules_w_pins) - \
self.hard_macro_pins_cnt - self.soft_macro_pins_cnt) \
== self.module_cnt
def __peek(self, f:io.TextIOWrapper):
"""
Return String next line by peeking into the next line without moving file descriptor
"""
pos = f.tell()
t_line = f.readline()
f.seek(pos)
return t_line
def __read_protobuf(self):
"""
private function: Protobuf Netlist Parser
"""
print("#[INFO] Reading from " + self.netlist_file)
with open(self.netlist_file) as fp:
line = fp.readline()
node_cnt = 0
while line:
line_item = re.findall(r'\w+', line)
# skip empty lines
if len(line_item) == 0:
# advance ptr
line = fp.readline()
continue
# skip comments
if re.search(r"\S", line)[0] == '#':
# advance ptr
line = fp.readline()
continue
# node found
if line_item[0] == 'node':
node_name = ''
input_list = []
# advance ptr
line = fp.readline()
line_item = re.findall(r'\w+[^\:\n\\{\}\s"]*', line)
# retrieve node name
if line_item[0] == 'name':
node_name = line_item[1]
# skip metadata header
if node_name == "__metadata__":
pass
else:
node_cnt += 1
else:
node_name = 'N/A name'
# advance ptr
line = fp.readline()
line_item = re.findall(r'\w+[^\:\n\\{\}\s"]*', line)
# retrieve node input
if line_item[0] == 'input':
input_list.append(line_item[1])
while re.findall(r'\w+[^\:\n\\{\}\s"]*', self.__peek(fp))[0] == 'input':
line = fp.readline()
line_item = re.findall(r'\w+[^\:\n\\{\}\s"]*', line)
input_list.append(line_item[1])
line = fp.readline()
line_item = re.findall(r'\w+[^\:\n\\{\}\s"]*', line)
else:
input_list = None
# advance, expect multiple attributes
attr_dict = {}
while len(line_item) != 0 and line_item[0] == 'attr':
# advance, expect key
line = fp.readline()
line_item = re.findall(r'\w+', line)
key = line_item[1]
if key == "macro_name":
# advance, expect value
line = fp.readline()
line_item = re.findall(r'\w+', line)
# advance, expect value item
line = fp.readline()
line_item = re.findall(r'\w+[^\:\n\\{\}\s"]*', line)
attr_dict[key] = line_item
line = fp.readline()
line = fp.readline()
line = fp.readline()
line_item = re.findall(r'\w+', line)
else:
# advance, expect value
line = fp.readline()
line_item = re.findall(r'\w+', line)
# advance, expect value item
line = fp.readline()
line_item = re.findall(r'\-*\w+\.*\/{0,1}\w*[\w+\/{0,1}\w*]*', line)
attr_dict[key] = line_item
line = fp.readline()
line = fp.readline()
line = fp.readline()
line_item = re.findall(r'\w+', line)
# putting info into data structure
if node_name == "__metadata__":
# skipping metadata header
logging.info('[INFO NETLIST PARSER] skipping invalid net input')
elif attr_dict['type'][1] == 'macro':
# soft macro
# check if all required information is obtained
try:
assert 'x' in attr_dict.keys()
except AssertionError:
logging.warning('[ERROR NETLIST PARSER] x is not defined')
try:
assert 'y' in attr_dict.keys()
except AssertionError:
logging.warning('[ERROR NETLIST PARSER] y is not defined')
soft_macro = self.SoftMacro(name=node_name, width=attr_dict['width'][1],
height = attr_dict['height'][1],
x = attr_dict['x'][1], y = attr_dict['y'][1])
self.modules_w_pins.append(soft_macro)
self.modules.append(soft_macro)
# mapping node_name ==> node idx
self.mod_name_to_indices[node_name] = node_cnt-1
# mapping node idx ==> node_name
self.indices_to_mod_name[node_cnt-1] = node_name
# store current node indx
self.soft_macro_indices.append(node_cnt-1)
elif attr_dict['type'][1] == 'macro_pin':
# [MACRO_NAME]/[PIN_NAME]
soft_macro_name = node_name.rsplit('/', 1)[0]
# soft macro pin
soft_macro_pin = self.SoftMacroPin(name=node_name,ref_id=None,
x = attr_dict['x'][1],
y = attr_dict['y'][1],
macro_name = attr_dict['macro_name'][1])
if 'weight' in attr_dict.keys():
soft_macro_pin.set_weight(float(attr_dict['weight'][1]))
# if pin has net info
if input_list:
# net count should be factored by net weight
if 'weight' in attr_dict.keys():
self.net_cnt += 1 * float(attr_dict['weight'][1])
else:
self.net_cnt += 1
soft_macro_pin.add_sinks(input_list)
# add net
self.nets[node_name] = input_list
self.modules_w_pins.append(soft_macro_pin)
# mapping node_name ==> node idx
self.mod_name_to_indices[node_name] = node_cnt-1
# mapping node idx ==> node_name
self.indices_to_mod_name[node_cnt-1] = node_name
# store current node indx
self.soft_macro_pin_indices.append(node_cnt-1)
if soft_macro_name in self.soft_macros_to_inpins.keys():
self.soft_macros_to_inpins[soft_macro_name]\
.append(soft_macro_pin.get_name())
else:
self.soft_macros_to_inpins[soft_macro_name]\
= [soft_macro_pin.get_name()]
elif attr_dict['type'][1] == 'MACRO':
# hard macro
hard_macro = self.HardMacro(name=node_name,
width=attr_dict['width'][1],
height = attr_dict['height'][1],
x = attr_dict['x'][1],
y = attr_dict['y'][1],
orientation = attr_dict['orientation'][1])
self.modules_w_pins.append(hard_macro)
self.modules.append(hard_macro)
# mapping node_name ==> node idx
self.mod_name_to_indices[node_name] = node_cnt-1
# mapping node idx ==> node_name
self.indices_to_mod_name[node_cnt-1] = node_name
# store current node indx
self.hard_macro_indices.append(node_cnt-1)
elif attr_dict['type'][1] == 'MACRO_PIN':
# [MACRO_NAME]/[PIN_NAME]
hard_macro_name = node_name.rsplit('/', 1)[0]
# hard macro pin
hard_macro_pin = self.HardMacroPin(name=node_name,ref_id=None,
x = attr_dict['x'][1],
y = attr_dict['y'][1],
x_offset = attr_dict['x_offset'][1],
y_offset = attr_dict['y_offset'][1],
macro_name = attr_dict['macro_name'][1])
# if net weight is defined, set weight
if 'weight' in attr_dict.keys():
hard_macro_pin.set_weight(float(attr_dict['weight'][1]))
# if pin has net info
if input_list:
# net count should be factored by net weight
if 'weight' in attr_dict.keys():
self.net_cnt += 1 * float(attr_dict['weight'][1])
else:
self.net_cnt += 1
hard_macro_pin.add_sinks(input_list)
self.nets[node_name] = input_list
self.modules_w_pins.append(hard_macro_pin)
# mapping node_name ==> node idx
self.mod_name_to_indices[node_name] = node_cnt-1
# mapping node idx ==> node_name
self.indices_to_mod_name[node_cnt-1] = node_name
# store current node indx
self.hard_macro_pin_indices.append(node_cnt-1)
# add to dict
if hard_macro_name in self.hard_macros_to_inpins.keys():
self.hard_macros_to_inpins[hard_macro_name]\
.append(hard_macro_pin.get_name())
else:
self.hard_macros_to_inpins[hard_macro_name]\
= [hard_macro_pin.get_name()]
elif attr_dict['type'][1] == 'PORT':
# port
port = self.Port(name= node_name,
x = attr_dict['x'][1],
y = attr_dict['y'][1],
side = attr_dict['side'][1])
# if pin has net info
if input_list:
self.net_cnt += 1
port.add_sinks(input_list)
# ports does not have pins so update connection immediately
port.add_connections(input_list)
self.nets[node_name] = input_list
self.modules_w_pins.append(port)
self.modules.append(port)
# mapping node_name ==> node idx
self.mod_name_to_indices[node_name] = node_cnt-1
# mapping node idx ==> node_name
self.indices_to_mod_name[node_cnt-1] = node_name
# store current node indx
self.port_indices.append(node_cnt-1)
# 1. mapping connection degree to each macros
# 2. update offset based on Hard macro orientation
self.__update_connection()
# all hard macros are placed on canvas initially
self.__update_init_placed_node()
def __read_plc(self, plc_pth: str):
"""
Plc file Parser
"""
# meta information
_columns = 0
_rows = 0
_width = 0.0
_height = 0.0
_area = 0.0
_block = None
_routes_per_micron_hor = 0.0
_routes_per_micron_ver = 0.0
_routes_used_by_macros_hor = 0.0
_routes_used_by_macros_ver = 0.0
_smoothing_factor = 0
_overlap_threshold = 0.0
# node information
_hard_macros_cnt = 0
_hard_macro_pins_cnt = 0
_macros_cnt = 0
_macro_pin_cnt = 0
_ports_cnt = 0
_soft_macros_cnt = 0
_soft_macro_pins_cnt = 0
_stdcells_cnt = 0
# node placement
_node_plc = {}
for cnt, line in enumerate(open(plc_pth, 'r')):
line_item = re.findall(r'[0-9A-Za-z\.\-]+', line)
# skip empty lines
if len(line_item) == 0:
continue
if 'Columns' in line_item and 'Rows' in line_item:
# Columns and Rows should be defined on the same one-line
_columns = int(line_item[1])
_rows = int(line_item[3])
elif "Width" in line_item and "Height" in line_item:
# Width and Height should be defined on the same one-line
_width = float(line_item[1])
_height = float(line_item[3])
elif all(it in line_item for it in ['Area', 'stdcell', 'macros']):
# Total core area of modules
_area = float(line_item[3])
elif "Area" in line_item:
# Total core area of modules
_area = float(line_item[1])
elif "Block" in line_item:
# The block name of the testcase
_block = str(line_item[1])
elif all(it in line_item for it in\
['Routes', 'per', 'micron', 'hor', 'ver']):
# For routing congestion computation
_routes_per_micron_hor = float(line_item[4])
_routes_per_micron_ver = float(line_item[6])
elif all(it in line_item for it in\
['Routes', 'used', 'by', 'macros', 'hor', 'ver']):
# For MACRO congestion computation
_routes_used_by_macros_hor = float(line_item[5])
_routes_used_by_macros_ver = float(line_item[7])
elif all(it in line_item for it in ['Smoothing', 'factor']):
# smoothing factor for routing congestion
_smoothing_factor = int(line_item[2])
elif all(it in line_item for it in ['Overlap', 'threshold']):
# overlap
_overlap_threshold = float(line_item[2])
elif all(it in line_item for it in ['HARD', 'MACROs'])\
and len(line_item) == 3:
_hard_macros_cnt = int(line_item[2])
elif all(it in line_item for it in ['HARD', 'MACRO', 'PINs'])\
and len(line_item) == 4:
_hard_macro_pins_cnt = int(line_item[3])
elif all(it in line_item for it in ['PORTs'])\
and len(line_item) == 2:
_ports_cnt = int(line_item[1])
elif all(it in line_item for it in ['SOFT', 'MACROs'])\
and len(line_item) == 3:
_soft_macros_cnt = int(line_item[2])
elif all(it in line_item for it in ['SOFT', 'MACRO', 'PINs'])\
and len(line_item) == 4:
_soft_macro_pins_cnt = int(line_item[3])
elif all(it in line_item for it in ['STDCELLs'])\
and len(line_item) == 2:
_stdcells_cnt = int(line_item[1])
elif all(it in line_item for it in ['MACROs'])\
and len(line_item) == 2:
_macros_cnt = int(line_item[1])
elif all(re.match(r'[0-9FNEWS\.\-]+', it) for it in line_item)\
and len(line_item) == 5:
# [node_index] [x] [y] [orientation] [fixed]
_node_plc[int(line_item[0])] = line_item[1:]
# return as dictionary
info_dict = { "columns":_columns,
"rows":_rows,
"width":_width,
"height":_height,
"area":_area,
"block":_block,
"routes_per_micron_hor":_routes_per_micron_hor,
"routes_per_micron_ver":_routes_per_micron_ver,
"routes_used_by_macros_hor":_routes_used_by_macros_hor,
"routes_used_by_macros_ver":_routes_used_by_macros_ver,
"smoothing_factor":_smoothing_factor,
"overlap_threshold":_overlap_threshold,
"hard_macros_cnt":_hard_macros_cnt,
"hard_macro_pins_cnt":_hard_macro_pins_cnt,
"macros_cnt":_macros_cnt,
"macro_pin_cnt":_macro_pin_cnt,
"ports_cnt":_ports_cnt,
"soft_macros_cnt":_soft_macros_cnt,
"soft_macro_pins_cnt":_soft_macro_pins_cnt,
"stdcells_cnt":_stdcells_cnt,
"node_plc":_node_plc
}
return info_dict
def restore_placement(self, plc_pth: str, ifInital=True, ifValidate=False, ifReadComment = False):
"""
Read and retrieve .plc file information
NOTE: DO NOT always set self.init_plc because this function is also
used to read final placement file.
ifReadComment: By default, Google's plc_client does not extract
information from .plc comment. This is purely done in
placement_util.py. For purpose of testing, we included this option.
"""
# if plc is an initial placement
if ifInital:
self.init_plc = plc_pth
# recompute cost from new location
self.FLAG_UPDATE_CONGESTION = True
self.FLAG_UPDATE_DENSITY = True
self.FLAG_UPDATE_WIRELENGTH = True
self.FLAG_UPDATE_NODE_MASK = True
# extracted information from .plc file
info_dict = self.__read_plc(plc_pth)
# validate netlist.pb.txt is on par with .plc
if ifValidate:
try:
assert(self.hard_macro_cnt == info_dict['hard_macros_cnt'])
assert(self.hard_macro_pins_cnt == info_dict['hard_macro_pins_cnt'])
assert(self.soft_macros_cnt == info_dict['soft_macros_cnt'])
assert(self.soft_macro_pins_cnt == info_dict['soft_macro_pins_cnt'])
assert(self.ports_cnt == info_dict['ports_cnt'])
except AssertionError:
_, _, tb = sys.exc_info()
traceback.print_tb(tb)
tb_info = traceback.extract_tb(tb)
_, line, _, text = tb_info[-1]
print('[ERROR NETLIST/PLC MISMATCH] at line {} in statement {}'\
.format(line, text))
exit(1)
# restore placement for each module
try:
# print(sorted(list(info_dict['node_plc'].keys())))
assert sorted(self.port_indices +\
self.hard_macro_indices +\
self.soft_macro_indices) == sorted(list(info_dict['node_plc'].keys()))
except AssertionError:
print('[ERROR PLC INDICES MISMATCH]', len(sorted(self.port_indices +\
self.hard_macro_indices +\
self.soft_macro_indices)), len(list(info_dict['node_plc'].keys())))
exit(1)
for mod_idx in info_dict['node_plc'].keys():
mod_x = mod_y = mod_orient = mod_ifFixed = None
try:
mod_x = float(info_dict['node_plc'][mod_idx][0])
mod_y = float(info_dict['node_plc'][mod_idx][1])
mod_orient = info_dict['node_plc'][mod_idx][2]
mod_ifFixed = int(info_dict['node_plc'][mod_idx][3])
except Exception as e:
print('[ERROR PLC PARSER] %s' % str(e))
#TODO ValueError: Error in calling RestorePlacement with ('./Plc_client/test/ariane/initial.plc',): Can't place macro i_ariane/i_frontend/i_icache/sram_block_3__tag_sram/mem/mem_inst_mem_256x45_256x16_0x0 at (341.75, 8.8835). Exceeds the boundaries of the placement area..
self.modules_w_pins[mod_idx].set_pos(mod_x, mod_y)
if mod_orient and mod_orient != '-':
self.modules_w_pins[mod_idx].set_orientation(mod_orient)
if mod_ifFixed == 0:
self.modules_w_pins[mod_idx].set_fix_flag(False)
elif mod_ifFixed == 1:
self.modules_w_pins[mod_idx].set_fix_flag(True)
# set meta information
if ifReadComment:
print("[INFO] Retrieving Meta information from .plc comments")
self.set_canvas_size(info_dict['width'], info_dict['height'])
self.set_placement_grid(info_dict['columns'], info_dict['rows'])
self.set_block_name(info_dict['block'])
self.set_routes_per_micron(
info_dict['routes_per_micron_hor'],
info_dict['routes_per_micron_ver']
)
self.set_macro_routing_allocation(
info_dict['routes_used_by_macros_hor'],
info_dict['routes_used_by_macros_ver']
)
self.set_congestion_smooth_range(info_dict['smoothing_factor'])
self.set_overlap_threshold(info_dict['overlap_threshold'])
def __update_connection(self):
"""
Update connection degree for each macro pin
"""
for macro_idx in (self.hard_macro_indices + self.soft_macro_indices):
macro = self.modules_w_pins[macro_idx]
macro_name = macro.get_name()
# Hard macro
if not self.is_node_soft_macro(macro_idx):
if macro_name in self.hard_macros_to_inpins.keys():
pin_names = self.hard_macros_to_inpins[macro_name]
else:
print("[ERROR UPDATE CONNECTION] MACRO pins not found")
continue
# also update pin offset based on macro orientation
orientation = macro.get_orientation()
self.update_macro_orientation(macro_idx, orientation)
# Soft macro
elif self.is_node_soft_macro(macro_idx):
if macro_name in self.soft_macros_to_inpins.keys():
pin_names = self.soft_macros_to_inpins[macro_name]
else:
print("[ERROR UPDATE CONNECTION] macro pins not found")
continue
for pin_name in pin_names:
pin = self.modules_w_pins[self.mod_name_to_indices[pin_name]]
inputs = pin.get_sink()
if inputs:
for k in inputs.keys():
if self.get_node_type(macro_idx) == "MACRO":
weight = pin.get_weight()
macro.add_connections(inputs[k], weight)
def __update_init_placed_node(self):
"""
Place all hard macros on node mask initially
"""
for macro_idx in (self.hard_macro_indices + self.soft_macro_indices):
self.placed_macro.append(macro_idx)
def get_cost(self) -> float:
"""
Compute wirelength cost from wirelength
"""
if self.net_cnt == 0:
self.net_cnt = 1
if self.FLAG_UPDATE_WIRELENGTH:
self.FLAG_UPDATE_WIRELENGTH = False
return self.get_wirelength() / ((self.get_canvas_width_height()[0]\
+ self.get_canvas_width_height()[1]) * self.net_cnt)
def get_area(self) -> float:
"""
Compute Total Module Area
"""
total_area = 0.0
for mod in self.modules_w_pins:
if hasattr(mod, 'get_area'):
total_area += mod.get_area()
return total_area
def get_hard_macros_count(self) -> int:
return self.hard_macro_cnt
def get_ports_count(self) -> int:
return self.ports_cnt
def get_soft_macros_count(self) -> int:
return self.soft_macros_cnt
def get_hard_macro_pins_count(self) -> int:
return self.hard_macro_pins_cnt
def get_soft_macro_pins_count(self) -> int:
return self.soft_macro_pins_cnt
def __get_pin_position(self, pin_idx):
"""
private function for getting pin location
* PORT = its own position
* HARD MACRO PIN = ref position + offset position
* SOFT MACRO PIN = ref position
"""
try:
assert (self.modules_w_pins[pin_idx].get_type() == 'MACRO_PIN' or\
self.modules_w_pins[pin_idx].get_type() == 'PORT')
except Exception:
print("[ERROR PIN POSITION] Not a MACRO PIN", self.modules_w_pins[pin_idx].get_name())
exit(1)
# PORT pin pos is itself
if self.modules_w_pins[pin_idx].get_type() == 'PORT':
return self.modules_w_pins[pin_idx].get_pos()
# Retrieve node that this pin instantiated on
ref_node_idx = self.get_ref_node_id(pin_idx)
if ref_node_idx == -1:
print("[ERROR PIN POSITION] Parent Node Not Found.")
exit(1)
# Parent node
ref_node = self.modules_w_pins[ref_node_idx]
ref_node_x, ref_node_y = ref_node.get_pos()
# Retrieve current pin node position
pin_node = self.modules_w_pins[pin_idx]
pin_node_x_offset, pin_node_y_offset = pin_node.get_offset()
# Google's Plc client DOES NOT compute (node_position + pin_offset) when reading input
return (ref_node_x + pin_node_x_offset, ref_node_y + pin_node_y_offset)
# return pin_node.get_pos()
def get_wirelength(self) -> float:
"""
Proxy HPWL computation w/ [Experimental] net
"""
total_hpwl = 0.0
for driver_pin_name in self.nets.keys():
weight_fact = 1.0
x_coord = []
y_coord = []
# extract driver pin
driver_pin_idx = self.mod_name_to_indices[driver_pin_name]
driver_pin = self.modules_w_pins[driver_pin_idx]
# extract net weight
weight_fact = driver_pin.get_weight()
x_coord.append(self.__get_pin_position(driver_pin_idx)[0])
y_coord.append(self.__get_pin_position(driver_pin_idx)[1])
# iterate through each sink
for sink_pin_name in self.nets[driver_pin_name]:
sink_pin_idx = self.mod_name_to_indices[sink_pin_name]
x_coord.append(self.__get_pin_position(sink_pin_idx)[0])
y_coord.append(self.__get_pin_position(sink_pin_idx)[1])
if x_coord:
total_hpwl += weight_fact * \
(abs(max(x_coord) - min(x_coord)) + \
abs(max(y_coord) - min(y_coord)))
return total_hpwl
def _get_wirelength(self) -> float:
"""
Proxy HPWL computation
"""
# NOTE: in pb.txt, netlist input count exceed certain threshold will be ommitted
total_hpwl = 0.0
for mod_idx, mod in enumerate(self.modules_w_pins):
norm_fact = 1.0
curr_type = mod.get_type()
# bounding box data structure
x_coord = []
y_coord = []
# default value of weight
weight_fact = 1.0
# NOTE: connection only defined on PORT, soft/hard macro pins
if curr_type == "PORT" and mod.get_sink():
# add source position
x_coord.append(mod.get_pos()[0])
y_coord.append(mod.get_pos()[1])
# get sink
for sink_name in mod.get_sink():
for sink_pin in mod.get_sink()[sink_name]:
# retrieve indx in modules_w_pins
sink_idx = self.mod_name_to_indices[sink_pin]
# retrieve sink object
sink = self.modules_w_pins[sink_idx]
# only consider placed sink
# ref_sink = self.modules_w_pins[self.get_ref_node_id(sink_idx)]
# if not placed, skip this edge
# if not ref_sink.get_placed_flag():
# x_coord.append(0)
# y_coord.append(0)
# else:# retrieve location
x_coord.append(self.__get_pin_position(sink_idx)[0])
y_coord.append(self.__get_pin_position(sink_idx)[1])
elif curr_type == "MACRO_PIN":
ref_mod = self.modules_w_pins[self.get_ref_node_id(mod_idx)]
# # if not placed, skip this edge
# if not ref_mod.get_placed_flag():
# continue
# get pin weight
weight_fact = mod.get_weight()
# add source position
x_coord.append(self.__get_pin_position(mod_idx)[0])
y_coord.append(self.__get_pin_position(mod_idx)[1])
if mod.get_sink():
for input_list in mod.get_sink().values():
for sink_name in input_list:
# retrieve indx in modules_w_pins
input_idx = self.mod_name_to_indices[sink_name]
# sink_ref_mod = self.modules_w_pins[self.get_ref_node_id(mod_idx)]
# if not placed, skip this edge
# if not sink_ref_mod.get_placed_flag():
# x_coord.append(0)
# y_coord.append(0)
# else:
# retrieve location
x_coord.append(self.__get_pin_position(input_idx)[0])
y_coord.append(self.__get_pin_position(input_idx)[1])
if x_coord:
total_hpwl += weight_fact * \
(abs(max(x_coord) - min(x_coord)) + \
abs(max(y_coord) - min(y_coord)))
return total_hpwl
def abu(self, xx, n = 0.1):
xxs = sorted(xx, reverse = True)
cnt = math.floor(len(xxs)*n)
if cnt == 0:
return max(xxs)
return sum(xxs[0:cnt])/cnt
def get_V_congestion_cost(self) -> float:
"""
compute average of top 10% of grid cell cong and take half of it
"""
occupied_cells = sorted([gc for gc in self.V_routing_cong if gc != 0.0], reverse=True)
cong_cost = 0.0
# take top 10%
cong_cnt = math.floor(len(self.V_routing_cong) * 0.1)
# if grid cell smaller than 10, take the average over occupied cells
if len(self.V_routing_cong) < 10:
cong_cost = float(sum(occupied_cells) / len(occupied_cells))
return cong_cost
idx = 0
sum_cong = 0
# take top 10%
while idx < cong_cnt and idx < len(occupied_cells):
sum_cong += occupied_cells[idx]
idx += 1
return float(sum_cong / cong_cnt)
def get_H_congestion_cost(self) -> float:
"""
compute average of top 10% of grid cell cong and take half of it
"""
occupied_cells = sorted([gc for gc in self.H_routing_cong if gc != 0.0], reverse=True)
cong_cost = 0.0
# take top 10%
cong_cnt = math.floor(len(self.H_routing_cong) * 0.1)
# if grid cell smaller than 10, take the average over occupied cells
if len(self.H_routing_cong) < 10:
cong_cost = float(sum(occupied_cells) / len(occupied_cells))
return cong_cost
idx = 0
sum_cong = 0
# take top 10%
while idx < cong_cnt and idx < len(occupied_cells):
sum_cong += occupied_cells[idx]
idx += 1
return float(sum_cong / cong_cnt)
def get_congestion_cost(self):
"""
Return congestion cost based on routing and macro placement
"""
if self.FLAG_UPDATE_CONGESTION:
self.get_routing()
return self.abu(self.V_routing_cong + self.H_routing_cong, 0.05)
def __get_grid_cell_location(self, x_pos, y_pos):
"""
private function: for getting grid cell row/col ranging from 0...N
"""
self.grid_width = float(self.width/self.grid_col)
self.grid_height = float(self.height/self.grid_row)
row = math.floor(y_pos / self.grid_height)
col = math.floor(x_pos / self.grid_width)
return row, col
def __get_grid_location_position(self, col:int, row:int):
"""
private function: for getting x y coord from grid cell row/col
"""
self.grid_width = float(self.width/self.grid_col)
self.grid_height = float(self.height/self.grid_row)
x_pos = self.grid_width * col + self.grid_width / 2
y_pos = self.grid_height * row + self.grid_height / 2
return x_pos, y_pos
def __get_grid_cell_position(self, grid_cell_idx:int):
"""
private function: for getting x y coord from grid cell row/col
"""
row = grid_cell_idx // self.grid_col
col = grid_cell_idx % self.grid_col
assert row * self.grid_col + col == grid_cell_idx
return self.__get_grid_location_position(col, row)
def __place_node_mask(self,
grid_cell_idx:int,
mod_width:float,
mod_height:float
):
"""
private function: for updating node mask after a placement
"""
row = grid_cell_idx // self.grid_col
col = grid_cell_idx % self.grid_col
assert row * self.grid_col + col == grid_cell_idx
hor_pad, ver_pad = self.__node_pad_cell(mod_width=mod_width,
mod_height=mod_height)
self.node_mask[ row - ver_pad:row + ver_pad + 1,
col - hor_pad:col + hor_pad + 1] = 0
def __overlap_area(self, block_i, block_j, return_pos=False):
"""
private function: for computing block overlapping
"""
x_min_max = min(block_i.x_max, block_j.x_max)
x_max_min = max(block_i.x_min, block_j.x_min)
y_min_max = min(block_i.y_max, block_j.y_max)
y_max_min = max(block_i.y_min, block_j.y_min)
x_diff = x_min_max - x_max_min
y_diff = y_min_max - y_max_min
if x_diff >= 0 and y_diff >= 0:
if return_pos:
return x_diff * y_diff, (x_min_max, y_min_max), (x_max_min, y_max_min)
else:
return x_diff * y_diff
return 0
def __overlap_dist(self, block_i, block_j):
"""
private function: for computing block overlapping
"""
x_diff = min(block_i.x_max, block_j.x_max) - max(block_i.x_min, block_j.x_min)
y_diff = min(block_i.y_max, block_j.y_max) - max(block_i.y_min, block_j.y_min)
if x_diff > 0 and y_diff > 0:
return x_diff, y_diff
return 0, 0
def __add_module_to_grid_cells(self, mod_x, mod_y, mod_w, mod_h):
"""
private function: for add module to grid cells
"""
# Two corners
ur = (mod_x + (mod_w/2), mod_y + (mod_h/2))
bl = (mod_x - (mod_w/2), mod_y - (mod_h/2))
# construct block based on current module
module_block = Block(
x_max=mod_x + (mod_w/2),
y_max=mod_y + (mod_h/2),