x54-729 commited on
Commit
7f8a007
1 Parent(s): 006a525

Upload folder using huggingface_hub

Browse files
README.md ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # InternLM2-WQX-20B
2
+
3
+ <div align="center">
4
+
5
+ <img src="https://raw.githubusercontent.com/InternLM/InternLM/main/assets/logo.svg" width="200"/>
6
+ <div> </div>
7
+ <div align="center">
8
+ <b><font size="5">InternLM2-WQX</font></b>
9
+ <sup>
10
+ <a href="https://internlm.intern-ai.org.cn/">
11
+ <i><font size="4">HOT</font></i>
12
+ </a>
13
+ </sup>
14
+ <div> </div>
15
+ </div>
16
+
17
+ [![license](https://raw.githubusercontent.com/InternLM/InternLM/main/assets/license.svg)](./LICENSE)
18
+
19
+
20
+
21
+ [💻 Github](https://github.com/InternLM/InternLM2-WQX) [🤗 Huggingface](https://huggingface.co/collections/internlm/InternLM2-WQX) [<img src="./assets/modelscope_logo.png" width="20px" /> ModelScope](https://modelscope.cn/models/Shanghai_AI_Laboratory/InternLM2-WQX/summary)
22
+ </div>
23
+
24
+ # Introduction
25
+ InternLM2-WQX是InternLM团队推出的文曲星系列模型。评测Comming Soon。
26
+
27
+ # MD5 Check
28
+ 以下是权重文件的md5值
29
+ ```
30
+ md5sum ./*
31
+ 5209adfd6ef7d1724848ff0372362568 ./model-00001-of-00004.safetensors
32
+ e37ee2eafecfed543d10dca75998204e ./model-00002-of-00004.safetensors
33
+ ea3da8035b0c2a31c369dd463adf9b52 ./model-00003-of-00004.safetensors
34
+ f1ff218f801c69fd4c12c534b64e1b60 ./model-00004-of-00004.safetensors
35
+ ```
config.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "InternLM2ForCausalLM"
4
+ ],
5
+ "attn_implementation": "eager",
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_internlm2.InternLM2Config",
8
+ "AutoModelForCausalLM": "modeling_internlm2.InternLM2ForCausalLM",
9
+ "AutoModel": "modeling_internlm2.InternLM2ForCausalLM"
10
+ },
11
+ "bias": false,
12
+ "bos_token_id": 1,
13
+ "eos_token_id": 2,
14
+ "hidden_act": "silu",
15
+ "hidden_size": 6144,
16
+ "initializer_range": 0.02,
17
+ "intermediate_size": 16384,
18
+ "max_position_embeddings": 4096,
19
+ "model_type": "internlm2",
20
+ "num_attention_heads": 48,
21
+ "num_hidden_layers": 48,
22
+ "num_key_value_heads": 8,
23
+ "pad_token_id": 2,
24
+ "rms_norm_eps": 1e-05,
25
+ "rope_scaling": null,
26
+ "rope_theta": 1000000,
27
+ "tie_word_embeddings": false,
28
+ "torch_dtype": "bfloat16",
29
+ "transformers_version": "4.39.3",
30
+ "use_cache": true,
31
+ "vocab_size": 92544
32
+ }
configuration_internlm2.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on transformers/src/transformers/models/llama/configuration_llama.py
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ """ InternLM2 model configuration"""
18
+
19
+ from transformers.configuration_utils import PretrainedConfig
20
+ from transformers.utils import logging
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+ INTERNLM2_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
25
+
26
+
27
+ # Modified from transformers.model.llama.configuration_llama.LlamaConfig
28
+ class InternLM2Config(PretrainedConfig):
29
+ r"""
30
+ This is the configuration class to store the configuration of a [`InternLM2Model`]. It is used to instantiate
31
+ an InternLM2 model according to the specified arguments, defining the model architecture. Instantiating a
32
+ configuration with the defaults will yield a similar configuration to that of the InternLM2-7B.
33
+
34
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
35
+ documentation from [`PretrainedConfig`] for more information.
36
+
37
+
38
+ Args:
39
+ vocab_size (`int`, *optional*, defaults to 32000):
40
+ Vocabulary size of the InternLM2 model. Defines the number of different tokens that can be represented
41
+ by the `inputs_ids` passed when calling [`InternLM2Model`]
42
+ hidden_size (`int`, *optional*, defaults to 4096):
43
+ Dimension of the hidden representations.
44
+ intermediate_size (`int`, *optional*, defaults to 11008):
45
+ Dimension of the MLP representations.
46
+ num_hidden_layers (`int`, *optional*, defaults to 32):
47
+ Number of hidden layers in the Transformer encoder.
48
+ num_attention_heads (`int`, *optional*, defaults to 32):
49
+ Number of attention heads for each attention layer in the Transformer encoder.
50
+ num_key_value_heads (`int`, *optional*):
51
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
52
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
53
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
54
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
55
+ by meanpooling all the original heads within that group. For more details checkout [this
56
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
57
+ `num_attention_heads`.
58
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
59
+ The non-linear activation function (function or string) in the decoder.
60
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
61
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
62
+ just in case (e.g., 512 or 1024 or 2048).
63
+ initializer_range (`float`, *optional*, defaults to 0.02):
64
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
65
+ rms_norm_eps (`float`, *optional*, defaults to 1e-12):
66
+ The epsilon used by the rms normalization layers.
67
+ use_cache (`bool`, *optional*, defaults to `True`):
68
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
69
+ relevant if `config.is_decoder=True`.
70
+ tie_word_embeddings(`bool`, *optional*, defaults to `False`):
71
+ Whether to tie weight embeddings
72
+ Example:
73
+
74
+ """
75
+ model_type = "internlm2"
76
+ _auto_class = "AutoConfig"
77
+
78
+ def __init__( # pylint: disable=W0102
79
+ self,
80
+ vocab_size=103168,
81
+ hidden_size=4096,
82
+ intermediate_size=11008,
83
+ num_hidden_layers=32,
84
+ num_attention_heads=32,
85
+ num_key_value_heads=None,
86
+ hidden_act="silu",
87
+ max_position_embeddings=2048,
88
+ initializer_range=0.02,
89
+ rms_norm_eps=1e-6,
90
+ use_cache=True,
91
+ pad_token_id=0,
92
+ bos_token_id=1,
93
+ eos_token_id=2,
94
+ tie_word_embeddings=False,
95
+ bias=True,
96
+ rope_theta=10000,
97
+ rope_scaling=None,
98
+ attn_implementation="eager",
99
+ **kwargs,
100
+ ):
101
+ self.vocab_size = vocab_size
102
+ self.max_position_embeddings = max_position_embeddings
103
+ self.hidden_size = hidden_size
104
+ self.intermediate_size = intermediate_size
105
+ self.num_hidden_layers = num_hidden_layers
106
+ self.num_attention_heads = num_attention_heads
107
+ self.bias = bias
108
+
109
+ if num_key_value_heads is None:
110
+ num_key_value_heads = num_attention_heads
111
+ self.num_key_value_heads = num_key_value_heads
112
+
113
+ self.hidden_act = hidden_act
114
+ self.initializer_range = initializer_range
115
+ self.rms_norm_eps = rms_norm_eps
116
+ self.use_cache = use_cache
117
+ self.rope_theta = rope_theta
118
+ self.rope_scaling = rope_scaling
119
+ self._rope_scaling_validation()
120
+
121
+ self.attn_implementation = attn_implementation
122
+ if self.attn_implementation is None:
123
+ self.attn_implementation = "eager"
124
+ super().__init__(
125
+ pad_token_id=pad_token_id,
126
+ bos_token_id=bos_token_id,
127
+ eos_token_id=eos_token_id,
128
+ tie_word_embeddings=tie_word_embeddings,
129
+ **kwargs,
130
+ )
131
+
132
+ def _rope_scaling_validation(self):
133
+ """
134
+ Validate the `rope_scaling` configuration.
135
+ """
136
+ if self.rope_scaling is None:
137
+ return
138
+
139
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
140
+ raise ValueError(
141
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
142
+ f"got {self.rope_scaling}"
143
+ )
144
+ rope_scaling_type = self.rope_scaling.get("type", None)
145
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
146
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
147
+ raise ValueError(
148
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
149
+ )
150
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor < 1.0:
151
+ 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.39.3"
7
+ }
model-00001-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:174691f5d4133f30f24ec992540794f4e861e0e93a82c26bbad176528b1734a5
3
+ size 9895166840
model-00002-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cd2036d8ad5a778caac6d20450cbbc0398f5f90ceb9d17bbeaf288ca3c6fc451
3
+ size 9965995968
model-00003-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a5a686066d5406c96c564634221670419265b06049d761655d17dde7630e6ff0
3
+ size 9940805472
model-00004-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e2462e6b7aff664c82aea9f3751fe6daa4e0bfa0505e4d5b4e635d68207b48fb
3
+ size 9920369776
model.safetensors.index.json ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 39722299392
4
+ },
5
+ "weight_map": {
6
+ "model.layers.0.attention.wo.weight": "model-00001-of-00004.safetensors",
7
+ "model.layers.0.attention.wqkv.weight": "model-00001-of-00004.safetensors",
8
+ "model.layers.0.attention_norm.weight": "model-00001-of-00004.safetensors",
9
+ "model.layers.0.feed_forward.w1.weight": "model-00001-of-00004.safetensors",
10
+ "model.layers.0.feed_forward.w2.weight": "model-00001-of-00004.safetensors",
11
+ "model.layers.0.feed_forward.w3.weight": "model-00001-of-00004.safetensors",
12
+ "model.layers.0.ffn_norm.weight": "model-00001-of-00004.safetensors",
13
+ "model.layers.1.attention.wo.weight": "model-00001-of-00004.safetensors",
14
+ "model.layers.1.attention.wqkv.weight": "model-00001-of-00004.safetensors",
15
+ "model.layers.1.attention_norm.weight": "model-00001-of-00004.safetensors",
16
+ "model.layers.1.feed_forward.w1.weight": "model-00001-of-00004.safetensors",
17
+ "model.layers.1.feed_forward.w2.weight": "model-00001-of-00004.safetensors",
18
+ "model.layers.1.feed_forward.w3.weight": "model-00001-of-00004.safetensors",
19
+ "model.layers.1.ffn_norm.weight": "model-00001-of-00004.safetensors",
20
+ "model.layers.10.attention.wo.weight": "model-00001-of-00004.safetensors",
21
+ "model.layers.10.attention.wqkv.weight": "model-00001-of-00004.safetensors",
22
+ "model.layers.10.attention_norm.weight": "model-00001-of-00004.safetensors",
23
+ "model.layers.10.feed_forward.w1.weight": "model-00001-of-00004.safetensors",
24
+ "model.layers.10.feed_forward.w2.weight": "model-00001-of-00004.safetensors",
25
+ "model.layers.10.feed_forward.w3.weight": "model-00001-of-00004.safetensors",
26
+ "model.layers.10.ffn_norm.weight": "model-00001-of-00004.safetensors",
27
+ "model.layers.11.attention.wo.weight": "model-00001-of-00004.safetensors",
28
+ "model.layers.11.attention.wqkv.weight": "model-00001-of-00004.safetensors",
29
+ "model.layers.11.attention_norm.weight": "model-00002-of-00004.safetensors",
30
+ "model.layers.11.feed_forward.w1.weight": "model-00002-of-00004.safetensors",
31
+ "model.layers.11.feed_forward.w2.weight": "model-00002-of-00004.safetensors",
32
+ "model.layers.11.feed_forward.w3.weight": "model-00002-of-00004.safetensors",
33
+ "model.layers.11.ffn_norm.weight": "model-00002-of-00004.safetensors",
34
+ "model.layers.12.attention.wo.weight": "model-00002-of-00004.safetensors",
35
+ "model.layers.12.attention.wqkv.weight": "model-00002-of-00004.safetensors",
36
+ "model.layers.12.attention_norm.weight": "model-00002-of-00004.safetensors",
37
+ "model.layers.12.feed_forward.w1.weight": "model-00002-of-00004.safetensors",
38
+ "model.layers.12.feed_forward.w2.weight": "model-00002-of-00004.safetensors",
39
+ "model.layers.12.feed_forward.w3.weight": "model-00002-of-00004.safetensors",
40
+ "model.layers.12.ffn_norm.weight": "model-00002-of-00004.safetensors",
41
+ "model.layers.13.attention.wo.weight": "model-00002-of-00004.safetensors",
42
+ "model.layers.13.attention.wqkv.weight": "model-00002-of-00004.safetensors",
43
+ "model.layers.13.attention_norm.weight": "model-00002-of-00004.safetensors",
44
+ "model.layers.13.feed_forward.w1.weight": "model-00002-of-00004.safetensors",
45
+ "model.layers.13.feed_forward.w2.weight": "model-00002-of-00004.safetensors",
46
+ "model.layers.13.feed_forward.w3.weight": "model-00002-of-00004.safetensors",
47
+ "model.layers.13.ffn_norm.weight": "model-00002-of-00004.safetensors",
48
+ "model.layers.14.attention.wo.weight": "model-00002-of-00004.safetensors",
49
+ "model.layers.14.attention.wqkv.weight": "model-00002-of-00004.safetensors",
50
+ "model.layers.14.attention_norm.weight": "model-00002-of-00004.safetensors",
51
+ "model.layers.14.feed_forward.w1.weight": "model-00002-of-00004.safetensors",
52
+ "model.layers.14.feed_forward.w2.weight": "model-00002-of-00004.safetensors",
53
+ "model.layers.14.feed_forward.w3.weight": "model-00002-of-00004.safetensors",
54
+ "model.layers.14.ffn_norm.weight": "model-00002-of-00004.safetensors",
55
+ "model.layers.15.attention.wo.weight": "model-00002-of-00004.safetensors",
56
+ "model.layers.15.attention.wqkv.weight": "model-00002-of-00004.safetensors",
57
+ "model.layers.15.attention_norm.weight": "model-00002-of-00004.safetensors",
58
+ "model.layers.15.feed_forward.w1.weight": "model-00002-of-00004.safetensors",
59
+ "model.layers.15.feed_forward.w2.weight": "model-00002-of-00004.safetensors",
60
+ "model.layers.15.feed_forward.w3.weight": "model-00002-of-00004.safetensors",
61
+ "model.layers.15.ffn_norm.weight": "model-00002-of-00004.safetensors",
62
+ "model.layers.16.attention.wo.weight": "model-00002-of-00004.safetensors",
63
+ "model.layers.16.attention.wqkv.weight": "model-00002-of-00004.safetensors",
64
+ "model.layers.16.attention_norm.weight": "model-00002-of-00004.safetensors",
65
+ "model.layers.16.feed_forward.w1.weight": "model-00002-of-00004.safetensors",
66
+ "model.layers.16.feed_forward.w2.weight": "model-00002-of-00004.safetensors",
67
+ "model.layers.16.feed_forward.w3.weight": "model-00002-of-00004.safetensors",
68
+ "model.layers.16.ffn_norm.weight": "model-00002-of-00004.safetensors",
69
+ "model.layers.17.attention.wo.weight": "model-00002-of-00004.safetensors",
70
+ "model.layers.17.attention.wqkv.weight": "model-00002-of-00004.safetensors",
71
+ "model.layers.17.attention_norm.weight": "model-00002-of-00004.safetensors",
72
+ "model.layers.17.feed_forward.w1.weight": "model-00002-of-00004.safetensors",
73
+ "model.layers.17.feed_forward.w2.weight": "model-00002-of-00004.safetensors",
74
+ "model.layers.17.feed_forward.w3.weight": "model-00002-of-00004.safetensors",
75
+ "model.layers.17.ffn_norm.weight": "model-00002-of-00004.safetensors",
76
+ "model.layers.18.attention.wo.weight": "model-00002-of-00004.safetensors",
77
+ "model.layers.18.attention.wqkv.weight": "model-00002-of-00004.safetensors",
78
+ "model.layers.18.attention_norm.weight": "model-00002-of-00004.safetensors",
79
+ "model.layers.18.feed_forward.w1.weight": "model-00002-of-00004.safetensors",
80
+ "model.layers.18.feed_forward.w2.weight": "model-00002-of-00004.safetensors",
81
+ "model.layers.18.feed_forward.w3.weight": "model-00002-of-00004.safetensors",
82
+ "model.layers.18.ffn_norm.weight": "model-00002-of-00004.safetensors",
83
+ "model.layers.19.attention.wo.weight": "model-00002-of-00004.safetensors",
84
+ "model.layers.19.attention.wqkv.weight": "model-00002-of-00004.safetensors",
85
+ "model.layers.19.attention_norm.weight": "model-00002-of-00004.safetensors",
86
+ "model.layers.19.feed_forward.w1.weight": "model-00002-of-00004.safetensors",
87
+ "model.layers.19.feed_forward.w2.weight": "model-00002-of-00004.safetensors",
88
+ "model.layers.19.feed_forward.w3.weight": "model-00002-of-00004.safetensors",
89
+ "model.layers.19.ffn_norm.weight": "model-00002-of-00004.safetensors",
90
+ "model.layers.2.attention.wo.weight": "model-00001-of-00004.safetensors",
91
+ "model.layers.2.attention.wqkv.weight": "model-00001-of-00004.safetensors",
92
+ "model.layers.2.attention_norm.weight": "model-00001-of-00004.safetensors",
93
+ "model.layers.2.feed_forward.w1.weight": "model-00001-of-00004.safetensors",
94
+ "model.layers.2.feed_forward.w2.weight": "model-00001-of-00004.safetensors",
95
+ "model.layers.2.feed_forward.w3.weight": "model-00001-of-00004.safetensors",
96
+ "model.layers.2.ffn_norm.weight": "model-00001-of-00004.safetensors",
97
+ "model.layers.20.attention.wo.weight": "model-00002-of-00004.safetensors",
98
+ "model.layers.20.attention.wqkv.weight": "model-00002-of-00004.safetensors",
99
+ "model.layers.20.attention_norm.weight": "model-00002-of-00004.safetensors",
100
+ "model.layers.20.feed_forward.w1.weight": "model-00002-of-00004.safetensors",
101
+ "model.layers.20.feed_forward.w2.weight": "model-00002-of-00004.safetensors",
102
+ "model.layers.20.feed_forward.w3.weight": "model-00002-of-00004.safetensors",
103
+ "model.layers.20.ffn_norm.weight": "model-00002-of-00004.safetensors",
104
+ "model.layers.21.attention.wo.weight": "model-00002-of-00004.safetensors",
105
+ "model.layers.21.attention.wqkv.weight": "model-00002-of-00004.safetensors",
106
+ "model.layers.21.attention_norm.weight": "model-00002-of-00004.safetensors",
107
+ "model.layers.21.feed_forward.w1.weight": "model-00002-of-00004.safetensors",
108
+ "model.layers.21.feed_forward.w2.weight": "model-00002-of-00004.safetensors",
109
+ "model.layers.21.feed_forward.w3.weight": "model-00002-of-00004.safetensors",
110
+ "model.layers.21.ffn_norm.weight": "model-00002-of-00004.safetensors",
111
+ "model.layers.22.attention.wo.weight": "model-00002-of-00004.safetensors",
112
+ "model.layers.22.attention.wqkv.weight": "model-00002-of-00004.safetensors",
113
+ "model.layers.22.attention_norm.weight": "model-00002-of-00004.safetensors",
114
+ "model.layers.22.feed_forward.w1.weight": "model-00002-of-00004.safetensors",
115
+ "model.layers.22.feed_forward.w2.weight": "model-00002-of-00004.safetensors",
116
+ "model.layers.22.feed_forward.w3.weight": "model-00002-of-00004.safetensors",
117
+ "model.layers.22.ffn_norm.weight": "model-00002-of-00004.safetensors",
118
+ "model.layers.23.attention.wo.weight": "model-00002-of-00004.safetensors",
119
+ "model.layers.23.attention.wqkv.weight": "model-00002-of-00004.safetensors",
120
+ "model.layers.23.attention_norm.weight": "model-00002-of-00004.safetensors",
121
+ "model.layers.23.feed_forward.w1.weight": "model-00002-of-00004.safetensors",
122
+ "model.layers.23.feed_forward.w2.weight": "model-00002-of-00004.safetensors",
123
+ "model.layers.23.feed_forward.w3.weight": "model-00002-of-00004.safetensors",
124
+ "model.layers.23.ffn_norm.weight": "model-00002-of-00004.safetensors",
125
+ "model.layers.24.attention.wo.weight": "model-00003-of-00004.safetensors",
126
+ "model.layers.24.attention.wqkv.weight": "model-00003-of-00004.safetensors",
127
+ "model.layers.24.attention_norm.weight": "model-00003-of-00004.safetensors",
128
+ "model.layers.24.feed_forward.w1.weight": "model-00003-of-00004.safetensors",
129
+ "model.layers.24.feed_forward.w2.weight": "model-00003-of-00004.safetensors",
130
+ "model.layers.24.feed_forward.w3.weight": "model-00003-of-00004.safetensors",
131
+ "model.layers.24.ffn_norm.weight": "model-00003-of-00004.safetensors",
132
+ "model.layers.25.attention.wo.weight": "model-00003-of-00004.safetensors",
133
+ "model.layers.25.attention.wqkv.weight": "model-00003-of-00004.safetensors",
134
+ "model.layers.25.attention_norm.weight": "model-00003-of-00004.safetensors",
135
+ "model.layers.25.feed_forward.w1.weight": "model-00003-of-00004.safetensors",
136
+ "model.layers.25.feed_forward.w2.weight": "model-00003-of-00004.safetensors",
137
+ "model.layers.25.feed_forward.w3.weight": "model-00003-of-00004.safetensors",
138
+ "model.layers.25.ffn_norm.weight": "model-00003-of-00004.safetensors",
139
+ "model.layers.26.attention.wo.weight": "model-00003-of-00004.safetensors",
140
+ "model.layers.26.attention.wqkv.weight": "model-00003-of-00004.safetensors",
141
+ "model.layers.26.attention_norm.weight": "model-00003-of-00004.safetensors",
142
+ "model.layers.26.feed_forward.w1.weight": "model-00003-of-00004.safetensors",
143
+ "model.layers.26.feed_forward.w2.weight": "model-00003-of-00004.safetensors",
144
+ "model.layers.26.feed_forward.w3.weight": "model-00003-of-00004.safetensors",
145
+ "model.layers.26.ffn_norm.weight": "model-00003-of-00004.safetensors",
146
+ "model.layers.27.attention.wo.weight": "model-00003-of-00004.safetensors",
147
+ "model.layers.27.attention.wqkv.weight": "model-00003-of-00004.safetensors",
148
+ "model.layers.27.attention_norm.weight": "model-00003-of-00004.safetensors",
149
+ "model.layers.27.feed_forward.w1.weight": "model-00003-of-00004.safetensors",
150
+ "model.layers.27.feed_forward.w2.weight": "model-00003-of-00004.safetensors",
151
+ "model.layers.27.feed_forward.w3.weight": "model-00003-of-00004.safetensors",
152
+ "model.layers.27.ffn_norm.weight": "model-00003-of-00004.safetensors",
153
+ "model.layers.28.attention.wo.weight": "model-00003-of-00004.safetensors",
154
+ "model.layers.28.attention.wqkv.weight": "model-00003-of-00004.safetensors",
155
+ "model.layers.28.attention_norm.weight": "model-00003-of-00004.safetensors",
156
+ "model.layers.28.feed_forward.w1.weight": "model-00003-of-00004.safetensors",
157
+ "model.layers.28.feed_forward.w2.weight": "model-00003-of-00004.safetensors",
158
+ "model.layers.28.feed_forward.w3.weight": "model-00003-of-00004.safetensors",
159
+ "model.layers.28.ffn_norm.weight": "model-00003-of-00004.safetensors",
160
+ "model.layers.29.attention.wo.weight": "model-00003-of-00004.safetensors",
161
+ "model.layers.29.attention.wqkv.weight": "model-00003-of-00004.safetensors",
162
+ "model.layers.29.attention_norm.weight": "model-00003-of-00004.safetensors",
163
+ "model.layers.29.feed_forward.w1.weight": "model-00003-of-00004.safetensors",
164
+ "model.layers.29.feed_forward.w2.weight": "model-00003-of-00004.safetensors",
165
+ "model.layers.29.feed_forward.w3.weight": "model-00003-of-00004.safetensors",
166
+ "model.layers.29.ffn_norm.weight": "model-00003-of-00004.safetensors",
167
+ "model.layers.3.attention.wo.weight": "model-00001-of-00004.safetensors",
168
+ "model.layers.3.attention.wqkv.weight": "model-00001-of-00004.safetensors",
169
+ "model.layers.3.attention_norm.weight": "model-00001-of-00004.safetensors",
170
+ "model.layers.3.feed_forward.w1.weight": "model-00001-of-00004.safetensors",
171
+ "model.layers.3.feed_forward.w2.weight": "model-00001-of-00004.safetensors",
172
+ "model.layers.3.feed_forward.w3.weight": "model-00001-of-00004.safetensors",
173
+ "model.layers.3.ffn_norm.weight": "model-00001-of-00004.safetensors",
174
+ "model.layers.30.attention.wo.weight": "model-00003-of-00004.safetensors",
175
+ "model.layers.30.attention.wqkv.weight": "model-00003-of-00004.safetensors",
176
+ "model.layers.30.attention_norm.weight": "model-00003-of-00004.safetensors",
177
+ "model.layers.30.feed_forward.w1.weight": "model-00003-of-00004.safetensors",
178
+ "model.layers.30.feed_forward.w2.weight": "model-00003-of-00004.safetensors",
179
+ "model.layers.30.feed_forward.w3.weight": "model-00003-of-00004.safetensors",
180
+ "model.layers.30.ffn_norm.weight": "model-00003-of-00004.safetensors",
181
+ "model.layers.31.attention.wo.weight": "model-00003-of-00004.safetensors",
182
+ "model.layers.31.attention.wqkv.weight": "model-00003-of-00004.safetensors",
183
+ "model.layers.31.attention_norm.weight": "model-00003-of-00004.safetensors",
184
+ "model.layers.31.feed_forward.w1.weight": "model-00003-of-00004.safetensors",
185
+ "model.layers.31.feed_forward.w2.weight": "model-00003-of-00004.safetensors",
186
+ "model.layers.31.feed_forward.w3.weight": "model-00003-of-00004.safetensors",
187
+ "model.layers.31.ffn_norm.weight": "model-00003-of-00004.safetensors",
188
+ "model.layers.32.attention.wo.weight": "model-00003-of-00004.safetensors",
189
+ "model.layers.32.attention.wqkv.weight": "model-00003-of-00004.safetensors",
190
+ "model.layers.32.attention_norm.weight": "model-00003-of-00004.safetensors",
191
+ "model.layers.32.feed_forward.w1.weight": "model-00003-of-00004.safetensors",
192
+ "model.layers.32.feed_forward.w2.weight": "model-00003-of-00004.safetensors",
193
+ "model.layers.32.feed_forward.w3.weight": "model-00003-of-00004.safetensors",
194
+ "model.layers.32.ffn_norm.weight": "model-00003-of-00004.safetensors",
195
+ "model.layers.33.attention.wo.weight": "model-00003-of-00004.safetensors",
196
+ "model.layers.33.attention.wqkv.weight": "model-00003-of-00004.safetensors",
197
+ "model.layers.33.attention_norm.weight": "model-00003-of-00004.safetensors",
198
+ "model.layers.33.feed_forward.w1.weight": "model-00003-of-00004.safetensors",
199
+ "model.layers.33.feed_forward.w2.weight": "model-00003-of-00004.safetensors",
200
+ "model.layers.33.feed_forward.w3.weight": "model-00003-of-00004.safetensors",
201
+ "model.layers.33.ffn_norm.weight": "model-00003-of-00004.safetensors",
202
+ "model.layers.34.attention.wo.weight": "model-00003-of-00004.safetensors",
203
+ "model.layers.34.attention.wqkv.weight": "model-00003-of-00004.safetensors",
204
+ "model.layers.34.attention_norm.weight": "model-00003-of-00004.safetensors",
205
+ "model.layers.34.feed_forward.w1.weight": "model-00003-of-00004.safetensors",
206
+ "model.layers.34.feed_forward.w2.weight": "model-00003-of-00004.safetensors",
207
+ "model.layers.34.feed_forward.w3.weight": "model-00003-of-00004.safetensors",
208
+ "model.layers.34.ffn_norm.weight": "model-00003-of-00004.safetensors",
209
+ "model.layers.35.attention.wo.weight": "model-00003-of-00004.safetensors",
210
+ "model.layers.35.attention.wqkv.weight": "model-00003-of-00004.safetensors",
211
+ "model.layers.35.attention_norm.weight": "model-00003-of-00004.safetensors",
212
+ "model.layers.35.feed_forward.w1.weight": "model-00003-of-00004.safetensors",
213
+ "model.layers.35.feed_forward.w2.weight": "model-00003-of-00004.safetensors",
214
+ "model.layers.35.feed_forward.w3.weight": "model-00003-of-00004.safetensors",
215
+ "model.layers.35.ffn_norm.weight": "model-00003-of-00004.safetensors",
216
+ "model.layers.36.attention.wo.weight": "model-00003-of-00004.safetensors",
217
+ "model.layers.36.attention.wqkv.weight": "model-00003-of-00004.safetensors",
218
+ "model.layers.36.attention_norm.weight": "model-00004-of-00004.safetensors",
219
+ "model.layers.36.feed_forward.w1.weight": "model-00003-of-00004.safetensors",
220
+ "model.layers.36.feed_forward.w2.weight": "model-00004-of-00004.safetensors",
221
+ "model.layers.36.feed_forward.w3.weight": "model-00003-of-00004.safetensors",
222
+ "model.layers.36.ffn_norm.weight": "model-00004-of-00004.safetensors",
223
+ "model.layers.37.attention.wo.weight": "model-00004-of-00004.safetensors",
224
+ "model.layers.37.attention.wqkv.weight": "model-00004-of-00004.safetensors",
225
+ "model.layers.37.attention_norm.weight": "model-00004-of-00004.safetensors",
226
+ "model.layers.37.feed_forward.w1.weight": "model-00004-of-00004.safetensors",
227
+ "model.layers.37.feed_forward.w2.weight": "model-00004-of-00004.safetensors",
228
+ "model.layers.37.feed_forward.w3.weight": "model-00004-of-00004.safetensors",
229
+ "model.layers.37.ffn_norm.weight": "model-00004-of-00004.safetensors",
230
+ "model.layers.38.attention.wo.weight": "model-00004-of-00004.safetensors",
231
+ "model.layers.38.attention.wqkv.weight": "model-00004-of-00004.safetensors",
232
+ "model.layers.38.attention_norm.weight": "model-00004-of-00004.safetensors",
233
+ "model.layers.38.feed_forward.w1.weight": "model-00004-of-00004.safetensors",
234
+ "model.layers.38.feed_forward.w2.weight": "model-00004-of-00004.safetensors",
235
+ "model.layers.38.feed_forward.w3.weight": "model-00004-of-00004.safetensors",
236
+ "model.layers.38.ffn_norm.weight": "model-00004-of-00004.safetensors",
237
+ "model.layers.39.attention.wo.weight": "model-00004-of-00004.safetensors",
238
+ "model.layers.39.attention.wqkv.weight": "model-00004-of-00004.safetensors",
239
+ "model.layers.39.attention_norm.weight": "model-00004-of-00004.safetensors",
240
+ "model.layers.39.feed_forward.w1.weight": "model-00004-of-00004.safetensors",
241
+ "model.layers.39.feed_forward.w2.weight": "model-00004-of-00004.safetensors",
242
+ "model.layers.39.feed_forward.w3.weight": "model-00004-of-00004.safetensors",
243
+ "model.layers.39.ffn_norm.weight": "model-00004-of-00004.safetensors",
244
+ "model.layers.4.attention.wo.weight": "model-00001-of-00004.safetensors",
245
+ "model.layers.4.attention.wqkv.weight": "model-00001-of-00004.safetensors",
246
+ "model.layers.4.attention_norm.weight": "model-00001-of-00004.safetensors",
247
+ "model.layers.4.feed_forward.w1.weight": "model-00001-of-00004.safetensors",
248
+ "model.layers.4.feed_forward.w2.weight": "model-00001-of-00004.safetensors",
249
+ "model.layers.4.feed_forward.w3.weight": "model-00001-of-00004.safetensors",
250
+ "model.layers.4.ffn_norm.weight": "model-00001-of-00004.safetensors",
251
+ "model.layers.40.attention.wo.weight": "model-00004-of-00004.safetensors",
252
+ "model.layers.40.attention.wqkv.weight": "model-00004-of-00004.safetensors",
253
+ "model.layers.40.attention_norm.weight": "model-00004-of-00004.safetensors",
254
+ "model.layers.40.feed_forward.w1.weight": "model-00004-of-00004.safetensors",
255
+ "model.layers.40.feed_forward.w2.weight": "model-00004-of-00004.safetensors",
256
+ "model.layers.40.feed_forward.w3.weight": "model-00004-of-00004.safetensors",
257
+ "model.layers.40.ffn_norm.weight": "model-00004-of-00004.safetensors",
258
+ "model.layers.41.attention.wo.weight": "model-00004-of-00004.safetensors",
259
+ "model.layers.41.attention.wqkv.weight": "model-00004-of-00004.safetensors",
260
+ "model.layers.41.attention_norm.weight": "model-00004-of-00004.safetensors",
261
+ "model.layers.41.feed_forward.w1.weight": "model-00004-of-00004.safetensors",
262
+ "model.layers.41.feed_forward.w2.weight": "model-00004-of-00004.safetensors",
263
+ "model.layers.41.feed_forward.w3.weight": "model-00004-of-00004.safetensors",
264
+ "model.layers.41.ffn_norm.weight": "model-00004-of-00004.safetensors",
265
+ "model.layers.42.attention.wo.weight": "model-00004-of-00004.safetensors",
266
+ "model.layers.42.attention.wqkv.weight": "model-00004-of-00004.safetensors",
267
+ "model.layers.42.attention_norm.weight": "model-00004-of-00004.safetensors",
268
+ "model.layers.42.feed_forward.w1.weight": "model-00004-of-00004.safetensors",
269
+ "model.layers.42.feed_forward.w2.weight": "model-00004-of-00004.safetensors",
270
+ "model.layers.42.feed_forward.w3.weight": "model-00004-of-00004.safetensors",
271
+ "model.layers.42.ffn_norm.weight": "model-00004-of-00004.safetensors",
272
+ "model.layers.43.attention.wo.weight": "model-00004-of-00004.safetensors",
273
+ "model.layers.43.attention.wqkv.weight": "model-00004-of-00004.safetensors",
274
+ "model.layers.43.attention_norm.weight": "model-00004-of-00004.safetensors",
275
+ "model.layers.43.feed_forward.w1.weight": "model-00004-of-00004.safetensors",
276
+ "model.layers.43.feed_forward.w2.weight": "model-00004-of-00004.safetensors",
277
+ "model.layers.43.feed_forward.w3.weight": "model-00004-of-00004.safetensors",
278
+ "model.layers.43.ffn_norm.weight": "model-00004-of-00004.safetensors",
279
+ "model.layers.44.attention.wo.weight": "model-00004-of-00004.safetensors",
280
+ "model.layers.44.attention.wqkv.weight": "model-00004-of-00004.safetensors",
281
+ "model.layers.44.attention_norm.weight": "model-00004-of-00004.safetensors",
282
+ "model.layers.44.feed_forward.w1.weight": "model-00004-of-00004.safetensors",
283
+ "model.layers.44.feed_forward.w2.weight": "model-00004-of-00004.safetensors",
284
+ "model.layers.44.feed_forward.w3.weight": "model-00004-of-00004.safetensors",
285
+ "model.layers.44.ffn_norm.weight": "model-00004-of-00004.safetensors",
286
+ "model.layers.45.attention.wo.weight": "model-00004-of-00004.safetensors",
287
+ "model.layers.45.attention.wqkv.weight": "model-00004-of-00004.safetensors",
288
+ "model.layers.45.attention_norm.weight": "model-00004-of-00004.safetensors",
289
+ "model.layers.45.feed_forward.w1.weight": "model-00004-of-00004.safetensors",
290
+ "model.layers.45.feed_forward.w2.weight": "model-00004-of-00004.safetensors",
291
+ "model.layers.45.feed_forward.w3.weight": "model-00004-of-00004.safetensors",
292
+ "model.layers.45.ffn_norm.weight": "model-00004-of-00004.safetensors",
293
+ "model.layers.46.attention.wo.weight": "model-00004-of-00004.safetensors",
294
+ "model.layers.46.attention.wqkv.weight": "model-00004-of-00004.safetensors",
295
+ "model.layers.46.attention_norm.weight": "model-00004-of-00004.safetensors",
296
+ "model.layers.46.feed_forward.w1.weight": "model-00004-of-00004.safetensors",
297
+ "model.layers.46.feed_forward.w2.weight": "model-00004-of-00004.safetensors",
298
+ "model.layers.46.feed_forward.w3.weight": "model-00004-of-00004.safetensors",
299
+ "model.layers.46.ffn_norm.weight": "model-00004-of-00004.safetensors",
300
+ "model.layers.47.attention.wo.weight": "model-00004-of-00004.safetensors",
301
+ "model.layers.47.attention.wqkv.weight": "model-00004-of-00004.safetensors",
302
+ "model.layers.47.attention_norm.weight": "model-00004-of-00004.safetensors",
303
+ "model.layers.47.feed_forward.w1.weight": "model-00004-of-00004.safetensors",
304
+ "model.layers.47.feed_forward.w2.weight": "model-00004-of-00004.safetensors",
305
+ "model.layers.47.feed_forward.w3.weight": "model-00004-of-00004.safetensors",
306
+ "model.layers.47.ffn_norm.weight": "model-00004-of-00004.safetensors",
307
+ "model.layers.5.attention.wo.weight": "model-00001-of-00004.safetensors",
308
+ "model.layers.5.attention.wqkv.weight": "model-00001-of-00004.safetensors",
309
+ "model.layers.5.attention_norm.weight": "model-00001-of-00004.safetensors",
310
+ "model.layers.5.feed_forward.w1.weight": "model-00001-of-00004.safetensors",
311
+ "model.layers.5.feed_forward.w2.weight": "model-00001-of-00004.safetensors",
312
+ "model.layers.5.feed_forward.w3.weight": "model-00001-of-00004.safetensors",
313
+ "model.layers.5.ffn_norm.weight": "model-00001-of-00004.safetensors",
314
+ "model.layers.6.attention.wo.weight": "model-00001-of-00004.safetensors",
315
+ "model.layers.6.attention.wqkv.weight": "model-00001-of-00004.safetensors",
316
+ "model.layers.6.attention_norm.weight": "model-00001-of-00004.safetensors",
317
+ "model.layers.6.feed_forward.w1.weight": "model-00001-of-00004.safetensors",
318
+ "model.layers.6.feed_forward.w2.weight": "model-00001-of-00004.safetensors",
319
+ "model.layers.6.feed_forward.w3.weight": "model-00001-of-00004.safetensors",
320
+ "model.layers.6.ffn_norm.weight": "model-00001-of-00004.safetensors",
321
+ "model.layers.7.attention.wo.weight": "model-00001-of-00004.safetensors",
322
+ "model.layers.7.attention.wqkv.weight": "model-00001-of-00004.safetensors",
323
+ "model.layers.7.attention_norm.weight": "model-00001-of-00004.safetensors",
324
+ "model.layers.7.feed_forward.w1.weight": "model-00001-of-00004.safetensors",
325
+ "model.layers.7.feed_forward.w2.weight": "model-00001-of-00004.safetensors",
326
+ "model.layers.7.feed_forward.w3.weight": "model-00001-of-00004.safetensors",
327
+ "model.layers.7.ffn_norm.weight": "model-00001-of-00004.safetensors",
328
+ "model.layers.8.attention.wo.weight": "model-00001-of-00004.safetensors",
329
+ "model.layers.8.attention.wqkv.weight": "model-00001-of-00004.safetensors",
330
+ "model.layers.8.attention_norm.weight": "model-00001-of-00004.safetensors",
331
+ "model.layers.8.feed_forward.w1.weight": "model-00001-of-00004.safetensors",
332
+ "model.layers.8.feed_forward.w2.weight": "model-00001-of-00004.safetensors",
333
+ "model.layers.8.feed_forward.w3.weight": "model-00001-of-00004.safetensors",
334
+ "model.layers.8.ffn_norm.weight": "model-00001-of-00004.safetensors",
335
+ "model.layers.9.attention.wo.weight": "model-00001-of-00004.safetensors",
336
+ "model.layers.9.attention.wqkv.weight": "model-00001-of-00004.safetensors",
337
+ "model.layers.9.attention_norm.weight": "model-00001-of-00004.safetensors",
338
+ "model.layers.9.feed_forward.w1.weight": "model-00001-of-00004.safetensors",
339
+ "model.layers.9.feed_forward.w2.weight": "model-00001-of-00004.safetensors",
340
+ "model.layers.9.feed_forward.w3.weight": "model-00001-of-00004.safetensors",
341
+ "model.layers.9.ffn_norm.weight": "model-00001-of-00004.safetensors",
342
+ "model.norm.weight": "model-00004-of-00004.safetensors",
343
+ "model.tok_embeddings.weight": "model-00001-of-00004.safetensors",
344
+ "output.weight": "model-00004-of-00004.safetensors"
345
+ }
346
+ }
modeling_internlm2.py ADDED
@@ -0,0 +1,1439 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # This code is based on transformers/src/transformers/models/llama/modeling_llama.py
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """ PyTorch InternLM2 model."""
17
+ import math
18
+ import queue
19
+ import threading
20
+ import warnings
21
+ from typing import List, Optional, Tuple, Union
22
+
23
+ import torch
24
+ import torch.nn.functional as F
25
+ import torch.utils.checkpoint
26
+ from einops import rearrange
27
+ from torch import nn
28
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
29
+ from transformers.activations import ACT2FN
30
+ from transformers.modeling_outputs import (
31
+ BaseModelOutputWithPast,
32
+ CausalLMOutputWithPast,
33
+ SequenceClassifierOutputWithPast,
34
+ )
35
+ from transformers.modeling_utils import PreTrainedModel
36
+ from transformers.utils import (
37
+ add_start_docstrings,
38
+ add_start_docstrings_to_model_forward,
39
+ logging,
40
+ replace_return_docstrings,
41
+ )
42
+
43
+ try:
44
+ from transformers.generation.streamers import BaseStreamer
45
+ except Exception:
46
+ BaseStreamer = None
47
+
48
+ from .configuration_internlm2 import InternLM2Config
49
+
50
+ logger = logging.get_logger(__name__)
51
+
52
+ _CONFIG_FOR_DOC = "InternLM2Config"
53
+
54
+ flash_attn_func, flash_attn_varlen_func = None, None
55
+ pad_input, index_first_axis, unpad_input = None, None, None
56
+
57
+
58
+ def _import_flash_attn():
59
+ global flash_attn_func, flash_attn_varlen_func
60
+ global pad_input, index_first_axis, unpad_input
61
+ try:
62
+ from flash_attn import flash_attn_func as _flash_attn_func
63
+ from flash_attn import flash_attn_varlen_func as _flash_attn_varlen_func
64
+ from flash_attn.bert_padding import index_first_axis as _index_first_axis
65
+ from flash_attn.bert_padding import pad_input as _pad_input
66
+ from flash_attn.bert_padding import unpad_input as _unpad_input
67
+
68
+ flash_attn_func, flash_attn_varlen_func = _flash_attn_func, _flash_attn_varlen_func
69
+ pad_input, index_first_axis, unpad_input = _pad_input, _index_first_axis, _unpad_input
70
+ except ImportError:
71
+ raise ImportError("flash_attn is not installed.")
72
+
73
+
74
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
75
+ def _get_unpad_data(attention_mask):
76
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
77
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
78
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
79
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
80
+ return (
81
+ indices,
82
+ cu_seqlens,
83
+ max_seqlen_in_batch,
84
+ )
85
+
86
+
87
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
88
+ def _make_causal_mask(
89
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
90
+ ):
91
+ """
92
+ Make causal mask used for bi-directional self-attention.
93
+ """
94
+ bsz, tgt_len = input_ids_shape
95
+ mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
96
+ mask_cond = torch.arange(mask.size(-1), device=device)
97
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
98
+ mask = mask.to(dtype)
99
+
100
+ if past_key_values_length > 0:
101
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
102
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
103
+
104
+
105
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
106
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
107
+ """
108
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
109
+ """
110
+ bsz, src_len = mask.size()
111
+ tgt_len = tgt_len if tgt_len is not None else src_len
112
+
113
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
114
+
115
+ inverted_mask = 1.0 - expanded_mask
116
+
117
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
118
+
119
+
120
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->InternLM2
121
+ class InternLM2RMSNorm(nn.Module):
122
+ """
123
+ InternLM2 RMSNorm implemention.
124
+ """
125
+
126
+ def __init__(self, hidden_size, eps=1e-6):
127
+ """
128
+ InternLM2RMSNorm is equivalent to T5LayerNorm
129
+ """
130
+ super().__init__()
131
+ self.weight = nn.Parameter(torch.ones(hidden_size))
132
+ self.variance_epsilon = eps
133
+
134
+ def forward(self, hidden_states):
135
+ input_dtype = hidden_states.dtype
136
+ hidden_states = hidden_states.to(torch.float32)
137
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
138
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
139
+ return self.weight * hidden_states.to(input_dtype)
140
+
141
+
142
+ # Copied from transformers.model.llama.modeling_llama.LlamaRotaryEmbedding with Llama->InternLM2
143
+ class InternLM2RotaryEmbedding(nn.Module):
144
+ """
145
+ Normal InternLM2 rotary embedding.
146
+ """
147
+
148
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
149
+ super().__init__()
150
+
151
+ self.dim = dim
152
+ self.max_position_embeddings = max_position_embeddings
153
+ self.base = base
154
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
155
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
156
+
157
+ # Build here to make `torch.jit.trace` work.
158
+ self._set_cos_sin_cache(
159
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
160
+ )
161
+
162
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
163
+ self.max_seq_len_cached = seq_len
164
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
165
+
166
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
167
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
168
+ emb = torch.cat((freqs, freqs), dim=-1)
169
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
170
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
171
+
172
+ def forward(self, x, seq_len=None):
173
+ # x: [bs, num_attention_heads, seq_len, head_size]
174
+ if seq_len > self.max_seq_len_cached:
175
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=torch.float32)
176
+
177
+ return (
178
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
179
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
180
+ )
181
+
182
+
183
+ # Copied from transformers.model.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->InternLM2
184
+ class InternLM2LinearScalingRotaryEmbedding(InternLM2RotaryEmbedding):
185
+ """InternLM2RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
186
+
187
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
188
+ self.scaling_factor = scaling_factor
189
+ super().__init__(dim, max_position_embeddings, base, device)
190
+
191
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
192
+ self.max_seq_len_cached = seq_len
193
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
194
+ t = t / self.scaling_factor
195
+
196
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
197
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
198
+ emb = torch.cat((freqs, freqs), dim=-1)
199
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
200
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
201
+
202
+
203
+ # Copied from transformers.model.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->InternLM2
204
+ class InternLM2DynamicNTKScalingRotaryEmbedding(InternLM2RotaryEmbedding):
205
+ """InternLM2RotaryEmbedding extended with Dynamic NTK scaling.
206
+ Credits to the Reddit users /u/bloc97 and /u/emozilla.
207
+ """
208
+
209
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
210
+ self.scaling_factor = scaling_factor
211
+ super().__init__(dim, max_position_embeddings, base, device)
212
+
213
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
214
+ self.max_seq_len_cached = seq_len
215
+
216
+ if seq_len > self.max_position_embeddings:
217
+ base = self.base * (
218
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
219
+ ) ** (self.dim / (self.dim - 2))
220
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
221
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
222
+
223
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
224
+
225
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
226
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
227
+ emb = torch.cat((freqs, freqs), dim=-1)
228
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
229
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
230
+
231
+
232
+ # Copied from transformers.model.llama.modeling_llama.rotate_half
233
+ def rotate_half(x):
234
+ """Rotates half the hidden dims of the input."""
235
+ x1 = x[..., : x.shape[-1] // 2]
236
+ x2 = x[..., x.shape[-1] // 2 :]
237
+ return torch.cat((-x2, x1), dim=-1)
238
+
239
+
240
+ # Copied from transformers.model.llama.modeling_llama.apply_rotary_pos_emb
241
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
242
+ """Applies Rotary Position Embedding to the query and key tensors."""
243
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
244
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
245
+ q_embed = (q * cos) + (rotate_half(q) * sin)
246
+ k_embed = (k * cos) + (rotate_half(k) * sin)
247
+ return q_embed, k_embed
248
+
249
+
250
+ class InternLM2MLP(nn.Module):
251
+ """
252
+ InternLM2 FFN.
253
+ """
254
+
255
+ def __init__(self, config):
256
+ super().__init__()
257
+ self.config = config
258
+ self.hidden_size = config.hidden_size
259
+ self.intermediate_size = config.intermediate_size
260
+ self.w1 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
261
+ self.w3 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
262
+ self.w2 = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
263
+ self.act_fn = ACT2FN[config.hidden_act]
264
+
265
+ def forward(self, x):
266
+ down_proj = self.w2(self.act_fn(self.w1(x)) * self.w3(x))
267
+
268
+ return down_proj
269
+
270
+
271
+ # Copied from transformers.model.llama.modeling_llama.repeat_kv
272
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
273
+ """
274
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
275
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
276
+ """
277
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
278
+ if n_rep == 1:
279
+ return hidden_states
280
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
281
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
282
+
283
+
284
+ # Modified from transformers.model.llama.modeling_llama.LlamaAttention
285
+ class InternLM2Attention(nn.Module):
286
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
287
+
288
+ def __init__(self, config: InternLM2Config):
289
+ super().__init__()
290
+ self.config = config
291
+ self.hidden_size = config.hidden_size
292
+ self.num_heads = config.num_attention_heads
293
+ self.head_dim = self.hidden_size // self.num_heads
294
+ self.num_key_value_heads = config.num_key_value_heads
295
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
296
+ self.max_position_embeddings = config.max_position_embeddings
297
+ self.is_causal = True
298
+
299
+ if (self.head_dim * self.num_heads) != self.hidden_size:
300
+ raise ValueError(
301
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
302
+ f" and `num_heads`: {self.num_heads})."
303
+ )
304
+
305
+ self.wqkv = nn.Linear(
306
+ self.hidden_size,
307
+ (self.num_heads + 2 * self.num_key_value_heads) * self.head_dim,
308
+ bias=config.bias,
309
+ )
310
+
311
+ self.wo = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.bias)
312
+ self._init_rope()
313
+
314
+ def _init_rope(self):
315
+ if self.config.rope_scaling is None:
316
+ self.rotary_emb = InternLM2RotaryEmbedding(
317
+ self.head_dim,
318
+ max_position_embeddings=self.max_position_embeddings,
319
+ base=self.config.rope_theta,
320
+ )
321
+ else:
322
+ scaling_type = self.config.rope_scaling["type"]
323
+ scaling_factor = self.config.rope_scaling["factor"]
324
+ if scaling_type == "dynamic":
325
+ self.rotary_emb = InternLM2DynamicNTKScalingRotaryEmbedding(
326
+ self.head_dim,
327
+ max_position_embeddings=self.max_position_embeddings,
328
+ base=self.config.rope_theta,
329
+ scaling_factor=scaling_factor,
330
+ )
331
+ elif scaling_type == "linear":
332
+ self.rotary_emb = InternLM2LinearScalingRotaryEmbedding(
333
+ self.head_dim,
334
+ max_position_embeddings=self.max_position_embeddings,
335
+ base=self.config.rope_theta,
336
+ scaling_factor=scaling_factor,
337
+ )
338
+ else:
339
+ raise ValueError("Currently we only support rotary embedding's type being 'dynamic' or 'linear'.")
340
+ return self.rotary_emb
341
+
342
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
343
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
344
+
345
+ def forward(
346
+ self,
347
+ hidden_states: torch.Tensor,
348
+ attention_mask: Optional[torch.Tensor] = None,
349
+ position_ids: Optional[torch.LongTensor] = None,
350
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
351
+ output_attentions: bool = False,
352
+ use_cache: bool = False,
353
+ **kwargs,
354
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
355
+ if "padding_mask" in kwargs:
356
+ warnings.warn(
357
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. "
358
+ "Please make sure use `attention_mask` instead.`"
359
+ )
360
+
361
+ bsz, q_len, _ = hidden_states.size()
362
+
363
+ qkv_states = self.wqkv(hidden_states)
364
+
365
+ qkv_states = rearrange(
366
+ qkv_states,
367
+ "b q (h gs d) -> b q h gs d",
368
+ gs=2 + self.num_key_value_groups,
369
+ d=self.head_dim,
370
+ )
371
+
372
+ query_states = qkv_states[..., : self.num_key_value_groups, :]
373
+ query_states = rearrange(query_states, "b q h gs d -> b q (h gs) d")
374
+ key_states = qkv_states[..., -2, :]
375
+ value_states = qkv_states[..., -1, :]
376
+
377
+ query_states = query_states.transpose(1, 2)
378
+ key_states = key_states.transpose(1, 2)
379
+ value_states = value_states.transpose(1, 2)
380
+
381
+ kv_seq_len = key_states.shape[-2]
382
+ if past_key_value is not None:
383
+ kv_seq_len += past_key_value[0].shape[-2]
384
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
385
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
386
+
387
+ if past_key_value is not None:
388
+ # reuse k, v, self_attention
389
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
390
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
391
+
392
+ past_key_value = (key_states, value_states) if use_cache else None
393
+
394
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
395
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
396
+
397
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
398
+
399
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
400
+ raise ValueError(
401
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
402
+ f" {attn_weights.size()}"
403
+ )
404
+
405
+ if attention_mask is not None:
406
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
407
+ raise ValueError(
408
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
409
+ )
410
+ attn_weights = attn_weights + attention_mask
411
+
412
+ # upcast attention to fp32
413
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
414
+ attn_output = torch.matmul(attn_weights, value_states)
415
+
416
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
417
+ raise ValueError(
418
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
419
+ f" {attn_output.size()}"
420
+ )
421
+
422
+ attn_output = attn_output.transpose(1, 2).contiguous()
423
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
424
+
425
+ attn_output = self.wo(attn_output)
426
+
427
+ if not output_attentions:
428
+ attn_weights = None
429
+
430
+ return attn_output, attn_weights, past_key_value
431
+
432
+
433
+ # Modified from transformers.model.llama.modeling_llama.InternLM2FlashAttention2
434
+ class InternLM2FlashAttention2(InternLM2Attention):
435
+ """
436
+ InternLM2 flash attention module. This module inherits from `InternLM2Attention` as the weights of the module stays
437
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
438
+ flash attention and deal with padding tokens in case the input contains any of them.
439
+ """
440
+
441
+ def forward(
442
+ self,
443
+ hidden_states: torch.Tensor,
444
+ attention_mask: Optional[torch.LongTensor] = None,
445
+ position_ids: Optional[torch.LongTensor] = None,
446
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
447
+ output_attentions: bool = False,
448
+ use_cache: bool = False,
449
+ **kwargs,
450
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
451
+ # InternLM2FlashAttention2 attention does not support output_attentions
452
+ if "padding_mask" in kwargs:
453
+ warnings.warn(
454
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. "
455
+ "Please make sure use `attention_mask` instead.`"
456
+ )
457
+
458
+ # overwrite attention_mask with padding_mask
459
+ attention_mask = kwargs.pop("padding_mask")
460
+
461
+ output_attentions = False
462
+
463
+ bsz, q_len, _ = hidden_states.size()
464
+
465
+ qkv_states = self.wqkv(hidden_states)
466
+
467
+ qkv_states = rearrange(
468
+ qkv_states,
469
+ "b q (h gs d) -> b q h gs d",
470
+ gs=2 + self.num_key_value_groups,
471
+ d=self.head_dim,
472
+ )
473
+
474
+ query_states = qkv_states[..., : self.num_key_value_groups, :]
475
+ query_states = rearrange(query_states, "b q h gs d -> b q (h gs) d")
476
+ key_states = qkv_states[..., -2, :]
477
+ value_states = qkv_states[..., -1, :]
478
+
479
+ query_states = query_states.transpose(1, 2)
480
+ key_states = key_states.transpose(1, 2)
481
+ value_states = value_states.transpose(1, 2)
482
+
483
+ kv_seq_len = key_states.shape[-2]
484
+ if past_key_value is not None:
485
+ kv_seq_len += past_key_value[0].shape[-2]
486
+
487
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
488
+
489
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
490
+
491
+ if past_key_value is not None:
492
+ # reuse k, v, self_attention
493
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
494
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
495
+
496
+ past_key_value = (key_states, value_states) if use_cache else None
497
+
498
+ query_states = query_states.transpose(1, 2)
499
+ key_states = key_states.transpose(1, 2)
500
+ value_states = value_states.transpose(1, 2)
501
+
502
+ attn_output = self._flash_attention_forward(query_states, key_states, value_states, attention_mask, q_len)
503
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
504
+ attn_output = self.wo(attn_output)
505
+
506
+ if not output_attentions:
507
+ attn_weights = None
508
+
509
+ return attn_output, attn_weights, past_key_value
510
+
511
+ def _flash_attention_forward(
512
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
513
+ ):
514
+ """
515
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
516
+ first unpad the input, then computes the attention scores and pad the final attention scores.
517
+
518
+ Args:
519
+ query_states (`torch.Tensor`):
520
+ Input query states to be passed to Flash Attention API
521
+ key_states (`torch.Tensor`):
522
+ Input key states to be passed to Flash Attention API
523
+ value_states (`torch.Tensor`):
524
+ Input value states to be passed to Flash Attention API
525
+ attention_mask (`torch.Tensor`):
526
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
527
+ position of padding tokens and 1 for the position of non-padding tokens.
528
+ dropout (`int`, *optional*):
529
+ Attention dropout
530
+ softmax_scale (`float`, *optional*):
531
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
532
+ """
533
+ # Contains at least one padding token in the sequence
534
+ causal = self.is_causal and query_length != 1
535
+ if attention_mask is not None:
536
+ batch_size = query_states.shape[0]
537
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._unpad_input(
538
+ query_states, key_states, value_states, attention_mask, query_length
539
+ )
540
+
541
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
542
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
543
+
544
+ attn_output_unpad = flash_attn_varlen_func(
545
+ query_states,
546
+ key_states,
547
+ value_states,
548
+ cu_seqlens_q=cu_seqlens_q,
549
+ cu_seqlens_k=cu_seqlens_k,
550
+ max_seqlen_q=max_seqlen_in_batch_q,
551
+ max_seqlen_k=max_seqlen_in_batch_k,
552
+ dropout_p=dropout,
553
+ softmax_scale=softmax_scale,
554
+ causal=causal,
555
+ )
556
+
557
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
558
+ else:
559
+ attn_output = flash_attn_func(
560
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
561
+ )
562
+
563
+ return attn_output
564
+
565
+ def _unpad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
566
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
567
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
568
+
569
+ key_layer = index_first_axis(
570
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
571
+ )
572
+ value_layer = index_first_axis(
573
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
574
+ )
575
+
576
+ if query_length == kv_seq_len:
577
+ query_layer = index_first_axis(
578
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
579
+ )
580
+ cu_seqlens_q = cu_seqlens_k
581
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
582
+ indices_q = indices_k
583
+ elif query_length == 1:
584
+ max_seqlen_in_batch_q = 1
585
+ cu_seqlens_q = torch.arange(
586
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
587
+ ) # There is a memcpy here, that is very bad.
588
+ indices_q = cu_seqlens_q[:-1]
589
+ query_layer = query_layer.squeeze(1)
590
+ else:
591
+ # The -q_len: slice assumes left padding.
592
+ attention_mask = attention_mask[:, -query_length:]
593
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
594
+
595
+ return (
596
+ query_layer,
597
+ key_layer,
598
+ value_layer,
599
+ indices_q.to(torch.int64),
600
+ (cu_seqlens_q, cu_seqlens_k),
601
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
602
+ )
603
+
604
+
605
+ INTERNLM2_ATTENTION_CLASSES = {
606
+ "eager": InternLM2Attention,
607
+ "flash_attention_2": InternLM2FlashAttention2,
608
+ }
609
+
610
+
611
+ # Modified from transformers.model.llama.modeling_llama.LlamaDecoderLayer
612
+ class InternLM2DecoderLayer(nn.Module):
613
+ """
614
+ InternLM2 decoder layer.
615
+ """
616
+
617
+ def __init__(self, config: InternLM2Config):
618
+ super().__init__()
619
+ self.hidden_size = config.hidden_size
620
+
621
+ self.attention = INTERNLM2_ATTENTION_CLASSES[config.attn_implementation](config=config)
622
+
623
+ self.feed_forward = InternLM2MLP(config)
624
+ self.attention_norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
625
+ self.ffn_norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
626
+
627
+ def forward(
628
+ self,
629
+ hidden_states: torch.Tensor,
630
+ attention_mask: Optional[torch.Tensor] = None,
631
+ position_ids: Optional[torch.LongTensor] = None,
632
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
633
+ output_attentions: Optional[bool] = False,
634
+ use_cache: Optional[bool] = False,
635
+ **kwargs,
636
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
637
+ """
638
+ Args:
639
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
640
+ attention_mask (`torch.FloatTensor`, *optional*):
641
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
642
+ query_sequence_length, key_sequence_length)` if default attention is used.
643
+ output_attentions (`bool`, *optional*):
644
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
645
+ returned tensors for more detail.
646
+ use_cache (`bool`, *optional*):
647
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
648
+ (see `past_key_values`).
649
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
650
+ """
651
+ if "padding_mask" in kwargs:
652
+ warnings.warn(
653
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. "
654
+ "Please make sure use `attention_mask` instead.`"
655
+ )
656
+
657
+ residual = hidden_states
658
+
659
+ hidden_states = self.attention_norm(hidden_states)
660
+
661
+ # Self Attention
662
+ hidden_states, self_attn_weights, present_key_value = self.attention(
663
+ hidden_states=hidden_states,
664
+ attention_mask=attention_mask,
665
+ position_ids=position_ids,
666
+ past_key_value=past_key_value,
667
+ output_attentions=output_attentions,
668
+ use_cache=use_cache,
669
+ **kwargs,
670
+ )
671
+ hidden_states = residual + hidden_states
672
+
673
+ # Fully Connected
674
+ residual = hidden_states
675
+ hidden_states = self.ffn_norm(hidden_states)
676
+ hidden_states = self.feed_forward(hidden_states)
677
+ hidden_states = residual + hidden_states
678
+
679
+ outputs = (hidden_states,)
680
+
681
+ if output_attentions:
682
+ outputs += (self_attn_weights,)
683
+
684
+ if use_cache:
685
+ outputs += (present_key_value,)
686
+
687
+ return outputs
688
+
689
+
690
+ InternLM2_START_DOCSTRING = r"""
691
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
692
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
693
+ etc.)
694
+
695
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
696
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
697
+ and behavior.
698
+
699
+ Parameters:
700
+ config ([`InternLM2Config`]):
701
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
702
+ load the weights associated with the model, only the configuration. Check out the
703
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
704
+ """
705
+
706
+
707
+ # Copied from transformers.models.llama.modeling_llama.LlamaPreTrainedModel with Llama->InternLM2
708
+ @add_start_docstrings(
709
+ "The bare InternLM2 Model outputting raw hidden-states without any specific head on top.",
710
+ InternLM2_START_DOCSTRING,
711
+ )
712
+ class InternLM2PreTrainedModel(PreTrainedModel):
713
+ """
714
+ InternLM2 pretraiend model's base class.
715
+ """
716
+
717
+ config_class = InternLM2Config
718
+ base_model_prefix = "model"
719
+ supports_gradient_checkpointing = True
720
+ _no_split_modules = ["InternLM2DecoderLayer"]
721
+ _skip_keys_device_placement = "past_key_values"
722
+
723
+ def _init_weights(self, module):
724
+ std = self.config.initializer_range
725
+ if isinstance(module, nn.Linear):
726
+ module.weight.data.normal_(mean=0.0, std=std)
727
+ if module.bias is not None:
728
+ module.bias.data.zero_()
729
+ elif isinstance(module, nn.Embedding):
730
+ module.weight.data.normal_(mean=0.0, std=std)
731
+ if module.padding_idx is not None:
732
+ module.weight.data[module.padding_idx].zero_()
733
+
734
+
735
+ InternLM2_INPUTS_DOCSTRING = r"""
736
+ Args:
737
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
738
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
739
+ it.
740
+
741
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
742
+ [`PreTrainedTokenizer.__call__`] for details.
743
+
744
+ [What are input IDs?](../glossary#input-ids)
745
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
746
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
747
+
748
+ - 1 for tokens that are **not masked**,
749
+ - 0 for tokens that are **masked**.
750
+
751
+ [What are attention masks?](../glossary#attention-mask)
752
+
753
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
754
+ [`PreTrainedTokenizer.__call__`] for details.
755
+
756
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
757
+ `past_key_values`).
758
+
759
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
760
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
761
+ information on the default strategy.
762
+
763
+ - 1 indicates the head is **not masked**,
764
+ - 0 indicates the head is **masked**.
765
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
766
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
767
+ config.n_positions - 1]`.
768
+
769
+ [What are position IDs?](../glossary#position-ids)
770
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or
771
+ when `config.use_cache=True`):
772
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
773
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
774
+ `(batch_size, num_heads, decoder_sequence_length, embed_size_per_head)`.
775
+
776
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
777
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
778
+
779
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
780
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
781
+ of shape `(batch_size, sequence_length)`.
782
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
783
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
784
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
785
+ model's internal embedding lookup matrix.
786
+ use_cache (`bool`, *optional*):
787
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
788
+ `past_key_values`).
789
+ output_attentions (`bool`, *optional*):
790
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
791
+ tensors for more detail.
792
+ output_hidden_states (`bool`, *optional*):
793
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
794
+ more detail.
795
+ return_dict (`bool`, *optional*):
796
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
797
+ """
798
+
799
+
800
+ # Modified from transformers.model.llama.modeling_llama.LlamaModel
801
+ @add_start_docstrings(
802
+ "The bare InternLM2 Model outputting raw hidden-states without any specific head on top.",
803
+ InternLM2_START_DOCSTRING,
804
+ )
805
+ class InternLM2Model(InternLM2PreTrainedModel):
806
+ """
807
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`InternLM2DecoderLayer`]
808
+
809
+ Args:
810
+ config: InternLM2Config
811
+ """
812
+
813
+ _auto_class = "AutoModel"
814
+
815
+ def __init__(self, config: InternLM2Config):
816
+ super().__init__(config)
817
+ self.padding_idx = config.pad_token_id
818
+ self.vocab_size = config.vocab_size
819
+ self.config = config
820
+
821
+ self.tok_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
822
+
823
+ self.layers = nn.ModuleList([InternLM2DecoderLayer(config) for _ in range(config.num_hidden_layers)])
824
+ self.norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
825
+
826
+ self.gradient_checkpointing = False
827
+ # Initialize weights and apply final processing
828
+ self.post_init()
829
+
830
+ def get_input_embeddings(self):
831
+ return self.tok_embeddings
832
+
833
+ def set_input_embeddings(self, value):
834
+ self.tok_embeddings = value
835
+
836
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
837
+ # create causal mask
838
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
839
+ combined_attention_mask = None
840
+ if input_shape[-1] > 1:
841
+ combined_attention_mask = _make_causal_mask(
842
+ input_shape,
843
+ inputs_embeds.dtype,
844
+ device=inputs_embeds.device,
845
+ past_key_values_length=past_key_values_length,
846
+ )
847
+
848
+ if attention_mask is not None:
849
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
850
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
851
+ inputs_embeds.device
852
+ )
853
+ combined_attention_mask = (
854
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
855
+ )
856
+
857
+ return combined_attention_mask
858
+
859
+ @add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
860
+ def forward(
861
+ self,
862
+ input_ids: torch.LongTensor = None,
863
+ attention_mask: Optional[torch.Tensor] = None,
864
+ position_ids: Optional[torch.LongTensor] = None,
865
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
866
+ inputs_embeds: Optional[torch.FloatTensor] = None,
867
+ use_cache: Optional[bool] = None,
868
+ output_attentions: Optional[bool] = None,
869
+ output_hidden_states: Optional[bool] = None,
870
+ return_dict: Optional[bool] = None,
871
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
872
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
873
+ output_hidden_states = (
874
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
875
+ )
876
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
877
+
878
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
879
+
880
+ if self.config.attn_implementation == "flash_attention_2":
881
+ _import_flash_attn()
882
+
883
+ # retrieve input_ids and inputs_embeds
884
+ if input_ids is not None and inputs_embeds is not None:
885
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
886
+ elif input_ids is not None:
887
+ batch_size, seq_length = input_ids.shape[:2]
888
+ elif inputs_embeds is not None:
889
+ batch_size, seq_length = inputs_embeds.shape[:2]
890
+ else:
891
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
892
+
893
+ seq_length_with_past = seq_length
894
+ past_key_values_length = 0
895
+ if past_key_values is not None:
896
+ past_key_values_length = past_key_values[0][0].shape[2]
897
+ seq_length_with_past = seq_length_with_past + past_key_values_length
898
+
899
+ if position_ids is None:
900
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
901
+ position_ids = torch.arange(
902
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
903
+ )
904
+ position_ids = position_ids.unsqueeze(0)
905
+
906
+ if inputs_embeds is None:
907
+ inputs_embeds = self.tok_embeddings(input_ids)
908
+
909
+ if self.config.attn_implementation == "flash_attention_2":
910
+ # 2d mask is passed through the layers
911
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
912
+ else:
913
+ if attention_mask is None:
914
+ attention_mask = torch.ones(
915
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
916
+ )
917
+ attention_mask = self._prepare_decoder_attention_mask(
918
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
919
+ )
920
+
921
+ # embed positions
922
+ hidden_states = inputs_embeds
923
+
924
+ if self.gradient_checkpointing and self.training:
925
+ if use_cache:
926
+ logger.warning_once(
927
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
928
+ )
929
+ use_cache = False
930
+
931
+ # decoder layers
932
+ all_hidden_states = () if output_hidden_states else None
933
+ all_self_attns = () if output_attentions else None
934
+ next_decoder_cache = () if use_cache else None
935
+
936
+ for idx, decoder_layer in enumerate(self.layers):
937
+ if output_hidden_states:
938
+ all_hidden_states += (hidden_states,)
939
+
940
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
941
+
942
+ if self.gradient_checkpointing and self.training:
943
+
944
+ def create_custom_forward(module):
945
+ def custom_forward(*inputs):
946
+ # None for past_key_value
947
+ return module(*inputs, output_attentions, None)
948
+
949
+ return custom_forward
950
+
951
+ layer_outputs = torch.utils.checkpoint.checkpoint(
952
+ create_custom_forward(decoder_layer),
953
+ hidden_states,
954
+ attention_mask,
955
+ position_ids,
956
+ None,
957
+ )
958
+ else:
959
+ layer_outputs = decoder_layer(
960
+ hidden_states,
961
+ attention_mask=attention_mask,
962
+ position_ids=position_ids,
963
+ past_key_value=past_key_value,
964
+ output_attentions=output_attentions,
965
+ use_cache=use_cache,
966
+ )
967
+
968
+ hidden_states = layer_outputs[0]
969
+
970
+ if use_cache:
971
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
972
+
973
+ if output_attentions:
974
+ all_self_attns += (layer_outputs[1],)
975
+
976
+ hidden_states = self.norm(hidden_states)
977
+
978
+ # add hidden states from the last decoder layer
979
+ if output_hidden_states:
980
+ all_hidden_states += (hidden_states,)
981
+
982
+ next_cache = next_decoder_cache if use_cache else None
983
+ if not return_dict:
984
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
985
+ return BaseModelOutputWithPast(
986
+ last_hidden_state=hidden_states,
987
+ past_key_values=next_cache,
988
+ hidden_states=all_hidden_states,
989
+ attentions=all_self_attns,
990
+ )
991
+
992
+
993
+ # Modified from transformers.model.llama.modeling_llama.LlamaForCausalLM
994
+ class InternLM2ForCausalLM(InternLM2PreTrainedModel):
995
+ """
996
+ InternLM2 causal language model.
997
+ """
998
+
999
+ _auto_class = "AutoModelForCausalLM"
1000
+
1001
+ _tied_weights_keys = ["output.weight"]
1002
+
1003
+ def __init__(self, config):
1004
+ super().__init__(config)
1005
+ self.model = InternLM2Model(config)
1006
+ self.vocab_size = config.vocab_size
1007
+ self.output = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1008
+
1009
+ # Initialize weights and apply final processing
1010
+ self.post_init()
1011
+
1012
+ def get_input_embeddings(self):
1013
+ return self.model.tok_embeddings
1014
+
1015
+ def set_input_embeddings(self, value):
1016
+ self.model.tok_embeddings = value
1017
+
1018
+ def get_output_embeddings(self):
1019
+ return self.output
1020
+
1021
+ def set_output_embeddings(self, new_embeddings):
1022
+ self.output = new_embeddings
1023
+
1024
+ def set_decoder(self, decoder):
1025
+ self.model = decoder
1026
+
1027
+ def get_decoder(self):
1028
+ return self.model
1029
+
1030
+ @add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
1031
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1032
+ def forward(
1033
+ self,
1034
+ input_ids: torch.LongTensor = None,
1035
+ attention_mask: Optional[torch.Tensor] = None,
1036
+ position_ids: Optional[torch.LongTensor] = None,
1037
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1038
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1039
+ labels: Optional[torch.LongTensor] = None,
1040
+ use_cache: Optional[bool] = None,
1041
+ output_attentions: Optional[bool] = None,
1042
+ output_hidden_states: Optional[bool] = None,
1043
+ return_dict: Optional[bool] = None,
1044
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1045
+ r"""
1046
+ Args:
1047
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1048
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1049
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1050
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1051
+
1052
+ Returns:
1053
+
1054
+ Example:
1055
+
1056
+ ```python
1057
+ >>> from transformers import AutoTokenizer, InternLM2ForCausalLM
1058
+
1059
+ >>> model = InternLM2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1060
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1061
+
1062
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1063
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1064
+
1065
+ >>> # Generate
1066
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1067
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1068
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1069
+ ```"""
1070
+
1071
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1072
+ output_hidden_states = (
1073
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1074
+ )
1075
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1076
+
1077
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1078
+ outputs = self.model(
1079
+ input_ids=input_ids,
1080
+ attention_mask=attention_mask,
1081
+ position_ids=position_ids,
1082
+ past_key_values=past_key_values,
1083
+ inputs_embeds=inputs_embeds,
1084
+ use_cache=use_cache,
1085
+ output_attentions=output_attentions,
1086
+ output_hidden_states=output_hidden_states,
1087
+ return_dict=return_dict,
1088
+ )
1089
+
1090
+ hidden_states = outputs[0]
1091
+ logits = self.output(hidden_states)
1092
+ logits = logits.float()
1093
+
1094
+ loss = None
1095
+ if labels is not None:
1096
+ # Shift so that tokens < n predict n
1097
+ shift_logits = logits[..., :-1, :].contiguous()
1098
+ shift_labels = labels[..., 1:].contiguous()
1099
+ # Flatten the tokens
1100
+ loss_fct = CrossEntropyLoss()
1101
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1102
+ shift_labels = shift_labels.view(-1)
1103
+ # Enable model parallelism
1104
+ shift_labels = shift_labels.to(shift_logits.device)
1105
+ loss = loss_fct(shift_logits, shift_labels)
1106
+
1107
+ if not return_dict:
1108
+ output = (logits,) + outputs[1:]
1109
+ return (loss,) + output if loss is not None else output
1110
+
1111
+ return CausalLMOutputWithPast(
1112
+ loss=loss,
1113
+ logits=logits,
1114
+ past_key_values=outputs.past_key_values,
1115
+ hidden_states=outputs.hidden_states,
1116
+ attentions=outputs.attentions,
1117
+ )
1118
+
1119
+ def prepare_inputs_for_generation(
1120
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1121
+ ):
1122
+ if past_key_values is not None:
1123
+ past_length = past_key_values[0][0].shape[2]
1124
+
1125
+ # Some generation methods already pass only the last input ID
1126
+ if input_ids.shape[1] > past_length:
1127
+ remove_prefix_length = past_length
1128
+ else:
1129
+ # Default to old behavior: keep only final ID
1130
+ remove_prefix_length = input_ids.shape[1] - 1
1131
+
1132
+ input_ids = input_ids[:, remove_prefix_length:]
1133
+
1134
+ position_ids = kwargs.get("position_ids", None)
1135
+ if attention_mask is not None and position_ids is None:
1136
+ # create position_ids on the fly for batch generation
1137
+ position_ids = attention_mask.long().cumsum(-1) - 1
1138
+ position_ids.masked_fill_(attention_mask == 0, 1)
1139
+ if past_key_values:
1140
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1141
+
1142
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1143
+ if inputs_embeds is not None and past_key_values is None:
1144
+ model_inputs = {"inputs_embeds": inputs_embeds}
1145
+ else:
1146
+ model_inputs = {"input_ids": input_ids}
1147
+
1148
+ model_inputs.update(
1149
+ {
1150
+ "position_ids": position_ids,
1151
+ "past_key_values": past_key_values,
1152
+ "use_cache": kwargs.get("use_cache"),
1153
+ "attention_mask": attention_mask,
1154
+ }
1155
+ )
1156
+ return model_inputs
1157
+
1158
+ @staticmethod
1159
+ def _reorder_cache(past_key_values, beam_idx):
1160
+ reordered_past = ()
1161
+ for layer_past in past_key_values:
1162
+ reordered_past += (
1163
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1164
+ )
1165
+ return reordered_past
1166
+
1167
+ def build_inputs(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, meta_instruction=""):
1168
+ if history is None:
1169
+ history = []
1170
+ if tokenizer.add_bos_token:
1171
+ prompt = ""
1172
+ else:
1173
+ prompt = tokenizer.bos_token
1174
+ if meta_instruction:
1175
+ prompt += f"""<|im_start|>system\n{meta_instruction}<|im_end|>\n"""
1176
+ for record in history:
1177
+ prompt += f"""<|im_start|>user\n{record[0]}<|im_end|>\n<|im_start|>assistant\n{record[1]}<|im_end|>\n"""
1178
+ prompt += f"""<|im_start|>user\n{query}<|im_end|>\n<|im_start|>assistant\n"""
1179
+ return tokenizer([prompt], return_tensors="pt")
1180
+
1181
+ @torch.no_grad()
1182
+ def chat(
1183
+ self,
1184
+ tokenizer,
1185
+ query: str,
1186
+ history: Optional[List[Tuple[str, str]]] = None,
1187
+ streamer: Optional[BaseStreamer] = None,
1188
+ max_new_tokens: int = 1024,
1189
+ do_sample: bool = True,
1190
+ temperature: float = 0.8,
1191
+ top_p: float = 0.8,
1192
+ meta_instruction: str = "You are an AI assistant whose name is InternLM (书生·浦语).\n"
1193
+ "- InternLM (书生·浦语) is a conversational language model that is developed by Shanghai AI Laboratory "
1194
+ "(上海人工智能实验室). It is designed to be helpful, honest, and harmless.\n"
1195
+ "- InternLM (书生·浦语) can understand and communicate fluently in the language chosen by the user such "
1196
+ "as English and 中文.",
1197
+ **kwargs,
1198
+ ):
1199
+ if history is None:
1200
+ history = []
1201
+ inputs = self.build_inputs(tokenizer, query, history, meta_instruction)
1202
+ inputs = {k: v.to(self.device) for k, v in inputs.items() if torch.is_tensor(v)}
1203
+ # also add end-of-assistant token in eos token id to avoid unnecessary generation
1204
+ eos_token_id = [tokenizer.eos_token_id, tokenizer.convert_tokens_to_ids(["<|im_end|>"])[0]]
1205
+ outputs = self.generate(
1206
+ **inputs,
1207
+ streamer=streamer,
1208
+ max_new_tokens=max_new_tokens,
1209
+ do_sample=do_sample,
1210
+ temperature=temperature,
1211
+ top_p=top_p,
1212
+ eos_token_id=eos_token_id,
1213
+ **kwargs,
1214
+ )
1215
+ outputs = outputs[0].cpu().tolist()[len(inputs["input_ids"][0]) :]
1216
+ response = tokenizer.decode(outputs, skip_special_tokens=True)
1217
+ response = response.split("<|im_end|>")[0]
1218
+ history = history + [(query, response)]
1219
+ return response, history
1220
+
1221
+ @torch.no_grad()
1222
+ def stream_chat(
1223
+ self,
1224
+ tokenizer,
1225
+ query: str,
1226
+ history: List[Tuple[str, str]] = None,
1227
+ max_new_tokens: int = 1024,
1228
+ do_sample: bool = True,
1229
+ temperature: float = 0.8,
1230
+ top_p: float = 0.8,
1231
+ **kwargs,
1232
+ ):
1233
+ if history is None:
1234
+ history = []
1235
+ """
1236
+ Return a generator in format: (response, history)
1237
+ Eg.
1238
+ ('你好,有什么可以帮助您的吗', [('你好', '你好,有什么可以帮助您的吗')])
1239
+ ('你好,有什么可以帮助您的吗?', [('你好', '你好,有什么可以帮助您的吗?')])
1240
+ """
1241
+ if BaseStreamer is None:
1242
+ raise ModuleNotFoundError(
1243
+ "The version of `transformers` is too low. Please make sure "
1244
+ "that you have installed `transformers>=4.28.0`."
1245
+ )
1246
+
1247
+ response_queue = queue.Queue(maxsize=20)
1248
+
1249
+ class ChatStreamer(BaseStreamer):
1250
+ """
1251
+ Streamer used in generate to print words one by one.
1252
+ """
1253
+
1254
+ def __init__(self, tokenizer) -> None:
1255
+ super().__init__()
1256
+ self.tokenizer = tokenizer
1257
+ self.queue = response_queue
1258
+ self.query = query
1259
+ self.history = history
1260
+ self.response = ""
1261
+ self.cache = []
1262
+ self.received_inputs = False
1263
+ self.queue.put((self.response, history + [(self.query, self.response)]))
1264
+
1265
+ def put(self, value):
1266
+ if len(value.shape) > 1 and value.shape[0] > 1:
1267
+ raise ValueError("ChatStreamer only supports batch size 1")
1268
+ elif len(value.shape) > 1:
1269
+ value = value[0]
1270
+
1271
+ if not self.received_inputs:
1272
+ # The first received value is input_ids, ignore here
1273
+ self.received_inputs = True
1274
+ return
1275
+
1276
+ self.cache.extend(value.tolist())
1277
+ token = self.tokenizer.decode(self.cache, skip_special_tokens=True)
1278
+ if token.strip() != "<|im_end|>":
1279
+ self.response = self.response + token
1280
+ history = self.history + [(self.query, self.response)]
1281
+ self.queue.put((self.response, history))
1282
+ self.cache = []
1283
+ else:
1284
+ self.end()
1285
+
1286
+ def end(self):
1287
+ self.queue.put(None)
1288
+
1289
+ def stream_producer():
1290
+ return self.chat(
1291
+ tokenizer=tokenizer,
1292
+ query=query,
1293
+ streamer=ChatStreamer(tokenizer=tokenizer),
1294
+ history=history,
1295
+ max_new_tokens=max_new_tokens,
1296
+ do_sample=do_sample,
1297
+ temperature=temperature,
1298
+ top_p=top_p,
1299
+ **kwargs,
1300
+ )
1301
+
1302
+ def consumer():
1303
+ producer = threading.Thread(target=stream_producer)
1304
+ producer.start()
1305
+ while True:
1306
+ res = response_queue.get()
1307
+ if res is None:
1308
+ return
1309
+ yield res
1310
+
1311
+ return consumer()
1312
+
1313
+
1314
+ # Copied from transformers.model.llama.modeling_llama.LlamaForSequenceClassification with Llama->InternLM2
1315
+ @add_start_docstrings(
1316
+ """
1317
+ The InternLM2 Model transformer with a sequence classification head on top (linear layer).
1318
+
1319
+ [`InternLM2ForSequenceClassification`] uses the last token in order to do the classification,
1320
+ as other causal models (e.g. GPT-2) do.
1321
+
1322
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1323
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1324
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1325
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1326
+ each row of the batch).
1327
+ """,
1328
+ InternLM2_START_DOCSTRING,
1329
+ )
1330
+ class InternLM2ForSequenceClassification(InternLM2PreTrainedModel):
1331
+ """
1332
+ InternLM2 sequence classification model.
1333
+ """
1334
+
1335
+ def __init__(self, config):
1336
+ super().__init__(config)
1337
+ self.num_labels = config.num_labels
1338
+ self.model = InternLM2Model(config)
1339
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1340
+
1341
+ # Initialize weights and apply final processing
1342
+ self.post_init()
1343
+
1344
+ def get_input_embeddings(self):
1345
+ return self.model.tok_embeddings
1346
+
1347
+ def set_input_embeddings(self, value):
1348
+ self.model.tok_embeddings = value
1349
+
1350
+ @add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
1351
+ def forward(
1352
+ self,
1353
+ input_ids: torch.LongTensor = None,
1354
+ attention_mask: Optional[torch.Tensor] = None,
1355
+ position_ids: Optional[torch.LongTensor] = None,
1356
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1357
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1358
+ labels: Optional[torch.LongTensor] = None,
1359
+ use_cache: Optional[bool] = None,
1360
+ output_attentions: Optional[bool] = None,
1361
+ output_hidden_states: Optional[bool] = None,
1362
+ return_dict: Optional[bool] = None,
1363
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1364
+ r"""
1365
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1366
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1367
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1368
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1369
+ """
1370
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1371
+
1372
+ transformer_outputs = self.model(
1373
+ input_ids,
1374
+ attention_mask=attention_mask,
1375
+ position_ids=position_ids,
1376
+ past_key_values=past_key_values,
1377
+ inputs_embeds=inputs_embeds,
1378
+ use_cache=use_cache,
1379
+ output_attentions=output_attentions,
1380
+ output_hidden_states=output_hidden_states,
1381
+ return_dict=return_dict,
1382
+ )
1383
+ hidden_states = transformer_outputs[0]
1384
+ logits = self.score(hidden_states)
1385
+
1386
+ if input_ids is not None:
1387
+ batch_size = input_ids.shape[0]
1388
+ else:
1389
+ batch_size = inputs_embeds.shape[0]
1390
+
1391
+ if self.config.pad_token_id is None and batch_size != 1:
1392
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1393
+ if self.config.pad_token_id is None:
1394
+ sequence_lengths = -1
1395
+ else:
1396
+ if input_ids is not None:
1397
+ sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1).to(
1398
+ logits.device
1399
+ )
1400
+ else:
1401
+ sequence_lengths = -1
1402
+
1403
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1404
+
1405
+ loss = None
1406
+ if labels is not None:
1407
+ labels = labels.to(logits.device)
1408
+ if self.config.problem_type is None:
1409
+ if self.num_labels == 1:
1410
+ self.config.problem_type = "regression"
1411
+
1412
+ elif self.num_labels > 1 and labels.dtype in (torch.long, torch.int):
1413
+ self.config.problem_type = "single_label_classification"
1414
+ else:
1415
+ self.config.problem_type = "multi_label_classification"
1416
+
1417
+ if self.config.problem_type == "regression":
1418
+ loss_fct = MSELoss()
1419
+ if self.num_labels == 1:
1420
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1421
+ else:
1422
+ loss = loss_fct(pooled_logits, labels)
1423
+ elif self.config.problem_type == "single_label_classification":
1424
+ loss_fct = CrossEntropyLoss()
1425
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1426
+ elif self.config.problem_type == "multi_label_classification":
1427
+ loss_fct = BCEWithLogitsLoss()
1428
+ loss = loss_fct(pooled_logits, labels)
1429
+ if not return_dict:
1430
+ output = (pooled_logits,) + transformer_outputs[1:]
1431
+ return ((loss,) + output) if loss is not None else output
1432
+
1433
+ return SequenceClassifierOutputWithPast(
1434
+ loss=loss,
1435
+ logits=pooled_logits,
1436
+ past_key_values=transformer_outputs.past_key_values,
1437
+ hidden_states=transformer_outputs.hidden_states,
1438
+ attentions=transformer_outputs.attentions,
1439
+ )
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_internlm2.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on transformers/src/transformers/models/llama/tokenization_llama.py
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """Tokenization classes for InternLM."""
19
+ import os
20
+ from shutil import copyfile
21
+ from typing import Any, Dict, List, Optional, Tuple
22
+
23
+ import sentencepiece as spm
24
+ from transformers.tokenization_utils import PreTrainedTokenizer
25
+ from transformers.utils import logging
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+ VOCAB_FILES_NAMES = {"vocab_file": "./tokenizer.model"}
30
+
31
+ PRETRAINED_VOCAB_FILES_MAP = {}
32
+
33
+
34
+ # Modified from transformers.model.llama.tokenization_llama.LlamaTokenizer
35
+ class InternLM2Tokenizer(PreTrainedTokenizer):
36
+ """
37
+ Construct a InternLM2 tokenizer. Based on byte-level Byte-Pair-Encoding.
38
+
39
+ Args:
40
+ vocab_file (`str`):
41
+ Path to the vocabulary file.
42
+ """
43
+
44
+ vocab_files_names = VOCAB_FILES_NAMES
45
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
46
+ model_input_names = ["input_ids", "attention_mask"]
47
+ _auto_class = "AutoTokenizer"
48
+
49
+ def __init__(
50
+ self,
51
+ vocab_file,
52
+ unk_token="<unk>",
53
+ bos_token="<s>",
54
+ eos_token="</s>",
55
+ pad_token="</s>",
56
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
57
+ add_bos_token=True,
58
+ add_eos_token=False,
59
+ decode_with_prefix_space=False,
60
+ clean_up_tokenization_spaces=False,
61
+ **kwargs,
62
+ ):
63
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
64
+ self.vocab_file = vocab_file
65
+ self.add_bos_token = add_bos_token
66
+ self.add_eos_token = add_eos_token
67
+ self.decode_with_prefix_space = decode_with_prefix_space
68
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
69
+ self.sp_model.Load(vocab_file)
70
+ self._no_prefix_space_tokens = None
71
+ super().__init__(
72
+ bos_token=bos_token,
73
+ eos_token=eos_token,
74
+ unk_token=unk_token,
75
+ pad_token=pad_token,
76
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
77
+ **kwargs,
78
+ )
79
+
80
+ @property
81
+ def no_prefix_space_tokens(self):
82
+ if self._no_prefix_space_tokens is None:
83
+ vocab = self.convert_ids_to_tokens(list(range(self.vocab_size)))
84
+ self._no_prefix_space_tokens = {i for i, tok in enumerate(vocab) if not tok.startswith("▁")}
85
+ return self._no_prefix_space_tokens
86
+
87
+ @property
88
+ def vocab_size(self):
89
+ """Returns vocab size"""
90
+ return self.sp_model.get_piece_size()
91
+
92
+ @property
93
+ def bos_token_id(self) -> Optional[int]:
94
+ return self.sp_model.bos_id()
95
+
96
+ @property
97
+ def eos_token_id(self) -> Optional[int]:
98
+ return self.sp_model.eos_id()
99
+
100
+ def get_vocab(self):
101
+ """Returns vocab as a dict"""
102
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
103
+ vocab.update(self.added_tokens_encoder)
104
+ return vocab
105
+
106
+ def _tokenize(self, text):
107
+ """Returns a tokenized string."""
108
+ return self.sp_model.encode(text, out_type=str)
109
+
110
+ def _convert_token_to_id(self, token):
111
+ """Converts a token (str) in an id using the vocab."""
112
+ return self.sp_model.piece_to_id(token)
113
+
114
+ def _convert_id_to_token(self, index):
115
+ """Converts an index (integer) in a token (str) using the vocab."""
116
+ token = self.sp_model.IdToPiece(index)
117
+ return token
118
+
119
+ def _maybe_add_prefix_space(self, tokens, decoded):
120
+ if tokens and tokens[0] not in self.no_prefix_space_tokens:
121
+ return " " + decoded
122
+ else:
123
+ return decoded
124
+
125
+ def convert_tokens_to_string(self, tokens):
126
+ """Converts a sequence of tokens (string) in a single string."""
127
+ current_sub_tokens = []
128
+ out_string = ""
129
+ prev_is_special = False
130
+ for token in tokens:
131
+ # make sure that special tokens are not decoded using sentencepiece model
132
+ if token in self.all_special_tokens:
133
+ if not prev_is_special:
134
+ out_string += " "
135
+ out_string += self.sp_model.decode(current_sub_tokens) + token
136
+ prev_is_special = True
137
+ current_sub_tokens = []
138
+ else:
139
+ current_sub_tokens.append(token)
140
+ prev_is_special = False
141
+ out_string += self.sp_model.decode(current_sub_tokens)
142
+ out_string = self.clean_up_tokenization(out_string)
143
+ out_string = self._maybe_add_prefix_space(tokens=tokens, decoded=out_string)
144
+ return out_string[1:]
145
+
146
+ def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
147
+ """
148
+ Save the vocabulary and special tokens file to a directory.
149
+
150
+ Args:
151
+ save_directory (`str`):
152
+ The directory in which to save the vocabulary.
153
+
154
+ Returns:
155
+ `Tuple(str)`: Paths to the files saved.
156
+ """
157
+ if not os.path.isdir(save_directory):
158
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
159
+ return
160
+ out_vocab_file = os.path.join(
161
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
162
+ )
163
+
164
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
165
+ copyfile(self.vocab_file, out_vocab_file)
166
+ elif not os.path.isfile(self.vocab_file):
167
+ with open(out_vocab_file, "wb") as fi:
168
+ content_spiece_model = self.sp_model.serialized_model_proto()
169
+ fi.write(content_spiece_model)
170
+
171
+ return (out_vocab_file,)
172
+
173
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
174
+ if self.add_bos_token:
175
+ bos_token_ids = [self.bos_token_id]
176
+ else:
177
+ bos_token_ids = []
178
+
179
+ output = bos_token_ids + token_ids_0
180
+
181
+ if token_ids_1 is not None:
182
+ output = output + token_ids_1
183
+
184
+ if self.add_eos_token:
185
+ output = output + [self.eos_token_id]
186
+
187
+ return output
188
+
189
+ def get_special_tokens_mask(
190
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
191
+ ) -> List[int]:
192
+ """
193
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
194
+ special tokens using the tokenizer `prepare_for_model` method.
195
+
196
+ Args:
197
+ token_ids_0 (`List[int]`):
198
+ List of IDs.
199
+ token_ids_1 (`List[int]`, *optional*):
200
+ Optional second list of IDs for sequence pairs.
201
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
202
+ Whether or not the token list is already formatted with special tokens for the model.
203
+
204
+ Returns:
205
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
206
+ """
207
+ if already_has_special_tokens:
208
+ return super().get_special_tokens_mask(
209
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
210
+ )
211
+
212
+ if token_ids_1 is None:
213
+ return [1] + ([0] * len(token_ids_0)) + [1]
214
+ return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
215
+
216
+ def create_token_type_ids_from_sequences(
217
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
218
+ ) -> List[int]:
219
+ """
220
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. T5 does not make
221
+ use of token type ids, therefore a list of zeros is returned.
222
+
223
+ Args:
224
+ token_ids_0 (`List[int]`):
225
+ List of IDs.
226
+ token_ids_1 (`List[int]`, *optional*):
227
+ Optional second list of IDs for sequence pairs.
228
+
229
+ Returns:
230
+ `List[int]`: List of zeros.
231
+ """
232
+ eos = [self.eos_token_id]
233
+
234
+ if token_ids_1 is None:
235
+ return len(token_ids_0 + eos) * [0]
236
+ return len(token_ids_0 + eos + token_ids_1 + eos) * [0]
tokenization_internlm2_fast.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on transformers/src/transformers/models/llama/tokenization_llama_fast.py
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """Tokenization Fast class for InternLM."""
19
+ import os
20
+ from shutil import copyfile
21
+ from typing import Any, Dict, Optional, Tuple
22
+
23
+ from tokenizers import Tokenizer, decoders, normalizers, processors
24
+ from tokenizers.models import BPE
25
+ from transformers.convert_slow_tokenizer import (
26
+ SLOW_TO_FAST_CONVERTERS,
27
+ SentencePieceExtractor,
28
+ SpmConverter,
29
+ )
30
+ from transformers.tokenization_utils_fast import PreTrainedTokenizerFast
31
+ from transformers.utils import logging
32
+
33
+ from .tokenization_internlm2 import InternLM2Tokenizer
34
+
35
+ logger = logging.get_logger(__name__)
36
+
37
+ VOCAB_FILES_NAMES = {"vocab_file": "./tokenizer.model"}
38
+
39
+
40
+ # Modified from transformers.convert_slow_tokenizer.LlamaConverter
41
+ class InternLM2Converter(SpmConverter):
42
+ """
43
+ Fast tokenizer converter for InternLM2.
44
+ """
45
+
46
+ handle_byte_fallback = True
47
+
48
+ def vocab(self, proto):
49
+ vocab = [
50
+ ("<unk>", 0.0),
51
+ ("<s>", 0.0),
52
+ ("</s>", 0.0),
53
+ ]
54
+ vocab += [(piece.piece, piece.score) for piece in proto.pieces[3:]]
55
+ return vocab
56
+
57
+ def unk_id(self, proto): # pylint: disable=W0613
58
+ unk_id = 0
59
+ return unk_id
60
+
61
+ def decoder(self, replacement, add_prefix_space): # pylint: disable=W0613
62
+ decoders_sequence = [
63
+ decoders.Replace("▁", " "),
64
+ decoders.ByteFallback(),
65
+ decoders.Fuse(),
66
+ ]
67
+ if self.proto.normalizer_spec.add_dummy_prefix:
68
+ decoders_sequence.append(decoders.Strip(content=" ", left=1))
69
+ return decoders.Sequence(decoders_sequence)
70
+
71
+ def tokenizer(self, proto):
72
+ model_type = proto.trainer_spec.model_type
73
+ vocab_scores = self.vocab(proto)
74
+ # special tokens
75
+ added_tokens = self.original_tokenizer.added_tokens_decoder
76
+ for i in range(len(vocab_scores)):
77
+ _, score = vocab_scores[i]
78
+ if i in added_tokens:
79
+ vocab_scores[i] = (added_tokens[i].content, score)
80
+ if model_type == 1:
81
+ raise RuntimeError("InternLM2 is supposed to be a BPE model!")
82
+
83
+ elif model_type == 2:
84
+ _, merges = SentencePieceExtractor(self.original_tokenizer.vocab_file).extract(vocab_scores)
85
+ bpe_vocab = {word: i for i, (word, _score) in enumerate(vocab_scores)}
86
+ tokenizer = Tokenizer(
87
+ BPE(bpe_vocab, merges, unk_token=proto.trainer_spec.unk_piece, fuse_unk=True, byte_fallback=True)
88
+ )
89
+ tokenizer.add_special_tokens([added_token for index, added_token in added_tokens.items()])
90
+ else:
91
+ raise Exception(
92
+ "You're trying to run a `Unigram` model but you're file was trained with a different algorithm"
93
+ )
94
+
95
+ return tokenizer
96
+
97
+ def normalizer(self, proto):
98
+ normalizers_list = []
99
+ if proto.normalizer_spec.add_dummy_prefix:
100
+ normalizers_list.append(normalizers.Prepend(prepend="▁"))
101
+ normalizers_list.append(normalizers.Replace(pattern=" ", content="▁"))
102
+ return normalizers.Sequence(normalizers_list)
103
+
104
+ def pre_tokenizer(self, replacement, add_prefix_space): # pylint: disable=W0613
105
+ return None
106
+
107
+
108
+ SLOW_TO_FAST_CONVERTERS["InternLM2Tokenizer"] = InternLM2Converter
109
+
110
+
111
+ # Modified from transformers.model.llama.tokenization_llama_fast.LlamaTokenizerFast -> InternLM2TokenizerFast
112
+ class InternLM2TokenizerFast(PreTrainedTokenizerFast):
113
+ """
114
+ Fast tokenizer for InternLM2.
115
+ """
116
+
117
+ vocab_files_names = VOCAB_FILES_NAMES
118
+ slow_tokenizer_class = InternLM2Tokenizer
119
+ padding_side = "left"
120
+ model_input_names = ["input_ids", "attention_mask"]
121
+ _auto_class = "AutoTokenizer"
122
+
123
+ def __init__(
124
+ self,
125
+ vocab_file,
126
+ unk_token="<unk>",
127
+ bos_token="<s>",
128
+ eos_token="</s>",
129
+ pad_token="</s>",
130
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
131
+ add_bos_token=True,
132
+ add_eos_token=False,
133
+ decode_with_prefix_space=False,
134
+ clean_up_tokenization_spaces=False,
135
+ **kwargs,
136
+ ):
137
+ super().__init__(
138
+ vocab_file=vocab_file,
139
+ unk_token=unk_token,
140
+ bos_token=bos_token,
141
+ eos_token=eos_token,
142
+ pad_token=pad_token,
143
+ sp_model_kwargs=sp_model_kwargs,
144
+ add_bos_token=add_bos_token,
145
+ add_eos_token=add_eos_token,
146
+ decode_with_prefix_space=decode_with_prefix_space,
147
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
148
+ **kwargs,
149
+ )
150
+ self._add_bos_token = add_bos_token
151
+ self._add_eos_token = add_eos_token
152
+ self.update_post_processor()
153
+ self.vocab_file = vocab_file
154
+
155
+ @property
156
+ def can_save_slow_tokenizer(self) -> bool:
157
+ return os.path.isfile(self.vocab_file) if self.vocab_file else False
158
+
159
+ def update_post_processor(self):
160
+ """
161
+ Updates the underlying post processor with the current `bos_token` and `eos_token`.
162
+ """
163
+ bos = self.bos_token
164
+ bos_token_id = self.bos_token_id
165
+ if bos is None and self.add_bos_token:
166
+ raise ValueError("add_bos_token = True but bos_token = None")
167
+
168
+ eos = self.eos_token
169
+ eos_token_id = self.eos_token_id
170
+ if eos is None and self.add_eos_token:
171
+ raise ValueError("add_eos_token = True but eos_token = None")
172
+
173
+ single = f"{(bos+':0 ') if self.add_bos_token else ''}$A:0{(' '+eos+':0') if self.add_eos_token else ''}"
174
+ pair = (
175
+ f"{single}{(' '+bos+':1') if self.add_bos_token else ''} $B:1{(' '+eos+':1') if self.add_eos_token else ''}"
176
+ )
177
+
178
+ special_tokens = []
179
+ if self.add_bos_token:
180
+ special_tokens.append((bos, bos_token_id))
181
+ if self.add_eos_token:
182
+ special_tokens.append((eos, eos_token_id))
183
+ self._tokenizer.post_processor = processors.TemplateProcessing(
184
+ single=single, pair=pair, special_tokens=special_tokens
185
+ )
186
+
187
+ @property
188
+ def add_eos_token(self):
189
+ return self._add_eos_token
190
+
191
+ @property
192
+ def add_bos_token(self):
193
+ return self._add_bos_token
194
+
195
+ @add_eos_token.setter
196
+ def add_eos_token(self, value):
197
+ self._add_eos_token = value
198
+ self.update_post_processor()
199
+
200
+ @add_bos_token.setter
201
+ def add_bos_token(self, value):
202
+ self._add_bos_token = value
203
+ self.update_post_processor()
204
+
205
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
206
+ if not self.can_save_slow_tokenizer:
207
+ raise ValueError(
208
+ "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
209
+ "tokenizer."
210
+ )
211
+
212
+ if not os.path.isdir(save_directory):
213
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
214
+ return
215
+ out_vocab_file = os.path.join(
216
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
217
+ )
218
+
219
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
220
+ copyfile(self.vocab_file, out_vocab_file)
221
+
222
+ return (out_vocab_file,)
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f868398fc4e05ee1e8aeba95ddf18ddcc45b8bce55d5093bead5bbf80429b48b
3
+ size 1477754
tokenizer_config.json ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "added_tokens_decoder": {
5
+ "0": {
6
+ "content": "<unk>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "1": {
14
+ "content": "<s>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "2": {
22
+ "content": "</s>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ }
29
+ },
30
+ "auto_map": {
31
+ "AutoTokenizer": [
32
+ "tokenization_internlm2.InternLM2Tokenizer",
33
+ "tokenization_internlm2_fast.InternLM2TokenizerFast"
34
+ ]
35
+ },
36
+ "bos_token": "<s>",
37
+ "clean_up_tokenization_spaces": false,
38
+ "decode_with_prefix_space": false,
39
+ "eos_token": "</s>",
40
+ "model_max_length": 1000000000000000019884624838656,
41
+ "pad_token": "</s>",
42
+ "sp_model_kwargs": null,
43
+ "tokenizer_class": "InternLM2Tokenizer",
44
+ "unk_token": "<unk>"
45
+ }