guanwenyu1995 commited on
Commit
8cc726f
·
verified ·
1 Parent(s): 76509ae

Update modeling_minicpm.py

Browse files
Files changed (1) hide show
  1. modeling_minicpm.py +382 -709
modeling_minicpm.py CHANGED
@@ -21,10 +21,10 @@ from typing import Any, Dict, List, Optional, Tuple, Union
21
  import torch
22
  import torch.nn.functional as F
23
  import torch.utils.checkpoint
24
- from torch import nn
25
  from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
26
  from transformers.activations import ACT2FN
27
- from transformers.cache_utils import Cache, DynamicCache
28
  from transformers.modeling_attn_mask_utils import (
29
  AttentionMaskConverter,
30
  _prepare_4d_attention_mask,
@@ -47,7 +47,9 @@ from transformers.utils import (
47
  )
48
  from transformers.utils.import_utils import is_torch_fx_available
49
 
50
- from .configuration_minicpm import MiniCPMConfig
 
 
51
 
52
  try:
53
  from flash_attn import flash_attn_func, flash_attn_varlen_func
@@ -57,6 +59,7 @@ try:
57
  infllmv2_attn_varlen_func,
58
  infllmv2_attn_with_kvcache,
59
  max_pooling_1d,
 
60
  )
61
  except:
62
  pass
@@ -64,184 +67,74 @@ except:
64
  from functools import lru_cache
65
 
66
 
67
-
68
- def get_quantizer(quant_type="none", bit=4, group_size=128):
69
- if quant_type == "intsym":
70
- return SteIntSymQuantizerGPTQ(bit, group_size)
71
- elif quant_type == "ternary":
72
- return SteTernaryQuantizer(group_size)
73
- elif quant_type == "none":
74
- return NoQuantizer()
75
- else:
76
- raise ValueError(f"Unsupported quantization type: {quant_type}")
77
-
78
- class SteIntSymQuantizerGPTQ(nn.Module):
79
- def __init__(self, bit=4, group_size=-1):
80
- super().__init__()
81
- self.bit = bit
82
- self.group_size = group_size
83
-
84
- def forward(self, x):
85
- org_w_shape = x.shape
86
-
87
- if self.group_size > 0:
88
- assert org_w_shape[-1] % self.group_size == 0
89
- x = x.reshape(-1, self.group_size)
90
- elif self.group_size == -1:
91
- assert org_w_shape[-1] % self.group_size == 0
92
- x = x.reshape(-1, x.shape[-1])
93
- elif self.group_size == 0:
94
- x = x.reshape(1, -1)
95
-
96
- assert x.dim() == 2
97
-
98
- xmax = x.max(dim=1, keepdim=True)[0]
99
- xmin = x.min(dim=1, keepdim=True)[0]
100
- abs_max_val = torch.maximum(torch.abs(xmin), xmax) # 与Quantizer的xmax计算一致
101
- scales = abs_max_val * 2 / (2 ** self.bit - 1) # 分子分母都对齐
102
-
103
- max_int = 2 ** (self.bit - 1) - 1
104
- min_int = - (2 ** (self.bit - 1))
105
-
106
- assert torch.isnan(scales).sum() == 0
107
-
108
- x_q = (torch.clamp(torch.round(x / scales), min_int, max_int)) * scales
109
-
110
- assert torch.isnan(x_q).sum() == 0
111
-
112
- x = x.reshape(org_w_shape)
113
- x_q = x_q.reshape(org_w_shape)
114
-
115
- return x + (x_q - x).detach()
116
-
117
- class SteTernaryQuantizer(nn.Module):
118
- def __init__(self, group_size):
119
- super().__init__()
120
- self.group_size = group_size
121
-
122
- def forward(self, x):
123
- org_w_shape = x.shape
124
- if self.group_size > 0:
125
- assert x.shape[-1] % self.group_size == 0
126
- x = x.reshape(-1, self.group_size)
127
- elif self.group_size == -1:
128
- x = x.reshape(-1, x.shape[-1])
129
-
130
- assert x.dim() == 2
131
-
132
- scales = 1.0 / (x.abs().mean(dim=1, keepdim=True).clamp_(min=1e-5))
133
- x_q = (torch.clamp(torch.round(x * scales),-1,1) / scales)
134
-
135
- assert torch.isnan(x_q).sum() == 0
136
-
137
- x = x.reshape(org_w_shape)
138
- x_q = x_q.reshape(org_w_shape)
139
-
140
- return x + (x_q - x).detach()
141
-
142
- class NoQuantizer(nn.Module):
143
- def __init__(self):
144
- super().__init__()
145
-
146
- def forward(self, x):
147
- return x
148
-
149
- class LinearQuantizer(nn.Linear):
150
- def __init__(self, in_features, out_features, bias=False, quant_type="ternary", bit=4, group_size=-1):
151
- super().__init__(in_features, out_features, bias)
152
- self.quantizer = get_quantizer(quant_type, bit, group_size)
153
-
154
- def forward(self, x):
155
- weight_tensor = self.quantizer(self.weight)
156
- x = torch.nn.functional.linear(x, weight_tensor)
157
- if self.bias is not None:
158
- x = x + self.bias
159
- return x
160
-
161
  def compressed_attention(
162
  q: torch.Tensor,
163
  k: torch.Tensor,
164
- v: torch.Tensor,
165
  kernel_size: int,
166
  kernel_stride: int,
167
  block_size: int,
168
  topk: int,
169
  cu_seqlens_q: torch.Tensor,
170
  cu_seqlens_k: torch.Tensor,
 
171
  max_seqlen_q: int,
172
  max_seqlen_k: int,
173
  sm_scale: float = None,
174
  init_blocks: int = 1,
175
  local_blocks: int = 2,
176
- parallel_topk_compute: Union[str, bool] = 'auto',
177
- total_seq_lens=-1,
178
  ) -> Tuple[torch.Tensor, torch.Tensor]:
179
- """Attention between query and compressed key and value. Compute attention output and topk block idx used in topk_sparse_attention.
180
-
181
- Args:
182
- q (torch.Tensor): shape [total_q_len, num_q_heads, head_dim]
183
- k (torch.Tensor): shape [total_kv_len, num_kv_heads, head_dim]
184
- v (torch.Tensor): shape [total_kv_len, num_kv_heads, head_dim]
185
- kernel_size (int): kernel size in compress_key_value
186
- kernel_stride (int): stride of compress_key_value
187
- block_size (int): key value block size for topk sparse attention.
188
- topk (int): number of blocks for each query.
189
- cu_seqlens_q (torch.Tensor): shape [batch_size + 1], similar to cu_seqlens_q in flash_attn_func_varlen.
190
- cu_seqlens_k (torch.Tensor): shape [batch_size + 1], similar to cu_seqlens_k in flash_attn_func_varlen.
191
- max_seqlen_q (int): max q len of the batch.
192
- max_seqlen_k (int): max k len of the batch.
193
- sm_scale (float, optional): softmax scale. Defaults to None, means 1/sqrt(head_dim).
194
- init_blocks (int, optional): Number of init blocks for each query. Defaults to 1.
195
- local_blocks (int, optional): Number of local blocks for each query. Defaults to 2.
196
- parallel_topk_compute (str, optional): Only set it to False when the sequence length is too long. This can avoid a current bug.
197
- We'll fix this issue later. Defaults to auto, it will be set to False when the sequence length is greater than 32k and True otherwise.
198
-
199
- Returns:
200
- Tuple[torch.Tensor, torch.Tensor]: attention output and topk_idx used in topk_sparse_attention
201
- """
202
  with torch.no_grad():
203
- cache_len = 0
204
  batch_size = cu_seqlens_q.shape[0] - 1
205
- if total_seq_lens == -1:
206
- total_seq_lens = max_seqlen_q
207
- q_idx = torch.cat(
208
- [
209
- torch.arange(cu_seqlens_q[i + 1] - cu_seqlens_q[i], device=q.device) + total_seq_lens - (cu_seqlens_q[i + 1] - cu_seqlens_q[i])
210
- for i in range(batch_size)
211
- ],
212
- dim=0,
213
- )
214
- q_idx = q_idx // block_size
215
-
216
- else:
217
- cache_len = total_seq_lens - max_seqlen_q
218
- assert batch_size == 1, 'batch_size must be 1 when total_seq_lens is set'
219
- q_idx = torch.tensor([total_seq_lens - 1], device=q.device, dtype=torch.int32) // block_size
220
-
 
221
  score = infllmv2_attn_stage1(
222
  q.contiguous(),
223
  k.contiguous(),
224
- v.contiguous(),
225
  cu_seqlens_q=cu_seqlens_q,
226
  cu_seqlens_k=cu_seqlens_k,
 
227
  max_seqlen_q=max_seqlen_q,
228
  max_seqlen_k=max_seqlen_k,
229
- causal=q_idx.shape[0] > 1)
230
- score = score[:, :q_idx.shape[0], :]
231
-
232
- # Replace transform_score with max_pooling_1d
233
- block_score = max_pooling_1d(
234
  score.contiguous(),
235
- cache_len=cache_len,
 
 
 
 
236
  local_blocks=local_blocks,
237
  init_blocks=init_blocks,
238
  block_size=block_size,
239
- stride=kernel_stride,
240
- )
 
 
241
  # get topk
242
  topk = min(topk, block_score.shape[-1])
243
  topk_idx = block_score.topk(topk, dim=-1).indices.sort(-1).values
244
- topk_idx[topk_idx >= q_idx[None, :, None]] = -1
245
  topk_idx = topk_idx.to(torch.int32)
