-
Notifications
You must be signed in to change notification settings - Fork 0
/
program_evaluator.py
679 lines (564 loc) · 21.8 KB
/
program_evaluator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
# run the generated programs and evalute the grounding results
import argparse
import functools
import json
import os
import random
import sys
import traceback
from dataclasses import dataclass
from multiprocessing import Pool
from tqdm import tqdm
from tqdm.contrib.concurrent import process_map
from typing_extensions import Self
from program_functions_csp import reset_csp_solver, run_csp_solver
from scannet_utils import ObjInstance, ScanNetScene
from scope_env import (
TargetInfo,
get_eval_scope,
set_instance_map,
set_room_center,
)
@dataclass
class EvalSingleResultScanRefer:
acc05: bool = False
acc05_potential: bool = False
acc025: bool = False
acc025_potential: bool = False
is_unique: bool = True
eval_result: dict = None
error: bool = False
llm_used: bool = False
@dataclass
class EvalSingleResultNr3D:
eval_result: dict = None
is_hard: bool = False
is_view_dependent: bool = False
success: bool = False
could_success: bool = False
error: bool = False
llm_used: bool = False
def eval_single_scanrefer(
query_info: tuple[int, dict],
mask3d_pred_path: str | None = None,
maskcluster_pred_path: str | None = None,
cache_root: str | None = None,
solver_type: str = "default",
select_solution: str = "min_dist",
verbose: int = 0,
) -> EvalSingleResultScanRefer:
query_id, query = query_info
result = EvalSingleResultScanRefer()
result.eval_result = query.copy()
result.eval_result["query_id"] = query_id
result.eval_result["acc05"] = False
result.eval_result["acc025"] = False
# todo:
# loading the scene for every query is slow!
# we should load all relevant scens at the beginning.
scene_id = query["scene_id"]
scene = ScanNetScene(
f"./data/scans/{scene_id}",
mask3d_pred_path=mask3d_pred_path,
maskcluster_pred_path=maskcluster_pred_path,
add_room_center=True,
add_room_corners=True,
cache_root=cache_root,
)
# scene.visualize()
# used to get groundtruth bounding boxes
gt_scene = ScanNetScene(
f"./data/scans/{scene_id}",
mask3d_pred_path=None,
maskcluster_pred_path=None,
add_room_center=False,
add_room_corners=False,
cache_root=cache_root,
)
# check if the query is "unique" or "multiple"
result.is_unique = gt_scene.is_unique_label(
query["target_label"].replace("_", " ").lower().strip()
)
if verbose >= 2:
print(f"==================> vvv Query {query_id} vvv <==================")
print(query["text"])
print(query["scene_id"])
print(query["target_id"])
print(query["target_label"])
print(query["program"])
print()
use_min_dist_heuristic = True
query_text = query["text"].lower()
if any(
x in query_text
for x in {"far", "across", "opposite", "away", "remote", "distant"}
):
use_min_dist_heuristic = False
try:
# this is such a mess... it would be better to implement an interpreter manually,
# which will provide better error messages and debugging support
set_instance_map(scene.get_instance_map())
set_room_center(scene.get_room_center())
reset_csp_solver()
TargetInfo.reset()
exec(query["program"], get_eval_scope(use_type_check_funcs=False))
run_csp_solver(
query=query["text"],
solver_type=solver_type,
select_solution=select_solution,
)
# check acc@0.25/0.5
gt_bbox = gt_scene.get_instance_bbox(str(query["target_id"]))
if TargetInfo.best_instance is not None:
iou_best = TargetInfo.best_instance.bbox.iou(gt_bbox)
iou_others = [
inst.bbox.iou(gt_bbox) for inst in TargetInfo.candidate_instances
]
result.eval_result["predicted_bbox"] = {
"pmin": [float(x) for x in list(TargetInfo.best_instance.bbox.pmin)],
"pmax": [float(x) for x in list(TargetInfo.best_instance.bbox.pmax)],
}
result.eval_result["anchor_bboxes"] = {
name: {
"pmin": [float(x) for x in list(inst.bbox.pmin)],
"pmax": [float(x) for x in list(inst.bbox.pmax)],
}
if isinstance(inst, ObjInstance)
else [
{
"pmin": [float(x) for x in list(y.bbox.pmin)],
"pmax": [float(x) for x in list(y.bbox.pmax)],
}
for y in inst
]
for name, inst in TargetInfo.anchor_instances.items()
}
result.eval_result["csp_desc"] = TargetInfo.csp_desc
result.llm_used = TargetInfo.llm_used
if iou_best >= 0.5:
result.acc05 = True
result.eval_result["acc05"] = True
if iou_best >= 0.25:
result.acc025 = True
result.eval_result["acc025"] = True
if (result.acc05 or result.acc025) and verbose >= 2:
print()
print("*** SUCCESSFUL ***")
print()
if any(x >= 0.5 for x in iou_others):
result.acc05_potential = True
# if result.acc05 is False:
# result.eval_result["far"] = True
if any(x >= 0.25 for x in iou_others):
result.acc025_potential = True
if (result.acc05_potential or result.acc025_potential) and verbose >= 2:
print()
print("*** COULD BE SUCCESSFUL ***")
print()
if verbose >= 2:
# print(TargetInfo.label)
# for inst in TargetInfo.instances:
# print(inst.inst_id, inst.label)
print(f"==================> ^^^ Query {query_id} ^^^ <==================")
print()
print()
print()
except Exception as e:
# raise e
if verbose >= 2:
print()
print("============> Query Failed <============")
print(query["program"])
print("========================================")
print()
if verbose >= 1:
print()
print(f"QUERY {query_id} THROWS EXCEPTION!")
print()
print(os.linesep.join([s for s in query["program"].splitlines() if s]))
print()
traceback.print_exc(file=sys.stdout)
print()
result.acc025 = False
result.acc025_potential = False
result.acc05 = False
result.acc05_potential = False
result.eval_result = query.copy()
result.eval_result["acc05"] = False
result.eval_result["acc025"] = False
result.error = True
return result
def eval_single_nr3d(
query_info: tuple[int, dict],
mask3d_pred_path: str | None = None,
maskcluster_pred_path: str | None = None,
cache_root: str | None = None,
solver_type: str = "default",
select_solution: str = "min_dist",
verbose: int = 0,
) -> EvalSingleResultNr3D:
query_id, query = query_info
result = EvalSingleResultNr3D()
result.eval_result = query.copy()
result.eval_result["success"] = False
assert "view_dependent" in query
assert "hard" in query
result.is_hard = query["hard"]
result.is_view_dependent = query["view_dependent"]
scene_id = query["scene_id"]
scene = ScanNetScene(
f"./data/scans/{scene_id}",
mask3d_pred_path=mask3d_pred_path,
maskcluster_pred_path=maskcluster_pred_path,
add_room_center=True,
add_room_corners=True,
cache_root=cache_root,
)
# scene.visualize()
# used to get groundtruth bounding boxes
gt_scene = ScanNetScene(
f"./data/scans/{scene_id}",
mask3d_pred_path=None,
maskcluster_pred_path=None,
add_room_center=False,
add_room_corners=False,
cache_root=cache_root,
)
if verbose >= 2:
print(f"==================> vvv Query {query_id} vvv <==================")
print(query["text"])
print(query["scene_id"])
print(query["target_id"])
print(query["target_label"])
print(query["program"])
print()
use_min_dist_heuristic = True
query_text = query["text"].lower()
if any(
x in query_text
for x in {"far", "across", "opposite", "away", "remote", "distant"}
):
use_min_dist_heuristic = False
try:
# this is such a mess... it would be better to implement an interpreter manually,
# which will provide better error messages and debugging support
set_instance_map(scene.get_instance_map())
set_room_center(scene.get_room_center())
reset_csp_solver()
TargetInfo.reset()
exec(query["program"], get_eval_scope(use_type_check_funcs=False))
run_csp_solver(
query=query["text"],
solver_type=solver_type,
select_solution=select_solution,
)
except Exception as e:
# raise e
if verbose >= 2:
print()
print("============> Query Failed <============")
print(query["program"])
print("========================================")
print()
if verbose >= 1:
print()
print(f"QUERY {query_id} THROWS EXCEPTION!")
print()
print(
os.linesep.join(
[s for s in query["program"].splitlines() if s.rstrip()]
)
)
print()
traceback.print_exc(file=sys.stdout)
print()
result.error = True
if TargetInfo.best_instance is not None:
if str(TargetInfo.best_instance.inst_id) == str(query["target_id"]):
result.success = True
result.eval_result["success"] = True
if verbose >= 2:
print()
print("*** SUCCESSFUL ***")
print()
if str(TargetInfo.best_instance.inst_id) in set(
str(inst.inst_id) for inst in TargetInfo.candidate_instances
):
result.could_success = True
if verbose >= 2:
print()
print("*** COULD BE SUCCESSFUL ***")
print()
result.eval_result["predicted_bbox"] = {
"pmin": [float(x) for x in list(TargetInfo.best_instance.bbox.pmin)],
"pmax": [float(x) for x in list(TargetInfo.best_instance.bbox.pmax)],
}
result.eval_result["anchor_bboxes"] = {
name: {
"pmin": [float(x) for x in list(inst.bbox.pmin)],
"pmax": [float(x) for x in list(inst.bbox.pmax)],
}
if isinstance(inst, ObjInstance)
else [
{
"pmin": [float(x) for x in list(y.bbox.pmin)],
"pmax": [float(x) for x in list(y.bbox.pmax)],
}
for y in inst
]
for name, inst in TargetInfo.anchor_instances.items()
}
result.eval_result["csp_desc"] = TargetInfo.csp_desc
result.llm_used = TargetInfo.llm_used
if verbose >= 2:
# print(TargetInfo.label)
# for inst in TargetInfo.instances:
# print(inst.inst_id, inst.label)
print(f"==================> ^^^ Query {query_id} ^^^ <==================")
print()
print()
print()
assert isinstance(result, EvalSingleResultNr3D)
return result
def main():
# register predefined functions
# import program_functions as _
import program_functions_csp as _
parser = argparse.ArgumentParser()
parser.add_argument(
"--solver", type=str, choices=["default", "non_csp"], default="default"
)
parser.add_argument(
"--select-solution",
type=str,
choices=["min_dist", "max_dist", "random", "first"],
default="min_dist",
)
parser.add_argument("--dataset", type=str, required=True)
parser.add_argument("--experiment-name", type=str)
parser.add_argument("--seg", type=str, choices=["gt", "mask3d"], required=True)
parser.add_argument("--num-threads", type=int, default=30)
parser.add_argument("--num-queries", type=int)
parser.add_argument("--verbose", type=int, default=0)
parser.add_argument("--print-if-succeed", action="store_true")
args = parser.parse_args()
tags = []
if args.seg == "gt":
print("using gt segmentation")
tags.append("gt")
mask3d_pred = None
maskcluster_pred = None
if args.seg == "mask3d":
print("using mask3d segmentation")
mask3d_pred = "./data/eval_output/mask3d_val"
tags.append("mask3d")
if args.seg == "maskcluster":
print("using maskclustering segmentation")
maskcluster_pred = "./data/eval_output/maskcluster"
tags.append("maskcluster")
raise NotImplementedError()
assert len(tags) == 1
if args.dataset == "scanrefer":
print("using scanrefer dataset")
tags.append("scanrefer")
if args.dataset == "nr3d":
print("using nr3d dataset")
tags.append("nr3d")
if args.dataset == "custom":
print("using custom dataset")
tags.append("custom")
if len(tags) < 2:
assert args.dataset
print(f"using custom dataset: {args.dataset}")
tags.append(args.dataset)
assert len(tags) == 2
if args.experiment_name:
print(f"using experiment name: {args.experiment_name}")
tags.append(args.experiment_name)
cache_root = "./data/instance_cache"
eval_file_path = f"./output/eval_data_{'_'.join(tags)}.json"
eval_results_file_path = f"./output/eval_results_{'_'.join(tags)}.json"
print(f"loading eval file: [{eval_file_path}].")
print(f"will write results to file: [{eval_results_file_path}].")
if not os.path.isfile(eval_file_path):
print("eval file not found.")
return
print(f"using csp solver: {args.solver}.")
with open(eval_file_path) as f:
eval_data = json.load(f)
if args.num_queries is not None:
random.seed()
random.shuffle(eval_data)
eval_data = eval_data[0 : args.num_queries]
num_threads = args.num_threads
num_errors = 0
num_llm_used = 0
num_llm_correct = 0
verbose = args.verbose
print()
if args.dataset != "nr3d":
# accumulate some statistics
num_acc05 = 0
num_acc025 = 0
num_acc05_potential = 0
num_acc025_potential = 0
num_evals = 0
num_acc05_unique = 0
num_acc025_unique = 0
num_acc05_potential_unique = 0
num_acc025_potential_unique = 0
num_evals_unique = 0
num_acc05_multiple = 0
num_acc025_multiple = 0
num_acc05_potential_multiple = 0
num_acc025_potential_multiple = 0
num_evals_multiple = 0
good_query_indices = []
# start evaluation
eval_results = []
eval_data = eval_data[:]
eval_single_func = functools.partial(
eval_single_scanrefer,
mask3d_pred_path=mask3d_pred,
maskcluster_pred_path=maskcluster_pred,
cache_root=cache_root,
solver_type=args.solver,
select_solution=args.select_solution,
verbose=verbose,
)
with Pool(num_threads) as pool:
for result in tqdm(
pool.imap_unordered(
eval_single_func,
zip(range(len(eval_data)), eval_data),
),
total=len(eval_data),
):
if args.print_if_succeed:
print()
print(f"query: {result.eval_result['text']}")
print(f"program:\n{result.eval_result['program']}")
print("success" if result.acc05 else "failure")
print()
num_errors += int(result.error)
if result.llm_used:
num_llm_used += 1
num_llm_correct += int(result.acc05)
num_acc05 += int(result.acc05)
num_acc025 += int(result.acc025)
num_acc05_potential += int(result.acc05_potential)
num_acc025_potential += int(result.acc025_potential)
num_evals += 1
if result.is_unique:
num_acc05_unique += int(result.acc05)
num_acc025_unique += int(result.acc025)
num_acc05_potential_unique += int(result.acc05_potential)
num_acc025_potential_unique += int(result.acc025_potential)
num_evals_unique += 1
else:
num_acc05_multiple += int(result.acc05)
num_acc025_multiple += int(result.acc025)
num_acc05_potential_multiple += int(result.acc05_potential)
num_acc025_potential_multiple += int(result.acc025_potential)
num_evals_multiple += 1
assert result.eval_result
eval_results.append(result.eval_result)
if result.acc05:
good_query_indices.append(result.eval_result["query_id"])
print()
print("========================= evalutation results =========================")
print()
# fmt: off
print(f"acc@0.5: {num_acc05 / num_evals:.4f} ({num_acc05} / {num_evals})")
print(f"acc@0.25: {num_acc025 / num_evals:.4f} ({num_acc025} / {num_evals})")
print(f"acc@0.5 (?): {num_acc05_potential / num_evals:.4f} ({num_acc05_potential} / {num_evals})")
print(f"acc@0.25 (?): {num_acc025_potential / num_evals:.4f} ({num_acc025_potential} / {num_evals})")
if num_evals_unique > 0:
print(f"acc@0.5 (u): {num_acc05_unique / num_evals_unique:.4f} ({num_acc05_unique} / {num_evals_unique})")
print(f"acc@0.25 (u): {num_acc025_unique / num_evals_unique:.4f} ({num_acc025_unique} / {num_evals_unique})")
if num_evals_multiple > 0:
print(f"acc@0.5 (m): {num_acc05_multiple / num_evals_multiple:.4f} ({num_acc05_multiple} / {num_evals_multiple})")
print(f"acc@0.25 (m): {num_acc025_multiple / num_evals_multiple:.4f} ({num_acc025_multiple} / {num_evals_multiple})")
print(f"errors: {num_errors}")
print(f"llm: {num_llm_correct} / {num_llm_used}")
# fmt: on
# print(sorted(good_query_indices))
print()
print("========================= evalutation results =========================")
print()
if args.dataset == "nr3d":
num_overall = 0
num_overall_success = 0
num_easy = 0
num_easy_success = 0
num_hard = 0
num_hard_success = 0
num_view_dep = 0
num_view_dep_success = 0
num_view_indep = 0
num_view_indep_success = 0
# start evaluation
eval_results = []
eval_data = eval_data[:]
eval_single_func = functools.partial(
eval_single_nr3d,
mask3d_pred_path=mask3d_pred,
maskcluster_pred_path=maskcluster_pred,
cache_root=cache_root,
solver_type=args.solver,
select_solution=args.select_solution,
verbose=verbose,
)
with Pool(num_threads) as pool:
for result in tqdm(
pool.imap_unordered(
eval_single_func,
zip(range(len(eval_data)), eval_data),
),
total=len(eval_data),
):
if args.print_if_succeed:
print()
print(f"query: {result.eval_result['text']}")
print("success" if result.acc05 else "failure")
print()
num_errors += int(result.error)
if result.llm_used:
num_llm_used += 1
num_llm_correct += int(result.acc05)
num_overall += 1
num_overall_success += int(result.success)
if result.is_hard:
num_hard += 1
num_hard_success += int(result.success)
else:
num_easy += 1
num_easy_success += int(result.success)
if result.is_view_dependent:
num_view_dep += 1
num_view_dep_success += int(result.success)
else:
num_view_indep += 1
num_view_indep_success += int(result.success)
assert result.eval_result
eval_results.append(result.eval_result)
print()
print("========================= evalutation results =========================")
print()
# fmt: off
print(f"overall: {num_overall_success / num_overall:.4f} ({num_overall_success} / {num_overall})")
print(f"easy: {num_easy_success / num_easy:.4f} ({num_easy_success} / {num_easy})")
print(f"hard: {num_hard_success / num_hard:.4f} ({num_hard_success} / {num_hard})")
print(f"view dep: {num_view_dep_success / num_view_dep:.4f} ({num_view_dep_success} / {num_view_dep})")
print(f"view indep: {num_view_indep_success / num_view_indep:.4f} ({num_view_indep_success} / {num_view_indep})")
print(f"errors: {num_errors}")
print(f"llm: {num_llm_correct} / {num_llm_used}")
# fmt: on
print()
print("========================= evalutation results =========================")
print()
with open(eval_results_file_path, "w") as f:
json.dump(eval_results, f)
if __name__ == "__main__":
# random.seed(0)
main()