kvaishnavi commited on
Commit
bd10177
1 Parent(s): 2ea77f6

Upload Phi-3.5-vision-instruct scripts to make ONNX models

Browse files
Files changed (3) hide show
  1. onnx/builder.py +232 -0
  2. onnx/config.json +151 -0
  3. onnx/modeling_phi3_v.py +2085 -0
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.5-v-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.replace("dml", "cuda"), dtype=torch.int64),
113
+ "image_features": torch.randn(num_img_tokens, config.hidden_size, device=args.execution_provider.replace("dml", "cuda"), dtype=args.precision),
114
+ "inputs_embeds": torch.randn(batch_size, sequence_length, config.hidden_size, device=args.execution_provider.replace("dml", "cuda"), 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.5-v-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.5-v-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.5 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,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "Phi-3.5-vision-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
+ "embd_pdrop": 0.0,
20
+ "eos_token_id": 2,
21
+ "hidden_act": "silu",
22
+ "hidden_size": 3072,
23
+ "img_processor": {
24
+ "image_dim_out": 1024,
25
+ "model_name": "openai/clip-vit-large-patch14-336",
26
+ "name": "clip_vision_model",
27
+ "num_img_tokens": 144
28
+ },
29
+ "initializer_range": 0.02,
30
+ "intermediate_size": 8192,
31
+ "max_position_embeddings": 131072,
32
+ "model_type": "phi3_v",
33
+ "num_attention_heads": 32,
34
+ "num_hidden_layers": 32,
35
+ "num_key_value_heads": 32,
36
+ "original_max_position_embeddings": 4096,
37
+ "pad_token_id": 32000,
38
+ "resid_pdrop": 0.0,
39
+ "rms_norm_eps": 1e-05,
40
+ "rope_scaling": {
41
+ "long_factor": [
42
+ 1.0800000429153442,
43
+ 1.1100000143051147,
44
+ 1.1399999856948853,
45
+ 1.340000033378601,
46
+ 1.5899999141693115,
47
+ 1.600000023841858,
48
+ 1.6200000047683716,
49
+ 2.620000123977661,
50
+ 3.2300000190734863,
51
+ 3.2300000190734863,
52
+ 4.789999961853027,
53
+ 7.400000095367432,
54
+ 7.700000286102295,
55
+ 9.09000015258789,
56
+ 12.199999809265137,
57
+ 17.670000076293945,
58
+ 24.46000099182129,
59
+ 28.57000160217285,
60
+ 30.420001983642578,
61
+ 30.840002059936523,
62
+ 32.590003967285156,
63
+ 32.93000411987305,
64
+ 42.320003509521484,
65
+ 44.96000289916992,
66
+ 50.340003967285156,
67
+ 50.45000457763672,
68
+ 57.55000305175781,
69
+ 57.93000411987305,
70
+ 58.21000289916992,
71
+ 60.1400032043457,
72
+ 62.61000442504883,
73
+ 62.62000274658203,
74
+ 62.71000289916992,
75
+ 63.1400032043457,
76
+ 63.1400032043457,
77
+ 63.77000427246094,
78
+ 63.93000411987305,
79
+ 63.96000289916992,
80
+ 63.970001220703125,
81
+ 64.02999877929688,
82
+ 64.06999969482422,
83
+ 64.08000183105469,
84
+ 64.12000274658203,
85
+ 64.41000366210938,
86
+ 64.4800033569336,
87
+ 64.51000213623047,
88
+ 64.52999877929688,
89
+ 64.83999633789062
90
+ ],
91
+ "short_factor": [
92
+ 1.08,
93
+ 1.1,
94
+ 1.1300000000000001,
95
+ 1.2800000000000002,
96
+ 1.3100000000000003,
97
+ 1.4500000000000004,
98
+ 1.4500000000000004,
99
+ 1.9500000000000008,
100
+ 2.030000000000001,
101
+ 2.4299999999999926,
102
+ 2.5699999999999896,
103
+ 2.9499999999999815,
104
+ 3.729999999999965,
105
+ 3.869999999999962,
106
+ 4.189999999999955,
107
+ 4.43999999999995,
108
+ 4.6399999999999455,
109
+ 4.979999999999938,
110
+ 5.159999999999934,
111
+ 5.279999999999932,
112
+ 5.759999999999922,
113
+ 5.889999999999919,
114
+ 5.889999999999919,
115
+ 5.969999999999917,
116
+ 6.089999999999915,
117
+ 6.2799999999999105,
118
+ 6.7699999999999,
119
+ 6.8899999999998975,
120
+ 7.109999999999893,
121
+ 7.129999999999892,
122
+ 7.179999999999891,
123
+ 7.289999999999889,
124
+ 7.339999999999888,
125
+ 7.559999999999883,
126
+ 7.619999999999882,
127
+ 7.69999999999988,
128
+ 7.879999999999876,
129
+ 7.879999999999876,
130
+ 7.879999999999876,
131
+ 7.939999999999875,
132
+ 7.949999999999875,
133
+ 7.979999999999874,
134
+ 8.19999999999987,
135
+ 8.439999999999864,
136
+ 8.469999999999864,
137
+ 8.589999999999861,
138
+ 8.809999999999857,
139
+ 8.999999999999853
140
+ ],
141
+ "type": "su"
142
+ },
143
+ "rope_theta": 10000.0,
144
+ "sliding_window": 262144,
145
+ "tie_word_embeddings": false,
146
+ "torch_dtype": "bfloat16",
147
+ "transformers_version": "4.38.1",
148
+ "use_cache": true,
149
+ "vocab_size": 32064,
150
+ "_attn_implementation": "eager"
151
+ }
onnx/modeling_phi3_v.py ADDED
@@ -0,0 +1,2085 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
49
+ try:
50
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
51
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
52
+
53
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
54
+ except ImportError:
55
+ pass
56
+
57
+ import torch
58
+ from torch import nn
59
+ from transformers import CLIPVisionConfig, CLIPVisionModel, PretrainedConfig
60
+ from transformers.models.clip.modeling_clip import CLIPAttention
61
+ from transformers.utils import logging
62
+
63
+ logger = logging.get_logger(__name__)
64
+
65
+
66
+ MAX_INPUT_ID = int(1e9)
67
+
68
+ CLIP_VIT_LARGE_PATCH14_336_CONFIG = CLIPVisionConfig(
69
+ attention_dropout=0.0,
70
+ dropout=0.0,
71
+ hidden_act="quick_gelu",
72
+ hidden_size=1024,
73
+ image_size=336,
74
+ initializer_factor=1.0,
75
+ initializer_range=0.02,
76
+ intermediate_size=4096,
77
+ layer_norm_eps=1e-05,
78
+ num_attention_heads=16,
79
+ num_channels=3,
80
+ num_hidden_layers=24,
81
+ patch_size=14,
82
+ projection_dim=768,
83
+ attn_implementation="eager",
84
+ )
85
+
86
+ class CLIPAttentionFA2(CLIPAttention):
87
+ """Add flash attention 2 to CLIPAttention. (This is only used in the vision encoder)"""
88
+
89
+ def forward(self,
90
+ hidden_states,
91
+ attention_mask=None,
92
+ causal_attention_mask=None,
93
+ output_attentions=False,
94
+ ):
95
+ """Input shape: Batch x Time x Channel"""
96
+
97
+ assert attention_mask is None, "CLIPAttentionFA2 does not support attention_mask"
98
+ assert causal_attention_mask is None, "CLIPAttentionFA2 does not support causal_attention_mask"
99
+ assert output_attentions is False, "CLIPAttentionFA2 does not support output_attentions"
100
+
101
+ bsz, tgt_len, embed_dim = hidden_states.size()
102
+ query_states = self.q_proj(hidden_states).reshape(bsz, tgt_len, self.num_heads, self.head_dim)
103
+ key_states = self.k_proj(hidden_states).reshape(bsz, tgt_len, self.num_heads, self.head_dim)
104
+ value_states = self.v_proj(hidden_states).reshape(bsz, tgt_len, self.num_heads, self.head_dim)
105
+
106
+ attn_output = flash_attn_func(
107
+ query_states,
108
+ key_states,
109
+ value_states,
110
+ dropout_p=self.dropout if self.training else 0.0,
111
+ softmax_scale=self.scale,
112
+ causal=False,
113
+ ).reshape(bsz, tgt_len, embed_dim)
114
+
115
+ attn_output = self.out_proj(attn_output)
116
+ return attn_output, None
117
+
118
+
119
+ def reshape_hd_patches_2x2merge(image_features, h_crop, w_crop):
120
+ """
121
+ image_features: (num_images*num_crops, 24*24, 1024)
122
+ output: (num_images, h_crop*12, w_crop*12, 4096), h_crop*w_crop == num_crops
123
+ """
124
+ N, L, C = image_features.shape
125
+ assert L == 24 * 24 and C == 1024 and N % (h_crop * w_crop) == 0
126
+ num_images = torch.tensor(N // (h_crop * w_crop), dtype=torch.int64)
127
+ H = torch.tensor(int(L**0.5), dtype=torch.int64)
128
+ H_div_2 = torch.tensor(H // 2, dtype=torch.int64)
129
+
130
+ image_features_hd = (
131
+ image_features.reshape(N, H, H, C) # N, 24, 24, 1024
132
+ .reshape(N, H_div_2, 2, H_div_2, 2, C) # N, 12, 2, 12, 2, 1024
133
+ .permute(0, 1, 3, 2, 4, 5) # N, 12, 12, 2, 2, 1024
134
+ .reshape(N, -1, 4 * C) # N, 144, 4096
135
+ .reshape(
136
+ num_images, h_crop, w_crop, H_div_2, H_div_2, -1
137
+ ) # n_img, h_crop, w_crop, 12, 12, 4096
138
+ .permute(0, 1, 3, 2, 4, 5) # n_img, h_crop, 12, w_crop, 12, 4096
139
+ .reshape(
140
+ num_images, h_crop * H_div_2, w_crop * H_div_2, 4 * C
141
+ ) # n_img, h_crop*12, w_crop*12, 4096
142
+ )
143
+
144
+ return image_features_hd
145
+
146
+
147
+ def add_image_newline(image_features_hd, sub_GN):
148
+ """
149
+ image_features_hd: (num_images, h_crop*12, w_crop*12, 4096)
150
+ output: (num_images, (h_crop*12) * (w_crop*12+1), 4096)
151
+ """
152
+ num_images, h, w, hid_dim = image_features_hd.shape
153
+ # add the newline token to the HD image feature patches
154
+ newline_embeddings = sub_GN.expand(num_images, h, -1, -1) # (n_img, h, 1, hid_dim)
155
+ image_features_hd_newline = torch.cat(
156
+ [image_features_hd, newline_embeddings], dim=2
157
+ ).reshape(num_images, -1, hid_dim)
158
+ return image_features_hd_newline
159
+
160
+
161
+ @torch.jit.script_if_tracing
162
+ def get_image_embeddings(image_dim_out, image_sizes, image_features, global_image_features_hd_newline):
163
+ """
164
+ Get image embeddings for all images.
165
+ Need a for loop to process each image because of different image sizes
166
+ (patch arrangement is different for each image)
167
+ """
168
+ glb_GN = torch.zeros(1, 1, image_dim_out * 4).to(image_features.device)
169
+ sub_GN = torch.zeros(1, 1, 1, image_dim_out * 4).to(image_features.device)
170
+
171
+ all_image_embeddings = torch.empty(0, 4096).to(image_features.device)
172
+ for i, img_size in enumerate(image_sizes):
173
+ # h, w = img_size
174
+ h, w = img_size[0], img_size[1]
175
+ h_crop = torch.tensor(h // 336, dtype=torch.int64)
176
+ w_crop = torch.tensor(w // 336, dtype=torch.int64)
177
+ num_crops = h_crop * w_crop
178
+
179
+ # NOTE: real num_crops is padded
180
+ # (num_crops, 24*24, 1024)
181
+ sub_image_features = image_features[i, 1 : 1 + num_crops]
182
+ sub_image_features_hd = reshape_hd_patches_2x2merge(sub_image_features, h_crop, w_crop)
183
+ sub_image_features_hd_newline = add_image_newline(sub_image_features_hd, sub_GN)
184
+
185
+ # # [sub features, separator, global features]
186
+ # all_image_embeddings.extend(
187
+ # [
188
+ # sub_image_features_hd_newline.squeeze(0), # (h_crop*12*(w_crop*12+1), 4096)
189
+ # self.glb_GN.squeeze(0),
190
+ # global_image_features_hd_newline[i],
191
+ # ]
192
+ # )
193
+
194
+ # [sub features, separator, global features]
195
+ all_image_embeddings = torch.cat(
196
+ [
197
+ all_image_embeddings,
198
+ sub_image_features_hd_newline.view(-1, 4096), # (h_crop*12*(w_crop*12+1), 4096)
199
+ glb_GN.view(-1, 4096),
200
+ global_image_features_hd_newline[i],
201
+ ]
202
+ )
203
+
204
+ return all_image_embeddings
205
+
206
+
207
+ @torch.jit.script_if_tracing
208
+ def clamp_input_ids(input_ids: torch.LongTensor, image_features: torch.FloatTensor, vocab_size: int):
209
+ if image_features.numel():
210
+ input_shape = input_ids.size()
211
+ input_ids = input_ids.view(-1, input_shape[-1])
212
+
213
+ # positions for image tokens
214
+ condition = (input_ids < 0) & (input_ids > -int(1e9))
215
+ positions = torch.where(condition)
216
+ # has_image = len(positions[0].tolist()) > 0
217
+ input_ids = input_ids.clamp_min(0).clamp_max(vocab_size).detach()
218
+
219
+ return input_ids, positions
220
+
221
+ return input_ids, torch.where(torch.zeros((1, 1), dtype=torch.bool))
222
+
223
+
224
+ @torch.jit.script_if_tracing
225
+ def select_logic(hidden_states: torch.FloatTensor, image_features: torch.FloatTensor, positions: List[torch.LongTensor]):
226
+ if image_features.numel():
227
+ # apply 'select' logic
228
+ hidden_states = hidden_states.index_put(
229
+ positions, image_features, accumulate=False
230
+ )
231
+
232
+ return hidden_states
233
+
234
+
235
+ class Phi3Embedding(nn.Module):
236
+ """Phi3 embedding for text-only and vision + text."""
237
+ def __init__(self, wte, vocab_size):
238
+ super().__init__()
239
+ self.wte = wte
240
+ self.vocab_size = vocab_size
241
+
242
+ def forward(self, input_ids: torch.LongTensor, image_features: torch.FloatTensor) -> torch.FloatTensor:
243
+ input_ids, positions = clamp_input_ids(input_ids, image_features, self.vocab_size)
244
+ hidden_states = self.wte(input_ids)
245
+ hidden_states = select_logic(hidden_states, image_features, positions)
246
+ return hidden_states
247
+
248
+
249
+ class Phi3ImageEmbedding(nn.Module):
250
+ """Phi3 Image embedding."""
251
+
252
+ def __init__(self, config: PretrainedConfig, wte=None, **kwargs) -> None:
253
+ super().__init__()
254
+
255
+ # n_embed or hidden_size
256
+ hidden_size = config.n_embd if hasattr(config, 'n_embd') else config.hidden_size
257
+ if hasattr(config, 'embd_pdrop') or hasattr(config, 'embed_pdrop'):
258
+ embd_drop = config.embd_pdrop if hasattr(config, 'embd_pdrop') else config.embed_pdrop
259
+ self.drop = nn.Dropout(embd_drop)
260
+ else:
261
+ self.drop = None
262
+
263
+ self.wte = wte
264
+
265
+ if isinstance(config.img_processor, dict) and config.img_processor.get('name', None) == 'clip_vision_model':
266
+ assert 'model_name' in config.img_processor, 'model_name must be provided for CLIPVisionModel'
267
+ assert 'image_dim_out' in config.img_processor, 'image_dim_out must be provided for CLIPVisionModel'
268
+ assert 'num_img_tokens' in config.img_processor, 'num_img_tokens must be provided for CLIPVisionModel'
269
+ assert config.img_processor['model_name'] == 'openai/clip-vit-large-patch14-336'
270
+ clip_config = CLIP_VIT_LARGE_PATCH14_336_CONFIG
271
+ self.img_processor = CLIPVisionModel(clip_config)
272
+ image_dim_out = config.img_processor['image_dim_out']
273
+ self.num_img_tokens = config.img_processor['num_img_tokens']
274
+
275
+ # FA2 in CLIP
276
+ if config._attn_implementation == 'flash_attention_2':
277
+ for layer in self.img_processor.vision_model.encoder.layers:
278
+ clip_fa2 = CLIPAttentionFA2(clip_config)
279
+ del layer.self_attn
280
+ layer.self_attn = clip_fa2
281
+ else:
282
+ raise NotImplementedError(f'img_processor = {config.img_processor}, not implemented')
283
+
284
+ self.image_dim_out = image_dim_out
285
+ self.img_sizes = None
286
+
287
+ # global_gn and sub_gn for hd transform, serves as line separator
288
+ self.use_hd_transform = kwargs.get('use_hd_transform', False)
289
+ self.with_learnable_separator = kwargs.get('with_learnable_separator', False)
290
+ self.hd_transform_order = kwargs.get('hd_transform_order', 'glb_sub')
291
+ # with_hd_transform and with_learnable_separator should have same value
292
+ assert self.use_hd_transform == self.with_learnable_separator, 'use_hd_transform and with_learnable_separator should have same value'
293
+ if self.with_learnable_separator:
294
+ assert self.use_hd_transform, 'learnable separator is only for hd transform'
295
+ # 1024 * 4, merge spatial to channel dimension
296
+ self.glb_GN = nn.Parameter(torch.zeros([1, 1, self.image_dim_out * 4]))
297
+ self.sub_GN = nn.Parameter(torch.zeros([1, 1, 1, self.image_dim_out * 4]))
298
+ logger.info(f'learnable separator enabled for hd transform, hd_transform_order = {self.hd_transform_order}')
299
+
300
+ projection_cls = kwargs.get('projection_cls', 'linear')
301
+ if projection_cls == 'linear':
302
+ self.img_projection = nn.Linear(image_dim_out, hidden_size)
303
+ elif projection_cls == 'mlp' and self.use_hd_transform:
304
+ dim_projection = hidden_size
305
+ depth = 2
306
+ layers = [nn.Linear(image_dim_out * 4, dim_projection)]
307
+ for _ in range(1, depth):
308
+ layers.extend([nn.GELU(),
309
+ nn.Linear(dim_projection, dim_projection)])
310
+ self.img_projection = nn.Sequential(*layers)
311
+ elif projection_cls == 'mlp':
312
+ dim_projection = hidden_size
313
+ depth = 2
314
+ layers = [nn.Linear(image_dim_out, dim_projection)]
315
+ for _ in range(1, depth):
316
+ layers.extend([nn.GELU(),
317
+ nn.Linear(dim_projection, dim_projection)])
318
+ self.img_projection = nn.Sequential(*layers)
319
+ else:
320
+ raise NotImplementedError(f'projection_cls = {projection_cls}, not implemented')
321
+
322
+ self.vocab_size = config.vocab_size
323
+ self.img_features = None
324
+
325
+ if isinstance(config.img_processor, dict):
326
+ self.layer_idx = config.img_processor.get('layer_idx', -2)
327
+ self.type_feature = config.img_processor.get('type_feature', 'patch')
328
+ else:
329
+ self.layer_idx = -2
330
+ self.type_feature = 'patch'
331
+
332
+
333
+ def set_img_features(self, img_features: torch.FloatTensor) -> None:
334
+ self.img_features = img_features
335
+
336
+ def set_img_sizes(self, img_sizes: torch.LongTensor) -> None:
337
+ self.img_sizes = img_sizes
338
+
339
+ def get_img_features(self, img_embeds: torch.FloatTensor) -> torch.FloatTensor:
340
+ LAYER_IDX = self.layer_idx
341
+ TYPE_FEATURE = self.type_feature
342
+
343
+ img_processor_output = self.img_processor(img_embeds, output_hidden_states=True)
344
+ img_feature = img_processor_output.hidden_states[LAYER_IDX]
345
+
346
+ if TYPE_FEATURE == "patch":
347
+ patch_feature = img_feature[:, 1:]
348
+ return patch_feature
349
+
350
+ raise NotImplementedError
351
+
352
+ # def forward(
353
+ # self, input_ids: torch.LongTensor, pixel_values: torch.FloatTensor, image_sizes=None
354
+ # ) -> torch.FloatTensor:
355
+ # input_shape = input_ids.size()
356
+ # input_ids = input_ids.view(-1, input_shape[-1])
357
+
358
+ # # positions for image tokens
359
+ # positions = torch.nonzero((input_ids < 0) & (input_ids > -MAX_INPUT_ID), as_tuple=True)
360
+ # has_image = len(positions[0].tolist()) > 0
361
+ # input_ids = input_ids.clamp_min(0).clamp_max(self.vocab_size).detach()
362
+ # hidden_states = self.wte(input_ids)
363
+
364
+ # if has_image:
365
+ # assert self.use_hd_transform
366
+ # num_images, num_crops, c, h, w = pixel_values.shape
367
+ # assert c == 3 and h == w == 336
368
+ # img_features = self.get_img_features(pixel_values.flatten(0, 1)).reshape(
369
+ # num_images, num_crops, -1, self.image_dim_out
370
+ # )
371
+ # image_features_proj = self.hd_feature_transform(img_features, image_sizes)
372
+ # hidden_states = hidden_states.index_put(
373
+ # positions, image_features_proj, accumulate=False
374
+ # )
375
+
376
+ # if self.drop is not None:
377
+ # hidden_states = self.drop(hidden_states)
378
+
379
+ # return hidden_states
380
+
381
+ def forward(self, pixel_values: torch.FloatTensor, image_sizes=None) -> torch.FloatTensor:
382
+ assert self.use_hd_transform
383
+ num_images, num_crops, c, h, w = pixel_values.shape
384
+ assert c == 3 and h == w == 336
385
+ img_features = self.get_img_features(pixel_values.flatten(0, 1)).reshape(
386
+ num_images, num_crops, -1, self.image_dim_out
387
+ )
388
+ image_features_proj = self.hd_feature_transform(img_features, image_sizes)
389
+
390
+ return image_features_proj
391
+
392
+ def hd_feature_transform(self, image_features, image_sizes):
393
+ """
394
+ image_features: (num_images, num_crops+1, 24*24, 1024)
395
+ """
396
+ assert (
397
+ self.hd_transform_order == 'sub_glb'
398
+ ), f'hd_transform_order `{self.hd_transform_order}` not implemented'
399
+ if isinstance(self.img_projection, nn.Sequential):
400
+ target_device = self.img_projection[0].bias.device
401
+ target_dtype = self.img_projection[0].bias.dtype
402
+ else: # It's a single nn.Linear layer
403
+ target_device = self.img_projection.bias.device
404
+ target_dtype = self.img_projection.bias.dtype
405
+
406
+ global_image_features = image_features[:, 0] # (num_images, 24*24, 1024)
407
+ # global feature can be viewed as a special HD case with num_crops 1x1
408
+ global_image_features_hd = self.reshape_hd_patches_2x2merge(global_image_features, 1, 1)
409
+ global_image_features_hd_newline = self.add_image_newline(global_image_features_hd)
410
+
411
+ # all_image_embeddings = []
412
+ # # need a for loop to process each image because of different image sizes
413
+ # # (patch arrangement is different for each image)
414
+ # for i, img_size in enumerate(image_sizes):
415
+ # h, w = img_size
416
+ # h_crop = h // 336
417
+ # w_crop = w // 336
418
+ # num_crops = h_crop * w_crop
419
+
420
+ # # NOTE: real num_crops is padded
421
+ # # (num_crops, 24*24, 1024)
422
+ # sub_image_features = image_features[i, 1 : 1 + num_crops]
423
+ # sub_image_features_hd = self.reshape_hd_patches_2x2merge(
424
+ # sub_image_features, h_crop, w_crop
425
+ # )
426
+ # sub_image_features_hd_newline = self.add_image_newline(sub_image_features_hd)
427
+
428
+ # # [sub features, separator, global features]
429
+ # all_image_embeddings.extend(
430
+ # [
431
+ # sub_image_features_hd_newline.squeeze(0), # (h_crop*12*(w_crop*12+1), 4096)
432
+ # self.glb_GN.squeeze(0),
433
+ # global_image_features_hd_newline[i],
434
+ # ]
435
+ # )
436
+
437
+ # image_features_proj = self.img_projection(
438
+ # torch.cat(all_image_embeddings, dim=0).to(target_device).to(target_dtype)
439
+ # )
440
+
441
+ # return image_features_proj
442
+
443
+ all_image_embeddings = get_image_embeddings(torch.tensor(self.image_dim_out), image_sizes, image_features, global_image_features_hd_newline)
444
+ image_features_proj = self.img_projection(
445
+ all_image_embeddings.unsqueeze(0).to(target_device).to(target_dtype)
446
+ )
447
+ return image_features_proj.squeeze()
448
+
449
+ def reshape_hd_patches_2x2merge(self, image_features, h_crop, w_crop):
450
+ """
451
+ image_features: (num_images*num_crops, 24*24, 1024)
452
+ output: (num_images, h_crop*12, w_crop*12, 4096), h_crop*w_crop == num_crops
453
+ """
454
+ N, L, C = image_features.shape
455
+ assert L == 24 * 24 and C == 1024 and N % (h_crop * w_crop) == 0
456
+ num_images = N // (h_crop * w_crop)
457
+ H = int(L**0.5)
458
+ image_features_hd = (
459
+ image_features.reshape(N, H, H, C) # N, 24, 24, 1024
460
+ .reshape(N, H // 2, 2, H // 2, 2, C) # N, 12, 2, 12, 2, 1024
461
+ .permute(0, 1, 3, 2, 4, 5) # N, 12, 12, 2, 2, 1024
462
+ .reshape(N, -1, 4 * C) # N, 144, 4096
463
+ .reshape(
464
+ num_images, h_crop, w_crop, H // 2, H // 2, -1
465
+ ) # n_img, h_crop, w_crop, 12, 12, 4096
466
+ .permute(0, 1, 3, 2, 4, 5) # n_img, h_crop, 12, w_crop, 12, 4096
467
+ .reshape(
468
+ num_images, h_crop * H // 2, w_crop * H // 2, 4 * C
469
+ ) # n_img, h_crop*12, w_crop*12, 4096
470
+ )
471
+
472
+ # alternative implementation using einops
473
+ # from einops import rearrange
474
+ # image_features_nhwc = rearrange(
475
+ # image_features,
476
+ # 'N (H W) c -> N H W c',
477
+ # H=H,
478
+ # W=H,
479
+ # )
480
+ # image_features_2x2merge = rearrange(
481
+ # image_features_nhwc,
482
+ # 'N (h h_pool) (w w_pool) c -> N h w (h_pool w_pool c)',
483
+ # h_pool=2,
484
+ # w_pool=2,
485
+ # )
486
+ # image_features_hd = rearrange(
487
+ # image_features_2x2merge,
488
+ # '(n_img h_crop w_crop) h w C -> n_img (h_crop h) (w_crop w) C',
489
+ # h_crop=h_crop,
490
+ # w_crop=w_crop,
491
+ # )
492
+
493
+ return image_features_hd
494
+
495
+ def add_image_newline(self, image_features_hd):
496
+ """
497
+ image_features_hd: (num_images, h_crop*12, w_crop*12, 4096)
498
+ output: (num_images, (h_crop*12) * (w_crop*12+1), 4096)
499
+ """
500
+ num_images, h, w, hid_dim = image_features_hd.shape
501
+ # add the newline token to the HD image feature patches
502
+ newline_embeddings = self.sub_GN.expand(num_images, h, -1, -1) # (n_img, h, 1, hid_dim)
503
+ image_features_hd_newline = torch.cat(
504
+ [image_features_hd, newline_embeddings], dim=2
505
+ ).reshape(num_images, -1, hid_dim)
506
+ return image_features_hd_newline
507
+
508
+
509
+ logger = logging.get_logger(__name__)
510
+
511
+ _CHECKPOINT_FOR_DOC = "microsoft/Phi-3-vision-128k-instruct"
512
+ _CONFIG_FOR_DOC = "Phi3VConfig"
513
+
514
+ PHI3V_PRETRAINED_MODEL_ARCHIVE_LIST = [
515
+ "microsoft/Phi-3-vision-128k-instruct",
516
+ # See all Phi-3 models at https://huggingface.co/models?filter=Phi-3
517
+ ]
518
+
519
+
520
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Phi3
521
+ class Phi3RMSNorm(nn.Module):
522
+ def __init__(self, hidden_size, eps=1e-6):
523
+ """
524
+ Phi3RMSNorm is equivalent to T5LayerNorm
525
+ """
526
+ super().__init__()
527
+ self.weight = nn.Parameter(torch.ones(hidden_size))
528
+ self.variance_epsilon = eps
529
+
530
+ def forward(self, hidden_states):
531
+ input_dtype = hidden_states.dtype
532
+ hidden_states = hidden_states.to(torch.float32)
533
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
534
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
535
+ return self.weight * hidden_states.to(input_dtype)
536
+
537
+
538
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
539
+ def _get_unpad_data(attention_mask):
540
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
541
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
542
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
543
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
544
+ return (
545
+ indices,
546
+ cu_seqlens,
547
+ max_seqlen_in_batch,
548
+ )
549
+
550
+
551
+ # Copied from transformers.models.gemma.modeling_gemma.GemmaRotaryEmbedding with gemma->phi3, Gemma->Phi3
552
+ class Phi3RotaryEmbedding(nn.Module):
553
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
554
+ super().__init__()
555
+
556
+ self.dim = dim
557
+ self.max_position_embeddings = max_position_embeddings
558
+ self.base = base
559
+ self.register_buffer("inv_freq", None, persistent=False)
560
+
561
+ @torch.no_grad()
562
+ def forward(self, x, position_ids, seq_len=None):
563
+ # x: [bs, num_attention_heads, seq_len, head_size]
564
+ if self.inv_freq is None:
565
+ self.inv_freq = 1.0 / (
566
+ self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim)
567
+ )
568
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
569
+ position_ids_expanded = position_ids[:, None, :].float()
570
+ # Force float32 since bfloat16 loses precision on long contexts
571
+ # See https://github.com/huggingface/transformers/pull/29285
572
+ device_type = x.device.type
573
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
574
+ with torch.autocast(device_type=device_type, enabled=False):
575
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
576
+ emb = torch.cat((freqs, freqs), dim=-1)
577
+ cos = emb.cos()
578
+ sin = emb.sin()
579
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
580
+
581
+
582
+ class Phi3SuScaledRotaryEmbedding(Phi3RotaryEmbedding):
583
+ def __init__(self, dim, config, device=None):
584
+ super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)
585
+
586
+ self.short_factor = config.rope_scaling["short_factor"]
587
+ self.long_factor = config.rope_scaling["long_factor"]
588
+ self.original_max_position_embeddings = config.original_max_position_embeddings
589
+
590
+ @torch.no_grad()
591
+ def forward(self, x, position_ids, seq_len=None):
592
+ seq_len = torch.max(position_ids) + 1
593
+ if seq_len > self.original_max_position_embeddings:
594
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
595
+ else:
596
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
597
+
598
+ inv_freq_shape = torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim
599
+ self.inv_freq = 1.0 / (ext_factors * self.base**inv_freq_shape)
600
+
601
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
602
+ position_ids_expanded = position_ids[:, None, :].float()
603
+
604
+ # Force float32 since bfloat16 loses precision on long contexts
605
+ # See https://github.com/huggingface/transformers/pull/29285
606
+ device_type = x.device.type
607
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
608
+ with torch.autocast(device_type=device_type, enabled=False):
609
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
610
+ emb = torch.cat((freqs, freqs), dim=-1)
611
+
612
+ scale = self.max_position_embeddings / self.original_max_position_embeddings
613
+ if scale <= 1.0:
614
+ scaling_factor = 1.0
615
+ else:
616
+ scaling_factor = math.sqrt(1 + math.log(scale) / math.log(self.original_max_position_embeddings))
617
+
618
+ cos = emb.cos() * scaling_factor
619
+ sin = emb.sin() * scaling_factor
620
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
621
+
622
+
623
+ class Phi3YarnScaledRotaryEmbedding(Phi3RotaryEmbedding):
624
+ def __init__(self, dim, config, device=None):
625
+ super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)
626
+
627
+ self.short_factor = config.rope_scaling["short_factor"]
628
+ self.long_factor = config.rope_scaling["long_factor"]
629
+ self.original_max_position_embeddings = config.original_max_position_embeddings
630
+
631
+ @torch.no_grad()
632
+ def forward(self, x, position_ids, seq_len=None):
633
+ seq_len = torch.max(position_ids) + 1
634
+ if seq_len > self.original_max_position_embeddings:
635
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
636
+ else:
637
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
638
+
639
+ inv_freq_shape = torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim
640
+ self.inv_freq = 1.0 / (ext_factors * self.base**inv_freq_shape)
641
+
642
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
643
+ position_ids_expanded = position_ids[:, None, :].float()
644
+
645
+ # Force float32 since bfloat16 loses precision on long contexts
646
+ # See https://github.com/huggingface/transformers/pull/29285
647
+ device_type = x.device.type
648
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
649
+ with torch.autocast(device_type=device_type, enabled=False):
650
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
651
+ emb = torch.cat((freqs, freqs), dim=-1)
652
+
653
+ scale = self.max_position_embeddings / self.original_max_position_embeddings
654
+ if scale <= 1.0:
655
+ scaling_factor = 1.0
656
+ else:
657
+ scaling_factor = 0.1 * math.log(scale) + 1.0
658
+
659
+ cos = emb.cos() * scaling_factor
660
+ sin = emb.sin() * scaling_factor
661
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
662
+
663
+
664
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
665
+ def rotate_half(x):
666
+ """Rotates half the hidden dims of the input."""
667
+ x1 = x[..., : x.shape[-1] // 2]
668
+ x2 = x[..., x.shape[-1] // 2 :]
669
+ return torch.cat((-x2, x1), dim=-1)
670
+
671
+
672
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
673
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
674
+ """Applies Rotary Position Embedding to the query and key tensors.
675
+
676
+ Args:
677
+ q (`torch.Tensor`): The query tensor.
678
+ k (`torch.Tensor`): The key tensor.
679
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
680
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
681
+ position_ids (`torch.Tensor`, *optional*):
682
+ Deprecated and unused.
683
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
684
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
685
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
686
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
687
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
688
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
689
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
690
+ Returns:
691
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
692
+ """
693
+ cos = cos.unsqueeze(unsqueeze_dim)
694
+ sin = sin.unsqueeze(unsqueeze_dim)
695
+ q_embed = (q * cos) + (rotate_half(q) * sin)
696
+ k_embed = (k * cos) + (rotate_half(k) * sin)
697
+ return q_embed, k_embed
698
+
699
+
700
+ class Phi3MLP(nn.Module):
701
+ def __init__(self, config):
702
+ super().__init__()
703
+
704
+ self.config = config
705
+ self.gate_up_proj = nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=False)
706
+ self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
707
+
708
+ self.activation_fn = ACT2FN[config.hidden_act]
709
+
710
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
711
+ up_states = self.gate_up_proj(hidden_states)
712
+
713
+ gate, up_states = up_states.chunk(2, dim=-1)
714
+ up_states = up_states * self.activation_fn(gate)
715
+
716
+ return self.down_proj(up_states)
717
+
718
+
719
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv with llama->phi
720
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
721
+ """
722
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
723
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
724
+ """
725
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
726
+ if n_rep == 1:
727
+ return hidden_states
728
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
729
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
730
+
731
+
732
+ class Phi3Attention(nn.Module):
733
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
734
+
735
+ def __init__(self, config: Phi3VConfig, layer_idx: Optional[int] = None):
736
+ super().__init__()
737
+ self.config = config
738
+ self.layer_idx = layer_idx
739
+ if layer_idx is None:
740
+ logger.warning_once(
741
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
742
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
743
+ "when creating this class."
744
+ )
745
+
746
+ self.attention_dropout = config.attention_dropout
747
+ self.hidden_size = config.hidden_size
748
+ self.num_heads = config.num_attention_heads
749
+ self.head_dim = self.hidden_size // self.num_heads
750
+ self.num_key_value_heads = config.num_key_value_heads
751
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
752
+ self.max_position_embeddings = config.max_position_embeddings
753
+ self.original_max_position_embeddings = config.original_max_position_embeddings
754
+ self.rope_theta = config.rope_theta
755
+ self.rope_scaling = config.rope_scaling
756
+ self.is_causal = True
757
+
758
+ if (self.head_dim * self.num_heads) != self.hidden_size:
759
+ raise ValueError(
760
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
761
+ f" and `num_heads`: {self.num_heads})."
762
+ )
763
+
764
+ op_size = self.num_heads * self.head_dim + 2 * (self.num_key_value_heads * self.head_dim)
765
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
766
+ self.qkv_proj = nn.Linear(self.hidden_size, op_size, bias=False)
767
+ self._init_rope()
768
+
769
+ def _init_rope(self):
770
+ if self.rope_scaling is None:
771
+ self.rotary_emb = Phi3RotaryEmbedding(
772
+ self.head_dim,
773
+ max_position_embeddings=self.max_position_embeddings,
774
+ base=self.rope_theta,
775
+ )
776
+ else:
777
+ scaling_type = self.config.rope_scaling["type"]
778
+ if scaling_type == "su":
779
+ self.rotary_emb = Phi3SuScaledRotaryEmbedding(self.head_dim, self.config)
780
+ elif scaling_type == "yarn":
781
+ self.rotary_emb = Phi3YarnScaledRotaryEmbedding(self.head_dim, self.config)
782
+ else:
783
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
784
+
785
+ def forward(
786
+ self,
787
+ hidden_states: torch.Tensor,
788
+ attention_mask: Optional[torch.Tensor] = None,
789
+ position_ids: Optional[torch.LongTensor] = None,
790
+ past_key_value: Optional[Cache] = None,
791
+ output_attentions: bool = False,
792
+ use_cache: bool = False,
793
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
794
+ logger.warning_once("You are not running the flash-attention implementation, expect numerical differences.")
795
+
796
+ bsz, q_len, _ = hidden_states.size()
797
+
798
+ qkv = self.qkv_proj(hidden_states)
799
+ query_pos = self.num_heads * self.head_dim
800
+ query_states = qkv[..., :query_pos]
801
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
802
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
803
+
804
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
805
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
806
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
807
+
808
+ kv_seq_len = key_states.shape[-2]
809
+ if past_key_value is not None:
810
+ if self.layer_idx is None:
811
+ raise ValueError(
812
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
813
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
814
+ "with a layer index."
815
+ )
816
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
817
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)
818
+
819
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
820
+
821
+ if past_key_value is not None:
822
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
823
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
824
+
825
+ # repeat k/v heads if n_kv_heads < n_heads
826
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
827
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
828
+
829
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
830
+
831
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
832
+ raise ValueError(
833
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
834
+ f" {attn_weights.size()}"
835
+ )
836
+
837
+ if attention_mask is not None:
838
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
839
+ raise ValueError(
840
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
841
+ )
842
+ attn_weights = attn_weights + attention_mask
843
+
844
+ # upcast attention to fp32
845
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(value_states.dtype)
846
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
847
+
848
+ attn_output = torch.matmul(attn_weights, value_states)
849
+
850
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
851
+ raise ValueError(
852
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
853
+ f" {attn_output.size()}"
854
+ )
855
+
856
+ attn_output = attn_output.transpose(1, 2).contiguous()
857
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
858
+
859
+ attn_output = self.o_proj(attn_output)
860
+
861
+ if not output_attentions:
862
+ attn_weights = None
863
+
864
+ return attn_output, attn_weights, past_key_value
865
+
866
+
867
+ class Phi3FlashAttention2(Phi3Attention):
868
+ """
869
+ Phi-3 flash attention module. This module inherits from `Phi3Attention` as the weights of the module stays
870
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
871
+ flash attention and deal with padding tokens in case the input contains any of them.
872
+ """
873
+
874
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
875
+ def __init__(self, *args, **kwargs):
876
+ super().__init__(*args, **kwargs)
877
+
878
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
879
+ # 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.
880
+ # 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).
881
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
882
+
883
+ def forward(
884
+ self,
885
+ hidden_states: torch.Tensor,
886
+ attention_mask: Optional[torch.LongTensor] = None,
887
+ position_ids: Optional[torch.LongTensor] = None,
888
+ past_key_value: Optional[Cache] = None,
889
+ output_attentions: bool = False,
890
+ use_cache: bool = False,
891
+ **kwargs,
892
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
893
+ # Phi3FlashAttention2 attention does not support output_attentions
894
+
895
+ if not _flash_supports_window_size:
896
+ logger.warning_once(
897
+ "The current flash attention version does not support sliding window attention. Please use `attn_implementation='eager'` or upgrade flash-attn library."
898
+ )
899
+ raise ValueError("The current flash attention version does not support sliding window attention.")
900
+
901
+ output_attentions = False
902
+
903
+ if "padding_mask" in kwargs:
904
+ warnings.warn(
905
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
906
+ )
907
+
908
+ # overwrite attention_mask with padding_mask
909
+ attention_mask = kwargs.pop("padding_mask")
910
+
911
+ bsz, q_len, _ = hidden_states.size()
912
+
913
+ qkv = self.qkv_proj(hidden_states)
914
+ query_pos = self.num_heads * self.head_dim
915
+ query_states = qkv[..., :query_pos]
916
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
917
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
918
+
919
+ # Flash attention requires the input to have the shape
920
+ # batch_size x seq_length x head_dim x hidden_dim
921
+ # therefore we just need to keep the original shape
922
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
923
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
924
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
925
+
926
+ kv_seq_len = key_states.shape[-2]
927
+ if past_key_value is not None:
928
+ if self.layer_idx is None:
929
+ raise ValueError(
930
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
931
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
932
+ "with a layer index."
933
+ )
934
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
935
+
936
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
937
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
938
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=rotary_seq_len)
939
+
940
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
941
+
942
+ use_sliding_windows = (
943
+ _flash_supports_window_size
944
+ and getattr(self.config, "sliding_window", None) is not None
945
+ and kv_seq_len > self.config.sliding_window
946
+ )
947
+
948
+ if past_key_value is not None:
949
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
950
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
951
+ if (
952
+ getattr(self.config, "sliding_window", None) is not None
953
+ and kv_seq_len > self.config.sliding_window
954
+ and cache_has_contents
955
+ ):
956
+ slicing_tokens = 1 - self.config.sliding_window
957
+
958
+ past_key = past_key_value[self.layer_idx][0]
959
+ past_value = past_key_value[self.layer_idx][1]
960
+
961
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
962
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
963
+
964
+ if past_key.shape[-2] != self.config.sliding_window - 1:
965
+ raise ValueError(
966
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
967
+ f" {past_key.shape}"
968
+ )
969
+
970
+ if attention_mask is not None:
971
+ attention_mask = attention_mask[:, slicing_tokens:]
972
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
973
+
974
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
975
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
976
+
977
+ # repeat k/v heads if n_kv_heads < n_heads
978
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
979
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
980
+
981
+ attn_dropout = self.attention_dropout if self.training else 0.0
982
+
983
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
984
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
985
+ # cast them back in the correct dtype just to be sure everything works as expected.
986
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
987
+ # in fp32.
988
+
989
+ if query_states.dtype == torch.float32:
990
+ if torch.is_autocast_enabled():
991
+ target_dtype = torch.get_autocast_gpu_dtype()
992
+ # Handle the case where the model is quantized
993
+ elif hasattr(self.config, "_pre_quantization_dtype"):
994
+ target_dtype = self.config._pre_quantization_dtype
995
+ else:
996
+ target_dtype = self.qkv_proj.weight.dtype
997
+
998
+ logger.warning_once(
999
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
1000
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
1001
+ f" {target_dtype}."
1002
+ )
1003
+
1004
+ query_states = query_states.to(target_dtype)
1005
+ key_states = key_states.to(target_dtype)
1006
+ value_states = value_states.to(target_dtype)
1007
+
1008
+ # Reashape to the expected shape for Flash Attention
1009
+ query_states = query_states.transpose(1, 2)
1010
+ key_states = key_states.transpose(1, 2)
1011
+ value_states = value_states.transpose(1, 2)
1012
+
1013
+ attn_output = self._flash_attention_forward(
1014
+ query_states,
1015
+ key_states,
1016
+ value_states,
1017
+ attention_mask,
1018
+ q_len,
1019
+ dropout=attn_dropout,
1020
+ use_sliding_windows=use_sliding_windows,
1021
+ )
1022
+
1023
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
1024
+ attn_output = self.o_proj(attn_output)
1025
+
1026
+ if not output_attentions:
1027
+ attn_weights = None
1028
+
1029
+ return attn_output, attn_weights, past_key_value
1030
+
1031
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._flash_attention_forward
1032
+ def _flash_attention_forward(
1033
+ self,
1034
+ query_states,
1035
+ key_states,
1036
+ value_states,
1037
+ attention_mask,
1038
+ query_length,
1039
+ dropout=0.0,
1040
+ softmax_scale=None,
1041
+ use_sliding_windows=False,
1042
+ ):
1043
+ """
1044
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
1045
+ first unpad the input, then computes the attention scores and pad the final attention scores.
1046
+
1047
+ Args:
1048
+ query_states (`torch.Tensor`):
1049
+ Input query states to be passed to Flash Attention API
1050
+ key_states (`torch.Tensor`):
1051
+ Input key states to be passed to Flash Attention API
1052
+ value_states (`torch.Tensor`):
1053
+ Input value states to be passed to Flash Attention API
1054
+ attention_mask (`torch.Tensor`):
1055
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
1056
+ position of padding tokens and 1 for the position of non-padding tokens.
1057
+ dropout (`float`):
1058
+ Attention dropout
1059
+ softmax_scale (`float`, *optional*):
1060
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
1061
+ use_sliding_windows (`bool`, *optional*):
1062
+ Whether to activate sliding window attention.
1063
+ """
1064
+ if not self._flash_attn_uses_top_left_mask:
1065
+ causal = self.is_causal
1066
+ else:
1067
+ # 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__.
1068
+ causal = self.is_causal and query_length != 1
1069
+
1070
+ # Contains at least one padding token in the sequence
1071
+ if attention_mask is not None:
1072
+ batch_size = query_states.shape[0]
1073
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
1074
+ query_states, key_states, value_states, attention_mask, query_length
1075
+ )
1076
+
1077
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
1078
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
1079
+
1080
+ if not use_sliding_windows:
1081
+ attn_output_unpad = flash_attn_varlen_func(
1082
+ query_states,
1083
+ key_states,
1084
+ value_states,
1085
+ cu_seqlens_q=cu_seqlens_q,
1086
+ cu_seqlens_k=cu_seqlens_k,
1087
+ max_seqlen_q=max_seqlen_in_batch_q,
1088
+ max_seqlen_k=max_seqlen_in_batch_k,
1089
+ dropout_p=dropout,
1090
+ softmax_scale=softmax_scale,
1091
+ causal=causal,
1092
+ )
1093
+ else:
1094
+ attn_output_unpad = flash_attn_varlen_func(
1095
+ query_states,
1096
+ key_states,
1097
+ value_states,
1098
+ cu_seqlens_q=cu_seqlens_q,
1099
+ cu_seqlens_k=cu_seqlens_k,
1100
+ max_seqlen_q=max_seqlen_in_batch_q,
1101
+ max_seqlen_k=max_seqlen_in_batch_k,
1102
+ dropout_p=dropout,
1103
+ softmax_scale=softmax_scale,
1104
+ causal=causal,
1105
+ window_size=(self.config.sliding_window, self.config.sliding_window),
1106
+ )
1107
+
1108
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
1109
+ else:
1110
+ if not use_sliding_windows:
1111
+ attn_output = flash_attn_func(
1112
+ query_states,
1113
+ key_states,
1114
+ value_states,
1115
+ dropout,
1116
+ softmax_scale=softmax_scale,
1117
+ causal=causal,
1118
+ )
1119
+ else:
1120
+ attn_output = flash_attn_func(
1121
+ query_states,
1122
+ key_states,
1123
+ value_states,
1124
+ dropout,
1125
+ softmax_scale=softmax_scale,
1126
+ causal=causal,
1127
+ window_size=(self.config.sliding_window, self.config.sliding_window),
1128
+ )
1129
+
1130
+ return attn_output
1131
+
1132
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._upad_input
1133
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
1134
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
1135
+
1136
+ # On the first iteration we need to properly re-create the padding mask
1137
+ # by slicing it on the proper place
1138
+ if kv_seq_len != attention_mask.shape[-1]:
1139
+ attention_mask_num_tokens = attention_mask.shape[-1]
1140
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
1141
+
1142
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
1143
+
1144
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
1145
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
1146
+
1147
+ if query_length == kv_seq_len:
1148
+ query_layer = index_first_axis(
1149
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
1150
+ )
1151
+ cu_seqlens_q = cu_seqlens_k
1152
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
1153
+ indices_q = indices_k
1154
+ elif query_length == 1:
1155
+ max_seqlen_in_batch_q = 1
1156
+ cu_seqlens_q = torch.arange(
1157
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
1158
+ ) # There is a memcpy here, that is very bad.
1159
+ indices_q = cu_seqlens_q[:-1]
1160
+ query_layer = query_layer.squeeze(1)
1161
+ else:
1162
+ # The -q_len: slice assumes left padding.
1163
+ attention_mask = attention_mask[:, -query_length:]
1164
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
1165
+
1166
+ return (
1167
+ query_layer,
1168
+ key_layer,
1169
+ value_layer,
1170
+ indices_q,
1171
+ (cu_seqlens_q, cu_seqlens_k),
1172
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
1173
+ )
1174
+
1175
+
1176
+ # copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Phi3
1177
+ # TODO @Arthur no longer copied from LLama after static cache
1178
+ class Phi3SdpaAttention(Phi3Attention):
1179
+ """
1180
+ Phi3 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
1181
+ `Phi3Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
1182
+ SDPA API.
1183
+ """
1184
+
1185
+ # Adapted from Phi3Attention.forward
1186
+ def forward(
1187
+ self,
1188
+ hidden_states: torch.Tensor,
1189
+ attention_mask: Optional[torch.Tensor] = None,
1190
+ position_ids: Optional[torch.LongTensor] = None,
1191
+ past_key_value: Optional[Cache] = None,
1192
+ output_attentions: bool = False,
1193
+ use_cache: bool = False,
1194
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
1195
+ if output_attentions:
1196
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
1197
+ logger.warning_once(
1198
+ "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, "
1199
+ '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.'
1200
+ )
1201
+ return super().forward(
1202
+ hidden_states=hidden_states,
1203
+ attention_mask=attention_mask,
1204
+ position_ids=position_ids,
1205
+ past_key_value=past_key_value,
1206
+ output_attentions=output_attentions,
1207
+ use_cache=use_cache,
1208
+ )
1209
+
1210
+ bsz, q_len, _ = hidden_states.size()
1211
+
1212
+ qkv = self.qkv_proj(hidden_states)
1213
+ query_pos = self.num_heads * self.head_dim
1214
+ query_states = qkv[..., :query_pos]
1215
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
1216
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
1217
+
1218
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
1219
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
1220
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
1221
+
1222
+ kv_seq_len = key_states.shape[-2]
1223
+ if past_key_value is not None:
1224
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
1225
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)
1226
+
1227
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
1228
+
1229
+ if past_key_value is not None:
1230
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
1231
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
1232
+
1233
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
1234
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
1235
+
1236
+ if attention_mask is not None:
1237
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
1238
+ raise ValueError(
1239
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
1240
+ )
1241
+
1242
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
1243
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
1244
+ if query_states.device.type == "cuda" and attention_mask is not None:
1245
+ query_states = query_states.contiguous()
1246
+ key_states = key_states.contiguous()
1247
+ value_states = value_states.contiguous()
1248
+
1249
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
1250
+ query_states,
1251
+ key_states,
1252
+ value_states,
1253
+ attn_mask=attention_mask,
1254
+ dropout_p=self.attention_dropout if self.training else 0.0,
1255
+ # 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.
1256
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
1257
+ )
1258
+
1259
+ attn_output = attn_output.transpose(1, 2).contiguous()
1260
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
1261
+
1262
+ attn_output = self.o_proj(attn_output)
1263
+
1264
+ return attn_output, None, past_key_value
1265
+
1266
+
1267
+ PHI3_ATTENTION_CLASSES = {
1268
+ "eager": Phi3Attention,
1269
+ "flash_attention_2": Phi3FlashAttention2,
1270
+ "sdpa": Phi3SdpaAttention,
1271
+ }
1272
+
1273
+
1274
+ class Phi3DecoderLayer(nn.Module):
1275
+ def __init__(self, config: Phi3VConfig, layer_idx: int):
1276
+ super().__init__()
1277
+
1278
+ self.config = config
1279
+ self.self_attn = PHI3_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
1280
+
1281
+ self.mlp = Phi3MLP(config)
1282
+ self.input_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1283
+
1284
+ self.resid_attn_dropout = nn.Dropout(config.resid_pdrop)
1285
+ self.resid_mlp_dropout = nn.Dropout(config.resid_pdrop)
1286
+ self.post_attention_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1287
+
1288
+ def forward(
1289
+ self,
1290
+ hidden_states: torch.Tensor,
1291
+ attention_mask: Optional[torch.Tensor] = None,
1292
+ position_ids: Optional[torch.LongTensor] = None,
1293
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1294
+ output_attentions: Optional[bool] = False,
1295
+ use_cache: Optional[bool] = False,
1296
+ **kwargs,
1297
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
1298
+ if "padding_mask" in kwargs:
1299
+ warnings.warn(
1300
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1301
+ )
1302
+ """
1303
+ Args:
1304
+ hidden_states (`torch.FloatTensor`):
1305
+ input to the layer of shape `(batch, seq_len, embed_dim)`
1306
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
1307
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
1308
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
1309
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
1310
+ `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
1311
+ output_attentions (`bool`, *optional*):
1312
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1313
+ returned tensors for more detail.
1314
+ use_cache (`bool`, *optional*):
1315
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1316
+ (see `past_key_values`).
1317
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
1318
+ """
1319
+
1320
+ residual = hidden_states
1321
+
1322
+ hidden_states = self.input_layernorm(hidden_states)
1323
+
1324
+ # Self Attention
1325
+ attn_outputs, self_attn_weights, present_key_value = self.self_attn(
1326
+ hidden_states=hidden_states,
1327
+ attention_mask=attention_mask,
1328
+ position_ids=position_ids,
1329
+ past_key_value=past_key_value,
1330
+ output_attentions=output_attentions,
1331
+ use_cache=use_cache,
1332
+ )
1333
+
1334
+ hidden_states = residual + self.resid_attn_dropout(attn_outputs)
1335
+
1336
+ residual = hidden_states
1337
+ hidden_states = self.post_attention_layernorm(hidden_states)
1338
+ hidden_states = self.mlp(hidden_states)
1339
+ hidden_states = residual + self.resid_mlp_dropout(hidden_states)
1340
+
1341
+ outputs = (hidden_states,)
1342
+
1343
+ if output_attentions:
1344
+ outputs += (self_attn_weights,)
1345
+
1346
+ if use_cache:
1347
+ outputs += (present_key_value,)
1348
+
1349
+ return outputs
1350
+
1351
+
1352
+ PHI3V_START_DOCSTRING = r"""
1353
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1354
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1355
+ etc.)
1356
+
1357
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1358
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1359
+ and behavior.
1360
+
1361
+ Parameters:
1362
+ config ([`Phi3VConfig`]):
1363
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1364
+ load the weights associated with the model, only the configuration. Check out the
1365
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1366
+ """
1367
+
1368
+
1369
+ @add_start_docstrings(
1370
+ "The bare Phi-3-V model outputting raw hidden-states without any specific head on top.",
1371
+ PHI3V_START_DOCSTRING,
1372
+ )
1373
+ class Phi3VPreTrainedModel(PreTrainedModel):
1374
+ config_class = Phi3VConfig
1375
+ base_model_prefix = "model"
1376
+ supports_gradient_checkpointing = True
1377
+ _no_split_modules = ["Phi3DecoderLayer"]
1378
+ _skip_keys_device_placement = "past_key_values"
1379
+ _supports_flash_attn_2 = True
1380
+ _supports_sdpa = False
1381
+ _supports_cache_class = True
1382
+
1383
+ _version = "0.0.5"
1384
+
1385
+ def _init_weights(self, module):
1386
+ std = self.config.initializer_range
1387
+ if isinstance(module, nn.Linear):
1388
+ module.weight.data.normal_(mean=0.0, std=std)
1389
+ if module.bias is not None:
1390
+ module.bias.data.zero_()
1391
+ elif isinstance(module, nn.Embedding):
1392
+ module.weight.data.normal_(mean=0.0, std=std)
1393
+ if module.padding_idx is not None:
1394
+ module.weight.data[module.padding_idx].zero_()
1395
+
1396
+
1397
+ PHI3V_INPUTS_DOCSTRING = r"""
1398
+ Args:
1399
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1400
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1401
+ it.
1402
+
1403
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1404
+ [`PreTrainedTokenizer.__call__`] for details.
1405
+
1406
+ [What are input IDs?](../glossary#input-ids)
1407
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1408
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1409
+
1410
+ - 1 for tokens that are **not masked**,
1411
+ - 0 for tokens that are **masked**.
1412
+
1413
+ [What are attention masks?](../glossary#attention-mask)
1414
+
1415
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1416
+ [`PreTrainedTokenizer.__call__`] for details.
1417
+
1418
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1419
+ `past_key_values`).
1420
+
1421
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1422
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1423
+ information on the default strategy.
1424
+
1425
+ - 1 indicates the head is **not masked**,
1426
+ - 0 indicates the head is **masked**.
1427
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1428
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1429
+ config.n_positions - 1]`.
1430
+
1431
+ [What are position IDs?](../glossary#position-ids)
1432
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1433
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1434
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1435
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1436
+
1437
+ Two formats are allowed:
1438
+ - a [`~cache_utils.Cache`] instance;
1439
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1440
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1441
+ cache format.
1442
+
1443
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1444
+ legacy cache format will be returned.
1445
+
1446
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1447
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1448
+ of shape `(batch_size, sequence_length)`.
1449
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1450
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1451
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1452
+ model's internal embedding lookup matrix.
1453
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)):
1454
+ The tensors corresponding to the input images. Pixel values can be obtained using [`AutoImageProcessor`].
1455
+ See [`Phi3ImageProcessor.__call__`] for details.
1456
+ image_sizes (`torch.LongTensor` of shape `(batch_size, 2)`, *optional*):
1457
+ The sizes of the images in the batch, being (height, width) for each image.
1458
+ use_cache (`bool`, *optional*):
1459
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1460
+ `past_key_values`).
1461
+ output_attentions (`bool`, *optional*):
1462
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1463
+ tensors for more detail.
1464
+ output_hidden_states (`bool`, *optional*):
1465
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1466
+ more detail.
1467
+ return_dict (`bool`, *optional*):
1468
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1469
+ """
1470
+
1471
+
1472
+ @add_start_docstrings(
1473
+ "The bare Phi-3-V model outputting raw hidden-states without any specific head on top.",
1474
+ PHI3V_START_DOCSTRING,
1475
+ )
1476
+ class Phi3VModel(Phi3VPreTrainedModel):
1477
+ """
1478
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Phi3DecoderLayer`]
1479
+
1480
+ Args:
1481
+ config: Phi3Config
1482
+ """
1483
+
1484
+ def __init__(self, config: Phi3VConfig):
1485
+ super().__init__(config)
1486
+ self.padding_idx = config.pad_token_id
1487
+ self.vocab_size = config.vocab_size
1488
+
1489
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1490
+ self.embed_dropout = nn.Dropout(config.embd_pdrop)
1491
+ self.combined_embed = Phi3Embedding(self.embed_tokens, config.vocab_size)
1492
+
1493
+ self.vision_embed_tokens = None
1494
+ if isinstance(config.embd_layer, dict):
1495
+ # vision embedding layer
1496
+ embedding_config = {
1497
+ 'embedding_cls': config.embd_layer['embedding_cls'],
1498
+ **config.embd_layer
1499
+ }
1500
+ self.vision_embed_tokens = Phi3ImageEmbedding(config, wte=self.embed_tokens, **embedding_config)
1501
+ # # set wte the same for vision embedding
1502
+ # self.vision_embed_tokens.wte.weight = self.embed_tokens.weight
1503
+
1504
+ self.layers = nn.ModuleList(
1505
+ [Phi3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1506
+ )
1507
+ self._attn_implementation = config._attn_implementation
1508
+ self.norm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1509
+
1510
+ self.gradient_checkpointing = False
1511
+ # Initialize weights and apply final processing
1512
+ self.post_init()
1513
+
1514
+ def get_input_embeddings(self):
1515
+ return self.embed_tokens
1516
+
1517
+ def set_input_embeddings(self, value):
1518
+ self.embed_tokens = value
1519
+
1520
+ @add_start_docstrings_to_model_forward(PHI3V_INPUTS_DOCSTRING)
1521
+ def forward(
1522
+ self,
1523
+ input_ids: torch.LongTensor = None,
1524
+ attention_mask: Optional[torch.Tensor] = None,
1525
+ position_ids: Optional[torch.LongTensor] = None,
1526
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1527
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1528
+ pixel_values: Optional[torch.FloatTensor] = None,
1529
+ image_sizes: Optional[torch.LongTensor] = None,
1530
+ use_cache: Optional[bool] = None,
1531
+ output_attentions: Optional[bool] = None,
1532
+ output_hidden_states: Optional[bool] = None,
1533
+ return_dict: Optional[bool] = None,
1534
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1535
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1536
+ output_hidden_states = (
1537
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1538
+ )
1539
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1540
+
1541
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1542
+
1543
+ # retrieve input_ids and inputs_embeds
1544
+ if input_ids is not None and inputs_embeds is not None:
1545
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1546
+ elif input_ids is not None:
1547
+ batch_size, seq_length = input_ids.shape[:2]
1548
+ elif inputs_embeds is not None:
1549
+ batch_size, seq_length = inputs_embeds.shape[:2]
1550
+ else:
1551
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1552
+
1553
+ past_key_values_length = 0
1554
+
1555
+ if self.gradient_checkpointing and self.training:
1556
+ if use_cache:
1557
+ logger.warning_once(
1558
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1559
+ )
1560
+ use_cache = False
1561
+
1562
+ if use_cache:
1563
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1564
+ if use_legacy_cache:
1565
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1566
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1567
+
1568
+ if position_ids is None:
1569
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1570
+ position_ids = torch.arange(
1571
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1572
+ )
1573
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1574
+ else:
1575
+ position_ids = position_ids.view(-1, seq_length).long()
1576
+
1577
+ if inputs_embeds is None:
1578
+ if pixel_values is not None and image_sizes is not None:
1579
+ assert self.vision_embed_tokens is not None, "Vision embedding layer is not defined"
1580
+ # inputs_embeds = self.vision_embed_tokens(input_ids, pixel_values=pixel_values, image_sizes=image_sizes)
1581
+ inputs_embeds = self.vision_embed_tokens(pixel_values=pixel_values, image_sizes=image_sizes)
1582
+ else:
1583
+ inputs_embeds = self.embed_tokens(input_ids)
1584
+
1585
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
1586
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1587
+ if is_padding_right:
1588
+ raise ValueError(
1589
+ "You are attempting to perform batched generation with padding_side='right'"
1590
+ " this may lead to unexpected behaviour for Flash Attention version of Phi3. Make sure to "
1591
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1592
+ )
1593
+
1594
+ if self._attn_implementation == "flash_attention_2":
1595
+ # 2d mask is passed through the layers
1596
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1597
+ else:
1598
+ # 4d mask is passed through the layers
1599
+ attention_mask = _prepare_4d_causal_attention_mask(
1600
+ attention_mask,
1601
+ (batch_size, seq_length),
1602
+ inputs_embeds,
1603
+ past_key_values_length,
1604
+ sliding_window=self.config.sliding_window,
1605
+ )
1606
+
1607
+ hidden_states = inputs_embeds
1608
+
1609
+ # decoder layers
1610
+ all_hidden_states = () if output_hidden_states else None
1611
+ all_self_attns = () if output_attentions else None
1612
+ next_decoder_cache = None
1613
+
1614
+ for decoder_layer in self.layers:
1615
+ if output_hidden_states:
1616
+ all_hidden_states += (hidden_states,)
1617
+
1618
+ if self.gradient_checkpointing and self.training:
1619
+ layer_outputs = self._gradient_checkpointing_func(
1620
+ decoder_layer.__call__,
1621
+ hidden_states,
1622
+ attention_mask,
1623
+ position_ids,
1624
+ past_key_values,
1625
+ output_attentions,
1626
+ use_cache,
1627
+ )
1628
+ else:
1629
+ layer_outputs = decoder_layer(
1630
+ hidden_states,
1631
+ attention_mask=attention_mask,
1632
+ position_ids=position_ids,
1633
+ past_key_value=past_key_values,
1634
+ output_attentions=output_attentions,
1635
+ use_cache=use_cache,
1636
+ )
1637
+
1638
+ hidden_states = layer_outputs[0]
1639
+
1640
+ if use_cache:
1641
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1642
+
1643
+ if output_attentions:
1644
+ all_self_attns += (layer_outputs[1],)
1645
+
1646
+ hidden_states = self.norm(hidden_states)
1647
+
1648
+ # add hidden states from the last decoder layer
1649
+ if output_hidden_states:
1650
+ all_hidden_states += (hidden_states,)
1651
+
1652
+ next_cache = None
1653
+ if use_cache:
1654
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1655
+ if not return_dict:
1656
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1657
+ return BaseModelOutputWithPast(
1658
+ last_hidden_state=hidden_states,
1659
+ past_key_values=next_cache,
1660
+ hidden_states=all_hidden_states,
1661
+ attentions=all_self_attns,
1662
+ )
1663
+
1664
+
1665
+ class Phi3VForCausalLM(Phi3VPreTrainedModel):
1666
+ _tied_weights_keys = ["lm_head.weight"]
1667
+
1668
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with Llama->Phi3
1669
+ def __init__(self, config):
1670
+ super().__init__(config)
1671
+ self.model = Phi3VModel(config)
1672
+ self.vocab_size = config.vocab_size
1673
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1674
+
1675
+ # Initialize weights and apply final processing
1676
+ self.post_init()
1677
+
1678
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_input_embeddings
1679
+ def get_input_embeddings(self):
1680
+ return self.model.embed_tokens
1681
+
1682
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_input_embeddings
1683
+ def set_input_embeddings(self, value):
1684
+ self.model.embed_tokens = value
1685
+
1686
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_output_embeddings
1687
+ def get_output_embeddings(self):
1688
+ return self.lm_head
1689
+
1690
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_output_embeddings
1691
+ def set_output_embeddings(self, new_embeddings):
1692
+ self.lm_head = new_embeddings
1693
+
1694
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_decoder
1695
+ def set_decoder(self, decoder):
1696
+ self.model = decoder
1697
+
1698
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_decoder
1699
+ def get_decoder(self):
1700
+ return self.model
1701
+
1702
+ # Ignore copy
1703
+ @add_start_docstrings_to_model_forward(PHI3V_INPUTS_DOCSTRING)
1704
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1705
+ def forward(
1706
+ self,
1707
+ input_ids: torch.LongTensor = None,
1708
+ attention_mask: Optional[torch.Tensor] = None,
1709
+ position_ids: Optional[torch.LongTensor] = None,
1710
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1711
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1712
+ pixel_values: Optional[torch.FloatTensor] = None,
1713
+ image_sizes: Optional[torch.LongTensor] = None,
1714
+ labels: Optional[torch.LongTensor] = None,
1715
+ use_cache: Optional[bool] = None,
1716
+ output_attentions: Optional[bool] = None,
1717
+ output_hidden_states: Optional[bool] = None,
1718
+ return_dict: Optional[bool] = None,
1719
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1720
+ r"""
1721
+ Args:
1722
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1723
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1724
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1725
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1726
+
1727
+ Returns:
1728
+
1729
+ Example:
1730
+
1731
+ ```python
1732
+ >>> from transformers import AutoTokenizer, Phi3ForCausalLM
1733
+
1734
+ >>> model = Phi3ForCausalLM.from_pretrained("microsoft/phi-3-mini-4k-instruct")
1735
+ >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-3-mini-4k-instruct")
1736
+
1737
+ >>> prompt = "This is an example script ."
1738
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1739
+
1740
+ >>> # Generate
1741
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1742
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1743
+ 'This is an example script .\n Certainly! Below is a sample script that demonstrates a simple task, such as calculating the sum'
1744
+ ```"""
1745
+
1746
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1747
+ output_hidden_states = (
1748
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1749
+ )
1750
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1751
+
1752
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1753
+ outputs = self.model(
1754
+ input_ids=input_ids,
1755
+ attention_mask=attention_mask,
1756
+ position_ids=position_ids,
1757
+ past_key_values=past_key_values,
1758
+ inputs_embeds=inputs_embeds,
1759
+ pixel_values=pixel_values,
1760
+ image_sizes=image_sizes,
1761
+ use_cache=use_cache,
1762
+ output_attentions=output_attentions,
1763
+ output_hidden_states=output_hidden_states,
1764
+ return_dict=return_dict,
1765
+ )
1766
+
1767
+ hidden_states = outputs[0]
1768
+ logits = self.lm_head(hidden_states)
1769
+ logits = logits.float()
1770
+
1771
+ loss = None
1772
+ if labels is not None:
1773
+ # Shift so that tokens < n predict n
1774
+ shift_logits = logits[..., :-1, :].contiguous()
1775
+ shift_labels = labels[..., 1:].contiguous()
1776
+ # Flatten the tokens
1777
+ loss_fct = CrossEntropyLoss()
1778
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1779
+ shift_labels = shift_labels.view(-1)
1780
+ # Enable model parallelism
1781
+ shift_labels = shift_labels.to(shift_logits.device)
1782
+ loss = loss_fct(shift_logits, shift_labels)
1783
+
1784
+ if not return_dict:
1785
+ output = (logits,) + outputs[1:]
1786
+ return (loss,) + output if loss is not None else output
1787
+
1788
+ return CausalLMOutputWithPast(
1789
+ loss=loss,
1790
+ logits=logits,
1791
+ past_key_values=outputs.past_key_values,
1792
+ hidden_states=outputs.hidden_states,
1793
+ attentions=outputs.attentions,
1794
+ )
1795
+
1796
+ # Copied from transformers.models.persimmon.modeling_persimmon.PersimmonForCausalLM.prepare_inputs_for_generation
1797
+ def prepare_inputs_for_generation(
1798
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, pixel_values=None, image_sizes=None, **kwargs
1799
+ ):
1800
+ if past_key_values is not None:
1801
+ if isinstance(past_key_values, Cache):
1802
+ cache_length = past_key_values.get_seq_length()
1803
+ past_length = past_key_values.seen_tokens
1804
+ max_cache_length = past_key_values.get_max_length()
1805
+ else:
1806
+ cache_length = past_length = past_key_values[0][0].shape[2]
1807
+ max_cache_length = None
1808
+
1809
+ # Keep only the unprocessed tokens:
1810
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1811
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1812
+ # input)
1813
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1814
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1815
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1816
+ # input_ids based on the past_length.
1817
+ elif past_length < input_ids.shape[1]:
1818
+ input_ids = input_ids[:, past_length:]
1819
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1820
+
1821
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1822
+ if (
1823
+ max_cache_length is not None
1824
+ and attention_mask is not None
1825
+ and cache_length + input_ids.shape[1] > max_cache_length
1826
+ ):
1827
+ attention_mask = attention_mask[:, -max_cache_length:]
1828
+
1829
+ position_ids = kwargs.get("position_ids", None)
1830
+ if attention_mask is not None and position_ids is None:
1831
+ # create position_ids on the fly for batch generation
1832
+ position_ids = attention_mask.long().cumsum(-1) - 1
1833
+ position_ids.masked_fill_(attention_mask == 0, 1)
1834
+ if past_key_values:
1835
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1836
+
1837
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1838
+ if inputs_embeds is not None and past_key_values is None:
1839
+ model_inputs = {"inputs_embeds": inputs_embeds}
1840
+ else:
1841
+ model_inputs = {"input_ids": input_ids}
1842
+
1843
+ model_inputs.update(
1844
+ {
1845
+ "position_ids": position_ids,
1846
+ "past_key_values": past_key_values,
1847
+ "use_cache": kwargs.get("use_cache"),
1848
+ "attention_mask": attention_mask,
1849
+ "pixel_values": pixel_values,
1850
+ "image_sizes": image_sizes,
1851
+ }
1852
+ )
1853
+ return model_inputs
1854
+
1855
+ @staticmethod
1856
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM._reorder_cache
1857
+ def _reorder_cache(past_key_values, beam_idx):
1858
+ reordered_past = ()
1859
+ for layer_past in past_key_values:
1860
+ reordered_past += (
1861
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1862
+ )
1863
+ return reordered_past
1864
+
1865
+
1866
+ @add_start_docstrings(
1867
+ """
1868
+ The [`Phi3VModel`] with a sequence classification head on top (linear layer).
1869
+
1870
+ [`Phi3VForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1871
+ (e.g. GPT-2) do.
1872
+
1873
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1874
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1875
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1876
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1877
+ each row of the batch).
1878
+ """,
1879
+ PHI3V_START_DOCSTRING,
1880
+ )
1881
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->Phi3, LLAMA->PHI3, self.transformer->self.model, transformer_outputs->model_outputs
1882
+ class Phi3VForSequenceClassification(Phi3VPreTrainedModel):
1883
+ def __init__(self, config):
1884
+ super().__init__(config)
1885
+ self.num_labels = config.num_labels
1886
+ self.model = Phi3VModel(config)
1887
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1888
+
1889
+ # Initialize weights and apply final processing
1890
+ self.post_init()
1891
+
1892
+ def get_input_embeddings(self):
1893
+ return self.model.embed_tokens
1894
+
1895
+ def set_input_embeddings(self, value):
1896
+ self.model.embed_tokens = value
1897
+
1898
+ @add_start_docstrings_to_model_forward(PHI3V_INPUTS_DOCSTRING)
1899
+ def forward(
1900
+ self,
1901
+ input_ids: torch.LongTensor = None,
1902
+ attention_mask: Optional[torch.Tensor] = None,
1903
+ position_ids: Optional[torch.LongTensor] = None,
1904
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1905
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1906
+ pixel_values: Optional[torch.FloatTensor] = None,
1907
+ image_sizes: Optional[torch.LongTensor] = None,
1908
+ labels: Optional[torch.LongTensor] = None,
1909
+ use_cache: Optional[bool] = None,
1910
+ output_attentions: Optional[bool] = None,
1911
+ output_hidden_states: Optional[bool] = None,
1912
+ return_dict: Optional[bool] = None,
1913
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1914
+ r"""
1915
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1916
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1917
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1918
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1919
+ """
1920
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1921
+
1922
+ model_outputs = self.model(
1923
+ input_ids,
1924
+ attention_mask=attention_mask,
1925
+ position_ids=position_ids,
1926
+ past_key_values=past_key_values,
1927
+ inputs_embeds=inputs_embeds,
1928
+ pixel_values=pixel_values,
1929
+ image_sizes=image_sizes,
1930
+ use_cache=use_cache,
1931
+ output_attentions=output_attentions,
1932
+ output_hidden_states=output_hidden_states,
1933
+ return_dict=return_dict,
1934
+ )
1935
+ hidden_states = model_outputs[0]
1936
+ logits = self.score(hidden_states)
1937
+
1938
+ if input_ids is not None:
1939
+ batch_size = input_ids.shape[0]
1940
+ else:
1941
+ batch_size = inputs_embeds.shape[0]
1942
+
1943
+ if self.config.pad_token_id is None and batch_size != 1:
1944
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1945
+ if self.config.pad_token_id is None:
1946
+ sequence_lengths = -1
1947
+ else:
1948
+ if input_ids is not None:
1949
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1950
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1951
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1952
+ sequence_lengths = sequence_lengths.to(logits.device)
1953
+ else:
1954
+ sequence_lengths = -1
1955
+
1956
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1957
+
1958
+ loss = None
1959
+ if labels is not None:
1960
+ labels = labels.to(logits.device)
1961
+ if self.config.problem_type is None:
1962
+ if self.num_labels == 1:
1963
+ self.config.problem_type = "regression"
1964
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1965
+ self.config.problem_type = "single_label_classification"
1966
+ else:
1967
+ self.config.problem_type = "multi_label_classification"
1968
+
1969
+ if self.config.problem_type == "regression":
1970
+ loss_fct = MSELoss()
1971
+ if self.num_labels == 1:
1972
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1973
+ else:
1974
+ loss = loss_fct(pooled_logits, labels)
1975
+ elif self.config.problem_type == "single_label_classification":
1976
+ loss_fct = CrossEntropyLoss()
1977
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1978
+ elif self.config.problem_type == "multi_label_classification":
1979
+ loss_fct = BCEWithLogitsLoss()
1980
+ loss = loss_fct(pooled_logits, labels)
1981
+ if not return_dict:
1982
+ output = (pooled_logits,) + model_outputs[1:]
1983
+ return ((loss,) + output) if loss is not None else output
1984
+
1985
+ return SequenceClassifierOutputWithPast(
1986
+ loss=loss,
1987
+ logits=pooled_logits,
1988
+ past_key_values=model_outputs.past_key_values,
1989
+ hidden_states=model_outputs.hidden_states,
1990
+ attentions=model_outputs.attentions,
1991
+ )
1992
+
1993
+
1994
+ @add_start_docstrings(
1995
+ """
1996
+ [`Phi3VModel`] with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1997
+ Named-Entity-Recognition (NER) tasks.
1998
+ """,
1999
+ PHI3V_START_DOCSTRING,
2000
+ )
2001
+ # Copied from transformers.models.mpt.modeling_mpt.MptForTokenClassification with Mpt->Phi3,MPT->PHI3,self.transformer->self.model,transformer_outputs->model_outputs
2002
+ class Phi3VForTokenClassification(Phi3VPreTrainedModel):
2003
+ def __init__(self, config: Phi3VConfig):
2004
+ super().__init__(config)
2005
+ self.num_labels = config.num_labels
2006
+
2007
+ self.model = Phi3VModel(config)
2008
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
2009
+ classifier_dropout = config.classifier_dropout
2010
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
2011
+ classifier_dropout = config.hidden_dropout
2012
+ else:
2013
+ classifier_dropout = 0.1
2014
+ self.dropout = nn.Dropout(classifier_dropout)
2015
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
2016
+
2017
+ # Initialize weights and apply final processing
2018
+ self.post_init()
2019
+
2020
+ @add_start_docstrings_to_model_forward(PHI3V_INPUTS_DOCSTRING)
2021
+ @add_code_sample_docstrings(
2022
+ checkpoint=_CHECKPOINT_FOR_DOC,
2023
+ output_type=TokenClassifierOutput,
2024
+ config_class=_CONFIG_FOR_DOC,
2025
+ )
2026
+ def forward(
2027
+ self,
2028
+ input_ids: Optional[torch.LongTensor] = None,
2029
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
2030
+ attention_mask: Optional[torch.Tensor] = None,
2031
+ inputs_embeds: Optional[torch.Tensor] = None,
2032
+ pixel_values: Optional[torch.FloatTensor] = None,
2033
+ image_sizes: Optional[torch.LongTensor] = None,
2034
+ labels: Optional[torch.Tensor] = None,
2035
+ use_cache: Optional[bool] = None,
2036
+ output_attentions: Optional[bool] = None,
2037
+ output_hidden_states: Optional[bool] = None,
2038
+ return_dict: Optional[bool] = None,
2039
+ **deprecated_arguments,
2040
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
2041
+ r"""
2042
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
2043
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
2044
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
2045
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
2046
+ """
2047
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
2048
+
2049
+ model_outputs = self.model(
2050
+ input_ids,
2051
+ past_key_values=past_key_values,
2052
+ attention_mask=attention_mask,
2053
+ inputs_embeds=inputs_embeds,
2054
+ pixel_values=pixel_values,
2055
+ image_sizes=image_sizes,
2056
+ use_cache=use_cache,
2057
+ output_attentions=output_attentions,
2058
+ output_hidden_states=output_hidden_states,
2059
+ return_dict=return_dict,
2060
+ )
2061
+
2062
+ hidden_states = model_outputs[0]
2063
+ hidden_states = self.dropout(hidden_states)
2064
+ logits = self.classifier(hidden_states)
2065
+
2066
+ loss = None
2067
+ if labels is not None:
2068
+ # move labels to correct device to enable model parallelism
2069
+ labels = labels.to(logits.device)
2070
+ batch_size, seq_length = labels.shape
2071
+ loss_fct = CrossEntropyLoss()
2072
+ loss = loss_fct(
2073
+ logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
2074
+ )
2075
+
2076
+ if not return_dict:
2077
+ output = (logits,) + model_outputs[2:]
2078
+ return ((loss,) + output) if loss is not None else output
2079
+
2080
+ return TokenClassifierOutput(
2081
+ loss=loss,
2082
+ logits=logits,
2083
+ hidden_states=model_outputs.hidden_states,
2084
+ attentions=model_outputs.attentions,
2085
+ )