File size: 56,615 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
"""

This training script can be run both on a single gpu in debug mode,

and also in a larger training run with distributed data parallel (ddp).



To run on a single GPU, example:

$ python train_maze.py --batch_size=32 --compile=False



To run with DDP on 4 gpus on 1 node, example:

$ torchrun --standalone --nproc_per_node=4 train_maze.py



To run with DDP on 4 gpus across 2 nodes, example:

- Run on the first (master) node with example IP 123.456.123.456:

$ torchrun --nproc_per_node=8 --nnodes=2 --node_rank=0 --master_addr=123.456.123.456 --master_port=1234 train_maze.py

- Run on the worker node:

$ torchrun --nproc_per_node=8 --nnodes=2 --node_rank=1 --master_addr=123.456.123.456 --master_port=1234 train_maze.py

(If your cluster does not have Infiniband interconnect prepend NCCL_IB_DISABLE=1)

"""

import os
import time
import math
import pickle
from contextlib import nullcontext
import argparse


import numpy as np
import torch
import torch.nn.functional as F
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.distributed import init_process_group, destroy_process_group
import networkx as nx
import re 

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
from logger import get_logger
import logging
from cli_utils import parse_count, format_count

# Suppress verbose PyTorch Dynamo debug messages
logging.getLogger("torch._dynamo").setLevel(logging.WARNING)

# torch.backends.cuda.enable_flash_sdp(False)
# torch.backends.cuda.enable_mem_efficient_sdp(False)

# -----------------------------------------------------------------------------
# the input parameters

parser = argparse.ArgumentParser(description='Training of the NanoGPT for maze data.')

parser.add_argument('--dataset', type=str, default='maze', help='Name of the dataset to use')
parser.add_argument('--model', type=str, default='transformer-nextlat', choices=['transformer', 'transformer-rope', 'transformer-nextlat', 'mamba', 'mamba2', 'gated-deltanet', 'gru'],
                    help='Model architecture to train. Outputs go to out/<model>/... (default: transformer)')
parser.add_argument('--n_layer', type=int, default=6, help='Number of layers (default: 1)')
parser.add_argument('--n_head', type=int, default=6, help='Number of attention heads (default: 1)')
parser.add_argument('--n_embd', type=int, default=384, help='Size of the embeddings (default: 120)')
parser.add_argument('--max_iters', type=int, default=10000, help='Number of Iterations (default: 10000)')
parser.add_argument('--num_nodes', type=int, default=100, help='Number of Nodes (default: 100)')
parser.add_argument('--num_of_paths', type=int, default=20, help='Number of Paths (default: 20)')
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='500K', 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='A1', help='Task specification (e.g., A1, A1B1, A3B2, A1D1F1). Default: A1')
parser.add_argument('--init_ckpt', type=int, default=0, help='Initial checkpoint iteration to resume from (default: 0 means train from scratch)')
parser.add_argument('--validation', action=argparse.BooleanOptionalAction, default=False, help='Enable periodic validation and checkpointing (default: False)')
parser.add_argument('--ckpt_interval', type=int, default=None, help='Override checkpoint save interval (default: max_iters // 2)')
parser.add_argument('--CL', action=argparse.BooleanOptionalAction, default=False, help='Enable Task C label mode (append node labels after L/R turns) and add _CL_ in filenames')
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('--compile', action=argparse.BooleanOptionalAction, default=True, help='Use PyTorch 2.0 to compile the model (default: True). Disable with --no-compile if you encounter Triton/CUDA errors.')
parser.add_argument('--batch_size', type=int, default=128, help='Training batch size (default: 1024). Reduce if you encounter OOM errors.')
parser.add_argument('--grad_accum', type=int, default=8, help='Gradient accumulation steps (default: 1). Use a small --batch_size with larger --grad_accum to keep tokens/iter constant under memory limits (e.g. pure-PyTorch Mamba).')
parser.add_argument('--mamba_cuda', action='store_true', default=True,
                    help='For --model mamba: use the official mamba_ssm CUDA selective-scan kernel (much faster) instead of the pure-PyTorch parallel scan. Requires mamba-ssm + causal-conv1d to be installed.')
# 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, data decoding will handle the no-task-tag format. 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.')
# NextLat (Next-Latent Prediction) arguments (used with --model transformer-nextlat)
parser.add_argument('--nextlat_horizon', type=int, default=8,
                    help='NextLat latent dynamics rollout horizon d (default: 1)')
parser.add_argument('--lambda_h', type=float, default=1.0,
                    help='NextLat weight for next-hidden-state regression loss (default: 1.0)')
parser.add_argument('--lambda_kl', type=float, default=0.1,
                    help='NextLat weight for KL divergence loss (default: 1.0)')
parser.add_argument('--mlp_hidden_dim', type=int, default=None,
                    help='NextLat MLP hidden dimension (default: 2*n_embd)')
# PostGRU: Post-Transformer GRU refinement layer
parser.add_argument('--PostGRU', action='store_true', default=False,
                    help='Enable Post-Transformer GRU refinement layer (adds _PGR suffix to filenames)')
# NLS: Per-block Non-Linear prefix Scan sublayer
parser.add_argument('--NLS', action='store_true', default=False,
                    help='Enable per-block Non-Linear prefix Scan sublayer (adds _NLS suffix to filenames)')
# DyadicAttn: baseline transformer whose attention is hard-coded to the
# same fixed 0.5/0.5 dyadic-doubling pattern as the NLS scan. Mutually
# exclusive with --NLS / --PostGRU. For fair comparison set
# n_layer = ceil(log2(block_size)).
parser.add_argument('--DyadicAttn', action='store_true', default=False,
                    help='Enable DyadicTransformer baseline: replace self-attention with fixed 0.5/0.5 dyadic-pattern attention (adds _DA suffix to filenames)')
parser.add_argument('--DyadicHybrid', action='store_true', default=False,
                    help='Enable DyadicHybrid ablation: each --n_layer normal Transformer block is followed by ceil(log2(block_size)) DyadicAttn blocks (adds _DH suffix to filenames). Total physical blocks = n_layer * (1 + ceil(log2(block_size))).')
parser.add_argument('--auto_n_layer', action='store_true', default=False,
                    help='For DyadicAttn: automatically set n_layer = ceil(log2(block_size)) so the per-layer dyadic strides cover the full sequence length recorded in meta.')
# Auxiliary state-supervision: force one layer's OUTPUT hidden state to linearly
# decode the walker's (current_node, facing). Supported on transformer+Task C
# and gru+Task H.
parser.add_argument('--aux_layer', type=int, default=None,
                    help='1-based index of the block/layer whose OUTPUT hidden state is '
                         'supervised toward (node, facing). None disables the auxiliary loss '
                         '(default: None). E.g. --aux_layer 3 = the 3rd layer. Supported on '
                         'transformer (Task C) and gru (Task H). Enabling it adds an _SA suffix '
                         'to checkpoint filenames.')
parser.add_argument('--aux_lambda', type=float, default=1.0,
                    help='Weight of the auxiliary (node, facing) cross-entropy loss.')

