Text Generation
Transformers
Safetensors
English
internlm2
custom_code
renma commited on
Commit
28f6503
·
verified ·
1 Parent(s): d6d4857

Upload folder using huggingface_hub

Browse files
config.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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": 4096,
16
+ "initializer_range": 0.02,
17
+ "intermediate_size": 14336,
18
+ "max_position_embeddings": 1024,
19
+ "model_type": "internlm2",
20
+ "num_attention_heads": 32,
21
+ "num_hidden_layers": 32,
22
+ "num_key_value_heads": 8,
23
+ "pad_token_id": 2,
24
+ "pretraining_tp": 1,
25
+ "rms_norm_eps": 1e-05,
26
+ "rope_scaling": {
27
+ "factor": 2.0,
28
+ "type": "dynamic"
29
+ },
30
+ "rope_theta": 1000000,
31
+ "tie_word_embeddings": false,
32
+ "torch_dtype": "bfloat16",
33
+ "transformers_version": "4.39.1",
34
+ "use_cache": true,
35
+ "vocab_size": 32000
36
+ }
configuration_internlm2.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 by
41
+ 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 decoder.
48
+ num_attention_heads (`int`, *optional*, defaults to 32):
49
+ Number of attention heads for each attention layer in the Transformer decoder.
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. InternLM2 supports up to 32768 tokens.
62
+ initializer_range (`float`, *optional*, defaults to 0.02):
63
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
64
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
65
+ The epsilon used by the rms normalization layers.
66
+ use_cache (`bool`, *optional*, defaults to `True`):
67
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
68
+ relevant if `config.is_decoder=True`.
69
+ pad_token_id (`int`, *optional*):
70
+ Padding token id.
71
+ bos_token_id (`int`, *optional*, defaults to 1):
72
+ Beginning of stream token id.
73
+ eos_token_id (`int`, *optional*, defaults to 2):
74
+ End of stream token id.
75
+ pretraining_tp (`int`, *optional*, defaults to 1):
76
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
77
+ document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism)
78
+ to understand more about it. This value is necessary to ensure exact reproducibility
79
+ of the pretraining results. Please refer to [this
80
+ issue](https://github.com/pytorch/pytorch/issues/76232).
81
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
82
+ Whether to tie weight embeddings
83
+ rope_theta (`float`, *optional*, defaults to 10000.0):
84
+ The base period of the RoPE embeddings.
85
+ rope_scaling (`Dict`, *optional*):
86
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
87
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
88
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
89
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
90
+ these scaling strategies behave:
91
+ https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
92
+ experimental feature, subject to breaking API changes in future versions.
93
+ """
94
+ _auto_class = "AutoConfig"
95
+ model_type = "internlm2"
96
+ keys_to_ignore_at_inference = ["past_key_values"]
97
+
98
+ def __init__( # pylint: disable=W0102
99
+ self,
100
+ vocab_size=103168,
101
+ hidden_size=4096,
102
+ intermediate_size=11008,
103
+ num_hidden_layers=32,
104
+ num_attention_heads=32,
105
+ num_key_value_heads=None,
106
+ hidden_act="silu",
107
+ max_position_embeddings=2048,
108
+ initializer_range=0.02,
109
+ rms_norm_eps=1e-6,
110
+ use_cache=True,
111
+ pad_token_id=0,
112
+ bos_token_id=1,
113
+ eos_token_id=2,
114
+ pretraining_tp=1,
115
+ tie_word_embeddings=False,
116
+ bias=True,
117
+ rope_theta=10000,
118
+ rope_scaling=None,
119
+ attn_implementation=None,
120
+ **kwargs,
121
+ ):
122
+ self.vocab_size = vocab_size
123
+ self.max_position_embeddings = max_position_embeddings
124
+ self.hidden_size = hidden_size
125
+ self.intermediate_size = intermediate_size
126
+ self.num_hidden_layers = num_hidden_layers
127
+ self.num_attention_heads = num_attention_heads
128
+ self.bias = bias
129
+
130
+ if num_key_value_heads is None:
131
+ num_key_value_heads = num_attention_heads
132
+ self.num_key_value_heads = num_key_value_heads
133
+
134
+ self.hidden_act = hidden_act
135
+ self.initializer_range = initializer_range
136
+ self.rms_norm_eps = rms_norm_eps
137
+ self.pretraining_tp = pretraining_tp
138
+ self.use_cache = use_cache
139
+ self.rope_theta = rope_theta
140
+ self.rope_scaling = rope_scaling
141
+ self._rope_scaling_validation()
142
+ self.attn_implementation = attn_implementation
143
+ if self.attn_implementation is None:
144
+ self.attn_implementation = "eager"
145
+
146
+ super().__init__(
147
+ pad_token_id=pad_token_id,
148
+ bos_token_id=bos_token_id,
149
+ eos_token_id=eos_token_id,
150
+ tie_word_embeddings=tie_word_embeddings,
151
+ **kwargs,
152
+ )
153
+
154
+ def _rope_scaling_validation(self):
155
+ """
156
+ Validate the `rope_scaling` configuration.
157
+ """
158
+ if self.rope_scaling is None:
159
+ return
160
+
161
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
162
+ raise ValueError(
163
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
164
+ f"got {self.rope_scaling}"
165
+ )
166
+ rope_scaling_type = self.rope_scaling.get("type", None)
167
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
168
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
169
+ raise ValueError(
170
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
171
+ )
172
+ if (
173
+ rope_scaling_factor is None
174
+ or not isinstance(rope_scaling_factor, (float, int))
175
+ or rope_scaling_factor < 1.0
176
+ ):
177
+ raise ValueError(
178
+ f"`rope_scaling`'s factor field must be a number >= 1, got {rope_scaling_factor} "
179
+ f"of type {type(rope_scaling_factor)}"
180
+ )
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.1"
7
+ }
model-00001-of-00008.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6ac29319aba3ab69536eb5b06d26eff3cce4c0f97840173feb8a6519ab67485e
3
+ size 1889586048
model-00002-of-00008.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a211c4528b226c098c727896c22035fc1dbc4fd908199bfb0201376c25c124b7
3
+ size 1946242696
model-00003-of-00008.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a8a05031cfbd8a0a0e151157e2916842e625f03b2a604246f9bebacaa94598ee
3
+ size 1979780448
model-00004-of-00008.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4be2311ba268c33004cd79d904e3f66bb701231ebc0172741b3fcd1f0f7f4070
3
+ size 1946242728
model-00005-of-00008.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bb07a4ec7a81c50cfc2f2b1380a74c7a5a3be863c0e7c812fc35d73594116227
3
+ size 1979780456
model-00006-of-00008.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:750cd2f9bff4310a187053ef2cb70a7380342ee64ce0a2c4101c847005cf1ede
3
+ size 1946242728
model-00007-of-00008.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:033ba9774a448e3fa5cb704ab0a0605ddfcbcd88a0e7d678c65f3101bf43156e
3
+ size 1979780456
model-00008-of-00008.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:506b0879ddca174dd82011e981302ed9ac88efb696b3c90e28f066698e05583a
3
+ size 815834408
model.safetensors.index.json ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 14483464192
4
+ },
5
+ "weight_map": {
6
+ "model.layers.0.attention.wo.weight": "model-00001-of-00008.safetensors",
7
+ "model.layers.0.attention.wqkv.weight": "model-00001-of-00008.safetensors",
8
+ "model.layers.0.attention_norm.weight": "model-00001-of-00008.safetensors",
9
+ "model.layers.0.feed_forward.w1.weight": "model-00001-of-00008.safetensors",
10
+ "model.layers.0.feed_forward.w2.weight": "model-00001-of-00008.safetensors",
11
+ "model.layers.0.feed_forward.w3.weight": "model-00001-of-00008.safetensors",
12
+ "model.layers.0.ffn_norm.weight": "model-00001-of-00008.safetensors",
13
+ "model.layers.1.attention.wo.weight": "model-00001-of-00008.safetensors",
14
+ "model.layers.1.attention.wqkv.weight": "model-00001-of-00008.safetensors",
15
+ "model.layers.1.attention_norm.weight": "model-00001-of-00008.safetensors",
16
+ "model.layers.1.feed_forward.w1.weight": "model-00001-of-00008.safetensors",
17
+ "model.layers.1.feed_forward.w2.weight": "model-00001-of-00008.safetensors",
18
+ "model.layers.1.feed_forward.w3.weight": "model-00001-of-00008.safetensors",
19
+ "model.layers.1.ffn_norm.weight": "model-00001-of-00008.safetensors",
20
+ "model.layers.10.attention.wo.weight": "model-00003-of-00008.safetensors",
21
+ "model.layers.10.attention.wqkv.weight": "model-00003-of-00008.safetensors",
22
+ "model.layers.10.attention_norm.weight": "model-00003-of-00008.safetensors",
23
+ "model.layers.10.feed_forward.w1.weight": "model-00003-of-00008.safetensors",
24
+ "model.layers.10.feed_forward.w2.weight": "model-00003-of-00008.safetensors",
25
+ "model.layers.10.feed_forward.w3.weight": "model-00003-of-00008.safetensors",
26
+ "model.layers.10.ffn_norm.weight": "model-00003-of-00008.safetensors",
27
+ "model.layers.11.attention.wo.weight": "model-00003-of-00008.safetensors",
28
+ "model.layers.11.attention.wqkv.weight": "model-00003-of-00008.safetensors",
29
+ "model.layers.11.attention_norm.weight": "model-00003-of-00008.safetensors",
30
+ "model.layers.11.feed_forward.w1.weight": "model-00003-of-00008.safetensors",
31
+ "model.layers.11.feed_forward.w2.weight": "model-00003-of-00008.safetensors",
32
+ "model.layers.11.feed_forward.w3.weight": "model-00003-of-00008.safetensors",
33
+ "model.layers.11.ffn_norm.weight": "model-00003-of-00008.safetensors",
34
+ "model.layers.12.attention.wo.weight": "model-00003-of-00008.safetensors",
35
+ "model.layers.12.attention.wqkv.weight": "model-00003-of-00008.safetensors",
36
+ "model.layers.12.attention_norm.weight": "model-00004-of-00008.safetensors",
37
+ "model.layers.12.feed_forward.w1.weight": "model-00003-of-00008.safetensors",
38
+ "model.layers.12.feed_forward.w2.weight": "model-00004-of-00008.safetensors",
39
+ "model.layers.12.feed_forward.w3.weight": "model-00003-of-00008.safetensors",
40
+ "model.layers.12.ffn_norm.weight": "model-00004-of-00008.safetensors",
41
+ "model.layers.13.attention.wo.weight": "model-00004-of-00008.safetensors",
42
+ "model.layers.13.attention.wqkv.weight": "model-00004-of-00008.safetensors",
43
+ "model.layers.13.attention_norm.weight": "model-00004-of-00008.safetensors",
44
+ "model.layers.13.feed_forward.w1.weight": "model-00004-of-00008.safetensors",
45
+ "model.layers.13.feed_forward.w2.weight": "model-00004-of-00008.safetensors",
46
+ "model.layers.13.feed_forward.w3.weight": "model-00004-of-00008.safetensors",
47
+ "model.layers.13.ffn_norm.weight": "model-00004-of-00008.safetensors",
48
+ "model.layers.14.attention.wo.weight": "model-00004-of-00008.safetensors",
49
+ "model.layers.14.attention.wqkv.weight": "model-00004-of-00008.safetensors",
50
+ "model.layers.14.attention_norm.weight": "model-00004-of-00008.safetensors",
51
+ "model.layers.14.feed_forward.w1.weight": "model-00004-of-00008.safetensors",
52
+ "model.layers.14.feed_forward.w2.weight": "model-00004-of-00008.safetensors",
53
+ "model.layers.14.feed_forward.w3.weight": "model-00004-of-00008.safetensors",
54
+ "model.layers.14.ffn_norm.weight": "model-00004-of-00008.safetensors",
55
+ "model.layers.15.attention.wo.weight": "model-00004-of-00008.safetensors",
56
+ "model.layers.15.attention.wqkv.weight": "model-00004-of-00008.safetensors",
57
+ "model.layers.15.attention_norm.weight": "model-00004-of-00008.safetensors",
58
+ "model.layers.15.feed_forward.w1.weight": "model-00004-of-00008.safetensors",
59
+ "model.layers.15.feed_forward.w2.weight": "model-00004-of-00008.safetensors",
60
+ "model.layers.15.feed_forward.w3.weight": "model-00004-of-00008.safetensors",
61
+ "model.layers.15.ffn_norm.weight": "model-00004-of-00008.safetensors",
62
+ "model.layers.16.attention.wo.weight": "model-00004-of-00008.safetensors",
63
+ "model.layers.16.attention.wqkv.weight": "model-00004-of-00008.safetensors",
64
+ "model.layers.16.attention_norm.weight": "model-00004-of-00008.safetensors",
65
+ "model.layers.16.feed_forward.w1.weight": "model-00004-of-00008.safetensors",
66
+ "model.layers.16.feed_forward.w2.weight": "model-00004-of-00008.safetensors",
67
+ "model.layers.16.feed_forward.w3.weight": "model-00004-of-00008.safetensors",
68
+ "model.layers.16.ffn_norm.weight": "model-00004-of-00008.safetensors",
69
+ "model.layers.17.attention.wo.weight": "model-00004-of-00008.safetensors",
70
+ "model.layers.17.attention.wqkv.weight": "model-00004-of-00008.safetensors",
71
+ "model.layers.17.attention_norm.weight": "model-00005-of-00008.safetensors",
72
+ "model.layers.17.feed_forward.w1.weight": "model-00005-of-00008.safetensors",
73
+ "model.layers.17.feed_forward.w2.weight": "model-00005-of-00008.safetensors",
74
+ "model.layers.17.feed_forward.w3.weight": "model-00005-of-00008.safetensors",
75
+ "model.layers.17.ffn_norm.weight": "model-00005-of-00008.safetensors",
76
+ "model.layers.18.attention.wo.weight": "model-00005-of-00008.safetensors",
77
+ "model.layers.18.attention.wqkv.weight": "model-00005-of-00008.safetensors",
78
+ "model.layers.18.attention_norm.weight": "model-00005-of-00008.safetensors",
79
+ "model.layers.18.feed_forward.w1.weight": "model-00005-of-00008.safetensors",
80
+ "model.layers.18.feed_forward.w2.weight": "model-00005-of-00008.safetensors",
81
+ "model.layers.18.feed_forward.w3.weight": "model-00005-of-00008.safetensors",
82
+ "model.layers.18.ffn_norm.weight": "model-00005-of-00008.safetensors",
83
+ "model.layers.19.attention.wo.weight": "model-00005-of-00008.safetensors",
84
+ "model.layers.19.attention.wqkv.weight": "model-00005-of-00008.safetensors",
85
+ "model.layers.19.attention_norm.weight": "model-00005-of-00008.safetensors",
86
+ "model.layers.19.feed_forward.w1.weight": "model-00005-of-00008.safetensors",
87
+ "model.layers.19.feed_forward.w2.weight": "model-00005-of-00008.safetensors",
88
+ "model.layers.19.feed_forward.w3.weight": "model-00005-of-00008.safetensors",
89
+ "model.layers.19.ffn_norm.weight": "model-00005-of-00008.safetensors",
90
+ "model.layers.2.attention.wo.weight": "model-00001-of-00008.safetensors",
91
+ "model.layers.2.attention.wqkv.weight": "model-00001-of-00008.safetensors",
92
+ "model.layers.2.attention_norm.weight": "model-00001-of-00008.safetensors",
93
+ "model.layers.2.feed_forward.w1.weight": "model-00001-of-00008.safetensors",
94
+ "model.layers.2.feed_forward.w2.weight": "model-00001-of-00008.safetensors",
95
+ "model.layers.2.feed_forward.w3.weight": "model-00001-of-00008.safetensors",
96
+ "model.layers.2.ffn_norm.weight": "model-00001-of-00008.safetensors",
97
+ "model.layers.20.attention.wo.weight": "model-00005-of-00008.safetensors",
98
+ "model.layers.20.attention.wqkv.weight": "model-00005-of-00008.safetensors",
99
+ "model.layers.20.attention_norm.weight": "model-00005-of-00008.safetensors",
100
+ "model.layers.20.feed_forward.w1.weight": "model-00005-of-00008.safetensors",
101
+ "model.layers.20.feed_forward.w2.weight": "model-00005-of-00008.safetensors",
102
+ "model.layers.20.feed_forward.w3.weight": "model-00005-of-00008.safetensors",
103
+ "model.layers.20.ffn_norm.weight": "model-00005-of-00008.safetensors",
104
+ "model.layers.21.attention.wo.weight": "model-00005-of-00008.safetensors",
105
+ "model.layers.21.attention.wqkv.weight": "model-00005-of-00008.safetensors",
106
+ "model.layers.21.attention_norm.weight": "model-00006-of-00008.safetensors",
107
+ "model.layers.21.feed_forward.w1.weight": "model-00005-of-00008.safetensors",
108
+ "model.layers.21.feed_forward.w2.weight": "model-00006-of-00008.safetensors",
109
+ "model.layers.21.feed_forward.w3.weight": "model-00005-of-00008.safetensors",
110
+ "model.layers.21.ffn_norm.weight": "model-00006-of-00008.safetensors",
111
+ "model.layers.22.attention.wo.weight": "model-00006-of-00008.safetensors",
112
+ "model.layers.22.attention.wqkv.weight": "model-00006-of-00008.safetensors",
113
+ "model.layers.22.attention_norm.weight": "model-00006-of-00008.safetensors",
114
+ "model.layers.22.feed_forward.w1.weight": "model-00006-of-00008.safetensors",
115
+ "model.layers.22.feed_forward.w2.weight": "model-00006-of-00008.safetensors",
116
+ "model.layers.22.feed_forward.w3.weight": "model-00006-of-00008.safetensors",
117
+ "model.layers.22.ffn_norm.weight": "model-00006-of-00008.safetensors",
118
+ "model.layers.23.attention.wo.weight": "model-00006-of-00008.safetensors",
119
+ "model.layers.23.attention.wqkv.weight": "model-00006-of-00008.safetensors",
120
+ "model.layers.23.attention_norm.weight": "model-00006-of-00008.safetensors",
121
+ "model.layers.23.feed_forward.w1.weight": "model-00006-of-00008.safetensors",
122
+ "model.layers.23.feed_forward.w2.weight": "model-00006-of-00008.safetensors",
123
+ "model.layers.23.feed_forward.w3.weight": "model-00006-of-00008.safetensors",
124
+ "model.layers.23.ffn_norm.weight": "model-00006-of-00008.safetensors",
125
+ "model.layers.24.attention.wo.weight": "model-00006-of-00008.safetensors",
126
+ "model.layers.24.attention.wqkv.weight": "model-00006-of-00008.safetensors",
127
+ "model.layers.24.attention_norm.weight": "model-00006-of-00008.safetensors",
128
+ "model.layers.24.feed_forward.w1.weight": "model-00006-of-00008.safetensors",
129
+ "model.layers.24.feed_forward.w2.weight": "model-00006-of-00008.safetensors",
130
+ "model.layers.24.feed_forward.w3.weight": "model-00006-of-00008.safetensors",
131
+ "model.layers.24.ffn_norm.weight": "model-00006-of-00008.safetensors",
132
+ "model.layers.25.attention.wo.weight": "model-00006-of-00008.safetensors",
133
+ "model.layers.25.attention.wqkv.weight": "model-00006-of-00008.safetensors",
134
+ "model.layers.25.attention_norm.weight": "model-00006-of-00008.safetensors",
135
+ "model.layers.25.feed_forward.w1.weight": "model-00006-of-00008.safetensors",
136
+ "model.layers.25.feed_forward.w2.weight": "model-00006-of-00008.safetensors",
137
+ "model.layers.25.feed_forward.w3.weight": "model-00006-of-00008.safetensors",
138
+ "model.layers.25.ffn_norm.weight": "model-00006-of-00008.safetensors",
139
+ "model.layers.26.attention.wo.weight": "model-00006-of-00008.safetensors",
140
+ "model.layers.26.attention.wqkv.weight": "model-00006-of-00008.safetensors",
141
+ "model.layers.26.attention_norm.weight": "model-00007-of-00008.safetensors",
142
+ "model.layers.26.feed_forward.w1.weight": "model-00007-of-00008.safetensors",
143
+ "model.layers.26.feed_forward.w2.weight": "model-00007-of-00008.safetensors",
144
+ "model.layers.26.feed_forward.w3.weight": "model-00007-of-00008.safetensors",
145
+ "model.layers.26.ffn_norm.weight": "model-00007-of-00008.safetensors",
146
+ "model.layers.27.attention.wo.weight": "model-00007-of-00008.safetensors",
147
+ "model.layers.27.attention.wqkv.weight": "model-00007-of-00008.safetensors",
148
+ "model.layers.27.attention_norm.weight": "model-00007-of-00008.safetensors",
149
+ "model.layers.27.feed_forward.w1.weight": "model-00007-of-00008.safetensors",
150
+ "model.layers.27.feed_forward.w2.weight": "model-00007-of-00008.safetensors",
151
+ "model.layers.27.feed_forward.w3.weight": "model-00007-of-00008.safetensors",
152
+ "model.layers.27.ffn_norm.weight": "model-00007-of-00008.safetensors",
153
+ "model.layers.28.attention.wo.weight": "model-00007-of-00008.safetensors",
154
+ "model.layers.28.attention.wqkv.weight": "model-00007-of-00008.safetensors",
155
+ "model.layers.28.attention_norm.weight": "model-00007-of-00008.safetensors",
156
+ "model.layers.28.feed_forward.w1.weight": "model-00007-of-00008.safetensors",
157
+ "model.layers.28.feed_forward.w2.weight": "model-00007-of-00008.safetensors",
158
+ "model.layers.28.feed_forward.w3.weight": "model-00007-of-00008.safetensors",
159
+ "model.layers.28.ffn_norm.weight": "model-00007-of-00008.safetensors",
160
+ "model.layers.29.attention.wo.weight": "model-00007-of-00008.safetensors",
161
+ "model.layers.29.attention.wqkv.weight": "model-00007-of-00008.safetensors",
162
+ "model.layers.29.attention_norm.weight": "model-00007-of-00008.safetensors",
163
+ "model.layers.29.feed_forward.w1.weight": "model-00007-of-00008.safetensors",
164
+ "model.layers.29.feed_forward.w2.weight": "model-00007-of-00008.safetensors",
165
+ "model.layers.29.feed_forward.w3.weight": "model-00007-of-00008.safetensors",
166
+ "model.layers.29.ffn_norm.weight": "model-00007-of-00008.safetensors",
167
+ "model.layers.3.attention.wo.weight": "model-00001-of-00008.safetensors",
168
+ "model.layers.3.attention.wqkv.weight": "model-00001-of-00008.safetensors",
169
+ "model.layers.3.attention_norm.weight": "model-00002-of-00008.safetensors",
170
+ "model.layers.3.feed_forward.w1.weight": "model-00001-of-00008.safetensors",
171
+ "model.layers.3.feed_forward.w2.weight": "model-00002-of-00008.safetensors",
172
+ "model.layers.3.feed_forward.w3.weight": "model-00001-of-00008.safetensors",
173
+ "model.layers.3.ffn_norm.weight": "model-00002-of-00008.safetensors",
174
+ "model.layers.30.attention.wo.weight": "model-00007-of-00008.safetensors",
175
+ "model.layers.30.attention.wqkv.weight": "model-00007-of-00008.safetensors",
176
+ "model.layers.30.attention_norm.weight": "model-00008-of-00008.safetensors",
177
+ "model.layers.30.feed_forward.w1.weight": "model-00007-of-00008.safetensors",
178
+ "model.layers.30.feed_forward.w2.weight": "model-00008-of-00008.safetensors",
179
+ "model.layers.30.feed_forward.w3.weight": "model-00007-of-00008.safetensors",
180
+ "model.layers.30.ffn_norm.weight": "model-00008-of-00008.safetensors",
181
+ "model.layers.31.attention.wo.weight": "model-00008-of-00008.safetensors",
182
+ "model.layers.31.attention.wqkv.weight": "model-00008-of-00008.safetensors",
183
+ "model.layers.31.attention_norm.weight": "model-00008-of-00008.safetensors",
184
+ "model.layers.31.feed_forward.w1.weight": "model-00008-of-00008.safetensors",
185
+ "model.layers.31.feed_forward.w2.weight": "model-00008-of-00008.safetensors",
186
+ "model.layers.31.feed_forward.w3.weight": "model-00008-of-00008.safetensors",
187
+ "model.layers.31.ffn_norm.weight": "model-00008-of-00008.safetensors",
188
+ "model.layers.4.attention.wo.weight": "model-00002-of-00008.safetensors",
189
+ "model.layers.4.attention.wqkv.weight": "model-00002-of-00008.safetensors",
190
+ "model.layers.4.attention_norm.weight": "model-00002-of-00008.safetensors",
191
+ "model.layers.4.feed_forward.w1.weight": "model-00002-of-00008.safetensors",
192
+ "model.layers.4.feed_forward.w2.weight": "model-00002-of-00008.safetensors",
193
+ "model.layers.4.feed_forward.w3.weight": "model-00002-of-00008.safetensors",
194
+ "model.layers.4.ffn_norm.weight": "model-00002-of-00008.safetensors",
195
+ "model.layers.5.attention.wo.weight": "model-00002-of-00008.safetensors",
196
+ "model.layers.5.attention.wqkv.weight": "model-00002-of-00008.safetensors",
197
+ "model.layers.5.attention_norm.weight": "model-00002-of-00008.safetensors",
198
+ "model.layers.5.feed_forward.w1.weight": "model-00002-of-00008.safetensors",
199
+ "model.layers.5.feed_forward.w2.weight": "model-00002-of-00008.safetensors",
200
+ "model.layers.5.feed_forward.w3.weight": "model-00002-of-00008.safetensors",
201
+ "model.layers.5.ffn_norm.weight": "model-00002-of-00008.safetensors",
202
+ "model.layers.6.attention.wo.weight": "model-00002-of-00008.safetensors",
203
+ "model.layers.6.attention.wqkv.weight": "model-00002-of-00008.safetensors",
204
+ "model.layers.6.attention_norm.weight": "model-00002-of-00008.safetensors",
205
+ "model.layers.6.feed_forward.w1.weight": "model-00002-of-00008.safetensors",
206
+ "model.layers.6.feed_forward.w2.weight": "model-00002-of-00008.safetensors",
207
+ "model.layers.6.feed_forward.w3.weight": "model-00002-of-00008.safetensors",
208
+ "model.layers.6.ffn_norm.weight": "model-00002-of-00008.safetensors",
209
+ "model.layers.7.attention.wo.weight": "model-00002-of-00008.safetensors",
210
+ "model.layers.7.attention.wqkv.weight": "model-00002-of-00008.safetensors",
211
+ "model.layers.7.attention_norm.weight": "model-00002-of-00008.safetensors",
212
+ "model.layers.7.feed_forward.w1.weight": "model-00002-of-00008.safetensors",
213
+ "model.layers.7.feed_forward.w2.weight": "model-00002-of-00008.safetensors",
214
+ "model.layers.7.feed_forward.w3.weight": "model-00002-of-00008.safetensors",
215
+ "model.layers.7.ffn_norm.weight": "model-00002-of-00008.safetensors",
216
+ "model.layers.8.attention.wo.weight": "model-00002-of-00008.safetensors",
217
+ "model.layers.8.attention.wqkv.weight": "model-00002-of-00008.safetensors",
218
+ "model.layers.8.attention_norm.weight": "model-00003-of-00008.safetensors",
219
+ "model.layers.8.feed_forward.w1.weight": "model-00003-of-00008.safetensors",
220
+ "model.layers.8.feed_forward.w2.weight": "model-00003-of-00008.safetensors",
221
+ "model.layers.8.feed_forward.w3.weight": "model-00003-of-00008.safetensors",
222
+ "model.layers.8.ffn_norm.weight": "model-00003-of-00008.safetensors",
223
+ "model.layers.9.attention.wo.weight": "model-00003-of-00008.safetensors",
224
+ "model.layers.9.attention.wqkv.weight": "model-00003-of-00008.safetensors",
225
+ "model.layers.9.attention_norm.weight": "model-00003-of-00008.safetensors",
226
+ "model.layers.9.feed_forward.w1.weight": "model-00003-of-00008.safetensors",
227
+ "model.layers.9.feed_forward.w2.weight": "model-00003-of-00008.safetensors",
228
+ "model.layers.9.feed_forward.w3.weight": "model-00003-of-00008.safetensors",
229
+ "model.layers.9.ffn_norm.weight": "model-00003-of-00008.safetensors",
230
+ "model.norm.weight": "model-00008-of-00008.safetensors",
231
+ "model.tok_embeddings.weight": "model-00001-of-00008.safetensors",
232
+ "output.weight": "model-00008-of-00008.safetensors"
233
+ }
234
+ }
modeling_internlm2.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+
3
+ from packaging import version
4
+
5
+ if version.parse(importlib.metadata.version("transformers")) >= version.parse("4.38.0"):
6
+ from .modeling_internlm2_above_4_38_0 import * # noqa: F401 # pylint: disable=W0401,W0614
7
+ else:
8
+ from .modeling_internlm2_below_4_38_0 import * # noqa: F401 # pylint: disable=W0401,W0614
modeling_internlm2_above_4_38_0.py ADDED
@@ -0,0 +1,1799 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import List, Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.nn.functional as F
24
+ import torch.utils.checkpoint
25
+ from einops import rearrange
26
+ from torch import nn
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+ from transformers.activations import ACT2FN
29
+ from transformers.cache_utils import Cache, DynamicCache, StaticCache
30
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
31
+ from transformers.modeling_outputs import (
32
+ BaseModelOutputWithPast,
33
+ CausalLMOutputWithPast,
34
+ QuestionAnsweringModelOutput,
35
+ SequenceClassifierOutputWithPast,
36
+ TokenClassifierOutput,
37
+ )
38
+ from transformers.modeling_utils import PreTrainedModel
39
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
40
+ from transformers.utils import (
41
+ add_start_docstrings,
42
+ add_start_docstrings_to_model_forward,
43
+ is_flash_attn_greater_or_equal_2_10,
44
+ logging,
45
+ replace_return_docstrings,
46
+ )
47
+
48
+ try:
49
+ from transformers.generation.streamers import BaseStreamer
50
+ except Exception:
51
+ BaseStreamer = None
52
+
53
+ from .configuration_internlm2 import InternLM2Config
54
+
55
+ try:
56
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
57
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input
58
+ except Exception:
59
+ pass
60
+
61
+
62
+ logger = logging.get_logger(__name__)
63
+
64
+ _CONFIG_FOR_DOC = "InternLM2Config"
65
+
66
+
67
+ def _get_unpad_data(attention_mask):
68
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
69
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
70
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
71
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0)) # pylint: disable=E1102
72
+ return (
73
+ indices,
74
+ cu_seqlens,
75
+ max_seqlen_in_batch,
76
+ )
77
+
78
+
79
+ class InternLM2RMSNorm(nn.Module):
80
+ """InternLM2RMSNorm is equivalent to T5LayerNorm."""
81
+
82
+ def __init__(self, hidden_size, eps=1e-6):
83
+ super().__init__()
84
+ self.weight = nn.Parameter(torch.ones(hidden_size))
85
+ self.variance_epsilon = eps
86
+
87
+ def forward(self, hidden_states):
88
+ input_dtype = hidden_states.dtype
89
+ hidden_states = hidden_states.to(torch.float32)
90
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
91
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
92
+ return self.weight * hidden_states.to(input_dtype)
93
+
94
+
95
+ ALL_LAYERNORM_LAYERS.append(InternLM2RMSNorm)
96
+
97
+
98
+ class InternLM2RotaryEmbedding(nn.Module):
99
+ """Rotary Position Embedding for the InternLM2 model. Credits to the Reddit user /u/lucidrains."""
100
+
101
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
102
+ super().__init__()
103
+ self.scaling_factor = scaling_factor
104
+ self.dim = dim
105
+ self.max_position_embeddings = max_position_embeddings
106
+ self.base = base
107
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
108
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
109
+ # For BC we register cos and sin cached
110
+ self.max_seq_len_cached = max_position_embeddings
111
+
112
+ @torch.no_grad()
113
+ def forward(self, x, position_ids):
114
+ # x: [bs, num_attention_heads, seq_len, head_size]
115
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
116
+ position_ids_expanded = position_ids[:, None, :].float()
117
+ # Force float32 since bfloat16 loses precision on long contexts
118
+ # See https://github.com/huggingface/transformers/pull/29285
119
+ device_type = x.device.type
120
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
121
+ with torch.autocast(device_type=device_type, enabled=False):
122
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
123
+ emb = torch.cat((freqs, freqs), dim=-1)
124
+ cos = emb.cos()
125
+ sin = emb.sin()
126
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
127
+
128
+
129
+ class InternLM2LinearScalingRotaryEmbedding(InternLM2RotaryEmbedding):
130
+ """InternLM2RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
131
+
132
+ def forward(self, x, position_ids):
133
+ # difference to the original RoPE: a scaling factor is aplied to the position ids
134
+ position_ids = position_ids.float() / self.scaling_factor
135
+ cos, sin = super().forward(x, position_ids)
136
+ return cos, sin
137
+
138
+
139
+ class InternLM2DynamicNTKScalingRotaryEmbedding(InternLM2RotaryEmbedding):
140
+ """InternLM2RotaryEmbedding extended with Dynamic NTK scaling.
141
+ Credits to the Reddit users /u/bloc97 and /u/emozilla"""
142
+
143
+ def forward(self, x, position_ids):
144
+ # difference to the original RoPE: inv_freq is recomputed when the sequence length > original length
145
+ seq_len = torch.max(position_ids) + 1
146
+ if seq_len > self.max_position_embeddings:
147
+ base = self.base * (
148
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
149
+ ) ** (self.dim / (self.dim - 2))
150
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(x.device) / self.dim))
151
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: this may break with compilation
152
+
153
+ cos, sin = super().forward(x, position_ids)
154
+ return cos, sin
155
+
156
+
157
+ def rotate_half(x):
158
+ """Rotates half the hidden dims of the input."""
159
+ x1 = x[..., : x.shape[-1] // 2]
160
+ x2 = x[..., x.shape[-1] // 2 :]
161
+ return torch.cat((-x2, x1), dim=-1)
162
+
163
+
164
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1): # pylint: disable=unused-argument
165
+ """Applies Rotary Position Embedding to the query and key tensors.
166
+
167
+ Args:
168
+ q (`torch.Tensor`): The query tensor.
169
+ k (`torch.Tensor`): The key tensor.
170
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
171
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
172
+ position_ids (`torch.Tensor`, *optional*):
173
+ Deprecated and unused.
174
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
175
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
176
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
177
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
178
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
179
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
180
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
181
+ Returns:
182
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
183
+ """
184
+ cos = cos.unsqueeze(unsqueeze_dim)
185
+ sin = sin.unsqueeze(unsqueeze_dim)
186
+ q_embed = (q * cos) + (rotate_half(q) * sin)
187
+ k_embed = (k * cos) + (rotate_half(k) * sin)
188
+ return q_embed, k_embed
189
+
190
+
191
+ class InternLM2MLP(nn.Module):
192
+ """MLP for InternLM2 model."""
193
+
194
+ def __init__(self, config):
195
+ super().__init__()
196
+ self.config = config
197
+ self.hidden_size = config.hidden_size
198
+ self.intermediate_size = config.intermediate_size
199
+ self.w1 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
200
+ self.w3 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
201
+ self.w2 = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
202
+ self.act_fn = ACT2FN[config.hidden_act]
203
+
204
+ def forward(self, x):
205
+ down_proj = self.w2(self.act_fn(self.w1(x)) * self.w3(x))
206
+
207
+ return down_proj
208
+
209
+
210
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
211
+ """
212
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
213
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
214
+ """
215
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
216
+ if n_rep == 1:
217
+ return hidden_states
218
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
219
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
220
+
221
+
222
+ class InternLM2Attention(nn.Module):
223
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
224
+
225
+ def __init__(self, config: InternLM2Config, layer_idx: Optional[int] = None):
226
+ super().__init__()
227
+ self.config = config
228
+ self.layer_idx = layer_idx
229
+ if layer_idx is None:
230
+ logger.warning_once(
231
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
232
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
233
+ "when creating this class."
234
+ )
235
+
236
+ self.hidden_size = config.hidden_size
237
+ self.num_heads = config.num_attention_heads
238
+ self.head_dim = self.hidden_size // self.num_heads
239
+ self.num_key_value_heads = config.num_key_value_heads
240
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
241
+ self.max_position_embeddings = config.max_position_embeddings
242
+ self.rope_theta = config.rope_theta
243
+ self.is_causal = True
244
+
245
+ if (self.head_dim * self.num_heads) != self.hidden_size:
246
+ raise ValueError(
247
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
248
+ f" and `num_heads`: {self.num_heads})."
249
+ )
250
+
251
+ self.wqkv = nn.Linear(
252
+ self.hidden_size,
253
+ (self.num_heads + 2 * self.num_key_value_heads) * self.head_dim,
254
+ bias=config.bias,
255
+ )
256
+ self.wo = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.bias)
257
+
258
+ self._init_rope()
259
+
260
+ def _init_rope(self):
261
+ if self.config.rope_scaling is None:
262
+ self.rotary_emb = InternLM2RotaryEmbedding(
263
+ self.head_dim,
264
+ max_position_embeddings=self.max_position_embeddings,
265
+ base=self.rope_theta,
266
+ )
267
+ else:
268
+ scaling_type = self.config.rope_scaling["type"]
269
+ scaling_factor = self.config.rope_scaling["factor"]
270
+ if scaling_type == "linear":
271
+ self.rotary_emb = InternLM2LinearScalingRotaryEmbedding(
272
+ self.head_dim,
273
+ max_position_embeddings=self.max_position_embeddings,
274
+ scaling_factor=scaling_factor,
275
+ base=self.rope_theta,
276
+ )
277
+ elif scaling_type == "dynamic":
278
+ self.rotary_emb = InternLM2DynamicNTKScalingRotaryEmbedding(
279
+ self.head_dim,
280
+ max_position_embeddings=self.max_position_embeddings,
281
+ scaling_factor=scaling_factor,
282
+ base=self.rope_theta,
283
+ )
284
+ else:
285
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
286
+
287
+ def forward(
288
+ self,
289
+ hidden_states: torch.Tensor,
290
+ attention_mask: Optional[torch.Tensor] = None,
291
+ position_ids: Optional[torch.LongTensor] = None,
292
+ past_key_value: Optional[Cache] = None,
293
+ output_attentions: bool = False,
294
+ use_cache: bool = False, # pylint: disable=unused-argument
295
+ cache_position: Optional[torch.LongTensor] = None,
296
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
297
+ bsz, q_len, _ = hidden_states.size()
298
+
299
+ if self.config.pretraining_tp > 1:
300
+ # split qkv_states by tp size
301
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
302
+ qkv_slices = self.wqkv.weight.split(key_value_slicing, dim=0)
303
+ qkv_states = torch.cat(
304
+ [F.linear(hidden_states, qkv_slice) for qkv_slice in qkv_slices], dim=-1 # pylint: disable=E1102
305
+ )
306
+ else:
307
+ qkv_states = self.wqkv(hidden_states)
308
+
309
+ qkv_states = rearrange(
310
+ qkv_states,
311
+ "b q (h gs d) -> b q h gs d",
312
+ gs=2 + self.num_key_value_groups,
313
+ d=self.head_dim,
314
+ )
315
+
316
+ query_states = qkv_states[..., : self.num_key_value_groups, :]
317
+ query_states = rearrange(query_states, "b q h gs d -> b q (h gs) d").transpose(1, 2)
318
+ key_states = qkv_states[..., -2, :].transpose(1, 2)
319
+ value_states = qkv_states[..., -1, :].transpose(1, 2)
320
+
321
+ cos, sin = self.rotary_emb(value_states, position_ids)
322
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
323
+
324
+ if past_key_value is not None:
325
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
326
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
327
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
328
+
329
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
330
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
331
+
332
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
333
+
334
+ if attention_mask is not None: # no matter the length, we just slice it
335
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
336
+ attn_weights = attn_weights + causal_mask
337
+
338
+ # upcast attention to fp32
339
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
340
+ attn_output = torch.matmul(attn_weights, value_states)
341
+
342
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
343
+ raise ValueError(
344
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
345
+ f" {attn_output.size()}"
346
+ )
347
+
348
+ attn_output = attn_output.transpose(1, 2).contiguous()
349
+
350
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
351
+
352
+ if self.config.pretraining_tp > 1:
353
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
354
+ o_proj_slices = self.wo.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
355
+ attn_output = sum(
356
+ [
357
+ F.linear(attn_output[i], o_proj_slices[i]) # pylint: disable=E1102
358
+ for i in range(self.config.pretraining_tp)
359
+ ]
360
+ )
361
+ else:
362
+ attn_output = self.wo(attn_output)
363
+
364
+ if not output_attentions:
365
+ attn_weights = None
366
+
367
+ return attn_output, attn_weights, past_key_value
368
+
369
+
370
+ class InternLM2FlashAttention2(InternLM2Attention):
371
+ """
372
+ InternLM2 flash attention module. This module inherits from `InternLM2Attention` as the weights of the module stays
373
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
374
+ flash attention and deal with padding tokens in case the input contains any of them.
375
+ """
376
+
377
+ def __init__(self, *args, **kwargs):
378
+ super().__init__(*args, **kwargs)
379
+
380
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
381
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement,
382
+ # that was made default for flash_attn>=2.1. This attribute is used to handle this difference.
383
+ # Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
384
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1)
385
+ # produces a wrong mask (top-left).
386
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
387
+
388
+ def forward(
389
+ self,
390
+ hidden_states: torch.Tensor,
391
+ attention_mask: Optional[torch.LongTensor] = None,
392
+ position_ids: Optional[torch.LongTensor] = None,
393
+ past_key_value: Optional[Cache] = None,
394
+ output_attentions: bool = False,
395
+ use_cache: bool = False,
396
+ cache_position: Optional[torch.LongTensor] = None,
397
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
398
+ if isinstance(past_key_value, StaticCache):
399
+ raise ValueError(
400
+ "`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
401
+ "make sure to use `sdpa` in the mean time, and open an issue at "
402
+ "https://github.com/huggingface/transformers"
403
+ )
404
+
405
+ output_attentions = False
406
+
407
+ bsz, q_len, _ = hidden_states.size()
408
+
409
+ qkv_states = self.wqkv(hidden_states)
410
+
411
+ qkv_states = rearrange(
412
+ qkv_states,
413
+ "b q (h gs d) -> b q h gs d",
414
+ gs=2 + self.num_key_value_groups,
415
+ d=self.head_dim,
416
+ )
417
+
418
+ query_states = qkv_states[..., : self.num_key_value_groups, :]
419
+ query_states = rearrange(query_states, "b q h gs d -> b q (h gs) d")
420
+ key_states = qkv_states[..., -2, :]
421
+ value_states = qkv_states[..., -1, :]
422
+
423
+ query_states = query_states.transpose(1, 2)
424
+ key_states = key_states.transpose(1, 2)
425
+ value_states = value_states.transpose(1, 2)
426
+
427
+ cos, sin = self.rotary_emb(value_states, position_ids)
428
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
429
+
430
+ if past_key_value is not None:
431
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
432
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
433
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
434
+
435
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout
436
+ # [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
437
+ # to be able to avoid many of these transpose/reshape/view.
438
+ query_states = query_states.transpose(1, 2)
439
+ key_states = key_states.transpose(1, 2)
440
+ value_states = value_states.transpose(1, 2)
441
+
442
+ # dropout_rate = self.attention_dropout if self.training else 0.0
443
+ dropout_rate = 0.0
444
+
445
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
446
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
447
+ # cast them back in the correct dtype just to be sure everything works as expected.
448
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
449
+ # in fp32. (InternLM2RMSNorm handles it correctly)
450
+
451
+ input_dtype = query_states.dtype
452
+ if input_dtype == torch.float32:
453
+ if torch.is_autocast_enabled():
454
+ target_dtype = torch.get_autocast_gpu_dtype()
455
+ # Handle the case where the model is quantized
456
+ elif hasattr(self.config, "_pre_quantization_dtype"):
457
+ target_dtype = self.config._pre_quantization_dtype
458
+ else:
459
+ target_dtype = self.wqkv.weight.dtype
460
+
461
+ logger.warning_once(
462
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
463
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
464
+ f" {target_dtype}."
465
+ )
466
+
467
+ query_states = query_states.to(target_dtype)
468
+ key_states = key_states.to(target_dtype)
469
+ value_states = value_states.to(target_dtype)
470
+
471
+ attn_output = self._flash_attention_forward(
472
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
473
+ )
474
+
475
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
476
+ attn_output = self.wo(attn_output)
477
+
478
+ if not output_attentions:
479
+ attn_weights = None
480
+
481
+ return attn_output, attn_weights, past_key_value # pylint: disable=E0606
482
+
483
+ def _flash_attention_forward(
484
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
485
+ ):
486
+ """
487
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
488
+ first unpad the input, then computes the attention scores and pad the final attention scores.
489
+
490
+ Args:
491
+ query_states (`torch.Tensor`):
492
+ Input query states to be passed to Flash Attention API
493
+ key_states (`torch.Tensor`):
494
+ Input key states to be passed to Flash Attention API
495
+ value_states (`torch.Tensor`):
496
+ Input value states to be passed to Flash Attention API
497
+ attention_mask (`torch.Tensor`):
498
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
499
+ position of padding tokens and 1 for the position of non-padding tokens.
500
+ dropout (`float`):
501
+ Attention dropout
502
+ softmax_scale (`float`, *optional*):
503
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
504
+ """
505
+ if not self._flash_attn_uses_top_left_mask:
506
+ causal = self.is_causal
507
+ else:
508
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1.
509
+ # For details, please see the comment in InternLM2FlashAttention2 __init__.
510
+ causal = self.is_causal and query_length != 1
511
+
512
+ # Contains at least one padding token in the sequence
513
+ if attention_mask is not None:
514
+ batch_size = query_states.shape[0]
515
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
516
+ query_states, key_states, value_states, attention_mask, query_length
517
+ )
518
+
519
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
520
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
521
+
522
+ attn_output_unpad = flash_attn_varlen_func( # pylint: disable=E0606
523
+ query_states,
524
+ key_states,
525
+ value_states,
526
+ cu_seqlens_q=cu_seqlens_q,
527
+ cu_seqlens_k=cu_seqlens_k,
528
+ max_seqlen_q=max_seqlen_in_batch_q,
529
+ max_seqlen_k=max_seqlen_in_batch_k,
530
+ dropout_p=dropout,
531
+ softmax_scale=softmax_scale,
532
+ causal=causal,
533
+ )
534
+
535
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length) # pylint: disable=E0606
536
+ else:
537
+ attn_output = flash_attn_func( # pylint: disable=E0606
538
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
539
+ )
540
+
541
+ return attn_output
542
+
543
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
544
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
545
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
546
+
547
+ key_layer = index_first_axis( # pylint: disable=E0606
548
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
549
+ )
550
+ value_layer = index_first_axis( # pylint: disable=E0606
551
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
552
+ )
553
+ if query_length == kv_seq_len:
554
+ query_layer = index_first_axis( # pylint: disable=E0606
555
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
556
+ )
557
+ cu_seqlens_q = cu_seqlens_k
558
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
559
+ indices_q = indices_k
560
+ elif query_length == 1:
561
+ max_seqlen_in_batch_q = 1
562
+ cu_seqlens_q = torch.arange(
563
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
564
+ ) # There is a memcpy here, that is very bad.
565
+ indices_q = cu_seqlens_q[:-1]
566
+ query_layer = query_layer.squeeze(1)
567
+ else:
568
+ # The -q_len: slice assumes left padding.
569
+ attention_mask = attention_mask[:, -query_length:]
570
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input( # pylint: disable=E0606
571
+ query_layer, attention_mask
572
+ )
573
+
574
+ return (
575
+ query_layer,
576
+ key_layer,
577
+ value_layer,
578
+ indices_q,
579
+ (cu_seqlens_q, cu_seqlens_k),
580
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
581
+ )
582
+
583
+
584
+ # Copied from transformers.models.llama.modeling_llama.LllamaSdpaAttention with Llama->InternLM2
585
+ class InternLM2SdpaAttention(InternLM2Attention):
586
+ """
587
+ InternLM2 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
588
+ `InternLM2Attention` as the weights of the module stays untouched. The only changes are on the forward pass
589
+ to adapt to SDPA API.
590
+ """
591
+
592
+ # Adapted from InternLM2Attention.forward
593
+ def forward(
594
+ self,
595
+ hidden_states: torch.Tensor,
596
+ attention_mask: Optional[torch.Tensor] = None,
597
+ position_ids: Optional[torch.LongTensor] = None,
598
+ past_key_value: Optional[Cache] = None,
599
+ output_attentions: bool = False,
600
+ use_cache: bool = False,
601
+ cache_position: Optional[torch.LongTensor] = None,
602
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
603
+ if output_attentions:
604
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"`
605
+ # once this is implemented.
606
+ logger.warning_once(
607
+ "InternLM2Model uses InternLM2SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` "
608
+ "does not support `output_attentions=True`. Falling back to the manual attention implementation, "
609
+ "but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. "
610
+ 'This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
611
+ )
612
+ return super().forward(
613
+ hidden_states=hidden_states,
614
+ attention_mask=attention_mask,
615
+ position_ids=position_ids,
616
+ past_key_value=past_key_value,
617
+ output_attentions=output_attentions,
618
+ use_cache=use_cache,
619
+ cache_position=cache_position,
620
+ )
621
+
622
+ bsz, q_len, _ = hidden_states.size()
623
+
624
+ qkv_states = self.wqkv(hidden_states)
625
+
626
+ qkv_states = rearrange(
627
+ qkv_states,
628
+ "b q (h gs d) -> b q h gs d",
629
+ gs=2 + self.num_key_value_groups,
630
+ d=self.head_dim,
631
+ )
632
+
633
+ query_states = qkv_states[..., : self.num_key_value_groups, :]
634
+ query_states = rearrange(query_states, "b q h gs d -> b q (h gs) d")
635
+ key_states = qkv_states[..., -2, :]
636
+ value_states = qkv_states[..., -1, :]
637
+
638
+ query_states = query_states.transpose(1, 2)
639
+ key_states = key_states.transpose(1, 2)
640
+ value_states = value_states.transpose(1, 2)
641
+
642
+ cos, sin = self.rotary_emb(value_states, position_ids)
643
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
644
+
645
+ if past_key_value is not None:
646
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
647
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
648
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
649
+
650
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
651
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
652
+
653
+ causal_mask = attention_mask
654
+ if attention_mask is not None:
655
+ causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
656
+
657
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with
658
+ # custom attn_mask, Reference: https://github.com/pytorch/pytorch/issues/112577.
659
+ if query_states.device.type == "cuda" and causal_mask is not None:
660
+ query_states = query_states.contiguous()
661
+ key_states = key_states.contiguous()
662
+ value_states = value_states.contiguous()
663
+
664
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of
665
+ # an inline conditional assignment in SDPA to support both torch.compile's dynamic shapes and full graph
666
+ # options. An inline conditional prevents dynamic shapes from compiling.
667
+ is_causal = bool(causal_mask is None and q_len > 1)
668
+
669
+ attn_output = torch.nn.functional.scaled_dot_product_attention( # pylint: disable=E1102
670
+ query_states,
671
+ key_states,
672
+ value_states,
673
+ attn_mask=causal_mask,
674
+ dropout_p=0.0,
675
+ is_causal=is_causal,
676
+ )
677
+
678
+ attn_output = attn_output.transpose(1, 2).contiguous()
679
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
680
+
681
+ attn_output = self.wo(attn_output)
682
+
683
+ return attn_output, None, past_key_value
684
+
685
+
686
+ INTERNLM2_ATTENTION_CLASSES = {
687
+ "eager": InternLM2Attention,
688
+ "flash_attention_2": InternLM2FlashAttention2,
689
+ "sdpa": InternLM2SdpaAttention,
690
+ }
691
+
692
+
693
+ # Modified from transformers.models.llama.modeling_llama.LlamaDecoderLayer with Llama->InternLM2
694
+ class InternLM2DecoderLayer(nn.Module):
695
+ """InternLM2 Decoder Layer. This module is a single layer of the InternLM2 model."""
696
+
697
+ def __init__(self, config: InternLM2Config, layer_idx: int):
698
+ super().__init__()
699
+ self.hidden_size = config.hidden_size
700
+ self.layer_idx = layer_idx
701
+
702
+ self.attention = INTERNLM2_ATTENTION_CLASSES[config.attn_implementation](config=config, layer_idx=layer_idx)
703
+
704
+ self.feed_forward = InternLM2MLP(config)
705
+ self.attention_norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
706
+ self.ffn_norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
707
+
708
+ def forward(
709
+ self,
710
+ hidden_states: torch.Tensor,
711
+ attention_mask: Optional[torch.Tensor] = None,
712
+ position_ids: Optional[torch.LongTensor] = None,
713
+ past_key_value: Optional[Cache] = None,
714
+ output_attentions: Optional[bool] = False,
715
+ use_cache: Optional[bool] = False,
716
+ cache_position: Optional[torch.LongTensor] = None,
717
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
718
+ """
719
+ Args:
720
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
721
+ attention_mask (`torch.FloatTensor`, *optional*):
722
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
723
+ query_sequence_length, key_sequence_length)` if default attention is used.
724
+ output_attentions (`bool`, *optional*):
725
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
726
+ returned tensors for more detail.
727
+ use_cache (`bool`, *optional*):
728
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
729
+ (see `past_key_values`).
730
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
731
+ """
732
+ residual = hidden_states
733
+
734
+ hidden_states = self.attention_norm(hidden_states)
735
+
736
+ # Self Attention
737
+ hidden_states, self_attn_weights, present_key_value = self.attention(
738
+ hidden_states=hidden_states,
739
+ attention_mask=attention_mask,
740
+ position_ids=position_ids,
741
+ past_key_value=past_key_value,
742
+ output_attentions=output_attentions,
743
+ use_cache=use_cache,
744
+ cache_position=cache_position,
745
+ )
746
+ hidden_states = residual + hidden_states
747
+
748
+ # Fully Connected
749
+ residual = hidden_states
750
+ hidden_states = self.ffn_norm(hidden_states)
751
+ hidden_states = self.feed_forward(hidden_states)
752
+ hidden_states = residual + hidden_states
753
+
754
+ outputs = (hidden_states,)
755
+
756
+ if output_attentions:
757
+ outputs += (self_attn_weights,)
758
+
759
+ if use_cache:
760
+ outputs += (present_key_value,)
761
+
762
+ return outputs
763
+
764
+
765
+ InternLM2_START_DOCSTRING = r"""
766
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
767
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
768
+ etc.)
769
+
770
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
771
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
772
+ and behavior.
773
+
774
+ Parameters:
775
+ config ([`InternLM2Config`]):
776
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
777
+ load the weights associated with the model, only the configuration. Check out the
778
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
779
+ """
780
+
781
+
782
+ # Copied from transformers.models.llama.modeling_llama.LlamaPreTrainedModel with Llama->InternLM2
783
+ @add_start_docstrings(
784
+ "The bare InternLM2 Model outputting raw hidden-states without any specific head on top.",
785
+ InternLM2_START_DOCSTRING,
786
+ )
787
+ class InternLM2PreTrainedModel(PreTrainedModel):
788
+ """
789
+ InternLM2 pretraiend model's base class.
790
+ """
791
+
792
+ config_class = InternLM2Config
793
+ base_model_prefix = "model"
794
+ supports_gradient_checkpointing = True
795
+ _no_split_modules = ["InternLM2DecoderLayer"]
796
+ _skip_keys_device_placement = ["past_key_values"]
797
+ _supports_flash_attn_2 = True
798
+ _supports_sdpa = True
799
+ _supports_cache_class = True
800
+ _supports_quantized_cache = True
801
+ _supports_static_cache = True
802
+
803
+ def _init_weights(self, module):
804
+ std = self.config.initializer_range
805
+ if isinstance(module, nn.Linear):
806
+ module.weight.data.normal_(mean=0.0, std=std)
807
+ if module.bias is not None:
808
+ module.bias.data.zero_()
809
+ elif isinstance(module, nn.Embedding):
810
+ module.weight.data.normal_(mean=0.0, std=std)
811
+ if module.padding_idx is not None:
812
+ module.weight.data[module.padding_idx].zero_()
813
+
814
+
815
+ InternLM2_INPUTS_DOCSTRING = r"""
816
+ Args:
817
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
818
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
819
+ it.
820
+
821
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
822
+ [`PreTrainedTokenizer.__call__`] for details.
823
+
824
+ [What are input IDs?](../glossary#input-ids)
825
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
826
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
827
+
828
+ - 1 for tokens that are **not masked**,
829
+ - 0 for tokens that are **masked**.
830
+
831
+ [What are attention masks?](../glossary#attention-mask)
832
+
833
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
834
+ [`PreTrainedTokenizer.__call__`] for details.
835
+
836
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
837
+ `past_key_values`).
838
+
839
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
840
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
841
+ information on the default strategy.
842
+
843
+ - 1 indicates the head is **not masked**,
844
+ - 0 indicates the head is **masked**.
845
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
846
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
847
+ config.n_positions - 1]`.
848
+
849
+ [What are position IDs?](../glossary#position-ids)
850
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
851
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
852
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
853
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
854
+
855
+ Two formats are allowed:
856
+ - a [`~cache_utils.Cache`] instance;
857
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
858
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
859
+ cache format.
860
+
861
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
862
+ legacy cache format will be returned.
863
+
864
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
865
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
866
+ of shape `(batch_size, sequence_length)`.
867
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
868
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
869
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
870
+ model's internal embedding lookup matrix.
871
+ use_cache (`bool`, *optional*):
872
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
873
+ `past_key_values`).
874
+ output_attentions (`bool`, *optional*):
875
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
876
+ tensors for more detail.
877
+ output_hidden_states (`bool`, *optional*):
878
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
879
+ more detail.
880
+ return_dict (`bool`, *optional*):
881
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
882
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
883
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
884
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
885
+ the complete sequence length.
886
+ """
887
+
888
+
889
+ # Modified from transformers.models.llama.modeling_llama.LlamaModel with Llama->InternLM2
890
+ @add_start_docstrings(
891
+ "The bare InternLM2 Model outputting raw hidden-states without any specific head on top.",
892
+ InternLM2_START_DOCSTRING,
893
+ )
894
+ class InternLM2Model(InternLM2PreTrainedModel):
895
+ """
896
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`InternLM2DecoderLayer`]
897
+
898
+ Args:
899
+ config: InternLM2Config
900
+ """
901
+
902
+ _auto_class = "AutoModel"
903
+
904
+ def __init__(self, config: InternLM2Config):
905
+ super().__init__(config)
906
+ self.padding_idx = config.pad_token_id
907
+ self.vocab_size = config.vocab_size
908
+ self.config = config
909
+
910
+ self.tok_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
911
+
912
+ self.layers = nn.ModuleList(
913
+ [InternLM2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
914
+ )
915
+ self.norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
916
+
917
+ self.gradient_checkpointing = False
918
+ # Initialize weights and apply final processing
919
+ self.post_init()
920
+
921
+ def get_input_embeddings(self):
922
+ return self.tok_embeddings
923
+
924
+ def set_input_embeddings(self, value):
925
+ self.tok_embeddings = value
926
+
927
+ @add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
928
+ def forward(
929
+ self,
930
+ input_ids: torch.LongTensor = None,
931
+ attention_mask: Optional[torch.Tensor] = None,
932
+ position_ids: Optional[torch.LongTensor] = None,
933
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
934
+ inputs_embeds: Optional[torch.FloatTensor] = None,
935
+ use_cache: Optional[bool] = None,
936
+ output_attentions: Optional[bool] = None,
937
+ output_hidden_states: Optional[bool] = None,
938
+ return_dict: Optional[bool] = None,
939
+ cache_position: Optional[torch.LongTensor] = None,
940
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
941
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
942
+ output_hidden_states = (
943
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
944
+ )
945
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
946
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
947
+
948
+ if (input_ids is None) ^ (inputs_embeds is not None):
949
+ raise ValueError(
950
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
951
+ )
952
+
953
+ if self.gradient_checkpointing and self.training and use_cache:
954
+ logger.warning_once(
955
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
956
+ )
957
+ use_cache = False
958
+
959
+ if inputs_embeds is None:
960
+ inputs_embeds = self.tok_embeddings(input_ids)
961
+
962
+ return_legacy_cache = False
963
+ if use_cache and not isinstance(past_key_values, Cache): # kept for BC (non `Cache` `past_key_values` inputs)
964
+ return_legacy_cache = True
965
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
966
+
967
+ if cache_position is None:
968
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
969
+ cache_position = torch.arange(
970
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
971
+ )
972
+ if position_ids is None:
973
+ position_ids = cache_position.unsqueeze(0)
974
+
975
+ causal_mask = self._update_causal_mask(
976
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
977
+ )
978
+
979
+ # embed positions
980
+ hidden_states = inputs_embeds
981
+
982
+ # decoder layers
983
+ all_hidden_states = () if output_hidden_states else None
984
+ all_self_attns = () if output_attentions else None
985
+ next_decoder_cache = None
986
+
987
+ for decoder_layer in self.layers:
988
+ if output_hidden_states:
989
+ all_hidden_states += (hidden_states,)
990
+
991
+ if self.gradient_checkpointing and self.training:
992
+ layer_outputs = self._gradient_checkpointing_func(
993
+ decoder_layer.__call__,
994
+ hidden_states,
995
+ causal_mask,
996
+ position_ids,
997
+ past_key_values,
998
+ output_attentions,
999
+ use_cache,
1000
+ cache_position,
1001
+ )
1002
+ else:
1003
+ layer_outputs = decoder_layer(
1004
+ hidden_states,
1005
+ attention_mask=causal_mask,
1006
+ position_ids=position_ids,
1007
+ past_key_value=past_key_values,
1008
+ output_attentions=output_attentions,
1009
+ use_cache=use_cache,
1010
+ cache_position=cache_position,
1011
+ )
1012
+
1013
+ hidden_states = layer_outputs[0]
1014
+
1015
+ if use_cache:
1016
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1017
+
1018
+ if output_attentions:
1019
+ all_self_attns += (layer_outputs[1],)
1020
+
1021
+ hidden_states = self.norm(hidden_states)
1022
+
1023
+ # add hidden states from the last decoder layer
1024
+ if output_hidden_states:
1025
+ all_hidden_states += (hidden_states,)
1026
+
1027
+ next_cache = next_decoder_cache if use_cache else None
1028
+ if return_legacy_cache:
1029
+ next_cache = next_cache.to_legacy_cache()
1030
+
1031
+ if not return_dict:
1032
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1033
+ return BaseModelOutputWithPast(
1034
+ last_hidden_state=hidden_states,
1035
+ past_key_values=next_cache,
1036
+ hidden_states=all_hidden_states,
1037
+ attentions=all_self_attns,
1038
+ )
1039
+
1040
+ def _update_causal_mask(
1041
+ self,
1042
+ attention_mask: torch.Tensor,
1043
+ input_tensor: torch.Tensor,
1044
+ cache_position: torch.Tensor,
1045
+ past_key_values: Cache,
1046
+ output_attentions: bool,
1047
+ ):
1048
+ # TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length
1049
+ # even when the static KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at
1050
+ # each decode steps due to the dynamic shapes. (`recording cudagraph tree for symint key 13`, etc.), which is
1051
+ # VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using `fullgraph=True`.
1052
+ # See more context in https://github.com/huggingface/transformers/pull/29114
1053
+
1054
+ if self.config.attn_implementation == "flash_attention_2":
1055
+ if attention_mask is not None and 0.0 in attention_mask:
1056
+ return attention_mask
1057
+ return None
1058
+
1059
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
1060
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
1061
+ # to infer the attention mask.
1062
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1063
+ using_static_cache = isinstance(past_key_values, StaticCache)
1064
+
1065
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
1066
+ if self.config.attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
1067
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1068
+ attention_mask,
1069
+ inputs_embeds=input_tensor,
1070
+ past_key_values_length=past_seen_tokens,
1071
+ is_training=self.training,
1072
+ ):
1073
+ return None
1074
+
1075
+ dtype, device = input_tensor.dtype, input_tensor.device
1076
+ min_dtype = torch.finfo(dtype).min
1077
+ sequence_length = input_tensor.shape[1]
1078
+ if using_static_cache:
1079
+ target_length = past_key_values.get_max_length()
1080
+ else:
1081
+ target_length = (
1082
+ attention_mask.shape[-1]
1083
+ if isinstance(attention_mask, torch.Tensor)
1084
+ else past_seen_tokens + sequence_length + 1
1085
+ )
1086
+
1087
+ if attention_mask is not None and attention_mask.dim() == 4:
1088
+ # in this case we assume that the mask comes already in inverted form and requires no inversion or slicing
1089
+ if attention_mask.max() != 0:
1090
+ raise ValueError("Custom 4D attention mask should be passed in inverted form with max==0`")
1091
+ causal_mask = attention_mask
1092
+ else:
1093
+ causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device)
1094
+ if sequence_length != 1:
1095
+ causal_mask = torch.triu(causal_mask, diagonal=1)
1096
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
1097
+ causal_mask = causal_mask[None, None, :, :].expand(input_tensor.shape[0], 1, -1, -1)
1098
+ if attention_mask is not None:
1099
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1100
+ mask_length = attention_mask.shape[-1]
1101
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
1102
+ padding_mask = padding_mask == 0
1103
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
1104
+ padding_mask, min_dtype
1105
+ )
1106
+ if (
1107
+ self.config.attn_implementation == "sdpa"
1108
+ and attention_mask is not None
1109
+ and attention_mask.device.type == "cuda"
1110
+ and not output_attentions
1111
+ ):
1112
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1113
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1114
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1115
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype) # pylint: disable=E1120
1116
+
1117
+ return causal_mask
1118
+
1119
+
1120
+ # Modified from transformers.models.llama.modeling_llama.LlamaForCausalLM
1121
+ class InternLM2ForCausalLM(InternLM2PreTrainedModel):
1122
+ """Causal language model (CLM) for InternLM2."""
1123
+
1124
+ _auto_class = "AutoModelForCausalLM"
1125
+ _tied_weights_keys = ["output.weight"]
1126
+
1127
+ def __init__(self, config):
1128
+ super().__init__(config)
1129
+ self.model = InternLM2Model(config)
1130
+ self.vocab_size = config.vocab_size
1131
+ self.output = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1132
+
1133
+ # Initialize weights and apply final processing
1134
+ self.post_init()
1135
+
1136
+ def get_input_embeddings(self):
1137
+ return self.model.tok_embeddings
1138
+
1139
+ def set_input_embeddings(self, value):
1140
+ self.model.tok_embeddings = value
1141
+
1142
+ def get_output_embeddings(self):
1143
+ return self.output
1144
+
1145
+ def set_output_embeddings(self, new_embeddings):
1146
+ self.output = new_embeddings
1147
+
1148
+ def set_decoder(self, decoder):
1149
+ self.model = decoder
1150
+
1151
+ def get_decoder(self):
1152
+ return self.model
1153
+
1154
+ @add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
1155
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1156
+ def forward(
1157
+ self,
1158
+ input_ids: torch.LongTensor = None,
1159
+ attention_mask: Optional[torch.Tensor] = None,
1160
+ position_ids: Optional[torch.LongTensor] = None,
1161
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1162
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1163
+ labels: Optional[torch.LongTensor] = None,
1164
+ use_cache: Optional[bool] = None,
1165
+ output_attentions: Optional[bool] = None,
1166
+ output_hidden_states: Optional[bool] = None,
1167
+ return_dict: Optional[bool] = None,
1168
+ cache_position: Optional[torch.LongTensor] = None,
1169
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1170
+ r"""
1171
+ Args:
1172
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1173
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1174
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1175
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1176
+
1177
+ Returns:
1178
+
1179
+ Example:
1180
+
1181
+ ```python
1182
+ >>> from transformers import AutoTokenizer, InternLM2ForCausalLM
1183
+
1184
+ >>> model = InternLM2ForCausalLM.from_pretrained("meta-InternLM2/InternLM2-2-7b-hf")
1185
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-InternLM2/InternLM2-2-7b-hf")
1186
+
1187
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1188
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1189
+
1190
+ >>> # Generate
1191
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1192
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1193
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1194
+ ```"""
1195
+
1196
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1197
+ output_hidden_states = (
1198
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1199
+ )
1200
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1201
+
1202
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1203
+ outputs = self.model(
1204
+ input_ids=input_ids,
1205
+ attention_mask=attention_mask,
1206
+ position_ids=position_ids,
1207
+ past_key_values=past_key_values,
1208
+ inputs_embeds=inputs_embeds,
1209
+ use_cache=use_cache,
1210
+ output_attentions=output_attentions,
1211
+ output_hidden_states=output_hidden_states,
1212
+ return_dict=return_dict,
1213
+ cache_position=cache_position,
1214
+ )
1215
+
1216
+ hidden_states = outputs[0]
1217
+ if self.config.pretraining_tp > 1:
1218
+ output_slices = self.output.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1219
+ logits = [
1220
+ F.linear(hidden_states, output_slices[i]) # pylint: disable=not-callable
1221
+ for i in range(self.config.pretraining_tp)
1222
+ ]
1223
+ logits = torch.cat(logits, dim=-1)
1224
+ else:
1225
+ logits = self.output(hidden_states)
1226
+ logits = logits.float()
1227
+
1228
+ loss = None
1229
+ if labels is not None:
1230
+ # Shift so that tokens < n predict n
1231
+ shift_logits = logits[..., :-1, :].contiguous()
1232
+ shift_labels = labels[..., 1:].contiguous()
1233
+ # Flatten the tokens
1234
+ loss_fct = CrossEntropyLoss()
1235
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1236
+ shift_labels = shift_labels.view(-1)
1237
+ # Enable model parallelism
1238
+ shift_labels = shift_labels.to(shift_logits.device)
1239
+ loss = loss_fct(shift_logits, shift_labels)
1240
+
1241
+ if not return_dict:
1242
+ output = (logits,) + outputs[1:]
1243
+ return (loss,) + output if loss is not None else output
1244
+
1245
+ return CausalLMOutputWithPast(
1246
+ loss=loss,
1247
+ logits=logits,
1248
+ past_key_values=outputs.past_key_values,
1249
+ hidden_states=outputs.hidden_states,
1250
+ attentions=outputs.attentions,
1251
+ )
1252
+
1253
+ def prepare_inputs_for_generation(
1254
+ self,
1255
+ input_ids,
1256
+ past_key_values=None,
1257
+ attention_mask=None,
1258
+ inputs_embeds=None,
1259
+ cache_position=None,
1260
+ use_cache=True,
1261
+ **kwargs,
1262
+ ):
1263
+ past_length = 0
1264
+ if past_key_values is not None:
1265
+ if isinstance(past_key_values, Cache):
1266
+ past_length = cache_position[0] if cache_position is not None else past_key_values.get_seq_length()
1267
+ max_cache_length = (
1268
+ torch.tensor(past_key_values.get_max_length(), device=input_ids.device)
1269
+ if past_key_values.get_max_length() is not None
1270
+ else None
1271
+ )
1272
+ cache_length = past_length if max_cache_length is None else torch.min(max_cache_length, past_length)
1273
+ # TODO joao: remove this `else` after `generate` prioritizes `Cache` objects
1274
+ else:
1275
+ cache_length = past_length = past_key_values[0][0].shape[2]
1276
+ max_cache_length = None
1277
+
1278
+ # Keep only the unprocessed tokens:
1279
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1280
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as input)
1281
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1282
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1283
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1284
+ # input_ids based on the past_length.
1285
+ elif past_length < input_ids.shape[1]:
1286
+ input_ids = input_ids[:, past_length:]
1287
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1288
+
1289
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1290
+ if (
1291
+ max_cache_length is not None
1292
+ and attention_mask is not None
1293
+ and cache_length + input_ids.shape[1] > max_cache_length
1294
+ ):
1295
+ attention_mask = attention_mask[:, -max_cache_length:] # pylint: disable=E1130
1296
+
1297
+ position_ids = kwargs.get("position_ids", None)
1298
+ if attention_mask is not None and position_ids is None:
1299
+ # create position_ids on the fly for batch generation
1300
+ position_ids = attention_mask.long().cumsum(-1) - 1
1301
+ position_ids.masked_fill_(attention_mask == 0, 1)
1302
+ if past_key_values:
1303
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1304
+
1305
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1306
+ if inputs_embeds is not None and past_key_values is None:
1307
+ model_inputs = {"inputs_embeds": inputs_embeds}
1308
+ else:
1309
+ # The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
1310
+ # recompiles graphs as the stride of the inputs is a guard.
1311
+ # Ref: https://github.com/huggingface/transformers/pull/29114
1312
+ # TODO: use `next_tokens` directly instead.
1313
+ model_inputs = {"input_ids": input_ids.contiguous()}
1314
+
1315
+ input_length = position_ids.shape[-1] if position_ids is not None else input_ids.shape[-1]
1316
+ if cache_position is None:
1317
+ cache_position = torch.arange(past_length, past_length + input_length, device=input_ids.device)
1318
+ elif use_cache:
1319
+ cache_position = cache_position[-input_length:]
1320
+
1321
+ model_inputs.update(
1322
+ {
1323
+ "position_ids": position_ids,
1324
+ "cache_position": cache_position,
1325
+ "past_key_values": past_key_values,
1326
+ "use_cache": use_cache,
1327
+ "attention_mask": attention_mask,
1328
+ }
1329
+ )
1330
+ return model_inputs
1331
+
1332
+ @staticmethod
1333
+ def _reorder_cache(past_key_values, beam_idx):
1334
+ reordered_past = ()
1335
+ for layer_past in past_key_values:
1336
+ reordered_past += (
1337
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1338
+ )
1339
+ return reordered_past
1340
+
1341
+ def build_inputs(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, meta_instruction=""):
1342
+ if history is None:
1343
+ history = []
1344
+ if tokenizer.add_bos_token:
1345
+ prompt = ""
1346
+ else:
1347
+ prompt = tokenizer.bos_token
1348
+ if meta_instruction:
1349
+ prompt += f"""<|im_start|>system\n{meta_instruction}<|im_end|>\n"""
1350
+ for record in history:
1351
+ prompt += f"""<|im_start|>user\n{record[0]}<|im_end|>\n<|im_start|>assistant\n{record[1]}<|im_end|>\n"""
1352
+ prompt += f"""<|im_start|>user\n{query}<|im_end|>\n<|im_start|>assistant\n"""
1353
+ return tokenizer([prompt], return_tensors="pt")
1354
+
1355
+ @torch.no_grad()
1356
+ def chat(
1357
+ self,
1358
+ tokenizer,
1359
+ query: str,
1360
+ history: Optional[List[Tuple[str, str]]] = None,
1361
+ streamer: Optional[BaseStreamer] = None,
1362
+ max_new_tokens: int = 1024,
1363
+ do_sample: bool = True,
1364
+ temperature: float = 0.8,
1365
+ top_p: float = 0.8,
1366
+ meta_instruction: str = "You are an AI assistant whose name is InternLM (书生·浦语).\n"
1367
+ "- InternLM (书生·浦语) is a conversational language model that is developed by Shanghai AI Laboratory "
1368
+ "(上海人工智能实验室). It is designed to be helpful, honest, and harmless.\n"
1369
+ "- InternLM (书生·浦语) can understand and communicate fluently in the language chosen by the user such "
1370
+ "as English and 中文.",
1371
+ **kwargs,
1372
+ ):
1373
+ if history is None:
1374
+ history = []
1375
+ inputs = self.build_inputs(tokenizer, query, history, meta_instruction)
1376
+ inputs = {k: v.to(self.device) for k, v in inputs.items() if torch.is_tensor(v)}
1377
+ # also add end-of-assistant token in eos token id to avoid unnecessary generation
1378
+ eos_token_id = [tokenizer.eos_token_id, tokenizer.convert_tokens_to_ids(["<|im_end|>"])[0]]
1379
+ outputs = self.generate(
1380
+ **inputs,
1381
+ streamer=streamer,
1382
+ max_new_tokens=max_new_tokens,
1383
+ do_sample=do_sample,
1384
+ temperature=temperature,
1385
+ top_p=top_p,
1386
+ eos_token_id=eos_token_id,
1387
+ **kwargs,
1388
+ )
1389
+ outputs = outputs[0].cpu().tolist()[len(inputs["input_ids"][0]) :]
1390
+ response = tokenizer.decode(outputs, skip_special_tokens=True)
1391
+ response = response.split("<|im_end|>")[0]
1392
+ history = history + [(query, response)]
1393
+ return response, history
1394
+
1395
+ @torch.no_grad()
1396
+ def stream_chat(
1397
+ self,
1398
+ tokenizer,
1399
+ query: str,
1400
+ history: List[Tuple[str, str]] = None,
1401
+ max_new_tokens: int = 1024,
1402
+ do_sample: bool = True,
1403
+ temperature: float = 0.8,
1404
+ top_p: float = 0.8,
1405
+ **kwargs,
1406
+ ):
1407
+ if history is None:
1408
+ history = []
1409
+ """
1410
+ Return a generator in format: (response, history)
1411
+ Eg.
1412
+ ('你好,有什么可以帮助您的吗', [('你好', '你好,有什么可以帮助您的吗')])
1413
+ ('你好,有什么可以帮助您的吗?', [('你好', '你好,有什么可以帮助您的吗?')])
1414
+ """
1415
+ if BaseStreamer is None:
1416
+ raise ModuleNotFoundError(
1417
+ "The version of `transformers` is too low. Please make sure "
1418
+ "that you have installed `transformers>=4.28.0`."
1419
+ )
1420
+
1421
+ response_queue = queue.Queue(maxsize=20)
1422
+
1423
+ class ChatStreamer(BaseStreamer):
1424
+ """
1425
+ Streamer used in generate to print words one by one.
1426
+ """
1427
+
1428
+ def __init__(self, tokenizer) -> None:
1429
+ super().__init__()
1430
+ self.tokenizer = tokenizer
1431
+ self.queue = response_queue
1432
+ self.query = query
1433
+ self.history = history
1434
+ self.response = ""
1435
+ self.cache = []
1436
+ self.received_inputs = False
1437
+ self.queue.put((self.response, history + [(self.query, self.response)]))
1438
+
1439
+ def put(self, value):
1440
+ if len(value.shape) > 1 and value.shape[0] > 1:
1441
+ raise ValueError("ChatStreamer only supports batch size 1")
1442
+ elif len(value.shape) > 1:
1443
+ value = value[0]
1444
+
1445
+ if not self.received_inputs:
1446
+ # The first received value is input_ids, ignore here
1447
+ self.received_inputs = True
1448
+ return
1449
+
1450
+ self.cache.extend(value.tolist())
1451
+ token = self.tokenizer.decode(self.cache, skip_special_tokens=True)
1452
+ if token.strip() != "<|im_end|>":
1453
+ self.response = self.response + token
1454
+ history = self.history + [(self.query, self.response)]
1455
+ self.queue.put((self.response, history))
1456
+ self.cache = []
1457
+ else:
1458
+ self.end()
1459
+
1460
+ def end(self):
1461
+ self.queue.put(None)
1462
+
1463
+ def stream_producer():
1464
+ return self.chat(
1465
+ tokenizer=tokenizer,
1466
+ query=query,
1467
+ streamer=ChatStreamer(tokenizer=tokenizer),
1468
+ history=history,
1469
+ max_new_tokens=max_new_tokens,
1470
+ do_sample=do_sample,
1471
+ temperature=temperature,
1472
+ top_p=top_p,
1473
+ **kwargs,
1474
+ )
1475
+
1476
+ def consumer():
1477
+ producer = threading.Thread(target=stream_producer)
1478
+ producer.start()
1479
+ while True:
1480
+ res = response_queue.get()
1481
+ if res is None:
1482
+ return
1483
+ yield res
1484
+
1485
+ return consumer()
1486
+
1487
+
1488
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->InternLM2
1489
+ @add_start_docstrings(
1490
+ """
1491
+ The InternLM2 Model transformer with a sequence classification head on top (linear layer).
1492
+
1493
+ [`InternLM2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1494
+ (e.g. GPT-2) do.
1495
+
1496
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1497
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1498
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1499
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1500
+ each row of the batch).
1501
+ """,
1502
+ InternLM2_START_DOCSTRING,
1503
+ )
1504
+ class InternLM2ForSequenceClassification(InternLM2PreTrainedModel):
1505
+ """Sequence Classification Head for InternLM2 Model."""
1506
+
1507
+ def __init__(self, config):
1508
+ super().__init__(config)
1509
+ self.num_labels = config.num_labels
1510
+ self.model = InternLM2Model(config)
1511
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1512
+
1513
+ # Initialize weights and apply final processing
1514
+ self.post_init()
1515
+
1516
+ def get_input_embeddings(self):
1517
+ return self.model.tok_embeddings
1518
+
1519
+ def set_input_embeddings(self, value):
1520
+ self.model.tok_embeddings = value
1521
+
1522
+ @add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
1523
+ def forward(
1524
+ self,
1525
+ input_ids: torch.LongTensor = None,
1526
+ attention_mask: Optional[torch.Tensor] = None,
1527
+ position_ids: Optional[torch.LongTensor] = None,
1528
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1529
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1530
+ labels: Optional[torch.LongTensor] = None,
1531
+ use_cache: Optional[bool] = None,
1532
+ output_attentions: Optional[bool] = None,
1533
+ output_hidden_states: Optional[bool] = None,
1534
+ return_dict: Optional[bool] = None,
1535
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1536
+ r"""
1537
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1538
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1539
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1540
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1541
+ """
1542
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1543
+
1544
+ transformer_outputs = self.model(
1545
+ input_ids,
1546
+ attention_mask=attention_mask,
1547
+ position_ids=position_ids,
1548
+ past_key_values=past_key_values,
1549
+ inputs_embeds=inputs_embeds,
1550
+ use_cache=use_cache,
1551
+ output_attentions=output_attentions,
1552
+ output_hidden_states=output_hidden_states,
1553
+ return_dict=return_dict,
1554
+ )
1555
+ hidden_states = transformer_outputs[0]
1556
+ logits = self.score(hidden_states)
1557
+
1558
+ if input_ids is not None:
1559
+ batch_size = input_ids.shape[0]
1560
+ else:
1561
+ batch_size = inputs_embeds.shape[0]
1562
+
1563
+ if self.config.pad_token_id is None and batch_size != 1:
1564
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1565
+ if self.config.pad_token_id is None:
1566
+ sequence_lengths = -1
1567
+ else:
1568
+ if input_ids is not None:
1569
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1570
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1571
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1572
+ sequence_lengths = sequence_lengths.to(logits.device)
1573
+ else:
1574
+ sequence_lengths = -1
1575
+
1576
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1577
+
1578
+ loss = None
1579
+ if labels is not None:
1580
+ labels = labels.to(logits.device)
1581
+ if self.config.problem_type is None:
1582
+ if self.num_labels == 1:
1583
+ self.config.problem_type = "regression"
1584
+ elif self.num_labels > 1 and (labels.dtype in (torch.long, torch.int)):
1585
+ self.config.problem_type = "single_label_classification"
1586
+ else:
1587
+ self.config.problem_type = "multi_label_classification"
1588
+
1589
+ if self.config.problem_type == "regression":
1590
+ loss_fct = MSELoss()
1591
+ if self.num_labels == 1:
1592
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1593
+ else:
1594
+ loss = loss_fct(pooled_logits, labels)
1595
+ elif self.config.problem_type == "single_label_classification":
1596
+ loss_fct = CrossEntropyLoss()
1597
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1598
+ elif self.config.problem_type == "multi_label_classification":
1599
+ loss_fct = BCEWithLogitsLoss()
1600
+ loss = loss_fct(pooled_logits, labels)
1601
+ if not return_dict:
1602
+ output = (pooled_logits,) + transformer_outputs[1:]
1603
+ return ((loss,) + output) if loss is not None else output
1604
+
1605
+ return SequenceClassifierOutputWithPast(
1606
+ loss=loss,
1607
+ logits=pooled_logits,
1608
+ past_key_values=transformer_outputs.past_key_values,
1609
+ hidden_states=transformer_outputs.hidden_states,
1610
+ attentions=transformer_outputs.attentions,
1611
+ )
1612
+
1613
+
1614
+ # Copied from transformers.models.llama.modeling_llama.LlamaForQuestionAnswering with Llama->InternLM2
1615
+ @add_start_docstrings(
1616
+ """
1617
+ The InternLM2 Model transformer with a span classification head on top for extractive question-answering tasks like
1618
+ SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1619
+ """,
1620
+ InternLM2_START_DOCSTRING,
1621
+ )
1622
+ class InternLM2ForQuestionAnswering(InternLM2PreTrainedModel):
1623
+ """Question Answering model for InternLM2."""
1624
+
1625
+ base_model_prefix = "transformer"
1626
+
1627
+ def __init__(self, config):
1628
+ super().__init__(config)
1629
+ self.transformer = InternLM2Model(config)
1630
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1631
+
1632
+ # Initialize weights and apply final processing
1633
+ self.post_init()
1634
+
1635
+ def get_input_embeddings(self):
1636
+ return self.transformer.tok_embeddings
1637
+
1638
+ def set_input_embeddings(self, value):
1639
+ self.transformer.tok_embeddings = value
1640
+
1641
+ @add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
1642
+ def forward(
1643
+ self,
1644
+ input_ids: Optional[torch.LongTensor] = None,
1645
+ attention_mask: Optional[torch.FloatTensor] = None,
1646
+ position_ids: Optional[torch.LongTensor] = None,
1647
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1648
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1649
+ start_positions: Optional[torch.LongTensor] = None,
1650
+ end_positions: Optional[torch.LongTensor] = None,
1651
+ output_attentions: Optional[bool] = None,
1652
+ output_hidden_states: Optional[bool] = None,
1653
+ return_dict: Optional[bool] = None,
1654
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1655
+ r"""
1656
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1657
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1658
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1659
+ are not taken into account for computing the loss.
1660
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1661
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1662
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1663
+ are not taken into account for computing the loss.
1664
+ """
1665
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1666
+
1667
+ outputs = self.transformer(
1668
+ input_ids,
1669
+ attention_mask=attention_mask,
1670
+ position_ids=position_ids,
1671
+ past_key_values=past_key_values,
1672
+ inputs_embeds=inputs_embeds,
1673
+ output_attentions=output_attentions,
1674
+ output_hidden_states=output_hidden_states,
1675
+ return_dict=return_dict,
1676
+ )
1677
+
1678
+ sequence_output = outputs[0]
1679
+
1680
+ logits = self.qa_outputs(sequence_output)
1681
+ start_logits, end_logits = logits.split(1, dim=-1)
1682
+ start_logits = start_logits.squeeze(-1).contiguous()
1683
+ end_logits = end_logits.squeeze(-1).contiguous()
1684
+
1685
+ total_loss = None
1686
+ if start_positions is not None and end_positions is not None:
1687
+ # If we are on multi-GPU, split add a dimension
1688
+ if len(start_positions.size()) > 1:
1689
+ start_positions = start_positions.squeeze(-1).to(start_logits.device)
1690
+ if len(end_positions.size()) > 1:
1691
+ end_positions = end_positions.squeeze(-1).to(end_logits.device)
1692
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1693
+ ignored_index = start_logits.size(1)
1694
+ start_positions = start_positions.clamp(0, ignored_index)
1695
+ end_positions = end_positions.clamp(0, ignored_index)
1696
+
1697
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1698
+ start_loss = loss_fct(start_logits, start_positions)
1699
+ end_loss = loss_fct(end_logits, end_positions)
1700
+ total_loss = (start_loss + end_loss) / 2
1701
+
1702
+ if not return_dict:
1703
+ output = (start_logits, end_logits) + outputs[2:]
1704
+ return ((total_loss,) + output) if total_loss is not None else output
1705
+
1706
+ return QuestionAnsweringModelOutput(
1707
+ loss=total_loss,
1708
+ start_logits=start_logits,
1709
+ end_logits=end_logits,
1710
+ hidden_states=outputs.hidden_states,
1711
+ attentions=outputs.attentions,
1712
+ )
1713
+
1714
+
1715
+ # Copied from transformers.models.llama.modeling_llama.LlamaForTokenClassification with Llama->InternLM2
1716
+ @add_start_docstrings(
1717
+ """
1718
+ The InternLM2 Model transformer with a token classification head on top (a linear layer on top of the hidden-states
1719
+ output) e.g. for Named-Entity-Recognition (NER) tasks.
1720
+ """,
1721
+ InternLM2_START_DOCSTRING,
1722
+ )
1723
+ class InternLM2ForTokenClassification(InternLM2PreTrainedModel):
1724
+ """Token classification model for InternLM2."""
1725
+
1726
+ def __init__(self, config):
1727
+ super().__init__(config)
1728
+ self.num_labels = config.num_labels
1729
+ self.model = InternLM2Model(config)
1730
+ if getattr(config, "classifier_dropout", None) is not None:
1731
+ classifier_dropout = config.classifier_dropout
1732
+ elif getattr(config, "hidden_dropout", None) is not None:
1733
+ classifier_dropout = config.hidden_dropout
1734
+ else:
1735
+ classifier_dropout = 0.1
1736
+ self.dropout = nn.Dropout(classifier_dropout)
1737
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
1738
+
1739
+ # Initialize weights and apply final processing
1740
+ self.post_init()
1741
+
1742
+ def get_input_embeddings(self):
1743
+ return self.model.tok_embeddings
1744
+
1745
+ def set_input_embeddings(self, value):
1746
+ self.model.tok_embeddings = value
1747
+
1748
+ @add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
1749
+ def forward(
1750
+ self,
1751
+ input_ids: torch.LongTensor = None,
1752
+ attention_mask: Optional[torch.Tensor] = None,
1753
+ position_ids: Optional[torch.LongTensor] = None,
1754
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1755
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1756
+ labels: Optional[torch.LongTensor] = None,
1757
+ use_cache: Optional[bool] = None,
1758
+ output_attentions: Optional[bool] = None,
1759
+ output_hidden_states: Optional[bool] = None,
1760
+ return_dict: Optional[bool] = None,
1761
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1762
+ r"""
1763
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1764
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1765
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1766
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1767
+ """
1768
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1769
+
1770
+ outputs = self.model(
1771
+ input_ids,
1772
+ attention_mask=attention_mask,
1773
+ position_ids=position_ids,
1774
+ past_key_values=past_key_values,
1775
+ inputs_embeds=inputs_embeds,
1776
+ use_cache=use_cache,
1777
+ output_attentions=output_attentions,
1778
+ output_hidden_states=output_hidden_states,
1779
+ return_dict=return_dict,
1780
+ )
1781
+ sequence_output = outputs[0]
1782
+ sequence_output = self.dropout(sequence_output)
1783
+ logits = self.score(sequence_output)
1784
+
1785
+ loss = None
1786
+ if labels is not None:
1787
+ loss_fct = CrossEntropyLoss()
1788
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1789
+
1790
+ if not return_dict:
1791
+ output = (logits,) + outputs[2:]
1792
+ return ((loss,) + output) if loss is not None else output
1793
+
1794
+ return TokenClassifierOutput(
1795
+ loss=loss,
1796
+ logits=logits,
1797
+ hidden_states=outputs.hidden_states,
1798
+ attentions=outputs.attentions,
1799
+ )
modeling_internlm2_below_4_38_0.py ADDED
@@ -0,0 +1,1424 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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: # noqa: E722 # pylint: disable=bare-except
46
+ BaseStreamer = None
47
+
48
+ from .configuration_internlm2 import InternLM2Config
49
+
50
+ logger = logging.get_logger(__name__)
51
+
52
+ _CONFIG_FOR_DOC = "InternLM2Config"
53
+
54
+ flash_attn_func, flash_attn_varlen_func = None, None
55
+ pad_input, index_first_axis, unpad_input = None, None, None
56
+
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
+ """InternLM2RMSNorm is equivalent to T5LayerNorm."""
123
+
124
+ def __init__(self, hidden_size, eps=1e-6):
125
+ """
126
+ InternLM2RMSNorm is equivalent to T5LayerNorm
127
+ """
128
+ super().__init__()
129
+ self.weight = nn.Parameter(torch.ones(hidden_size))
130
+ self.variance_epsilon = eps
131
+
132
+ def forward(self, hidden_states):
133
+ input_dtype = hidden_states.dtype
134
+ hidden_states = hidden_states.to(torch.float32)
135
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
136
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
137
+ return self.weight * hidden_states.to(input_dtype)
138
+
139
+
140
+ # Copied from transformers.model.llama.modeling_llama.LlamaRotaryEmbedding with Llama->InternLM2
141
+ class InternLM2RotaryEmbedding(nn.Module):
142
+ """Rotary Position Embedding for the InternLM2 model. Credits to the Reddit user /u/lucidrains."""
143
+
144
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
145
+ super().__init__()
146
+
147
+ self.dim = dim
148
+ self.max_position_embeddings = max_position_embeddings
149
+ self.base = base
150
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
151
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
152
+
153
+ # Build here to make `torch.jit.trace` work.
154
+ self._set_cos_sin_cache(
155
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
156
+ )
157
+
158
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
159
+ self.max_seq_len_cached = seq_len
160
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
161
+
162
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
163
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
164
+ emb = torch.cat((freqs, freqs), dim=-1)
165
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
166
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
167
+
168
+ def forward(self, x, seq_len=None):
169
+ # x: [bs, num_attention_heads, seq_len, head_size]
170
+ if seq_len > self.max_seq_len_cached:
171
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=torch.float32)
172
+
173
+ return (
174
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
175
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
176
+ )
177
+
178
+
179
+ # Copied from transformers.model.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->InternLM2
180
+ class InternLM2LinearScalingRotaryEmbedding(InternLM2RotaryEmbedding):
181
+ """InternLM2RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
182
+
183
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
184
+ self.scaling_factor = scaling_factor
185
+ super().__init__(dim, max_position_embeddings, base, device)
186
+
187
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
188
+ self.max_seq_len_cached = seq_len
189
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
190
+ t = t / self.scaling_factor
191
+
192
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
193
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
194
+ emb = torch.cat((freqs, freqs), dim=-1)
195
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
196
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
197
+
198
+
199
+ # Copied from transformers.model.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->InternLM2
200
+ class InternLM2DynamicNTKScalingRotaryEmbedding(InternLM2RotaryEmbedding):
201
+ """InternLM2RotaryEmbedding extended with Dynamic NTK scaling.
202
+ Credits to the Reddit users /u/bloc97 and /u/emozilla.
203
+ """
204
+
205
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
206
+ self.scaling_factor = scaling_factor
207
+ super().__init__(dim, max_position_embeddings, base, device)
208
+
209
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
210
+ self.max_seq_len_cached = seq_len
211
+
212
+ if seq_len > self.max_position_embeddings:
213
+ base = self.base * (
214
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
215
+ ) ** (self.dim / (self.dim - 2))
216
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
217
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
218
+
219
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
220
+
221
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
222
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
223
+ emb = torch.cat((freqs, freqs), dim=-1)
224
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
225
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
226
+
227
+
228
+ # Copied from transformers.model.llama.modeling_llama.rotate_half
229
+ def rotate_half(x):
230
+ """Rotates half the hidden dims of the input."""
231
+ x1 = x[..., : x.shape[-1] // 2]
232
+ x2 = x[..., x.shape[-1] // 2 :]
233
+ return torch.cat((-x2, x1), dim=-1)
234
+
235
+
236
+ # Copied from transformers.model.llama.modeling_llama.apply_rotary_pos_emb
237
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
238
+ """Applies Rotary Position Embedding to the query and key tensors."""
239
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
240
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
241
+ q_embed = (q * cos) + (rotate_half(q) * sin)
242
+ k_embed = (k * cos) + (rotate_half(k) * sin)
243
+ return q_embed, k_embed
244
+
245
+
246
+ class InternLM2MLP(nn.Module):
247
+ """MLP for InternLM2 model."""
248
+
249
+ def __init__(self, config):
250
+ super().__init__()
251
+ self.config = config
252
+ self.hidden_size = config.hidden_size
253
+ self.intermediate_size = config.intermediate_size
254
+ self.w1 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
255
+ self.w3 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
256
+ self.w2 = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
257
+ self.act_fn = ACT2FN[config.hidden_act]
258
+
259
+ def forward(self, x):
260
+ down_proj = self.w2(self.act_fn(self.w1(x)) * self.w3(x))
261
+
262
+ return down_proj
263
+
264
+
265
+ # Copied from transformers.model.llama.modeling_llama.repeat_kv
266
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
267
+ """
268
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
269
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
270
+ """
271
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
272
+ if n_rep == 1:
273
+ return hidden_states
274
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
275
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
276
+
277
+
278
+ # Modified from transformers.model.llama.modeling_llama.LlamaAttention
279
+ class InternLM2Attention(nn.Module):
280
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
281
+
282
+ def __init__(self, config: InternLM2Config):
283
+ super().__init__()
284
+ self.config = config
285
+ self.hidden_size = config.hidden_size
286
+ self.num_heads = config.num_attention_heads
287
+ self.head_dim = self.hidden_size // self.num_heads
288
+ self.num_key_value_heads = config.num_key_value_heads
289
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
290
+ self.max_position_embeddings = config.max_position_embeddings
291
+ self.is_causal = True
292
+
293
+ if (self.head_dim * self.num_heads) != self.hidden_size:
294
+ raise ValueError(
295
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
296
+ f" and `num_heads`: {self.num_heads})."
297
+ )
298
+
299
+ self.wqkv = nn.Linear(
300
+ self.hidden_size,
301
+ (self.num_heads + 2 * self.num_key_value_heads) * self.head_dim,
302
+ bias=config.bias,
303
+ )
304
+
305
+ self.wo = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.bias)
306
+ self._init_rope()
307
+
308
+ def _init_rope(self):
309
+ if self.config.rope_scaling is None:
310
+ self.rotary_emb = InternLM2RotaryEmbedding(
311
+ self.head_dim,
312
+ max_position_embeddings=self.max_position_embeddings,
313
+ base=self.config.rope_theta,
314
+ )
315
+ else:
316
+ scaling_type = self.config.rope_scaling["type"]
317
+ scaling_factor = self.config.rope_scaling["factor"]
318
+ if scaling_type == "dynamic":
319
+ self.rotary_emb = InternLM2DynamicNTKScalingRotaryEmbedding(
320
+ self.head_dim,
321
+ max_position_embeddings=self.max_position_embeddings,
322
+ base=self.config.rope_theta,
323
+ scaling_factor=scaling_factor,
324
+ )
325
+ elif scaling_type == "linear":
326
+ self.rotary_emb = InternLM2LinearScalingRotaryEmbedding(
327
+ self.head_dim,
328
+ max_position_embeddings=self.max_position_embeddings,
329
+ base=self.config.rope_theta,
330
+ scaling_factor=scaling_factor,
331
+ )
332
+ else:
333
+ raise ValueError("Currently we only support rotary embedding's type being 'dynamic' or 'linear'.")
334
+ return self.rotary_emb
335
+
336
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
337
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
338
+
339
+ def forward(
340
+ self,
341
+ hidden_states: torch.Tensor,
342
+ attention_mask: Optional[torch.Tensor] = None,
343
+ position_ids: Optional[torch.LongTensor] = None,
344
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
345
+ output_attentions: bool = False,
346
+ use_cache: bool = False,
347
+ **kwargs,
348
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
349
+ if "padding_mask" in kwargs:
350
+ warnings.warn(
351
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. "
352
+ "Please make sure use `attention_mask` instead.`"
353
+ )
354
+
355
+ bsz, q_len, _ = hidden_states.size()
356
+
357
+ qkv_states = self.wqkv(hidden_states)
358
+
359
+ qkv_states = rearrange(
360
+ qkv_states,
361
+ "b q (h gs d) -> b q h gs d",
362
+ gs=2 + self.num_key_value_groups,
363
+ d=self.head_dim,
364
+ )
365
+
366
+ query_states = qkv_states[..., : self.num_key_value_groups, :]
367
+ query_states = rearrange(query_states, "b q h gs d -> b q (h gs) d")
368
+ key_states = qkv_states[..., -2, :]
369
+ value_states = qkv_states[..., -1, :]
370
+
371
+ query_states = query_states.transpose(1, 2)
372
+ key_states = key_states.transpose(1, 2)
373
+ value_states = value_states.transpose(1, 2)
374
+
375
+ kv_seq_len = key_states.shape[-2]
376
+ if past_key_value is not None:
377
+ kv_seq_len += past_key_value[0].shape[-2]
378
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
379
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
380
+
381
+ if past_key_value is not None:
382
+ # reuse k, v, self_attention
383
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
384
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
385
+
386
+ past_key_value = (key_states, value_states) if use_cache else None
387
+
388
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
389
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
390
+
391
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
392
+
393
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
394
+ raise ValueError(
395
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
396
+ f" {attn_weights.size()}"
397
+ )
398
+
399
+ if attention_mask is not None:
400
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
401
+ raise ValueError(
402
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
403
+ )
404
+ attn_weights = attn_weights + attention_mask
405
+
406
+ # upcast attention to fp32
407
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
408
+ attn_output = torch.matmul(attn_weights, value_states)
409
+
410
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
411
+ raise ValueError(
412
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
413
+ f" {attn_output.size()}"
414
+ )
415
+
416
+ attn_output = attn_output.transpose(1, 2).contiguous()
417
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
418
+
419
+ attn_output = self.wo(attn_output)
420
+
421
+ if not output_attentions:
422
+ attn_weights = None
423
+
424
+ return attn_output, attn_weights, past_key_value
425
+
426
+
427
+ # Modified from transformers.model.llama.modeling_llama.InternLM2FlashAttention2
428
+ class InternLM2FlashAttention2(InternLM2Attention):
429
+ """
430
+ InternLM2 flash attention module. This module inherits from `InternLM2Attention` as the weights of the module stays
431
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
432
+ flash attention and deal with padding tokens in case the input contains any of them.
433
+ """
434
+
435
+ def forward(
436
+ self,
437
+ hidden_states: torch.Tensor,
438
+ attention_mask: Optional[torch.LongTensor] = None,
439
+ position_ids: Optional[torch.LongTensor] = None,
440
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
441
+ output_attentions: bool = False,
442
+ use_cache: bool = False,
443
+ **kwargs,
444
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
445
+ # InternLM2FlashAttention2 attention does not support output_attentions
446
+ if "padding_mask" in kwargs:
447
+ warnings.warn(
448
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. "
449
+ "Please make sure use `attention_mask` instead.`"
450
+ )
451
+
452
+ # overwrite attention_mask with padding_mask
453
+ attention_mask = kwargs.pop("padding_mask")
454
+
455
+ output_attentions = False
456
+
457
+ bsz, q_len, _ = hidden_states.size()
458
+
459
+ qkv_states = self.wqkv(hidden_states)
460
+
461
+ qkv_states = rearrange(
462
+ qkv_states,
463
+ "b q (h gs d) -> b q h gs d",
464
+ gs=2 + self.num_key_value_groups,
465
+ d=self.head_dim,
466
+ )
467
+
468
+ query_states = qkv_states[..., : self.num_key_value_groups, :]
469
+ query_states = rearrange(query_states, "b q h gs d -> b q (h gs) d")
470
+ key_states = qkv_states[..., -2, :]
471
+ value_states = qkv_states[..., -1, :]
472
+
473
+ query_states = query_states.transpose(1, 2)
474
+ key_states = key_states.transpose(1, 2)
475
+ value_states = value_states.transpose(1, 2)
476
+
477
+ kv_seq_len = key_states.shape[-2]
478
+ if past_key_value is not None:
479
+ kv_seq_len += past_key_value[0].shape[-2]
480
+
481
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
482
+
483
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
484
+
485
+ if past_key_value is not None:
486
+ # reuse k, v, self_attention
487
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
488
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
489
+
490
+ past_key_value = (key_states, value_states) if use_cache else None
491
+
492
+ query_states = query_states.transpose(1, 2)
493
+ key_states = key_states.transpose(1, 2)
494
+ value_states = value_states.transpose(1, 2)
495
+
496
+ attn_output = self._flash_attention_forward(query_states, key_states, value_states, attention_mask, q_len)
497
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
498
+ attn_output = self.wo(attn_output)
499
+
500
+ if not output_attentions:
501
+ attn_weights = None
502
+
503
+ return attn_output, attn_weights, past_key_value
504
+
505
+ def _flash_attention_forward(
506
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
507
+ ):
508
+ """
509
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
510
+ first unpad the input, then computes the attention scores and pad the final attention scores.
511
+
512
+ Args:
513
+ query_states (`torch.Tensor`):
514
+ Input query states to be passed to Flash Attention API
515
+ key_states (`torch.Tensor`):
516
+ Input key states to be passed to Flash Attention API
517
+ value_states (`torch.Tensor`):
518
+ Input value states to be passed to Flash Attention API
519
+ attention_mask (`torch.Tensor`):
520
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
521
+ position of padding tokens and 1 for the position of non-padding tokens.
522
+ dropout (`int`, *optional*):
523
+ Attention dropout
524
+ softmax_scale (`float`, *optional*):
525
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
526
+ """
527
+ # Contains at least one padding token in the sequence
528
+ causal = self.is_causal and query_length != 1
529
+ if attention_mask is not None:
530
+ batch_size = query_states.shape[0]
531
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._unpad_input(
532
+ query_states, key_states, value_states, attention_mask, query_length
533
+ )
534
+
535
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
536
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
537
+
538
+ attn_output_unpad = flash_attn_varlen_func(
539
+ query_states,
540
+ key_states,
541
+ value_states,
542
+ cu_seqlens_q=cu_seqlens_q,
543
+ cu_seqlens_k=cu_seqlens_k,
544
+ max_seqlen_q=max_seqlen_in_batch_q,
545
+ max_seqlen_k=max_seqlen_in_batch_k,
546
+ dropout_p=dropout,
547
+ softmax_scale=softmax_scale,
548
+ causal=causal,
549
+ )
550
+
551
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
552
+ else:
553
+ attn_output = flash_attn_func(
554
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
555
+ )
556
+
557
+ return attn_output
558
+
559
+ def _unpad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
560
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
561
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
562
+
563
+ key_layer = index_first_axis(
564
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
565
+ )
566
+ value_layer = index_first_axis(
567
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
568
+ )
569
+
570
+ if query_length == kv_seq_len:
571
+ query_layer = index_first_axis(
572
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
573
+ )
574
+ cu_seqlens_q = cu_seqlens_k
575
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
576
+ indices_q = indices_k
577
+ elif query_length == 1:
578
+ max_seqlen_in_batch_q = 1
579
+ cu_seqlens_q = torch.arange(
580
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
581
+ ) # There is a memcpy here, that is very bad.
582
+ indices_q = cu_seqlens_q[:-1]
583
+ query_layer = query_layer.squeeze(1)
584
+ else:
585
+ # The -q_len: slice assumes left padding.
586
+ attention_mask = attention_mask[:, -query_length:]
587
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
588
+
589
+ return (
590
+ query_layer,
591
+ key_layer,
592
+ value_layer,
593
+ indices_q.to(torch.int64),
594
+ (cu_seqlens_q, cu_seqlens_k),
595
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
596
+ )
597
+
598
+
599
+ INTERNLM2_ATTENTION_CLASSES = {
600
+ "eager": InternLM2Attention,
601
+ "flash_attention_2": InternLM2FlashAttention2,
602
+ }
603
+
604
+
605
+ # Modified from transformers.model.llama.modeling_llama.LlamaDecoderLayer
606
+ class InternLM2DecoderLayer(nn.Module):
607
+ """InternLM2 Decoder Layer. This module is a single layer of the InternLM2 model."""
608
+
609
+ def __init__(self, config: InternLM2Config):
610
+ super().__init__()
611
+ self.hidden_size = config.hidden_size
612
+
613
+ self.attention = INTERNLM2_ATTENTION_CLASSES[config.attn_implementation](config=config)
614
+
615
+ self.feed_forward = InternLM2MLP(config)
616
+ self.attention_norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
617
+ self.ffn_norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
618
+
619
+ def forward(
620
+ self,
621
+ hidden_states: torch.Tensor,
622
+ attention_mask: Optional[torch.Tensor] = None,
623
+ position_ids: Optional[torch.LongTensor] = None,
624
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
625
+ output_attentions: Optional[bool] = False,
626
+ use_cache: Optional[bool] = False,
627
+ **kwargs,
628
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
629
+ """
630
+ Args:
631
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
632
+ attention_mask (`torch.FloatTensor`, *optional*):
633
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
634
+ query_sequence_length, key_sequence_length)` if default attention is used.
635
+ output_attentions (`bool`, *optional*):
636
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
637
+ returned tensors for more detail.
638
+ use_cache (`bool`, *optional*):
639
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
640
+ (see `past_key_values`).
641
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
642
+ """
643
+ if "padding_mask" in kwargs:
644
+ warnings.warn(
645
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. "
646
+ "Please make sure use `attention_mask` instead.`"
647
+ )
648
+
649
+ residual = hidden_states
650
+
651
+ hidden_states = self.attention_norm(hidden_states)
652
+
653
+ # Self Attention
654
+ hidden_states, self_attn_weights, present_key_value = self.attention(
655
+ hidden_states=hidden_states,
656
+ attention_mask=attention_mask,
657
+ position_ids=position_ids,
658
+ past_key_value=past_key_value,
659
+ output_attentions=output_attentions,
660
+ use_cache=use_cache,
661
+ **kwargs,
662
+ )
663
+ hidden_states = residual + hidden_states
664
+
665
+ # Fully Connected
666
+ residual = hidden_states
667
+ hidden_states = self.ffn_norm(hidden_states)
668
+ hidden_states = self.feed_forward(hidden_states)
669
+ hidden_states = residual + hidden_states
670
+
671
+ outputs = (hidden_states,)
672
+
673
+ if output_attentions:
674
+ outputs += (self_attn_weights,)
675
+
676
+ if use_cache:
677
+ outputs += (present_key_value,)
678
+
679
+ return outputs
680
+
681
+
682
+ InternLM2_START_DOCSTRING = r"""
683
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
684
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
685
+ etc.)
686
+
687
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
688
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
689
+ and behavior.
690
+
691
+ Parameters:
692
+ config ([`InternLM2Config`]):
693
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
694
+ load the weights associated with the model, only the configuration. Check out the
695
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
696
+ """
697
+
698
+
699
+ # Copied from transformers.models.llama.modeling_llama.LlamaPreTrainedModel with Llama->InternLM2
700
+ @add_start_docstrings(
701
+ "The bare InternLM2 Model outputting raw hidden-states without any specific head on top.",
702
+ InternLM2_START_DOCSTRING,
703
+ )
704
+ class InternLM2PreTrainedModel(PreTrainedModel):
705
+ """
706
+ InternLM2 pretraiend model's base class.
707
+ """
708
+
709
+ config_class = InternLM2Config
710
+ base_model_prefix = "model"
711
+ supports_gradient_checkpointing = True
712
+ _no_split_modules = ["InternLM2DecoderLayer"]
713
+ _skip_keys_device_placement = "past_key_values"
714
+
715
+ def _init_weights(self, module):
716
+ std = self.config.initializer_range
717
+ if isinstance(module, nn.Linear):
718
+ module.weight.data.normal_(mean=0.0, std=std)
719
+ if module.bias is not None:
720
+ module.bias.data.zero_()
721
+ elif isinstance(module, nn.Embedding):
722
+ module.weight.data.normal_(mean=0.0, std=std)
723
+ if module.padding_idx is not None:
724
+ module.weight.data[module.padding_idx].zero_()
725
+
726
+
727
+ InternLM2_INPUTS_DOCSTRING = r"""
728
+ Args:
729
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
730
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
731
+ it.
732
+
733
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
734
+ [`PreTrainedTokenizer.__call__`] for details.
735
+
736
+ [What are input IDs?](../glossary#input-ids)
737
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
738
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
739
+
740
+ - 1 for tokens that are **not masked**,
741
+ - 0 for tokens that are **masked**.
742
+
743
+ [What are attention masks?](../glossary#attention-mask)
744
+
745
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
746
+ [`PreTrainedTokenizer.__call__`] for details.
747
+
748
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
749
+ `past_key_values`).
750
+
751
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
752
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
753
+ information on the default strategy.
754
+
755
+ - 1 indicates the head is **not masked**,
756
+ - 0 indicates the head is **masked**.
757
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
758
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
759
+ config.n_positions - 1]`.
760
+
761
+ [What are position IDs?](../glossary#position-ids)
762
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or
763
+ when `config.use_cache=True`):
764
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
765
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
766
+ `(batch_size, num_heads, decoder_sequence_length, embed_size_per_head)`.
767
+
768
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
769
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
770
+
771
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
772
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
773
+ of shape `(batch_size, sequence_length)`.
774
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
775
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
776
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
777
+ model's internal embedding lookup matrix.
778
+ use_cache (`bool`, *optional*):
779
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
780
+ `past_key_values`).
781
+ output_attentions (`bool`, *optional*):
782
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
783
+ tensors for more detail.
784
+ output_hidden_states (`bool`, *optional*):
785
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
786
+ more detail.
787
+ return_dict (`bool`, *optional*):
788
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
789
+ """
790
+
791
+
792
+ # Modified from transformers.model.llama.modeling_llama.LlamaModel
793
+ @add_start_docstrings(
794
+ "The bare InternLM2 Model outputting raw hidden-states without any specific head on top.",
795
+ InternLM2_START_DOCSTRING,
796
+ )
797
+ class InternLM2Model(InternLM2PreTrainedModel):
798
+ """
799
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`InternLM2DecoderLayer`]
800
+
801
+ Args:
802
+ config: InternLM2Config
803
+ """
804
+
805
+ _auto_class = "AutoModel"
806
+
807
+ def __init__(self, config: InternLM2Config):
808
+ super().__init__(config)
809
+ self.padding_idx = config.pad_token_id
810
+ self.vocab_size = config.vocab_size
811
+ self.config = config
812
+
813
+ self.tok_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
814
+
815
+ self.layers = nn.ModuleList([InternLM2DecoderLayer(config) for _ in range(config.num_hidden_layers)])
816
+ self.norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
817
+
818
+ self.gradient_checkpointing = False
819
+ # Initialize weights and apply final processing
820
+ self.post_init()
821
+
822
+ def get_input_embeddings(self):
823
+ return self.tok_embeddings
824
+
825
+ def set_input_embeddings(self, value):
826
+ self.tok_embeddings = value
827
+
828
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
829
+ # create causal mask
830
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
831
+ combined_attention_mask = None
832
+ if input_shape[-1] > 1:
833
+ combined_attention_mask = _make_causal_mask(
834
+ input_shape,
835
+ inputs_embeds.dtype,
836
+ device=inputs_embeds.device,
837
+ past_key_values_length=past_key_values_length,
838
+ )
839
+
840
+ if attention_mask is not None:
841
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
842
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
843
+ inputs_embeds.device
844
+ )
845
+ combined_attention_mask = (
846
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
847
+ )
848
+
849
+ return combined_attention_mask
850
+
851
+ @add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
852
+ def forward(
853
+ self,
854
+ input_ids: torch.LongTensor = None,
855
+ attention_mask: Optional[torch.Tensor] = None,
856
+ position_ids: Optional[torch.LongTensor] = None,
857
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
858
+ inputs_embeds: Optional[torch.FloatTensor] = None,
859
+ use_cache: Optional[bool] = None,
860
+ output_attentions: Optional[bool] = None,
861
+ output_hidden_states: Optional[bool] = None,
862
+ return_dict: Optional[bool] = None,
863
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
864
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
865
+ output_hidden_states = (
866
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
867
+ )
868
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
869
+
870
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
871
+
872
+ if self.config.attn_implementation == "flash_attention_2":
873
+ _import_flash_attn()
874
+
875
+ # retrieve input_ids and inputs_embeds
876
+ if input_ids is not None and inputs_embeds is not None:
877
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
878
+ elif input_ids is not None:
879
+ batch_size, seq_length = input_ids.shape[:2]
880
+ elif inputs_embeds is not None:
881
+ batch_size, seq_length = inputs_embeds.shape[:2]
882
+ else:
883
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
884
+
885
+ seq_length_with_past = seq_length
886
+ past_key_values_length = 0
887
+ if past_key_values is not None:
888
+ past_key_values_length = past_key_values[0][0].shape[2]
889
+ seq_length_with_past = seq_length_with_past + past_key_values_length
890
+
891
+ if position_ids is None:
892
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
893
+ position_ids = torch.arange(
894
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
895
+ )
896
+ position_ids = position_ids.unsqueeze(0)
897
+
898
+ if inputs_embeds is None:
899
+ inputs_embeds = self.tok_embeddings(input_ids)
900
+
901
+ if self.config.attn_implementation == "flash_attention_2":
902
+ # 2d mask is passed through the layers
903
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
904
+ else:
905
+ if attention_mask is None:
906
+ attention_mask = torch.ones(
907
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
908
+ )
909
+ attention_mask = self._prepare_decoder_attention_mask(
910
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
911
+ )
912
+
913
+ # embed positions
914
+ hidden_states = inputs_embeds
915
+
916
+ if self.gradient_checkpointing and self.training:
917
+ if use_cache:
918
+ logger.warning_once(
919
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
920
+ )
921
+ use_cache = False
922
+
923
+ # decoder layers
924
+ all_hidden_states = () if output_hidden_states else None
925
+ all_self_attns = () if output_attentions else None
926
+ next_decoder_cache = () if use_cache else None
927
+
928
+ for idx, decoder_layer in enumerate(self.layers):
929
+ if output_hidden_states:
930
+ all_hidden_states += (hidden_states,)
931
+
932
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
933
+
934
+ if self.gradient_checkpointing and self.training:
935
+
936
+ def create_custom_forward(module):
937
+ def custom_forward(*inputs):
938
+ # None for past_key_value
939
+ return module(*inputs, output_attentions, None)
940
+
941
+ return custom_forward
942
+
943
+ layer_outputs = torch.utils.checkpoint.checkpoint(
944
+ create_custom_forward(decoder_layer),
945
+ hidden_states,
946
+ attention_mask,
947
+ position_ids,
948
+ None,
949
+ )
950
+ else:
951
+ layer_outputs = decoder_layer(
952
+ hidden_states,
953
+ attention_mask=attention_mask,
954
+ position_ids=position_ids,
955
+ past_key_value=past_key_value,
956
+ output_attentions=output_attentions,
957
+ use_cache=use_cache,
958
+ )
959
+
960
+ hidden_states = layer_outputs[0]
961
+
962
+ if use_cache:
963
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
964
+
965
+ if output_attentions:
966
+ all_self_attns += (layer_outputs[1],)
967
+
968
+ hidden_states = self.norm(hidden_states)
969
+
970
+ # add hidden states from the last decoder layer
971
+ if output_hidden_states:
972
+ all_hidden_states += (hidden_states,)
973
+
974
+ next_cache = next_decoder_cache if use_cache else None
975
+ if not return_dict:
976
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
977
+ return BaseModelOutputWithPast(
978
+ last_hidden_state=hidden_states,
979
+ past_key_values=next_cache,
980
+ hidden_states=all_hidden_states,
981
+ attentions=all_self_attns,
982
+ )
983
+
984
+
985
+ # Modified from transformers.model.llama.modeling_llama.LlamaForCausalLM
986
+ class InternLM2ForCausalLM(InternLM2PreTrainedModel):
987
+ """Causal language model (CLM) for InternLM2."""
988
+
989
+ _auto_class = "AutoModelForCausalLM"
990
+
991
+ _tied_weights_keys = ["output.weight"]
992
+
993
+ def __init__(self, config):
994
+ super().__init__(config)
995
+ self.model = InternLM2Model(config)
996
+ self.vocab_size = config.vocab_size
997
+ self.output = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
998
+
999
+ # Initialize weights and apply final processing
1000
+ self.post_init()
1001
+
1002
+ def get_input_embeddings(self):
1003
+ return self.model.tok_embeddings
1004
+
1005
+ def set_input_embeddings(self, value):
1006
+ self.model.tok_embeddings = value
1007
+
1008
+ def get_output_embeddings(self):
1009
+ return self.output
1010
+
1011
+ def set_output_embeddings(self, new_embeddings):
1012
+ self.output = new_embeddings
1013
+
1014
+ def set_decoder(self, decoder):
1015
+ self.model = decoder
1016
+
1017
+ def get_decoder(self):
1018
+ return self.model
1019
+
1020
+ @add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
1021
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1022
+ def forward(
1023
+ self,
1024
+ input_ids: torch.LongTensor = None,
1025
+ attention_mask: Optional[torch.Tensor] = None,
1026
+ position_ids: Optional[torch.LongTensor] = None,
1027
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1028
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1029
+ labels: Optional[torch.LongTensor] = None,
1030
+ use_cache: Optional[bool] = None,
1031
+ output_attentions: Optional[bool] = None,
1032
+ output_hidden_states: Optional[bool] = None,
1033
+ return_dict: Optional[bool] = None,
1034
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1035
+ r"""
1036
+ Args:
1037
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1038
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1039
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1040
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1041
+
1042
+ Returns:
1043
+
1044
+ Example:
1045
+
1046
+ ```python
1047
+ >>> from transformers import AutoTokenizer, InternLM2ForCausalLM
1048
+
1049
+ >>> model = InternLM2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1050
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1051
+
1052
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1053
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1054
+
1055
+ >>> # Generate
1056
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1057
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1058
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1059
+ ```"""
1060
+
1061
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1062
+ output_hidden_states = (
1063
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1064
+ )
1065
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1066
+
1067
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1068
+ outputs = self.model(
1069
+ input_ids=input_ids,
1070
+ attention_mask=attention_mask,
1071
+ position_ids=position_ids,
1072
+ past_key_values=past_key_values,
1073
+ inputs_embeds=inputs_embeds,
1074
+ use_cache=use_cache,
1075
+ output_attentions=output_attentions,
1076
+ output_hidden_states=output_hidden_states,
1077
+ return_dict=return_dict,
1078
+ )
1079
+
1080
+ hidden_states = outputs[0]
1081
+ logits = self.output(hidden_states)
1082
+ logits = logits.float()
1083
+
1084
+ loss = None
1085
+ if labels is not None:
1086
+ # Shift so that tokens < n predict n
1087
+ shift_logits = logits[..., :-1, :].contiguous()
1088
+ shift_labels = labels[..., 1:].contiguous()
1089
+ # Flatten the tokens
1090
+ loss_fct = CrossEntropyLoss()
1091
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1092
+ shift_labels = shift_labels.view(-1)
1093
+ # Enable model parallelism
1094
+ shift_labels = shift_labels.to(shift_logits.device)
1095
+ loss = loss_fct(shift_logits, shift_labels)
1096
+
1097
+ if not return_dict:
1098
+ output = (logits,) + outputs[1:]
1099
+ return (loss,) + output if loss is not None else output
1100
+
1101
+ return CausalLMOutputWithPast(
1102
+ loss=loss,
1103
+ logits=logits,
1104
+ past_key_values=outputs.past_key_values,
1105
+ hidden_states=outputs.hidden_states,
1106
+ attentions=outputs.attentions,
1107
+ )
1108
+
1109
+ def prepare_inputs_for_generation(
1110
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1111
+ ):
1112
+ if past_key_values is not None:
1113
+ past_length = past_key_values[0][0].shape[2]
1114
+
1115
+ # Some generation methods already pass only the last input ID
1116
+ if input_ids.shape[1] > past_length:
1117
+ remove_prefix_length = past_length
1118
+ else:
1119
+ # Default to old behavior: keep only final ID
1120
+ remove_prefix_length = input_ids.shape[1] - 1
1121
+
1122
+ input_ids = input_ids[:, remove_prefix_length:]
1123
+
1124
+ position_ids = kwargs.get("position_ids", None)
1125
+ if attention_mask is not None and position_ids is None:
1126
+ # create position_ids on the fly for batch generation
1127
+ position_ids = attention_mask.long().cumsum(-1) - 1
1128
+ position_ids.masked_fill_(attention_mask == 0, 1)
1129
+ if past_key_values:
1130
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1131
+
1132
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1133
+ if inputs_embeds is not None and past_key_values is None:
1134
+ model_inputs = {"inputs_embeds": inputs_embeds}
1135
+ else:
1136
+ model_inputs = {"input_ids": input_ids}
1137
+
1138
+ model_inputs.update(
1139
+ {
1140
+ "position_ids": position_ids,
1141
+ "past_key_values": past_key_values,
1142
+ "use_cache": kwargs.get("use_cache"),
1143
+ "attention_mask": attention_mask,
1144
+ }
1145
+ )
1146
+ return model_inputs
1147
+
1148
+ @staticmethod
1149
+ def _reorder_cache(past_key_values, beam_idx):
1150
+ reordered_past = ()
1151
+ for layer_past in past_key_values:
1152
+ reordered_past += (
1153
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1154
+ )
1155
+ return reordered_past
1156
+
1157
+ def build_inputs(self, tokenizer, query: str, history: Optional[List[Tuple[str, str]]] = None, meta_instruction=""):
1158
+ if history is None:
1159
+ history = []
1160
+ if tokenizer.add_bos_token:
1161
+ prompt = ""
1162
+ else:
1163
+ prompt = tokenizer.bos_token
1164
+ if meta_instruction:
1165
+ prompt += f"""<|im_start|>system\n{meta_instruction}<|im_end|>\n"""
1166
+ for record in history:
1167
+ prompt += f"""<|im_start|>user\n{record[0]}<|im_end|>\n<|im_start|>assistant\n{record[1]}<|im_end|>\n"""
1168
+ prompt += f"""<|im_start|>user\n{query}<|im_end|>\n<|im_start|>assistant\n"""
1169
+ return tokenizer([prompt], return_tensors="pt")
1170
+
1171
+ @torch.no_grad()
1172
+ def chat(
1173
+ self,
1174
+ tokenizer,
1175
+ query: str,
1176
+ history: Optional[List[Tuple[str, str]]] = None,
1177
+ streamer: Optional[BaseStreamer] = None,
1178
+ max_new_tokens: int = 1024,
1179
+ do_sample: bool = True,
1180
+ temperature: float = 0.8,
1181
+ top_p: float = 0.8,
1182
+ meta_instruction: str = "You are an AI assistant whose name is InternLM (书生·浦语).\n"
1183
+ "- InternLM (书生·浦语) is a conversational language model that is developed by Shanghai AI Laboratory (上海人工智能实验室). It is designed to be helpful, honest, and harmless.\n" # noqa: E501 # pylint: disable=C0301
1184
+ "- InternLM (书生·浦语) can understand and communicate fluently in the language chosen by the user such as English and 中文.", # noqa: E501 # pylint: disable=C0301
1185
+ **kwargs,
1186
+ ):
1187
+ if history is None:
1188
+ history = []
1189
+ inputs = self.build_inputs(tokenizer, query, history, meta_instruction)
1190
+ inputs = {k: v.to(self.device) for k, v in inputs.items() if torch.is_tensor(v)}
1191
+ # also add end-of-assistant token in eos token id to avoid unnecessary generation
1192
+ eos_token_id = [tokenizer.eos_token_id, tokenizer.convert_tokens_to_ids(["<|im_end|>"])[0]]
1193
+ outputs = self.generate(
1194
+ **inputs,
1195
+ streamer=streamer,
1196
+ max_new_tokens=max_new_tokens,
1197
+ do_sample=do_sample,
1198
+ temperature=temperature,
1199
+ top_p=top_p,
1200
+ eos_token_id=eos_token_id,
1201
+ **kwargs,
1202
+ )
1203
+ outputs = outputs[0].cpu().tolist()[len(inputs["input_ids"][0]) :]
1204
+ response = tokenizer.decode(outputs, skip_special_tokens=True)
1205
+ response = response.split("<|im_end|>")[0]
1206
+ history = history + [(query, response)]
1207
+ return response, history
1208
+
1209
+ @torch.no_grad()
1210
+ def stream_chat(
1211
+ self,
1212
+ tokenizer,
1213
+ query: str,
1214
+ history: Optional[List[Tuple[str, str]]] = None,
1215
+ max_new_tokens: int = 1024,
1216
+ do_sample: bool = True,
1217
+ temperature: float = 0.8,
1218
+ top_p: float = 0.8,
1219
+ **kwargs,
1220
+ ):
1221
+ """
1222
+ Return a generator in format: (response, history)
1223
+ Eg.
1224
+ ('你好,有什么可以帮助您的吗', [('你好', '你好,有什么可以帮助您的吗')])
1225
+ ('你好,有什么可以帮助您的吗?', [('你好', '你好,有什么可以帮助您的吗?')])
1226
+ """
1227
+ if history is None:
1228
+ history = []
1229
+ if BaseStreamer is None:
1230
+ raise ModuleNotFoundError(
1231
+ "The version of `transformers` is too low. Please make sure "
1232
+ "that you have installed `transformers>=4.28.0`."
1233
+ )
1234
+
1235
+ response_queue = queue.Queue(maxsize=20)
1236
+
1237
+ class ChatStreamer(BaseStreamer):
1238
+ """
1239
+ Class for streaming chat.
1240
+ """
1241
+
1242
+ def __init__(self, tokenizer) -> None:
1243
+ super().__init__()
1244
+ self.tokenizer = tokenizer
1245
+ self.queue = response_queue
1246
+ self.query = query
1247
+ self.history = history
1248
+ self.response = ""
1249
+ self.cache = []
1250
+ self.received_inputs = False
1251
+ self.queue.put((self.response, history + [(self.query, self.response)]))
1252
+
1253
+ def put(self, value):
1254
+ if len(value.shape) > 1 and value.shape[0] > 1:
1255
+ raise ValueError("ChatStreamer only supports batch size 1")
1256
+ elif len(value.shape) > 1:
1257
+ value = value[0]
1258
+
1259
+ if not self.received_inputs:
1260
+ # The first received value is input_ids, ignore here
1261
+ self.received_inputs = True
1262
+ return
1263
+
1264
+ self.cache.extend(value.tolist())
1265
+ token = self.tokenizer.decode(self.cache, skip_special_tokens=True)
1266
+ if token.strip() != "<|im_end|>":
1267
+ self.response = self.response + token
1268
+ history = self.history + [(self.query, self.response)]
1269
+ self.queue.put((self.response, history))
1270
+ self.cache = []
1271
+ else:
1272
+ self.end()
1273
+
1274
+ def end(self):
1275
+ self.queue.put(None)
1276
+
1277
+ def stream_producer():
1278
+ return self.chat(
1279
+ tokenizer=tokenizer,
1280
+ query=query,
1281
+ streamer=ChatStreamer(tokenizer=tokenizer),
1282
+ history=history,
1283
+ max_new_tokens=max_new_tokens,
1284
+ do_sample=do_sample,
1285
+ temperature=temperature,
1286
+ top_p=top_p,
1287
+ **kwargs,
1288
+ )
1289
+
1290
+ def consumer():
1291
+ producer = threading.Thread(target=stream_producer)
1292
+ producer.start()
1293
+ while True:
1294
+ res = response_queue.get()
1295
+ if res is None:
1296
+ return
1297
+ yield res
1298
+
1299
+ return consumer()
1300
+
1301
+
1302
+ # Copied from transformers.model.llama.modeling_llama.LlamaForSequenceClassification with Llama->InternLM2
1303
+ @add_start_docstrings(
1304
+ """
1305
+ The InternLM2 Model transformer with a sequence classification head on top (linear layer).
1306
+
1307
+ [`InternLM2ForSequenceClassification`] uses the last token in order to do the classification,
1308
+ as other causal models (e.g. GPT-2) do.
1309
+
1310
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1311
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1312
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1313
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1314
+ each row of the batch).
1315
+ """,
1316
+ InternLM2_START_DOCSTRING,
1317
+ )
1318
+ class InternLM2ForSequenceClassification(InternLM2PreTrainedModel):
1319
+ """Sequence Classification Head for InternLM2 Model."""
1320
+
1321
+ def __init__(self, config):
1322
+ super().__init__(config)
1323
+ self.num_labels = config.num_labels
1324
+ self.model = InternLM2Model(config)
1325
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1326
+
1327
+ # Initialize weights and apply final processing
1328
+ self.post_init()
1329
+
1330
+ def get_input_embeddings(self):
1331
+ return self.model.tok_embeddings
1332
+
1333
+ def set_input_embeddings(self, value):
1334
+ self.model.tok_embeddings = value
1335
+
1336
+ @add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
1337
+ def forward(
1338
+ self,
1339
+ input_ids: torch.LongTensor = None,
1340
+ attention_mask: Optional[torch.Tensor] = None,
1341
+ position_ids: Optional[torch.LongTensor] = None,
1342
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1343
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1344
+ labels: Optional[torch.LongTensor] = None,
1345
+ use_cache: Optional[bool] = None,
1346
+ output_attentions: Optional[bool] = None,
1347
+ output_hidden_states: Optional[bool] = None,
1348
+ return_dict: Optional[bool] = None,
1349
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1350
+ r"""
1351
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1352
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1353
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1354
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1355
+ """
1356
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1357
+
1358
+ transformer_outputs = self.model(
1359
+ input_ids,
1360
+ attention_mask=attention_mask,
1361
+ position_ids=position_ids,
1362
+ past_key_values=past_key_values,
1363
+ inputs_embeds=inputs_embeds,
1364
+ use_cache=use_cache,
1365
+ output_attentions=output_attentions,
1366
+ output_hidden_states=output_hidden_states,
1367
+ return_dict=return_dict,
1368
+ )
1369
+ hidden_states = transformer_outputs[0]
1370
+ logits = self.score(hidden_states)
1371
+
1372
+ if input_ids is not None:
1373
+ batch_size = input_ids.shape[0]
1374
+ else:
1375
+ batch_size = inputs_embeds.shape[0]
1376
+
1377
+ if self.config.pad_token_id is None and batch_size != 1:
1378
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1379
+ if self.config.pad_token_id is None:
1380
+ sequence_lengths = -1
1381
+ else:
1382
+ if input_ids is not None:
1383
+ sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1).to(
1384
+ logits.device
1385
+ )
1386
+ else:
1387
+ sequence_lengths = -1
1388
+
1389
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1390
+
1391
+ loss = None
1392
+ if labels is not None:
1393
+ labels = labels.to(logits.device)
1394
+ if self.config.problem_type is None:
1395
+ if self.num_labels == 1:
1396
+ self.config.problem_type = "regression"
1397
+ elif self.num_labels > 1 and labels.dtype in (torch.long, torch.int):
1398
+ self.config.problem_type = "single_label_classification"
1399
+ else:
1400
+ self.config.problem_type = "multi_label_classification"
1401
+
1402
+ if self.config.problem_type == "regression":
1403
+ loss_fct = MSELoss()
1404
+ if self.num_labels == 1:
1405
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1406
+ else:
1407
+ loss = loss_fct(pooled_logits, labels)
1408
+ elif self.config.problem_type == "single_label_classification":
1409
+ loss_fct = CrossEntropyLoss()
1410
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1411
+ elif self.config.problem_type == "multi_label_classification":
1412
+ loss_fct = BCEWithLogitsLoss()
1413
+ loss = loss_fct(pooled_logits, labels)
1414
+ if not return_dict:
1415
+ output = (pooled_logits,) + transformer_outputs[1:]
1416
+ return ((loss,) + output) if loss is not None else output
1417
+
1418
+ return SequenceClassifierOutputWithPast(
1419
+ loss=loss,
1420
+ logits=pooled_logits,
1421
+ past_key_values=transformer_outputs.past_key_values,
1422
+ hidden_states=transformer_outputs.hidden_states,
1423
+ attentions=transformer_outputs.attentions,
1424
+ )
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:9e556afd44213b6bd1be2b850ebbbd98f5481437a8021afaf58ee7fb1818d347
3
+ size 499723
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
+ }