246
 
247
  return topk_idx
@@ -340,299 +233,133 @@ class CompressK(torch.nn.Module):
340
  return compressed_k, cu_seqlens_compressed
341
 
342
 
343
- class DynamicCacheQKV(DynamicCache):
344
- """
345
- A cache that grows dynamically as more tokens are generated. This is the default for generative models.
346
-
347
- It stores the Key and Value states as a list of tensors, one for each layer. The expected shape for each tensor is
348
- `[batch_size, num_heads, seq_len, head_dim]`.
349
-
350
- Example:
351
- ```python
352
- >>> from transformers import AutoTokenizer, AutoModelForCausalLM, DynamicCache
353
-
354
- >>> model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B-Instruct")
355
- >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct")
356
-
357
- >>> inputs = tokenizer(text="My name is Qwen2", return_tensors="pt")
358
 
359
- >>> # Prepare a cache class and pass it to model's forward
360
- >>> past_key_values = DynamicCache()
361
- >>> outputs = model(**inputs, past_key_values=past_key_values, use_cache=True)
362
- >>> outputs.past_key_values # access cache filled with key/values from generation
363
- DynamicCache()
364
- ```
365
- """
366
- def __init__(self, num_hidden_layers: Optional[int] = None) -> None:
367
  super().__init__()
368
- if num_hidden_layers is None:
369
- self.key_cache: List[torch.Tensor] = []
370
- self.value_cache: List[torch.Tensor] = []
371
- self.compress_k_cache: List[torch.Tensor] = []
372
- self.no_compress_k_cache: List[torch.Tensor] = []
373
- self.cached_compressed_cu_seqlens: List[torch.Tensor] = []
374
- self.no_rope_key_cache: List[torch.Tensor] = []
 
 
 
 
 
 
 
 
375
  else:
376
- self.key_cache: List[torch.Tensor] = [[] for _ in range(num_hidden_layers)]
377
- self.value_cache: List[torch.Tensor] = [[] for _ in range(num_hidden_layers)]
378
- self.compress_k_cache: List[torch.Tensor] = [[] for _ in range(num_hidden_layers)]
379
- self.no_compress_k_cache: List[torch.Tensor] = [[] for _ in range(num_hidden_layers)]
380
- self.cached_compressed_cu_seqlens: List[torch.Tensor] = [[] for _ in range(num_hidden_layers)]
381
- self.no_rope_key_cache: List[torch.Tensor] = [[] for _ in range(num_hidden_layers)]
382
- self._seen_tokens = 0 # Used in `generate` to keep tally of how many tokens the cache has seen
383
-
384
- def __getitem__(self, layer_idx: int) -> List[Tuple[torch.Tensor]]:
385
- """
386
- Support for backwards-compatible `past_key_value` indexing, e.g. `past_key_value[0][0].shape[2]` to get the
387
- sequence length.
388
- """
389
- if layer_idx < len(self):
390
- return (self.key_cache[layer_idx], self.value_cache[layer_idx])
391
  else:
392
- raise KeyError(f'Cache only has {len(self)} layers, attempted to access layer with index {layer_idx}')
393
-
394
- def __iter__(self):
395
- """
396
- Support for backwards-compatible `past_key_value` iteration, e.g. `for x in past_key_value:` to iterate over
397
- keys and values
398
- """
399
- for layer_idx in range(len(self)):
400
- yield (self.key_cache[layer_idx], self.value_cache[layer_idx])
401
-
402
- def __len__(self):
403
- """
404
- Support for backwards-compatible `past_key_value` length, e.g. `len(past_key_value)`. This value corresponds
405
- to the number of layers in the model.
406
- """
407
- return len(self.key_cache)
408
-
409
- def update(
410
- self,
411
- key_states: torch.Tensor,
412
- value_states: torch.Tensor,
413
- layer_idx: int,
414
- cache_kwargs: Optional[Dict[str, Any]] = None
415
- ) -> Tuple[torch.Tensor, torch.Tensor]:
416
- """
417
- Updates the cache with the new `key_states` and `value_states` for the layer `layer_idx`.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
418
 
419
- Parameters:
420
- key_states (`torch.Tensor`):
421
- The new key states to cache.
422
- value_states (`torch.Tensor`):
423
- The new value states to cache.
424
- layer_idx (`int`):
425
- The index of the layer to cache the states for.
426
- cache_kwargs (`Dict[str, Any]`, `optional`):
427
- Additional arguments for the cache subclass. No additional arguments are used in `DynamicCache`.
428
-
429
- Return:
430
- A tuple containing the updated key and value states.
431
- """
432
- # Update the number of seen tokens
433
  if layer_idx == 0:
434
  self._seen_tokens += key_states.shape[-2]
 
435
 
436
- # Update the cache
437
- if len(self.key_cache) <= layer_idx:
438
- self.key_cache.append(key_states)
439
- self.value_cache.append(value_states)
440
-
441
- # content on layer cache can be a tensor and checking not tensor causes errors
442
- # so we explicitly check for the empty list
443
- elif self.key_cache[layer_idx] == []:
444
- self.key_cache[layer_idx] = key_states
445
- self.value_cache[layer_idx] = value_states
446
 
447
- else:
448
- self.key_cache[layer_idx] = torch.cat([self.key_cache[layer_idx], key_states], dim=-2)
449
- self.value_cache[layer_idx] = torch.cat([self.value_cache[layer_idx], value_states], dim=-2)
450
- return self.key_cache[layer_idx], self.value_cache[layer_idx]
451
-
452
- def update_no_rope_key(
453
- self,
454
- key_states: torch.Tensor,
455
- layer_idx: int,
456
- cache_kwargs: Optional[Dict[str, Any]] = None):
457
-
458
- # Update the cache
459
- if len(self.no_rope_key_cache) <= layer_idx:
460
- self.no_rope_key_cache.append(key_states)
461
-
462
- # content on layer cache can be a tensor and checking not tensor causes errors
463
- # so we explicitly check for the empty list
464
- elif self.no_rope_key_cache[layer_idx] == []:
465
- self.no_rope_key_cache[layer_idx] = key_states
466
- else:
467
- self.no_rope_key_cache[layer_idx] = torch.cat([self.no_rope_key_cache[layer_idx], key_states], dim=1)
468
- return self.no_rope_key_cache[layer_idx]
469
-
470
- def update_compress_k(
471
- self,
472
- key_states: torch.Tensor,
473
- layer_idx: int,
474
- cache_kwargs: Optional[Dict[str, Any]] = None
475
- ) -> Tuple[torch.Tensor, torch.Tensor]:
476
- """
477
- Updates the cache with the new `key_states` and `value_states` for the layer `layer_idx`.
478
-
479
- Parameters:
480
- key_states (`torch.Tensor`):
481
- The new key states to cache.
482
- value_states (`torch.Tensor`):
483
- The new value states to cache.
484
- layer_idx (`int`):
485
- The index of the layer to cache the states for.
486
- cache_kwargs (`Dict[str, Any]`, `optional`):
487
- Additional arguments for the cache subclass. No additional arguments are used in `DynamicCache`.
488
-
489
- Return:
490
- A tuple containing the updated key and value states.
491
- """
492
 
493
- # Update the cache
494
- if len(self.compress_k_cache) <= layer_idx:
495
- self.compress_k_cache.append(key_states)
496
 
497
- # content on layer cache can be a tensor and checking not tensor causes errors
498
- # so we explicitly check for the empty list
499
- elif self.compress_k_cache[layer_idx] == []:
500
- self.compress_k_cache[layer_idx] = key_states
501
- else:
502
- self.compress_k_cache[layer_idx] = torch.cat([self.compress_k_cache[layer_idx], key_states], dim=0)
503
- return self.compress_k_cache[layer_idx]
504
 
505
- def update_no_compress_k(
506
- self,
507
- key_states: torch.Tensor,
508
- layer_idx: int,
509
- kernel_size: int = 32,
510
- kernel_stride: int = 16,
511
- cache_kwargs: Optional[Dict[str, Any]] = None
512
- ) -> Tuple[torch.Tensor, torch.Tensor]:
513
- """
514
- Updates the cache with the new `key_states` and `value_states` for the layer `layer_idx`.
515
 
516
- Parameters:
517
- key_states (`torch.Tensor`):
518
- The new key states to cache.
519
- value_states (`torch.Tensor`):
520
- The new value states to cache.
521
- layer_idx (`int`):
522
- The index of the layer to cache the states for.
523
- cache_kwargs (`Dict[str, Any]`, `optional`):
524
- Additional arguments for the cache subclass. No additional arguments are used in `DynamicCache`.
525
-
526
- Return:
527
- A tuple containing the updated key and value states.
528
- """
529
- # Update the cache
530
- if len(self.no_compress_k_cache) <= layer_idx:
531
- self.no_compress_k_cache.append(key_states)
532
-
533
- # content on layer cache can be a tensor and checking not tensor causes errors
534
- # so we explicitly check for the empty list
535
- elif self.no_compress_k_cache[layer_idx] == []:
536
- self.no_compress_k_cache[layer_idx] = key_states
537
- else:
538
- self.no_compress_k_cache[layer_idx] = torch.cat([self.no_compress_k_cache[layer_idx], key_states], dim=0)
539
 
540
- current_len = self.no_compress_k_cache[layer_idx].shape[0]
 
 
541
 
