adwardlee commited on
Commit
11b9c8d
·
verified ·
1 Parent(s): 33a11e7

Upload folder using huggingface_hub

Browse files
Files changed (27) hide show
  1. model/Internlm.py +102 -0
  2. model/__init__.py +7 -0
  3. model/__pycache__/Internlm.cpython-311.pyc +0 -0
  4. model/__pycache__/__init__.cpython-311.pyc +0 -0
  5. model/__pycache__/base.cpython-311.pyc +0 -0
  6. model/base.py +89 -0
  7. model/internlm_xcomposer/__pycache__/build_mlp.cpython-310.pyc +0 -0
  8. model/internlm_xcomposer/__pycache__/build_mlp.cpython-311.pyc +0 -0
  9. model/internlm_xcomposer/__pycache__/build_mlp.cpython-39.pyc +0 -0
  10. model/internlm_xcomposer/__pycache__/configuration_internlm_xcomposer2.cpython-310.pyc +0 -0
  11. model/internlm_xcomposer/__pycache__/configuration_internlm_xcomposer2.cpython-311.pyc +0 -0
  12. model/internlm_xcomposer/__pycache__/configuration_internlm_xcomposer2.cpython-39.pyc +0 -0
  13. model/internlm_xcomposer/__pycache__/modeling_internlm2.cpython-310.pyc +0 -0
  14. model/internlm_xcomposer/__pycache__/modeling_internlm2.cpython-311.pyc +0 -0
  15. model/internlm_xcomposer/__pycache__/modeling_internlm2.cpython-39.pyc +0 -0
  16. model/internlm_xcomposer/__pycache__/modeling_internlm_xcomposer2.cpython-310.pyc +0 -0
  17. model/internlm_xcomposer/__pycache__/modeling_internlm_xcomposer2.cpython-311.pyc +0 -0
  18. model/internlm_xcomposer/__pycache__/modeling_internlm_xcomposer2.cpython-39.pyc +0 -0
  19. model/internlm_xcomposer/__pycache__/tokenization_internlm_xcomposer2.cpython-310.pyc +0 -0
  20. model/internlm_xcomposer/__pycache__/tokenization_internlm_xcomposer2.cpython-311.pyc +0 -0
  21. model/internlm_xcomposer/__pycache__/tokenization_internlm_xcomposer2.cpython-39.pyc +0 -0
  22. model/internlm_xcomposer/build_mlp.py +217 -0
  23. model/internlm_xcomposer/configuration_internlm_xcomposer2.py +159 -0
  24. model/internlm_xcomposer/modeling_internlm2.py +1131 -0
  25. model/internlm_xcomposer/modeling_internlm_xcomposer2.py +759 -0
  26. model/internlm_xcomposer/tokenization_internlm_xcomposer2.py +252 -0
  27. model/internlm_xcomposer/zero_to_fp32.py +587 -0
model/Internlm.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from model.internlm_xcomposer.configuration_internlm_xcomposer2 import InternLMXcomposer2Config
3
+ from model.internlm_xcomposer.modeling_internlm_xcomposer2 import InternLMXComposer2ForCausalLM
4
+ from model.internlm_xcomposer.tokenization_internlm_xcomposer2 import InternLMXComposer2Tokenizer
5
+ from peft import LoraConfig, get_peft_model
6
+
7
+ from .base import BaseModel
8
+
9
+ class InternLM(BaseModel):
10
+ def __init__(self, **kwargs):
11
+ super().__init__(**kwargs)
12
+
13
+ def load_model_tokenizer(self):
14
+ config = InternLMXcomposer2Config.from_pretrained(self.model_path)
15
+ config.use_cache = False
16
+ config.max_length = self.training_args.max_length
17
+
18
+ model = InternLMXComposer2ForCausalLM.from_pretrained(
19
+ self.model_path,
20
+ config=config,
21
+ device_map=None,
22
+ use_caption=self.use_caption
23
+ )
24
+
25
+ if self.data_args.img_size != 336:
26
+ model.vit.resize_pos()
27
+
28
+ tokenizer_path = self.model_path if self.lora_args.lora_weight_path == '' \
29
+ else self.lora_args.lora_weight_path
30
+ tokenizer = InternLMXComposer2Tokenizer.from_pretrained(
31
+ tokenizer_path,
32
+ padding_side='right',
33
+ use_fast=False,
34
+ )
35
+
36
+ self.model = model
37
+ self.tokenizer = tokenizer
38
+
39
+ def configure_training_args(self):
40
+ training_args = self.training_args
41
+ if training_args.fix_vit:
42
+ self.model.vit.requires_grad_(False)
43
+ else:
44
+ self.model.vit.requires_grad_(True)
45
+ self.model.vit.vision_tower.vision_model.post_layernorm = torch.nn.Identity()
46
+
47
+ if training_args.fix_sampler or self.use_caption:
48
+ self.model.vision_proj.requires_grad_(False)
49
+ else:
50
+ self.model.vision_proj.requires_grad_(True)
51
+
52
+ def configure_peft(self):
53
+ if not self.training_args.use_lora:
54
+ for name, param in self.model.model.named_parameters():
55
+ if 'vision_cross' not in name:
56
+ param.requires_grad = False
57
+ return
58
+
59
+ lora_args = self.lora_args
60
+ if lora_args.lora_type == 'lora':
61
+ for name, param in self.model.model.named_parameters():
62
+ if 'vision_cross' in name:
63
+ continue
64
+ param.requires_grad = False
65
+ lora_config = LoraConfig(
66
+ r=lora_args.lora_r,
67
+ lora_alpha=lora_args.lora_alpha,
68
+ target_modules=lora_args.lora_target_modules,
69
+ lora_dropout=lora_args.lora_dropout,
70
+ bias=lora_args.lora_bias,
71
+ task_type='CAUSAL_LM',
72
+ )
73
+
74
+ self.model = get_peft_model(self.model, lora_config)
75
+ elif lora_args.lora_type == 'plora':
76
+ for name, param in self.model.model.named_parameters():
77
+ if 'Plora' not in name:
78
+ param.requires_grad = False
79
+
80
+ if self.use_caption:
81
+ if lora_args.lora_type == 'lora':
82
+ self.model.model.vision_proj.requires_grad_(True)
83
+ self.model.model.model.tok_embeddings.requires_grad_(True)
84
+ self.model.model.logit_scale.requires_grad_(True)
85
+ else:
86
+ self.model.vision_proj.requires_grad_(True)
87
+ self.model.model.tok_embeddings.requires_grad_(True)
88
+ self.model.logit_scale.requires_grad_(True)
89
+
90
+ ####
91
+ for name, param in self.model.model.named_parameters():
92
+ if 'vision_cross' in name:
93
+ param.requires_grad = True
94
+
95
+ if self.training_args.gradient_checkpointing:
96
+ self.model.enable_input_require_grads()
97
+ # self.model.gradient_checkpointing_enable()
98
+ self.model.model.vit.vision_tower.gradient_checkpointing_enable({"use_reentrant": True})
99
+
100
+
101
+
102
+
model/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from .Internlm import InternLM
2
+ model_dict = {
3
+ 'Internlm': InternLM,
4
+
5
+ }
6
+ def get_model(model_name, **kwargs):
7
+ return model_dict[model_name](**kwargs)
model/__pycache__/Internlm.cpython-311.pyc ADDED
Binary file (5.65 kB). View file
 
model/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (461 Bytes). View file
 
model/__pycache__/base.cpython-311.pyc ADDED
Binary file (5.33 kB). View file
 
model/base.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from utils.arguments import TrainingArguments, DataArguments, LoraArguments
2
+
3
+ def smart_tokenizer_and_embedding_resize(special_tokens_dict, tokenizer, model):
4
+ """Resize tokenizer and embedding.
5
+
6
+ Note: This is the unoptimized version that may make your embedding size not be divisible by 64.
7
+ """
8
+ num_new_tokens = tokenizer.add_special_tokens(special_tokens_dict) # TODO: maybe save special tokens in tokenizer
9
+ model.resize_token_embeddings(len(tokenizer)) # this set lm_head and embed_tokens requires_grad = True
10
+
11
+ if num_new_tokens > 0:
12
+ input_embeddings = model.get_input_embeddings().weight.data
13
+ output_embeddings = model.get_output_embeddings().weight.data
14
+
15
+ input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(
16
+ dim=0, keepdim=True)
17
+ output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(
18
+ dim=0, keepdim=True)
19
+
20
+ input_embeddings[-num_new_tokens:] = input_embeddings_avg
21
+ output_embeddings[-num_new_tokens:] = output_embeddings_avg
22
+
23
+ def reshape_model_embedding(tokenizer, model):
24
+ token_length = len(tokenizer)
25
+ embedding_length = model.get_input_embeddings().num_embeddings
26
+ if token_length != embedding_length:
27
+ num_new_tokens = token_length - embedding_length
28
+ model.resize_token_embeddings(len(tokenizer)) # this set lm_head and embed_tokens requires_grad = True
29
+ input_embeddings = model.get_input_embeddings().weight.data
30
+ output_embeddings = model.get_output_embeddings().weight.data
31
+
32
+ input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(
33
+ dim=0, keepdim=True)
34
+ output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(
35
+ dim=0, keepdim=True)
36
+
37
+ input_embeddings[-num_new_tokens:] = input_embeddings_avg
38
+ output_embeddings[-num_new_tokens:] = output_embeddings_avg
39
+
40
+ class BaseModel:
41
+ def __init__(
42
+ self,
43
+ model_path,
44
+ training_args: TrainingArguments,
45
+ data_args: DataArguments,
46
+ lora_args: LoraArguments,
47
+ use_caption = None,
48
+ ):
49
+ self.model_path = model_path
50
+ self.training_args = training_args
51
+ self.data_args = data_args
52
+ self.lora_args = lora_args
53
+ self.use_caption = use_caption
54
+
55
+ self.load_model_tokenizer()
56
+ self.configure_special_tokens()
57
+ self.configure_training_args()
58
+ self.configure_peft()
59
+ try:
60
+ self.model.print_trainable_parameters()
61
+ except:
62
+ pass
63
+ print('lljllj self model use_cache :', self.model.config.use_cache, flush=True)
64
+
65
+ def configure_special_tokens(self):
66
+ if self.use_caption and self.use_caption.get('text_pool', 'eot') == 'eot':
67
+ eot_token = '[EOT]'
68
+ smart_tokenizer_and_embedding_resize(
69
+ special_tokens_dict=dict(additional_special_tokens=[eot_token]),
70
+ tokenizer=self.tokenizer,
71
+ model=self.model)
72
+ else:
73
+ reshape_model_embedding(self.tokenizer, self.model)
74
+ self.model.tokenizer = self.tokenizer
75
+
76
+ def load_model_tokenizer(self):
77
+ raise NotImplementedError
78
+
79
+ def configure_training_args(self):
80
+ raise NotImplementedError
81
+
82
+ def configure_peft(self):
83
+ raise NotImplementedError
84
+
85
+ def get_model_tokenizer(self):
86
+ return self.model, self.tokenizer
87
+
88
+ def get_model_processor(self):
89
+ return self.model, self.processor
model/internlm_xcomposer/__pycache__/build_mlp.cpython-310.pyc ADDED
Binary file (6.64 kB). View file
 
model/internlm_xcomposer/__pycache__/build_mlp.cpython-311.pyc ADDED
Binary file (12.3 kB). View file
 
model/internlm_xcomposer/__pycache__/build_mlp.cpython-39.pyc ADDED
Binary file (6.61 kB). View file
 
model/internlm_xcomposer/__pycache__/configuration_internlm_xcomposer2.cpython-310.pyc ADDED
Binary file (5.89 kB). View file
 
model/internlm_xcomposer/__pycache__/configuration_internlm_xcomposer2.cpython-311.pyc ADDED
Binary file (7.02 kB). View file
 
model/internlm_xcomposer/__pycache__/configuration_internlm_xcomposer2.cpython-39.pyc ADDED
Binary file (5.84 kB). View file
 
model/internlm_xcomposer/__pycache__/modeling_internlm2.cpython-310.pyc ADDED
Binary file (29.3 kB). View file
 
model/internlm_xcomposer/__pycache__/modeling_internlm2.cpython-311.pyc ADDED
Binary file (53.6 kB). View file
 
model/internlm_xcomposer/__pycache__/modeling_internlm2.cpython-39.pyc ADDED
Binary file (29.5 kB). View file
 
model/internlm_xcomposer/__pycache__/modeling_internlm_xcomposer2.cpython-310.pyc ADDED
Binary file (20.3 kB). View file
 
model/internlm_xcomposer/__pycache__/modeling_internlm_xcomposer2.cpython-311.pyc ADDED
Binary file (40.5 kB). View file
 
model/internlm_xcomposer/__pycache__/modeling_internlm_xcomposer2.cpython-39.pyc ADDED
Binary file (20.2 kB). View file
 
model/internlm_xcomposer/__pycache__/tokenization_internlm_xcomposer2.cpython-310.pyc ADDED
Binary file (8.17 kB). View file
 
model/internlm_xcomposer/__pycache__/tokenization_internlm_xcomposer2.cpython-311.pyc ADDED
Binary file (12.2 kB). View file
 
model/internlm_xcomposer/__pycache__/tokenization_internlm_xcomposer2.cpython-39.pyc ADDED
Binary file (8.14 kB). View file
 
