forked from conan0220/FloorSet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevaluate_detail.py
More file actions
1807 lines (1523 loc) · 70.5 KB
/
evaluate_detail.py
File metadata and controls
1807 lines (1523 loc) · 70.5 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
#!/usr/bin/env python3
"""
ICCAD 2026 FloorSet Challenge - Contest Framework
Unified contest framework with all functionality accessible via switches.
Dataset Terminology:
- Training set: 1M samples (LiteTensorData/) - for training models
- Validation set: 100 samples (LiteTensorDataTest/) - for local evaluation
- Test set: 100 samples (hidden) - for final contest ranking
All datasets contain floorplans with 21 to 120 blocks.
Usage:
python iccad2026_evaluate.py --evaluate my_optimizer.py # Evaluate on validation set
python iccad2026_evaluate.py --validate my_optimizer.py # Validate submission format
python iccad2026_evaluate.py --baseline # Generate baseline metrics
python iccad2026_evaluate.py --score solution.json # Score a solution file
python iccad2026_evaluate.py --visualize --test-id 0 # Visualize validation case
python iccad2026_evaluate.py --info # Show contest info
Examples:
python iccad2026_evaluate.py --evaluate my_optimizer.py --test-id 0 --verbose
python iccad2026_evaluate.py --baseline --output baselines.json
python iccad2026_evaluate.py --validate my_optimizer.py --quick
"""
import argparse
import importlib.util
import json
import math
import os
import random
import sys
import time
from dataclasses import dataclass, asdict, field
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Tuple, Optional, Any, Callable
import numpy as np
import torch
from torch.utils.data import DataLoader
from tqdm import tqdm
# Add parent directory for imports
sys.path.insert(0, str(Path(__file__).parent.parent))
sys.path.insert(0, str(Path(__file__).parent.parent / "solution"))
from litetestLoader import FloorplanDatasetLiteTest, floorplan_collate as test_floorplan_collate
from liteLoader import FloorplanDatasetLite # Training data (1M samples)
from lite_dataset import floorplan_collate as train_floorplan_collate
from cost import calculate_weighted_b2b_wirelength, calculate_weighted_p2b_wirelength
from utils import (
unpad_tensor,
check_fixed_const, check_preplaced_const, check_mib_const,
check_clust_const, check_boundary_const
)
try:
from viz_utils import save_floorplan_viz
VIZ_AVAILABLE = True
except ImportError:
VIZ_AVAILABLE = False
try:
from shapely.geometry import Polygon, box
from shapely.ops import unary_union
SHAPELY_AVAILABLE = True
except ImportError:
SHAPELY_AVAILABLE = False
# =============================================================================
# CONTEST PARAMETERS (from problem statement)
# =============================================================================
ALPHA = 0.5 # Quality metrics weight
BETA = 2.0 # Violation penalty exponent
GAMMA = 0.3 # Runtime factor damping
M_PENALTY = 10.0 # Infeasibility penalty
AREA_TOLERANCE = 0.01 # 1% area tolerance
# =============================================================================
# DATA CLASSES
# =============================================================================
@dataclass
class SolutionMetrics:
"""Container for all evaluation metrics."""
is_feasible: bool
overlap_violations: int
area_violations: int
hpwl_b2b: float
hpwl_p2b: float
hpwl_total: float
hpwl_baseline: float
hpwl_gap: float
bbox_area: float
bbox_area_baseline: float
area_gap: float
fixed_violations: int
preplaced_violations: int
boundary_violations: int
grouping_violations: int
mib_violations: int
total_soft_violations: int
max_possible_violations: int
violations_relative: float
runtime_seconds: float
cost: float
@dataclass
class TestResult:
"""Result for a single validation/test case evaluation."""
test_id: int # case index (0-99)
block_count: int
is_feasible: bool
hpwl_gap: float
area_gap: float
violations_relative: float
runtime_seconds: float
cost: float
# Detailed breakdown fields
overlap_violations: int = 0
area_violations: int = 0
hpwl_total: float = 0.0
hpwl_baseline: float = 0.0
bbox_area: float = 0.0
area_baseline: float = 0.0
positions: Optional[List[Tuple[float, float, float, float]]] = None
error: Optional[str] = None
@dataclass
class EvaluationResult:
"""Complete evaluation result."""
submission_name: str
timestamp: str
total_score: float
test_results: List[TestResult]
summary: Dict[str, Any]
# =============================================================================
# SCORING FUNCTIONS
# =============================================================================
def calculate_hpwl_b2b(
positions: List[Tuple[float, float, float, float]],
b2b_connectivity: torch.Tensor
) -> float:
"""Calculate block-to-block HPWL."""
if b2b_connectivity is None or len(b2b_connectivity) == 0:
return 0.0
total_wl = 0.0
for edge in b2b_connectivity:
if edge[0] == -1:
continue
i, j, weight = int(edge[0]), int(edge[1]), float(edge[2])
if i < len(positions) and j < len(positions):
x1 = positions[i][0] + positions[i][2] / 2
y1 = positions[i][1] + positions[i][3] / 2
x2 = positions[j][0] + positions[j][2] / 2
y2 = positions[j][1] + positions[j][3] / 2
total_wl += weight * (abs(x2 - x1) + abs(y2 - y1))
return total_wl
def calculate_hpwl_p2b(
positions: List[Tuple[float, float, float, float]],
p2b_connectivity: torch.Tensor,
pins_pos: torch.Tensor
) -> float:
"""Calculate pin-to-block HPWL."""
if p2b_connectivity is None or len(p2b_connectivity) == 0:
return 0.0
total_wl = 0.0
for edge in p2b_connectivity:
if edge[0] == -1:
continue
pin_idx, block_idx, weight = int(edge[0]), int(edge[1]), float(edge[2])
if block_idx < len(positions) and pin_idx < len(pins_pos):
px, py = float(pins_pos[pin_idx][0]), float(pins_pos[pin_idx][1])
bx = positions[block_idx][0] + positions[block_idx][2] / 2
by = positions[block_idx][1] + positions[block_idx][3] / 2
total_wl += weight * (abs(px - bx) + abs(py - by))
return total_wl
def calculate_bbox_area(positions: List[Tuple[float, float, float, float]]) -> float:
"""Calculate bounding box area of all blocks."""
if not positions:
return 0.0
x_min = min(p[0] for p in positions)
y_min = min(p[1] for p in positions)
x_max = max(p[0] + p[2] for p in positions)
y_max = max(p[1] + p[3] for p in positions)
return (x_max - x_min) * (y_max - y_min)
def check_overlap(positions: List[Tuple[float, float, float, float]]) -> int:
"""Check for overlapping blocks (touching edges OK)."""
violations = 0
n = len(positions)
for i in range(n):
for j in range(i + 1, n):
x1, y1, w1, h1 = positions[i]
x2, y2, w2, h2 = positions[j]
# Check for actual overlap (not just touching)
overlap_x = max(0, min(x1 + w1, x2 + w2) - max(x1, x2))
overlap_y = max(0, min(y1 + h1, y2 + h2) - max(y1, y2))
if overlap_x > 1e-6 and overlap_y > 1e-6:
violations += 1
return violations
def check_area_tolerance(
positions: List[Tuple[float, float, float, float]],
target_areas: torch.Tensor,
tolerance: float = AREA_TOLERANCE
) -> int:
"""Check if block areas are within tolerance of targets."""
violations = 0
for i, (x, y, w, h) in enumerate(positions):
if i >= len(target_areas) or target_areas[i] == -1:
continue
actual_area = w * h
target_area = float(target_areas[i])
if target_area > 0:
diff = abs(actual_area - target_area) / target_area
if diff > tolerance:
violations += 1
return violations
def compute_cost(
hpwl_gap: float,
area_gap: float,
violations_relative: float,
runtime_factor: float,
is_feasible: bool
) -> float:
"""
Compute the official contest cost.
Cost = (1 + α·(HPWL_gap + Area_gap)) × exp(β·V_rel) × max(0.7, R^γ)
= M (10.0) if infeasible
"""
if not is_feasible:
return M_PENALTY
quality_factor = 1 + ALPHA * (max(0, hpwl_gap) + max(0, area_gap))
violation_factor = math.exp(BETA * violations_relative)
runtime_adjustment = max(0.7, math.pow(max(0.01, runtime_factor), GAMMA))
return quality_factor * violation_factor * runtime_adjustment
def evaluate_solution(
solution: Dict,
baseline_metrics: Dict,
target_constraints: torch.Tensor,
b2b_connectivity: torch.Tensor,
p2b_connectivity: torch.Tensor,
pins_pos: torch.Tensor,
target_areas: torch.Tensor,
target_positions: Optional[List] = None,
median_runtime: float = 1.0
) -> SolutionMetrics:
"""Evaluate a solution and compute all metrics."""
positions = solution['positions']
runtime = solution.get('runtime', 1.0)
block_count = len(positions)
# Calculate HPWL
hpwl_b2b = calculate_hpwl_b2b(positions, b2b_connectivity)
hpwl_p2b = calculate_hpwl_p2b(positions, p2b_connectivity, pins_pos)
hpwl_total = hpwl_b2b + hpwl_p2b
hpwl_baseline = baseline_metrics.get('hpwl_baseline', hpwl_total)
hpwl_gap = (hpwl_total - hpwl_baseline) / max(hpwl_baseline, 1e-6)
# Calculate area
bbox_area = calculate_bbox_area(positions)
area_baseline = baseline_metrics.get('area_baseline', bbox_area)
area_gap = (bbox_area - area_baseline) / max(area_baseline, 1e-6)
# Check hard constraints (feasibility)
overlap_violations = check_overlap(positions)
area_violations = check_area_tolerance(positions, target_areas)
is_feasible = (overlap_violations == 0) and (area_violations == 0)
# Check soft constraints
fixed_violations = 0
preplaced_violations = 0
boundary_violations = 0
grouping_violations = 0
mib_violations = 0
# Count constraint instances
max_violations = 0
if target_constraints is not None and len(target_constraints) >= block_count:
for i in range(block_count):
if target_constraints.shape[1] > 0 and target_constraints[i, 0] != 0:
max_violations += 1 # Fixed
if target_constraints.shape[1] > 1 and target_constraints[i, 1] != 0:
max_violations += 1 # Preplaced
if target_constraints.shape[1] > 4 and target_constraints[i, 4] != 0:
max_violations += 1 # Boundary
# MIB groups
if target_constraints.shape[1] > 2:
mib_groups = set(int(target_constraints[i, 2]) for i in range(block_count)
if target_constraints[i, 2] > 0)
max_violations += len(mib_groups)
# Cluster groups
if target_constraints.shape[1] > 3:
cluster_groups = set(int(target_constraints[i, 3]) for i in range(block_count)
if target_constraints[i, 3] > 0)
max_violations += len(cluster_groups)
total_soft_violations = (fixed_violations + preplaced_violations +
boundary_violations + grouping_violations + mib_violations)
violations_relative = total_soft_violations / max(max_violations, 1)
# Compute cost
runtime_factor = runtime / max(median_runtime, 0.01)
cost = compute_cost(hpwl_gap, area_gap, violations_relative, runtime_factor, is_feasible)
return SolutionMetrics(
is_feasible=is_feasible,
overlap_violations=overlap_violations,
area_violations=area_violations,
hpwl_b2b=hpwl_b2b,
hpwl_p2b=hpwl_p2b,
hpwl_total=hpwl_total,
hpwl_baseline=hpwl_baseline,
hpwl_gap=hpwl_gap,
bbox_area=bbox_area,
bbox_area_baseline=area_baseline,
area_gap=area_gap,
fixed_violations=fixed_violations,
preplaced_violations=preplaced_violations,
boundary_violations=boundary_violations,
grouping_violations=grouping_violations,
mib_violations=mib_violations,
total_soft_violations=total_soft_violations,
max_possible_violations=max_violations,
violations_relative=violations_relative,
runtime_seconds=runtime,
cost=cost
)
def compute_total_score(costs: List[float], block_counts: List[int]) -> float:
"""Compute weighted average score."""
if not costs:
return 0.0
total_weight = sum(block_counts)
if total_weight == 0:
return sum(costs) / len(costs)
return sum(c * w for c, w in zip(costs, block_counts)) / total_weight
# =============================================================================
# OPTIMIZER BASE CLASS & BASELINES
# =============================================================================
class FloorplanOptimizer:
"""Base class for floorplanning optimizers."""
def __init__(self, verbose: bool = False):
self.verbose = verbose
def solve(
self,
block_count: int,
area_targets: torch.Tensor,
b2b_connectivity: torch.Tensor,
p2b_connectivity: torch.Tensor,
pins_pos: torch.Tensor,
constraints: torch.Tensor
) -> List[Tuple[float, float, float, float]]:
"""
Solve the floorplanning problem.
Returns: List of (x, y, width, height) for each block
"""
raise NotImplementedError("Subclasses must implement solve()")
def query_cost(
self,
positions: List[Tuple[float, float, float, float]],
b2b_connectivity: torch.Tensor,
p2b_connectivity: torch.Tensor,
pins_pos: torch.Tensor
) -> Dict[str, float]:
"""Query cost function during optimization."""
hpwl_b2b = calculate_hpwl_b2b(positions, b2b_connectivity)
hpwl_p2b = calculate_hpwl_p2b(positions, p2b_connectivity, pins_pos)
bbox_area = calculate_bbox_area(positions)
overlaps = check_overlap(positions)
return {
'hpwl_b2b': hpwl_b2b,
'hpwl_p2b': hpwl_p2b,
'hpwl_total': hpwl_b2b + hpwl_p2b,
'bbox_area': bbox_area,
'overlaps': overlaps,
'total': hpwl_b2b + hpwl_p2b + bbox_area + overlaps * 1000
}
class RandomOptimizer(FloorplanOptimizer):
"""Simple random placement baseline."""
def solve(self, block_count, area_targets, b2b_connectivity,
p2b_connectivity, pins_pos, constraints):
positions = []
canvas_size = math.sqrt(sum(float(a) for a in area_targets[:block_count] if a > 0)) * 2
for i in range(block_count):
area = float(area_targets[i]) if area_targets[i] > 0 else 1.0
w = h = math.sqrt(area)
x = random.uniform(0, canvas_size - w)
y = random.uniform(0, canvas_size - h)
positions.append((x, y, w, h))
return positions
class SimulatedAnnealingOptimizer(FloorplanOptimizer):
"""Simulated Annealing baseline optimizer."""
def __init__(self, max_iterations: int = 5000, initial_temp: float = 1000.0,
cooling_rate: float = 0.995, verbose: bool = False):
super().__init__(verbose)
self.max_iterations = max_iterations
self.initial_temp = initial_temp
self.cooling_rate = cooling_rate
def solve(self, block_count, area_targets, b2b_connectivity,
p2b_connectivity, pins_pos, constraints):
# Initialize with random placement
positions = []
total_area = sum(float(a) for a in area_targets[:block_count] if a > 0)
canvas_size = math.sqrt(total_area) * 1.5
for i in range(block_count):
area = float(area_targets[i]) if area_targets[i] > 0 else 1.0
w = h = math.sqrt(area)
x = random.uniform(0, max(0, canvas_size - w))
y = random.uniform(0, max(0, canvas_size - h))
positions.append([x, y, w, h])
# SA optimization
current_cost = self._evaluate(positions, b2b_connectivity, p2b_connectivity, pins_pos)
best_positions = [tuple(p) for p in positions]
best_cost = current_cost
temp = self.initial_temp
for iteration in range(self.max_iterations):
# Random move
idx = random.randint(0, block_count - 1)
old_pos = positions[idx].copy()
move_type = random.choice(['translate', 'swap', 'resize'])
if move_type == 'translate':
dx = random.gauss(0, canvas_size * 0.1)
dy = random.gauss(0, canvas_size * 0.1)
positions[idx][0] = max(0, positions[idx][0] + dx)
positions[idx][1] = max(0, positions[idx][1] + dy)
elif move_type == 'swap' and block_count > 1:
idx2 = random.randint(0, block_count - 1)
if idx2 != idx:
positions[idx][0], positions[idx2][0] = positions[idx2][0], positions[idx][0]
positions[idx][1], positions[idx2][1] = positions[idx2][1], positions[idx][1]
else: # resize
target_area = float(area_targets[idx]) if area_targets[idx] > 0 else positions[idx][2] * positions[idx][3]
aspect = random.uniform(0.5, 2.0)
positions[idx][2] = math.sqrt(target_area * aspect)
positions[idx][3] = math.sqrt(target_area / aspect)
new_cost = self._evaluate(positions, b2b_connectivity, p2b_connectivity, pins_pos)
delta = new_cost - current_cost
if delta < 0 or random.random() < math.exp(-delta / max(temp, 1e-10)):
current_cost = new_cost
if current_cost < best_cost:
best_cost = current_cost
best_positions = [tuple(p) for p in positions]
else:
positions[idx] = old_pos
temp *= self.cooling_rate
return best_positions
def _evaluate(self, positions, b2b_conn, p2b_conn, pins_pos):
pos_tuples = [tuple(p) for p in positions]
hpwl = calculate_hpwl_b2b(pos_tuples, b2b_conn) + calculate_hpwl_p2b(pos_tuples, p2b_conn, pins_pos)
area = calculate_bbox_area(pos_tuples)
overlaps = check_overlap(pos_tuples)
return hpwl + area * 0.01 + overlaps * 10000
# =============================================================================
# TRAINING LOSS BREAKDOWN
# =============================================================================
def _print_training_loss(
positions, # List[(x,y,w,h)] original order, raw pixel space
area_target, # [n_padded]
b2b_conn, # [n_edges, 3]
p2b_conn, # [n_edges, 3]
pins_pos, # [n_pins, 2]
constraints, # [n_padded, 5]
labels, # (polygons, metrics) from dataset
target_pos, # List[(x,y,w,h)] GT positions in original order, raw pixel
test_id: int,
):
"""Compute and print weighted training loss components for one test case."""
import sys
from pathlib import Path as _Path
_repo = _Path(__file__).resolve().parent.parent
if str(_repo / "solution") not in sys.path:
sys.path.insert(0, str(_repo / "solution"))
import torch as _torch
from data.floorset_loader import preprocess_sample
from loss.wirelength_loss import wirelength_loss
from loss.area_loss import area_loss
from loss.violation_loss import violation_loss
from config import (
LAMBDA_WIRELENGTH, LAMBDA_AREA,
LAMBDA_GROUPING, LAMBDA_MIB, LAMBDA_BOUNDARY, LAMBDA_OVERLAP,
)
_, metrics_raw = labels
# Build fp_sol [n_padded, 4] as [w, h, x, y] from GT positions
n_padded = area_target.shape[0]
fp_sol = _torch.zeros(n_padded, 4)
for i, (x, y, w, h) in enumerate(target_pos):
fp_sol[i] = _torch.tensor([w, h, x, y])
s = preprocess_sample(
area_target, b2b_conn, p2b_conn, pins_pos, constraints, fp_sol, metrics_raw
)
k = s["block_count"]
canvas_ref = s["canvas_ref"]
sort_idx = s["sort_idx"] # original → sorted
sort_inv = s["sort_inv"] # original → sorted position
# Convert predicted positions (original order, raw pixel) → sorted, normalised
pos_tensor = _torch.tensor(positions, dtype=_torch.float32) # [k, 4]
pos_sorted = pos_tensor[sort_idx] # [k, 4] sorted order
pred_norm = (pos_sorted / canvas_ref).unsqueeze(0) # [1, k, 4]
pred_raw = pos_sorted.unsqueeze(0) # [1, k, 4] raw
tf = s["token_features"][:k].unsqueeze(0) # [1, k, 21]
wi = s["w_int"][:k, :k].unsqueeze(0) # [1, k, k]
cons = s["constraints_sorted"][:k].unsqueeze(0) # [1, k, 5]
pins = s["pins_pos"].unsqueeze(0) # [1, p, 2]
p2b = s["p2b_conn"].unsqueeze(0) # [1, e, 3]
hbase = _torch.tensor([s["hpwl_baseline"]]) # [1]
abase = _torch.tensor([s["area_baseline"]]) # [1]
with _torch.no_grad():
l_wl = wirelength_loss(pred_raw, wi, pins, p2b, hbase)
l_area = area_loss(pred_raw, abase)
v_grouping, v_mib, v_boundary, v_overlap = violation_loss(pred_norm, cons)
w_wl = LAMBDA_WIRELENGTH * l_wl.item()
w_area = LAMBDA_AREA * l_area.item()
w_grp = LAMBDA_GROUPING * v_grouping.item()
w_mib = LAMBDA_MIB * v_mib.item()
w_bnd = LAMBDA_BOUNDARY * v_boundary.item()
w_ovlp = LAMBDA_OVERLAP * v_overlap.item()
total = w_wl + w_area + w_grp + w_mib + w_bnd + w_ovlp
print(f"\n [loss] Test {test_id} (canvas_ref={canvas_ref:.2f})")
print(f" {'component':<18} {'raw':>10} {'weight':>8} {'weighted':>10}")
print(f" {'-'*50}")
print(f" {'wirelength':<18} {l_wl.item():>10.6f} {'×'+str(LAMBDA_WIRELENGTH):>8} {w_wl:>10.6f}")
print(f" {'area':<18} {l_area.item():>10.6f} {'×'+str(LAMBDA_AREA):>8} {w_area:>10.6f}")
print(f" {'v_grouping':<18} {v_grouping.item():>10.6f} {'×'+str(LAMBDA_GROUPING):>8} {w_grp:>10.6f}")
print(f" {'v_mib':<18} {v_mib.item():>10.6f} {'×'+str(LAMBDA_MIB):>8} {w_mib:>10.6f}")
print(f" {'v_boundary':<18} {v_boundary.item():>10.6f} {'×'+str(LAMBDA_BOUNDARY):>8} {w_bnd:>10.6f}")
print(f" {'v_overlap':<18} {v_overlap.item():>10.6f} {'×'+str(LAMBDA_OVERLAP):>8} {w_ovlp:>10.6f}")
print(f" {'-'*50}")
print(f" {'TOTAL':<18} {'':>10} {'':>8} {total:>10.6f}")
# =============================================================================
# EVALUATION ENGINE
# =============================================================================
class ContestEvaluator:
"""Main evaluation engine."""
def __init__(self, data_path: str = "../", verbose: bool = True, checkpoint: str = None):
self.data_path = Path(data_path)
self.verbose = verbose
self.dataset = None
self._checkpoint = checkpoint
def _load_dataset(self):
if self.dataset is None:
if self.verbose:
print("Loading validation dataset...")
self.dataset = FloorplanDatasetLiteTest(str(self.data_path))
if self.verbose:
print(f"Loaded {len(self.dataset)} validation cases")
def _load_optimizer(self, optimizer_path: str, checkpoint: str = None) -> FloorplanOptimizer:
"""Load optimizer from file."""
path = Path(optimizer_path)
if not path.exists():
raise FileNotFoundError(f"Optimizer file not found: {optimizer_path}")
spec = importlib.util.spec_from_file_location("optimizer_module", path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
kwargs = {"verbose": self.verbose}
if checkpoint is not None:
kwargs["checkpoint"] = checkpoint
# Find optimizer class
for name in dir(module):
obj = getattr(module, name)
if (isinstance(obj, type) and
issubclass(obj, FloorplanOptimizer) and
obj is not FloorplanOptimizer):
try:
return obj(**kwargs)
except TypeError:
return obj(verbose=self.verbose)
# Try common names
for name in ['MyOptimizer', 'Optimizer', 'ContestOptimizer']:
if hasattr(module, name):
try:
return getattr(module, name)(**kwargs)
except TypeError:
return getattr(module, name)(verbose=self.verbose)
raise ValueError(f"No optimizer class found in {optimizer_path}")
def _extract_baseline(self, idx, labels, b2b_conn, p2b_conn, pins_pos, block_count):
"""Extract baseline metrics from ground truth."""
polygons, metrics = labels
positions = []
for i in range(block_count):
block = polygons[i]
valid = block[block[:, 0] != -1]
if len(valid) > 0:
x_min, y_min = valid.min(dim=0).values
x_max, y_max = valid.max(dim=0).values
positions.append((float(x_min), float(y_min),
float(x_max - x_min), float(y_max - y_min)))
else:
positions.append((0, 0, 1, 1))
hpwl = calculate_hpwl_b2b(positions, b2b_conn) + calculate_hpwl_p2b(positions, p2b_conn, pins_pos)
area = calculate_bbox_area(positions)
# Use stored metrics if available
if metrics is not None and len(metrics) >= 8:
if metrics[0] > 0:
area = float(metrics[0])
if metrics[-2] > 0 and metrics[-1] >= 0:
hpwl = float(metrics[-2]) + float(metrics[-1])
return {'hpwl_baseline': hpwl, 'area_baseline': area}, positions
def evaluate(
self,
optimizer_path: str,
test_ids: Optional[List[int]] = None,
timeout: float = 60.0,
viz_dir: Optional[Path] = None,
compute_loss: bool = False,
draw_nets: bool = False,
) -> EvaluationResult:
"""Run full evaluation."""
self._load_dataset()
optimizer = self._load_optimizer(optimizer_path, checkpoint=getattr(self, '_checkpoint', None))
if test_ids is None:
test_ids = list(range(len(self.dataset)))
results = []
runtimes = []
iterator = tqdm(test_ids, desc="Evaluating") if self.verbose else test_ids
for idx in iterator:
try:
sample = self.dataset[idx]
inputs, labels = sample['input'], sample['label']
area_target, b2b_conn, p2b_conn, pins_pos, constraints = inputs
block_count = int((area_target != -1).sum().item())
baseline, target_pos = self._extract_baseline(
idx, labels, b2b_conn, p2b_conn, pins_pos, block_count
)
# Run optimizer
start = time.time()
positions = optimizer.solve(
block_count, area_target, b2b_conn, p2b_conn, pins_pos, constraints
)
runtime = time.time() - start
runtimes.append(runtime)
# Evaluate
metrics = evaluate_solution(
{'positions': positions, 'runtime': runtime},
baseline,
constraints,
b2b_conn,
p2b_conn,
pins_pos,
area_target,
target_pos,
median_runtime=runtime # runtime_factor=1.0, no runtime penalty
)
results.append(TestResult(
test_id=idx,
block_count=block_count,
is_feasible=metrics.is_feasible,
hpwl_gap=metrics.hpwl_gap,
area_gap=metrics.area_gap,
violations_relative=metrics.violations_relative,
runtime_seconds=runtime,
cost=metrics.cost,
overlap_violations=metrics.overlap_violations,
area_violations=metrics.area_violations,
hpwl_total=metrics.hpwl_total,
hpwl_baseline=metrics.hpwl_baseline,
bbox_area=metrics.bbox_area,
area_baseline=metrics.bbox_area_baseline,
positions=positions
))
# Training loss breakdown
if compute_loss:
_print_training_loss(
positions, area_target, b2b_conn, p2b_conn,
pins_pos, constraints, labels, target_pos, idx,
)
# Visualize GT vs Pred
if viz_dir is not None and VIZ_AVAILABLE:
title = (
f"Test {idx} | blocks={block_count} | "
f"{'FEASIBLE' if metrics.is_feasible else 'INFEASIBLE'} | "
f"overlaps={metrics.overlap_violations} area_viol={metrics.area_violations} | "
f"hpwl_gap={metrics.hpwl_gap:+.4f} area_gap={metrics.area_gap:+.4f} | "
f"cost={metrics.cost:.4f}"
)
save_floorplan_viz(
gt_raw=target_pos,
pred_raw=positions,
block_count=block_count,
out_path=viz_dir / f"test_{idx:03d}.png",
title=title,
constraints=constraints[:block_count] if constraints is not None else None,
b2b_conn=b2b_conn if draw_nets else None,
p2b_conn=p2b_conn if draw_nets else None,
pins_pos=pins_pos if draw_nets else None,
)
except Exception as e:
results.append(TestResult(
test_id=idx, block_count=0, is_feasible=False,
hpwl_gap=0, area_gap=0, violations_relative=1.0,
runtime_seconds=0, cost=M_PENALTY, error=str(e)
))
# Recompute with median runtime
if runtimes:
median_rt = sorted(runtimes)[len(runtimes)//2]
for r in results:
if r.error is None:
rt_factor = r.runtime_seconds / max(median_rt, 0.01)
r.cost = compute_cost(r.hpwl_gap, r.area_gap, r.violations_relative,
rt_factor, r.is_feasible)
costs = [r.cost for r in results]
blocks = [r.block_count for r in results]
total_score = compute_total_score(costs, blocks)
return EvaluationResult(
submission_name=Path(optimizer_path).stem,
timestamp=datetime.now().isoformat(),
total_score=total_score,
test_results=results,
summary={
'num_tests': len(results),
'num_feasible': sum(1 for r in results if r.is_feasible),
'avg_cost': sum(costs) / len(costs) if costs else 0,
'avg_runtime': sum(runtimes) / len(runtimes) if runtimes else 0,
}
)
# =============================================================================
# SUBMISSION VALIDATOR
# =============================================================================
def validate_submission(optimizer_path: str, quick: bool = False, verbose: bool = True) -> bool:
"""Validate a submission file."""
checks = []
def log(msg, ok=True):
status = "✓" if ok else "✗"
if verbose:
print(f" {status} {msg}")
checks.append((msg, ok))
if verbose:
print(f"\nValidating: {optimizer_path}")
print("-" * 50)
# Check file exists
path = Path(optimizer_path)
if not path.exists():
log(f"File exists", False)
return False
log("File exists")
# Check Python syntax
try:
with open(path) as f:
compile(f.read(), path, 'exec')
log("Valid Python syntax")
except SyntaxError as e:
log(f"Valid Python syntax: {e}", False)
return False
# Try to load module
try:
spec = importlib.util.spec_from_file_location("test_module", path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
log("Module loads successfully")
except Exception as e:
log(f"Module loads: {e}", False)
return False
# Find optimizer class
optimizer_class = None
for name in dir(module):
obj = getattr(module, name)
if isinstance(obj, type) and hasattr(obj, 'solve'):
optimizer_class = obj
break
if optimizer_class is None:
log("Contains optimizer class with solve() method", False)
return False
log(f"Contains optimizer class: {optimizer_class.__name__}")
# Test on dummy data (unless quick mode)
if not quick:
try:
optimizer = optimizer_class()
dummy_areas = torch.tensor([100.0] * 5)
dummy_b2b = torch.tensor([[0, 1, 1.0], [1, 2, 1.0]])
dummy_p2b = torch.tensor([[0, 0, 1.0]])
dummy_pins = torch.tensor([[0.0, 0.0]])
dummy_constraints = torch.zeros(5, 5)
start = time.time()
result = optimizer.solve(5, dummy_areas, dummy_b2b, dummy_p2b,
dummy_pins, dummy_constraints)
runtime = time.time() - start
if not isinstance(result, list) or len(result) != 5:
log(f"Returns correct format (expected list of 5 tuples)", False)
else:
log(f"Returns correct format")
log(f"Sample runtime: {runtime:.3f}s")
except Exception as e:
log(f"Runs on sample data: {e}", False)
return False
passed = all(ok for _, ok in checks)
if verbose:
print("-" * 50)
print(f"Result: {'PASSED' if passed else 'FAILED'}")
return passed
# =============================================================================
# BASELINE GENERATOR
# =============================================================================
def generate_baselines(data_path: str = "../", output_path: str = None,
verbose: bool = True) -> Dict:
"""Generate baseline metrics for all validation cases."""
if verbose:
print("Generating baseline metrics...")
dataset = FloorplanDatasetLiteTest(data_path)
baselines = []
iterator = tqdm(range(len(dataset)), desc="Processing") if verbose else range(len(dataset))
for idx in iterator:
sample = dataset[idx]
inputs, labels = sample['input'], sample['label']
area_target, b2b_conn, p2b_conn, pins_pos, constraints = inputs
polygons, metrics = labels
block_count = int((area_target != -1).sum().item())
# Extract positions from ground truth
positions = []
for i in range(block_count):
block = polygons[i]
valid = block[block[:, 0] != -1]
if len(valid) > 0:
x_min, y_min = valid.min(dim=0).values
x_max, y_max = valid.max(dim=0).values
positions.append((float(x_min), float(y_min),
float(x_max - x_min), float(y_max - y_min)))
else:
positions.append((0, 0, 1, 1))
hpwl_b2b = calculate_hpwl_b2b(positions, b2b_conn)
hpwl_p2b = calculate_hpwl_p2b(positions, p2b_conn, pins_pos)
area = calculate_bbox_area(positions)
# Use stored metrics if available
if metrics is not None and len(metrics) >= 8:
if metrics[0] > 0:
area = float(metrics[0])
if metrics[-2] > 0:
hpwl_b2b = float(metrics[-2])
if metrics[-1] >= 0:
hpwl_p2b = float(metrics[-1])
baselines.append({
'test_id': idx,
'block_count': block_count,
'hpwl_b2b': hpwl_b2b,
'hpwl_p2b': hpwl_p2b,
'hpwl_total': hpwl_b2b + hpwl_p2b,
'area': area
})
result = {'baselines': baselines, 'generated': datetime.now().isoformat()}
if output_path:
with open(output_path, 'w') as f:
json.dump(result, f, indent=2)
if verbose:
print(f"Saved to {output_path}")
return result
# =============================================================================
# TRAINING DATA UTILITIES
# =============================================================================
def compute_training_loss(
positions: List[Tuple[float, float, float, float]],
b2b_connectivity: torch.Tensor,
p2b_connectivity: torch.Tensor,
pins_pos: torch.Tensor,
area_targets: torch.Tensor,
baseline_metrics: Optional[torch.Tensor] = None,
constraints: Optional[torch.Tensor] = None,
return_components: bool = False
) -> Dict[str, float]:
"""
Compute training loss/cost for a training sample.
WARNING: This is a TRAINING PROXY, not the actual contest evaluation score!
Differences from actual contest evaluation:
- Uses training data ground truth as baseline (evaluation uses test baselines)
- NOT differentiable (uses integer violation counts, conditional logic)
- Does NOT check all placement constraints (fixed, MIB, cluster, boundary)
For gradient-based training, implement differentiable approximations.
For RL/evolution, this can serve as a reward signal.
Final contest ranking uses hidden TEST data (same format as validation).