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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
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
import os
import re
import math
import random
import pickle
import argparse
from collections import defaultdict
from tqdm import tqdm

import torch
import numpy as np
import networkx as nx

from model.transformer import GPTConfig, GPT
from model.transformer_rope import GPTRoPEConfig, GPTRoPE
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
from model.transformer_nextlat import TransformerNextLatConfig, TransformerNextLat
from cli_utils import (
    parse_count,
    format_count,
    parse_task_distribution,
    sample_task,
    directions_to_turns,
)


def build_model_from_checkpoint(checkpoint, model_type, device, local=False):
    """Reconstruct the right architecture from a checkpoint, honoring its stored model_type."""
    ckpt_model_type = checkpoint.get('model_type', model_type)
    model_args = checkpoint['model_args']
    if ckpt_model_type == 'mamba':
        conf = MambaConfig(**model_args)
        model = Mamba(conf)
    elif ckpt_model_type == 'mamba2':
        conf = Mamba2Config(**model_args)
        model = Mamba2(conf)
    elif ckpt_model_type == 'gated-deltanet':
        conf = GatedDeltaNetConfig(**model_args)
        model = GatedDeltaNet(conf)
    elif ckpt_model_type == 'gru':
        conf = GRUConfig(**model_args)
        model = GRU(conf)
    elif ckpt_model_type == 'transformer-nextlat':
        conf = TransformerNextLatConfig(**model_args)
        model = TransformerNextLat(conf)
    elif ckpt_model_type == 'transformer-rope':
        if local and 'use_flash' in model_args:
            model_args['use_flash'] = False
        conf = GPTRoPEConfig(**model_args)
        model = GPTRoPE(conf)
    else:
        if local and 'use_flash' in model_args:
            model_args['use_flash'] = False
        conf = GPTConfig(**model_args)
        model = GPT(conf)
    state_dict = checkpoint['model']
    model.load_state_dict({k.replace('_orig_mod.', ''): v for k, v in state_dict.items()})
    model.eval()
    model.to(device)
    return model, conf


