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