File size: 55,682 Bytes
0c0ff0e | 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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 | import os
from model.transformer import GPTConfig, GPT
from model.transformer_rope import GPTRoPEConfig, GPTRoPE
from model.transformer_nextlat import TransformerNextLatConfig, TransformerNextLat
from model.mamba import MambaConfig, Mamba
from model.mamba2 import Mamba2Config, Mamba2
from model.gated_deltanet import GatedDeltaNetConfig, GatedDeltaNet
from model.gru import GRUConfig, GRU
import numpy as np
import networkx as nx
import argparse
import pickle
import re
import torch
import math
from torch.nn.utils.rnn import pad_sequence
from cli_utils import parse_count, format_count
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--ckpt_iter', type=int, default=10000)
parser.add_argument('--model', type=str, default='transformer', choices=['transformer', 'transformer-rope', 'transformer-nextlat', 'mamba', 'mamba2', 'gated-deltanet', 'gru'],
help='Model architecture; selects out/<model>/ and how the checkpoint is built.')
parser.add_argument('--config', type=str, default='12_12_576')
parser.add_argument('--temperature', type=float, default=1)
parser.add_argument('--device', type=str, default='cuda:0')
parser.add_argument('--num_nodes', type=int, default=100)
parser.add_argument('--num_of_paths', type=int, default=20)
parser.add_argument('--batch_size', type=int, default=100)
parser.add_argument('--num_iters', type=int, default=10)
parser.add_argument('--multitasks', action=argparse.BooleanOptionalAction, default=True,
help='Use multitask data (default: True)')
parser.add_argument('--num_train_dataset', type=parse_count, default='10M',
help='Number of multitask training entries (supports K/M/B, default: 50000)')
parser.add_argument('--num_test_dataset', type=parse_count, default=10000,
help='Number of multitask test entries (supports K/M/B, default: 10000)')
parser.add_argument('--tasks', type=str, default='H1',
help='Task specification (e.g., A1, A1B1, A3B2, A1D1F1). Default: A1')
parser.add_argument('--CL', action=argparse.BooleanOptionalAction, default=False,
help='Task C turn-label mode (default: False)')
parser.add_argument('--graph_file', type=str, default=None,
help='Optional GraphML path; if provided, load this graph instead of the default')
parser.add_argument('--B_graph_file', type=str, default=None,
help='Optional GraphML path for Task B; if provided, use this graph for Task B validation instead of the default')
parser.add_argument('--local', action='store_true', default=False,
help='Disable flash attention for local GPU compatibility (default: False)')
parser.add_argument('--path_type', type=str, default='RWs', choices=['RWc', 'RWa', 'RWs'],
help='Path generation type: RWc (random walk with cycles), RWa (random walk acyclic, default), RWs (single source random walk).')
parser.add_argument('--partial', action='store_true', default=False,
help='Test with partial prefixes: use a random portion of the path as prompt instead of just "A source target:" (default: False)')
# New argument to handle data without task tags
parser.add_argument('--no_task_tag', action='store_true', default=False,
help='Data files do not contain task identifiers (A, B, C, etc.). When enabled, task tokens will not be considered in data processing. This should match the setting used during data generation.')
parser.add_argument('--num_labels', type=int, default=10,
help='Number of distinct node labels (default: 10). Must match data generation.')
parser.add_argument('--PostGRU', action='store_true', default=False,
help='Load PostGRU checkpoint (adds _PGR suffix to checkpoint filename)')
parser.add_argument('--NLS', action='store_true', default=False,
help='Load NLS checkpoint (adds _NLS suffix to checkpoint filename)')
parser.add_argument('--DyadicAttn', action='store_true', default=False,
help='Load DyadicAttn checkpoint (adds _DA suffix to checkpoint filename)')
parser.add_argument('--DyadicHybrid', action='store_true', default=False,
help='Load DyadicHybrid checkpoint (adds _DH suffix to checkpoint filename)')
parser.add_argument('--ckpt_suffix', type=str, default='',
help='Extra checkpoint tag to select a specific variant trained by '
'train_taskC.py (e.g. "SA" loads ..._{tasks_tag}_SA_{train_label}.pt). '
'Default empty = baseline model.')
# batch_size = 100 is for my laptop GPU with 4GB memory, for A100 GPU, you can set batch_size = 1000
return parser.parse_args()
args = parse_args()
dataset = 'maze'
ckpt_iter = args.ckpt_iter
device = args.device
temperature = args.temperature
num_nodes = args.num_nodes
num_of_paths = args.num_of_paths
config = args.config
multitasks = args.multitasks
num_train_dataset = args.num_train_dataset
num_test_dataset = args.num_test_dataset
train_label = format_count(num_train_dataset)
test_dataset_label = format_count(num_test_dataset)
run_test_label = args.batch_size * args.num_iters
no_task_tag = args.no_task_tag # Get the no_task_tag flag
tasks_str = args.tasks
tasks_tag = f"{tasks_str}_CL" if args.CL else tasks_str
# Parse path_type for filenames (RWc = cyclic, RWa = acyclic, RWs = single source)
allow_cycles = (args.path_type in ['RWc', 'RWs'])
path_type_tag = args.path_type
tasks_tag = f"{tasks_tag}_{path_type_tag}"
# Include num_labels in tags when non-default
if args.num_labels != 10:
tasks_tag = f"{tasks_tag}_L{args.num_labels}"
# Add _NT_ tag to tasks_tag when no_task_tag is enabled
if args.no_task_tag:
tasks_tag = f"{tasks_tag}_NT"
# data_tasks_tag: used for finding data/meta files (no _NL suffix)
data_tasks_tag = tasks_tag
# Add _NL tag to tasks_tag for transformer-nextlat (affects checkpoint and output naming only)
if args.model == 'transformer-nextlat':
tasks_tag = f"{tasks_tag}_NL"
# Add _PGR tag to tasks_tag when PostGRU is enabled (affects checkpoint and output naming only)
if args.PostGRU:
tasks_tag = f"{tasks_tag}_PGR"
# Add _NLS tag to tasks_tag when NLS is enabled (affects checkpoint and output naming only)
if args.NLS:
tasks_tag = f"{tasks_tag}_NLS"
# Add _DA tag to tasks_tag when DyadicAttn is enabled
if args.DyadicAttn:
tasks_tag = f"{tasks_tag}_DA"
if args.DyadicHybrid:
tasks_tag = f"{tasks_tag}_DH"
# Append an arbitrary variant suffix (e.g. SA = state-aligned from train_taskC.py).
# Affects checkpoint loading and prediction output naming, not data/graph discovery.
if args.ckpt_suffix:
tasks_tag = f"{tasks_tag}_{args.ckpt_suffix}"
# Graph tag includes path type to match generated graph files
graph_tag = f"{tasks_str}_CL" if args.CL else tasks_str
graph_tag = f"{graph_tag}_{path_type_tag}"
# Include num_labels in graph_tag when non-default
if args.num_labels != 10:
graph_tag = f"{graph_tag}_L{args.num_labels}"
# Add _NT_ tag to graph_tag when no_task_tag is enabled
if args.no_task_tag:
graph_tag = f"{graph_tag}_NT"
data_path = f'data/{dataset}/{num_nodes}'
def pick_first_existing_meta(candidates):
for path in candidates:
if os.path.exists(path):
return path
return candidates[0]
meta_path = pick_first_existing_meta([
f'{data_path}/meta_{data_tasks_tag}.pkl',
f'{data_path}/meta_{tasks_str}.pkl',
f'{data_path}/meta.pkl',
])
print(f"Loading meta from {meta_path}...")
with open(meta_path, 'rb') as f:
meta = pickle.load(f)
stoi, itos = meta['stoi'], meta['itos']
max_new_tokens = meta['block_size']
top_k = len(itos)
simple_format = meta['simple_format']
# Check if metadata contains no_task_tag flag and use it if available
if 'no_task_tag' in meta:
meta_no_task_tag = meta['no_task_tag']
nt_suffix = '_NT' if no_task_tag else ''
out_dir = f'out/{args.model.replace("-", "_")}/{dataset}_{config}_{num_nodes}{nt_suffix}/'
def pick_first_existing(candidates):
for path in candidates:
if os.path.exists(path):
return path
return candidates[0]
if multitasks:
candidate_ckpts = [
os.path.join(out_dir, f'{ckpt_iter}_ckpt_maze_{tasks_tag}_{train_label}.pt'),
os.path.join(out_dir, f'{ckpt_iter}_ckpt_maze_{tasks_tag}_{num_train_dataset}.pt'),
os.path.join(out_dir, f'{ckpt_iter}_ckpt_maze_{tasks_str}_{train_label}.pt'),
os.path.join(out_dir, f'{ckpt_iter}_ckpt_maze_{tasks_str}_{num_train_dataset}.pt'),
os.path.join(out_dir, f'{ckpt_iter}_ckpt_maze_{num_of_paths}.pt'),
os.path.join(out_dir, f'{ckpt_iter}_ckpt_maze.pt'),
]
ckpt_path = pick_first_existing(candidate_ckpts)
else:
if (num_of_paths == 0):
ckpt_path = os.path.join(out_dir, f'{ckpt_iter}_ckpt_maze.pt')
else:
ckpt_path = os.path.join(out_dir, f'{ckpt_iter}_ckpt_maze_{num_of_paths}.pt')
checkpoint = torch.load(ckpt_path, map_location=device, weights_only=False)
model_args = checkpoint['model_args']
ckpt_model_type = checkpoint.get('model_type', args.model)
if ckpt_model_type == 'mamba':
model = Mamba(MambaConfig(**model_args))
elif ckpt_model_type == 'mamba2':
model = Mamba2(Mamba2Config(**model_args))
elif ckpt_model_type == 'gated-deltanet':
model = GatedDeltaNet(GatedDeltaNetConfig(**model_args))
elif ckpt_model_type == 'gru':
model = GRU(GRUConfig(**model_args))
elif ckpt_model_type == 'transformer-nextlat':
if args.local:
model_args['use_flash'] = False # Override for local GPU compatibility
model = TransformerNextLat(TransformerNextLatConfig(**model_args))
elif ckpt_model_type == 'transformer-rope':
if args.local:
model_args['use_flash'] = False # Override for local GPU compatibility
model = GPTRoPE(GPTRoPEConfig(**model_args))
else:
if args.local:
model_args['use_flash'] = False # Override for local GPU compatibility
gptconf = GPTConfig(**model_args)
model = GPT(gptconf)
state_dict = checkpoint['model']
unwanted_prefix = '_orig_mod.'
for k, v in list(state_dict.items()):
if k.startswith(unwanted_prefix):
state_dict[k[len(unwanted_prefix):]] = state_dict.pop(k)
model.load_state_dict(state_dict)
model.eval()
model.to(device)
graph_file = args.graph_file
if graph_file is not None:
maze_graph_path = graph_file if os.path.isabs(graph_file) else os.path.join(data_path, graph_file)
else:
if multitasks:
maze_graph_path = pick_first_existing([
f'{data_path}/maze_graph_{graph_tag}.graphml',
f'{data_path}/maze_graph_{tasks_str}.graphml',
f'{data_path}/maze_graph.graphml',
])
else:
maze_graph_path = f'{data_path}/maze_graph.graphml'
maze_graph = nx.read_graphml(maze_graph_path)
# Discover node labels from graph (supports arbitrary label sets)
graph_node_labels = set(attrs.get('label', '?') for _, attrs in maze_graph.nodes(data=True))
print(f"Graph labels ({len(graph_node_labels)}): {sorted(graph_node_labels)[:10]}{'...' if len(graph_node_labels) > 10 else ''}")
# Load separate graph for Task B if specified
B_graph_file = args.B_graph_file
if B_graph_file is not None:
B_graph_path = B_graph_file if os.path.isabs(B_graph_file) else os.path.join(data_path, B_graph_file)
print(f"Loading Task B graph from {B_graph_path}...")
maze_graph_B = nx.read_graphml(B_graph_path)
else:
maze_graph_B = maze_graph # Use the same graph for Task B
# Calculate grid size from number of nodes
n = int(math.sqrt(num_nodes))
def find_third_number_position(number_string):
numbers = number_string.split()
if no_task_tag:
# In no_task_tag mode, there is no task ID, so source and target are at indices 0 and 1
third_number_index = 2 # source + target
else:
# Check if first token is a task ID (A, B, C, D, E, F, G)
if numbers[0] in ['A', 'B', 'C', 'D', 'E', 'F', 'G']:
# Skip task ID, then get source and target nodes (indices 1 and 2)
third_number_index = 3 # task_id + source + target
else:
# Old format without task ID
third_number_index = 2 # source + target
position = sum(len(num) for num in numbers[:third_number_index]) + third_number_index - 1
return position
def encode(s):
ss = s.split(" ")
encoded_string = [stoi[ch] for ch in ss]
return encoded_string
def decode(l):
dec = ""
for i in l:
dec = dec + itos[i] + " "
return dec[:-1]
def check_maze_path(G, gen_str, n, prefix_dir_count=0):
"""
Check if a maze path in direction format is valid.
Format: "task_id source_node target_node direction_sequence" or "source_node target_node direction_sequence"
Task IDs: A, B, C, D, E, F, G (optional, for multi-task support)
Directions: N (north/up), S (south/down), E (east/right), W (west/left)
Args:
G: The graph
gen_str: The generated string to check
n: Grid size
prefix_dir_count: Number of prefix directions (for partial mode, step numbers in errors will be offset)
Returns:
'' if path is correct
error message otherwise
"""
tokens = [t for t in gen_str.split() if t != ':' and t != '>']
# Check if first token is a task ID (only if not in no_task_tag mode)
task_offset = 0
if not no_task_tag and len(tokens) > 0 and tokens[0] in ['A', 'B', 'C', 'D', 'E', 'F', 'G']:
task_offset = 1
# Check basic syntax: need at least source and target (after task ID if present)
if len(tokens) < 2 + task_offset:
return 'syntax error'
try:
source = int(tokens[task_offset])
target = int(tokens[task_offset + 1])
except (ValueError, IndexError):
return 'syntax error'
# Validate node IDs
if source < 0 or source >= num_nodes or target < 0 or target >= num_nodes:
return 'syntax error'
# Extract direction sequence (everything after task_id, source and target)
directions = tokens[2 + task_offset:]
# Start from source node
current_node = source
# Follow each direction
for i, direction in enumerate(directions):
if direction not in ['N', 'S', 'E', 'W']:
return 'syntax error'
# Calculate next node based on direction
next_node = None
if direction == 'N': # North (up)
next_node = current_node - n
elif direction == 'S': # South (down)
next_node = current_node + n
elif direction == 'E': # East (right)
next_node = current_node + 1
elif direction == 'W': # West (left)
next_node = current_node - 1
# Check if next_node is valid
# For partial mode, report step number relative to suffix (subtract prefix_dir_count)
suffix_step = i - prefix_dir_count
if next_node is None or next_node < 0 or next_node >= num_nodes:
if prefix_dir_count > 0 and suffix_step >= 0:
return f'suffix_step {suffix_step} node {current_node} direction {direction} is illegal'
else:
return f'step {i} node {current_node} direction {direction} is illegal'
# Check if edge exists in the graph
if not G.has_edge(str(current_node), str(next_node)):
if prefix_dir_count > 0 and suffix_step >= 0:
return f'suffix_step {suffix_step} node {current_node} direction {direction} is illegal'
else:
return f'step {i} node {current_node} direction {direction} is illegal'
# Move to next node
current_node = next_node
# Check if we reached the target
if current_node != target:
return 'incorrect target node'
return ''
def check_turn_path(G, gen_str, n, cl_mode=False):
"""Validate a path expressed as relative turns (L/R/F/T).
The agent starts facing East at the source node. Each token both turns
and advances one step in the grid.
When cl_mode is True, after each L or R turn token, there should be a
node label token matching the current node (before moving).
"""
tokens = [t for t in gen_str.split() if t != ':']
task_offset = 0
if not no_task_tag and len(tokens) > 0 and tokens[0] in TASK_TOKENS:
task_offset = 1
if len(tokens) < 2 + task_offset:
return 'syntax error'
try:
source = int(tokens[task_offset])
target = int(tokens[task_offset + 1])
except (ValueError, IndexError):
return 'syntax error'
if source < 0 or source >= num_nodes or target < 0 or target >= num_nodes:
return 'syntax error'
actions = tokens[2 + task_offset:]
orientation = 'E' # starts facing east
current_node = source
left_of = {'N': 'W', 'W': 'S', 'S': 'E', 'E': 'N'}
right_of = {v: k for k, v in left_of.items()}
opposite_of = {'N': 'S', 'S': 'N', 'E': 'W', 'W': 'E'}
delta = {'N': -n, 'S': n, 'E': 1, 'W': -1}
node_labels = graph_node_labels
action_idx = 0
step = 0
while action_idx < len(actions):
action = actions[action_idx]
if action not in ['L', 'R', 'F', 'T']:
return 'syntax error'
if action == 'F':
next_orientation = orientation
elif action == 'L':
next_orientation = left_of[orientation]
elif action == 'R':
next_orientation = right_of[orientation]
else: # 'T'
next_orientation = opposite_of[orientation]
next_node = current_node + delta[next_orientation]
if next_node < 0 or next_node >= num_nodes:
return f'step {step} node {current_node} direction {action} is illegal'
if not G.has_edge(str(current_node), str(next_node)):
return f'step {step} node {current_node} direction {action} is illegal'
# In CL mode, after L or R, expect a node label for the current node (checked after direction validity)
if cl_mode and action in ['L', 'R']:
if action_idx + 1 >= len(actions):
return 'syntax error' # missing label after L/R
label_token = actions[action_idx + 1]
if label_token not in node_labels:
return 'syntax error' # expected a node label
expected_label = G.nodes[str(current_node)]['label']
if label_token != expected_label:
return f'step {step} incorrect label {label_token} (expected {expected_label})'
action_idx += 1 # skip the label token
orientation = next_orientation
current_node = next_node
action_idx += 1
step += 1
if current_node != target:
return 'incorrect target node'
return ''
# Task-aware correctness wrappers
TASK_TOKENS = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'}
def check_correctness_taskA(G, gen_str, n, prefix_dir_count=0):
# Task A shares the same validation as path finding.
return check_maze_path(G, gen_str, n, prefix_dir_count=prefix_dir_count)
def check_correctness_taskB(G, gen_str, n, prompt_tokens=None):
# Validate Task B outputs against the prompt (start + directions) and graph labels.
if prompt_tokens is None:
return 'syntax error'
def strip_colon(seq):
return [t for t in seq if t != ':']
tokens_raw = gen_str.strip().split()
if no_task_tag:
# In no_task_tag mode, there is no 'B' task identifier
if ':' not in tokens_raw:
return 'syntax error'
colon_idx = tokens_raw.index(':')
prompt_part = tokens_raw[:colon_idx]
answer_part = tokens_raw[colon_idx + 1:]
else:
# Original format with task ID
if not tokens_raw or tokens_raw[0] != 'B':
return 'syntax error'
if ':' not in tokens_raw:
return 'syntax error'
colon_idx = tokens_raw.index(':')
prompt_part = tokens_raw[:colon_idx]
answer_part = tokens_raw[colon_idx + 1:]
prompt_clean = strip_colon(prompt_tokens)
if no_task_tag:
if len(prompt_clean) < 1:
return 'syntax error'
try:
start_node = int(prompt_clean[0])
except Exception:
return 'syntax error'
directions = prompt_clean[1:]
else:
if len(prompt_clean) < 2 or prompt_clean[0] != 'B':
return 'syntax error'
try:
start_node = int(prompt_clean[1])
except Exception:
return 'syntax error'
directions = prompt_clean[2:]
# Walk the prompt directions to find the true end node
current = start_node
for direction in directions:
if direction not in ['N', 'S', 'E', 'W']:
return 'syntax error'
if direction == 'N':
next_node = current - n
elif direction == 'S':
next_node = current + n
elif direction == 'E':
next_node = current + 1
else: # 'W'
next_node = current - 1
if next_node < 0 or next_node >= len(G.nodes):
return 'syntax error'
if not G.has_edge(str(current), str(next_node)):
return 'syntax error'
current = next_node
true_end = current
# Expect exactly: <target_label> <E> <S> <W> <N>
if len(answer_part) != 5:
return 'syntax error'
pred_label = answer_part[0]
true_label = G.nodes[str(true_end)]['label']
if pred_label != true_label:
return 'incorrect target node label'
pred_neighbors = answer_part[1:5]
neighbors_order = [(1, 'east'), (n, 'south'), (-1, 'west'), (-n, 'north')]
for idx, (offset, dir_name) in enumerate(neighbors_order):
neighbor_id = true_end + offset
has_neighbor = G.has_edge(str(true_end), str(neighbor_id))
true_neighbor_label = G.nodes[str(neighbor_id)]['label'] if has_neighbor else '/'
if pred_neighbors[idx] != true_neighbor_label:
return f'incorrect neighbor label {dir_name}'
return ''
def check_correctness_taskC(G, gen_str, n, cl_mode=False):
return check_turn_path(G, gen_str, n, cl_mode=cl_mode)
def check_correctness_taskD(G, gen_str, n, prompt_tokens=None):
if prompt_tokens is None:
return 'syntax error'
prompt_clean = [t for t in prompt_tokens if t != ':']
if no_task_tag:
if len(prompt_clean) < 2:
return 'syntax error'
try:
source = int(prompt_clean[0])
except Exception:
return 'syntax error'
target_label = prompt_clean[1]
else:
if len(prompt_clean) < 3 or prompt_clean[0] != 'D':
return 'syntax error'
try:
source = int(prompt_clean[1])
except Exception:
return 'syntax error'
target_label = prompt_clean[2]
node_labels = graph_node_labels
if target_label not in node_labels:
return 'syntax error'
tokens_raw = gen_str.strip().split()
if no_task_tag:
if ':' not in tokens_raw:
return 'syntax error'
answer_part = tokens_raw[tokens_raw.index(':') + 1:]
else:
if not tokens_raw or tokens_raw[0] != 'D' or ':' not in tokens_raw:
return 'syntax error'
answer_part = tokens_raw[tokens_raw.index(':') + 1:]
if not answer_part:
return 'syntax error'
current_node = source
for i, direction in enumerate(answer_part):
if direction not in ['N', 'S', 'E', 'W']:
return 'syntax error'
if direction == 'N':
next_node = current_node - n
elif direction == 'S':
next_node = current_node + n
elif direction == 'E':
next_node = current_node + 1
else:
next_node = current_node - 1
if next_node < 0 or next_node >= num_nodes:
return f'step {i} node {current_node} direction {direction} is illegal'
if not G.has_edge(str(current_node), str(next_node)):
return f'step {i} node {current_node} direction {direction} is illegal'
current_node = next_node
end_label = G.nodes[str(current_node)]['label']
if end_label != target_label:
return 'incorrect target node'
lengths = nx.single_source_shortest_path_length(G, str(source))
min_dist = None
for node_id, attrs in G.nodes(data=True):
if attrs.get('label') != target_label:
continue
dist = lengths.get(str(node_id))
if dist is None:
continue
if min_dist is None or dist < min_dist:
min_dist = dist
if min_dist is None or len(answer_part) != min_dist:
return 'incorrect target node'
return ''
def check_correctness_taskE(G, gen_str, n, prompt_tokens=None):
if prompt_tokens is None:
return "syntax error"
prompt_clean = [t for t in prompt_tokens if t != ':']
if no_task_tag:
if len(prompt_clean) < 2:
return "syntax error"
try:
source = int(prompt_clean[0]); target = int(prompt_clean[1])
except Exception:
return "syntax error"
else:
if len(prompt_clean) < 3 or prompt_clean[0] != 'E':
return "syntax error"
try:
source = int(prompt_clean[1]); target = int(prompt_clean[2])
except Exception:
return "syntax error"
tokens_raw = gen_str.strip().split()
if no_task_tag:
if ':' not in tokens_raw:
return "syntax error"
answer_part = tokens_raw[tokens_raw.index(':') + 1:]
else:
if not tokens_raw or tokens_raw[0] != 'E' or ':' not in tokens_raw:
return "syntax error"
answer_part = tokens_raw[tokens_raw.index(':') + 1:]
if not answer_part:
return "syntax error"
if len(answer_part) % 2 != 0:
return f"step {len(answer_part) - 1} syntax error"
node_labels = graph_node_labels
dirs = {'N', 'S', 'E', 'W'}
runs = []
for i in range(0, len(answer_part), 2):
d = answer_part[i]
lab = answer_part[i + 1]
if d not in dirs:
return f"step {i} syntax error"
if lab not in node_labels:
return f"step {i + 1} syntax error"
if not runs or runs[-1][0] != d or runs[-1][1] != lab:
runs.append([d, lab, 1, i])
else:
runs[-1][2] += 1
try:
total_nodes = G.number_of_nodes()
except Exception:
total_nodes = None
current = source
def step(node, direction):
if direction == 'N': return node - n
if direction == 'S': return node + n
if direction == 'E': return node + 1
return node - 1
for run_idx, (direction, lab, k, start_tok_idx) in enumerate(runs):
seen = 0
step_cap = total_nodes + 5 if total_nodes is not None else 10000
steps = 0
while True:
steps += 1
if steps > step_cap:
return f"step {start_tok_idx} run seems non-terminating"
nxt = step(current, direction)
if total_nodes is not None and (nxt < 0 or nxt >= total_nodes):
return f"step {start_tok_idx} node {current} direction {direction} is illegal"
if not G.has_edge(str(current), str(nxt)):
return f"step {start_tok_idx} node {current} direction {direction} is illegal"
current = nxt
node_label = G.nodes[str(current)]['label']
if node_label == lab:
seen += 1
if seen == k:
break
if current != target:
return "incorrect target node"
return ""
def check_correctness_taskF(G, gen_str, n, prompt_tokens=None):
if prompt_tokens is None:
return 'syntax error'
prompt_clean = [t for t in prompt_tokens if t != ':']
if no_task_tag:
if len(prompt_clean) < 1:
return 'syntax error'
start_label = prompt_clean[0]
directions = prompt_clean[1:]
else:
if len(prompt_clean) < 3 or prompt_clean[0] != 'F':
return 'syntax error'
start_label = prompt_clean[1]
directions = prompt_clean[2:]
if start_label not in graph_node_labels:
return 'syntax error'
valid_target_labels = set()
any_start = False
for node_id, attrs in G.nodes(data=True):
if attrs.get('label') != start_label:
continue
any_start = True
current_node = int(node_id)
for direction in directions:
if direction not in ['N', 'S', 'E', 'W']:
return 'syntax error'
if direction == 'N':
next_node = current_node - n
elif direction == 'S':
next_node = current_node + n
elif direction == 'E':
next_node = current_node + 1
else:
next_node = current_node - 1
if next_node < 0 or next_node >= num_nodes:
current_node = None
break
if not G.has_edge(str(current_node), str(next_node)):
current_node = None
break
current_node = next_node
if current_node is not None:
valid_target_labels.add(G.nodes[str(current_node)]['label'])
if not any_start or not valid_target_labels:
return 'syntax error'
tokens_raw = gen_str.strip().split()
if no_task_tag:
if ':' not in tokens_raw:
return 'syntax error'
answer_part = tokens_raw[tokens_raw.index(':') + 1:]
else:
if not tokens_raw or tokens_raw[0] != 'F' or ':' not in tokens_raw:
return 'syntax error'
answer_part = tokens_raw[tokens_raw.index(':') + 1:]
if len(answer_part) != 1:
return 'syntax error'
if answer_part[0] not in valid_target_labels:
return 'incorrect target label'
return ''
def check_correctness_taskG(G, gen_str, n, prompt_tokens=None):
if prompt_tokens is None:
return 'syntax error'
prompt_clean = [t for t in prompt_tokens if t != ':']
if no_task_tag:
if len(prompt_clean) < 4:
return 'syntax error'
try:
source1 = int(prompt_clean[0])
source2 = int(prompt_clean[1])
target1 = int(prompt_clean[2])
target2 = int(prompt_clean[3])
except Exception:
return 'syntax error'
else:
if len(prompt_clean) < 5 or prompt_clean[0] != 'G':
return 'syntax error'
try:
source1 = int(prompt_clean[1])
source2 = int(prompt_clean[2])
target1 = int(prompt_clean[3])
target2 = int(prompt_clean[4])
except Exception:
return 'syntax error'
tokens_raw = gen_str.strip().split()
if no_task_tag:
if ':' not in tokens_raw:
return 'syntax error'
answer_part = tokens_raw[tokens_raw.index(':') + 1:]
else:
if not tokens_raw or tokens_raw[0] != 'G' or ':' not in tokens_raw:
return 'syntax error'
answer_part = tokens_raw[tokens_raw.index(':') + 1:]
if len(answer_part) < 3:
return 'syntax error'
try:
chosen_source = int(answer_part[0])
chosen_target = int(answer_part[1])
except Exception:
return 'syntax error'
if (chosen_source, chosen_target) not in [(source1, target1), (source2, target2)]:
return 'syntax error'
if not nx.has_path(G, str(chosen_source), str(chosen_target)):
return 'incorrect target node'
directions = answer_part[2:]
current_node = chosen_source
for i, direction in enumerate(directions):
if direction not in ['N', 'S', 'E', 'W']:
return 'syntax error'
if direction == 'N':
next_node = current_node - n
elif direction == 'S':
next_node = current_node + n
elif direction == 'E':
next_node = current_node + 1
else:
next_node = current_node - 1
if next_node < 0 or next_node >= num_nodes:
return f'step {i} node {current_node} direction {direction} is illegal'
if not G.has_edge(str(current_node), str(next_node)):
return f'step {i} node {current_node} direction {direction} is illegal'
current_node = next_node
if current_node != chosen_target:
return 'incorrect target node'
return ''
def check_correctness_taskH(G, gen_str, n, prompt_tokens=None):
"""Validate Task H: relative clockwise-index path encoding.
The walker starts facing East. Each answer token is a 1-based index
into the feasible edges enumerated clockwise starting from the first
direction after the current facing direction.
"""
if prompt_tokens is None:
return 'syntax error'
prompt_clean = [t for t in prompt_tokens if t != ':']
if no_task_tag:
if len(prompt_clean) < 2:
return 'syntax error'
try:
source = int(prompt_clean[0])
target = int(prompt_clean[1])
except Exception:
return 'syntax error'
else:
if len(prompt_clean) < 3 or prompt_clean[0] != 'H':
return 'syntax error'
try:
source = int(prompt_clean[1])
target = int(prompt_clean[2])
except Exception:
return 'syntax error'
tokens_raw = gen_str.strip().split()
if no_task_tag:
if ':' not in tokens_raw:
return 'syntax error'
answer_part = tokens_raw[tokens_raw.index(':') + 1:]
else:
if not tokens_raw or tokens_raw[0] != 'H' or ':' not in tokens_raw:
return 'syntax error'
answer_part = tokens_raw[tokens_raw.index(':') + 1:]
if not answer_part:
return 'syntax error'
CLOCKWISE_SCAN = {
'N': ['N', 'E', 'S', 'W'],
'E': ['E', 'S', 'W', 'N'],
'S': ['S', 'W', 'N', 'E'],
'W': ['W', 'N', 'E', 'S'],
}
DELTA = {'N': -n, 'S': n, 'E': 1, 'W': -1}
facing = 'E'
current = source
for step_idx, token in enumerate(answer_part):
try:
idx = int(token)
except ValueError:
return f'step {step_idx} syntax error'
if idx < 1 or idx > 4:
return f'step {step_idx} invalid index {idx}'
# Enumerate feasible directions clockwise from facing
scan_order = CLOCKWISE_SCAN[facing]
feasible = []
for d in scan_order:
neighbor = current + DELTA[d]
if 0 <= neighbor < num_nodes and G.has_edge(str(current), str(neighbor)):
feasible.append(d)
if not feasible:
return f'step {step_idx} no feasible edges from node {current}'
if idx > len(feasible):
return f'step {step_idx} index {idx} exceeds feasible count {len(feasible)}'
direction = feasible[idx - 1]
next_node = current + DELTA[direction]
facing = direction
current = next_node
if current != target:
return 'incorrect target node'
return ''
def check_correctness_taskI(G, gen_str, n, prompt_tokens=None):
"""Validate Task I: absolute clockwise-index path encoding (fixed North).
Like Task H but feasible edges are always enumerated clockwise from a
FIXED North reference (N, E, S, W); the walker does not track facing.
Each answer token is the 1-based index into the node's feasible edges
in this fixed order.
"""
if prompt_tokens is None:
return 'syntax error'
prompt_clean = [t for t in prompt_tokens if t != ':']
if no_task_tag:
if len(prompt_clean) < 2:
return 'syntax error'
try:
source = int(prompt_clean[0])
target = int(prompt_clean[1])
except Exception:
return 'syntax error'
else:
if len(prompt_clean) < 3 or prompt_clean[0] != 'I':
return 'syntax error'
try:
source = int(prompt_clean[1])
target = int(prompt_clean[2])
except Exception:
return 'syntax error'
tokens_raw = gen_str.strip().split()
if no_task_tag:
if ':' not in tokens_raw:
return 'syntax error'
answer_part = tokens_raw[tokens_raw.index(':') + 1:]
else:
if not tokens_raw or tokens_raw[0] != 'I' or ':' not in tokens_raw:
return 'syntax error'
answer_part = tokens_raw[tokens_raw.index(':') + 1:]
if not answer_part:
return 'syntax error'
FIXED_SCAN = ['N', 'E', 'S', 'W']
DELTA = {'N': -n, 'S': n, 'E': 1, 'W': -1}
current = source
for step_idx, token in enumerate(answer_part):
try:
idx = int(token)
except ValueError:
return f'step {step_idx} syntax error'
if idx < 1 or idx > 4:
return f'step {step_idx} invalid index {idx}'
# Enumerate feasible directions clockwise from a fixed North reference
feasible = []
for d in FIXED_SCAN:
neighbor = current + DELTA[d]
if 0 <= neighbor < num_nodes and G.has_edge(str(current), str(neighbor)):
feasible.append(d)
if not feasible:
return f'step {step_idx} no feasible edges from node {current}'
if idx > len(feasible):
return f'step {step_idx} index {idx} exceeds feasible count {len(feasible)}'
direction = feasible[idx - 1]
current = current + DELTA[direction]
if current != target:
return 'incorrect target node'
return ''
def check_path_unreachable(G, gen_str, gt):
path = re.findall(r'\d+|x', gen_str)
if 'x' in path and len(path) < 4:
return 0 if 'x' in gt else 1
if 'x' in gt and 'x' not in gen_str:
return 1
return check_maze_path(G, gen_str, n)
typedata = 'test'
typedata_candidates = (
[
os.path.join(data_path, f'test_{data_tasks_tag}_{test_dataset_label}.txt'),
os.path.join(data_path, f'test_{data_tasks_tag}_{num_test_dataset}.txt'),
os.path.join(data_path, f'test_{data_tasks_tag}_{run_test_label}.txt'),
os.path.join(data_path, f'test_{tasks_str}_{test_dataset_label}.txt'),
os.path.join(data_path, f'test_{tasks_str}_{num_test_dataset}.txt'),
]
if multitasks else [os.path.join(data_path, f'{typedata}.txt')]
)
typedata_path = pick_first_existing(typedata_candidates)
f = open(typedata_path, encoding='gbk')
texts = []
encode_texts = []
ground_truth = []
full_lines = [] # Store full lines for partial prefix mode
for line in f:
line = line.strip()
if not line:
continue
full_lines.append(line) # Store full line for partial mode
if multitasks:
texts.append(line.split(':')[0] + ':')
encode_texts.append(encode(line.split(':')[0] + ':'))
else:
pos = find_third_number_position(line)
if (line[:pos] != ''):
texts.append(line[:pos])
encode_texts.append(encode(line[:pos]))
ground_truth.append(line)
ground_truth = np.array(ground_truth)
# Convert to torch tensors without padding to avoid training distribution mismatch
encode_texts = [torch.tensor(seq, dtype=torch.long).to(device) for seq in encode_texts]
# NOTE: Padding is NOT used due to variable-length prompts causing model to learn [PAD] tokens.
# During mixed task training (A+B), Task B prompts are much longer than Task A, causing heavy
# padding of Task A prompts. The model then learns to generate [PAD] as a valid output token.
# [Wei: the above is the comment from copilot. I guess technically it is not learning to generate [PAD], it is just that
# with [PAD] in the prompts, the model never learns how to generate proper output with [PAD] input, causing it to generate
# wrong outputs.]
# Instead, we process prompts individually without padding to match training distribution.
# Commented code below shows the original padding approach:
#
# encode_texts = pad_sequence(
# [torch.tensor(seq, dtype=torch.long) for seq in encode_texts],
# batch_first=True,
# padding_value=0
# ).to(device)
from tqdm import tqdm
import random
batch_size = args.batch_size
# Add temperature suffix when temperature is not default (1.0)
temp_suffix = f'_t{temperature}' if temperature != 1.0 else ''
# Modify filename for partial mode
if args.partial:
pred_filename = (
f'pred_{typedata}_{tasks_tag}_{ckpt_iter}_{run_test_label}{temp_suffix}_partial.txt'
if multitasks else f'pred_{typedata}_{ckpt_iter}_{num_of_paths}{temp_suffix}_partial.txt'
)
else:
pred_filename = (
f'pred_{typedata}_{tasks_tag}_{ckpt_iter}_{run_test_label}{temp_suffix}.txt'
if multitasks else f'pred_{typedata}_{ckpt_iter}_{num_of_paths}{temp_suffix}.txt'
)
with open(out_dir + pred_filename, 'w') as f:
pass
wrong = 0
total = 0
partial_prefix_lengths = [] # Track prefix lengths for partial mode statistics
j = 1
for i in tqdm(range(args.num_iters), desc="Testing batches"):
ix = torch.randint(len(encode_texts), (batch_size,))
if args.partial:
# For partial mode, create random prefixes from full lines
x_list = []
partial_texts = [] # Store the partial prefix text for this batch
prefix_dir_counts = [] # Track number of direction tokens in each prefix
for idx in ix:
full_line = full_lines[idx]
# Split into prompt and path parts
if ':' in full_line:
prompt_part = full_line.split(':')[0] + ':' # "A source target:" or "source target:"
path_part = full_line.split(':')[1].strip() # directions after ":"
path_tokens = path_part.split()
if len(path_tokens) > 0:
# Random prefix length: at least 1 token, up to all but 1 token
max_prefix_len = max(1, len(path_tokens) - 1)
prefix_len = random.randint(1, max_prefix_len)
partial_prefix_lengths.append(prefix_len)
prefix_dir_counts.append(prefix_len) # Track prefix direction count
# Create partial prefix: prompt + some path tokens
partial_prefix = prompt_part + ' ' + ' '.join(path_tokens[:prefix_len])
partial_texts.append(partial_prefix)
x_list.append(torch.tensor(encode(partial_prefix), dtype=torch.long).to(device).unsqueeze(0))
else:
# No path tokens, use original prompt
partial_texts.append(prompt_part)
prefix_dir_counts.append(0)
x_list.append(encode_texts[idx].unsqueeze(0))
else:
# No colon, use original encoding
partial_texts.append(texts[idx])
prefix_dir_counts.append(0)
x_list.append(encode_texts[idx].unsqueeze(0))
else:
x_list = [encode_texts[idx].unsqueeze(0) for idx in ix] # Convert each to batch size 1
x_gt = ground_truth[ix]
with torch.no_grad():
y_pred_list = []
confidence_list = [] # Store confidence scores for each sample
top3_tokens_list = [] # Store top-3 token indices for each sample
top3_probs_list = [] # Store top-3 probabilities for each sample
# Group samples in x_list by prompt length so each group can be
# generated in a single batched forward (huge speedup, especially
# with NLS where per-step CUDA-launch overhead dominates).
# Preserve original order via idx tracking.
from collections import defaultdict
groups = defaultdict(list) # prompt_len -> list of (orig_idx, x_tensor)
for orig_i, x in enumerate(x_list):
groups[x.size(1)].append((orig_i, x))
# Pre-allocate result slots so we can write back in original order.
y_pred_list = [None] * len(x_list)
confidence_list = [None] * len(x_list)
top3_tokens_list = [None] * len(x_list)
top3_probs_list = [None] * len(x_list)
for prompt_len, items in groups.items():
xb = torch.cat([x for _, x in items], dim=0) # (B, prompt_len)
yb, conf_b, t3t_b, t3p_b = model.generate(
xb, max_new_tokens, temperature=temperature, top_k=top_k, return_confidence=True)
B = xb.size(0)
if B == 1:
# generate() returns flat per-time lists for B=1.
orig_i = items[0][0]
y_pred_list[orig_i] = decode(yb[0].tolist()).split('\n')[0]
confidence_list[orig_i] = conf_b
top3_tokens_list[orig_i] = t3t_b
top3_probs_list[orig_i] = t3p_b
else:
for k, (orig_i, _) in enumerate(items):
y_pred_list[orig_i] = decode(yb[k].tolist()).split('\n')[0]
confidence_list[orig_i] = conf_b[k]
top3_tokens_list[orig_i] = t3t_b[k]
top3_probs_list[orig_i] = t3p_b[k]
y_pred = y_pred_list
batch_wrong = 0
with open(out_dir + pred_filename, 'a') as f:
for t, item in enumerate(y_pred):
total += 1
tokens = item.split()
if no_task_tag:
original_prompt = texts[ix[t]].split() if not args.partial else partial_texts[t].split()
if ':' in item:
colon_idx_char = item.index(':')
answer_part = item[colon_idx_char + 1:].strip()
answer_tokens = answer_part.split()
if len(original_prompt) >= 2 and original_prompt[0].isdigit() and original_prompt[1].isdigit():
if len(answer_tokens) >= 2 and answer_tokens[1] in graph_node_labels:
task_id = 'E'
elif any(tok in ['L', 'R', 'F', 'T'] for tok in answer_tokens):
task_id = 'C'
else:
task_id = 'A'
elif len(original_prompt) >= 2 and original_prompt[0].isdigit():
has_directions_in_prompt = any(tok in ['N', 'S', 'E', 'W'] for tok in original_prompt[1:])
task_id = 'B' if (has_directions_in_prompt and len(answer_tokens) == 5) else None
elif len(original_prompt) >= 2 and original_prompt[0].isdigit() and \
original_prompt[1] in graph_node_labels:
task_id = 'D'
elif len(original_prompt) >= 2 and original_prompt[0] in graph_node_labels:
task_id = 'F'
elif len(original_prompt) >= 4 and all(token.isdigit() for token in original_prompt[:4]):
task_id = 'G'
else:
task_id = None
else:
task_id = None
else:
task_id = tokens[0] if len(tokens) > 0 and tokens[0] in TASK_TOKENS else None
prompt_tokens = texts[ix[t]].split() if not args.partial else partial_texts[t].split()
pdc = prefix_dir_counts[t] if args.partial else 0
output_task_label = f"({task_id}) " if (no_task_tag and task_id) else ""
if task_id == 'A' or (task_id is None and not multitasks):
symbol = check_correctness_taskA(maze_graph, item, n, prefix_dir_count=pdc)
elif task_id == 'B':
symbol = check_correctness_taskB(maze_graph_B, item, n, prompt_tokens=prompt_tokens)
elif task_id == 'C':
symbol = check_correctness_taskC(maze_graph, item, n, cl_mode=args.CL)
elif task_id == 'D':
symbol = check_correctness_taskD(maze_graph, item, n, prompt_tokens=prompt_tokens)
elif task_id == 'E':
symbol = check_correctness_taskE(maze_graph, item, n, prompt_tokens=prompt_tokens)
elif task_id == 'F':
symbol = check_correctness_taskF(maze_graph, item, n, prompt_tokens=prompt_tokens)
elif task_id == 'G':
symbol = check_correctness_taskG(maze_graph, item, n, prompt_tokens=prompt_tokens)
elif task_id == 'H':
symbol = check_correctness_taskH(maze_graph, item, n, prompt_tokens=prompt_tokens)
elif task_id == 'I':
symbol = check_correctness_taskI(maze_graph, item, n, prompt_tokens=prompt_tokens)
else:
symbol = check_maze_path(maze_graph, item, n, prefix_dir_count=pdc)
if (symbol != ""):
wrong += 1
batch_wrong += 1
error_confidence_info = ""
if symbol != "" and t < len(confidence_list):
error_pos = None
# 1. Try to find step number from error message (Illegal direction/label)
step_match = re.search(r'(?:step|suffix_step|run)\s+(\d+)', symbol)
if step_match:
error_pos = int(step_match.group(1))
# 2. Handle "incorrect target node" or "syntax error"
elif symbol == 'incorrect target node' or 'syntax error' in symbol:
gen_tokens = item.split()
if ':' in gen_tokens:
# Error is usually at the end of the generated sequence (the \n or the token after colon)
error_pos = len(gen_tokens) - gen_tokens.index(':') - 1
# 3. Handle Task B/F specific label errors
elif 'incorrect' in symbol and 'label' in symbol:
gen_tokens = item.split()
if ':' in gen_tokens:
# For label tasks, errors often happen at the first or specific token of the answer
error_pos = 0 # Default to the first token of the answer
# If we found a position, extract confidence data
if error_pos is not None and error_pos < len(confidence_list[t]):
error_conf = confidence_list[t][error_pos]
top3_tok = top3_tokens_list[t][error_pos]
top3_prob = top3_probs_list[t][error_pos]
top3_strs = [itos[tok] if tok < len(itos) else f"<{tok}>" for tok in top3_tok]
# Determine mistake type based on gap between top1 and the chosen token
if (top3_prob[0] - error_conf) > 0.4:
mistake_type = "LOW-CONF"
else:
mistake_type = "HIGH-CONF"
error_confidence_info = f" [{mistake_type}: conf={error_conf:.4f}, top3={top3_strs}, probs=[{top3_prob[0]:.4f},{top3_prob[1]:.4f},{top3_prob[2]:.4f}]]"
if args.partial:
gen_tokens = item.split()
if ':' in gen_tokens:
colon_idx = gen_tokens.index(':')
marker_pos = colon_idx + 1 + pdc
if marker_pos <= len(gen_tokens):
gen_tokens.insert(marker_pos, '>')
marked_item = ' '.join(gen_tokens)
else:
marked_item = item
f.write(output_task_label + marked_item + " " + symbol + error_confidence_info + '\n')
else:
f.write(output_task_label + item + " " + symbol + error_confidence_info + '\n')
# Calculate and display accuracy for this batch
batch_correct = batch_size - batch_wrong
batch_accuracy = 100.0 * batch_correct / batch_size
# Update tqdm description with real-time accuracy
print(f"Batch {j}/{args.num_iters}: Accuracy = {batch_accuracy:.2f}% ({batch_correct}/{batch_size})")
j = j + 1
# Update overall accuracy in tqdm progress bar
overall_accuracy = 100.0 * (total - wrong) / total if total > 0 else 0.0
# Final accuracy calculation
overall_accuracy = 100.0 * (total - wrong) / total if total > 0 else 0.0
print(f"\nTotal predictions: {total}")
print(f"Correct predictions: {total - wrong}")
print(f"Wrong predictions: {wrong}")
print(f"Overall accuracy: {overall_accuracy:.2f}%")
# Print partial mode statistics
if args.partial and partial_prefix_lengths:
avg_prefix_len = sum(partial_prefix_lengths) / len(partial_prefix_lengths)
print(f"\nPartial prefix mode statistics:")
print(f" Average prefix length: {avg_prefix_len:.2f} tokens")
print(f" Min prefix length: {min(partial_prefix_lengths)}")
print(f" Max prefix length: {max(partial_prefix_lengths)}")
# Automatically run analyze_maze.py with the same arguments
import subprocess
import sys
print("\n" + "=" * 60)
print("Running analyze_maze.py...")
print("=" * 60)
analyze_cmd = [
sys.executable, 'analyze_maze.py',
'--ckpt_iter', str(args.ckpt_iter),
'--model', args.model,
'--config', config,
'--dataset', dataset,
'--num_nodes', str(args.num_nodes),
'--num_of_paths', str(args.num_of_paths),
'--num_train_dataset', str(num_train_dataset),
'--num_test_dataset', str(num_test_dataset),
'--tasks', tasks_str,
'--batch_size', str(args.batch_size),
'--num_iters', str(args.num_iters),
'--path_type', args.path_type,
]
if args.multitasks:
analyze_cmd.append('--multitasks')
else:
analyze_cmd.append('--no-multitasks')
if args.CL:
analyze_cmd.append('--CL')
if args.partial:
analyze_cmd.append('--partial')
if args.no_task_tag:
analyze_cmd.append('--no_task_tag')
if args.PostGRU:
analyze_cmd.append('--PostGRU')
if args.NLS:
analyze_cmd.append('--NLS')
if args.DyadicAttn:
analyze_cmd.append('--DyadicAttn')
if args.DyadicHybrid:
analyze_cmd.append('--DyadicHybrid')
if args.temperature != 1.0:
analyze_cmd.extend(['--temperature', str(args.temperature)])
subprocess.run(analyze_cmd) |