542
- if current_len >= kernel_size:
543
- k_chunk = self.no_compress_k_cache[layer_idx][:kernel_size]
544
- self.no_compress_k_cache[layer_idx] = self.no_compress_k_cache[layer_idx][kernel_stride:]
545
- return k_chunk
546
- else:
547
- return None
548
-
549
- def get_seq_length(self, layer_idx: Optional[int] = 0) -> int:
550
- """Returns the sequence length of the cached states. A layer index can be optionally passed."""
551
- # TODO: deprecate this function in favor of `cache_position`
552
- if len(self.key_cache) <= layer_idx or (len(self.key_cache) > layer_idx and self.key_cache[layer_idx] == []):
553
- return 0
554
- return self.key_cache[layer_idx].shape[-2]
555
-
556
- def get_max_length(self) -> Optional[int]:
557
- """Returns the maximum sequence length of the cached states. DynamicCache does not have a maximum length."""
558
- return None
559
-
560
- def to_legacy_cache(self) -> Tuple[Tuple[torch.Tensor], Tuple[torch.Tensor]]:
561
- """Converts the `DynamicCache` instance into the its equivalent in the legacy cache format. Used for
562
- backward compatibility."""
563
- legacy_cache = ()
564
- for layer_idx in range(len(self)):
565
- legacy_cache += ((self.key_cache[layer_idx], self.value_cache[layer_idx]),)
566
- return legacy_cache
567
-
568
- # @classmethod
569
- # def from_legacy_cache(
570
- # cls, past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None, num_hidden_layers: int = None
571
- # ) -> "DynamicCacheQKV":
572
- # """Converts a cache in the legacy cache format into an equivalent `DynamicCache`. Used for
573
- # backward compatibility."""
574
- # cache = cls(num_hidden_layers)
575
- # if past_key_values is not None:
576
- # for layer_idx in range(len(past_key_values)):
577
- # key_states, value_states, query_status = past_key_values[layer_idx]
578
- # cache.update(key_states, value_states, query_status,layer_idx)
579
- # return cache
580
-
581
- def crop(self, max_length: int):
582
- """Crop the past key values up to a new `max_length` in terms of tokens. `max_length` can also be
583
- negative to remove `max_length` tokens. This is used in assisted decoding and contrastive search."""
584
- # In case it is negative
585
- if max_length < 0:
586
- max_length = self.get_seq_length() - abs(max_length)
587
-
588
- if self.get_seq_length() <= max_length:
589
- return
590
-
591
- self._seen_tokens = max_length
592
- for idx in range(len(self.key_cache)):
593
- if self.key_cache[idx] != []:
594
- self.key_cache[idx] = self.key_cache[idx][..., :max_length, :]
595
- self.value_cache[idx] = self.value_cache[idx][..., :max_length, :]
596
-
597
- def batch_split(self, full_batch_size: int, split_size: int, num_hidden_layers: int) -> List['DynamicCacheQKV']:
598
- """Split the current instance into a list of `DynamicCache` by the batch size. This will be used by
599
- `_split_model_inputs()` in `generation.utils`"""
600
- out = []
601
- for i in range(0, full_batch_size, split_size):
602
- current_split = DynamicCacheQKV(num_hidden_layers)
603
- current_split._seen_tokens = self._seen_tokens
604
- current_split.key_cache = [tensor[i: i + split_size] for tensor in self.key_cache]
605
- current_split.value_cache = [tensor[i: i + split_size] for tensor in self.value_cache]
606
- out.append(current_split)
607
- return out
608
-
609
- @classmethod
610
- def from_batch_splits(cls, splits: List['DynamicCacheQKV'], num_hidden_layers: int) -> 'DynamicCacheQKV':
611
- """This is the opposite of the above `batch_split()` method. This will be used by `stack_model_outputs` in
612
- `generation.utils`"""
613
- cache = cls(num_hidden_layers)
614
- for idx in range(len(splits[0])):
615
- key_cache = [current.key_cache[idx] for current in splits if current.key_cache[idx] != []]
616
- value_cache = [current.key_cache[idx] for current in splits if current.key_cache[idx] != []]
617
- query_cache = [current.key_cache[idx] for current in splits if current.key_cache[idx] != []]
618
- if key_cache != []:
619
- layer_keys = torch.cat(key_cache, dim=0)
620
- layer_values = torch.cat(value_cache, dim=0)
621
- layer_query = torch.cat(query_cache, dim=0)
622
- cache.update(layer_keys, layer_values, idx, query_states=layer_query)
623
- return cache
624
-
625
- def batch_repeat_interleave(self, repeats: int):
626
- """Repeat the cache `repeats` times in the batch dimension. Used in contrastive search."""
627
- for layer_idx in range(len(self)):
628
- self.key_cache[layer_idx] = self.key_cache[layer_idx].repeat_interleave(repeats, dim=0)
629
- self.value_cache[layer_idx] = self.value_cache[layer_idx].repeat_interleave(repeats, dim=0)
630
-
631
- def batch_select_indices(self, indices: torch.Tensor):
632
- """Only keep the `indices` in the batch dimension of the cache. Used in contrastive search."""
633
- for layer_idx in range(len(self)):
634
- self.key_cache[layer_idx] = self.key_cache[layer_idx][indices, ...]
635
- self.value_cache[layer_idx] = self.value_cache[layer_idx][indices, ...]
636
 
637
 
638
  # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
@@ -661,22 +388,6 @@ def _get_unpad_data(attention_mask):
661
  )
662
 
663
 
664
- def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
665
- warnings.warn(
666
- 'Calling `transformers.models.minicpm.modeling_minicpm._prepare_4d_attention_mask` is deprecated and will be removed in v4.37. Use `transformers.modeling_attn_mask_utils._prepare_4d_attention_mask'
667
- )
668
- return _prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
669
-
670
-
671
- def _make_causal_mask(
672
- input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
673
- ):
674
- warnings.warn(
675
- 'Calling `transformers.models.minicpm.modeling_minicpm._make_causal_mask` is deprecated and will be removed in v4.37. Use `transformers.models.minicpm.modeling_minicpm.AttentionMaskConverter._make_causal_mask'
676
- )
677
- return AttentionMaskConverter._make_causal_mask(
678
- input_ids_shape=input_ids_shape, dtype=dtype, device=device, past_key_values_length=past_key_values_length
679
- )
680
 
681
 
682
  # @torch.jit.script # type: ignore
@@ -863,12 +574,9 @@ class MiniCPMMLP(nn.Module):
863
  self.config = config
864
  self.hidden_size = config.hidden_size
865
  self.intermediate_size = config.intermediate_size
866
- self.gate_proj = LinearQuantizer(self.hidden_size, self.intermediate_size, bias=False, quant_type="ternary", bit=4, group_size=-1)
867
- self.up_proj = LinearQuantizer(self.hidden_size, self.intermediate_size, bias=False, quant_type="ternary", bit=4, group_size=-1)
868
- self.down_proj = LinearQuantizer(self.intermediate_size, self.hidden_size, bias=False, quant_type="ternary", bit=4, group_size=-1)
869
- # self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
870
- # self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
871
- # self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
872
  self.act_fn = ACT2FN[config.hidden_act]
873
 
874
  def forward(self, x):
@@ -893,7 +601,21 @@ class MiniCPMMLP(nn.Module):
893
 
894
  return down_proj
895
 
896
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
897
  def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
