File size: 59,166 Bytes
4d2e4b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
"""
Graph Neural Network models for Ruby code complexity prediction.

This module contains PyTorch Geometric models for learning from
Ruby AST structures with performance optimizations.
"""

import torch
import torch.nn.functional as F
from torch_geometric.nn import GCNConv, SAGEConv, GATConv, GINConv, GraphConv, global_mean_pool
from torch_geometric.data import Data, Batch
import torch_geometric
from typing import Dict
try:
    from sentence_transformers import SentenceTransformer
    SENTENCE_TRANSFORMERS_AVAILABLE = True
except ImportError:
    SENTENCE_TRANSFORMERS_AVAILABLE = False

# Performance optimization: Cache CUDA availability
CUDA_AVAILABLE = torch.cuda.is_available()


class RubyComplexityGNN(torch.nn.Module):
    """
    Graph Neural Network for predicting Ruby method complexity.
    
    This model uses Graph Convolutional Networks (GCN) or GraphSAGE layers
    to learn from Abstract Syntax Tree representations of Ruby methods.
    """
    
    def __init__(self, input_dim: int, hidden_dim: int = 64, num_layers: int = 3, 
                 conv_type: str = 'GCN', dropout: float = 0.1):
        """
        Initialize the GNN model.
        
        Args:
            input_dim: Dimension of input node features
            hidden_dim: Hidden layer dimension
            num_layers: Number of convolutional layers
            conv_type: Type of convolution ('GCN', 'SAGE', 'GAT', 'GIN', 'GraphConv')
            dropout: Dropout probability for regularization
        """
        super().__init__()
        
        supported = ['GCN', 'SAGE', 'GAT', 'GIN', 'GraphConv']
        if conv_type not in supported:
            raise ValueError(f"conv_type must be one of {supported}")
        
        self.num_layers = num_layers
        self.conv_type = conv_type
        self.dropout = dropout
        self.convs = torch.nn.ModuleList()
        
        def _make_conv(in_dim, out_dim):
            if conv_type == 'GCN':
                return GCNConv(in_dim, out_dim)
            elif conv_type == 'SAGE':
                return SAGEConv(in_dim, out_dim)
            elif conv_type == 'GAT':
                return GATConv(in_dim, out_dim, heads=1)
            elif conv_type == 'GIN':
                mlp = torch.nn.Sequential(
                    torch.nn.Linear(in_dim, out_dim),
                    torch.nn.ReLU(),
                    torch.nn.Linear(out_dim, out_dim),
                )
                return GINConv(mlp)
            elif conv_type == 'GraphConv':
                return GraphConv(in_dim, out_dim)
        
        # First layer
        self.convs.append(_make_conv(input_dim, hidden_dim))
        
        # Hidden layers
        for _ in range(num_layers - 2):
            self.convs.append(_make_conv(hidden_dim, hidden_dim))
            
        # Last layer
        if num_layers > 1:
            self.convs.append(_make_conv(hidden_dim, hidden_dim))
        
        # Output layer for complexity prediction
        self.predictor = torch.nn.Linear(hidden_dim, 1)
        
    def forward(self, data: Data, return_embedding: bool = False) -> torch.Tensor:
        """
        Forward pass through the network.
        
        Args:
            data: PyTorch Geometric Data object containing graph
            return_embedding: If True, return graph embedding instead of prediction
            
        Returns:
            Complexity prediction tensor of shape (batch_size, 1) or
            Graph embedding tensor of shape (batch_size, hidden_dim) if return_embedding=True
        """
        x, edge_index, batch = data.x, data.edge_index, data.batch
        
        # Apply convolution layers with ReLU activation and dropout
        for i, conv in enumerate(self.convs):
            x = conv(x, edge_index)
            if i < len(self.convs) - 1:  # No activation after last layer
                x = F.relu(x)
                x = F.dropout(x, p=self.dropout, training=self.training)
        
        # Global pooling to get graph-level representation
        embedding = global_mean_pool(x, batch)
        
        if return_embedding:
            return embedding
        
        # Predict complexity
        return self.predictor(embedding)
    
    def get_model_info(self) -> str:
        """
        Get information about the model configuration.
        
        Returns:
            String describing the model architecture
        """
        return (f"RubyComplexityGNN({self.conv_type}, "
                f"layers={self.num_layers}, "
                f"dropout={self.dropout})")