args = parser.parse_args()

dataset = args.dataset
model_type = args.model
n_layer = args.n_layer
n_head = args.n_head
n_embd = args.n_embd
max_iters = args.max_iters
num_nodes = args.num_nodes
num_of_paths = args.num_of_paths
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_label = format_count(num_test_dataset)
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 == 'RWc')
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"
# NextLat mode: enabled by selecting --model transformer-nextlat. The latent
# dynamics model is encapsulated in the module, so a single optimizer + single
# checkpoint covers everything.
use_nextlat = (args.model == 'transformer-nextlat')
nextlat_horizon = args.nextlat_horizon
lambda_h = args.lambda_h
lambda_kl = args.lambda_kl
# data_tasks_tag: used for finding data/meta files (no _NL suffix)
data_tasks_tag = tasks_tag
# Add _NL tag to tasks_tag when NextLat is enabled (affects checkpoint naming only)
if use_nextlat:
    tasks_tag = f"{tasks_tag}_NL"
# PostGRU mode
use_post_gru = args.PostGRU
# Add _PGR tag to tasks_tag when PostGRU is enabled (affects checkpoint naming only)
if use_post_gru:
    tasks_tag = f"{tasks_tag}_PGR"
# NLS mode
use_nls = args.NLS
# DyadicAttn mode (mutually exclusive with NLS / PostGRU / transformer-nextlat)
use_dyadic_attn = args.DyadicAttn
use_dyadic_hybrid = args.DyadicHybrid
if use_dyadic_hybrid and use_dyadic_attn:
    # Hybrid takes precedence; DyadicAttn default may be True from CLI.
    print('[Info] --DyadicHybrid given; auto-disabling DyadicAttn for this run.')
    use_dyadic_attn = False
if (use_dyadic_attn or use_dyadic_hybrid) and (use_post_gru or use_nextlat):
    raise ValueError('--DyadicAttn / --DyadicHybrid is mutually exclusive with --PostGRU / --model transformer-nextlat')
if (use_dyadic_attn or use_dyadic_hybrid) and use_nls:
    print(f"[Info] --{'DyadicAttn' if use_dyadic_attn else 'DyadicHybrid'} given; auto-disabling NLS for this run.")
    use_nls = False
# Add _NLS tag to tasks_tag when NLS is enabled (affects checkpoint naming only)
if use_nls:
    tasks_tag = f"{tasks_tag}_NLS"
if use_dyadic_attn:
    tasks_tag = f"{tasks_tag}_DA"
if use_dyadic_hybrid:
    tasks_tag = f"{tasks_tag}_DH"
# Auxiliary state-supervision (Task C, transformer). Enabled when --aux_layer is
# given. Adds a separate linear head that decodes (current_node, facing) from a
# chosen block's output; its loss is added to the LM loss. Checkpoints get an
# _SA suffix so they never overwrite the baseline (load via test_maze.py
# --ckpt_suffix SA).
use_aux = args.aux_layer is not None
# --aux_layer is 1-based on the CLI; convert to a 0-based block/layer index internally.
aux_layer = (args.aux_layer - 1) if use_aux else None
aux_lambda = args.aux_lambda
aux_task = None  # 'C' (transformer) or 'H' (gru) when use_aux
if use_aux:
    aux_task = args.tasks[0].upper()
    if model_type == 'transformer':
        if aux_task != 'C':
            raise ValueError('--aux_layer with --model transformer is defined for Task C only')
    elif model_type == 'gru':
        if aux_task != 'H':
            raise ValueError('--aux_layer with --model gru is defined for Task H only')
    else:
        raise ValueError('--aux_layer state-supervision is only implemented for '
                         '--model transformer (Task C) or --model gru (Task H)')
    if use_nextlat or use_post_gru or use_nls or use_dyadic_attn or use_dyadic_hybrid:
        raise ValueError('--aux_layer is mutually exclusive with NextLat / PostGRU / NLS / DyadicAttn / DyadicHybrid')
    tasks_tag = f"{tasks_tag}_SA"
# Mamba does not support the transformer-only training variants.
if model_type in ('mamba', 'mamba2', 'gated-deltanet', 'gru') and (use_nextlat or use_post_gru or use_nls
                              or use_dyadic_attn or use_dyadic_hybrid):
    raise ValueError(f'--model {model_type} is incompatible with '
                     'transformer-nextlat / --PostGRU / --NLS / --DyadicAttn / --DyadicHybrid')
# Graph tag without path type (same graph structure)
graph_tag = f"{tasks_str}_CL" if args.CL else tasks_str
# Add _NT_ tag to graph_tag when no_task_tag is enabled
if args.no_task_tag:
    graph_tag = f"{graph_tag}_NT"
init_ckpt = args.init_ckpt
validation = args.validation
local_mode = args.local
no_task_tag = args.no_task_tag  # Get the no_task_tag flag

data_dir = os.path.join('data', f'{dataset}/{num_nodes}')

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

