camillebrl commited on
Commit
0c995b5
1 Parent(s): 9199ca3

Upload InternLMXComposer2ForCausalLM

Browse files
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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]
build_mlp.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import re
4
+ import math
5
+ from transformers import CLIPVisionModel, CLIPImageProcessor, CLIPVisionConfig
6
+
7
+
8
+ def build_vision_tower():
9
+ vision_tower = 'openai/clip-vit-large-patch14-336'
10
+ return CLIPVisionTower(vision_tower)
11
+
12
+
13
+ def build_vision_projector():
14
+ projector_type = 'mlp2x_gelu'
15
+ mm_hidden_size = 4096
16
+ mid_hidden_size = 4096
17
+ hidden_size = 4096
18
+
19
+ mlp_gelu_match = re.match(r'^mlp(\d+)x_gelu$', projector_type)
20
+ if mlp_gelu_match:
21
+ mlp_depth = int(mlp_gelu_match.group(1))
22
+ modules = [nn.Linear(mm_hidden_size, mid_hidden_size)]
23
+ for _ in range(1, mlp_depth):
24
+ modules.append(nn.GELU())
25
+ modules.append(nn.Linear(mid_hidden_size, mid_hidden_size))
26
+
27
+ return nn.Sequential(*modules)
28
+
29
+ if projector_type == 'identity':
30
+ return IdentityMap()
31
+
32
+ raise ValueError(f'Unknown projector type: {projector_type}')
33
+
34
+ class IdentityMap(nn.Module):
35
+ def __init__(self):
36
+ super().__init__()
37
+
38
+ def forward(self, x, *args, **kwargs):
39
+ return x
40
+
41
+ @property
42
+ def config(self):
43
+ return {"mm_projector_type": 'identity'}
44
+
45
+
46
+ class CLIPVisionTower(nn.Module):
47
+ def __init__(self, vision_tower):
48
+ super().__init__()
49
+
50
+ self.is_loaded = False
51
+
52
+ self.vision_tower_name = vision_tower
53
+ self.select_layer = -1
54
+ self.select_feature = 'patch'
55
+ self.load_model()
56
+
57
+ def load_model(self):
58
+ self.vision_tower = CLIPVisionModel.from_pretrained(self.vision_tower_name)
59
+ self.vision_tower.requires_grad_(False)
60
+
61
+ self.is_loaded = True
62
+
63
+ def resize_pos(self):
64
+ print ('Dummy Resized')
65
+
66
+ def feature_select(self, image_forward_outs):
67
+ image_features = image_forward_outs.hidden_states[self.select_layer]
68
+ if self.select_feature == 'patch':
69
+ image_features = image_features[:, 1:]
70
+ elif self.select_feature == 'cls_patch':
71
+ image_features = image_features
72
+ else:
73
+ raise ValueError(f'Unexpected select feature: {self.select_feature}')
74
+ return image_features
75
+
76
+ def forward(self, images, glb_GN, sub_GN):
77
+ if not self.is_loaded:
78
+ self.load_model()
79
+ assert type(images) is list
80
+ shapes = []
81
+ input_imgs = []
82
+ for img in images:
83
+ _, C, H, W = img.shape
84
+ shapes.append([H//336, W//336])
85
+ sub_img = img.reshape(1,3,H//336,336,W//336,336).permute(0,2,4,1,3,5).reshape(-1,3,336,336).contiguous()
86
+ glb_img = torch.nn.functional.interpolate(img.float(), size=(336,336), mode='bicubic',).to(sub_img.dtype)
87
+ input_imgs.append(glb_img)
88
+ input_imgs.append(sub_img)
89
+ input_imgs = torch.cat(input_imgs, dim=0)
90
+
91
+ image_forward_outs = self.vision_tower(input_imgs.to(device=self.device, dtype=self.dtype), output_hidden_states=True)
92
+ image_features = self.feature_select(image_forward_outs).to(input_imgs.dtype) ### B*?, N, C
93
+ _, N, C = image_features.shape
94
+ H = int(math.sqrt(N))
95
+ assert N == 24 ** 2
96
+
97
+ output_imgs = []
98
+ output_len = []
99
+ for [h, w] in shapes:
100
+ B_ = h*w
101
+ glb_img = image_features[:1] ### 1, N, C
102
+ glb_img = glb_img.reshape(1,H,H,C).reshape(1,H//2,2,H//2,2,C).contiguous().permute(0,1,3,2,4,5).reshape(1,H//2,H//2,4*C).contiguous()
103
+ temp_glb_GN = sub_GN.repeat(1, H//2, 1, 1)
104
+ glb_img = torch.cat([glb_img, temp_glb_GN], dim=2).reshape(1,-1,4*C)
105
+
106
+ sub_img = image_features[1:1+B_] ### ?, N, C
107
+ sub_img = sub_img.reshape(B_,H,H,C).reshape(B_,H//2,2,H//2,2,C).contiguous().permute(0,1,3,2,4,5).reshape(B_,-1,4*C).contiguous()
108
+ sub_img = sub_img.reshape(1, h, w, 12, 12, -1).permute(0,1,3,2,4,5).reshape(1,h*12,w*12,4*C)
109
+ temp_sub_GN = sub_GN.repeat(1, h*12, 1, 1)
110
+ sub_img = torch.cat([sub_img, temp_sub_GN], dim=2).reshape(1,-1,4*C)
111
+
112
+ output_imgs.append(torch.cat([glb_img, glb_GN, sub_img], dim=1))
113
+ temp_len = int((h*w+1)*144 + 1 + (h+1)*12)
114
+ assert temp_len == output_imgs[-1].shape[1]
115
+ output_len.append(temp_len)
116
+
117
+ image_features = image_features[1+h*w:]
118
+
119
+ output_imgs = torch.cat(output_imgs, dim=1)
120
+
121
+ return output_imgs, output_len
122
+
123
+ @property
124
+ def dummy_feature(self):
125
+ return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
126
+
127
+ @property
128
+ def dtype(self):
129
+ return self.vision_tower.dtype
130
+
131
+ @property
132
+ def device(self):
133
+ return self.vision_tower.device
134
+
135
+ @property
136
+ def config(self):
137
+ if self.is_loaded:
138
+ return self.vision_tower.config
139
+ else:
140
+ return self.cfg_only
141
+
142
+ @property
143
+ def hidden_size(self):
144
+ return self.config.hidden_size
145
+
146
+ @property
147
+ def num_patches(self):
148
+ return (self.config.image_size // self.config.patch_size) ** 2
149
+
150
+ class PLoRA(nn.Linear):
151
+ def __init__(self,
152
+ in_features: int,
153
+ out_features: int,
154
+ bias: bool = True,
155
+ device=None,
156
+ dtype=None,
157
+ lora_r=8,
158
+ lora_alpha=16,
159
+ lora_dropout=0.05,
160
+ lora_len=0,
161
+ **kwargs) -> None:
162
+ super().__init__(in_features, out_features, bias, device, dtype)
163
+ self.lora_r = lora_r
164
+ self.lora_alpha = lora_alpha
165
+ self.lora_len = lora_len
166
+ if lora_dropout > 0.:
167
+ self.lora_dropout = nn.Dropout(p=lora_dropout)
168
+ else:
169
+ self.lora_dropout = lambda x: x
170
+ self.lora_scaling = self.lora_alpha / self.lora_r
171
+
172
+ self.Plora_A = nn.Linear(in_features,
173
+ self.lora_r,
174
+ bias=False,
175
+ device=device,
176
+ dtype=dtype)
177
+ self.Plora_B = nn.Linear(self.lora_r,
178
+ out_features,
179
+ bias=False,
180
+ device=device,
181
+ dtype=dtype)
182
+
183
+ self.reset_parameters()
184
+
185
+ def reset_parameters(self):
186
+ if hasattr(self, 'lora_A'):
187
+ # initialize A the same way as the default for nn.Linear and B to zero
188
+ nn.init.kaiming_uniform_(self.lora_A.weight, a=math.sqrt(5))
189
+ nn.init.zeros_(self.lora_B.weight)
190
+ #print ("lora weight init {} {}".format(torch.mean(self.lora_A.weight), torch.mean(self.lora_B.weight)))
191
+
192
+ def forward(self, x, im_mask=None):
193
+ B, N, C = x.shape
194
+ x = x.reshape(-1, C)
195
+ im_mask = im_mask.view(-1)
196
+ res = super().forward(x)
197
+ if im_mask is not None:
198
+ if torch.sum(im_mask) > 0:
199
+ part_x = x[im_mask]
200
+ res[im_mask] += self.Plora_B(self.Plora_A(
201
+ self.lora_dropout(part_x))) * self.lora_scaling
202
+ else:
203
+ part_x = x[:1]
204
+ res[:1] += self.Plora_B(self.Plora_A(
205
+ self.lora_dropout(part_x))) * 0
206
+
207
+ return res.reshape(B, N, -1)
config.json ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "internlm/internlm-xcomposer2-4khd-7b",
3
+ "architectures": [
4
+ "InternLMXComposer2ForCausalLM"
5
+ ],
6
+ "attn_implementation": "eager",
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_internlm_xcomposer2.InternLMXcomposer2Config",
9
+ "AutoModel": "internlm/internlm-xcomposer2-4khd-7b--modeling_internlm_xcomposer2.InternLMXComposer2ForCausalLM",
10
+ "AutoModelForCausalLM": "modeling_internlm_xcomposer2.InternLMXComposer2ForCausalLM"
11
+ },
12
+ "bias": false,
13
+ "bos_token_id": 1,
14
+ "eos_token_id": 2,
15
+ "hidden_act": "silu",
16
+ "hidden_size": 4096,
17
+ "initializer_range": 0.02,
18
+ "intermediate_size": 14336,
19
+ "max_length": 16384,
20
+ "max_position_embeddings": 32768,
21
+ "model_type": "internlm2",
22
+ "num_attention_heads": 32,
23
+ "num_hidden_layers": 32,
24
+ "num_key_value_heads": 8,
25
+ "pad_token_id": 2,
26
+ "quantization_config": {
27
+ "_load_in_4bit": true,
28
+ "_load_in_8bit": false,
29
+ "bnb_4bit_compute_dtype": "float32",
30
+ "bnb_4bit_quant_storage": "uint8",
31
+ "bnb_4bit_quant_type": "fp4",
32
+ "bnb_4bit_use_double_quant": false,
33
+ "llm_int8_enable_fp32_cpu_offload": false,
34
+ "llm_int8_has_fp16_weight": false,
35
+ "llm_int8_skip_modules": null,
36
+ "llm_int8_threshold": 6.0,
37
+ "load_in_4bit": true,
38
+ "load_in_8bit": false,
39
+ "quant_method": "bitsandbytes"
40
+ },
41
+ "rms_norm_eps": 1e-05,
42
+ "rope_scaling": null,
43
+ "rope_theta": 1000000,
44
+ "tie_word_embeddings": false,
45
+ "torch_dtype": "float16",
46
+ "transformers_version": "4.43.4",
47
+ "use_cache": false,
48
+ "vocab_size": 92544
49
+ }
configuration_internlm_xcomposer2.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ class InternLMXcomposer2Config(PretrainedConfig):
28
+ r"""
29
+ This is the configuration class to store the configuration of a [`InternLM2Model`]. It is used to instantiate
30
+ an InternLM2 model according to the specified arguments, defining the model architecture. Instantiating a
31
+ configuration with the defaults will yield a similar configuration to that of the InternLM2-7B.
32
+
33
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
34
+ documentation from [`PretrainedConfig`] for more information.
35
+
36
+
37
+ Args:
38
+ vocab_size (`int`, *optional*, defaults to 32000):
39
+ Vocabulary size of the InternLM2 model. Defines the number of different tokens that can be represented by the
40
+ `inputs_ids` passed when calling [`InternLM2Model`]
41
+ hidden_size (`int`, *optional*, defaults to 4096):
42
+ Dimension of the hidden representations.
43
+ intermediate_size (`int`, *optional*, defaults to 11008):
44
+ Dimension of the MLP representations.
45
+ num_hidden_layers (`int`, *optional*, defaults to 32):
46
+ Number of hidden layers in the Transformer encoder.
47
+ num_attention_heads (`int`, *optional*, defaults to 32):
48
+ Number of attention heads for each attention layer in the Transformer encoder.
49
+ num_key_value_heads (`int`, *optional*):
50
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
51
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
52
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
53
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
54
+ by meanpooling all the original heads within that group. For more details checkout [this
55
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
56
+ `num_attention_heads`.
57
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
58
+ The non-linear activation function (function or string) in the decoder.
59
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
60
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
61
+ just in case (e.g., 512 or 1024 or 2048).
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-12):
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
+ tie_word_embeddings(`bool`, *optional*, defaults to `False`):
70
+ Whether to tie weight embeddings
71
+ Example:
72
+
73
+ """
74
+ model_type = "internlm2"
75
+ _auto_class = "AutoConfig"
76
+
77
+ def __init__( # pylint: disable=W0102
78
+ self,
79
+ vocab_size=103168,
80
+ hidden_size=4096,
81
+ intermediate_size=11008,
82
+ num_hidden_layers=32,
83
+ num_attention_heads=32,
84
+ num_key_value_heads=None,
85
+ hidden_act="silu",
86
+ max_position_embeddings=2048,
87
+ initializer_range=0.02,
88
+ rms_norm_eps=1e-6,
89
+ use_cache=True,
90
+ pad_token_id=0,
91
+ bos_token_id=1,
92
+ eos_token_id=2,
93
+ tie_word_embeddings=False,
94
+ bias=True,
95
+ rope_theta=10000,
96
+ rope_scaling=None,
97
+ attn_implementation="eager",
98
+ **kwargs,
99
+ ):
100
+ self.vocab_size = vocab_size
101
+ self.max_position_embeddings = max_position_embeddings
102
+ self.hidden_size = hidden_size
103
+ self.intermediate_size = intermediate_size
104
+ self.num_hidden_layers = num_hidden_layers
105
+ self.num_attention_heads = num_attention_heads
106
+ self.bias = bias
107
+
108
+ if num_key_value_heads is None:
109
+ num_key_value_heads = num_attention_heads
110
+ self.num_key_value_heads = num_key_value_heads
111
+
112
+ self.hidden_act = hidden_act
113
+ self.initializer_range = initializer_range
114
+ self.rms_norm_eps = rms_norm_eps
115
+ self.use_cache = use_cache
116
+ self.rope_theta = rope_theta
117
+ self.rope_scaling = rope_scaling
118
+ self._rope_scaling_validation()
119
+
120
+ self.attn_implementation = attn_implementation
121
+ if self.attn_implementation is None:
122
+ self.attn_implementation = "eager"
123
+ super().__init__(
124
+ pad_token_id=pad_token_id,
125
+ bos_token_id=bos_token_id,
126
+ eos_token_id=eos_token_id,
127
+ tie_word_embeddings=tie_word_embeddings,
128
+ **kwargs,
129
+ )
130
+
131
+ def _rope_scaling_validation(self):
132
+ """
133
+ Validate the `rope_scaling` configuration.
134
+ """
135
+ if self.rope_scaling is None:
136
+ return
137
+
138
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
139
+ raise ValueError(
140
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
141
+ f"got {self.rope_scaling}"
142
+ )
143
+ rope_scaling_type = self.rope_scaling.get("type", None)
144
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
145
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
146
+ raise ValueError(
147
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
148
+ )
149
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor < 1.0:
150
+ raise ValueError(f"`rope_scaling`'s factor field must be a float >= 1, got {rope_scaling_factor}")
generation_config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "max_length": 4480,
6
+ "pad_token_id": 2,
7
+ "transformers_version": "4.43.4",
8
+ "use_cache": false
9
+ }
ixc_utils.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ import torchvision
4
+ from PIL import Image
5
+ from torchvision.transforms.functional import InterpolationMode
6
+ import torchvision.transforms as transforms
7
+
8
+ def padding_336(b):
9
+ width, height = b.size
10
+ tar = int(np.ceil(height / 336) * 336)
11
+ top_padding = int((tar - height)/2)
12
+ bottom_padding = tar - height - top_padding
13
+ left_padding = 0
14
+ right_padding = 0
15
+ b = transforms.functional.pad(b, [left_padding, top_padding, right_padding, bottom_padding], fill=[255,255,255])
16
+
17
+ return b
18
+
19
+ def HD_transform(img, hd_num=16):
20
+ width, height = img.size
21
+ trans = False
22
+ if width < height:
23
+ img = img.transpose(Image.TRANSPOSE)
24
+ trans = True
25
+ width, height = img.size
26
+ ratio = (width/ height)
27
+ scale = 1
28
+ while scale*np.ceil(scale/ratio) <= hd_num:
29
+ scale += 1
30
+ scale -= 1
31
+ new_w = int(scale * 336)
32
+ new_h = int(new_w / ratio)
33
+
34
+ img = transforms.functional.resize(img, [new_h, new_w],)
35
+ img = padding_336(img)
36
+ width, height = img.size
37
+ if trans:
38
+ img = img.transpose(Image.TRANSPOSE)
39
+
40
+ return img
41
+
42
+
model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bbda3f36cae26a9e3f61241d1ee58d80cdee7991fd24a125456b066f2f8fd584
3
+ size 4684645592
model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aa4ec6e7696b542a5f33b5c586f38945b525749daae584e804da5b0d172aaafe
3
+ size 950057426
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,990 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import copy
22
+ import numpy as np
23
+ from typing import List, Optional, Tuple, Union
24
+ from torchvision import transforms
25
+ from torchvision.transforms.functional import InterpolationMode
26
+ from PIL import Image
27
+
28
+ import torch
29
+ import torch.nn.functional as F
30
+ import torch.utils.checkpoint
31
+ from einops import rearrange
32
+ from torch import nn
33
+ from transformers.activations import ACT2FN
34
+ from transformers.modeling_outputs import (
35
+ BaseModelOutputWithPast,
36
+ CausalLMOutputWithPast,
37
+ SequenceClassifierOutputWithPast,
38
+ )
39
+ from transformers.modeling_utils import PreTrainedModel
40
+ from transformers.utils import (
41
+ add_start_docstrings,
42
+ add_start_docstrings_to_model_forward,
43
+ logging,
44
+ replace_return_docstrings,
45
+ )
46
+
47
+ try:
48
+ from transformers.generation.streamers import BaseStreamer
49
+ except: # noqa # pylint: disable=bare-except
50
+ BaseStreamer = None
51
+
52
+ from .build_mlp import PLoRA
53
+ from .configuration_internlm_xcomposer2 import InternLMXcomposer2Config as InternLM2Config
54
+
55
+ logger = logging.get_logger(__name__)
56
+
57
+ _CONFIG_FOR_DOC = "InternLM2Config"
58
+
59
+ flash_attn_func, flash_attn_varlen_func = None, None
60
+ pad_input, index_first_axis, unpad_input = None, None, None
61
+ def _import_flash_attn():
62
+ global flash_attn_func, flash_attn_varlen_func
63
+ global pad_input, index_first_axis, unpad_input
64
+ try:
65
+ from flash_attn import flash_attn_func as _flash_attn_func, flash_attn_varlen_func as _flash_attn_varlen_func
66
+ from flash_attn.bert_padding import pad_input as _pad_input, index_first_axis as _index_first_axis, unpad_input as _unpad_input
67
+ flash_attn_func, flash_attn_varlen_func = _flash_attn_func, _flash_attn_varlen_func
68
+ pad_input, index_first_axis, unpad_input = _pad_input, _index_first_axis, _unpad_input
69
+ except ImportError:
70
+ raise ImportError("flash_attn is not installed.")
71
+
72
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
73
+ def _get_unpad_data(attention_mask):
74
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
75
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
76
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
77
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
78
+ return (
79
+ indices,
80
+ cu_seqlens,
81
+ max_seqlen_in_batch,
82
+ )
83
+
84
+
85
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
86
+ def _make_causal_mask(
87
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
88
+ ):
89
+ """
90
+ Make causal mask used for bi-directional self-attention.
91
+ """
92
+ bsz, tgt_len = input_ids_shape
93
+ mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
94
+ mask_cond = torch.arange(mask.size(-1), device=device)
95
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
96
+ mask = mask.to(dtype)
97
+
98
+ if past_key_values_length > 0:
99
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
100
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
101
+
102
+
103
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
104
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
105
+ """
106
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
107
+ """
108
+ bsz, src_len = mask.size()
109
+ tgt_len = tgt_len if tgt_len is not None else src_len
110
+
111
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
112
+
113
+ inverted_mask = 1.0 - expanded_mask
114
+
115
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
116
+
117
+
118
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->InternLM2
119
+ class InternLM2RMSNorm(nn.Module):
120
+ def __init__(self, hidden_size, eps=1e-6):
121
+ """
122
+ InternLM2RMSNorm is equivalent to T5LayerNorm
123
+ """
124
+ super().__init__()
125
+ self.weight = nn.Parameter(torch.ones(hidden_size))
126
+ self.variance_epsilon = eps
127
+
128
+ def forward(self, hidden_states):
129
+ input_dtype = hidden_states.dtype
130
+ hidden_states = hidden_states.to(torch.float32)
131
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
132
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
133
+ return self.weight * hidden_states.to(input_dtype)
134
+
135
+
136
+ # Copied from transformers.model.llama.modeling_llama.LlamaRotaryEmbedding with Llama->InternLM2
137
+ class InternLM2RotaryEmbedding(nn.Module):
138
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
139
+ super().__init__()
140
+
141
+ self.dim = dim
142
+ self.max_position_embeddings = max_position_embeddings
143
+ self.base = base
144
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
145
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
146
+
147
+ # Build here to make `torch.jit.trace` work.
148
+ self._set_cos_sin_cache(
149
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
150
+ )
151
+
152
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
153
+ self.max_seq_len_cached = seq_len
154
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
155
+
156
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
157
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
158
+ emb = torch.cat((freqs, freqs), dim=-1)
159
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
160
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
161
+
162
+ def forward(self, x, seq_len=None):
163
+ # x: [bs, num_attention_heads, seq_len, head_size]
164
+ if seq_len > self.max_seq_len_cached:
165
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=torch.float32)
166
+
167
+ return (
168
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
169
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
170
+ )
171
+
172
+
173
+ # Copied from transformers.model.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->InternLM2
174
+ class InternLM2LinearScalingRotaryEmbedding(InternLM2RotaryEmbedding):
175
+ """InternLM2RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
176
+
177
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
178
+ self.scaling_factor = scaling_factor
179
+ super().__init__(dim, max_position_embeddings, base, device)
180
+
181
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
182
+ self.max_seq_len_cached = seq_len
183
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
184
+ t = t / self.scaling_factor
185
+
186
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
187
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
188
+ emb = torch.cat((freqs, freqs), dim=-1)
189
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
190
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
191
+
192
+
193
+ # Copied from transformers.model.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->InternLM2
194
+ class InternLM2DynamicNTKScalingRotaryEmbedding(InternLM2RotaryEmbedding):
195
+ """InternLM2RotaryEmbedding extended with Dynamic NTK scaling.
196
+ Credits to the Reddit users /u/bloc97 and /u/emozilla.
197
+ """
198
+
199
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
200
+ self.scaling_factor = scaling_factor
201
+ super().__init__(dim, max_position_embeddings, base, device)
202
+
203
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
204
+ self.max_seq_len_cached = seq_len
205
+
206
+ if seq_len > self.max_position_embeddings:
207
+ base = self.base * (
208
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
209
+ ) ** (self.dim / (self.dim - 2))
210
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
211
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
212
+
213
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
214
+
215
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
216
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
217
+ emb = torch.cat((freqs, freqs), dim=-1)
218
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
219
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
220
+
221
+
222
+ # Copied from transformers.model.llama.modeling_llama.rotate_half
223
+ def rotate_half(x):
224
+ """Rotates half the hidden dims of the input."""
225
+ x1 = x[..., : x.shape[-1] // 2]
226
+ x2 = x[..., x.shape[-1] // 2 :]
227
+ return torch.cat((-x2, x1), dim=-1)
228
+
229
+
230
+ # Copied from transformers.model.llama.modeling_llama.apply_rotary_pos_emb
231
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
232
+ """Applies Rotary Position Embedding to the query and key tensors."""
233
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
234
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
235
+ q_embed = (q * cos) + (rotate_half(q) * sin)
236
+ k_embed = (k * cos) + (rotate_half(k) * sin)
237
+ return q_embed, k_embed
238
+
239
+
240
+ class InternLM2MLP(nn.Module):
241
+ def __init__(self, config):
242
+ super().__init__()
243
+ self.config = config
244
+ self.hidden_size = config.hidden_size
245
+ self.intermediate_size = config.intermediate_size
246
+ #self.w1 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
247
+ #self.w3 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
248
+ #self.w2 = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
249
+
250
+ self.w1 = PLoRA(self.hidden_size, self.intermediate_size, bias=False,
251
+ lora_r=256, lora_alpha=256, lora_len=1225)
252
+ self.w3 = PLoRA(self.hidden_size, self.intermediate_size, bias=False,
253
+ lora_r=256, lora_alpha=256, lora_len=1225)
254
+ self.w2 = PLoRA(self.intermediate_size, self.hidden_size, bias=False,
255
+ lora_r=256, lora_alpha=256, lora_len=1225)
256
+
257
+ self.act_fn = ACT2FN[config.hidden_act]
258
+
259
+ def forward(self, x, im_mask):
260
+ down_proj = self.w2(self.act_fn(self.w1(x, im_mask)) * self.w3(x, im_mask), im_mask)
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.wqkv = PLoRA(
301
+ self.hidden_size,
302
+ (self.num_heads + 2 * self.num_key_value_heads) * self.head_dim,
303
+ bias=config.bias,
304
+ )
305
+
306
+ #self.wo = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.bias)
307
+ self.wo = PLoRA(self.num_heads * self.head_dim, self.hidden_size, bias=config.bias,
308
+ lora_r=256, lora_alpha=256, lora_len=1225)
309
+ self._init_rope()
310
+
311
+ def _init_rope(self):
312
+ if self.config.rope_scaling is None:
313
+ self.rotary_emb = InternLM2RotaryEmbedding(
314
+ self.head_dim,
315
+ max_position_embeddings=self.max_position_embeddings,
316
+ base=self.config.rope_theta,
317
+ )
318
+ else:
319
+ scaling_type = self.config.rope_scaling["type"]
320
+ scaling_factor = self.config.rope_scaling["factor"]
321
+ if scaling_type == "dynamic":
322
+ self.rotary_emb = InternLM2DynamicNTKScalingRotaryEmbedding(
323
+ self.head_dim,
324
+ max_position_embeddings=self.max_position_embeddings,
325
+ base=self.config.rope_theta,
326
+ scaling_factor=scaling_factor,
327
+ )
328
+ elif scaling_type == "linear":
329
+ self.rotary_emb = InternLM2LinearScalingRotaryEmbedding(
330
+ self.head_dim,
331
+ max_position_embeddings=self.max_position_embeddings,
332
+ base=self.config.rope_theta,
333
+ scaling_factor=scaling_factor,
334
+ )
335
+ else:
336
+ raise ValueError("Currently we only support rotary embedding's type being 'dynamic' or 'linear'.")
337
+ return self.rotary_emb
338
+
339
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
340
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
341
+
342
+ def forward(
343
+ self,
344
+ hidden_states: torch.Tensor,
345
+ attention_mask: Optional[torch.Tensor] = None,
346
+ position_ids: Optional[torch.LongTensor] = None,
347
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
348
+ output_attentions: bool = False,
349
+ use_cache: bool = False,
350
+ im_mask: Optional[Tuple[torch.Tensor]] = None,
351
+ **kwargs,
352
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
353
+ if "padding_mask" in kwargs:
354
+ warnings.warn(
355
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. "
356
+ "Please make sure use `attention_mask` instead.`"
357
+ )
358
+
359
+ bsz, q_len, _ = hidden_states.size()
360
+
361
+ qkv_states = self.wqkv(hidden_states, im_mask)
362
+
363
+ qkv_states = rearrange(
364
+ qkv_states,
365
+ "b q (h gs d) -> b q h gs d",
366
+ gs=2 + self.num_key_value_groups,
367
+ d=self.head_dim,
368
+ )
369
+
370
+ query_states = qkv_states[..., : self.num_key_value_groups, :]
371
+ query_states = rearrange(query_states, "b q h gs d -> b q (h gs) d")
372
+ key_states = qkv_states[..., -2, :]
373
+ value_states = qkv_states[..., -1, :]
374
+
375
+ query_states = query_states.transpose(1, 2)
376
+ key_states = key_states.transpose(1, 2)
377
+ value_states = value_states.transpose(1, 2)
378
+
379
+ kv_seq_len = key_states.shape[-2]
380
+ if past_key_value is not None:
381
+ kv_seq_len += past_key_value[0].shape[-2]
382
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
383
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
384
+
385
+ if past_key_value is not None:
386
+ # reuse k, v, self_attention
387
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
388
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
389
+
390
+ past_key_value = (key_states, value_states) if use_cache else None
391
+
392
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
393
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
394
+
395
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
396
+
397
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
398
+ raise ValueError(
399
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
400
+ f" {attn_weights.size()}"
401
+ )
402
+
403
+ if attention_mask is not None:
404
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
405
+ raise ValueError(
406
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
407
+ )
408
+ attn_weights = attn_weights + attention_mask
409
+
410
+ # upcast attention to fp32
411
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
412
+ attn_output = torch.matmul(attn_weights, value_states)
413
+
414
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
415
+ raise ValueError(
416
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
417
+ f" {attn_output.size()}"
418
+ )
419
+
420
+ attn_output = attn_output.transpose(1, 2).contiguous()
421
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
422
+
423
+ attn_output = self.wo(attn_output, im_mask)
424
+
425
+ if not output_attentions:
426
+ attn_weights = None
427
+
428
+ return attn_output, attn_weights, past_key_value
429
+
430
+
431
+ # Modified from transformers.model.llama.modeling_llama.InternLM2FlashAttention2
432
+ class InternLM2FlashAttention2(InternLM2Attention):
433
+ """
434
+ InternLM2 flash attention module. This module inherits from `InternLM2Attention` as the weights of the module stays
435
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
436
+ flash attention and deal with padding tokens in case the input contains any of them.
437
+ """
438
+
439
+ def forward(
440
+ self,
441
+ hidden_states: torch.Tensor,
442
+ attention_mask: Optional[torch.LongTensor] = None,
443
+ position_ids: Optional[torch.LongTensor] = None,
444
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
445
+ output_attentions: bool = False,
446
+ use_cache: bool = False,
447
+ im_mask: Optional[Tuple[torch.Tensor]] = None,
448
+ **kwargs,
449
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
450
+ # InternLM2FlashAttention2 attention does not support output_attentions
451
+ if "padding_mask" in kwargs:
452
+ warnings.warn(
453
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. "
454
+ "Please make sure use `attention_mask` instead.`"
455
+ )
456
+
457
+ # overwrite attention_mask with padding_mask
458
+ attention_mask = kwargs.pop("padding_mask")
459
+
460
+ output_attentions = False
461
+
462
+ bsz, q_len, _ = hidden_states.size()
463
+
464
+ qkv_states = self.wqkv(hidden_states, im_mask)
465
+
466
+ qkv_states = rearrange(
467
+ qkv_states,
468
+ "b q (h gs d) -> b q h gs d",
469
+ gs=2 + self.num_key_value_groups,
470
+ d=self.head_dim,
471
+ )
472
+
473
+ query_states = qkv_states[..., : self.num_key_value_groups, :]
474
+ query_states = rearrange(query_states, "b q h gs d -> b q (h gs) d")
475
+ key_states = qkv_states[..., -2, :]
476
+ value_states = qkv_states[..., -1, :]
477
+
478
+ query_states = query_states.transpose(1, 2)
479
+ key_states = key_states.transpose(1, 2)
480
+ value_states = value_states.transpose(1, 2)
481
+
482
+ kv_seq_len = key_states.shape[-2]
483
+ if past_key_value is not None:
484
+ kv_seq_len += past_key_value[0].shape[-2]
485
+
486
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
487
+
488
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
489
+
490
+ if past_key_value is not None:
491
+ # reuse k, v, self_attention
492
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
493
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
494
+
495
+ past_key_value = (key_states, value_states) if use_cache else None
496
+
497
+ query_states = query_states.transpose(1, 2)
498
+ key_states = key_states.transpose(1, 2)
499
+ value_states = value_states.transpose(1, 2)
500
+
501
+ attn_output = self._flash_attention_forward(
502
+ query_states, key_states, value_states, attention_mask, q_len
503
+ )
504
+
505
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
506
+ attn_output = self.wo(attn_output, im_mask)
507
+
508
+ if not output_attentions:
509
+ attn_weights = None
510
+
511
+ return attn_output, attn_weights, past_key_value
512
+
513
+ def _flash_attention_forward(
514
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
515
+ ):
516
+ """
517
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
518
+ first unpad the input, then computes the attention scores and pad the final attention scores.
519
+
520
+ Args:
521
+ query_states (`torch.Tensor`):
522
+ Input query states to be passed to Flash Attention API
523
+ key_states (`torch.Tensor`):
524
+ Input key states to be passed to Flash Attention API
525
+ value_states (`torch.Tensor`):
526
+ Input value states to be passed to Flash Attention API
527
+ attention_mask (`torch.Tensor`):
528
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
529
+ position of padding tokens and 1 for the position of non-padding tokens.
530
+ dropout (`int`, *optional*):
531
+ Attention dropout
532
+ softmax_scale (`float`, *optional*):
533
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
534
+ """
535
+ # Contains at least one padding token in the sequence
536
+ causal = self.is_causal and query_length != 1
537
+ if attention_mask is not None:
538
+ batch_size = query_states.shape[0]
539
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._unpad_input(
540
+ query_states, key_states, value_states, attention_mask, query_length
541
+ )
542
+
543
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
544
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
545
+
546
+ attn_output_unpad = flash_attn_varlen_func(
547
+ query_states,
548
+ key_states,
549
+ value_states,
550
+ cu_seqlens_q=cu_seqlens_q,
551
+ cu_seqlens_k=cu_seqlens_k,
552
+ max_seqlen_q=max_seqlen_in_batch_q,
553
+ max_seqlen_k=max_seqlen_in_batch_k,
554
+ dropout_p=dropout,
555
+ softmax_scale=softmax_scale,
556
+ causal=causal,
557
+ )
558
+
559
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
560
+ else:
561
+ attn_output = flash_attn_func(
562
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
563
+ )
564
+
565
+ return attn_output
566
+
567
+ def _unpad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
568
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
569
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
570
+
571
+ key_layer = index_first_axis(
572
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
573
+ )
574
+ value_layer = index_first_axis(
575
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
576
+ )
577
+
578
+ if query_length == kv_seq_len:
579
+ query_layer = index_first_axis(
580
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
581
+ )
582
+ cu_seqlens_q = cu_seqlens_k
583
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
584
+ indices_q = indices_k
585
+ elif query_length == 1:
586
+ max_seqlen_in_batch_q = 1
587
+ cu_seqlens_q = torch.arange(
588
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
589
+ ) # There is a memcpy here, that is very bad.
590
+ indices_q = cu_seqlens_q[:-1]
591
+ query_layer = query_layer.squeeze(1)
592
+ else:
593
+ # The -q_len: slice assumes left padding.
594
+ attention_mask = attention_mask[:, -query_length:]
595
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
596
+
597
+ return (
598
+ query_layer,
599
+ key_layer,
600
+ value_layer,
601
+ indices_q.to(torch.int64),
602
+ (cu_seqlens_q, cu_seqlens_k),
603
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
604
+ )
605
+
606
+ INTERNLM2_ATTENTION_CLASSES = {
607
+ "eager": InternLM2Attention,
608
+ "flash_attention_2": InternLM2FlashAttention2,
609
+ }
610
+
611
+ # Modified from transformers.model.llama.modeling_llama.LlamaDecoderLayer
612
+ class InternLM2DecoderLayer(nn.Module):
613
+ def __init__(self, config: InternLM2Config):
614
+ super().__init__()
615
+ self.hidden_size = config.hidden_size
616
+
617
+ self.attention = INTERNLM2_ATTENTION_CLASSES[config.attn_implementation](config=config)
618
+
619
+ self.feed_forward = InternLM2MLP(config)
620
+ self.attention_norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
621
+ self.ffn_norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
622
+
623
+ def forward(
624
+ self,
625
+ hidden_states: torch.Tensor,
626
+ attention_mask: Optional[torch.Tensor] = None,
627
+ position_ids: Optional[torch.LongTensor] = None,
628
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
629
+ output_attentions: Optional[bool] = False,
630
+ use_cache: Optional[bool] = False,
631
+ im_mask: Optional[Tuple[torch.Tensor]] = None,
632
+ **kwargs,
633
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
634
+ """
635
+ Args:
636
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
637
+ attention_mask (`torch.FloatTensor`, *optional*):
638
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
639
+ query_sequence_length, key_sequence_length)` if default attention is used.
640
+ output_attentions (`bool`, *optional*):
641
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
642
+ returned tensors for more detail.
643
+ use_cache (`bool`, *optional*):
644
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
645
+ (see `past_key_values`).
646
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
647
+ """
648
+ if "padding_mask" in kwargs:
649
+ warnings.warn(
650
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. "
651
+ "Please make sure use `attention_mask` instead.`"
652
+ )
653
+
654
+ residual = hidden_states
655
+
656
+ hidden_states = self.attention_norm(hidden_states)
657
+
658
+ # Self Attention
659
+ hidden_states, self_attn_weights, present_key_value = self.attention(
660
+ hidden_states=hidden_states,
661
+ attention_mask=attention_mask,
662
+ position_ids=position_ids,
663
+ past_key_value=past_key_value,
664
+ output_attentions=output_attentions,
665
+ use_cache=use_cache,
666
+ im_mask=im_mask,
667
+ **kwargs,
668
+ )
669
+ hidden_states = residual + hidden_states
670
+
671
+ # Fully Connected
672
+ residual = hidden_states
673
+ hidden_states = self.ffn_norm(hidden_states)
674
+ hidden_states = self.feed_forward(hidden_states, im_mask)
675
+ hidden_states = residual + hidden_states
676
+
677
+ outputs = (hidden_states,)
678
+
679
+ if output_attentions:
680
+ outputs += (self_attn_weights,)
681
+
682
+ if use_cache:
683
+ outputs += (present_key_value,)
684
+
685
+ return outputs
686
+
687
+
688
+ InternLM2_START_DOCSTRING = r"""
689
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
690
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
691
+ etc.)
692
+
693
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
694
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
695
+ and behavior.
696
+
697
+ Parameters:
698
+ config ([`InternLM2Config`]):
699
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
700
+ load the weights associated with the model, only the configuration. Check out the
701
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
702
+ """
703
+
704
+
705
+ # Copied from transformers.models.llama.modeling_llama.LlamaPreTrainedModel with Llama->InternLM2
706
+ @add_start_docstrings(
707
+ "The bare InternLM2 Model outputting raw hidden-states without any specific head on top.",
708
+ InternLM2_START_DOCSTRING,
709
+ )
710
+ class InternLM2PreTrainedModel(PreTrainedModel):
711
+ config_class = InternLM2Config
712
+ base_model_prefix = "model"
713
+ supports_gradient_checkpointing = True
714
+ _no_split_modules = ["InternLM2DecoderLayer"]
715
+ _skip_keys_device_placement = "past_key_values"
716
+
717
+ def _init_weights(self, module):
718
+ std = self.config.initializer_range
719
+ if isinstance(module, nn.Linear):
720
+ module.weight.data.normal_(mean=0.0, std=std)
721
+ if module.bias is not None:
722
+ module.bias.data.zero_()
723
+ elif isinstance(module, nn.Embedding):
724
+ module.weight.data.normal_(mean=0.0, std=std)
725
+ if module.padding_idx is not None:
726
+ module.weight.data[module.padding_idx].zero_()
727
+
728
+
729
+ InternLM2_INPUTS_DOCSTRING = r"""
730
+ Args:
731
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
732
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
733
+ it.
734
+
735
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
736
+ [`PreTrainedTokenizer.__call__`] for details.
737
+
738
+ [What are input IDs?](../glossary#input-ids)
739
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
740
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
741
+
742
+ - 1 for tokens that are **not masked**,
743
+ - 0 for tokens that are **masked**.
744
+
745
+ [What are attention masks?](../glossary#attention-mask)
746
+
747
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
748
+ [`PreTrainedTokenizer.__call__`] for details.
749
+
750
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
751
+ `past_key_values`).
752
+
753
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
754
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
755
+ information on the default strategy.
756
+
757
+ - 1 indicates the head is **not masked**,
758
+ - 0 indicates the head is **masked**.
759
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
760
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
761
+ config.n_positions - 1]`.
762
+
763
+ [What are position IDs?](../glossary#position-ids)
764
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or
765
+ when `config.use_cache=True`):
766
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
767
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
768
+ `(batch_size, num_heads, decoder_sequence_length, embed_size_per_head)`.
769
+
770
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
771
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
772
+
773
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
774
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
775
+ of shape `(batch_size, sequence_length)`.
776
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
777
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
778
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
779
+ model's internal embedding lookup matrix.
780
+ use_cache (`bool`, *optional*):
781
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
782
+ `past_key_values`).
783
+ output_attentions (`bool`, *optional*):
784
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
785
+ tensors for more detail.
786
+ output_hidden_states (`bool`, *optional*):
787
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
788
+ more detail.
789
+ return_dict (`bool`, *optional*):
790
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
791
+ """
792
+
793
+
794
+ # Modified from transformers.model.llama.modeling_llama.LlamaModel
795
+ @add_start_docstrings(
796
+ "The bare InternLM2 Model outputting raw hidden-states without any specific head on top.",
797
+ InternLM2_START_DOCSTRING,
798
+ )
799
+ class InternLM2Model(InternLM2PreTrainedModel):
800
+ """
801
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`InternLM2DecoderLayer`]
802
+
803
+ Args:
804
+ config: InternLM2Config
805
+ """
806
+
807
+ _auto_class = "AutoModel"
808
+
809
+ def __init__(self, config: InternLM2Config):
810
+ super().__init__(config)
811
+ self.padding_idx = config.pad_token_id
812
+ self.vocab_size = config.vocab_size
813
+ self.config = config
814
+
815
+ self.tok_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
816
+
817
+ self.layers = nn.ModuleList([InternLM2DecoderLayer(config) for _ in range(config.num_hidden_layers)])
818
+ self.norm = InternLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
819
+
820
+ self.gradient_checkpointing = False
821
+ # Initialize weights and apply final processing
822
+ self.post_init()
823
+
824
+ def get_input_embeddings(self):
825
+ return self.tok_embeddings
826
+
827
+ def set_input_embeddings(self, value):
828
+ self.tok_embeddings = value
829
+
830
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
831
+ # create causal mask
832
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
833
+ combined_attention_mask = None
834
+ if input_shape[-1] > 1:
835
+ combined_attention_mask = _make_causal_mask(
836
+ input_shape,
837
+ inputs_embeds.dtype,
838
+ device=inputs_embeds.device,
839
+ past_key_values_length=past_key_values_length,
840
+ )
841
+
842
+ if attention_mask is not None:
843
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
844
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
845
+ inputs_embeds.device
846
+ )
847
+ combined_attention_mask = (
848
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
849
+ )
850
+
851
+ return combined_attention_mask
852
+
853
+ @add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
854
+ def forward(
855
+ self,
856
+ input_ids: torch.LongTensor = None,
857
+ attention_mask: Optional[torch.Tensor] = None,
858
+ position_ids: Optional[torch.LongTensor] = None,
859
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
860
+ inputs_embeds: Optional[torch.FloatTensor] = None,
861
+ use_cache: Optional[bool] = None,
862
+ output_attentions: Optional[bool] = None,
863
+ output_hidden_states: Optional[bool] = None,
864
+ return_dict: Optional[bool] = None,
865
+ **kwargs
866
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
867
+
868
+ im_mask = kwargs.get('im_mask', None)
869
+
870
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
871
+ output_hidden_states = (
872
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
873
+ )
874
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
875
+
876
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
877
+
878
+ if self.config.attn_implementation == "flash_attention_2":
879
+ _import_flash_attn()
880
+
881
+ # retrieve input_ids and inputs_embeds
882
+ if input_ids is not None and inputs_embeds is not None:
883
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
884
+ elif input_ids is not None:
885
+ batch_size, seq_length = input_ids.shape[:2]
886
+ elif inputs_embeds is not None:
887
+ batch_size, seq_length = inputs_embeds.shape[:2]
888
+ else:
889
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
890
+
891
+ seq_length_with_past = seq_length
892
+ past_key_values_length = 0
893
+ if past_key_values is not None:
894
+ past_key_values_length = past_key_values[0][0].shape[2]
895
+ seq_length_with_past = seq_length_with_past + past_key_values_length
896
+
897
+ if position_ids is None:
898
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
899
+ position_ids = torch.arange(
900
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
901
+ )
902
+ position_ids = position_ids.unsqueeze(0)
903
+
904
+ if inputs_embeds is None:
905
+ inputs_embeds = self.tok_embeddings(input_ids)
906
+ im_mask = torch.zeros(inputs_embeds.shape[:2]).to(inputs_embeds.device).bool()
907
+
908
+ if self.config.attn_implementation == "flash_attention_2":
909
+ # 2d mask is passed through the layers
910
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
911
+ else:
912
+ if attention_mask is None:
913
+ attention_mask = torch.ones(
914
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
915
+ )
916
+ attention_mask = self._prepare_decoder_attention_mask(
917
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
918
+ )
919
+
920
+ # embed positions
921
+ hidden_states = inputs_embeds
922
+
923
+ if self.gradient_checkpointing and self.training:
924
+ if use_cache:
925
+ logger.warning_once(
926
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
927
+ )
928
+ use_cache = False
929
+
930
+ # decoder layers
931
+ all_hidden_states = () if output_hidden_states else None
932
+ all_self_attns = () if output_attentions else None
933
+ next_decoder_cache = () if use_cache else None
934
+
935
+ for idx, decoder_layer in enumerate(self.layers):
936
+ if output_hidden_states:
937
+ all_hidden_states += (hidden_states,)
938
+
939
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
940
+
941
+ if self.gradient_checkpointing and self.training:
942
+
943
+ def create_custom_forward(module):
944
+ def custom_forward(*inputs):
945
+ # None for past_key_value
946
+ return module(*inputs, output_attentions, None, im_mask)
947
+
948
+ return custom_forward
949
+
950
+ layer_outputs = torch.utils.checkpoint.checkpoint(
951
+ create_custom_forward(decoder_layer),
952
+ hidden_states,
953
+ attention_mask,
954
+ position_ids,
955
+ None,
956
+ )
957
+ else:
958
+ layer_outputs = decoder_layer(
959
+ hidden_states,
960
+ attention_mask=attention_mask,
961
+ position_ids=position_ids,
962
+ past_key_value=past_key_value,
963
+ output_attentions=output_attentions,
964
+ use_cache=use_cache,
965
+ im_mask=im_mask,
966
+ )
967
+
968
+ hidden_states = layer_outputs[0]
969
+
970
+ if use_cache:
971
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
972
+
973
+ if output_attentions:
974
+ all_self_attns += (layer_outputs[1],)
975
+
976
+ hidden_states = self.norm(hidden_states)
977
+
978
+ # add hidden states from the last decoder layer
979
+ if output_hidden_states:
980
+ all_hidden_states += (hidden_states,)
981
+
982
+ next_cache = next_decoder_cache if use_cache else None
983
+ if not return_dict:
984
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
985
+ return BaseModelOutputWithPast(
986
+ last_hidden_state=hidden_states,
987
+ past_key_values=next_cache,
988
+ hidden_states=all_hidden_states,
989
+ attentions=all_self_attns,
990
+ )
modeling_internlm_xcomposer2.py ADDED
@@ -0,0 +1,538 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
17
+ """PyTorch InternLMXComposer2 model."""
18
+ import copy
19
+ import queue
20
+ import threading
21
+ from typing import List, Optional, Tuple, Union
22
+
23
+ import torch
24
+ import torch.utils.checkpoint
25
+ from PIL import Image
26
+ from torch import nn
27
+ from torch.nn import CrossEntropyLoss
28
+ from torchvision import transforms
29
+ from torchvision.transforms.functional import InterpolationMode
30
+ from transformers.modeling_outputs import CausalLMOutputWithPast
31
+ from transformers.utils import (add_start_docstrings_to_model_forward,
32
+ replace_return_docstrings)
33
+
34
+ try:
35
+ from transformers.generation.streamers import BaseStreamer
36
+ except: # noqa # pylint: disable=bare-except
37
+ BaseStreamer = None
38
+
39
+ from .build_mlp import build_vision_projector, build_vision_tower
40
+ from .ixc_utils import HD_transform
41
+ from .configuration_internlm_xcomposer2 import InternLMXcomposer2Config
42
+ from .modeling_internlm2 import (InternLM2_INPUTS_DOCSTRING, InternLM2Model,
43
+ InternLM2PreTrainedModel)
44
+
45
+ _CONFIG_FOR_DOC = 'InternLMXcomposer2Config'
46
+
47
+
48
+ class InternLMXComposer2ForCausalLM(InternLM2PreTrainedModel):
49
+ _auto_class = 'AutoModelForCausalLM'
50
+
51
+ _tied_weights_keys = ['output.weight']
52
+
53
+ def __init__(self, config):
54
+ super().__init__(config)
55
+ self.model = InternLM2Model(config)
56
+ self.vocab_size = config.vocab_size
57
+ self.output = nn.Linear(
58
+ config.hidden_size, config.vocab_size, bias=False)
59
+ self.tokenizer = None
60
+
61
+ self.max_length = config.max_length
62
+ print(f'Set max length to {self.max_length}')
63
+ # Initialize weights and apply final processing
64
+ self.post_init()
65
+ self.plora_glb_GN = nn.Parameter(torch.zeros([1, 1, 4096]))
66
+ self.plora_sub_GN = nn.Parameter(torch.zeros([1, 1, 1, 4096]))
67
+
68
+ self.vit = build_vision_tower()
69
+ self.vision_proj = build_vision_projector()
70
+
71
+ self.vis_processor = transforms.Compose([
72
+ transforms.ToTensor(),
73
+ transforms.Normalize((0.48145466, 0.4578275, 0.40821073),
74
+ (0.26862954, 0.26130258, 0.27577711)),
75
+ ])
76
+
77
+ def _set_gradient_checkpointing(self, module, value=False):
78
+ if isinstance(module, InternLM2Model):
79
+ module.gradient_checkpointing = value
80
+ if value:
81
+ self.vit.vision_tower.vision_model.encoder.gradient_checkpointing = value
82
+
83
+ def get_input_embeddings(self):
84
+ return self.model.tok_embeddings
85
+
86
+ def set_input_embeddings(self, value):
87
+ self.model.tok_embeddings = value
88
+
89
+ def get_output_embeddings(self):
90
+ return self.output
91
+
92
+ def set_output_embeddings(self, new_embeddings):
93
+ self.output = new_embeddings
94
+
95
+ def set_decoder(self, decoder):
96
+ self.model = decoder
97
+
98
+ def get_decoder(self):
99
+ return self.model
100
+
101
+ def encode_text(self, text, add_special_tokens=False):
102
+ token = self.tokenizer(
103
+ text, return_tensors='pt',
104
+ add_special_tokens=add_special_tokens).input_ids.to(self.device)
105
+ embs = self.model.tok_embeddings(token)
106
+ return embs
107
+
108
+ def encode_img(self, image, hd_num=25):
109
+ if image is None:
110
+ return None
111
+ if isinstance(image, str):
112
+ image = Image.open(image).convert('RGB')
113
+ image = HD_transform(image, hd_num = hd_num)
114
+ image = self.vis_processor(image).unsqueeze(0).to(self.device)
115
+
116
+ img_embeds, atts_img, img_target = self.img2emb(image)
117
+ return img_embeds
118
+
119
+ def img2emb(self, image):
120
+ img_embeds, img_split = self.vit([image],
121
+ self.plora_glb_GN, self.plora_sub_GN)
122
+ if len(img_split) > 1:
123
+ print ('Batch Size >1 is not supported.')
124
+ assert 0
125
+ #print (img_embeds.shape)
126
+ img_embeds = self.vision_proj(img_embeds)
127
+ atts_img = torch.ones(
128
+ img_embeds.size()[:-1], dtype=torch.long).to(img_embeds.device)
129
+
130
+ img_target = torch.ones(
131
+ img_embeds.size()[:2], dtype=torch.long).to(
132
+ img_embeds.device) * -100
133
+
134
+ return img_embeds, atts_img, img_target
135
+
136
+ def prompt_wrap(self, img_embeds, prompt):
137
+ batch_size = img_embeds.shape[0]
138
+ p_before, p_after = prompt.split('<ImageHere>')
139
+ p_before_tokens = self.tokenizer(
140
+ p_before, return_tensors='pt',
141
+ add_special_tokens=True).to(img_embeds.device)
142
+
143
+ p_before_embeds = self.model.tok_embeddings(
144
+ p_before_tokens.input_ids).expand(batch_size, -1, -1)
145
+ wrapped_img_embeds = torch.cat([p_before_embeds, img_embeds], dim=1)
146
+
147
+ wrapped_atts_img = torch.ones(
148
+ wrapped_img_embeds.size()[:-1],
149
+ dtype=torch.long).to(img_embeds.device)
150
+
151
+ wrapped_target = torch.ones(
152
+ batch_size, wrapped_img_embeds.shape[1], dtype=torch.long).to(
153
+ img_embeds.device) * -100
154
+
155
+ return wrapped_img_embeds, wrapped_atts_img, wrapped_target
156
+
157
+ def text2emb(self, text, add_special=False):
158
+ to_regress_tokens = self.tokenizer(
159
+ text,
160
+ return_tensors='pt',
161
+ padding='longest',
162
+ truncation=True,
163
+ max_length=self.max_length,
164
+ add_special_tokens=add_special).to(self.device)
165
+
166
+ targets = self.mask_human_targets(to_regress_tokens.input_ids)
167
+ targets = targets.to(self.device)
168
+ return to_regress_tokens, targets
169
+
170
+ def interleav_wrap_chat(self, tokenizer, query, image, history, meta_instruction):
171
+ prompt = ''
172
+ if meta_instruction:
173
+ prompt += f"""[UNUSED_TOKEN_146]system\n{meta_instruction}[UNUSED_TOKEN_145]\n"""
174
+ for record in history:
175
+ prompt += f"""[UNUSED_TOKEN_146]user\n{record[0]}[UNUSED_TOKEN_145]\n[UNUSED_TOKEN_146]assistant\n{record[1]}[UNUSED_TOKEN_145]\n"""
176
+ prompt += f"""[UNUSED_TOKEN_146]user\n{query}[UNUSED_TOKEN_145]\n[UNUSED_TOKEN_146]assistant\n"""
177
+
178
+ im_len = image.shape[1]
179
+ image_nums = len(image)
180
+ parts = prompt.split('<ImageHere>')
181
+ wrap_embeds, wrap_im_mask = [], []
182
+ temp_len = 0
183
+
184
+ if len(parts) != image_nums + 1:
185
+ raise ValueError('Invalid <ImageHere> prompt format.')
186
+
187
+ for idx, part in enumerate(parts):
188
+ if len(part) > 0:
189
+ part_tokens = tokenizer(part, return_tensors='pt').to(self.device)
190
+ part_embeds = self.model.tok_embeddings(
191
+ part_tokens.input_ids)
192
+ wrap_embeds.append(part_embeds)
193
+ wrap_im_mask.append(torch.zeros(part_embeds.shape[:2]))
194
+ temp_len += part_embeds.shape[1]
195
+ if idx < image_nums:
196
+ wrap_embeds.append(image[idx].unsqueeze(0))
197
+ wrap_im_mask.append(torch.ones(1, image[idx].shape[0]))
198
+ temp_len += im_len
199
+
200
+ if temp_len > self.max_length:
201
+ break
202
+
203
+ wrap_embeds = torch.cat(wrap_embeds, dim=1)
204
+ wrap_im_mask = torch.cat(wrap_im_mask, dim=1)
205
+ wrap_embeds = wrap_embeds[:, :self.max_length].to(self.device)
206
+ wrap_im_mask = wrap_im_mask[:, :self.max_length].to(self.device).bool()
207
+ inputs = {
208
+ 'inputs_embeds': wrap_embeds
209
+ }
210
+ return inputs, wrap_im_mask
211
+
212
+ def interleav_wrap(self, img_list, text_list):
213
+ wrap_embeds_list, wrap_atts_list = [], []
214
+ wrap_target_list, wrap_im_mask_list = [], []
215
+
216
+ for image, text in zip(img_list, text_list):
217
+ img_embeds, atts_img, img_target = self.img2emb(image)
218
+ text = text[0]
219
+ parts = text.split('<ImageHere>')
220
+ wrap_tokens, wrap_embeds, wrap_atts, wrap_im_mask = [], [], [], []
221
+ temp_len = 0
222
+ image_nums, im_len = img_embeds.shape[:2]
223
+ need_bos = True
224
+ for idx, part in enumerate(parts):
225
+ if len(part) > 0:
226
+ part_tokens = self.tokenizer(
227
+ part,
228
+ return_tensors='pt',
229
+ padding='longest',
230
+ add_special_tokens=need_bos).to(self.device)
231
+ if need_bos:
232
+ need_bos = False
233
+ wrap_tokens.append(part_tokens.input_ids)
234
+ part_embeds = self.model.tok_embeddings(
235
+ part_tokens.input_ids)
236
+ wrap_embeds.append(part_embeds)
237
+ wrap_atts.append(part_tokens.attention_mask)
238
+ wrap_im_mask.append(
239
+ torch.zeros(part_embeds.shape[:2]).to(self.device))
240
+
241
+ temp_len += part_embeds.shape[1]
242
+ if idx < image_nums:
243
+ wrap_tokens.append(img_target[idx].unsqueeze(0))
244
+ wrap_embeds.append(img_embeds[idx].unsqueeze(0))
245
+ wrap_atts.append(atts_img[idx].unsqueeze(0))
246
+ wrap_im_mask.append(
247
+ torch.ones_like(atts_img[idx].unsqueeze(0)))
248
+
249
+ temp_len += im_len
250
+ if temp_len > self.max_length:
251
+ break
252
+
253
+ wrap_tokens = torch.cat(wrap_tokens, dim=1)
254
+ wrap_embeds = torch.cat(wrap_embeds, dim=1)
255
+ wrap_atts = torch.cat(wrap_atts, dim=1)
256
+ wrap_im_mask = torch.cat(wrap_im_mask, dim=1)
257
+
258
+ wrap_target = self.mask_human_targets(wrap_tokens).to(self.device)
259
+
260
+ wrap_embeds = wrap_embeds[:, :self.max_length].to(self.device)
261
+ wrap_atts = wrap_atts[:, :self.max_length].to(self.device)
262
+ wrap_target = wrap_target[:, :self.max_length].to(self.device)
263
+ wrap_im_mask = wrap_im_mask[:, :self.max_length].to(self.device)
264
+
265
+ wrap_embeds_list.append(wrap_embeds)
266
+ wrap_atts_list.append(wrap_atts)
267
+ wrap_target_list.append(wrap_target)
268
+ wrap_im_mask_list.append(wrap_im_mask)
269
+
270
+ wrap_embeds = torch.cat(wrap_embeds_list)
271
+ wrap_atts = torch.cat(wrap_atts_list)
272
+ wrap_target = torch.cat(wrap_target_list)
273
+ wrap_im_mask = torch.cat(wrap_im_mask_list)
274
+ return wrap_embeds, wrap_atts, wrap_target, wrap_im_mask
275
+
276
+ def mask_human_targets(self, input_ids, pure=False):
277
+ target_batch = []
278
+ for bs in range(input_ids.shape[0]):
279
+ ids = input_ids[bs]
280
+ targets = copy.deepcopy(ids)
281
+ end_count = 0
282
+ last_eoa = 0
283
+ for i, temp_id in enumerate(ids):
284
+ if temp_id == 92542:
285
+ if end_count % 2 == 0:
286
+ targets[last_eoa:i + 6] = -100
287
+ else:
288
+ last_eoa = i + 1
289
+ end_count += 1
290
+ # # eos and following pad
291
+ elif temp_id == 2:
292
+ # loss on eos, but not on pad
293
+ targets[i + 1:] = -100
294
+ break
295
+ # trunction, end at last question
296
+ if temp_id != 2 and end_count % 2 == 0:
297
+ # mask all after the last answer
298
+ targets[last_eoa + 1:] = -100
299
+ target_batch.append(targets.unsqueeze(0))
300
+ target_batch = torch.cat(target_batch, dim=0)
301
+ return target_batch
302
+
303
+ @add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
304
+ @replace_return_docstrings(
305
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
306
+ def forward(self,
307
+ input_ids: torch.LongTensor = None,
308
+ attention_mask: Optional[torch.Tensor] = None,
309
+ position_ids: Optional[torch.LongTensor] = None,
310
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
311
+ inputs_embeds: Optional[torch.FloatTensor] = None,
312
+ labels: Optional[torch.LongTensor] = None,
313
+ use_cache: Optional[bool] = None,
314
+ output_attentions: Optional[bool] = None,
315
+ output_hidden_states: Optional[bool] = None,
316
+ return_dict: Optional[bool] = None,
317
+ **kwargs) -> Union[Tuple, CausalLMOutputWithPast]:
318
+ r"""
319
+ Args:
320
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
321
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
322
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
323
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
324
+ Returns:
325
+ """
326
+
327
+ samples = kwargs.get('samples', None)
328
+ if samples:
329
+ if samples['data_type'][0] == 'text':
330
+ has_img = False
331
+ elif samples['data_type'][0] == 'multi':
332
+ has_img = True
333
+ else:
334
+ raise NotImplementedError
335
+
336
+ # encode text
337
+ text = samples['text_input']
338
+ # encode image
339
+ if has_img:
340
+ image = samples['image']
341
+ to_regress_embeds, attention_mask, targets, im_mask = self.interleav_wrap(
342
+ image, text)
343
+ else:
344
+ to_regress_tokens, targets = self.text2emb(
345
+ text, add_special=True)
346
+ to_regress_embeds = self.model.tok_embeddings(
347
+ to_regress_tokens.input_ids)
348
+ attention_mask = to_regress_tokens.attention_mask
349
+ im_mask = torch.zeros(to_regress_embeds.shape[:2]).cuda()
350
+
351
+ inputs_embeds = to_regress_embeds[:, :self.max_length]
352
+ attention_mask = attention_mask[:, :self.max_length]
353
+ targets = targets[:, :self.max_length]
354
+ im_mask = im_mask[:, :self.max_length].bool()
355
+ labels = targets
356
+ else:
357
+ im_mask = kwargs.get('im_mask', None)
358
+ if im_mask is None and inputs_embeds is not None:
359
+ im_mask = torch.zeros(inputs_embeds.shape[:2]).to(
360
+ inputs_embeds.device)
361
+ im_mask = im_mask.bool()
362
+
363
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
364
+ output_hidden_states = (
365
+ output_hidden_states if output_hidden_states is not None else
366
+ self.config.output_hidden_states)
367
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
368
+
369
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
370
+ outputs = self.model(
371
+ input_ids=input_ids,
372
+ attention_mask=attention_mask,
373
+ position_ids=position_ids,
374
+ past_key_values=past_key_values,
375
+ inputs_embeds=inputs_embeds,
376
+ use_cache=use_cache,
377
+ output_attentions=output_attentions,
378
+ output_hidden_states=output_hidden_states,
379
+ return_dict=return_dict,
380
+ im_mask=im_mask,
381
+ )
382
+
383
+ hidden_states = outputs[0]
384
+ logits = self.output(hidden_states)
385
+ logits = logits.float()
386
+
387
+ loss = None
388
+ if labels is not None:
389
+ # Shift so that tokens < n predict n
390
+ shift_logits = logits[..., :-1, :].contiguous()
391
+ shift_labels = labels[..., 1:].contiguous()
392
+ # Flatten the tokens
393
+ loss_fct = CrossEntropyLoss()
394
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
395
+ shift_labels = shift_labels.view(-1)
396
+ # Enable model parallelism
397
+ shift_labels = shift_labels.to(shift_logits.device)
398
+ loss = loss_fct(shift_logits, shift_labels)
399
+
400
+ if not return_dict:
401
+ output = (logits, ) + outputs[1:]
402
+ return (loss, ) + output if loss is not None else output
403
+
404
+ return CausalLMOutputWithPast(
405
+ loss=loss,
406
+ logits=logits,
407
+ past_key_values=outputs.past_key_values,
408
+ hidden_states=outputs.hidden_states,
409
+ attentions=outputs.attentions,
410
+ )
411
+
412
+ def prepare_inputs_for_generation(self,
413
+ input_ids,
414
+ past_key_values=None,
415
+ attention_mask=None,
416
+ inputs_embeds=None,
417
+ im_mask=None,
418
+ **kwargs):
419
+ if past_key_values is not None:
420
+ past_length = past_key_values[0][0].shape[2]
421
+
422
+ # Some generation methods already pass only the last input ID
423
+ if input_ids.shape[1] > past_length:
424
+ remove_prefix_length = past_length
425
+ else:
426
+ # Default to old behavior: keep only final ID
427
+ remove_prefix_length = input_ids.shape[1] - 1
428
+
429
+ input_ids = input_ids[:, remove_prefix_length:]
430
+
431
+ position_ids = kwargs.get('position_ids', None)
432
+ if attention_mask is not None and position_ids is None:
433
+ # create position_ids on the fly for batch generation
434
+ position_ids = attention_mask.long().cumsum(-1) - 1
435
+ position_ids.masked_fill_(attention_mask == 0, 1)
436
+ if past_key_values:
437
+ position_ids = position_ids[:, -input_ids.shape[1]:]
438
+
439
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
440
+ if inputs_embeds is not None and past_key_values is None:
441
+ model_inputs = {'inputs_embeds': inputs_embeds}
442
+ else:
443
+ model_inputs = {'input_ids': input_ids}
444
+
445
+ im_mask = im_mask
446
+
447
+ model_inputs.update({
448
+ 'position_ids': position_ids,
449
+ 'past_key_values': past_key_values,
450
+ 'use_cache': kwargs.get('use_cache'),
451
+ 'attention_mask': attention_mask,
452
+ 'im_mask': im_mask,
453
+ })
454
+ return model_inputs
455
+
456
+ @staticmethod
457
+ def _reorder_cache(past_key_values, beam_idx):
458
+ reordered_past = ()
459
+ for layer_past in past_key_values:
460
+ reordered_past += (tuple(
461
+ past_state.index_select(0, beam_idx.to(past_state.device))
462
+ for past_state in layer_past), )
463
+ return reordered_past
464
+
465
+ def build_inputs(self,
466
+ tokenizer,
467
+ query: str,
468
+ history: List[Tuple[str, str]] = [],
469
+ meta_instruction=''):
470
+ prompt = ''
471
+ if meta_instruction:
472
+ prompt += f"""<s>[UNUSED_TOKEN_146]system\n{meta_instruction}[UNUSED_TOKEN_145]\n"""
473
+ else:
474
+ prompt += '<s>'
475
+ for record in history:
476
+ prompt += f"""[UNUSED_TOKEN_146]user\n{record[0]}[UNUSED_TOKEN_145]\n[UNUSED_TOKEN_146]assistant\n{record[1]}[UNUSED_TOKEN_145]\n"""
477
+ prompt += f"""[UNUSED_TOKEN_146]user\n{query}[UNUSED_TOKEN_145]\n[UNUSED_TOKEN_146]assistant\n"""
478
+ return tokenizer([prompt], return_tensors='pt')
479
+
480
+ @torch.no_grad()
481
+ def chat(
482
+ self,
483
+ tokenizer,
484
+ query: str,
485
+ image: torch.Tensor = None,
486
+ hd_num: int = 25,
487
+ history: List[Tuple[str, str]] = [],
488
+ streamer: Optional[BaseStreamer] = None,
489
+ max_new_tokens: int = 1024,
490
+ do_sample: bool = True,
491
+ num_beams: int = 1,
492
+ temperature: float = 1.0,
493
+ top_p: float = 0.8,
494
+ repetition_penalty: float=1.005,
495
+ meta_instruction:
496
+ str = 'You are an AI assistant whose name is InternLM-XComposer (浦语·灵笔).\n'
497
+ '- InternLM-XComposer (浦语·灵笔) is a multi-modality conversational language model that is developed by Shanghai AI Laboratory (上海人工智能实验室). It is designed to be helpful, honest, and harmless.\n'
498
+ '- InternLM-XComposer (浦语·灵笔) can understand and communicate fluently in the language chosen by the user such as English and 中文.\n'
499
+ '- InternLM-XComposer (浦语·灵笔) is capable of comprehending and articulating responses effectively based on the provided image.',
500
+ **kwargs,
501
+ ):
502
+ if image is None:
503
+ inputs = self.build_inputs(tokenizer, query, history, meta_instruction)
504
+ im_mask = torch.zeros(inputs['input_ids'].shape[:2]).cuda().bool()
505
+ else:
506
+ image = self.encode_img(image, hd_num=hd_num)
507
+ inputs, im_mask = self.interleav_wrap_chat(tokenizer, query, image, history, meta_instruction)
508
+ inputs = {
509
+ k: v.to(self.device)
510
+ for k, v in inputs.items() if torch.is_tensor(v)
511
+ }
512
+ # also add end-of-assistant token in eos token id to avoid unnecessary generation
513
+ eos_token_id = [
514
+ tokenizer.eos_token_id,
515
+ tokenizer.convert_tokens_to_ids(['[UNUSED_TOKEN_145]'])[0]
516
+ ]
517
+ outputs = self.generate(
518
+ **inputs,
519
+ streamer=streamer,
520
+ max_new_tokens=max_new_tokens,
521
+ num_beams=num_beams,
522
+ do_sample=do_sample,
523
+ temperature=temperature,
524
+ top_p=top_p,
525
+ eos_token_id=eos_token_id,
526
+ repetition_penalty=repetition_penalty,
527
+ im_mask=im_mask,
528
+ **kwargs,
529
+ )
530
+ if image is None:
531
+ outputs = outputs[0].cpu().tolist()[len(inputs['input_ids'][0]):]
532
+ else:
533
+ outputs = outputs[0].cpu().tolist()
534
+ response = tokenizer.decode(outputs, skip_special_tokens=True)
535
+ response = response.split('[UNUSED_TOKEN_145]')[0]
536
+ history = history + [(query, response)]
537
+ return response, history
538
+