ZwwWayne
commited on
Commit
•
38ae535
1
Parent(s):
21e46b7
update tokenizers
Browse files- config.json +3 -3
- configuration_internlm.py → configuration_internlm2.py +18 -26
- modeling_internlm2.py +189 -69
- tokenization_internlm.py → tokenization_internlm2.py +6 -10
- tokenization_internlm2_fast.py +214 -0
- tokenizer_config.json +63 -14
config.json
CHANGED
@@ -3,7 +3,7 @@
|
|
3 |
"InternLM2ForCausalLM"
|
4 |
],
|
5 |
"auto_map": {
|
6 |
-
"AutoConfig": "
|
7 |
"AutoModelForCausalLM": "modeling_internlm2.InternLM2ForCausalLM",
|
8 |
"AutoModel": "modeling_internlm2.InternLM2ForCausalLM"
|
9 |
},
|
@@ -15,14 +15,14 @@
|
|
15 |
"initializer_range": 0.02,
|
16 |
"intermediate_size": 8192,
|
17 |
"max_position_embeddings": 32768,
|
18 |
-
"model_type": "
|
19 |
"num_attention_heads": 16,
|
20 |
"num_hidden_layers": 24,
|
21 |
"num_key_value_heads": 8,
|
22 |
"pad_token_id": 2,
|
23 |
"rms_norm_eps": 1e-05,
|
24 |
"rope_scaling": {
|
25 |
-
"factor":
|
26 |
"type": "dynamic"
|
27 |
},
|
28 |
"rope_theta": 1000000,
|
|
|
3 |
"InternLM2ForCausalLM"
|
4 |
],
|
5 |
"auto_map": {
|
6 |
+
"AutoConfig": "configuration_internlm2.InternLM2Config",
|
7 |
"AutoModelForCausalLM": "modeling_internlm2.InternLM2ForCausalLM",
|
8 |
"AutoModel": "modeling_internlm2.InternLM2ForCausalLM"
|
9 |
},
|
|
|
15 |
"initializer_range": 0.02,
|
16 |
"intermediate_size": 8192,
|
17 |
"max_position_embeddings": 32768,
|
18 |
+
"model_type": "internlm2",
|
19 |
"num_attention_heads": 16,
|
20 |
"num_hidden_layers": 24,
|
21 |
"num_key_value_heads": 8,
|
22 |
"pad_token_id": 2,
|
23 |
"rms_norm_eps": 1e-05,
|
24 |
"rope_scaling": {
|
25 |
+
"factor": 2.0,
|
26 |
"type": "dynamic"
|
27 |
},
|
28 |
"rope_theta": 1000000,
|
configuration_internlm.py → configuration_internlm2.py
RENAMED
@@ -1,10 +1,7 @@
|
|
1 |
# coding=utf-8
|
2 |
-
# Copyright (c) InternLM. All rights reserved.
|
3 |
#
|
4 |
-
# This code is based on
|
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.
|
@@ -17,21 +14,22 @@
|
|
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 |
-
"""
|
21 |
|
22 |
from transformers.configuration_utils import PretrainedConfig
|
23 |
from transformers.utils import logging
|
24 |
|
25 |
logger = logging.get_logger(__name__)
|
26 |
|
27 |
-
|
28 |
|
29 |
|
30 |
-
|
|
|
31 |
r"""
|
32 |
-
This is the configuration class to store the configuration of a [`
|
33 |
-
an
|
34 |
-
configuration with the defaults will yield a similar configuration to that of the
|
35 |
|
36 |
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
37 |
documentation from [`PretrainedConfig`] for more information.
|
@@ -39,8 +37,8 @@ class InternLMConfig(PretrainedConfig):
|
|
39 |
|
40 |
Args:
|
41 |
vocab_size (`int`, *optional*, defaults to 32000):
|
42 |
-
Vocabulary size of the
|
43 |
-
`inputs_ids` passed when calling [`
|
44 |
hidden_size (`int`, *optional*, defaults to 4096):
|
45 |
Dimension of the hidden representations.
|
46 |
intermediate_size (`int`, *optional*, defaults to 11008):
|
@@ -73,19 +71,8 @@ class InternLMConfig(PretrainedConfig):
|
|
73 |
Whether to tie weight embeddings
|
74 |
Example:
|
75 |
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
>>> # Initializing a InternLM internlm-7b style configuration
|
80 |
-
>>> configuration = InternLMConfig()
|
81 |
-
|
82 |
-
>>> # Initializing a model from the internlm-7b style configuration
|
83 |
-
>>> model = InternLMModel(configuration)
|
84 |
-
|
85 |
-
>>> # Accessing the model configuration
|
86 |
-
>>> configuration = model.config
|
87 |
-
```"""
|
88 |
-
model_type = "internlm"
|
89 |
_auto_class = "AutoConfig"
|
90 |
|
91 |
def __init__( # pylint: disable=W0102
|
@@ -108,6 +95,7 @@ class InternLMConfig(PretrainedConfig):
|
|
108 |
bias=True,
|
109 |
rope_theta=10000,
|
110 |
rope_scaling=None,
|
|
|
111 |
**kwargs,
|
112 |
):
|
113 |
self.vocab_size = vocab_size
|
@@ -129,6 +117,10 @@ class InternLMConfig(PretrainedConfig):
|
|
129 |
self.rope_theta = rope_theta
|
130 |
self.rope_scaling = rope_scaling
|
131 |
self._rope_scaling_validation()
|
|
|
|
|
|
|
|
|
132 |
super().__init__(
|
133 |
pad_token_id=pad_token_id,
|
134 |
bos_token_id=bos_token_id,
|
|
|
1 |
# coding=utf-8
|
2 |
+
# Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
|
3 |
#
|
4 |
+
# This code is based on transformers/src/transformers/models/llama/configuration_llama.py
|
|
|
|
|
|
|
5 |
#
|
6 |
# Licensed under the Apache License, Version 2.0 (the "License");
|
7 |
# you may not use this file except in compliance with the License.
|
|
|
14 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
15 |
# See the License for the specific language governing permissions and
|
16 |
# limitations under the License.
|
17 |
+
""" InternLM2 model configuration"""
|
18 |
|
19 |
from transformers.configuration_utils import PretrainedConfig
|
20 |
from transformers.utils import logging
|
21 |
|
22 |
logger = logging.get_logger(__name__)
|
23 |
|
24 |
+
INTERNLM2_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
|
25 |
|
26 |
|
27 |
+
# Modified from transformers.model.llama.configuration_llama.LlamaConfig
|
28 |
+
class InternLM2Config(PretrainedConfig):
|
29 |
r"""
|
30 |
+
This is the configuration class to store the configuration of a [`InternLM2Model`]. It is used to instantiate
|
31 |
+
an InternLM2 model according to the specified arguments, defining the model architecture. Instantiating a
|
32 |
+
configuration with the defaults will yield a similar configuration to that of the InternLM2-7B.
|
33 |
|
34 |
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
35 |
documentation from [`PretrainedConfig`] for more information.
|
|
|
37 |
|
38 |
Args:
|
39 |
vocab_size (`int`, *optional*, defaults to 32000):
|
40 |
+
Vocabulary size of the InternLM2 model. Defines the number of different tokens that can be represented by the
|
41 |
+
`inputs_ids` passed when calling [`InternLM2Model`]
|
42 |
hidden_size (`int`, *optional*, defaults to 4096):
|
43 |
Dimension of the hidden representations.
|
44 |
intermediate_size (`int`, *optional*, defaults to 11008):
|
|
|
71 |
Whether to tie weight embeddings
|
72 |
Example:
|
73 |
|
74 |
+
"""
|
75 |
+
model_type = "internlm2"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
76 |
_auto_class = "AutoConfig"
|
77 |
|
78 |
def __init__( # pylint: disable=W0102
|
|
|
95 |
bias=True,
|
96 |
rope_theta=10000,
|
97 |
rope_scaling=None,
|
98 |
+
attn_implementation="eager",
|
99 |
**kwargs,
|
100 |
):
|
101 |
self.vocab_size = vocab_size
|
|
|
117 |
self.rope_theta = rope_theta
|
118 |
self.rope_scaling = rope_scaling
|
119 |
self._rope_scaling_validation()
|
120 |
+
|
121 |
+
self.attn_implementation = attn_implementation
|
122 |
+
if self.attn_implementation is None:
|
123 |
+
self.attn_implementation = "eager"
|
124 |
super().__init__(
|
125 |
pad_token_id=pad_token_id,
|
126 |
bos_token_id=bos_token_id,
|
modeling_internlm2.py
CHANGED
@@ -1,10 +1,6 @@
|
|
1 |
-
#
|
2 |
-
# # Copyright (c) InternLM. All rights reserved.
|
3 |
#
|
4 |
-
# This code is based on
|
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.
|
@@ -25,6 +21,7 @@ import warnings
|
|
25 |
from typing import List, Optional, Tuple, Union
|
26 |
|
27 |
import torch
|
|
|
28 |
import torch.utils.checkpoint
|
29 |
from einops import rearrange
|
30 |
from torch import nn
|
@@ -48,12 +45,37 @@ try:
|
|
48 |
except: # noqa # pylint: disable=bare-except
|
49 |
BaseStreamer = None
|
50 |
|
51 |
-
from .
|
52 |
|
53 |
logger = logging.get_logger(__name__)
|
54 |
|
55 |
_CONFIG_FOR_DOC = "InternLM2Config"
|
56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
57 |
|
58 |
# Copied from transformers.models.bart.modeling_bart._make_causal_mask
|
59 |
def _make_causal_mask(
|
@@ -88,6 +110,7 @@ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int]
|
|
88 |
return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
|
89 |
|
90 |
|
|
|
91 |
class InternLM2RMSNorm(nn.Module):
|
92 |
def __init__(self, hidden_size, eps=1e-6):
|
93 |
"""
|
@@ -105,6 +128,7 @@ class InternLM2RMSNorm(nn.Module):
|
|
105 |
return self.weight * hidden_states.to(input_dtype)
|
106 |
|
107 |
|
|
|
108 |
class InternLM2RotaryEmbedding(nn.Module):
|
109 |
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
110 |
super().__init__()
|
@@ -141,6 +165,7 @@ class InternLM2RotaryEmbedding(nn.Module):
|
|
141 |
)
|
142 |
|
143 |
|
|
|
144 |
class InternLM2LinearScalingRotaryEmbedding(InternLM2RotaryEmbedding):
|
145 |
"""InternLM2RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
|
146 |
|
@@ -160,6 +185,7 @@ class InternLM2LinearScalingRotaryEmbedding(InternLM2RotaryEmbedding):
|
|
160 |
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
161 |
|
162 |
|
|
|
163 |
class InternLM2DynamicNTKScalingRotaryEmbedding(InternLM2RotaryEmbedding):
|
164 |
"""InternLM2RotaryEmbedding extended with Dynamic NTK scaling.
|
165 |
Credits to the Reddit users /u/bloc97 and /u/emozilla.
|
@@ -188,6 +214,7 @@ class InternLM2DynamicNTKScalingRotaryEmbedding(InternLM2RotaryEmbedding):
|
|
188 |
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
189 |
|
190 |
|
|
|
191 |
def rotate_half(x):
|
192 |
"""Rotates half the hidden dims of the input."""
|
193 |
x1 = x[..., : x.shape[-1] // 2]
|
@@ -195,12 +222,13 @@ def rotate_half(x):
|
|
195 |
return torch.cat((-x2, x1), dim=-1)
|
196 |
|
197 |
|
198 |
-
|
199 |
-
|
200 |
-
|
|
|
|
|
201 |
q_embed = (q * cos) + (rotate_half(q) * sin)
|
202 |
k_embed = (k * cos) + (rotate_half(k) * sin)
|
203 |
-
|
204 |
return q_embed, k_embed
|
205 |
|
206 |
|
@@ -221,6 +249,7 @@ class InternLM2MLP(nn.Module):
|
|
221 |
return down_proj
|
222 |
|
223 |
|
|
|
224 |
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
225 |
"""
|
226 |
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
@@ -233,6 +262,7 @@ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
|
233 |
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
234 |
|
235 |
|
|
|
236 |
class InternLM2Attention(nn.Module):
|
237 |
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
238 |
|
@@ -277,14 +307,14 @@ class InternLM2Attention(nn.Module):
|
|
277 |
self.head_dim,
|
278 |
max_position_embeddings=self.max_position_embeddings,
|
279 |
base=self.config.rope_theta,
|
280 |
-
scaling_factor=scaling_factor
|
281 |
)
|
282 |
elif scaling_type == "linear":
|
283 |
self.rotary_emb = InternLM2LinearScalingRotaryEmbedding(
|
284 |
self.head_dim,
|
285 |
max_position_embeddings=self.max_position_embeddings,
|
286 |
base=self.config.rope_theta,
|
287 |
-
scaling_factor=scaling_factor
|
288 |
)
|
289 |
else:
|
290 |
raise ValueError("Currently we only support rotary embedding's type being 'dynamic' or 'linear'.")
|
@@ -381,6 +411,7 @@ class InternLM2Attention(nn.Module):
|
|
381 |
return attn_output, attn_weights, past_key_value
|
382 |
|
383 |
|
|
|
384 |
class InternLM2FlashAttention2(InternLM2Attention):
|
385 |
"""
|
386 |
InternLM2 flash attention module. This module inherits from `InternLM2Attention` as the weights of the module stays
|
@@ -417,9 +448,8 @@ class InternLM2FlashAttention2(InternLM2Attention):
|
|
417 |
qkv_states = rearrange(
|
418 |
qkv_states,
|
419 |
"b q (h gs d) -> b q h gs d",
|
420 |
-
gs=
|
421 |
d=self.head_dim,
|
422 |
-
q=q_len,
|
423 |
)
|
424 |
|
425 |
query_states = qkv_states[..., : self.num_key_value_groups, :]
|
@@ -427,6 +457,10 @@ class InternLM2FlashAttention2(InternLM2Attention):
|
|
427 |
key_states = qkv_states[..., -2, :]
|
428 |
value_states = qkv_states[..., -1, :]
|
429 |
|
|
|
|
|
|
|
|
|
430 |
kv_seq_len = key_states.shape[-2]
|
431 |
if past_key_value is not None:
|
432 |
kv_seq_len += past_key_value[0].shape[-2]
|
@@ -446,36 +480,9 @@ class InternLM2FlashAttention2(InternLM2Attention):
|
|
446 |
key_states = key_states.transpose(1, 2)
|
447 |
value_states = value_states.transpose(1, 2)
|
448 |
|
449 |
-
dropout_rate = 0.0 if not self.training else self.attention_dropout
|
450 |
-
|
451 |
-
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
452 |
-
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
453 |
-
# cast them back in the correct dtype just to be sure everything works as expected.
|
454 |
-
# This might slowdown training & inference so it is recommended to not cast the LayerNorms
|
455 |
-
# in fp32. (InternLM2RMSNorm handles it correctly)
|
456 |
-
|
457 |
-
input_dtype = query_states.dtype
|
458 |
-
if input_dtype == torch.float32:
|
459 |
-
# Handle the case where the model is quantized
|
460 |
-
if hasattr(self.config, "_pre_quantization_dtype"):
|
461 |
-
target_dtype = self.config._pre_quantization_dtype
|
462 |
-
else:
|
463 |
-
target_dtype = self.q_proj.weight.dtype
|
464 |
-
|
465 |
-
logger.warning_once(
|
466 |
-
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
467 |
-
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back "
|
468 |
-
f"the input in {target_dtype}."
|
469 |
-
)
|
470 |
-
|
471 |
-
query_states = query_states.to(target_dtype)
|
472 |
-
key_states = key_states.to(target_dtype)
|
473 |
-
value_states = value_states.to(target_dtype)
|
474 |
-
|
475 |
attn_output = self._flash_attention_forward(
|
476 |
-
query_states, key_states, value_states, attention_mask, q_len
|
477 |
)
|
478 |
-
|
479 |
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
|
480 |
attn_output = self.wo(attn_output)
|
481 |
|
@@ -484,16 +491,112 @@ class InternLM2FlashAttention2(InternLM2Attention):
|
|
484 |
|
485 |
return attn_output, attn_weights, past_key_value
|
486 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
487 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
488 |
class InternLM2DecoderLayer(nn.Module):
|
489 |
def __init__(self, config: InternLM2Config):
|
490 |
super().__init__()
|
491 |
self.hidden_size = config.hidden_size
|
492 |
-
|
493 |
-
|
494 |
-
|
495 |
-
else InternLM2FlashAttention2(config=config)
|
496 |
-
)
|
497 |
self.feed_forward = InternLM2MLP(config)
|
498 |
self.attention_norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
499 |
self.ffn_norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
@@ -578,6 +681,7 @@ InternLM2_START_DOCSTRING = r"""
|
|
578 |
"""
|
579 |
|
580 |
|
|
|
581 |
@add_start_docstrings(
|
582 |
"The bare InternLM2 Model outputting raw hidden-states without any specific head on top.",
|
583 |
InternLM2_START_DOCSTRING,
|
@@ -588,7 +692,6 @@ class InternLM2PreTrainedModel(PreTrainedModel):
|
|
588 |
supports_gradient_checkpointing = True
|
589 |
_no_split_modules = ["InternLM2DecoderLayer"]
|
590 |
_skip_keys_device_placement = "past_key_values"
|
591 |
-
_supports_flash_attn_2 = True
|
592 |
|
593 |
def _init_weights(self, module):
|
594 |
std = self.config.initializer_range
|
@@ -667,6 +770,7 @@ InternLM2_INPUTS_DOCSTRING = r"""
|
|
667 |
"""
|
668 |
|
669 |
|
|
|
670 |
@add_start_docstrings(
|
671 |
"The bare InternLM2 Model outputting raw hidden-states without any specific head on top.",
|
672 |
InternLM2_START_DOCSTRING,
|
@@ -685,8 +789,10 @@ class InternLM2Model(InternLM2PreTrainedModel):
|
|
685 |
super().__init__(config)
|
686 |
self.padding_idx = config.pad_token_id
|
687 |
self.vocab_size = config.vocab_size
|
|
|
688 |
|
689 |
self.tok_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
|
|
690 |
self.layers = nn.ModuleList([InternLM2DecoderLayer(config) for _ in range(config.num_hidden_layers)])
|
691 |
self.norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
692 |
|
@@ -700,7 +806,6 @@ class InternLM2Model(InternLM2PreTrainedModel):
|
|
700 |
def set_input_embeddings(self, value):
|
701 |
self.tok_embeddings = value
|
702 |
|
703 |
-
# Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
|
704 |
def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
|
705 |
# create causal mask
|
706 |
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
@@ -745,6 +850,9 @@ class InternLM2Model(InternLM2PreTrainedModel):
|
|
745 |
|
746 |
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
747 |
|
|
|
|
|
|
|
748 |
# retrieve input_ids and inputs_embeds
|
749 |
if input_ids is not None and inputs_embeds is not None:
|
750 |
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
@@ -770,14 +878,18 @@ class InternLM2Model(InternLM2PreTrainedModel):
|
|
770 |
|
771 |
if inputs_embeds is None:
|
772 |
inputs_embeds = self.tok_embeddings(input_ids)
|
773 |
-
|
774 |
-
if
|
775 |
-
|
776 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
777 |
)
|
778 |
-
attention_mask = self._prepare_decoder_attention_mask(
|
779 |
-
attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
|
780 |
-
)
|
781 |
|
782 |
# embed positions
|
783 |
hidden_states = inputs_embeds
|
@@ -851,6 +963,7 @@ class InternLM2Model(InternLM2PreTrainedModel):
|
|
851 |
)
|
852 |
|
853 |
|
|
|
854 |
class InternLM2ForCausalLM(InternLM2PreTrainedModel):
|
855 |
_auto_class = "AutoModelForCausalLM"
|
856 |
|
@@ -1021,14 +1134,15 @@ class InternLM2ForCausalLM(InternLM2PreTrainedModel):
|
|
1021 |
return reordered_past
|
1022 |
|
1023 |
def build_inputs(self, tokenizer, query: str, history: List[Tuple[str, str]] = [], meta_instruction=""):
|
1024 |
-
|
1025 |
-
|
1026 |
-
prompt += f"""<s>[UNUSED_TOKEN_146]system\n{meta_instruction}[UNUSED_TOKEN_145]\n"""
|
1027 |
else:
|
1028 |
-
prompt
|
|
|
|
|
1029 |
for record in history:
|
1030 |
-
prompt += f"""
|
1031 |
-
prompt += f"""
|
1032 |
return tokenizer([prompt], return_tensors="pt")
|
1033 |
|
1034 |
@torch.no_grad()
|
@@ -1043,14 +1157,14 @@ class InternLM2ForCausalLM(InternLM2PreTrainedModel):
|
|
1043 |
temperature: float = 0.8,
|
1044 |
top_p: float = 0.8,
|
1045 |
meta_instruction: str = "You are an AI assistant whose name is InternLM (书生·浦语).\n"
|
1046 |
-
"- InternLM (书生·浦语) is a conversational language model that is developed by Shanghai AI Laboratory (上海人工智能实验室). It is designed to be helpful, honest, and harmless.\n"
|
1047 |
-
"- InternLM (书生·浦语) can understand and communicate fluently in the language chosen by the user such as English and 中文.",
|
1048 |
**kwargs,
|
1049 |
):
|
1050 |
inputs = self.build_inputs(tokenizer, query, history, meta_instruction)
|
1051 |
inputs = {k: v.to(self.device) for k, v in inputs.items() if torch.is_tensor(v)}
|
1052 |
# also add end-of-assistant token in eos token id to avoid unnecessary generation
|
1053 |
-
eos_token_id = [tokenizer.eos_token_id, tokenizer.convert_tokens_to_ids(["
|
1054 |
outputs = self.generate(
|
1055 |
**inputs,
|
1056 |
streamer=streamer,
|
@@ -1063,7 +1177,7 @@ class InternLM2ForCausalLM(InternLM2PreTrainedModel):
|
|
1063 |
)
|
1064 |
outputs = outputs[0].cpu().tolist()[len(inputs["input_ids"][0]) :]
|
1065 |
response = tokenizer.decode(outputs, skip_special_tokens=True)
|
1066 |
-
response = response.split("
|
1067 |
history = history + [(query, response)]
|
1068 |
return response, history
|
1069 |
|
@@ -1101,6 +1215,7 @@ class InternLM2ForCausalLM(InternLM2PreTrainedModel):
|
|
1101 |
self.query = query
|
1102 |
self.history = history
|
1103 |
self.response = ""
|
|
|
1104 |
self.received_inputs = False
|
1105 |
self.queue.put((self.response, history + [(self.query, self.response)]))
|
1106 |
|
@@ -1115,11 +1230,15 @@ class InternLM2ForCausalLM(InternLM2PreTrainedModel):
|
|
1115 |
self.received_inputs = True
|
1116 |
return
|
1117 |
|
1118 |
-
|
1119 |
-
|
|
|
1120 |
self.response = self.response + token
|
1121 |
history = self.history + [(self.query, self.response)]
|
1122 |
self.queue.put((self.response, history))
|
|
|
|
|
|
|
1123 |
|
1124 |
def end(self):
|
1125 |
self.queue.put(None)
|
@@ -1149,6 +1268,7 @@ class InternLM2ForCausalLM(InternLM2PreTrainedModel):
|
|
1149 |
return consumer()
|
1150 |
|
1151 |
|
|
|
1152 |
@add_start_docstrings(
|
1153 |
"""
|
1154 |
The InternLM2 Model transformer with a sequence classification head on top (linear layer).
|
|
|
1 |
+
# Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
|
|
|
2 |
#
|
3 |
+
# This code is based on transformers/src/transformers/models/llama/modeling_llama.py
|
|
|
|
|
|
|
4 |
#
|
5 |
# Licensed under the Apache License, Version 2.0 (the "License");
|
6 |
# you may not use this file except in compliance with the License.
|
|
|
21 |
from typing import List, Optional, Tuple, Union
|
22 |
|
23 |
import torch
|
24 |
+
import torch.nn.functional as F
|
25 |
import torch.utils.checkpoint
|
26 |
from einops import rearrange
|
27 |
from torch import nn
|
|
|
45 |
except: # noqa # pylint: disable=bare-except
|
46 |
BaseStreamer = None
|
47 |
|
48 |
+
from .configuration_internlm2 import InternLM2Config
|
49 |
|
50 |
logger = logging.get_logger(__name__)
|
51 |
|
52 |
_CONFIG_FOR_DOC = "InternLM2Config"
|
53 |
|
54 |
+
flash_attn_func, flash_attn_varlen_func = None, None
|
55 |
+
pad_input, index_first_axis, unpad_input = None, None, None
|
56 |
+
def _import_flash_attn():
|
57 |
+
global flash_attn_func, flash_attn_varlen_func
|
58 |
+
global pad_input, index_first_axis, unpad_input
|
59 |
+
try:
|
60 |
+
from flash_attn import flash_attn_func as _flash_attn_func, flash_attn_varlen_func as _flash_attn_varlen_func
|
61 |
+
from flash_attn.bert_padding import pad_input as _pad_input, index_first_axis as _index_first_axis, unpad_input as _unpad_input
|
62 |
+
flash_attn_func, flash_attn_varlen_func = _flash_attn_func, _flash_attn_varlen_func
|
63 |
+
pad_input, index_first_axis, unpad_input = _pad_input, _index_first_axis, _unpad_input
|
64 |
+
except ImportError:
|
65 |
+
raise ImportError("flash_attn is not installed.")
|
66 |
+
|
67 |
+
# Copied from transformers.models.llama.modeling_llama._get_unpad_data
|
68 |
+
def _get_unpad_data(attention_mask):
|
69 |
+
seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
|
70 |
+
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
|
71 |
+
max_seqlen_in_batch = seqlens_in_batch.max().item()
|
72 |
+
cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
|
73 |
+
return (
|
74 |
+
indices,
|
75 |
+
cu_seqlens,
|
76 |
+
max_seqlen_in_batch,
|
77 |
+
)
|
78 |
+
|
79 |
|
80 |
# Copied from transformers.models.bart.modeling_bart._make_causal_mask
|
81 |
def _make_causal_mask(
|
|
|
110 |
return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
|
111 |
|
112 |
|
113 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->InternLM2
|
114 |
class InternLM2RMSNorm(nn.Module):
|
115 |
def __init__(self, hidden_size, eps=1e-6):
|
116 |
"""
|
|
|
128 |
return self.weight * hidden_states.to(input_dtype)
|
129 |
|
130 |
|
131 |
+
# Copied from transformers.model.llama.modeling_llama.LlamaRotaryEmbedding with Llama->InternLM2
|
132 |
class InternLM2RotaryEmbedding(nn.Module):
|
133 |
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
134 |
super().__init__()
|
|
|
165 |
)
|
166 |
|
167 |
|
168 |
+
# Copied from transformers.model.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->InternLM2
|
169 |
class InternLM2LinearScalingRotaryEmbedding(InternLM2RotaryEmbedding):
|
170 |
"""InternLM2RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
|
171 |
|
|
|
185 |
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
186 |
|
187 |
|
188 |
+
# Copied from transformers.model.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->InternLM2
|
189 |
class InternLM2DynamicNTKScalingRotaryEmbedding(InternLM2RotaryEmbedding):
|
190 |
"""InternLM2RotaryEmbedding extended with Dynamic NTK scaling.
|
191 |
Credits to the Reddit users /u/bloc97 and /u/emozilla.
|
|
|
214 |
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
215 |
|
216 |
|
217 |
+
# Copied from transformers.model.llama.modeling_llama.rotate_half
|
218 |
def rotate_half(x):
|
219 |
"""Rotates half the hidden dims of the input."""
|
220 |
x1 = x[..., : x.shape[-1] // 2]
|
|
|
222 |
return torch.cat((-x2, x1), dim=-1)
|
223 |
|
224 |
|
225 |
+
# Copied from transformers.model.llama.modeling_llama.apply_rotary_pos_emb
|
226 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
|
227 |
+
"""Applies Rotary Position Embedding to the query and key tensors."""
|
228 |
+
cos = cos[position_ids].unsqueeze(unsqueeze_dim)
|
229 |
+
sin = sin[position_ids].unsqueeze(unsqueeze_dim)
|
230 |
q_embed = (q * cos) + (rotate_half(q) * sin)
|
231 |
k_embed = (k * cos) + (rotate_half(k) * sin)
|
|
|
232 |
return q_embed, k_embed
|
233 |
|
234 |
|
|
|
249 |
return down_proj
|
250 |
|
251 |
|
252 |
+
# Copied from transformers.model.llama.modeling_llama.repeat_kv
|
253 |
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
254 |
"""
|
255 |
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
|
|
262 |
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
263 |
|
264 |
|
265 |
+
# Modified from transformers.model.llama.modeling_llama.LlamaAttention
|
266 |
class InternLM2Attention(nn.Module):
|
267 |
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
268 |
|
|
|
307 |
self.head_dim,
|
308 |
max_position_embeddings=self.max_position_embeddings,
|
309 |
base=self.config.rope_theta,
|
310 |
+
scaling_factor=scaling_factor,
|
311 |
)
|
312 |
elif scaling_type == "linear":
|
313 |
self.rotary_emb = InternLM2LinearScalingRotaryEmbedding(
|
314 |
self.head_dim,
|
315 |
max_position_embeddings=self.max_position_embeddings,
|
316 |
base=self.config.rope_theta,
|
317 |
+
scaling_factor=scaling_factor,
|
318 |
)
|
319 |
else:
|
320 |
raise ValueError("Currently we only support rotary embedding's type being 'dynamic' or 'linear'.")
|
|
|
411 |
return attn_output, attn_weights, past_key_value
|
412 |
|
413 |
|
414 |
+
# Modified from transformers.model.llama.modeling_llama.InternLM2FlashAttention2
|
415 |
class InternLM2FlashAttention2(InternLM2Attention):
|
416 |
"""
|
417 |
InternLM2 flash attention module. This module inherits from `InternLM2Attention` as the weights of the module stays
|
|
|
448 |
qkv_states = rearrange(
|
449 |
qkv_states,
|
450 |
"b q (h gs d) -> b q h gs d",
|
451 |
+
gs=2 + self.num_key_value_groups,
|
452 |
d=self.head_dim,
|
|
|
453 |
)
|
454 |
|
455 |
query_states = qkv_states[..., : self.num_key_value_groups, :]
|
|
|
457 |
key_states = qkv_states[..., -2, :]
|
458 |
value_states = qkv_states[..., -1, :]
|
459 |
|
460 |
+
query_states = query_states.transpose(1, 2)
|
461 |
+
key_states = key_states.transpose(1, 2)
|
462 |
+
value_states = value_states.transpose(1, 2)
|
463 |
+
|
464 |
kv_seq_len = key_states.shape[-2]
|
465 |
if past_key_value is not None:
|
466 |
kv_seq_len += past_key_value[0].shape[-2]
|
|
|
480 |
key_states = key_states.transpose(1, 2)
|
481 |
value_states = value_states.transpose(1, 2)
|
482 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
483 |
attn_output = self._flash_attention_forward(
|
484 |
+
query_states, key_states, value_states, attention_mask, q_len
|
485 |
)
|
|
|
486 |
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
|
487 |
attn_output = self.wo(attn_output)
|
488 |
|
|
|
491 |
|
492 |
return attn_output, attn_weights, past_key_value
|
493 |
|
494 |
+
def _flash_attention_forward(
|
495 |
+
self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
|
496 |
+
):
|
497 |
+
"""
|
498 |
+
Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
|
499 |
+
first unpad the input, then computes the attention scores and pad the final attention scores.
|
500 |
+
|
501 |
+
Args:
|
502 |
+
query_states (`torch.Tensor`):
|
503 |
+
Input query states to be passed to Flash Attention API
|
504 |
+
key_states (`torch.Tensor`):
|
505 |
+
Input key states to be passed to Flash Attention API
|
506 |
+
value_states (`torch.Tensor`):
|
507 |
+
Input value states to be passed to Flash Attention API
|
508 |
+
attention_mask (`torch.Tensor`):
|
509 |
+
The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
|
510 |
+
position of padding tokens and 1 for the position of non-padding tokens.
|
511 |
+
dropout (`int`, *optional*):
|
512 |
+
Attention dropout
|
513 |
+
softmax_scale (`float`, *optional*):
|
514 |
+
The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
|
515 |
+
"""
|
516 |
+
# Contains at least one padding token in the sequence
|
517 |
+
causal = self.is_causal and query_length != 1
|
518 |
+
if attention_mask is not None:
|
519 |
+
batch_size = query_states.shape[0]
|
520 |
+
query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._unpad_input(
|
521 |
+
query_states, key_states, value_states, attention_mask, query_length
|
522 |
+
)
|
523 |
+
|
524 |
+
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
525 |
+
max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
526 |
+
|
527 |
+
attn_output_unpad = flash_attn_varlen_func(
|
528 |
+
query_states,
|
529 |
+
key_states,
|
530 |
+
value_states,
|
531 |
+
cu_seqlens_q=cu_seqlens_q,
|
532 |
+
cu_seqlens_k=cu_seqlens_k,
|
533 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
534 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
535 |
+
dropout_p=dropout,
|
536 |
+
softmax_scale=softmax_scale,
|
537 |
+
causal=causal,
|
538 |
+
)
|
539 |
+
|
540 |
+
attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
|
541 |
+
else:
|
542 |
+
attn_output = flash_attn_func(
|
543 |
+
query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
|
544 |
+
)
|
545 |
|
546 |
+
return attn_output
|
547 |
+
|
548 |
+
def _unpad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
|
549 |
+
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
|
550 |
+
batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
|
551 |
+
|
552 |
+
key_layer = index_first_axis(
|
553 |
+
key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
554 |
+
)
|
555 |
+
value_layer = index_first_axis(
|
556 |
+
value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
557 |
+
)
|
558 |
+
|
559 |
+
if query_length == kv_seq_len:
|
560 |
+
query_layer = index_first_axis(
|
561 |
+
query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
|
562 |
+
)
|
563 |
+
cu_seqlens_q = cu_seqlens_k
|
564 |
+
max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
565 |
+
indices_q = indices_k
|
566 |
+
elif query_length == 1:
|
567 |
+
max_seqlen_in_batch_q = 1
|
568 |
+
cu_seqlens_q = torch.arange(
|
569 |
+
batch_size + 1, dtype=torch.int32, device=query_layer.device
|
570 |
+
) # There is a memcpy here, that is very bad.
|
571 |
+
indices_q = cu_seqlens_q[:-1]
|
572 |
+
query_layer = query_layer.squeeze(1)
|
573 |
+
else:
|
574 |
+
# The -q_len: slice assumes left padding.
|
575 |
+
attention_mask = attention_mask[:, -query_length:]
|
576 |
+
query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
|
577 |
+
|
578 |
+
return (
|
579 |
+
query_layer,
|
580 |
+
key_layer,
|
581 |
+
value_layer,
|
582 |
+
indices_q.to(torch.int64),
|
583 |
+
(cu_seqlens_q, cu_seqlens_k),
|
584 |
+
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
585 |
+
)
|
586 |
+
|
587 |
+
INTERNLM2_ATTENTION_CLASSES = {
|
588 |
+
"eager": InternLM2Attention,
|
589 |
+
"flash_attention_2": InternLM2FlashAttention2,
|
590 |
+
}
|
591 |
+
|
592 |
+
# Modified from transformers.model.llama.modeling_llama.LlamaDecoderLayer
|
593 |
class InternLM2DecoderLayer(nn.Module):
|
594 |
def __init__(self, config: InternLM2Config):
|
595 |
super().__init__()
|
596 |
self.hidden_size = config.hidden_size
|
597 |
+
|
598 |
+
self.attention = INTERNLM2_ATTENTION_CLASSES[config.attn_implementation](config=config)
|
599 |
+
|
|
|
|
|
600 |
self.feed_forward = InternLM2MLP(config)
|
601 |
self.attention_norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
602 |
self.ffn_norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
|
|
681 |
"""
|
682 |
|
683 |
|
684 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaPreTrainedModel with Llama->InternLM2
|
685 |
@add_start_docstrings(
|
686 |
"The bare InternLM2 Model outputting raw hidden-states without any specific head on top.",
|
687 |
InternLM2_START_DOCSTRING,
|
|
|
692 |
supports_gradient_checkpointing = True
|
693 |
_no_split_modules = ["InternLM2DecoderLayer"]
|
694 |
_skip_keys_device_placement = "past_key_values"
|
|
|
695 |
|
696 |
def _init_weights(self, module):
|
697 |
std = self.config.initializer_range
|
|
|
770 |
"""
|
771 |
|
772 |
|
773 |
+
# Modified from transformers.model.llama.modeling_llama.LlamaModel
|
774 |
@add_start_docstrings(
|
775 |
"The bare InternLM2 Model outputting raw hidden-states without any specific head on top.",
|
776 |
InternLM2_START_DOCSTRING,
|
|
|
789 |
super().__init__(config)
|
790 |
self.padding_idx = config.pad_token_id
|
791 |
self.vocab_size = config.vocab_size
|
792 |
+
self.config = config
|
793 |
|
794 |
self.tok_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
795 |
+
|
796 |
self.layers = nn.ModuleList([InternLM2DecoderLayer(config) for _ in range(config.num_hidden_layers)])
|
797 |
self.norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
798 |
|
|
|
806 |
def set_input_embeddings(self, value):
|
807 |
self.tok_embeddings = value
|
808 |
|
|
|
809 |
def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
|
810 |
# create causal mask
|
811 |
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
|
|
850 |
|
851 |
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
852 |
|
853 |
+
if self.config.attn_implementation == "flash_attention_2":
|
854 |
+
_import_flash_attn()
|
855 |
+
|
856 |
# retrieve input_ids and inputs_embeds
|
857 |
if input_ids is not None and inputs_embeds is not None:
|
858 |
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
|
|
878 |
|
879 |
if inputs_embeds is None:
|
880 |
inputs_embeds = self.tok_embeddings(input_ids)
|
881 |
+
|
882 |
+
if self.config.attn_implementation == "flash_attention_2":
|
883 |
+
# 2d mask is passed through the layers
|
884 |
+
attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
|
885 |
+
else:
|
886 |
+
if attention_mask is None:
|
887 |
+
attention_mask = torch.ones(
|
888 |
+
(batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
|
889 |
+
)
|
890 |
+
attention_mask = self._prepare_decoder_attention_mask(
|
891 |
+
attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
|
892 |
)
|
|
|
|
|
|
|
893 |
|
894 |
# embed positions
|
895 |
hidden_states = inputs_embeds
|
|
|
963 |
)
|
964 |
|
965 |
|
966 |
+
# Modified from transformers.model.llama.modeling_llama.LlamaForCausalLM
|
967 |
class InternLM2ForCausalLM(InternLM2PreTrainedModel):
|
968 |
_auto_class = "AutoModelForCausalLM"
|
969 |
|
|
|
1134 |
return reordered_past
|
1135 |
|
1136 |
def build_inputs(self, tokenizer, query: str, history: List[Tuple[str, str]] = [], meta_instruction=""):
|
1137 |
+
if tokenizer.add_bos_token:
|
1138 |
+
prompt = ""
|
|
|
1139 |
else:
|
1140 |
+
prompt = tokenizer.bos_token
|
1141 |
+
if meta_instruction:
|
1142 |
+
prompt += f"""<|im_start|>system\n{meta_instruction}<|im_end|>\n"""
|
1143 |
for record in history:
|
1144 |
+
prompt += f"""<|im_start|>user\n{record[0]}<|im_end|>\n<|im_start|>assistant\n{record[1]}<|im_end|>\n"""
|
1145 |
+
prompt += f"""<|im_start|>user\n{query}<|im_end|>\n<|im_start|>assistant\n"""
|
1146 |
return tokenizer([prompt], return_tensors="pt")
|
1147 |
|
1148 |
@torch.no_grad()
|
|
|
1157 |
temperature: float = 0.8,
|
1158 |
top_p: float = 0.8,
|
1159 |
meta_instruction: str = "You are an AI assistant whose name is InternLM (书生·浦语).\n"
|
1160 |
+
"- InternLM (书生·浦语) is a conversational language model that is developed by Shanghai AI Laboratory (上海人工智能实验室). It is designed to be helpful, honest, and harmless.\n"
|
1161 |
+
"- InternLM (书生·浦语) can understand and communicate fluently in the language chosen by the user such as English and 中文.",
|
1162 |
**kwargs,
|
1163 |
):
|
1164 |
inputs = self.build_inputs(tokenizer, query, history, meta_instruction)
|
1165 |
inputs = {k: v.to(self.device) for k, v in inputs.items() if torch.is_tensor(v)}
|
1166 |
# also add end-of-assistant token in eos token id to avoid unnecessary generation
|
1167 |
+
eos_token_id = [tokenizer.eos_token_id, tokenizer.convert_tokens_to_ids(["<|im_end|>"])[0]]
|
1168 |
outputs = self.generate(
|
1169 |
**inputs,
|
1170 |
streamer=streamer,
|
|
|
1177 |
)
|
1178 |
outputs = outputs[0].cpu().tolist()[len(inputs["input_ids"][0]) :]
|
1179 |
response = tokenizer.decode(outputs, skip_special_tokens=True)
|
1180 |
+
response = response.split("<|im_end|>")[0]
|
1181 |
history = history + [(query, response)]
|
1182 |
return response, history
|
1183 |
|
|
|
1215 |
self.query = query
|
1216 |
self.history = history
|
1217 |
self.response = ""
|
1218 |
+
self.cache = []
|
1219 |
self.received_inputs = False
|
1220 |
self.queue.put((self.response, history + [(self.query, self.response)]))
|
1221 |
|
|
|
1230 |
self.received_inputs = True
|
1231 |
return
|
1232 |
|
1233 |
+
self.cache.extend(value.tolist())
|
1234 |
+
token = self.tokenizer.decode(self.cache, skip_special_tokens=True)
|
1235 |
+
if token.strip() != "<|im_end|>":
|
1236 |
self.response = self.response + token
|
1237 |
history = self.history + [(self.query, self.response)]
|
1238 |
self.queue.put((self.response, history))
|
1239 |
+
self.cache = []
|
1240 |
+
else:
|
1241 |
+
self.end()
|
1242 |
|
1243 |
def end(self):
|
1244 |
self.queue.put(None)
|
|
|
1268 |
return consumer()
|
1269 |
|
1270 |
|
1271 |
+
# Copied from transformers.model.llama.modeling_llama.LlamaForSequenceClassification with Llama->InternLM2
|
1272 |
@add_start_docstrings(
|
1273 |
"""
|
1274 |
The InternLM2 Model transformer with a sequence classification head on top (linear layer).
|
tokenization_internlm.py → tokenization_internlm2.py
RENAMED
@@ -1,10 +1,7 @@
|
|
1 |
# coding=utf-8
|
2 |
-
# Copyright (c) InternLM. All rights reserved.
|
3 |
#
|
4 |
-
# This code is based on
|
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.
|
@@ -18,7 +15,7 @@
|
|
18 |
# See the License for the specific language governing permissions and
|
19 |
# limitations under the License.
|
20 |
|
21 |
-
"""Tokenization classes for
|
22 |
import os
|
23 |
from shutil import copyfile
|
24 |
from typing import Any, Dict, List, Optional, Tuple
|
@@ -34,9 +31,10 @@ VOCAB_FILES_NAMES = {"vocab_file": "./tokenizer.model"}
|
|
34 |
PRETRAINED_VOCAB_FILES_MAP = {}
|
35 |
|
36 |
|
37 |
-
|
|
|
38 |
"""
|
39 |
-
Construct a
|
40 |
|
41 |
Args:
|
42 |
vocab_file (`str`):
|
@@ -79,8 +77,6 @@ class InternLMTokenizer(PreTrainedTokenizer):
|
|
79 |
**kwargs,
|
80 |
)
|
81 |
|
82 |
-
""" Initialization"""
|
83 |
-
|
84 |
@property
|
85 |
def no_prefix_space_tokens(self):
|
86 |
if self._no_prefix_space_tokens is None:
|
|
|
1 |
# coding=utf-8
|
2 |
+
# Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
|
3 |
#
|
4 |
+
# This code is based on transformers/src/transformers/models/llama/tokenization_llama.py
|
|
|
|
|
|
|
5 |
#
|
6 |
# Licensed under the Apache License, Version 2.0 (the "License");
|
7 |
# you may not use this file except in compliance with the License.
|
|
|
15 |
# See the License for the specific language governing permissions and
|
16 |
# limitations under the License.
|
17 |
|
18 |
+
"""Tokenization classes for InternLM."""
|
19 |
import os
|
20 |
from shutil import copyfile
|
21 |
from typing import Any, Dict, List, Optional, Tuple
|
|
|
31 |
PRETRAINED_VOCAB_FILES_MAP = {}
|
32 |
|
33 |
|
34 |
+
# Modified from transformers.model.llama.tokenization_llama.LlamaTokenizer
|
35 |
+
class InternLM2Tokenizer(PreTrainedTokenizer):
|
36 |
"""
|
37 |
+
Construct a InternLM2 tokenizer. Based on byte-level Byte-Pair-Encoding.
|
38 |
|
39 |
Args:
|
40 |
vocab_file (`str`):
|
|
|
77 |
**kwargs,
|
78 |
)
|
79 |
|
|
|
|
|
80 |
@property
|
81 |
def no_prefix_space_tokens(self):
|
82 |
if self._no_prefix_space_tokens is None:
|
tokenization_internlm2_fast.py
ADDED
@@ -0,0 +1,214 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# This code is based on transformers/src/transformers/models/llama/tokenization_llama_fast.py
|
5 |
+
#
|
6 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
7 |
+
# you may not use this file except in compliance with the License.
|
8 |
+
# You may obtain a copy of the License at
|
9 |
+
#
|
10 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
11 |
+
#
|
12 |
+
# Unless required by applicable law or agreed to in writing, software
|
13 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
14 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
15 |
+
# See the License for the specific language governing permissions and
|
16 |
+
# limitations under the License.
|
17 |
+
|
18 |
+
"""Tokenization Fast class for InternLM."""
|
19 |
+
import os
|
20 |
+
from shutil import copyfile
|
21 |
+
from typing import Any, Dict, Optional, Tuple
|
22 |
+
|
23 |
+
from tokenizers import processors, decoders, Tokenizer, normalizers
|
24 |
+
from tokenizers.models import BPE
|
25 |
+
|
26 |
+
from transformers.tokenization_utils_fast import PreTrainedTokenizerFast
|
27 |
+
from transformers.utils import logging
|
28 |
+
|
29 |
+
from transformers.convert_slow_tokenizer import (
|
30 |
+
SLOW_TO_FAST_CONVERTERS,
|
31 |
+
SpmConverter,
|
32 |
+
SentencePieceExtractor,
|
33 |
+
)
|
34 |
+
|
35 |
+
from .tokenization_internlm2 import InternLM2Tokenizer
|
36 |
+
|
37 |
+
logger = logging.get_logger(__name__)
|
38 |
+
|
39 |
+
VOCAB_FILES_NAMES = {"vocab_file": "./tokenizer.model"}
|
40 |
+
|
41 |
+
# Modified from transformers.convert_slow_tokenizer.LlamaConverter
|
42 |
+
class InternLM2Converter(SpmConverter):
|
43 |
+
handle_byte_fallback = True
|
44 |
+
|
45 |
+
def vocab(self, proto):
|
46 |
+
vocab = [
|
47 |
+
("<unk>", 0.0),
|
48 |
+
("<s>", 0.0),
|
49 |
+
("</s>", 0.0),
|
50 |
+
]
|
51 |
+
vocab += [(piece.piece, piece.score) for piece in proto.pieces[3:]]
|
52 |
+
return vocab
|
53 |
+
|
54 |
+
def unk_id(self, proto):
|
55 |
+
unk_id = 0
|
56 |
+
return unk_id
|
57 |
+
|
58 |
+
def decoder(self, replacement, add_prefix_space):
|
59 |
+
return decoders.Sequence(
|
60 |
+
[
|
61 |
+
decoders.Replace("▁", " "),
|
62 |
+
decoders.ByteFallback(),
|
63 |
+
decoders.Fuse(),
|
64 |
+
decoders.Strip(content=" ", left=1),
|
65 |
+
]
|
66 |
+
)
|
67 |
+
|
68 |
+
def tokenizer(self, proto):
|
69 |
+
model_type = proto.trainer_spec.model_type
|
70 |
+
vocab_scores = self.vocab(proto)
|
71 |
+
# special tokens
|
72 |
+
added_tokens = self.original_tokenizer.added_tokens_decoder
|
73 |
+
for i in range(len(vocab_scores)):
|
74 |
+
piece, score = vocab_scores[i]
|
75 |
+
if i in added_tokens:
|
76 |
+
vocab_scores[i] = (added_tokens[i].content, score)
|
77 |
+
if model_type == 1:
|
78 |
+
raise RuntimeError("InternLM2 is supposed to be a BPE model!")
|
79 |
+
|
80 |
+
elif model_type == 2:
|
81 |
+
_, merges = SentencePieceExtractor(self.original_tokenizer.vocab_file).extract(vocab_scores)
|
82 |
+
bpe_vocab = {word: i for i, (word, _score) in enumerate(vocab_scores)}
|
83 |
+
tokenizer = Tokenizer(
|
84 |
+
BPE(bpe_vocab, merges, unk_token=proto.trainer_spec.unk_piece, fuse_unk=True, byte_fallback=True)
|
85 |
+
)
|
86 |
+
tokenizer.add_special_tokens(
|
87 |
+
[ added_token for index, added_token in added_tokens.items()]
|
88 |
+
)
|
89 |
+
else:
|
90 |
+
raise Exception(
|
91 |
+
"You're trying to run a `Unigram` model but you're file was trained with a different algorithm"
|
92 |
+
)
|
93 |
+
|
94 |
+
return tokenizer
|
95 |
+
|
96 |
+
def normalizer(self, proto):
|
97 |
+
normalizers_list = []
|
98 |
+
if proto.normalizer_spec.add_dummy_prefix:
|
99 |
+
normalizers_list.append(normalizers.Prepend(prepend="▁"))
|
100 |
+
normalizers_list.append(normalizers.Replace(pattern=" ", content="▁"))
|
101 |
+
return normalizers.Sequence(normalizers_list)
|
102 |
+
|
103 |
+
def pre_tokenizer(self, replacement, add_prefix_space):
|
104 |
+
return None
|
105 |
+
|
106 |
+
SLOW_TO_FAST_CONVERTERS["InternLM2Tokenizer"] = InternLM2Converter
|
107 |
+
|
108 |
+
|
109 |
+
# Modified from transformers.model.llama.tokenization_llama_fast.LlamaTokenizerFast -> InternLM2TokenizerFast
|
110 |
+
class InternLM2TokenizerFast(PreTrainedTokenizerFast):
|
111 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
112 |
+
slow_tokenizer_class = InternLM2Tokenizer
|
113 |
+
padding_side = "left"
|
114 |
+
model_input_names = ["input_ids", "attention_mask"]
|
115 |
+
_auto_class = "AutoTokenizer"
|
116 |
+
|
117 |
+
def __init__(
|
118 |
+
self,
|
119 |
+
vocab_file,
|
120 |
+
unk_token="<unk>",
|
121 |
+
bos_token="<s>",
|
122 |
+
eos_token="</s>",
|
123 |
+
pad_token="</s>",
|
124 |
+
sp_model_kwargs: Optional[Dict[str, Any]] = None,
|
125 |
+
add_bos_token=True,
|
126 |
+
add_eos_token=False,
|
127 |
+
decode_with_prefix_space=False,
|
128 |
+
clean_up_tokenization_spaces=False,
|
129 |
+
**kwargs,
|
130 |
+
):
|
131 |
+
super().__init__(
|
132 |
+
vocab_file=vocab_file,
|
133 |
+
unk_token=unk_token,
|
134 |
+
bos_token=bos_token,
|
135 |
+
eos_token=eos_token,
|
136 |
+
pad_token=pad_token,
|
137 |
+
sp_model_kwargs=sp_model_kwargs,
|
138 |
+
add_bos_token=add_bos_token,
|
139 |
+
add_eos_token=add_eos_token,
|
140 |
+
decode_with_prefix_space=decode_with_prefix_space,
|
141 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
142 |
+
**kwargs,
|
143 |
+
)
|
144 |
+
self._add_bos_token = add_bos_token
|
145 |
+
self._add_eos_token = add_eos_token
|
146 |
+
self.update_post_processor()
|
147 |
+
self.vocab_file = vocab_file
|
148 |
+
|
149 |
+
@property
|
150 |
+
def can_save_slow_tokenizer(self) -> bool:
|
151 |
+
return os.path.isfile(self.vocab_file) if self.vocab_file else False
|
152 |
+
|
153 |
+
def update_post_processor(self):
|
154 |
+
"""
|
155 |
+
Updates the underlying post processor with the current `bos_token` and `eos_token`.
|
156 |
+
"""
|
157 |
+
bos = self.bos_token
|
158 |
+
bos_token_id = self.bos_token_id
|
159 |
+
if bos is None and self.add_bos_token:
|
160 |
+
raise ValueError("add_bos_token = True but bos_token = None")
|
161 |
+
|
162 |
+
eos = self.eos_token
|
163 |
+
eos_token_id = self.eos_token_id
|
164 |
+
if eos is None and self.add_eos_token:
|
165 |
+
raise ValueError("add_eos_token = True but eos_token = None")
|
166 |
+
|
167 |
+
single = f"{(bos+':0 ') if self.add_bos_token else ''}$A:0{(' '+eos+':0') if self.add_eos_token else ''}"
|
168 |
+
pair = f"{single}{(' '+bos+':1') if self.add_bos_token else ''} $B:1{(' '+eos+':1') if self.add_eos_token else ''}"
|
169 |
+
|
170 |
+
special_tokens = []
|
171 |
+
if self.add_bos_token:
|
172 |
+
special_tokens.append((bos, bos_token_id))
|
173 |
+
if self.add_eos_token:
|
174 |
+
special_tokens.append((eos, eos_token_id))
|
175 |
+
self._tokenizer.post_processor = processors.TemplateProcessing(
|
176 |
+
single=single, pair=pair, special_tokens=special_tokens
|
177 |
+
)
|
178 |
+
|
179 |
+
@property
|
180 |
+
def add_eos_token(self):
|
181 |
+
return self._add_eos_token
|
182 |
+
|
183 |
+
@property
|
184 |
+
def add_bos_token(self):
|
185 |
+
return self._add_bos_token
|
186 |
+
|
187 |
+
@add_eos_token.setter
|
188 |
+
def add_eos_token(self, value):
|
189 |
+
self._add_eos_token = value
|
190 |
+
self.update_post_processor()
|
191 |
+
|
192 |
+
@add_bos_token.setter
|
193 |
+
def add_bos_token(self, value):
|
194 |
+
self._add_bos_token = value
|
195 |
+
self.update_post_processor()
|
196 |
+
|
197 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
198 |
+
if not self.can_save_slow_tokenizer:
|
199 |
+
raise ValueError(
|
200 |
+
"Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
|
201 |
+
"tokenizer."
|
202 |
+
)
|
203 |
+
|
204 |
+
if not os.path.isdir(save_directory):
|
205 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
206 |
+
return
|
207 |
+
out_vocab_file = os.path.join(
|
208 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
209 |
+
)
|
210 |
+
|
211 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
|
212 |
+
copyfile(self.vocab_file, out_vocab_file)
|
213 |
+
|
214 |
+
return (out_vocab_file,)
|
tokenizer_config.json
CHANGED
@@ -1,4 +1,17 @@
|
|
1 |
{
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
"added_tokens_decoder": {
|
3 |
"0": {
|
4 |
"content": "<unk>",
|
@@ -23,19 +36,55 @@
|
|
23 |
"rstrip": false,
|
24 |
"single_word": false,
|
25 |
"special": true
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
26 |
}
|
27 |
},
|
28 |
-
"
|
29 |
-
|
30 |
-
"tokenization_internlm.InternLMTokenizer",
|
31 |
-
null
|
32 |
-
]
|
33 |
-
},
|
34 |
-
"bos_token": "<s>",
|
35 |
-
"clean_up_tokenization_spaces": false,
|
36 |
-
"eos_token": "</s>",
|
37 |
-
"model_max_length": 1000000000000000019884624838656,
|
38 |
-
"pad_token": "</s>",
|
39 |
-
"tokenizer_class": "InternLMTokenizer",
|
40 |
-
"unk_token": "<unk>"
|
41 |
-
}
|
|
|
1 |
{
|
2 |
+
"auto_map": {
|
3 |
+
"AutoTokenizer": [
|
4 |
+
"tokenization_internlm2.InternLM2Tokenizer",
|
5 |
+
"tokenization_internlm2_fast.InternLM2TokenizerFast"
|
6 |
+
]
|
7 |
+
},
|
8 |
+
"bos_token": "<s>",
|
9 |
+
"clean_up_tokenization_spaces": false,
|
10 |
+
"eos_token": "</s>",
|
11 |
+
"model_max_length": 1000000000000000019884624838656,
|
12 |
+
"pad_token": "</s>",
|
13 |
+
"tokenizer_class": "InternLM2Tokenizer",
|
14 |
+
"unk_token": "<unk>",
|
15 |
"added_tokens_decoder": {
|
16 |
"0": {
|
17 |
"content": "<unk>",
|
|
|
36 |
"rstrip": false,
|
37 |
"single_word": false,
|
38 |
"special": true
|
39 |
+
},
|
40 |
+
"92543": {
|
41 |
+
"content": "<|im_start|>",
|
42 |
+
"lstrip": false,
|
43 |
+
"normalized": false,
|
44 |
+
"rstrip": false,
|
45 |
+
"single_word": false,
|
46 |
+
"special": true
|
47 |
+
},
|
48 |
+
"92542": {
|
49 |
+
"content": "<|im_end|>",
|
50 |
+
"lstrip": false,
|
51 |
+
"normalized": false,
|
52 |
+
"rstrip": false,
|
53 |
+
"single_word": false,
|
54 |
+
"special": true
|
55 |
+
},
|
56 |
+
"92541": {
|
57 |
+
"content": "<|action_start|>",
|
58 |
+
"lstrip": false,
|
59 |
+
"normalized": false,
|
60 |
+
"rstrip": false,
|
61 |
+
"single_word": false,
|
62 |
+
"special": true
|
63 |
+
},
|
64 |
+
"92540": {
|
65 |
+
"content": "<|action_end|>",
|
66 |
+
"lstrip": false,
|
67 |
+
"normalized": false,
|
68 |
+
"rstrip": false,
|
69 |
+
"single_word": false,
|
70 |
+
"special": true
|
71 |
+
},
|
72 |
+
"92539": {
|
73 |
+
"content": "<|interpreter|>",
|
74 |
+
"lstrip": false,
|
75 |
+
"normalized": false,
|
76 |
+
"rstrip": false,
|
77 |
+
"single_word": false,
|
78 |
+
"special": true
|
79 |
+
},
|
80 |
+
"92538": {
|
81 |
+
"content": "<|plugin|>",
|
82 |
+
"lstrip": false,
|
83 |
+
"normalized": false,
|
84 |
+
"rstrip": false,
|
85 |
+
"single_word": false,
|
86 |
+
"special": true
|
87 |
}
|
88 |
},
|
89 |
+
"chat_template": "{{ bos_token }}{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}"
|
90 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|