898
  """
899
  This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
@@ -936,14 +658,10 @@ class MiniCPMAttention(nn.Module):
936
  f' and `num_heads`: {self.num_heads}).'
937
  )
938
 
939
- # self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
940
- # self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
941
- # self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
942
- # self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
943
- self.q_proj = LinearQuantizer(config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias, quant_type="ternary", bit=4, group_size=-1)
944
- self.k_proj = LinearQuantizer(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias, quant_type="ternary", bit=4, group_size=-1)
945
- self.v_proj = LinearQuantizer(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias, quant_type="ternary", bit=4, group_size=-1)
946
- self.o_proj = LinearQuantizer(config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias, quant_type="ternary", bit=4, group_size=-1)
947
  self._init_rope()
948
 
949
  def _init_rope(self):
@@ -1028,15 +746,7 @@ class MiniCPMAttention(nn.Module):
1028
  key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
1029
  value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
1030
 
1031
- kv_seq_len = key_states.shape[-2]
1032
- if past_key_value is not None:
1033
- if self.layer_idx is None:
1034
- raise ValueError(
1035
- f'The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} '
1036
- 'for auto-regressive decoding with k/v caching, please make sure to initialize the attention class '
1037
- 'with a layer index.'
1038
- )
1039
- kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
1040
  cos, sin = self.rotary_emb(value_states.to(torch.float32), seq_len=kv_seq_len)
1041
 
1042
  query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
@@ -1138,9 +848,7 @@ class MiniCPMFlashAttention2(MiniCPMAttention):
1138
  key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
1139
  value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
1140
 
1141
- kv_seq_len = key_states.shape[-2]
1142
- if past_key_value is not None:
1143
- kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
1144
  cos, sin = self.rotary_emb(value_states.to(torch.float32), seq_len=kv_seq_len)
1145
  query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
1146
 
@@ -1312,9 +1020,11 @@ class MiniCPMInfLLMv2Attention(MiniCPMAttention):
1312
  self.dense_len = self.config.sparse_config.get('dense_len', 8192)
1313
 
1314
  self.local_blocks = self.window_size // self.block_size # local_blocks
1315
- self.topk = self.config.sparse_config.get('topk', 64)
1316
  self.use_nope = self.config.sparse_config.get('use_nope', False)
 
1317
  self.compress_k = CompressK(self.num_key_value_heads, self.head_dim, kernel_size=self.kernel_size, kernel_stride=self.kernel_stride)
 
1318
 
1319
  def forward(
1320
  self,
@@ -1338,7 +1048,7 @@ class MiniCPMInfLLMv2Attention(MiniCPMAttention):
1338
  output_attentions = False
1339
 
1340
  bsz, q_len, _ = hidden_states.size()
1341
- assert bsz == 1, 'Only batch_size=1 is supported at the moment.'
1342
 
1343
  query_states = self.q_proj(hidden_states)
1344
  key_states = self.k_proj(hidden_states)
@@ -1356,9 +1066,7 @@ class MiniCPMInfLLMv2Attention(MiniCPMAttention):
1356
  key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
1357
  value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
1358
 
1359
- kv_seq_len = key_states.shape[-2]
1360
- if past_key_value is not None:
1361
- kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
1362
  cos, sin = self.rotary_emb(value_states.to(torch.float32), seq_len=kv_seq_len)
1363
  query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
1364
 
@@ -1372,12 +1080,12 @@ class MiniCPMInfLLMv2Attention(MiniCPMAttention):
1372
  key_states = key_states.transpose(1, 2)
1373
  value_states = value_states.transpose(1, 2)
1374
  if self.use_nope:
 
1375
  no_rope_param = {
1376
  'key_states_no_rope': key_states_no_rope,
1377
  'query_states_no_rope': query_states_no_rope,
1378
  }
1379
- if kv_seq_len <= self.dense_len:
1380
- past_key_value.update_no_rope_key(key_states_no_rope, self.layer_idx)
1381
  else:
1382
  no_rope_param = None
1383
 
@@ -1409,15 +1117,11 @@ class MiniCPMInfLLMv2Attention(MiniCPMAttention):
1409
  if kv_seq_len < self.dense_len:
1410
  attn_output = self._flash_attention_forward_dense(
1411
  query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate)
1412
- elif past_key_value is None or q_len != 1: # prefilling
1413
- attn_output = self._flash_attention_forward(
1414
  query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate,
1415
  no_rope_param=no_rope_param, # if past_key_value is not None else None,
1416
  past_key_value=past_key_value)
1417
- else:
1418
- attn_output = self._flash_attention_forward_with_kv_cache(
1419
- query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate, no_rope_param=no_rope_param, past_key_value=past_key_value)
1420
-
1421
  attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
1422
  attn_output = self.o_proj(attn_output)
1423
 
@@ -1426,123 +1130,180 @@ class MiniCPMInfLLMv2Attention(MiniCPMAttention):
1426
 
1427
  return attn_output, attn_weights, past_key_value
1428
 
1429
- def _flash_attention_forward(
1430
- self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None, no_rope_param=None, past_key_value=None
1431
- ):
1432
- """
1433
- Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
1434
- first unpad the input, then computes the attention scores and pad the final attention scores.
1435
-
1436
- Args:
1437
- query_states (`torch.Tensor`):
1438
- Input query states to be passed to Flash Attention API
1439
- key_states (`torch.Tensor`):
1440
- Input key states to be passed to Flash Attention API
1441
- value_states (`torch.Tensor`):
1442
- Input value states to be passed to Flash Attention API
1443
- attention_mask (`torch.Tensor`):
1444
- The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
1445
- position of padding tokens and 1 for the position of non-padding tokens.
1446
- dropout (`int`, *optional*):
1447
- Attention dropout
1448
- softmax_scale (`float`, *optional*):
1449
- The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
1450
- """
1451
- if not self._flash_attn_uses_top_left_mask:
1452
- causal = self.is_causal
1453
- else:
1454
- # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in MiniCPMFlashAttention2 __init__.
1455
- causal = self.is_causal and query_length != 1
1456
- # Contains at least one padding token in the sequence
1457
- if attention_mask is not None:
1458
- batch_size = query_states.shape[0]
1459
- query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
1460
- query_states, key_states, value_states, attention_mask, query_length
1461
- )
1462
- if no_rope_param is not None:
1463
- # nope unpad
1464
- no_rope_param['query_states_no_rope'] = no_rope_param['query_states_no_rope'].squeeze(0)
1465
- no_rope_param['key_states_no_rope'] = no_rope_param['key_states_no_rope'].squeeze(0)
1466
-
1467
- cu_seqlens_q, cu_seqlens_k = cu_seq_lens
1468
- max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
1469
- attn_output_unpad = self.sparse_forward(
1470
- query_states,
1471
- key_states,
1472
- value_states,
1473
- cu_seqlens_q,
1474
- cu_seqlens_k,
1475
- max_seqlen_in_batch_q,
1476
- max_seqlen_in_batch_k,
1477
- no_rope_param=no_rope_param,
1478
- past_key_value=past_key_value,
1479
- )
1480
-
1481
- attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
1482
- else:
1483
- raise ValueError('Need attention mask')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1484
 
1485
- return attn_output
 
 
 
1486
 
1487
- def _flash_attention_forward_with_kv_cache(
1488
- self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None, no_rope_param=None, past_key_value=None
1489
- ):
1490
  """
1491
- Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
1492
- first unpad the input, then computes the attention scores and pad the final attention scores.
1493
-
1494
  Args:
1495
- query_states (`torch.Tensor`):
1496
- Input query states to be passed to Flash Attention API
1497
- key_states (`torch.Tensor`):
1498
- Input key states to be passed to Flash Attention API
1499
- value_states (`torch.Tensor`):
1500
- Input value states to be passed to Flash Attention API
1501
- attention_mask (`torch.Tensor`):
1502
- The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
1503
- position of padding tokens and 1 for the position of non-padding tokens.
1504
- dropout (`int`, *optional*):
1505
- Attention dropout
1506
- softmax_scale (`float`, *optional*):
1507
- The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
1508
  """
1509
- if not self._flash_attn_uses_top_left_mask:
1510
- causal = self.is_causal
1511
- else:
1512
- # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in MiniCPMFlashAttention2 __init__.
1513
- causal = self.is_causal and query_length != 1
1514
- # Contains at least one padding token in the sequence
1515
- if attention_mask is not None:
1516
-
1517
- batch_size = query_states.shape[0]
1518
-
1519
- # query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
1520
- # query_states, key_states, value_states, attention_mask, query_length=query_length
1521
- # )
1522
-
1523
- assert batch_size == 1, 'Only batch_size=1 is supported at the moment.'
1524
- # prepare past kv ,new kv
1525
- new_q = query_states
1526
-
1527
- new_k = key_states[:, -1:, :, :].contiguous()
1528
- new_v = value_states[:, -1:, :, :].contiguous()
1529
-
1530
- past_k = key_states[:, :-1, :, :].contiguous()
1531
- past_v = value_states[:, :-1, :, :].contiguous()
1532
- if no_rope_param is not None:
1533
- # nope unpad
1534
- no_rope_param['query_states_no_rope'] = no_rope_param['query_states_no_rope'].squeeze(0)
1535
- no_rope_param['key_states_no_rope'] = no_rope_param['key_states_no_rope'].squeeze(0)
1536
 
1537
- attn_output = self.sparse_forward_with_kv_cache(
1538
- past_k=past_k, past_v=past_v, new_k=new_k, new_v=new_v, new_q=new_q, batch_size=batch_size, no_rope_param=no_rope_param, past_key_value=past_key_value)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1539
 
1540
- # attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1541
  else:
1542
- raise ValueError('need attention mask')
1543
-
1544
- return attn_output
1545
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1546
  def sparse_forward(self,
1547
  query_layer,
1548
  key_layer,
@@ -1552,37 +1313,32 @@ class MiniCPMInfLLMv2Attention(MiniCPMAttention):
1552
  max_seqlen_in_batch_q,
1553
  max_seqlen_in_batch_k,
1554
  no_rope_param=None,
1555
- past_key_value=None):
1556
- stage1_k = key_layer if no_rope_param is None else no_rope_param['key_states_no_rope']
1557
- compressed_k, compressed_cu_seqlens = self.compress_k(stage1_k, cu_seqlens_k)
1558
- compressed_v = compressed_k.clone()
1559
- if past_key_value is not None:
1560
- # Compute the start indices of keys (k) that were not compressed, Only batch_size=1 is supported at the moment.
1561
- no_compress_k_start = compressed_k.shape[0] * self.kernel_stride
1562
- past_key_value.update_compress_k(
1563
- compressed_k, self.layer_idx
1564
- )
1565
- past_key_value.update_no_compress_k(
1566
- key_layer[no_compress_k_start:], self.layer_idx, no_compress_k_start)
1567
- past_key_value.cached_compressed_cu_seqlens.append(compressed_cu_seqlens)
1568
  compressed_seqlens = compressed_cu_seqlens[1:] - compressed_cu_seqlens[:-1]
 
 
 
 
 
1569
  topk_idx = compressed_attention(
1570
  query_layer if no_rope_param is None else no_rope_param['query_states_no_rope'],
1571
  compressed_k,
1572
- compressed_v,
1573
  self.kernel_size,
1574
  self.kernel_stride,
1575
  self.block_size,
1576
  self.topk,
1577
  cu_seqlens_q,
1578
  compressed_cu_seqlens,
 
1579
  max_seqlen_in_batch_q,
1580
  compressed_seqlens.max().item(),
1581
  None,
1582
  init_blocks=self.init_blocks,
1583
  local_blocks=self.local_blocks,
 
1584
  )
1585
-
1586
  topk_attn_output = infllmv2_attn_varlen_func(
1587
  query_layer,
1588
  key_layer,
@@ -1594,102 +1350,14 @@ class MiniCPMInfLLMv2Attention(MiniCPMAttention):
1594
  dropout_p=0.0,
1595
  deterministic=False,
1596
  softmax_scale=None,
1597
- causal=True,
1598
  return_attn_probs=False,
1599
- block_window_size=self.window_size // self.block_size,
1600
  topk_idx=topk_idx
1601
  )
1602
 
1603
  return topk_attn_output
1604
 
1605
- def sparse_forward_with_kv_cache(self, past_k=None, past_v=None, new_k=None, new_v=None, new_q=None, batch_size=None, no_rope_param=None, past_key_value=None):
1606
-
1607
- # stage1_k = new_k.squeeze(0) if no_rope_param is None else no_rope_param['key_states_no_rope']
1608
- if past_k.shape[1] + new_k.shape[1] == self.dense_len and (past_key_value.compress_k_cache == [] or len(past_key_value.compress_k_cache) < self.layer_idx + 1 or past_key_value.compress_k_cache[self.layer_idx] == []):
1609
- if no_rope_param is not None:
1610
- stage1_k = past_key_value.no_rope_key_cache[self.layer_idx].squeeze(0).contiguous() # just batch_size ==1
1611
- else:
1612
- stage1_k = torch.cat([past_k, new_k], dim=1).contiguous().squeeze(0).contiguous() # just batch_size ==1
1613
- compressed_k, compressed_cu_seqlens = self.compress_k(stage1_k, torch.tensor([0, stage1_k.shape[0]], device=stage1_k.device, dtype=torch.int32)) # just batch_size ==1
1614
-
1615
- # Compute the start indices of keys (k) that were not compressed, Only batch_size=1 is supported at the moment.
1616
- no_compress_k_start = compressed_k.shape[0] * self.kernel_stride
1617
- past_key_value.update_compress_k(
1618
- compressed_k, self.layer_idx
1619
- )
1620
- past_key_value.update_no_compress_k(
1621
- stage1_k[no_compress_k_start:], self.layer_idx, no_compress_k_start)
1622
- past_key_value.cached_compressed_cu_seqlens.append(compressed_cu_seqlens)
1623
-
1624
- else:
1625
- stage1_k = new_k.squeeze(0) if no_rope_param is None else no_rope_param['key_states_no_rope']
1626
- no_compress_k = past_key_value.update_no_compress_k(
1627
- stage1_k, self.layer_idx, kernel_stride=self.kernel_stride, kernel_size=self.kernel_size)
1628
- if no_compress_k is not None:
1629
- compressed_k = no_compress_k.mean(dim=0, keepdim=True) # [1, n_heads_k, head_dim]
1630
-
1631
- compressed_k = past_key_value.update_compress_k(
1632
- compressed_k, self.layer_idx) # [seqlen, nheads_k, head_dim]
1633
-
1634
- past_key_value.cached_compressed_cu_seqlens[self.layer_idx][-1] += 1 # !Increment the last entry in sequence lengths by 1; currently supports only batch_size = 1
1635
- compressed_cu_seqlens = past_key_value.cached_compressed_cu_seqlens[self.layer_idx]
1636
- else:
1637
- compressed_k = past_key_value.compress_k_cache[self.layer_idx] # [seqlen, nheads_k, head_dim]
1638
- compressed_cu_seqlens = past_key_value.cached_compressed_cu_seqlens[self.layer_idx]
1639
-
1640
- compressed_v = compressed_k.clone()
1641
-
1642
- compressed_seqlens = compressed_cu_seqlens[1:] - compressed_cu_seqlens[:-1]
1643
- torch.cuda.synchronize()
1644
- # Manually verify that the lengths match
1645
- assert compressed_k.shape[0] == compressed_seqlens.sum().item(), 'The length of compressed_k does not match the sum of compressed_seqlens'
1646
- topk_idx = compressed_attention(
1647
- new_q.squeeze(0).contiguous() if no_rope_param is None else no_rope_param['query_states_no_rope'],
1648
- compressed_k,
1649
- compressed_v,
1650
- self.kernel_size,
1651
- self.kernel_stride,
1652
- self.block_size,
1653
- self.topk,
1654
- torch.tensor([0, 1], device=compressed_k.device, dtype=torch.int32),
1655
- compressed_cu_seqlens,
1656
- 1,
1657
- compressed_seqlens.max().item(),
1658
- None,
1659
- init_blocks=self.init_blocks,
1660
- local_blocks=self.local_blocks,
1661
- total_seq_lens=past_k.shape[1] + 1, # !Only batch_size=1 is supported at the moment.
1662
- )
1663
-
1664
- repeat_times = 1
1665
- if repeat_times > 1:
1666
- new_q = new_q.repeat_interleave(repeat_times, dim=-2)
1667
- else:
1668
- new_q = new_q
1669
-
1670
- cache_batch_idx = torch.arange(batch_size, device=new_q.device, dtype=torch.int32)
1671
-
1672
- seqlen_k = past_k.shape[1] + new_k.shape[1] # !Only batch_size=1 is supported at the moment.
1673
- seqlens_k = torch.full((batch_size,), seqlen_k - 1, dtype=torch.int32, device=new_q.device)
1674
-
1675
- past_k = torch.cat([past_k, torch.zeros_like(new_k, dtype=new_k.dtype)], dim=1).contiguous() # Append one zero vector to avoid potential out-of-bounds access
1676
- past_v = torch.cat([past_v, torch.zeros_like(new_v, dtype=new_v.dtype)], dim=1).contiguous() # Append one zero vector to avoid potential out-of-bounds access
1677
- topk_attn_output = infllmv2_attn_with_kvcache(
1678
- q=new_q,
1679
- k_cache=past_k,
1680
- v_cache=past_v,
1681
- topk_idx=topk_idx,
1682
- block_window_size=self.window_size // self.block_size,
1683
- k=new_k, # [batch_size, 1, nheads_k, d]
1684
- v=new_v, # [batch_size, 1, nheads_k, d]
1685
- cache_seqlens=seqlens_k, # current_seqlens_k-1
1686
- rotary_cos=None, # No rotary embeddings
1687
- rotary_sin=None, # No rotary embeddings
1688
- cache_batch_idx=cache_batch_idx,
1689
- causal=False, # Renaming to match function signature
1690
- )
1691
- return topk_attn_output
1692
-
1693
  def _flash_attention_forward_dense(
1694
  self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
1695
  ):
@@ -1828,9 +1496,7 @@ class MiniCPMSdpaAttention(MiniCPMAttention):
1828
  key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
1829
  value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
1830
 
1831
- kv_seq_len = key_states.shape[-2]
1832
- if past_key_value is not None:
1833
- kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
1834
  cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
1835
 
1836
  query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
@@ -2153,11 +1819,13 @@ class MiniCPMModel(MiniCPMPreTrainedModel):
2153
  raise ValueError(
2154
  'You must use the new past_key_values format, such as the Cache class, instead of the old tuple format.'
2155
  )
2156
- past_key_values = DynamicCache.from_legacy_cache(past_key_values)
2157
 
2158
- past_key_values_length = past_key_values.get_usable_length(seq_length)
 
 
 
2159
  if self.config.sparse_config is not None and torch.cuda.is_available() and past_key_values_length == 0:
2160
- past_key_values = DynamicCacheQKV()
2161
 
2162
  if position_ids is None:
2163
  device = input_ids.device if input_ids is not None else inputs_embeds.device
@@ -2383,12 +2051,17 @@ class MiniCPMForCausalLM(MiniCPMPreTrainedModel):
2383
  ):
2384
  if past_key_values is not None:
2385
  if isinstance(past_key_values, Cache):
 
2386
  cache_length = past_key_values.get_seq_length()
2387
- past_length = past_key_values.seen_tokens
2388
- max_cache_length = None # past_key_values.get_max_length()
2389
- else:
2390
- cache_length = past_length = past_key_values[0][0].shape[2]
2391
  max_cache_length = None
 
 
 
 
2392
 
2393
  # Keep only the unprocessed tokens:
2394
  # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
@@ -2607,4 +2280,4 @@ class MiniCPMForSequenceClassification(MiniCPMPreTrainedModel):
2607
  past_key_values=transformer_outputs.past_key_values,
2608
  hidden_states=transformer_outputs.hidden_states,
2609
  attentions=transformer_outputs.attentions,
2610
- )
 
21
  import torch
22
  import torch.nn.functional as F
23
  import torch.utils.checkpoint
24
+ from torch import nn
25
  from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
26
  from transformers.activations import ACT2FN
27
+ from transformers.cache_utils import Cache, DynamicCache, CacheLayerMixin, DynamicLayer
28
  from transformers.modeling_attn_mask_utils import (
29
  AttentionMaskConverter,
30
  _prepare_4d_attention_mask,
 
47
  )
48
  from transformers.utils.import_utils import is_torch_fx_available
49
 
50
+
51
+
52
+ from .configuration_minicpm import MiniCPMConfig #!一定要改
53
 
54
  try:
55
  from flash_attn import flash_attn_func, flash_attn_varlen_func
 
59
  infllmv2_attn_varlen_func,
60
  infllmv2_attn_with_kvcache,
61
  max_pooling_1d,
62
+ max_pooling_1d_varlen
63
  )
64
  except:
65
  pass
 
67
  from functools import lru_cache
68
 
69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  def compressed_attention(
71
  q: torch.Tensor,
72
  k: torch.Tensor,
73
+ k2: torch.Tensor,
74
  kernel_size: int,
75
  kernel_stride: int,
76
  block_size: int,
77
  topk: int,
78
  cu_seqlens_q: torch.Tensor,
79
  cu_seqlens_k: torch.Tensor,
80
+ cu_seqlens_k2: torch.Tensor,
81
  max_seqlen_q: int,
82
  max_seqlen_k: int,
83
  sm_scale: float = None,
84
  init_blocks: int = 1,
85
  local_blocks: int = 2,
86
+ cache_lens=None,
 
87
  ) -> Tuple[torch.Tensor, torch.Tensor]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  with torch.no_grad():
 
89
  batch_size = cu_seqlens_q.shape[0] - 1
90
+
91
+ # Check if it's prefilling stage
92
+ is_prefilling = cache_lens is None or (cache_lens == 0).all().item()
93
+
94
+ if is_prefilling: # prefilling stage
95
+ # Calculate q_idx for each query position in each batch
96
+ cache_lens = torch.zeros(batch_size, dtype=torch.int32, device=q.device)
97
+ q_idx = torch.cat([
98
+ (torch.arange(cu_seqlens_q[i + 1] - cu_seqlens_q[i], device=q.device) +
99
+ max_seqlen_q - (cu_seqlens_q[i + 1] - cu_seqlens_q[i])) // block_size
100
+ for i in range(batch_size)
101
+ ], dim=0) # shape: [total_q_len]
102
+ else: # decoding stage
103
+ # Each batch has only one query (last position)
104
+ q_idx = cache_lens // block_size # shape: [batch_size] = [total_q_len] in decoding
105
+
106
+ # 计算attention score
107
  score = infllmv2_attn_stage1(
108
  q.contiguous(),
109
  k.contiguous(),
110
+ k2.contiguous(),
111
  cu_seqlens_q=cu_seqlens_q,
112
  cu_seqlens_k=cu_seqlens_k,
113
+ cu_seqlens_v=cu_seqlens_k2,
114
  max_seqlen_q=max_seqlen_q,
115
  max_seqlen_k=max_seqlen_k,
116
+ causal=is_prefilling
117
+ )
118
+ score = score[:, :q_idx.shape[0], :] # [num_heads, total_q_len, num_blocks]
119
+
120
+ block_score = max_pooling_1d_varlen(
121
  score.contiguous(),
122
+ cu_seqlens_q,
123
+ cu_seqlens_k,
124
+ cache_lens,
125
+ max_seqlen_q,
126
+ max_seqlen_k,
127
  local_blocks=local_blocks,
128
  init_blocks=init_blocks,
129
  block_size=block_size,
130
+ stride=kernel_stride
131
+ ) # shape: [num_heads, total_q_len, num_blocks]
132
+
133
+
134
  # get topk
135
  topk = min(topk, block_score.shape[-1])
136
  topk_idx = block_score.topk(topk, dim=-1).indices.sort(-1).values
137
+ topk_idx[topk_idx > q_idx[None, :, None]] = -1
138
  topk_idx = topk_idx.to(torch.int32)
139
 
140
  return topk_idx
 
233
  return compressed_k, cu_seqlens_compressed
234
 
235
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
 
237
+ class InfLLMv2CacheLayer(DynamicLayer):
238
+ def __init__(self):
 
 
 
 
 
 
239
  super().__init__()
240
+ # Initialize any additional attributes specific to InfLLMv2CacheLayer
241
+ self.no_rope_keys = torch.tensor([], dtype=torch.float32)
242
+ self.compress_k_cache = []
243
+ self.no_compress_k_cache = []
244
+ self.cached_compressed_cu_seqlens = torch.tensor([], dtype=torch.int32)
245
+ self.compress_k_cache_varlen = torch.tensor([], dtype=torch.float32)
246
+ # Add support for compress_k2
247
+ self.compress_k2_cache = []
248
+ self.cached_compressed_cu_seqlens2 = torch.tensor([], dtype=torch.int32)
249
+ self.compress_k2_cache_varlen = torch.tensor([], dtype=torch.float32)
250
+ self.no_compress_k2_cache = []
251
+
252
+ def update_no_rope_key(self, key_states):
253
+ if self.no_rope_keys.numel() == 0:
254
+ self.no_rope_keys = key_states
255
  else:
256
+ self.no_rope_keys = torch.cat([self.no_rope_keys, key_states], dim=1)
257
+ return self.no_rope_keys
258
+
259
+ def update_compress_k(self, key_states, cu_seqlens=None):
260
+ if len(self.compress_k_cache) == 0:
261
+ if cu_seqlens is not None:
262
+ self.cached_compressed_cu_seqlens = cu_seqlens.clone()
263
+ self.compress_k_cache_varlen = key_states
264
+ split_sizes = (cu_seqlens[1:] - cu_seqlens[:-1]).tolist()
265
+ self.compress_k_cache = list(torch.split(key_states, split_sizes))
 
 
 
 
 
266
  else:
267
+ for index, k in enumerate(key_states):
268
+ if k is not None:
269
+ self.compress_k_cache[index] = torch.cat([self.compress_k_cache[index], k], dim=0)
270
+ new_seq_lens = torch.tensor([tensor.shape[0] for tensor in self.compress_k_cache], dtype=torch.int32)
271
+ new_cumsum = torch.cumsum(new_seq_lens, dim=0, dtype=torch.int32)
272
+
273
+ self.compress_k_cache_varlen = torch.cat(self.compress_k_cache, dim=0)
274
+ self.cached_compressed_cu_seqlens = torch.cat([torch.tensor([0], dtype=torch.int32), new_cumsum]).to(self.compress_k_cache_varlen.device)
275
+ return self.compress_k_cache_varlen, self.cached_compressed_cu_seqlens
276
+
277
+ def update_no_compress_k(self, key_states, kernel_size=32, kernel_stride=16):
278
+ k_chunk_list = []
279
+ for index, k in enumerate(key_states):
280
+ if len(self.no_compress_k_cache) <= index:
281
+ self.no_compress_k_cache.append(k)
282
+ else:
283
+ self.no_compress_k_cache[index] = torch.cat([self.no_compress_k_cache[index], k], dim=0)
284
+ current_len = self.no_compress_k_cache[index].shape[0]
285
+ if current_len >= kernel_size:
286
+ k_chunk_list.append(self.no_compress_k_cache[index][:kernel_size])
287
+ self.no_compress_k_cache[index] = self.no_compress_k_cache[index][kernel_stride:]
288
+ else:
289
+ k_chunk_list.append(None)
290
+ return k_chunk_list
291
+
292
+ def update_compress_k2(self, key_states, cu_seqlens=None):
293
+ if len(self.compress_k2_cache) == 0:
294
+ if cu_seqlens is not None:
295
+ self.cached_compressed_cu_seqlens2 = cu_seqlens.clone()
296
+ self.compress_k2_cache_varlen = key_states
297
+ split_sizes = (cu_seqlens[1:] - cu_seqlens[:-1]).tolist()
298
+ self.compress_k2_cache = list(torch.split(key_states, split_sizes))
299
+ else:
300
+ for index, k in enumerate(key_states):
301
+ if k is not None:
302
+ self.compress_k2_cache[index] = torch.cat([self.compress_k2_cache[index], k], dim=0)
303
+ new_seq_lens = torch.tensor([tensor.shape[0] for tensor in self.compress_k2_cache], dtype=torch.int32)
304
+ new_cumsum = torch.cumsum(new_seq_lens, dim=0, dtype=torch.int32)
305
+
306
+ self.compress_k2_cache_varlen = torch.cat(self.compress_k2_cache, dim=0)
307
+ self.cached_compressed_cu_seqlens2 = torch.cat([torch.tensor([0], dtype=torch.int32), new_cumsum]).to(self.compress_k2_cache_varlen.device)
308
+ return self.compress_k2_cache_varlen, self.cached_compressed_cu_seqlens2
309
+
310
+ def update_no_compress_k2(self, key_states, kernel_size=128, kernel_stride=64):
311
+ k_chunk_list = []
312
+ for index, k in enumerate(key_states):
313
+ if len(self.no_compress_k2_cache) <= index:
314
+ self.no_compress_k2_cache.append(k)
315
+ else:
316
+ self.no_compress_k2_cache[index] = torch.cat([self.no_compress_k2_cache[index], k], dim=0)
317
+ current_len = self.no_compress_k2_cache[index].shape[0]
318
+ if current_len >= kernel_size:
319
+ k_chunk_list.append(self.no_compress_k2_cache[index][:kernel_size])
320
+ self.no_compress_k2_cache[index] = self.no_compress_k2_cache[index][kernel_stride:]
321
+ else:
322
+ k_chunk_list.append(None)
323
+ return k_chunk_list
324
+
325
+ class InfLLMv2Cache(DynamicCache):
326
+ def __init__(self, config,num_hidden_layers: Optional[int] = None) -> None:
327
+ super().__init__(config=config)
328
+ self.layers = [InfLLMv2CacheLayer() for _ in range(num_hidden_layers)] if num_hidden_layers else []
329
+ self._seen_tokens = 0
330
+
331
 
332
+ def update(self, key_states, value_states, layer_idx, cache_kwargs=None):
 
 
 
 
 
 
 
 
 
 
 
 
 
333
  if layer_idx == 0:
334
  self._seen_tokens += key_states.shape[-2]
335
+ return self.layers[layer_idx].update(key_states, value_states, cache_kwargs)
336
 
337
+ def update_no_rope_key(self, key_states, layer_idx, cache_kwargs=None):
338
+ return self.layers[layer_idx].update_no_rope_key(key_states)
 
 
 
 
 
 
 
 
339
 
340
+ def update_compress_k(self, key_states, layer_idx, cu_seqlens=None, cache_kwargs=None):
341
+ return self.layers[layer_idx].update_compress_k(key_states, cu_seqlens)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
342
 
343
+ def update_no_compress_k(self, key_states, layer_idx, kernel_size=32, kernel_stride=16, cache_kwargs=None):
344
+ return self.layers[layer_idx].update_no_compress_k(key_states, kernel_size, kernel_stride)
 
345
 
346
+ def update_compress_k2(self, key_states, layer_idx, cu_seqlens=None, cache_kwargs=None):
347
+ return self.layers[layer_idx].update_compress_k2(key_states, cu_seqlens)
 
 
 
 
 
348
 
349
+ def update_no_compress_k2(self, key_states, layer_idx, kernel_size=128, kernel_stride=64, cache_kwargs=None):
350
+ return self.layers[layer_idx].update_no_compress_k2(key_states, kernel_size, kernel_stride)
 
 
 
 
 
 
 
 
351
 
352
+ def crop(self, max_length):
353
+ for layer in self.layers:
354
+ layer.crop(max_length)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
355
 
356
+ def batch_repeat_interleave(self, repeats):
357
+ for layer in self.layers:
358
+ layer.batch_repeat_interleave(repeats)
359
 
360
+ def batch_select_indices(self, indices):
361
+ for layer in self.layers:
362
+ layer.batch_select_indices(indices)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
363
 
364
 
365
  # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
 
388
  )
389
 
390
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
391
 
392
 
393
  # @torch.jit.script # type: ignore
 
574
  self.config = config
575
  self.hidden_size = config.hidden_size
576
  self.intermediate_size = config.intermediate_size
577
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
578
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
579
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
 
 
 
580
  self.act_fn = ACT2FN[config.hidden_act]
581
 
582
  def forward(self, x):
 
601
 
602
  return down_proj
603
 
604
+ def _unpad_one_tensor(hidden_states, attention_mask):
605
+ # Unpad the hidden states using the indices
606
+ indices, cu_seqlens, max_seqlen_in_batch = _get_unpad_data(attention_mask)
607
+ batch_size, seq_len = hidden_states.shape[:2]
608
+
609
+ # Get the remaining dimensions
610
+ remaining_dims = hidden_states.shape[2:]
611
+
612
+ # Reshape to (batch_size * seq_len, *remaining_dims)
613
+ reshaped_states = hidden_states.reshape(batch_size * seq_len, *remaining_dims)
614
+
615
+ # Apply unpadding using indices
616
+ unpadded_states = index_first_axis(reshaped_states, indices)
617
+
618
+ return unpadded_states, indices, cu_seqlens, max_seqlen_in_batch
619
  def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
620
  """
