DLight1551 commited on
Commit
5aa1ab6
·
1 Parent(s): e5373b1
Files changed (4) hide show
  1. build_mlp.py +2 -2
  2. build_mlp.py~ +206 -0
  3. modeling_internlm2.py +5 -3
  4. modeling_internlm2.py~ +1548 -0
build_mlp.py CHANGED
@@ -52,8 +52,8 @@ class CLIPVisionTower(nn.Module):
52
  self.vision_tower_name = vision_tower
53
  self.select_layer = -1
54
  self.select_feature = 'patch'
55
- self.load_model()
56
- self.resize_pos()
57
 
58
  def load_model(self):
59
  self.vision_tower = CLIPVisionModel.from_pretrained(self.vision_tower_name)
 
52
  self.vision_tower_name = vision_tower
53
  self.select_layer = -1
54
  self.select_feature = 'patch'
55
+ #self.load_model()
56
+ #self.resize_pos()
57
 
58
  def load_model(self):
59
  self.vision_tower = CLIPVisionModel.from_pretrained(self.vision_tower_name)
build_mlp.py~ ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import re
4
+ import os
5
+ import math
6
+ from transformers import CLIPVisionModel, CLIPImageProcessor, CLIPVisionConfig
7
+
8
+
9
+ def build_vision_tower(path):
10
+ vision_tower = os.path.join(path, 'clip_l_336')
11
+ return CLIPVisionTower(vision_tower)
12
+
13
+
14
+ def build_vision_projector():
15
+ projector_type = 'mlp2x_gelu'
16
+ mm_hidden_size = 1024
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, hidden_size)]
23
+ for _ in range(1, mlp_depth):
24
+ modules.append(nn.GELU())
25
+ modules.append(nn.Linear(hidden_size, hidden_size))
26
+ return nn.Sequential(*modules)
27
+
28
+ if projector_type == 'identity':
29
+ return IdentityMap()
30
+
31
+ raise ValueError(f'Unknown projector type: {projector_type}')
32
+
33
+ class IdentityMap(nn.Module):
34
+ def __init__(self):
35
+ super().__init__()
36
+
37
+ def forward(self, x, *args, **kwargs):
38
+ return x
39
+
40
+ @property
41
+ def config(self):
42
+ return {"mm_projector_type": 'identity'}
43
+
44
+
45
+ class CLIPVisionTower(nn.Module):
46
+ def __init__(self, vision_tower):
47
+ super().__init__()
48
+
49
+ self.is_loaded = False
50
+ self.is_resize_pos = False
51
+
52
+ self.vision_tower_name = vision_tower
53
+ self.select_layer = -1
54
+ self.select_feature = 'patch'
55
+ #self.load_model()
56
+ #self.resize_pos()
57
+
58
+ def load_model(self):
59
+ self.vision_tower = CLIPVisionModel.from_pretrained(self.vision_tower_name)
60
+ self.vision_tower.requires_grad_(False)
61
+
62
+ self.is_loaded = True
63
+ def resize_pos(self):
64
+ pos_embed_checkpoint = self.vision_tower.vision_model.embeddings.position_embedding.weight
65
+ pos_embed_checkpoint = pos_embed_checkpoint.unsqueeze(0)
66
+ orig_size = 24
67
+ new_size = 16
68
+
69
+ if pos_embed_checkpoint.shape[1] == new_size ** 2 + 1:
70
+ self.is_resize_pos = True
71
+ else:
72
+ embedding_size = pos_embed_checkpoint.shape[-1]
73
+ num_extra_tokens = 1
74
+ new_num = new_size ** 2 + num_extra_tokens
75
+ print("Position interpolate from %dx%d to %dx%d" %
76
+ (orig_size, orig_size, new_size, new_size))
77
+ extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
78
+ # only the position tokens are interpolated
79
+ pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]
80
+ pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size,
81
+ embedding_size).permute(
82
+ 0, 3, 1, 2)
83
+ pos_tokens = torch.nn.functional.interpolate(pos_tokens,
84
+ size=(new_size,
85
+ new_size),
86
+ mode='bicubic',
87
+ align_corners=False)
88
+ pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2)
89
+ new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
90
+
91
+ new_pos_embed = new_pos_embed.squeeze(0)
92
+
93
+ self.vision_tower.vision_model.embeddings.position_embedding = torch.nn.Embedding(new_num, 1024)
94
+ self.vision_tower.vision_model.embeddings.position_embedding.weight = torch.nn.Parameter(new_pos_embed.to(pos_embed_checkpoint.dtype))
95
+ self.vision_tower.vision_model.embeddings.position_ids = torch.arange(new_num).expand((1, -1))
96
+
97
+ #self.vision_tower.vision_model.embeddings.position_embedding.weight = torch.nn.Parameter(new_pos_embed.to(pos_embed_checkpoint.device).to(pos_embed_checkpoint.dtype))
98
+ #self.vision_tower.vision_model.embeddings.position_ids = torch.arange(new_num).expand((1, -1)).to(pos_embed_checkpoint.device)
99
+ self.is_resize_pos = True
100
+
101
+ def feature_select(self, image_forward_outs):
102
+ image_features = image_forward_outs.hidden_states[self.select_layer]
103
+ if self.select_feature == 'patch':
104
+ image_features = image_features[:, 1:]
105
+ elif self.select_feature == 'cls_patch':
106
+ image_features = image_features
107
+ else:
108
+ raise ValueError(f'Unexpected select feature: {self.select_feature}')
109
+ return image_features
110
+
111
+ def forward(self, images):
112
+ if not self.is_loaded:
113
+ self.load_model()
114
+ if type(images) is list:
115
+ image_features = []
116
+ for image in images:
117
+ image_forward_out = self.vision_tower(image.to(device=self.device, dtype=self.dtype).unsqueeze(0), output_hidden_states=True)
118
+ image_feature = self.feature_select(image_forward_out).to(image.dtype)
119
+ image_features.append(image_feature)
120
+ else:
121
+ image_forward_outs = self.vision_tower(images.to(device=self.device, dtype=self.dtype), output_hidden_states=True)
122
+ image_features = self.feature_select(image_forward_outs).to(images.dtype)
123
+
124
+ return image_features
125
+
126
+ @property
127
+ def dummy_feature(self):
128
+ return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
129
+
130
+ @property
131
+ def dtype(self):
132
+ return self.vision_tower.dtype
133
+
134
+ @property
135
+ def device(self):
136
+ return self.vision_tower.device
137
+
138
+ @property
139
+ def config(self):
140
+ if self.is_loaded:
141
+ return self.vision_tower.config
142
+ else:
143
+ return self.cfg_only
144
+
145
+ @property
146
+ def hidden_size(self):
147
+ return self.config.hidden_size
148
+
149
+ @property
150
+ def num_patches(self):
151
+ return (self.config.image_size // self.config.patch_size) ** 2
152
+
153
+ class PLoRA(nn.Linear):
154
+ def __init__(self,
155
+ in_features: int,
156
+ out_features: int,
157
+ bias: bool = True,
158
+ device=None,
159
+ dtype=None,
160
+ lora_r=8,
161
+ lora_alpha=16,
162
+ lora_dropout=0.05,
163
+ lora_len=0,
164
+ **kwargs) -> None:
165
+ super().__init__(in_features, out_features, bias, device, dtype)
166
+ self.lora_r = lora_r
167
+ self.lora_alpha = lora_alpha
168
+ self.lora_len = lora_len
169
+ if lora_dropout > 0.:
170
+ self.lora_dropout = nn.Dropout(p=lora_dropout)
171
+ else:
172
+ self.lora_dropout = lambda x: x
173
+ self.lora_scaling = self.lora_alpha / self.lora_r
174
+
175
+ self.Plora_A = nn.Linear(in_features,
176
+ self.lora_r,
177
+ bias=False,
178
+ device=device,
179
+ dtype=dtype)
180
+ self.Plora_B = nn.Linear(self.lora_r,
181
+ out_features,
182
+ bias=False,
183
+ device=device,
184
+ dtype=dtype)
185
+
186
+ self.reset_parameters()
187
+
188
+ def reset_parameters(self):
189
+ if hasattr(self, 'lora_A'):
190
+ # initialize A the same way as the default for nn.Linear and B to zero
191
+ nn.init.kaiming_uniform_(self.lora_A.weight, a=math.sqrt(5))
192
+ nn.init.zeros_(self.lora_B.weight)
193
+ #print ("lora weight init {} {}".format(torch.mean(self.lora_A.weight), torch.mean(self.lora_B.weight)))
194
+
195
+ def forward(self, x, im_mask=None):
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
+ return res
modeling_internlm2.py CHANGED
@@ -1015,8 +1015,8 @@ class InternLM2ForCausalLM(InternLM2PreTrainedModel):
1015
  def _set_gradient_checkpointing(self, module, value=False):
1016
  if isinstance(module, InternLM2Model):
1017
  module.gradient_checkpointing = value
1018
- if value:
1019
- self.vit.vision_tower.vision_model.encoder.gradient_checkpointing = value
1020
 
1021
  def get_input_embeddings(self):
1022
  return self.model.tok_embeddings
@@ -1064,7 +1064,9 @@ class InternLM2ForCausalLM(InternLM2PreTrainedModel):
1064
  return img_embeds
1065
 
1066
  def img2emb(self, image):
1067
- img_embeds = self.vision_proj(self.vit(image.to(self.device)))
 
 
1068
  atts_img = torch.ones(
1069
  img_embeds.size()[:-1], dtype=torch.long).to(img_embeds.device)
1070
 
 
1015
  def _set_gradient_checkpointing(self, module, value=False):
1016
  if isinstance(module, InternLM2Model):
1017
  module.gradient_checkpointing = value
1018
+ #if value:
1019
+ # self.vit.vision_tower.vision_model.encoder.gradient_checkpointing = value
1020
 
1021
  def get_input_embeddings(self):
1022
  return self.model.tok_embeddings
 
1064
  return img_embeds
1065
 
1066
  def img2emb(self, image):
1067
+ bs = image.shape[0]
1068
+ #img_embeds = self.vision_proj(self.vit(image.to(self.device)))
1069
+ img_embeds = torch.ones(bs,5,4096).to(torch.bfloat16).to(self.device)
1070
  atts_img = torch.ones(
1071
  img_embeds.size()[:-1], dtype=torch.long).to(img_embeds.device)
1072
 
modeling_internlm2.py~ ADDED
@@ -0,0 +1,1548 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # # Copyright (c) InternLM. All rights reserved.
2
+ #
3
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
4
+ # and OPT implementations in this library. It has been modified from its
5
+ # original forms to accommodate minor architectural differences compared
6
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
7
+ #
8
+ # Licensed under the Apache License, Version 2.0 (the "License");
9
+ # you may not use this file except in compliance with the License.
10
+ # You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing, software
15
+ # distributed under the License is distributed on an "AS IS" BASIS,
16
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ # See the License for the specific language governing permissions and
18
+ # limitations under the License.
19
+ """PyTorch InternLM2 model."""
20
+ import copy
21
+ import math
22
+ import queue
23
+ import threading
24
+ import warnings
25
+ from typing import List, Optional, Tuple, Union
26
+
27
+ import torch
28
+ import torch.utils.checkpoint
29
+ from einops import rearrange
30
+ from PIL import Image
31
+ from torch import nn
32
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
33
+ from torchvision import transforms
34
+ from torchvision.transforms.functional import InterpolationMode
35
+ from transformers.activations import ACT2FN
36
+ from transformers.modeling_outputs import (BaseModelOutputWithPast,
37
+ CausalLMOutputWithPast,
38
+ SequenceClassifierOutputWithPast)
39
+ from transformers.modeling_utils import PreTrainedModel
40
+ from transformers.utils import (add_start_docstrings,
41
+ add_start_docstrings_to_model_forward, logging,
42
+ replace_return_docstrings)
43
+
44
+ try:
45
+ from transformers.generation.streamers import BaseStreamer
46
+ except: # noqa # pylint: disable=bare-except
47
+ BaseStreamer = None
48
+
49
+ from .build_mlp import PLoRA, build_vision_projector, build_vision_tower
50
+ from .configuration_internlm import InternLMConfig as InternLM2Config
51
+
52
+ logger = logging.get_logger(__name__)
53
+
54
+ _CONFIG_FOR_DOC = 'InternLM2Config'
55
+
56
+
57
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
58
+ def _make_causal_mask(input_ids_shape: torch.Size,
59
+ dtype: torch.dtype,
60
+ device: torch.device,
61
+ past_key_values_length: int = 0):
62
+ """Make causal mask used for bi-directional self-attention."""
63
+ bsz, tgt_len = input_ids_shape
64
+ mask = torch.full((tgt_len, tgt_len),
65
+ torch.tensor(torch.finfo(dtype).min, device=device),
66
+ device=device)
67
+ mask_cond = torch.arange(mask.size(-1), device=device)
68
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
69
+ mask = mask.to(dtype)
70
+
71
+ if past_key_values_length > 0:
72
+ mask = torch.cat([
73
+ torch.zeros(
74
+ tgt_len, past_key_values_length, dtype=dtype, device=device),
75
+ mask
76
+ ],
77
+ dim=-1)
78
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len,
79
+ tgt_len + past_key_values_length)
80
+
81
+
82
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
83
+ def _expand_mask(mask: torch.Tensor,
84
+ dtype: torch.dtype,
85
+ tgt_len: Optional[int] = None):
86
+ """Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len,
87
+ src_seq_len]`."""
88
+ bsz, src_len = mask.size()
89
+ tgt_len = tgt_len if tgt_len is not None else src_len
90
+
91
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len,
92
+ src_len).to(dtype)
93
+
94
+ inverted_mask = 1.0 - expanded_mask
95
+
96
+ return inverted_mask.masked_fill(
97
+ inverted_mask.to(torch.bool),
98
+ torch.finfo(dtype).min)
99
+
100
+
101
+ class InternLM2RMSNorm(nn.Module):
102
+
103
+ def __init__(self, hidden_size, eps=1e-6):
104
+ """InternLM2RMSNorm is equivalent to T5LayerNorm."""
105
+ super().__init__()
106
+ self.weight = nn.Parameter(torch.ones(hidden_size))
107
+ self.variance_epsilon = eps
108
+
109
+ def forward(self, hidden_states):
110
+ input_dtype = hidden_states.dtype
111
+ hidden_states = hidden_states.to(torch.float32)
112
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
113
+ hidden_states = hidden_states * torch.rsqrt(variance +
114
+ self.variance_epsilon)
115
+ return self.weight * hidden_states.to(input_dtype)
116
+
117
+
118
+ class InternLM2RotaryEmbedding(nn.Module):
119
+
120
+ def __init__(self,
121
+ dim,
122
+ max_position_embeddings=2048,
123
+ base=10000,
124
+ device=None):
125
+ super().__init__()
126
+
127
+ self.dim = dim
128
+ self.max_position_embeddings = max_position_embeddings
129
+ self.base = base
130
+ inv_freq = 1.0 / (
131
+ self.base
132
+ **(torch.arange(0, self.dim, 2).float().to(device) / self.dim))
133
+ self.register_buffer('inv_freq', inv_freq, persistent=False)
134
+
135
+ # Build here to make `torch.jit.trace` work.
136
+ self._set_cos_sin_cache(
137
+ seq_len=max_position_embeddings,
138
+ device=self.inv_freq.device,
139
+ dtype=torch.get_default_dtype())
140
+
141
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
142
+ self.max_seq_len_cached = seq_len
143
+ t = torch.arange(
144
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
145
+
146
+ freqs = torch.einsum('i,j->ij', t, self.inv_freq)
147
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
148
+ emb = torch.cat((freqs, freqs), dim=-1)
149
+ self.register_buffer(
150
+ 'cos_cached', emb.cos().to(dtype), persistent=False)
151
+ self.register_buffer(
152
+ 'sin_cached', emb.sin().to(dtype), persistent=False)
153
+
154
+ def forward(self, x, seq_len=None):
155
+ # x: [bs, num_attention_heads, seq_len, head_size]
156
+ if seq_len > self.max_seq_len_cached:
157
+ self._set_cos_sin_cache(
158
+ seq_len=seq_len, device=x.device, dtype=x.dtype)
159
+
160
+ return (
161
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
162
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
163
+ )
164
+
165
+
166
+ class InternLM2LinearScalingRotaryEmbedding(InternLM2RotaryEmbedding):
167
+ """InternLM2RotaryEmbedding extended with linear scaling.
168
+
169
+ Credits to the Reddit user /u/kaiokendev
170
+ """
171
+
172
+ def __init__(self,
173
+ dim,
174
+ max_position_embeddings=2048,
175
+ base=10000,
176
+ device=None,
177
+ 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(
184
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
185
+ t = t / self.scaling_factor
186
+
187
+ freqs = torch.einsum('i,j->ij', t, self.inv_freq)
188
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
189
+ emb = torch.cat((freqs, freqs), dim=-1)
190
+ self.register_buffer(
191
+ 'cos_cached', emb.cos().to(dtype), persistent=False)
192
+ self.register_buffer(
193
+ 'sin_cached', emb.sin().to(dtype), persistent=False)
194
+
195
+
196
+ class InternLM2DynamicNTKScalingRotaryEmbedding(InternLM2RotaryEmbedding):
197
+ """InternLM2RotaryEmbedding extended with Dynamic NTK scaling.
198
+
199
+ Credits to the Reddit users /u/bloc97 and /u/emozilla.
200
+ """
201
+
202
+ def __init__(self,
203
+ dim,
204
+ max_position_embeddings=2048,
205
+ base=10000,
206
+ device=None,
207
+ scaling_factor=1.0):
208
+ self.scaling_factor = scaling_factor
209
+ super().__init__(dim, max_position_embeddings, base, device)
210
+
211
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
212
+ self.max_seq_len_cached = seq_len
213
+
214
+ if seq_len > self.max_position_embeddings:
215
+ base = self.base * ((self.scaling_factor * seq_len /
216
+ self.max_position_embeddings) -
217
+ (self.scaling_factor - 1))**(
218
+ self.dim / (self.dim - 2))
219
+ inv_freq = 1.0 / (
220
+ base
221
+ **(torch.arange(0, self.dim, 2).float().to(device) / self.dim))
222
+ self.register_buffer('inv_freq', inv_freq, persistent=False)
223
+
224
+ t = torch.arange(
225
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
226
+
227
+ freqs = torch.einsum('i,j->ij', t, self.inv_freq)
228
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
229
+ emb = torch.cat((freqs, freqs), dim=-1)
230
+ self.register_buffer(
231
+ 'cos_cached', emb.cos().to(dtype), persistent=False)
232
+ self.register_buffer(
233
+ 'sin_cached', emb.sin().to(dtype), persistent=False)
234
+
235
+
236
+ def rotate_half(x):
237
+ """Rotates half the hidden dims of the input."""
238
+ x1 = x[..., :x.shape[-1] // 2]
239
+ x2 = x[..., x.shape[-1] // 2:]
240
+ return torch.cat((-x2, x1), dim=-1)
241
+
242
+
243
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
244
+ # The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
245
+ cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
246
+ sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
247
+ cos = cos.unsqueeze(0).unsqueeze(0).expand(len(position_ids), -1, -1, -1)
248
+ sin = sin.unsqueeze(0).unsqueeze(0).expand(len(position_ids), -1, -1, -1)
249
+ if q.size(2) == 1:
250
+ q_embed = (q * cos[:, :, -1:, :]) + (
251
+ rotate_half(q) * sin[:, :, -1:, :])
252
+ else:
253
+ q_embed = (q * cos) + (rotate_half(q) * sin)
254
+
255
+ if k.size(2) == 1:
256
+ k_embed = (k * cos[:, :, -1:, :]) + (
257
+ rotate_half(k) * sin[:, :, -1:, :])
258
+ else:
259
+ k_embed = (k * cos) + (rotate_half(k) * sin)
260
+
261
+ return q_embed, k_embed
262
+
263
+
264
+ class InternLM2MLP(nn.Module):
265
+
266
+ def __init__(self, config):
267
+ super().__init__()
268
+ self.config = config
269
+ self.hidden_size = config.hidden_size
270
+ self.intermediate_size = config.intermediate_size
271
+ #self.w1 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
272
+ #self.w3 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
273
+ #self.w2 = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
274
+
275
+ self.w1 = PLoRA(
276
+ self.hidden_size,
277
+ self.intermediate_size,
278
+ bias=False,
279
+ lora_r=256,
280
+ lora_alpha=256,
281
+ lora_len=576)
282
+ self.w3 = PLoRA(
283
+ self.hidden_size,
284
+ self.intermediate_size,
285
+ bias=False,
286
+ lora_r=256,
287
+ lora_alpha=256,
288
+ lora_len=576)
289
+ self.w2 = PLoRA(
290
+ self.intermediate_size,
291
+ self.hidden_size,
292
+ bias=False,
293
+ lora_r=256,
294
+ lora_alpha=256,
295
+ lora_len=576)
296
+
297
+ self.act_fn = ACT2FN[config.hidden_act]
298
+
299
+ def forward(self, x, im_mask):
300
+ down_proj = self.w2(
301
+ self.act_fn(self.w1(x, im_mask)) * self.w3(x, im_mask), im_mask)
302
+
303
+ return down_proj
304
+
305
+
306
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
307
+ """This is the equivalent of torch.repeat_interleave(x, dim=1,
308
+ repeats=n_rep).
309
+
310
+ The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to
311
+ (batch, num_attention_heads, seqlen, head_dim)
312
+ """
313
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
314
+ if n_rep == 1:
315
+ return hidden_states
316
+ hidden_states = hidden_states[:, :,
317
+ None, :, :].expand(batch,
318
+ num_key_value_heads,
319
+ n_rep, slen, head_dim)
320
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen,
321
+ head_dim)
322
+
323
+
324
+ class InternLM2Attention(nn.Module):
325
+ """Multi-headed attention from 'Attention Is All You Need' paper."""
326
+
327
+ def __init__(self, config: InternLM2Config):
328
+ super().__init__()
329
+ self.config = config
330
+ self.hidden_size = config.hidden_size
331
+ self.num_heads = config.num_attention_heads
332
+ self.head_dim = self.hidden_size // self.num_heads
333
+ self.num_key_value_heads = config.num_key_value_heads
334
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
335
+ self.max_position_embeddings = config.max_position_embeddings
336
+ self.is_causal = True
337
+
338
+ if (self.head_dim * self.num_heads) != self.hidden_size:
339
+ raise ValueError(
340
+ f'hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}'
341
+ f' and `num_heads`: {self.num_heads}).')
342
+
343
+ #self.wqkv = nn.Linear(
344
+ self.wqkv = PLoRA(
345
+ self.hidden_size,
346
+ (self.num_heads + 2 * self.num_key_value_heads) * self.head_dim,
347
+ bias=config.bias,
348
+ lora_r=256,
349
+ lora_alpha=256,
350
+ lora_len=576)
351
+
352
+ #self.wo = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.bias)
353
+ self.wo = PLoRA(
354
+ self.num_heads * self.head_dim,
355
+ self.hidden_size,
356
+ bias=config.bias,
357
+ lora_r=256,
358
+ lora_alpha=256,
359
+ lora_len=576)
360
+ self._init_rope()
361
+
362
+ def _init_rope(self):
363
+ if self.config.rope_scaling is None:
364
+ self.rotary_emb = InternLM2RotaryEmbedding(
365
+ self.head_dim,
366
+ max_position_embeddings=self.max_position_embeddings,
367
+ base=self.config.rope_theta,
368
+ )
369
+ else:
370
+ scaling_type = self.config.rope_scaling['type']
371
+ scaling_factor = self.config.rope_scaling['factor']
372
+ if scaling_type == 'dynamic':
373
+ self.rotary_emb = InternLM2DynamicNTKScalingRotaryEmbedding(
374
+ self.head_dim,
375
+ max_position_embeddings=self.max_position_embeddings,
376
+ base=self.config.rope_theta,
377
+ scaling_factor=scaling_factor)
378
+ else:
379
+ raise ValueError(
380
+ "Currently we only support rotary embedding's type being 'dynamic'."
381
+ )
382
+ return self.rotary_emb
383
+
384
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
385
+ return tensor.view(bsz, seq_len, self.num_heads,
386
+ self.head_dim).transpose(1, 2).contiguous()
387
+
388
+ def forward(
389
+ self,
390
+ hidden_states: torch.Tensor,
391
+ attention_mask: Optional[torch.Tensor] = None,
392
+ position_ids: Optional[torch.LongTensor] = None,
393
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
394
+ output_attentions: bool = False,
395
+ use_cache: bool = False,
396
+ im_mask: Optional[Tuple[torch.Tensor]] = None,
397
+ **kwargs,
398
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor],
399
+ Optional[Tuple[torch.Tensor]]]:
400
+ if 'padding_mask' in kwargs:
401
+ warnings.warn(
402
+ 'Passing `padding_mask` is deprecated and will be removed in v4.37. '
403
+ 'Please make sure use `attention_mask` instead.`')
404
+
405
+ bsz, q_len, _ = hidden_states.size()
406
+
407
+ qkv_states = self.wqkv(hidden_states, im_mask)
408
+
409
+ qkv_states = rearrange(
410
+ qkv_states,
411
+ 'b q (h gs d) -> b q h gs d',
412
+ gs=2 + self.num_key_value_groups,
413
+ d=self.head_dim,
414
+ )
415
+
416
+ query_states = qkv_states[..., :self.num_key_value_groups, :]
417
+ query_states = rearrange(query_states, 'b q h gs d -> b q (h gs) d')
418
+ key_states = qkv_states[..., -2, :]
419
+ value_states = qkv_states[..., -1, :]
420
+
421
+ query_states = query_states.transpose(1, 2)
422
+ key_states = key_states.transpose(1, 2)
423
+ value_states = value_states.transpose(1, 2)
424
+
425
+ kv_seq_len = key_states.shape[-2]
426
+ if past_key_value is not None:
427
+ kv_seq_len += past_key_value[0].shape[-2]
428
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
429
+ query_states, key_states = apply_rotary_pos_emb(
430
+ query_states, key_states, cos, sin, position_ids)
431
+
432
+ if past_key_value is not None:
433
+ # reuse k, v, self_attention
434
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
435
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
436
+
437
+ past_key_value = (key_states, value_states) if use_cache else None
438
+
439
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
440
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
441
+
442
+ attn_weights = torch.matmul(query_states, key_states.transpose(
443
+ 2, 3)) / math.sqrt(self.head_dim)
444
+
445
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
446
+ raise ValueError(
447
+ f'Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is'
448
+ f' {attn_weights.size()}')
449
+
450
+ if attention_mask is not None:
451
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
452
+ raise ValueError(
453
+ f'Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}'
454
+ )
455
+ attn_weights = attn_weights + attention_mask
456
+
457
+ # upcast attention to fp32
458
+ attn_weights = nn.functional.softmax(
459
+ attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
460
+ attn_output = torch.matmul(attn_weights, value_states)
461
+
462
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
463
+ raise ValueError(
464
+ f'`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is'
465
+ f' {attn_output.size()}')
466
+
467
+ attn_output = attn_output.transpose(1, 2).contiguous()
468
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
469
+
470
+ attn_output = self.wo(attn_output, im_mask)
471
+
472
+ if not output_attentions:
473
+ attn_weights = None
474
+
475
+ return attn_output, attn_weights, past_key_value
476
+
477
+
478
+ class InternLM2FlashAttention2(InternLM2Attention):
479
+ """InternLM2 flash attention module.
480
+
481
+ This module inherits from `InternLM2Attention` as the weights of the module
482
+ stays untouched. The only required change would be on the forward pass
483
+ where it needs to correctly call the public API of flash attention and deal
484
+ with padding tokens in case the input contains any of them.
485
+ """
486
+
487
+ def forward(
488
+ self,
489
+ hidden_states: torch.Tensor,
490
+ attention_mask: Optional[torch.LongTensor] = None,
491
+ position_ids: Optional[torch.LongTensor] = None,
492
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
493
+ output_attentions: bool = False,
494
+ use_cache: bool = False,
495
+ im_mask: Optional[Tuple[torch.Tensor]] = None,
496
+ **kwargs,
497
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor],
498
+ Optional[Tuple[torch.Tensor]]]:
499
+ # InternLM2FlashAttention2 attention does not support output_attentions
500
+ if 'padding_mask' in kwargs:
501
+ warnings.warn(
502
+ 'Passing `padding_mask` is deprecated and will be removed in v4.37. '
503
+ 'Please make sure use `attention_mask` instead.`')
504
+
505
+ # overwrite attention_mask with padding_mask
506
+ attention_mask = kwargs.pop('padding_mask')
507
+
508
+ output_attentions = False
509
+
510
+ bsz, q_len, _ = hidden_states.size()
511
+
512
+ qkv_states = self.wqkv(hidden_states, im_mask)
513
+
514
+ qkv_states = rearrange(
515
+ qkv_states,
516
+ 'b q (h gs d) -> b q h gs d',
517
+ gs=self.num_heads + 2 * self.num_key_value_heads,
518
+ d=self.head_dim,
519
+ q=q_len,
520
+ )
521
+
522
+ query_states = qkv_states[..., :self.num_key_value_groups, :]
523
+ query_states = rearrange(query_states, 'b q h gs d -> b q (h gs) d')
524
+ key_states = qkv_states[..., -2, :]
525
+ value_states = qkv_states[..., -1, :]
526
+
527
+ kv_seq_len = key_states.shape[-2]
528
+ if past_key_value is not None:
529
+ kv_seq_len += past_key_value[0].shape[-2]
530
+
531
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
532
+
533
+ query_states, key_states = apply_rotary_pos_emb(
534
+ query_states, key_states, cos, sin, position_ids)
535
+
536
+ if past_key_value is not None:
537
+ # reuse k, v, self_attention
538
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
539
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
540
+
541
+ past_key_value = (key_states, value_states) if use_cache else None
542
+
543
+ query_states = query_states.transpose(1, 2)
544
+ key_states = key_states.transpose(1, 2)
545
+ value_states = value_states.transpose(1, 2)
546
+
547
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
548
+
549
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
550
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
551
+ # cast them back in the correct dtype just to be sure everything works as expected.
552
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
553
+ # in fp32. (InternLM2RMSNorm handles it correctly)
554
+
555
+ input_dtype = query_states.dtype
556
+ if input_dtype == torch.float32:
557
+ # Handle the case where the model is quantized
558
+ if hasattr(self.config, '_pre_quantization_dtype'):
559
+ target_dtype = self.config._pre_quantization_dtype
560
+ else:
561
+ target_dtype = self.q_proj.weight.dtype
562
+
563
+ logger.warning_once(
564
+ f'The input hidden states seems to be silently casted in float32, this might be related to'
565
+ f' the fact you have upcasted embedding or layer norm layers in float32. We will cast back '
566
+ f'the input in {target_dtype}.')
567
+
568
+ query_states = query_states.to(target_dtype)
569
+ key_states = key_states.to(target_dtype)
570
+ value_states = value_states.to(target_dtype)
571
+
572
+ attn_output = self._flash_attention_forward(
573
+ query_states,
574
+ key_states,
575
+ value_states,
576
+ attention_mask,
577
+ q_len,
578
+ dropout=dropout_rate)
579
+
580
+ attn_output = attn_output.reshape(bsz, q_len,
581
+ self.hidden_size).contiguous()
582
+ attn_output = self.wo(attn_output, im_mask)
583
+
584
+ if not output_attentions:
585
+ attn_weights = None
586
+
587
+ return attn_output, attn_weights, past_key_value
588
+
589
+
590
+ class InternLM2DecoderLayer(nn.Module):
591
+
592
+ def __init__(self, config: InternLM2Config):
593
+ super().__init__()
594
+ self.hidden_size = config.hidden_size
595
+ self.attention = (
596
+ InternLM2Attention(config=config)
597
+ if not getattr(config, '_flash_attn_2_enabled', False) else
598
+ InternLM2FlashAttention2(config=config))
599
+ self.feed_forward = InternLM2MLP(config)
600
+ self.attention_norm = InternLM2RMSNorm(
601
+ config.hidden_size, eps=config.rms_norm_eps)
602
+ self.ffn_norm = InternLM2RMSNorm(
603
+ config.hidden_size, eps=config.rms_norm_eps)
604
+
605
+ def forward(
606
+ self,
607
+ hidden_states: torch.Tensor,
608
+ attention_mask: Optional[torch.Tensor] = None,
609
+ position_ids: Optional[torch.LongTensor] = None,
610
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
611
+ output_attentions: Optional[bool] = False,
612
+ use_cache: Optional[bool] = False,
613
+ im_mask: Optional[Tuple[torch.Tensor]] = None,
614
+ **kwargs,
615
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor,
616
+ torch.FloatTensor]]]:
617
+ """
618
+ Args:
619
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
620
+ attention_mask (`torch.FloatTensor`, *optional*):
621
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
622
+ query_sequence_length, key_sequence_length)` if default attention is used.
623
+ output_attentions (`bool`, *optional*):
624
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
625
+ returned tensors for more detail.
626
+ use_cache (`bool`, *optional*):
627
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
628
+ (see `past_key_values`).
629
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
630
+ """
631
+ if 'padding_mask' in kwargs:
632
+ warnings.warn(
633
+ 'Passing `padding_mask` is deprecated and will be removed in v4.37. '
634
+ 'Please make sure use `attention_mask` instead.`')
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
+ im_mask=im_mask,
649
+ **kwargs,
650
+ )
651
+ hidden_states = residual + hidden_states
652
+
653
+ # Fully Connected
654
+ residual = hidden_states
655
+ hidden_states = self.ffn_norm(hidden_states)
656
+ hidden_states = self.feed_forward(hidden_states, im_mask)
657
+ hidden_states = residual + hidden_states
658
+
659
+ outputs = (hidden_states, )
660
+
661
+ if output_attentions:
662
+ outputs += (self_attn_weights, )
663
+
664
+ if use_cache:
665
+ outputs += (present_key_value, )
666
+
667
+ return outputs
668
+
669
+
670
+ InternLM2_START_DOCSTRING = r"""
671
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
672
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
673
+ etc.)
674
+
675
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
676
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
677
+ and behavior.
678
+
679
+ Parameters:
680
+ config ([`InternLM2Config`]):
681
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
682
+ load the weights associated with the model, only the configuration. Check out the
683
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
684
+ """
685
+
686
+
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
+ _supports_flash_attn_2 = True
698
+
699
+ def _init_weights(self, module):
700
+ std = self.config.initializer_range
701
+ if isinstance(module, nn.Linear):
702
+ module.weight.data.normal_(mean=0.0, std=std)
703
+ if module.bias is not None:
704
+ module.bias.data.zero_()
705
+ elif isinstance(module, nn.Embedding):
706
+ module.weight.data.normal_(mean=0.0, std=std)
707
+ if module.padding_idx is not None:
708
+ module.weight.data[module.padding_idx].zero_()
709
+
710
+
711
+ InternLM2_INPUTS_DOCSTRING = r"""
712
+ Args:
713
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
714
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
715
+ it.
716
+
717
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
718
+ [`PreTrainedTokenizer.__call__`] for details.
719
+
720
+ [What are input IDs?](../glossary#input-ids)
721
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
722
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
723
+
724
+ - 1 for tokens that are **not masked**,
725
+ - 0 for tokens that are **masked**.
726
+
727
+ [What are attention masks?](../glossary#attention-mask)
728
+
729
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
730
+ [`PreTrainedTokenizer.__call__`] for details.
731
+
732
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
733
+ `past_key_values`).
734
+
735
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
736
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
737
+ information on the default strategy.
738
+
739
+ - 1 indicates the head is **not masked**,
740
+ - 0 indicates the head is **masked**.
741
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
742
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
743
+ config.n_positions - 1]`.
744
+
745
+ [What are position IDs?](../glossary#position-ids)
746
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or
747
+ when `config.use_cache=True`):
748
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
749
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
750
+ `(batch_size, num_heads, decoder_sequence_length, embed_size_per_head)`.
751
+
752
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
753
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
754
+
755
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
756
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
757
+ of shape `(batch_size, sequence_length)`.
758
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
759
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
760
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
761
+ model's internal embedding lookup matrix.
762
+ use_cache (`bool`, *optional*):
763
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
764
+ `past_key_values`).
765
+ output_attentions (`bool`, *optional*):
766
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
767
+ tensors for more detail.
768
+ output_hidden_states (`bool`, *optional*):
769
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
770
+ more detail.
771
+ return_dict (`bool`, *optional*):
772
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
773
+ """
774
+
775
+
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
+ """Transformer decoder consisting of *config.num_hidden_layers* layers.
782
+ 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
+
795
+ self.tok_embeddings = nn.Embedding(config.vocab_size,
796
+ config.hidden_size,
797
+ self.padding_idx)
798
+ self.layers = nn.ModuleList([
799
+ InternLM2DecoderLayer(config)
800
+ for _ in range(config.num_hidden_layers)
801
+ ])
802
+ self.norm = InternLM2RMSNorm(
803
+ config.hidden_size, eps=config.rms_norm_eps)
804
+
805
+ self.gradient_checkpointing = False
806
+ # Initialize weights and apply final processing
807
+ self.post_init()
808
+
809
+ def get_input_embeddings(self):
810
+ return self.tok_embeddings
811
+
812
+ def set_input_embeddings(self, value):
813
+ self.tok_embeddings = value
814
+
815
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
816
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape,
817
+ inputs_embeds, past_key_values_length):
818
+ # create causal mask
819
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
820
+ combined_attention_mask = None
821
+ if input_shape[-1] > 1:
822
+ combined_attention_mask = _make_causal_mask(
823
+ input_shape,
824
+ inputs_embeds.dtype,
825
+ device=inputs_embeds.device,
826
+ past_key_values_length=past_key_values_length,
827
+ )
828
+
829
+ if attention_mask is not None:
830
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
831
+ expanded_attn_mask = _expand_mask(
832
+ attention_mask, inputs_embeds.dtype,
833
+ tgt_len=input_shape[-1]).to(inputs_embeds.device)
834
+ combined_attention_mask = (
835
+ expanded_attn_mask if combined_attention_mask is None else
836
+ expanded_attn_mask + combined_attention_mask)
837
+
838
+ return combined_attention_mask
839
+
840
+ @add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
841
+ def forward(self,
842
+ input_ids: torch.LongTensor = None,
843
+ attention_mask: Optional[torch.Tensor] = None,
844
+ position_ids: Optional[torch.LongTensor] = None,
845
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
846
+ inputs_embeds: Optional[torch.FloatTensor] = None,
847
+ use_cache: Optional[bool] = None,
848
+ output_attentions: Optional[bool] = None,
849
+ output_hidden_states: Optional[bool] = None,
850
+ return_dict: Optional[bool] = None,
851
+ **kwargs) -> Union[Tuple, BaseModelOutputWithPast]:
852
+
853
+ im_mask = kwargs.get('im_mask', None)
854
+
855
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
856
+ output_hidden_states = (
857
+ output_hidden_states if output_hidden_states is not None else
858
+ self.config.output_hidden_states)
859
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
860
+
861
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
862
+
863
+ # retrieve input_ids and inputs_embeds
864
+ if input_ids is not None and inputs_embeds is not None:
865
+ raise ValueError(
866
+ 'You cannot specify both input_ids and inputs_embeds at the same time'
867
+ )
868
+ elif input_ids is not None:
869
+ batch_size, seq_length = input_ids.shape[:2]
870
+ elif inputs_embeds is not None:
871
+ batch_size, seq_length = inputs_embeds.shape[:2]
872
+ else:
873
+ raise ValueError(
874
+ 'You have to specify either input_ids or inputs_embeds')
875
+
876
+ seq_length_with_past = seq_length
877
+ past_key_values_length = 0
878
+ if past_key_values is not None:
879
+ past_key_values_length = past_key_values[0][0].shape[2]
880
+ seq_length_with_past = seq_length_with_past + past_key_values_length
881
+
882
+ if position_ids is None:
883
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
884
+ position_ids = torch.arange(
885
+ past_key_values_length,
886
+ seq_length + past_key_values_length,
887
+ dtype=torch.long,
888
+ device=device)
889
+ position_ids = position_ids.unsqueeze(0)
890
+
891
+ if inputs_embeds is None:
892
+ inputs_embeds = self.tok_embeddings(input_ids)
893
+ im_mask = torch.zeros(inputs_embeds.shape[:2]).to(
894
+ inputs_embeds.device).bool()
895
+ # embed positions
896
+ if attention_mask is None:
897
+ attention_mask = torch.ones((batch_size, seq_length_with_past),
898
+ dtype=torch.bool,
899
+ device=inputs_embeds.device)
900
+ attention_mask = self._prepare_decoder_attention_mask(
901
+ attention_mask, (batch_size, seq_length), inputs_embeds,
902
+ past_key_values_length)
903
+
904
+ # embed positions
905
+ hidden_states = inputs_embeds
906
+
907
+ if self.gradient_checkpointing and self.training:
908
+ if use_cache:
909
+ logger.warning_once(
910
+ '`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...'
911
+ )
912
+ use_cache = False
913
+
914
+ # decoder layers
915
+ all_hidden_states = () if output_hidden_states else None
916
+ all_self_attns = () if output_attentions else None
917
+ next_decoder_cache = () if use_cache else None
918
+
919
+ for idx, decoder_layer in enumerate(self.layers):
920
+ if output_hidden_states:
921
+ all_hidden_states += (hidden_states, )
922
+
923
+ past_key_value = past_key_values[
924
+ idx] if past_key_values is not None else None
925
+
926
+ if self.gradient_checkpointing and self.training:
927
+
928
+ def create_custom_forward(module):
929
+
930
+ def custom_forward(*inputs):
931
+ # None for past_key_value
932
+ return module(*inputs, output_attentions, None,
933
+ im_mask)
934
+
935
+ return custom_forward
936
+
937
+ layer_outputs = torch.utils.checkpoint.checkpoint(
938
+ create_custom_forward(decoder_layer),
939
+ hidden_states,
940
+ attention_mask,
941
+ position_ids,
942
+ None,
943
+ )
944
+ else:
945
+ layer_outputs = decoder_layer(
946
+ hidden_states,
947
+ attention_mask=attention_mask,
948
+ position_ids=position_ids,
949
+ past_key_value=past_key_value,
950
+ output_attentions=output_attentions,
951
+ use_cache=use_cache,
952
+ im_mask=im_mask,
953
+ )
954
+
955
+ hidden_states = layer_outputs[0]
956
+
957
+ if use_cache:
958
+ next_decoder_cache += (
959
+ layer_outputs[2 if output_attentions else 1], )
960
+
961
+ if output_attentions:
962
+ all_self_attns += (layer_outputs[1], )
963
+
964
+ hidden_states = self.norm(hidden_states)
965
+
966
+ # add hidden states from the last decoder layer
967
+ if output_hidden_states:
968
+ all_hidden_states += (hidden_states, )
969
+
970
+ next_cache = next_decoder_cache if use_cache else None
971
+ if not return_dict:
972
+ return tuple(
973
+ v for v in
974
+ [hidden_states, next_cache, all_hidden_states, all_self_attns]
975
+ if v is not None)
976
+ return BaseModelOutputWithPast(
977
+ last_hidden_state=hidden_states,
978
+ past_key_values=next_cache,
979
+ hidden_states=all_hidden_states,
980
+ attentions=all_self_attns,
981
+ )
982
+
983
+
984
+ class InternLM2ForCausalLM(InternLM2PreTrainedModel):
985
+ _auto_class = 'AutoModelForCausalLM'
986
+
987
+ _tied_weights_keys = ['output.weight']
988
+
989
+ def __init__(self, config):
990
+ super().__init__(config)
991
+ self.model = InternLM2Model(config)
992
+ self.vocab_size = config.vocab_size
993
+ self.output = nn.Linear(
994
+ config.hidden_size, config.vocab_size, bias=False)
995
+ self.debug_flag = 1
996
+ self.tokenizer = None
997
+
998
+ self.max_length = config.max_length
999
+ print(f'Set max length to {self.max_length}')
1000
+ self.debug_flag = 1
1001
+ # Initialize weights and apply final processing
1002
+ self.post_init()
1003
+
1004
+ self.vit = build_vision_tower(config._name_or_path)
1005
+ self.vision_proj = build_vision_projector()
1006
+
1007
+ self.vis_processor = transforms.Compose([
1008
+ transforms.Resize((336, 336),
1009
+ interpolation=InterpolationMode.BICUBIC),
1010
+ transforms.ToTensor(),
1011
+ transforms.Normalize((0.48145466, 0.4578275, 0.40821073),
1012
+ (0.26862954, 0.26130258, 0.27577711)),
1013
+ ])
1014
+
1015
+ def _set_gradient_checkpointing(self, module, value=False):
1016
+ if isinstance(module, InternLM2Model):
1017
+ module.gradient_checkpointing = value
1018
+ #if value:
1019
+ # self.vit.vision_tower.vision_model.encoder.gradient_checkpointing = value
1020
+
1021
+ def get_input_embeddings(self):
1022
+ return self.model.tok_embeddings
1023
+
1024
+ def set_input_embeddings(self, value):
1025
+ self.model.tok_embeddings = value
1026
+
1027
+ def get_output_embeddings(self):
1028
+ return self.output
1029
+
1030
+ def set_output_embeddings(self, new_embeddings):
1031
+ self.output = new_embeddings
1032
+
1033
+ def set_decoder(self, decoder):
1034
+ self.model = decoder
1035
+
1036
+ def get_decoder(self):
1037
+ return self.model
1038
+
1039
+ def encode_text(self, t, add_special_tokens=False):
1040
+ t = t.replace('<|User|>:', '[UNUSED_TOKEN_146]user\n')
1041
+ t = t.replace('<|Bot|>:', '[UNUSED_TOKEN_146]assistant\n')
1042
+ t = t.replace('<TOKENS_UNUSED_0>', '[UNUSED_TOKEN_145]')
1043
+ t = t.replace('<TOKENS_UNUSED_1>', '[UNUSED_TOKEN_145]')
1044
+ t = t.replace('[UNUSED_TOKEN_0]', '[UNUSED_TOKEN_145]')
1045
+ t = t.replace('[UNUSED_TOKEN_1]', '[UNUSED_TOKEN_145]')
1046
+
1047
+ text = t
1048
+ token = self.tokenizer(
1049
+ text, return_tensors='pt',
1050
+ add_special_tokens=add_special_tokens).input_ids.to(self.device)
1051
+ embs = self.model.tok_embeddings(token)
1052
+ return embs
1053
+
1054
+ def encode_img(self, image):
1055
+ if image is None:
1056
+ return None
1057
+ if isinstance(image, str):
1058
+ image = Image.open(image).convert('RGB')
1059
+ image = self.vis_processor(image).unsqueeze(0).to(self.device)
1060
+ else:
1061
+ assert isinstance(image, torch.Tensor)
1062
+
1063
+ img_embeds, atts_img, img_target = self.img2emb(image)
1064
+ return img_embeds
1065
+
1066
+ def img2emb(self, image):
1067
+ bs = image.shape[0]
1068
+ #img_embeds = self.vision_proj(self.vit(image.to(self.device)))
1069
+ img_embeds =
1070
+ atts_img = torch.ones(
1071
+ img_embeds.size()[:-1], dtype=torch.long).to(img_embeds.device)
1072
+
1073
+ img_target = torch.ones(
1074
+ img_embeds.size()[:2], dtype=torch.long).to(
1075
+ img_embeds.device) * -100
1076
+
1077
+ return img_embeds, atts_img, img_target
1078
+
1079
+ def prompt_wrap(self, img_embeds, prompt):
1080
+ batch_size = img_embeds.shape[0]
1081
+ p_before, p_after = prompt.split('<ImageHere>')
1082
+ p_before_tokens = self.tokenizer(
1083
+ p_before, return_tensors='pt',
1084
+ add_special_tokens=True).to(img_embeds.device)
1085
+
1086
+ p_before_embeds = self.model.tok_embeddings(
1087
+ p_before_tokens.input_ids).expand(batch_size, -1, -1)
1088
+ wrapped_img_embeds = torch.cat([p_before_embeds, img_embeds], dim=1)
1089
+
1090
+ wrapped_atts_img = torch.ones(
1091
+ wrapped_img_embeds.size()[:-1],
1092
+ dtype=torch.long).to(img_embeds.device)
1093
+
1094
+ wrapped_target = torch.ones(
1095
+ batch_size, wrapped_img_embeds.shape[1], dtype=torch.long).to(
1096
+ img_embeds.device) * -100
1097
+
1098
+ return wrapped_img_embeds, wrapped_atts_img, wrapped_target
1099
+
1100
+ def text2emb(self, text, add_special=False):
1101
+ if type(text) == str:
1102
+ new_text = []
1103
+ for t in text:
1104
+ t = t.replace('<|User|>:', '[UNUSED_TOKEN_146]user\n')
1105
+ t = t.replace('<|Bot|>:', '[UNUSED_TOKEN_146]assistant\n')
1106
+ t = t.replace('<TOKENS_UNUSED_0>', '[UNUSED_TOKEN_145]')
1107
+ t = t.replace('<TOKENS_UNUSED_1>', '[UNUSED_TOKEN_145]')
1108
+ new_text.append(t)
1109
+ text = new_text
1110
+ elif type(text) == list:
1111
+ new_text = []
1112
+ text_list = text
1113
+ for text in text_list:
1114
+ for t in text:
1115
+ t = t.replace('<|User|>:', '[UNUSED_TOKEN_146]user\n')
1116
+ t = t.replace('<|Bot|>:', '[UNUSED_TOKEN_146]assistant\n')
1117
+ t = t.replace('<TOKENS_UNUSED_0>', '[UNUSED_TOKEN_145]')
1118
+ t = t.replace('<TOKENS_UNUSED_1>', '[UNUSED_TOKEN_145]')
1119
+ new_text.append(t)
1120
+ text = new_text
1121
+ to_regress_tokens = self.tokenizer(
1122
+ text,
1123
+ return_tensors='pt',
1124
+ padding='longest',
1125
+ truncation=True,
1126
+ max_length=self.max_length,
1127
+ add_special_tokens=add_special).to(self.device)
1128
+
1129
+ targets = self.mask_human_targets(to_regress_tokens.input_ids)
1130
+ targets = targets.to(self.device)
1131
+
1132
+ return to_regress_tokens, targets
1133
+
1134
+ def interleav_wrap(self, img_list, text_list):
1135
+ wrap_embeds_list, wrap_atts_list = [], []
1136
+ wrap_target_list, wrap_im_mask_list = [], []
1137
+
1138
+ for image, text in zip(img_list, text_list):
1139
+ img_embeds, atts_img, img_target = self.img2emb(image)
1140
+ text = text[0]
1141
+ parts = text.split('<ImageHere>')
1142
+ wrap_tokens, wrap_embeds, wrap_atts, wrap_im_mask = [], [], [], []
1143
+ temp_len = 0
1144
+ image_nums, im_len = img_embeds.shape[:2]
1145
+ need_bos = True
1146
+ for idx, part in enumerate(parts):
1147
+ if len(part) > 0:
1148
+ part_tokens = self.tokenizer(
1149
+ part,
1150
+ return_tensors='pt',
1151
+ padding='longest',
1152
+ add_special_tokens=need_bos).to(self.device)
1153
+ if need_bos:
1154
+ need_bos = False
1155
+ wrap_tokens.append(part_tokens.input_ids)
1156
+ part_embeds = self.model.tok_embeddings(
1157
+ part_tokens.input_ids)
1158
+ wrap_embeds.append(part_embeds)
1159
+ wrap_atts.append(part_tokens.attention_mask)
1160
+ wrap_im_mask.append(
1161
+ torch.zeros(part_embeds.shape[:2]).to(self.device))
1162
+
1163
+ temp_len += part_embeds.shape[1]
1164
+ if idx < image_nums:
1165
+ wrap_tokens.append(img_target[idx].unsqueeze(0))
1166
+ wrap_embeds.append(img_embeds[idx].unsqueeze(0))
1167
+ wrap_atts.append(atts_img[idx].unsqueeze(0))
1168
+ wrap_im_mask.append(
1169
+ torch.ones_like(atts_img[idx].unsqueeze(0)))
1170
+
1171
+ temp_len += im_len
1172
+ if temp_len > self.max_length:
1173
+ break
1174
+
1175
+ wrap_tokens = torch.cat(wrap_tokens, dim=1)
1176
+ wrap_embeds = torch.cat(wrap_embeds, dim=1)
1177
+ wrap_atts = torch.cat(wrap_atts, dim=1)
1178
+ wrap_im_mask = torch.cat(wrap_im_mask, dim=1)
1179
+
1180
+ wrap_target = self.mask_human_targets(wrap_tokens).to(self.device)
1181
+
1182
+ wrap_embeds = wrap_embeds[:, :self.max_length].to(self.device)
1183
+ wrap_atts = wrap_atts[:, :self.max_length].to(self.device)
1184
+ wrap_target = wrap_target[:, :self.max_length].to(self.device)
1185
+ wrap_im_mask = wrap_im_mask[:, :self.max_length].to(self.device)
1186
+
1187
+ wrap_embeds_list.append(wrap_embeds)
1188
+ wrap_atts_list.append(wrap_atts)
1189
+ wrap_target_list.append(wrap_target)
1190
+ wrap_im_mask_list.append(wrap_im_mask)
1191
+
1192
+ wrap_embeds = torch.cat(wrap_embeds_list)
1193
+ wrap_atts = torch.cat(wrap_atts_list)
1194
+ wrap_target = torch.cat(wrap_target_list)
1195
+ wrap_im_mask = torch.cat(wrap_im_mask_list)
1196
+ return wrap_embeds, wrap_atts, wrap_target, wrap_im_mask
1197
+
1198
+ def mask_human_targets(self, input_ids, pure=False):
1199
+ target_batch = []
1200
+ for bs in range(input_ids.shape[0]):
1201
+ cur_idx = 0
1202
+ ids = input_ids[bs]
1203
+ targets = copy.deepcopy(ids)
1204
+ end_count = 0
1205
+ last_eoa = 0
1206
+ for i, temp_id in enumerate(ids):
1207
+ if temp_id == 92542:
1208
+ if end_count % 2 == 0:
1209
+ targets[last_eoa:i + 6] = -100
1210
+ else:
1211
+ last_eoa = i + 1
1212
+ end_count += 1
1213
+ elif temp_id == 2: ### eos and following pad
1214
+ targets[i + 1:] = -100 #### loss on eos, but not on pad
1215
+ break
1216
+ if temp_id != 2 and end_count % 2 == 0: ### trunction, end at last question
1217
+ targets[last_eoa +
1218
+ 1:] = -100 #### mask all after the last answer
1219
+
1220
+ target_batch.append(targets.unsqueeze(0))
1221
+ if self.debug_flag:
1222
+ print('#### Warning! System meta is not support now')
1223
+ targets_vis = targets.clone()
1224
+ targets_vis[targets_vis == -100] = 92399
1225
+ targets_vis_tokens = ''.join(
1226
+ self.tokenizer.convert_ids_to_tokens(targets_vis)).replace(
1227
+ '[UNUSED_TOKEN_2]', ' ')
1228
+ # print(''.join(self.tokenizer.convert_ids_to_tokens(ids)))
1229
+ print('-----------')
1230
+ print([targets_vis_tokens])
1231
+ print('-----------------------------')
1232
+
1233
+ target_batch = torch.cat(target_batch, dim=0)
1234
+ return target_batch
1235
+
1236
+ @add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
1237
+ @replace_return_docstrings(
1238
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1239
+ def forward(self,
1240
+ input_ids: torch.LongTensor = None,
1241
+ attention_mask: Optional[torch.Tensor] = None,
1242
+ position_ids: Optional[torch.LongTensor] = None,
1243
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1244
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1245
+ labels: Optional[torch.LongTensor] = None,
1246
+ use_cache: Optional[bool] = None,
1247
+ output_attentions: Optional[bool] = None,
1248
+ output_hidden_states: Optional[bool] = None,
1249
+ return_dict: Optional[bool] = None,
1250
+ **kwargs) -> Union[Tuple, CausalLMOutputWithPast]:
1251
+ r"""
1252
+ Args:
1253
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1254
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1255
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1256
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1257
+
1258
+ Returns:
1259
+
1260
+ Example:
1261
+
1262
+ ```python
1263
+ >>> from transformers import AutoTokenizer, InternLM2ForCausalLM
1264
+
1265
+ >>> model = InternLM2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1266
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1267
+
1268
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1269
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1270
+
1271
+ >>> # Generate
1272
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1273
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1274
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1275
+ ```"""
1276
+ samples = kwargs.get('samples', None)
1277
+ if samples:
1278
+ if self.debug_flag:
1279
+ self.debug_flag += 1
1280
+ if self.debug_flag > 5:
1281
+ self.debug_flag = 0
1282
+
1283
+ if samples['data_type'][0] == 'text':
1284
+ has_img = False
1285
+ elif samples['data_type'][0] == 'multi':
1286
+ has_img = True
1287
+ else:
1288
+ raise NotImplementedError
1289
+
1290
+ ### encode text
1291
+ text = samples['text_input']
1292
+ if has_img:
1293
+ image = samples['image']
1294
+ to_regress_embeds, attention_mask, targets, im_mask = self.interleav_wrap(
1295
+ image, text)
1296
+ else:
1297
+ to_regress_tokens, targets = self.text2emb(
1298
+ text, add_special=True)
1299
+ to_regress_embeds = self.model.tok_embeddings(
1300
+ to_regress_tokens.input_ids)
1301
+ attention_mask = to_regress_tokens.attention_mask
1302
+ im_mask = torch.zeros(to_regress_embeds.shape[:2]).cuda()
1303
+
1304
+ inputs_embeds = to_regress_embeds[:, :self.max_length]
1305
+ attention_mask = attention_mask[:, :self.max_length]
1306
+ targets = targets[:, :self.max_length]
1307
+ im_mask = im_mask[:, :self.max_length].bool()
1308
+ labels = targets
1309
+ if self.debug_flag:
1310
+ print(targets.shape, inputs_embeds.shape, attention_mask.shape)
1311
+ le = len(samples['text_input'])
1312
+ data_type = samples['data_type'][0]
1313
+ print(
1314
+ f'DataType: {data_type}. Has Image: {has_img}. Current max length: {self.max_length}, BatchSize is {le}'
1315
+ )
1316
+ # if has_img:
1317
+ # print(img_embeds.shape)
1318
+
1319
+ else:
1320
+ self.debug_flag = 0
1321
+ im_mask = kwargs.get('im_mask', None)
1322
+
1323
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1324
+ output_hidden_states = (
1325
+ output_hidden_states if output_hidden_states is not None else
1326
+ self.config.output_hidden_states)
1327
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1328
+
1329
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1330
+ outputs = self.model(
1331
+ input_ids=input_ids,
1332
+ attention_mask=attention_mask,
1333
+ position_ids=position_ids,
1334
+ past_key_values=past_key_values,
1335
+ inputs_embeds=inputs_embeds,
1336
+ use_cache=use_cache,
1337
+ output_attentions=output_attentions,
1338
+ output_hidden_states=output_hidden_states,
1339
+ return_dict=return_dict,
1340
+ im_mask=im_mask,
1341
+ )
1342
+
1343
+ hidden_states = outputs[0]
1344
+ logits = self.output(hidden_states)
1345
+ logits = logits.float()
1346
+
1347
+ loss = None
1348
+ if labels is not None:
1349
+ # Shift so that tokens < n predict n
1350
+ shift_logits = logits[..., :-1, :].contiguous()
1351
+ shift_labels = labels[..., 1:].contiguous()
1352
+ # Flatten the tokens
1353
+ loss_fct = CrossEntropyLoss()
1354
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1355
+ shift_labels = shift_labels.view(-1)
1356
+ # Enable model parallelism
1357
+ shift_labels = shift_labels.to(shift_logits.device)
1358
+ loss = loss_fct(shift_logits, shift_labels)
1359
+
1360
+ if not return_dict:
1361
+ output = (logits, ) + outputs[1:]
1362
+ return (loss, ) + output if loss is not None else output
1363
+
1364
+ return CausalLMOutputWithPast(
1365
+ loss=loss,
1366
+ logits=logits,
1367
+ past_key_values=outputs.past_key_values,
1368
+ hidden_states=outputs.hidden_states,
1369
+ attentions=outputs.attentions,
1370
+ )
1371
+
1372
+ def prepare_inputs_for_generation(self,
1373
+ input_ids,
1374
+ past_key_values=None,
1375
+ attention_mask=None,
1376
+ inputs_embeds=None,
1377
+ im_mask=None,
1378
+ **kwargs):
1379
+ if past_key_values is not None:
1380
+ past_length = past_key_values[0][0].shape[2]
1381
+
1382
+ # Some generation methods already pass only the last input ID
1383
+ if input_ids.shape[1] > past_length:
1384
+ remove_prefix_length = past_length
1385
+ else:
1386
+ # Default to old behavior: keep only final ID
1387
+ remove_prefix_length = input_ids.shape[1] - 1
1388
+
1389
+ input_ids = input_ids[:, remove_prefix_length:]
1390
+
1391
+ position_ids = kwargs.get('position_ids', None)
1392
+ if attention_mask is not None and position_ids is None:
1393
+ # create position_ids on the fly for batch generation
1394
+ position_ids = attention_mask.long().cumsum(-1) - 1
1395
+ position_ids.masked_fill_(attention_mask == 0, 1)
1396
+ if past_key_values:
1397
+ position_ids = position_ids[:, -input_ids.shape[1]:]
1398
+
1399
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1400
+ if inputs_embeds is not None and past_key_values is None:
1401
+ model_inputs = {'inputs_embeds': inputs_embeds}
1402
+ else:
1403
+ model_inputs = {'input_ids': input_ids}
1404
+
1405
+ im_mask = im_mask
1406
+
1407
+ model_inputs.update({
1408
+ 'position_ids': position_ids,
1409
+ 'past_key_values': past_key_values,
1410
+ 'use_cache': kwargs.get('use_cache'),
1411
+ 'attention_mask': attention_mask,
1412
+ 'im_mask': im_mask,
1413
+ })
1414
+ return model_inputs
1415
+
1416
+ @staticmethod
1417
+ def _reorder_cache(past_key_values, beam_idx):
1418
+ reordered_past = ()
1419
+ for layer_past in past_key_values:
1420
+ reordered_past += (tuple(
1421
+ past_state.index_select(0, beam_idx.to(past_state.device))
1422
+ for past_state in layer_past), )
1423
+ return reordered_past
1424
+
1425
+ def build_inputs(self,
1426
+ tokenizer,
1427
+ query: str,
1428
+ history: List[Tuple[str, str]] = []):
1429
+ prompt = ''
1430
+ for record in history:
1431
+ prompt += f"""<|User|>:{record[0]}\n<|Bot|>:{record[1]}[UNUSED_TOKEN_0]\n"""
1432
+ prompt += f"""<|User|>:{query}\n<|Bot|>:"""
1433
+ return tokenizer([prompt], return_tensors='pt')
1434
+
1435
+ @torch.no_grad()
1436
+ def chat(
1437
+ self,
1438
+ tokenizer,
1439
+ query: str,
1440
+ history: List[Tuple[str, str]] = [],
1441
+ streamer: Optional[BaseStreamer] = None,
1442
+ max_new_tokens: int = 1024,
1443
+ do_sample: bool = True,
1444
+ temperature: float = 0.8,
1445
+ top_p: float = 0.8,
1446
+ **kwargs,
1447
+ ):
1448
+ inputs = self.build_inputs(tokenizer, query, history)
1449
+ inputs = {
1450
+ k: v.to(self.device)
1451
+ for k, v in inputs.items() if torch.is_tensor(v)
1452
+ }
1453
+ outputs = self.generate(
1454
+ **inputs,
1455
+ streamer=streamer,
1456
+ max_new_tokens=max_new_tokens,
1457
+ do_sample=do_sample,
1458
+ temperature=temperature,
1459
+ top_p=top_p,
1460
+ **kwargs,
1461
+ )
1462
+ outputs = outputs[0].cpu().tolist()[len(inputs['input_ids'][0]):]
1463
+ response = tokenizer.decode(outputs, skip_special_tokens=True)
1464
+ response = response.split('[UNUSED_TOKEN_0]')[0]
1465
+ history = history + [(query, response)]
1466
+ return response, history
1467
+
1468
+ @torch.no_grad()
1469
+ def stream_chat(
1470
+ self,
1471
+ tokenizer,
1472
+ query: str,
1473
+ history: List[Tuple[str, str]] = [],
1474
+ max_new_tokens: int = 1024,
1475
+ do_sample: bool = True,
1476
+ temperature: float = 0.8,
1477
+ top_p: float = 0.8,
1478
+ **kwargs,
1479
+ ):
1480
+ """Return a generator in format: (response, history) Eg.
1481
+
1482
+ ('你好,有什么可以帮助您的吗', [('你好', '你好,有什么可以帮助您的吗')]) ('你好,有什么可以帮助您的吗?', [('你好',
1483
+ '你好,有什么可以帮助您的吗?')])
1484
+ """
1485
+ if BaseStreamer is None:
1486
+ raise ModuleNotFoundError(
1487
+ 'The version of `transformers` is too low. Please make sure '
1488
+ 'that you have installed `transformers>=4.28.0`.')
1489
+
1490
+ response_queue = queue.Queue(maxsize=20)
1491
+
1492
+ class ChatStreamer(BaseStreamer):
1493
+
1494
+ def __init__(self, tokenizer) -> None:
1495
+ super().__init__()
1496
+ self.tokenizer = tokenizer
1497
+ self.queue = response_queue
1498
+ self.query = query
1499
+ self.history = history
1500
+ self.response = ''
1501
+ self.received_inputs = False
1502
+ self.queue.put(
1503
+ (self.response, history + [(self.query, self.response)]))
1504
+
1505
+ def put(self, value):
1506
+ if len(value.shape) > 1 and value.shape[0] > 1:
1507
+ raise ValueError('ChatStreamer only supports batch size 1')
1508
+ elif len(value.shape) > 1:
1509
+ value = value[0]
1510
+
1511
+ if not self.received_inputs:
1512
+ # The first received value is input_ids, ignore here
1513
+ self.received_inputs = True
1514
+ return
1515
+
1516
+ token = self.tokenizer.decode([value[-1]],
1517
+ skip_special_tokens=True)
1518
+ if token.strip() != '[UNUSED_TOKEN_0]':
1519
+ self.response = self.response + token
1520
+ history = self.history + [(self.query, self.response)]
1521
+ self.queue.put((self.response, history))
1522
+
1523
+ def end(self):
1524
+ self.queue.put(None)
1525
+
1526
+ def stream_producer():
1527
+ return self.chat(
1528
+ tokenizer=tokenizer,
1529
+ query=query,
1530
+ streamer=ChatStreamer(tokenizer=tokenizer),
1531
+ history=history,
1532
+ max_new_tokens=max_new_tokens,
1533
+ do_sample=do_sample,
1534
+ temperature=temperature,
1535
+ top_p=top_p,
1536
+ **kwargs,
1537
+ )
1538
+
1539
+ def consumer():
1540
+ producer = threading.Thread(target=stream_producer)
1541
+ producer.start()
1542
+ while True:
1543
+ res = response_queue.get()
1544
+ if res is None:
1545
+ return
1546
+ yield res
1547
+
1548
+ return consumer()