class ASTDecoder(torch.nn.Module):
    """
    GNN-based decoder for reconstructing Abstract Syntax Trees from embeddings.
    
    This module takes a graph embedding and autoregressively generates node features
    and edge structure to reconstruct an AST.
    """
    
    def __init__(self, embedding_dim: int, output_node_dim: int, hidden_dim: int = 256, 
                 num_layers: int = 5, max_nodes: int = 100, conv_type: str = 'GCN',
                 gradient_checkpointing: bool = False):
        """
        Initialize the AST decoder.
        
        Args:
            embedding_dim: Dimension of input graph embedding
            output_node_dim: Dimension of output node features
            hidden_dim: Hidden layer dimension for GNN layers.
            num_layers: Number of decoder GNN layers.
            max_nodes: Maximum number of nodes to generate.
            conv_type: The type of GNN layer to use ('GCN', 'SAGE', 'GAT', 'GIN', 'GraphConv').
            gradient_checkpointing: Whether to use gradient checkpointing for memory efficiency.
        """
        super().__init__()
        
        self.embedding_dim = embedding_dim
        self.output_node_dim = output_node_dim
        self.hidden_dim = hidden_dim
        self.num_layers = num_layers
        self.max_nodes = max_nodes
        self.gradient_checkpointing = gradient_checkpointing
        
        self.embedding_transform = torch.nn.Linear(embedding_dim, hidden_dim)
        
        self.convs = torch.nn.ModuleList()
        current_dim = hidden_dim

        for i in range(num_layers):
            if conv_type == 'GAT':
                heads = 4
                conv = GATConv(current_dim, hidden_dim, heads=heads)
                current_dim = hidden_dim * heads
            elif conv_type == 'GIN':
                mlp = torch.nn.Sequential(
                    torch.nn.Linear(current_dim, current_dim),
                    torch.nn.ReLU(),
                    torch.nn.Linear(current_dim, current_dim)
                )
                conv = GINConv(mlp)
            elif conv_type == 'SAGE':
                conv = SAGEConv(current_dim, current_dim)
            elif conv_type == 'GCN':
                conv = GCNConv(current_dim, current_dim)
            elif conv_type == 'GraphConv':
                conv = GraphConv(current_dim, current_dim)
            else:
                raise ValueError(f"Unsupported conv_type: {conv_type}")
            
            self.convs.append(conv)

        self.node_output = torch.nn.Linear(current_dim, output_node_dim)
        self.parent_predictor = torch.nn.Linear(current_dim, max_nodes)
        
    def forward(self, embedding: torch.Tensor, num_nodes_per_graph: torch.Tensor) -> dict:
        """
        Forward pass to decode a batch of embeddings into AST structures.
        
        Args:
            embedding: Graph embedding tensor of shape [batch_size, embedding_dim].
            num_nodes_per_graph: Tensor of shape [batch_size] with the number of nodes for each graph.
            
        Returns:
            Dictionary containing batched node features and parent predictions.
        """
        batch_size = embedding.size(0)
        device = embedding.device
        
        # Use torch.repeat_interleave to expand each graph's embedding
        # to match the number of nodes in that graph.
        # This is the core of the batch-aware processing.
        node_features = self.embedding_transform(embedding)
        node_features = node_features.repeat_interleave(num_nodes_per_graph, dim=0)

        # Vectorized edge construction for sequential edges within each graph.
        # This approach avoids loops over graphs in the batch, creating all edges
        # at once for efficiency.
        num_edges_per_graph = torch.clamp(num_nodes_per_graph - 1, min=0)
        total_edges = torch.sum(num_edges_per_graph).item()

        if total_edges == 0:
            edge_index = torch.empty((2, 0), dtype=torch.long, device=device)
        else:
            # Calculate node offsets for each graph
            node_offsets = torch.cat([torch.zeros(1, device=device, dtype=num_nodes_per_graph.dtype), 
                                    torch.cumsum(num_nodes_per_graph[:-1], dim=0)])
            
            # Efficient edge index computation for sequential nodes
            # Pre-allocate tensors to avoid repeated allocations
            total_edges = num_edges_per_graph.sum().item()
            
            # Determine which graph each edge belongs to
            graph_indices = torch.repeat_interleave(torch.arange(len(num_nodes_per_graph), device=device), num_edges_per_graph)
            
            # Calculate the starting edge index for each graph
            edge_offsets = torch.cat([torch.zeros(1, device=device, dtype=num_edges_per_graph.dtype), 
                                    torch.cumsum(num_edges_per_graph[:-1], dim=0)])
            
            # Compute local (within-graph) source indices more efficiently
            src_in_graph = torch.arange(total_edges, device=device) - edge_offsets[graph_indices]
            
            # Get the starting node index for each edge's graph
            edge_node_offsets = node_offsets[graph_indices]
            
            # Compute global source and destination indices
            src = edge_node_offsets + src_in_graph
            dst = src + 1
            
            edge_index = torch.stack([src, dst], dim=0)

        # GNNs are typically undirected, so we add reverse edges.
        edge_index = torch_geometric.utils.to_undirected(edge_index)

        # Apply GNN layers with optional gradient checkpointing
        x = node_features
        if self.gradient_checkpointing and self.training:
            # Use gradient checkpointing for memory efficiency during training
            def create_custom_forward(module):
                def custom_forward(*inputs):
                    return module(*inputs)
                return custom_forward
            
            for conv in self.convs:
                x = torch.utils.checkpoint.checkpoint(
                    create_custom_forward(conv), x, edge_index, use_reentrant=False
                )
                x = F.relu(x)
        else:
            # Standard forward pass
            for conv in self.convs:
                x = conv(x, edge_index)
                x = F.relu(x)  # In-place for memory efficiency
        
        # Predict the final node features and parent logits for all nodes in the batch.
        output_node_features = self.node_output(x)
        parent_logits = self.parent_predictor(x)
        
        return {
            'node_features': output_node_features, # Shape: [total_nodes, feature_dim]
            'parent_logits': parent_logits         # Shape: [total_nodes, max_nodes]
        }


