-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
1828 lines (1538 loc) · 68.6 KB
/
main.py
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
# main.py
import os
import sys
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader, IterableDataset
from typing import Optional, Tuple, List, Dict, Any, Iterable, Union
import math
from dataclasses import dataclass
from torch import amp
from torch.amp import autocast # Corrected import
import gc
import wandb
import argparse
import platform
from torch.optim import Optimizer
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.distributed import init_process_group, destroy_process_group, is_initialized
import socket
from collections import deque
import logging
import numpy as np
import random
import itertools
from EnhancedSGD import EnhancedSGD # Ensure this is correctly implemented and accessible
# Configure logging
logging.basicConfig(
level=logging.INFO, # Changed to INFO for standard logs
format='%(asctime)s - %(levelname)s - %(message)s'
)
# ----------------------------
# Sampler Configuration
# ----------------------------
@dataclass
class SamplerConfig:
low_entropy_threshold: float = 0.3
medium_entropy_threshold: float = 1.2
high_entropy_threshold: float = 2.5
# ----------------------------
# ByteTokenizer
# ----------------------------
class ByteTokenizer:
def encode(self, text: str) -> List[int]:
return [b for b in text.encode('utf-8')]
def decode(self, byte_sequence: Iterable[int]) -> str:
return bytes(byte_sequence).decode('utf-8', errors='replace')
# ----------------------------
# BabylonIndex
# ----------------------------
class BabylonIndex:
"""Enhanced index for byte sequence analysis with efficient window management."""
def __init__(
self,
scales: List[int] = [3, 5, 7],
max_cache_size: int = 100000,
min_entropy_threshold: float = 0.3
):
self.scales = scales
self.hash_index = {} # Maps hash values to window positions
self.entropy_cache = {} # LRU cache for entropy values
self.max_cache_size = max_cache_size
self.min_entropy_threshold = min_entropy_threshold
# Pre-compute base powers for efficiency
self.base = 256
self.mod = 2**32
self.base_powers = {
scale: [pow(self.base, i, self.mod) for i in range(scale)]
for scale in scales
}
def _clean_cache(self):
"""Clean entropy cache if it exceeds max size."""
if len(self.entropy_cache) > self.max_cache_size:
# Remove 20% of oldest entries
remove_count = self.max_cache_size // 5
old_keys = list(self.entropy_cache.keys())[:remove_count]
for k in old_keys:
del self.entropy_cache[k]
def _is_valid_utf8_boundary(self, byte_seq: List[int], boundary: int) -> bool:
"""Check if a boundary in the byte sequence does not split a multi-byte UTF-8 character."""
if boundary == 0 or boundary >= len(byte_seq):
return True
# Check the byte before the boundary to see if it's a continuation byte
# Continuation bytes have the form 10xxxxxx
prev_byte = byte_seq[boundary - 1]
if 0x80 <= prev_byte <= 0xBF:
# Find the start of the multi-byte character
start = boundary - 1
while start > 0 and 0x80 <= byte_seq[start - 1] <= 0xBF:
start -= 1
# Number of continuation bytes
num_continuations = boundary - start
first_byte = byte_seq[start]
# Determine the number of bytes in this character based on first byte
if first_byte >> 5 == 0b110:
expected = 2
elif first_byte >> 4 == 0b1110:
expected = 3
elif first_byte >> 3 == 0b11110:
expected = 4
else:
return True # Single-byte character or invalid, allow boundary
return num_continuations < (expected - 1)
return True # Not a continuation byte, allow boundary
def rolling_hash(self, byte_sequence: List[int], scale: int) -> List[Tuple[int, List[int]]]:
"""Compute rolling hashes with corresponding windows.
Args:
byte_sequence: Input bytes as list of integers
scale: Window size
Returns:
List of tuples (hash_value, window_bytes)
"""
results = []
byte_len = len(byte_sequence)
if byte_len < scale:
return results
# Initialize hash value for the first window
window = byte_sequence[:scale]
hash_val = 0
for b in window:
hash_val = (hash_val * self.base + b) % self.mod
results.append((hash_val, window.copy()))
# Rolling hash
for i in range(1, byte_len - scale + 1):
# Remove the leftmost byte and add the new rightmost byte
left_byte = byte_sequence[i - 1]
new_byte = byte_sequence[i + scale - 1]
hash_val = (hash_val * self.base - left_byte * self.base_powers[scale][-1] + new_byte) % self.mod
window = byte_sequence[i:i + scale]
results.append((hash_val, window.copy()))
# Update hash index for future lookups
self.hash_index[hash_val] = (i, i + scale)
return results
def compute_entropy(self, byte_window: np.ndarray) -> float:
"""Compute Shannon entropy of byte window.
Args:
byte_window: Numpy array of bytes
Returns:
Entropy value
"""
# Use numpy for efficient counting
byte_counts = np.bincount(byte_window, minlength=256)
total_bytes = byte_counts.sum()
# Handle zero counts
probs = byte_counts[byte_counts > 0] / total_bytes
return float(-np.sum(probs * np.log2(probs)))
def get_window_features(self, window: List[int]) -> Dict[str, float]:
"""Extract additional features from byte window.
Args:
window: List of bytes
Returns:
Dictionary of feature values
"""
arr = np.array(window)
return {
'mean': float(np.mean(arr)),
'std': float(np.std(arr)),
'unique_ratio': len(np.unique(arr)) / len(arr),
'max_run': max(len(list(g)) for _, g in itertools.groupby(window))
}
def prioritize(self, byte_sequence: List[int]) -> List[Tuple[int, Dict[str, float]]]:
"""Prioritize sequence regions based on entropy and features.
Args:
byte_sequence: Input byte sequence as list of integers
Returns:
List of (hash_value, metrics) tuples sorted by priority
"""
self._clean_cache() # Maintain cache size
# Process each scale
all_scores = []
for scale in self.scales:
hash_windows = self.rolling_hash(byte_sequence, scale)
for hash_val, window in hash_windows:
if hash_val in self.entropy_cache:
metrics = self.entropy_cache[hash_val]
else:
# Compute entropy and features
window_arr = np.array(window)
entropy = self.compute_entropy(window_arr)
# Only process high-entropy regions
if entropy > self.min_entropy_threshold:
features = self.get_window_features(window)
metrics = {
'entropy': entropy,
'scale': scale,
**features
}
self.entropy_cache[hash_val] = metrics
all_scores.append((hash_val, metrics))
# Sort by composite score
def score_window(metrics):
return (
metrics['entropy'] * 0.4 +
metrics['unique_ratio'] * 0.3 +
(1.0 / metrics['scale']) * 0.2 + # Prefer smaller windows
(1.0 / (1.0 + metrics['max_run'])) * 0.1 # Penalize long runs
)
all_scores.sort(key=lambda x: score_window(x[1]), reverse=True)
return all_scores
def get_window_position(self, hash_val: int) -> Optional[Tuple[int, int]]:
"""Get the position of a window from its hash value."""
return self.hash_index.get(hash_val)
def analyze_region(self, byte_sequence: List[int], start: int, end: int) -> Dict[str, float]:
"""Detailed analysis of a specific sequence region."""
if start >= end or end > len(byte_sequence):
return {}
region = byte_sequence[start:end]
return {
'entropy': self.compute_entropy(np.array(region)),
**self.get_window_features(region)
}
def find_patch_boundaries(self, byte_seq: torch.Tensor) -> List[int]:
"""Find patch boundaries ensuring no multi-byte UTF-8 characters are split."""
byte_seq_np = byte_seq.cpu().numpy().tolist()[0] # Assuming batch size 1
# Decode to string with replacement for invalid sequences
try:
decoded_str = bytes(byte_seq_np).decode('utf-8', errors='replace')
# Convert string back to byte indices for valid characters
byte_indices = []
current_byte = 0
for char in decoded_str:
char_bytes = char.encode('utf-8')
current_byte += len(char_bytes)
byte_indices.append(current_byte)
except Exception as e:
logging.error(f"Error decoding byte sequence: {e}")
byte_indices = []
# Now, use the byte_indices as possible patch boundaries
boundaries = []
for boundary in byte_indices:
# Ensure boundary is valid in the original byte sequence
if 0 < boundary < len(byte_seq_np):
boundaries.append(boundary)
# Now, use the BabylonIndex's prioritize method to sort boundaries
prioritized_boundaries = self.prioritize(byte_seq_np)
selected_boundaries = []
for hash_val, metrics in prioritized_boundaries:
pos = self.get_window_position(hash_val)
if pos and self._is_valid_utf8_boundary(byte_seq_np, pos[0]):
selected_boundaries.append(pos[0])
# Ensure boundaries are sorted and unique
selected_boundaries = sorted(list(set(selected_boundaries)))
# Final boundaries aligned with valid UTF-8 character boundaries
final_boundaries = [b for b in selected_boundaries if b in byte_indices]
return final_boundaries
def create_patches(self, byte_seq: torch.Tensor) -> List[torch.Tensor]:
"""Convert byte sequence into patches based on entropy boundaries."""
boundaries = self.find_patch_boundaries(byte_seq)
patches = []
start_idx = 0
for end_idx in boundaries:
if end_idx > start_idx:
patch = byte_seq[:, start_idx:end_idx]
patches.append(patch)
start_idx = end_idx
# Add final patch
if start_idx < byte_seq.size(1):
patches.append(byte_seq[:, start_idx:])
return patches
@torch.no_grad()
def reset_context(self):
"""Reset context when starting new document/segment."""
# Clear any stateful buffers in entropy model
pass
# ----------------------------
# CrossAttentionBlock
# ----------------------------
class CrossAttentionBlock(nn.Module):
"""Cross-attention block that properly mixes byte and patch information."""
def __init__(
self,
hidden_size: int,
num_heads: int = 8,
dropout: float = 0.1,
):
super().__init__()
self.hidden_size = hidden_size
self.num_heads = num_heads
self.head_dim = hidden_size // num_heads
assert self.head_dim * num_heads == hidden_size, "hidden_size must be divisible by num_heads"
# Single projection for Q, K, V
self.qkv = nn.Linear(hidden_size, 3 * hidden_size)
nn.init.normal_(self.qkv.weight, std=0.02)
nn.init.zeros_(self.qkv.bias)
self.out_proj = nn.Linear(hidden_size, hidden_size)
nn.init.normal_(self.out_proj.weight, std=0.02)
nn.init.zeros_(self.out_proj.bias)
self.norm = nn.LayerNorm(hidden_size, eps=1e-6)
self.dropout = nn.Dropout(dropout)
def forward(
self,
queries: torch.Tensor, # [batch_size, num_queries, hidden_size]
keys_values: torch.Tensor, # [batch_size, seq_len, hidden_size]
attention_mask: Optional[torch.Tensor] = None
) -> torch.Tensor:
"""Forward pass with proper masking and scaling."""
batch_size, num_queries, _ = queries.size()
seq_len = keys_values.size(1)
# Layer norm first
queries = self.norm(queries)
keys_values = self.norm(keys_values)
# Project all Q, K, V at once
qkv = self.qkv(queries) # [batch_size, num_queries, 3 * hidden_size]
kv = self.qkv(keys_values) # [batch_size, seq_len, 3 * hidden_size]
# Split into Q, K, V
q = qkv[:, :, :self.hidden_size]
k = kv[:, :, self.hidden_size:2*self.hidden_size]
v = kv[:, :, 2*self.hidden_size:]
# Split heads
q = q.view(batch_size, num_queries, self.num_heads, self.head_dim).transpose(1, 2) # [batch_size, num_heads, num_queries, head_dim]
k = k.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2) # [batch_size, num_heads, seq_len, head_dim]
v = v.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2) # [batch_size, num_heads, seq_len, head_dim]
# Compute attention scores
scale = 1.0 / math.sqrt(self.head_dim)
scores = torch.matmul(q, k.transpose(-2, -1)) * scale # [batch_size, num_heads, num_queries, seq_len]
if attention_mask is not None:
# Expand mask to match attention scores shape
attention_mask = attention_mask.unsqueeze(1).unsqueeze(2) # [batch_size, 1, 1, seq_len]
scores = scores.masked_fill(~attention_mask, float('-inf'))
# Convert scores to probabilities
attn_probs = torch.softmax(scores, dim=-1)
attn_probs = self.dropout(attn_probs)
# Apply attention to values
output = torch.matmul(attn_probs, v) # [batch_size, num_heads, num_queries, head_dim]
# Reshape and project output
output = output.transpose(1, 2).contiguous().view(batch_size, num_queries, self.hidden_size)
output = self.out_proj(output)
output = self.dropout(output)
return output
# ----------------------------
# GlobalLatentTransformer
# ----------------------------
class GlobalLatentTransformer(nn.Module):
"""Large global transformer that processes patch representations."""
def __init__(
self,
hidden_size: int = 1024, # Reduced from 4096
num_layers: int = 16, # Reduced from 32
num_heads: int = 32,
dropout: float = 0.1
):
super().__init__()
# Layer initialization with pre-LayerNorm
self.layers = nn.ModuleList([
nn.ModuleDict({
'norm1': nn.LayerNorm(hidden_size, eps=1e-6),
'attention': nn.MultiheadAttention(
embed_dim=hidden_size,
num_heads=num_heads,
dropout=dropout,
batch_first=True
),
'norm2': nn.LayerNorm(hidden_size, eps=1e-6),
'mlp': nn.Sequential(
nn.Linear(hidden_size, hidden_size * 4),
nn.GELU(),
nn.Dropout(dropout),
nn.Linear(hidden_size * 4, hidden_size),
nn.Dropout(dropout)
)
}) for _ in range(num_layers)
])
self.final_norm = nn.LayerNorm(hidden_size, eps=1e-6)
def create_causal_mask(self, seq_len: int, device: torch.device) -> torch.Tensor:
"""Create causal attention mask."""
return torch.triu(
torch.ones(seq_len, seq_len, device=device),
diagonal=1
).bool()
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""Process patch representations with causal attention."""
# Create causal mask
mask = self.create_causal_mask(x.size(1), x.device)
# Process through transformer layers
for layer in self.layers:
# Pre-LayerNorm for attention
normed = layer['norm1'](x)
# Self-attention with causal masking
attn_output, _ = layer['attention'](
query=normed,
key=normed,
value=normed,
attn_mask=mask,
need_weights=False
)
x = x + attn_output
# Pre-LayerNorm for MLP
normed = layer['norm2'](x)
# MLP block
x = x + layer['mlp'](normed)
return self.final_norm(x)
# ----------------------------
# EntropyGuidedAttention Placeholder
# ----------------------------
class EntropyGuidedAttention(nn.Module):
"""Placeholder for EntropyGuidedAttention. Replace with actual implementation."""
def __init__(self, hidden_size: int, num_heads: int, dropout: float = 0.1):
super().__init__()
self.multihead_attn = nn.MultiheadAttention(hidden_size, num_heads, dropout=dropout, batch_first=True)
self.dropout = nn.Dropout(dropout)
self.norm = nn.LayerNorm(hidden_size, eps=1e-6)
def forward(self, x: torch.Tensor, attention_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
attn_output, _ = self.multihead_attn(x, x, x, attn_mask=attention_mask)
attn_output = self.dropout(attn_output)
x = self.norm(x + attn_output)
return x
# ----------------------------
# BLTModel
# ----------------------------
class BLTModel(nn.Module):
"""Complete Byte Latent Transformer model implementation."""
def __init__(
self,
local_hidden_size: int = 256, # Adjusted to 256
global_hidden_size: int = 1024, # Reduced from 4096
num_local_encoder_layers: int = 1,
num_global_layers: int = 16, # Reduced from 32
num_local_decoder_layers: int = 4, # Reduced from 9
dropout: float = 0.1,
window_size: int = 256, # Smaller window for better memory handling
n_gram_sizes: List[int] = [3, 4], # Reduced n-gram sizes
n_gram_vocab_size: int = 30000 # Smaller n-gram vocab
):
super().__init__()
# Enable memory-efficient attention
if hasattr(torch.backends.cuda, 'enable_mem_efficient_sdp'):
torch.backends.cuda.enable_mem_efficient_sdp(True)
# Entropy-based patching
self.patcher = BabylonIndex(
scales=n_gram_sizes,
max_cache_size=100000,
min_entropy_threshold=0.3
)
# Local encoder for bytes to patches
self.local_encoder = LocalEncoder(
hidden_size=local_hidden_size,
num_layers=num_local_encoder_layers,
num_heads=8,
window_size=window_size,
n_gram_sizes=n_gram_sizes,
n_gram_vocab_size=n_gram_vocab_size
)
# Project patches to global hidden size
self.patch_projection = nn.Sequential(
nn.Linear(local_hidden_size, global_hidden_size),
nn.LayerNorm(global_hidden_size, eps=1e-6)
)
# Global transformer for patches
self.global_transformer = GlobalLatentTransformer(
hidden_size=global_hidden_size,
num_layers=num_global_layers,
num_heads=32,
dropout=dropout
)
# Project back to local hidden size
self.patch_deprojection = nn.Sequential(
nn.Linear(global_hidden_size, local_hidden_size),
nn.LayerNorm(local_hidden_size, eps=1e-6)
)
# Local decoder for patches to bytes
self.local_decoder = LocalDecoder(
hidden_size=local_hidden_size,
num_layers=num_local_decoder_layers,
num_heads=8,
dropout=dropout
)
self.context_size = window_size # For sampling purposes
def forward(
self,
byte_seq: torch.Tensor, # [batch_size, seq_len]
return_patch_boundaries: bool = False
) -> Union[torch.Tensor, Tuple[torch.Tensor, List[int]]]:
"""Complete forward pass of BLT model."""
batch_size, seq_len = byte_seq.size()
device = byte_seq.device
# Find patch boundaries using entropy model
patch_boundaries = self.patcher.find_patch_boundaries(byte_seq)
# Encode bytes into patches
patch_repr = self.local_encoder(byte_seq, patch_boundaries) # [batch_size, num_patches, local_hidden]
# Project to global hidden size
patch_repr = self.patch_projection(patch_repr) # [batch_size, num_patches, global_hidden]
# Process with global transformer
patch_repr = self.global_transformer(patch_repr) # [batch_size, num_patches, global_hidden]
# Project back to local hidden size
patch_repr = self.patch_deprojection(patch_repr) # [batch_size, num_patches, local_hidden]
# Create causal mask for decoder
history_len = 1 # Changed from min(seq_len, 256) to 1 for single-byte prediction
causal_mask = torch.ones(history_len, history_len, device=device).bool() # No masking needed for single byte
# Get byte history embeddings
history = byte_seq[:, -history_len:]
history_embeds = self.local_encoder.byte_embeddings(history)
# Decode to byte predictions
byte_logits = self.local_decoder(
patches=patch_repr,
byte_history=history_embeds,
causal_mask=causal_mask
) # [batch_size, 1, 256]
if return_patch_boundaries:
return byte_logits, patch_boundaries
return byte_logits
@staticmethod
def compute_loss(
logits: torch.Tensor, # [batch_size, 1, 256]
targets: torch.Tensor, # [batch_size]
smoothing: float = 0.1
) -> torch.Tensor:
"""Compute cross entropy loss with label smoothing."""
vocab_size = logits.size(-1)
# Reshape logits and targets for loss computation
logits = logits.view(-1, vocab_size) # [(batch_size * 1), 256]
targets = targets.view(-1) # [(batch_size * 1)]
# Check target indices are within [0, vocab_size-1]
if targets.max() >= vocab_size or targets.min() < 0:
logging.error(f"Target indices out of bounds: min={targets.min()}, max={targets.max()}")
raise ValueError("Target indices exceed vocabulary size!")
# Create smoothed target distribution
with torch.no_grad():
true_dist = torch.zeros_like(logits)
true_dist.fill_(smoothing / (vocab_size - 1))
true_dist.scatter_(-1, targets.unsqueeze(-1), 1.0 - smoothing)
return -torch.sum(true_dist * F.log_softmax(logits, dim=-1), dim=-1).mean()
# ----------------------------
# LocalEncoder
# ----------------------------
class LocalEncoder(nn.Module):
"""Local encoder that efficiently maps bytes to patches."""
def __init__(
self,
hidden_size: int = 256,
num_layers: int = 1,
num_heads: int = 8,
window_size: int = 512,
dropout: float = 0.1,
n_gram_sizes: List[int] = [3, 4, 5],
n_gram_vocab_size: int = 30000
):
super().__init__()
# Byte embeddings
self.byte_embeddings = nn.Embedding(256, hidden_size)
nn.init.normal_(self.byte_embeddings.weight, mean=0.0, std=1.0 / math.sqrt(hidden_size))
# N-gram hash embeddings
self.n_gram_embeddings = nn.ModuleDict({
f'n{n}': nn.Embedding(n_gram_vocab_size, hidden_size)
for n in n_gram_sizes
})
for embed in self.n_gram_embeddings.values():
nn.init.normal_(embed.weight, mean=0.0, std=0.02)
self.n_gram_sizes = n_gram_sizes
self.window_size = window_size
self.n_gram_vocab_size = n_gram_vocab_size # Store for use in hashing
# Local transformer layers with fixed window attention
encoder_layer = nn.TransformerEncoderLayer(
d_model=hidden_size,
nhead=num_heads,
dim_feedforward=hidden_size * 4,
dropout=dropout,
batch_first=True
)
self.transformer = nn.ModuleList([encoder_layer for _ in range(num_layers)])
# Cross attention for patch creation
self.cross_attention = CrossAttentionBlock(
hidden_size=hidden_size,
num_heads=num_heads,
dropout=dropout
)
self.norm = nn.LayerNorm(hidden_size, eps=1e-6)
self.dropout = nn.Dropout(dropout)
def compute_n_gram_hashes(self, byte_seq: torch.Tensor) -> Dict[int, torch.Tensor]:
"""Compute rolling hash values for n-grams efficiently with bounds checking."""
batch_size, seq_len = byte_seq.size()
device = byte_seq.device
hashes = {}
for n in self.n_gram_sizes:
if seq_len < n:
continue
# Use safe indexing with proper bounds checking
n_gram = byte_seq.unfold(1, n, 1) # [batch_size, seq_len - n + 1, n]
powers = torch.tensor([pow(256, i, 2**32) for i in range(n)],
dtype=torch.long, device=device)
# Compute hash: sum(byte * (256^i)) mod 2^32
hash_vals = (n_gram * powers).sum(dim=-1) % 2**32
# Map hash_vals to [0, n_gram_vocab_size - 1]
hash_vals = hash_vals % self.n_gram_vocab_size
hashes[n] = hash_vals
return hashes
def create_local_attention_mask(self, seq_len: int, device: torch.device) -> torch.Tensor:
"""Create local window attention mask with proper bounds checking."""
mask = torch.ones(seq_len, seq_len, dtype=torch.bool, device=device)
window_size = min(self.window_size, seq_len) # Ensure window size doesn't exceed sequence length
for i in range(seq_len):
start = max(0, i - window_size)
end = min(seq_len, i + 1) # +1 for causal masking
mask[i, start:end] = False
return mask
def forward(
self,
byte_seq: torch.Tensor,
patch_boundaries: List[int]
) -> torch.Tensor:
"""Forward pass with safe indexing and bounds checking."""
batch_size, seq_len = byte_seq.size()
# Input validation
if seq_len == 0:
return torch.zeros((batch_size, 1, self.byte_embeddings.embedding_dim),
device=byte_seq.device)
# Get byte embeddings
x = self.byte_embeddings(byte_seq) # [batch_size, seq_len, hidden_size]
# Add n-gram embeddings with safe indexing
n_gram_hashes = self.compute_n_gram_hashes(byte_seq)
n_gram_scale = 1.0 / (len(self.n_gram_sizes) + 1)
for n, hash_vals in n_gram_hashes.items():
valid_length = hash_vals.size(1)
if valid_length > 0:
n_gram_embeds = self.n_gram_embeddings[f'n{n}'](hash_vals) * n_gram_scale
# Safely add embeddings only where we have valid n-grams
x[:, :valid_length] += n_gram_embeds
x = self.dropout(x)
# Process through local transformer layers with safe masking
attention_mask = self.create_local_attention_mask(seq_len, x.device)
for layer in self.transformer:
x = layer(x, src_mask=attention_mask)
# Create patch representations through cross attention with bounds checking
patches = []
start_idx = 0
# Ensure patch boundaries are valid
valid_boundaries = [b for b in patch_boundaries if 0 < b <= seq_len]
if not valid_boundaries:
valid_boundaries = [seq_len]
for end_idx in valid_boundaries:
if end_idx > start_idx:
# Get bytes for this patch
patch_bytes = x[:, start_idx:end_idx]
# Safe mean pooling for query
if patch_bytes.size(1) > 0:
query = torch.mean(patch_bytes, dim=1, keepdim=True)
# Cross attend to create patch representation
patch_repr = self.cross_attention(
queries=query,
keys_values=patch_bytes
)
patches.append(patch_repr)
start_idx = end_idx
# Handle final patch if needed
if start_idx < seq_len:
patch_bytes = x[:, start_idx:]
query = torch.mean(patch_bytes, dim=1, keepdim=True)
patch_repr = self.cross_attention(
queries=query,
keys_values=patch_bytes
)
patches.append(patch_repr)
# Combine patches with safe handling
if patches:
patches = torch.cat(patches, dim=1)
else:
# Fallback if no valid patches were created
patches = x.mean(dim=1, keepdim=True)
return self.norm(patches)
# ----------------------------
# LocalDecoder
# ----------------------------
class LocalDecoder(nn.Module):
"""Local decoder that maps patches back to bytes."""
def __init__(
self,
hidden_size: int = 256, # Adjusted to 256
num_layers: int = 4, # Reduced from 9
num_heads: int = 8,
dropout: float = 0.1
):
super().__init__()
# Cross attention to get initial byte representations from patches
self.initial_cross_attention = CrossAttentionBlock(
hidden_size=hidden_size,
num_heads=num_heads,
dropout=dropout
)
# Transformer decoder layers
decoder_layer = nn.TransformerDecoderLayer(
d_model=hidden_size,
nhead=num_heads,
dim_feedforward=hidden_size * 4,
dropout=dropout,
batch_first=True
)
self.transformer = nn.ModuleList([decoder_layer for _ in range(num_layers)])
# Output projection to bytes with proper initialization
self.byte_pred = nn.Linear(hidden_size, 256)
nn.init.normal_(self.byte_pred.weight, std=0.02)
nn.init.zeros_(self.byte_pred.bias)
self.norm = nn.LayerNorm(hidden_size, eps=1e-6)
self.dropout = nn.Dropout(dropout)
def create_causal_mask(self, seq_len: int, device: torch.device) -> torch.Tensor:
"""Create causal attention mask for decoder."""
return torch.triu(
torch.ones(seq_len, seq_len, device=device),
diagonal=1
).bool()
def forward(
self,
patches: torch.Tensor, # [batch_size, num_patches, hidden_size]
byte_history: torch.Tensor, # [batch_size, history_len, hidden_size]
causal_mask: Optional[torch.Tensor] = None
) -> torch.Tensor:
"""
Decode patches to byte predictions.
Args:
patches: Patch representations from global transformer
byte_history: Embeddings of previous bytes for causal decoding
causal_mask: Optional pre-computed causal mask
Returns:
Logits for next byte prediction [batch_size, history_len, 256]
"""
batch_size = patches.size(0)
history_len = byte_history.size(1)
# Create causal mask if not provided
if causal_mask is None:
causal_mask = self.create_causal_mask(history_len, patches.device)
# Initial cross attention from history to patches
byte_repr = self.initial_cross_attention(
queries=byte_history,
keys_values=patches
)
byte_repr = self.dropout(byte_repr)
# Process through transformer decoder layers
for layer in self.transformer:
byte_repr = layer(
tgt=byte_repr,
memory=patches,
tgt_mask=causal_mask,
tgt_key_padding_mask=None
)
# Project to byte predictions
byte_repr = self.norm(byte_repr)
byte_logits = self.byte_pred(byte_repr) # [batch_size, history_len, 256]
return byte_logits
def generate_step(
self,
patches: torch.Tensor,
byte_history: torch.Tensor,
temperature: float = 1.0,
top_k: int = 50
) -> torch.Tensor:
"""
Generate single next byte prediction for autoregressive generation.
Args:
patches: Current patch representations
byte_history: Previous byte history
temperature: Sampling temperature
top_k: Number of top logits to sample from
Returns:
Predicted next byte index [batch_size, 1]
"""
logits = self(patches, byte_history)[:, -1] # Get predictions for last position
logits = logits / temperature
# Apply top-k sampling
top_k_logits, top_k_indices = torch.topk(logits, k=top_k)
probs = F.softmax(top_k_logits, dim=-1)
# Sample next byte
next_byte_idx = torch.multinomial(probs, num_samples=1)
next_byte = torch.gather(top_k_indices, -1, next_byte_idx).squeeze(-1)
return next_byte
# ----------------------------
# RLHFTrainer
# ----------------------------
class RLHFTrainer:
"""Trainer class that integrates RLHF mechanisms with the training loop."""
def __init__(self, model: nn.Module, optimizer: Optimizer, babylon_index: BabylonIndex, tokenizer: ByteTokenizer, device: torch.device):
self.model = model
self.optimizer = optimizer
self.babylon_index = babylon_index
self.tokenizer = tokenizer
self.device = device
self.criterion = nn.CrossEntropyLoss()
self.scaler = amp.GradScaler(enabled=True)
self._step_count = 0 # Initialize step count
def train_step(self, context: torch.Tensor, target: torch.Tensor, accumulation_steps: int = 1) -> float:
"""
Perform a single training step with gradient accumulation.
Args:
context (torch.Tensor): Input byte sequences [batch_size, context_size].
target (torch.Tensor): Target bytes [batch_size].
accumulation_steps (int): Number of steps to accumulate gradients.
Returns:
float: Loss value.
"""
self.model.train()
loss = None
with autocast(device_type='cuda', enabled=self.scaler.is_enabled()):
# Forward pass with proper handling of cross-attention masking
logits = self.model(context) # [batch_size, 1, 256]
loss = self.model.compute_loss(logits, target) / accumulation_steps
self.scaler.scale(loss).backward()
if (self._step_count + 1) % accumulation_steps == 0:
# Optimizer step
self.scaler.step(self.optimizer)
self.scaler.update()
self.optimizer.zero_grad(set_to_none=True)
self._step_count += 1
return loss.item()
def save_model(self, epoch: int, checkpoint_dir: str = "checkpoints"):
"""Save model checkpoint along with optimizer state."""
os.makedirs(checkpoint_dir, exist_ok=True)
checkpoint_path = os.path.join(checkpoint_dir, f'checkpoint_epoch_{epoch}.pt')
model_state_dict = self.model.module.state_dict() if isinstance(
self.model, DDP
) else self.model.state_dict()
torch.save({
'epoch': epoch,
'model_state_dict': model_state_dict,
'optimizer_state_dict': self.optimizer.state_dict(),
'scaler_state_dict': self.scaler.state_dict(),
}, checkpoint_path)
logging.info(f'Checkpoint saved at {checkpoint_path}')
def load_model(self, checkpoint_path: str) -> int:
"""Load model checkpoint along with optimizer state."""
if not os.path.exists(checkpoint_path):
logging.error(f"Checkpoint file {checkpoint_path} does not exist.")
return 0 # Starting from epoch 0
checkpoint = torch.load(checkpoint_path, map_location='cpu')
model_state_dict = checkpoint['model_state_dict']
optimizer_state_dict = checkpoint['optimizer_state_dict']
scaler_state_dict = checkpoint['scaler_state_dict']
epoch = checkpoint.get('epoch', 0)