kvaishnavi commited on
Commit
8a6e50e
·
1 Parent(s): 73b4139

Upload Phi-3-vision-128k-instruct scripts to make ONNX models

Browse files
onnx/builder.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import onnx
3
+ import os
4
+ import requests
5
+ import shutil
6
+ import subprocess
7
+ import sys
8
+ import torch
9
+
10
+ from onnxruntime_genai.models.builder import create_model
11
+ from PIL import Image
12
+ from transformers import AutoConfig, AutoProcessor, AutoModelForCausalLM
13
+
14
+
15
+ def build_vision(args):
16
+ # Many images:
17
+ prompt = f"{user_prompt}<|image_1|>\n <|image_2|>\n <|image_3|>\n <|image_4|>\n What is shown in these four images?{prompt_suffix}{assistant_prompt}"
18
+ url = "https://www.ilankelman.org/stopsigns/australia.jpg"
19
+ image_1 = Image.open(requests.get(url, stream=True).raw)
20
+ url = "https://img.freepik.com/free-photo/painting-mountain-lake-with-mountain-background_188544-9126.jpg?w=2000"
21
+ image_2 = Image.open(requests.get(url, stream=True).raw)
22
+ url = "https://th.bing.com/th/id/OIP.gCvQ1vmPVJmrq1nnzM3ZHQHaEo?rs=1&pid=ImgDetMain"
23
+ image_3 = Image.open(requests.get(url, stream=True).raw)
24
+ url = "https://wallpaper.dog/large/10809054.jpg"
25
+ image_4 = Image.open(requests.get(url, stream=True).raw)
26
+ images = [image_1, image_2, image_3, image_4]
27
+ inputs = processor(prompt, images, return_tensors="pt").to(args.execution_provider.replace("dml", "cuda"))
28
+ inputs["pixel_values"] = inputs["pixel_values"].to(args.precision)
29
+
30
+ # TorchScript export
31
+ dummy_inputs = (
32
+ inputs["pixel_values"], # inputs_embeds: Optional[torch.FloatTensor] = None,
33
+ inputs["image_sizes"], # image_sizes: Optional[torch.FloatTensor] = None,
34
+ )
35
+ dynamic_axes = {
36
+ "pixel_values": {0: "num_images", 1: "max_num_crops", 3: "height", 4: "width"},
37
+ "image_sizes": {0: "num_images"},
38
+ "image_features": {0: "num_image_tokens"},
39
+ }
40
+ filename = "phi-3-v-128k-instruct-vision.onnx"
41
+
42
+ temp_folder_1 = os.path.join(args.output, "vision_init_export")
43
+ os.makedirs(temp_folder_1, exist_ok=True)
44
+
45
+ fpath_1 = os.path.join(temp_folder_1, filename)
46
+ torch.onnx.export(
47
+ model.model.vision_embed_tokens,
48
+ args=dummy_inputs,
49
+ f=fpath_1,
50
+ export_params=True,
51
+ input_names=["pixel_values", "image_sizes"],
52
+ output_names=["image_features"],
53
+ dynamic_axes=dynamic_axes,
54
+ opset_version=14,
55
+ do_constant_folding=True,
56
+ )
57
+
58
+ onnx.checker.check_model(fpath_1)
59
+ onnx.shape_inference.infer_shapes_path(fpath_1)
60
+ onnx_model = onnx.load_model(fpath_1, load_external_data=True)
61
+
62
+ temp_folder_2 = os.path.join(args.output, "vision_after_export")
63
+ os.makedirs(temp_folder_2, exist_ok=True)
64
+
65
+ fpath_2 = os.path.join(temp_folder_2, filename)
66
+ onnx.save_model(
67
+ onnx_model,
68
+ fpath_2,
69
+ save_as_external_data=True,
70
+ all_tensors_to_one_file=True,
71
+ location=f"{filename}.data",
72
+ size_threshold=0,
73
+ convert_attribute=False,
74
+ )
75
+ shutil.rmtree(temp_folder_1)
76
+
77
+ # ORT transformer optimizer
78
+ temp_folder_3 = os.path.join(args.output, "vision_after_opt")
79
+ fpath_3 = os.path.join(temp_folder_3, filename)
80
+ subprocess.run(
81
+ [
82
+ f"{sys.executable}", "-m", "onnxruntime.transformers.optimizer",
83
+ "--input", fpath_2,
84
+ "--output", fpath_3,
85
+ "--model_type", "clip",
86
+ "--num_heads", str(16),
87
+ "--hidden_size", str(1024),
88
+ "--use_external_data_format",
89
+ "--opt_level", str(0),
90
+ "--disable_shape_inference",
91
+ ]
92
+ )
93
+ shutil.rmtree(temp_folder_2)
94
+
95
+ # ORT 4-bits quantizer
96
+ fpath_4 = os.path.join(args.output, filename)
97
+ cmd = [
98
+ f"{sys.executable}", "-m", "onnxruntime.quantization.matmul_4bits_quantizer",
99
+ "--input_model", fpath_3,
100
+ "--output_model", fpath_4,
101
+ "--block_size", str(32),
102
+ ]
103
+ if args.precision == torch.float32: cmd.extend(["--accuracy_level", str(4)])
104
+ subprocess.run(cmd)
105
+ shutil.rmtree(temp_folder_3)
106
+
107
+
108
+ def build_embedding(args):
109
+ # TorchScript export
110
+ batch_size, sequence_length, num_img_tokens = 2, 8, 2
111
+ inputs = {
112
+ "input_ids": torch.randint(low=0, high=config.vocab_size, size=(batch_size, sequence_length), device=args.execution_provider, dtype=torch.int64),
113
+ "image_features": torch.randn(num_img_tokens, config.hidden_size, device=args.execution_provider, dtype=args.precision),
114
+ "inputs_embeds": torch.randn(batch_size, sequence_length, config.hidden_size, device=args.execution_provider, dtype=args.precision),
115
+ }
116
+ inputs["input_ids"][0][0] = -1
117
+ inputs["input_ids"][0][1] = -1
118
+ dummy_inputs = (
119
+ inputs["input_ids"], # input_ids: torch.LongTensor
120
+ inputs["image_features"], # image_features: Optional[torch.FloatTensor] = None,
121
+ )
122
+ dynamic_axes = {
123
+ "input_ids": {0: "batch_size", 1: "sequence_length"},
124
+ "image_features": {0: "num_image_tokens"},
125
+ "inputs_embeds": {0: "batch_size", 1: "sequence_length"},
126
+ }
127
+ filename = "phi-3-v-128k-instruct-embedding.onnx"
128
+
129
+ temp_folder_1 = os.path.join(args.output, "embedding_init_export")
130
+ os.makedirs(temp_folder_1, exist_ok=True)
131
+
132
+ fpath_1 = os.path.join(temp_folder_1, filename)
133
+ torch.onnx.export(
134
+ model.model.combined_embed,
135
+ args=dummy_inputs,
136
+ f=fpath_1,
137
+ export_params=True,
138
+ input_names=["input_ids", "image_features"],
139
+ output_names=["inputs_embeds"],
140
+ dynamic_axes=dynamic_axes,
141
+ opset_version=14,
142
+ do_constant_folding=True,
143
+ )
144
+
145
+ onnx.checker.check_model(fpath_1)
146
+ onnx.shape_inference.infer_shapes_path(fpath_1)
147
+ onnx_model = onnx.load_model(fpath_1, load_external_data=True)
148
+
149
+ fpath_2 = os.path.join(args.output, filename)
150
+ onnx.save_model(
151
+ onnx_model,
152
+ fpath_2,
153
+ save_as_external_data=True,
154
+ all_tensors_to_one_file=True,
155
+ location=f"{filename}.data",
156
+ size_threshold=0,
157
+ convert_attribute=False,
158
+ )
159
+ shutil.rmtree(temp_folder_1)
160
+
161
+
162
+ def build_text(args):
163
+ # Create ONNX model
164
+ model_name = None
165
+ precision = "int4"
166
+ extra_options = {
167
+ "exclude_embeds": "true",
168
+ "filename": "phi-3-v-128k-instruct-text.onnx",
169
+ }
170
+ if args.precision == torch.float32: extra_options["int4_accuracy_level"] = 4
171
+ create_model(model_name, args.input, args.output, precision, args.execution_provider, args.cache_dir, **extra_options)
172
+
173
+
174
+ def get_args():
175
+ parser = argparse.ArgumentParser()
176
+
177
+ parser.add_argument(
178
+ "-i",
179
+ "--input",
180
+ required=True,
181
+ help="Path to folder on disk containing the Hugging Face config, model, tokenizer, etc.",
182
+ )
183
+
184
+ parser.add_argument(
185
+ "-o",
186
+ "--output",
187
+ required=True,
188
+ help="Path to folder to store ONNX model and additional files (e.g. GenAI config, external data files, etc.)",
189
+ )
190
+
191
+ parser.add_argument(
192
+ "-p",
193
+ "--precision",
194
+ required=True,
195
+ choices=["fp16", "fp32"],
196
+ help="Precision to export PyTorch components with",
197
+ )
198
+
199
+ parser.add_argument(
200
+ "-e",
201
+ "--execution_provider",
202
+ required=True,
203
+ choices=["cpu", "cuda", "dml"],
204
+ help="Execution provider for Phi-3 vision components",
205
+ )
206
+
207
+ parser.add_argument(
208
+ "-c",
209
+ "--cache_dir",
210
+ required=False,
211
+ default=os.path.join('.', 'cache_dir'),
212
+ help="Cache directory for Hugging Face files and temporary ONNX external data files",
213
+ )
214
+
215
+ args = parser.parse_args()
216
+ args.precision = torch.float16 if args.precision == "fp16" else torch.float32
217
+ return args
218
+
219
+ if __name__ == "__main__":
220
+ user_prompt = '<|user|>\n'
221
+ assistant_prompt = '<|assistant|>\n'
222
+ prompt_suffix = "<|end|>\n"
223
+
224
+ args = get_args()
225
+ config = AutoConfig.from_pretrained(args.input, trust_remote_code=True)
226
+ processor = AutoProcessor.from_pretrained(args.input, trust_remote_code=True)
227
+ model = AutoModelForCausalLM.from_pretrained(args.input, trust_remote_code=True, torch_dtype=args.precision).to(args.execution_provider.replace("dml", "cuda"))
228
+
229
+ # Build model components
230
+ build_vision(args)
231
+ build_embedding(args)
232
+ build_text(args)
onnx/config.json ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "Phi-3-vision-128k-instruct",
3
+ "architectures": [
4
+ "Phi3VForCausalLM"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_phi3_v.Phi3VConfig",
9
+ "AutoModelForCausalLM": "modeling_phi3_v.Phi3VForCausalLM"
10
+ },
11
+ "bos_token_id": 1,
12
+ "embd_layer": {
13
+ "embedding_cls": "image",
14
+ "hd_transform_order": "sub_glb",
15
+ "projection_cls": "mlp",
16
+ "use_hd_transform": true,
17
+ "with_learnable_separator": true
18
+ },
19
+ "eos_token_id": 2,
20
+ "hidden_act": "silu",
21
+ "hidden_size": 3072,
22
+ "img_processor": {
23
+ "image_dim_out": 1024,
24
+ "model_name": "openai/clip-vit-large-patch14-336",
25
+ "name": "clip_vision_model",
26
+ "num_img_tokens": 144
27
+ },
28
+ "initializer_range": 0.02,
29
+ "intermediate_size": 8192,
30
+ "max_position_embeddings": 131072,
31
+ "model_type": "phi3_v",
32
+ "num_attention_heads": 32,
33
+ "num_hidden_layers": 32,
34
+ "num_key_value_heads": 32,
35
+ "original_max_position_embeddings": 4096,
36
+ "rms_norm_eps": 1e-05,
37
+ "rope_scaling": {
38
+ "long_factor": [
39
+ 1.0299999713897705,
40
+ 1.0499999523162842,
41
+ 1.0499999523162842,
42
+ 1.0799999237060547,
43
+ 1.2299998998641968,
44
+ 1.2299998998641968,
45
+ 1.2999999523162842,
46
+ 1.4499999284744263,
47
+ 1.5999999046325684,
48
+ 1.6499998569488525,
49
+ 1.8999998569488525,
50
+ 2.859999895095825,
51
+ 3.68999981880188,
52
+ 5.419999599456787,
53
+ 5.489999771118164,
54
+ 5.489999771118164,
55
+ 9.09000015258789,
56
+ 11.579999923706055,
57
+ 15.65999984741211,
58
+ 15.769999504089355,
59
+ 15.789999961853027,
60
+ 18.360000610351562,
61
+ 21.989999771118164,
62
+ 23.079999923706055,
63
+ 30.009998321533203,
64
+ 32.35000228881836,
65
+ 32.590003967285156,
66
+ 35.56000518798828,
67
+ 39.95000457763672,
68
+ 53.840003967285156,
69
+ 56.20000457763672,
70
+ 57.95000457763672,
71
+ 59.29000473022461,
72
+ 59.77000427246094,
73
+ 59.920005798339844,
74
+ 61.190006256103516,
75
+ 61.96000671386719,
76
+ 62.50000762939453,
77
+ 63.3700065612793,
78
+ 63.48000717163086,
79
+ 63.48000717163086,
80
+ 63.66000747680664,
81
+ 63.850006103515625,
82
+ 64.08000946044922,
83
+ 64.760009765625,
84
+ 64.80001068115234,
85
+ 64.81001281738281,
86
+ 64.81001281738281
87
+ ],
88
+ "short_factor": [
89
+ 1.05,
90
+ 1.05,
91
+ 1.05,
92
+ 1.1,
93
+ 1.1,
94
+ 1.1,
95
+ 1.2500000000000002,
96
+ 1.2500000000000002,
97
+ 1.4000000000000004,
98
+ 1.4500000000000004,
99
+ 1.5500000000000005,
100
+ 1.8500000000000008,
101
+ 1.9000000000000008,
102
+ 2.000000000000001,
103
+ 2.000000000000001,
104
+ 2.000000000000001,
105
+ 2.000000000000001,
106
+ 2.000000000000001,
107
+ 2.000000000000001,
108
+ 2.000000000000001,
109
+ 2.000000000000001,
110
+ 2.000000000000001,
111
+ 2.000000000000001,
112
+ 2.000000000000001,
113
+ 2.000000000000001,
114
+ 2.000000000000001,
115
+ 2.000000000000001,
116
+ 2.000000000000001,
117
+ 2.000000000000001,
118
+ 2.000000000000001,
119
+ 2.000000000000001,
120
+ 2.000000000000001,
121
+ 2.1000000000000005,
122
+ 2.1000000000000005,
123
+ 2.2,
124
+ 2.3499999999999996,
125
+ 2.3499999999999996,
126
+ 2.3499999999999996,
127
+ 2.3499999999999996,
128
+ 2.3999999999999995,
129
+ 2.3999999999999995,
130
+ 2.6499999999999986,
131
+ 2.6999999999999984,
132
+ 2.8999999999999977,
133
+ 2.9499999999999975,
134
+ 3.049999999999997,
135
+ 3.049999999999997,
136
+ 3.049999999999997
137
+ ],
138
+ "type": "su"
139
+ },
140
+ "rope_theta": 10000.0,
141
+ "sliding_window": 131072,
142
+ "tie_word_embeddings": false,
143
+ "torch_dtype": "bfloat16",
144
+ "transformers_version": "4.38.1",
145
+ "use_cache": true,
146
+ "vocab_size": 32064,
147
+ "_attn_implementation": "eager"
148
+ }
onnx/image_embedding_phi3_v.py ADDED
@@ -0,0 +1,480 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ import warnings
16
+
17
+ import torch
18
+ from torch import nn
19
+ from transformers import CLIPVisionConfig, CLIPVisionModel, PretrainedConfig
20
+ from transformers.models.clip.modeling_clip import CLIPAttention
21
+ from transformers.utils import logging
22
+ from typing import List
23
+
24
+ try:
25
+ from flash_attn import flash_attn_func
26
+ except ImportError:
27
+ pass
28
+
29
+ logger = logging.get_logger(__name__)
30
+
31
+
32
+ MAX_INPUT_ID = int(1e9)
33
+
34
+ CLIP_VIT_LARGE_PATCH14_336_CONFIG = CLIPVisionConfig(
35
+ attention_dropout=0.0,
36
+ dropout=0.0,
37
+ hidden_act="quick_gelu",
38
+ hidden_size=1024,
39
+ image_size=336,
40
+ initializer_factor=1.0,
41
+ initializer_range=0.02,
42
+ intermediate_size=4096,
43
+ layer_norm_eps=1e-05,
44
+ num_attention_heads=16,
45
+ num_channels=3,
46
+ num_hidden_layers=24,
47
+ patch_size=14,
48
+ projection_dim=768,
49
+ attn_implementation="eager",
50
+ )
51
+
52
+ class CLIPAttentionFA2(CLIPAttention):
53
+ """Add flash attention 2 to CLIPAttention. (This is only used in the vision encoder)"""
54
+
55
+ def forward(self,
56
+ hidden_states,
57
+ attention_mask=None,
58
+ causal_attention_mask=None,
59
+ output_attentions=False,
60
+ ):
61
+ """Input shape: Batch x Time x Channel"""
62
+
63
+ assert attention_mask is None, "CLIPAttentionFA2 does not support attention_mask"
64
+ assert causal_attention_mask is None, "CLIPAttentionFA2 does not support causal_attention_mask"
65
+ assert output_attentions is False, "CLIPAttentionFA2 does not support output_attentions"
66
+
67
+ bsz, tgt_len, embed_dim = hidden_states.size()
68
+ query_states = self.q_proj(hidden_states).reshape(bsz, tgt_len, self.num_heads, self.head_dim)
69
+ key_states = self.k_proj(hidden_states).reshape(bsz, tgt_len, self.num_heads, self.head_dim)
70
+ value_states = self.v_proj(hidden_states).reshape(bsz, tgt_len, self.num_heads, self.head_dim)
71
+
72
+ attn_output = flash_attn_func(
73
+ query_states,
74
+ key_states,
75
+ value_states,
76
+ dropout_p=self.dropout if self.training else 0.0,
77
+ softmax_scale=self.scale,
78
+ causal=False,
79
+ ).reshape(bsz, tgt_len, embed_dim)
80
+
81
+ attn_output = self.out_proj(attn_output)
82
+ return attn_output, None
83
+
84
+
85
+ def reshape_hd_patches_2x2merge(image_features, h_crop, w_crop):
86
+ """
87
+ image_features: (num_images*num_crops, 24*24, 1024)
88
+ output: (num_images, h_crop*12, w_crop*12, 4096), h_crop*w_crop == num_crops
89
+ """
90
+ N, L, C = image_features.shape
91
+ assert L == 24 * 24 and C == 1024 and N % (h_crop * w_crop) == 0
92
+ num_images = torch.tensor(N // (h_crop * w_crop), dtype=torch.int64)
93
+ H = torch.tensor(int(L**0.5), dtype=torch.int64)
94
+ H_div_2 = torch.tensor(H // 2, dtype=torch.int64)
95
+
96
+ image_features_hd = (
97
+ image_features.reshape(N, H, H, C) # N, 24, 24, 1024
98
+ .reshape(N, H_div_2, 2, H_div_2, 2, C) # N, 12, 2, 12, 2, 1024
99
+ .permute(0, 1, 3, 2, 4, 5) # N, 12, 12, 2, 2, 1024
100
+ .reshape(N, -1, 4 * C) # N, 144, 4096
101
+ .reshape(
102
+ num_images, h_crop, w_crop, H_div_2, H_div_2, -1
103
+ ) # n_img, h_crop, w_crop, 12, 12, 4096
104
+ .permute(0, 1, 3, 2, 4, 5) # n_img, h_crop, 12, w_crop, 12, 4096
105
+ .reshape(
106
+ num_images, h_crop * H_div_2, w_crop * H_div_2, 4 * C
107
+ ) # n_img, h_crop*12, w_crop*12, 4096
108
+ )
109
+
110
+ return image_features_hd
111
+
112
+
113
+ def add_image_newline(image_features_hd, sub_GN):
114
+ """
115
+ image_features_hd: (num_images, h_crop*12, w_crop*12, 4096)
116
+ output: (num_images, (h_crop*12) * (w_crop*12+1), 4096)
117
+ """
118
+ num_images, h, w, hid_dim = image_features_hd.shape
119
+ # add the newline token to the HD image feature patches
120
+ newline_embeddings = sub_GN.expand(num_images, h, -1, -1) # (n_img, h, 1, hid_dim)
121
+ image_features_hd_newline = torch.cat(
122
+ [image_features_hd, newline_embeddings], dim=2
123
+ ).reshape(num_images, -1, hid_dim)
124
+ return image_features_hd_newline
125
+
126
+
127
+ @torch.jit.script_if_tracing
128
+ def get_image_embeddings(image_dim_out, image_sizes, image_features, global_image_features_hd_newline):
129
+ """
130
+ Get image embeddings for all images.
131
+ Need a for loop to process each image because of different image sizes
132
+ (patch arrangement is different for each image)
133
+ """
134
+ glb_GN = torch.zeros(1, 1, image_dim_out * 4).to(image_features.device)
135
+ sub_GN = torch.zeros(1, 1, 1, image_dim_out * 4).to(image_features.device)
136
+
137
+ all_image_embeddings = torch.empty(0, 4096).to(image_features.device)
138
+ for i, img_size in enumerate(image_sizes):
139
+ # h, w = img_size
140
+ h, w = img_size[0], img_size[1]
141
+ h_crop = torch.tensor(h // 336, dtype=torch.int64)
142
+ w_crop = torch.tensor(w // 336, dtype=torch.int64)
143
+ num_crops = h_crop * w_crop
144
+
145
+ # NOTE: real num_crops is padded
146
+ # (num_crops, 24*24, 1024)
147
+ sub_image_features = image_features[i, 1 : 1 + num_crops]
148
+ sub_image_features_hd = reshape_hd_patches_2x2merge(sub_image_features, h_crop, w_crop)
149
+ sub_image_features_hd_newline = add_image_newline(sub_image_features_hd, sub_GN)
150
+
151
+ # # [sub features, separator, global features]
152
+ # all_image_embeddings.extend(
153
+ # [
154
+ # sub_image_features_hd_newline.squeeze(0), # (h_crop*12*(w_crop*12+1), 4096)
155
+ # self.glb_GN.squeeze(0),
156
+ # global_image_features_hd_newline[i],
157
+ # ]
158
+ # )
159
+
160
+ # [sub features, separator, global features]
161
+ all_image_embeddings = torch.cat(
162
+ [
163
+ all_image_embeddings,
164
+ sub_image_features_hd_newline.view(-1, 4096), # (h_crop*12*(w_crop*12+1), 4096)
165
+ glb_GN.view(-1, 4096),
166
+ global_image_features_hd_newline[i],
167
+ ]
168
+ )
169
+
170
+ return all_image_embeddings
171
+
172
+
173
+ @torch.jit.script_if_tracing
174
+ def clamp_input_ids(input_ids: torch.LongTensor, image_features: torch.FloatTensor, vocab_size: int):
175
+ if image_features.numel():
176
+ input_shape = input_ids.size()
177
+ input_ids = input_ids.view(-1, input_shape[-1])
178
+
179
+ # positions for image tokens
180
+ condition = (input_ids < 0) & (input_ids > -int(1e9))
181
+ positions = torch.where(condition)
182
+ # has_image = len(positions[0].tolist()) > 0
183
+ input_ids = input_ids.clamp_min(0).clamp_max(vocab_size).detach()
184
+
185
+ return input_ids, positions
186
+
187
+ return input_ids, torch.where(torch.zeros((1, 1), dtype=torch.bool))
188
+
189
+
190
+ @torch.jit.script_if_tracing
191
+ def select_logic(hidden_states: torch.FloatTensor, image_features: torch.FloatTensor, positions: List[torch.LongTensor]):
192
+ if image_features.numel():
193
+ # apply 'select' logic
194
+ hidden_states = hidden_states.index_put(
195
+ positions, image_features, accumulate=False
196
+ )
197
+
198
+ return hidden_states
199
+
200
+
201
+ class Phi3Embedding(nn.Module):
202
+ """Phi3 embedding for text-only and vision + text."""
203
+ def __init__(self, wte, vocab_size):
204
+ super().__init__()
205
+ self.wte = wte
206
+ self.vocab_size = vocab_size
207
+
208
+ def forward(self, input_ids: torch.LongTensor, image_features: torch.FloatTensor) -> torch.FloatTensor:
209
+ input_ids, positions = clamp_input_ids(input_ids, image_features, self.vocab_size)
210
+ hidden_states = self.wte(input_ids)
211
+ hidden_states = select_logic(hidden_states, image_features, positions)
212
+ return hidden_states
213
+
214
+
215
+ class Phi3ImageEmbedding(nn.Module):
216
+ """Phi3 Image embedding."""
217
+
218
+ def __init__(self, config: PretrainedConfig, wte=None, **kwargs) -> None:
219
+ super().__init__()
220
+
221
+ # n_embed or hidden_size
222
+ hidden_size = config.n_embd if hasattr(config, 'n_embd') else config.hidden_size
223
+ if hasattr(config, 'embd_pdrop') or hasattr(config, 'embed_pdrop'):
224
+ embd_drop = config.embd_pdrop if hasattr(config, 'embd_pdrop') else config.embed_pdrop
225
+ self.drop = nn.Dropout(embd_drop)
226
+ else:
227
+ self.drop = None
228
+
229
+ self.wte = wte
230
+
231
+ if isinstance(config.img_processor, dict) and config.img_processor.get('name', None) == 'clip_vision_model':
232
+ assert 'model_name' in config.img_processor, 'model_name must be provided for CLIPVisionModel'
233
+ assert 'image_dim_out' in config.img_processor, 'image_dim_out must be provided for CLIPVisionModel'
234
+ assert 'num_img_tokens' in config.img_processor, 'num_img_tokens must be provided for CLIPVisionModel'
235
+ assert config.img_processor['model_name'] == 'openai/clip-vit-large-patch14-336'
236
+ clip_config = CLIP_VIT_LARGE_PATCH14_336_CONFIG
237
+ self.img_processor = CLIPVisionModel(clip_config)
238
+ image_dim_out = config.img_processor['image_dim_out']
239
+ self.num_img_tokens = config.img_processor['num_img_tokens']
240
+
241
+ # FA2 in CLIP
242
+ if config._attn_implementation == 'flash_attention_2':
243
+ for layer in self.img_processor.vision_model.encoder.layers:
244
+ clip_fa2 = CLIPAttentionFA2(clip_config)
245
+ del layer.self_attn
246
+ layer.self_attn = clip_fa2
247
+ else:
248
+ raise NotImplementedError(f'img_processor = {config.img_processor}, not implemented')
249
+
250
+ self.image_dim_out = image_dim_out
251
+ self.img_sizes = None
252
+
253
+ # global_gn and sub_gn for hd transform, serves as line separator
254
+ self.use_hd_transform = kwargs.get('use_hd_transform', False)
255
+ self.with_learnable_separator = kwargs.get('with_learnable_separator', False)
256
+ self.hd_transform_order = kwargs.get('hd_transform_order', 'glb_sub')
257
+ # with_hd_transform and with_learnable_separator should have same value
258
+ assert self.use_hd_transform == self.with_learnable_separator, 'use_hd_transform and with_learnable_separator should have same value'
259
+ if self.with_learnable_separator:
260
+ assert self.use_hd_transform, 'learnable separator is only for hd transform'
261
+ # 1024 * 4, merge spatial to channel dimension
262
+ self.glb_GN = nn.Parameter(torch.zeros([1, 1, self.image_dim_out * 4]))
263
+ self.sub_GN = nn.Parameter(torch.zeros([1, 1, 1, self.image_dim_out * 4]))
264
+ logger.info(f'learnable separator enabled for hd transform, hd_transform_order = {self.hd_transform_order}')
265
+
266
+ projection_cls = kwargs.get('projection_cls', 'linear')
267
+ if projection_cls == 'linear':
268
+ self.img_projection = nn.Linear(image_dim_out, hidden_size)
269
+ elif projection_cls == 'mlp' and self.use_hd_transform:
270
+ dim_projection = hidden_size
271
+ depth = 2
272
+ layers = [nn.Linear(image_dim_out * 4, dim_projection)]
273
+ for _ in range(1, depth):
274
+ layers.extend([nn.GELU(),
275
+ nn.Linear(dim_projection, dim_projection)])
276
+ self.img_projection = nn.Sequential(*layers)
277
+ elif projection_cls == 'mlp':
278
+ dim_projection = hidden_size
279
+ depth = 2
280
+ layers = [nn.Linear(image_dim_out, dim_projection)]
281
+ for _ in range(1, depth):
282
+ layers.extend([nn.GELU(),
283
+ nn.Linear(dim_projection, dim_projection)])
284
+ self.img_projection = nn.Sequential(*layers)
285
+ else:
286
+ raise NotImplementedError(f'projection_cls = {projection_cls}, not implemented')
287
+
288
+ self.vocab_size = config.vocab_size
289
+ self.img_features = None
290
+
291
+ if isinstance(config.img_processor, dict):
292
+ self.layer_idx = config.img_processor.get('layer_idx', -2)
293
+ self.type_feature = config.img_processor.get('type_feature', 'patch')
294
+ else:
295
+ self.layer_idx = -2
296
+ self.type_feature = 'patch'
297
+
298
+
299
+ def set_img_features(self, img_features: torch.FloatTensor) -> None:
300
+ self.img_features = img_features
301
+
302
+ def set_img_sizes(self, img_sizes: torch.LongTensor) -> None:
303
+ self.img_sizes = img_sizes
304
+
305
+ def get_img_features(self, img_embeds: torch.FloatTensor) -> torch.FloatTensor:
306
+ LAYER_IDX = self.layer_idx
307
+ TYPE_FEATURE = self.type_feature
308
+
309
+ img_processor_output = self.img_processor(img_embeds, output_hidden_states=True)
310
+ img_feature = img_processor_output.hidden_states[LAYER_IDX]
311
+
312
+ if TYPE_FEATURE == "patch":
313
+ patch_feature = img_feature[:, 1:]
314
+ return patch_feature
315
+
316
+ raise NotImplementedError
317
+
318
+ # def forward(
319
+ # self, input_ids: torch.LongTensor, pixel_values: torch.FloatTensor, image_sizes=None
320
+ # ) -> torch.FloatTensor:
321
+ # input_shape = input_ids.size()
322
+ # input_ids = input_ids.view(-1, input_shape[-1])
323
+
324
+ # # positions for image tokens
325
+ # positions = torch.nonzero((input_ids < 0) & (input_ids > -MAX_INPUT_ID), as_tuple=True)
326
+ # has_image = len(positions[0].tolist()) > 0
327
+ # # input_ids = input_ids.clamp_min(0).clamp_max(self.vocab_size).detach()
328
+ # input_ids.clamp_min_(0).clamp_max_(self.vocab_size)
329
+ # warnings.warn(
330
+ # "Phi-3-V modifies `input_ids` in-place and the tokens indicating images will be "
331
+ # "removed after model forward. If your workflow requires multiple forward passes on "
332
+ # "the same `input_ids`, please make a copy of `input_ids` before passing it to the "
333
+ # "model."
334
+ # )
335
+
336
+ # hidden_states = self.wte(input_ids)
337
+
338
+ # if has_image:
339
+ # assert self.use_hd_transform
340
+ # num_images, num_crops, c, h, w = pixel_values.shape
341
+ # assert c == 3 and h == w == 336
342
+ # img_features = self.get_img_features(pixel_values.flatten(0, 1)).reshape(
343
+ # num_images, num_crops, -1, self.image_dim_out
344
+ # )
345
+ # image_features_proj = self.hd_feature_transform(img_features, image_sizes)
346
+ # hidden_states = hidden_states.index_put(
347
+ # positions, image_features_proj, accumulate=False
348
+ # )
349
+
350
+ # if self.drop is not None:
351
+ # hidden_states = self.drop(hidden_states)
352
+
353
+ # return hidden_states
354
+
355
+ def forward(self, pixel_values: torch.FloatTensor, image_sizes=None) -> torch.FloatTensor:
356
+ assert self.use_hd_transform
357
+ num_images, num_crops, c, h, w = pixel_values.shape
358
+ assert c == 3 and h == w == 336
359
+ img_features = self.get_img_features(pixel_values.flatten(0, 1)).reshape(
360
+ num_images, num_crops, -1, self.image_dim_out
361
+ )
362
+ image_features_proj = self.hd_feature_transform(img_features, image_sizes)
363
+
364
+ return image_features_proj
365
+
366
+ def hd_feature_transform(self, image_features, image_sizes):
367
+ """
368
+ image_features: (num_images, num_crops+1, 24*24, 1024)
369
+ """
370
+ assert (
371
+ self.hd_transform_order == 'sub_glb'
372
+ ), f'hd_transform_order `{self.hd_transform_order}` not implemented'
373
+ if isinstance(self.img_projection, nn.Sequential):
374
+ target_device = self.img_projection[0].bias.device
375
+ target_dtype = self.img_projection[0].bias.dtype
376
+ else: # It's a single nn.Linear layer
377
+ target_device = self.img_projection.bias.device
378
+ target_dtype = self.img_projection.bias.dtype
379
+
380
+ global_image_features = image_features[:, 0] # (num_images, 24*24, 1024)
381
+ # global feature can be viewed as a special HD case with num_crops 1x1
382
+ global_image_features_hd = self.reshape_hd_patches_2x2merge(global_image_features, 1, 1)
383
+ global_image_features_hd_newline = self.add_image_newline(global_image_features_hd)
384
+
385
+ # all_image_embeddings = []
386
+ # # need a for loop to process each image because of different image sizes
387
+ # # (patch arrangement is different for each image)
388
+ # for i, img_size in enumerate(image_sizes):
389
+ # h, w = img_size
390
+ # h_crop = h // 336
391
+ # w_crop = w // 336
392
+ # num_crops = h_crop * w_crop
393
+
394
+ # # NOTE: real num_crops is padded
395
+ # # (num_crops, 24*24, 1024)
396
+ # sub_image_features = image_features[i, 1 : 1 + num_crops]
397
+ # sub_image_features_hd = self.reshape_hd_patches_2x2merge(
398
+ # sub_image_features, h_crop, w_crop
399
+ # )
400
+ # sub_image_features_hd_newline = self.add_image_newline(sub_image_features_hd)
401
+
402
+ # # [sub features, separator, global features]
403
+ # all_image_embeddings.extend(
404
+ # [
405
+ # sub_image_features_hd_newline.squeeze(0), # (h_crop*12*(w_crop*12+1), 4096)
406
+ # self.glb_GN.squeeze(0),
407
+ # global_image_features_hd_newline[i],
408
+ # ]
409
+ # )
410
+
411
+ # image_features_proj = self.img_projection(
412
+ # torch.cat(all_image_embeddings, dim=0).to(target_device).to(target_dtype)
413
+ # )
414
+
415
+ # return image_features_proj
416
+
417
+ all_image_embeddings = get_image_embeddings(torch.tensor(self.image_dim_out), image_sizes, image_features, global_image_features_hd_newline)
418
+ image_features_proj = self.img_projection(
419
+ all_image_embeddings.unsqueeze(0).to(target_device).to(target_dtype)
420
+ )
421
+ return image_features_proj.squeeze()
422
+
423
+ def reshape_hd_patches_2x2merge(self, image_features, h_crop, w_crop):
424
+ """
425
+ image_features: (num_images*num_crops, 24*24, 1024)
426
+ output: (num_images, h_crop*12, w_crop*12, 4096), h_crop*w_crop == num_crops
427
+ """
428
+ N, L, C = image_features.shape
429
+ assert L == 24 * 24 and C == 1024 and N % (h_crop * w_crop) == 0
430
+ num_images = N // (h_crop * w_crop)
431
+ H = int(L**0.5)
432
+ image_features_hd = (
433
+ image_features.reshape(N, H, H, C) # N, 24, 24, 1024
434
+ .reshape(N, H // 2, 2, H // 2, 2, C) # N, 12, 2, 12, 2, 1024
435
+ .permute(0, 1, 3, 2, 4, 5) # N, 12, 12, 2, 2, 1024
436
+ .reshape(N, -1, 4 * C) # N, 144, 4096
437
+ .reshape(
438
+ num_images, h_crop, w_crop, H // 2, H // 2, -1
439
+ ) # n_img, h_crop, w_crop, 12, 12, 4096
440
+ .permute(0, 1, 3, 2, 4, 5) # n_img, h_crop, 12, w_crop, 12, 4096
441
+ .reshape(
442
+ num_images, h_crop * H // 2, w_crop * H // 2, 4 * C
443
+ ) # n_img, h_crop*12, w_crop*12, 4096
444
+ )
445
+
446
+ # alternative implementation using einops
447
+ # from einops import rearrange
448
+ # image_features_nhwc = rearrange(
449
+ # image_features,
450
+ # 'N (H W) c -> N H W c',
451
+ # H=H,
452
+ # W=H,
453
+ # )
454
+ # image_features_2x2merge = rearrange(
455
+ # image_features_nhwc,
456
+ # 'N (h h_pool) (w w_pool) c -> N h w (h_pool w_pool c)',
457
+ # h_pool=2,
458
+ # w_pool=2,
459
+ # )
460
+ # image_features_hd = rearrange(
461
+ # image_features_2x2merge,
462
+ # '(n_img h_crop w_crop) h w C -> n_img (h_crop h) (w_crop w) C',
463
+ # h_crop=h_crop,
464
+ # w_crop=w_crop,
465
+ # )
466
+
467
+ return image_features_hd
468
+
469
+ def add_image_newline(self, image_features_hd):
470
+ """
471
+ image_features_hd: (num_images, h_crop*12, w_crop*12, 4096)
472
+ output: (num_images, (h_crop*12) * (w_crop*12+1), 4096)
473
+ """
474
+ num_images, h, w, hid_dim = image_features_hd.shape
475
+ # add the newline token to the HD image feature patches
476
+ newline_embeddings = self.sub_GN.expand(num_images, h, -1, -1) # (n_img, h, 1, hid_dim)
477
+ image_features_hd_newline = torch.cat(
478
+ [image_features_hd, newline_embeddings], dim=2
479
+ ).reshape(num_images, -1, hid_dim)
480
+ return image_features_hd_newline
onnx/modeling_phi3_v.py ADDED
@@ -0,0 +1,1635 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """ PyTorch Phi-3-V model."""
17
+
18
+ import inspect
19
+ import math
20
+ import warnings
21
+ from typing import List, Optional, Tuple, Union
22
+
23
+ import torch
24
+ import torch.nn.functional as F
25
+ import torch.utils.checkpoint
26
+ from torch import nn
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+
29
+ from transformers.activations import ACT2FN
30
+ from transformers.cache_utils import Cache, DynamicCache
31
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
32
+ from transformers.modeling_outputs import (
33
+ BaseModelOutputWithPast,
34
+ CausalLMOutputWithPast,
35
+ SequenceClassifierOutputWithPast,
36
+ TokenClassifierOutput,
37
+ )
38
+ from transformers.modeling_utils import PreTrainedModel
39
+ from transformers.utils import (
40
+ add_code_sample_docstrings,
41
+ add_start_docstrings,
42
+ add_start_docstrings_to_model_forward,
43
+ is_flash_attn_greater_or_equal_2_10,
44
+ logging,
45
+ replace_return_docstrings,
46
+ )
47
+ from .configuration_phi3_v import Phi3VConfig
48
+ from .image_embedding_phi3_v import Phi3ImageEmbedding, Phi3Embedding
49
+
50
+
51
+ try:
52
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
53
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
54
+
55
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
56
+ except ImportError:
57
+ pass
58
+
59
+ logger = logging.get_logger(__name__)
60
+
61
+ _CHECKPOINT_FOR_DOC = "microsoft/Phi-3-vision-128k-instruct"
62
+ _CONFIG_FOR_DOC = "Phi3VConfig"
63
+
64
+ PHI3V_PRETRAINED_MODEL_ARCHIVE_LIST = [
65
+ "microsoft/Phi-3-vision-128k-instruct",
66
+ # See all Phi-3 models at https://huggingface.co/models?filter=Phi-3
67
+ ]
68
+
69
+
70
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Phi3
71
+ class Phi3RMSNorm(nn.Module):
72
+ def __init__(self, hidden_size, eps=1e-6):
73
+ """
74
+ Phi3RMSNorm is equivalent to T5LayerNorm
75
+ """
76
+ super().__init__()
77
+ self.weight = nn.Parameter(torch.ones(hidden_size))
78
+ self.variance_epsilon = eps
79
+
80
+ def forward(self, hidden_states):
81
+ input_dtype = hidden_states.dtype
82
+ hidden_states = hidden_states.to(torch.float32)
83
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
84
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
85
+ return self.weight * hidden_states.to(input_dtype)
86
+
87
+
88
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
89
+ def _get_unpad_data(attention_mask):
90
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
91
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
92
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
93
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
94
+ return (
95
+ indices,
96
+ cu_seqlens,
97
+ max_seqlen_in_batch,
98
+ )
99
+
100
+
101
+ # Copied from transformers.models.gemma.modeling_gemma.GemmaRotaryEmbedding with gemma->phi3, Gemma->Phi3
102
+ class Phi3RotaryEmbedding(nn.Module):
103
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
104
+ super().__init__()
105
+
106
+ self.dim = dim
107
+ self.max_position_embeddings = max_position_embeddings
108
+ self.base = base
109
+ self.register_buffer("inv_freq", None, persistent=False)
110
+
111
+ @torch.no_grad()
112
+ def forward(self, x, position_ids, seq_len=None):
113
+ # x: [bs, num_attention_heads, seq_len, head_size]
114
+ if self.inv_freq is None:
115
+ self.inv_freq = 1.0 / (
116
+ self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim)
117
+ )
118
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
119
+ position_ids_expanded = position_ids[:, None, :].float()
120
+ # Force float32 since bfloat16 loses precision on long contexts
121
+ # See https://github.com/huggingface/transformers/pull/29285
122
+ device_type = x.device.type
123
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
124
+ with torch.autocast(device_type=device_type, enabled=False):
125
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
126
+ emb = torch.cat((freqs, freqs), dim=-1)
127
+ cos = emb.cos()
128
+ sin = emb.sin()
129
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
130
+
131
+
132
+ class Phi3SuScaledRotaryEmbedding(Phi3RotaryEmbedding):
133
+ def __init__(self, dim, config, device=None):
134
+ super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)
135
+
136
+ self.short_factor = config.rope_scaling["short_factor"]
137
+ self.long_factor = config.rope_scaling["long_factor"]
138
+ self.original_max_position_embeddings = config.original_max_position_embeddings
139
+
140
+ @torch.no_grad()
141
+ def forward(self, x, position_ids, seq_len=None):
142
+ seq_len = torch.max(position_ids) + 1
143
+ if seq_len > self.original_max_position_embeddings:
144
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
145
+ else:
146
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
147
+
148
+ inv_freq_shape = torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim
149
+ self.inv_freq = 1.0 / (ext_factors * self.base**inv_freq_shape)
150
+
151
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
152
+ position_ids_expanded = position_ids[:, None, :].float()
153
+
154
+ # Force float32 since bfloat16 loses precision on long contexts
155
+ # See https://github.com/huggingface/transformers/pull/29285
156
+ device_type = x.device.type
157
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
158
+ with torch.autocast(device_type=device_type, enabled=False):
159
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
160
+ emb = torch.cat((freqs, freqs), dim=-1)
161
+
162
+ scale = self.max_position_embeddings / self.original_max_position_embeddings
163
+ if scale <= 1.0:
164
+ scaling_factor = 1.0
165
+ else:
166
+ scaling_factor = math.sqrt(1 + math.log(scale) / math.log(self.original_max_position_embeddings))
167
+
168
+ cos = emb.cos() * scaling_factor
169
+ sin = emb.sin() * scaling_factor
170
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
171
+
172
+
173
+ class Phi3YarnScaledRotaryEmbedding(Phi3RotaryEmbedding):
174
+ def __init__(self, dim, config, device=None):
175
+ super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)
176
+
177
+ self.short_factor = config.rope_scaling["short_factor"]
178
+ self.long_factor = config.rope_scaling["long_factor"]
179
+ self.original_max_position_embeddings = config.original_max_position_embeddings
180
+
181
+ @torch.no_grad()
182
+ def forward(self, x, position_ids, seq_len=None):
183
+ seq_len = torch.max(position_ids) + 1
184
+ if seq_len > self.original_max_position_embeddings:
185
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
186
+ else:
187
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
188
+
189
+ inv_freq_shape = torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim
190
+ self.inv_freq = 1.0 / (ext_factors * self.base**inv_freq_shape)
191
+
192
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
193
+ position_ids_expanded = position_ids[:, None, :].float()
194
+
195
+ # Force float32 since bfloat16 loses precision on long contexts
196
+ # See https://github.com/huggingface/transformers/pull/29285
197
+ device_type = x.device.type
198
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
199
+ with torch.autocast(device_type=device_type, enabled=False):
200
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
201
+ emb = torch.cat((freqs, freqs), dim=-1)
202
+
203
+ scale = self.max_position_embeddings / self.original_max_position_embeddings
204
+ if scale <= 1.0:
205
+ scaling_factor = 1.0
206
+ else:
207
+ scaling_factor = 0.1 * math.log(scale) + 1.0
208
+
209
+ cos = emb.cos() * scaling_factor
210
+ sin = emb.sin() * scaling_factor
211
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
212
+
213
+
214
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
215
+ def rotate_half(x):
216
+ """Rotates half the hidden dims of the input."""
217
+ x1 = x[..., : x.shape[-1] // 2]
218
+ x2 = x[..., x.shape[-1] // 2 :]
219
+ return torch.cat((-x2, x1), dim=-1)
220
+
221
+
222
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
223
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
224
+ """Applies Rotary Position Embedding to the query and key tensors.
225
+
226
+ Args:
227
+ q (`torch.Tensor`): The query tensor.
228
+ k (`torch.Tensor`): The key tensor.
229
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
230
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
231
+ position_ids (`torch.Tensor`, *optional*):
232
+ Deprecated and unused.
233
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
234
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
235
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
236
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
237
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
238
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
239
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
240
+ Returns:
241
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
242
+ """
243
+ cos = cos.unsqueeze(unsqueeze_dim)
244
+ sin = sin.unsqueeze(unsqueeze_dim)
245
+ q_embed = (q * cos) + (rotate_half(q) * sin)
246
+ k_embed = (k * cos) + (rotate_half(k) * sin)
247
+ return q_embed, k_embed
248
+
249
+
250
+ class Phi3MLP(nn.Module):
251
+ def __init__(self, config):
252
+ super().__init__()
253
+
254
+ self.config = config
255
+ self.gate_up_proj = nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=False)
256
+ self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
257
+
258
+ self.activation_fn = ACT2FN[config.hidden_act]
259
+
260
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
261
+ up_states = self.gate_up_proj(hidden_states)
262
+
263
+ gate, up_states = up_states.chunk(2, dim=-1)
264
+ up_states = up_states * self.activation_fn(gate)
265
+
266
+ return self.down_proj(up_states)
267
+
268
+
269
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv with llama->phi
270
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
271
+ """
272
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
273
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
274
+ """
275
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
276
+ if n_rep == 1:
277
+ return hidden_states
278
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
279
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
280
+
281
+
282
+ class Phi3Attention(nn.Module):
283
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
284
+
285
+ def __init__(self, config: Phi3VConfig, layer_idx: Optional[int] = None):
286
+ super().__init__()
287
+ self.config = config
288
+ self.layer_idx = layer_idx
289
+ if layer_idx is None:
290
+ logger.warning_once(
291
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
292
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
293
+ "when creating this class."
294
+ )
295
+
296
+ self.attention_dropout = config.attention_dropout
297
+ self.hidden_size = config.hidden_size
298
+ self.num_heads = config.num_attention_heads
299
+ self.head_dim = self.hidden_size // self.num_heads
300
+ self.num_key_value_heads = config.num_key_value_heads
301
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
302
+ self.max_position_embeddings = config.max_position_embeddings
303
+ self.original_max_position_embeddings = config.original_max_position_embeddings
304
+ self.rope_theta = config.rope_theta
305
+ self.rope_scaling = config.rope_scaling
306
+ self.is_causal = True
307
+
308
+ if (self.head_dim * self.num_heads) != self.hidden_size:
309
+ raise ValueError(
310
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
311
+ f" and `num_heads`: {self.num_heads})."
312
+ )
313
+
314
+ op_size = self.num_heads * self.head_dim + 2 * (self.num_key_value_heads * self.head_dim)
315
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
316
+ self.qkv_proj = nn.Linear(self.hidden_size, op_size, bias=False)
317
+ self._init_rope()
318
+
319
+ def _init_rope(self):
320
+ if self.rope_scaling is None:
321
+ self.rotary_emb = Phi3RotaryEmbedding(
322
+ self.head_dim,
323
+ max_position_embeddings=self.max_position_embeddings,
324
+ base=self.rope_theta,
325
+ )
326
+ else:
327
+ scaling_type = self.config.rope_scaling["type"]
328
+ if scaling_type == "su":
329
+ self.rotary_emb = Phi3SuScaledRotaryEmbedding(self.head_dim, self.config)
330
+ elif scaling_type == "yarn":
331
+ self.rotary_emb = Phi3YarnScaledRotaryEmbedding(self.head_dim, self.config)
332
+ else:
333
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
334
+
335
+ def forward(
336
+ self,
337
+ hidden_states: torch.Tensor,
338
+ attention_mask: Optional[torch.Tensor] = None,
339
+ position_ids: Optional[torch.LongTensor] = None,
340
+ past_key_value: Optional[Cache] = None,
341
+ output_attentions: bool = False,
342
+ use_cache: bool = False,
343
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
344
+ logger.warning_once("You are not running the flash-attention implementation, expect numerical differences.")
345
+
346
+ bsz, q_len, _ = hidden_states.size()
347
+
348
+ qkv = self.qkv_proj(hidden_states)
349
+ query_pos = self.num_heads * self.head_dim
350
+ query_states = qkv[..., :query_pos]
351
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
352
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
353
+
354
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
355
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
356
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
357
+
358
+ kv_seq_len = key_states.shape[-2]
359
+ if past_key_value is not None:
360
+ if self.layer_idx is None:
361
+ raise ValueError(
362
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
363
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
364
+ "with a layer index."
365
+ )
366
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
367
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)
368
+
369
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
370
+
371
+ if past_key_value is not None:
372
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
373
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
374
+
375
+ # repeat k/v heads if n_kv_heads < n_heads
376
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
377
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
378
+
379
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
380
+
381
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
382
+ raise ValueError(
383
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
384
+ f" {attn_weights.size()}"
385
+ )
386
+
387
+ if attention_mask is not None:
388
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
389
+ raise ValueError(
390
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
391
+ )
392
+ attn_weights = attn_weights + attention_mask
393
+
394
+ # upcast attention to fp32
395
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(value_states.dtype)
396
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
397
+
398
+ attn_output = torch.matmul(attn_weights, value_states)
399
+
400
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
401
+ raise ValueError(
402
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
403
+ f" {attn_output.size()}"
404
+ )
405
+
406
+ attn_output = attn_output.transpose(1, 2).contiguous()
407
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
408
+
409
+ attn_output = self.o_proj(attn_output)
410
+
411
+ if not output_attentions:
412
+ attn_weights = None
413
+
414
+ return attn_output, attn_weights, past_key_value
415
+
416
+
417
+ class Phi3FlashAttention2(Phi3Attention):
418
+ """
419
+ Phi-3 flash attention module. This module inherits from `Phi3Attention` as the weights of the module stays
420
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
421
+ flash attention and deal with padding tokens in case the input contains any of them.
422
+ """
423
+
424
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
425
+ def __init__(self, *args, **kwargs):
426
+ super().__init__(*args, **kwargs)
427
+
428
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
429
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
430
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
431
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
432
+
433
+ def forward(
434
+ self,
435
+ hidden_states: torch.Tensor,
436
+ attention_mask: Optional[torch.LongTensor] = None,
437
+ position_ids: Optional[torch.LongTensor] = None,
438
+ past_key_value: Optional[Cache] = None,
439
+ output_attentions: bool = False,
440
+ use_cache: bool = False,
441
+ **kwargs,
442
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
443
+ # Phi3FlashAttention2 attention does not support output_attentions
444
+
445
+ if not _flash_supports_window_size:
446
+ logger.warning_once(
447
+ "The current flash attention version does not support sliding window attention. Please use `attn_implementation='eager'` or upgrade flash-attn library."
448
+ )
449
+ raise ValueError("The current flash attention version does not support sliding window attention.")
450
+
451
+ output_attentions = False
452
+
453
+ if "padding_mask" in kwargs:
454
+ warnings.warn(
455
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
456
+ )
457
+
458
+ # overwrite attention_mask with padding_mask
459
+ attention_mask = kwargs.pop("padding_mask")
460
+
461
+ bsz, q_len, _ = hidden_states.size()
462
+
463
+ qkv = self.qkv_proj(hidden_states)
464
+ query_pos = self.num_heads * self.head_dim
465
+ query_states = qkv[..., :query_pos]
466
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
467
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
468
+
469
+ # Flash attention requires the input to have the shape
470
+ # batch_size x seq_length x head_dim x hidden_dim
471
+ # therefore we just need to keep the original shape
472
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
473
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
474
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
475
+
476
+ kv_seq_len = key_states.shape[-2]
477
+ if past_key_value is not None:
478
+ if self.layer_idx is None:
479
+ raise ValueError(
480
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
481
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
482
+ "with a layer index."
483
+ )
484
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
485
+
486
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
487
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
488
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=rotary_seq_len)
489
+
490
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
491
+
492
+ use_sliding_windows = (
493
+ _flash_supports_window_size
494
+ and getattr(self.config, "sliding_window", None) is not None
495
+ and kv_seq_len > self.config.sliding_window
496
+ )
497
+
498
+ if past_key_value is not None:
499
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
500
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
501
+ if (
502
+ getattr(self.config, "sliding_window", None) is not None
503
+ and kv_seq_len > self.config.sliding_window
504
+ and cache_has_contents
505
+ ):
506
+ slicing_tokens = 1 - self.config.sliding_window
507
+
508
+ past_key = past_key_value[self.layer_idx][0]
509
+ past_value = past_key_value[self.layer_idx][1]
510
+
511
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
512
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
513
+
514
+ if past_key.shape[-2] != self.config.sliding_window - 1:
515
+ raise ValueError(
516
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
517
+ f" {past_key.shape}"
518
+ )
519
+
520
+ if attention_mask is not None:
521
+ attention_mask = attention_mask[:, slicing_tokens:]
522
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
523
+
524
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
525
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
526
+
527
+ # repeat k/v heads if n_kv_heads < n_heads
528
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
529
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
530
+
531
+ attn_dropout = self.attention_dropout if self.training else 0.0
532
+
533
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
534
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
535
+ # cast them back in the correct dtype just to be sure everything works as expected.
536
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
537
+ # in fp32.
538
+
539
+ if query_states.dtype == torch.float32:
540
+ if torch.is_autocast_enabled():
541
+ target_dtype = torch.get_autocast_gpu_dtype()
542
+ # Handle the case where the model is quantized
543
+ elif hasattr(self.config, "_pre_quantization_dtype"):
544
+ target_dtype = self.config._pre_quantization_dtype
545
+ else:
546
+ target_dtype = self.qkv_proj.weight.dtype
547
+
548
+ logger.warning_once(
549
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
550
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
551
+ f" {target_dtype}."
552
+ )
553
+
554
+ query_states = query_states.to(target_dtype)
555
+ key_states = key_states.to(target_dtype)
556
+ value_states = value_states.to(target_dtype)
557
+
558
+ # Reashape to the expected shape for Flash Attention
559
+ query_states = query_states.transpose(1, 2)
560
+ key_states = key_states.transpose(1, 2)
561
+ value_states = value_states.transpose(1, 2)
562
+
563
+ attn_output = self._flash_attention_forward(
564
+ query_states,
565
+ key_states,
566
+ value_states,
567
+ attention_mask,
568
+ q_len,
569
+ dropout=attn_dropout,
570
+ use_sliding_windows=use_sliding_windows,
571
+ )
572
+
573
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
574
+ attn_output = self.o_proj(attn_output)
575
+
576
+ if not output_attentions:
577
+ attn_weights = None
578
+
579
+ return attn_output, attn_weights, past_key_value
580
+
581
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._flash_attention_forward
582
+ def _flash_attention_forward(
583
+ self,
584
+ query_states,
585
+ key_states,
586
+ value_states,
587
+ attention_mask,
588
+ query_length,
589
+ dropout=0.0,
590
+ softmax_scale=None,
591
+ use_sliding_windows=False,
592
+ ):
593
+ """
594
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
595
+ first unpad the input, then computes the attention scores and pad the final attention scores.
596
+
597
+ Args:
598
+ query_states (`torch.Tensor`):
599
+ Input query states to be passed to Flash Attention API
600
+ key_states (`torch.Tensor`):
601
+ Input key states to be passed to Flash Attention API
602
+ value_states (`torch.Tensor`):
603
+ Input value states to be passed to Flash Attention API
604
+ attention_mask (`torch.Tensor`):
605
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
606
+ position of padding tokens and 1 for the position of non-padding tokens.
607
+ dropout (`float`):
608
+ Attention dropout
609
+ softmax_scale (`float`, *optional*):
610
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
611
+ use_sliding_windows (`bool`, *optional*):
612
+ Whether to activate sliding window attention.
613
+ """
614
+ if not self._flash_attn_uses_top_left_mask:
615
+ causal = self.is_causal
616
+ else:
617
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
618
+ causal = self.is_causal and query_length != 1
619
+
620
+ # Contains at least one padding token in the sequence
621
+ if attention_mask is not None:
622
+ batch_size = query_states.shape[0]
623
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
624
+ query_states, key_states, value_states, attention_mask, query_length
625
+ )
626
+
627
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
628
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
629
+
630
+ if not use_sliding_windows:
631
+ attn_output_unpad = flash_attn_varlen_func(
632
+ query_states,
633
+ key_states,
634
+ value_states,
635
+ cu_seqlens_q=cu_seqlens_q,
636
+ cu_seqlens_k=cu_seqlens_k,
637
+ max_seqlen_q=max_seqlen_in_batch_q,
638
+ max_seqlen_k=max_seqlen_in_batch_k,
639
+ dropout_p=dropout,
640
+ softmax_scale=softmax_scale,
641
+ causal=causal,
642
+ )
643
+ else:
644
+ attn_output_unpad = flash_attn_varlen_func(
645
+ query_states,
646
+ key_states,
647
+ value_states,
648
+ cu_seqlens_q=cu_seqlens_q,
649
+ cu_seqlens_k=cu_seqlens_k,
650
+ max_seqlen_q=max_seqlen_in_batch_q,
651
+ max_seqlen_k=max_seqlen_in_batch_k,
652
+ dropout_p=dropout,
653
+ softmax_scale=softmax_scale,
654
+ causal=causal,
655
+ window_size=(self.config.sliding_window, self.config.sliding_window),
656
+ )
657
+
658
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
659
+ else:
660
+ if not use_sliding_windows:
661
+ attn_output = flash_attn_func(
662
+ query_states,
663
+ key_states,
664
+ value_states,
665
+ dropout,
666
+ softmax_scale=softmax_scale,
667
+ causal=causal,
668
+ )
669
+ else:
670
+ attn_output = flash_attn_func(
671
+ query_states,
672
+ key_states,
673
+ value_states,
674
+ dropout,
675
+ softmax_scale=softmax_scale,
676
+ causal=causal,
677
+ window_size=(self.config.sliding_window, self.config.sliding_window),
678
+ )
679
+
680
+ return attn_output
681
+
682
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._upad_input
683
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
684
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
685
+
686
+ # On the first iteration we need to properly re-create the padding mask
687
+ # by slicing it on the proper place
688
+ if kv_seq_len != attention_mask.shape[-1]:
689
+ attention_mask_num_tokens = attention_mask.shape[-1]
690
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
691
+
692
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
693
+
694
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
695
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
696
+
697
+ if query_length == kv_seq_len:
698
+ query_layer = index_first_axis(
699
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
700
+ )
701
+ cu_seqlens_q = cu_seqlens_k
702
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
703
+ indices_q = indices_k
704
+ elif query_length == 1:
705
+ max_seqlen_in_batch_q = 1
706
+ cu_seqlens_q = torch.arange(
707
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
708
+ ) # There is a memcpy here, that is very bad.
709
+ indices_q = cu_seqlens_q[:-1]
710
+ query_layer = query_layer.squeeze(1)
711
+ else:
712
+ # The -q_len: slice assumes left padding.
713
+ attention_mask = attention_mask[:, -query_length:]
714
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
715
+
716
+ return (
717
+ query_layer,
718
+ key_layer,
719
+ value_layer,
720
+ indices_q,
721
+ (cu_seqlens_q, cu_seqlens_k),
722
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
723
+ )
724
+
725
+
726
+ # copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Phi3
727
+ # TODO @Arthur no longer copied from LLama after static cache
728
+ class Phi3SdpaAttention(Phi3Attention):
729
+ """
730
+ Phi3 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
731
+ `Phi3Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
732
+ SDPA API.
733
+ """
734
+
735
+ # Adapted from Phi3Attention.forward
736
+ def forward(
737
+ self,
738
+ hidden_states: torch.Tensor,
739
+ attention_mask: Optional[torch.Tensor] = None,
740
+ position_ids: Optional[torch.LongTensor] = None,
741
+ past_key_value: Optional[Cache] = None,
742
+ output_attentions: bool = False,
743
+ use_cache: bool = False,
744
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
745
+ if output_attentions:
746
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
747
+ logger.warning_once(
748
+ "Phi3Model is using Phi3SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
749
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
750
+ )
751
+ return super().forward(
752
+ hidden_states=hidden_states,
753
+ attention_mask=attention_mask,
754
+ position_ids=position_ids,
755
+ past_key_value=past_key_value,
756
+ output_attentions=output_attentions,
757
+ use_cache=use_cache,
758
+ )
759
+
760
+ bsz, q_len, _ = hidden_states.size()
761
+
762
+ qkv = self.qkv_proj(hidden_states)
763
+ query_pos = self.num_heads * self.head_dim
764
+ query_states = qkv[..., :query_pos]
765
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
766
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
767
+
768
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
769
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
770
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
771
+
772
+ kv_seq_len = key_states.shape[-2]
773
+ if past_key_value is not None:
774
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
775
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)
776
+
777
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
778
+
779
+ if past_key_value is not None:
780
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
781
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
782
+
783
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
784
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
785
+
786
+ if attention_mask is not None:
787
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
788
+ raise ValueError(
789
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
790
+ )
791
+
792
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
793
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
794
+ if query_states.device.type == "cuda" and attention_mask is not None:
795
+ query_states = query_states.contiguous()
796
+ key_states = key_states.contiguous()
797
+ value_states = value_states.contiguous()
798
+
799
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
800
+ query_states,
801
+ key_states,
802
+ value_states,
803
+ attn_mask=attention_mask,
804
+ dropout_p=self.attention_dropout if self.training else 0.0,
805
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
806
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
807
+ )
808
+
809
+ attn_output = attn_output.transpose(1, 2).contiguous()
810
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
811
+
812
+ attn_output = self.o_proj(attn_output)
813
+
814
+ return attn_output, None, past_key_value
815
+
816
+
817
+ PHI3_ATTENTION_CLASSES = {
818
+ "eager": Phi3Attention,
819
+ "flash_attention_2": Phi3FlashAttention2,
820
+ "sdpa": Phi3SdpaAttention,
821
+ }
822
+
823
+
824
+ class Phi3DecoderLayer(nn.Module):
825
+ def __init__(self, config: Phi3VConfig, layer_idx: int):
826
+ super().__init__()
827
+
828
+ self.config = config
829
+ self.self_attn = PHI3_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
830
+
831
+ self.mlp = Phi3MLP(config)
832
+ self.input_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
833
+
834
+ self.resid_attn_dropout = nn.Dropout(config.resid_pdrop)
835
+ self.resid_mlp_dropout = nn.Dropout(config.resid_pdrop)
836
+ self.post_attention_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
837
+
838
+ def forward(
839
+ self,
840
+ hidden_states: torch.Tensor,
841
+ attention_mask: Optional[torch.Tensor] = None,
842
+ position_ids: Optional[torch.LongTensor] = None,
843
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
844
+ output_attentions: Optional[bool] = False,
845
+ use_cache: Optional[bool] = False,
846
+ **kwargs,
847
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
848
+ if "padding_mask" in kwargs:
849
+ warnings.warn(
850
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
851
+ )
852
+ """
853
+ Args:
854
+ hidden_states (`torch.FloatTensor`):
855
+ input to the layer of shape `(batch, seq_len, embed_dim)`
856
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
857
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
858
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
859
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
860
+ `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
861
+ output_attentions (`bool`, *optional*):
862
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
863
+ returned tensors for more detail.
864
+ use_cache (`bool`, *optional*):
865
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
866
+ (see `past_key_values`).
867
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
868
+ """
869
+
870
+ residual = hidden_states
871
+
872
+ hidden_states = self.input_layernorm(hidden_states)
873
+
874
+ # Self Attention
875
+ attn_outputs, self_attn_weights, present_key_value = self.self_attn(
876
+ hidden_states=hidden_states,
877
+ attention_mask=attention_mask,
878
+ position_ids=position_ids,
879
+ past_key_value=past_key_value,
880
+ output_attentions=output_attentions,
881
+ use_cache=use_cache,
882
+ )
883
+
884
+ hidden_states = residual + self.resid_attn_dropout(attn_outputs)
885
+
886
+ residual = hidden_states
887
+ hidden_states = self.post_attention_layernorm(hidden_states)
888
+ hidden_states = self.mlp(hidden_states)
889
+ hidden_states = residual + self.resid_mlp_dropout(hidden_states)
890
+
891
+ outputs = (hidden_states,)
892
+
893
+ if output_attentions:
894
+ outputs += (self_attn_weights,)
895
+
896
+ if use_cache:
897
+ outputs += (present_key_value,)
898
+
899
+ return outputs
900
+
901
+
902
+ PHI3V_START_DOCSTRING = r"""
903
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
904
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
905
+ etc.)
906
+
907
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
908
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
909
+ and behavior.
910
+
911
+ Parameters:
912
+ config ([`Phi3VConfig`]):
913
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
914
+ load the weights associated with the model, only the configuration. Check out the
915
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
916
+ """
917
+
918
+
919
+ @add_start_docstrings(
920
+ "The bare Phi-3-V model outputting raw hidden-states without any specific head on top.",
921
+ PHI3V_START_DOCSTRING,
922
+ )
923
+ class Phi3VPreTrainedModel(PreTrainedModel):
924
+ config_class = Phi3VConfig
925
+ base_model_prefix = "model"
926
+ supports_gradient_checkpointing = True
927
+ _no_split_modules = ["Phi3DecoderLayer"]
928
+ _skip_keys_device_placement = "past_key_values"
929
+ _supports_flash_attn_2 = True
930
+ _supports_sdpa = False
931
+ _supports_cache_class = True
932
+
933
+ _version = "0.0.5"
934
+
935
+ def _init_weights(self, module):
936
+ std = self.config.initializer_range
937
+ if isinstance(module, nn.Linear):
938
+ module.weight.data.normal_(mean=0.0, std=std)
939
+ if module.bias is not None:
940
+ module.bias.data.zero_()
941
+ elif isinstance(module, nn.Embedding):
942
+ module.weight.data.normal_(mean=0.0, std=std)
943
+ if module.padding_idx is not None:
944
+ module.weight.data[module.padding_idx].zero_()
945
+
946
+
947
+ PHI3V_INPUTS_DOCSTRING = r"""
948
+ Args:
949
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
950
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
951
+ it.
952
+
953
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
954
+ [`PreTrainedTokenizer.__call__`] for details.
955
+
956
+ [What are input IDs?](../glossary#input-ids)
957
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
958
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
959
+
960
+ - 1 for tokens that are **not masked**,
961
+ - 0 for tokens that are **masked**.
962
+
963
+ [What are attention masks?](../glossary#attention-mask)
964
+
965
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
966
+ [`PreTrainedTokenizer.__call__`] for details.
967
+
968
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
969
+ `past_key_values`).
970
+
971
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
972
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
973
+ information on the default strategy.
974
+
975
+ - 1 indicates the head is **not masked**,
976
+ - 0 indicates the head is **masked**.
977
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
978
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
979
+ config.n_positions - 1]`.
980
+
981
+ [What are position IDs?](../glossary#position-ids)
982
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
983
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
984
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
985
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
986
+
987
+ Two formats are allowed:
988
+ - a [`~cache_utils.Cache`] instance;
989
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
990
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
991
+ cache format.
992
+
993
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
994
+ legacy cache format will be returned.
995
+
996
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
997
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
998
+ of shape `(batch_size, sequence_length)`.
999
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1000
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1001
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1002
+ model's internal embedding lookup matrix.
1003
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)):
1004
+ The tensors corresponding to the input images. Pixel values can be obtained using [`AutoImageProcessor`].
1005
+ See [`Phi3ImageProcessor.__call__`] for details.
1006
+ image_sizes (`torch.LongTensor` of shape `(batch_size, 2)`, *optional*):
1007
+ The sizes of the images in the batch, being (height, width) for each image.
1008
+ use_cache (`bool`, *optional*):
1009
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1010
+ `past_key_values`).
1011
+ output_attentions (`bool`, *optional*):
1012
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1013
+ tensors for more detail.
1014
+ output_hidden_states (`bool`, *optional*):
1015
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1016
+ more detail.
1017
+ return_dict (`bool`, *optional*):
1018
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1019
+ """
1020
+
1021
+
1022
+ @add_start_docstrings(
1023
+ "The bare Phi-3-V model outputting raw hidden-states without any specific head on top.",
1024
+ PHI3V_START_DOCSTRING,
1025
+ )
1026
+ class Phi3VModel(Phi3VPreTrainedModel):
1027
+ """
1028
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Phi3DecoderLayer`]
1029
+
1030
+ Args:
1031
+ config: Phi3Config
1032
+ """
1033
+
1034
+ def __init__(self, config: Phi3VConfig):
1035
+ super().__init__(config)
1036
+ self.padding_idx = config.pad_token_id
1037
+ self.vocab_size = config.vocab_size
1038
+
1039
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1040
+ self.embed_dropout = nn.Dropout(config.embd_pdrop)
1041
+ self.combined_embed = Phi3Embedding(self.embed_tokens, config.vocab_size)
1042
+
1043
+ self.vision_embed_tokens = None
1044
+ if isinstance(config.embd_layer, dict):
1045
+ # vision embedding layer
1046
+ embedding_config = {
1047
+ 'embedding_cls': config.embd_layer['embedding_cls'],
1048
+ **config.embd_layer
1049
+ }
1050
+ self.vision_embed_tokens = Phi3ImageEmbedding(config, wte=self.embed_tokens, **embedding_config)
1051
+ # # set wte the same for vision embedding
1052
+ # self.vision_embed_tokens.wte.weight = self.embed_tokens.weight
1053
+
1054
+ self.layers = nn.ModuleList(
1055
+ [Phi3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1056
+ )
1057
+ self._attn_implementation = config._attn_implementation
1058
+ self.norm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1059
+
1060
+ self.gradient_checkpointing = False
1061
+ # Initialize weights and apply final processing
1062
+ self.post_init()
1063
+
1064
+ def get_input_embeddings(self):
1065
+ return self.embed_tokens
1066
+
1067
+ def set_input_embeddings(self, value):
1068
+ self.embed_tokens = value
1069
+
1070
+ @add_start_docstrings_to_model_forward(PHI3V_INPUTS_DOCSTRING)
1071
+ def forward(
1072
+ self,
1073
+ input_ids: torch.LongTensor = None,
1074
+ attention_mask: Optional[torch.Tensor] = None,
1075
+ position_ids: Optional[torch.LongTensor] = None,
1076
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1077
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1078
+ pixel_values: Optional[torch.FloatTensor] = None,
1079
+ image_sizes: Optional[torch.LongTensor] = None,
1080
+ use_cache: Optional[bool] = None,
1081
+ output_attentions: Optional[bool] = None,
1082
+ output_hidden_states: Optional[bool] = None,
1083
+ return_dict: Optional[bool] = None,
1084
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1085
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1086
+ output_hidden_states = (
1087
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1088
+ )
1089
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1090
+
1091
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1092
+
1093
+ # retrieve input_ids and inputs_embeds
1094
+ if input_ids is not None and inputs_embeds is not None:
1095
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1096
+ elif input_ids is not None:
1097
+ batch_size, seq_length = input_ids.shape[:2]
1098
+ elif inputs_embeds is not None:
1099
+ batch_size, seq_length = inputs_embeds.shape[:2]
1100
+ else:
1101
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1102
+
1103
+ past_key_values_length = 0
1104
+
1105
+ if self.gradient_checkpointing and self.training:
1106
+ if use_cache:
1107
+ logger.warning_once(
1108
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1109
+ )
1110
+ use_cache = False
1111
+
1112
+ if use_cache:
1113
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1114
+ if use_legacy_cache:
1115
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1116
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1117
+
1118
+ if position_ids is None:
1119
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1120
+ position_ids = torch.arange(
1121
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1122
+ )
1123
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1124
+ else:
1125
+ position_ids = position_ids.view(-1, seq_length).long()
1126
+
1127
+ if inputs_embeds is None:
1128
+ if pixel_values is not None and image_sizes is not None:
1129
+ assert self.vision_embed_tokens is not None, "Vision embedding layer is not defined"
1130
+ # inputs_embeds = self.vision_embed_tokens(input_ids, pixel_values=pixel_values, image_sizes=image_sizes)
1131
+ inputs_embeds = self.vision_embed_tokens(pixel_values=pixel_values, image_sizes=image_sizes)
1132
+ else:
1133
+ inputs_embeds = self.embed_tokens(input_ids)
1134
+
1135
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
1136
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1137
+ if is_padding_right:
1138
+ raise ValueError(
1139
+ "You are attempting to perform batched generation with padding_side='right'"
1140
+ " this may lead to unexpected behaviour for Flash Attention version of Phi3. Make sure to "
1141
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1142
+ )
1143
+
1144
+ if self._attn_implementation == "flash_attention_2":
1145
+ # 2d mask is passed through the layers
1146
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1147
+ else:
1148
+ # 4d mask is passed through the layers
1149
+ attention_mask = _prepare_4d_causal_attention_mask(
1150
+ attention_mask,
1151
+ (batch_size, seq_length),
1152
+ inputs_embeds,
1153
+ past_key_values_length,
1154
+ sliding_window=self.config.sliding_window,
1155
+ )
1156
+
1157
+ hidden_states = inputs_embeds
1158
+
1159
+ # decoder layers
1160
+ all_hidden_states = () if output_hidden_states else None
1161
+ all_self_attns = () if output_attentions else None
1162
+ next_decoder_cache = None
1163
+
1164
+ for decoder_layer in self.layers:
1165
+ if output_hidden_states:
1166
+ all_hidden_states += (hidden_states,)
1167
+
1168
+ if self.gradient_checkpointing and self.training:
1169
+ layer_outputs = self._gradient_checkpointing_func(
1170
+ decoder_layer.__call__,
1171
+ hidden_states,
1172
+ attention_mask,
1173
+ position_ids,
1174
+ past_key_values,
1175
+ output_attentions,
1176
+ use_cache,
1177
+ )
1178
+ else:
1179
+ layer_outputs = decoder_layer(
1180
+ hidden_states,
1181
+ attention_mask=attention_mask,
1182
+ position_ids=position_ids,
1183
+ past_key_value=past_key_values,
1184
+ output_attentions=output_attentions,
1185
+ use_cache=use_cache,
1186
+ )
1187
+
1188
+ hidden_states = layer_outputs[0]
1189
+
1190
+ if use_cache:
1191
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1192
+
1193
+ if output_attentions:
1194
+ all_self_attns += (layer_outputs[1],)
1195
+
1196
+ hidden_states = self.norm(hidden_states)
1197
+
1198
+ # add hidden states from the last decoder layer
1199
+ if output_hidden_states:
1200
+ all_hidden_states += (hidden_states,)
1201
+
1202
+ next_cache = None
1203
+ if use_cache:
1204
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1205
+ if not return_dict:
1206
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1207
+ return BaseModelOutputWithPast(
1208
+ last_hidden_state=hidden_states,
1209
+ past_key_values=next_cache,
1210
+ hidden_states=all_hidden_states,
1211
+ attentions=all_self_attns,
1212
+ )
1213
+
1214
+
1215
+ class Phi3VForCausalLM(Phi3VPreTrainedModel):
1216
+ _tied_weights_keys = ["lm_head.weight"]
1217
+
1218
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with Llama->Phi3
1219
+ def __init__(self, config):
1220
+ super().__init__(config)
1221
+ self.model = Phi3VModel(config)
1222
+ self.vocab_size = config.vocab_size
1223
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1224
+
1225
+ # Initialize weights and apply final processing
1226
+ self.post_init()
1227
+
1228
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_input_embeddings
1229
+ def get_input_embeddings(self):
1230
+ return self.model.embed_tokens
1231
+
1232
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_input_embeddings
1233
+ def set_input_embeddings(self, value):
1234
+ self.model.embed_tokens = value
1235
+
1236
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_output_embeddings
1237
+ def get_output_embeddings(self):
1238
+ return self.lm_head
1239
+
1240
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_output_embeddings
1241
+ def set_output_embeddings(self, new_embeddings):
1242
+ self.lm_head = new_embeddings
1243
+
1244
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_decoder
1245
+ def set_decoder(self, decoder):
1246
+ self.model = decoder
1247
+
1248
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_decoder
1249
+ def get_decoder(self):
1250
+ return self.model
1251
+
1252
+ # Ignore copy
1253
+ @add_start_docstrings_to_model_forward(PHI3V_INPUTS_DOCSTRING)
1254
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1255
+ def forward(
1256
+ self,
1257
+ input_ids: torch.LongTensor = None,
1258
+ attention_mask: Optional[torch.Tensor] = None,
1259
+ position_ids: Optional[torch.LongTensor] = None,
1260
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1261
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1262
+ pixel_values: Optional[torch.FloatTensor] = None,
1263
+ image_sizes: Optional[torch.LongTensor] = None,
1264
+ labels: Optional[torch.LongTensor] = None,
1265
+ use_cache: Optional[bool] = None,
1266
+ output_attentions: Optional[bool] = None,
1267
+ output_hidden_states: Optional[bool] = None,
1268
+ return_dict: Optional[bool] = None,
1269
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1270
+ r"""
1271
+ Args:
1272
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1273
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1274
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1275
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1276
+
1277
+ Returns:
1278
+
1279
+ Example:
1280
+
1281
+ ```python
1282
+ >>> from transformers import AutoTokenizer, Phi3ForCausalLM
1283
+
1284
+ >>> model = Phi3ForCausalLM.from_pretrained("microsoft/phi-3-mini-4k-instruct")
1285
+ >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-3-mini-4k-instruct")
1286
+
1287
+ >>> prompt = "This is an example script ."
1288
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1289
+
1290
+ >>> # Generate
1291
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1292
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1293
+ 'This is an example script .\n Certainly! Below is a sample script that demonstrates a simple task, such as calculating the sum'
1294
+ ```"""
1295
+
1296
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1297
+ output_hidden_states = (
1298
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1299
+ )
1300
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1301
+
1302
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1303
+ outputs = self.model(
1304
+ input_ids=input_ids,
1305
+ attention_mask=attention_mask,
1306
+ position_ids=position_ids,
1307
+ past_key_values=past_key_values,
1308
+ inputs_embeds=inputs_embeds,
1309
+ pixel_values=pixel_values,
1310
+ image_sizes=image_sizes,
1311
+ use_cache=use_cache,
1312
+ output_attentions=output_attentions,
1313
+ output_hidden_states=output_hidden_states,
1314
+ return_dict=return_dict,
1315
+ )
1316
+
1317
+ hidden_states = outputs[0]
1318
+ logits = self.lm_head(hidden_states)
1319
+ logits = logits.float()
1320
+
1321
+ loss = None
1322
+ if labels is not None:
1323
+ # Shift so that tokens < n predict n
1324
+ shift_logits = logits[..., :-1, :].contiguous()
1325
+ shift_labels = labels[..., 1:].contiguous()
1326
+ # Flatten the tokens
1327
+ loss_fct = CrossEntropyLoss()
1328
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1329
+ shift_labels = shift_labels.view(-1)
1330
+ # Enable model parallelism
1331
+ shift_labels = shift_labels.to(shift_logits.device)
1332
+ loss = loss_fct(shift_logits, shift_labels)
1333
+
1334
+ if not return_dict:
1335
+ output = (logits,) + outputs[1:]
1336
+ return (loss,) + output if loss is not None else output
1337
+
1338
+ return CausalLMOutputWithPast(
1339
+ loss=loss,
1340
+ logits=logits,
1341
+ past_key_values=outputs.past_key_values,
1342
+ hidden_states=outputs.hidden_states,
1343
+ attentions=outputs.attentions,
1344
+ )
1345
+
1346
+ # Copied from transformers.models.persimmon.modeling_persimmon.PersimmonForCausalLM.prepare_inputs_for_generation
1347
+ def prepare_inputs_for_generation(
1348
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, pixel_values=None, image_sizes=None, **kwargs
1349
+ ):
1350
+ if past_key_values is not None:
1351
+ if isinstance(past_key_values, Cache):
1352
+ cache_length = past_key_values.get_seq_length()
1353
+ past_length = past_key_values.seen_tokens
1354
+ max_cache_length = past_key_values.get_max_length()
1355
+ else:
1356
+ cache_length = past_length = past_key_values[0][0].shape[2]
1357
+ max_cache_length = None
1358
+
1359
+ # Keep only the unprocessed tokens:
1360
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1361
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1362
+ # input)
1363
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1364
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1365
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1366
+ # input_ids based on the past_length.
1367
+ elif past_length < input_ids.shape[1]:
1368
+ input_ids = input_ids[:, past_length:]
1369
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1370
+
1371
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1372
+ if (
1373
+ max_cache_length is not None
1374
+ and attention_mask is not None
1375
+ and cache_length + input_ids.shape[1] > max_cache_length
1376
+ ):
1377
+ attention_mask = attention_mask[:, -max_cache_length:]
1378
+
1379
+ position_ids = kwargs.get("position_ids", None)
1380
+ if attention_mask is not None and position_ids is None:
1381
+ # create position_ids on the fly for batch generation
1382
+ position_ids = attention_mask.long().cumsum(-1) - 1
1383
+ position_ids.masked_fill_(attention_mask == 0, 1)
1384
+ if past_key_values:
1385
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1386
+
1387
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1388
+ if inputs_embeds is not None and past_key_values is None:
1389
+ model_inputs = {"inputs_embeds": inputs_embeds}
1390
+ else:
1391
+ model_inputs = {"input_ids": input_ids}
1392
+
1393
+ model_inputs.update(
1394
+ {
1395
+ "position_ids": position_ids,
1396
+ "past_key_values": past_key_values,
1397
+ "use_cache": kwargs.get("use_cache"),
1398
+ "attention_mask": attention_mask,
1399
+ "pixel_values": pixel_values,
1400
+ "image_sizes": image_sizes,
1401
+ }
1402
+ )
1403
+ return model_inputs
1404
+
1405
+ @staticmethod
1406
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM._reorder_cache
1407
+ def _reorder_cache(past_key_values, beam_idx):
1408
+ reordered_past = ()
1409
+ for layer_past in past_key_values:
1410
+ reordered_past += (
1411
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1412
+ )
1413
+ return reordered_past
1414
+
1415
+
1416
+ @add_start_docstrings(
1417
+ """
1418
+ The [`Phi3VModel`] with a sequence classification head on top (linear layer).
1419
+
1420
+ [`Phi3VForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1421
+ (e.g. GPT-2) do.
1422
+
1423
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1424
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1425
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1426
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1427
+ each row of the batch).
1428
+ """,
1429
+ PHI3V_START_DOCSTRING,
1430
+ )
1431
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->Phi3, LLAMA->PHI3, self.transformer->self.model, transformer_outputs->model_outputs
1432
+ class Phi3VForSequenceClassification(Phi3VPreTrainedModel):
1433
+ def __init__(self, config):
1434
+ super().__init__(config)
1435
+ self.num_labels = config.num_labels
1436
+ self.model = Phi3VModel(config)
1437
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1438
+
1439
+ # Initialize weights and apply final processing
1440
+ self.post_init()
1441
+
1442
+ def get_input_embeddings(self):
1443
+ return self.model.embed_tokens
1444
+
1445
+ def set_input_embeddings(self, value):
1446
+ self.model.embed_tokens = value
1447
+
1448
+ @add_start_docstrings_to_model_forward(PHI3V_INPUTS_DOCSTRING)
1449
+ def forward(
1450
+ self,
1451
+ input_ids: torch.LongTensor = None,
1452
+ attention_mask: Optional[torch.Tensor] = None,
1453
+ position_ids: Optional[torch.LongTensor] = None,
1454
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1455
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1456
+ pixel_values: Optional[torch.FloatTensor] = None,
1457
+ image_sizes: Optional[torch.LongTensor] = None,
1458
+ labels: Optional[torch.LongTensor] = None,
1459
+ use_cache: Optional[bool] = None,
1460
+ output_attentions: Optional[bool] = None,
1461
+ output_hidden_states: Optional[bool] = None,
1462
+ return_dict: Optional[bool] = None,
1463
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1464
+ r"""
1465
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1466
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1467
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1468
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1469
+ """
1470
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1471
+
1472
+ model_outputs = self.model(
1473
+ input_ids,
1474
+ attention_mask=attention_mask,
1475
+ position_ids=position_ids,
1476
+ past_key_values=past_key_values,
1477
+ inputs_embeds=inputs_embeds,
1478
+ pixel_values=pixel_values,
1479
+ image_sizes=image_sizes,
1480
+ use_cache=use_cache,
1481
+ output_attentions=output_attentions,
1482
+ output_hidden_states=output_hidden_states,
1483
+ return_dict=return_dict,
1484
+ )
1485
+ hidden_states = model_outputs[0]
1486
+ logits = self.score(hidden_states)
1487
+
1488
+ if input_ids is not None:
1489
+ batch_size = input_ids.shape[0]
1490
+ else:
1491
+ batch_size = inputs_embeds.shape[0]
1492
+
1493
+ if self.config.pad_token_id is None and batch_size != 1:
1494
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1495
+ if self.config.pad_token_id is None:
1496
+ sequence_lengths = -1
1497
+ else:
1498
+ if input_ids is not None:
1499
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1500
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1501
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1502
+ sequence_lengths = sequence_lengths.to(logits.device)
1503
+ else:
1504
+ sequence_lengths = -1
1505
+
1506
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1507
+
1508
+ loss = None
1509
+ if labels is not None:
1510
+ labels = labels.to(logits.device)
1511
+ if self.config.problem_type is None:
1512
+ if self.num_labels == 1:
1513
+ self.config.problem_type = "regression"
1514
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1515
+ self.config.problem_type = "single_label_classification"
1516
+ else:
1517
+ self.config.problem_type = "multi_label_classification"
1518
+
1519
+ if self.config.problem_type == "regression":
1520
+ loss_fct = MSELoss()
1521
+ if self.num_labels == 1:
1522
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1523
+ else:
1524
+ loss = loss_fct(pooled_logits, labels)
1525
+ elif self.config.problem_type == "single_label_classification":
1526
+ loss_fct = CrossEntropyLoss()
1527
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1528
+ elif self.config.problem_type == "multi_label_classification":
1529
+ loss_fct = BCEWithLogitsLoss()
1530
+ loss = loss_fct(pooled_logits, labels)
1531
+ if not return_dict:
1532
+ output = (pooled_logits,) + model_outputs[1:]
1533
+ return ((loss,) + output) if loss is not None else output
1534
+
1535
+ return SequenceClassifierOutputWithPast(
1536
+ loss=loss,
1537
+ logits=pooled_logits,
1538
+ past_key_values=model_outputs.past_key_values,
1539
+ hidden_states=model_outputs.hidden_states,
1540
+ attentions=model_outputs.attentions,
1541
+ )
1542
+
1543
+
1544
+ @add_start_docstrings(
1545
+ """
1546
+ [`Phi3VModel`] with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1547
+ Named-Entity-Recognition (NER) tasks.
1548
+ """,
1549
+ PHI3V_START_DOCSTRING,
1550
+ )
1551
+ # Copied from transformers.models.mpt.modeling_mpt.MptForTokenClassification with Mpt->Phi3,MPT->PHI3,self.transformer->self.model,transformer_outputs->model_outputs
1552
+ class Phi3VForTokenClassification(Phi3VPreTrainedModel):
1553
+ def __init__(self, config: Phi3VConfig):
1554
+ super().__init__(config)
1555
+ self.num_labels = config.num_labels
1556
+
1557
+ self.model = Phi3VModel(config)
1558
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
1559
+ classifier_dropout = config.classifier_dropout
1560
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
1561
+ classifier_dropout = config.hidden_dropout
1562
+ else:
1563
+ classifier_dropout = 0.1
1564
+ self.dropout = nn.Dropout(classifier_dropout)
1565
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1566
+
1567
+ # Initialize weights and apply final processing
1568
+ self.post_init()
1569
+
1570
+ @add_start_docstrings_to_model_forward(PHI3V_INPUTS_DOCSTRING)
1571
+ @add_code_sample_docstrings(
1572
+ checkpoint=_CHECKPOINT_FOR_DOC,
1573
+ output_type=TokenClassifierOutput,
1574
+ config_class=_CONFIG_FOR_DOC,
1575
+ )
1576
+ def forward(
1577
+ self,
1578
+ input_ids: Optional[torch.LongTensor] = None,
1579
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1580
+ attention_mask: Optional[torch.Tensor] = None,
1581
+ inputs_embeds: Optional[torch.Tensor] = None,
1582
+ pixel_values: Optional[torch.FloatTensor] = None,
1583
+ image_sizes: Optional[torch.LongTensor] = None,
1584
+ labels: Optional[torch.Tensor] = None,
1585
+ use_cache: Optional[bool] = None,
1586
+ output_attentions: Optional[bool] = None,
1587
+ output_hidden_states: Optional[bool] = None,
1588
+ return_dict: Optional[bool] = None,
1589
+ **deprecated_arguments,
1590
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1591
+ r"""
1592
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1593
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1594
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1595
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1596
+ """
1597
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1598
+
1599
+ model_outputs = self.model(
1600
+ input_ids,
1601
+ past_key_values=past_key_values,
1602
+ attention_mask=attention_mask,
1603
+ inputs_embeds=inputs_embeds,
1604
+ pixel_values=pixel_values,
1605
+ image_sizes=image_sizes,
1606
+ use_cache=use_cache,
1607
+ output_attentions=output_attentions,
1608
+ output_hidden_states=output_hidden_states,
1609
+ return_dict=return_dict,
1610
+ )
1611
+
1612
+ hidden_states = model_outputs[0]
1613
+ hidden_states = self.dropout(hidden_states)
1614
+ logits = self.classifier(hidden_states)
1615
+
1616
+ loss = None
1617
+ if labels is not None:
1618
+ # move labels to correct device to enable model parallelism
1619
+ labels = labels.to(logits.device)
1620
+ batch_size, seq_length = labels.shape
1621
+ loss_fct = CrossEntropyLoss()
1622
+ loss = loss_fct(
1623
+ logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
1624
+ )
1625
+
1626
+ if not return_dict:
1627
+ output = (logits,) + model_outputs[2:]
1628
+ return ((loss,) + output) if loss is not None else output
1629
+
1630
+ return TokenClassifierOutput(
1631
+ loss=loss,
1632
+ logits=logits,
1633
+ hidden_states=model_outputs.hidden_states,
1634
+ attentions=model_outputs.attentions,
1635
+ )