maverickrzw commited on
Commit
94da4ad
·
1 Parent(s): 1ff0286

Init commit

Browse files
Intern_300m/config.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "InternLMForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "modeling_internlm.InternLMConfig",
7
+ "AutoModelForCausalLM": "modeling_internlm.InternLMForCausalLM",
8
+ "AutoModel": "modeling_internlm.InternLMForCausalLM"
9
+ },
10
+ "bias": true,
11
+ "hidden_act": "silu",
12
+ "hidden_size": 1024,
13
+ "initializer_range": 0.02,
14
+ "intermediate_size": 2816,
15
+ "max_position_embeddings": 2048,
16
+ "model_type": "internlm",
17
+ "num_attention_heads": 8,
18
+ "num_hidden_layers": 22,
19
+ "rms_norm_eps": 1e-06,
20
+ "tie_word_embeddings": false,
21
+ "torch_dtype": "float16",
22
+ "transformers_version": "4.30.2",
23
+ "use_cache": true,
24
+ "vocab_size": 8192
25
+ }
Intern_300m/generation_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "transformers_version": "4.30.2"
4
+ }
Intern_300m/modeling_internlm.py ADDED
@@ -0,0 +1,1062 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch InternLM model."""
21
+ import math
22
+ import queue
23
+ import threading
24
+ from typing import List, Optional, Tuple, Union
25
+
26
+ import torch
27
+ import torch.utils.checkpoint
28
+ from torch import nn
29
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
30
+ from transformers.activations import ACT2FN
31
+ from transformers.configuration_utils import PretrainedConfig
32
+ from transformers.generation.streamers import BaseStreamer
33
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, \
34
+ SequenceClassifierOutputWithPast
35
+ from transformers.modeling_utils import PreTrainedModel
36
+ from transformers.utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, \
37
+ replace_return_docstrings
38
+
39
+ logger = logging.get_logger(__name__)
40
+
41
+ INTERNLM_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
42
+ _CONFIG_FOR_DOC = "InternLMConfig"
43
+
44
+
45
+ class InternLMConfig(PretrainedConfig):
46
+ r"""
47
+ This is the configuration class to store the configuration of a [`InternLMModel`]. It is used to instantiate an InternLM
48
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
49
+ defaults will yield a similar configuration to that of the InternLM-7B.
50
+
51
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
52
+ documentation from [`PretrainedConfig`] for more information.
53
+
54
+
55
+ Args:
56
+ vocab_size (`int`, *optional*, defaults to 32000):
57
+ Vocabulary size of the InternLM model. Defines the number of different tokens that can be represented by the
58
+ `inputs_ids` passed when calling [`InternLMModel`]
59
+ hidden_size (`int`, *optional*, defaults to 4096):
60
+ Dimension of the hidden representations.
61
+ intermediate_size (`int`, *optional*, defaults to 11008):
62
+ Dimension of the MLP representations.
63
+ num_hidden_layers (`int`, *optional*, defaults to 32):
64
+ Number of hidden layers in the Transformer encoder.
65
+ num_attention_heads (`int`, *optional*, defaults to 32):
66
+ Number of attention heads for each attention layer in the Transformer encoder.
67
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
68
+ The non-linear activation function (function or string) in the decoder.
69
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
70
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
71
+ just in case (e.g., 512 or 1024 or 2048).
72
+ initializer_range (`float`, *optional*, defaults to 0.02):
73
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
74
+ rms_norm_eps (`float`, *optional*, defaults to 1e-12):
75
+ The epsilon used by the rms normalization layers.
76
+ use_cache (`bool`, *optional*, defaults to `True`):
77
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
78
+ relevant if `config.is_decoder=True`.
79
+ tie_word_embeddings(`bool`, *optional*, defaults to `False`):
80
+ Whether to tie weight embeddings
81
+ """
82
+ model_type = "internlm"
83
+ _auto_class = "AutoConfig"
84
+
85
+ def __init__(
86
+ self,
87
+ vocab_size=103168,
88
+ hidden_size=4096,
89
+ intermediate_size=11008,
90
+ num_hidden_layers=32,
91
+ num_attention_heads=32,
92
+ hidden_act="silu",
93
+ max_position_embeddings=2048,
94
+ initializer_range=0.02,
95
+ rms_norm_eps=1e-6,
96
+ use_cache=True,
97
+ pad_token_id=None,
98
+ bos_token_id=None,
99
+ eos_token_id=None,
100
+ tie_word_embeddings=False,
101
+ bias=True,
102
+ **kwargs,
103
+ ):
104
+ self.vocab_size = vocab_size
105
+ self.max_position_embeddings = max_position_embeddings
106
+ self.hidden_size = hidden_size
107
+ self.intermediate_size = intermediate_size
108
+ self.num_hidden_layers = num_hidden_layers
109
+ self.num_attention_heads = num_attention_heads
110
+ self.hidden_act = hidden_act
111
+ self.initializer_range = initializer_range
112
+ self.rms_norm_eps = rms_norm_eps
113
+ self.use_cache = use_cache
114
+ self.bias = bias
115
+ super().__init__(
116
+ pad_token_id=pad_token_id,
117
+ bos_token_id=bos_token_id,
118
+ eos_token_id=eos_token_id,
119
+ tie_word_embeddings=tie_word_embeddings,
120
+ **kwargs,
121
+ )
122
+
123
+
124
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
125
+ def _make_causal_mask(
126
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
127
+ ):
128
+ """
129
+ Make causal mask used for bi-directional self-attention.
130
+ """
131
+ bsz, tgt_len = input_ids_shape
132
+ mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
133
+ mask_cond = torch.arange(mask.size(-1), device=device)
134
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
135
+ mask = mask.to(dtype)
136
+
137
+ if past_key_values_length > 0:
138
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
139
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
140
+
141
+
142
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
143
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
144
+ """
145
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
146
+ """
147
+ bsz, src_len = mask.size()
148
+ tgt_len = tgt_len if tgt_len is not None else src_len
149
+
150
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
151
+
152
+ inverted_mask = 1.0 - expanded_mask
153
+
154
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
155
+
156
+
157
+ class InternLMRMSNorm(nn.Module):
158
+ def __init__(self, hidden_size, eps=1e-6):
159
+ """
160
+ InternLMRMSNorm is equivalent to T5LayerNorm
161
+ """
162
+ super().__init__()
163
+ self.weight = nn.Parameter(torch.ones(hidden_size))
164
+ self.variance_epsilon = eps
165
+
166
+ def forward(self, hidden_states):
167
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
168
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
169
+
170
+ # convert into half-precision if necessary
171
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
172
+ hidden_states = hidden_states.to(self.weight.dtype)
173
+
174
+ return self.weight * hidden_states
175
+
176
+
177
+ class InternLMRotaryEmbedding(torch.nn.Module):
178
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
179
+ super().__init__()
180
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
181
+ self.register_buffer("inv_freq", inv_freq)
182
+
183
+ # Build here to make `torch.jit.trace` work.
184
+ self.max_seq_len_cached = max_position_embeddings
185
+ t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
186
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
187
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
188
+ emb = torch.cat((freqs, freqs), dim=-1)
189
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :], persistent=False)
190
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :], persistent=False)
191
+
192
+ def forward(self, x, seq_len=None):
193
+ # x: [bs, num_attention_heads, seq_len, head_size]
194
+ # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
195
+ if seq_len > self.max_seq_len_cached:
196
+ self.max_seq_len_cached = seq_len
197
+ t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
198
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
199
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
200
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
201
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :], persistent=False)
202
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :], persistent=False)
203
+ return (
204
+ self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
205
+ self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
206
+ )
207
+
208
+
209
+ def rotate_half(x):
210
+ """Rotates half the hidden dims of the input."""
211
+ x1 = x[..., : x.shape[-1] // 2]
212
+ x2 = x[..., x.shape[-1] // 2:]
213
+ return torch.cat((-x2, x1), dim=-1)
214
+
215
+
216
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
217
+ # The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
218
+ cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
219
+ sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
220
+ cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
221
+ sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
222
+ q_embed = (q * cos) + (rotate_half(q) * sin)
223
+ k_embed = (k * cos) + (rotate_half(k) * sin)
224
+ return q_embed, k_embed
225
+
226
+
227
+ class InternLMMLP(nn.Module):
228
+ def __init__(
229
+ self,
230
+ hidden_size: int,
231
+ intermediate_size: int,
232
+ hidden_act: str,
233
+ ):
234
+ super().__init__()
235
+ self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
236
+ self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
237
+ self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
238
+ self.act_fn = ACT2FN[hidden_act]
239
+
240
+ def forward(self, x):
241
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
242
+
243
+
244
+ class InternLMAttention(nn.Module):
245
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
246
+
247
+ def __init__(self, config: InternLMConfig):
248
+ super().__init__()
249
+ self.config = config
250
+ self.hidden_size = config.hidden_size
251
+ self.num_heads = config.num_attention_heads
252
+ self.head_dim = self.hidden_size // self.num_heads
253
+ self.max_position_embeddings = config.max_position_embeddings
254
+
255
+ if (self.head_dim * self.num_heads) != self.hidden_size:
256
+ raise ValueError(
257
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
258
+ f" and `num_heads`: {self.num_heads})."
259
+ )
260
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.bias)
261
+ self.k_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.bias)
262
+ self.v_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.bias)
263
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.bias)
264
+ self.rotary_emb = InternLMRotaryEmbedding(self.head_dim, max_position_embeddings=self.max_position_embeddings)
265
+
266
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
267
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
268
+
269
+ def forward(
270
+ self,
271
+ hidden_states: torch.Tensor,
272
+ attention_mask: Optional[torch.Tensor] = None,
273
+ position_ids: Optional[torch.LongTensor] = None,
274
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
275
+ output_attentions: bool = False,
276
+ use_cache: bool = False,
277
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
278
+ bsz, q_len, _ = hidden_states.size()
279
+
280
+ query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
281
+ key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
282
+ value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
283
+
284
+ kv_seq_len = key_states.shape[-2]
285
+ if past_key_value is not None:
286
+ kv_seq_len += past_key_value[0].shape[-2]
287
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
288
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
289
+ # [bsz, nh, t, hd]
290
+
291
+ if past_key_value is not None:
292
+ # reuse k, v, self_attention
293
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
294
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
295
+
296
+ past_key_value = (key_states, value_states) if use_cache else None
297
+
298
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
299
+
300
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
301
+ raise ValueError(
302
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
303
+ f" {attn_weights.size()}"
304
+ )
305
+
306
+ if attention_mask is not None:
307
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
308
+ raise ValueError(
309
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
310
+ )
311
+ attn_weights = attn_weights + attention_mask
312
+ attn_weights = torch.max(attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min))
313
+
314
+ # upcast attention to fp32
315
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
316
+ attn_output = torch.matmul(attn_weights, value_states)
317
+
318
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
319
+ raise ValueError(
320
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
321
+ f" {attn_output.size()}"
322
+ )
323
+
324
+ attn_output = attn_output.transpose(1, 2)
325
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
326
+
327
+ attn_output = self.o_proj(attn_output)
328
+
329
+ if not output_attentions:
330
+ attn_weights = None
331
+
332
+ return attn_output, attn_weights, past_key_value
333
+
334
+
335
+ class InternLMDecoderLayer(nn.Module):
336
+ def __init__(self, config: InternLMConfig):
337
+ super().__init__()
338
+ self.hidden_size = config.hidden_size
339
+ self.self_attn = InternLMAttention(config=config)
340
+ self.mlp = InternLMMLP(
341
+ hidden_size=self.hidden_size,
342
+ intermediate_size=config.intermediate_size,
343
+ hidden_act=config.hidden_act,
344
+ )
345
+ self.input_layernorm = InternLMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
346
+ self.post_attention_layernorm = InternLMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
347
+
348
+ def forward(
349
+ self,
350
+ hidden_states: torch.Tensor,
351
+ attention_mask: Optional[torch.Tensor] = None,
352
+ position_ids: Optional[torch.LongTensor] = None,
353
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
354
+ output_attentions: Optional[bool] = False,
355
+ use_cache: Optional[bool] = False,
356
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
357
+ """
358
+ Args:
359
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
360
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
361
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
362
+ output_attentions (`bool`, *optional*):
363
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
364
+ returned tensors for more detail.
365
+ use_cache (`bool`, *optional*):
366
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
367
+ (see `past_key_values`).
368
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
369
+ """
370
+
371
+ residual = hidden_states
372
+
373
+ hidden_states = self.input_layernorm(hidden_states)
374
+
375
+ # Self Attention
376
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
377
+ hidden_states=hidden_states,
378
+ attention_mask=attention_mask,
379
+ position_ids=position_ids,
380
+ past_key_value=past_key_value,
381
+ output_attentions=output_attentions,
382
+ use_cache=use_cache,
383
+ )
384
+ hidden_states = residual + hidden_states
385
+
386
+ # Fully Connected
387
+ residual = hidden_states
388
+ hidden_states = self.post_attention_layernorm(hidden_states)
389
+ hidden_states = self.mlp(hidden_states)
390
+ hidden_states = residual + hidden_states
391
+
392
+ outputs = (hidden_states,)
393
+
394
+ if output_attentions:
395
+ outputs += (self_attn_weights,)
396
+
397
+ if use_cache:
398
+ outputs += (present_key_value,)
399
+
400
+ return outputs
401
+
402
+
403
+ INTERNLM_START_DOCSTRING = r"""
404
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
405
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
406
+ etc.)
407
+
408
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
409
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
410
+ and behavior.
411
+
412
+ Parameters:
413
+ config ([`InternLMConfig`]):
414
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
415
+ load the weights associated with the model, only the configuration. Check out the
416
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
417
+ """
418
+
419
+
420
+ @add_start_docstrings(
421
+ "The bare InternLM Model outputting raw hidden-states without any specific head on top.",
422
+ INTERNLM_START_DOCSTRING,
423
+ )
424
+ class InternLMPreTrainedModel(PreTrainedModel):
425
+ config_class = InternLMConfig
426
+ base_model_prefix = "model"
427
+ supports_gradient_checkpointing = True
428
+ _no_split_modules = ["InternLMDecoderLayer"]
429
+ _keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
430
+
431
+ def _init_weights(self, module):
432
+ std = self.config.initializer_range
433
+ if isinstance(module, nn.Linear):
434
+ module.weight.data.normal_(mean=0.0, std=std)
435
+ if module.bias is not None:
436
+ module.bias.data.zero_()
437
+ elif isinstance(module, nn.Embedding):
438
+ module.weight.data.normal_(mean=0.0, std=std)
439
+ if module.padding_idx is not None:
440
+ module.weight.data[module.padding_idx].zero_()
441
+
442
+ def _set_gradient_checkpointing(self, module, value=False):
443
+ if isinstance(module, InternLMModel):
444
+ module.gradient_checkpointing = value
445
+
446
+
447
+ INTERNLM_INPUTS_DOCSTRING = r"""
448
+ Args:
449
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
450
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
451
+ it.
452
+
453
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
454
+ [`PreTrainedTokenizer.__call__`] for details.
455
+
456
+ [What are input IDs?](../glossary#input-ids)
457
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
458
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
459
+
460
+ - 1 for tokens that are **not masked**,
461
+ - 0 for tokens that are **masked**.
462
+
463
+ [What are attention masks?](../glossary#attention-mask)
464
+
465
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
466
+ [`PreTrainedTokenizer.__call__`] for details.
467
+
468
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
469
+ `past_key_values`).
470
+
471
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
472
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
473
+ information on the default strategy.
474
+
475
+ - 1 indicates the head is **not masked**,
476
+ - 0 indicates the head is **masked**.
477
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
478
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
479
+ config.n_positions - 1]`.
480
+
481
+ [What are position IDs?](../glossary#position-ids)
482
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
483
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
484
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
485
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
486
+
487
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
488
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
489
+
490
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
491
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
492
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
493
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
494
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
495
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
496
+ model's internal embedding lookup matrix.
497
+ use_cache (`bool`, *optional*):
498
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
499
+ `past_key_values`).
500
+ output_attentions (`bool`, *optional*):
501
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
502
+ tensors for more detail.
503
+ output_hidden_states (`bool`, *optional*):
504
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
505
+ more detail.
506
+ return_dict (`bool`, *optional*):
507
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
508
+ """
509
+
510
+ @add_start_docstrings(
511
+ "The bare InternLM Model outputting raw hidden-states without any specific head on top.",
512
+ INTERNLM_START_DOCSTRING,
513
+ )
514
+ class InternLMModel(InternLMPreTrainedModel):
515
+ """
516
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`InternLMDecoderLayer`]
517
+
518
+ Args:
519
+ config: InternLMConfig
520
+ """
521
+ _auto_class = "AutoModel"
522
+
523
+ def __init__(self, config: InternLMConfig):
524
+ super().__init__(config)
525
+ self.vocab_size = config.vocab_size
526
+
527
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
528
+ self.layers = nn.ModuleList([InternLMDecoderLayer(config) for _ in range(config.num_hidden_layers)])
529
+ self.norm = InternLMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
530
+
531
+ self.gradient_checkpointing = False
532
+ # Initialize weights and apply final processing
533
+ self.post_init()
534
+
535
+ def get_input_embeddings(self):
536
+ return self.embed_tokens
537
+
538
+ def set_input_embeddings(self, value):
539
+ self.embed_tokens = value
540
+
541
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
542
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
543
+ # create causal mask
544
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
545
+ combined_attention_mask = None
546
+ if input_shape[-1] > 1:
547
+ combined_attention_mask = _make_causal_mask(
548
+ input_shape,
549
+ inputs_embeds.dtype,
550
+ device=inputs_embeds.device,
551
+ past_key_values_length=past_key_values_length,
552
+ )
553
+
554
+ if attention_mask is not None:
555
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
556
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
557
+ inputs_embeds.device
558
+ )
559
+ combined_attention_mask = (
560
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
561
+ )
562
+
563
+ return combined_attention_mask
564
+
565
+ @add_start_docstrings_to_model_forward(INTERNLM_INPUTS_DOCSTRING)
566
+ def forward(
567
+ self,
568
+ input_ids: torch.LongTensor = None,
569
+ attention_mask: Optional[torch.Tensor] = None,
570
+ position_ids: Optional[torch.LongTensor] = None,
571
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
572
+ inputs_embeds: Optional[torch.FloatTensor] = None,
573
+ use_cache: Optional[bool] = None,
574
+ output_attentions: Optional[bool] = None,
575
+ output_hidden_states: Optional[bool] = None,
576
+ return_dict: Optional[bool] = None,
577
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
578
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
579
+ output_hidden_states = (
580
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
581
+ )
582
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
583
+
584
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
585
+
586
+ # retrieve input_ids and inputs_embeds
587
+ if input_ids is not None and inputs_embeds is not None:
588
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
589
+ elif input_ids is not None:
590
+ batch_size, seq_length = input_ids.shape
591
+ elif inputs_embeds is not None:
592
+ batch_size, seq_length, _ = inputs_embeds.shape
593
+ else:
594
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
595
+
596
+ seq_length_with_past = seq_length
597
+ past_key_values_length = 0
598
+
599
+ if past_key_values is not None:
600
+ past_key_values_length = past_key_values[0][0].shape[2]
601
+ seq_length_with_past = seq_length_with_past + past_key_values_length
602
+
603
+ if position_ids is None:
604
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
605
+ position_ids = torch.arange(
606
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
607
+ )
608
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
609
+ else:
610
+ position_ids = position_ids.view(-1, seq_length).long()
611
+
612
+ if inputs_embeds is None:
613
+ inputs_embeds = self.embed_tokens(input_ids)
614
+ # embed positions
615
+ if attention_mask is None:
616
+ attention_mask = torch.ones(
617
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
618
+ )
619
+ attention_mask = self._prepare_decoder_attention_mask(
620
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
621
+ )
622
+
623
+ hidden_states = inputs_embeds
624
+
625
+ if self.gradient_checkpointing and self.training:
626
+ if use_cache:
627
+ logger.warning_once(
628
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
629
+ )
630
+ use_cache = False
631
+
632
+ # decoder layers
633
+ all_hidden_states = () if output_hidden_states else None
634
+ all_self_attns = () if output_attentions else None
635
+ next_decoder_cache = () if use_cache else None
636
+
637
+ for idx, decoder_layer in enumerate(self.layers):
638
+ if output_hidden_states:
639
+ all_hidden_states += (hidden_states,)
640
+
641
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
642
+
643
+ if self.gradient_checkpointing and self.training:
644
+
645
+ def create_custom_forward(module):
646
+ def custom_forward(*inputs):
647
+ # None for past_key_value
648
+ return module(*inputs, output_attentions, None)
649
+
650
+ return custom_forward
651
+
652
+ layer_outputs = torch.utils.checkpoint.checkpoint(
653
+ create_custom_forward(decoder_layer),
654
+ hidden_states,
655
+ attention_mask,
656
+ position_ids,
657
+ None,
658
+ )
659
+ else:
660
+ layer_outputs = decoder_layer(
661
+ hidden_states,
662
+ attention_mask=attention_mask,
663
+ position_ids=position_ids,
664
+ past_key_value=past_key_value,
665
+ output_attentions=output_attentions,
666
+ use_cache=use_cache,
667
+ )
668
+
669
+ hidden_states = layer_outputs[0]
670
+
671
+ if use_cache:
672
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
673
+
674
+ if output_attentions:
675
+ all_self_attns += (layer_outputs[1],)
676
+
677
+ hidden_states = self.norm(hidden_states)
678
+
679
+ # add hidden states from the last decoder layer
680
+ if output_hidden_states:
681
+ all_hidden_states += (hidden_states,)
682
+
683
+ next_cache = next_decoder_cache if use_cache else None
684
+ if not return_dict:
685
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
686
+ return BaseModelOutputWithPast(
687
+ last_hidden_state=hidden_states,
688
+ past_key_values=next_cache,
689
+ hidden_states=all_hidden_states,
690
+ attentions=all_self_attns,
691
+ )
692
+
693
+
694
+ class InternLMForCausalLM(InternLMPreTrainedModel):
695
+ _auto_class = "AutoModelForCausalLM"
696
+
697
+ def __init__(self, config):
698
+ super().__init__(config)
699
+ self.model = InternLMModel(config)
700
+
701
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
702
+
703
+ # Initialize weights and apply final processing
704
+ self.post_init()
705
+
706
+ def get_input_embeddings(self):
707
+ return self.model.embed_tokens
708
+
709
+ def set_input_embeddings(self, value):
710
+ self.model.embed_tokens = value
711
+
712
+ def get_output_embeddings(self):
713
+ return self.lm_head
714
+
715
+ def set_output_embeddings(self, new_embeddings):
716
+ self.lm_head = new_embeddings
717
+
718
+ def set_decoder(self, decoder):
719
+ self.model = decoder
720
+
721
+ def get_decoder(self):
722
+ return self.model
723
+
724
+ @add_start_docstrings_to_model_forward(INTERNLM_INPUTS_DOCSTRING)
725
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
726
+ def forward(
727
+ self,
728
+ input_ids: torch.LongTensor = None,
729
+ attention_mask: Optional[torch.Tensor] = None,
730
+ position_ids: Optional[torch.LongTensor] = None,
731
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
732
+ inputs_embeds: Optional[torch.FloatTensor] = None,
733
+ labels: Optional[torch.LongTensor] = None,
734
+ use_cache: Optional[bool] = None,
735
+ output_attentions: Optional[bool] = None,
736
+ output_hidden_states: Optional[bool] = None,
737
+ return_dict: Optional[bool] = None,
738
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
739
+ r"""
740
+ Args:
741
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
742
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
743
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
744
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
745
+
746
+ Returns:
747
+ """
748
+
749
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
750
+ output_hidden_states = (
751
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
752
+ )
753
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
754
+
755
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
756
+ outputs = self.model(
757
+ input_ids=input_ids,
758
+ attention_mask=attention_mask,
759
+ position_ids=position_ids,
760
+ past_key_values=past_key_values,
761
+ inputs_embeds=inputs_embeds,
762
+ use_cache=use_cache,
763
+ output_attentions=output_attentions,
764
+ output_hidden_states=output_hidden_states,
765
+ return_dict=return_dict,
766
+ )
767
+
768
+ hidden_states = outputs[0]
769
+ logits = self.lm_head(hidden_states)
770
+
771
+ loss = None
772
+ if labels is not None:
773
+ # Shift so that tokens < n predict n
774
+ shift_logits = logits[..., :-1, :].contiguous()
775
+ shift_labels = labels[..., 1:].contiguous()
776
+ # Flatten the tokens
777
+ loss_fct = CrossEntropyLoss()
778
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
779
+ shift_labels = shift_labels.view(-1)
780
+ # Enable model parallelism
781
+ shift_labels = shift_labels.to(shift_logits.device)
782
+ loss = loss_fct(shift_logits, shift_labels)
783
+
784
+ if not return_dict:
785
+ output = (logits,) + outputs[1:]
786
+ return (loss,) + output if loss is not None else output
787
+
788
+ return CausalLMOutputWithPast(
789
+ loss=loss,
790
+ logits=logits,
791
+ past_key_values=outputs.past_key_values,
792
+ hidden_states=outputs.hidden_states,
793
+ attentions=outputs.attentions,
794
+ )
795
+
796
+ def prepare_inputs_for_generation(
797
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
798
+ ):
799
+ if past_key_values:
800
+ input_ids = input_ids[:, -1:]
801
+
802
+ position_ids = kwargs.get("position_ids", None)
803
+ if attention_mask is not None and position_ids is None:
804
+ # create position_ids on the fly for batch generation
805
+ position_ids = attention_mask.long().cumsum(-1) - 1
806
+ position_ids.masked_fill_(attention_mask == 0, 1)
807
+ if past_key_values:
808
+ position_ids = position_ids[:, -1].unsqueeze(-1)
809
+
810
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
811
+ if inputs_embeds is not None and past_key_values is None:
812
+ model_inputs = {"inputs_embeds": inputs_embeds}
813
+ else:
814
+ model_inputs = {"input_ids": input_ids}
815
+
816
+ model_inputs.update(
817
+ {
818
+ "position_ids": position_ids,
819
+ "past_key_values": past_key_values,
820
+ "use_cache": kwargs.get("use_cache"),
821
+ "attention_mask": attention_mask,
822
+ }
823
+ )
824
+ return model_inputs
825
+
826
+ @staticmethod
827
+ def _reorder_cache(past_key_values, beam_idx):
828
+ reordered_past = ()
829
+ for layer_past in past_key_values:
830
+ reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
831
+ return reordered_past
832
+
833
+ def build_inputs(self, tokenizer, query: str, history: List[Tuple[str, str]] = []):
834
+ prompt = ""
835
+ for record in history:
836
+ prompt += f"""<s><|User|>:{record[0]}<eoh>\n<|Bot|>:{record[1]}<eoa>\n"""
837
+ if len(prompt) == 0:
838
+ prompt += "<s>"
839
+ prompt += f"""<|User|>:{query}<eoh>\n<|Bot|>:"""
840
+ return tokenizer([prompt], return_tensors="pt")
841
+
842
+ @torch.no_grad()
843
+ def chat(self,
844
+ tokenizer,
845
+ query: str,
846
+ history: List[Tuple[str, str]] = [],
847
+ streamer: Optional[BaseStreamer] = None,
848
+ max_new_tokens: int = 1024,
849
+ do_sample: bool = True,
850
+ temperature: float = 0.8,
851
+ top_p: float = 0.8,
852
+ **kwargs):
853
+ inputs = self.build_inputs(tokenizer, query, history)
854
+ inputs = {k: v.to(self.device) for k, v in inputs.items() if torch.is_tensor(v)}
855
+ outputs = self.generate(**inputs,
856
+ streamer=streamer,
857
+ max_new_tokens=max_new_tokens,
858
+ do_sample=do_sample,
859
+ temperature=temperature,
860
+ top_p=top_p,
861
+ **kwargs)
862
+ outputs = outputs[0].cpu().tolist()[len(inputs["input_ids"][0]):]
863
+ response = tokenizer.decode(outputs, skip_special_tokens=True)
864
+ response = response.split("<eoa>")[0]
865
+ history = history + [(query, response)]
866
+ return response, history
867
+
868
+ @torch.no_grad()
869
+ def stream_chat(self,
870
+ tokenizer,
871
+ query: str,
872
+ history: List[Tuple[str, str]] = [],
873
+ max_new_tokens: int = 1024,
874
+ do_sample: bool = True,
875
+ temperature: float = 0.8,
876
+ top_p: float = 0.8,
877
+ **kwargs):
878
+ """
879
+ Return a generator in format: (response, history)
880
+ Eg.
881
+ ('你好,有什么可以帮助您的吗', [('你好', '你好,有什么可以帮助您的吗')])
882
+ ('你好,有什么可以帮助您的吗?', [('你好', '你好,有什么可以帮助您的吗?')])
883
+ """
884
+
885
+ response_queue = queue.Queue(maxsize=20)
886
+
887
+ class ChatStreamer(BaseStreamer):
888
+ def __init__(self, tokenizer) -> None:
889
+ super().__init__()
890
+ self.tokenizer = tokenizer
891
+ self.queue = response_queue
892
+ self.query = query
893
+ self.history = history
894
+ self.response = ""
895
+ self.received_inputs = False
896
+ self.queue.put((self.response, history + [(self.query, self.response)]))
897
+
898
+ def put(self, value):
899
+ if len(value.shape) > 1 and value.shape[0] > 1:
900
+ raise ValueError("ChatStreamer only supports batch size 1")
901
+ elif len(value.shape) > 1:
902
+ value = value[0]
903
+
904
+ if not self.received_inputs:
905
+ # The first received value is input_ids, ignore here
906
+ self.received_inputs = True
907
+ return
908
+
909
+ token = self.tokenizer.decode([value[-1]], skip_special_tokens=True)
910
+ if token.strip() != "<eoa>":
911
+ self.response = self.response + token
912
+ history = self.history + [(self.query, self.response)]
913
+ self.queue.put((self.response, history))
914
+
915
+ def end(self):
916
+ self.queue.put(None)
917
+
918
+ def stream_producer():
919
+ return self.chat(
920
+ tokenizer=tokenizer,
921
+ query=query,
922
+ streamer=ChatStreamer(tokenizer=tokenizer),
923
+ history=history,
924
+ max_new_tokens=max_new_tokens,
925
+ do_sample=do_sample,
926
+ temperature=temperature,
927
+ top_p=top_p,
928
+ **kwargs
929
+ )
930
+
931
+ def consumer():
932
+ producer = threading.Thread(target=stream_producer)
933
+ producer.start()
934
+ while True:
935
+ res = response_queue.get()
936
+ if res is not None:
937
+ return
938
+ yield res
939
+
940
+ return consumer()
941
+
942
+
943
+ @add_start_docstrings(
944
+ """
945
+ The InternLM Model transformer with a sequence classification head on top (linear layer).
946
+
947
+ [`InternLMForSequenceClassification`] uses the last token in order to do the classification, as other causal models
948
+ (e.g. GPT-2) do.
949
+
950
+ Since it does classification on the last token, it requires to know the position of the last token. If a
951
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
952
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
953
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
954
+ each row of the batch).
955
+ """,
956
+ INTERNLM_START_DOCSTRING,
957
+ )
958
+ class InternLMForSequenceClassification(InternLMPreTrainedModel):
959
+ _keys_to_ignore_on_load_missing = [r"lm_head.weight"]
960
+
961
+ def __init__(self, config):
962
+ super().__init__(config)
963
+ self.num_labels = config.num_labels
964
+ self.model = InternLMModel(config)
965
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
966
+
967
+ # Initialize weights and apply final processing
968
+ self.post_init()
969
+
970
+ def get_input_embeddings(self):
971
+ return self.model.embed_tokens
972
+
973
+ def set_input_embeddings(self, value):
974
+ self.model.embed_tokens = value
975
+
976
+ @add_start_docstrings_to_model_forward(INTERNLM_INPUTS_DOCSTRING)
977
+ def forward(
978
+ self,
979
+ input_ids: torch.LongTensor = None,
980
+ attention_mask: Optional[torch.Tensor] = None,
981
+ position_ids: Optional[torch.LongTensor] = None,
982
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
983
+ inputs_embeds: Optional[torch.FloatTensor] = None,
984
+ labels: Optional[torch.LongTensor] = None,
985
+ use_cache: Optional[bool] = None,
986
+ output_attentions: Optional[bool] = None,
987
+ output_hidden_states: Optional[bool] = None,
988
+ return_dict: Optional[bool] = None,
989
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
990
+ r"""
991
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
992
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
993
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
994
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
995
+ """
996
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
997
+
998
+ transformer_outputs = self.model(
999
+ input_ids,
1000
+ attention_mask=attention_mask,
1001
+ position_ids=position_ids,
1002
+ past_key_values=past_key_values,
1003
+ inputs_embeds=inputs_embeds,
1004
+ use_cache=use_cache,
1005
+ output_attentions=output_attentions,
1006
+ output_hidden_states=output_hidden_states,
1007
+ return_dict=return_dict,
1008
+ )
1009
+ hidden_states = transformer_outputs[0]
1010
+ logits = self.score(hidden_states)
1011
+
1012
+ if input_ids is not None:
1013
+ batch_size = input_ids.shape[0]
1014
+ else:
1015
+ batch_size = inputs_embeds.shape[0]
1016
+
1017
+ if self.config.pad_token_id is None and batch_size != 1:
1018
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1019
+ if self.config.pad_token_id is None:
1020
+ sequence_lengths = -1
1021
+ else:
1022
+ if input_ids is not None:
1023
+ sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device)
1024
+ else:
1025
+ sequence_lengths = -1
1026
+
1027
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1028
+
1029
+ loss = None
1030
+ if labels is not None:
1031
+ labels = labels.to(logits.device)
1032
+ if self.config.problem_type is None:
1033
+ if self.num_labels == 1:
1034
+ self.config.problem_type = "regression"
1035
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1036
+ self.config.problem_type = "single_label_classification"
1037
+ else:
1038
+ self.config.problem_type = "multi_label_classification"
1039
+
1040
+ if self.config.problem_type == "regression":
1041
+ loss_fct = MSELoss()
1042
+ if self.num_labels == 1:
1043
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1044
+ else:
1045
+ loss = loss_fct(pooled_logits, labels)
1046
+ elif self.config.problem_type == "single_label_classification":
1047
+ loss_fct = CrossEntropyLoss()
1048
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1049
+ elif self.config.problem_type == "multi_label_classification":
1050
+ loss_fct = BCEWithLogitsLoss()
1051
+ loss = loss_fct(pooled_logits, labels)
1052
+ if not return_dict:
1053
+ output = (pooled_logits,) + transformer_outputs[1:]
1054
+ return ((loss,) + output) if loss is not None else output
1055
+
1056
+ return SequenceClassifierOutputWithPast(
1057
+ loss=loss,
1058
+ logits=pooled_logits,
1059
+ past_key_values=transformer_outputs.past_key_values,
1060
+ hidden_states=transformer_outputs.hidden_states,
1061
+ attentions=transformer_outputs.attentions,
1062
+ )
Intern_300m/pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:84461a03839dadb8c60f06a37447448a26d334b5383abfbfa59b1fe7963d3bf7
3
+ size 599112083
calvin_fsq.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4b23c0abfa4f24be0478edde89dd7ef82fa3112c16c90da2e12431a3ee4a2d37
3
+ size 2129266013
go_fsq.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d44f340a6065dfd3f00fba7809842579e5858d98cbc72592728314d10ab8e706
3
+ size 2039685796