File size: 39,322 Bytes
ad93bc0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Full definition of a GPT Language Model, all of it in this single file.
References:
1) the official GPT-2 TensorFlow implementation released by OpenAI:
https://github.com/openai/gpt-2/blob/master/src/model.py
2) huggingface/transformers PyTorch implementation:
https://github.com/huggingface/transformers/blob/main/src/transformers/models/gpt2/modeling_gpt2.py
"""

"""
change the configure_optimizers method to handle combined optimizers
add activation hooks to enable activation preconditioning
"""

import math
import inspect
from dataclasses import dataclass

import torch
import torch.nn as nn
from torch.nn import functional as F
import contextlib



from optimizer.optimizer_strategies import OPTIMIZER_STRATEGIES, OptimizerConfig


# +++ NEW: RoPE Helper Functions +++
def precompute_freqs_cis(dim: int, end: int, theta: float = 10000.0):
    """
    预计算 Cos 和 Sin 表。
    dim: head_dim (n_embd // n_head)
    end: block_size
    """
    freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
    t = torch.arange(end, device=freqs.device)  # type: ignore
    freqs = torch.outer(t, freqs).float()  # (end, dim // 2)
    freqs_cos = torch.cos(freqs)  # Real part
    freqs_sin = torch.sin(freqs)  # Imaginary part
    return freqs_cos, freqs_sin

def apply_rotary_emb(xq, xk, freqs_cos, freqs_sin):
    """
    应用旋转。
    xq, xk shape: (B, T, n_head, head_dim)
    freqs_cos, freqs_sin shape: (T, head_dim/2) -> 广播到 (1, T, 1, head_dim/2)
    """
    # reshape xq, xk to manipulate pairs
    # input: (B, T, n_head, head_dim)
    # 我们将 head_dim 拆分为 (head_dim//2, 2) 以便进行旋转
    
    # 将 freqs 切片以匹配当前序列长度 (用于推理时的 extrapolation)
    seq_len = xq.shape[1]
    freqs_cos = freqs_cos[:seq_len].view(1, seq_len, 1, -1)
    freqs_sin = freqs_sin[:seq_len].view(1, seq_len, 1, -1)

    # 核心旋转逻辑
    # x: [x1, x2, x3, x4] -> x_real: [x1, x3], x_imag: [x2, x4] (这是一种简单的 split 方式)
    # 这里我们采用 Llama/PaLM 常用的 split 方式:将前半部分作为 real,后半部分作为 imag
    d = xq.shape[-1] // 2
    
    xq_r, xq_i = xq[..., :d], xq[..., d:]
    xk_r, xk_i = xk[..., :d], xk[..., d:]
    
    # 旋转公式:
    # x' = x_r * cos - x_i * sin
    # y' = x_r * sin + x_i * cos
    
    xq_out_r = xq_r * freqs_cos - xq_i * freqs_sin
    xq_out_i = xq_r * freqs_sin + xq_i * freqs_cos
    
    xk_out_r = xk_r * freqs_cos - xk_i * freqs_sin
    xk_out_i = xk_r * freqs_sin + xk_i * freqs_cos
    
    # 拼接回去
    xq_out = torch.cat([xq_out_r, xq_out_i], dim=-1)
    xk_out = torch.cat([xk_out_r, xk_out_i], dim=-1)
    
    return xq_out, xk_out
# +++ END NEW +++


# +++ NEW: LoRA Layer Definition +++
class LoRALinear(nn.Module):
    """
    Implements a LoRA-enabled Linear layer.
    
    This layer contains a frozen, pre-trained linear layer and two 
    low-rank matrices (A and B) that are trainable.
    
    The forward pass computes: y = Wx + (s * BA)x
    where W is the frozen weight, B and A are the low-rank matrices,
    and s is the scaling factor (lora_alpha / r).
    """
    def __init__(self, in_features, out_features, r, lora_alpha, lora_dropout, bias=True):
        super().__init__()
        self.in_features = in_features
        self.out_features = out_features
        self.r = r
        self.lora_alpha = lora_alpha

        # 1. Original, frozen linear layer
        self.linear = nn.Linear(in_features, out_features, bias=bias)
        
        # 2. LoRA matrices (A and B)
        # B is (out, r) and A is (r, in)
        self.lora_A = nn.Parameter(torch.zeros(r, in_features))
        self.lora_B = nn.Parameter(torch.zeros(out_features, r))
        
        # 3. Scaling factor
        self.scaling = self.lora_alpha / self.r
        
        # 4. Dropout
        self.lora_dropout = nn.Dropout(lora_dropout)
        
        # 5. Freeze the original linear layer
        self.linear.requires_grad_(False)
        
        # 6. Initialize LoRA weights
        # Kaiming uniform for A, zeros for B
        # This ensures that (s * BA)x is zero at the beginning of training
        nn.init.kaiming_uniform_(self.lora_A, a=math.sqrt(5))
        # nn.init.zeros_(self.lora_B) # lora_B is already initialized to zeros

    def forward(self, x: torch.Tensor):
        # Original, frozen path
        result = self.linear(x)
        
        # LoRA path
        # Note: We don't apply dropout to the original path (result)
        lora_update = self.lora_dropout(x)
        lora_update = lora_update @ self.lora_A.transpose(0, 1) # (B, T, in) @ (in, r) -> (B, T, r)
        lora_update = lora_update @ self.lora_B.transpose(0, 1) # (B, T, r) @ (r, out) -> (B, T, out)
        
        return result + lora_update * self.scaling

    def __repr__(self):
        return (f"LoRALinear(in_features={self.in_features}, out_features={self.out_features}, "
                f"r={self.r}, lora_alpha={self.lora_alpha}, bias={self.linear.bias is not None})")


# +++ MODIFIED: Updated LayerNorm implementation +++
class LayerNorm(nn.Module):
    """ LayerNorm that supports p-norms (1, 2, inf). """

    def __init__(self, ndim, bias, p=2.0):
        super().__init__()
        self.weight = nn.Parameter(torch.ones(ndim))
        self.bias = nn.Parameter(torch.zeros(ndim)) if bias else None
        self.p = p
        self.eps = 1e-5

    def forward(self, x):
        # x shape: (Batch, Time, Channels)
        
        # 1. Calculate Mean and Center
        mu = x.mean(dim=-1, keepdim=True)
        x_centered = x - mu

        # 2. Calculate Normalization Factor based on p
        if self.p == 2:
            # Standard LayerNorm (Scale by Standard Deviation)
            # using F.layer_norm is faster and more stable for p=2
            return F.layer_norm(x, self.weight.shape, self.weight, self.bias, self.eps)
        
        elif self.p == 1:
            # L1 Norm: Scale by Mean Absolute Deviation
            # norm = mean(|x - mu|)
            norm_factor = x_centered.abs().mean(dim=-1, keepdim=True)
            x_norm = x_centered / (norm_factor + self.eps)
            
        elif self.p == float('inf'):
            # L_inf Norm: Scale by Max Absolute Deviation
            # norm = max(|x - mu|)
            norm_factor = x_centered.abs().max(dim=-1, keepdim=True)[0]
            x_norm = x_centered / (norm_factor + self.eps)
            
        else:
            # Generic p-norm (average based)
            # norm = (mean(|x - mu|^p))^(1/p)
            norm_factor = x_centered.abs().pow(self.p).mean(dim=-1, keepdim=True).pow(1/self.p)
            x_norm = x_centered / (norm_factor + self.eps)

        # 3. Apply Affine Transform
        if self.bias is not None:
            return x_norm * self.weight + self.bias
        else:
            return x_norm * self.weight
# +++ END MODIFIED +++

class CausalSelfAttention(nn.Module):

    def __init__(self, config):
        super().__init__()
        assert config.n_embd % config.n_head == 0
        # key, query, value projections for all heads, but in a batch
        self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd, bias=config.bias)
        # output projection
        self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias)
        # regularization
        self.attn_dropout = nn.Dropout(config.dropout)
        self.resid_dropout = nn.Dropout(config.dropout)
        self.n_head = config.n_head
        self.n_embd = config.n_embd
        self.dropout = config.dropout
        # flash attention make GPU go brrrrr but support is only in PyTorch >= 2.0
        self.flash = hasattr(torch.nn.functional, 'scaled_dot_product_attention')
        if not self.flash:
            print("WARNING: using slow attention. Flash Attention requires PyTorch >= 2.0")
            # causal mask to ensure that attention is only applied to the left in the input sequence
            self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size))
                                        .view(1, 1, config.block_size, config.block_size))

    # +++ MODIFIED: Forward 签名增加 RoPE 参数 +++
    def forward(self, x, freqs_cos=None, freqs_sin=None):
        B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd)

        # calculate query, key, values for all heads in batch and move head forward to be the batch dim
        q, k, v  = self.c_attn(x).split(self.n_embd, dim=2)
        k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
        q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
        v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)

        # +++ NEW: Apply RoPE if provided +++
        if freqs_cos is not None and freqs_sin is not None:
            # RoPE expects (B, T, nh, hs), so we transpose back temporarily
            k = k.transpose(1, 2)
            q = q.transpose(1, 2)
            
            q, k = apply_rotary_emb(q, k, freqs_cos, freqs_sin)
            
            # Transpose back to (B, nh, T, hs) for attention calculation
            k = k.transpose(1, 2)
            q = q.transpose(1, 2)
        # +++ END NEW +++

        # causal self-attention; Self-attend: (B, nh, T, hs) x (B, nh, hs, T) -> (B, nh, T, T)
        if self.flash:
            # efficient attention using Flash Attention CUDA kernels
            y = torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=None, dropout_p=self.dropout if self.training else 0, is_causal=True)
        else:
            # manual implementation of attention
            att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
            att = att.masked_fill(self.bias[:,:,:T,:T] == 0, float('-inf'))
            att = F.softmax(att, dim=-1)
            att = self.attn_dropout(att)
            y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
        y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side

        # output projection
        y = self.resid_dropout(self.c_proj(y))
        return y

class MLP(nn.Module):

    def __init__(self, config):
        super().__init__()
        self.activation_function = config.activation_function
        
        if self.activation_function == 'swiglu':
            # SwiGLU uses a different structure and hidden dimension, often 2/3 of the standard 4*n_embd
            # This is a common practice from papers like LLaMA
            hidden_dim = int(2 * (4 * config.n_embd) / 3)
            self.c_fc   = nn.Linear(config.n_embd, 2 * hidden_dim, bias=config.bias) # Projects to both gate and value
            self.c_proj = nn.Linear(hidden_dim, config.n_embd, bias=config.bias)
        
        elif self.activation_function == 'gelu':
            self.c_fc    = nn.Linear(config.n_embd, 4 * config.n_embd, bias=config.bias)
            self.gelu    = nn.GELU()
            self.c_proj  = nn.Linear(4 * config.n_embd, config.n_embd, bias=config.bias)
        
        else:
            raise ValueError(f"Unsupported activation function: {self.activation_function}")
        
        self.dropout = nn.Dropout(config.dropout)

    def forward(self, x):
        
        if self.activation_function == 'swiglu':
            # Project to get both gate and value tensors
            gate, value = self.c_fc(x).chunk(2, dim=-1)
            # Apply the SwiGLU activation: silu(gate) * value
            x = F.silu(gate) * value
        
        else: # 'gelu'
            x = self.c_fc(x)
            x = self.gelu(x)
        
        x = self.c_proj(x)
        x = self.dropout(x)
        return x

class Block(nn.Module):

    def __init__(self, config):
        super().__init__()
        # +++ MODIFIED: Pass layer_norm_p to LayerNorm +++
        self.ln_1 = LayerNorm(config.n_embd, bias=config.bias, p=config.layer_norm_p)
        self.attn = CausalSelfAttention(config)
        self.ln_2 = LayerNorm(config.n_embd, bias=config.bias, p=config.layer_norm_p)
        # +++ END MODIFIED +++
        self.mlp = MLP(config)

    def forward(self, x, freqs_cos=None, freqs_sin=None):
        x = x + self.attn(self.ln_1(x), freqs_cos=freqs_cos, freqs_sin=freqs_sin)
        x = x + self.mlp(self.ln_2(x))
        return x

@dataclass
class GPTConfig:
    block_size: int = 1024
    vocab_size: int = 50304 # GPT-2 vocab_size of 50257, padded up to nearest multiple of 64 for efficiency
    n_layer: int = 12
    n_head: int = 12
    n_embd: int = 768
    dropout: float = 0.0
    bias: bool = True # True: bias in Linears and LayerNorms, like GPT-2. False: a bit better and faster
    
    # +++ NEW: Config for Positional Embedding +++
    pos_emb_type: str = 'absolute' # 'absolute' or 'rope'
    # +++ NEW: Layer Norm P +++
    layer_norm_p: float = 2.0
    # +++ END NEW +++
    
    # add use_activation_precond
    use_activation_precond: bool = False # whether to use activation preconditioning
    activation_function: str = 'gelu' # 'gelu' or 'swiglu'
    use_activation_monitoring: bool = False # whether to capture activations for monitoring

    # +++ NEW: Initialization Scale Parameters +++
    attn_init_scale: float = 0.02 # Base scale for QKV weights
    mlp_init_scale: float = 0.02 # Base scale for MLP expansion c_fc weights
    emb_init_scale: float = 0.02 # Base scale for Embedding weights
    # +++ END NEW +++

    # +++ NEW: LoRA Configuration +++
    use_lora: bool = False
    lora_r: int = 8
    lora_alpha: float = 16.0
    lora_dropout: float = 0.05
    # List of module name suffixes to apply LoRA to.
    # E.g., 'attn.c_attn' will target 'transformer.h.0.attn.c_attn'
    lora_target_modules: list = None
    # +++ END NEW +++

class GPT(nn.Module):

    def __init__(self, config):
        super().__init__()
        assert config.vocab_size is not None
        assert config.block_size is not None
        self.config = config

        self.transformer = nn.ModuleDict(dict(
            wte = nn.Embedding(config.vocab_size, config.n_embd),
            # +++ MODIFIED: Conditional WPE +++
            # 如果是 'rope',我们不需要学习的 wpe,但为了兼容性或简单起见,可以设为 None 或 Identity
            # 为了严谨,如果是 RoPE,我们就不初始化 wpe
            wpe = nn.Embedding(config.block_size, config.n_embd) if config.pos_emb_type == 'absolute' else None,
            # +++ END MODIFIED +++
            drop = nn.Dropout(config.dropout),
            h = nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
            # +++ MODIFIED: Pass p to final LayerNorm +++
            ln_f = LayerNorm(config.n_embd, bias=config.bias, p=config.layer_norm_p),
            # +++ END MODIFIED +++
        ))

        # +++ NEW: Initialize RoPE Cache +++
        if config.pos_emb_type == 'rope':
            # head_dim
            head_dim = config.n_embd // config.n_head
            # 预计算 cos/sin table,注册为 buffer (不作为参数更新,但随模型保存)
            cos, sin = precompute_freqs_cis(head_dim, config.block_size)
            self.register_buffer("freqs_cos", cos)
            self.register_buffer("freqs_sin", sin)
        # +++ END NEW +++

        self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
        # with weight tying when using torch.compile() some warnings get generated:
        # "UserWarning: functional_call was passed multiple values for tied weights.
        # This behavior is deprecated and will be an error in future versions"
        # not 100% sure what this is, so far seems to be harmless. TODO investigate
        self.transformer.wte.weight = self.lm_head.weight # https://paperswithcode.com/method/weight-tying

        # init all weights
        self.apply(self._init_weights)
        # apply special scaled init to the residual projections, per GPT-2 paper
        # for pn, p in self.named_parameters():
        #     if pn.endswith('c_proj.weight'):
        #         torch.nn.init.normal_(p, mean=0.0, std=0.02/math.sqrt(2 * config.n_layer))
        
        # 2. 自定义初始化覆盖 (Custom Initialization Override)
        # 包含了 Q, K, V, MLP Expansion 以及 Residual Projections 的缩放
        self.custom_init_weights()

        # report number of parameters
        print("number of parameters: %.2fM" % (self.get_num_params()/1e6,))

        # +++ NEW: Add a dictionary to store activations and register monitoring hooks +++
        if config.use_activation_monitoring:
            self.monitoring_activations = {}
            self.register_monitoring_hooks()

        # +++ ADDED: Register forward hooks for activation preconditioning +++
        # self.register_activation_hooks()
        if config.use_activation_precond:
            self.register_preconditioning_hooks()
    
    # NEW: custom initialization
    def custom_init_weights(self):
        """
        应用自定义的初始化标准差到 Attention 和 MLP 层。
        同时应用 GPT-2 论文中的残差缩放逻辑:std = base_std / sqrt(2 * n_layer)
        """
        config = self.config
        
        # 计算残差层的缩放因子
        # GPT-2 论文建议:随着层数增加,残差路径上的累积方差会增大,因此需要按层数缩放初始化值
        resid_scale_factor = 1.0 / math.sqrt(2.0 * config.n_layer)

        print(f"Applying custom init: attn_scale={config.attn_init_scale}, emb_scale={config.emb_init_scale}, mlp_scale={config.mlp_init_scale}, resid_factor={resid_scale_factor:.4f}")

        for name, module in self.named_modules():
            if isinstance(module, nn.Linear):
                target_std = None
                
                # --- Attention Block ---
                # 1. Q, K, V (Attention Input Projections)
                # use attn_init_scale
                if any(name.endswith(f'.attn.c_{t}') for t in ['q', 'k', 'v']) or name.endswith('.attn.c_attn'):
                    # note that we are changing here to allow c_attn
                    target_std = config.attn_init_scale
                
                # 2. Attention Output Projection (Residual Layer)
                # 使用 attn_init_scale * resid_scale_factor
                elif name.endswith('.attn.c_proj'):
                    target_std = config.attn_init_scale * resid_scale_factor

                # --- MLP Block ---
                # 3. MLP Expansion (c_fc)
                # 使用 mlp_init_scale
                elif name.endswith('.mlp.c_fc'):
                    target_std = config.mlp_init_scale
                
                # 4. MLP Output Projection (Residual Layer)
                # 使用 mlp_init_scale * resid_scale_factor
                elif name.endswith('.mlp.c_proj'):
                    target_std = config.mlp_init_scale * resid_scale_factor

                
                # --- Apply Initialization ---
                if target_std is not None:
                    
                    torch.nn.init.normal_(module.weight, mean=0.0, std=target_std)
                    if module.bias is not None:
                        torch.nn.init.zeros_(module.bias)
            
            # +++ NEW: Handle Embedding Layers +++
            elif isinstance(module, nn.Embedding):
                target_std = None
                # Check for wte or wpe (Token or Position embeddings)
                if name.endswith('.wte') or name.endswith('.wpe'):
                    target_std = config.emb_init_scale
                
                if target_std is not None:
                    torch.nn.init.normal_(module.weight, mean=0.0, std=target_std)
    
    
    # +++ MODIFIED: Replaced register_activation_hooks with a more general version +++
    def register_preconditioning_hooks(self):
        
        # --- Forward hook to capture input activations (X_t) ---
        def hook_fn_forward(module, input, output):
            x = input[0] 
            x = x.view(-1, x.size(-1))
            # Normalize by batch size for stability
            xxt = torch.matmul(x.t(), x) / x.shape[0]
            # Attach to the weight parameter
            module.weight.activation_second_moment = xxt

        # --- Backward hook to capture output gradients (G_Yt) ---
        def hook_fn_backward(module, grad_input, grad_output):
            gy = grad_output[0]
            gy = gy.view(-1, gy.size(-1))
            # Normalize by batch size for stability
            gygyt = torch.matmul(gy.t(), gy) / gy.shape[0]
            # Attach to the weight parameter
            module.weight.output_gradient_second_moment = gygyt

        print("Registering forward and backward hooks for preconditioning.")
        for name, module in self.named_modules():
            # Apply to all Linear layers except embeddings and the final head
            if isinstance(module, nn.Linear) and '.wte.' not in name and '.wpe.' not in name and 'lm_head' not in name:
                if hasattr(module, 'weight') and module.weight.dim() >= 2:
                    print(f"  - Hooks registered for: {name}")
                    module.register_forward_hook(hook_fn_forward)
                    module.register_full_backward_hook(hook_fn_backward)
    
    
    # +++ NEW: Method to register hooks for capturing activations for monitoring +++
    def register_monitoring_hooks(self):
        """
        Registers forward hooks on model layers to capture their input and output
        activations for detailed monitoring.
        """
        self.monitoring_activations.clear() # Clear previous activations

        def get_hook(name):
            def hook_fn(module, input, output):
                # Store both input and output activations
                if isinstance(input, tuple):
                    # For linear layers, input is a tuple
                    self.monitoring_activations[f"{name}.input"] = input[0].detach()
                else:
                    self.monitoring_activations[f"{name}.input"] = input.detach()
                
                if isinstance(output, tuple):
                    self.monitoring_activations[f"{name}.output"] = output[0].detach()
                else:
                    self.monitoring_activations[f"{name}.output"] = output.detach()
            return hook_fn

        print("Registering forward hooks for Activation Monitoring.")
        for name, module in self.named_modules():
            # We capture activations from Linear layers and LayerNorms
            if isinstance(module, (nn.Linear, LayerNorm)):
                 # We avoid the embedding layers and the final language model head
                # if '.wte.' not in name and '.wpe.' not in name and 'lm_head' not in name:
                #     print(f"  - Monitoring hook registered for: {name}")
                #     module.register_forward_hook(get_hook(name))
                # print(f"  - Monitoring hook registered for: {name}")
                module.register_forward_hook(get_hook(name))


    @contextlib.contextmanager
    def activation_logging_context(self):
        """
        在 Context 内注册 Hook,退出时自动移除。
        """
        hooks = []
        self.monitoring_activations = {} # 清空旧数据

        def get_hook(name):
            def hook_fn(module, input, output):
                # 你的 Hook 逻辑
                if isinstance(input, tuple):
                    self.monitoring_activations[f"{name}.input"] = input[0].detach()
                else:
                    self.monitoring_activations[f"{name}.input"] = input.detach()
                
                if isinstance(output, tuple):
                    self.monitoring_activations[f"{name}.output"] = output[0].detach()
                else:
                    self.monitoring_activations[f"{name}.output"] = output.detach()
            return hook_fn

        # 注册 Hooks
        for name, module in self.named_modules():
            # 这里可以保留你的过滤逻辑,例如只监控 Linear 层
            if isinstance(module, (nn.Linear, LayerNorm)): 
                 # 可以在这里加额外的过滤,例如排除 lm_head
                 hooks.append(module.register_forward_hook(get_hook(name)))
        
        try:
            yield # 执行被包裹的代码 (Forward Pass)
        finally:
            # 退出时移除所有 Hook
            for h in hooks:
                h.remove()

    def get_num_params(self, non_embedding=True):
        """
        Return the number of parameters in the model.
        For non-embedding count (default), the position embeddings get subtracted.
        The token embeddings would too, except due to the parameter sharing these
        params are actually used as weights in the final layer, so we include them.
        """
        n_params = sum(p.numel() for p in self.parameters())
        # if non_embedding:
        #     n_params -= self.transformer.wpe.weight.numel()
        return n_params

    def _init_weights(self, module):
        if isinstance(module, nn.Linear):
            torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
            if module.bias is not None:
                torch.nn.init.zeros_(module.bias)
        elif isinstance(module, nn.Embedding):
            torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)

    def forward(self, idx, targets=None):
        device = idx.device
        b, t = idx.size()
        assert t <= self.config.block_size, f"Cannot forward sequence of length {t}, block size is only {self.config.block_size}"
        
        # +++ MODIFIED: Positional Embedding Logic +++
        tok_emb = self.transformer.wte(idx) # token embeddings of shape (b, t, n_embd)
        
        if self.config.pos_emb_type == 'absolute':
            pos = torch.arange(0, t, dtype=torch.long, device=device) # shape (t)
            pos_emb = self.transformer.wpe(pos) # position embeddings of shape (t, n_embd)
            x = self.transformer.drop(tok_emb + pos_emb)
            # RoPE args are None
            freqs_cos, freqs_sin = None, None
            
        elif self.config.pos_emb_type == 'rope':
            # 不加 pos_emb,只做 dropout
            x = self.transformer.drop(tok_emb)
            # 准备 RoPE 需要的 freq table
            freqs_cos = self.freqs_cos
            freqs_sin = self.freqs_sin
        else:
            raise ValueError(f"Unknown pos_emb_type: {self.config.pos_emb_type}")
        # +++ END MODIFIED +++
        
               
        for block in self.transformer.h:
            x = block(x, freqs_cos=freqs_cos, freqs_sin=freqs_sin)
        x = self.transformer.ln_f(x)

        if targets is not None:
            # if we are given some desired targets also calculate the loss
            logits = self.lm_head(x)
            loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1)
        else:
            # inference-time mini-optimization: only forward the lm_head on the very last position
            logits = self.lm_head(x[:, [-1], :]) # note: using list [-1] to preserve the time dim
            loss = None

        return logits, loss

    def crop_block_size(self, block_size):
        # model surgery to decrease the block size if necessary
        # e.g. we may load the GPT2 pretrained model checkpoint (block size 1024)
        # but want to use a smaller block size for some smaller, simpler model
        assert block_size <= self.config.block_size
        self.config.block_size = block_size
        self.transformer.wpe.weight = nn.Parameter(self.transformer.wpe.weight[:block_size])
        for block in self.transformer.h:
            if hasattr(block.attn, 'bias'):
                block.attn.bias = block.attn.bias[:,:,:block_size,:block_size]

    @classmethod
    def from_pretrained(cls, model_type, override_args=None):
        assert model_type in {'gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'}
        override_args = override_args or {} # default to empty dict
        # only dropout can be overridden see more notes below
        assert all(k == 'dropout' for k in override_args)
        from transformers import GPT2LMHeadModel
        print("loading weights from pretrained gpt: %s" % model_type)

        # n_layer, n_head and n_embd are determined from model_type
        config_args = {
            'gpt2':         dict(n_layer=12, n_head=12, n_embd=768),  # 124M params
            'gpt2-medium':  dict(n_layer=24, n_head=16, n_embd=1024), # 350M params
            'gpt2-large':   dict(n_layer=36, n_head=20, n_embd=1280), # 774M params
            'gpt2-xl':      dict(n_layer=48, n_head=25, n_embd=1600), # 1558M params
        }[model_type]
        print("forcing vocab_size=50257, block_size=1024, bias=True")
        config_args['vocab_size'] = 50257 # always 50257 for GPT model checkpoints
        config_args['block_size'] = 1024 # always 1024 for GPT model checkpoints
        config_args['bias'] = True # always True for GPT model checkpoints
        # we can override the dropout rate, if desired
        if 'dropout' in override_args:
            print(f"overriding dropout rate to {override_args['dropout']}")
            config_args['dropout'] = override_args['dropout']
        # create a from-scratch initialized minGPT model
        config = GPTConfig(**config_args)
        model = GPT(config)
        sd = model.state_dict()
        sd_keys = sd.keys()
        sd_keys = [k for k in sd_keys if not k.endswith('.attn.bias')] # discard this mask / buffer, not a param

        # init a huggingface/transformers model
        model_hf = GPT2LMHeadModel.from_pretrained(model_type)
        sd_hf = model_hf.state_dict()

        # copy while ensuring all of the parameters are aligned and match in names and shapes
        sd_keys_hf = sd_hf.keys()
        sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.masked_bias')] # ignore these, just a buffer
        sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.bias')] # same, just the mask (buffer)
        transposed = ['attn.c_attn.weight', 'attn.c_proj.weight', 'mlp.c_fc.weight', 'mlp.c_proj.weight']
        # basically the openai checkpoints use a "Conv1D" module, but we only want to use a vanilla Linear
        # this means that we have to transpose these weights when we import them
        assert len(sd_keys_hf) == len(sd_keys), f"mismatched keys: {len(sd_keys_hf)} != {len(sd_keys)}"
        for k in sd_keys_hf:
            if any(k.endswith(w) for w in transposed):
                # special treatment for the Conv1D weights we need to transpose
                assert sd_hf[k].shape[::-1] == sd[k].shape
                with torch.no_grad():
                    sd[k].copy_(sd_hf[k].t())
            else:
                # vanilla copy over the other parameters
                assert sd_hf[k].shape == sd[k].shape
                with torch.no_grad():
                    sd[k].copy_(sd_hf[k])

        return model

    
    # +++ NEW: Helper methods for LoRA +++
    
    def freeze_all_parameters(self):
        """
        Freezes all parameters in the model *except* for LayerNorm parameters.
        This is called before applying LoRA adapters.
        """
        print("Freezing all parameters except LayerNorms...")
        for name, param in self.named_parameters():
            # 检查参数名是否属于 LayerNorm
            # 您的 LayerNorm 模块名为 'ln_1', 'ln_2', 'ln_f'
            if '.ln_' in name or '.ln_f.' in name:
                param.requires_grad = True
                print(f"  - Unfreezing (LayerNorm): {name}")
            else:
                param.requires_grad = False

    def apply_lora(self):
        """
        Recursively finds target nn.Linear layers and replaces them
        with LoRALinear layers.
        """
        config = self.config

        print(f"Applying LoRA (r={config.lora_r}, alpha={config.lora_alpha}) to target modules: {config.lora_target_modules}")
        
        target_modules = set(config.lora_target_modules)
        if not target_modules:
            print("Warning: `lora_target_modules` is empty. No LoRA layers will be applied.")
            return

        # Store (parent_module, child_name, old_module)
        modules_to_replace = []

        # First pass: find all modules to replace
        for name, module in self.named_modules():
            if isinstance(module, nn.Linear):
                # Check if the module's name ends with any target suffix
                for target_suffix in target_modules:
                    if name.endswith(target_suffix):
                        # Found a target
                        parent_name = ".".join(name.split('.')[:-1])
                        child_name = name.split('.')[-1]
                        
                        parent_module = self
                        if parent_name:
                            parent_module = dict(self.named_modules())[parent_name]
                            
                        modules_to_replace.append((parent_module, child_name, module))
                        break # Found a match, move to next module

        if not modules_to_replace:
            print("Warning: No matching nn.Linear layers found for target modules.")
            return

        # Second pass: perform the replacement
        for parent_module, child_name, old_module in modules_to_replace:
            # Create new LoRALinear layer
            new_lora_layer = LoRALinear(
                in_features=old_module.in_features,
                out_features=old_module.out_features,
                r=config.lora_r,
                lora_alpha=config.lora_alpha,
                lora_dropout=config.lora_dropout,
                bias=(old_module.bias is not None)
            )
            
            # Copy original weights and bias to the frozen .linear part
            new_lora_layer.linear.weight.data.copy_(old_module.weight.data)
            if old_module.bias is not None:
                new_lora_layer.linear.bias.data.copy_(old_module.bias.data)
                
            # Replace the old module with the new LoRA-enabled one
            setattr(parent_module, child_name, new_lora_layer)
            print(f"  - Replaced {name} with {new_lora_layer}")

    def print_trainable_parameters(self):
        """
        Prints a summary of trainable parameters in the model.
        """
        trainable_params = 0
        all_params = 0
        print("Trainable parameter summary:")
        for name, param in self.named_parameters():
            all_params += param.numel()
            if param.requires_grad:
                trainable_params += param.numel()
                print(f"  - {name} (shape: {param.shape}, numel: {param.numel()})")
        
        print(f"\nTotal trainable parameters: {trainable_params}")
        print(f"Total all parameters: {all_params}")
        print(f"Trainable percentage: {100 * trainable_params / all_params:.4f}%")
        
    def freeze_for_lora_resume(self):
        """
        Freezes all parameters *except* for LoRA parameters.
        Used when resuming a checkpoint that already has LoRA layers.
        """
        print("Freezing non-LoRA parameters for resume...")
        for name, param in self.named_parameters():
            if '.lora_A' not in name and '.lora_B' not in name:
                param.requires_grad = False
            else:
                # Ensure LoRA params are trainable (they should be already)
                param.requires_grad = True
                
    # +++ END NEW +++
    
    
    def configure_optimizers(self, config: OptimizerConfig, device_type: str, optimizer_name: str):
        """
        Configures the optimizer based on a strategy name and a configuration object.
        """
        # +++ MODIFIED: Import moved inside the method +++
        # This avoids import errors when this method is not called, e.g. during evaluation.
        from optimizer.optimizer_strategies import OPTIMIZER_STRATEGIES, OptimizerConfig

        # Determine if fused AdamW is available and update the config
        fused_available = 'fused' in inspect.signature(torch.optim.AdamW).parameters
        use_fused = fused_available and device_type == 'cuda'
        config.extra_args = dict(fused=True) if use_fused else dict()

        print(f"Selected optimizer strategy: '{optimizer_name}'")
        if optimizer_name not in OPTIMIZER_STRATEGIES:
            raise ValueError(f"Unknown optimizer_name: '{optimizer_name}'. Available: {list(OPTIMIZER_STRATEGIES.keys())}")
        
        # Get the strategy function from the registry and execute it
        strategy_func = OPTIMIZER_STRATEGIES[optimizer_name]
        optimizer = strategy_func(self, config)

        print(f"Optimizer configured. Fused AdamW used: {use_fused}")
        return optimizer
    

    def estimate_mfu(self, fwdbwd_per_iter, dt):
        """ estimate model flops utilization (MFU) in units of A100 bfloat16 peak FLOPS """
        # first estimate the number of flops we do per iteration.
        # see PaLM paper Appendix B as ref: https://arxiv.org/abs/2204.02311
        N = self.get_num_params()
        cfg = self.config
        L, H, Q, T = cfg.n_layer, cfg.n_head, cfg.n_embd//cfg.n_head, cfg.block_size
        flops_per_token = 6*N + 12*L*H*Q*T
        flops_per_fwdbwd = flops_per_token * T
        flops_per_iter = flops_per_fwdbwd * fwdbwd_per_iter
        # express our flops throughput as ratio of A100 bfloat16 peak flops
        flops_achieved = flops_per_iter * (1.0/dt) # per second
        flops_promised = 312e12 # A100 GPU bfloat16 peak flops is 312 TFLOPS
        mfu = flops_achieved / flops_promised
        return mfu

    @torch.no_grad()
    def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None):
        """
        Take a conditioning sequence of indices idx (LongTensor of shape (b,t)) and complete
        the sequence max_new_tokens times, feeding the predictions back into the model each time.
        Most likely you'll want to make sure to be in model.eval() mode of operation for this.
        """
        for _ in range(max_new_tokens):
            # if the sequence context is growing too long we must crop it at block_size
            idx_cond = idx if idx.size(1) <= self.config.block_size else idx[:, -self.config.block_size:]
            # forward the model to get the logits for the index in the sequence
            logits, _ = self(idx_cond)
            # pluck the logits at the final step and scale by desired temperature
            logits = logits[:, -1, :] / temperature
            # optionally crop the logits to only the top k options
            if top_k is not None:
                v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
                logits[logits < v[:, [-1]]] = -float('Inf')
            # apply softmax to convert logits to (normalized) probabilities
            probs = F.softmax(logits, dim=-1)
            # sample from the distribution
            idx_next = torch.multinomial(probs, num_samples=1)
            # append sampled index to the running sequence and continue
            idx = torch.cat((idx, idx_next), dim=1)

        return idx