Repository navigation
Expand file tree
/
Copy pathflashgpt_model.py
More file actions
3198 lines (2585 loc) · 152 KB
/
Copy pathflashgpt_model.py
File metadata and controls
3198 lines (2585 loc) · 152 KB
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
# flashgpt_model.py
# This module contains the GPT model definitions, MPS optimization utilities,
# training functions, and other components for the FlashGPT project.
import os
import time
import math
import logging
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader, Dataset
from datasets import load_dataset # Using datasets library for example data (dependency needed if OptimizedDataset uses it)
from tqdm.auto import tqdm
from torch.utils.checkpoint import checkpoint
import sympy as sp
import numpy as np
from transformers import AutoTokenizer, PreTrainedTokenizerBase # For tokenization
import threading
from pathlib import Path
import gc # For garbage collection in training loop
# --- Configuration ---
# Setup logging
# Note: It's often better to configure logging in the main script,
# but keeping it here as it was in the original code.
logging.basicConfig(
filename='training_log.txt', # Consider making this configurable
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__) # Use __name__ for module logger
# Setting up device (will be determined dynamically or passed as argument)
# We'll define functions that determine the device later.
device = None # Placeholder, will be set by optimize_for_apple_silicon or passed in functions
# MPS related stuff ###################################################
# --- Configuration for MPS Optimization ---
def optimize_for_apple_silicon():
"""Configure PyTorch for optimal performance on Apple Silicon."""
global device # Modify the global device variable
import torch
import os
# Set environment variables for MPS optimization
os.environ['PYTORCH_ENABLE_MPS_FALLBACK'] = '1'
# Determine device and settings
if torch.backends.mps.is_available():
device = torch.device("mps")
print("Using MPS device")
# Print device properties
print("Apple Silicon MPS device detected")
try:
# Note: current_allocated_memory might be 0 initially
print(f"Initial allocated memory: {torch.mps.current_allocated_memory() / 1e9:.2f} GB")
except Exception as e:
print(f"Could not get MPS memory info: {e}")
# Set autocast and benchmark flags (benchmark might not be needed/available for MPS)
# torch.backends.mps.enable_cudnn_benchmark = True # No cudnn on MPS
elif torch.cuda.is_available():
device = torch.device("cuda")
print("Using CUDA device")
else:
device = torch.device("cpu")
print("MPS/CUDA device not found, using CPU")
# Move model to device (should happen after model initialization)
torch.manual_seed(42)
if torch.cuda.is_available():
# torch.backends.cudnn.deterministic = True # Optional for reproducibility
# torch.backends.cudnn.benchmark = False # Optional for reproducibility
pass # Keep defaults for now
# Return optimized device
return device
# --- Mixed-Precision Training Helper ---
class MPSMixedPrecision:
"""Helper for mixed precision training on MPS"""
def __init__(self, enabled=True, dtype=torch.float16):
# Ensure enabled is only True if MPS is available
self.enabled = enabled and torch.backends.mps.is_available()
self.dtype = dtype
# Initialize scaler only if enabled
self.scaler = torch.amp.GradScaler(enabled=self.enabled) if self.enabled else None
if self.enabled:
print(f"MPS Mixed Precision enabled with dtype {self.dtype}")
else:
print("MPS Mixed Precision disabled (MPS not available or not enabled)")
def __enter__(self):
if self.enabled:
# Use autocast context manager for MPS
return torch.autocast(device_type="mps", dtype=self.dtype, enabled=True)
else:
# Return a dummy context manager if not enabled
class DummyContext:
def __enter__(self): return self
def __exit__(self, *args): pass
return DummyContext()
def __exit__(self, *args):
# Exit autocast context implicitly
pass
def scale_loss(self, loss, optimizer):
if self.enabled and self.scaler:
return self.scaler.scale(loss)
return loss
def step(self, optimizer, loss=None, clip_grad=None, model=None):
if self.enabled and self.scaler:
if clip_grad is not None and model is not None:
# Unscale before clipping gradients
self.scaler.unscale_(optimizer)
torch.nn.utils.clip_grad_norm_(model.parameters(), clip_grad)
self.scaler.step(optimizer)
self.scaler.update()
else:
# Standard optimizer step if not using mixed precision
if clip_grad is not None and model is not None:
torch.nn.utils.clip_grad_norm_(model.parameters(), clip_grad)
optimizer.step()
# --- Optimized DataLoader for MPS ---
class MPSDataLoader:
"""DataLoader optimized for MPS with prefetching and pinning workarounds"""
def __init__(self, dataset, batch_size, num_workers, shuffle=True):
import torch
from torch.utils.data import DataLoader
self.dataset = dataset
self.batch_size = batch_size
self.num_workers = num_workers if num_workers > 0 else 0 # Ensure num_workers isn't negative
self.shuffle = shuffle
# For MPS, we need custom handling since pin_memory isn't supported directly
if torch.backends.mps.is_available():
print(f"Configuring MPS DataLoader (num_workers={self.num_workers})")
# Create a standard dataloader without pin_memory
# persistent_workers=True requires num_workers > 0
self.dataloader = DataLoader(
self.dataset,
batch_size=self.batch_size,
shuffle=self.shuffle,
num_workers=self.num_workers,
persistent_workers=True if self.num_workers > 0 else False,
prefetch_factor=3 if self.num_workers > 0 else None, # Increase prefetch factor
pin_memory=False # Explicitly False for MPS clarity
)
else:
print(f"Configuring standard DataLoader (pin_memory=True, num_workers={self.num_workers})")
# For other systems, use standard pinned memory if CUDA available
pin_memory_enabled = torch.cuda.is_available()
self.dataloader = DataLoader(
self.dataset,
batch_size=self.batch_size,
shuffle=self.shuffle,
num_workers=self.num_workers,
pin_memory=pin_memory_enabled,
persistent_workers=True if self.num_workers > 0 else False,
prefetch_factor=2 if self.num_workers > 0 else None
)
def __iter__(self):
# Return the iterator of the underlying DataLoader
return iter(self.dataloader)
def __len__(self):
# Return the length of the underlying DataLoader
return len(self.dataloader)
# --- Memory-Optimized Dataset ---
class OptimizedDataset(torch.utils.data.Dataset):
"""Basic Dataset wrapper for tokenization (can be optimized further)."""
def __init__(self, dataset, tokenizer, max_length, preload=False):
import torch
self.dataset = dataset # Expects a list/iterable of dictionaries with 'text' or 'content'
self.tokenizer = tokenizer
self.max_length = max_length
self.preload = preload
self.preloaded_items = []
# Preload a subset for faster access if requested
if self.preload:
print("Preloading dataset subset...")
num_to_preload = min(10000, len(self.dataset)) # Limit preloading
for idx in tqdm(range(num_to_preload), desc="Preloading"):
try:
self.preloaded_items.append(self._process_item(idx))
except Exception as e:
print(f"Warning: Skipping item {idx} during preload due to error: {e}")
print(f"Preloaded {len(self.preloaded_items)} items")
def _process_item(self, idx):
# Handle potential variations in dataset structure
item = self.dataset[idx]
text = item.get('text', item.get('content', '')) # Safely get text
if not text:
logger.warning(f"Empty text found at index {idx}. Skipping.")
# Return placeholder or raise error? Returning empty tensors might cause issues.
# Let's return tensors with pad tokens.
input_ids = torch.full((self.max_length,), self.tokenizer.pad_token_id, dtype=torch.long)
attention_mask = torch.zeros((self.max_length,), dtype=torch.long)
labels = torch.full((self.max_length,), -100, dtype=torch.long) # Ignore index for loss
return {"input_ids": input_ids, "attention_mask": attention_mask, "labels": labels}
encodings = self.tokenizer(text, truncation=True, max_length=self.max_length,
padding="max_length", return_tensors="pt")
input_ids = encodings['input_ids'].squeeze(0) # Remove batch dim
attention_mask = encodings['attention_mask'].squeeze(0) # Remove batch dim
labels = input_ids.clone()
# Mask padding tokens in labels
labels[input_ids == self.tokenizer.pad_token_id] = -100
return {"input_ids": input_ids, "attention_mask": attention_mask, "labels": labels}
def __len__(self):
return len(self.dataset)
def __getitem__(self, idx):
if self.preload and idx < len(self.preloaded_items):
return self.preloaded_items[idx]
# Process on-the-fly if not preloaded or index is out of preload range
return self._process_item(idx)
# --- GPT Configuration Class ---
class GPTConfig:
"""Configuration class for the GPT model architecture."""
def __init__(self, vocab_size: int, max_seq_len: int, n_embd: int, n_layer: int, n_head: int,
dropout_prob: float = 0.1, alibi: bool = False, use_rope: bool = True,
flash_attention: bool = True, n_kv_heads: int = None, use_gqa: bool = False,
use_rwkv: bool = False, use_ssm: bool = False,
use_moe: bool = False, num_experts: int = 8, top_k_experts: int = 2,
gradient_checkpointing: bool = False,
# Added for reasoning modules
mla_n_latent: int = 16, use_mla: bool = True,
reasoning_steps: int = 3, use_reasoning_tracker: bool = True,
algorithmic_reasoner_registers: int = 4, use_algorithmic_reasoner: bool = False,
# Added for tools
use_calculator: bool = True,
# Added for ToT (conceptual)
use_tree_of_thought: bool = False): # Added config flag for ToT
self.vocab_size = vocab_size
self.max_seq_len = max_seq_len
self.n_embd = n_embd
self.n_layer = n_layer
self.n_head = n_head
self.n_kv_heads = n_kv_heads if (n_kv_heads is not None and use_gqa) else n_head
self.dropout_prob = dropout_prob
# Architectural choices
self.alibi = alibi
self.use_rope = use_rope and not alibi # RoPE and ALiBi are usually alternatives
self.flash_attention = flash_attention and hasattr(F, 'scaled_dot_product_attention') # Check if available
self.use_gqa = use_gqa and (n_kv_heads is not None) and (n_head % n_kv_heads == 0)
self.use_rwkv = use_rwkv
self.use_ssm = use_ssm
self.use_moe = use_moe
self.num_experts = num_experts
self.top_k_experts = top_k_experts
self.gradient_checkpointing = gradient_checkpointing
# Enhanced features
self.mla_n_latent = mla_n_latent
self.use_mla = use_mla
self.reasoning_steps = reasoning_steps
self.use_reasoning_tracker = use_reasoning_tracker
self.algorithmic_reasoner_registers = algorithmic_reasoner_registers
self.use_algorithmic_reasoner = use_algorithmic_reasoner
self.use_calculator = use_calculator
self.use_tree_of_thought = use_tree_of_thought # Store ToT config flag
# Validation
if self.use_gqa:
assert self.n_head % self.n_kv_heads == 0, "n_head must be divisible by n_kv_heads for GQA"
if self.alibi and self.use_rope:
logger.warning("Both ALiBi and RoPE are enabled. RoPE will be disabled.")
self.use_rope = False
if not self.flash_attention and hasattr(F, 'scaled_dot_product_attention'):
logger.info("Flash Attention is available but disabled in config.")
elif self.flash_attention and not hasattr(F, 'scaled_dot_product_attention'):
logger.warning("Flash Attention requested but F.scaled_dot_product_attention not found. Disabling.")
self.flash_attention = False
# --- Memory Optimization Techniques ---
# Helper function: Chunked matrix multiplication (Included as it was in the original code)
def chunked_matmul(a: torch.Tensor, b: torch.Tensor, chunk_size: int = 64) -> torch.Tensor:
"""
Computes batched matrix multiplication between tensors 'a' and 'b' in smaller chunks
along the sequence dimension to reduce peak memory usage.
Args:
a: Tensor of shape (B, n_heads, T_a, head_dim)
b: Tensor of shape (B, n_heads, head_dim, T_b)
chunk_size: Number of tokens (T_a dimension) to process in one chunk.
Returns:
A tensor of shape (B, n_heads, T_a, T_b)
"""
B, n_heads, T_a, head_dim_a = a.shape
_, _, head_dim_b, T_b = b.shape
assert head_dim_a == head_dim_b, "Head dimensions must match"
output_chunks = []
for start in range(0, T_a, chunk_size):
end = min(start + chunk_size, T_a)
chunk_result = torch.matmul(a[:, :, start:end, :], b) # (B, n_heads, chunk_size, T_b)
output_chunks.append(chunk_result)
return torch.cat(output_chunks, dim=2)
# KV Cache for efficient inference
class KVCache:
"""Stores past Key and Value tensors for efficient autoregressive decoding."""
def __init__(self, max_batch_size: int, max_seq_len: int, n_kv_heads: int, head_dim: int, dtype=torch.float32, device: torch.device = None):
self.max_batch_size = max_batch_size
self.max_seq_len = max_seq_len
self.n_kv_heads = n_kv_heads # Use n_kv_heads for GQA compatibility
self.head_dim = head_dim
self.dtype = dtype
self.device = device
# Initialize empty cache tensors (on CPU initially, moved on first update)
self.k_cache = torch.zeros(max_batch_size, n_kv_heads, max_seq_len, head_dim, dtype=dtype)
self.v_cache = torch.zeros(max_batch_size, n_kv_heads, max_seq_len, head_dim, dtype=dtype)
self.current_seq_len = 0
self.initialized_device = False
def _initialize_device(self, input_tensor: torch.Tensor):
"""Move cache to the same device as the input tensor on first use."""
if not self.initialized_device or self.device != input_tensor.device:
self.device = input_tensor.device
self.k_cache = self.k_cache.to(self.device)
self.v_cache = self.v_cache.to(self.device)
self.initialized_device = True
logger.info(f"KV cache initialized on device {self.device}, shape: {self.k_cache.shape}")
def update(self, k: torch.Tensor, v: torch.Tensor, position: int = None):
"""
Update the KV cache with new key-value pairs.
Args:
k: Key tensor of shape (B, n_kv_heads, T_new, head_dim)
v: Value tensor of shape (B, n_kv_heads, T_new, head_dim)
position: Start position index to update (defaults to appending).
Used for overwriting or specific insertion points.
"""
self._initialize_device(k)
B, n_kv_heads, T_new, head_dim = k.shape
# Basic validation
if B > self.max_batch_size:
logger.error(f"KV Cache Error: Batch size {B} exceeds max cache size {self.max_batch_size}. Resizing needed or error.")
# Option 1: Raise error
raise ValueError(f"Batch size {B} exceeds max cache size {self.max_batch_size}")
# Option 2: Attempt resize (could lead to OOM)
# self.reset(batch_size=B) # This would clear existing cache! Not ideal mid-generation.
assert n_kv_heads == self.n_kv_heads, f"KV heads mismatch: got {n_kv_heads}, expected {self.n_kv_heads}"
assert head_dim == self.head_dim, f"Head dimension mismatch: got {head_dim}, expected {self.head_dim}"
if position is None:
# Append to the end
start_pos = self.current_seq_len
end_pos = start_pos + T_new
else:
# Update at a specific position
start_pos = position
end_pos = start_pos + T_new
# If this is a position we've already filled, log it:
if start_pos < self.current_seq_len:
logger.debug(f"KV Cache: Overwriting cache at pos {start_pos} with {T_new} tokens")
# Check for cache overflow and apply sliding window
if end_pos > self.max_seq_len:
# Calculate how many tokens to discard from the beginning
to_discard = end_pos - self.max_seq_len
logger.warning(f"KV Cache overflow: max_seq_len={self.max_seq_len}, needed={end_pos}. Discarding {to_discard} oldest tokens.")
# Shift existing cache content left
self.k_cache = torch.roll(self.k_cache, shifts=(-to_discard,), dims=2)
self.v_cache = torch.roll(self.v_cache, shifts=(-to_discard,), dims=2)
# Adjust positions for insertion at the *new* end of the shifted cache
start_pos = self.max_seq_len - T_new
end_pos = self.max_seq_len
# Update current_seq_len to reflect full cache
self.current_seq_len = self.max_seq_len
else:
# Only update current_seq_len if appending or extending beyond current length
if position is None or end_pos > self.current_seq_len:
self.current_seq_len = max(self.current_seq_len, end_pos)
# Validate final positions before writing
if not (0 <= start_pos < end_pos <= self.max_seq_len):
raise ValueError(f"KV Cache Error: Invalid cache write indices: start={start_pos}, end={end_pos}, max={self.max_seq_len}")
# Update the cache slice
try:
self.k_cache[:B, :, start_pos:end_pos] = k
self.v_cache[:B, :, start_pos:end_pos] = v
logger.debug(f"KV Cache: Updated pos {start_pos}:{end_pos}. New seq_len={self.current_seq_len}")
except IndexError as e:
logger.error(f"KV Cache Error during write: {e}. Shapes - k_cache: {self.k_cache.shape}, k: {k.shape}, B: {B}, start: {start_pos}, end: {end_pos}")
raise
def get(self, current_batch_size: int):
"""
Retrieve the current key-value pairs from the cache up to current_seq_len.
Args:
current_batch_size: The actual batch size being processed (<= max_batch_size).
Returns:
Tuple of (k_cache, v_cache) for the current sequence length and batch size.
Shape: (B, n_kv_heads, current_seq_len, head_dim)
"""
if not self.initialized_device or self.current_seq_len == 0:
# Return empty tensors if cache hasn't been used yet
return (torch.zeros(current_batch_size, self.n_kv_heads, 0, self.head_dim, dtype=self.dtype, device=self.device),
torch.zeros(current_batch_size, self.n_kv_heads, 0, self.head_dim, dtype=self.dtype, device=self.device))
# Validate batch size against cache size
if current_batch_size > self.max_batch_size:
logger.error(f"KV Cache Get Error: Requested batch size {current_batch_size} > cache max {self.max_batch_size}")
raise ValueError(f"Requested batch size {current_batch_size} exceeds max cache size {self.max_batch_size}")
# Return the relevant slice of the cache
return (self.k_cache[:current_batch_size, :, :self.current_seq_len],
self.v_cache[:current_batch_size, :, :self.current_seq_len])
def reset(self, batch_size: int = None):
"""Reset the cache, optionally resizing batch dimension if needed."""
new_batch_size = batch_size if batch_size is not None else self.max_batch_size
if self.initialized_device and new_batch_size != self.k_cache.shape[0]:
# Reinitialize if batch size changes (potentially expensive)
logger.info(f"Resetting KV Cache and resizing batch dim from {self.max_batch_size} to {new_batch_size}")
self.max_batch_size = new_batch_size
self.k_cache = torch.zeros(self.max_batch_size, self.n_kv_heads, self.max_seq_len, self.head_dim,
dtype=self.dtype, device=self.device)
self.v_cache = torch.zeros(self.max_batch_size, self.n_kv_heads, self.max_seq_len, self.head_dim,
dtype=self.dtype, device=self.device)
elif self.initialized_device:
# Just clear the existing cache contents
self.k_cache.zero_()
self.v_cache.zero_()
logger.debug(f"KV Cache: Reset content (batch size {self.max_batch_size} unchanged)")
# Else: not initialized yet, reset does nothing until first update
self.current_seq_len = 0
# --- Core Model Architecture Components ---
# RMSNorm (Root Mean Square Layer Normalization)
class RMSNorm(nn.Module):
def __init__(self, dim: int, eps: float = 1e-6): # Use common 1e-6 epsilon
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim))
def _norm(self, x: torch.Tensor) -> torch.Tensor:
# Compute Root Mean Square along the feature dimension
# Use float32 for stability during calculation
return x.float() * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
def forward(self, x: torch.Tensor) -> torch.Tensor:
output = self._norm(x).type_as(x) # Cast back to original input type
return output * self.weight
# SwiGLU Feed-Forward Block
class SwiGLU(nn.Module):
""" SwiGLU FFN Layer """
def __init__(self, hidden_dim: int, expansion_factor: float = 8/3, dropout_prob: float = 0.0):
super().__init__()
# Calculate intermediate dimension, often making it multiple of 256
intermediate_dim = int(expansion_factor * hidden_dim)
multiple_of = 256
intermediate_dim = multiple_of * ((intermediate_dim + multiple_of - 1) // multiple_of)
self.w1 = nn.Linear(hidden_dim, intermediate_dim, bias=False)
self.w3 = nn.Linear(hidden_dim, intermediate_dim, bias=False) # Gated component
self.w2 = nn.Linear(intermediate_dim, hidden_dim, bias=False)
self.dropout = nn.Dropout(dropout_prob) # Added dropout
def forward(self, x: torch.Tensor) -> torch.Tensor:
# Apply SiLU activation to the first projection
swish_gate = F.silu(self.w1(x))
# Element-wise multiply with the third projection (gate)
gated_output = swish_gate * self.w3(x)
# Apply final projection
output = self.w2(gated_output)
# Apply dropout
output = self.dropout(output)
return output
# ALiBi Positional Bias (Attention with Linear Biases)
def build_alibi_tensor(n_heads: int, seq_len: int, device: torch.device, dtype: torch.dtype) -> torch.Tensor:
"""Builds the ALiBi tensor for biasing attention scores."""
def get_slopes(n: int) -> list[float]:
# Standard ALiBi slope calculation (handles powers of 2 and non-powers of 2)
try:
closest_power_of_2 = 2 ** math.floor(math.log2(n))
base = torch.tensor(2 ** (-(2 ** -(math.log2(closest_power_of_2) - 3))), dtype=torch.float32)
powers = torch.arange(1, 1 + closest_power_of_2, dtype=torch.float32)
slopes = torch.pow(base, powers)
if closest_power_of_2 != n: # Handle cases where n is not a power of 2
extra_base = torch.tensor(2 ** (-(2 ** -(math.log2(2 * closest_power_of_2) - 3))), dtype=torch.float32)
# Corrected extra_powers calculation for non-power-of-2 heads
extra_powers = torch.arange(1, 1 + 2 * (n - closest_power_of_2), 2, dtype=torch.float32)
slopes = torch.cat([slopes, torch.pow(extra_base, extra_powers)], dim=0)
return slopes.tolist() # Return as list
except Exception as e:
# Fallback if calculation fails (simple geometric progression)
logger.error(f"Error calculating ALiBi slopes: {e}. Using simpler power-of-2 calculation.")
start = 2 ** (-8.0 / n) # Example fallback start value
ratio = start
return [start * (ratio ** i) for i in range(n)]
slopes = torch.tensor(get_slopes(n_heads), device=device, dtype=dtype) # (n_heads,)
# Create relative distances (causal mask style)
relative_position = torch.arange(seq_len, device=device).unsqueeze(0) - torch.arange(seq_len, device=device).unsqueeze(1) # (seq_len, seq_len)
# ALiBi uses negative relative position * slope
# Result shape needs to be (1, n_heads, seq_len, seq_len) for broadcasting
alibi = slopes.unsqueeze(1).unsqueeze(2) * relative_position.abs().mul(-1).unsqueeze(0)
return alibi.unsqueeze(0) # Add batch dimension
# --- Modern Positional Embeddings ---
# Rotary Position Embeddings (RoPE)
class RotaryPositionEmbeddings(nn.Module):
def __init__(self, dim: int, max_seq_len: int = 4096, base: int = 10000, device: torch.device = None):
super().__init__()
self.dim = dim
self.max_seq_len_cached = 0 # Track cache size
self.base = base
self.device = device # Store target device
# Precompute inverse frequencies (theta_i) - moved to _build_cache
# self.register_buffer("inv_freq", None, persistent=False)
# self.register_buffer("cos_cached", None, persistent=False)
# self.register_buffer("sin_cached", None, persistent=False)
self._build_cache(max_seq_len) # Initial cache build
def _build_cache(self, seq_len: int):
# Only rebuild if needed seq_len > cached length or device changes
current_device = self.device if self.device else torch.device('cpu') # Default to CPU if not set
# if seq_len <= self.max_seq_len_cached and hasattr(self, 'inv_freq') and self.inv_freq.device == current_device:
# return # Cache is sufficient
logger.info(f"Building RoPE cache for seq_len {seq_len} on device {current_device}")
self.max_seq_len_cached = seq_len
self.device = current_device # Update stored device
# Calculate inverse frequencies (theta_i)
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, device=self.device).float() / self.dim))
self.register_buffer("inv_freq", inv_freq, persistent=False)
t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=torch.float32)
freqs = torch.einsum("i,j->ij", t, self.inv_freq) # Outer product: (seq_len, dim/2)
# Different from paper ordering? -> Corrected einsum and emb generation
# emb = torch.cat((freqs, freqs), dim=-1) # Shape: (seq_len, dim)
# self.register_buffer("cos_cached", emb.cos(), persistent=False)
# self.register_buffer("sin_cached", emb.sin(), persistent=False)
# Store freqs directly (no duplication needed before applying)
self.register_buffer("cos_cached", freqs.cos().to(inv_freq.dtype), persistent=False) # Shape: (seq_len, dim/2)
self.register_buffer("sin_cached", freqs.sin().to(inv_freq.dtype), persistent=False) # Shape: (seq_len, dim/2)
def _apply_rotary_emb(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
"""Applies rotary embeddings to the input tensor x."""
# x: (..., seq_len, head_dim)
# cos, sin: (seq_len, head_dim/2)
d = x.shape[-1]
cos = cos[:, : d // 2] # Ensure dimensions match if dim is not the RoPE dim
sin = sin[:, : d // 2]
# Reshape x to separate real/imaginary parts (pairs of features)
# x = (x1, x2, x3, x4, ...) -> x_half1 = (x1, x3, ...), x_half2 = (x2, x4, ...)
x_half1 = x[..., 0 : d : 2]
x_half2 = x[..., 1 : d : 2]
# Unsqueeze cos/sin to match batch/head dimensions if necessary
# Example: if x is (B, H, T, D), cos/sin need to be (1, 1, T, D/2) for broadcasting
while cos.ndim < x.ndim -1:
cos = cos.unsqueeze(0)
sin = sin.unsqueeze(0)
# Apply rotation using complex number multiplication formula:
# rotated_x1 = x1 * cos - x2 * sin
# rotated_x2 = x1 * sin + x2 * cos
rotated_x_half1 = x_half1 * cos - x_half2 * sin
rotated_x_half2 = x_half1 * sin + x_half2 * cos
# Combine back: create tensor of shape (..., D) where pairs are interleaved
rotated_x = torch.empty_like(x)
rotated_x[..., 0 : d : 2] = rotated_x_half1
rotated_x[..., 1 : d : 2] = rotated_x_half2
return rotated_x
def forward(self, q: torch.Tensor, k: torch.Tensor, seq_len: int) -> tuple[torch.Tensor, torch.Tensor]:
"""
Applies RoPE to Query and Key tensors.
Args:
q: Query tensor (..., seq_len, head_dim)
k: Key tensor (..., seq_len, head_dim)
seq_len: The current sequence length of q and k.
Returns:
Tuple of (rotated_q, rotated_k)
"""
# Ensure cache is built for the required sequence length and device
self._build_cache(seq_len)
# Retrieve cached cos/sin values for the current sequence length
# Slicing ensures we only use the relevant part of the cache
cos = self.cos_cached[:seq_len] # Shape: (seq_len, dim/2)
sin = self.sin_cached[:seq_len] # Shape: (seq_len, dim/2)
# Apply rotary embeddings to q and k
q_embed = self._apply_rotary_emb(q, cos, sin)
k_embed = self._apply_rotary_emb(k, cos, sin)
return q_embed, k_embed
# --- Advanced Attention Mechanisms ---
# Base Attention Class (to share common logic)
class BaseAttention(nn.Module):
def __init__(self, config: GPTConfig):
super().__init__()
self.n_embd = config.n_embd
self.n_head = config.n_head
self.head_dim = self.n_embd // self.n_head
assert self.head_dim * self.n_head == self.n_embd, "n_embd must be divisible by n_head"
self.dropout_prob = config.dropout_prob
self.use_flash_attention = config.flash_attention
self.use_rope = config.use_rope
self.use_alibi = config.alibi
self.max_seq_len = config.max_seq_len
if self.use_rope:
# Initialize RoPE - try to infer device, fallback to CPU
try:
rope_device = next(self.parameters()).device
except StopIteration: # No parameters yet, default to CPU or MPS if available
rope_device = optimize_for_apple_silicon() if torch.backends.mps.is_available() else torch.device('cpu')
self.rope = RotaryPositionEmbeddings(self.head_dim, self.max_seq_len, device=rope_device)
# KV cache needs n_kv_heads (number of heads for K and V)
self.n_kv_heads = config.n_kv_heads if config.use_gqa else config.n_head
self.kv_cache: KVCache | None = None # Initialize later if use_cache=True
# Output projection and dropout common to all attention types
self.out_proj = nn.Linear(self.n_embd, self.n_embd, bias=False)
self.attn_dropout = nn.Dropout(self.dropout_prob)
self.resid_dropout = nn.Dropout(self.dropout_prob) # Dropout after residual connection
def _init_kv_cache(self, batch_size: int, dtype: torch.dtype, device: torch.device):
"""Initializes the KV cache if needed or resizes if batch size changes."""
if self.kv_cache is None:
logger.info(f"Initializing KV Cache: B={batch_size}, T={self.max_seq_len}, heads={self.n_kv_heads}, dim={self.head_dim}")
self.kv_cache = KVCache(batch_size, self.max_seq_len, self.n_kv_heads, self.head_dim, dtype=dtype, device=device)
elif self.kv_cache.max_batch_size != batch_size or self.kv_cache.device != device:
logger.warning(f"Re-initializing KV Cache due to change: B={batch_size}(old {self.kv_cache.max_batch_size}), device={device}(old {self.kv_cache.device})")
# Reset and potentially resize
self.kv_cache.reset(batch_size=batch_size)
# Ensure device is correct after reset
if self.kv_cache.device != device:
self.kv_cache = KVCache(batch_size, self.max_seq_len, self.n_kv_heads, self.head_dim, dtype=dtype, device=device)
else:
# Reset content for new sequence if batch size/device are same
self.kv_cache.reset()
def _process_kv_cache(self, k: torch.Tensor, v: torch.Tensor, use_cache: bool, position_ids: torch.LongTensor | None) -> tuple[torch.Tensor, torch.Tensor]:
"""Updates and retrieves from KV cache."""
if not use_cache:
return k, v
B, _, T_new, _ = k.shape
# Initialize cache if this is the first call with use_cache=True
if self.kv_cache is None:
self._init_kv_cache(B, k.dtype, k.device)
# If cache exists, ensure it matches current batch size/device, reset content only
elif self.kv_cache.max_batch_size != B or self.kv_cache.device != k.device:
self._init_kv_cache(B, k.dtype, k.device) # Re-init if mismatch
# else: cache exists and matches, content will be reset by update/get logic implicitly
# Determine the position for cache update based on position_ids or cache state
cache_position = None
if position_ids is not None:
# Use the minimum position_id as the starting point for the update
# Assumes position_ids are contiguous for the new tokens
cache_position = position_ids.min().item()
else:
# If no position_ids, assume we are appending to the current cache length
cache_position = self.kv_cache.current_seq_len
# Update cache with new keys/values at the determined position
self.kv_cache.update(k, v, position=cache_position)
# Get the full sequence from cache up to the new length
k_full, v_full = self.kv_cache.get(current_batch_size=B)
return k_full, v_full
def _manual_attention(self, q, k, v, attention_mask, alibi_bias, is_causal):
"""Manual attention computation as fallback with stability improvements."""
B, n_heads, T_q, head_dim = q.shape
T_k = k.shape[-2]
# Use float32 for score calculation for stability
q_f32 = q.to(torch.float32)
k_f32 = k.to(torch.float32)
# Compute attention scores
attn_scores = torch.matmul(q_f32, k_f32.transpose(-2, -1)) / math.sqrt(head_dim)
# Apply ALiBi bias if needed (before masks)
if self.use_alibi and alibi_bias is not None:
# Ensure bias matches score dimensions (T_q, T_k)
if alibi_bias.size(-2) >= T_q and alibi_bias.size(-1) >= T_k:
# Slice or pad bias if necessary
alibi_bias_sliced = alibi_bias[:, :, :T_q, :T_k]
attn_scores = attn_scores + alibi_bias_sliced.to(torch.float32) # Add bias
else:
logger.warning(f"ALiBi bias shape {alibi_bias.shape} incompatible with attn scores {attn_scores.shape} (Tq={T_q}, Tk={T_k}). Skipping ALiBi.")
# Apply causal mask if needed (for training or full sequence processing)
if is_causal: # Typically True when T_q == T_k during training/prompt processing
# Create causal mask dynamically based on T_q and T_k
# Mask needs to be False where attention is allowed
causal_mask = torch.ones(T_q, T_k, device=q.device, dtype=torch.bool).tril(diagonal=0)
attn_scores = attn_scores.masked_fill(~causal_mask, -float('inf')) # Mask out upper triangle
# Apply padding attention mask if provided
if attention_mask is not None:
# Expected shape (B, T_k) or (B, 1, 1, T_k) or (B, 1, T_q, T_k)
if attention_mask.dim() == 2: # (B, T_k) -> (B, 1, 1, T_k)
mask_expanded = attention_mask.view(B, 1, 1, T_k)
elif attention_mask.dim() == 3: # Maybe (B, T_q, T_k) -> (B, 1, T_q, T_k) ? Unlikely. Assume (B, 1, T_k)?
mask_expanded = attention_mask.unsqueeze(1) # (B, 1, T_q/1?, T_k)
elif attention_mask.dim() == 4:
mask_expanded = attention_mask
else:
raise ValueError(f"Unexpected attention mask shape: {attention_mask.shape}")
# Ensure mask length matches key length Tk
if mask_expanded.shape[-1] != T_k:
logger.warning(f"Attention mask length {mask_expanded.shape[-1]} != Key length {T_k}. Adjusting mask.")
if mask_expanded.shape[-1] > T_k:
mask_expanded = mask_expanded[..., :T_k]
else: # Pad mask if shorter (assume padding allows attention)
pad_width = T_k - mask_expanded.shape[-1]
mask_expanded = F.pad(mask_expanded, (0, pad_width), value=1) # Pad with 1 (allow attn)
# Ensure mask query length matches query length Tq if mask is 4D
if mask_expanded.dim() == 4 and mask_expanded.shape[-2] != T_q:
if mask_expanded.shape[-2] == 1: # Broadastable mask (e.g., from padding only)
pass # Okay
else:
logger.warning(f"Attention mask query length {mask_expanded.shape[-2]} != Query length {T_q}. Adjusting mask.")
if mask_expanded.shape[-2] > T_q:
mask_expanded = mask_expanded[..., :T_q, :]
else: # Pad mask query dimension (highly unusual)
pad_height = T_q - mask_expanded.shape[-2]
mask_expanded = F.pad(mask_expanded, (0, 0, 0, pad_height), value=1)
# Apply mask: mask value of 0 means mask out (fill with -inf)
# Ensure mask is bool for masked_fill
attn_scores = attn_scores.masked_fill(mask_expanded == 0, -float('inf'))
# Compute attention weights (softmax)
# Use float32 for stability
attn_weights = F.softmax(attn_scores, dim=-1).type_as(q) # Cast back to original type
# Apply dropout to attention weights
attn_weights = self.attn_dropout(attn_weights)
# Compute output (weighted sum of values)
attn_output = torch.matmul(attn_weights, v) # (B, n_heads, T_q, head_dim)
# Sanity check for NaNs in output
if torch.isnan(attn_output).any():
logger.error("NaN detected in manual attention output!")
# Option: replace NaNs with zeros? Might hide underlying issues.
# attn_output = torch.nan_to_num(attn_output, nan=0.0)
raise FloatingPointError("NaN detected in manual attention output")
return attn_output
def _compute_attention(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor,
attention_mask: torch.Tensor | None, alibi_bias: torch.Tensor | None) -> torch.Tensor:
"""Computes attention output using FlashAttention or manual implementation."""
B, n_heads, T_q, head_dim = q.shape
T_k = k.shape[-2]
# Determine if causal masking is needed based on sequence lengths and context
# Causal is typically needed when T_q == T_k (processing a full sequence)
# or when generating the very first token from a prompt (T_q=1, T_k=PromptLength).
# It's NOT needed when generating subsequent tokens (T_q=1, T_k=PromptLength+PreviousGenerated).
is_causal = T_q == T_k # Default: assume causal if lengths match
is_generation_step = T_q == 1 and T_k > 1 # True if generating single token with cache
# Flash Attention Requirements:
# - No ALiBi bias
# - No explicit attention_mask (padding handled separately or assumes none)
# - Compatible hardware/pytorch version
# - Dtype often needs to be fp16 or bf16
can_use_flash = (
self.use_flash_attention
and not self.use_alibi # Flash Attn v2 supports ALiBi, but basic F.sdpa might not handle it easily
and attention_mask is None # F.sdpa can take a mask, but simpler without
and hasattr(F, 'scaled_dot_product_attention')
)
# Check for NaN/Inf in inputs before attention
if __debug__: # Only run checks during development/debugging
for name, tensor in [('q', q), ('k', k), ('v', v)]:
if torch.isnan(tensor).any() or torch.isinf(tensor).any():
logger.warning(f"NaN/Inf detected in input '{name}' to attention. Shape: {tensor.shape}")
# Consider clamping or replacing NaNs here if it's a recurring issue
# tensor = torch.nan_to_num(tensor, nan=0.0, posinf=1.0, neginf=-1.0)
if can_use_flash:
# Prepare inputs for F.scaled_dot_product_attention if needed (B, T, H, D_h)
# Q, K, V should have shape (B, H, T, D_h) for our manual path,
# but F.sdpa prefers (B, T, H, D_h). Let's keep our shape and transpose inside if needed.
# Note: F.sdpa handles causal masking internally with `is_causal=True`
# If it's a generation step (T_q=1, T_k > 1), we should NOT use causal masking.
sdpa_is_causal = is_causal and not is_generation_step
try:
# logger.debug(f"Using Flash Attention (F.sdpa): Tq={T_q}, Tk={T_k}, is_causal={sdpa_is_causal}")
# Use dropout only during training
dropout_p = self.attn_dropout.p if self.training else 0.0
attn_output = F.scaled_dot_product_attention(
q, k, v,
attn_mask=None, # Explicit mask handled manually or not used with flash
dropout_p=dropout_p,
is_causal=sdpa_is_causal
)
return attn_output
except Exception as e:
# Catch potential errors like dtype/device incompatibility or OOM
logger.warning(f"Flash Attention (F.sdpa) failed: {e}. Falling back to manual attention. Tq={T_q}, Tk={T_k}, is_causal={sdpa_is_causal}")
# Fallthrough to manual attention
# Manual Attention Calculation (Fallback or if flash cannot be used)
# logger.debug(f"Using Manual Attention: Tq={T_q}, Tk={T_k}, is_causal={is_causal}, is_gen={is_generation_step}")
# Pass `is_causal=True` only if processing a full sequence or the very first token generation
manual_is_causal = is_causal # Use the originally determined causality for manual path
return self._manual_attention(q, k, v, attention_mask, alibi_bias, manual_is_causal)
def forward(self, *args, **kwargs):
raise NotImplementedError("Subclasses must implement the forward method")
# MultiHead Self Attention (Standard)
class MultiHeadSelfAttention(BaseAttention):
def __init__(self, config: GPTConfig):
super().__init__(config)
if config.use_gqa:
logger.warning("MHA initialized, but GQA is enabled in config. Ensure this is intended.")
assert config.n_embd % config.n_head == 0
# Projections for Q, K, V (all map from n_embd to n_embd)
self.q_proj = nn.Linear(self.n_embd, self.n_embd, bias=False)
self.k_proj = nn.Linear(self.n_embd, self.n_embd, bias=False)
self.v_proj = nn.Linear(self.n_embd, self.n_embd, bias=False)
def forward(self, x: torch.Tensor, attention_mask: torch.Tensor | None = None,
alibi_bias: torch.Tensor | None = None, use_cache: bool = False,
position_ids: torch.LongTensor | None = None) -> torch.Tensor:
B, T, C = x.size() # Input shape: Batch, Sequence Length, Embedding Dim
# 1. Project Q, K, V
q = self.q_proj(x)
k = self.k_proj(x)
v = self.v_proj(x)
# 2. Reshape for multi-head: (B, T, C) -> (B, n_head, T, head_dim)
q = q.view(B, T, self.n_head, self.head_dim).transpose(1, 2)
k = k.view(B, T, self.n_head, self.head_dim).transpose(1, 2) # K has n_head heads
v = v.view(B, T, self.n_head, self.head_dim).transpose(1, 2) # V has n_head heads
# 3. Apply RoPE if enabled (before caching)
if self.use_rope:
# Determine sequence length for RoPE based on input T or cache state
current_seq_len = T # Length of the new input sequence
q, k = self.rope(q, k, current_seq_len)
# 4. Handle KV Caching (operates on k and v)
# Note: k, v passed here have n_head heads (same as q)
k_cache, v_cache = self._process_kv_cache(k, v, use_cache, position_ids)
# k_cache, v_cache might have different T dimension (T_full) if cache is used
# 5. Compute attention using potentially cached K/V
# Q is from current input, K/V are from cache (or current input if no cache)
attn_output = self._compute_attention(q, k_cache, v_cache, attention_mask, alibi_bias)
# attn_output shape: (B, n_head, T_q, head_dim), where T_q = T (input sequence length)
# 6. Combine heads and project output
attn_output = attn_output.transpose(1, 2).contiguous().view(B, T, C) # (B, T_q, C)
output = self.resid_dropout(self.out_proj(attn_output)) # Apply output projection and dropout
return output
# Grouped Query Attention (GQA)
class GroupedQueryAttention(BaseAttention):
def __init__(self, config: GPTConfig):
super().__init__(config)
if not config.use_gqa:
logger.warning("GQA class initialized, but use_gqa=False in config.")
assert config.n_head % config.n_kv_heads == 0, "n_head must be divisible by n_kv_heads for GQA"
self.n_kv_heads = config.n_kv_heads
self.num_query_groups = config.n_head // self.n_kv_heads
# Projections: Q maps to n_head, K/V map to n_kv_heads
self.q_proj = nn.Linear(self.n_embd, self.n_embd, bias=False) # Output dim C = n_head * head_dim
self.k_proj = nn.Linear(self.n_embd, self.n_kv_heads * self.head_dim, bias=False) # Output dim C_kv
self.v_proj = nn.Linear(self.n_embd, self.n_kv_heads * self.head_dim, bias=False) # Output dim C_kv
def _repeat_kv(self, x: torch.Tensor, n_rep: int) -> torch.Tensor:
"""Repeats KV heads to match query heads: (B, n_kv, T, head_dim) -> (B, n_q, T, head_dim)"""
B, n_kv, T, head_dim = x.shape
if n_rep == 1:
return x
# Expand and reshape: insert group dim, expand, reshape to flatten kv*rep
return (
x.unsqueeze(2) # (B, n_kv, 1, T, head_dim)
.expand(B, n_kv, n_rep, T, head_dim) # (B, n_kv, n_rep, T, head_dim)
.reshape(B, n_kv * n_rep, T, head_dim) # (B, n_q, T, head_dim)
)
def forward(self, x: torch.Tensor, attention_mask: torch.Tensor | None = None,
alibi_bias: torch.Tensor | None = None, use_cache: bool = False,
position_ids: torch.LongTensor | None = None) -> torch.Tensor:
B, T, C = x.size()
# 1. Project Q, K, V
q = self.q_proj(x)
k = self.k_proj(x)
v = self.v_proj(x)
# 2. Reshape Q: (B, T, C) -> (B, n_head, T, head_dim)
q = q.view(B, T, self.n_head, self.head_dim).transpose(1, 2)
# Reshape K/V: (B, T, C_kv) -> (B, n_kv_head, T, head_dim)
k = k.view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2)
v = v.view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2)
# 3. Apply RoPE if enabled (before caching)
if self.use_rope:
current_seq_len = T
q, k = self.rope(q, k, current_seq_len) # Apply RoPE to Q and K (with fewer heads)
# 4. Handle KV Caching (operates on the n_kv_heads dimension)
k_cache, v_cache = self._process_kv_cache(k, v, use_cache, position_ids)
# k_cache, v_cache have shape (B, n_kv_heads, T_full, head_dim)
# 5. Repeat K/V heads to match query heads for attention calculation
# Only repeat if cache is used (T dimension might change) or if T_q != T_k
k_rep = self._repeat_kv(k_cache, self.num_query_groups) # (B, n_head, T_full, head_dim)
v_rep = self._repeat_kv(v_cache, self.num_query_groups) # (B, n_head, T_full, head_dim)