@@ -60,11 +60,16 @@ def compress(
6060 kwargs ,
6161 ):
6262 bsz , n_heads , k_len , _ = keys .shape
63- total_tokens_seen = int (kwargs ["position_ids" ].max ().item ()) + 1
64- n_kept = max (1 , int (total_tokens_seen * (1 - self .target_compression_ratio )))
65- n_kept = min (n_kept , k_len )
66-
67- if n_kept >= k_len :
63+ position_ids = kwargs ["position_ids" ]
64+ if position_ids .dim () == 1 :
65+ position_ids = position_ids .unsqueeze (0 )
66+ if position_ids .shape [0 ] == 1 :
67+ position_ids = position_ids .expand (bsz , - 1 )
68+ total_tokens_seen = position_ids .max (dim = - 1 ).values + 1
69+ n_kept = (total_tokens_seen .float () * (1 - self .target_compression_ratio )).round ().long ()
70+ n_kept = n_kept .clamp (min = 1 , max = k_len )
71+
72+ if (n_kept >= k_len ).all ():
6873 return keys , values
6974
7075 # Build per-head valid mask from accumulated masked_key_indices
@@ -87,7 +92,9 @@ def compress(
8792 )
8893 scores [b , h , valid_pos ] = head_scores [0 , 0 ]
8994
90- threshold = scores .topk (n_kept , dim = - 1 , sorted = True ).values [:, :, - 1 ]
95+ sorted_scores , _ = scores .sort (dim = - 1 , descending = True )
96+ idx = (n_kept - 1 ).view (- 1 , 1 , 1 ).expand (- 1 , n_heads , 1 )
97+ threshold = sorted_scores .gather (- 1 , idx ).squeeze (- 1 )
9198 rejected = scores [:, :, - 1 ] < threshold
9299
93100 if rejected .all ():
0 commit comments