class TreeAwareASTDecoder(torch.nn.Module):
    """
    Tree-topology-aware AST decoder.

    Unlike ASTDecoder which constructs sequential chain edges (0→1→2→…),
    this decoder uses the actual AST tree structure for GNN message passing.

    Three edge modes:
      - 'chain':          Legacy sequential edges (same as ASTDecoder).
      - 'teacher_forced': Uses ground-truth AST edges during training.
      - 'iterative':      Two-pass: chain edges → predict parents → rebuild
                          tree edges → refine predictions.  Fully feed-forward.
    """

    def __init__(self, embedding_dim: int, output_node_dim: int,
                 hidden_dim: int = 256, num_layers: int = 5,
                 max_nodes: int = 100, conv_type: str = 'GCN',
                 edge_mode: str = 'teacher_forced',
                 gradient_checkpointing: bool = False):
        super().__init__()
        self.embedding_dim = embedding_dim
        self.output_node_dim = output_node_dim
        self.hidden_dim = hidden_dim
        self.num_layers = num_layers
        self.max_nodes = max_nodes
        self.edge_mode = edge_mode
        self.gradient_checkpointing = gradient_checkpointing

        self.embedding_transform = torch.nn.Linear(embedding_dim, hidden_dim)

        # Primary GNN stack
        self.convs = torch.nn.ModuleList()
        current_dim = hidden_dim
        for _ in range(num_layers):
            conv, current_dim = self._make_conv(conv_type, current_dim, hidden_dim)
            self.convs.append(conv)

        self.node_output = torch.nn.Linear(current_dim, output_node_dim)
        self.parent_predictor = torch.nn.Linear(current_dim, max_nodes)

        # Refinement GNN stack (only used in iterative mode)
        if edge_mode == 'iterative':
            self.refine_convs = torch.nn.ModuleList()
            ref_dim = current_dim
            for _ in range(max(num_layers // 2, 1)):
                conv, ref_dim = self._make_conv(conv_type, ref_dim, hidden_dim)
                self.refine_convs.append(conv)
            self.refine_node_output = torch.nn.Linear(ref_dim, output_node_dim)
            self.refine_parent_predictor = torch.nn.Linear(ref_dim, max_nodes)

    @staticmethod
    def _make_conv(conv_type: str, in_dim: int, hidden_dim: int):
        if conv_type == 'GAT':
            heads = 4
            return GATConv(in_dim, hidden_dim, heads=heads), hidden_dim * heads
        elif conv_type == 'GIN':
            mlp = torch.nn.Sequential(
                torch.nn.Linear(in_dim, in_dim),
                torch.nn.ReLU(),
                torch.nn.Linear(in_dim, in_dim),
            )
            return GINConv(mlp), in_dim
        elif conv_type == 'SAGE':
            return SAGEConv(in_dim, in_dim), in_dim
        elif conv_type == 'GCN':
            return GCNConv(in_dim, in_dim), in_dim
        elif conv_type == 'GraphConv':
            return GraphConv(in_dim, in_dim), in_dim
        else:
            raise ValueError(f"Unsupported conv_type: {conv_type}")

    # ------------------------------------------------------------------
    # Edge construction helpers
    # ------------------------------------------------------------------

    @staticmethod
    def _build_chain_edges(num_nodes_per_graph: torch.Tensor) -> torch.Tensor:
        """Build sequential chain edges (legacy behaviour)."""
        device = num_nodes_per_graph.device
        num_edges_per_graph = torch.clamp(num_nodes_per_graph - 1, min=0)
        total_edges = num_edges_per_graph.sum().item()
        if total_edges == 0:
            return torch.empty((2, 0), dtype=torch.long, device=device)

        node_offsets = torch.cat([
            torch.zeros(1, device=device, dtype=num_nodes_per_graph.dtype),
            torch.cumsum(num_nodes_per_graph[:-1], dim=0),
        ])
        graph_indices = torch.repeat_interleave(
            torch.arange(len(num_nodes_per_graph), device=device),
            num_edges_per_graph,
        )
        edge_offsets = torch.cat([
            torch.zeros(1, device=device, dtype=num_edges_per_graph.dtype),
            torch.cumsum(num_edges_per_graph[:-1], dim=0),
        ])
        src_in_graph = torch.arange(total_edges, device=device) - edge_offsets[graph_indices]
        edge_node_offsets = node_offsets[graph_indices]
        src = edge_node_offsets + src_in_graph
        dst = src + 1
        return torch.stack([src, dst], dim=0)

    @staticmethod
    def _parents_to_edges(parent_logits: torch.Tensor,
                          num_nodes_per_graph: torch.Tensor) -> torch.Tensor:
        """Convert per-node parent logits to a hard edge_index (argmax)."""
        device = parent_logits.device
        total_nodes = parent_logits.size(0)
        max_nodes = parent_logits.size(1)

        # Compute graph membership and node offsets
        batch_vec = torch.repeat_interleave(
            torch.arange(len(num_nodes_per_graph), device=device),
            num_nodes_per_graph,
        )
        node_offsets = torch.cat([
            torch.zeros(1, device=device, dtype=num_nodes_per_graph.dtype),
            torch.cumsum(num_nodes_per_graph[:-1], dim=0),
        ])

        # Mask out logits for positions beyond each graph's node count
        mask = torch.arange(max_nodes, device=device).unsqueeze(0).expand(total_nodes, -1)
        graph_sizes = num_nodes_per_graph[batch_vec].unsqueeze(1)
        parent_logits = parent_logits.clone()
        parent_logits[mask >= graph_sizes] = float('-inf')

        # Local parent index → global parent index
        local_parent = parent_logits.argmax(dim=1)  # [total_nodes]
        global_parent = local_parent + node_offsets[batch_vec]

        # Node 0 of each graph (the root) has no parent — remove those edges
        local_idx = torch.arange(total_nodes, device=device) - node_offsets[batch_vec]
        is_root = local_idx == 0
        src = global_parent[~is_root]
        dst = torch.arange(total_nodes, device=device)[~is_root]
        return torch.stack([src, dst], dim=0).long()

    # ------------------------------------------------------------------
    # Forward
    # ------------------------------------------------------------------

    def _apply_convs(self, x, edge_index, convs):
        edge_index = torch_geometric.utils.to_undirected(edge_index)
        if self.gradient_checkpointing and self.training:
            def _make_fn(module):
                def fn(*inputs):
                    return module(*inputs)
                return fn
            for conv in convs:
                x = torch.utils.checkpoint.checkpoint(
                    _make_fn(conv), x, edge_index, use_reentrant=False,
                )
                x = F.relu(x)
        else:
            for conv in convs:
                x = conv(x, edge_index)
                x = F.relu(x)
        return x

    def forward(self, embedding: torch.Tensor,
                num_nodes_per_graph: torch.Tensor,
                gt_edge_index: torch.Tensor | None = None) -> dict:
        """
        Args:
            embedding: [batch_size, embedding_dim]
            num_nodes_per_graph: [batch_size]
            gt_edge_index: [2, num_edges] ground-truth AST edges (optional).
                           Required for teacher_forced mode during training.
        """
        device = embedding.device
        node_features = self.embedding_transform(embedding)
        node_features = node_features.repeat_interleave(num_nodes_per_graph, dim=0)

        # ---- choose edges for the first GNN pass ----
        if self.edge_mode == 'teacher_forced' and gt_edge_index is not None:
            first_pass_edges = gt_edge_index
        else:
            first_pass_edges = self._build_chain_edges(num_nodes_per_graph)

        x = self._apply_convs(node_features, first_pass_edges, self.convs)
        output_node_features = self.node_output(x)
        parent_logits = self.parent_predictor(x)

        # ---- optional second (refinement) pass ----
        if self.edge_mode == 'iterative':
            predicted_edges = self._parents_to_edges(parent_logits, num_nodes_per_graph)
            if predicted_edges.size(1) > 0:
                x2 = self._apply_convs(x, predicted_edges, self.refine_convs)
                output_node_features = self.refine_node_output(x2)
                parent_logits = self.refine_parent_predictor(x2)

        return {
            'node_features': output_node_features,
            'parent_logits': parent_logits,
        }


class AutoregressiveASTDecoder(torch.nn.Module):
    """
    Autoregressive decoder for generating Abstract Syntax Trees sequentially.
    
    This decoder generates AST nodes one by one, maintaining state across generation
    steps and considering both text description and current partial graph context.
    """
    
    def __init__(self, 
                 text_embedding_dim: int = 64,
                 graph_hidden_dim: int = 64,
                 state_hidden_dim: int = 128,
                 node_types: int = 74,
                 max_nodes: int = 100,
                 sequence_model: str = 'GRU'):  # Options: 'GRU', 'LSTM', 'Transformer'
        """
        Initialize the AutoregressiveASTDecoder.
        
        Args:
            text_embedding_dim: Dimension of text embeddings (from alignment model)
            graph_hidden_dim: Hidden dimension for graph encoding
            state_hidden_dim: Hidden dimension for sequential state
            node_types: Number of possible node types (also node feature dimension)
            max_nodes: Maximum number of nodes for connection prediction
            sequence_model: Type of sequence model ('GRU', 'LSTM', 'Transformer')
        """
        super().__init__()
        
        self.text_embedding_dim = text_embedding_dim
        self.graph_hidden_dim = graph_hidden_dim
        self.state_hidden_dim = state_hidden_dim
        self.node_types = node_types
        self.max_nodes = max_nodes
        self.sequence_model = sequence_model
        
        # Graph Context Encoder - GNN for processing partial graph structure
        # Note: Node features are node_types dimensional (one-hot encoded)
        self.graph_gnn_layers = torch.nn.ModuleList([
            GCNConv(node_types, graph_hidden_dim),
            GCNConv(graph_hidden_dim, graph_hidden_dim)
        ])
        self.graph_layer_norm = torch.nn.LayerNorm(graph_hidden_dim)
        self.graph_dropout = torch.nn.Dropout(0.1)
        
        # Sequential State Encoder - maintains state across generation steps
        input_size = text_embedding_dim + graph_hidden_dim
        
        if sequence_model == 'GRU':
            self.state_encoder = torch.nn.GRU(
                input_size=input_size,
                hidden_size=state_hidden_dim,
                num_layers=2,
                batch_first=True,
                dropout=0.1
            )
        elif sequence_model == 'LSTM':
            self.state_encoder = torch.nn.LSTM(
                input_size=input_size,
                hidden_size=state_hidden_dim,
                num_layers=2,
                batch_first=True,
                dropout=0.1
            )
        elif sequence_model == 'Transformer':
            # For transformer, we'll use a transformer encoder layer
            encoder_layer = torch.nn.TransformerEncoderLayer(
                d_model=state_hidden_dim,
                nhead=8,
                dim_feedforward=256,
                dropout=0.1,
                batch_first=True
            )
            self.state_encoder = torch.nn.TransformerEncoder(
                encoder_layer=encoder_layer,
                num_layers=4
            )
            # For transformer, we need to project input to state_hidden_dim
            self.input_projection = torch.nn.Linear(input_size, state_hidden_dim)
        else:
            raise ValueError(f"Unknown sequence model: {sequence_model}. Choose from 'GRU', 'LSTM', 'Transformer'")
        
        # Dual Prediction Heads
        
        # Predict next node type
        self.node_type_predictor = torch.nn.Linear(state_hidden_dim, node_types)
        
        # Predict connection to existing nodes
        self.connection_predictor = torch.nn.Sequential(
            torch.nn.Linear(state_hidden_dim, max_nodes),
            torch.nn.Sigmoid()  # Probability of connection to each existing node
        )
        
    def forward(self, text_embedding, partial_graph=None, hidden_state=None):
        """
        Forward pass for autoregressive AST generation.
        
        Args:
            text_embedding: (batch_size, text_embedding_dim) - Text description embedding
            partial_graph: Dict with keys 'x', 'edge_index', 'batch' - Current partial AST (optional)
            hidden_state: Previous hidden state for sequence model (optional)
            
        Returns:
            Dictionary containing:
                - node_type_logits: (batch_size, node_types) - Probabilities for next node type
                - connection_probs: (batch_size, max_nodes) - Connection probabilities
                - hidden_state: Updated hidden state
        """
        batch_size = text_embedding.size(0)
        device = text_embedding.device
        
        # 1. Encode current graph state using GNN
        if partial_graph is not None and 'x' in partial_graph and len(partial_graph['x']) > 0:
            # We have a non-empty partial graph - process it with GNN
            
            # Convert partial graph to tensor if needed
            graph_features = partial_graph['x']
            if isinstance(graph_features, list):
                # Convert list of features to tensor
                if graph_features and isinstance(graph_features[0], list):
                    graph_features = torch.tensor(graph_features, dtype=torch.float32, device=device)
                else:
                    # Empty or malformed graph
                    graph_encoded = torch.zeros(batch_size, self.graph_hidden_dim, device=device)
            else:
                graph_features = graph_features.to(device)
            
            if len(graph_features.shape) == 2 and graph_features.size(0) > 0:
                # Get edge information for GNN processing
                edge_index = partial_graph.get('edge_index', None)
                if edge_index is None:
                    # Create simple sequential edges if no edges provided
                    num_nodes = graph_features.size(0)
                    if num_nodes > 1:
                        edge_list = []
                        for i in range(num_nodes - 1):
                            edge_list.extend([[i, i + 1], [i + 1, i]])  # Bidirectional edges
                        edge_index = torch.tensor(edge_list, dtype=torch.long, device=device).t()
                    else:
                        # Single node - no edges
                        edge_index = torch.empty((2, 0), dtype=torch.long, device=device)
                else:
                    if isinstance(edge_index, list):
                        edge_index = torch.tensor(edge_index, dtype=torch.long, device=device)
                    else:
                        edge_index = edge_index.to(device)
                
                # Apply GNN layers for structural encoding
                x = graph_features
                for i, gnn_layer in enumerate(self.graph_gnn_layers):
                    x = gnn_layer(x, edge_index)
                    if i < len(self.graph_gnn_layers) - 1:  # Apply activation for all but last layer
                        x = F.relu(x)
                        x = self.graph_dropout(x)
                
                # Apply layer normalization to final GNN output
                x = self.graph_layer_norm(x)
                
                # Global pooling to get graph-level representation per batch
                if 'batch' in partial_graph and partial_graph['batch'] is not None:
                    # Use batch indices for proper pooling
                    batch_indices = partial_graph['batch']
                    if isinstance(batch_indices, list):
                        batch_indices = torch.tensor(batch_indices, dtype=torch.long, device=device)
                    else:
                        batch_indices = batch_indices.to(device)
                    
                    # Use global_mean_pool for proper batched pooling
                    graph_encoded = global_mean_pool(x, batch_indices, size=batch_size)
                    
                    # Ensure we have the right batch size
                    if graph_encoded.size(0) < batch_size:
                        # Pad with zeros for missing batches
                        padding = torch.zeros(batch_size - graph_encoded.size(0), self.graph_hidden_dim, device=device)
                        graph_encoded = torch.cat([graph_encoded, padding], dim=0)
                    elif graph_encoded.size(0) > batch_size:
                        # Trim if too many
                        graph_encoded = graph_encoded[:batch_size]
                else:
                    # Single graph case - use mean pooling
                    graph_encoded = x.mean(dim=0).unsqueeze(0).expand(batch_size, -1)
            else:
                # Unexpected shape or empty, use zeros
                graph_encoded = torch.zeros(batch_size, self.graph_hidden_dim, device=device)
        else:
            # Empty graph - start with zero representation
            graph_encoded = torch.zeros(batch_size, self.graph_hidden_dim, device=device)
        
        # 2. Combine text and graph context
        combined_input = torch.cat([text_embedding, graph_encoded], dim=-1)
        
        # 3. Update sequential state
        if self.sequence_model == 'Transformer':
            # For transformer, project input and treat as sequence
            sequence_input = self.input_projection(combined_input.unsqueeze(1))  # (batch_size, 1, state_hidden_dim)
            sequence_output = self.state_encoder(sequence_input)  # (batch_size, 1, state_hidden_dim)
            sequence_output = sequence_output.squeeze(1)  # (batch_size, state_hidden_dim)
            new_hidden_state = None  # Transformers don't maintain hidden state in the same way
        else:
            # For RNN/GRU/LSTM
            sequence_input = combined_input.unsqueeze(1)  # (batch_size, 1, input_size)
            sequence_output, new_hidden_state = self.state_encoder(sequence_input, hidden_state)
            sequence_output = sequence_output.squeeze(1)  # (batch_size, state_hidden_dim)
        
        # 4. Predict next step
        node_type_logits = self.node_type_predictor(sequence_output)
        connection_probs = self.connection_predictor(sequence_output)
        
        return {
            'node_type_logits': node_type_logits,
            'connection_probs': connection_probs,
            'hidden_state': new_hidden_state
        }
    
    def get_model_info(self) -> str:
        """
        Get information about the autoregressive decoder configuration.
        
        Returns:
            String describing the model architecture
        """
        return (f"AutoregressiveASTDecoder(\n"
                f"  text_dim={self.text_embedding_dim}, "
                f"  graph_dim={self.graph_hidden_dim}, "
                f"  state_dim={self.state_hidden_dim}\n"
                f"  node_types={self.node_types}, "
                f"  sequence_model={self.sequence_model}\n"
                f")")


class ASTAutoencoder(torch.nn.Module):
    """
    Autoencoder for Abstract Syntax Trees using Graph Neural Networks.
    
    Combines the existing RubyComplexityGNN (as encoder) with the new ASTDecoder
    to create an autoencoder that can reconstruct ASTs from learned embeddings.
    """
    
    def __init__(self, encoder_input_dim: int, node_output_dim: int, 
                 hidden_dim: int = 64, num_layers: int = 3, 
                 conv_type: str = 'GCN', dropout: float = 0.1,
                 freeze_encoder: bool = False, encoder_weights_path: str = None,
                 max_nodes: int = 100, decoder_conv_type: str = 'GCN',
                 gradient_checkpointing: bool = False,
                 decoder_edge_mode: str = 'chain'):
        """
        Initialize the AST autoencoder.
        
        Args:
            encoder_input_dim: Input dimension for encoder (node feature dimension)
            node_output_dim: Output dimension for decoder node features
            hidden_dim: Hidden dimension for both encoder and decoder
            num_layers: Number of layers in both encoder and decoder
            conv_type: Type of convolution for encoder ('GCN' or 'SAGE')
            dropout: Dropout rate for encoder
            freeze_encoder: Whether to freeze encoder weights
            encoder_weights_path: Path to pre-trained encoder weights
            max_nodes: Maximum number of nodes for the decoder.
            decoder_conv_type: The GNN layer type for the decoder.
            gradient_checkpointing: Whether to enable gradient checkpointing for memory efficiency.
            decoder_edge_mode: Edge construction strategy for the decoder.
                'chain' uses the original ASTDecoder with sequential edges.
                'teacher_forced' or 'iterative' uses TreeAwareASTDecoder.
        """
        super().__init__()
        
        self.decoder_edge_mode = decoder_edge_mode
        # Initialize encoder (RubyComplexityGNN without prediction head)
        self.encoder = RubyComplexityGNN(
            input_dim=encoder_input_dim,
            hidden_dim=hidden_dim,
            num_layers=num_layers,
            conv_type=conv_type,
            dropout=dropout
        )
        
        # Load pre-trained weights if provided and adjust encoder config if needed
        self.encoder_weights_path = encoder_weights_path
        if encoder_weights_path is not None:
            try:
                checkpoint = torch.load(encoder_weights_path, map_location='cpu', weights_only=True)
                # Check if checkpoint contains model config and use it to create compatible encoder
                if 'model_config' in checkpoint:
                    saved_config = checkpoint['model_config']
                    # Recreate encoder with saved configuration if it differs from current
                    if (saved_config.get('conv_type', conv_type) != conv_type or
                        saved_config.get('hidden_dim', hidden_dim) != hidden_dim or
                        saved_config.get('num_layers', num_layers) != num_layers or
                        saved_config.get('dropout', dropout) != dropout):
                        print(f"Adjusting encoder config to match saved model: conv_type={saved_config.get('conv_type', conv_type)}")
                        self.encoder = RubyComplexityGNN(
                            input_dim=encoder_input_dim,
                            hidden_dim=saved_config.get('hidden_dim', hidden_dim),
                            num_layers=saved_config.get('num_layers', num_layers),
                            conv_type=saved_config.get('conv_type', conv_type),
                            dropout=saved_config.get('dropout', dropout)
                        )
                        # Update hidden_dim for decoder compatibility
                        hidden_dim = saved_config.get('hidden_dim', hidden_dim)
                
                self.encoder.load_state_dict(checkpoint['model_state_dict'])
                print(f"Loaded encoder weights from {encoder_weights_path}")
            except FileNotFoundError:
                print(f"Warning: Could not find encoder weights at {encoder_weights_path}")
            except Exception as e:
                print(f"Warning: Could not load encoder weights: {e}")
        
        # Freeze encoder if requested
        if freeze_encoder:
            for param in self.encoder.parameters():
                param.requires_grad = False
            print("Encoder weights frozen")
        
        # Initialize decoder
        if decoder_edge_mode in ('teacher_forced', 'iterative'):
            self.decoder = TreeAwareASTDecoder(
                embedding_dim=hidden_dim,
                output_node_dim=node_output_dim,
                hidden_dim=hidden_dim,
                num_layers=num_layers,
                max_nodes=max_nodes,
                conv_type=decoder_conv_type,
                edge_mode=decoder_edge_mode,
                gradient_checkpointing=gradient_checkpointing,
            )
        else:
            self.decoder = ASTDecoder(
                embedding_dim=hidden_dim,
                output_node_dim=node_output_dim,
                hidden_dim=hidden_dim,
                num_layers=num_layers,
                max_nodes=max_nodes,
                conv_type=decoder_conv_type,
                gradient_checkpointing=gradient_checkpointing,
            )
        
        self.hidden_dim = hidden_dim
        self.freeze_encoder = freeze_encoder
        
    def forward(self, data: Data) -> dict:
        """
        Forward pass through the autoencoder.
        
        Args:
            data: PyTorch Geometric Data object containing a batch of input ASTs.
            
        Returns:
            Dictionary containing reconstructed AST information for the batch.
        """
        # Encode: Batch of ASTs -> Batch of embeddings
        embedding = self.encoder(data, return_embedding=True)
        
        # Get the number of nodes in each graph of the batch
        num_nodes_per_graph = torch.bincount(data.batch)
        
        # Decode: Batch of embeddings -> Batch of reconstructed ASTs
        # Pass ground-truth edges for tree-aware decoders
        if self.decoder_edge_mode != 'chain':
            reconstruction = self.decoder(
                embedding, num_nodes_per_graph,
                gt_edge_index=data.edge_index,
            )
        else:
            reconstruction = self.decoder(embedding, num_nodes_per_graph)
        
        return {
            'embedding': embedding,
            'reconstruction': reconstruction
        }
    
    def get_model_info(self) -> str:
        """
        Get information about the autoencoder configuration.
        
        Returns:
            String describing the model architecture
        """
        encoder_info = self.encoder.get_model_info()
        decoder_info = f"ASTDecoder(embedding_dim={self.hidden_dim})"
        freeze_status = " [FROZEN]" if self.freeze_encoder else ""
        
        return (f"ASTAutoencoder(\n"
                f"  encoder: {encoder_info}{freeze_status}\n"
                f"  decoder: {decoder_info}\n"
                f")")


class SimpleTextEncoder(torch.nn.Module):
    """
    Simple text encoder as fallback when sentence-transformers is not available.
    
    This provides a basic text encoding mechanism using character-level features
    and a simple neural network. Used as fallback for testing when internet
    access is not available.
    """
    
    def __init__(self, output_dim: int = 384, max_length: int = 100):
        """
        Initialize the simple text encoder.
        
        Args:
            output_dim: Output embedding dimension
            max_length: Maximum text length to consider
        """
        super().__init__()
        self.output_dim = output_dim
        self.max_length = max_length
        
        # Character embedding (256 ASCII characters)
        self.char_embedding = torch.nn.Embedding(256, 64)
        
        # Simple RNN for text processing
        self.rnn = torch.nn.LSTM(64, 128, batch_first=True, bidirectional=True)
        
        # Output projection
        self.output_proj = torch.nn.Linear(256, output_dim)
        
    def encode(self, texts: list, convert_to_tensor: bool = True) -> torch.Tensor:
        """
        Encode texts to embeddings.
        
        Args:
            texts: List of text strings
            convert_to_tensor: Whether to return tensor (for compatibility)
            
        Returns:
            Text embeddings tensor
        """
        batch_size = len(texts)
        
        # Convert texts to character indices
        char_sequences = []
        for text in texts:
            # Convert to lowercase and get character codes
            chars = [min(ord(c), 255) for c in text.lower()[:self.max_length]]
            # Pad to max_length
            chars.extend([0] * (self.max_length - len(chars)))
            char_sequences.append(chars[:self.max_length])
        
        # Convert to tensor and move to same device as model
        char_tensor = torch.tensor(char_sequences, dtype=torch.long)
        char_tensor = char_tensor.to(next(self.parameters()).device)
        
        # Embed characters
        embedded = self.char_embedding(char_tensor)  # (batch, seq_len, embed_dim)
        
        # Process with RNN
        rnn_output, (hidden, _) = self.rnn(embedded)
        
        # Use last hidden state (concatenated forward and backward)
        final_hidden = torch.cat([hidden[0], hidden[1]], dim=1)  # (batch, 256)
        
        # Project to output dimension
        embeddings = self.output_proj(final_hidden)
        
        return embeddings
    
    def get_sentence_embedding_dimension(self) -> int:
        """Get embedding dimension for compatibility."""
        return self.output_dim


class AlignmentModel(torch.nn.Module):
    """
    Dual-encoder model for aligning text descriptions with code embeddings.
    
    This model combines a frozen RubyComplexityGNN (code encoder) with a 
    sentence-transformers text encoder to create aligned embeddings in the
    same 64-dimensional space.
    """
    
    def __init__(self, input_dim: int, hidden_dim: int = 64, num_layers: int = 3,
                 conv_type: str = 'GCN', dropout: float = 0.1,
                 text_model_name: str = 'all-MiniLM-L6-v2',
                 code_encoder_weights_path: str = 'models/best_model.pt'):
        """
        Initialize the alignment model.
        
        Args:
            input_dim: Input dimension for code encoder (node feature dimension)
            hidden_dim: Hidden dimension for both encoders (default: 64)
            num_layers: Number of layers in code encoder
            conv_type: Type of convolution for code encoder ('GCN' or 'SAGE')
            dropout: Dropout rate for code encoder
            text_model_name: Name of the sentence-transformers model to use
            code_encoder_weights_path: Path to pre-trained code encoder weights (default: 'models/best_encoder_model.pt')
        """
        super().__init__()
        
        self.hidden_dim = hidden_dim
        
        # Initialize frozen code encoder (RubyComplexityGNN without prediction head)
        self.code_encoder = RubyComplexityGNN(
            input_dim=input_dim,
            hidden_dim=hidden_dim,
            num_layers=num_layers,
            conv_type=conv_type,
            dropout=dropout
        )
        
        # Load pre-trained weights if provided
        if code_encoder_weights_path is not None:
            try:
                checkpoint = torch.load(code_encoder_weights_path, map_location='cpu', weights_only=True)
                # Handle both direct state dict and checkpoint format
                if 'model_state_dict' in checkpoint:
                    state_dict = checkpoint['model_state_dict']
                else:
                    state_dict = checkpoint
                
                # Load state dict, ignoring predictor weights if present
                model_state = {}
                for key, value in state_dict.items():
                    if not key.startswith('predictor'):
                        model_state[key] = value
                
                self.code_encoder.load_state_dict(model_state, strict=False)
                print(f"Loaded code encoder weights from {code_encoder_weights_path}")
            except FileNotFoundError:
                print(f"Warning: Could not find code encoder weights at {code_encoder_weights_path}")
            except Exception as e:
                print(f"Warning: Could not load code encoder weights: {e}")
        
        # Freeze code encoder parameters
        for param in self.code_encoder.parameters():
            param.requires_grad = False
        print("Code encoder weights frozen")
        
        # Initialize text encoder
        if SENTENCE_TRANSFORMERS_AVAILABLE:
            try:
                self.text_encoder = SentenceTransformer(text_model_name)
                self.text_encoder_type = "sentence_transformers"
                print(f"Using SentenceTransformer: {text_model_name}")
            except Exception as e:
                print(f"Warning: Could not load SentenceTransformer ({e}), using fallback")
                self.text_encoder = SimpleTextEncoder(output_dim=384)
                self.text_encoder_type = "simple"
        else:
            print("SentenceTransformers not available, using simple text encoder")
            self.text_encoder = SimpleTextEncoder(output_dim=384)
            self.text_encoder_type = "simple"
        
        # Get text encoder output dimension
        text_dim = self.text_encoder.get_sentence_embedding_dimension()
        
        # Projection head to align text embeddings to code embedding space
        # Small MLP for better capacity: Linear(384 -> 256) -> ReLU() -> Linear(256 -> 64)
        self.text_projection = torch.nn.Sequential(
            torch.nn.Linear(text_dim, 256),
            torch.nn.ReLU(),
            torch.nn.Linear(256, hidden_dim)
        )
        
        print(f"Text encoder output dim: {text_dim}, projecting to: {hidden_dim}")
        
    def encode_code(self, data: Data) -> torch.Tensor:
        """
        Encode graph data to embeddings using the frozen code encoder.
        
        Args:
            data: PyTorch Geometric Data object containing graph
            
        Returns:
            Code embeddings tensor of shape (batch_size, hidden_dim)
        """
        with torch.no_grad():  # Code encoder is frozen
            return self.code_encoder(data, return_embedding=True)
    
    def encode_text(self, texts: list) -> torch.Tensor:
        """
        Encode text descriptions to embeddings using the text encoder.
        
        Args:
            texts: List of text descriptions
            
        Returns:
            Text embeddings tensor of shape (batch_size, hidden_dim)
        """
        # Get text embeddings from sentence transformer
        text_embeddings = self.text_encoder.encode(texts, convert_to_tensor=True)
        
        # Clone tensor to create a normal tensor for autograd (SentenceTransformer creates inference tensors)
        text_embeddings = text_embeddings.clone()
        
        # Project to code embedding space
        projected_embeddings = self.text_projection(text_embeddings)
        
        return projected_embeddings
    
    def forward(self, data: Data, texts: list) -> dict:
        """
        Forward pass through both encoders.
        
        Args:
            data: PyTorch Geometric Data object containing graphs
            texts: List of text descriptions (same length as batch size)
            
        Returns:
            Dictionary containing:
                - 'code_embeddings': Code embeddings (batch_size, hidden_dim)
                - 'text_embeddings': Text embeddings (batch_size, hidden_dim)
        """
        # Encode code
        code_embeddings = self.encode_code(data)
        
        # Encode text
        text_embeddings = self.encode_text(texts)
        
        # Ensure embeddings are on the same device
        if code_embeddings.device != text_embeddings.device:
            text_embeddings = text_embeddings.to(code_embeddings.device)
        
        return {
            'code_embeddings': code_embeddings,
            'text_embeddings': text_embeddings
        }
    
    def get_model_info(self) -> str:
        """
        Get information about the alignment model configuration.
        
        Returns:
            String describing the model architecture
        """
        code_info = self.code_encoder.get_model_info()
        
        if self.text_encoder_type == "sentence_transformers":
            # Try to get model name from _model_config, fallback to transformer config, or use generic name
            model_name = self.text_encoder._model_config.get('_name_or_path')
            if model_name is None:
                # Try to get from transformer module config
                try:
                    model_name = self.text_encoder[0].auto_model.config._name_or_path
                except (AttributeError, IndexError):
                    model_name = "SentenceTransformer"
            text_info = f"SentenceTransformer({model_name})"
        else:
            text_info = f"SimpleTextEncoder(dim={self.text_encoder.output_dim})"
            
        # Handle Sequential projection (MLP) vs single Linear layer
        if isinstance(self.text_projection, torch.nn.Sequential):
            first_layer = self.text_projection[0]
            last_layer = self.text_projection[2]
            projection_info = f"MLP({first_layer.in_features} -> 256 -> {last_layer.out_features})"
        else:
            projection_info = f"Linear({self.text_projection.in_features} -> {self.text_projection.out_features})"
        
        return (f"AlignmentModel(\n"
                f"  code_encoder: {code_info} [FROZEN]\n"
                f"  text_encoder: {text_info}\n"
                f"  projection: {projection_info}\n"
                f")")


class HierarchicalASTDecoder(torch.nn.Module):
    """
    Hierarchical, coarse-to-fine decoder for generating ASTs level by level.

    This model takes a text embedding and progressively generates an AST from the
    root down, with each stage adding one level of depth to the tree. Uses proper
    GNN layers to process graph structures at each level.
    """

    def __init__(self, embedding_dim: int, hidden_dim: int, num_levels: int, node_feature_dim: int, conv_type: str = 'GCN'):
        """
        Initialize the HierarchicalASTDecoder.

        Args:
            embedding_dim: Dimension of the input text embedding.
            hidden_dim: Hidden dimension for the GNN layers.
            num_levels: The maximum depth of the AST to generate (number of stages).
            node_feature_dim: The dimension of the node features to be predicted.
            conv_type: The type of GNN convolution to use ('GCN' or 'SAGE').
        """
        super().__init__()
        self.embedding_dim = embedding_dim
        self.hidden_dim = hidden_dim
        self.num_levels = num_levels
        self.node_feature_dim = node_feature_dim
        self.conv_type = conv_type
        self.register_buffer('device_indicator', torch.empty(0))

        # Select GNN layer type
        if conv_type == 'GCN':
            ConvLayer = GCNConv
        elif conv_type == 'SAGE':
            ConvLayer = SAGEConv
        else:
            raise ValueError(f"Unsupported conv_type: {conv_type}. Use 'GCN' or 'SAGE'.")

        # A ModuleList to hold the generator for each level of the AST.
        self.level_generators = torch.nn.ModuleList()

        for i in range(num_levels):
            # Level 0 takes embedding as input, subsequent levels take hidden state
            # which has the same dimension as the output of the previous level's GNN
            if i == 0:
                input_dim = self.embedding_dim
            else:
                input_dim = self.hidden_dim
            
            # Each level generator uses proper GNN layers
            level_gnn = ConvLayer(input_dim, self.hidden_dim)
            node_predictor = torch.nn.Linear(self.hidden_dim, node_feature_dim)
            adjacency_predictor = torch.nn.Linear(self.hidden_dim, self.hidden_dim)

            self.level_generators.append(torch.nn.ModuleDict({
                'gnn': level_gnn,
                'node_predictor': node_predictor,
                'adjacency_predictor': adjacency_predictor,
            }))

    @property
    def device(self):
        """Returns the device the model is on."""
        return self.device_indicator.device

    def forward(self, input_data: Data, target_level: int) -> Dict[str, torch.Tensor]:
        """
        Performs a forward pass for a single level of generation.

        Args:
            input_data: PyG Data object with node features (x) and edge indices (edge_index).
                        For level 0, x should be the text embedding repeated for initial node(s).
            target_level: The specific AST level to generate.

        Returns:
            Dictionary containing:
                - pred_features: Predicted node features for next level
                - pred_adjacency: Predicted adjacency matrix (only diagonal for memory efficiency)
                - hidden_state: Hidden representations for next level
        """
        if target_level >= self.num_levels:
            raise ValueError(f"Target level {target_level} is out of bounds for {self.num_levels} levels.")

        generator = self.level_generators[target_level]
        
        # Process through GNN layer
        hidden_state = F.relu(generator['gnn'](input_data.x, input_data.edge_index))
        
        # Predict node features
        pred_features = generator['node_predictor'](hidden_state)
        
        # Predict adjacency - use diagonal only for memory efficiency
        # Only compute self-connections (diagonal) to avoid huge matrix
        adjacency_repr = generator['adjacency_predictor'](hidden_state)
        # For diagonal: just take dot product with self
        pred_adjacency_diag = (adjacency_repr * adjacency_repr).sum(dim=1, keepdim=True)

        return {
            'hidden_state': hidden_state,
            'pred_features': pred_features,
            'pred_adjacency_diag': pred_adjacency_diag  # Changed: return only diagonal
        }
    
    def generate(self, embedding: torch.Tensor, max_levels: int = None, max_nodes_per_level: int = 10, max_total_nodes: int = 1000) -> list:
        """
        Generate a complete AST from a text embedding using hierarchical generation.

        Args:
            embedding: Text embedding tensor of shape (1, embedding_dim) or (embedding_dim,)
            max_levels: Maximum depth of AST to generate (default: self.num_levels)
            max_nodes_per_level: Maximum children per parent node (default: 10)
            max_total_nodes: Maximum total nodes in AST to prevent runaway growth (default: 1000)

        Returns:
            List representing AST in JSON format with 'type' and 'children' fields
        """
        if max_levels is None:
            max_levels = self.num_levels
        
        device = self.device
        if embedding.dim() == 1:
            embedding = embedding.unsqueeze(0)
        embedding = embedding.to(device)
        
        # Track all nodes with their metadata
        all_nodes = []
        node_id_counter = 0
        
        # Level 0: Generate root node
        root_data = Data(
            x=embedding,  # Single node with embedding as features
            edge_index=torch.empty((2, 0), dtype=torch.long, device=device)
        )
        
        with torch.no_grad():
            root_output = self.forward(root_data, target_level=0)
            root_features = root_output['pred_features']
            root_type_idx = root_features.argmax(dim=1)[0].item()
            
            root_node = {
                'id': node_id_counter,
                'type_idx': root_type_idx,
                'features': root_features[0],
                'hidden': root_output['hidden_state'][0],  # Store hidden state for next level
                'children': [],
                'level': 0
            }
            all_nodes.append(root_node)
            node_id_counter += 1
        
        # Current level nodes that can spawn children
        current_level_nodes = [root_node]
        
        # Generate subsequent levels (optimized: batch all parents at each level)
        for level in range(1, max_levels):
            if len(current_level_nodes) == 0 or len(all_nodes) >= max_total_nodes:
                break
            
            next_level_nodes = []
            
            # OPTIMIZATION: Batch all parent nodes together
            if len(current_level_nodes) > 0:
                # Stack all parent hidden states
                parent_hiddens = torch.stack([node['hidden'] for node in current_level_nodes])
                
                # Create batched data (disconnected nodes, one per parent)
                batch_indices = torch.arange(len(current_level_nodes), device=device).repeat_interleave(1)
                batched_data = Data(
                    x=parent_hiddens,
                    edge_index=torch.empty((2, 0), dtype=torch.long, device=device),
                    batch=batch_indices
                )
                
                with torch.no_grad():
                    output = self.forward(batched_data, target_level=level)
                    pred_features = output['pred_features']  # (num_parents, node_feature_dim)
                    # Use diagonal adjacency values for spawn probability
                    
                    # Process each parent's output
                    for parent_idx, parent_node in enumerate(current_level_nodes):
                        # Use diagonal element as spawn probability for this parent
                        spawn_prob = torch.sigmoid(output['pred_adjacency_diag'][parent_idx, 0]).item()
                        num_children = min(int(spawn_prob * max_nodes_per_level), max_nodes_per_level)
                        
                        # Generate children nodes for this parent
                        for child_idx in range(num_children):
                            if len(all_nodes) >= max_total_nodes:
                                break  # Stop if we hit the node limit
                                
                            # Use the parent's predicted features/hidden state
                            child_features = pred_features[parent_idx]
                            child_hidden = output['hidden_state'][parent_idx]
                            child_type_idx = child_features.argmax(dim=0).item()
                            
                            child_node = {
                                'id': node_id_counter,
                                'type_idx': child_type_idx,
                                'features': child_features,
                                'hidden': child_hidden,
                                'children': [],
                                'level': level,
                                'parent_id': parent_node['id']
                            }
                            
                            parent_node['children'].append(child_node)
                            all_nodes.append(child_node)
                            next_level_nodes.append(child_node)
                            node_id_counter += 1
            
            current_level_nodes = next_level_nodes
        
        # Convert to AST JSON format (recursive structure)
        def node_to_ast_json(node):
            ast_node = {
                'type': f"type_{node['type_idx']}",  # Will be mapped to actual types by caller
                'children': [node_to_ast_json(child) for child in node['children']]
            }
            return ast_node
        
        if len(all_nodes) > 0:
            return [node_to_ast_json(all_nodes[0])]
        else:
            return []