guanwenyu1995 commited on
Commit
53aad9d
·
verified ·
1 Parent(s): 9f740f2

Upload modeling_minicpm.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_minicpm.py +1514 -0
modeling_minicpm.py ADDED
@@ -0,0 +1,1514 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The OpenBMB Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ PyTorch MiniCPM model."""
16
+ import math
17
+ import re
18
+ import warnings
19
+ from typing import Any, Dict, List, Optional, Tuple, Union
20
+
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,
31
+ _prepare_4d_causal_attention_mask,
32
+ _prepare_4d_causal_attention_mask_for_sdpa,
33
+ )
34
+ from transformers.modeling_outputs import (
35
+ BaseModelOutputWithPast,
36
+ CausalLMOutputWithPast,
37
+ SequenceClassifierOutputWithPast,
38
+ )
39
+ from transformers.modeling_utils import PreTrainedModel
40
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13
41
+ from transformers.utils import (
42
+ add_start_docstrings,
43
+ add_start_docstrings_to_model_forward,
44
+ is_flash_attn_greater_or_equal_2_10,
45
+ logging,
46
+ replace_return_docstrings,
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
54
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
55
+ except:
56
+ pass
57
+
58
+
59
+
60
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
61
+ # It means that the function will not be traced through and simply appear as a node in the graph.
62
+ if is_torch_fx_available():
63
+ if not is_torch_greater_or_equal_than_1_13:
64
+ import torch.fx
65
+
66
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
67
+
68
+
69
+ logger = logging.get_logger(__name__)
70
+
71
+ _CONFIG_FOR_DOC = 'MiniCPMConfig'
72
+
73
+
74
+ def _get_unpad_data(attention_mask):
75
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
76
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
77
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
78
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
79
+ return (
80
+ indices,
81
+ cu_seqlens,
82
+ max_seqlen_in_batch,
83
+ )
84
+
85
+
86
+
87
+
88
+ # @torch.jit.script # type: ignore
89
+ def rms_layernorm(hidden: torch.Tensor, weight: torch.Tensor, eps: float):
90
+ old_dtype = hidden.dtype
91
+ variance = hidden.to(torch.float32).pow(2).mean(dim=-1, keepdim=True)
92
+ hidden = (hidden * torch.rsqrt(variance + eps)).to(old_dtype)
93
+ return hidden * weight
94
+
95
+
96
+ class MiniCPMRMSNorm(nn.Module):
97
+ def __init__(self, hidden_size, eps=1e-6):
98
+ """
99
+ MiniCPMRMSNorm is equivalent to T5LayerNorm
100
+ """
101
+ super().__init__()
102
+ self.weight = nn.Parameter(torch.ones(hidden_size))
103
+ self.variance_epsilon = eps
104
+
105
+ def forward(self, hidden_states):
106
+ return rms_layernorm(hidden_states, self.weight, self.variance_epsilon)
107
+
108
+
109
+ ALL_LAYERNORM_LAYERS.append(MiniCPMRMSNorm)
110
+
111
+
112
+ class MiniCPMRotaryEmbedding(nn.Module):
113
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
114
+ super().__init__()
115
+
116
+ self.dim = dim
117
+ self.max_position_embeddings = max_position_embeddings
118
+ self.base = base
119
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
120
+ self.register_buffer('inv_freq', inv_freq, persistent=False)
121
+
122
+ # Build here to make `torch.jit.trace` work.
123
+ self._set_cos_sin_cache(
124
+ # seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
125
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.float32
126
+ )
127
+
128
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
129
+ self.max_seq_len_cached = seq_len
130
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
131
+ freqs = torch.outer(t, self.inv_freq)
132
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
133
+ emb = torch.cat((freqs, freqs), dim=-1)
134
+
135
+ self.register_buffer('cos_cached', emb.cos().to(dtype), persistent=False)
136
+ self.register_buffer('sin_cached', emb.sin().to(dtype), persistent=False)
137
+
138
+ def forward(self, x, seq_len=None):
139
+ # x: [bs, num_attention_heads, seq_len, head_size]
140
+ if seq_len > self.max_seq_len_cached:
141
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
142
+
143
+ return (
144
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
145
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
146
+ )
147
+
148
+
149
+ class MiniCPMLongRoPE(MiniCPMRotaryEmbedding):
150
+ """MiniCPMRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
151
+
152
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, short_factor=None, long_factor=None, original_max_position_embeddings=None):
153
+ self.short_factor = short_factor
154
+ self.long_factor = long_factor
155
+ self.original_max_position_embeddings = original_max_position_embeddings
156
+ scale = (max_position_embeddings / self.original_max_position_embeddings)
157
+ self.scaling_factor = math.sqrt(1 + math.log(scale) / math.log(self.original_max_position_embeddings))
158
+ super().__init__(dim, max_position_embeddings, base, device)
159
+
160
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
161
+ self.max_seq_len_cached = seq_len
162
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
163
+ if seq_len > self.original_max_position_embeddings:
164
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=device)
165
+ else:
166
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=device)
167
+
168
+ freqs = torch.mul(
169
+ torch.outer(t, 1.0 / ext_factors).to(device=device),
170
+ self.inv_freq.to(device=device).to(dtype)
171
+ )
172
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
173
+ emb = torch.cat((freqs, freqs), dim=-1)
174
+ self.register_buffer('cos_cached', emb.cos().to(dtype) * self.scaling_factor, persistent=False)
175
+ self.register_buffer('sin_cached', emb.sin().to(dtype) * self.scaling_factor, persistent=False)
176
+
177
+
178
+ class MiniCPMLinearScalingRotaryEmbedding(MiniCPMRotaryEmbedding):
179
+ """MiniCPMRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
180
+
181
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
182
+ self.scaling_factor = scaling_factor
183
+ super().__init__(dim, max_position_embeddings, base, device)
184
+
185
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
186
+ self.max_seq_len_cached = seq_len
187
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
188
+ t = t / self.scaling_factor
189
+
190
+ freqs = torch.outer(t, self.inv_freq)
191
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
192
+ emb = torch.cat((freqs, freqs), dim=-1)
193
+ self.register_buffer('cos_cached', emb.cos().to(dtype), persistent=False)
194
+ self.register_buffer('sin_cached', emb.sin().to(dtype), persistent=False)
195
+
196
+
197
+ class MiniCPMDynamicNTKScalingRotaryEmbedding(MiniCPMRotaryEmbedding):
198
+ """MiniCPMRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
199
+
200
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
201
+ self.scaling_factor = scaling_factor
202
+ super().__init__(dim, max_position_embeddings, base, device)
203
+
204
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
205
+ self.max_seq_len_cached = seq_len
206
+
207
+ if seq_len > self.max_position_embeddings:
208
+ base = self.base * (
209
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
210
+ ) ** (self.dim / (self.dim - 2))
211
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
212
+ self.register_buffer('inv_freq', inv_freq, persistent=False)
213
+
214
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
215
+
216
+ freqs = torch.outer(t, self.inv_freq)
217
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
218
+ emb = torch.cat((freqs, freqs), dim=-1)
219
+
220
+ self.register_buffer('cos_cached', emb.cos().to(dtype), persistent=False)
221
+ self.register_buffer('sin_cached', emb.sin().to(dtype), persistent=False)
222
+
223
+
224
+ def rotate_half(x):
225
+ """Rotates half the hidden dims of the input."""
226
+ x1 = x[..., : x.shape[-1] // 2]
227
+ x2 = x[..., x.shape[-1] // 2:]
228
+ return torch.cat((-x2, x1), dim=-1)
229
+
230
+
231
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
232
+ """Applies Rotary Position Embedding to the query and key tensors.
233
+
234
+ Args:
235
+ q (`torch.Tensor`): The query tensor.
236
+ k (`torch.Tensor`): The key tensor.
237
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
238
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
239
+ position_ids (`torch.Tensor`):
240
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
241
+ used to pass offsetted position ids when working with a KV-cache.
242
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
243
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
244
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
245
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
246
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
247
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
248
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
249
+ Returns:
250
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
251
+ """
252
+ # cos = cos[position_ids].unsqueeze(unsqueeze_dim)
253
+ # sin = sin[position_ids].unsqueeze(unsqueeze_dim)
254
+ # q_embed = (q * cos) + (rotate_half(q) * sin)
255
+ # k_embed = (k * cos) + (rotate_half(k) * sin)
256
+ orig_dtype = k.dtype
257
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim) # [bs, 1, seq_len, dim]
258
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim) # [bs, 1, seq_len, dim]
259
+ q_fp32 = q.to(dtype=torch.float32, device=q.device)
260
+ k_fp32 = k.to(dtype=torch.float32, device=k.device)
261
+ q_embed = (q_fp32 * cos) + (rotate_half(q_fp32) * sin)
262
+ k_embed = (k_fp32 * cos) + (rotate_half(k_fp32) * sin)
263
+ return q_embed.to(dtype=orig_dtype), k_embed.to(dtype=orig_dtype)
264
+
265
+
266
+ class MiniCPMMLP(nn.Module):
267
+ def __init__(self, config):
268
+ super().__init__()
269
+ self.config = config
270
+ self.hidden_size = config.hidden_size
271
+ self.intermediate_size = config.intermediate_size
272
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
273
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
274
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
275
+ self.act_fn = ACT2FN[config.hidden_act]
276
+
277
+ def forward(self, x):
278
+ if self.config.pretraining_tp > 1:
279
+ slice = self.intermediate_size // self.config.pretraining_tp
280
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
281
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
282
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
283
+
284
+ gate_proj = torch.cat(
285
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
286
+ )
287
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
288
+
289
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
290
+ down_proj = [
291
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
292
+ ]
293
+ down_proj = sum(down_proj)
294
+ else:
295
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
296
+
297
+ return down_proj
298
+
299
+ def _unpad_one_tensor(hidden_states, attention_mask):
300
+ # Unpad the hidden states using the indices
301
+ indices, cu_seqlens, max_seqlen_in_batch = _get_unpad_data(attention_mask)
302
+ batch_size, seq_len = hidden_states.shape[:2]
303
+
304
+ # Get the remaining dimensions
305
+ remaining_dims = hidden_states.shape[2:]
306
+
307
+ # Reshape to (batch_size * seq_len, *remaining_dims)
308
+ reshaped_states = hidden_states.reshape(batch_size * seq_len, *remaining_dims)
309
+
310
+ # Apply unpadding using indices
311
+ unpadded_states = index_first_axis(reshaped_states, indices)
312
+
313
+ return unpadded_states, indices, cu_seqlens, max_seqlen_in_batch
314
+
315
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
316
+ """
317
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
318
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
319
+ """
320
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
321
+ if n_rep == 1:
322
+ return hidden_states
323
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
324
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
325
+
326
+
327
+ class MiniCPMAttention(nn.Module):
328
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
329
+
330
+ def __init__(self, config: MiniCPMConfig, layer_idx: Optional[int] = None):
331
+ super().__init__()
332
+ self.config = config
333
+ self.layer_idx = layer_idx
334
+ if layer_idx is None:
335
+ logger.warning_once(
336
+ f'Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will '
337
+ 'to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` '
338
+ 'when creating this class.'
339
+ )
340
+
341
+ self.attention_dropout = config.attention_dropout
342
+ self.hidden_size = config.hidden_size
343
+ self.num_heads = config.num_attention_heads
344
+ self.head_dim = self.hidden_size // self.num_heads
345
+ self.num_key_value_heads = config.num_key_value_heads
346
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
347
+ self.max_position_embeddings = config.max_position_embeddings
348
+ self.rope_theta = config.rope_theta
349
+ self.is_causal = True
350
+
351
+ if (self.head_dim * self.num_heads) != self.hidden_size:
352
+ raise ValueError(
353
+ f'hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}'
354
+ f' and `num_heads`: {self.num_heads}).'
355
+ )
356
+
357
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
358
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
359
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
360
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
361
+ self._init_rope()
362
+
363
+ def _init_rope(self):
364
+ if self.config.rope_scaling is None:
365
+ self.rotary_emb = MiniCPMRotaryEmbedding(
366
+ self.head_dim,
367
+ max_position_embeddings=self.max_position_embeddings,
368
+ base=self.rope_theta,
369
+ )
370
+ else:
371
+ scaling_type = self.config.rope_scaling['rope_type']
372
+ scaling_factor = self.config.rope_scaling.get('factor', None)
373
+ if scaling_type == 'linear':
374
+ self.rotary_emb = MiniCPMLinearScalingRotaryEmbedding(
375
+ self.head_dim,
376
+ max_position_embeddings=self.max_position_embeddings,
377
+ scaling_factor=scaling_factor,
378
+ base=self.rope_theta,
379
+ )
380
+ elif scaling_type == 'dynamic':
381
+ self.rotary_emb = MiniCPMDynamicNTKScalingRotaryEmbedding(
382
+ self.head_dim,
383
+ max_position_embeddings=self.max_position_embeddings,
384
+ scaling_factor=scaling_factor,
385
+ base=self.rope_theta,
386
+ )
387
+ elif scaling_type == 'longrope':
388
+ self.rotary_emb = MiniCPMLongRoPE(
389
+ self.head_dim,
390
+ max_position_embeddings=self.max_position_embeddings,
391
+ short_factor=self.config.rope_scaling['short_factor'],
392
+ long_factor=self.config.rope_scaling['long_factor'],
393
+ base=self.rope_theta,
394
+ original_max_position_embeddings=self.config.rope_scaling['original_max_position_embeddings']
395
+ )
396
+ else:
397
+ raise ValueError(f'Unknown RoPE scaling type {scaling_type}')
398
+
399
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
400
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
401
+
402
+ def forward(
403
+ self,
404
+ hidden_states: torch.Tensor,
405
+ attention_mask: Optional[torch.Tensor] = None,
406
+ position_ids: Optional[torch.LongTensor] = None,
407
+ past_key_value: Optional[Cache] = None,
408
+ output_attentions: bool = False,
409
+ use_cache: bool = False,
410
+ **kwargs,
411
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
412
+ if 'padding_mask' in kwargs:
413
+ warnings.warn(
414
+ 'Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`'
415
+ )
416
+
417
+ bsz, q_len, _ = hidden_states.size()
418
+
419
+ if self.config.pretraining_tp > 1:
420
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
421
+ query_slices = self.q_proj.weight.split(
422
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
423
+ )
424
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
425
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
426
+
427
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
428
+ query_states = torch.cat(query_states, dim=-1)
429
+
430
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
431
+ key_states = torch.cat(key_states, dim=-1)
432
+
433
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
434
+ value_states = torch.cat(value_states, dim=-1)
435
+
436
+ else:
437
+ query_states = self.q_proj(hidden_states)
438
+ key_states = self.k_proj(hidden_states)
439
+ value_states = self.v_proj(hidden_states)
440
+
441
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
442
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
443
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
444
+
445
+ kv_seq_len = position_ids.max().item() + 1
446
+ cos, sin = self.rotary_emb(value_states.to(torch.float32), seq_len=kv_seq_len)
447
+
448
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
449
+
450
+ if past_key_value is not None:
451
+ cache_kwargs = {'sin': sin, 'cos': cos} # Specific to RoPE models
452
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
453
+
454
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
455
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
456
+
457
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
458
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
459
+ raise ValueError(
460
+ f'Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is'
461
+ f' {attn_weights.size()}'
462
+ )
463
+
464
+ if attention_mask is not None:
465
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
466
+ raise ValueError(
467
+ f'Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}'
468
+ )
469
+ attn_weights = attn_weights + attention_mask
470
+
471
+ # upcast attention to fp32
472
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
473
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
474
+ attn_output = torch.matmul(attn_weights, value_states)
475
+
476
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
477
+ raise ValueError(
478
+ f'`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is'
479
+ f' {attn_output.size()}'
480
+ )
481
+
482
+ attn_output = attn_output.transpose(1, 2).contiguous()
483
+
484
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
485
+
486
+ if self.config.pretraining_tp > 1:
487
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
488
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
489
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
490
+ else:
491
+ attn_output = self.o_proj(attn_output)
492
+
493
+ if not output_attentions:
494
+ attn_weights = None
495
+
496
+ return attn_output, attn_weights, past_key_value
497
+
498
+
499
+ class MiniCPMFlashAttention2(MiniCPMAttention):
500
+ """
501
+ MiniCPM flash attention module. This module inherits from `MiniCPMAttention` as the weights of the module stays
502
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
503
+ flash attention and deal with padding tokens in case the input contains any of them.
504
+ """
505
+
506
+ def __init__(self, *args, **kwargs):
507
+ super().__init__(*args, **kwargs)
508
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
509
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignment, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
510
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
511
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
512
+
513
+ def forward(
514
+ self,
515
+ hidden_states: torch.Tensor,
516
+ attention_mask: Optional[torch.LongTensor] = None,
517
+ position_ids: Optional[torch.LongTensor] = None,
518
+ past_key_value: Optional[Cache] = None,
519
+ output_attentions: bool = False,
520
+ use_cache: bool = False,
521
+ **kwargs,
522
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
523
+ # MiniCPMFlashAttention2 attention does not support output_attentions
524
+ if 'padding_mask' in kwargs:
525
+ warnings.warn(
526
+ 'Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`'
527
+ )
528
+
529
+ # overwrite attention_mask with padding_mask
530
+ attention_mask = kwargs.pop('padding_mask')
531
+
532
+ output_attentions = False
533
+
534
+ bsz, q_len, _ = hidden_states.size()
535
+
536
+ query_states = self.q_proj(hidden_states)
537
+ key_states = self.k_proj(hidden_states)
538
+ value_states = self.v_proj(hidden_states)
539
+
540
+ # Flash attention requires the input to have the shape
541
+ # batch_size x seq_length x head_dim x hidden_dim
542
+ # therefore we just need to keep the original shape
543
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
544
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
545
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
546
+
547
+ kv_seq_len = position_ids.max().item() + 1
548
+ cos, sin = self.rotary_emb(value_states.to(torch.float32), seq_len=kv_seq_len)
549
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
550
+
551
+ if past_key_value is not None:
552
+ cache_kwargs = {'sin': sin, 'cos': cos} # Specific to RoPE models
553
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
554
+
555
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
556
+ # to be able to avoid many of these transpose/reshape/view.
557
+ query_states = query_states.transpose(1, 2)
558
+ key_states = key_states.transpose(1, 2)
559
+ value_states = value_states.transpose(1, 2)
560
+
561
+ dropout_rate = self.attention_dropout if self.training else 0.0
562
+
563
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
564
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
565
+ # cast them back in the correct dtype just to be sure everything works as expected.
566
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
567
+ # in fp32. (MiniCPMRMSNorm handles it correctly)
568
+
569
+ input_dtype = query_states.dtype
570
+ if input_dtype == torch.float32:
571
+ # Handle the case where the model is quantized
572
+ if hasattr(self.config, '_pre_quantization_dtype'):
573
+ target_dtype = self.config._pre_quantization_dtype
574
+ else:
575
+ target_dtype = self.q_proj.weight.dtype
576
+
577
+ logger.warning_once(
578
+ f'The input hidden states seems to be silently casted in float32, this might be related to'
579
+ f' the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in'
580
+ f' {target_dtype}.'
581
+ )
582
+
583
+ query_states = query_states.to(target_dtype)
584
+ key_states = key_states.to(target_dtype)
585
+ value_states = value_states.to(target_dtype)
586
+
587
+ attn_output = self._flash_attention_forward(
588
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
589
+ )
590
+
591
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
592
+ attn_output = self.o_proj(attn_output)
593
+
594
+ if not output_attentions:
595
+ attn_weights = None
596
+
597
+ return attn_output, attn_weights, past_key_value
598
+
599
+ def _flash_attention_forward(
600
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
601
+ ):
602
+ """
603
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
604
+ first unpad the input, then computes the attention scores and pad the final attention scores.
605
+
606
+ Args:
607
+ query_states (`torch.Tensor`):
608
+ Input query states to be passed to Flash Attention API
609
+ key_states (`torch.Tensor`):
610
+ Input key states to be passed to Flash Attention API
611
+ value_states (`torch.Tensor`):
612
+ Input value states to be passed to Flash Attention API
613
+ attention_mask (`torch.Tensor`):
614
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
615
+ position of padding tokens and 1 for the position of non-padding tokens.
616
+ dropout (`int`, *optional*):
617
+ Attention dropout
618
+ softmax_scale (`float`, *optional*):
619
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
620
+ """
621
+ if not self._flash_attn_uses_top_left_mask:
622
+ causal = self.is_causal
623
+ else:
624
+ # 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__.
625
+ causal = self.is_causal and query_length != 1
626
+ # Contains at least one padding token in the sequence
627
+ if attention_mask is not None:
628
+ batch_size = query_states.shape[0]
629
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
630
+ query_states, key_states, value_states, attention_mask, query_length
631
+ )
632
+
633
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
634
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
635
+ attn_output_unpad = flash_attn_varlen_func(
636
+ query_states,
637
+ key_states,
638
+ value_states,
639
+ cu_seqlens_q=cu_seqlens_q,
640
+ cu_seqlens_k=cu_seqlens_k,
641
+ max_seqlen_q=max_seqlen_in_batch_q,
642
+ max_seqlen_k=max_seqlen_in_batch_k,
643
+ dropout_p=dropout,
644
+ softmax_scale=softmax_scale,
645
+ causal=causal,
646
+ )
647
+
648
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
649
+ else:
650
+ attn_output = flash_attn_func(
651
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
652
+ )
653
+
654
+ return attn_output
655
+
656
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
657
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
658
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
659
+
660
+ key_layer = index_first_axis(
661
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
662
+ )
663
+ value_layer = index_first_axis(
664
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
665
+ )
666
+ if query_length == kv_seq_len:
667
+ query_layer = index_first_axis(
668
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
669
+ )
670
+ cu_seqlens_q = cu_seqlens_k
671
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
672
+ indices_q = indices_k
673
+ elif query_length == 1:
674
+ max_seqlen_in_batch_q = 1
675
+ cu_seqlens_q = torch.arange(
676
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
677
+ ) # There is a memcpy here, that is very bad.
678
+ indices_q = cu_seqlens_q[:-1]
679
+ query_layer = query_layer.squeeze(1)
680
+ else:
681
+ # The -q_len: slice assumes left padding.
682
+ attention_mask = attention_mask[:, -query_length:]
683
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
684
+
685
+ return (
686
+ query_layer,
687
+ key_layer,
688
+ value_layer,
689
+ indices_q,
690
+ (cu_seqlens_q, cu_seqlens_k),
691
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
692
+ )
693
+
694
+
695
+ class MiniCPMSdpaAttention(MiniCPMAttention):
696
+ """
697
+ MiniCPM attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
698
+ `MiniCPMAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
699
+ SDPA API.
700
+ """
701
+
702
+ # Adapted from MiniCPMAttention.forward
703
+ def forward(
704
+ self,
705
+ hidden_states: torch.Tensor,
706
+ attention_mask: Optional[torch.Tensor] = None,
707
+ position_ids: Optional[torch.LongTensor] = None,
708
+ past_key_value: Optional[Cache] = None,
709
+ output_attentions: bool = False,
710
+ use_cache: bool = False,
711
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
712
+ if output_attentions:
713
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
714
+ logger.warning_once(
715
+ 'MiniCPMModel is using MiniCPMSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, '
716
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
717
+ )
718
+ return super().forward(
719
+ hidden_states=hidden_states,
720
+ attention_mask=attention_mask,
721
+ position_ids=position_ids,
722
+ past_key_value=past_key_value,
723
+ output_attentions=output_attentions,
724
+ use_cache=use_cache,
725
+ )
726
+
727
+ bsz, q_len, _ = hidden_states.size()
728
+
729
+ query_states = self.q_proj(hidden_states)
730
+ key_states = self.k_proj(hidden_states)
731
+ value_states = self.v_proj(hidden_states)
732
+
733
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
734
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
735
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
736
+
737
+ kv_seq_len = position_ids.max().item() + 1
738
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
739
+
740
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
741
+
742
+ if past_key_value is not None:
743
+ cache_kwargs = {'sin': sin, 'cos': cos} # Specific to RoPE models
744
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
745
+
746
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
747
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
748
+
749
+ if attention_mask is not None:
750
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
751
+ raise ValueError(
752
+ f'Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}'
753
+ )
754
+
755
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
756
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
757
+ if query_states.device.type == 'cuda' and attention_mask is not None:
758
+ query_states = query_states.contiguous()
759
+ key_states = key_states.contiguous()
760
+ value_states = value_states.contiguous()
761
+
762
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
763
+ query_states,
764
+ key_states,
765
+ value_states,
766
+ attn_mask=attention_mask,
767
+ dropout_p=self.attention_dropout if self.training else 0.0,
768
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
769
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
770
+ )
771
+
772
+ attn_output = attn_output.transpose(1, 2).contiguous()
773
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
774
+
775
+ attn_output = self.o_proj(attn_output)
776
+
777
+ return attn_output, None, past_key_value
778
+
779
+
780
+ MINICPM_ATTENTION_CLASSES = {
781
+ 'eager': MiniCPMAttention,
782
+ 'flash_attention_2': MiniCPMFlashAttention2,
783
+ 'sdpa': MiniCPMSdpaAttention,
784
+ }
785
+
786
+
787
+ class MiniCPMDecoderLayer(nn.Module):
788
+ def __init__(self, config: MiniCPMConfig, layer_idx: int):
789
+ super().__init__()
790
+ self.hidden_size = config.hidden_size
791
+ self.self_attn = MINICPM_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
792
+
793
+ self.mlp = MiniCPMMLP(config)
794
+ self.input_layernorm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
795
+ self.post_attention_layernorm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
796
+
797
+ self.scale_depth = config.scale_depth
798
+ self.num_hidden_layers = config.num_hidden_layers
799
+
800
+ def forward(
801
+ self,
802
+ hidden_states: torch.Tensor,
803
+ attention_mask: Optional[torch.Tensor] = None,
804
+ position_ids: Optional[torch.LongTensor] = None,
805
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
806
+ output_attentions: Optional[bool] = False,
807
+ use_cache: Optional[bool] = False,
808
+ **kwargs,
809
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
810
+ """
811
+ Args:
812
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
813
+ attention_mask (`torch.FloatTensor`, *optional*):
814
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
815
+ query_sequence_length, key_sequence_length)` if default attention is used.
816
+ output_attentions (`bool`, *optional*):
817
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
818
+ returned tensors for more detail.
819
+ use_cache (`bool`, *optional*):
820
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
821
+ (see `past_key_values`).
822
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
823
+ """
824
+ if 'padding_mask' in kwargs:
825
+ warnings.warn(
826
+ 'Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`'
827
+ )
828
+
829
+ residual = hidden_states
830
+ hidden_states = self.input_layernorm(hidden_states)
831
+ # Self Attention
832
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
833
+ hidden_states=hidden_states,
834
+ attention_mask=attention_mask,
835
+ position_ids=position_ids,
836
+ past_key_value=past_key_value,
837
+ output_attentions=output_attentions,
838
+ use_cache=use_cache,
839
+ **kwargs,
840
+ )
841
+
842
+ hidden_states = residual + hidden_states * (self.scale_depth / math.sqrt(self.num_hidden_layers))
843
+
844
+ # Fully Connected
845
+ residual = hidden_states
846
+ hidden_states = self.post_attention_layernorm(hidden_states)
847
+
848
+ hidden_states = self.mlp(hidden_states)
849
+ hidden_states = residual + hidden_states * (self.scale_depth / math.sqrt(self.num_hidden_layers))
850
+
851
+ outputs = (hidden_states,)
852
+
853
+ if output_attentions:
854
+ outputs += (self_attn_weights,)
855
+
856
+ if use_cache:
857
+ outputs += (present_key_value,)
858
+
859
+ return outputs
860
+
861
+
862
+ MINICPM_START_DOCSTRING = r"""
863
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
864
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
865
+ etc.)
866
+
867
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
868
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
869
+ and behavior.
870
+
871
+ Parameters:
872
+ config ([`MiniCPMConfig`]):
873
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
874
+ load the weights associated with the model, only the configuration. Check out the
875
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
876
+ """
877
+
878
+
879
+ @add_start_docstrings(
880
+ 'The bare MiniCPM Model outputting raw hidden-states without any specific head on top.',
881
+ MINICPM_START_DOCSTRING,
882
+ )
883
+ class MiniCPMPreTrainedModel(PreTrainedModel):
884
+ config_class = MiniCPMConfig
885
+ base_model_prefix = 'model'
886
+ supports_gradient_checkpointing = True
887
+ _no_split_modules = ['MiniCPMDecoderLayer']
888
+ _skip_keys_device_placement = 'past_key_values'
889
+ _supports_flash_attn_2 = True
890
+ _supports_sdpa = True
891
+ _supports_cache_class = True
892
+
893
+ def _init_weights(self, module):
894
+ std = self.config.initializer_range
895
+ if isinstance(module, nn.Linear):
896
+ module.weight.data.normal_(mean=0.0, std=std)
897
+ if module.bias is not None:
898
+ module.bias.data.zero_()
899
+ elif isinstance(module, nn.Embedding):
900
+ module.weight.data.normal_(mean=0.0, std=std)
901
+ if module.padding_idx is not None:
902
+ module.weight.data[module.padding_idx].zero_()
903
+
904
+
905
+ MINICPM_INPUTS_DOCSTRING = r"""
906
+ Args:
907
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
908
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
909
+ it.
910
+
911
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
912
+ [`PreTrainedTokenizer.__call__`] for details.
913
+
914
+ [What are input IDs?](../glossary#input-ids)
915
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
916
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
917
+
918
+ - 1 for tokens that are **not masked**,
919
+ - 0 for tokens that are **masked**.
920
+
921
+ [What are attention masks?](../glossary#attention-mask)
922
+
923
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
924
+ [`PreTrainedTokenizer.__call__`] for details.
925
+
926
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
927
+ `past_key_values`).
928
+
929
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
930
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
931
+ information on the default strategy.
932
+
933
+ - 1 indicates the head is **not masked**,
934
+ - 0 indicates the head is **masked**.
935
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
936
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
937
+ config.n_positions - 1]`.
938
+
939
+ [What are position IDs?](../glossary#position-ids)
940
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
941
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
942
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
943
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
944
+
945
+ Two formats are allowed:
946
+ - a [`~cache_utils.Cache`] instance;
947
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
948
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
949
+ cache format.
950
+
951
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
952
+ legacy cache format will be returned.
953
+
954
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
955
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
956
+ of shape `(batch_size, sequence_length)`.
957
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
958
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
959
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
960
+ model's internal embedding lookup matrix.
961
+ use_cache (`bool`, *optional*):
962
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
963
+ `past_key_values`).
964
+ output_attentions (`bool`, *optional*):
965
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
966
+ tensors for more detail.
967
+ output_hidden_states (`bool`, *optional*):
968
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
969
+ more detail.
970
+ return_dict (`bool`, *optional*):
971
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
972
+ """
973
+
974
+
975
+ @add_start_docstrings(
976
+ 'The bare MiniCPM Model outputting raw hidden-states without any specific head on top.',
977
+ MINICPM_START_DOCSTRING,
978
+ )
979
+ class MiniCPMModel(MiniCPMPreTrainedModel):
980
+ """
981
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MiniCPMDecoderLayer`]
982
+
983
+ Args:
984
+ config: MiniCPMConfig
985
+ """
986
+
987
+ def __init__(self, config: MiniCPMConfig):
988
+ super().__init__(config)
989
+ self.padding_idx = config.pad_token_id
990
+ self.vocab_size = config.vocab_size
991
+
992
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
993
+ self.layers = nn.ModuleList(
994
+ [MiniCPMDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
995
+ )
996
+ self._use_sdpa = config._attn_implementation == 'sdpa'
997
+ self._use_flash_attention_2 = config._attn_implementation == 'flash_attention_2'
998
+
999
+ self.norm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1000
+
1001
+ self.gradient_checkpointing = False
1002
+ # Initialize weights and apply final processing
1003
+ self.post_init()
1004
+
1005
+ def get_input_embeddings(self):
1006
+ return self.embed_tokens
1007
+
1008
+ def set_input_embeddings(self, value):
1009
+ self.embed_tokens = value
1010
+
1011
+ @add_start_docstrings_to_model_forward(MINICPM_INPUTS_DOCSTRING)
1012
+ def forward(
1013
+ self,
1014
+ input_ids: torch.LongTensor = None,
1015
+ attention_mask: Optional[torch.Tensor] = None,
1016
+ position_ids: Optional[torch.LongTensor] = None,
1017
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1018
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1019
+ use_cache: Optional[bool] = None,
1020
+ output_attentions: Optional[bool] = None,
1021
+ output_hidden_states: Optional[bool] = None,
1022
+ return_dict: Optional[bool] = None,
1023
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1024
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1025
+ output_hidden_states = (
1026
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1027
+ )
1028
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1029
+
1030
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1031
+
1032
+ # retrieve input_ids and inputs_embeds
1033
+ if input_ids is not None and inputs_embeds is not None:
1034
+ raise ValueError('You cannot specify both input_ids and inputs_embeds at the same time')
1035
+ elif input_ids is not None:
1036
+ batch_size, seq_length = input_ids.shape[:2]
1037
+ elif inputs_embeds is not None:
1038
+ batch_size, seq_length = inputs_embeds.shape[:2]
1039
+ else:
1040
+ raise ValueError('You have to specify either input_ids or inputs_embeds')
1041
+
1042
+ if self.gradient_checkpointing and self.training:
1043
+ if use_cache:
1044
+ logger.warning_once(
1045
+ '`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...'
1046
+ )
1047
+ use_cache = False
1048
+
1049
+ past_key_values_length = 0
1050
+
1051
+ if use_cache:
1052
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1053
+ if use_legacy_cache:
1054
+ raise ValueError(
1055
+ 'You must use the new past_key_values format, such as the Cache class, instead of the old tuple format.'
1056
+ )
1057
+
1058
+ # Calculate the usable length of past key values
1059
+ past_key_values_length = past_key_values.get_seq_length() if isinstance(past_key_values, Cache) else 0
1060
+
1061
+
1062
+ if position_ids is None:
1063
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1064
+ position_ids = torch.arange(
1065
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1066
+ )
1067
+ position_ids = position_ids.unsqueeze(0)
1068
+
1069
+ if inputs_embeds is None:
1070
+ inputs_embeds = self.embed_tokens(input_ids) * self.config.scale_emb
1071
+
1072
+ if self._use_flash_attention_2:
1073
+ # 2d mask is passed through the layers
1074
+ # attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1075
+ if attention_mask is None:
1076
+ raise ValueError(
1077
+ f'need attention_mask for flash attention, but got {attention_mask}.'
1078
+ )
1079
+ elif self._use_sdpa and not output_attentions:
1080
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1081
+ # the manual implementation that requires a 4D causal mask in all cases.
1082
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1083
+ attention_mask,
1084
+ (batch_size, seq_length),
1085
+ inputs_embeds,
1086
+ past_key_values_length,
1087
+ )
1088
+ else:
1089
+ # 4d mask is passed through the layers
1090
+ attention_mask = _prepare_4d_causal_attention_mask(
1091
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
1092
+ )
1093
+
1094
+ # embed positions
1095
+ hidden_states = inputs_embeds
1096
+
1097
+ # decoder layers
1098
+ all_hidden_states = () if output_hidden_states else None
1099
+ all_self_attns = () if output_attentions else None
1100
+ next_decoder_cache = None
1101
+
1102
+ for decoder_layer in self.layers:
1103
+ if output_hidden_states:
1104
+ all_hidden_states += (hidden_states,)
1105
+
1106
+ if self.gradient_checkpointing and self.training:
1107
+ layer_outputs = self._gradient_checkpointing_func(
1108
+ decoder_layer.__call__,
1109
+ hidden_states,
1110
+ attention_mask,
1111
+ position_ids,
1112
+ past_key_values,
1113
+ output_attentions,
1114
+ use_cache,
1115
+ )
1116
+ else:
1117
+ layer_outputs = decoder_layer(
1118
+ hidden_states,
1119
+ attention_mask=attention_mask,
1120
+ position_ids=position_ids,
1121
+ past_key_value=past_key_values,
1122
+ output_attentions=output_attentions,
1123
+ use_cache=use_cache,
1124
+ )
1125
+
1126
+ hidden_states = layer_outputs[0]
1127
+
1128
+ if use_cache:
1129
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1130
+
1131
+ if output_attentions:
1132
+ all_self_attns += (layer_outputs[1],)
1133
+
1134
+ hidden_states = self.norm(hidden_states)
1135
+
1136
+ # add hidden states from the last decoder layer
1137
+ if output_hidden_states:
1138
+ all_hidden_states += (hidden_states,)
1139
+
1140
+ next_cache = None
1141
+ if use_cache:
1142
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1143
+ if not return_dict:
1144
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1145
+ return BaseModelOutputWithPast(
1146
+ last_hidden_state=hidden_states,
1147
+ past_key_values=next_cache,
1148
+ hidden_states=all_hidden_states,
1149
+ attentions=all_self_attns,
1150
+ )
1151
+
1152
+
1153
+ class MiniCPMForCausalLM(MiniCPMPreTrainedModel):
1154
+ _tied_weights_keys = ['lm_head.weight']
1155
+
1156
+ def __init__(self, config):
1157
+ super().__init__(config)
1158
+ self.model = MiniCPMModel(config)
1159
+ self.vocab_size = config.vocab_size
1160
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1161
+
1162
+ # Initialize weights and apply final processing
1163
+ self.post_init()
1164
+
1165
+ def get_input_embeddings(self):
1166
+ return self.model.embed_tokens
1167
+
1168
+ def set_input_embeddings(self, value):
1169
+ self.model.embed_tokens = value
1170
+
1171
+ def get_output_embeddings(self):
1172
+ return self.lm_head
1173
+
1174
+ def set_output_embeddings(self, new_embeddings):
1175
+ self.lm_head = new_embeddings
1176
+
1177
+ def set_decoder(self, decoder):
1178
+ self.model = decoder
1179
+
1180
+ def get_decoder(self):
1181
+ return self.model
1182
+
1183
+ @add_start_docstrings_to_model_forward(MINICPM_INPUTS_DOCSTRING)
1184
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1185
+ def forward(
1186
+ self,
1187
+ input_ids: torch.LongTensor = None,
1188
+ attention_mask: Optional[torch.Tensor] = None,
1189
+ position_ids: Optional[torch.LongTensor] = None,
1190
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1191
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1192
+ labels: Optional[torch.LongTensor] = None,
1193
+ use_cache: Optional[bool] = None,
1194
+ output_attentions: Optional[bool] = None,
1195
+ output_hidden_states: Optional[bool] = None,
1196
+ return_dict: Optional[bool] = None,
1197
+ logits_to_keep: Union[int, torch.Tensor] = 0,
1198
+ **kwargs,
1199
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1200
+ r"""
1201
+ Args:
1202
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1203
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1204
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1205
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1206
+
1207
+ Returns:
1208
+
1209
+ Example:
1210
+
1211
+ ```python
1212
+ >>> from transformers import AutoTokenizer, MiniCPMForCausalLM
1213
+
1214
+ >>> model = MiniCPMForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1215
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1216
+
1217
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1218
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1219
+
1220
+ >>> # Generate
1221
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1222
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1223
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1224
+ ```"""
1225
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1226
+ output_hidden_states = (
1227
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1228
+ )
1229
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1230
+
1231
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1232
+ outputs = self.model(
1233
+ input_ids=input_ids,
1234
+ attention_mask=attention_mask,
1235
+ position_ids=position_ids,
1236
+ past_key_values=past_key_values,
1237
+ inputs_embeds=inputs_embeds,
1238
+ use_cache=use_cache,
1239
+ output_attentions=output_attentions,
1240
+ output_hidden_states=output_hidden_states,
1241
+ return_dict=return_dict,
1242
+ )
1243
+
1244
+ hidden_states = outputs[0]
1245
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1246
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1247
+ hidden_states = hidden_states[:, slice_indices, :].contiguous()
1248
+ if self.config.pretraining_tp > 1:
1249
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1250
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1251
+ logits = torch.cat(logits, dim=-1)
1252
+ else:
1253
+ logits = self.lm_head(hidden_states / (self.config.hidden_size / self.config.dim_model_base))
1254
+ logits = logits.float()
1255
+
1256
+ loss = None
1257
+ if labels is not None:
1258
+ # Shift so that tokens < n predict n
1259
+ shift_logits = logits[..., :-1, :].contiguous()
1260
+ shift_labels = labels[..., 1:].contiguous()
1261
+ # Flatten the tokens
1262
+ loss_fct = CrossEntropyLoss()
1263
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1264
+ shift_labels = shift_labels.view(-1)
1265
+ # Enable model parallelism
1266
+ shift_labels = shift_labels.to(shift_logits.device)
1267
+ loss = loss_fct(shift_logits, shift_labels)
1268
+
1269
+ if not return_dict:
1270
+ output = (logits,) + outputs[1:]
1271
+ return (loss,) + output if loss is not None else output
1272
+
1273
+ return CausalLMOutputWithPast(
1274
+ loss=loss,
1275
+ logits=logits,
1276
+ past_key_values=outputs.past_key_values,
1277
+ hidden_states=outputs.hidden_states,
1278
+ attentions=outputs.attentions,
1279
+ )
1280
+
1281
+ def prepare_inputs_for_generation(
1282
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1283
+ ):
1284
+ if past_key_values is not None:
1285
+ if isinstance(past_key_values, Cache):
1286
+ # Use the new Cache class methods
1287
+ cache_length = past_key_values.get_seq_length()
1288
+
1289
+
1290
+ past_length = cache_length
1291
+ max_cache_length = None
1292
+ else:
1293
+ raise ValueError(
1294
+ 'You must use the new past_key_values format, such as the Cache class, instead of the old tuple format.'
1295
+ )
1296
+
1297
+ # Keep only the unprocessed tokens:
1298
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1299
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1300
+ # input)
1301
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1302
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length):]
1303
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1304
+ # input_ids based on the past_length.
1305
+ elif past_length < input_ids.shape[1]:
1306
+ input_ids = input_ids[:, past_length:]
1307
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1308
+
1309
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1310
+ if (
1311
+ max_cache_length is not None
1312
+ and attention_mask is not None
1313
+ and cache_length + input_ids.shape[1] > max_cache_length
1314
+ ):
1315
+ attention_mask = attention_mask[:, -max_cache_length:]
1316
+
1317
+ position_ids = kwargs.get('position_ids', None)
1318
+ if attention_mask is not None and position_ids is None:
1319
+ # create position_ids on the fly for batch generation
1320
+ position_ids = attention_mask.long().cumsum(-1) - 1
1321
+ position_ids.masked_fill_(attention_mask == 0, 1)
1322
+ if past_key_values:
1323
+ position_ids = position_ids[:, -input_ids.shape[1]:]
1324
+
1325
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1326
+ if inputs_embeds is not None and past_key_values is None:
1327
+ model_inputs = {'inputs_embeds': inputs_embeds}
1328
+ else:
1329
+ model_inputs = {'input_ids': input_ids}
1330
+
1331
+ model_inputs.update(
1332
+ {
1333
+ 'position_ids': position_ids,
1334
+ 'past_key_values': past_key_values,
1335
+ 'use_cache': kwargs.get('use_cache'),
1336
+ 'attention_mask': attention_mask,
1337
+ }
1338
+ )
1339
+ # Forward ALL kwargs that are uninitialized (e.g. `use_cache`).
1340
+ for key, value in kwargs.items():
1341
+ if key not in model_inputs:
1342
+ model_inputs[key] = value
1343
+ return model_inputs
1344
+
1345
+ @staticmethod
1346
+ def _reorder_cache(past_key_values, beam_idx):
1347
+ reordered_past = ()
1348
+ for layer_past in past_key_values:
1349
+ reordered_past += (
1350
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1351
+ )
1352
+ return reordered_past
1353
+
1354
+ @torch.inference_mode()
1355
+ def chat(self, tokenizer, query: str, history: List[Dict] = None, role: str = 'user',
1356
+ max_length: int = 4096, num_beams=1, do_sample=True, top_p=0.8, temperature=0.3, logits_processor=None,
1357
+ **kwargs):
1358
+ if history is None:
1359
+ history = []
1360
+ if logits_processor:
1361
+ gen_kwargs = {
1362
+ 'max_length': max_length,
1363
+ 'num_beams': num_beams,
1364
+ 'do_sample': do_sample,
1365
+ 'top_p': top_p,
1366
+ 'temperature': temperature,
1367
+ 'logits_processor': logits_processor,
1368
+ **kwargs
1369
+ }
1370
+ else:
1371
+ gen_kwargs = {
1372
+ 'max_length': max_length,
1373
+ 'num_beams': num_beams,
1374
+ 'do_sample': do_sample,
1375
+ 'top_p': top_p,
1376
+ 'temperature': temperature,
1377
+ 'logits_processor': logits_processor,
1378
+ **kwargs
1379
+ }
1380
+
1381
+ history.append({'role': role, 'content': query})
1382
+ history_str = tokenizer.apply_chat_template(history, tokenize=False, add_generation_prompt=False)
1383
+ inputs = tokenizer(history_str, return_tensors='pt').to(self.device)
1384
+ outputs = self.generate(**inputs, **gen_kwargs)
1385
+ outputs = outputs.tolist()[0][len(inputs['input_ids'][0]):-1]
1386
+ response = tokenizer.decode(outputs)
1387
+ pattern = re.compile(r'.*?(?=<AI>|<用户>)', re.DOTALL)
1388
+ matches = pattern.findall(response)
1389
+ if len(matches) > 0:
1390
+ response = matches[0]
1391
+ history.append({'role': 'assistant', 'content': response})
1392
+ return response, history
1393
+
1394
+
1395
+ @add_start_docstrings(
1396
+ """
1397
+ The MiniCPM Model transformer with a sequence classification head on top (linear layer).
1398
+
1399
+ [`MiniCPMForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1400
+ (e.g. GPT-2) do.
1401
+
1402
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1403
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1404
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1405
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1406
+ each row of the batch).
1407
+ """,
1408
+ MINICPM_START_DOCSTRING,
1409
+ )
1410
+ class MiniCPMForSequenceClassification(MiniCPMPreTrainedModel):
1411
+ def __init__(self, config):
1412
+ super().__init__(config)
1413
+ self.num_labels = config.num_labels
1414
+ self.model = MiniCPMModel(config)
1415
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1416
+
1417
+ # Initialize weights and apply final processing
1418
+ self.post_init()
1419
+
1420
+ def get_input_embeddings(self):
1421
+ return self.model.embed_tokens
1422
+
1423
+ def set_input_embeddings(self, value):
1424
+ self.model.embed_tokens = value
1425
+
1426
+ @add_start_docstrings_to_model_forward(MINICPM_INPUTS_DOCSTRING)
1427
+ def forward(
1428
+ self,
1429
+ input_ids: torch.LongTensor = None,
1430
+ attention_mask: Optional[torch.Tensor] = None,
1431
+ position_ids: Optional[torch.LongTensor] = None,
1432
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1433
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1434
+ labels: Optional[torch.LongTensor] = None,
1435
+ use_cache: Optional[bool] = None,
1436
+ output_attentions: Optional[bool] = None,
1437
+ output_hidden_states: Optional[bool] = None,
1438
+ return_dict: Optional[bool] = None,
1439
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1440
+ r"""
1441
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1442
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1443
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1444
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1445
+ """
1446
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1447
+
1448
+ transformer_outputs = self.model(
1449
+ input_ids,
1450
+ attention_mask=attention_mask,
1451
+ position_ids=position_ids,
1452
+ past_key_values=past_key_values,
1453
+ inputs_embeds=inputs_embeds,
1454
+ use_cache=use_cache,
1455
+ output_attentions=output_attentions,
1456
+ output_hidden_states=output_hidden_states,
1457
+ return_dict=return_dict,
1458
+ )
1459
+ hidden_states = transformer_outputs[0]
1460
+ logits = self.score(hidden_states)
1461
+
1462
+ if input_ids is not None:
1463
+ batch_size = input_ids.shape[0]
1464
+ else:
1465
+ batch_size = inputs_embeds.shape[0]
1466
+
1467
+ if self.config.pad_token_id is None and batch_size != 1:
1468
+ raise ValueError('Cannot handle batch sizes > 1 if no padding token is defined.')
1469
+ if self.config.pad_token_id is None:
1470
+ sequence_lengths = -1
1471
+ else:
1472
+ if input_ids is not None:
1473
+ sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1).to(
1474
+ logits.device
1475
+ )
1476
+ else:
1477
+ sequence_lengths = -1
1478
+
1479
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1480
+
1481
+ loss = None
1482
+ if labels is not None:
1483
+ labels = labels.to(logits.device)
1484
+ if self.config.problem_type is None:
1485
+ if self.num_labels == 1:
1486
+ self.config.problem_type = 'regression'
1487
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1488
+ self.config.problem_type = 'single_label_classification'
1489
+ else:
1490
+ self.config.problem_type = 'multi_label_classification'
1491
+
1492
+ if self.config.problem_type == 'regression':
1493
+ loss_fct = MSELoss()
1494
+ if self.num_labels == 1:
1495
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1496
+ else:
1497
+ loss = loss_fct(pooled_logits, labels)
1498
+ elif self.config.problem_type == 'single_label_classification':
1499
+ loss_fct = CrossEntropyLoss()
1500
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1501
+ elif self.config.problem_type == 'multi_label_classification':
1502
+ loss_fct = BCEWithLogitsLoss()
1503
+ loss = loss_fct(pooled_logits, labels)
1504
+ if not return_dict:
1505
+ output = (pooled_logits,) + transformer_outputs[1:]
1506
+ return ((loss,) + output) if loss is not None else output
1507
+
1508
+ return SequenceClassifierOutputWithPast(
1509
+ loss=loss,
1510
+ logits=pooled_logits,
1511
+ past_key_values=transformer_outputs.past_key_values,
1512
+ hidden_states=transformer_outputs.hidden_states,
1513
+ attentions=transformer_outputs.attentions,
1514
+ )