def check_maze_path(G, gen_str, n, num_nodes, no_task_tag=False):
    """

    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 (optional, for multi-task support)

    Directions: N (north/up), S (south/down), E (east/right), W (west/left)



    Returns:

        '' if path is correct

        error message otherwise

    """
    tokens = [t for t in gen_str.split() if t != ':']

    # Check if first token is a task ID (only if no_task_tag is False)
    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
        if next_node is None or next_node < 0 or next_node >= num_nodes:
            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)):
            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, num_nodes, cl_mode=False, no_task_tag=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).

    """
    TASK_TOKENS = {'A', 'B', 'C', 'D', 'E', 'F', 'G'}
    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 = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'}

    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 ''


def check_task_e_path(G, gen_str, n, num_nodes, no_task_tag=False):
    """Validate a Task E path (pathfinding with label observations).



    Validation logic:

    - Parse direction-label pairs (e.g., N a, N b, E c)

    - Process each pair sequentially:

      "Move in direction D until a node with label L is found."

      - Any nodes encountered with labels != L are skipped over.

      - Once L is found, the segment for this pair ends at that node.

    - If boundary/no-edge is hit before finding L, it's an error.

    - After all pairs, must be at target.

    """
    TASK_TOKENS = {'A', 'B', 'C', 'D', 'E', 'F', 'G'}
    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'

    # Parse direction-label pairs
    action_tokens = tokens[2 + task_offset:]

    if len(action_tokens) % 2 != 0:
        return 'syntax error'

    current_node = source
    total_step = 0

    # Process pairs sequentially
    for i in range(0, len(action_tokens), 2):
        direction = action_tokens[i]
        target_label = action_tokens[i + 1]

        if direction not in ['N', 'S', 'E', 'W']:
            return 'syntax error'

        if target_label not in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']:
            return 'syntax error'

        # Simulate movement for this pair
        found = False
        # Cap max steps per segment to prevent infinite loops in cyclic graphs
        steps_in_segment = 0
        max_steps = num_nodes + 5

        while not found and steps_in_segment < max_steps:
            # Calculate next node
            if direction == 'N':
                next_node = current_node - n
            elif direction == 'S':
                next_node = current_node + n
            elif direction == 'E':
                next_node = current_node + 1
            elif direction == 'W':
                next_node = current_node - 1

            # Check bounds
            if next_node < 0 or next_node >= num_nodes:
                return f'step {total_step} node {current_node} direction {direction} is illegal (boundary)'

            # Check edge
            if not G.has_edge(str(current_node), str(next_node)):
                return f'step {total_step} node {current_node} direction {direction} is illegal (no edge)'

            # Move
            current_node = next_node
            total_step += 1
            steps_in_segment += 1

            # Check label
            node_label = G.nodes[str(current_node)]['label']
            if node_label == target_label:
                found = True

        if not found:
            return f'step {total_step} could not find label {target_label} in direction {direction}'

    # Check if we reached the target
    if current_node != target:
        return 'incorrect target node'

    return ''


# ---- Task H (relative clockwise-index encoding) helpers ----
_TASK_H_CLOCKWISE_SCAN = {
    'N': ['N', 'E', 'S', 'W'],
    'E': ['E', 'S', 'W', 'N'],
    'S': ['S', 'W', 'N', 'E'],
    'W': ['W', 'N', 'E', 'S'],
}


def _task_h_feasible_dirs(G, node, facing, n, num_nodes):
    """Feasible directions at `node`, scanned clockwise from `facing` (Task H)."""
    delta = {'N': -n, 'S': n, 'E': 1, 'W': -1}
    feasible = []
    for d in _TASK_H_CLOCKWISE_SCAN[facing]:
        neighbor = node + delta[d]
        if 0 <= neighbor < num_nodes and G.has_edge(str(node), str(neighbor)):
            feasible.append(d)
    return feasible


def encode_task_h_indices(G, source, path_dirs, n, num_nodes, start_facing='E'):
    """Convert an absolute-direction path into Task H clockwise-index tokens.



    Returns (tokens, final_facing); (None, None) if a direction is infeasible.

    """
    delta = {'N': -n, 'S': n, 'E': 1, 'W': -1}
    facing = start_facing
    current = int(source)
    tokens = []
    for d in path_dirs:
        feasible = _task_h_feasible_dirs(G, current, facing, n, num_nodes)
        if d not in feasible:
            return None, None
        tokens.append(str(feasible.index(d) + 1))
        current = current + delta[d]
        facing = d
    return tokens, facing


def check_task_h_path(G, gen_str, n, num_nodes, no_task_tag=False):
    """Validate a Task H path (relative clockwise-index encoding).



    The agent starts at source facing East. Each token is the 1-based index of

    the chosen direction among feasible edges, enumerated clockwise starting

    from the current facing. After moving, facing updates to the chosen direction.

    """
    TASK_TOKENS = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'}
    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:]
    delta = {'N': -n, 'S': n, 'E': 1, 'W': -1}
    facing = 'E'
    current_node = source

    for step, tok in enumerate(actions):
        if tok not in ['1', '2', '3', '4']:
            return 'syntax error'
        idx = int(tok)
        feasible = _task_h_feasible_dirs(G, current_node, facing, n, num_nodes)
        if idx < 1 or idx > len(feasible):
            return f'step {step} node {current_node} index {tok} is illegal'
        d = feasible[idx - 1]
        current_node = current_node + delta[d]
        facing = d

    if current_node != target:
        return 'incorrect target node'

    return ''


# ---- Task I (absolute clockwise-index encoding, FIXED North reference) helpers ----
# Like Task H but feasible edges are always scanned clockwise from a fixed
# North reference (N->E->S->W) regardless of the last move, so there is NO
# facing state: the walker's state is the current node alone.
_TASK_I_FIXED_SCAN = ['N', 'E', 'S', 'W']


def _task_i_feasible_dirs(G, node, n, num_nodes):
    """Feasible directions at `node`, scanned clockwise from fixed North (Task I)."""
    delta = {'N': -n, 'S': n, 'E': 1, 'W': -1}
    feasible = []
    for d in _TASK_I_FIXED_SCAN:
        neighbor = node + delta[d]
        if 0 <= neighbor < num_nodes and G.has_edge(str(node), str(neighbor)):
            feasible.append(d)
    return feasible


def encode_task_i_indices(G, source, path_dirs, n, num_nodes):
    """Convert an absolute-direction path into Task I fixed-North clockwise-index

    tokens. Returns tokens, or None if a direction is infeasible. No facing state."""
    delta = {'N': -n, 'S': n, 'E': 1, 'W': -1}
    current = int(source)
    tokens = []
    for d in path_dirs:
        feasible = _task_i_feasible_dirs(G, current, n, num_nodes)
        if d not in feasible:
            return None
        tokens.append(str(feasible.index(d) + 1))
        current = current + delta[d]
    return tokens


def check_task_i_path(G, gen_str, n, num_nodes, no_task_tag=False):
    """Validate a Task I path (absolute clockwise-index encoding, fixed North).



    The agent starts at source. Each token is the 1-based index of the chosen

    direction among feasible edges, enumerated clockwise from a fixed North

    reference (N->E->S->W). There is no facing state.

    """
    TASK_TOKENS = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'}
    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:]
    delta = {'N': -n, 'S': n, 'E': 1, 'W': -1}
    current_node = source

    for step, tok in enumerate(actions):
        if tok not in ['1', '2', '3', '4']:
            return 'syntax error'
        idx = int(tok)
        feasible = _task_i_feasible_dirs(G, current_node, n, num_nodes)
        if idx < 1 or idx > len(feasible):
            return f'step {step} node {current_node} index {tok} is illegal'
        d = feasible[idx - 1]
        current_node = current_node + delta[d]

    if current_node != target:
        return 'incorrect target node'

    return ''


def validate_suffix(G, prefix, suffix, n, num_nodes, task_id, cl_mode=False, no_task_tag=False):
    """Validate if concatenating prefix and suffix forms a valid path.



    Args:

        G: The maze graph

        prefix: List of prefix tokens (e.g., ['A', '0', '5', 'E', 'S'])

        suffix: List of suffix tokens (e.g., ['E', 'S'])

        n: Grid size

        num_nodes: Total number of nodes

        task_id: Task identifier ('A', 'C', or 'E')

        cl_mode: Whether CL mode is enabled for Task C

        no_task_tag: Whether data does not contain task identifiers



    Returns:

        '' if valid, error message otherwise

    """
    # Concatenate prefix and suffix into a full path string
    full_path = ' '.join(list(prefix) + list(suffix))

    # Calculate prefix direction count (steps before suffix)
    task_offset = 0 if no_task_tag else (1 if task_id in ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'] else 0)
    has_colon = 1 if ':' in prefix else 0

    if task_id == 'E':
        # For Task E, count direction-label pairs
        # Prefix format: [task_id, source, target, ':', dir1, label1, dir2, label2, ...]
        # or without task tag: [source, target, ':', dir1, label1, dir2, label2, ...]
        prefix_pairs = len(prefix) - 2 - task_offset - has_colon
        if prefix_pairs % 2 != 0:
            return 'syntax error'
        prefix_direction_count = prefix_pairs // 2
    else:
        prefix_direction_count = len(prefix) - 2 - task_offset - has_colon

    if task_id == 'A':
        error = check_maze_path(G, full_path, n, num_nodes, no_task_tag=no_task_tag)
    elif task_id == 'C':
        error = check_turn_path(G, full_path, n, num_nodes, cl_mode=cl_mode, no_task_tag=no_task_tag)
    elif task_id == 'E':
        error = check_task_e_path(G, full_path, n, num_nodes, no_task_tag=no_task_tag)
    elif task_id == 'H':
        error = check_task_h_path(G, full_path, n, num_nodes, no_task_tag=no_task_tag)
    elif task_id == 'I':
        error = check_task_i_path(G, full_path, n, num_nodes, no_task_tag=no_task_tag)
    else:
        # Fallback to maze path check
        error = check_maze_path(G, full_path, n, num_nodes, no_task_tag=no_task_tag)

    # Adjust step numbers to be relative to suffix (for detailed diagnostics)
    if 'is illegal' in error:
        match = re.search(r'step (\d+)', error)
        if match:
            full_step = int(match.group(1))
            suffix_step = full_step - prefix_direction_count
            # Replace the step number with suffix-relative step
            error = re.sub(r'step \d+', f'step {suffix_step}', error)

    return error


def detect_task_id_support(stoi, no_task_tag=False):
    """Detect if the model vocabulary includes task ID tokens (A, B, C, D, E, F, G)."""
    if no_task_tag:
        return False
    task_tokens = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
    return all(token in stoi for token in task_tokens)


def create_reverse_maps(valid_turns, node_and_direction_to_neighbor):
    """Create reverse direction maps for backward random walk sampling."""
    valid_previous_turns = defaultdict(list)
    node_and_previous_direction_to_neighbors = defaultdict(list)
    for node, moves in valid_turns.items():
        for move in moves:
            next_move = node_and_direction_to_neighbor[(node, move)]
            valid_previous_turns[next_move].append(move)
            node_and_previous_direction_to_neighbors[(next_move, move)].append(node)
    return valid_previous_turns, node_and_previous_direction_to_neighbors


def sample_length_k_prefix_from_state(current_state, end_state, k, valid_previous_turns,

                                      node_and_previous_direction_to_neighbors, use_task_id=False, task_id='A',

                                      allow_cycles=False, no_task_tag=False):
    """Sample a reverse random walk prefix up to length k ending at current_state.



    Args:

        current_state: Current node state

        end_state: Target end node

        k: Maximum length of the prefix

        valid_previous_turns: Valid previous turns mapping

        node_and_previous_direction_to_neighbors: Node and direction to neighbors mapping

        use_task_id: Whether to prepend task ID to the prefix

        task_id: Task identifier to prepend (default: 'A')

        allow_cycles: If False (default), path is acyclic. If True, path can contain cycles.

        no_task_tag: Whether data does not contain task identifiers

    """
    state = current_state
    direction_list = []
    visited = {state}

    for _ in range(k):
        # Collect candidate (direction, prev_state) pairs
        candidates = []
        for direction in valid_previous_turns[state]:
            for prev_state in node_and_previous_direction_to_neighbors[(state, direction)]:
                if allow_cycles or prev_state not in visited:
                    candidates.append((direction, prev_state))

        # If no candidates exist, stop early and use the partial walk
        if not candidates:
            break

        direction, prev_state = random.choice(candidates)
        direction_list.append(direction)
        state = prev_state
        visited.add(state)

    # Append end_node and current state, then reverse to get forward order
    direction_list.append(str(end_state))
    direction_list.append(str(state))
    direction_list = direction_list[::-1]

    # Prepend task ID if multi-task support is enabled and no_task_tag is False
    if use_task_id and not no_task_tag:
        direction_list = [task_id] + direction_list

    return direction_list


def encode(s, stoi):
    """Encode a string (space-separated tokens) into token IDs."""
    ss = s.split(" ")
    encoded_string = [stoi[ch] for ch in ss]
    return encoded_string


def decode(l, itos):
    """Decode token IDs back to space-separated string."""
    dec = ""
    for i in l:
        dec = dec + itos[i] + " "
    return dec[:-1]


def pick_first_existing(candidates):
    for path in candidates:
        if os.path.exists(path):
            return path
    return candidates[0]


def get_conditional_probability_of_suffixes_after_prefix(prefix, suffixes, model, stoi, itos, device, block_size,

                                                         batch_size=32):
    """

    Compute the conditional probability of each suffix given a prefix.

    Returns a list of probability arrays for each suffix.

    """
    prefix_len = len(prefix)
    max_suffix_len = max(len(suffix) for suffix in suffixes)

    input_ids = []
    for suffix in suffixes:
        full_sequence = prefix + suffix
        encoded_seq = encode(" ".join(full_sequence), stoi)
        input_ids.append(encoded_seq)

    # Pad input_ids to the same length
    padded_input_ids = []
    attention_masks = []
    for ids in input_ids:
        # Truncate or pad to block_size
        if len(ids) > block_size:
            ids = ids[:block_size]
        padding_length = block_size - len(ids)
        padded_ids = ids + [stoi.get('<pad>', 0)] * padding_length
        attention_mask = [1] * len(ids) + [0] * padding_length
        padded_input_ids.append(padded_ids)
        attention_masks.append(attention_mask)

    padded_input_ids = torch.tensor(padded_input_ids, dtype=torch.long, device=device)
    attention_masks = torch.tensor(attention_masks, dtype=torch.long, device=device)

    # Get logits from model
    num_batches = (len(padded_input_ids) - 1) // batch_size + 1
    logits_list = []
    for i in range(num_batches):
        start_idx = i * batch_size
        end_idx = start_idx + batch_size
        with torch.no_grad():
            # Use model forward with targets to get full-sequence logits (no attention mask support)
            logits, _ = model(
                padded_input_ids[start_idx:end_idx],
                targets=padded_input_ids[start_idx:end_idx]
            )
        logits_list.append(logits)

    logits = torch.cat(logits_list, dim=0)
    probs = torch.softmax(logits, dim=-1)

    # Get probabilities of next tokens in the suffix part
    # For each position in the suffix, gather the probability of the actual next token
    next_token_probs = torch.gather(probs[:, :-1], dim=-1, index=padded_input_ids[:, 1:].unsqueeze(-1))[:, :, 0]

    # Extract suffix probabilities (skip the prefix tokens)
    num_suffixes = len(suffixes)
    suffix_probs = []
    for j in range(num_suffixes):
        suffix_len = len(suffixes[j])
        # Probabilities from position (prefix_len-1) to (prefix_len + suffix_len - 1)
        suffix_prob = next_token_probs[j, (prefix_len - 1):(prefix_len + suffix_len - 1)].cpu().numpy()
        suffix_probs.append(suffix_prob)

    return suffix_probs


def parse_args():
    parser = argparse.ArgumentParser(description='Compression test for maze paths')
    parser.add_argument('--ckpt_iter', type=int, default=10000, help='Checkpoint iteration')
    parser.add_argument('--config', type=str, default='6_6_384', help='Model config')
    parser.add_argument('--model', type=str, default='transformer',
                        choices=['transformer', 'transformer-rope', 'transformer-nextlat', 'mamba', 'mamba2', 'gru', 'gated-deltanet'],
                        help='Model architecture; selects out/<model>/ and how the checkpoint is built.')
    parser.add_argument('--num_nodes', type=int, default=100, help='Number of nodes')
    parser.add_argument('--num_of_paths', type=int, default=20, help='Number of paths')
    parser.add_argument('--device', type=str, default='cuda:0', help='Device to use')
    parser.add_argument('--num_suffix_samples', type=int, default=30, help='Number of suffix samples')
    parser.add_argument('--epsilon', type=float, default=0.01, help='Probability threshold')
    parser.add_argument('--temperature', type=float, default=1.0, help='Sampling temperature for suffix generation (default: 1.0)')
    parser.add_argument('--num_trials', type=int, default=100, help='Number of trials')
    parser.add_argument('--use_untrained_model', action='store_true', help='Use untrained model')
    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='C1',
                        help='Task specification for file naming (e.g., A1, A1B1, A3B2, A1D1F1). Default: A1')
    parser.add_argument('--cmpr_tasks', type=str, default=None,
                        help='Task specification for compression prefix generation (e.g., A1, A1C1). If not specified, uses --tasks value. Syntax same as --tasks.')
    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('--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). "shortest" is not implemented yet.')
    # New argument for no task tag mode
    parser.add_argument('--no_task_tag', action='store_true', default=False,
                        help='Data does not contain task identifiers (A, B, C, etc.). When enabled, model assumes data starts directly with node numbers/labels without task tags.')
    return parser.parse_args()


def main():
    args = parse_args()
    dataset = 'maze'
    ckpt_iter = args.ckpt_iter
    device = args.device
    num_nodes = args.num_nodes
    num_of_paths = args.num_of_paths
    config = args.config
    num_suffix_samples = args.num_suffix_samples
    epsilon = args.epsilon
    temperature = args.temperature
    num_trials = args.num_trials
    multitasks = args.multitasks
    num_train_dataset = args.num_train_dataset
    num_test_dataset = args.num_test_dataset
    train_label = format_count(num_train_dataset)
    tasks_str = args.tasks
    tasks_tag = f"{tasks_str}_CL" if args.CL else tasks_str
    cl_mode = args.CL
    no_task_tag = args.no_task_tag  # Get the no_task_tag flag

    # 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}"
    # Add _NT_ tag to tasks_tag when no_task_tag is enabled
    if args.no_task_tag:
        tasks_tag = f"{tasks_tag}_NT"
    # Graph tag includes path type to match generated graph files
    graph_tag = f"{tasks_str}_CL" if cl_mode else tasks_str
    graph_tag = f"{graph_tag}_{path_type_tag}"
    # Add _NT_ tag to graph_tag when no_task_tag is enabled
    if args.no_task_tag:
        graph_tag = f"{graph_tag}_NT"

    # Load meta
    data_path = f'data/{dataset}/{num_nodes}'
    meta_path = pick_first_existing([
        f'{data_path}/meta_{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']
    block_size = meta['block_size']

    # Override no_task_tag from metadata if available
    if 'no_task_tag' in meta:
        no_task_tag = meta['no_task_tag']
        print(f"Overriding no_task_tag from metadata: {no_task_tag}")

    # Detect if model supports task IDs (considering no_task_tag flag)
    use_task_id = detect_task_id_support(stoi, no_task_tag)
    # Use cmpr_tasks for prefix generation if specified, otherwise fall back to tasks
    cmpr_tasks_str = args.cmpr_tasks if args.cmpr_tasks is not None else tasks_str
    task_weights = parse_task_distribution(cmpr_tasks_str, default_task='A')
    task_id = 'A'
    if use_task_id:
        print(f"Task ID support detected. Sampling compression prefix tasks using weights: {task_weights}")
        if args.cmpr_tasks is not None:
            print(f"  (cmpr_tasks={cmpr_tasks_str} overrides tasks={tasks_str} for prefix generation)")
    else:
        print(f"No task ID support detected. No task tag mode: {'Enabled' if no_task_tag else 'Disabled'}")

    # Load model checkpoint
    nt_suffix = '_NT' if no_task_tag else ''
    model_type = args.model
    out_dir = f'out/{model_type.replace("-", "_")}/{dataset}_{config}_{num_nodes}{nt_suffix}/'
    # transformer-nextlat checkpoints carry an extra _NL suffix on the task tag.
    ckpt_tag = f"{tasks_tag}_NL" if model_type == 'transformer-nextlat' else tasks_tag
    if multitasks:
        candidate_ckpts = [
            os.path.join(out_dir, f'{ckpt_iter}_ckpt_maze_{ckpt_tag}_{train_label}.pt'),
            os.path.join(out_dir, f'{ckpt_iter}_ckpt_maze_{ckpt_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')

    print(f"Loading model from {ckpt_path}...")
    checkpoint = torch.load(ckpt_path, map_location=device, weights_only=False)
    model, _ = build_model_from_checkpoint(checkpoint, model_type, device, local=args.local)

    # Load maze graph
    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'
    print(f"Loading maze graph from {maze_graph_path}...")
    G = nx.read_graphml(maze_graph_path)
    n = int(math.sqrt(num_nodes))

    # Build valid_turns and node_and_direction_to_neighbor from graph
    print("Building navigation maps from graph...")
    valid_turns = defaultdict(list)
    node_and_direction_to_neighbor = {}

    for node_str in G.nodes():
        node = int(node_str)
        for neighbor_str in G.neighbors(node_str):
            neighbor = int(neighbor_str)
            # Determine direction based on node positions in grid
            row_diff = neighbor // n - node // n
            col_diff = neighbor % n - node % n

            if row_diff == -1 and col_diff == 0:
                direction = 'N'
            elif row_diff == 1 and col_diff == 0:
                direction = 'S'
            elif row_diff == 0 and col_diff == 1:
                direction = 'E'
            elif row_diff == 0 and col_diff == -1:
                direction = 'W'
            else:
                # Non-standard edge, skip or handle
                continue

            valid_turns[node].append(direction)
            node_and_direction_to_neighbor[(node, direction)] = neighbor

    # Add end sentinels
    all_nodes = list(valid_turns.keys())
    for node in all_nodes:
        node_and_direction_to_neighbor[(node, 'end')] = 'end'
    node_and_direction_to_neighbor[('end', 'end')] = 'end'

    # Create reverse maps
    valid_previous_turns, node_and_previous_direction_to_neighbors = create_reverse_maps(
        valid_turns, node_and_direction_to_neighbor
    )

    # Generate all_pairs (source, target) from nodes with valid moves
    all_pairs = []
    for start in all_nodes:
        for end in all_nodes:
            if start != end:
                all_pairs.append((start, end))

    print(f"Found {len(all_nodes)} nodes with valid moves")
    print(f"Generated {len(all_pairs)} source-target pairs")

    # Helpers to build task-specific prefixes
    def build_task_prefix(start_node, end_node, prefix_len, task_id_local):
        """Build a task-specific prefix.



        Returns:

            For Task A: (prefix_tokens, valid_dirs, None, None)

            For Task C: (prefix_tokens, valid_dirs, final_orientation, None)

            For Task E: (prefix_tokens, valid_dir_label_pairs, None, None)

            None if prefix generation fails

        """
        raw_prefix = sample_length_k_prefix_from_state(
            start_node, end_node, prefix_len, valid_previous_turns,
            node_and_previous_direction_to_neighbors, use_task_id, task_id_local, allow_cycles=allow_cycles,
            no_task_tag=no_task_tag
        )
        if raw_prefix is None:
            return None

        if use_task_id and not no_task_tag:
            task_id_from_raw, start_tok, end_tok, *path_dirs = raw_prefix
        else:
            start_tok, end_tok, *path_dirs = raw_prefix

        final_orientation = None
        valid_dirs = None
        valid_dir_label_pairs = None

        if task_id_local == 'C':
            path_dirs = directions_to_turns(path_dirs)
            valid_dirs = {'L', 'R', 'F', 'T'}
            # Track orientation as we walk through the turns
            current = int(start_tok)
            orientation = 'E'
            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}

            # In CL mode, insert node labels after L/R turns
            if cl_mode:
                augmented_dirs = []
                for turn in path_dirs:
                    augmented_dirs.append(turn)
                    if turn in ['L', 'R']:
                        # Add label of current node (before moving)
                        label = G.nodes[str(current)]['label']
                        augmented_dirs.append(label)
                    # Update orientation and move
                    if turn == 'F':
                        next_orientation = orientation
                    elif turn == 'L':
                        next_orientation = left_of[orientation]
                    elif turn == 'R':
                        next_orientation = right_of[orientation]
                    else:  # 'T'
                        next_orientation = opposite_of[orientation]
                    current = current + delta[next_orientation]
                    orientation = next_orientation
                path_dirs = augmented_dirs
            else:
                # Still need to track final orientation even without CL mode
                for turn in path_dirs:
                    if turn == 'F':
                        next_orientation = orientation
                    elif turn == 'L':
                        next_orientation = left_of[orientation]
                    elif turn == 'R':
                        next_orientation = right_of[orientation]
                    else:  # 'T'
                        next_orientation = opposite_of[orientation]
                    current = current + delta[next_orientation]
                    orientation = next_orientation
            final_orientation = orientation

        elif task_id_local == 'E':
            # For Task E, we need to convert direction sequence to direction-label pairs
            # Follow the same compression rules as in create_multitask_maze.py
            # 1. Split only by turns (direction changes)
            # 2. For each straight segment, end_label is the label at the last node of this segment
            # 3. In that segment, keep ONLY positions whose label == end_label
            # 4. Emit (dir, end_label) once for each kept position

            # First, simulate the path to get labels
            current_node = int(start_tok)
            path_nodes = [current_node]

            for direction in path_dirs:
                if direction == 'N':
                    next_node = current_node - n
                elif direction == 'S':
                    next_node = current_node + n
                elif direction == 'E':
                    next_node = current_node + 1
                elif direction == 'W':
                    next_node = current_node - 1
                else:
                    return None  # Invalid direction

                path_nodes.append(next_node)
                current_node = next_node

            # Now apply Task E compression rules
            compressed_tokens = []
            run_dir = path_dirs[0] if path_dirs else ''
            run_labels = []

            for step_idx, direction in enumerate(path_dirs):
                node_id = path_nodes[step_idx + 1]
                label = G.nodes[str(node_id)]['label']

                # Direction changed => flush previous run, then start new
                if direction != run_dir:
                    if run_labels:
                        end_label = run_labels[-1]
                        cnt = sum(1 for x in run_labels if x == end_label)
                        for _ in range(cnt):
                            compressed_tokens.append(run_dir)
                            compressed_tokens.append(end_label)

                    # Start new run
                    run_dir = direction
                    run_labels = [label]
                else:
                    # Still same direction => accumulate
                    run_labels.append(label)

            # Flush last run
            if run_labels:
                end_label = run_labels[-1]
                cnt = sum(1 for x in run_labels if x == end_label)
                for _ in range(cnt):
                    compressed_tokens.append(run_dir)
                    compressed_tokens.append(end_label)

            path_dirs = compressed_tokens
            valid_dir_label_pairs = []
            for dir_token in ['N', 'S', 'E', 'W']:
                for label_token in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']:
                    valid_dir_label_pairs.append((dir_token, label_token))

        elif task_id_local == 'H':
            # Convert absolute directions to Task H clockwise-index tokens,
            # tracking the final orientation (facing) at the merge node.
            h_tokens, final_orientation = encode_task_h_indices(
                G, int(start_tok), path_dirs, n, num_nodes, start_facing='E')
            if h_tokens is None:
                return None
            path_dirs = h_tokens
            valid_dirs = {'1', '2', '3', '4'}

        elif task_id_local == 'I':
            # Convert absolute directions to Task I fixed-North index tokens.
            # No facing state, so final_orientation stays None.
            i_tokens = encode_task_i_indices(G, int(start_tok), path_dirs, n, num_nodes)
            if i_tokens is None:
                return None
            path_dirs = i_tokens
            valid_dirs = {'1', '2', '3', '4'}

        else:
            # Task A or other direction-based tasks
            valid_dirs = {'N', 'S', 'E', 'W'}

        if use_task_id and not no_task_tag:
            prefix_tokens = [str(task_id_from_raw), str(start_tok), str(end_tok), ':'] + path_dirs
        else:
            prefix_tokens = [str(start_tok), str(end_tok), ':'] + path_dirs

        return prefix_tokens, valid_dirs, final_orientation, valid_dir_label_pairs

    # Compression test
    def perform_single_compression_test():
        """Perform one trial of the compression test with random walk prefixes."""
        try:
            state_ind = np.random.choice(len(all_pairs))
            start_node, end_node = all_pairs[state_ind]

            # Random prefix length (leave room for prefix + suffix)
            max_prefix_len = block_size // 3
            prefix_len = np.random.choice(range(1, min(max_prefix_len + 1, 50)))

            # Sample task based on task_weights (includes A, C, E, H)
            task_choice = sample_task(task_weights, {'A', 'C', 'E', 'H', 'I'})
            prefix1_build = build_task_prefix(start_node, end_node, prefix_len, task_choice)
            if prefix1_build is None:
                return None
            prefix1, valid_directions, orientation1, valid_dir_label_pairs = prefix1_build

            prefix2_build = build_task_prefix(start_node, end_node, prefix_len, task_choice)
            if prefix2_build is None:
                return None
            prefix2, _, orientation2, _ = prefix2_build

            if prefix1 == prefix2:
                return None

            # For Task C/H, both prefixes must end with the same orientation
            # so they have equivalent suffix distributions
            if task_choice in ('C', 'H') and orientation1 != orientation2:
                return None

            prefix1_ids = torch.tensor([encode(" ".join(prefix1), stoi)], device=device)
            max_new_tokens = block_size - len(prefix1) - 5
            if max_new_tokens <= 0:
                return None

            with torch.no_grad():
                suffixes = []
                suffix_validations = []  # Store validation results for each suffix
                for _ in range(num_suffix_samples):
                    # Implement step-by-step generation with epsilon cutoff
                    curr_idx = prefix1_ids
                    for _step in range(max_new_tokens):
                        # Forward the model to get logits for the last token
                        idx_cond = curr_idx if curr_idx.size(1) <= block_size else curr_idx[:, -block_size:]
                        logits, _ = model(idx_cond)
                        logits = logits[:, -1, :] / temperature

                        # Apply epsilon cutoff: zero out probabilities < epsilon
                        probs = torch.softmax(logits, dim=-1)
                        mask = probs < epsilon
                        logits[mask] = -float('Inf')

                        # Re-calculate probabilities and sample
                        probs = torch.softmax(logits, dim=-1)
                        idx_next = torch.multinomial(probs, num_samples=1)
                        curr_idx = torch.cat((curr_idx, idx_next), dim=1)

                        # Break if newline/end of sequence token is sampled
                        if idx_next.item() == stoi.get('\n', -1):
                            break

                    generated_tokens = curr_idx[0, len(prefix1_ids[0]):].tolist()
                    suffix_str = decode(generated_tokens, itos)
                    suffix = suffix_str.split()

                    # Filter suffix based on task type
                    filtered_suffix = []
                    if task_choice == 'E':
                        # For Task E, filter for direction-label pairs
                        # Need to pair tokens as they come
                        i = 0
                        while i < len(suffix):
                            if suffix[i] in ['N', 'S', 'E', 'W']:
                                if i + 1 < len(suffix) and suffix[i + 1] in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
                                                                             'i', 'j']:
                                    filtered_suffix.append(suffix[i])
                                    filtered_suffix.append(suffix[i + 1])
                                    i += 2
                                else:
                                    break
                            else:
                                break
                    else:
                        # For Task A, C or H, filter based on valid directions
                        for token in suffix:
                            if task_choice == 'C':
                                if token in ['L', 'R', 'F', 'T']:
                                    filtered_suffix.append(token)
                                else:
                                    break
                            elif task_choice == 'H':
                                if token in ['1', '2', '3', '4']:
                                    filtered_suffix.append(token)
                                else:
                                    break
                            elif task_choice == 'I':
                                if token in ['1', '2', '3', '4']:
                                    filtered_suffix.append(token)
                                else:
                                    break
                            else:  # Task A
                                if token in ['N', 'S', 'E', 'W']:
                                    filtered_suffix.append(token)
                                else:
                                    break

                    if filtered_suffix:
                        suffixes.append(filtered_suffix)
                        # Validate suffix when concatenated with prefix1
                        error = validate_suffix(G, prefix1, filtered_suffix, n, num_nodes, task_choice, cl_mode=cl_mode,
                                                no_task_tag=no_task_tag)
                        suffix_validations.append(error)  # '' if valid, error message if not

            if not suffixes:
                return None

            suffix_probs_prefix2 = get_conditional_probability_of_suffixes_after_prefix(
                prefix2, suffixes, model, stoi, itos, device, block_size
            )

            precision = all([all(suffix_probs_prefix2[i] > epsilon) for i in range(len(suffixes))])

            return float(precision), tuple(prefix1), tuple(prefix2), tuple([tuple(s) for s in
                                                                            suffixes]), suffix_probs_prefix2, start_node, end_node, task_choice, suffix_validations

        except Exception:
            return None

    # Run trials
    state_pair_to_prefixes_to_score = defaultdict(lambda: defaultdict(list))
    compression_data = []  # Store detailed data for output file

    # Statistics for suffix validation - per task
    task_stats = {
        'A': {'total_suffixes': 0, 'valid_suffixes': 0, 'total_trials': 0, 'precisions': []},
        'C': {'total_suffixes': 0, 'valid_suffixes': 0, 'total_trials': 0, 'precisions': []},
        'E': {'total_suffixes': 0, 'valid_suffixes': 0, 'total_trials': 0, 'precisions': []},
        'H': {'total_suffixes': 0, 'valid_suffixes': 0, 'total_trials': 0, 'precisions': []}
    }
    total_suffixes = 0
    valid_suffixes = 0
    error_categories = defaultdict(int)  # Count errors by category
    iteration_accuracies = []  # Track accuracy per iteration

    bar = tqdm(range(num_trials))

    for trial in bar:
        result = perform_single_compression_test()
        if result is not None:
            precision, prefix1, prefix2, suffixes, suffix_probs, start_node, end_node, task_choice, suffix_validations = result
            state_pair_to_prefixes_to_score[(start_node, end_node)][(prefix1, prefix2)].append(precision)

            # Update task-specific statistics
            if task_choice in task_stats:
                task_stats[task_choice]['precisions'].append(precision)
                task_stats[task_choice]['total_trials'] += 1

                # Update suffix validation stats for this task
                iter_total = len(suffix_validations)
                iter_valid = sum(1 for v in suffix_validations if v == '')
                task_stats[task_choice]['total_suffixes'] += iter_total
                task_stats[task_choice]['valid_suffixes'] += iter_valid

            # Track overall suffix validation statistics
            iter_total = len(suffix_validations)
            iter_valid = sum(1 for v in suffix_validations if v == '')
            total_suffixes += iter_total
            valid_suffixes += iter_valid

            # Track accuracy for this iteration
            iter_accuracy = iter_valid / iter_total if iter_total > 0 else 0.0
            iteration_accuracies.append(iter_accuracy)

            # Count error categories (aggregate illegal directions)
            for error in suffix_validations:
                if error != '':
                    if 'is illegal' in error:
                        error_categories['illegal direction'] += 1
                    elif 'incorrect label' in error:
                        error_categories['incorrect label'] += 1
                    else:
                        error_categories[error] += 1

            # Store detailed data
            compression_data.append({
                'prefix1': prefix1,
                'prefix2': prefix2,
                'suffixes': suffixes,
                'suffix_probs': suffix_probs,
                'start_node': start_node,
                'end_node': end_node,
                'task_id': task_choice,
                'suffix_validations': suffix_validations
            })

            # Compute running stats
            average_precisions = [
                [np.mean(v) for k, v in inner_dict.items()]
                for k1, inner_dict in state_pair_to_prefixes_to_score.items()
            ]
            running_suffix_accuracy = valid_suffixes / total_suffixes if total_suffixes > 0 else 0.0
            if average_precisions:
                average_precisions = [item for sublist in average_precisions for item in sublist]
                mean_precision = np.mean(average_precisions)
                std = np.std(average_precisions) / np.sqrt(len(average_precisions) + 1e-6)
                bar.set_description(f"Precision: {mean_precision:.3f} | Suffix Acc: {running_suffix_accuracy:.3f}")

    # Final summary
    print("\n" + "=" * 60)
    print("Compression Test Results")
    print("=" * 60)

    # Prepare output filenames (use ckpt_iter and num_trials as requested)
    # Temperature tag for filenames (only when temperature != 1)
    temp_tag = f't{temperature}' if temperature != 1 else ''
    if multitasks:
        output_filename = f"compression_{tasks_tag}_{ckpt_iter}_{num_trials}_{temp_tag}.txt"
        data_filename = f"cpress_data_{tasks_tag}_{ckpt_iter}_{num_trials}_{temp_tag}.txt"
    else:
        output_filename = f"compression_{ckpt_iter}_{num_trials}_{temp_tag}.txt"
        data_filename = f"cpress_data_{ckpt_iter}_{num_trials}_{temp_tag}.txt"
    output_path = os.path.join(out_dir, output_filename)
    data_path = os.path.join(out_dir, data_filename)

    # Calculate overall suffix validation statistics
    final_suffix_accuracy = valid_suffixes / total_suffixes if total_suffixes > 0 else 0.0
    avg_iteration_accuracy = np.mean(iteration_accuracies) if iteration_accuracies else 0.0

    if state_pair_to_prefixes_to_score:
        average_precisions = [
            [np.mean(v) for k, v in inner_dict.items()]
            for k1, inner_dict in state_pair_to_prefixes_to_score.items()
        ]
        average_precisions = [item for sublist in average_precisions for item in sublist]
        mean_precision = np.mean(average_precisions)
        std = np.std(average_precisions) / np.sqrt(len(average_precisions) + 1e-6)

        # Print to console
        print(f"Mean compression precision: {mean_precision:.4f}")
        print(f"Standard error: {std:.4f}")
        print(f"Total valid trials: {len(average_precisions)}")

        # Print task-specific statistics
        print("\nTask-specific statistics:")
        for task_id, stats in task_stats.items():
            if stats['total_trials'] > 0:
                task_precision = np.mean(stats['precisions']) if stats['precisions'] else 0.0
                task_suffix_acc = stats['valid_suffixes'] / stats['total_suffixes'] if stats[
                                                                                           'total_suffixes'] > 0 else 0.0
                print(f"  Task {task_id}:")
                print(f"    Trials: {stats['total_trials']}")
                print(f"    Precision: {task_precision:.4f}")
                print(
                    f"    Suffix accuracy: {task_suffix_acc:.4f} ({stats['valid_suffixes']}/{stats['total_suffixes']})")

        print("-" * 60)
        print("Overall Suffix Validation Statistics:")
        print(f"  Total suffixes generated: {total_suffixes}")
        print(f"  Valid suffixes: {valid_suffixes}")
        print(f"  Invalid suffixes: {total_suffixes - valid_suffixes}")
        print(f"  Average accuracy per iteration: {avg_iteration_accuracy:.4f}")
        print(f"  Final overall accuracy: {final_suffix_accuracy:.4f}")
        if error_categories:
            print("  Error categories:")
            for error, count in sorted(error_categories.items(), key=lambda x: -x[1]):
                print(f"    {error}: {count}")
        print("=" * 60 + "\n")

        # Save summary to file
        with open(output_path, 'w') as f:
            f.write("=" * 60 + "\n")
            f.write("Compression Test Results\n")
            f.write("=" * 60 + "\n")
            f.write(f"Config: {config}\n")
            f.write(f"Checkpoint iteration: {ckpt_iter}\n")
            f.write(f"Number of nodes: {num_nodes}\n")
            f.write(f"Number of trials: {num_trials}\n")
            f.write(f"Epsilon: {epsilon}\n")
            f.write(f"Number of suffix samples: {num_suffix_samples}\n")
            f.write(f"No task tag mode: {'Enabled' if no_task_tag else 'Disabled'}\n")
            if multitasks:
                f.write(f"Training data task configuration: {tasks_str}\n")
                f.write(f"Compression test task configuration: {cmpr_tasks_str}\n")
            f.write("\n")
            f.write(f"Mean compression precision: {mean_precision:.4f}\n")
            f.write(f"Standard error: {std:.4f}\n")
            f.write(f"Total valid trials: {len(average_precisions)}\n")

            # Save task-specific statistics
            f.write("\nTask-specific statistics:\n")
            for task_id, stats in task_stats.items():
                if stats['total_trials'] > 0:
                    task_precision = np.mean(stats['precisions']) if stats['precisions'] else 0.0
                    task_suffix_acc = stats['valid_suffixes'] / stats['total_suffixes'] if stats[
                                                                                               'total_suffixes'] > 0 else 0.0
                    f.write(f"  Task {task_id}:\n")
                    f.write(f"    Trials: {stats['total_trials']}\n")
                    f.write(f"    Precision: {task_precision:.4f}\n")
                    f.write(
                        f"    Suffix accuracy: {task_suffix_acc:.4f} ({stats['valid_suffixes']}/{stats['total_suffixes']})\n")

            f.write("-" * 60 + "\n")
            f.write("Overall Suffix Validation Statistics:\n")
            f.write(f"  Total suffixes generated: {total_suffixes}\n")
            f.write(f"  Valid suffixes: {valid_suffixes}\n")
            f.write(f"  Invalid suffixes: {total_suffixes - valid_suffixes}\n")
            f.write(f"  Average accuracy per iteration: {avg_iteration_accuracy:.4f}\n")
            f.write(f"  Final overall accuracy: {final_suffix_accuracy:.4f}\n")
            if error_categories:
                f.write("  Error categories:\n")
                for error, count in sorted(error_categories.items(), key=lambda x: -x[1]):
                    f.write(f"    {error}: {count}\n")
            f.write("=" * 60 + "\n")

        # Save detailed data to file
        with open(data_path, 'w') as f:
            f.write("=" * 60 + "\n")
            f.write("Compression Test Detailed Data\n")
            f.write("=" * 60 + "\n")
            f.write(f"Config: {config}\n")
            f.write(f"Checkpoint iteration: {ckpt_iter}\n")
            f.write(f"Number of nodes: {num_nodes}\n")
            f.write(f"Epsilon: {epsilon}\n")
            f.write(f"Number of suffix samples: {num_suffix_samples}\n")
            f.write(f"No task tag mode: {'Enabled' if no_task_tag else 'Disabled'}\n")
            if multitasks:
                f.write(f"Training data task configuration: {tasks_str}\n")
                f.write(f"Compression test task configuration: {cmpr_tasks_str}\n")
            f.write("=" * 60 + "\n\n")

            for idx, data in enumerate(compression_data):
                # Calculate iteration accuracy
                iter_validations = data.get('suffix_validations', [])
                iter_valid = sum(1 for v in iter_validations if v == '')
                iter_total = len(iter_validations)
                iter_acc = iter_valid / iter_total if iter_total > 0 else 0.0

                f.write(f"Iteration {idx + 1}:\n")
                f.write(f"  Task: {data.get('task_id', 'A')}\n")
                f.write(f"  Merge node: {data['start_node']}\n")
                f.write(f"  Target node: {data['end_node']}\n")
                f.write(f"  prefix1: {' '.join(data['prefix1'])}\n")
                f.write(f"  prefix2: {' '.join(data['prefix2'])}\n")
                f.write(f"  Iteration suffix accuracy: {iter_acc:.4f} ({iter_valid}/{iter_total})\n")
                f.write(f"\n")

                # Write sampled suffixes with their probability vectors side by side
                f.write(f"  Suffix comparisons (from prefix1 vs probabilities after prefix2):\n")
                for suffix_idx, suffix in enumerate(data['suffixes']):
                    suffix_str = ' '.join(suffix)
                    # Format probabilities to 3 decimal places
                    probs = data['suffix_probs'][suffix_idx]
                    probs_str = ", ".join([f"{p:.3f}" for p in probs])
                    # Get validation result
                    validation_error = iter_validations[suffix_idx] if suffix_idx < len(iter_validations) else ''
                    validation_status = "VALID" if validation_error == '' else f"ERROR: {validation_error}"
                    f.write(f"    suffix_{suffix_idx}: {suffix_str}\n")
                    f.write(f"    suffix_{suffix_idx}_probs: [{probs_str}]\n")
                    f.write(f"    suffix_{suffix_idx}_validation: {validation_status}\n")
                    f.write(f"\n")

                f.write("\n")

        print(f"Detailed data saved to {data_path}")

        print(f"Results saved to {output_path}")
    else:
        print("No valid trials completed.")
        print("=" * 60 + "\n")


if __name__ == "__main__":
    main()