lokinfey commited on
Commit
645a7bf
1 Parent(s): 0a79d26

Upload ONNX file

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