621
  This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
 
658
  f' and `num_heads`: {self.num_heads}).'
659
  )
660
 
661
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
662
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
663
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
664
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
 
 
 
 
665
  self._init_rope()
666
 
667
  def _init_rope(self):
 
746
  key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
747
  value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
748
 
749
+ kv_seq_len = position_ids.max().item() + 1
 
 
 
 
 
 
 
 
750
  cos, sin = self.rotary_emb(value_states.to(torch.float32), seq_len=kv_seq_len)
751
 
752
  query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
 
848
  key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
849
  value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
850
 
851
+ kv_seq_len = position_ids.max().item() + 1
 
 
852
  cos, sin = self.rotary_emb(value_states.to(torch.float32), seq_len=kv_seq_len)
853
  query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
854
 
 
1020
  self.dense_len = self.config.sparse_config.get('dense_len', 8192)
1021
 
1022
  self.local_blocks = self.window_size // self.block_size # local_blocks
1023
+ self.topk = self.config.sparse_config.get('topk', 64) + (self.window_size//self.block_size)
1024
  self.use_nope = self.config.sparse_config.get('use_nope', False)
1025
+
1026
  self.compress_k = CompressK(self.num_key_value_heads, self.head_dim, kernel_size=self.kernel_size, kernel_stride=self.kernel_stride)
1027
+ self.compress_k2 = CompressK(self.num_key_value_heads, self.head_dim, kernel_size=self.kernel_size*4, kernel_stride=self.kernel_stride*4)
1028
 
1029
  def forward(
1030
  self,
 
1048
  output_attentions = False
1049
 
1050
  bsz, q_len, _ = hidden_states.size()
1051
+
1052
 
1053
  query_states = self.q_proj(hidden_states)
1054
  key_states = self.k_proj(hidden_states)
 
1066
  key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
1067
  value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
1068
 
1069
+ kv_seq_len = position_ids.max().item() + 1
 
 
1070
  cos, sin = self.rotary_emb(value_states.to(torch.float32), seq_len=kv_seq_len)
1071
  query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
1072
 
 
1080
  key_states = key_states.transpose(1, 2)
1081
  value_states = value_states.transpose(1, 2)
1082
  if self.use_nope:
1083
+ key_states_no_rope =past_key_value.update_no_rope_key(key_states_no_rope, self.layer_idx)
1084
  no_rope_param = {
1085
  'key_states_no_rope': key_states_no_rope,
1086
  'query_states_no_rope': query_states_no_rope,
1087
  }
1088
+
 
1089
  else:
1090
  no_rope_param = None
1091
 
 
1117
  if kv_seq_len < self.dense_len:
1118
  attn_output = self._flash_attention_forward_dense(
1119
  query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate)
1120
+ else:
1121
+ attn_output = self._sparse_attention_forward(
1122
  query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate,
1123
  no_rope_param=no_rope_param, # if past_key_value is not None else None,
1124
  past_key_value=past_key_value)
 
 
 
 
1125
  attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
1126
  attn_output = self.o_proj(attn_output)
1127
 
 
1130
 
1131
  return attn_output, attn_weights, past_key_value
1132
 
1133
+ def _sparse_attention_forward(
1134
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None, no_rope_param=None, past_key_value=None
1135
+ ):
1136
+ """
1137
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
1138
+ first unpad the input, then computes the attention scores and pad the final attention scores.
1139
+
1140
+ Args:
1141
+ query_states (`torch.Tensor`):
1142
+ Input query states to be passed to Flash Attention API
1143
+ key_states (`torch.Tensor`):
1144
+ Input key states to be passed to Flash Attention API
1145
+ value_states (`torch.Tensor`):
1146
+ Input value states to be passed to Flash Attention API
1147
+ attention_mask (`torch.Tensor`):
1148
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
1149
+ position of padding tokens and 1 for the position of non-padding tokens.
1150
+ dropout (`int`, *optional*):
1151
+ Attention dropout
1152
+ softmax_scale (`float`, *optional*):
1153
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
1154
+ """
1155
+ if not self._flash_attn_uses_top_left_mask:
1156
+ causal = self.is_causal
1157
+ else:
1158
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in MiniCPMFlashAttention2 __init__.
1159
+ causal = self.is_causal and query_length != 1
1160
+ # Contains at least one padding token in the sequence
1161
+ if attention_mask is not None:
1162
+ batch_size = query_states.shape[0]
1163
+ # assert batch_size == 1, 'Only batch_size=1 is supported at the moment.'
1164
+ if past_key_value!=None:
1165
+ compressed_k, compressed_cu_seqlens, compressed_k2, compressed_cu_seqlens2 = self.get_compress_k(
1166
+ key_states=key_states if self.use_nope ==False else no_rope_param['key_states_no_rope'], # This can be optimized a bit;
1167
+ attention_mask=attention_mask,
1168
+ past_key_value=past_key_value,
1169
+
1170
+ )
1171
+
1172
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
1173
+ query_states, key_states, value_states, attention_mask, query_length
1174
+ )
1175
+
1176
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
1177
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
1178
+ if no_rope_param != None:
1179
+ if max_seqlen_in_batch_q == 1:
1180
+ no_rope_param['query_states_no_rope'] = no_rope_param['query_states_no_rope'].squeeze(1)
1181
+ else:
1182
+ no_rope_param['query_states_no_rope'],_, _, _ = _unpad_one_tensor(no_rope_param['query_states_no_rope'],attention_mask=attention_mask)
1183
+ if past_key_value==None:
1184
+ # compress_k use varlen form
1185
+ compressed_k, compressed_cu_seqlens = self.compress_k(key_states,cu_seqlens_k)
1186
+ compressed_k2, compressed_cu_seqlens2 = self.compress_k2(key_states,cu_seqlens_k)
1187
+ else:
1188
+ # compressed_k and compressed_k2 already retrieved from get_compress_k above
1189
+ pass
1190
+
1191
+
1192
+ attn_output_unpad = self.sparse_forward(
1193
+ query_states,
1194
+ key_states,
1195
+ value_states,
1196
+ cu_seqlens_q,
1197
+ cu_seqlens_k,
1198
+ max_seqlen_in_batch_q,
1199
+ max_seqlen_in_batch_k,
1200
+ no_rope_param=no_rope_param,
1201
+ compressed_k=compressed_k, compressed_cu_seqlens=compressed_cu_seqlens,
1202
+ compressed_k2=compressed_k2, compressed_cu_seqlens2=compressed_cu_seqlens2
1203
+ )
1204
 
1205
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
1206
+
1207
+ else:
1208
+ raise ValueError('Need attention mask')
1209
 
1210
+ return attn_output
1211
+ def get_compress_k(self, key_states, attention_mask, past_key_value):
 
1212
  """
1213
+ Get compressed key states and corresponding cumulative sequence lengths.
1214
+
 
1215
  Args:
1216
+ key_states: Key states tensor
1217
+ cu_seqlens_k: Cumulative sequence lengths for keys
1218
+ past_key_value: Past key-value cache
1219
+ no_rope_param: Optional parameter containing key states without rope
1220
+
1221
+ Returns:
1222
+ Tuple of (compressed_k, compressed_cu_seqlens, compressed_k2, compressed_cu_seqlens2)
 
 
 
 
 
 
1223
  """
1224
+
1225
+ # Check if this is prefilling or initial compression condition
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1226
 
1227
+ is_prefilling = (
1228
+ key_states.shape[1] >= self.dense_len and
1229
+ (
1230
+ not past_key_value.layers[self.layer_idx].compress_k_cache
1231
+ )
1232
+ )
1233
+
1234
+ if is_prefilling:
1235
+ unpadded_key_states, indices, cu_seqlens, max_seqlen_in_batch = _unpad_one_tensor(key_states,attention_mask=attention_mask)
1236
+ # Compress the keys
1237
+ compressed_k, compressed_cu_seqlens = self.compress_k(unpadded_key_states, cu_seqlens)
1238
+ compressed_k2, compressed_cu_seqlens2 = self.compress_k2(unpadded_key_states, cu_seqlens)
1239
+
1240
+ past_key_value.update_compress_k(
1241
+ compressed_k, self.layer_idx, compressed_cu_seqlens)
1242
+ past_key_value.update_compress_k2(
1243
+ compressed_k2, self.layer_idx, compressed_cu_seqlens2)
1244
+
1245
+ no_compress_k_list = []
1246
+ # Compute and update no_compress_k
1247
+ for i in range(len(compressed_cu_seqlens)-1):
1248
+ no_compress_k_start = (compressed_cu_seqlens[i+1]- compressed_cu_seqlens[i]) * self.kernel_stride
1249
+
1250
+ no_compress_k_list.append(unpadded_key_states[cu_seqlens[i]+no_compress_k_start:cu_seqlens[i+1]].clone())
1251
 
1252
+ past_key_value.update_no_compress_k(
1253
+ no_compress_k_list, self.layer_idx,kernel_stride=self.kernel_stride,
1254
+ kernel_size=self.kernel_size)
1255
+
1256
+ # Also update no_compress_k2
1257
+ no_compress_k2_list = []
1258
+ for i in range(len(compressed_cu_seqlens2)-1):
1259
+ no_compress_k2_start = (compressed_cu_seqlens2[i+1]- compressed_cu_seqlens2[i]) * self.kernel_stride * 4
1260
+
1261
+ no_compress_k2_list.append(unpadded_key_states[cu_seqlens[i]+no_compress_k2_start:cu_seqlens[i+1]].clone())
1262
+
1263
+ past_key_value.update_no_compress_k2(
1264
+ no_compress_k2_list, self.layer_idx,kernel_stride=self.kernel_stride*4,
1265
+ kernel_size=self.kernel_size*4)
1266
+
1267
  else:
1268
+ # Decode case: incremental update
1269
+ batch_size = key_states.shape[0] # key_states.shape = [batch_size, seq, k_head_num, head_dim]
1270
+ key_states_split = list(torch.split(
1271
+ key_states[:,-1:].squeeze(1), #[batch_size, seq, k_head_num, head_dim]->[batch_size, 1, k_head_num, head_dim]-> [batch_size, k_head_num, head_dim]
1272
+ [1] * batch_size,dim=0,
1273
+ ))
1274
+ # Try to update no_compress_k buffer
1275
+ no_compress_k_list = past_key_value.update_no_compress_k(
1276
+ key_states_split, self.layer_idx,
1277
+ kernel_stride=self.kernel_stride,
1278
+ kernel_size=self.kernel_size)
1279
+ new_compressed_k_list = []
1280
+ for no_compress_k in no_compress_k_list:
1281
+
1282
+ if no_compress_k is not None:
1283
+ # We have enough tokens to compress
1284
+ new_compressed_k = no_compress_k.mean(dim=0, keepdim=True) # [1, n_heads_k, head_dim]
1285
+
1286
+ new_compressed_k_list.append(new_compressed_k)
1287
+ else:
1288
+ new_compressed_k_list.append(None)
1289
+ compressed_k, compressed_cu_seqlens = past_key_value.update_compress_k(new_compressed_k_list, self.layer_idx,)
1290
+
1291
+ # For compress_k2, update no_compress_k2 buffer and compress when ready
1292
+ no_compress_k2_list = past_key_value.update_no_compress_k2(
1293
+ key_states_split, self.layer_idx,
1294
+ kernel_stride=self.kernel_stride*4,
1295
+ kernel_size=self.kernel_size*4)
1296
+ new_compressed_k2_list = []
1297
+ for no_compress_k2 in no_compress_k2_list:
1298
+ if no_compress_k2 is not None:
1299
+ # We have enough tokens to compress for k2
1300
+ new_compressed_k2 = no_compress_k2.mean(dim=0, keepdim=True) # [1, n_heads_k, head_dim]
1301
+ new_compressed_k2_list.append(new_compressed_k2)
1302
+ else:
1303
+ new_compressed_k2_list.append(None)
1304
+ compressed_k2, compressed_cu_seqlens2 = past_key_value.update_compress_k2(new_compressed_k2_list, self.layer_idx,)
1305
+
1306
+ return compressed_k, compressed_cu_seqlens, compressed_k2, compressed_cu_seqlens2
1307
  def sparse_forward(self,
1308
  query_layer,
1309
  key_layer,
 
1313
  max_seqlen_in_batch_q,
1314
  max_seqlen_in_batch_k,
1315
  no_rope_param=None,
1316
+ compressed_k=None, compressed_cu_seqlens=None,
1317
+ compressed_k2=None, compressed_cu_seqlens2=None):
 
 
 
 
 
 
 
 
 
 
 
1318
  compressed_seqlens = compressed_cu_seqlens[1:] - compressed_cu_seqlens[:-1]
1319
+ cache_lens = None
1320
+ if max_seqlen_in_batch_q==1 and max_seqlen_in_batch_k>1: #decoding
1321
+ seq_lens_k = cu_seqlens_k[1:] - cu_seqlens_k[:-1]
1322
+ cache_lens = seq_lens_k-1
1323
+
1324
  topk_idx = compressed_attention(
1325
  query_layer if no_rope_param is None else no_rope_param['query_states_no_rope'],
1326
  compressed_k,
1327
+ compressed_k2,
1328
  self.kernel_size,
1329
  self.kernel_stride,
1330
  self.block_size,
1331
  self.topk,
1332
  cu_seqlens_q,
1333
  compressed_cu_seqlens,
1334
+ compressed_cu_seqlens2,
1335
  max_seqlen_in_batch_q,
1336
  compressed_seqlens.max().item(),
1337
  None,
1338
  init_blocks=self.init_blocks,
1339
  local_blocks=self.local_blocks,
1340
+ cache_lens=cache_lens
1341
  )
 
1342
  topk_attn_output = infllmv2_attn_varlen_func(
1343
  query_layer,
1344
  key_layer,
 
1350
  dropout_p=0.0,
1351
  deterministic=False,
1352
  softmax_scale=None,
1353
+ causal=max_seqlen_in_batch_q != 1,
1354
  return_attn_probs=False,
1355
+ # block_window_size=self.window_size // self.block_size,
1356
  topk_idx=topk_idx
1357
  )
1358
 
1359
  return topk_attn_output
1360
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1361
  def _flash_attention_forward_dense(
1362
  self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
1363
  ):
 
1496
  key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
1497
  value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
1498
 
1499
+ kv_seq_len = position_ids.max().item() + 1
 
 
1500
  cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
1501
 
1502
  query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
 
1819
  raise ValueError(
1820
  'You must use the new past_key_values format, such as the Cache class, instead of the old tuple format.'
1821
  )
 
1822
 
1823
+ # Calculate the usable length of past key values
1824
+ past_key_values_length = past_key_values.get_seq_length() if isinstance(past_key_values, InfLLMv2Cache) else 0
1825
+
1826
+ # Initialize InfLLMv2Cache if needed
1827
  if self.config.sparse_config is not None and torch.cuda.is_available() and past_key_values_length == 0:
1828
+ past_key_values = InfLLMv2Cache(config = self.config, num_hidden_layers=self.config.num_hidden_layers)
1829
 
1830
  if position_ids is None:
1831
  device = input_ids.device if input_ids is not None else inputs_embeds.device
 
2051
  ):
2052
  if past_key_values is not None:
2053
  if isinstance(past_key_values, Cache):
2054
+ # Use the new Cache class methods
2055
  cache_length = past_key_values.get_seq_length()
2056
+
2057
+ if self.config.sparse_config is not None and torch.cuda.is_available() and cache_length == 0:
2058
+ past_key_values = InfLLMv2Cache(config = self.config, num_hidden_layers=self.config.num_hidden_layers)
2059
+ past_length = cache_length
2060
  max_cache_length = None
2061
+ else:
2062
+ raise ValueError(
2063
+ 'You must use the new past_key_values format, such as the Cache class, instead of the old tuple format.'
2064
+ )
2065
 
2066
  # Keep only the unprocessed tokens:
2067
  # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
 
2280
  past_key_values=transformer_outputs.past_key_values,
2281
  hidden_states=transformer_outputs.hidden_states,
2282
  attentions=transformer_outputs.attentions,
2283
+ )