model/internlm_xcomposer/build_mlp.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import re
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ from transformers import CLIPVisionModel
7
+
8
+
9
+ def build_vision_tower():
10
+ vision_tower = 'openai/clip-vit-large-patch14-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
+
34
+ class IdentityMap(nn.Module):
35
+
36
+ def __init__(self):
37
+ super().__init__()
38
+
39
+ def forward(self, x, *args, **kwargs):
40
+ return x
41
+
42
+ @property
43
+ def config(self):
44
+ return {'mm_projector_type': 'identity'}
45
+
46
+
47
+ class CLIPVisionTower(nn.Module):
48
+
49
+ def __init__(self, vision_tower):
50
+ super().__init__()
51
+
52
+ self.is_loaded = False
53
+ self.is_resize_pos = False
54
+
55
+ self.vision_tower_name = vision_tower
56
+ self.select_layer = -1
57
+ self.select_feature = 'patch'
58
+ self.load_model()
59
+ self.resize_pos()
60
+
61
+ def load_model(self):
62
+ self.vision_tower = CLIPVisionModel.from_pretrained(
63
+ self.vision_tower_name)
64
+ self.vision_tower.requires_grad_(False)
65
+
66
+ self.is_loaded = True
67
+
68
+ def resize_pos(self):
69
+ pos_embed_checkpoint = self.vision_tower.vision_model.embeddings.position_embedding.weight
70
+ pos_embed_checkpoint = pos_embed_checkpoint.unsqueeze(0)
71
+ orig_size = 24
72
+ new_size = 35
73
+
74
+ if pos_embed_checkpoint.shape[1] == new_size**2 + 1:
75
+ self.is_resize_pos = True
76
+ else:
77
+ embedding_size = pos_embed_checkpoint.shape[-1]
78
+ num_extra_tokens = 1
79
+ new_num = new_size**2 + num_extra_tokens
80
+ #print('Position interpolate from %dx%d to %dx%d' %
81
+ # (orig_size, orig_size, new_size, new_size))
82
+ extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
83
+ # only the position tokens are interpolated
84
+ pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]
85
+ pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size,
86
+ embedding_size).permute(
87
+ 0, 3, 1, 2)
88
+ pos_tokens = torch.nn.functional.interpolate(
89
+ pos_tokens,
90
+ size=(new_size, new_size),
91
+ mode='bicubic',
92
+ align_corners=False)
93
+ pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2)
94
+ new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
95
+
96
+ new_pos_embed = new_pos_embed.squeeze(0)
97
+
98
+ self.vision_tower.vision_model.embeddings.position_embedding = torch.nn.Embedding(
99
+ new_num, 1024)
100
+ self.vision_tower.vision_model.embeddings.position_embedding.weight = torch.nn.Parameter(
101
+ new_pos_embed.to(pos_embed_checkpoint.dtype))
102
+ self.vision_tower.vision_model.embeddings.position_ids = torch.arange(
103
+ new_num).expand((1, -1))
104
+
105
+ self.is_resize_pos = True
106
+
107
+ def feature_select(self, image_forward_outs):
108
+ image_features = image_forward_outs.hidden_states[self.select_layer]
109
+ if self.select_feature == 'patch':
110
+ image_features = image_features[:, 1:]
111
+ elif self.select_feature == 'cls_patch':
112
+ image_features = image_features
113
+ else:
114
+ raise ValueError(
115
+ f'Unexpected select feature: {self.select_feature}')
116
+ return image_features
117
+
118
+ def forward(self, images):
119
+ if not self.is_loaded:
120
+ self.load_model()
121
+ if type(images) is list:
122
+ image_features = []
123
+ for image in images:
124
+ image_forward_out = self.vision_tower(
125
+ image.to(device=self.device,
126
+ dtype=self.dtype).unsqueeze(0),
127
+ output_hidden_states=True)
128
+ image_feature = self.feature_select(image_forward_out).to(
129
+ image.dtype)
130
+ image_features.append(image_feature)
131
+ else:
132
+ image_forward_outs = self.vision_tower(
133
+ images.to(device=self.device, dtype=self.dtype),
134
+ output_hidden_states=True)
135
+ image_features = self.feature_select(image_forward_outs).to(
136
+ images.dtype)
137
+
138
+ return image_features
139
+
140
+ @property
141
+ def dummy_feature(self):
142
+ return torch.zeros(
143
+ 1, self.hidden_size, device=self.device, dtype=self.dtype)
144
+
145
+ @property
146
+ def dtype(self):
147
+ return self.vision_tower.dtype
148
+
149
+ @property
150
+ def device(self):
151
+ return self.vision_tower.device
152
+
153
+ @property
154
+ def config(self):
155
+ if self.is_loaded:
156
+ return self.vision_tower.config
157
+ else:
158
+ return self.cfg_only
159
+
160
+ @property
161
+ def hidden_size(self):
162
+ return self.config.hidden_size
163
+
164
+ @property
165
+ def num_patches(self):
166
+ return (self.config.image_size // self.config.patch_size)**2
167
+
168
+
169
+ class PLoRA(nn.Linear):
170
+
171
+ def __init__(self,
172
+ in_features: int,
173
+ out_features: int,
174
+ bias: bool = True,
175
+ device=None,
176
+ dtype=None,
177
+ lora_r=8,
178
+ lora_alpha=16,
179
+ lora_dropout=0.05,
180
+ lora_len=0,
181
+ **kwargs) -> None:
182
+ super().__init__(in_features, out_features, bias, device, dtype)
183
+ self.lora_r = lora_r
184
+ self.lora_alpha = lora_alpha
185
+ self.lora_len = lora_len
186
+ if lora_dropout > 0.:
187
+ self.lora_dropout = nn.Dropout(p=lora_dropout)
188
+ else:
189
+ self.lora_dropout = lambda x: x
190
+ self.lora_scaling = self.lora_alpha / self.lora_r
191
+
192
+ self.Plora_A = nn.Linear(
193
+ in_features, self.lora_r, bias=False, device=device, dtype=dtype)
194
+ self.Plora_B = nn.Linear(
195
+ self.lora_r, out_features, bias=False, device=device, dtype=dtype)
196
+
197
+ self.reset_parameters()
198
+
199
+ def reset_parameters(self):
200
+ if hasattr(self, 'lora_A'):
201
+ # initialize A the same way as the default for nn.Linear and B to zero
202
+ nn.init.kaiming_uniform_(self.lora_A.weight, a=math.sqrt(5))
203
+ nn.init.zeros_(self.lora_B.weight)
204
+
205
+ def forward(self, x, im_mask=None):
206
+ res = super().forward(x)
207
+ if im_mask is not None:
208
+ if torch.sum(im_mask) > 0:
209
+ part_x = x[im_mask]
210
+ res[im_mask] += self.Plora_B(
211
+ self.Plora_A(
212
+ self.lora_dropout(part_x))) * self.lora_scaling
213
+ else:
214
+ part_x = x[:, :1]
215
+ res[:, :1] += self.Plora_B(
216
+ self.Plora_A(self.lora_dropout(part_x))) * 0
217
+ return res
model/internlm_xcomposer/configuration_internlm_xcomposer2.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright (c) InternLM. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ InternLM model configuration"""
21
+
22
+ from transformers.configuration_utils import PretrainedConfig
23
+ from transformers.utils import logging
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+ INTERNLM_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
28
+
29
+
30
+ class InternLMXcomposer2Config(PretrainedConfig):
31
+ r"""
32
+ This is the configuration class to store the configuration of a [`InternLMModel`]. It is used to instantiate
33
+ an InternLM model according to the specified arguments, defining the model architecture. Instantiating a
34
+ configuration with the defaults will yield a similar configuration to that of the InternLM-7B.
35
+
36
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
37
+ documentation from [`PretrainedConfig`] for more information.
38
+
39
+
40
+ Args:
41
+ vocab_size (`int`, *optional*, defaults to 32000):
42
+ Vocabulary size of the InternLM model. Defines the number of different tokens that can be represented by the
43
+ `inputs_ids` passed when calling [`InternLMModel`]
44
+ hidden_size (`int`, *optional*, defaults to 4096):
45
+ Dimension of the hidden representations.
46
+ intermediate_size (`int`, *optional*, defaults to 11008):
47
+ Dimension of the MLP representations.
48
+ num_hidden_layers (`int`, *optional*, defaults to 32):
49
+ Number of hidden layers in the Transformer encoder.
50
+ num_attention_heads (`int`, *optional*, defaults to 32):
51
+ Number of attention heads for each attention layer in the Transformer encoder.
52
+ num_key_value_heads (`int`, *optional*):
53
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
54
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
55
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
56
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
57
+ by meanpooling all the original heads within that group. For more details checkout [this
58
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
59
+ `num_attention_heads`.
60
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
61
+ The non-linear activation function (function or string) in the decoder.
62
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
63
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
64
+ just in case (e.g., 512 or 1024 or 2048).
65
+ initializer_range (`float`, *optional*, defaults to 0.02):
66
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
67
+ rms_norm_eps (`float`, *optional*, defaults to 1e-12):
68
+ The epsilon used by the rms normalization layers.
69
+ use_cache (`bool`, *optional*, defaults to `True`):
70
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
71
+ relevant if `config.is_decoder=True`.
72
+ tie_word_embeddings(`bool`, *optional*, defaults to `False`):
73
+ Whether to tie weight embeddings
74
+ Example:
75
+
76
+ ```python
77
+ >>> from transformers import InternLMModel, InternLMConfig
78
+
79
+ >>> # Initializing a InternLM internlm-7b style configuration
80
+ >>> configuration = InternLMConfig()
81
+
82
+ >>> # Initializing a model from the internlm-7b style configuration
83
+ >>> model = InternLMModel(configuration)
84
+
85
+ >>> # Accessing the model configuration
86
+ >>> configuration = model.config
87
+ ```"""
88
+ model_type = "internlm"
89
+ _auto_class = "AutoConfig"
90
+
91
+ def __init__( # pylint: disable=W0102
92
+ self,
93
+ vocab_size=103168,
94
+ hidden_size=4096,
95
+ intermediate_size=11008,
96
+ num_hidden_layers=32,
97
+ num_attention_heads=32,
98
+ num_key_value_heads=None,
99
+ hidden_act="silu",
100
+ max_position_embeddings=2048,
101
+ initializer_range=0.02,
102
+ rms_norm_eps=1e-6,
103
+ use_cache=True,
104
+ pad_token_id=0,
105
+ bos_token_id=1,
106
+ eos_token_id=2,
107
+ tie_word_embeddings=False,
108
+ bias=True,
109
+ rope_theta=10000,
110
+ rope_scaling=None,
111
+ **kwargs,
112
+ ):
113
+ self.vocab_size = vocab_size
114
+ self.max_position_embeddings = max_position_embeddings
115
+ self.hidden_size = hidden_size
116
+ self.intermediate_size = intermediate_size
117
+ self.num_hidden_layers = num_hidden_layers
118
+ self.num_attention_heads = num_attention_heads
119
+ self.bias = bias
120
+
121
+ if num_key_value_heads is None:
122
+ num_key_value_heads = num_attention_heads
123
+ self.num_key_value_heads = num_key_value_heads
124
+
125
+ self.hidden_act = hidden_act
126
+ self.initializer_range = initializer_range
127
+ self.rms_norm_eps = rms_norm_eps
128
+ self.use_cache = use_cache
129
+ self.rope_theta = rope_theta
130
+ self.rope_scaling = rope_scaling
131
+ self._rope_scaling_validation()
132
+ super().__init__(
133
+ pad_token_id=pad_token_id,
134
+ bos_token_id=bos_token_id,
135
+ eos_token_id=eos_token_id,
136
+ tie_word_embeddings=tie_word_embeddings,
137
+ **kwargs,
138
+ )
139
+
140
+ def _rope_scaling_validation(self):
141
+ """
142
+ Validate the `rope_scaling` configuration.
143
+ """
144
+ if self.rope_scaling is None:
145
+ return
146
+
147
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
148
+ raise ValueError(
149
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
150
+ f"got {self.rope_scaling}"
151
+ )
152
+ rope_scaling_type = self.rope_scaling.get("type", None)
153
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
154
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
155
+ raise ValueError(
156
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
157
+ )
158
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor < 1.0:
159
+ raise ValueError(f"`rope_scaling`'s factor field must be a float >= 1, got {rope_scaling_factor}")
model/internlm_xcomposer/modeling_internlm2.py ADDED
@@ -0,0 +1,1131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 math
21
+ import warnings
22
+ from typing import List, Optional, Tuple, Union
23
+
24
+ import torch
25
+ import torch.utils.checkpoint
26
+ from einops import rearrange
27
+ from torch import nn
28
+ from transformers.activations import ACT2FN
29
+ from transformers.modeling_outputs import BaseModelOutputWithPast
30
+ from transformers.modeling_utils import PreTrainedModel
31
+ from transformers.utils import (add_start_docstrings,
32
+ add_start_docstrings_to_model_forward, logging)
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 PLoRA
40
+ from .configuration_internlm_xcomposer2 import InternLMXcomposer2Config as InternLM2Config
41
+ logger = logging.get_logger(__name__)
42
+
43
+ _CONFIG_FOR_DOC = 'InternLM2Config'
44
+
45
+
46
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
47
+ def _make_causal_mask(input_ids_shape: torch.Size,
48
+ dtype: torch.dtype,
49
+ device: torch.device,
50
+ past_key_values_length: int = 0):
51
+ """Make causal mask used for bi-directional self-attention."""
52
+ bsz, tgt_len = input_ids_shape
53
+ mask = torch.full((tgt_len, tgt_len),
54
+ torch.tensor(torch.finfo(dtype).min, device=device),
55
+ device=device)
56
+ mask_cond = torch.arange(mask.size(-1), device=device)
57
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
58
+ mask = mask.to(dtype)
59
+
60
+ if past_key_values_length > 0:
61
+ mask = torch.cat([
62
+ torch.zeros(
63
+ tgt_len, past_key_values_length, dtype=dtype, device=device),
64
+ mask
65
+ ],
66
+ dim=-1)
67
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len,
68
+ tgt_len + past_key_values_length)
69
+
70
+
71
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
72
+ def _expand_mask(mask: torch.Tensor,
73
+ dtype: torch.dtype,
74
+ tgt_len: Optional[int] = None):
75
+ """Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len,
76
+ src_seq_len]`."""
77
+ bsz, src_len = mask.size()
78
+ tgt_len = tgt_len if tgt_len is not None else src_len
79
+
80
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len,
81
+ src_len).to(dtype)
82
+
83
+ inverted_mask = 1.0 - expanded_mask
84
+
85
+ return inverted_mask.masked_fill(
86
+ inverted_mask.to(torch.bool),
87
+ torch.finfo(dtype).min)
88
+
89
+
90
+ class InternLM2RMSNorm(nn.Module):
91
+
92
+ def __init__(self, hidden_size, eps=1e-6):
93
+ """InternLM2RMSNorm is equivalent to T5LayerNorm."""
94
+ super().__init__()
95
+ self.weight = nn.Parameter(torch.ones(hidden_size))
96
+ self.variance_epsilon = eps
97
+
98
+ def forward(self, hidden_states):
99
+ input_dtype = hidden_states.dtype
100
+ hidden_states = hidden_states.to(torch.float32)
101
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
102
+ hidden_states = hidden_states * torch.rsqrt(variance +
103
+ self.variance_epsilon)
104
+ return self.weight * hidden_states.to(input_dtype)
105
+
106
+
107
+ class InternLM2RotaryEmbedding(nn.Module):
108
+
109
+ def __init__(self,
110
+ dim,
111
+ max_position_embeddings=2048,
112
+ base=10000,
113
+ device=None):
114
+ super().__init__()
115
+
116
+ self.dim = dim
117
+ self.max_position_embeddings = max_position_embeddings
118
+ self.base = base
119
+ inv_freq = 1.0 / (
120
+ self.base
121
+ **(torch.arange(0, self.dim, 2).float().to(device) / self.dim))
122
+ self.register_buffer('inv_freq', inv_freq, persistent=False)
123
+
124
+ # Build here to make `torch.jit.trace` work.
125
+ self._set_cos_sin_cache(
126
+ seq_len=max_position_embeddings,
127
+ device=self.inv_freq.device,
128
+ dtype=torch.get_default_dtype())
129
+
130
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
131
+ self.max_seq_len_cached = seq_len
132
+ t = torch.arange(
133
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
134
+
135
+ freqs = torch.einsum('i,j->ij', t, self.inv_freq)
136
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
137
+ emb = torch.cat((freqs, freqs), dim=-1)
138
+ self.register_buffer(
139
+ 'cos_cached', emb.cos().to(dtype), persistent=False)
140
+ self.register_buffer(
141
+ 'sin_cached', emb.sin().to(dtype), persistent=False)
142
+
143
+ def forward(self, x, seq_len=None):
144
+ # x: [bs, num_attention_heads, seq_len, head_size]
145
+ if seq_len > self.max_seq_len_cached:
146
+ self._set_cos_sin_cache(
147
+ seq_len=seq_len, device=x.device, dtype=x.dtype)
148
+
149
+ return (
150
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
151
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
152
+ )
153
+
154
+
155
+ class InternLM2LinearScalingRotaryEmbedding(InternLM2RotaryEmbedding):
156
+ """InternLM2RotaryEmbedding extended with linear scaling.
157
+
158
+ Credits to the Reddit user /u/kaiokendev
159
+ """
160
+
161
+ def __init__(self,
162
+ dim,
163
+ max_position_embeddings=2048,
164
+ base=10000,
165
+ device=None,
166
+ scaling_factor=1.0):
167
+ self.scaling_factor = scaling_factor
168
+ super().__init__(dim, max_position_embeddings, base, device)
169
+
170
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
171
+ self.max_seq_len_cached = seq_len
172
+ t = torch.arange(
173
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
174
+ t = t / self.scaling_factor
175
+
176
+ freqs = torch.einsum('i,j->ij', t, self.inv_freq)
177
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
178
+ emb = torch.cat((freqs, freqs), dim=-1)
179
+ self.register_buffer(
180
+ 'cos_cached', emb.cos().to(dtype), persistent=False)
181
+ self.register_buffer(
182
+ 'sin_cached', emb.sin().to(dtype), persistent=False)
183
+
184
+
185
+ class InternLM2DynamicNTKScalingRotaryEmbedding(InternLM2RotaryEmbedding):
186
+ """InternLM2RotaryEmbedding extended with Dynamic NTK scaling.
187
+
188
+ Credits to the Reddit users /u/bloc97 and /u/emozilla.
189
+ """
190
+
191
+ def __init__(self,
192
+ dim,
193
+ max_position_embeddings=2048,
194
+ base=10000,
195
+ device=None,
196
+ scaling_factor=1.0):
197
+ self.scaling_factor = scaling_factor
198
+ super().__init__(dim, max_position_embeddings, base, device)
199
+
200
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
201
+ self.max_seq_len_cached = seq_len
202
+
203
+ if seq_len > self.max_position_embeddings:
204
+ base = self.base * ((self.scaling_factor * seq_len /
205
+ self.max_position_embeddings) -
206
+ (self.scaling_factor - 1))**(
207
+ self.dim / (self.dim - 2))
208
+ inv_freq = 1.0 / (
209
+ base
210
+ **(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(
214
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
215
+
216
+ freqs = torch.einsum('i,j->ij', t, self.inv_freq)
217
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
218
+ emb = torch.cat((freqs, freqs), dim=-1)
219
+ self.register_buffer(
220
+ 'cos_cached', emb.cos().to(dtype), persistent=False)
221
+ self.register_buffer(
222
+ 'sin_cached', emb.sin().to(dtype), persistent=False)
223
+
224
+
225
+ def rotate_half(x):
226
+ """Rotates half the hidden dims of the input."""
227
+ x1 = x[..., :x.shape[-1] // 2]
228
+ x2 = x[..., x.shape[-1] // 2:]
229
+ return torch.cat((-x2, x1), dim=-1)
230
+
231
+
232
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
233
+ # The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
234
+ cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
235
+ sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
236
+ cos = cos.unsqueeze(0).unsqueeze(0).expand(len(position_ids), -1, -1, -1)
237
+ sin = sin.unsqueeze(0).unsqueeze(0).expand(len(position_ids), -1, -1, -1)
238
+ if q.size(2) == 1:
239
+ q_embed = (q * cos[:, :, -1:, :]) + (
240
+ rotate_half(q) * sin[:, :, -1:, :])
241
+ else:
242
+ q_embed = (q * cos) + (rotate_half(q) * sin)
243
+
244
+ if k.size(2) == 1:
245
+ k_embed = (k * cos[:, :, -1:, :]) + (
246
+ rotate_half(k) * sin[:, :, -1:, :])
247
+ else:
248
+ k_embed = (k * cos) + (rotate_half(k) * sin)
249
+
250
+ return q_embed, k_embed
251
+
252
+
253
+ class InternLM2MLP(nn.Module):
254
+
255
+ def __init__(self, config):
256
+ super().__init__()
257
+ self.config = config
258
+ self.hidden_size = config.hidden_size
259
+ self.intermediate_size = config.intermediate_size
260
+
261
+ self.w1 = PLoRA(
262
+ self.hidden_size,
263
+ self.intermediate_size,
264
+ bias=False,
265
+ lora_r=256,
266
+ lora_alpha=256,
267
+ lora_len=576)
268
+ self.w3 = PLoRA(
269
+ self.hidden_size,
270
+ self.intermediate_size,
271
+ bias=False,
272
+ lora_r=256,
273
+ lora_alpha=256,
274
+ lora_len=576)
275
+ self.w2 = PLoRA(
276
+ self.intermediate_size,
277
+ self.hidden_size,
278
+ bias=False,
279
+ lora_r=256,
280
+ lora_alpha=256,
281
+ lora_len=576)
282
+
283
+ self.act_fn = ACT2FN[config.hidden_act]
284
+
285
+ def forward(self, x, im_mask):
286
+ down_proj = self.w2(
287
+ self.act_fn(self.w1(x, im_mask)) * self.w3(x, im_mask), im_mask)
288
+
289
+ return down_proj
290
+
291
+
292
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
293
+ """This is the equivalent of torch.repeat_interleave(x, dim=1,
294
+ repeats=n_rep).
295
+
296
+ The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to
297
+ (batch, num_attention_heads, seqlen, head_dim)
298
+ """
299
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
300
+ if n_rep == 1:
301
+ return hidden_states
302
+ hidden_states = hidden_states[:, :,
303
+ None, :, :].expand(batch,
304
+ num_key_value_heads,
305
+ n_rep, slen, head_dim)
306
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen,
307
+ head_dim)
308
+
309
+
310
+ class InternLM2Attention(nn.Module):
311
+ """Multi-headed attention from 'Attention Is All You Need' paper."""
312
+
313
+ def __init__(self, config: InternLM2Config):
314
+ super().__init__()
315
+ self.config = config
316
+ self.hidden_size = config.hidden_size
317
+ self.num_heads = config.num_attention_heads
318
+ self.head_dim = self.hidden_size // self.num_heads
319
+ self.num_key_value_heads = config.num_key_value_heads
320
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
321
+ self.max_position_embeddings = config.max_position_embeddings
322
+ self.is_causal = True
323
+
324
+ if (self.head_dim * self.num_heads) != self.hidden_size:
325
+ raise ValueError(
326
+ f'hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}'
327
+ f' and `num_heads`: {self.num_heads}).')
328
+
329
+ self.wqkv = PLoRA(
330
+ self.hidden_size,
331
+ (self.num_heads + 2 * self.num_key_value_heads) * self.head_dim,
332
+ bias=config.bias,
333
+ lora_r=256,
334
+ lora_alpha=256,
335
+ lora_len=576)
336
+
337
+ self.wo = PLoRA(
338
+ self.num_heads * self.head_dim,
339
+ self.hidden_size,
340
+ bias=config.bias,
341
+ lora_r=256,
342
+ lora_alpha=256,
343
+ lora_len=576)
344
+ self._init_rope()
345
+
346
+ def _init_rope(self):
347
+ if self.config.rope_scaling is None:
348
+ self.rotary_emb = InternLM2RotaryEmbedding(
349
+ self.head_dim,
350
+ max_position_embeddings=self.max_position_embeddings,
351
+ base=self.config.rope_theta,
352
+ )
353
+ else:
354
+ scaling_type = self.config.rope_scaling['type']
355
+ scaling_factor = self.config.rope_scaling['factor']
356
+ if scaling_type == 'dynamic':
357
+ self.rotary_emb = InternLM2DynamicNTKScalingRotaryEmbedding(
358
+ self.head_dim,
359
+ max_position_embeddings=self.max_position_embeddings,
360
+ base=self.config.rope_theta,
361
+ scaling_factor=scaling_factor)
362
+ else:
363
+ raise ValueError(
364
+ "Currently we only support rotary embedding's type being 'dynamic'."
365
+ )
366
+ return self.rotary_emb
367
+
368
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
369
+ return tensor.view(bsz, seq_len, self.num_heads,
370
+ self.head_dim).transpose(1, 2).contiguous()
371
+
372
+ def forward(
373
+ self,
374
+ hidden_states: torch.Tensor,
375
+ attention_mask: Optional[torch.Tensor] = None,
376
+ position_ids: Optional[torch.LongTensor] = None,
377
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
378
+ output_attentions: bool = False,
379
+ use_cache: bool = False,
380
+ im_mask: Optional[Tuple[torch.Tensor]] = None,
381
+ **kwargs,
382
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor],
383
+ Optional[Tuple[torch.Tensor]]]:
384
+ if 'padding_mask' in kwargs:
385
+ warnings.warn(
386
+ 'Passing `padding_mask` is deprecated and will be removed in v4.37. '
387
+ 'Please make sure use `attention_mask` instead.`')
388
+
389
+ bsz, q_len, _ = hidden_states.size()
390
+
391
+ qkv_states = self.wqkv(hidden_states, im_mask)
392
+
393
+ qkv_states = rearrange(
394
+ qkv_states,
395
+ 'b q (h gs d) -> b q h gs d',
396
+ gs=2 + self.num_key_value_groups,
397
+ d=self.head_dim,
398
+ )
399
+
400
+ query_states = qkv_states[..., :self.num_key_value_groups, :]
401
+ query_states = rearrange(query_states, 'b q h gs d -> b q (h gs) d')
402
+ key_states = qkv_states[..., -2, :]
403
+ value_states = qkv_states[..., -1, :]
404
+
405
+ query_states = query_states.transpose(1, 2)
406
+ key_states = key_states.transpose(1, 2)
407
+ value_states = value_states.transpose(1, 2)
408
+
409
+ kv_seq_len = key_states.shape[-2]
410
+ if past_key_value is not None:
411
+ kv_seq_len += past_key_value[0].shape[-2]
412
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
413
+ query_states, key_states = apply_rotary_pos_emb(
414
+ query_states, key_states, cos, sin, position_ids)
415
+
416
+ if past_key_value is not None:
417
+ # reuse k, v, self_attention
418
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
419
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
420
+
421
+ past_key_value = (key_states, value_states) if use_cache else None
422
+
423
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
424
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
425
+
426
+ attn_weights = torch.matmul(query_states, key_states.transpose(
427
+ 2, 3)) / math.sqrt(self.head_dim)
428
+
429
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
430
+ raise ValueError(
431
+ f'Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is'
432
+ f' {attn_weights.size()}')
433
+
434
+ if attention_mask is not None:
435
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
436
+ raise ValueError(
437
+ f'Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}'
438
+ )
439
+ attn_weights = attn_weights + attention_mask
440
+
441
+ # upcast attention to fp32
442
+ attn_weights = nn.functional.softmax(
443
+ attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
444
+ attn_output = torch.matmul(attn_weights, value_states)
445
+
446
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
447
+ raise ValueError(
448
+ f'`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is'
449
+ f' {attn_output.size()}')
450
+
451
+ attn_output = attn_output.transpose(1, 2).contiguous()
452
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
453
+
454
+ attn_output = self.wo(attn_output, im_mask)
455
+
456
+ if not output_attentions:
457
+ attn_weights = None
458
+
459
+ return attn_output, attn_weights, past_key_value
460
+
461
+ class VisionCrossAttn(nn.Module):
462
+ """Multi-headed attention from 'Attention Is All You Need' paper."""
463
+
464
+ def __init__(self, config: InternLM2Config):
465
+ super().__init__()
466
+ self.config = config
467
+ self.hidden_size = config.hidden_size
468
+ self.num_heads = config.num_attention_heads
469
+ self.head_dim = self.hidden_size // self.num_heads
470
+ self.num_key_value_heads = config.num_key_value_heads
471
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
472
+ self.max_position_embeddings = config.max_position_embeddings
473
+ self.is_causal = True
474
+
475
+ if (self.head_dim * self.num_heads) != self.hidden_size:
476
+ raise ValueError(
477
+ f'hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}'
478
+ f' and `num_heads`: {self.num_heads}).')
479
+
480
+ self.wq = nn.Linear(
481
+ self.hidden_size, self.num_heads * self.head_dim, bias=False)
482
+
483
+ self.wk = nn.Linear(
484
+ self.hidden_size, self.num_heads * self.head_dim, bias=False)
485
+
486
+ self.wv = nn.Linear(
487
+ self.hidden_size, self.num_heads * self.head_dim, bias=False)
488
+
489
+ self.wo = nn.Linear(
490
+ self.num_heads * self.head_dim, self.hidden_size, bias=False)
491
+
492
+ self.register_parameter("alpha_attn", nn.Parameter(torch.tensor(0.0)))
493
+
494
+ self._init_rope()
495
+
496
+ def _init_rope(self):
497
+ if self.config.rope_scaling is None:
498
+ self.rotary_emb = InternLM2RotaryEmbedding(
499
+ self.head_dim,
500
+ max_position_embeddings=self.max_position_embeddings,
501
+ base=self.config.rope_theta,
502
+ )
503
+ else:
504
+ scaling_type = self.config.rope_scaling['type']
505
+ scaling_factor = self.config.rope_scaling['factor']
506
+ if scaling_type == 'dynamic':
507
+ self.rotary_emb = InternLM2DynamicNTKScalingRotaryEmbedding(
508
+ self.head_dim,
509
+ max_position_embeddings=self.max_position_embeddings,
510
+ base=self.config.rope_theta,
511
+ scaling_factor=scaling_factor)
512
+ else:
513
+ raise ValueError(
514
+ "Currently we only support rotary embedding's type being 'dynamic'."
515
+ )
516
+ return self.rotary_emb
517
+
518
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
519
+ return tensor.view(bsz, seq_len, self.num_heads,
520
+ self.head_dim).transpose(1, 2).contiguous()
521
+
522
+ def forward(
523
+ self,
524
+ hidden_states: torch.Tensor,
525
+ attention_mask: Optional[torch.Tensor] = None,
526
+ position_ids: Optional[torch.LongTensor] = None,
527
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
528
+ output_attentions: bool = False,
529
+ use_cache: bool = False,
530
+ im_mask: Optional[Tuple[torch.Tensor]] = None,
531
+ **kwargs,
532
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor],
533
+ Optional[Tuple[torch.Tensor]]]:
534
+ if 'padding_mask' in kwargs:
535
+ warnings.warn(
536
+ 'Passing `padding_mask` is deprecated and will be removed in v4.37. '
537
+ 'Please make sure use `attention_mask` instead.`')
538
+ if im_mask is not None:
539
+ if torch.sum(im_mask) > 0:
540
+ bsz, h_len, _ = hidden_states.size()
541
+ vision_part = hidden_states[im_mask].reshape(bsz, -1, self.hidden_size)
542
+ language_part = hidden_states[~im_mask].reshape(bsz, -1, self.hidden_size)
543
+ query_states = self.wq(language_part)
544
+ query_states = rearrange(query_states, 'b l (h d) -> b l h d', d=self.head_dim)
545
+ key_vision = self.wk(vision_part)
546
+ key_vision = rearrange(key_vision, 'b l (h d) -> b l h d', d=self.head_dim)
547
+ value_vision = self.wv(vision_part)
548
+ value_vision = rearrange(value_vision, 'b l (h d) -> b l h d', d=self.head_dim)
549
+ query_states = query_states.transpose(1, 2)
550
+ key_states = key_vision.transpose(1, 2)
551
+ value_states = value_vision.transpose(1, 2)
552
+
553
+ bsz, q_len, _ = language_part.size()
554
+ kv_seq_len = key_states.shape[-2]
555
+ # cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
556
+ # query_states, key_states = apply_rotary_pos_emb(
557
+ # query_states, key_states, cos, sin, position_ids)
558
+
559
+ attn_weights = torch.matmul(query_states, key_states.transpose(
560
+ 2, 3)) / math.sqrt(self.head_dim)
561
+
562
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
563
+ raise ValueError(
564
+ f'Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is'
565
+ f' {attn_weights.size()}')
566
+
567
+ if attention_mask is not None:
568
+ # language_mask = ~im_mask[:, None, None, :].repeat(1, 1, q_len, 1)
569
+ # vision_mask = im_mask[:, None, :, None].repeat(1, 1, 1, h_len)
570
+ language_mask = ~im_mask[:, None, :, None].repeat(1, 1, 1, h_len)
571
+ vision_mask = im_mask[:, None, None, :].repeat(1, 1, q_len, 1)
572
+ # Apply the mask to the attention_mask
573
+ vision_mask = attention_mask[language_mask].reshape(bsz, 1, q_len, h_len)[vision_mask].reshape(bsz, 1, q_len, kv_seq_len)
574
+ if vision_mask.size() != (bsz, 1, q_len, kv_seq_len):
575
+ raise ValueError(
576
+ f'Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {vision_mask.size()}'
577
+ )
578
+ attn_weights = attn_weights + vision_mask
579
+
580
+ # upcast attention to fp32
581
+ attn_weights = nn.functional.softmax(
582
+ attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
583
+ attn_output = torch.matmul(attn_weights, value_states)
584
+
585
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
586
+ raise ValueError(
587
+ f'`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is'
588
+ f' {attn_output.size()}')
589
+
590
+ attn_output = attn_output.transpose(1, 2).contiguous()
591
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
592
+
593
+ attn_output = self.wo(attn_output)
594
+ return self.alpha_attn * attn_output
595
+ else:
596
+ part_x = hidden_states
597
+ part_x = self.wo(self.wq(part_x)) * 0
598
+ return part_x
599
+ else:
600
+ return 0
601
+
602
+
603
+ class InternLM2FlashAttention2(InternLM2Attention):
604
+ """InternLM2 flash attention module.
605
+
606
+ This module inherits from `InternLM2Attention` as the weights of the module
607
+ stays untouched. The only required change would be on the forward pass
608
+ where it needs to correctly call the public API of flash attention and deal
609
+ with padding tokens in case the input contains any of them.
610
+ """
611
+
612
+ def forward(
613
+ self,
614
+ hidden_states: torch.Tensor,
615
+ attention_mask: Optional[torch.LongTensor] = None,
616
+ position_ids: Optional[torch.LongTensor] = None,
617
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
618
+ output_attentions: bool = False,
619
+ use_cache: bool = False,
620
+ im_mask: Optional[Tuple[torch.Tensor]] = None,
621
+ **kwargs,
622
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor],
623
+ Optional[Tuple[torch.Tensor]]]:
624
+ # InternLM2FlashAttention2 attention does not support output_attentions
625
+ if 'padding_mask' in kwargs:
626
+ warnings.warn(
627
+ 'Passing `padding_mask` is deprecated and will be removed in v4.37. '
628
+ 'Please make sure use `attention_mask` instead.`')
629
+
630
+ # overwrite attention_mask with padding_mask
631
+ attention_mask = kwargs.pop('padding_mask')
632
+
633
+ output_attentions = False
634
+
635
+ bsz, q_len, _ = hidden_states.size()
636
+
637
+ qkv_states = self.wqkv(hidden_states, im_mask)
638
+
639
+ qkv_states = rearrange(
640
+ qkv_states,
641
+ 'b q (h gs d) -> b q h gs d',
642
+ gs=self.num_heads + 2 * self.num_key_value_heads,
643
+ d=self.head_dim,
644
+ q=q_len,
645
+ )
646
+
647
+ query_states = qkv_states[..., :self.num_key_value_groups, :]
648
+ query_states = rearrange(query_states, 'b q h gs d -> b q (h gs) d')
649
+ key_states = qkv_states[..., -2, :]
650
+ value_states = qkv_states[..., -1, :]
651
+
652
+ kv_seq_len = key_states.shape[-2]
653
+ if past_key_value is not None:
654
+ kv_seq_len += past_key_value[0].shape[-2]
655
+
656
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
657
+
658
+ query_states, key_states = apply_rotary_pos_emb(
659
+ query_states, key_states, cos, sin, position_ids)
660
+
661
+ if past_key_value is not None:
662
+ # reuse k, v, self_attention
663
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
664
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
665
+
666
+ past_key_value = (key_states, value_states) if use_cache else None
667
+
668
+ query_states = query_states.transpose(1, 2)
669
+ key_states = key_states.transpose(1, 2)
670
+ value_states = value_states.transpose(1, 2)
671
+
672
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
673
+
674
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
675
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
676
+ # cast them back in the correct dtype just to be sure everything works as expected.
677
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
678
+ # in fp32. (InternLM2RMSNorm handles it correctly)
679
+
680
+ input_dtype = query_states.dtype
681
+ if input_dtype == torch.float32:
682
+ # Handle the case where the model is quantized
683
+ if hasattr(self.config, '_pre_quantization_dtype'):
684
+ target_dtype = self.config._pre_quantization_dtype
685
+ else:
686
+ target_dtype = self.q_proj.weight.dtype
687
+
688
+ logger.warning_once(
689
+ f'The input hidden states seems to be silently casted in float32, this might be related to'
690
+ f' the fact you have upcasted embedding or layer norm layers in float32. We will cast back '
691
+ f'the input in {target_dtype}.')
692
+
693
+ query_states = query_states.to(target_dtype)
694
+ key_states = key_states.to(target_dtype)
695
+ value_states = value_states.to(target_dtype)
696
+
697
+ attn_output = self._flash_attention_forward(
698
+ query_states,
699
+ key_states,
700
+ value_states,
701
+ attention_mask,
702
+ q_len,
703
+ dropout=dropout_rate)
704
+
705
+ attn_output = attn_output.reshape(bsz, q_len,
706
+ self.hidden_size).contiguous()
707
+ attn_output = self.wo(attn_output, im_mask)
708
+
709
+ if not output_attentions:
710
+ attn_weights = None
711
+
712
+ return attn_output, attn_weights, past_key_value
713
+
714
+
715
+ class InternLM2DecoderLayer(nn.Module):
716
+
717
+ def __init__(self, config: InternLM2Config, crossattn=False):
718
+ super().__init__()
719
+ self.hidden_size = config.hidden_size
720
+ self.attention = (
721
+ InternLM2Attention(config=config)
722
+ if not getattr(config, '_flash_attn_2_enabled', False) else
723
+ InternLM2FlashAttention2(config=config))
724
+ self.feed_forward = InternLM2MLP(config)
725
+ self.attention_norm = InternLM2RMSNorm(
726
+ config.hidden_size, eps=config.rms_norm_eps)
727
+ self.ffn_norm = InternLM2RMSNorm(
728
+ config.hidden_size, eps=config.rms_norm_eps)
729
+ self.crossattn = crossattn
730
+ if crossattn:
731
+ self.vision_crossattn = VisionCrossAttn(config)
732
+
733
+ def forward(
734
+ self,
735
+ hidden_states: torch.Tensor,
736
+ attention_mask: Optional[torch.Tensor] = None,
737
+ position_ids: Optional[torch.LongTensor] = None,
738
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
739
+ output_attentions: Optional[bool] = False,
740
+ use_cache: Optional[bool] = False,
741
+ im_mask: Optional[Tuple[torch.Tensor]] = None,
742
+ **kwargs,
743
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor,
744
+ torch.FloatTensor]]]:
745
+ """
746
+ Args:
747
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
748
+ attention_mask (`torch.FloatTensor`, *optional*):
749
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
750
+ query_sequence_length, key_sequence_length)` if default attention is used.
751
+ output_attentions (`bool`, *optional*):
752
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
753
+ returned tensors for more detail.
754
+ use_cache (`bool`, *optional*):
755
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
756
+ (see `past_key_values`).
757
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
758
+ """
759
+ if 'padding_mask' in kwargs:
760
+ warnings.warn(
761
+ 'Passing `padding_mask` is deprecated and will be removed in v4.37. '
762
+ 'Please make sure use `attention_mask` instead.`')
763
+
764
+ residual = hidden_states
765
+
766
+ hidden_states = self.attention_norm(hidden_states)
767
+ if self.crossattn:
768
+ vision_states = self.vision_crossattn(hidden_states=hidden_states,
769
+ attention_mask=attention_mask,
770
+ position_ids=position_ids,
771
+ past_key_value=past_key_value,
772
+ output_attentions=output_attentions,
773
+ use_cache=use_cache,
774
+ im_mask=im_mask,
775
+ **kwargs,)
776
+ if im_mask is not None:
777
+ hidden_states[~im_mask] = hidden_states[~im_mask] + vision_states.reshape(-1, self.hidden_size)
778
+
779
+ # Self Attention
780
+ hidden_states, self_attn_weights, present_key_value = self.attention(
781
+ hidden_states=hidden_states,
782
+ attention_mask=attention_mask,
783
+ position_ids=position_ids,
784
+ past_key_value=past_key_value,
785
+ output_attentions=output_attentions,
786
+ use_cache=use_cache,
787
+ im_mask=im_mask,
788
+ **kwargs,
789
+ )
790
+ hidden_states = residual + hidden_states
791
+ tmp_attn = self_attn_weights
792
+ # Fully Connected
793
+ residual = hidden_states
794
+ hidden_states = self.ffn_norm(hidden_states)
795
+ hidden_states = self.feed_forward(hidden_states, im_mask)
796
+ hidden_states = residual + hidden_states
797
+
798
+ outputs = (hidden_states, )
799
+
800
+ if output_attentions:
801
+ outputs += (self_attn_weights, )
802
+
803
+ if use_cache:
804
+ outputs += (present_key_value, )
805
+
806
+ return outputs
807
+
808
+
809
+ InternLM2_START_DOCSTRING = r"""
810
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
811
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
812
+ etc.)
813
+
814
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
815
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
816
+ and behavior.
817
+
818
+ Parameters:
819
+ config ([`InternLM2Config`]):
820
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
821
+ load the weights associated with the model, only the configuration. Check out the
822
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
823
+ """
824
+
825
+
826
+ @add_start_docstrings(
827
+ 'The bare InternLM2 Model outputting raw hidden-states without any specific head on top.',
828
+ InternLM2_START_DOCSTRING,
829
+ )
830
+ class InternLM2PreTrainedModel(PreTrainedModel):
831
+ config_class = InternLM2Config
832
+ base_model_prefix = 'model'
833
+ supports_gradient_checkpointing = True
834
+ _no_split_modules = ['InternLM2DecoderLayer']
835
+ _skip_keys_device_placement = 'past_key_values'
836
+ _supports_flash_attn_2 = True
837
+
838
+ def _init_weights(self, module):
839
+ std = self.config.initializer_range
840
+ if isinstance(module, nn.Linear):
841
+ module.weight.data.normal_(mean=0.0, std=std)
842
+ if module.bias is not None:
843
+ module.bias.data.zero_()
844
+ elif isinstance(module, nn.Embedding):
845
+ module.weight.data.normal_(mean=0.0, std=std)
846
+ if module.padding_idx is not None:
847
+ module.weight.data[module.padding_idx].zero_()
848
+
849
+
850
+ InternLM2_INPUTS_DOCSTRING = r"""
851
+ Args:
852
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
853
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
854
+ it.
855
+
856
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
857
+ [`PreTrainedTokenizer.__call__`] for details.
858
+
859
+ [What are input IDs?](../glossary#input-ids)
860
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
861
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
862
+
863
+ - 1 for tokens that are **not masked**,
864
+ - 0 for tokens that are **masked**.
865
+
866
+ [What are attention masks?](../glossary#attention-mask)
867
+
868
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
869
+ [`PreTrainedTokenizer.__call__`] for details.
870
+
871
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
872
+ `past_key_values`).
873
+
874
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
875
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
876
+ information on the default strategy.
877
+
878
+ - 1 indicates the head is **not masked**,
879
+ - 0 indicates the head is **masked**.
880
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
881
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
882
+ config.n_positions - 1]`.
883
+
884
+ [What are position IDs?](../glossary#position-ids)
885
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or
886
+ when `config.use_cache=True`):
887
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
888
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
889
+ `(batch_size, num_heads, decoder_sequence_length, embed_size_per_head)`.
890
+
891
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
892
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
893
+
894
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
895
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
896
+ of shape `(batch_size, sequence_length)`.
897
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
898
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
899
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
900
+ model's internal embedding lookup matrix.
901
+ use_cache (`bool`, *optional*):
902
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
903
+ `past_key_values`).
904
+ output_attentions (`bool`, *optional*):
905
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
906
+ tensors for more detail.
907
+ output_hidden_states (`bool`, *optional*):
908
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
909
+ more detail.
910
+ return_dict (`bool`, *optional*):
911
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
912
+ """
913
+
914
+
915
+ @add_start_docstrings(
916
+ 'The bare InternLM2 Model outputting raw hidden-states without any specific head on top.',
917
+ InternLM2_START_DOCSTRING,
918
+ )
919
+ class InternLM2Model(InternLM2PreTrainedModel):
920
+ """Transformer decoder consisting of *config.num_hidden_layers* layers.
921
+ Each layer is a [`InternLM2DecoderLayer`]
922
+
923
+ Args:
924
+ config: InternLM2Config
925
+ """
926
+
927
+ _auto_class = 'AutoModel'
928
+
929
+ def __init__(self, config: InternLM2Config, crossattn=False):
930
+ super().__init__(config)
931
+ self.padding_idx = config.pad_token_id
932
+ self.vocab_size = config.vocab_size
933
+
934
+ self.tok_embeddings = nn.Embedding(config.vocab_size,
935
+ config.hidden_size,
936
+ self.padding_idx)
937
+ # self.layers = []
938
+ # for idx in range(config.num_hidden_layers):
939
+ # if -1 < idx and idx < 24:
940
+ # crossattn = True
941
+ # else:
942
+ # crossattn = False
943
+ # self.layers.append(InternLM2DecoderLayer(config, crossattn))
944
+ # self.layers = nn.ModuleList(self.layers)
945
+
946
+ self.layers = nn.ModuleList([
947
+ InternLM2DecoderLayer(config, crossattn)
948
+ for _ in range(config.num_hidden_layers)
949
+ ])
950
+
951
+
952
+ self.norm = InternLM2RMSNorm(
953
+ config.hidden_size, eps=config.rms_norm_eps)
954
+
955
+ self.gradient_checkpointing = False
956
+ # Initialize weights and apply final processing
957
+ self.post_init()
958
+
959
+ def get_input_embeddings(self):
960
+ return self.tok_embeddings
961
+
962
+ def set_input_embeddings(self, value):
963
+ self.tok_embeddings = value
964
+
965
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
966
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape,
967
+ inputs_embeds, past_key_values_length):
968
+ # create causal mask
969
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
970
+ combined_attention_mask = None
971
+ if input_shape[-1] > 1:
972
+ combined_attention_mask = _make_causal_mask(
973
+ input_shape,
974
+ inputs_embeds.dtype,
975
+ device=inputs_embeds.device,
976
+ past_key_values_length=past_key_values_length,
977
+ )
978
+
979
+ if attention_mask is not None:
980
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
981
+ expanded_attn_mask = _expand_mask(
982
+ attention_mask, inputs_embeds.dtype,
983
+ tgt_len=input_shape[-1]).to(inputs_embeds.device)
984
+ combined_attention_mask = (
985
+ expanded_attn_mask if combined_attention_mask is None else
986
+ expanded_attn_mask + combined_attention_mask)
987
+
988
+ return combined_attention_mask
989
+
990
+ @add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
991
+ def forward(self,
992
+ input_ids: torch.LongTensor = None,
993
+ attention_mask: Optional[torch.Tensor] = None,
994
+ position_ids: Optional[torch.LongTensor] = None,
995
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
996
+ inputs_embeds: Optional[torch.FloatTensor] = None,
997
+ use_cache: Optional[bool] = None,
998
+ output_attentions: Optional[bool] = None,
999
+ output_hidden_states: Optional[bool] = None,
1000
+ return_dict: Optional[bool] = None,
1001
+ **kwargs) -> Union[Tuple, BaseModelOutputWithPast]:
1002
+
1003
+ im_mask = kwargs.get('im_mask', None)
1004
+
1005
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1006
+ output_hidden_states = (
1007
+ output_hidden_states if output_hidden_states is not None else
1008
+ self.config.output_hidden_states)
1009
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1010
+
1011
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1012
+
1013
+ # retrieve input_ids and inputs_embeds
1014
+ if input_ids is not None and inputs_embeds is not None:
1015
+ raise ValueError(
1016
+ 'You cannot specify both input_ids and inputs_embeds at the same time'
1017
+ )
1018
+ elif input_ids is not None:
1019
+ batch_size, seq_length = input_ids.shape[:2]
1020
+ elif inputs_embeds is not None:
1021
+ batch_size, seq_length = inputs_embeds.shape[:2]
1022
+ else:
1023
+ raise ValueError(
1024
+ 'You have to specify either input_ids or inputs_embeds')
1025
+
1026
+ seq_length_with_past = seq_length
1027
+ past_key_values_length = 0
1028
+ if past_key_values is not None:
1029
+ past_key_values_length = past_key_values[0][0].shape[2]
1030
+ seq_length_with_past = seq_length_with_past + past_key_values_length
1031
+
1032
+ if position_ids is None:
1033
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1034
+ position_ids = torch.arange(
1035
+ past_key_values_length,
1036
+ seq_length + past_key_values_length,
1037
+ dtype=torch.long,
1038
+ device=device)
1039
+ position_ids = position_ids.unsqueeze(0)
1040
+
1041
+ if inputs_embeds is None:
1042
+ inputs_embeds = self.tok_embeddings(input_ids)
1043
+ im_mask = torch.zeros(inputs_embeds.shape[:2]).to(
1044
+ inputs_embeds.device).bool()
1045
+ # embed positions
1046
+ if attention_mask is None:
1047
+ attention_mask = torch.ones((batch_size, seq_length_with_past),
1048
+ dtype=torch.bool,
1049
+ device=inputs_embeds.device)
1050
+ attention_mask = self._prepare_decoder_attention_mask(
1051
+ attention_mask, (batch_size, seq_length), inputs_embeds,
1052
+ past_key_values_length)
1053
+
1054
+ # embed positions
1055
+ hidden_states = inputs_embeds
1056
+
1057
+ if self.gradient_checkpointing and self.training:
1058
+ if use_cache:
1059
+ logger.warning_once(
1060
+ '`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...'
1061
+ )
1062
+ use_cache = False
1063
+
1064
+ # decoder layers
1065
+ all_hidden_states = () if output_hidden_states else None
1066
+ all_self_attns = () if output_attentions else None
1067
+ next_decoder_cache = () if use_cache else None
1068
+
1069
+ for idx, decoder_layer in enumerate(self.layers):
1070
+ if output_hidden_states:
1071
+ all_hidden_states += (hidden_states, )
1072
+
1073
+ past_key_value = past_key_values[
1074
+ idx] if past_key_values is not None else None
1075
+
1076
+ if self.gradient_checkpointing and self.training:
1077
+
1078
+ def create_custom_forward(module):
1079
+
1080
+ def custom_forward(*inputs):
1081
+ # None for past_key_value
1082
+ return module(*inputs, output_attentions, None,
1083
+ im_mask)
1084
+
1085
+ return custom_forward
1086
+
1087
+ layer_outputs = torch.utils.checkpoint.checkpoint(
1088
+ create_custom_forward(decoder_layer),
1089
+ hidden_states,
1090
+ attention_mask,
1091
+ position_ids,
1092
+ None,
1093
+ )
1094
+ else:
1095
+ layer_outputs = decoder_layer(
1096
+ hidden_states,
1097
+ attention_mask=attention_mask,
1098
+ position_ids=position_ids,
1099
+ past_key_value=past_key_value,
1100
+ output_attentions=output_attentions,
1101
+ use_cache=use_cache,
1102
+ im_mask=im_mask,
1103
+ )
1104
+
1105
+ hidden_states = layer_outputs[0]
1106
+
1107
+ if use_cache:
1108
+ next_decoder_cache += (
1109
+ layer_outputs[2 if output_attentions else 1], )
1110
+
1111
+ if output_attentions:
1112
+ all_self_attns += (layer_outputs[1], )
1113
+
1114
+ hidden_states = self.norm(hidden_states)
1115
+
1116
+ # add hidden states from the last decoder layer
1117
+ if output_hidden_states:
1118
+ all_hidden_states += (hidden_states, )
1119
+
1120
+ next_cache = next_decoder_cache if use_cache else None
1121
+ if not return_dict:
1122
+ return tuple(
1123
+ v for v in
1124
+ [hidden_states, next_cache, all_hidden_states, all_self_attns]
1125
+ if v is not None)
1126
+ return BaseModelOutputWithPast(
1127
+ last_hidden_state=hidden_states,
1128
+ past_key_values=next_cache,
1129
+ hidden_states=all_hidden_states,
1130
+ attentions=all_self_attns,
1131
+ )
model/internlm_xcomposer/modeling_internlm_xcomposer2.py ADDED
@@ -0,0 +1,759 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 InternLMXComposer2 model."""
20
+ import copy
21
+ import queue
22
+ import threading
23
+ from typing import List, Optional, Tuple, Union
24
+ import numpy as np
25
+ import torch
26
+ import torch.utils.checkpoint
27
+ from PIL import Image
28
+ from torch import nn
29
+ from torch.nn import CrossEntropyLoss
30
+ from torchvision import transforms
31
+ from torchvision.transforms.functional import InterpolationMode
32
+ from transformers.modeling_outputs import CausalLMOutputWithPast
33
+ from transformers.utils import (add_start_docstrings_to_model_forward,
34
+ replace_return_docstrings)
35
+ from torch.nn.utils.rnn import pad_sequence
36
+ from torch.nn import functional as F
37
+ try:
38
+ from transformers.generation.streamers import BaseStreamer
39
+ except: # noqa # pylint: disable=bare-except
40
+ BaseStreamer = None
41
+
42
+ from .build_mlp import build_vision_projector, build_vision_tower
43
+ from .configuration_internlm_xcomposer2 import InternLMXcomposer2Config
44
+ from .modeling_internlm2 import (InternLM2_INPUTS_DOCSTRING, InternLM2Model,
45
+ InternLM2PreTrainedModel)
46
+
47
+ _CONFIG_FOR_DOC = 'InternLMXcomposer2Config'
48
+
49
+
50
+ class InternLMXComposer2ForCausalLM(InternLM2PreTrainedModel):
51
+ _auto_class = 'AutoModelForCausalLM'
52
+
53
+ _tied_weights_keys = ['output.weight']
54
+
55
+ def __init__(self, config, use_caption=False):
56
+ super().__init__(config)
57
+ self.use_caption = use_caption
58
+ if self.use_caption:
59
+ init_logit_scale = np.log(1 / 0.07)
60
+ self.logit_scale = nn.Parameter(torch.ones([]) * init_logit_scale)
61
+ self.image_pool = self.use_caption.get('image_pool', 'avg')
62
+ self.text_pool = self.use_caption.get('text_pool', 'eot')
63
+ self.loss_type = self.use_caption.get('loss_type', 'con')
64
+ crossattn = self.use_caption.get('crossattn', False)
65
+ self.lambda_contrastloss = 0.01
66
+ print(' lambda : ', self.lambda_contrastloss, flush=True)
67
+ else:
68
+ crossattn = False ##### change to true for crossattn
69
+ print('cross_attn: ', crossattn, flush=True)
70
+ self.model = InternLM2Model(config, crossattn)
71
+ self.vocab_size = config.vocab_size
72
+ self.output = nn.Linear(
73
+ config.hidden_size, config.vocab_size, bias=False)
74
+ self.tokenizer = None
75
+
76
+ self.max_length = config.max_length
77
+ print(f'Set max length to {self.max_length}')
78
+ # Initialize weights and apply final processing
79
+ self.post_init()
80
+
81
+ self.vit = build_vision_tower()
82
+ self.vision_proj = build_vision_projector()
83
+
84
+ self.vis_processor = transforms.Compose([
85
+ transforms.Resize((config.img_size, config.img_size),
86
+ interpolation=InterpolationMode.BICUBIC),
87
+ transforms.ToTensor(),
88
+ transforms.Normalize((0.48145466, 0.4578275, 0.40821073),
89
+ (0.26862954, 0.26130258, 0.27577711)),
90
+ ])
91
+
92
+ def _set_gradient_checkpointing(self, module, value=False):
93
+ if isinstance(module, InternLM2Model):
94
+ module.gradient_checkpointing = value
95
+ if value:
96
+ self.vit.vision_tower.vision_model.encoder.gradient_checkpointing = value
97
+
98
+ def get_input_embeddings(self):
99
+ return self.model.tok_embeddings
100
+
101
+ def set_input_embeddings(self, value):
102
+ self.model.tok_embeddings = value
103
+
104
+ def get_output_embeddings(self):
105
+ return self.output
106
+
107
+ def set_output_embeddings(self, new_embeddings):
108
+ self.output = new_embeddings
109
+
110
+ def set_decoder(self, decoder):
111
+ self.model = decoder
112
+
113
+ def get_decoder(self):
114
+ return self.model
115
+
116
+ def encode_text(self, text, add_special_tokens=False):
117
+ token = self.tokenizer(
118
+ text, return_tensors='pt',
119
+ add_special_tokens=add_special_tokens).input_ids.to(self.device)
120
+ embs = self.model.tok_embeddings(token)
121
+ return embs
122
+
123
+ def encode_img(self, image):
124
+ if image is None:
125
+ return None
126
+ if isinstance(image, str):
127
+ image = Image.open(image).convert('RGB')
128
+ image = self.vis_processor(image).unsqueeze(0).to(self.device)
129
+ else:
130
+ assert isinstance(image, torch.Tensor)
131
+
132
+ img_embeds, atts_img, img_target = self.img2emb(image)
133
+ return img_embeds
134
+
135
+ def img2emb(self, image):
136
+ img_embeds = self.vision_proj(self.vit(image.to(self.device)))
137
+ atts_img = torch.ones(
138
+ img_embeds.size()[:-1], dtype=torch.long).to(img_embeds.device)
139
+
140
+ img_target = torch.ones(
141
+ img_embeds.size()[:2], dtype=torch.long).to(
142
+ img_embeds.device) * -100
143
+
144
+ return img_embeds, atts_img, img_target
145
+
146
+ def prompt_wrap(self, img_embeds, prompt):
147
+ batch_size = img_embeds.shape[0]
148
+ p_before, p_after = prompt.split('<ImageHere>')
149
+ p_before_tokens = self.tokenizer(
150
+ p_before, return_tensors='pt',
151
+ add_special_tokens=True).to(img_embeds.device)
152
+
153
+ p_before_embeds = self.model.tok_embeddings(
154
+ p_before_tokens.input_ids).expand(batch_size, -1, -1)
155
+ wrapped_img_embeds = torch.cat([p_before_embeds, img_embeds], dim=1)
156
+
157
+ wrapped_atts_img = torch.ones(
158
+ wrapped_img_embeds.size()[:-1],
159
+ dtype=torch.long).to(img_embeds.device)
160
+
161
+ wrapped_target = torch.ones(
162
+ batch_size, wrapped_img_embeds.shape[1], dtype=torch.long).to(
163
+ img_embeds.device) * -100
164
+
165
+ return wrapped_img_embeds, wrapped_atts_img, wrapped_target
166
+
167
+ def text2emb(self, text, add_special=False):
168
+ to_regress_tokens = self.tokenizer(
169
+ text,
170
+ return_tensors='pt',
171
+ padding='longest',
172
+ truncation=True,
173
+ max_length=self.max_length,
174
+ add_special_tokens=add_special).to(self.device)
175
+
176
+ targets = self.mask_human_targets(to_regress_tokens.input_ids)
177
+ targets = targets.to(self.device)
178
+ return to_regress_tokens, targets
179
+
180
+ def interleav_wrap_chat(self, tokenizer, query, image, history, meta_instruction):
181
+ prompt = ''
182
+ if meta_instruction:
183
+ prompt += f"""[UNUSED_TOKEN_146]system\n{meta_instruction}[UNUSED_TOKEN_145]\n"""
184
+ for record in history:
185
+ prompt += f"""[UNUSED_TOKEN_146]user\n{record[0]}[UNUSED_TOKEN_145]\n[UNUSED_TOKEN_146]assistant\n{record[1]}[UNUSED_TOKEN_145]\n"""
186
+ prompt += f"""[UNUSED_TOKEN_146]user\n{query}[UNUSED_TOKEN_145]\n[UNUSED_TOKEN_146]assistant\n"""
187
+
188
+ im_len = image.shape[1]
189
+ image_nums = len(image)
190
+ parts = prompt.split('<ImageHere>')
191
+ wrap_embeds, wrap_im_mask = [], []
192
+ temp_len = 0
193
+
194
+ if len(parts) != image_nums + 1:
195
+ raise ValueError('Invalid <ImageHere> prompt format.')
196
+
197
+ for idx, part in enumerate(parts):
198
+ if len(part) > 0:
199
+ part_tokens = tokenizer(part, return_tensors='pt').to(self.device)
200
+ part_embeds = self.model.tok_embeddings(
201
+ part_tokens.input_ids)
202
+ wrap_embeds.append(part_embeds)
203
+ wrap_im_mask.append(torch.zeros(part_embeds.shape[:2]))
204
+ temp_len += part_embeds.shape[1]
205
+ if idx < image_nums:
206
+ wrap_embeds.append(image[idx].unsqueeze(0))
207
+ wrap_im_mask.append(torch.ones(1, image[idx].shape[0]))
208
+ temp_len += im_len
209
+
210
+ if temp_len > self.max_length:
211
+ break
212
+
213
+ wrap_embeds = torch.cat(wrap_embeds, dim=1)
214
+ wrap_im_mask = torch.cat(wrap_im_mask, dim=1)
215
+ wrap_embeds = wrap_embeds[:, :self.max_length].to(self.device)
216
+ wrap_im_mask = wrap_im_mask[:, :self.max_length].to(self.device).bool()
217
+ inputs = {
218
+ 'inputs_embeds': wrap_embeds
219
+ }
220
+ return inputs, wrap_im_mask
221
+
222
+ def interleav_wrap(self, img_list, text_list):
223
+ wrap_embeds_list, wrap_atts_list, image_embeds_list = [], [], []
224
+ wrap_target_list, wrap_im_mask_list = [], []
225
+ for image, text in zip(img_list, text_list):
226
+ img_embeds, atts_img, img_target = self.img2emb(image)
227
+ text = text[0]
228
+ parts = text.split('<ImageHere>')
229
+ wrap_tokens, wrap_embeds, wrap_atts, wrap_im_mask = [], [], [], []
230
+ temp_len = 0
231
+ image_nums, im_len = img_embeds.shape[:2]
232
+ if image_nums > 1:
233
+ raise NotImplementedError
234
+ image_embeds_list.append(img_embeds)
235
+ need_bos = True
236
+ for idx, part in enumerate(parts):
237
+ if len(part) > 0:
238
+ part_tokens = self.tokenizer(
239
+ part,
240
+ return_tensors='pt',
241
+ padding='longest',
242
+ add_special_tokens=need_bos).to(self.device)
243
+ if need_bos:
244
+ need_bos = False
245
+ wrap_tokens.append(part_tokens.input_ids)
246
+ part_embeds = self.model.tok_embeddings(
247
+ part_tokens.input_ids)
248
+ wrap_embeds.append(part_embeds)
249
+ wrap_atts.append(part_tokens.attention_mask)
250
+ wrap_im_mask.append(
251
+ torch.zeros(part_embeds.shape[:2]).to(self.device))
252
+
253
+ temp_len += part_embeds.shape[1]
254
+ if idx < image_nums:
255
+ wrap_tokens.append(img_target[idx].unsqueeze(0))
256
+ wrap_embeds.append(img_embeds[idx].unsqueeze(0))
257
+ wrap_atts.append(atts_img[idx].unsqueeze(0))
258
+ wrap_im_mask.append(
259
+ torch.ones_like(atts_img[idx].unsqueeze(0)))
260
+
261
+ temp_len += im_len
262
+ if temp_len > self.max_length:
263
+ break
264
+
265
+
266
+ wrap_tokens = torch.cat(wrap_tokens, dim=1)
267
+ wrap_embeds = torch.cat(wrap_embeds, dim=1)
268
+ wrap_atts = torch.cat(wrap_atts, dim=1)
269
+ wrap_im_mask = torch.cat(wrap_im_mask, dim=1)
270
+
271
+ wrap_target = self.mask_human_targets(wrap_tokens).to(self.device)
272
+
273
+ wrap_embeds = wrap_embeds[:, :self.max_length].to(self.device)
274
+ wrap_atts = wrap_atts[:, :self.max_length].to(self.device)
275
+ wrap_target = wrap_target[:, :self.max_length].to(self.device)
276
+ wrap_im_mask = wrap_im_mask[:, :self.max_length].to(self.device)
277
+
278
+
279
+ ### change llj ### for single image -> len(img_list) == 1
280
+ if len(img_list) != 1:
281
+ wrap_embeds_list.append(wrap_embeds[0])
282
+ elif len(img_list) == 1:
283
+ wrap_embeds_list.append(wrap_embeds)
284
+ if len(wrap_atts.shape) == 2 and len(img_list) != 1:
285
+ wrap_atts_list.append(wrap_atts[0,:,None])
286
+ else:
287
+ wrap_atts_list.append(wrap_atts)
288
+ # wrap_atts_list.append(wrap_atts)
289
+ if len(wrap_target.shape) == 2 and len(img_list) != 1:
290
+ wrap_target_list.append(wrap_target[0,:,None])
291
+ else:
292
+ wrap_target_list.append(wrap_target)
293
+ # wrap_target_list.append(wrap_target)
294
+ if len(wrap_im_mask.shape) == 2 and len(img_list) != 1:
295
+ wrap_im_mask_list.append(wrap_im_mask[0,:,None])
296
+ else:
297
+ wrap_im_mask_list.append(wrap_im_mask)
298
+
299
+ #### change llj ####
300
+ if len(wrap_embeds_list) > 1:
301
+ wrap_embeds = pad_sequence(wrap_embeds_list, batch_first=True, padding_value=self.tokenizer.pad_token_id)
302
+ wrap_atts_list = pad_sequence(wrap_atts_list, batch_first=True, padding_value=0)
303
+ wrap_atts = wrap_atts_list.squeeze(2)
304
+ wrap_target_list = pad_sequence(wrap_target_list, batch_first=True, padding_value=-100)
305
+ wrap_target = wrap_target_list.squeeze(2)
306
+ wrap_im_mask_list = pad_sequence(wrap_im_mask_list, batch_first=True, padding_value=0)
307
+ wrap_im_mask = wrap_im_mask_list.squeeze(2)
308
+ else:
309
+ wrap_embeds = torch.cat(wrap_embeds_list)
310
+ wrap_atts = torch.cat(wrap_atts_list)
311
+ wrap_target = torch.cat(wrap_target_list)
312
+ wrap_im_mask = torch.cat(wrap_im_mask_list)
313
+ return wrap_embeds, wrap_atts, wrap_target, wrap_im_mask, torch.cat(image_embeds_list)
314
+
315
+ def mask_human_targets(self, input_ids, pure=False):
316
+ target_batch = []
317
+ for bs in range(input_ids.shape[0]):
318
+ ids = input_ids[bs]
319
+ targets = copy.deepcopy(ids)
320
+ end_count = 0
321
+ last_eoa = 0
322
+ for i, temp_id in enumerate(ids):
323
+ if temp_id == 92542:
324
+ if end_count % 2 == 0:
325
+ targets[last_eoa:i + 6] = -100
326
+ else:
327
+ last_eoa = i + 1
328
+ end_count += 1
329
+ # # eos and following pad
330
+ elif temp_id == 2:
331
+ # loss on eos, but not on pad
332
+ targets[i + 1:] = -100
333
+ break
334
+ # trunction, end at last question
335
+ if temp_id != 2 and end_count % 2 == 0:
336
+ # mask all after the last answer
337
+ targets[last_eoa + 1:] = -100
338
+ target_batch.append(targets.unsqueeze(0))
339
+ target_batch = torch.cat(target_batch, dim=0)
340
+ return target_batch
341
+
342
+ @add_start_docstrings_to_model_forward(InternLM2_INPUTS_DOCSTRING)
343
+ @replace_return_docstrings(
344
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
345
+ def forward(self,
346
+ input_ids: torch.LongTensor = None,
347
+ attention_mask: Optional[torch.Tensor] = None,
348
+ position_ids: Optional[torch.LongTensor] = None,
349
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
350
+ inputs_embeds: Optional[torch.FloatTensor] = None,
351
+ labels: Optional[torch.LongTensor] = None,
352
+ use_cache: Optional[bool] = None,
353
+ output_attentions: Optional[bool] = None,
354
+ output_hidden_states: Optional[bool] = None,
355
+ return_dict: Optional[bool] = None,
356
+ **kwargs) -> Union[Tuple, CausalLMOutputWithPast]:
357
+ r"""
358
+ Args:
359
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
360
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
361
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
362
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
363
+ Returns:
364
+ """
365
+
366
+ samples = kwargs.get('samples', None)
367
+ if samples:
368
+ if samples['data_type'][0] == 'text':
369
+ has_img = False
370
+ elif samples['data_type'][0] == 'multi':
371
+ has_img = True
372
+ else:
373
+ raise NotImplementedError
374
+
375
+ # encode text
376
+ text = samples['text_input']
377
+ # encode image
378
+ if has_img:
379
+ image = samples['image']
380
+ to_regress_embeds, attention_mask, targets, im_mask, img_embeds = self.interleav_wrap(
381
+ image, text)
382
+ else:
383
+ to_regress_tokens, targets = self.text2emb(
384
+ text, add_special=True)
385
+ to_regress_embeds = self.model.tok_embeddings(
386
+ to_regress_tokens.input_ids)
387
+ attention_mask = to_regress_tokens.attention_mask
388
+ im_mask = torch.zeros(to_regress_embeds.shape[:2]).cuda()
389
+
390
+ inputs_embeds = to_regress_embeds[:, :self.max_length]
391
+ attention_mask = attention_mask[:, :self.max_length]
392
+ targets = targets[:, :self.max_length]
393
+ im_mask = im_mask[:, :self.max_length].bool()
394
+ labels = targets
395
+ else:
396
+ im_mask = kwargs.get('im_mask', None)
397
+ if im_mask is None and inputs_embeds is not None:
398
+ im_mask = torch.zeros(inputs_embeds.shape[:2]).to(
399
+ inputs_embeds.device)
400
+ im_mask = im_mask.bool()
401
+
402
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
403
+ output_hidden_states = (
404
+ output_hidden_states if output_hidden_states is not None else
405
+ self.config.output_hidden_states)
406
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
407
+
408
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
409
+ outputs = self.model(
410
+ input_ids=input_ids,
411
+ attention_mask=attention_mask,
412
+ position_ids=position_ids,
413
+ past_key_values=past_key_values,
414
+ inputs_embeds=inputs_embeds,
415
+ use_cache=use_cache,
416
+ output_attentions=output_attentions,
417
+ output_hidden_states=output_hidden_states,
418
+ return_dict=return_dict,
419
+ im_mask=im_mask,
420
+ )
421
+
422
+ hidden_states = outputs[0]
423
+ logits = self.output(hidden_states)
424
+ logits = logits.float()
425
+
426
+ loss = None
427
+ if labels is not None:
428
+ # Shift so that tokens < n predict n
429
+ shift_logits = logits[..., :-1, :].contiguous()
430
+ shift_labels = labels[..., 1:].contiguous()
431
+ # Flatten the tokens
432
+ loss_fct = CrossEntropyLoss()
433
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
434
+ shift_labels = shift_labels.view(-1)
435
+ # Enable model parallelism
436
+ shift_labels = shift_labels.to(shift_logits.device)
437
+ loss = loss_fct(shift_logits, shift_labels)
438
+
439
+ if self.use_caption:
440
+ captions = samples['caption']
441
+ img_embeds = self.image_pooling(img_embeds)
442
+ caption_embeds_list = []
443
+ for idx, caption in enumerate(captions):
444
+ if not caption:
445
+ caption_embeds_list.append(img_embeds[idx].clone().unsqueeze(0).detach()) # fake loss
446
+ continue
447
+ tokens = self.tokenizer(
448
+ caption,
449
+ return_tensors='pt',
450
+ padding='longest',
451
+ add_special_tokens=False).to(self.device)
452
+ token_embed = self.model.tok_embeddings(tokens.input_ids)
453
+ token_embed = self.text_pooling(token_embed, tokens)
454
+ caption_embeds_list.append(token_embed)
455
+
456
+ caption_embeds_list = torch.cat(caption_embeds_list)
457
+ loss += self.lambda_contrastloss * self.get_supp_loss(img_embeds, caption_embeds_list)
458
+
459
+
460
+ if not return_dict:
461
+ output = (logits, ) + outputs[1:]
462
+ return (loss, ) + output if loss is not None else output
463
+
464
+ return CausalLMOutputWithPast(
465
+ loss=loss,
466
+ logits=logits,
467
+ past_key_values=outputs.past_key_values,
468
+ hidden_states=outputs.hidden_states,
469
+ attentions=outputs.attentions,
470
+ )
471
+
472
+ def image_pooling(self, img_embeds):
473
+ # B, N, C
474
+ if self.image_pool == 'avg':
475
+ return img_embeds[:, 1:].mean(dim=1)
476
+ else:
477
+ raise NotImplementedError
478
+
479
+ def text_pooling(self, token_embed, tokens):
480
+ # 1, N, C
481
+ if self.text_pool == 'eot':
482
+ return token_embed[torch.arange(token_embed.shape[0]), tokens.input_ids.argmax(dim=-1)] # eot pooling
483
+ elif self.text_pool == 'avg':
484
+ return token_embed[:, :].mean(dim=1)
485
+ else:
486
+ raise NotImplementedError
487
+
488
+ def get_ground_truth(self, device, num_logits) -> torch.Tensor:
489
+ labels = torch.arange(num_logits, device=device, dtype=torch.long)
490
+ return labels
491
+
492
+ def get_logits(self, image_features, text_features):
493
+
494
+ return logits_per_image, logits_per_text
495
+
496
+ def contrastive_loss(self, image_features, text_features, device):
497
+ logits_per_image = self.logit_scale * image_features @ text_features.T
498
+ logits_per_text = self.logit_scale * text_features @ image_features.T
499
+ labels = torch.arange(logits_per_image.shape[0], device=device, dtype=torch.long)
500
+ loss = (
501
+ F.cross_entropy(logits_per_image, labels) +
502
+ F.cross_entropy(logits_per_text, labels)
503
+ ) / 2
504
+ return loss
505
+
506
+ def get_supp_loss(self, image_features, text_features):
507
+ image_features = F.normalize(image_features, dim=-1)
508
+ text_features = F.normalize(text_features, dim=-1)
509
+ device = image_features.device
510
+ if self.loss_type == 'con':
511
+ return self.contrastive_loss(image_features, text_features, device)
512
+ else:
513
+ raise NotImplementedError
514
+
515
+ def prepare_inputs_for_generation(self,
516
+ input_ids,
517
+ past_key_values=None,
518
+ attention_mask=None,
519
+ inputs_embeds=None,
520
+ im_mask=None,
521
+ **kwargs):
522
+ if past_key_values is not None:
523
+ past_length = past_key_values[0][0].shape[2]
524
+
525
+ # Some generation methods already pass only the last input ID
526
+ if input_ids.shape[1] > past_length:
527
+ remove_prefix_length = past_length
528
+ else:
529
+ # Default to old behavior: keep only final ID
530
+ remove_prefix_length = input_ids.shape[1] - 1
531
+
532
+ input_ids = input_ids[:, remove_prefix_length:]
533
+
534
+ position_ids = kwargs.get('position_ids', None)
535
+ if attention_mask is not None and position_ids is None:
536
+ # create position_ids on the fly for batch generation
537
+ position_ids = attention_mask.long().cumsum(-1) - 1
538
+ position_ids.masked_fill_(attention_mask == 0, 1)
539
+ if past_key_values:
540
+ position_ids = position_ids[:, -input_ids.shape[1]:]
541
+
542
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
543
+ if inputs_embeds is not None and past_key_values is None:
544
+ model_inputs = {'inputs_embeds': inputs_embeds}
545
+ else:
546
+ model_inputs = {'input_ids': input_ids}
547
+
548
+ im_mask = im_mask
549
+
550
+ model_inputs.update({
551
+ 'position_ids': position_ids,
552
+ 'past_key_values': past_key_values,
553
+ 'use_cache': kwargs.get('use_cache'),
554
+ 'attention_mask': attention_mask,
555
+ 'im_mask': im_mask,
556
+ })
557
+ return model_inputs
558
+
559
+ @staticmethod
560
+ def _reorder_cache(past_key_values, beam_idx):
561
+ reordered_past = ()
562
+ for layer_past in past_key_values:
563
+ reordered_past += (tuple(
564
+ past_state.index_select(0, beam_idx.to(past_state.device))
565
+ for past_state in layer_past), )
566
+ return reordered_past
567
+
568
+ def build_inputs(self,
569
+ tokenizer,
570
+ query: str,
571
+ history: List[Tuple[str, str]] = [],
572
+ meta_instruction=''):
573
+ prompt = ''
574
+ if meta_instruction:
575
+ prompt += f"""<s>[UNUSED_TOKEN_146]system\n{meta_instruction}[UNUSED_TOKEN_145]\n"""
576
+ else:
577
+ prompt += '<s>'
578
+ for record in history:
579
+ prompt += f"""[UNUSED_TOKEN_146]user\n{record[0]}[UNUSED_TOKEN_145]\n[UNUSED_TOKEN_146]assistant\n{record[1]}[UNUSED_TOKEN_145]\n"""
580
+ prompt += f"""[UNUSED_TOKEN_146]user\n{query}[UNUSED_TOKEN_145]\n[UNUSED_TOKEN_146]assistant\n"""
581
+ return tokenizer([prompt], return_tensors='pt')
582
+
583
+ @torch.no_grad()
584
+ def my_chat(
585
+ self,
586
+ tokenizer,
587
+ query: str,
588
+ image: torch.Tensor = None,
589
+ history: List[Tuple[str, str]] = [],
590
+ streamer: Optional[BaseStreamer] = None,
591
+ max_new_tokens: int = 1024,
592
+ do_sample: bool = True,
593
+ temperature: float = 1.0,
594
+ top_p: float = 0.8,
595
+ repetition_penalty: float=1.005,
596
+ meta_instruction:
597
+ str = 'You are an AI assistant whose name is InternLM-XComposer (浦语·灵笔).\n'
598
+ '- 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'
599
+ '- InternLM-XComposer (浦语·灵笔) can understand and communicate fluently in the language chosen by the user such as English and 中文.\n'
600
+ '- InternLM-XComposer (浦语·灵笔) is capable of comprehending and articulating responses effectively based on the provided image.',
601
+ **kwargs,
602
+ ):
603
+ if image is None:
604
+ inputs = self.build_inputs(tokenizer, query, history, meta_instruction)
605
+ im_mask = torch.zeros(inputs['input_ids'].shape[:2]).cuda().bool()
606
+ else:
607
+ image = self.encode_img(image)
608
+ inputs, im_mask = self.interleav_wrap_chat(tokenizer, query, image, history, meta_instruction)
609
+ inputs = {
610
+ k: v.to(self.device)
611
+ for k, v in inputs.items() if torch.is_tensor(v)
612
+ }
613
+ # also add end-of-assistant token in eos token id to avoid unnecessary generation
614
+ eos_token_id = [
615
+ tokenizer.eos_token_id,
616
+ tokenizer.convert_tokens_to_ids(['[UNUSED_TOKEN_145]'])[0]
617
+ ]
618
+
619
+ my_output = self.forward(**inputs, output_attentions=True)
620
+
621
+ return my_output, im_mask
622
+
623
+ @torch.no_grad()
624
+ def chat(
625
+ self,
626
+ tokenizer,
627
+ query: str,
628
+ image: torch.Tensor = None,
629
+ history: List[Tuple[str, str]] = [],
630
+ streamer: Optional[BaseStreamer] = None,
631
+ max_new_tokens: int = 1024,
632
+ do_sample: bool = True,
633
+ temperature: float = 1.0,
634
+ top_p: float = 0.8,
635
+ repetition_penalty: float=1.005,
636
+ meta_instruction:
637
+ str = 'You are an AI assistant whose name is InternLM-XComposer (浦语·灵笔).\n'
638
+ '- 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'
639
+ '- InternLM-XComposer (浦语·灵笔) can understand and communicate fluently in the language chosen by the user such as English and 中文.\n'
640
+ '- InternLM-XComposer (浦语·灵笔) is capable of comprehending and articulating responses effectively based on the provided image.',
641
+ **kwargs,
642
+ ):
643
+ if image is None:
644
+ inputs = self.build_inputs(tokenizer, query, history, meta_instruction)
645
+ im_mask = torch.zeros(inputs['input_ids'].shape[:2]).cuda().bool()
646
+ else:
647
+ image = self.encode_img(image)
648
+ inputs, im_mask = self.interleav_wrap_chat(tokenizer, query, image, history, meta_instruction)
649
+ inputs = {
650
+ k: v.to(self.device)
651
+ for k, v in inputs.items() if torch.is_tensor(v)
652
+ }
653
+ # also add end-of-assistant token in eos token id to avoid unnecessary generation
654
+ eos_token_id = [
655
+ tokenizer.eos_token_id,
656
+ tokenizer.convert_tokens_to_ids(['[UNUSED_TOKEN_145]'])[0]
657
+ ]
658
+ outputs = self.generate(
659
+ **inputs,
660
+ streamer=streamer,
661
+ max_new_tokens=max_new_tokens,
662
+ do_sample=do_sample,
663
+ temperature=temperature,
664
+ top_p=top_p,
665
+ eos_token_id=eos_token_id,
666
+ repetition_penalty=repetition_penalty,
667
+ im_mask=im_mask,
668
+ **kwargs,
669
+ )
670
+ if image is None:
671
+ outputs = outputs[0].cpu().tolist()[len(inputs['input_ids'][0]):]
672
+ else:
673
+ outputs = outputs[0].cpu().tolist()
674
+ response = tokenizer.decode(outputs, skip_special_tokens=True)
675
+ response = response.split('[UNUSED_TOKEN_145]')[0]
676
+ history = history + [(query, response)]
677
+ return response, history
678
+
679
+ @torch.no_grad()
680
+ def stream_chat(
681
+ self,
682
+ tokenizer,
683
+ query: str,
684
+ history: List[Tuple[str, str]] = [],
685
+ max_new_tokens: int = 1024,
686
+ do_sample: bool = True,
687
+ temperature: float = 0.8,
688
+ top_p: float = 0.8,
689
+ **kwargs,
690
+ ):
691
+ """Return a generator in format: (response, history) Eg.
692
+
693
+ ('你好,有什么可以帮助您的吗', [('你好', '你好,有什么可以帮助您的吗')]) ('你好,有什么可以帮助您的吗?', [('你好',
694
+ '你好,有什么可以帮助您的吗?')])
695
+ """
696
+ if BaseStreamer is None:
697
+ raise ModuleNotFoundError(
698
+ 'The version of `transformers` is too low. Please make sure '
699
+ 'that you have installed `transformers>=4.28.0`.')
700
+
701
+ response_queue = queue.Queue(maxsize=20)
702
+
703
+ class ChatStreamer(BaseStreamer):
704
+
705
+ def __init__(self, tokenizer) -> None:
706
+ super().__init__()
707
+ self.tokenizer = tokenizer
708
+ self.queue = response_queue
709
+ self.query = query
710
+ self.history = history
711
+ self.response = ''
712
+ self.received_inputs = False
713
+ self.queue.put(
714
+ (self.response, history + [(self.query, self.response)]))
715
+
716
+ def put(self, value):
717
+ if len(value.shape) > 1 and value.shape[0] > 1:
718
+ raise ValueError('ChatStreamer only supports batch size 1')
719
+ elif len(value.shape) > 1:
720
+ value = value[0]
721
+
722
+ if not self.received_inputs:
723
+ # The first received value is input_ids, ignore here
724
+ self.received_inputs = True
725
+ return
726
+
727
+ token = self.tokenizer.decode([value[-1]],
728
+ skip_special_tokens=True)
729
+ if token.strip() != '[UNUSED_TOKEN_145]':
730
+ self.response = self.response + token
731
+ history = self.history + [(self.query, self.response)]
732
+ self.queue.put((self.response, history))
733
+
734
+ def end(self):
735
+ self.queue.put(None)
736
+
737
+ def stream_producer():
738
+ return self.chat(
739
+ tokenizer=tokenizer,
740
+ query=query,
741
+ streamer=ChatStreamer(tokenizer=tokenizer),
742
+ history=history,
743
+ max_new_tokens=max_new_tokens,
744
+ do_sample=do_sample,
745
+ temperature=temperature,
746
+ top_p=top_p,
747
+ **kwargs,
748
+ )
749
+
750
+ def consumer():
751
+ producer = threading.Thread(target=stream_producer)
752
+ producer.start()
753
+ while True:
754
+ res = response_queue.get()
755
+ if res is None:
756
+ return
757
+ yield res
758
+
759
+ return consumer()
model/internlm_xcomposer/tokenization_internlm_xcomposer2.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Tokenization classes for IntermLM."""
20
+ import os
21
+ from shutil import copyfile
22
+ from typing import Any, Dict, List, Optional, Tuple
23
+
24
+ import sentencepiece as spm
25
+ from transformers.tokenization_utils import PreTrainedTokenizer
26
+ from transformers.utils import logging
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+ VOCAB_FILES_NAMES = {'vocab_file': './tokenizer.model'}
31
+
32
+ PRETRAINED_VOCAB_FILES_MAP = {}
33
+
34
+
35
+ class InternLMXComposer2Tokenizer(PreTrainedTokenizer):
36
+ """Construct a InternLM tokenizer. Based on byte-level Byte-Pair-Encoding.
37
+
38
+ Args:
39
+ vocab_file (`str`):
40
+ Path to the vocabulary file.
41
+ """
42
+
43
+ vocab_files_names = VOCAB_FILES_NAMES
44
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
45
+ model_input_names = ['input_ids', 'attention_mask']
46
+ _auto_class = 'AutoTokenizer'
47
+
48
+ def __init__(
49
+ self,
50
+ vocab_file,
51
+ unk_token='<unk>',
52
+ bos_token='<s>',
53
+ eos_token='</s>',
54
+ pad_token='</s>',
55
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
56
+ add_bos_token=True,
57
+ add_eos_token=False,
58
+ decode_with_prefix_space=False,
59
+ clean_up_tokenization_spaces=False,
60
+ **kwargs,
61
+ ):
62
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
63
+ self.vocab_file = vocab_file
64
+ self.add_bos_token = add_bos_token
65
+ self.add_eos_token = add_eos_token
66
+ self.decode_with_prefix_space = decode_with_prefix_space
67
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
68
+ self.sp_model.Load(vocab_file)
69
+ self._no_prefix_space_tokens = None
70
+ super().__init__(
71
+ bos_token=bos_token,
72
+ eos_token=eos_token,
73
+ unk_token=unk_token,
74
+ pad_token=pad_token,
75
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
76
+ **kwargs,
77
+ )
78
+ """ Initialization"""
79
+
80
+ @property
81
+ def no_prefix_space_tokens(self):
82
+ if self._no_prefix_space_tokens is None:
83
+ vocab = self.convert_ids_to_tokens(list(range(self.vocab_size)))
84
+ self._no_prefix_space_tokens = {
85
+ i
86
+ for i, tok in enumerate(vocab) if not tok.startswith('▁')
87
+ }
88
+ return self._no_prefix_space_tokens
89
+
90
+ @property
91
+ def vocab_size(self):
92
+ """Returns vocab size."""
93
+ return self.sp_model.get_piece_size()
94
+
95
+ @property
96
+ def bos_token_id(self) -> Optional[int]:
97
+ return self.sp_model.bos_id()
98
+
99
+ @property
100
+ def eos_token_id(self) -> Optional[int]:
101
+ return self.sp_model.eos_id()
102
+
103
+ def get_vocab(self):
104
+ """Returns vocab as a dict."""
105
+ vocab = {
106
+ self.convert_ids_to_tokens(i): i
107
+ for i in range(self.vocab_size)
108
+ }
109
+ vocab.update(self.added_tokens_encoder)
110
+ return vocab
111
+
112
+ def _tokenize(self, text):
113
+ """Returns a tokenized string."""
114
+ return self.sp_model.encode(text, out_type=str)
115
+
116
+ def _convert_token_to_id(self, token):
117
+ """Converts a token (str) in an id using the vocab."""
118
+ return self.sp_model.piece_to_id(token)
119
+
120
+ def _convert_id_to_token(self, index):
121
+ """Converts an index (integer) in a token (str) using the vocab."""
122
+ token = self.sp_model.IdToPiece(index)
123
+ return token
124
+
125
+ def _maybe_add_prefix_space(self, tokens, decoded):
126
+ if tokens and tokens[0] not in self.no_prefix_space_tokens:
127
+ return ' ' + decoded
128
+ else:
129
+ return decoded
130
+
131
+ def convert_tokens_to_string(self, tokens):
132
+ """Converts a sequence of tokens (string) in a single string."""
133
+ current_sub_tokens = []
134
+ out_string = ''
135
+ prev_is_special = False
136
+ for token in tokens:
137
+ # make sure that special tokens are not decoded using sentencepiece model
138
+ if token in self.all_special_tokens:
139
+ if not prev_is_special:
140
+ out_string += ' '
141
+ out_string += self.sp_model.decode(current_sub_tokens) + token
142
+ prev_is_special = True
143
+ current_sub_tokens = []
144
+ else:
145
+ current_sub_tokens.append(token)
146
+ prev_is_special = False
147
+ out_string += self.sp_model.decode(current_sub_tokens)
148
+ out_string = self.clean_up_tokenization(out_string)
149
+ out_string = self._maybe_add_prefix_space(
150
+ tokens=tokens, decoded=out_string)
151
+ return out_string[1:]
152
+
153
+ def save_vocabulary(self,
154
+ save_directory,
155
+ filename_prefix: Optional[str] = None) -> Tuple[str]:
156
+ """Save the vocabulary and special tokens file to a directory.
157
+
158
+ Args:
159
+ save_directory (`str`):
160
+ The directory in which to save the vocabulary.
161
+
162
+ Returns:
163
+ `Tuple(str)`: Paths to the files saved.
164
+ """
165
+ if not os.path.isdir(save_directory):
166
+ logger.error(
167
+ f'Vocabulary path ({save_directory}) should be a directory')
168
+ return
169
+ out_vocab_file = os.path.join(
170
+ save_directory,
171
+ (filename_prefix + '-' if filename_prefix else '') +
172
+ VOCAB_FILES_NAMES['vocab_file'])
173
+
174
+ if os.path.abspath(self.vocab_file) != os.path.abspath(
175
+ out_vocab_file) and os.path.isfile(self.vocab_file):
176
+ copyfile(self.vocab_file, out_vocab_file)
177
+ elif not os.path.isfile(self.vocab_file):
178
+ with open(out_vocab_file, 'wb') as fi:
179
+ content_spiece_model = self.sp_model.serialized_model_proto()
180
+ fi.write(content_spiece_model)
181
+
182
+ return (out_vocab_file, )
183
+
184
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
185
+ if self.add_bos_token:
186
+ bos_token_ids = [self.bos_token_id]
187
+ else:
188
+ bos_token_ids = []
189
+
190
+ output = bos_token_ids + token_ids_0
191
+
192
+ if token_ids_1 is not None:
193
+ output = output + token_ids_1
194
+
195
+ if self.add_eos_token:
196
+ output = output + [self.eos_token_id]
197
+
198
+ return output
199
+
200
+ def get_special_tokens_mask(
201
+ self,
202
+ token_ids_0: List[int],
203
+ token_ids_1: Optional[List[int]] = None,
204
+ already_has_special_tokens: bool = False) -> List[int]:
205
+ """Retrieve sequence ids from a token list that has no special tokens
206
+ added. This method is called when adding special tokens using the
207
+ tokenizer `prepare_for_model` method.
208
+
209
+ Args:
210
+ token_ids_0 (`List[int]`):
211
+ List of IDs.
212
+ token_ids_1 (`List[int]`, *optional*):
213
+ Optional second list of IDs for sequence pairs.
214
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
215
+ Whether or not the token list is already formatted with special tokens for the model.
216
+
217
+ Returns:
218
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
219
+ """
220
+ if already_has_special_tokens:
221
+ return super().get_special_tokens_mask(
222
+ token_ids_0=token_ids_0,
223
+ token_ids_1=token_ids_1,
224
+ already_has_special_tokens=True)
225
+
226
+ if token_ids_1 is None:
227
+ return [1] + ([0] * len(token_ids_0)) + [1]
228
+ return [1] + ([0] * len(token_ids_0)) + [1, 1] + (
229
+ [0] * len(token_ids_1)) + [1]
230
+
231
+ def create_token_type_ids_from_sequences(
232
+ self,
233
+ token_ids_0: List[int],
234
+ token_ids_1: Optional[List[int]] = None) -> List[int]:
235
+ """Create a mask from the two sequences passed to be used in a
236
+ sequence-pair classification task. T5 does not make use of token type
237
+ ids, therefore a list of zeros is returned.
238
+
239
+ Args:
240
+ token_ids_0 (`List[int]`):
241
+ List of IDs.
242
+ token_ids_1 (`List[int]`, *optional*):
243
+ Optional second list of IDs for sequence pairs.
244
+
245
+ Returns:
246
+ `List[int]`: List of zeros.
247
+ """
248
+ eos = [self.eos_token_id]
249
+
250
+ if token_ids_1 is None:
251
+ return len(token_ids_0 + eos) * [0]
252
+ return len(token_ids_0 + eos + token_ids_1 + eos) * [0]
model/internlm_xcomposer/zero_to_fp32.py ADDED
@@ -0,0 +1,587 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright (c) Microsoft Corporation.
4
+ # SPDX-License-Identifier: Apache-2.0
5
+
6
+ # DeepSpeed Team
7
+
8
+ # This script extracts fp32 consolidated weights from a zero 1, 2 and 3 DeepSpeed checkpoints. It gets
9
+ # copied into the top level checkpoint dir, so the user can easily do the conversion at any point in
10
+ # the future. Once extracted, the weights don't require DeepSpeed and can be used in any
11
+ # application.
12
+ #
13
+ # example: python zero_to_fp32.py . pytorch_model.bin
14
+
15
+ import argparse
16
+ import torch
17
+ import glob
18
+ import math
19
+ import os
20
+ import re
21
+ from collections import OrderedDict
22
+ from dataclasses import dataclass
23
+
24
+ # while this script doesn't use deepspeed to recover data, since the checkpoints are pickled with
25
+ # DeepSpeed data structures it has to be available in the current python environment.
26
+ from deepspeed.utils import logger
27
+ from deepspeed.checkpoint.constants import (DS_VERSION, OPTIMIZER_STATE_DICT, SINGLE_PARTITION_OF_FP32_GROUPS,
28
+ FP32_FLAT_GROUPS, ZERO_STAGE, PARTITION_COUNT, PARAM_SHAPES, BUFFER_NAMES,
29
+ FROZEN_PARAM_SHAPES, FROZEN_PARAM_FRAGMENTS)
30
+
31
+
32
+ @dataclass
33
+ class zero_model_state:
34
+ buffers: dict()
35
+ param_shapes: dict()
36
+ shared_params: list
37
+ ds_version: int
38
+ frozen_param_shapes: dict()
39
+ frozen_param_fragments: dict()
40
+
41
+
42
+ debug = 0
43
+
44
+ # load to cpu
45
+ device = torch.device('cpu')
46
+
47
+
48
+ def atoi(text):
49
+ return int(text) if text.isdigit() else text
50
+
51
+
52
+ def natural_keys(text):
53
+ '''
54
+ alist.sort(key=natural_keys) sorts in human order
55
+ http://nedbatchelder.com/blog/200712/human_sorting.html
56
+ (See Toothy's implementation in the comments)
57
+ '''
58
+ return [atoi(c) for c in re.split(r'(\d+)', text)]
59
+
60
+
61
+ def get_model_state_file(checkpoint_dir, zero_stage):
62
+ if not os.path.isdir(checkpoint_dir):
63
+ raise FileNotFoundError(f"Directory '{checkpoint_dir}' doesn't exist")
64
+
65
+ # there should be only one file
66
+ if zero_stage <= 2:
67
+ file = os.path.join(checkpoint_dir, "mp_rank_00_model_states.pt")
68
+ elif zero_stage == 3:
69
+ file = os.path.join(checkpoint_dir, "zero_pp_rank_0_mp_rank_00_model_states.pt")
70
+
71
+ if not os.path.exists(file):
72
+ raise FileNotFoundError(f"can't find model states file at '{file}'")
73
+
74
+ return file
75
+
76
+
77
+ def get_checkpoint_files(checkpoint_dir, glob_pattern):
78
+ # XXX: need to test that this simple glob rule works for multi-node setup too
79
+ ckpt_files = sorted(glob.glob(os.path.join(checkpoint_dir, glob_pattern)), key=natural_keys)
80
+
81
+ if len(ckpt_files) == 0:
82
+ raise FileNotFoundError(f"can't find {glob_pattern} files in directory '{checkpoint_dir}'")
83
+
84
+ return ckpt_files
85
+
86
+
87
+ def get_optim_files(checkpoint_dir):
88
+ return get_checkpoint_files(checkpoint_dir, "*_optim_states.pt")
89
+
90
+
91
+ def get_model_state_files(checkpoint_dir):
92
+ return get_checkpoint_files(checkpoint_dir, "*_model_states.pt")
93
+
94
+
95
+ def parse_model_states(files):
96
+ zero_model_states = []
97
+ for file in files:
98
+ state_dict = torch.load(file, map_location=device)
99
+
100
+ if BUFFER_NAMES not in state_dict:
101
+ raise ValueError(f"{file} is not a model state checkpoint")
102
+ buffer_names = state_dict[BUFFER_NAMES]
103
+ if debug:
104
+ print("Found buffers:", buffer_names)
105
+
106
+ # recover just the buffers while restoring them to fp32 if they were saved in fp16
107
+ buffers = {k: v.float() for k, v in state_dict["module"].items() if k in buffer_names}
108
+ param_shapes = state_dict[PARAM_SHAPES]
109
+
110
+ # collect parameters that are included in param_shapes
111
+ param_names = []
112
+ for s in param_shapes:
113
+ for name in s.keys():
114
+ param_names.append(name)
115
+
116
+ # update with frozen parameters
117
+ frozen_param_shapes = state_dict.get(FROZEN_PARAM_SHAPES, None)
118
+ if frozen_param_shapes is not None:
119
+ if debug:
120
+ print(f"Found frozen_param_shapes: {frozen_param_shapes}")
121
+ param_names += list(frozen_param_shapes.keys())
122
+
123
+ # handle shared params
124
+ shared_params = [[k, v] for k, v in state_dict["shared_params"].items()]
125
+
126
+ ds_version = state_dict.get(DS_VERSION, None)
127
+
128
+ frozen_param_fragments = state_dict.get(FROZEN_PARAM_FRAGMENTS, None)
129
+
130
+ z_model_state = zero_model_state(buffers=buffers,
131
+ param_shapes=param_shapes,
132
+ shared_params=shared_params,
133
+ ds_version=ds_version,
134
+ frozen_param_shapes=frozen_param_shapes,
135
+ frozen_param_fragments=frozen_param_fragments)
136
+ zero_model_states.append(z_model_state)
137
+
138
+ return zero_model_states
139
+
140
+
141
+ def parse_optim_states(files, ds_checkpoint_dir):
142
+
143
+ total_files = len(files)
144
+ state_dicts = []
145
+ for f in files:
146
+ state_dict = torch.load(f, map_location=device)
147
+ # immediately discard the potentially huge 2 optimizer states as we only care for fp32 master weights
148
+ # and also handle the case where it was already removed by another helper script
149
+ state_dict["optimizer_state_dict"].pop("optimizer_state_dict", None)
150
+ state_dicts.append(state_dict)
151
+
152
+ if not ZERO_STAGE in state_dicts[0][OPTIMIZER_STATE_DICT]:
153
+ raise ValueError(f"{files[0]} is not a zero checkpoint")
154
+ zero_stage = state_dicts[0][OPTIMIZER_STATE_DICT][ZERO_STAGE]
155
+ world_size = state_dicts[0][OPTIMIZER_STATE_DICT][PARTITION_COUNT]
156
+
157
+ # For ZeRO-2 each param group can have different partition_count as data parallelism for expert
158
+ # parameters can be different from data parallelism for non-expert parameters. So we can just
159
+ # use the max of the partition_count to get the dp world_size.
160
+
161
+ if type(world_size) is list:
162
+ world_size = max(world_size)
163
+
164
+ if world_size != total_files:
165
+ raise ValueError(
166
+ f"Expected {world_size} of '*_optim_states.pt' under '{ds_checkpoint_dir}' but found {total_files} files. "
167
+ "Possibly due to an overwrite of an old checkpoint, or a checkpoint didn't get saved by one or more processes."
168
+ )
169
+
170
+ # the groups are named differently in each stage
171
+ if zero_stage <= 2:
172
+ fp32_groups_key = SINGLE_PARTITION_OF_FP32_GROUPS
173
+ elif zero_stage == 3:
174
+ fp32_groups_key = FP32_FLAT_GROUPS
175
+ else:
176
+ raise ValueError(f"unknown zero stage {zero_stage}")
177
+
178
+ if zero_stage <= 2:
179
+ fp32_flat_groups = [state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key] for i in range(len(state_dicts))]
180
+ elif zero_stage == 3:
181
+ # if there is more than one param group, there will be multiple flattened tensors - one
182
+ # flattened tensor per group - for simplicity merge them into a single tensor
183
+ #
184
+ # XXX: could make the script more memory efficient for when there are multiple groups - it
185
+ # will require matching the sub-lists of param_shapes for each param group flattened tensor
186
+
187
+ fp32_flat_groups = [
188
+ torch.cat(state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key], 0) for i in range(len(state_dicts))
189
+ ]
190
+
191
+ return zero_stage, world_size, fp32_flat_groups
192
+
193
+
194
+ def _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir):
195
+ """
196
+ Returns fp32 state_dict reconstructed from ds checkpoint
197
+
198
+ Args:
199
+ - ``ds_checkpoint_dir``: path to the deepspeed checkpoint folder (where the optimizer files are)
200
+
201
+ """
202
+ print(f"Processing zero checkpoint '{ds_checkpoint_dir}'")
203
+
204
+ optim_files = get_optim_files(ds_checkpoint_dir)
205
+ zero_stage, world_size, fp32_flat_groups = parse_optim_states(optim_files, ds_checkpoint_dir)
206
+ print(f"Detected checkpoint of type zero stage {zero_stage}, world_size: {world_size}")
207
+
208
+ model_files = get_model_state_files(ds_checkpoint_dir)
209
+
210
+ zero_model_states = parse_model_states(model_files)
211
+ print(f'Parsing checkpoint created by deepspeed=={zero_model_states[0].ds_version}')
212
+
213
+ if zero_stage <= 2:
214
+ return _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states)
215
+ elif zero_stage == 3:
216
+ return _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states)
217
+
218
+
219
+ def _zero2_merge_frozen_params(state_dict, zero_model_states):
220
+ if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
221
+ return
222
+
223
+ frozen_param_shapes = zero_model_states[0].frozen_param_shapes
224
+ frozen_param_fragments = zero_model_states[0].frozen_param_fragments
225
+
226
+ if debug:
227
+ num_elem = sum(s.numel() for s in frozen_param_shapes.values())
228
+ print(f'rank 0: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
229
+
230
+ wanted_params = len(frozen_param_shapes)
231
+ wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
232
+ avail_numel = sum([p.numel() for p in frozen_param_fragments.values()])
233
+ print(f'Frozen params: Have {avail_numel} numels to process.')
234
+ print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
235
+
236
+ total_params = 0
237
+ total_numel = 0
238
+ for name, shape in frozen_param_shapes.items():
239
+ total_params += 1
240
+ unpartitioned_numel = shape.numel()
241
+ total_numel += unpartitioned_numel
242
+
243
+ state_dict[name] = frozen_param_fragments[name]
244
+
245
+ if debug:
246
+ print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
247
+
248
+ print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
249
+
250
+
251
+ def _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
252
+ param_shapes = zero_model_states[0].param_shapes
253
+
254
+ # Reconstruction protocol:
255
+ #
256
+ # XXX: document this
257
+
258
+ if debug:
259
+ for i in range(world_size):
260
+ for j in range(len(fp32_flat_groups[0])):
261
+ print(f"{FP32_FLAT_GROUPS}[{i}][{j}].shape={fp32_flat_groups[i][j].shape}")
262
+
263
+ # XXX: memory usage doubles here (zero2)
264
+ num_param_groups = len(fp32_flat_groups[0])
265
+ merged_single_partition_of_fp32_groups = []
266
+ for i in range(num_param_groups):
267
+ merged_partitions = [sd[i] for sd in fp32_flat_groups]
268
+ full_single_fp32_vector = torch.cat(merged_partitions, 0)
269
+ merged_single_partition_of_fp32_groups.append(full_single_fp32_vector)
270
+ avail_numel = sum(
271
+ [full_single_fp32_vector.numel() for full_single_fp32_vector in merged_single_partition_of_fp32_groups])
272
+
273
+ if debug:
274
+ wanted_params = sum([len(shapes) for shapes in param_shapes])
275
+ wanted_numel = sum([sum(shape.numel() for shape in shapes.values()) for shapes in param_shapes])
276
+ # not asserting if there is a mismatch due to possible padding
277
+ print(f"Have {avail_numel} numels to process.")
278
+ print(f"Need {wanted_numel} numels in {wanted_params} params.")
279
+
280
+ # params
281
+ # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
282
+ # out-of-core computing solution
283
+ total_numel = 0
284
+ total_params = 0
285
+ for shapes, full_single_fp32_vector in zip(param_shapes, merged_single_partition_of_fp32_groups):
286
+ offset = 0
287
+ avail_numel = full_single_fp32_vector.numel()
288
+ for name, shape in shapes.items():
289
+
290
+ unpartitioned_numel = shape.numel()
291
+ total_numel += unpartitioned_numel
292
+ total_params += 1
293
+
294
+ if debug:
295
+ print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
296
+ state_dict[name] = full_single_fp32_vector.narrow(0, offset, unpartitioned_numel).view(shape)
297
+ offset += unpartitioned_numel
298
+
299
+ # Z2 started to align to 2*world_size to improve nccl performance. Therefore both offset and
300
+ # avail_numel can differ by anywhere between 0..2*world_size. Due to two unrelated complex
301
+ # paddings performed in the code it's almost impossible to predict the exact numbers w/o the
302
+ # live optimizer object, so we are checking that the numbers are within the right range
303
+ align_to = 2 * world_size
304
+
305
+ def zero2_align(x):
306
+ return align_to * math.ceil(x / align_to)
307
+
308
+ if debug:
309
+ print(f"original offset={offset}, avail_numel={avail_numel}")
310
+
311
+ offset = zero2_align(offset)
312
+ avail_numel = zero2_align(avail_numel)
313
+
314
+ if debug:
315
+ print(f"aligned offset={offset}, avail_numel={avail_numel}")
316
+
317
+ # Sanity check
318
+ if offset != avail_numel:
319
+ raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
320
+
321
+ print(f"Reconstructed fp32 state dict with {total_params} params {total_numel} elements")
322
+
323
+
324
+ def _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states):
325
+ state_dict = OrderedDict()
326
+
327
+ # buffers
328
+ buffers = zero_model_states[0].buffers
329
+ state_dict.update(buffers)
330
+ if debug:
331
+ print(f"added {len(buffers)} buffers")
332
+
333
+ _zero2_merge_frozen_params(state_dict, zero_model_states)
334
+
335
+ _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
336
+
337
+ # recover shared parameters
338
+ for pair in zero_model_states[0].shared_params:
339
+ if pair[1] in state_dict:
340
+ state_dict[pair[0]] = state_dict[pair[1]]
341
+
342
+ return state_dict
343
+
344
+
345
+ def zero3_partitioned_param_info(unpartitioned_numel, world_size):
346
+ remainder = unpartitioned_numel % world_size
347
+ padding_numel = (world_size - remainder) if remainder else 0
348
+ partitioned_numel = math.ceil(unpartitioned_numel / world_size)
349
+ return partitioned_numel, padding_numel
350
+
351
+
352
+ def _zero3_merge_frozen_params(state_dict, world_size, zero_model_states):
353
+ if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
354
+ return
355
+
356
+ if debug:
357
+ for i in range(world_size):
358
+ num_elem = sum(s.numel() for s in zero_model_states[i].frozen_param_fragments.values())
359
+ print(f'rank {i}: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
360
+
361
+ frozen_param_shapes = zero_model_states[0].frozen_param_shapes
362
+ wanted_params = len(frozen_param_shapes)
363
+ wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
364
+ avail_numel = sum([p.numel() for p in zero_model_states[0].frozen_param_fragments.values()]) * world_size
365
+ print(f'Frozen params: Have {avail_numel} numels to process.')
366
+ print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
367
+
368
+ total_params = 0
369
+ total_numel = 0
370
+ for name, shape in zero_model_states[0].frozen_param_shapes.items():
371
+ total_params += 1
372
+ unpartitioned_numel = shape.numel()
373
+ total_numel += unpartitioned_numel
374
+
375
+ param_frags = tuple(model_state.frozen_param_fragments[name] for model_state in zero_model_states)
376
+ state_dict[name] = torch.cat(param_frags, 0).narrow(0, 0, unpartitioned_numel).view(shape)
377
+
378
+ partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
379
+
380
+ if debug:
381
+ print(
382
+ f"Frozen params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
383
+ )
384
+
385
+ print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
386
+
387
+
388
+ def _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
389
+ param_shapes = zero_model_states[0].param_shapes
390
+ avail_numel = fp32_flat_groups[0].numel() * world_size
391
+ # Reconstruction protocol: For zero3 we need to zip the partitions together at boundary of each
392
+ # param, re-consolidating each param, while dealing with padding if any
393
+
394
+ # merge list of dicts, preserving order
395
+ param_shapes = {k: v for d in param_shapes for k, v in d.items()}
396
+
397
+ if debug:
398
+ for i in range(world_size):
399
+ print(f"{FP32_FLAT_GROUPS}[{i}].shape={fp32_flat_groups[i].shape}")
400
+
401
+ wanted_params = len(param_shapes)
402
+ wanted_numel = sum(shape.numel() for shape in param_shapes.values())
403
+ # not asserting if there is a mismatch due to possible padding
404
+ avail_numel = fp32_flat_groups[0].numel() * world_size
405
+ print(f"Trainable params: Have {avail_numel} numels to process.")
406
+ print(f"Trainable params: Need {wanted_numel} numels in {wanted_params} params.")
407
+
408
+ # params
409
+ # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
410
+ # out-of-core computing solution
411
+ offset = 0
412
+ total_numel = 0
413
+ total_params = 0
414
+ for name, shape in param_shapes.items():
415
+
416
+ unpartitioned_numel = shape.numel()
417
+ total_numel += unpartitioned_numel
418
+ total_params += 1
419
+
420
+ partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
421
+
422
+ if debug:
423
+ print(
424
+ f"Trainable params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
425
+ )
426
+
427
+ # XXX: memory usage doubles here
428
+ state_dict[name] = torch.cat(
429
+ tuple(fp32_flat_groups[i].narrow(0, offset, partitioned_numel) for i in range(world_size)),
430
+ 0).narrow(0, 0, unpartitioned_numel).view(shape)
431
+ offset += partitioned_numel
432
+
433
+ offset *= world_size
434
+
435
+ # Sanity check
436
+ if offset != avail_numel:
437
+ raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
438
+
439
+ print(f"Reconstructed Trainable fp32 state dict with {total_params} params {total_numel} elements")
440
+
441
+
442
+ def _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states):
443
+ state_dict = OrderedDict()
444
+
445
+ # buffers
446
+ buffers = zero_model_states[0].buffers
447
+ state_dict.update(buffers)
448
+ if debug:
449
+ print(f"added {len(buffers)} buffers")
450
+
451
+ _zero3_merge_frozen_params(state_dict, world_size, zero_model_states)
452
+
453
+ _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
454
+
455
+ # recover shared parameters
456
+ for pair in zero_model_states[0].shared_params:
457
+ if pair[1] in state_dict:
458
+ state_dict[pair[0]] = state_dict[pair[1]]
459
+
460
+ return state_dict
461
+
462
+
463
+ def get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag=None):
464
+ """
465
+ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated state_dict that can be loaded with
466
+ ``load_state_dict()`` and used for training without DeepSpeed or shared with others, for example
467
+ via a model hub.
468
+
469
+ Args:
470
+ - ``checkpoint_dir``: path to the desired checkpoint folder
471
+ - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in 'latest' file. e.g., ``global_step14``
472
+
473
+ Returns:
474
+ - pytorch ``state_dict``
475
+
476
+ Note: this approach may not work if your application doesn't have sufficient free CPU memory and
477
+ you may need to use the offline approach using the ``zero_to_fp32.py`` script that is saved with
478
+ the checkpoint.
479
+
480
+ A typical usage might be ::
481
+
482
+ from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
483
+ # do the training and checkpoint saving
484
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) # already on cpu
485
+ model = model.cpu() # move to cpu
486
+ model.load_state_dict(state_dict)
487
+ # submit to model hub or save the model to share with others
488
+
489
+ In this example the ``model`` will no longer be usable in the deepspeed context of the same
490
+ application. i.e. you will need to re-initialize the deepspeed engine, since
491
+ ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
492
+
493
+ If you want it all done for you, use ``load_state_dict_from_zero_checkpoint`` instead.
494
+
495
+ """
496
+ if tag is None:
497
+ latest_path = os.path.join(checkpoint_dir, 'latest')
498
+ if os.path.isfile(latest_path):
499
+ with open(latest_path, 'r') as fd:
500
+ tag = fd.read().strip()
501
+ else:
502
+ raise ValueError(f"Unable to find 'latest' file at {latest_path}")
503
+
504
+ ds_checkpoint_dir = os.path.join(checkpoint_dir, tag)
505
+
506
+ if not os.path.isdir(ds_checkpoint_dir):
507
+ raise FileNotFoundError(f"Directory '{ds_checkpoint_dir}' doesn't exist")
508
+
509
+ return _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir)
510
+
511
+
512
+ def convert_zero_checkpoint_to_fp32_state_dict(checkpoint_dir, output_file, tag=None):
513
+ """
514
+ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` file that can be
515
+ loaded with ``torch.load(file)`` + ``load_state_dict()`` and used for training without DeepSpeed.
516
+
517
+ Args:
518
+ - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
519
+ - ``output_file``: path to the pytorch fp32 state_dict output file (e.g. path/pytorch_model.bin)
520
+ - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14``
521
+ """
522
+
523
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
524
+ print(f"Saving fp32 state dict to {output_file}")
525
+ torch.save(state_dict, output_file)
526
+
527
+
528
+ def load_state_dict_from_zero_checkpoint(model, checkpoint_dir, tag=None):
529
+ """
530
+ 1. Put the provided model to cpu
531
+ 2. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict``
532
+ 3. Load it into the provided model
533
+
534
+ Args:
535
+ - ``model``: the model object to update
536
+ - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
537
+ - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14``
538
+
539
+ Returns:
540
+ - ``model`: modified model
541
+
542
+ Make sure you have plenty of CPU memory available before you call this function. If you don't
543
+ have enough use the ``zero_to_fp32.py`` utility to do the conversion. You will find it
544
+ conveniently placed for you in the checkpoint folder.
545
+
546
+ A typical usage might be ::
547
+
548
+ from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint
549
+ model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir)
550
+ # submit to model hub or save the model to share with others
551
+
552
+ Note, that once this was run, the ``model`` will no longer be usable in the deepspeed context
553
+ of the same application. i.e. you will need to re-initialize the deepspeed engine, since
554
+ ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
555
+
556
+ """
557
+ logger.info(f"Extracting fp32 weights")
558
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
559
+
560
+ logger.info(f"Overwriting model with fp32 weights")
561
+ model = model.cpu()
562
+ model.load_state_dict(state_dict, strict=False)
563
+
564
+ return model
565
+
566
+
567
+ if __name__ == "__main__":
568
+
569
+ parser = argparse.ArgumentParser()
570
+ parser.add_argument("checkpoint_dir",
571
+ type=str,
572
+ help="path to the desired checkpoint folder, e.g., path/checkpoint-12")
573
+ parser.add_argument(
574
+ "output_file",
575
+ type=str,
576
+ help="path to the pytorch fp32 state_dict output file (e.g. path/checkpoint-12/pytorch_model.bin)")
577
+ parser.add_argument("-t",
578
+ "--tag",
579
+ type=str,
580
+ default=None,
581
+ help="checkpoint tag used as a unique identifier for checkpoint. e.g., global_step1")
582
+ parser.add_argument("-d", "--debug", action='store_true', help="enable debug")
583
+ args = parser.parse_args()
584
+
585
+ debug = args.debug
586
+
587
+ convert_zero_checkpoint_to_fp32_state_dict(args.checkpoint_dir, args.output_file, tag=args.tag)