SVECTOR-OFFICIAL commited on
Commit
0276682
·
verified ·
1 Parent(s): e33eaae

Upload modeling_spec_vision.py with huggingface_hub

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