-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
2018 lines (1700 loc) · 83.3 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
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import AutoTokenizer, AutoModel
from dataclasses import dataclass
from typing import List, Dict, Tuple, Optional
import math
import argparse
import random
@dataclass
class CompressionState:
"""Holds the state of a compression operation."""
centroids: torch.Tensor # Compressed token representations
compression_factors: torch.Tensor # Compression factor used for each token
original_tokens: torch.Tensor # Original uncompressed tokens
class RecursiveCompressionLayer(nn.Module):
"""
Layer that compresses its own activations based on semantic similarity.
Args:
d_model (int): Dimension of model embeddings.
compression_factor (int): Factor by which embeddings are reduced.
similarity_threshold (float): Threshold above which two tokens are considered redundant.
position_weight (float): Weight given to positional proximity in similarity calculation.
percentile_threshold (float): Percentile to use for adaptive thresholding (0-100).
preserve_special_tokens (bool): Whether to preserve special tokens from compression.
residual_compression_factor (int): Factor by which residuals are compressed.
use_residuals (bool): Whether to use residual vectors for reconstruction.
residual_gate_threshold (float): Threshold for residual gating (0-1).
residual_sparsity (float): Percentage of residual components to keep.
residual_bits (int): Number of bits to use for quantization.
residual_importance_threshold (float): Threshold for adaptive residual storage.
adaptive_compression (bool): Whether to use adaptive compression based on token importance.
min_compression_factor (int): Minimum compression factor for important tokens.
max_compression_factor (int): Maximum compression factor for unimportant tokens.
attention_weight (float): Weight for attention-based decisions.
contrastive_margin (float): Margin for contrastive loss.
"""
def __init__(
self,
d_model: int,
compression_factor: int = 4,
similarity_threshold: float = 0.75,
position_weight: float = 0.2,
percentile_threshold: float = 95.0,
preserve_special_tokens: bool = True,
residual_compression_factor: int = 4,
use_residuals: bool = True,
residual_gate_threshold: float = 0.1,
residual_sparsity: float = 0.9, # Keep only top 10% components
residual_bits: int = 8, # 8-bit quantization for residuals
residual_importance_threshold: float = 0.1, # Only keep residuals above this reconstruction error
adaptive_compression: bool = True, # Enable adaptive compression
min_compression_factor: int = 2, # Minimum compression for important tokens
max_compression_factor: int = 8, # Maximum compression for unimportant tokens
attention_weight: float = 0.3, # NEW: Weight for attention-based decisions
contrastive_margin: float = 0.2, # NEW: Margin for contrastive loss
):
super().__init__()
self.d_model = d_model
self.compression_factor = compression_factor
self.base_threshold = similarity_threshold # Renamed to base_threshold
self.position_weight = position_weight
self.percentile_threshold = percentile_threshold
self.preserve_special_tokens = preserve_special_tokens
self.residual_compression_factor = residual_compression_factor
self.use_residuals = use_residuals
self.residual_gate_threshold = residual_gate_threshold
self.residual_sparsity = residual_sparsity
self.residual_bits = residual_bits
self.residual_importance_threshold = residual_importance_threshold
self.adaptive_compression = adaptive_compression
self.min_compression_factor = min_compression_factor
self.max_compression_factor = max_compression_factor
self.attention_weight = (
attention_weight # NEW: Weight for attention-based decisions
)
self.contrastive_margin = contrastive_margin # NEW: Margin for contrastive loss
# Compression state
self.centroids = None
self.compressed_residuals = None
self.residual_gates = None
# Flag to enable/disable compression during inference
self.compression_enabled = True
self.last_ce_loss = None # NEW: Track last CE loss for emergency parachute
# New learnable components for adaptive thresholding
self.threshold_modulator = nn.Linear(d_model, 1)
# Contrastive projection head
self.contrastive_projector = nn.Sequential(
nn.Linear(d_model, d_model // 2), nn.GELU(), nn.Linear(d_model // 2, 128)
)
# Compression components - now we'll have multiple compressors for adaptive compression
if adaptive_compression:
# Create multiple compressors with different compression factors
self.compressors = nn.ModuleDict(
{
f"compressor_{factor}": nn.Linear(d_model, d_model // factor)
for factor in range(
min_compression_factor, max_compression_factor + 1
)
}
)
# Default compressor for backward compatibility
self.compressor = self.compressors[f"compressor_{compression_factor}"]
else:
# Single compressor with fixed compression factor
self.compressor = nn.Linear(d_model, d_model // compression_factor)
# Residual compression components
if use_residuals:
# Network to compress residuals
self.residual_compressor = nn.Sequential(
nn.Linear(d_model, d_model // residual_compression_factor),
nn.GELU(),
nn.Linear(d_model // residual_compression_factor, d_model),
)
# Network to learn which parts of residuals are important
self.residual_gate = nn.Sequential(
nn.Linear(d_model, d_model // 4),
nn.GELU(),
nn.Linear(d_model // 4, d_model),
nn.Sigmoid(),
)
# Network to enhance reconstruction
self.reconstruction_enhancer = nn.Sequential(
nn.Linear(d_model * 2, d_model), nn.GELU(), nn.Linear(d_model, d_model)
)
# Enhanced decompressor with attention mechanism
self.compressed_dim = d_model // compression_factor
self.decompressor_query = nn.Linear(self.compressed_dim, self.compressed_dim)
self.decompressor_key = nn.Linear(self.compressed_dim, self.compressed_dim)
self.decompressor_value = nn.Linear(self.compressed_dim, self.compressed_dim)
self.decompressor_mlp = nn.Sequential(
nn.Linear(self.compressed_dim, d_model // 2),
nn.GELU(),
nn.Linear(d_model // 2, d_model),
nn.LayerNorm(d_model),
)
# Token importance estimator
self.importance_estimator = nn.Linear(d_model, 1)
# Adaptive decompressors for different compression factors
if adaptive_compression:
self.decompressors = nn.ModuleDict()
for factor in range(min_compression_factor, max_compression_factor + 1):
compressed_dim = d_model // factor
self.decompressors[f"decompressor_{factor}"] = nn.Sequential(
nn.Linear(compressed_dim, d_model // 2),
nn.GELU(),
nn.Linear(d_model // 2, d_model),
nn.LayerNorm(d_model),
)
# Calculate intermediate dimensions for decompressor
dims = []
current_dim = self.compressed_dim
while current_dim < d_model:
dims.append(current_dim)
current_dim = min(current_dim * 2, d_model)
if dims[-1] != d_model:
dims.append(d_model)
# Initialize decompressor with proper dimension scaling
layers = []
for i in range(len(dims) - 1):
layers.extend(
[
nn.Linear(dims[i], dims[i + 1]),
nn.ReLU() if i < len(dims) - 2 else nn.Identity(),
]
)
self.decompressor = nn.Sequential(*layers)
def compute_adaptive_threshold(self, hidden_states):
"""Dynamically compute threshold based on hidden states distribution."""
# Calculate pairwise similarities for percentile-based threshold
token_embeddings = hidden_states.view(-1, self.d_model)
token_embeddings = F.normalize(token_embeddings, dim=1)
pairwise_sims = torch.matmul(token_embeddings, token_embeddings.transpose(0, 1))
# Get similarity threshold based on percentile
sim_threshold = torch.quantile(
pairwise_sims.view(-1), self.percentile_threshold / 100
)
# Learnable modulation based on context
context_vector = hidden_states.mean(dim=1) # Aggregate context
threshold_mod = torch.sigmoid(self.threshold_modulator(context_vector)) * 0.1
# Final threshold combines base + statistical + learned components
# Base threshold is the floor, not the ceiling
final_threshold = torch.clamp(
self.base_threshold
+ (1 - self.base_threshold) * sim_threshold
+ threshold_mod,
min=self.base_threshold,
max=0.98, # Safety cap to prevent threshold from getting too high
)
return final_threshold
def compute_similarity_matrix(self, hidden_states, attention_scores=None):
"""Compute similarity matrix with optional attention weighting."""
batch_size, seq_length, d_model = hidden_states.shape
# Normalize embeddings for cosine similarity
normalized = F.normalize(hidden_states, dim=2)
# Compute embedding similarity matrix
emb_similarity = torch.bmm(normalized, normalized.transpose(1, 2))
# If attention scores are provided, use them to weight similarity
if attention_scores is not None and self.attention_weight > 0:
# Average across attention heads if needed
if len(attention_scores.shape) == 4: # [batch, heads, seq, seq]
attn = attention_scores.mean(dim=1) # [batch, seq, seq]
else:
attn = attention_scores
# Compute attention pattern similarity
# If two tokens attend to the same context similarly, they're functionally similar
attn_similarity = torch.bmm(attn, attn.transpose(1, 2))
# Combine embedding and attention similarities
combined_sim = (
emb_similarity * (1 - self.attention_weight)
+ attn_similarity * self.attention_weight
)
else:
combined_sim = emb_similarity
# Apply positional penalty
pos_indices = torch.arange(seq_length, device=hidden_states.device)
pos_diff = (pos_indices.unsqueeze(1) - pos_indices.unsqueeze(0)).abs()
pos_penalty = torch.exp(-pos_diff / (seq_length * self.position_weight))
# Final similarity with positional weighting
final_sim = combined_sim * pos_penalty.unsqueeze(0)
return final_sim
def contrastive_loss(self, hidden_states, clusters):
"""Enforce separation between dissimilar token clusters."""
# Project to contrastive space
projections = self.contrastive_projector(hidden_states)
projections = F.normalize(projections, dim=2)
batch_size, seq_length, _ = projections.shape
loss = 0
for b in range(batch_size):
# For each cluster, compute centroid
unique_clusters = torch.unique(clusters[b])
centroids = []
for c in unique_clusters:
mask = clusters[b] == c
if mask.sum() > 0:
centroid = projections[b, mask].mean(0)
centroids.append((c, centroid))
# Contrastive loss between centroids
for i, (c1, cent1) in enumerate(centroids):
for j, (c2, cent2) in enumerate(centroids):
if i != j:
# Push different clusters apart
sim = torch.dot(cent1, cent2)
loss += F.relu(sim - (1 - self.contrastive_margin))
return loss / batch_size if batch_size > 0 else 0
def compress(self, tokens, attention_scores=None):
"""Compress input tokens using adaptive compression."""
batch_size, seq_len, d_model = tokens.shape
device = tokens.device
# Calculate token importances with enhanced metrics
token_importances = self.calculate_token_importance(tokens)
# Calculate adaptive threshold using dynamic percentile
sorted_importances = torch.sort(token_importances)[0]
# Use higher percentile for more selective compression
percentile_idx = int(len(sorted_importances) * 0.90) # Using 90th percentile
adaptive_threshold = sorted_importances[percentile_idx]
# Use the current_threshold (which may be adaptive) instead of base_threshold
# for similarity comparisons in clustering
similarity_threshold = getattr(self, "current_threshold", self.base_threshold)
# Print thresholds for debugging - handle tensor values properly
if isinstance(self.base_threshold, torch.Tensor):
if self.base_threshold.numel() == 1:
base_threshold_val = self.base_threshold.item()
else:
# If it's a multi-element tensor, use the first value
base_threshold_val = self.base_threshold[0].item()
else:
base_threshold_val = self.base_threshold
if isinstance(similarity_threshold, torch.Tensor):
if similarity_threshold.numel() == 1:
similarity_threshold_val = similarity_threshold.item()
else:
# If it's a multi-element tensor, use the first value
similarity_threshold_val = similarity_threshold[0].item()
else:
similarity_threshold_val = similarity_threshold
# Print thresholds for debugging - handle tensor values properly - MAKE LESS VERBOSE
if (
self.training and random.random() < 0.05
): # Only print 5% of the time during training
print(
f"DEBUG: base_threshold={base_threshold_val:.4f}, current_threshold={similarity_threshold_val:.4f}"
)
# Find important tokens with stricter criteria
important_indices = torch.where(token_importances > adaptive_threshold)[0]
# Initialize storage for compressed tokens and their factors
compressed_centroids = []
token_compression_factors = []
# CRITICAL FIX: If similarity threshold is too low, force it higher to prevent over-compression
if similarity_threshold_val < 0.90 and self.training:
print(
f"⚠️ WARNING: Similarity threshold too low ({similarity_threshold_val:.4f}), forcing to minimum 0.90"
)
similarity_threshold_val = max(similarity_threshold_val, 0.90)
# Convert back to tensor if needed
if isinstance(similarity_threshold, torch.Tensor):
similarity_threshold = torch.tensor(
similarity_threshold_val, device=device
)
else:
similarity_threshold = similarity_threshold_val
# NEW SAFETY CHECK: Estimate compression ratio before proceeding
# If we're going to compress too aggressively, adjust threshold immediately
estimated_compression = 0
for i in range(seq_len):
token = tokens[:, i, :]
similarities = torch.cosine_similarity(token.unsqueeze(1), tokens, dim=2)
similar_indices = torch.where(similarities > similarity_threshold_val)[1]
if len(similar_indices) > 1:
estimated_compression += 1
# Get max_compression_ratio if it exists, otherwise use default of 20.0
max_ratio = getattr(self, "max_compression_ratio", 5.0) # Reduced from 20.0
# Calculate how many tokens we need to keep to achieve max_ratio
# We need to keep at least seq_len / max_ratio tokens
# Use floor instead of ceil to ensure we don't exceed max_ratio
tokens_to_keep = math.floor(seq_len / max_ratio)
# Ensure we keep at least 4 tokens (more conservative)
tokens_to_keep = max(tokens_to_keep, 4)
tokens_to_compress = seq_len - tokens_to_keep
# Print target compression info - MAKE LESS VERBOSE
if estimated_compression > 0 and (
not self.training or random.random() < 0.05
): # Only print 5% of the time during training
# Avoid division by zero by ensuring denominator is at least 1
remaining_tokens = max(1, seq_len - estimated_compression)
estimated_ratio = seq_len / remaining_tokens
print(
f"Target compression: {max_ratio:.2f}x (keeping {tokens_to_keep}/{seq_len} tokens, compressing {tokens_to_compress})"
)
if (
estimated_ratio > max_ratio
): # Use configurable upper bound on compression ratio
print(
f"🚨 EMERGENCY: Estimated compression ratio too high ({estimated_ratio:.2f}x)!"
)
print(
f"Forcing similarity threshold higher to prevent model destruction..."
)
# Force much higher threshold to prevent catastrophic compression
similarity_threshold_val = max(
similarity_threshold_val, 0.99
) # Increased from 0.95
if isinstance(similarity_threshold, torch.Tensor):
similarity_threshold = torch.tensor(
similarity_threshold_val, device=device
)
else:
similarity_threshold = similarity_threshold_val
print(f"Emergency threshold adjustment: {similarity_threshold_val:.4f}")
# Also update base threshold for future iterations
self.base_threshold = max(
self.base_threshold, 0.95
) # Increased from 0.90
# NEW: Create a list to track which tokens have been compressed
compressed_token_count = 0
already_compressed = set()
# Process each token with enhanced similarity analysis
for i in range(seq_len):
# NEW: Skip if we've already compressed the maximum allowed tokens
if (
compressed_token_count >= tokens_to_compress
and i not in already_compressed
):
# Just use standard compression for this token without merging
compressed_token = self.compressor(tokens[:, i, :])
factor = self.compression_factor
compressed_centroids.append(compressed_token)
token_compression_factors.append(factor)
continue
token = tokens[:, i, :] # Shape: [batch_size, d_model]
# Enhanced importance-based compression
if i in important_indices:
# Important tokens get lighter compression
compressed_token = self.compressor(
token
) # Shape: [batch_size, compressed_dim]
factor = max(self.min_compression_factor, self.compression_factor - 1)
else:
# Find similar tokens with stricter similarity threshold
similarities = torch.cosine_similarity(
token.unsqueeze(1), tokens, dim=2
)
similar_indices = torch.where(similarities > similarity_threshold_val)[
1
]
if (
len(similar_indices) > 1
and compressed_token_count < tokens_to_compress
):
# Enhanced clustering with attention to token positions
cluster_tokens = tokens[:, similar_indices, :]
# Weight tokens by position similarity
pos_weights = torch.exp(
-0.1
* torch.abs(
torch.arange(len(similar_indices), device=device)
- similar_indices.float()
)
)
weighted_tokens = cluster_tokens * pos_weights.unsqueeze(
-1
).unsqueeze(0)
centroid = torch.sum(weighted_tokens, dim=1) / torch.sum(
pos_weights
)
# Compress with adaptive factor based on cluster size
cluster_size = len(similar_indices)
# Get max_compression_ratio if it exists, otherwise use default max factor
max_factor = min(
getattr(
self, "max_compression_ratio", self.max_compression_factor
),
self.max_compression_factor,
)
# More conservative adaptive factor calculation
# Use logarithm with base 4 instead of base 2 for slower growth
log_factor = math.log(max(cluster_size, 2)) / math.log(4)
adaptive_factor = min(
max_factor, self.compression_factor + int(log_factor)
)
# Cap the adaptive factor to avoid exceeding max_ratio
if hasattr(self, "max_compression_ratio"):
adaptive_factor = min(
adaptive_factor, self.max_compression_ratio
)
compressed_token = self.compressor(centroid)
factor = adaptive_factor
# Track which tokens have been compressed
compressed_token_count += (
len(similar_indices) - 1
) # -1 because we're keeping one token
already_compressed.update(similar_indices.tolist())
else:
# No similar tokens found - use standard compression
compressed_token = self.compressor(token)
factor = self.compression_factor
# Project to uniform compressed dimension with enhanced precision
if compressed_token.shape[-1] != self.compressed_dim:
projection = nn.Linear(
compressed_token.shape[-1], self.compressed_dim, device=device
)
# Initialize projection weights to preserve variance
nn.init.orthogonal_(projection.weight)
compressed_token = projection(compressed_token)
# Apply L2 normalization to maintain vector magnitudes
compressed_token = F.normalize(compressed_token, p=2, dim=-1)
compressed_centroids.append(compressed_token)
token_compression_factors.append(factor)
# Stack results
compressed_centroids = torch.stack(
compressed_centroids, dim=1
) # Shape: [batch_size, seq_len, compressed_dim]
token_compression_factors = torch.tensor(
token_compression_factors, device=device
)
# Create dummy clusters tensor for compatibility with our enhanced implementation
clusters = torch.zeros((batch_size, seq_len), dtype=torch.long, device=device)
# Print actual compression achieved - MAKE LESS VERBOSE
if (
not self.training or random.random() < 0.05
): # Only print 5% of the time during training
# Ensure we never compress all tokens (avoid division by zero)
safe_compressed_token_count = min(compressed_token_count, seq_len - 1)
actual_ratio = (
seq_len / (seq_len - safe_compressed_token_count)
if safe_compressed_token_count > 0
else 1.0
)
print(
f"Actual compression ratio: {actual_ratio:.2f}x (compressed {compressed_token_count}/{seq_len} tokens)"
)
return (
CompressionState(
centroids=compressed_centroids,
compression_factors=token_compression_factors,
original_tokens=tokens,
),
clusters,
)
def forward(self, hidden_states, attention_scores=None, labels=None):
"""Forward pass with dynamic compression and emergency parachute."""
# Store original states for reconstruction loss
original_states = hidden_states.clone()
# Calculate adaptive threshold for this forward pass if in training mode
if self.adaptive_compression and self.training:
adaptive_threshold = self.compute_adaptive_threshold(hidden_states)
# Actually use the computed threshold instead of just the base_threshold
self.current_threshold = adaptive_threshold
else:
self.current_threshold = self.base_threshold
# Apply compression - pass the current threshold to compress method
compressed_state, clusters = self.compress(hidden_states, attention_scores)
# Decompress the state
if isinstance(compressed_state, CompressionState):
compressed_states = self.decompress(compressed_state)
else:
compressed_states = compressed_state
# If we have labels, compute language modeling loss
ce_loss = None
if labels is not None and self.training:
# This assumes we have a projection layer to vocabulary size
if hasattr(self, "output_projection"):
logits = self.output_projection(compressed_states)
ce_loss = F.cross_entropy(
logits.view(-1, logits.size(-1)), labels.view(-1)
)
# Emergency parachute: if CE loss spikes, reduce compression
if self.last_ce_loss is not None:
loss_increase = ce_loss / self.last_ce_loss
# If loss increases dramatically, adjust threshold for next iteration
# Lower the threshold from 1.5 to 1.2 for more sensitivity
if loss_increase > 1.2: # Was 1.5
self.base_threshold = min(0.95, self.base_threshold + 0.05)
print(
f"⚠️ Emergency parachute deployed! Increasing threshold to {self.base_threshold:.2f}"
)
# Make this more aggressive too
elif loss_increase < 0.9: # Was 0.8
self.base_threshold = max(
0.65, self.base_threshold - 0.02
) # More reduction
print(
f"🚀 Compression successful! Decreasing threshold to {self.base_threshold:.2f}"
)
self.last_ce_loss = ce_loss.detach()
# Compute contrastive loss if training
cont_loss = 0
if self.training and clusters is not None:
cont_loss = self.contrastive_loss(hidden_states, clusters)
# Compute reconstruction loss
rec_loss = F.mse_loss(compressed_states, original_states)
# Total loss combines all components
total_loss = 0
if ce_loss is not None:
total_loss = ce_loss + 0.1 * cont_loss + 0.05 * rec_loss
return compressed_states, total_loss
def enable_compression(self):
"""Enable compression during inference."""
self.compression_enabled = True
def disable_compression(self):
"""Disable compression during inference."""
self.compression_enabled = False
def calculate_token_importance(self, activations: torch.Tensor) -> torch.Tensor:
"""
Calculate importance scores for each token to determine which should be preserved.
Args:
activations (torch.Tensor): Token activations of shape (num_tokens, d_model)
Returns:
importance (torch.Tensor): Importance scores of shape (num_tokens,)
"""
# Simple approach: use a learned projection to estimate importance
importance = self.importance_estimator(activations).squeeze(-1)
# Normalize to [0, 1] range
importance = torch.sigmoid(importance)
return importance
def detect_redundancy(
self,
activations: torch.Tensor,
positions: List[int] = None,
token_ids: List[int] = None,
) -> Tuple[torch.Tensor, Dict[int, int]]:
"""
Detect redundant tokens in the input activations.
Args:
activations (torch.Tensor): Token activations of shape (num_tokens, d_model)
positions (List[int], optional): Token positions for positional weighting
token_ids (List[int], optional): Token IDs for special token preservation
Returns:
Tuple[torch.Tensor, Dict[int, int]]: Centroids and token mapping
"""
# Calculate pairwise cosine similarity
activations_norm = F.normalize(activations, p=2, dim=1)
similarity = torch.mm(activations_norm, activations_norm.t())
# Set diagonal to zero to avoid self-similarity
similarity.fill_diagonal_(0)
# Apply positional weighting if positions are provided
if positions is not None:
# Create position distance matrix
num_tokens = similarity.shape[0]
pos_array = torch.tensor(positions, device=similarity.device)
pos_dist = torch.abs(pos_array.unsqueeze(1) - pos_array.unsqueeze(0))
# Convert to similarity (closer = more similar)
max_dist = float(torch.max(pos_dist))
if max_dist > 0: # Avoid division by zero
pos_sim = 1.0 - (pos_dist / max_dist)
# Combine semantic and positional similarity
similarity = (
1 - self.position_weight
) * similarity + self.position_weight * pos_sim
# Use current_threshold (which may be adaptive) instead of just base_threshold
current_threshold = getattr(self, "current_threshold", self.base_threshold)
# Adaptive thresholding based on percentile
flat_sim = similarity.view(-1)
k = int(len(flat_sim) * (self.percentile_threshold / 100.0))
if k > 0: # Ensure we have enough elements
threshold = torch.kthvalue(flat_sim, k).values.item()
print(
f"Adaptive threshold based on {self.percentile_threshold}th percentile: {threshold:.4f}"
)
# Use the higher of adaptive threshold or current threshold
effective_threshold = max(threshold, current_threshold)
else:
effective_threshold = current_threshold
print(f"Effective similarity threshold: {effective_threshold:.4f}")
print(
f"Max similarity between any two tokens: {torch.max(similarity).item():.4f}"
)
# Identify important tokens that should be preserved
important_indices = set()
if token_ids is not None and self.preserve_special_tokens:
# Identify special tokens (this is a simple heuristic for GPT-2)
for i, token_id in enumerate(token_ids):
if token_id < 50: # Most special tokens have low IDs
important_indices.add(i)
# Add tokens with high importance scores
importance_threshold = (
self.calculate_token_importance(activations).median()
+ self.calculate_token_importance(activations).std()
)
for i, imp in enumerate(self.calculate_token_importance(activations)):
if imp > importance_threshold:
important_indices.add(i)
print(f"Preserving {len(important_indices)} important tokens")
redundancy_map = {}
used_indices = set()
# Greedy approach: For each token, find all that exceed the threshold and map them.
for i in range(similarity.shape[0]):
if i in used_indices or i in important_indices:
continue
similar_indices = torch.where(similarity[i] > effective_threshold)[
0
].tolist()
for idx in similar_indices:
# Only map forward to avoid cycles, and don't map important tokens
if idx not in used_indices and idx > i and idx not in important_indices:
redundancy_map[idx] = i
used_indices.add(idx)
# Unique tokens are those that aren't assigned to anything
unique_indices = [
i for i in range(similarity.shape[0]) if i not in redundancy_map
]
compressed_activations = activations[unique_indices]
# Visualize token clusters (for debugging)
self.visualize_token_clusters(similarity, redundancy_map, token_ids)
return (
compressed_activations,
redundancy_map,
self.calculate_token_importance(activations).tolist(),
)
def visualize_token_clusters(
self,
similarity: torch.Tensor,
redundancy_map: Dict[int, int],
token_ids: List[int] = None,
):
"""
Create a simple visualization of token clusters for debugging.
Args:
similarity (torch.Tensor): Similarity matrix
redundancy_map (Dict[int, int]): Mapping of redundant tokens
token_ids (List[int], optional): Original token IDs
"""
# Build clusters
clusters = {}
for idx, rep_idx in redundancy_map.items():
# Follow the chain to find the root representative
root = rep_idx
while root in redundancy_map:
root = redundancy_map[root]
if root not in clusters:
clusters[root] = []
clusters[root].append(idx)
# Print cluster information
print(f"\nFound {len(clusters)} clusters:")
for root, members in clusters.items():
if token_ids is not None:
try:
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("gpt2")
root_token = tokenizer.decode([token_ids[root]])
member_tokens = [tokenizer.decode([token_ids[m]]) for m in members]
print(f" Cluster {root} ('{root_token}'): {member_tokens}")
except:
print(f" Cluster {root}: {members}")
else:
print(f" Cluster {root}: {members}")
print() # Empty line for readability
def get_token_importance_by_type(self, token_ids: List[int]) -> torch.Tensor:
"""
Calculate importance weights for tokens based on their types.
Prioritizes content words (nouns, verbs, adjectives) over function words.
Args:
token_ids: List of token IDs
Returns:
Tensor of importance weights for each token
"""
# Initialize with default importance
importance_weights = torch.ones(
len(token_ids),
device=self.centroids.device if self.centroids is not None else None,
)
# Try to load GPT-2 tokenizer for better token type detection
try:
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("gpt2")
# Decode each token to get its text
for i, token_id in enumerate(token_ids):
token_text = tokenizer.decode([token_id]).strip()
# Special tokens and punctuation get lower importance
if token_id < 50 or token_text in [
".",
",",
"!",
"?",
";",
":",
'"',
"'",
"(",
")",
"[",
"]",
"{",
"}",
]:
importance_weights[i] = 0.5
# Content words (longer tokens) get higher importance
elif len(token_text) > 2 and token_text[0] != " ":
importance_weights[i] = 3.0 # Increased from 2.0
# Beginning of words (tokens with leading space) get medium-high importance
elif token_text.startswith(" ") and len(token_text) > 2:
importance_weights[i] = 2.0 # Increased from 1.5
# Extra boost for likely semantic keywords
if any(
keyword in token_text.lower()
for keyword in [
"neural",
"model",
"language",
"compress",
"semantic",
"efficient",
"represent",
"memory",
"footprint",
]
):
importance_weights[i] *= 1.5
print("Using enhanced token-type aware importance weights")
except:
# Fallback if tokenizer can't be loaded
print("Using simple token ID-based importance weights")
for i, token_id in enumerate(token_ids):
# Special tokens get lower importance
if token_id < 50:
importance_weights[i] = 0.5
# Higher token IDs (likely content words) get higher importance
elif token_id > 1000:
importance_weights[i] = 2.0 # Increased from 1.5
return importance_weights
def compress_residuals(
self,
residuals: torch.Tensor,
original_tokens: torch.Tensor,
centroids: torch.Tensor,
assignments: List[int],
token_ids: List[int] = None,
) -> Dict:
"""
Aggressively compress residuals through sparsification and quantization.
Now with adaptive storage - only keep residuals for tokens where they matter.
Uses token-type awareness to prioritize important tokens.
Args:
residuals: Tensor of shape (num_tokens, d_model) containing residual vectors
original_tokens: Original token activations
centroids: Compressed centroids
assignments: Which centroid each token maps to
token_ids: Original token IDs for token-type awareness
Returns:
Dictionary containing compressed residual information
"""
# First, determine which tokens actually need residuals
# For each token, calculate reconstruction error without residuals
reconstructed_without_residuals = torch.zeros_like(original_tokens)
for i, centroid_idx in enumerate(assignments):
reconstructed_without_residuals[i] = centroids[centroid_idx]
# Calculate reconstruction error for each token
reconstruction_error = torch.norm(
original_tokens - reconstructed_without_residuals, dim=1
)
# Get token importance weights based on token types
token_importance = torch.ones_like(reconstruction_error)
if token_ids is not None:
token_importance = self.get_token_importance_by_type(token_ids)
# Apply token importance to reconstruction error
weighted_error = reconstruction_error * token_importance
# Normalize errors to [0,1] range for easier thresholding
if weighted_error.max() > 0:
normalized_error = weighted_error / weighted_error.max()
else:
normalized_error = weighted_error
# NEW: Analyze semantic importance of tokens in context
# We'll use a sliding window approach to identify tokens that are important for context
semantic_importance = torch.zeros_like(normalized_error)
window_size = min(
5, len(normalized_error)
) # Use a context window of 5 tokens or less
# For each token, check if it's semantically important in its local context
for i in range(len(normalized_error)):
# Get window around current token
start_idx = max(0, i - window_size // 2)
end_idx = min(len(normalized_error), i + window_size // 2 + 1)
window = normalized_error[start_idx:end_idx]
# If this token has higher error than average in its window, it's important
if normalized_error[i] > window.mean():
semantic_importance[i] = normalized_error[i] / window.mean()
else:
semantic_importance[i] = 0.5 # Baseline importance
# Combine semantic importance with normalized error
combined_importance = (normalized_error + semantic_importance) / 2
# Use a much lower threshold for determining which tokens need residuals
# This ensures we keep more residuals, especially for semantically important tokens
adaptive_threshold = max(0.01, self.residual_importance_threshold / 2)
needs_residual = combined_importance > adaptive_threshold
# NEW: Always keep residuals for special tokens and sentence boundaries
if token_ids is not None:
for i, token_id in enumerate(token_ids):
# Special tokens and punctuation often mark important boundaries
if token_id < 50 or token_id in [
13,
30,
50,
764,
837,
13959,
13782,
]: # Common punctuation in GPT-2
needs_residual[i] = True
# Count how many tokens need residuals
num_tokens_with_residuals = torch.sum(needs_residual).item()
tokens_with_residuals_pct = 100 * num_tokens_with_residuals / len(assignments)
print(
f"Tokens needing residuals: {num_tokens_with_residuals}/{len(assignments)} ({tokens_with_residuals_pct:.1f}%)"
)
# If no tokens need residuals, return empty
if num_tokens_with_residuals == 0:
return {"format": "empty", "shape": residuals.shape, "sparsity": 1.0}
# Create mask for tokens that need residuals
token_mask = needs_residual.unsqueeze(1).expand_as(residuals)
# Zero out residuals for tokens that don't need them
masked_residuals = residuals * token_mask
# Now apply component-wise sparsity to the remaining residuals
magnitudes = torch.abs(masked_residuals)