samgreen commited on
Commit
5a4b70d
1 Parent(s): 68f3765

Upload InternLM2ForCausalLM

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