meta_path = pick_first_existing([
    os.path.join(data_dir, f'meta_{data_tasks_tag}.pkl'),
    os.path.join(data_dir, f'meta_{tasks_str}.pkl'),
    os.path.join(data_dir, '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']

# Auto-derive n_layer for DyadicAttn so the dyadic strides reach the full
# sequence length (max stride = 2^(n_layer-1) >= block_size).
if use_dyadic_attn and args.auto_n_layer:
    auto_n = max(1, math.ceil(math.log2(block_size))) if block_size > 1 else 1
    if n_layer != auto_n:
        print(f"[auto_n_layer] DyadicAttn: overriding n_layer {n_layer} -> {auto_n}"
              f" (block_size={block_size}, ceil(log2)={auto_n})")
        n_layer = auto_n
        args.n_layer = auto_n

# Check if metadata contains no_task_tag flag
meta_no_task_tag = meta.get('no_task_tag', False)
print(f"Metadata no_task_tag flag: {meta_no_task_tag}")
print(f"Command line no_task_tag flag: {no_task_tag}")

# Use metadata flag if provided, otherwise use command line flag
# This ensures consistency with the data generation
if 'no_task_tag' in meta:
    no_task_tag = meta['no_task_tag']
    print(f"Using no_task_tag flag from metadata: {no_task_tag}")

nt_suffix = '_NT' if args.no_task_tag else ''
model_dir = model_type.replace('-', '_')  # filesystem-friendly (transformer-nextlat -> transformer_nextlat)
# Recurrent / SSM models have no attention heads, so omit n_head from the dir name.
if model_type in ('mamba', 'mamba2', 'gated-deltanet', 'gru'):
    arch_tag = f'{n_layer}_{n_embd}'
else:
    arch_tag = f'{n_layer}_{n_head}_{n_embd}'
out_dir = f'out/{model_dir}/{dataset}_{arch_tag}_{num_nodes}{nt_suffix}/'
# -----------------------------------------------------------------------------
# default config values designed to train a gpt2 (124M) on OpenWebText
# I/O
eval_interval = max_iters // 10 if validation else None
checkpoint_interval = args.ckpt_interval if args.ckpt_interval is not None else max_iters // 2  # checkpoint cadence (independent of validation)
log_interval = max_iters // 100
eval_iters = max_iters // 10 if validation else 1

eval_only = False # if True, script exits right after the first eval
always_save_checkpoint = True # if True, always save a checkpoint after each eval
init_from = 'resume' if init_ckpt > 0 else 'scratch' # determined by --init_ckpt argument
# wandb logging
wandb_log = False # disabled by default
wandb_project = 'owt'
wandb_run_name = 'gpt2' # 'run' + str(time.time())
# data
#dataset = 'reasoning'
gradient_accumulation_steps = args.grad_accum # used to simulate larger batch sizes
train_batch_size = args.batch_size # if gradient_accumulation_steps > 1, this is the micro-batch size
val_batch_size = 64
batch_size = train_batch_size
#block_size = 64
# model
#n_layer = 1 #12
#n_head = 1 #12
#n_embd = 384 #768


dropout = 0.0 # for pretraining 0 is good, for finetuning try 0.1+
bias = False # do we use bias inside LayerNorm and Linear layers?
# adamw optimizer
learning_rate = 5e-4 # max learning rate
#max_iters = 50000 # total number of training iterations
weight_decay = 1e-1
beta1 = 0.9
beta2 = 0.95
grad_clip = 1.0 # clip gradients at this value, or disable if == 0.0
# learning rate decay settings
decay_lr = True # whether to decay the learning rate
warmup_iters = max_iters//20 # how many steps to warm up for
lr_decay_iters = max_iters # should be ~= max_iters per Chinchilla
min_lr = learning_rate/10 # minimum learning rate, should be ~= learning_rate/10 per Chinchilla
# DDP settings
backend = 'nccl' # 'nccl', 'gloo', etc.
# system
device = 'cuda' # examples: 'cpu', 'cuda', 'cuda:0', 'cuda:1' etc., or try 'mps' on macbooks
dtype = 'bfloat16' # 'float32', 'bfloat16', or 'float16', the latter will auto implement a GradScaler
compile = args.compile # use PyTorch 2.0 to compile the model to be faster

'''check_type = 'shortest'

max_path_len = 10

max_new_tokens = 200

flag = 0

test_interval = 100'''
# -----------------------------------------------------------------------------
config_keys = [k for k,v in globals().items() if not k.startswith('_') and isinstance(v, (int, float, bool, str))]
#exec(open('configurator.py').read()) # overrides from command line or config file
config = {k: globals()[k] for k in config_keys} # will be useful for logging
# -----------------------------------------------------------------------------

# various inits, derived attributes, I/O setup
ddp = int(os.environ.get('RANK', -1)) != -1 # is this a ddp run?
if ddp:
    init_process_group(backend=backend)
    ddp_rank = int(os.environ['RANK'])
    ddp_local_rank = int(os.environ['LOCAL_RANK'])
    ddp_world_size = int(os.environ['WORLD_SIZE'])
    device = f'cuda:{ddp_local_rank}'
    torch.cuda.set_device(device)
    master_process = ddp_rank == 0 # this process will do logging, checkpointing etc.
    seed_offset = ddp_rank # each process gets a different seed
    assert gradient_accumulation_steps % torch.cuda.device_count() == 0
    gradient_accumulation_steps //= torch.cuda.device_count()
else:
    # if not ddp, we are running on a single gpu, and one process
    master_process = True
    seed_offset = 0
    ddp_world_size = 1
tokens_per_iter = gradient_accumulation_steps * ddp_world_size * batch_size * block_size
print(f"tokens per iteration will be: {tokens_per_iter:,}")

if master_process:
    os.makedirs(out_dir, exist_ok=True)
torch.manual_seed(1337 + seed_offset)
torch.backends.cuda.matmul.allow_tf32 = True # allow tf32 on matmul
torch.backends.cudnn.allow_tf32 = True # allow tf32 on cudnn
device_type = 'cuda' if 'cuda' in device else 'cpu' # for later use in torch.autocast
# note: float16 data type will automatically use a GradScaler
ptdtype = {'float32': torch.float32, 'bfloat16': torch.bfloat16, 'float16': torch.float16}[dtype]
ctx = nullcontext() if device_type == 'cpu' else torch.amp.autocast(device_type=device_type, dtype=ptdtype)


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

# poor man's data loader
if multitasks:
    train_file = pick_first_existing([
        os.path.join(data_dir, f'train_{data_tasks_tag}_{train_label}.bin'),
        os.path.join(data_dir, f'train_{data_tasks_tag}_{num_train_dataset}.bin'),
        os.path.join(data_dir, f'train_{tasks_str}_{train_label}.bin'),
        os.path.join(data_dir, f'train_{tasks_str}_{num_train_dataset}.bin'),
    ])
    val_file = pick_first_existing([
        os.path.join(data_dir, f'val_{data_tasks_tag}_{test_label}.bin'),
        os.path.join(data_dir, f'val_{data_tasks_tag}_{num_test_dataset}.bin'),
        os.path.join(data_dir, f'val_{tasks_str}_{test_label}.bin'),
        os.path.join(data_dir, f'val_{tasks_str}_{num_test_dataset}.bin'),
    ])
    train_data = np.memmap(train_file, dtype=np.uint16, mode='r')
    val_data = np.memmap(val_file, dtype=np.uint16, mode='r')
else:
    if(num_of_paths == 0):
        train_file = os.path.join(data_dir, 'train.bin')
        val_file = os.path.join(data_dir, 'val.bin')
    else:
        train_file = os.path.join(data_dir, f'train_{num_of_paths}.bin')
        val_file = os.path.join(data_dir, 'val.bin')
    train_data = np.memmap(train_file, dtype=np.uint16, mode='r')
    val_data = np.memmap(val_file, dtype=np.uint16, mode='r')

if master_process:
    print(f"Training data file: {train_file}")
    print(f"No task tag mode: {'Enabled' if no_task_tag else 'Disabled'}")


# -----------------------------------------------------------------------------
# Auxiliary state-supervision. Per-position (current_node, facing) labels are
# recomputed on the fly by replaying each row against the maze. Two label
# schemes:
#   * Task C (transformer): replay relative turns L/R/F/T starting facing East.
#   * Task H (gru): replay clockwise feasible-direction indices starting facing
#     East -- identical logic to train.py / create_multitask_maze.py::taskH.
if use_aux:
    aux_n_grid = int(round(num_nodes ** 0.5))
    AUX_DELTA = {'N': -aux_n_grid, 'S': aux_n_grid, 'E': 1, 'W': -1}
    AUX_FACE = {'N': 0, 'E': 1, 'S': 2, 'W': 3}
    AUX_NUM_STATES = num_nodes * 4
    AUX_IGNORE = -1
    AUX_PAD_ID, AUX_NL_ID = 0, 1
    AUX_COLON_ID = stoi[':']
    assert 0 <= aux_layer < n_layer, f"--aux_layer must be in [1, {n_layer}] (1-based)"
    if aux_task == 'C':
        AUX_LEFT = {'N': 'W', 'W': 'S', 'S': 'E', 'E': 'N'}
        AUX_RIGHT = {v: k for k, v in AUX_LEFT.items()}
        AUX_OPP = {'N': 'S', 'S': 'N', 'E': 'W', 'W': 'E'}
        AUX_C_ID = stoi['C']
        AUX_L_ID, AUX_R_ID = stoi['L'], stoi['R']
        AUX_F_ID, AUX_T_ID = stoi['F'], stoi['T']
    else:  # Task H
        AUX_CLOCKWISE_SCAN = {
            'N': ['N', 'E', 'S', 'W'],
            'E': ['E', 'S', 'W', 'N'],
            'S': ['S', 'W', 'N', 'E'],
            'W': ['W', 'N', 'E', 'S'],
        }
        AUX_H_ID = stoi['H']
        aux_graph_path = os.path.join(data_dir, f'maze_graph_{tasks_str}_{path_type_tag}.graphml')
        print(f"[aux] Loading maze graph from {aux_graph_path}...")
        _aux_G = nx.read_graphml(aux_graph_path)
        AUX_NODE_DIRS = {}
        for _nd in range(num_nodes):
            _dirs = set()
            for _d in ('N', 'E', 'S', 'W'):
                _nb = _nd + AUX_DELTA[_d]
                if 0 <= _nb < num_nodes and _aux_G.has_edge(str(_nd), str(_nb)):
                    _dirs.add(_d)
            AUX_NODE_DIRS[_nd] = _dirs


def row_state_labels_taskC(row):
    """Given a (block_size+1)-id Task C row, return a length-block_size int array

    S aligned to y (= row[1:]) where S[t] is the PRE-move state (node*4 + facing)

    the walker stands in just before emitting the turn token at row position t+1,

    and AUX_IGNORE elsewhere. Node token id n encodes node (n-2)."""
    S = np.full(block_size, AUX_IGNORE, dtype=np.int64)
    if len(row) < 5 or int(row[0]) != AUX_C_ID or int(row[3]) != AUX_COLON_ID:
        return S
    source = int(row[1]) - 2  # node token id n -> node (n-2)
    if not (0 <= source < num_nodes):
        return S
    current = source
    facing = 'E'
    p = 4  # row position of the first turn token
    while p < len(row):
        tok = int(row[p])
        if tok == AUX_NL_ID or tok == AUX_PAD_ID:
            break
        t = p - 1  # hidden at row pos p-1 predicts token at pos p
        if 0 <= t < block_size:
            S[t] = current * 4 + AUX_FACE[facing]
        if tok == AUX_F_ID:
            new_facing = facing
        elif tok == AUX_L_ID:
            new_facing = AUX_LEFT[facing]
        elif tok == AUX_R_ID:
            new_facing = AUX_RIGHT[facing]
        elif tok == AUX_T_ID:
            new_facing = AUX_OPP[facing]
        else:
            break
        current = current + AUX_DELTA[new_facing]
        if not (0 <= current < num_nodes):
            break
        facing = new_facing
        p += 1
    return S


def row_state_labels_taskH(row):
    """Given a (block_size+1)-id Task H row, return a length-block_size int array

    S aligned to y (= row[1:]) where S[t] is the PRE-move state (node*4 + facing)

    the walker stands in just before emitting the index token at row position

    t+1, and AUX_IGNORE elsewhere. Replays clockwise feasible-direction indices

    starting facing East. Node token id n encodes node (n-2)."""
    S = np.full(block_size, AUX_IGNORE, dtype=np.int64)
    if len(row) < 5 or int(row[0]) != AUX_H_ID or int(row[3]) != AUX_COLON_ID:
        return S
    source = int(row[1]) - 2  # node token id n -> node (n-2)
    if not (0 <= source < num_nodes):
        return S
    current = source
    facing = 'E'
    p = 4  # row position of the first index token
    while p < len(row):
        tok = int(row[p])
        if tok == AUX_NL_ID or tok == AUX_PAD_ID:
            break
        idx = tok - 2  # index '1'..'4' encoded as node tokens 1..4 -> ids 3..6
        t = p - 1  # hidden at row pos p-1 predicts token at pos p
        if 0 <= t < block_size:
            S[t] = current * 4 + AUX_FACE[facing]
        scan_order = AUX_CLOCKWISE_SCAN[facing]
        feasible = [d for d in scan_order if d in AUX_NODE_DIRS[current]]
        if idx < 1 or idx > len(feasible):
            break
        direction = feasible[idx - 1]
        current = current + AUX_DELTA[direction]
        if not (0 <= current < num_nodes):
            break
        facing = direction
        p += 1
    return S


if use_aux:
    row_state_labels = row_state_labels_taskC if aux_task == 'C' else row_state_labels_taskH


def get_batch(split):
    data = train_data if split == 'train' else val_data
    batch_size = train_batch_size if split == 'train' else val_batch_size

    data_size = block_size + 1
    data = train_data if split == 'train' else val_data
    ix = torch.randint( (len(data) - data_size)//data_size , (batch_size,)) * data_size
    x = torch.stack([torch.from_numpy((data[i:i+block_size]).astype(np.int64)) for i in ix])
    y = torch.stack([torch.from_numpy((data[i+1:i+1+block_size]).astype(np.int64)) for i in ix])

    if use_aux:
        rows = [np.asarray(data[i:i + data_size]).astype(np.int64) for i in ix.tolist()]
        s = torch.stack([torch.from_numpy(row_state_labels(r)) for r in rows])
    else:
        s = None

    if device_type == 'cuda':
        # pin arrays x,y, which allows us to move them to GPU asynchronously (non_blocking=True)
        x, y = x.pin_memory().to(device, non_blocking=True), y.pin_memory().to(device, non_blocking=True)
        if s is not None:
            s = s.pin_memory().to(device, non_blocking=True)
    else:
        x, y = x.to(device), y.to(device)
        if s is not None:
            s = s.to(device)
    return x, y, s


# init these up here, can override if init_from='resume' (i.e. from a checkpoint)
iter_num = 0
best_val_loss = 1e9

# logger
if(num_of_paths == 0):
    logger = get_logger(os.path.join(out_dir, "no_output_train_maze.log"))
    log_file_name = os.path.join(out_dir, "train_maze.log")
    #logger.setLevel(logging.DEBUG)
else:
    logger = get_logger(os.path.join(out_dir, f'no_output_train_maze_{num_of_paths}.log'))
    log_file_name = os.path.join(out_dir, f"train_maze_{num_of_paths}.log")
    #logger.setLevel(logging.DEBUG)



# attempt to derive vocab_size from the dataset
# Use the task-specific meta file (already loaded earlier) instead of hardcoded meta.pkl
meta_vocab_size = None
if meta is not None and 'vocab_size' in meta:
    meta_vocab_size = meta['vocab_size']
    print(f"found vocab_size = {meta_vocab_size} (inside {meta_path})")

def get_shortest(p_graph):
    shortest_paths = {}
    for i in p_graph.nodes:
        for j in p_graph.nodes:
            try:
                shortest_paths[(i,j)] = list(nx.all_shortest_paths(p_graph, i, j))
            except:
                shortest_paths[(i,j)] = []
    return shortest_paths

if dataset == 'reasoning':
    p_graph_path = os.path.join(data_dir, 'fixed_model.graphml')
    p_graph = nx.read_graphml(p_graph_path)
    shortest_paths = get_shortest(p_graph)

stoi, itos = meta['stoi'], meta['itos']

# Modified decode function to handle no_task_tag format
def decode_token_list(l):
    """Decode a list of token IDs to string."""
    if no_task_tag:
        # In no_task_tag mode, just join all tokens with spaces
        return ' '.join([itos[i] for i in l if i in itos])
    else:
        # Original decode behavior
        return ''.join([itos[i] for i in l if i in itos])

decode = decode_token_list  # Assign the function to decode variable

# model init
if model_type in ('transformer', 'transformer-rope'):
    model_args = dict(n_layer=n_layer, n_head=n_head, n_embd=n_embd, block_size=block_size,
                      bias=bias, vocab_size=None, dropout=dropout, use_flash=not local_mode,
                      post_gru=use_post_gru, per_block_nls=use_nls,
                      dyadic_attn=use_dyadic_attn,
                      dyadic_hybrid=use_dyadic_hybrid) # start with model_args from command line
elif model_type == 'transformer-nextlat':
    # GPT backbone + encapsulated NextLat latent dynamics model. The latent model
    # is part of the module, so a single optimizer / checkpoint covers everything.
    model_args = dict(model_type='transformer-nextlat',
                      n_layer=n_layer, n_head=n_head, n_embd=n_embd, block_size=block_size,
                      bias=bias, vocab_size=None, dropout=dropout, use_flash=not local_mode,
                      mlp_hidden_dim=args.mlp_hidden_dim,
                      nextlat_horizon=nextlat_horizon, lambda_h=lambda_h, lambda_kl=lambda_kl)
elif model_type == 'gru':
    # Stacked residual GRU baseline (no attention). pad_id=0 mirrors the
    # transformer's ignore_index=0 for the padding token.
    model_args = dict(model_type='gru', n_layer=n_layer, n_embd=n_embd,
                      vocab_size=None, dropout=dropout, bias=bias, pad_id=0)
elif model_type == 'gated-deltanet':
    # Gated DeltaNet (linear-attention / delta-rule). No positional encoding;
    # token order is carried by the recurrence. pad_id=0 mirrors the
    # transformer's ignore_index=0 for the padding token.
    model_args = dict(model_type='gated-deltanet', n_layer=n_layer, n_embd=n_embd,
                      vocab_size=None, pad_id=0)
else:  # mamba
    # By default use the pure-PyTorch parallel scan so it runs without the
    # mamba_ssm package. With --mamba_cuda, use the official fused CUDA
    # selective-scan kernel (much faster) when mamba-ssm is installed.
    # pad_id=0 mirrors the transformer's ignore_index=0 for the padding token.
    if model_type == 'mamba2':
        # Semi-official Mamba-2: official fused Triton kernel when mamba_ssm>=2.2
        # is installed (--mamba_cuda, default), else pure-PyTorch chunked SSD.
        model_args = dict(model_type='mamba2', n_layer=n_layer, n_embd=n_embd,
                          vocab_size=None, pscan=True, use_cuda=args.mamba_cuda, pad_id=0)
    else:
        model_args = dict(model_type='mamba', n_layer=n_layer, n_embd=n_embd,
                          vocab_size=None, pscan=True, use_cuda=args.mamba_cuda, pad_id=0)


def build_model(margs):
    """Instantiate the architecture selected by --model from a model_args dict."""
    if model_type == 'mamba':
        return Mamba(MambaConfig(**margs))
    if model_type == 'mamba2':
        return Mamba2(Mamba2Config(**margs))
    if model_type == 'gated-deltanet':
        return GatedDeltaNet(GatedDeltaNetConfig(**margs))
    if model_type == 'transformer-nextlat':
        return TransformerNextLat(TransformerNextLatConfig(**margs))
    if model_type == 'transformer-rope':
        return GPTRoPE(GPTRoPEConfig(**margs))
    if model_type == 'gru':
        return GRU(GRUConfig(**margs))
    return GPT(GPTConfig(**margs))


if init_from == 'scratch':
    print("Initializing a new model from scratch")
    if meta_vocab_size is None:
        print("defaulting to vocab_size of GPT-2 to 50304 (50257 rounded up for efficiency)")
    model_args['vocab_size'] = meta_vocab_size if meta_vocab_size is not None else 50304
    model = build_model(model_args)
elif init_from == 'resume':
    # Determine the checkpoint file path based on init_ckpt and multitask setting
    if multitasks:
        candidate_ckpts = [
            os.path.join(out_dir, f'{init_ckpt}_ckpt_maze_{tasks_tag}_{train_label}.pt'),
            os.path.join(out_dir, f'{init_ckpt}_ckpt_maze_{tasks_tag}_{num_train_dataset}.pt'),
            os.path.join(out_dir, f'{init_ckpt}_ckpt_maze_{tasks_str}_{train_label}.pt'),
            os.path.join(out_dir, f'{init_ckpt}_ckpt_maze_{num_of_paths}.pt'),
            os.path.join(out_dir, f'{init_ckpt}_ckpt_maze.pt'),
        ]
        ckpt_path = None
        for path in candidate_ckpts:
            if os.path.exists(path):
                ckpt_path = path
                break
        if ckpt_path is None:
            ckpt_path = candidate_ckpts[0]
    else:
        if num_of_paths == 0:
            ckpt_path = os.path.join(out_dir, f'{init_ckpt}_ckpt_maze.pt')
        else:
            ckpt_path = os.path.join(out_dir, f'{init_ckpt}_ckpt_maze_{num_of_paths}.pt')
    print(f"Resuming training from {ckpt_path}")
    # resume training from a checkpoint.
    checkpoint = torch.load(ckpt_path, map_location=device)
    checkpoint_model_args = checkpoint['model_args']
    # force these config attributes to be equal otherwise we can't even resume training
    # the rest of the attributes (e.g. dropout) can stay as desired from command line
    if model_type in ('transformer', 'transformer-rope'):
        for k in ['n_layer', 'n_head', 'n_embd', 'block_size', 'bias', 'vocab_size']:
            model_args[k] = checkpoint_model_args[k]
        # Restore optional transformer-variant flags from checkpoint if present
        for k in ['post_gru', 'per_block_nls', 'dyadic_attn', 'dyadic_hybrid']:
            if k in checkpoint_model_args:
                model_args[k] = checkpoint_model_args[k]
    elif model_type == 'transformer-nextlat':
        for k in ['model_type', 'n_layer', 'n_head', 'n_embd', 'block_size', 'bias',
                  'vocab_size', 'use_flash', 'dropout', 'mlp_hidden_dim',
                  'nextlat_horizon', 'lambda_h', 'lambda_kl']:
            if k in checkpoint_model_args:
                model_args[k] = checkpoint_model_args[k]
    elif model_type == 'gru':
        for k in ['model_type', 'n_layer', 'n_embd', 'vocab_size', 'dropout', 'bias', 'pad_id']:
            if k in checkpoint_model_args:
                model_args[k] = checkpoint_model_args[k]
    elif model_type == 'gated-deltanet':
        for k in ['model_type', 'n_layer', 'n_embd', 'vocab_size', 'pad_id',
                  'head_dim', 'expand_v', 'conv_size']:
            if k in checkpoint_model_args:
                model_args[k] = checkpoint_model_args[k]
    else:  # mamba / mamba2
        for k in ['model_type', 'n_layer', 'n_embd', 'vocab_size', 'pscan', 'use_cuda',
                  'pad_id', 'd_state', 'expand_factor', 'd_conv', 'dt_rank',
                  'headdim', 'ngroups']:
            if k in checkpoint_model_args:
                model_args[k] = checkpoint_model_args[k]
    # create the model
    model = build_model(model_args)
    state_dict = checkpoint['model']
    # fix the keys of the state dictionary :(
    # honestly no idea how checkpoints sometimes get this prefix, have to debug more
    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)
    iter_num = checkpoint['iter_num']
    best_val_loss = checkpoint['best_val_loss']
elif init_from.startswith('gpt2'):
    print(f"Initializing from OpenAI GPT-2 weights: {init_from}")
    override_args = dict(dropout=dropout)
    model = GPT.from_pretrained(init_from, override_args)
    for k in ['n_layer', 'n_head', 'n_embd', 'block_size', 'bias', 'vocab_size']:
        model_args[k] = getattr(model.config, k)

if model_type in ('transformer', 'transformer-rope', 'transformer-nextlat') and block_size < model.config.block_size:
    model.crop_block_size(block_size)
    model_args['block_size'] = block_size # so that the checkpoint will have the right value
model.to(device)

# NextLat: the latent dynamics model is encapsulated inside the
# transformer-nextlat module (model.latent_model), covered by the single
# optimizer / checkpoint below.
if use_nextlat:
    print(f"NextLat (encapsulated) enabled: horizon={nextlat_horizon}, lambda_h={lambda_h}, lambda_kl={lambda_kl}, mlp_hidden_dim={args.mlp_hidden_dim if args.mlp_hidden_dim is not None else 2 * n_embd}")

if use_post_gru:
    gru_params = sum(
        p.numel()
        for block in model.transformer.h
        if block.per_block_gru is not None
        for p in block.per_block_gru.parameters()
    )
    print(f"PostGRU enabled (per-block): total GRU parameters: {gru_params / 1e6:.4f}M")

if use_nls:
    nls_params = sum(
        p.numel()
        for block in model.transformer.h
        if block.per_block_nls is not None
        for p in block.per_block_nls.parameters()
    )
    # Number of dyadic-doubling levels actually traversed for this block_size:
    # stride starts at 1 and doubles until stride >= L, so levels = ceil(log2(L)).
    nls_levels = max(1, math.ceil(math.log2(block_size))) if block_size > 1 else 0
    nls_blocks = sum(1 for block in model.transformer.h if block.per_block_nls is not None)
    nls_share = all(
        block.per_block_nls.share
        for block in model.transformer.h
        if block.per_block_nls is not None
    )
    print(
        f"NLS enabled (per-block): {nls_blocks} blocks, "
        f"{nls_levels} scan levels per block (block_size={block_size}, share={nls_share}), "
        f"total NLS parameters: {nls_params / 1e6:.4f}M"
    )

# Auxiliary (node, facing) linear head reading the chosen block's output.
aux_head = None
if use_aux:
    import torch.nn as nn
    aux_head = nn.Linear(n_embd, AUX_NUM_STATES, bias=True).to(device)
    _aux_unit = 'block' if model_type == 'transformer' else 'layer'
    print(f"Auxiliary supervision (Task {aux_task}): {_aux_unit} {aux_layer + 1} (1-based) output -> (node, facing) "
          f"{AUX_NUM_STATES}-way, lambda={aux_lambda}")

# optimizer
optimizer = model.configure_optimizers(weight_decay, learning_rate, (beta1, beta2), device_type)
if use_aux:
    optimizer.add_param_group({'params': [aux_head.weight], 'weight_decay': weight_decay})
    optimizer.add_param_group({'params': [aux_head.bias], 'weight_decay': 0.0})
if init_from == 'resume':
    optimizer.load_state_dict(checkpoint['optimizer'])
    if use_aux and 'aux_head' in checkpoint:
        aux_head.load_state_dict(checkpoint['aux_head'])

# initialize a GradScaler. If enabled=False scaler is a no-op
scaler = torch.cuda.amp.GradScaler(enabled=(dtype == 'float16'))
if init_from == 'resume' and 'scaler' in checkpoint:
    scaler.load_state_dict(checkpoint['scaler'])

# restore random states for reproducibility
if init_from == 'resume':
    if 'torch_rng_state' in checkpoint:
        # RNG state must be a ByteTensor on CPU
        torch.set_rng_state(checkpoint['torch_rng_state'].cpu())
    if 'cuda_rng_state' in checkpoint and checkpoint['cuda_rng_state'] is not None and torch.cuda.is_available():
        # CUDA RNG state must also be a ByteTensor on CPU before setting
        torch.cuda.set_rng_state(checkpoint['cuda_rng_state'].cpu())
    if 'numpy_rng_state' in checkpoint:
        np.random.set_state(checkpoint['numpy_rng_state'])

checkpoint = None # free up memory

# compile the model
if compile and model_type in ('mamba', 'mamba2', 'gated-deltanet'):
    print(f"[Info] --model {model_type} uses a custom parallel-scan autograd Function; "
          "disabling torch.compile for stability.")
    compile = False
if compile and use_aux:
    print("[Info] --aux_layer hooks into the model's internal blocks; disabling torch.compile.")
    compile = False
if use_aux and ddp:
    raise ValueError('--aux_layer state-supervision does not support DDP; run on a single GPU.')
if compile:
    print("compiling the model... (takes a ~minute)")
    unoptimized_model = model
    model = torch.compile(model) # requires PyTorch 2.0

# wrap model into DDP container
if ddp:
    model = DDP(model, device_ids=[ddp_local_rank])

# helps estimate an arbitrarily accurate loss over either split using many batches
@torch.no_grad()
def estimate_loss():
    out = {}
    model.eval()
    for split in ['train', 'val']:
        losses = torch.zeros(eval_iters)
        for k in range(eval_iters):
            X, Y, _ = get_batch(split)
            with ctx:
                _, loss = model(X, Y)
            losses[k] = loss.item()
        out[split] = losses.mean()
    model.train()
    return out

# learning rate decay scheduler (cosine with warmup)
def get_lr(it):
    # 1) linear warmup for warmup_iters steps
    if it < warmup_iters:
        return learning_rate * it / warmup_iters
    # 2) if it > lr_decay_iters, return min learning rate
    if it > lr_decay_iters:
        return min_lr
    # 3) in between, use cosine decay down to min learning rate
    decay_ratio = (it - warmup_iters) / (lr_decay_iters - warmup_iters)
    assert 0 <= decay_ratio <= 1
    coeff = 0.5 * (1.0 + math.cos(math.pi * decay_ratio)) # coeff ranges 0..1
    return min_lr + coeff * (learning_rate - min_lr)

def open_and_append(filename, text):
    with open(filename, 'a') as file:
        file.write(text + '\n')

# logging
if wandb_log and master_process:
    import wandb
    wandb.init(project=wandb_project, name=wandb_run_name, config=config)

# Helper function to format seconds into HH:MM:SS
def format_time(seconds):
    hours = int(seconds // 3600)
    minutes = int((seconds % 3600) // 60)
    secs = int(seconds % 60)
    return f"{hours:02d}:{minutes:02d}:{secs:02d}"

# training loop
X, Y, S = get_batch('train') # fetch the very first batch
t0 = time.time()
start_time = time.time()  # record overall training start time
local_iter_num = 0 # number of iterations in the lifetime of this process
raw_model = model.module if ddp else model # unwrap DDP container if needed
running_mfu = -1.0
accuracy = []
corrects = []
totals = []


def forward_with_aux(idx, targets, state_targets):
    """Forward that also returns the auxiliary (node, facing) loss computed from

    the chosen block/layer's output. Branches on model_type: transformer mirrors

    GPT.forward, gru mirrors GRU.forward for the LM path."""
    if model_type == 'gru':
        h = raw_model.drop(raw_model.embedding(idx))
        h_aux = None
        for i, layer in enumerate(raw_model.layers):
            h = layer(h)
            if i == aux_layer:
                h_aux = h
        h = raw_model.out_norm(h)
        logits = raw_model.lm_head(h)
    else:
        b, t = idx.size()
        pos = torch.arange(0, t, dtype=torch.long, device=idx.device).unsqueeze(0)
        h = raw_model.transformer.drop(raw_model.transformer.wte(idx) + raw_model.transformer.wpe(pos))
        h_aux = None
        for i, block in enumerate(raw_model.transformer.h):
            h = block(h)
            if i == aux_layer:
                h_aux = h
        h = raw_model.transformer.ln_f(h)
        logits = raw_model.lm_head(h)
    lm_loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=AUX_PAD_ID)
    aux_logits = aux_head(h_aux)
    aux_loss = F.cross_entropy(aux_logits.view(-1, AUX_NUM_STATES), state_targets.view(-1), ignore_index=AUX_IGNORE)
    with torch.no_grad():
        mask = state_targets.view(-1) != AUX_IGNORE
        if mask.any():
            pred = aux_logits.view(-1, AUX_NUM_STATES).argmax(-1)
            aux_acc = (pred[mask] == state_targets.view(-1)[mask]).float().mean()
        else:
            aux_acc = torch.zeros((), device=idx.device)
    return logits, lm_loss, aux_loss, aux_acc

# Consolidated training-config summary
if master_process:
    variant_flags = []
    if use_nextlat: variant_flags.append('NextLat')
    if use_post_gru: variant_flags.append('PostGRU')
    if use_nls: variant_flags.append('NLS')
    if use_dyadic_attn: variant_flags.append('DyadicAttn')
    if use_dyadic_hybrid: variant_flags.append('DyadicHybrid')
    if use_aux: variant_flags.append(f'AuxState{aux_task}(L{aux_layer + 1}{aux_lambda})')
    variant_str = '+'.join(variant_flags) if variant_flags else 'baseline'
    total_params = sum(p.numel() for p in raw_model.parameters())
    print("=" * 70)
    print("TRAINING CONFIGURATION")
    print("=" * 70)
    print(f"  Variant         : {variant_str}")
    print(f"  Dataset         : {dataset} | tasks={tasks_str} | path_type={args.path_type}"
          f" | num_nodes={num_nodes} | no_task_tag={no_task_tag}")
    print(f"  Model           : n_layer={n_layer}, n_head={n_head}, n_embd={n_embd},"
          f" block_size={block_size}, vocab_size={meta['vocab_size']}, bias={bias}, dropout={dropout}")
    print(f"  Total params    : {total_params / 1e6:.2f}M")
    print(f"  Optim           : AdamW lr={learning_rate} (min={min_lr}), wd={weight_decay},"
          f" betas=({beta1},{beta2}), grad_clip={grad_clip}")
    print(f"  Schedule        : max_iters={max_iters}, warmup={warmup_iters},"
          f" decay_iters={lr_decay_iters}, decay_lr={decay_lr}")
    print(f"  Batch / dtype   : batch_size={batch_size}, grad_accum={gradient_accumulation_steps},"
          f" tokens/iter={tokens_per_iter:,}, dtype={dtype}, compile={compile}, ddp={ddp} (world={ddp_world_size})")
    print(f"  Init from       : {init_from}" + (f" (iter {init_ckpt})" if init_from == 'resume' else ""))
    if use_nextlat:
        print(f"  NextLat         : horizon={nextlat_horizon}, lambda_h={lambda_h},"
              f" lambda_kl={lambda_kl}, mlp_hidden_dim={args.mlp_hidden_dim or 2 * n_embd}")
    if use_post_gru:
        print(f"  PostGRU         : per-block GRU enabled")
    if use_nls:
        print(f"  NLS             : per-block Non-Linear prefix Scan enabled")
    if use_dyadic_attn:
        recommended_layers = max(1, math.ceil(math.log2(block_size))) if block_size > 1 else 1
        warn = '' if n_layer == recommended_layers else f' [WARNING: for fair comparison set n_layer={recommended_layers} (= ceil(log2({block_size})))]'
        strides = [1 << i for i in range(n_layer)]
        print(f"  DyadicAttn      : fixed 0.5/0.5 attention; per-layer strides={strides}{warn}")
    if use_dyadic_hybrid:
        L_levels = max(1, math.ceil(math.log2(block_size))) if block_size > 1 else 1
        total_blocks = n_layer * (1 + L_levels)
        unit_strides = [1 << k for k in range(L_levels)]
        print(f"  DyadicHybrid    : {n_layer} units of (1 normal + {L_levels} DyadicAttn) = {total_blocks} physical blocks; per-unit dyadic strides={unit_strides}")
    print(f"  Output dir      : {out_dir}")
    print("=" * 70)
    logger.info(f"TRAINING CONFIG: variant={variant_str}, n_layer={n_layer}, n_head={n_head},"
                f" n_embd={n_embd}, block_size={block_size}, batch_size={batch_size},"
                f" max_iters={max_iters}, lr={learning_rate}, params={total_params/1e6:.2f}M")
    open_and_append(log_file_name,
                    f"TRAINING CONFIG: variant={variant_str}, n_layer={n_layer}, n_head={n_head},"
                    f" n_embd={n_embd}, block_size={block_size}, batch_size={batch_size},"
                    f" max_iters={max_iters}, lr={learning_rate}, params={total_params/1e6:.2f}M")

while True:

    # determine and set the learning rate for this iteration
    lr = get_lr(iter_num) if decay_lr else learning_rate
    for param_group in optimizer.param_groups:
        param_group['lr'] = lr

    # evaluate the loss on train/val sets and write checkpoints
    if iter_num % checkpoint_interval == 0 and master_process:
        losses = None
        if validation and eval_interval is not None:
            losses = estimate_loss()
            print(f"step {iter_num}: train loss {losses['train']:.4f}, val loss {losses['val']:.4f}")
            logger.info(f"step {iter_num}: train loss {losses['train']:.4f}, val loss {losses['val']:.4f}")
            open_and_append(log_file_name, f"step {iter_num}: train loss {losses['train']:.4f}, val loss {losses['val']:.4f}")
            if wandb_log:
                wandb.log({
                    "iter": iter_num,
                    "train/loss": losses['train'],
                    "val/loss": losses['val'],
                    "lr": lr,
                    "mfu": running_mfu*100, # convert to percentage
                })

        # Decide whether to save checkpoint
        save_due_to_val = validation and losses is not None and losses['val'] < best_val_loss
        save_due_to_policy = always_save_checkpoint

        if (save_due_to_val or save_due_to_policy) and iter_num > 0:
            if validation and losses is not None:
                best_val_loss = min(best_val_loss, losses['val'])
            checkpoint = {
                'model': raw_model.state_dict(),
                'optimizer': optimizer.state_dict(),
                'model_args': model_args,
                'model_type': model_type,
                'iter_num': iter_num,
                'best_val_loss': best_val_loss,
                'config': config,
                'scaler': scaler.state_dict(),
                'torch_rng_state': torch.get_rng_state(),
                'cuda_rng_state': torch.cuda.get_rng_state() if torch.cuda.is_available() else None,
                'numpy_rng_state': np.random.get_state(),
            }
            if use_aux:
                checkpoint['aux_head'] = aux_head.state_dict()
                checkpoint['aux_layer'] = aux_layer
                checkpoint['aux_lambda'] = aux_lambda
            print(f"saving checkpoint to {out_dir} (validation={'on' if validation else 'off'})")
            logger.info(f"saving checkpoint to {out_dir}")
            open_and_append(log_file_name, f"saving checkpoint to {out_dir}")
            if multitasks:
                torch.save(checkpoint, os.path.join(out_dir, f'{iter_num}_ckpt_maze_{tasks_tag}_{train_label}.pt'))
            elif num_of_paths == 0:
                torch.save(checkpoint, os.path.join(out_dir, f'{iter_num}_ckpt_maze.pt'))
            else:
                torch.save(checkpoint, os.path.join(out_dir, f'{iter_num}_ckpt_maze_{num_of_paths}.pt'))

    # if iter_num % test_interval == 0 and master_process:
    #     correct, tot = test_model()
    #     corrects.append(correct)
    #     totals.append(tot)

    if iter_num == 0 and eval_only:
        break

    # forward backward update, with optional gradient accumulation to simulate larger batch size
    # and using the GradScaler if data type is float16
    for micro_step in range(gradient_accumulation_steps):
        if ddp:
            model.require_backward_grad_sync = (micro_step == gradient_accumulation_steps - 1)
        with ctx:
            if use_aux:
                logits, lm_loss, aux_loss, aux_acc = forward_with_aux(X, Y, S)
                loss = (lm_loss + aux_lambda * aux_loss) / gradient_accumulation_steps
            elif use_nextlat:
                total_loss, loss_nt, loss_nh, loss_kl = raw_model.forward_nextlat(
                    X, Y, horizon=nextlat_horizon,
                    lambda_h=lambda_h, lambda_kl=lambda_kl)
                loss = total_loss / gradient_accumulation_steps
            else:
                logits, loss = model(X, Y)
                loss = loss / gradient_accumulation_steps # scale the loss to account for gradient accumulation
        X, Y, S = get_batch('train')
        # backward pass, with gradient scaling if training in fp16
        scaler.scale(loss).backward()
    # clip the gradient
    if grad_clip != 0.0:
        scaler.unscale_(optimizer)
        clip_params = list(model.parameters()) + (list(aux_head.parameters()) if use_aux else [])
        torch.nn.utils.clip_grad_norm_(clip_params, grad_clip)
    scaler.step(optimizer)
    scaler.update()
    optimizer.zero_grad(set_to_none=True)

    # timing and logging
    t1 = time.time()
    dt = t1 - t0
    t0 = t1
    if iter_num % log_interval == 0 and master_process:
        lossf = loss.item() * gradient_accumulation_steps
        if local_iter_num >= 5: # let the training loop settle a bit
            mfu = raw_model.estimate_mfu(batch_size * gradient_accumulation_steps, dt)
            running_mfu = mfu if running_mfu == -1.0 else 0.9*running_mfu + 0.1*mfu
        # Compute elapsed and estimated remaining time
        elapsed = time.time() - start_time
        if iter_num > 0:
            eta = (elapsed / iter_num) * (max_iters - iter_num)
            elapsed_str = format_time(elapsed)
            eta_str = format_time(eta)
            time_info = f"elapsed {elapsed_str}, eta {eta_str}"
        else:
            time_info = "elapsed 00:00:00, eta --:--:--"
        if use_nextlat:
            print(f"iter {iter_num}: loss {lossf:.4f} (nt={loss_nt.item():.4f}, nh={loss_nh.item():.4f}, kl={loss_kl.item():.4f}), time {dt*1000:.2f}ms, mfu {running_mfu*100:.2f}%, {time_info}")
        elif use_aux:
            print(f"iter {iter_num}: loss {lossf:.4f} (lm={lm_loss.item():.4f}, aux={aux_loss.item():.4f}, aux_acc={aux_acc.item()*100:.1f}%), time {dt*1000:.2f}ms, mfu {running_mfu*100:.2f}%, {time_info}")
        else:
            print(f"iter {iter_num}: loss {lossf:.4f}, time {dt*1000:.2f}ms, mfu {running_mfu*100:.2f}%, {time_info}")
        logger.info(f"iter {iter_num}: loss {lossf:.4f}")
        open_and_append(log_file_name, f"iter {iter_num}: loss {lossf:.4f}")
    iter_num += 1
    local_iter_num += 1

    if iter_num > max_iters:
        break

torch.save(torch.tensor(corrects).cpu(), os.path.join(out_dir, f'corrects_maze.pt'))
torch.save(torch.tensor(totals).cpu(), os.path.join(out_dir, f'totals_maze.pt'))

# Final total training time summary
if master_process:
    total_elapsed = time.time() - start_time
    total_str = format_time(total_elapsed)
    avg_iter_ms = (total_elapsed / max(1, iter_num)) * 1000
    summary = (f"Total training time: {total_str} ({total_elapsed:.1f}s) "
               f"over {iter_num} iters, avg {avg_iter_ms:.2f} ms/iter")
    print(summary)
    logger.info(summary)
    open_and_append(log_file_name, summary)

if ddp:
    destroy_process_group()