adnlp commited on
Commit
60cbb5b
·
verified ·
1 Parent(s): 0beaae8

Upload 10 files

Browse files
config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoConfig": "modeling_multicasttimer.MulTiCastTimerConfig",
4
+ "AutoModel": "modeling_multicasttimer.MulTiCastTimerModel"
5
+ },
6
+ "forecasting_length": 56,
7
+ "text_model_name": "Qwen",
8
+ "text_model_prompt_len": 4,
9
+ "timer_prompt_len": 4,
10
+ "transformers_version": "4.40.1",
11
+ "vision_model_name": "CLIP",
12
+ "vision_model_prompt_len": 10
13
+ }
configuration_timer.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+ from transformers import PretrainedConfig
3
+
4
+
5
+ class TimerConfig(PretrainedConfig):
6
+ model_type = "timer"
7
+ keys_to_ignore_at_inference = ["past_key_values"]
8
+
9
+ def __init__(
10
+ self,
11
+ input_token_len: int = 1,
12
+ hidden_size: int = 1024,
13
+ intermediate_size: int = 2048,
14
+ output_token_lens: List[int] = [1, 8, 32, 64],
15
+ num_hidden_layers: int = 8,
16
+ num_attention_heads: int = 8,
17
+ hidden_act: str = "silu",
18
+ use_cache: bool = True,
19
+ rope_theta: int = 10000,
20
+ attention_dropout: float = 0.0,
21
+ initializer_range: float = 0.02,
22
+ max_position_embeddings: int = 10000,
23
+ **kwargs,
24
+ ):
25
+ self.input_token_len = input_token_len
26
+ self.hidden_size = hidden_size
27
+ self.intermediate_size = intermediate_size
28
+ self.num_hidden_layers = num_hidden_layers
29
+ self.num_attention_heads = num_attention_heads
30
+ self.hidden_act = hidden_act
31
+ self.output_token_lens = output_token_lens
32
+ self.use_cache = use_cache
33
+ self.rope_theta = rope_theta
34
+ self.attention_dropout = attention_dropout
35
+ self.initializer_range = initializer_range
36
+ self.max_position_embeddings = max_position_embeddings
37
+
38
+ super().__init__(
39
+ **kwargs,
40
+ )
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d3a4e052bdb44da28792f4b0b24ce5d141143c8ff1da2148fb4b05d0b80c0e76
3
+ size 10638152
modeling_clipPT.py ADDED
@@ -0,0 +1,1374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The OpenAI Team Authors and The HuggingFace 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
+ """ PyTorch CLIP model."""
16
+
17
+
18
+ from dataclasses import dataclass
19
+ from typing import Any, Optional, Tuple, Union
20
+
21
+ import torch
22
+ import torch.utils.checkpoint
23
+ from torch import nn
24
+
25
+ from transformers.activations import ACT2FN
26
+ from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling
27
+ from transformers.modeling_utils import PreTrainedModel
28
+ from transformers.utils import (
29
+ ModelOutput,
30
+ add_start_docstrings,
31
+ add_start_docstrings_to_model_forward,
32
+ logging,
33
+ replace_return_docstrings,
34
+ )
35
+ from transformers.models.clip.configuration_clip import CLIPConfig, CLIPTextConfig, CLIPVisionConfig
36
+
37
+
38
+ logger = logging.get_logger(__name__)
39
+
40
+ _CHECKPOINT_FOR_DOC = "openai/clip-vit-base-patch32"
41
+
42
+ CLIP_PRETRAINED_MODEL_ARCHIVE_LIST = [
43
+ "openai/clip-vit-base-patch32",
44
+ # See all CLIP models at https://huggingface.co/models?filter=clip
45
+ ]
46
+
47
+
48
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
49
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
50
+ """
51
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
52
+ """
53
+ bsz, src_len = mask.size()
54
+ tgt_len = tgt_len if tgt_len is not None else src_len
55
+
56
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
57
+
58
+ inverted_mask = 1.0 - expanded_mask
59
+
60
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
61
+
62
+
63
+ # contrastive loss function, adapted from
64
+ # https://sachinruk.github.io/blog/2021-03-07-clip.html
65
+ def contrastive_loss(logits: torch.Tensor) -> torch.Tensor:
66
+ return nn.functional.cross_entropy(logits, torch.arange(len(logits), device=logits.device))
67
+
68
+
69
+ def clip_loss(similarity: torch.Tensor) -> torch.Tensor:
70
+ caption_loss = contrastive_loss(similarity)
71
+ image_loss = contrastive_loss(similarity.t())
72
+ return (caption_loss + image_loss) / 2.0
73
+
74
+
75
+ @dataclass
76
+ class CLIPVisionModelOutput(ModelOutput):
77
+ """
78
+ Base class for vision model's outputs that also contains image embeddings of the pooling of the last hidden states.
79
+
80
+ Args:
81
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
82
+ The image embeddings obtained by applying the projection layer to the pooler_output.
83
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
84
+ Sequence of hidden-states at the output of the last layer of the model.
85
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
86
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
87
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
88
+
89
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
90
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
91
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
92
+ sequence_length)`.
93
+
94
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
95
+ heads.
96
+ """
97
+
98
+ image_embeds: Optional[torch.FloatTensor] = None
99
+ last_hidden_state: torch.FloatTensor = None
100
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
101
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
102
+
103
+
104
+ @dataclass
105
+ class CLIPTextModelOutput(ModelOutput):
106
+ """
107
+ Base class for text model's outputs that also contains a pooling of the last hidden states.
108
+
109
+ Args:
110
+ text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
111
+ The text embeddings obtained by applying the projection layer to the pooler_output.
112
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
113
+ Sequence of hidden-states at the output of the last layer of the model.
114
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
115
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
116
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
117
+
118
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
119
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
120
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
121
+ sequence_length)`.
122
+
123
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
124
+ heads.
125
+ """
126
+
127
+ text_embeds: Optional[torch.FloatTensor] = None
128
+ last_hidden_state: torch.FloatTensor = None
129
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
130
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
131
+
132
+
133
+ @dataclass
134
+ class CLIPOutput(ModelOutput):
135
+ """
136
+ Args:
137
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
138
+ Contrastive loss for image-text similarity.
139
+ logits_per_image:(`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
140
+ The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
141
+ similarity scores.
142
+ logits_per_text:(`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
143
+ The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
144
+ similarity scores.
145
+ text_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
146
+ The text embeddings obtained by applying the projection layer to the pooled output of [`CLIPTextModel`].
147
+ image_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
148
+ The image embeddings obtained by applying the projection layer to the pooled output of [`CLIPVisionModel`].
149
+ text_model_output(`BaseModelOutputWithPooling`):
150
+ The output of the [`CLIPTextModel`].
151
+ vision_model_output(`BaseModelOutputWithPooling`):
152
+ The output of the [`CLIPVisionModel`].
153
+ """
154
+
155
+ loss: Optional[torch.FloatTensor] = None
156
+ logits_per_image: torch.FloatTensor = None
157
+ logits_per_text: torch.FloatTensor = None
158
+ text_embeds: torch.FloatTensor = None
159
+ image_embeds: torch.FloatTensor = None
160
+ text_model_output: BaseModelOutputWithPooling = None
161
+ vision_model_output: BaseModelOutputWithPooling = None
162
+
163
+ def to_tuple(self) -> Tuple[Any]:
164
+ return tuple(
165
+ self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
166
+ for k in self.keys()
167
+ )
168
+
169
+
170
+ class CLIPVisionEmbeddings(nn.Module):
171
+ def __init__(self, config: CLIPVisionConfig):
172
+ super().__init__()
173
+ self.config = config
174
+ self.embed_dim = config.hidden_size
175
+ self.image_size = config.image_size
176
+ self.patch_size = config.patch_size
177
+
178
+ self.class_embedding = nn.Parameter(torch.randn(self.embed_dim))
179
+
180
+ self.patch_embedding = nn.Conv2d(
181
+ in_channels=config.num_channels,
182
+ out_channels=self.embed_dim,
183
+ kernel_size=self.patch_size,
184
+ stride=self.patch_size,
185
+ bias=False,
186
+ )
187
+
188
+ self.num_patches = (self.image_size // self.patch_size) ** 2
189
+ self.num_positions = self.num_patches + 1
190
+ self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
191
+ self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent=False)
192
+
193
+ def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
194
+ batch_size = pixel_values.shape[0]
195
+ patch_embeds = self.patch_embedding(pixel_values) # shape = [*, width, grid, grid]
196
+ patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
197
+
198
+ class_embeds = self.class_embedding.expand(batch_size, 1, -1)
199
+ embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
200
+ embeddings = embeddings + self.position_embedding(self.position_ids)
201
+ return embeddings
202
+
203
+
204
+ class CLIPTextEmbeddings(nn.Module):
205
+ def __init__(self, config: CLIPTextConfig):
206
+ super().__init__()
207
+ embed_dim = config.hidden_size
208
+
209
+ self.token_embedding = nn.Embedding(config.vocab_size, embed_dim)
210
+ self.position_embedding = nn.Embedding(config.max_position_embeddings, embed_dim)
211
+
212
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
213
+ self.register_buffer(
214
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
215
+ )
216
+
217
+ def forward(
218
+ self,
219
+ input_ids: Optional[torch.LongTensor] = None,
220
+ position_ids: Optional[torch.LongTensor] = None,
221
+ inputs_embeds: Optional[torch.FloatTensor] = None,
222
+ ) -> torch.Tensor:
223
+ seq_length = input_ids.shape[-1] if input_ids is not None else inputs_embeds.shape[-2]
224
+
225
+ if position_ids is None:
226
+ position_ids = self.position_ids[:, :seq_length]
227
+
228
+ if inputs_embeds is None:
229
+ inputs_embeds = self.token_embedding(input_ids)
230
+
231
+ position_embeddings = self.position_embedding(position_ids)
232
+ embeddings = inputs_embeds + position_embeddings
233
+
234
+ return embeddings
235
+
236
+
237
+ class CLIPAttention(nn.Module):
238
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
239
+
240
+ def __init__(self, config):
241
+ super().__init__()
242
+ self.config = config
243
+ self.embed_dim = config.hidden_size
244
+ self.num_heads = config.num_attention_heads
245
+ self.head_dim = self.embed_dim // self.num_heads
246
+ if self.head_dim * self.num_heads != self.embed_dim:
247
+ raise ValueError(
248
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
249
+ f" {self.num_heads})."
250
+ )
251
+ self.scale = self.head_dim**-0.5
252
+ self.dropout = config.attention_dropout
253
+
254
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
255
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
256
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
257
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
258
+
259
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
260
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
261
+
262
+ def forward(
263
+ self,
264
+ hidden_states: torch.Tensor,
265
+ attention_mask: Optional[torch.Tensor] = None,
266
+ causal_attention_mask: Optional[torch.Tensor] = None,
267
+ output_attentions: Optional[bool] = False,
268
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
269
+ """Input shape: Batch x Time x Channel"""
270
+
271
+ bsz, tgt_len, embed_dim = hidden_states.size()
272
+
273
+ # get query proj
274
+ query_states = self.q_proj(hidden_states) * self.scale
275
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
276
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
277
+
278
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
279
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
280
+ key_states = key_states.view(*proj_shape)
281
+ value_states = value_states.view(*proj_shape)
282
+
283
+ src_len = key_states.size(1)
284
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
285
+
286
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
287
+ raise ValueError(
288
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
289
+ f" {attn_weights.size()}"
290
+ )
291
+
292
+ # apply the causal_attention_mask first
293
+ if causal_attention_mask is not None:
294
+ if causal_attention_mask.size() != (bsz, 1, tgt_len, src_len):
295
+ raise ValueError(
296
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is"
297
+ f" {causal_attention_mask.size()}"
298
+ )
299
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + causal_attention_mask
300
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
301
+
302
+ if attention_mask is not None:
303
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
304
+ raise ValueError(
305
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
306
+ )
307
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
308
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
309
+
310
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
311
+
312
+ if output_attentions:
313
+ # this operation is a bit akward, but it's required to
314
+ # make sure that attn_weights keeps its gradient.
315
+ # In order to do so, attn_weights have to reshaped
316
+ # twice and have to be reused in the following
317
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
318
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
319
+ else:
320
+ attn_weights_reshaped = None
321
+
322
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
323
+
324
+ attn_output = torch.bmm(attn_probs, value_states)
325
+
326
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
327
+ raise ValueError(
328
+ f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
329
+ f" {attn_output.size()}"
330
+ )
331
+
332
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
333
+ attn_output = attn_output.transpose(1, 2)
334
+ attn_output = attn_output.reshape(bsz, tgt_len, embed_dim)
335
+
336
+ attn_output = self.out_proj(attn_output)
337
+
338
+ return attn_output, attn_weights_reshaped
339
+
340
+
341
+ class CLIPMLP(nn.Module):
342
+ def __init__(self, config):
343
+ super().__init__()
344
+ self.config = config
345
+ self.activation_fn = ACT2FN[config.hidden_act]
346
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
347
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
348
+
349
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
350
+ hidden_states = self.fc1(hidden_states)
351
+ hidden_states = self.activation_fn(hidden_states)
352
+ hidden_states = self.fc2(hidden_states)
353
+ return hidden_states
354
+
355
+
356
+ class CLIPEncoderLayer(nn.Module):
357
+ def __init__(self, config: CLIPConfig):
358
+ super().__init__()
359
+ self.embed_dim = config.hidden_size
360
+ self.self_attn = CLIPAttention(config)
361
+ self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
362
+ self.mlp = CLIPMLP(config)
363
+ self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
364
+
365
+ def forward(
366
+ self,
367
+ hidden_states: torch.Tensor,
368
+ attention_mask: torch.Tensor,
369
+ causal_attention_mask: torch.Tensor,
370
+ output_attentions: Optional[bool] = False,
371
+ ) -> Tuple[torch.FloatTensor]:
372
+ """
373
+ Args:
374
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
375
+ attention_mask (`torch.FloatTensor`): attention mask of size
376
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
377
+ `(config.encoder_attention_heads,)`.
378
+ output_attentions (`bool`, *optional*):
379
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
380
+ returned tensors for more detail.
381
+ """
382
+ residual = hidden_states
383
+
384
+ hidden_states = self.layer_norm1(hidden_states)
385
+ hidden_states, attn_weights = self.self_attn(
386
+ hidden_states=hidden_states,
387
+ attention_mask=attention_mask,
388
+ causal_attention_mask=causal_attention_mask,
389
+ output_attentions=output_attentions,
390
+ )
391
+ hidden_states = residual + hidden_states
392
+
393
+ residual = hidden_states
394
+ hidden_states = self.layer_norm2(hidden_states)
395
+ hidden_states = self.mlp(hidden_states)
396
+ hidden_states = residual + hidden_states
397
+
398
+ outputs = (hidden_states,)
399
+
400
+ if output_attentions:
401
+ outputs += (attn_weights,)
402
+
403
+ return outputs
404
+
405
+
406
+ class CLIPPreTrainedModel(PreTrainedModel):
407
+ """
408
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
409
+ models.
410
+ """
411
+
412
+ config_class = CLIPConfig
413
+ base_model_prefix = "clip"
414
+ supports_gradient_checkpointing = True
415
+
416
+ def _init_weights(self, module):
417
+ """Initialize the weights"""
418
+ factor = self.config.initializer_factor
419
+ if isinstance(module, CLIPTextEmbeddings):
420
+ module.token_embedding.weight.data.normal_(mean=0.0, std=factor * 0.02)
421
+ module.position_embedding.weight.data.normal_(mean=0.0, std=factor * 0.02)
422
+ elif isinstance(module, CLIPVisionEmbeddings):
423
+ factor = self.config.initializer_factor
424
+ nn.init.normal_(module.class_embedding, mean=0.0, std=module.embed_dim**-0.5 * factor)
425
+ nn.init.normal_(module.patch_embedding.weight, std=module.config.initializer_range * factor)
426
+ nn.init.normal_(module.position_embedding.weight, std=module.config.initializer_range * factor)
427
+ elif isinstance(module, CLIPAttention):
428
+ factor = self.config.initializer_factor
429
+ in_proj_std = (module.embed_dim**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
430
+ out_proj_std = (module.embed_dim**-0.5) * factor
431
+ nn.init.normal_(module.q_proj.weight, std=in_proj_std)
432
+ nn.init.normal_(module.k_proj.weight, std=in_proj_std)
433
+ nn.init.normal_(module.v_proj.weight, std=in_proj_std)
434
+ nn.init.normal_(module.out_proj.weight, std=out_proj_std)
435
+ elif isinstance(module, CLIPMLP):
436
+ factor = self.config.initializer_factor
437
+ in_proj_std = (
438
+ (module.config.hidden_size**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
439
+ )
440
+ fc_std = (2 * module.config.hidden_size) ** -0.5 * factor
441
+ nn.init.normal_(module.fc1.weight, std=fc_std)
442
+ nn.init.normal_(module.fc2.weight, std=in_proj_std)
443
+ elif isinstance(module, CLIPModel):
444
+ nn.init.normal_(
445
+ module.text_projection.weight,
446
+ std=module.text_embed_dim**-0.5 * self.config.initializer_factor,
447
+ )
448
+ nn.init.normal_(
449
+ module.visual_projection.weight,
450
+ std=module.vision_embed_dim**-0.5 * self.config.initializer_factor,
451
+ )
452
+ elif isinstance(module, CLIPVisionModelWithProjection):
453
+ nn.init.normal_(
454
+ module.visual_projection.weight,
455
+ std=self.config.hidden_size**-0.5 * self.config.initializer_factor,
456
+ )
457
+ elif isinstance(module, CLIPTextModelWithProjection):
458
+ nn.init.normal_(
459
+ module.text_projection.weight,
460
+ std=self.config.hidden_size**-0.5 * self.config.initializer_factor,
461
+ )
462
+
463
+ if isinstance(module, nn.LayerNorm):
464
+ module.bias.data.zero_()
465
+ module.weight.data.fill_(1.0)
466
+ if isinstance(module, nn.Linear) and module.bias is not None:
467
+ module.bias.data.zero_()
468
+
469
+ def _set_gradient_checkpointing(self, module, value=False):
470
+ if isinstance(module, CLIPEncoder):
471
+ module.gradient_checkpointing = value
472
+
473
+
474
+ CLIP_START_DOCSTRING = r"""
475
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
476
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
477
+ etc.)
478
+
479
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
480
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
481
+ and behavior.
482
+
483
+ Parameters:
484
+ config ([`CLIPConfig`]): Model configuration class with all the parameters of the model.
485
+ Initializing with a config file does not load the weights associated with the model, only the
486
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
487
+ """
488
+
489
+ CLIP_TEXT_INPUTS_DOCSTRING = r"""
490
+ Args:
491
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
492
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
493
+ it.
494
+
495
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
496
+ [`PreTrainedTokenizer.__call__`] for details.
497
+
498
+ [What are input IDs?](../glossary#input-ids)
499
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
500
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
501
+
502
+ - 1 for tokens that are **not masked**,
503
+ - 0 for tokens that are **masked**.
504
+
505
+ [What are attention masks?](../glossary#attention-mask)
506
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
507
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
508
+ config.max_position_embeddings - 1]`.
509
+
510
+ [What are position IDs?](../glossary#position-ids)
511
+ output_attentions (`bool`, *optional*):
512
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
513
+ tensors for more detail.
514
+ output_hidden_states (`bool`, *optional*):
515
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
516
+ more detail.
517
+ return_dict (`bool`, *optional*):
518
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
519
+ """
520
+
521
+ CLIP_VISION_INPUTS_DOCSTRING = r"""
522
+ Args:
523
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
524
+ Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
525
+ [`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
526
+ output_attentions (`bool`, *optional*):
527
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
528
+ tensors for more detail.
529
+ output_hidden_states (`bool`, *optional*):
530
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
531
+ more detail.
532
+ return_dict (`bool`, *optional*):
533
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
534
+ """
535
+
536
+ CLIP_INPUTS_DOCSTRING = r"""
537
+ Args:
538
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
539
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
540
+ it.
541
+
542
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
543
+ [`PreTrainedTokenizer.__call__`] for details.
544
+
545
+ [What are input IDs?](../glossary#input-ids)
546
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
547
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
548
+
549
+ - 1 for tokens that are **not masked**,
550
+ - 0 for tokens that are **masked**.
551
+
552
+ [What are attention masks?](../glossary#attention-mask)
553
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
554
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
555
+ config.max_position_embeddings - 1]`.
556
+
557
+ [What are position IDs?](../glossary#position-ids)
558
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
559
+ Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
560
+ [`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
561
+ return_loss (`bool`, *optional*):
562
+ Whether or not to return the contrastive loss.
563
+ output_attentions (`bool`, *optional*):
564
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
565
+ tensors for more detail.
566
+ output_hidden_states (`bool`, *optional*):
567
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
568
+ more detail.
569
+ return_dict (`bool`, *optional*):
570
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
571
+ """
572
+
573
+
574
+ class CLIPEncoder(nn.Module):
575
+ """
576
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
577
+ [`CLIPEncoderLayer`].
578
+
579
+ Args:
580
+ config: CLIPConfig
581
+ """
582
+
583
+ def __init__(self, config: CLIPConfig, PT_len):
584
+ super().__init__()
585
+ self.config = config
586
+ self.prompts = []
587
+ self.prompts_token_len = PT_len #PT_len
588
+ import torch.nn.init as init
589
+ if self.prompts_token_len > 0:
590
+ for i in range(config.num_hidden_layers):
591
+ self.prompts.append(init.xavier_uniform_(nn.Parameter(torch.randn(1,PT_len,config.hidden_size))))
592
+ self.prompts = nn.ParameterList(self.prompts)
593
+ self.layers = nn.ModuleList([CLIPEncoderLayer(config) for _ in range(config.num_hidden_layers)])
594
+ # for check parameter
595
+ self.debug_weights = 0
596
+ self.index = 0
597
+ self.gradient_checkpointing = False
598
+
599
+ def forward(
600
+ self,
601
+ inputs_embeds,
602
+ attention_mask: Optional[torch.Tensor] = None,
603
+ causal_attention_mask: Optional[torch.Tensor] = None,
604
+ output_attentions: Optional[bool] = None,
605
+ output_hidden_states: Optional[bool] = None,
606
+ return_dict: Optional[bool] = None,
607
+ ) -> Union[Tuple, BaseModelOutput]:
608
+ r"""
609
+ Args:
610
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
611
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
612
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
613
+ than the model's internal embedding lookup matrix.
614
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
615
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
616
+
617
+ - 1 for tokens that are **not masked**,
618
+ - 0 for tokens that are **masked**.
619
+
620
+ [What are attention masks?](../glossary#attention-mask)
621
+ causal_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
622
+ Causal mask for the text model. Mask values selected in `[0, 1]`:
623
+
624
+ - 1 for tokens that are **not masked**,
625
+ - 0 for tokens that are **masked**.
626
+
627
+ [What are attention masks?](../glossary#attention-mask)
628
+ output_attentions (`bool`, *optional*):
629
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
630
+ returned tensors for more detail.
631
+ output_hidden_states (`bool`, *optional*):
632
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
633
+ for more detail.
634
+ return_dict (`bool`, *optional*):
635
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
636
+ """
637
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
638
+ output_hidden_states = (
639
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
640
+ )
641
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
642
+
643
+ encoder_states = () if output_hidden_states else None
644
+ all_attentions = () if output_attentions else None
645
+
646
+ # hidden_states = inputs_embeds
647
+ if self.prompts_token_len > 0:
648
+ inputs_PT = self.prompts[0].repeat(inputs_embeds.size(0), 1, 1).to(inputs_embeds.device).to(inputs_embeds.dtype)
649
+ hidden_states = torch.cat((inputs_PT,inputs_embeds), dim=1)
650
+ # if self.index > 2:
651
+ # print(f"CLIP sanity check:.Sum differ:{torch.sum(self.debug_weights - self.prompts[-5])},Require_grad?:{self.prompts[-5].requires_grad},Grad?:{self.prompts[-5].grad}")
652
+ self.debug_weights = self.prompts[-5].data.clone().detach()
653
+ self.index += 1
654
+ # print(F"CLIP VIT-before:{inputs_embeds.shape},after add Turnable Prompt:{hidden_states.shape}")
655
+ else:
656
+ hidden_states = inputs_embeds
657
+ # print("No ClipViT learnable Prompt added")
658
+
659
+ for idx, encoder_layer in enumerate(self.layers):
660
+ if self.prompts_token_len > 0:
661
+ # [1,257,1024]
662
+ hidden_states[:, :self.prompts_token_len, :] = self.prompts[idx].repeat(inputs_embeds.size(0),1, 1).to(hidden_states.device).to(hidden_states.dtype)
663
+ if output_hidden_states:
664
+ encoder_states = encoder_states + (hidden_states,)
665
+ if self.gradient_checkpointing and self.training:
666
+
667
+ def create_custom_forward(module):
668
+ def custom_forward(*inputs):
669
+ return module(*inputs, output_attentions)
670
+
671
+ return custom_forward
672
+
673
+ layer_outputs = torch.utils.checkpoint.checkpoint(
674
+ create_custom_forward(encoder_layer),
675
+ hidden_states,
676
+ attention_mask,
677
+ causal_attention_mask,
678
+ )
679
+ else:
680
+ layer_outputs = encoder_layer(
681
+ hidden_states,
682
+ attention_mask,
683
+ causal_attention_mask,
684
+ output_attentions=output_attentions,
685
+ )
686
+
687
+ hidden_states = layer_outputs[0]
688
+
689
+ if output_attentions:
690
+ all_attentions = all_attentions + (layer_outputs[1],)
691
+
692
+ if output_hidden_states:
693
+ encoder_states = encoder_states + (hidden_states,)
694
+
695
+ if not return_dict:
696
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
697
+ return BaseModelOutput(
698
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
699
+ )
700
+
701
+
702
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
703
+ def _make_causal_mask(
704
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
705
+ ):
706
+ """
707
+ Make causal mask used for bi-directional self-attention.
708
+ """
709
+ bsz, tgt_len = input_ids_shape
710
+ mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
711
+ mask_cond = torch.arange(mask.size(-1), device=device)
712
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
713
+ mask = mask.to(dtype)
714
+
715
+ if past_key_values_length > 0:
716
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
717
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
718
+
719
+ # [batch_size,seq_len,hidden_dim]
720
+ # img -》 Conv -> |Prompt token| VIT [batch_size,seq_len,hidden_dim]
721
+ # [batch_size,seq_len + X, hidden_dim]
722
+ class CLIPTextTransformer(nn.Module):
723
+ def __init__(self, config: CLIPTextConfig):
724
+ super().__init__()
725
+ self.config = config
726
+ embed_dim = config.hidden_size
727
+ self.embeddings = CLIPTextEmbeddings(config)
728
+ self.encoder = CLIPEncoder(config)
729
+ self.final_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
730
+
731
+ @add_start_docstrings_to_model_forward(CLIP_TEXT_INPUTS_DOCSTRING)
732
+ @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=CLIPTextConfig)
733
+ def forward(
734
+ self,
735
+ input_ids: Optional[torch.Tensor] = None,
736
+ attention_mask: Optional[torch.Tensor] = None,
737
+ position_ids: Optional[torch.Tensor] = None,
738
+ output_attentions: Optional[bool] = None,
739
+ output_hidden_states: Optional[bool] = None,
740
+ return_dict: Optional[bool] = None,
741
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
742
+ r"""
743
+ Returns:
744
+
745
+ """
746
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
747
+ output_hidden_states = (
748
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
749
+ )
750
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
751
+
752
+ if input_ids is None:
753
+ raise ValueError("You have to specify input_ids")
754
+
755
+ input_shape = input_ids.size()
756
+ input_ids = input_ids.view(-1, input_shape[-1])
757
+
758
+ hidden_states = self.embeddings(input_ids=input_ids, position_ids=position_ids)
759
+
760
+ # CLIP's text model uses causal mask, prepare it here.
761
+ # https://github.com/openai/CLIP/blob/cfcffb90e69f37bf2ff1e988237a0fbe41f33c04/clip/model.py#L324
762
+ causal_attention_mask = _make_causal_mask(input_shape, hidden_states.dtype, device=hidden_states.device)
763
+ # expand attention_mask
764
+ if attention_mask is not None:
765
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
766
+ attention_mask = _expand_mask(attention_mask, hidden_states.dtype)
767
+
768
+ encoder_outputs = self.encoder(
769
+ inputs_embeds=hidden_states,
770
+ attention_mask=attention_mask,
771
+ causal_attention_mask=causal_attention_mask,
772
+ output_attentions=output_attentions,
773
+ output_hidden_states=output_hidden_states,
774
+ return_dict=return_dict,
775
+ )
776
+
777
+ last_hidden_state = encoder_outputs[0]
778
+ last_hidden_state = self.final_layer_norm(last_hidden_state)
779
+
780
+ # text_embeds.shape = [batch_size, sequence_length, transformer.width]
781
+ # take features from the eot embedding (eot_token is the highest number in each sequence)
782
+ # casting to torch.int for onnx compatibility: argmax doesn't support int64 inputs with opset 14
783
+ pooled_output = last_hidden_state[
784
+ torch.arange(last_hidden_state.shape[0], device=last_hidden_state.device),
785
+ input_ids.to(dtype=torch.int, device=last_hidden_state.device).argmax(dim=-1),
786
+ ]
787
+
788
+ if not return_dict:
789
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
790
+
791
+ return BaseModelOutputWithPooling(
792
+ last_hidden_state=last_hidden_state,
793
+ pooler_output=pooled_output,
794
+ hidden_states=encoder_outputs.hidden_states,
795
+ attentions=encoder_outputs.attentions,
796
+ )
797
+
798
+
799
+ @add_start_docstrings(
800
+ """The text model from CLIP without any head or projection on top.""",
801
+ CLIP_START_DOCSTRING,
802
+ )
803
+ class CLIPTextModel(CLIPPreTrainedModel):
804
+ config_class = CLIPTextConfig
805
+
806
+ _no_split_modules = ["CLIPEncoderLayer"]
807
+
808
+ def __init__(self, config: CLIPTextConfig):
809
+ super().__init__(config)
810
+ self.text_model = CLIPTextTransformer(config)
811
+ # Initialize weights and apply final processing
812
+ self.post_init()
813
+
814
+ def get_input_embeddings(self) -> nn.Module:
815
+ return self.text_model.embeddings.token_embedding
816
+
817
+ def set_input_embeddings(self, value):
818
+ self.text_model.embeddings.token_embedding = value
819
+
820
+ @add_start_docstrings_to_model_forward(CLIP_TEXT_INPUTS_DOCSTRING)
821
+ @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=CLIPTextConfig)
822
+ def forward(
823
+ self,
824
+ input_ids: Optional[torch.Tensor] = None,
825
+ attention_mask: Optional[torch.Tensor] = None,
826
+ position_ids: Optional[torch.Tensor] = None,
827
+ output_attentions: Optional[bool] = None,
828
+ output_hidden_states: Optional[bool] = None,
829
+ return_dict: Optional[bool] = None,
830
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
831
+ r"""
832
+ Returns:
833
+
834
+ Examples:
835
+
836
+ ```python
837
+ >>> from transformers import AutoTokenizer, CLIPTextModel
838
+
839
+ >>> model = CLIPTextModel.from_pretrained("openai/clip-vit-base-patch32")
840
+ >>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")
841
+
842
+ >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
843
+
844
+ >>> outputs = model(**inputs)
845
+ >>> last_hidden_state = outputs.last_hidden_state
846
+ >>> pooled_output = outputs.pooler_output # pooled (EOS token) states
847
+ ```"""
848
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
849
+
850
+ return self.text_model(
851
+ input_ids=input_ids,
852
+ attention_mask=attention_mask,
853
+ position_ids=position_ids,
854
+ output_attentions=output_attentions,
855
+ output_hidden_states=output_hidden_states,
856
+ return_dict=return_dict,
857
+ )
858
+
859
+
860
+ class CLIPVisionTransformer(nn.Module):
861
+ def __init__(self, config: CLIPVisionConfig, PT_len):
862
+ super().__init__()
863
+ self.config = config
864
+ embed_dim = config.hidden_size
865
+
866
+ self.embeddings = CLIPVisionEmbeddings(config)
867
+ self.pre_layrnorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
868
+ self.encoder = CLIPEncoder(config,PT_len)
869
+ self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
870
+ def make_prompt_learnable(self):
871
+ # go through all prompts and make them learnable
872
+ for pt in self.encoder.prompts:
873
+ for p in pt.parameters():
874
+ p.requires_grad = True
875
+ @add_start_docstrings_to_model_forward(CLIP_VISION_INPUTS_DOCSTRING)
876
+ @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=CLIPVisionConfig)
877
+ def forward(
878
+ self,
879
+ pixel_values: Optional[torch.FloatTensor] = None,
880
+ output_attentions: Optional[bool] = None,
881
+ output_hidden_states: Optional[bool] = None,
882
+ return_dict: Optional[bool] = None,
883
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
884
+ r"""
885
+ Returns:
886
+
887
+ """
888
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
889
+ output_hidden_states = (
890
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
891
+ )
892
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
893
+
894
+ if pixel_values is None:
895
+ raise ValueError("You have to specify pixel_values")
896
+
897
+ hidden_states = self.embeddings(pixel_values)
898
+ hidden_states = self.pre_layrnorm(hidden_states)
899
+ # add prompt tokens here?
900
+
901
+ encoder_outputs = self.encoder(
902
+ inputs_embeds=hidden_states,
903
+ output_attentions=output_attentions,
904
+ output_hidden_states=output_hidden_states,
905
+ return_dict=return_dict,
906
+ )
907
+
908
+ last_hidden_state = encoder_outputs[0]
909
+ pooled_output = last_hidden_state[:, 0, :]
910
+ pooled_output = self.post_layernorm(pooled_output)
911
+
912
+ if not return_dict:
913
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
914
+
915
+ return BaseModelOutputWithPooling(
916
+ last_hidden_state=last_hidden_state,
917
+ pooler_output=pooled_output,
918
+ hidden_states=encoder_outputs.hidden_states,
919
+ attentions=encoder_outputs.attentions,
920
+ )
921
+
922
+
923
+ @add_start_docstrings(
924
+ """The vision model from CLIP without any head or projection on top.""",
925
+ CLIP_START_DOCSTRING,
926
+ )
927
+ class CLIPVisionModel(CLIPPreTrainedModel):
928
+ config_class = CLIPVisionConfig
929
+ main_input_name = "pixel_values"
930
+
931
+ def __init__(self, config: CLIPVisionConfig, PT_len):
932
+ super().__init__(config)
933
+ self.vision_model = CLIPVisionTransformer(config,PT_len)
934
+ self.vision_model.eval()
935
+ # Initialize weights and apply final processing
936
+ self.post_init()
937
+ def get_prompt_embeddings(self):
938
+ return self.vision_model.encoder.prompts
939
+ def make_prompt_learnable(self):
940
+ for p in self.vision_model.encoder.parameters():
941
+ p.requires_grad = False
942
+ self.vision_model.encoder.prompts.requires_grad_(True)
943
+ def make_prompt_unlearnable(self):
944
+ for p in self.vision_model.encoder.parameters():
945
+ p.requires_grad = False
946
+ self.vision_model.encoder.prompts.requires_grad_(False)
947
+
948
+ def get_input_embeddings(self) -> nn.Module:
949
+ return self.vision_model.embeddings.patch_embedding
950
+
951
+ @add_start_docstrings_to_model_forward(CLIP_VISION_INPUTS_DOCSTRING)
952
+ @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=CLIPVisionConfig)
953
+ def forward(
954
+ self,
955
+ pixel_values: Optional[torch.FloatTensor] = None,
956
+ output_attentions: Optional[bool] = None,
957
+ output_hidden_states: Optional[bool] = None,
958
+ return_dict: Optional[bool] = None,
959
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
960
+ r"""
961
+ Returns:
962
+
963
+ Examples:
964
+
965
+ ```python
966
+ >>> from PIL import Image
967
+ >>> import requests
968
+ >>> from transformers import AutoProcessor, CLIPVisionModel
969
+
970
+ >>> model = CLIPVisionModel.from_pretrained("openai/clip-vit-base-patch32")
971
+ >>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
972
+
973
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
974
+ >>> image = Image.open(requests.get(url, stream=True).raw)
975
+
976
+ >>> inputs = processor(images=image, return_tensors="pt")
977
+
978
+ >>> outputs = model(**inputs)
979
+ >>> last_hidden_state = outputs.last_hidden_state
980
+ >>> pooled_output = outputs.pooler_output # pooled CLS states
981
+ ```"""
982
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
983
+
984
+ return self.vision_model(
985
+ pixel_values=pixel_values,
986
+ output_attentions=output_attentions,
987
+ output_hidden_states=output_hidden_states,
988
+ return_dict=return_dict,
989
+ )
990
+
991
+
992
+ @add_start_docstrings(CLIP_START_DOCSTRING)
993
+ class CLIPModel(CLIPPreTrainedModel):
994
+ config_class = CLIPConfig
995
+
996
+ def __init__(self, config: CLIPConfig):
997
+ super().__init__(config)
998
+
999
+ if not isinstance(config.text_config, CLIPTextConfig):
1000
+ raise ValueError(
1001
+ "config.text_config is expected to be of type CLIPTextConfig but is of type"
1002
+ f" {type(config.text_config)}."
1003
+ )
1004
+
1005
+ if not isinstance(config.vision_config, CLIPVisionConfig):
1006
+ raise ValueError(
1007
+ "config.vision_config is expected to be of type CLIPVisionConfig but is of type"
1008
+ f" {type(config.vision_config)}."
1009
+ )
1010
+
1011
+ text_config = config.text_config
1012
+ vision_config = config.vision_config
1013
+
1014
+ self.projection_dim = config.projection_dim
1015
+ self.text_embed_dim = text_config.hidden_size
1016
+ self.vision_embed_dim = vision_config.hidden_size
1017
+
1018
+ self.text_model = CLIPTextTransformer(text_config)
1019
+ self.vision_model = CLIPVisionTransformer(vision_config)
1020
+
1021
+ self.visual_projection = nn.Linear(self.vision_embed_dim, self.projection_dim, bias=False)
1022
+ self.text_projection = nn.Linear(self.text_embed_dim, self.projection_dim, bias=False)
1023
+ self.logit_scale = nn.Parameter(torch.tensor(self.config.logit_scale_init_value))
1024
+
1025
+ # Initialize weights and apply final processing
1026
+ self.post_init()
1027
+
1028
+ @add_start_docstrings_to_model_forward(CLIP_TEXT_INPUTS_DOCSTRING)
1029
+ def get_text_features(
1030
+ self,
1031
+ input_ids: Optional[torch.Tensor] = None,
1032
+ attention_mask: Optional[torch.Tensor] = None,
1033
+ position_ids: Optional[torch.Tensor] = None,
1034
+ output_attentions: Optional[bool] = None,
1035
+ output_hidden_states: Optional[bool] = None,
1036
+ return_dict: Optional[bool] = None,
1037
+ ) -> torch.FloatTensor:
1038
+ r"""
1039
+ Returns:
1040
+ text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
1041
+ applying the projection layer to the pooled output of [`CLIPTextModel`].
1042
+
1043
+ Examples:
1044
+
1045
+ ```python
1046
+ >>> from transformers import AutoTokenizer, CLIPModel
1047
+
1048
+ >>> model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
1049
+ >>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")
1050
+
1051
+ >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
1052
+ >>> text_features = model.get_text_features(**inputs)
1053
+ ```"""
1054
+ # Use CLIP model's config for some fields (if specified) instead of those of vision & text components.
1055
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1056
+ output_hidden_states = (
1057
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1058
+ )
1059
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1060
+
1061
+ text_outputs = self.text_model(
1062
+ input_ids=input_ids,
1063
+ attention_mask=attention_mask,
1064
+ position_ids=position_ids,
1065
+ output_attentions=output_attentions,
1066
+ output_hidden_states=output_hidden_states,
1067
+ return_dict=return_dict,
1068
+ )
1069
+
1070
+ pooled_output = text_outputs[1]
1071
+ text_features = self.text_projection(pooled_output)
1072
+
1073
+ return text_features
1074
+
1075
+ @add_start_docstrings_to_model_forward(CLIP_VISION_INPUTS_DOCSTRING)
1076
+ def get_image_features(
1077
+ self,
1078
+ pixel_values: Optional[torch.FloatTensor] = None,
1079
+ output_attentions: Optional[bool] = None,
1080
+ output_hidden_states: Optional[bool] = None,
1081
+ return_dict: Optional[bool] = None,
1082
+ ) -> torch.FloatTensor:
1083
+ r"""
1084
+ Returns:
1085
+ image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by
1086
+ applying the projection layer to the pooled output of [`CLIPVisionModel`].
1087
+
1088
+ Examples:
1089
+
1090
+ ```python
1091
+ >>> from PIL import Image
1092
+ >>> import requests
1093
+ >>> from transformers import AutoProcessor, CLIPModel
1094
+
1095
+ >>> model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
1096
+ >>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
1097
+
1098
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1099
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1100
+
1101
+ >>> inputs = processor(images=image, return_tensors="pt")
1102
+
1103
+ >>> image_features = model.get_image_features(**inputs)
1104
+ ```"""
1105
+ # Use CLIP model's config for some fields (if specified) instead of those of vision & text components.
1106
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1107
+ output_hidden_states = (
1108
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1109
+ )
1110
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1111
+
1112
+ vision_outputs = self.vision_model(
1113
+ pixel_values=pixel_values,
1114
+ output_attentions=output_attentions,
1115
+ output_hidden_states=output_hidden_states,
1116
+ return_dict=return_dict,
1117
+ )
1118
+
1119
+ pooled_output = vision_outputs[1] # pooled_output
1120
+ image_features = self.visual_projection(pooled_output)
1121
+
1122
+ return image_features
1123
+
1124
+ @add_start_docstrings_to_model_forward(CLIP_INPUTS_DOCSTRING)
1125
+ @replace_return_docstrings(output_type=CLIPOutput, config_class=CLIPConfig)
1126
+ def forward(
1127
+ self,
1128
+ input_ids: Optional[torch.LongTensor] = None,
1129
+ pixel_values: Optional[torch.FloatTensor] = None,
1130
+ attention_mask: Optional[torch.Tensor] = None,
1131
+ position_ids: Optional[torch.LongTensor] = None,
1132
+ return_loss: Optional[bool] = None,
1133
+ output_attentions: Optional[bool] = None,
1134
+ output_hidden_states: Optional[bool] = None,
1135
+ return_dict: Optional[bool] = None,
1136
+ ) -> Union[Tuple, CLIPOutput]:
1137
+ r"""
1138
+ Returns:
1139
+
1140
+ Examples:
1141
+
1142
+ ```python
1143
+ >>> from PIL import Image
1144
+ >>> import requests
1145
+ >>> from transformers import AutoProcessor, CLIPModel
1146
+
1147
+ >>> model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
1148
+ >>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
1149
+
1150
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1151
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1152
+
1153
+ >>> inputs = processor(
1154
+ ... text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True
1155
+ ... )
1156
+
1157
+ >>> outputs = model(**inputs)
1158
+ >>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score
1159
+ >>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities
1160
+ ```"""
1161
+ # Use CLIP model's config for some fields (if specified) instead of those of vision & text components.
1162
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1163
+ output_hidden_states = (
1164
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1165
+ )
1166
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1167
+
1168
+ vision_outputs = self.vision_model(
1169
+ pixel_values=pixel_values,
1170
+ output_attentions=output_attentions,
1171
+ output_hidden_states=output_hidden_states,
1172
+ return_dict=return_dict,
1173
+ )
1174
+
1175
+ text_outputs = self.text_model(
1176
+ input_ids=input_ids,
1177
+ attention_mask=attention_mask,
1178
+ position_ids=position_ids,
1179
+ output_attentions=output_attentions,
1180
+ output_hidden_states=output_hidden_states,
1181
+ return_dict=return_dict,
1182
+ )
1183
+
1184
+ image_embeds = vision_outputs[1]
1185
+ image_embeds = self.visual_projection(image_embeds)
1186
+
1187
+ text_embeds = text_outputs[1]
1188
+ text_embeds = self.text_projection(text_embeds)
1189
+
1190
+ # normalized features
1191
+ image_embeds = image_embeds / image_embeds.norm(p=2, dim=-1, keepdim=True)
1192
+ text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
1193
+
1194
+ # cosine similarity as logits
1195
+ logit_scale = self.logit_scale.exp()
1196
+ logits_per_text = torch.matmul(text_embeds, image_embeds.t()) * logit_scale
1197
+ logits_per_image = logits_per_text.t()
1198
+
1199
+ loss = None
1200
+ if return_loss:
1201
+ loss = clip_loss(logits_per_text)
1202
+
1203
+ if not return_dict:
1204
+ output = (logits_per_image, logits_per_text, text_embeds, image_embeds, text_outputs, vision_outputs)
1205
+ return ((loss,) + output) if loss is not None else output
1206
+
1207
+ return CLIPOutput(
1208
+ loss=loss,
1209
+ logits_per_image=logits_per_image,
1210
+ logits_per_text=logits_per_text,
1211
+ text_embeds=text_embeds,
1212
+ image_embeds=image_embeds,
1213
+ text_model_output=text_outputs,
1214
+ vision_model_output=vision_outputs,
1215
+ )
1216
+
1217
+
1218
+ @add_start_docstrings(
1219
+ """
1220
+ CLIP Text Model with a projection layer on top (a linear layer on top of the pooled output).
1221
+ """,
1222
+ CLIP_START_DOCSTRING,
1223
+ )
1224
+ class CLIPTextModelWithProjection(CLIPPreTrainedModel):
1225
+ config_class = CLIPTextConfig
1226
+
1227
+ _no_split_modules = ["CLIPEncoderLayer"]
1228
+
1229
+ def __init__(self, config: CLIPTextConfig):
1230
+ super().__init__(config)
1231
+
1232
+ self.text_model = CLIPTextTransformer(config)
1233
+
1234
+ self.text_projection = nn.Linear(config.hidden_size, config.projection_dim, bias=False)
1235
+
1236
+ # Initialize weights and apply final processing
1237
+ self.post_init()
1238
+
1239
+ def get_input_embeddings(self) -> nn.Module:
1240
+ return self.text_model.embeddings.token_embedding
1241
+
1242
+ def set_input_embeddings(self, value):
1243
+ self.text_model.embeddings.token_embedding = value
1244
+
1245
+ @add_start_docstrings_to_model_forward(CLIP_TEXT_INPUTS_DOCSTRING)
1246
+ @replace_return_docstrings(output_type=CLIPTextModelOutput, config_class=CLIPTextConfig)
1247
+ def forward(
1248
+ self,
1249
+ input_ids: Optional[torch.Tensor] = None,
1250
+ attention_mask: Optional[torch.Tensor] = None,
1251
+ position_ids: Optional[torch.Tensor] = None,
1252
+ output_attentions: Optional[bool] = None,
1253
+ output_hidden_states: Optional[bool] = None,
1254
+ return_dict: Optional[bool] = None,
1255
+ ) -> Union[Tuple, CLIPTextModelOutput]:
1256
+ r"""
1257
+ Returns:
1258
+
1259
+ Examples:
1260
+
1261
+ ```python
1262
+ >>> from transformers import AutoTokenizer, CLIPTextModelWithProjection
1263
+
1264
+ >>> model = CLIPTextModelWithProjection.from_pretrained("openai/clip-vit-base-patch32")
1265
+ >>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")
1266
+
1267
+ >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
1268
+
1269
+ >>> outputs = model(**inputs)
1270
+ >>> text_embeds = outputs.text_embeds
1271
+ ```"""
1272
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1273
+
1274
+ text_outputs = self.text_model(
1275
+ input_ids=input_ids,
1276
+ attention_mask=attention_mask,
1277
+ position_ids=position_ids,
1278
+ output_attentions=output_attentions,
1279
+ output_hidden_states=output_hidden_states,
1280
+ return_dict=return_dict,
1281
+ )
1282
+
1283
+ pooled_output = text_outputs[1]
1284
+
1285
+ text_embeds = self.text_projection(pooled_output)
1286
+
1287
+ if not return_dict:
1288
+ outputs = (text_embeds, text_outputs[0]) + text_outputs[2:]
1289
+ return tuple(output for output in outputs if output is not None)
1290
+
1291
+ return CLIPTextModelOutput(
1292
+ text_embeds=text_embeds,
1293
+ last_hidden_state=text_outputs.last_hidden_state,
1294
+ hidden_states=text_outputs.hidden_states,
1295
+ attentions=text_outputs.attentions,
1296
+ )
1297
+
1298
+
1299
+ @add_start_docstrings(
1300
+ """
1301
+ CLIP Vision Model with a projection layer on top (a linear layer on top of the pooled output).
1302
+ """,
1303
+ CLIP_START_DOCSTRING,
1304
+ )
1305
+ class CLIPVisionModelWithProjection(CLIPPreTrainedModel):
1306
+ config_class = CLIPVisionConfig
1307
+ main_input_name = "pixel_values"
1308
+
1309
+ def __init__(self, config: CLIPVisionConfig):
1310
+ super().__init__(config)
1311
+
1312
+ self.vision_model = CLIPVisionTransformer(config)
1313
+
1314
+ self.visual_projection = nn.Linear(config.hidden_size, config.projection_dim, bias=False)
1315
+
1316
+ # Initialize weights and apply final processing
1317
+ self.post_init()
1318
+
1319
+ def get_input_embeddings(self) -> nn.Module:
1320
+ return self.vision_model.embeddings.patch_embedding
1321
+
1322
+ @add_start_docstrings_to_model_forward(CLIP_VISION_INPUTS_DOCSTRING)
1323
+ @replace_return_docstrings(output_type=CLIPVisionModelOutput, config_class=CLIPVisionConfig)
1324
+ def forward(
1325
+ self,
1326
+ pixel_values: Optional[torch.FloatTensor] = None,
1327
+ output_attentions: Optional[bool] = None,
1328
+ output_hidden_states: Optional[bool] = None,
1329
+ return_dict: Optional[bool] = None,
1330
+ ) -> Union[Tuple, CLIPVisionModelOutput]:
1331
+ r"""
1332
+ Returns:
1333
+
1334
+ Examples:
1335
+
1336
+ ```python
1337
+ >>> from PIL import Image
1338
+ >>> import requests
1339
+ >>> from transformers import AutoProcessor, CLIPVisionModelWithProjection
1340
+
1341
+ >>> model = CLIPVisionModelWithProjection.from_pretrained("openai/clip-vit-base-patch32")
1342
+ >>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
1343
+
1344
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1345
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1346
+
1347
+ >>> inputs = processor(images=image, return_tensors="pt")
1348
+
1349
+ >>> outputs = model(**inputs)
1350
+ >>> image_embeds = outputs.image_embeds
1351
+ ```"""
1352
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1353
+
1354
+ vision_outputs = self.vision_model(
1355
+ pixel_values=pixel_values,
1356
+ output_attentions=output_attentions,
1357
+ output_hidden_states=output_hidden_states,
1358
+ return_dict=return_dict,
1359
+ )
1360
+
1361
+ pooled_output = vision_outputs[1] # pooled_output
1362
+
1363
+ image_embeds = self.visual_projection(pooled_output)
1364
+
1365
+ if not return_dict:
1366
+ outputs = (image_embeds, vision_outputs[0]) + vision_outputs[2:]
1367
+ return tuple(output for output in outputs if output is not None)
1368
+
1369
+ return CLIPVisionModelOutput(
1370
+ image_embeds=image_embeds,
1371
+ last_hidden_state=vision_outputs.last_hidden_state,
1372
+ hidden_states=vision_outputs.hidden_states,
1373
+ attentions=vision_outputs.attentions,
1374
+ )
modeling_multicasttimer.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+ from transformers import PreTrainedModel, PretrainedConfig
4
+ from safetensors.torch import load_file
5
+
6
+ # CLIP
7
+ from .modeling_clipPT import CLIPVisionTransformer
8
+ from transformers import CLIPImageProcessor
9
+
10
+ from transformers import AutoTokenizer
11
+ # Qwen
12
+ from .modeling_qwen2 import Qwen2Model
13
+
14
+ # Timer
15
+ from .modeling_timer import TimerForPrediction
16
+
17
+ class MulTiCastTimerConfig(PretrainedConfig):
18
+ def __init__(
19
+ self,
20
+ forecasting_length = None,
21
+ vision_model_name = None,
22
+ text_model_name = None,
23
+ vision_model_prompt_len = None,
24
+ text_model_prompt_len = None,
25
+ timer_prompt_len = None,
26
+ **kwargs
27
+ ):
28
+ super().__init__(**kwargs)
29
+ self.forecasting_length = forecasting_length
30
+ self.vision_model_name = vision_model_name
31
+ self.text_model_name = text_model_name
32
+
33
+ self.vision_model_prompt_len = vision_model_prompt_len if vision_model_prompt_len is not None else 10
34
+ self.text_model_prompt_len = text_model_prompt_len if text_model_prompt_len is not None else 4
35
+ self.timer_prompt_len = timer_prompt_len if timer_prompt_len is not None else 4
36
+
37
+ class MulTiCastTimerModel(PreTrainedModel):
38
+
39
+ config_class = MulTiCastTimerConfig
40
+
41
+ def __init__(self, config):
42
+ super().__init__(config)
43
+ self.config = config
44
+
45
+ # Vision Model
46
+ if config.vision_model_name is None:
47
+ pass
48
+ elif config.vision_model_name == 'CLIP':
49
+ from transformers import AutoModel
50
+ vision_model = AutoModel.from_pretrained("openai/clip-vit-base-patch32").vision_model
51
+ state_dict = vision_model.state_dict()
52
+ state_dict = {k: v.to(torch.bfloat16) for k, v in state_dict.items()}
53
+ self.vision_model = CLIPVisionTransformer(vision_model.config, config.vision_model_prompt_len)
54
+ self.vision_model.load_state_dict(state_dict, strict=False)
55
+ self.processor = CLIPImageProcessor()
56
+ for name, param in self.vision_model.named_parameters(): # Freeze layers other than prompts
57
+ if "encoder.prompts" in name:
58
+ param.requires_grad = True
59
+ else:
60
+ param.requires_grad = False
61
+ else:
62
+ pass
63
+
64
+ # Text Model
65
+ if config.text_model_name is None:
66
+ pass
67
+ elif config.text_model_name == 'Qwen':
68
+ self.tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-1.5B-Instruct")
69
+ from transformers import AutoModelForCausalLM
70
+ text_model = AutoModelForCausalLM.from_pretrained(
71
+ "Qwen/Qwen2-1.5B-Instruct",
72
+ torch_dtype=torch.bfloat16,
73
+ device_map="cpu",
74
+ attn_implementation="sdpa"
75
+ ).model
76
+ state_dict = text_model.state_dict()
77
+ self.text_model = Qwen2Model(text_model.config, config.text_model_prompt_len)
78
+ self.text_model.load_state_dict(state_dict, strict=False)
79
+ for name, param in self.text_model.named_parameters(): # Freeze layers other than prompts
80
+ if "prompts" in name:
81
+ param.requires_grad = True
82
+ else:
83
+ param.requires_grad = False
84
+ else:
85
+ pass
86
+
87
+ # Timer
88
+ from transformers import AutoModelForCausalLM
89
+ timer = AutoModelForCausalLM.from_pretrained('thuml/timer-base-84m', trust_remote_code=True)
90
+ state_dict = timer.state_dict()
91
+ self.timer = TimerForPrediction(timer.config, config.timer_prompt_len)
92
+ self.timer.load_state_dict(state_dict, strict=False)
93
+ for name, param in self.timer.named_parameters(): # Freeze layers other than prompts
94
+ if "model.prompts" in name:
95
+ param.requires_grad = True
96
+ else:
97
+ param.requires_grad = False
98
+
99
+ # Vision Interaction Layer
100
+ if config.vision_model_name is None:
101
+ pass
102
+ else:
103
+ self.vision_interaction_layer = nn.Linear(self.vision_model.config.hidden_size, self.timer.config.hidden_size)
104
+
105
+ # Text Interaction Layer
106
+ if config.text_model_name is None:
107
+ pass
108
+ else:
109
+ self.text_interaction_layer = nn.Linear(self.text_model.config.hidden_size, self.timer.config.hidden_size)
110
+
111
+ def predict(self, input_ids = None, images = None, texts = None):
112
+ images = self.processor.preprocess(images)['pixel_values'][0]
113
+ images = torch.tensor(images)
114
+ images = images.unsqueeze(0)
115
+
116
+ if self.config.vision_model_name is None and images is None:
117
+ vision_embedding = None
118
+ else:
119
+ vision_output = self.vision_model(images, output_attentions=True)
120
+ vision_attentions = vision_output.attentions
121
+ vision_embedding = vision_output.pooler_output
122
+ vision_embedding = self.vision_interaction_layer(vision_embedding)
123
+
124
+ if self.config.text_model_name is None and all(x is None for x in texts):
125
+ text_embedding = None
126
+ else:
127
+ tokenized_texts = self.tokenizer(texts, return_tensors="pt")
128
+ text_embedding = self.text_model(**tokenized_texts)
129
+ text_embedding = text_embedding.last_hidden_state[:, 0 , :]
130
+ text_embedding = self.text_interaction_layer(text_embedding)
131
+
132
+ out = self.timer(input_ids=input_ids, vision_embedding=vision_embedding, text_embedding=text_embedding)
133
+
134
+ return {
135
+ "logits": out.logits,
136
+ "vision_attentions": vision_attentions,
137
+ "time_series_attentions": out.attentions
138
+ }
139
+
140
+ def forward(self, input_ids = None, images = None, texts = None, labels = None):
141
+ if self.config.vision_model_name is None and images is None:
142
+ vision_embedding = None
143
+ else:
144
+ vision_embedding = self.vision_model(images)
145
+ vision_embedding = vision_embedding.pooler_output
146
+ vision_embedding = self.vision_interaction_layer(vision_embedding)
147
+
148
+ if self.config.text_model_name is None and all(x is None for x in texts):
149
+ text_embedding = None
150
+ else:
151
+ tokenized_texts = self.tokenizer(texts, return_tensors="pt")
152
+ text_embedding = self.text_model(**tokenized_texts)
153
+ text_embedding = text_embedding.last_hidden_state[:, 0 , :]
154
+ text_embedding = self.text_interaction_layer(text_embedding)
155
+
156
+ out = self.timer(input_ids=input_ids, vision_embedding=vision_embedding, text_embedding=text_embedding)
157
+ out = out["logits"]
158
+
159
+ if labels is not None:
160
+ if self.config.forecasting_length == out.shape[-1]:
161
+ loss = torch.mean(torch.square(out-labels)) # MSE
162
+ else: # pretrained Timer has 96 forecasting length. This is in case of shorter forecasting length. Forecasting length larger than 96 will occure an error.
163
+ loss = torch.mean(torch.square(out[:, :self.config.forecasting_length]-labels))
164
+ else:
165
+ loss = None
166
+
167
+ return {
168
+ "loss": loss,
169
+ "logits": out
170
+ }
171
+
172
+ @classmethod
173
+ def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
174
+ from transformers.utils import cached_file
175
+ config = MulTiCastTimerConfig.from_pretrained(pretrained_model_name_or_path)
176
+ model = MulTiCastTimerModel(config)
177
+ resolved_file = cached_file(pretrained_model_name_or_path, "model.safetensors")
178
+ state_dict = load_file(resolved_file)
179
+ model.load_state_dict(state_dict, strict=False)
180
+
181
+ return model
modeling_qwen2.py ADDED
@@ -0,0 +1,1408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch Qwen2 model."""
21
+ import inspect
22
+ import math
23
+ import warnings
24
+ from typing import List, Optional, Tuple, Union
25
+
26
+ import torch
27
+ import torch.nn.functional as F
28
+ import torch.utils.checkpoint
29
+ from torch import nn
30
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
31
+
32
+ from transformers.activations import ACT2FN
33
+ from transformers.cache_utils import Cache, DynamicCache
34
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa
35
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
36
+ from transformers.modeling_utils import PreTrainedModel
37
+ from transformers.utils import (
38
+ add_start_docstrings,
39
+ add_start_docstrings_to_model_forward,
40
+ is_flash_attn_greater_or_equal_2_10,
41
+ logging,
42
+ replace_return_docstrings,
43
+ )
44
+ from transformers.models.qwen2.configuration_qwen2 import Qwen2Config
45
+
46
+
47
+ logger = logging.get_logger(__name__)
48
+
49
+
50
+ _CHECKPOINT_FOR_DOC = "Qwen/Qwen2-7B-beta"
51
+ _CONFIG_FOR_DOC = "Qwen2Config"
52
+
53
+
54
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
55
+ def _get_unpad_data(attention_mask):
56
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
57
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
58
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
59
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
60
+ return (
61
+ indices,
62
+ cu_seqlens,
63
+ max_seqlen_in_batch,
64
+ )
65
+
66
+
67
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Qwen2
68
+ class Qwen2RMSNorm(nn.Module):
69
+ def __init__(self, hidden_size, eps=1e-6):
70
+ """
71
+ Qwen2RMSNorm is equivalent to T5LayerNorm
72
+ """
73
+ super().__init__()
74
+ self.weight = nn.Parameter(torch.ones(hidden_size))
75
+ self.variance_epsilon = eps
76
+
77
+ def forward(self, hidden_states):
78
+ input_dtype = hidden_states.dtype
79
+ hidden_states = hidden_states.to(torch.float32)
80
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
81
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
82
+ return self.weight * hidden_states.to(input_dtype)
83
+
84
+
85
+ # Copied from transformers.models.mistral.modeling_mistral.MistralRotaryEmbedding with Mistral->Qwen2
86
+ class Qwen2RotaryEmbedding(nn.Module):
87
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
88
+ super().__init__()
89
+
90
+ self.dim = dim
91
+ self.max_position_embeddings = max_position_embeddings
92
+ self.base = base
93
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
94
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
95
+
96
+ # Build here to make `torch.jit.trace` work.
97
+ self._set_cos_sin_cache(
98
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
99
+ )
100
+
101
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
102
+ self.max_seq_len_cached = seq_len
103
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
104
+
105
+ freqs = torch.outer(t, self.inv_freq)
106
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
107
+ emb = torch.cat((freqs, freqs), dim=-1)
108
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
109
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
110
+
111
+ def forward(self, x, seq_len=None):
112
+ # x: [bs, num_attention_heads, seq_len, head_size]
113
+ if seq_len > self.max_seq_len_cached:
114
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
115
+
116
+ return (
117
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
118
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
119
+ )
120
+
121
+
122
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
123
+ def rotate_half(x):
124
+ """Rotates half the hidden dims of the input."""
125
+ x1 = x[..., : x.shape[-1] // 2]
126
+ x2 = x[..., x.shape[-1] // 2 :]
127
+ return torch.cat((-x2, x1), dim=-1)
128
+
129
+
130
+ # Copied from transformers.models.mistral.modeling_mistral.apply_rotary_pos_emb
131
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
132
+ """Applies Rotary Position Embedding to the query and key tensors.
133
+
134
+ Args:
135
+ q (`torch.Tensor`): The query tensor.
136
+ k (`torch.Tensor`): The key tensor.
137
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
138
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
139
+ position_ids (`torch.Tensor`):
140
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
141
+ used to pass offsetted position ids when working with a KV-cache.
142
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
143
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
144
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
145
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
146
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
147
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
148
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
149
+ Returns:
150
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
151
+ """
152
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
153
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
154
+ q_embed = (q * cos) + (rotate_half(q) * sin)
155
+ k_embed = (k * cos) + (rotate_half(k) * sin)
156
+ return q_embed, k_embed
157
+
158
+
159
+ # Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Qwen2
160
+ class Qwen2MLP(nn.Module):
161
+ def __init__(self, config):
162
+ super().__init__()
163
+ self.config = config
164
+ self.hidden_size = config.hidden_size
165
+ self.intermediate_size = config.intermediate_size
166
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
167
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
168
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
169
+ self.act_fn = ACT2FN[config.hidden_act]
170
+
171
+ def forward(self, x):
172
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
173
+
174
+
175
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
176
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
177
+ """
178
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
179
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
180
+ """
181
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
182
+ if n_rep == 1:
183
+ return hidden_states
184
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
185
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
186
+
187
+
188
+ class Qwen2Attention(nn.Module):
189
+ """
190
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
191
+ and "Generating Long Sequences with Sparse Transformers".
192
+ """
193
+
194
+ def __init__(self, config: Qwen2Config, layer_idx: Optional[int] = None):
195
+ super().__init__()
196
+ self.config = config
197
+ self.layer_idx = layer_idx
198
+ if layer_idx is None:
199
+ logger.warning_once(
200
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
201
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
202
+ "when creating this class."
203
+ )
204
+
205
+ self.hidden_size = config.hidden_size
206
+ self.num_heads = config.num_attention_heads
207
+ self.head_dim = self.hidden_size // self.num_heads
208
+ self.num_key_value_heads = config.num_key_value_heads
209
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
210
+ self.max_position_embeddings = config.max_position_embeddings
211
+ self.rope_theta = config.rope_theta
212
+ self.is_causal = True
213
+ self.attention_dropout = config.attention_dropout
214
+
215
+ if (self.head_dim * self.num_heads) != self.hidden_size:
216
+ raise ValueError(
217
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
218
+ f" and `num_heads`: {self.num_heads})."
219
+ )
220
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
221
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
222
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
223
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
224
+
225
+ self.rotary_emb = Qwen2RotaryEmbedding(
226
+ self.head_dim,
227
+ max_position_embeddings=self.max_position_embeddings,
228
+ base=self.rope_theta,
229
+ )
230
+
231
+ def forward(
232
+ self,
233
+ hidden_states: torch.Tensor,
234
+ attention_mask: Optional[torch.Tensor] = None,
235
+ position_ids: Optional[torch.LongTensor] = None,
236
+ past_key_value: Optional[Cache] = None,
237
+ output_attentions: bool = False,
238
+ use_cache: bool = False,
239
+ **kwargs,
240
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
241
+ if "padding_mask" in kwargs:
242
+ warnings.warn(
243
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
244
+ )
245
+ bsz, q_len, _ = hidden_states.size()
246
+
247
+ query_states = self.q_proj(hidden_states)
248
+ key_states = self.k_proj(hidden_states)
249
+ value_states = self.v_proj(hidden_states)
250
+
251
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
252
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
253
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
254
+
255
+ kv_seq_len = key_states.shape[-2]
256
+ if past_key_value is not None:
257
+ if self.layer_idx is None:
258
+ raise ValueError(
259
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
260
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
261
+ "with a layer index."
262
+ )
263
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
264
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
265
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
266
+
267
+ if past_key_value is not None:
268
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
269
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
270
+
271
+ # repeat k/v heads if n_kv_heads < n_heads
272
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
273
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
274
+
275
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
276
+
277
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
278
+ raise ValueError(
279
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
280
+ f" {attn_weights.size()}"
281
+ )
282
+
283
+ if attention_mask is not None:
284
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
285
+ raise ValueError(
286
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
287
+ )
288
+
289
+ attn_weights = attn_weights + attention_mask
290
+
291
+ # upcast attention to fp32
292
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
293
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
294
+ attn_output = torch.matmul(attn_weights, value_states)
295
+
296
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
297
+ raise ValueError(
298
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
299
+ f" {attn_output.size()}"
300
+ )
301
+
302
+ attn_output = attn_output.transpose(1, 2).contiguous()
303
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
304
+
305
+ attn_output = self.o_proj(attn_output)
306
+
307
+ if not output_attentions:
308
+ attn_weights = None
309
+
310
+ return attn_output, attn_weights, past_key_value
311
+
312
+
313
+ class Qwen2FlashAttention2(Qwen2Attention):
314
+ """
315
+ Qwen2 flash attention module, following Qwen2 attention module. This module inherits from `Qwen2Attention`
316
+ as the weights of the module stays untouched. The only required change would be on the forward pass
317
+ where it needs to correctly call the public API of flash attention and deal with padding tokens
318
+ in case the input contains any of them. Additionally, for sliding window attention, we apply SWA only to the bottom
319
+ config.max_window_layers layers.
320
+ """
321
+
322
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
323
+ def __init__(self, *args, **kwargs):
324
+ super().__init__(*args, **kwargs)
325
+
326
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
327
+ # 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.
328
+ # 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).
329
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
330
+
331
+ def forward(
332
+ self,
333
+ hidden_states: torch.Tensor,
334
+ attention_mask: Optional[torch.Tensor] = None,
335
+ position_ids: Optional[torch.LongTensor] = None,
336
+ past_key_value: Optional[Cache] = None,
337
+ output_attentions: bool = False,
338
+ use_cache: bool = False,
339
+ **kwargs,
340
+ ):
341
+ if "padding_mask" in kwargs:
342
+ warnings.warn(
343
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
344
+ )
345
+
346
+ # overwrite attention_mask with padding_mask
347
+ attention_mask = kwargs.pop("padding_mask")
348
+ bsz, q_len, _ = hidden_states.size()
349
+
350
+ query_states = self.q_proj(hidden_states)
351
+ key_states = self.k_proj(hidden_states)
352
+ value_states = self.v_proj(hidden_states)
353
+
354
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
355
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
356
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
357
+
358
+ kv_seq_len = key_states.shape[-2]
359
+ if past_key_value is not None:
360
+ if self.layer_idx is None:
361
+ raise ValueError(
362
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
363
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
364
+ "with a layer index."
365
+ )
366
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
367
+
368
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
369
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
370
+ cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
371
+
372
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
373
+
374
+ use_sliding_windows = (
375
+ _flash_supports_window_size
376
+ and getattr(self.config, "sliding_window", None) is not None
377
+ and kv_seq_len > self.config.sliding_window
378
+ and self.config.use_sliding_window
379
+ )
380
+
381
+ if not _flash_supports_window_size:
382
+ logger.warning_once(
383
+ "The current flash attention version does not support sliding window attention, for a more memory efficient implementation"
384
+ " make sure to upgrade flash-attn library."
385
+ )
386
+
387
+ if past_key_value is not None:
388
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
389
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
390
+ if (
391
+ getattr(self.config, "sliding_window", None) is not None
392
+ and kv_seq_len > self.config.sliding_window
393
+ and cache_has_contents
394
+ ):
395
+ slicing_tokens = 1 - self.config.sliding_window
396
+
397
+ past_key = past_key_value[self.layer_idx][0]
398
+ past_value = past_key_value[self.layer_idx][1]
399
+
400
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
401
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
402
+
403
+ if past_key.shape[-2] != self.config.sliding_window - 1:
404
+ raise ValueError(
405
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
406
+ f" {past_key.shape}"
407
+ )
408
+
409
+ if attention_mask is not None:
410
+ attention_mask = attention_mask[:, slicing_tokens:]
411
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
412
+
413
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
414
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
415
+
416
+ # repeat k/v heads if n_kv_heads < n_heads
417
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
418
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
419
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
420
+
421
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
422
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
423
+ # cast them back in float16 just to be sure everything works as expected.
424
+ input_dtype = query_states.dtype
425
+ if input_dtype == torch.float32:
426
+ if torch.is_autocast_enabled():
427
+ target_dtype = torch.get_autocast_gpu_dtype()
428
+ # Handle the case where the model is quantized
429
+ elif hasattr(self.config, "_pre_quantization_dtype"):
430
+ target_dtype = self.config._pre_quantization_dtype
431
+ else:
432
+ target_dtype = self.q_proj.weight.dtype
433
+
434
+ logger.warning_once(
435
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
436
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
437
+ f" {target_dtype}."
438
+ )
439
+
440
+ query_states = query_states.to(target_dtype)
441
+ key_states = key_states.to(target_dtype)
442
+ value_states = value_states.to(target_dtype)
443
+
444
+ # Reashape to the expected shape for Flash Attention
445
+ query_states = query_states.transpose(1, 2)
446
+ key_states = key_states.transpose(1, 2)
447
+ value_states = value_states.transpose(1, 2)
448
+
449
+ attn_output = self._flash_attention_forward(
450
+ query_states,
451
+ key_states,
452
+ value_states,
453
+ attention_mask,
454
+ q_len,
455
+ dropout=dropout_rate,
456
+ use_sliding_windows=use_sliding_windows,
457
+ )
458
+
459
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
460
+ attn_output = self.o_proj(attn_output)
461
+
462
+ if not output_attentions:
463
+ attn_weights = None
464
+
465
+ return attn_output, attn_weights, past_key_value
466
+
467
+ def _flash_attention_forward(
468
+ self,
469
+ query_states,
470
+ key_states,
471
+ value_states,
472
+ attention_mask,
473
+ query_length,
474
+ dropout=0.0,
475
+ softmax_scale=None,
476
+ use_sliding_windows=False,
477
+ ):
478
+ """
479
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
480
+ first unpad the input, then computes the attention scores and pad the final attention scores.
481
+
482
+ Args:
483
+ query_states (`torch.Tensor`):
484
+ Input query states to be passed to Flash Attention API
485
+ key_states (`torch.Tensor`):
486
+ Input key states to be passed to Flash Attention API
487
+ value_states (`torch.Tensor`):
488
+ Input value states to be passed to Flash Attention API
489
+ attention_mask (`torch.Tensor`):
490
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
491
+ position of padding tokens and 1 for the position of non-padding tokens.
492
+ dropout (`float`):
493
+ Attention dropout
494
+ softmax_scale (`float`, *optional*):
495
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
496
+ use_sliding_windows (`bool`, *optional*):
497
+ Whether to activate sliding window attention.
498
+ """
499
+ if not self._flash_attn_uses_top_left_mask:
500
+ causal = self.is_causal
501
+ else:
502
+ # 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__.
503
+ causal = self.is_causal and query_length != 1
504
+
505
+ # Decide whether to use SWA or not by layer index.
506
+ if use_sliding_windows and self.layer_idx >= self.config.max_window_layers:
507
+ use_sliding_windows = False
508
+
509
+ # Contains at least one padding token in the sequence
510
+ if attention_mask is not None:
511
+ batch_size = query_states.shape[0]
512
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
513
+ query_states, key_states, value_states, attention_mask, query_length
514
+ )
515
+
516
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
517
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
518
+
519
+ if not use_sliding_windows:
520
+ attn_output_unpad = flash_attn_varlen_func(
521
+ query_states,
522
+ key_states,
523
+ value_states,
524
+ cu_seqlens_q=cu_seqlens_q,
525
+ cu_seqlens_k=cu_seqlens_k,
526
+ max_seqlen_q=max_seqlen_in_batch_q,
527
+ max_seqlen_k=max_seqlen_in_batch_k,
528
+ dropout_p=dropout,
529
+ softmax_scale=softmax_scale,
530
+ causal=causal,
531
+ )
532
+ else:
533
+ attn_output_unpad = flash_attn_varlen_func(
534
+ query_states,
535
+ key_states,
536
+ value_states,
537
+ cu_seqlens_q=cu_seqlens_q,
538
+ cu_seqlens_k=cu_seqlens_k,
539
+ max_seqlen_q=max_seqlen_in_batch_q,
540
+ max_seqlen_k=max_seqlen_in_batch_k,
541
+ dropout_p=dropout,
542
+ softmax_scale=softmax_scale,
543
+ causal=causal,
544
+ window_size=(self.config.sliding_window, self.config.sliding_window),
545
+ )
546
+
547
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
548
+ else:
549
+ if not use_sliding_windows:
550
+ attn_output = flash_attn_func(
551
+ query_states,
552
+ key_states,
553
+ value_states,
554
+ dropout,
555
+ softmax_scale=softmax_scale,
556
+ causal=causal,
557
+ )
558
+ else:
559
+ attn_output = flash_attn_func(
560
+ query_states,
561
+ key_states,
562
+ value_states,
563
+ dropout,
564
+ softmax_scale=softmax_scale,
565
+ causal=causal,
566
+ window_size=(self.config.sliding_window, self.config.sliding_window),
567
+ )
568
+
569
+ return attn_output
570
+
571
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._upad_input
572
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
573
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
574
+
575
+ # On the first iteration we need to properly re-create the padding mask
576
+ # by slicing it on the proper place
577
+ if kv_seq_len != attention_mask.shape[-1]:
578
+ attention_mask_num_tokens = attention_mask.shape[-1]
579
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
580
+
581
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
582
+
583
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
584
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
585
+
586
+ if query_length == kv_seq_len:
587
+ query_layer = index_first_axis(
588
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
589
+ )
590
+ cu_seqlens_q = cu_seqlens_k
591
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
592
+ indices_q = indices_k
593
+ elif query_length == 1:
594
+ max_seqlen_in_batch_q = 1
595
+ cu_seqlens_q = torch.arange(
596
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
597
+ ) # There is a memcpy here, that is very bad.
598
+ indices_q = cu_seqlens_q[:-1]
599
+ query_layer = query_layer.squeeze(1)
600
+ else:
601
+ # The -q_len: slice assumes left padding.
602
+ attention_mask = attention_mask[:, -query_length:]
603
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
604
+
605
+ return (
606
+ query_layer,
607
+ key_layer,
608
+ value_layer,
609
+ indices_q,
610
+ (cu_seqlens_q, cu_seqlens_k),
611
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
612
+ )
613
+
614
+
615
+ # Copied from transformers.models.mistral.modeling_mistral.MistralSdpaAttention with Mistral->Qwen2
616
+ class Qwen2SdpaAttention(Qwen2Attention):
617
+ """
618
+ Qwen2 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
619
+ `Qwen2Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
620
+ SDPA API.
621
+ """
622
+
623
+ # Adapted from Qwen2Attention.forward
624
+ def forward(
625
+ self,
626
+ hidden_states: torch.Tensor,
627
+ attention_mask: Optional[torch.Tensor] = None,
628
+ position_ids: Optional[torch.LongTensor] = None,
629
+ past_key_value: Optional[Cache] = None,
630
+ output_attentions: bool = False,
631
+ use_cache: bool = False,
632
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
633
+ if output_attentions:
634
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
635
+ logger.warning_once(
636
+ "Qwen2Model is using Qwen2SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
637
+ '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.'
638
+ )
639
+ return super().forward(
640
+ hidden_states=hidden_states,
641
+ attention_mask=attention_mask,
642
+ position_ids=position_ids,
643
+ past_key_value=past_key_value,
644
+ output_attentions=output_attentions,
645
+ use_cache=use_cache,
646
+ )
647
+
648
+ bsz, q_len, _ = hidden_states.size()
649
+
650
+ query_states = self.q_proj(hidden_states)
651
+ key_states = self.k_proj(hidden_states)
652
+ value_states = self.v_proj(hidden_states)
653
+
654
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
655
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
656
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
657
+
658
+ kv_seq_len = key_states.shape[-2]
659
+ if past_key_value is not None:
660
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
661
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
662
+
663
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
664
+
665
+ if past_key_value is not None:
666
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
667
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
668
+
669
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
670
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
671
+
672
+ if attention_mask is not None:
673
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
674
+ raise ValueError(
675
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
676
+ )
677
+
678
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
679
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
680
+ if query_states.device.type == "cuda" and attention_mask is not None:
681
+ query_states = query_states.contiguous()
682
+ key_states = key_states.contiguous()
683
+ value_states = value_states.contiguous()
684
+
685
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
686
+ query_states,
687
+ key_states,
688
+ value_states,
689
+ attn_mask=attention_mask,
690
+ dropout_p=self.attention_dropout if self.training else 0.0,
691
+ # 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.
692
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
693
+ )
694
+
695
+ attn_output = attn_output.transpose(1, 2).contiguous()
696
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
697
+
698
+ attn_output = self.o_proj(attn_output)
699
+
700
+ return attn_output, None, past_key_value
701
+
702
+
703
+ QWEN2_ATTENTION_CLASSES = {
704
+ "eager": Qwen2Attention,
705
+ "flash_attention_2": Qwen2FlashAttention2,
706
+ "sdpa": Qwen2SdpaAttention,
707
+ }
708
+
709
+
710
+ class Qwen2DecoderLayer(nn.Module):
711
+ def __init__(self, config: Qwen2Config, layer_idx: int):
712
+ super().__init__()
713
+ self.hidden_size = config.hidden_size
714
+
715
+ if config.use_sliding_window and config._attn_implementation != "flash_attention_2":
716
+ logger.warning_once(
717
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
718
+ "unexpected results may be encountered."
719
+ )
720
+ self.self_attn = QWEN2_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
721
+
722
+ self.mlp = Qwen2MLP(config)
723
+ self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
724
+ self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
725
+
726
+ def forward(
727
+ self,
728
+ hidden_states: torch.Tensor,
729
+ attention_mask: Optional[torch.Tensor] = None,
730
+ position_ids: Optional[torch.LongTensor] = None,
731
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
732
+ output_attentions: Optional[bool] = False,
733
+ use_cache: Optional[bool] = False,
734
+ **kwargs,
735
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
736
+ if "padding_mask" in kwargs:
737
+ warnings.warn(
738
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. "
739
+ "Please make sure use `attention_mask` instead.`"
740
+ )
741
+ """
742
+ Args:
743
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
744
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
745
+ `(batch, sequence_length)` where padding elements are indicated by 0.
746
+ output_attentions (`bool`, *optional*):
747
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
748
+ returned tensors for more detail.
749
+ use_cache (`bool`, *optional*):
750
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
751
+ (see `past_key_values`).
752
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
753
+ """
754
+
755
+ residual = hidden_states
756
+
757
+ hidden_states = self.input_layernorm(hidden_states)
758
+
759
+ # Self Attention
760
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
761
+ hidden_states=hidden_states,
762
+ attention_mask=attention_mask,
763
+ position_ids=position_ids,
764
+ past_key_value=past_key_value,
765
+ output_attentions=output_attentions,
766
+ use_cache=use_cache,
767
+ )
768
+ hidden_states = residual + hidden_states
769
+
770
+ # Fully Connected
771
+ residual = hidden_states
772
+ hidden_states = self.post_attention_layernorm(hidden_states)
773
+ hidden_states = self.mlp(hidden_states)
774
+ hidden_states = residual + hidden_states
775
+
776
+ outputs = (hidden_states,)
777
+
778
+ if output_attentions:
779
+ outputs += (self_attn_weights,)
780
+
781
+ if use_cache:
782
+ outputs += (present_key_value,)
783
+
784
+ return outputs
785
+
786
+
787
+ QWEN2_START_DOCSTRING = r"""
788
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
789
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
790
+ etc.)
791
+
792
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
793
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
794
+ and behavior.
795
+
796
+ Parameters:
797
+ config ([`Qwen2Config`]):
798
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
799
+ load the weights associated with the model, only the configuration. Check out the
800
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
801
+ """
802
+
803
+
804
+ @add_start_docstrings(
805
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
806
+ QWEN2_START_DOCSTRING,
807
+ )
808
+ class Qwen2PreTrainedModel(PreTrainedModel):
809
+ config_class = Qwen2Config
810
+ base_model_prefix = "model"
811
+ supports_gradient_checkpointing = True
812
+ _no_split_modules = ["Qwen2DecoderLayer"]
813
+ _skip_keys_device_placement = "past_key_values"
814
+ _supports_flash_attn_2 = True
815
+ _supports_sdpa = True
816
+ _supports_cache_class = True
817
+
818
+ def _init_weights(self, module):
819
+ std = self.config.initializer_range
820
+ if isinstance(module, nn.Linear):
821
+ module.weight.data.normal_(mean=0.0, std=std)
822
+ if module.bias is not None:
823
+ module.bias.data.zero_()
824
+ elif isinstance(module, nn.Embedding):
825
+ module.weight.data.normal_(mean=0.0, std=std)
826
+ if module.padding_idx is not None:
827
+ module.weight.data[module.padding_idx].zero_()
828
+
829
+
830
+ QWEN2_INPUTS_DOCSTRING = r"""
831
+ Args:
832
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
833
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
834
+ it.
835
+
836
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
837
+ [`PreTrainedTokenizer.__call__`] for details.
838
+
839
+ [What are input IDs?](../glossary#input-ids)
840
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
841
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
842
+
843
+ - 1 for tokens that are **not masked**,
844
+ - 0 for tokens that are **masked**.
845
+
846
+ [What are attention masks?](../glossary#attention-mask)
847
+
848
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
849
+ [`PreTrainedTokenizer.__call__`] for details.
850
+
851
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
852
+ `past_key_values`).
853
+
854
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
855
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
856
+ information on the default strategy.
857
+
858
+ - 1 indicates the head is **not masked**,
859
+ - 0 indicates the head is **masked**.
860
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
861
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
862
+ config.n_positions - 1]`.
863
+
864
+ [What are position IDs?](../glossary#position-ids)
865
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
866
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
867
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
868
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
869
+
870
+ Two formats are allowed:
871
+ - a [`~cache_utils.Cache`] instance;
872
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
873
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
874
+ cache format.
875
+
876
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
877
+ legacy cache format will be returned.
878
+
879
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
880
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
881
+ of shape `(batch_size, sequence_length)`.
882
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
883
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
884
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
885
+ model's internal embedding lookup matrix.
886
+ use_cache (`bool`, *optional*):
887
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
888
+ `past_key_values`).
889
+ output_attentions (`bool`, *optional*):
890
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
891
+ tensors for more detail.
892
+ output_hidden_states (`bool`, *optional*):
893
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
894
+ more detail.
895
+ return_dict (`bool`, *optional*):
896
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
897
+ """
898
+
899
+
900
+ @add_start_docstrings(
901
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
902
+ QWEN2_START_DOCSTRING,
903
+ )
904
+ class Qwen2Model(Qwen2PreTrainedModel):
905
+ """
906
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]
907
+
908
+ Args:
909
+ config: Qwen2Config
910
+ """
911
+
912
+ def __init__(self, config: Qwen2Config, PT_len):
913
+ super().__init__(config)
914
+ self.padding_idx = config.pad_token_id
915
+ self.vocab_size = config.vocab_size
916
+
917
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
918
+
919
+ self.prompts = []
920
+ self.prompts_token_len = PT_len
921
+ import torch.nn.init as init
922
+ if self.prompts_token_len > 0:
923
+ for i in range(config.num_hidden_layers):
924
+ self.prompts.append(init.xavier_uniform_(nn.Parameter(torch.randn(1,PT_len,config.hidden_size))))
925
+ self.prompts = nn.ParameterList(self.prompts)
926
+ self.layers = nn.ModuleList(
927
+ [Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
928
+ )
929
+ self._attn_implementation = config._attn_implementation
930
+ self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
931
+
932
+ self.gradient_checkpointing = False
933
+ # Initialize weights and apply final processing
934
+ self.post_init()
935
+
936
+ def get_input_embeddings(self):
937
+ return self.embed_tokens
938
+
939
+ def set_input_embeddings(self, value):
940
+ self.embed_tokens = value
941
+
942
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
943
+ def forward(
944
+ self,
945
+ input_ids: torch.LongTensor = None,
946
+ attention_mask: Optional[torch.Tensor] = None,
947
+ position_ids: Optional[torch.LongTensor] = None,
948
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
949
+ inputs_embeds: Optional[torch.FloatTensor] = None,
950
+ use_cache: Optional[bool] = None,
951
+ output_attentions: Optional[bool] = None,
952
+ output_hidden_states: Optional[bool] = None,
953
+ return_dict: Optional[bool] = None,
954
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
955
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
956
+ output_hidden_states = (
957
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
958
+ )
959
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
960
+
961
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
962
+
963
+ # retrieve input_ids and inputs_embeds
964
+ if input_ids is not None and inputs_embeds is not None:
965
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
966
+ elif input_ids is not None:
967
+ batch_size, seq_length = input_ids.shape
968
+ elif inputs_embeds is not None:
969
+ batch_size, seq_length, _ = inputs_embeds.shape
970
+ else:
971
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
972
+
973
+ if self.prompts_token_len > 0:
974
+ seq_length += self.prompts_token_len
975
+
976
+ if self.gradient_checkpointing and self.training:
977
+ if use_cache:
978
+ logger.warning_once(
979
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
980
+ )
981
+ use_cache = False
982
+
983
+ past_key_values_length = 0
984
+
985
+ if use_cache:
986
+ use_legacy_cache = not isinstance(past_key_values, Cache)
987
+ if use_legacy_cache:
988
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
989
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
990
+
991
+ if position_ids is None:
992
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
993
+ position_ids = torch.arange(
994
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
995
+ )
996
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
997
+ else:
998
+ position_ids = position_ids.view(-1, seq_length).long()
999
+
1000
+ if inputs_embeds is None:
1001
+ inputs_embeds = self.embed_tokens(input_ids)
1002
+
1003
+ # prompt token
1004
+ if self.prompts_token_len > 0:
1005
+ inputs_PT = self.prompts[0].repeat(inputs_embeds.size(0), 1, 1).to(inputs_embeds.device).to(inputs_embeds.dtype)
1006
+ inputs_embeds = torch.cat((inputs_PT,inputs_embeds), dim=1)
1007
+
1008
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
1009
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1010
+ if is_padding_right:
1011
+ raise ValueError(
1012
+ "You are attempting to perform batched generation with padding_side='right'"
1013
+ " this may lead to unexpected behaviour for Flash Attention version of Qwen2. Make sure to "
1014
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1015
+ )
1016
+
1017
+ if self._attn_implementation == "flash_attention_2":
1018
+ # 2d mask is passed through the layers
1019
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1020
+ elif self._attn_implementation == "sdpa" and not output_attentions:
1021
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1022
+ # the manual implementation that requires a 4D causal mask in all cases.
1023
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1024
+ attention_mask,
1025
+ (batch_size, seq_length),
1026
+ inputs_embeds,
1027
+ past_key_values_length,
1028
+ sliding_window=self.config.sliding_window,
1029
+ )
1030
+ else:
1031
+ # 4d mask is passed through the layers
1032
+ attention_mask = _prepare_4d_causal_attention_mask(
1033
+ attention_mask,
1034
+ (batch_size, seq_length),
1035
+ inputs_embeds,
1036
+ past_key_values_length,
1037
+ sliding_window=self.config.sliding_window,
1038
+ )
1039
+
1040
+ hidden_states = inputs_embeds
1041
+
1042
+ # decoder layers
1043
+ all_hidden_states = () if output_hidden_states else None
1044
+ all_self_attns = () if output_attentions else None
1045
+ next_decoder_cache = None
1046
+
1047
+ for idx, decoder_layer in enumerate(self.layers):
1048
+ if self.prompts_token_len > 0:
1049
+ # hidden_states[:, :self.prompts_token_len, :] = self.prompts[idx].repeat(inputs_embeds.size(0),1, 1).to(hidden_states.device).to(hidden_states.dtype)
1050
+ hidden_states[:, :self.prompts_token_len, :] = self.prompts[idx].repeat(inputs_embeds.size(0),1, 1)
1051
+ if output_hidden_states:
1052
+ all_hidden_states += (hidden_states,)
1053
+
1054
+ if self.gradient_checkpointing and self.training:
1055
+ layer_outputs = self._gradient_checkpointing_func(
1056
+ decoder_layer.__call__,
1057
+ hidden_states,
1058
+ attention_mask,
1059
+ position_ids,
1060
+ past_key_values,
1061
+ output_attentions,
1062
+ use_cache,
1063
+ )
1064
+ else:
1065
+ layer_outputs = decoder_layer(
1066
+ hidden_states,
1067
+ attention_mask=attention_mask,
1068
+ position_ids=position_ids,
1069
+ past_key_value=past_key_values,
1070
+ output_attentions=output_attentions,
1071
+ use_cache=use_cache,
1072
+ )
1073
+
1074
+ hidden_states = layer_outputs[0]
1075
+
1076
+ if use_cache:
1077
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1078
+
1079
+ if output_attentions:
1080
+ all_self_attns += (layer_outputs[1],)
1081
+
1082
+ hidden_states = self.norm(hidden_states)
1083
+
1084
+ # add hidden states from the last decoder layer
1085
+ if output_hidden_states:
1086
+ all_hidden_states += (hidden_states,)
1087
+
1088
+ next_cache = None
1089
+ if use_cache:
1090
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1091
+
1092
+ if not return_dict:
1093
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1094
+ return BaseModelOutputWithPast(
1095
+ last_hidden_state=hidden_states,
1096
+ past_key_values=next_cache,
1097
+ hidden_states=all_hidden_states,
1098
+ attentions=all_self_attns,
1099
+ )
1100
+
1101
+
1102
+ class Qwen2ForCausalLM(Qwen2PreTrainedModel):
1103
+ _tied_weights_keys = ["lm_head.weight"]
1104
+
1105
+ def __init__(self, config):
1106
+ super().__init__(config)
1107
+ self.model = Qwen2Model(config)
1108
+ self.vocab_size = config.vocab_size
1109
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1110
+
1111
+ # Initialize weights and apply final processing
1112
+ self.post_init()
1113
+
1114
+ def get_input_embeddings(self):
1115
+ return self.model.embed_tokens
1116
+
1117
+ def set_input_embeddings(self, value):
1118
+ self.model.embed_tokens = value
1119
+
1120
+ def get_output_embeddings(self):
1121
+ return self.lm_head
1122
+
1123
+ def set_output_embeddings(self, new_embeddings):
1124
+ self.lm_head = new_embeddings
1125
+
1126
+ def set_decoder(self, decoder):
1127
+ self.model = decoder
1128
+
1129
+ def get_decoder(self):
1130
+ return self.model
1131
+
1132
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1133
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1134
+ def forward(
1135
+ self,
1136
+ input_ids: torch.LongTensor = None,
1137
+ attention_mask: Optional[torch.Tensor] = None,
1138
+ position_ids: Optional[torch.LongTensor] = None,
1139
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1140
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1141
+ labels: Optional[torch.LongTensor] = None,
1142
+ use_cache: Optional[bool] = None,
1143
+ output_attentions: Optional[bool] = None,
1144
+ output_hidden_states: Optional[bool] = None,
1145
+ return_dict: Optional[bool] = None,
1146
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1147
+ r"""
1148
+ Args:
1149
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1150
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1151
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1152
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1153
+
1154
+ Returns:
1155
+
1156
+ Example:
1157
+
1158
+ ```python
1159
+ >>> from transformers import AutoTokenizer, Qwen2ForCausalLM
1160
+
1161
+ >>> model = Qwen2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1162
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1163
+
1164
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1165
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1166
+
1167
+ >>> # Generate
1168
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1169
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1170
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1171
+ ```"""
1172
+
1173
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1174
+ output_hidden_states = (
1175
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1176
+ )
1177
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1178
+
1179
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1180
+ outputs = self.model(
1181
+ input_ids=input_ids,
1182
+ attention_mask=attention_mask,
1183
+ position_ids=position_ids,
1184
+ past_key_values=past_key_values,
1185
+ inputs_embeds=inputs_embeds,
1186
+ use_cache=use_cache,
1187
+ output_attentions=output_attentions,
1188
+ output_hidden_states=output_hidden_states,
1189
+ return_dict=return_dict,
1190
+ )
1191
+
1192
+ hidden_states = outputs[0]
1193
+ logits = self.lm_head(hidden_states)
1194
+ logits = logits.float()
1195
+
1196
+ loss = None
1197
+ if labels is not None:
1198
+ # Shift so that tokens < n predict n
1199
+ shift_logits = logits[..., :-1, :].contiguous()
1200
+ shift_labels = labels[..., 1:].contiguous()
1201
+ # Flatten the tokens
1202
+ loss_fct = CrossEntropyLoss()
1203
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1204
+ shift_labels = shift_labels.view(-1)
1205
+ # Enable model parallelism
1206
+ shift_labels = shift_labels.to(shift_logits.device)
1207
+ loss = loss_fct(shift_logits, shift_labels)
1208
+
1209
+ if not return_dict:
1210
+ output = (logits,) + outputs[1:]
1211
+ return (loss,) + output if loss is not None else output
1212
+
1213
+ return CausalLMOutputWithPast(
1214
+ loss=loss,
1215
+ logits=logits,
1216
+ past_key_values=outputs.past_key_values,
1217
+ hidden_states=outputs.hidden_states,
1218
+ attentions=outputs.attentions,
1219
+ )
1220
+
1221
+ def prepare_inputs_for_generation(
1222
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1223
+ ):
1224
+ # Omit tokens covered by past_key_values
1225
+ if past_key_values is not None:
1226
+ if isinstance(past_key_values, Cache):
1227
+ cache_length = past_key_values.get_seq_length()
1228
+ past_length = past_key_values.seen_tokens
1229
+ max_cache_length = past_key_values.get_max_length()
1230
+ else:
1231
+ cache_length = past_length = past_key_values[0][0].shape[2]
1232
+ max_cache_length = None
1233
+
1234
+ # Keep only the unprocessed tokens:
1235
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1236
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1237
+ # input)
1238
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1239
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1240
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1241
+ # input_ids based on the past_length.
1242
+ elif past_length < input_ids.shape[1]:
1243
+ input_ids = input_ids[:, past_length:]
1244
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1245
+
1246
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1247
+ if (
1248
+ max_cache_length is not None
1249
+ and attention_mask is not None
1250
+ and cache_length + input_ids.shape[1] > max_cache_length
1251
+ ):
1252
+ attention_mask = attention_mask[:, -max_cache_length:]
1253
+
1254
+ position_ids = kwargs.get("position_ids", None)
1255
+ if attention_mask is not None and position_ids is None:
1256
+ # create position_ids on the fly for batch generation
1257
+ position_ids = attention_mask.long().cumsum(-1) - 1
1258
+ position_ids.masked_fill_(attention_mask == 0, 1)
1259
+ if past_key_values:
1260
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1261
+
1262
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1263
+ if inputs_embeds is not None and past_key_values is None:
1264
+ model_inputs = {"inputs_embeds": inputs_embeds}
1265
+ else:
1266
+ model_inputs = {"input_ids": input_ids}
1267
+
1268
+ model_inputs.update(
1269
+ {
1270
+ "position_ids": position_ids,
1271
+ "past_key_values": past_key_values,
1272
+ "use_cache": kwargs.get("use_cache"),
1273
+ "attention_mask": attention_mask,
1274
+ }
1275
+ )
1276
+ return model_inputs
1277
+
1278
+ @staticmethod
1279
+ def _reorder_cache(past_key_values, beam_idx):
1280
+ reordered_past = ()
1281
+ for layer_past in past_key_values:
1282
+ reordered_past += (
1283
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1284
+ )
1285
+ return reordered_past
1286
+
1287
+
1288
+ @add_start_docstrings(
1289
+ """
1290
+ The Qwen2 Model transformer with a sequence classification head on top (linear layer).
1291
+
1292
+ [`Qwen2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1293
+ (e.g. GPT-2) do.
1294
+
1295
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1296
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1297
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1298
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1299
+ each row of the batch).
1300
+ """,
1301
+ QWEN2_START_DOCSTRING,
1302
+ )
1303
+ class Qwen2ForSequenceClassification(Qwen2PreTrainedModel):
1304
+ def __init__(self, config):
1305
+ super().__init__(config)
1306
+ self.num_labels = config.num_labels
1307
+ self.model = Qwen2Model(config)
1308
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1309
+
1310
+ # Initialize weights and apply final processing
1311
+ self.post_init()
1312
+
1313
+ def get_input_embeddings(self):
1314
+ return self.model.embed_tokens
1315
+
1316
+ def set_input_embeddings(self, value):
1317
+ self.model.embed_tokens = value
1318
+
1319
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1320
+ def forward(
1321
+ self,
1322
+ input_ids: torch.LongTensor = None,
1323
+ attention_mask: Optional[torch.Tensor] = None,
1324
+ position_ids: Optional[torch.LongTensor] = None,
1325
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1326
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1327
+ labels: Optional[torch.LongTensor] = None,
1328
+ use_cache: Optional[bool] = None,
1329
+ output_attentions: Optional[bool] = None,
1330
+ output_hidden_states: Optional[bool] = None,
1331
+ return_dict: Optional[bool] = None,
1332
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1333
+ r"""
1334
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1335
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1336
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1337
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1338
+ """
1339
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1340
+
1341
+ transformer_outputs = self.model(
1342
+ input_ids,
1343
+ attention_mask=attention_mask,
1344
+ position_ids=position_ids,
1345
+ past_key_values=past_key_values,
1346
+ inputs_embeds=inputs_embeds,
1347
+ use_cache=use_cache,
1348
+ output_attentions=output_attentions,
1349
+ output_hidden_states=output_hidden_states,
1350
+ return_dict=return_dict,
1351
+ )
1352
+ hidden_states = transformer_outputs[0]
1353
+ logits = self.score(hidden_states)
1354
+
1355
+ if input_ids is not None:
1356
+ batch_size = input_ids.shape[0]
1357
+ else:
1358
+ batch_size = inputs_embeds.shape[0]
1359
+
1360
+ if self.config.pad_token_id is None and batch_size != 1:
1361
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1362
+ if self.config.pad_token_id is None:
1363
+ sequence_lengths = -1
1364
+ else:
1365
+ if input_ids is not None:
1366
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1367
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1368
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1369
+ sequence_lengths = sequence_lengths.to(logits.device)
1370
+ else:
1371
+ sequence_lengths = -1
1372
+
1373
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1374
+
1375
+ loss = None
1376
+ if labels is not None:
1377
+ labels = labels.to(logits.device)
1378
+ if self.config.problem_type is None:
1379
+ if self.num_labels == 1:
1380
+ self.config.problem_type = "regression"
1381
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1382
+ self.config.problem_type = "single_label_classification"
1383
+ else:
1384
+ self.config.problem_type = "multi_label_classification"
1385
+
1386
+ if self.config.problem_type == "regression":
1387
+ loss_fct = MSELoss()
1388
+ if self.num_labels == 1:
1389
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1390
+ else:
1391
+ loss = loss_fct(pooled_logits, labels)
1392
+ elif self.config.problem_type == "single_label_classification":
1393
+ loss_fct = CrossEntropyLoss()
1394
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1395
+ elif self.config.problem_type == "multi_label_classification":
1396
+ loss_fct = BCEWithLogitsLoss()
1397
+ loss = loss_fct(pooled_logits, labels)
1398
+ if not return_dict:
1399
+ output = (pooled_logits,) + transformer_outputs[1:]
1400
+ return ((loss,) + output) if loss is not None else output
1401
+
1402
+ return SequenceClassifierOutputWithPast(
1403
+ loss=loss,
1404
+ logits=pooled_logits,
1405
+ past_key_values=transformer_outputs.past_key_values,
1406
+ hidden_states=transformer_outputs.hidden_states,
1407
+ attentions=transformer_outputs.attentions,
1408
+ )
modeling_timer.py ADDED
@@ -0,0 +1,604 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Tuple, List, Union
2
+ import torch
3
+ from torch import nn
4
+ import torch.nn.functional as F
5
+ from transformers import PreTrainedModel, Cache, DynamicCache
6
+ from transformers.activations import ACT2FN
7
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
8
+ from transformers.modeling_outputs import MoeModelOutputWithPast, MoeCausalLMOutputWithPast
9
+ from .configuration_timer import TimerConfig
10
+ from .ts_generation_mixin import TSGenerationMixin
11
+
12
+
13
+ def rotate_half(x):
14
+ x1 = x[..., : x.shape[-1] // 2]
15
+ x2 = x[..., x.shape[-1] // 2:]
16
+ return torch.cat((-x2, x1), dim=-1)
17
+
18
+
19
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
20
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
21
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
22
+ q_embed = (q * cos) + (rotate_half(q) * sin)
23
+ k_embed = (k * cos) + (rotate_half(k) * sin)
24
+ return q_embed, k_embed
25
+
26
+
27
+ class TimerPatchEmbedding(nn.Module):
28
+ def __init__(self, config: TimerConfig):
29
+ super().__init__()
30
+ self.input_token_len = config.input_token_len
31
+ self.emb = nn.Linear(config.input_token_len,
32
+ config.hidden_size, bias=False)
33
+
34
+ def forward(self, hidden_state: torch.Tensor):
35
+ batch_size, input_length = hidden_state.shape
36
+ if input_length < self.input_token_len: # Padding
37
+ pad = torch.full((batch_size, self.input_token_len-input_length), fill_value=0, dtype=hidden_state.dtype, device=hidden_state.device)
38
+ hidden_state = torch.cat((pad, hidden_state), -1)
39
+ hidden_state = hidden_state.unfold(
40
+ dimension=-1, size=self.input_token_len, step=self.input_token_len)
41
+ return self.emb(hidden_state)
42
+
43
+
44
+ class TimerPointEmbedding(nn.Module):
45
+ def __init__(self, config: TimerConfig):
46
+ super().__init__()
47
+ self.emb_layer = nn.Linear(
48
+ config.input_token_len, config.hidden_size, bias=False)
49
+ self.gate_layer = nn.Linear(
50
+ config.input_token_len, config.hidden_size, bias=False)
51
+ self.act_fn = ACT2FN[config.hidden_act]
52
+
53
+ def forward(self, x):
54
+ emb = self.act_fn(self.gate_layer(x)) * self.emb_layer(x)
55
+ return emb
56
+
57
+
58
+ class TimeMoeRotaryEmbedding(torch.nn.Module):
59
+ def __init__(self, dim, max_position_embeddings=10000, base=10000, device=None):
60
+ super().__init__()
61
+ self.dim = dim
62
+ self.max_position_embeddings = max_position_embeddings
63
+ self.base = base
64
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim,
65
+ 2, dtype=torch.int64).float().to(device) / self.dim))
66
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
67
+
68
+ # Build here to make `torch.jit.trace` work.
69
+ self._set_cos_sin_cache(
70
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
71
+ )
72
+
73
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
74
+ self.max_seq_len_cached = seq_len
75
+ t = torch.arange(self.max_seq_len_cached, device=device,
76
+ dtype=torch.int64).type_as(self.inv_freq)
77
+
78
+ freqs = torch.outer(t, self.inv_freq)
79
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
80
+ emb = torch.cat((freqs, freqs), dim=-1)
81
+ self.register_buffer(
82
+ "cos_cached", emb.cos().to(dtype), persistent=False)
83
+ self.register_buffer(
84
+ "sin_cached", emb.sin().to(dtype), persistent=False)
85
+
86
+ def forward(self, x, seq_len=None):
87
+ # x: [bs, num_attention_heads, seq_len, head_size]
88
+ if seq_len > self.max_seq_len_cached:
89
+ self._set_cos_sin_cache(
90
+ seq_len=seq_len, device=x.device, dtype=x.dtype)
91
+
92
+ return (
93
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
94
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
95
+ )
96
+
97
+
98
+ class TimerAttention(nn.Module):
99
+ def __init__(self, config: TimerConfig, layer_idx: Optional[int] = None):
100
+ super().__init__()
101
+ self.layer_idx = layer_idx
102
+ self.hidden_size = config.hidden_size
103
+ self.num_heads = config.num_attention_heads
104
+ self.head_dim = self.hidden_size // self.num_heads
105
+ self.attention_dropout = config.attention_dropout
106
+ self.q_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=True)
107
+ self.k_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=True)
108
+ self.v_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=True)
109
+ self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
110
+ self.rotary_emb = TimeMoeRotaryEmbedding(
111
+ self.head_dim, max_position_embeddings=config.max_position_embeddings)
112
+
113
+ def forward(
114
+ self,
115
+ hidden_states: torch.Tensor,
116
+ attention_mask: Optional[torch.Tensor] = None,
117
+ position_ids: Optional[torch.LongTensor] = None,
118
+ past_key_value: Optional[Cache] = None,
119
+ output_attentions: bool = False,
120
+ **kwargs,
121
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
122
+ bsz, q_len, _ = hidden_states.size()
123
+
124
+ query_states = self.q_proj(hidden_states)
125
+ key_states = self.k_proj(hidden_states)
126
+ value_states = self.v_proj(hidden_states)
127
+
128
+ query_states = query_states.view(
129
+ bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
130
+ key_states = key_states.view(
131
+ bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
132
+ value_states = value_states.view(
133
+ bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
134
+
135
+ kv_seq_len = key_states.shape[-2]
136
+ if past_key_value is not None:
137
+ kv_seq_len += past_key_value.get_usable_length(
138
+ kv_seq_len, self.layer_idx)
139
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
140
+ query_states, key_states = apply_rotary_pos_emb(
141
+ query_states, key_states, cos, sin, position_ids)
142
+
143
+ if past_key_value is not None:
144
+ key_states, value_states = past_key_value.update(
145
+ key_states, value_states, self.layer_idx)
146
+
147
+ attn_output = F.scaled_dot_product_attention(
148
+ query_states, key_states, value_states, attention_mask, dropout_p=self.attention_dropout)
149
+
150
+ attn_output = attn_output.transpose(1, 2).contiguous()
151
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
152
+ attn_output = self.o_proj(attn_output)
153
+
154
+ if not output_attentions:
155
+ attn_weights = None
156
+
157
+ return attn_output, attn_weights, past_key_value
158
+
159
+
160
+ class TimerMLP(nn.Module):
161
+ def __init__(self, hidden_size: int, intermediate_size: int, hidden_act: str):
162
+ super().__init__()
163
+ self.hidden_size = hidden_size
164
+ self.intermediate_size = intermediate_size
165
+ self.gate_proj = nn.Linear(
166
+ self.hidden_size, self.intermediate_size, bias=False)
167
+ self.up_proj = nn.Linear(
168
+ self.hidden_size, self.intermediate_size, bias=False)
169
+ self.down_proj = nn.Linear(
170
+ self.intermediate_size, self.hidden_size, bias=False)
171
+ self.act_fn = ACT2FN[hidden_act]
172
+
173
+ def forward(self, hidden_state):
174
+ return self.down_proj(self.act_fn(self.gate_proj(hidden_state)) * self.up_proj(hidden_state))
175
+
176
+
177
+ class TimerDecoderLayer(nn.Module):
178
+ def __init__(self, config: TimerConfig, layer_idx: int):
179
+ super().__init__()
180
+ self.self_attn = TimerAttention(config, layer_idx)
181
+
182
+ self.ffn_layer = TimerMLP(
183
+ hidden_size=config.hidden_size,
184
+ intermediate_size=config.intermediate_size,
185
+ hidden_act=config.hidden_act,
186
+ )
187
+ self.norm1 = torch.nn.LayerNorm(config.hidden_size)
188
+ self.norm2 = torch.nn.LayerNorm(config.hidden_size)
189
+
190
+ def forward(
191
+ self,
192
+ hidden_states: torch.Tensor,
193
+ attention_mask: Optional[torch.Tensor] = None,
194
+ position_ids: Optional[torch.LongTensor] = None,
195
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
196
+ output_attentions: Optional[bool] = False,
197
+ use_cache: Optional[bool] = False,
198
+ **kwargs,
199
+ ) -> Tuple[torch.FloatTensor, torch.FloatTensor, Optional[torch.FloatTensor], Optional[torch.FloatTensor]]:
200
+ residual = hidden_states
201
+
202
+ # Self Attention
203
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
204
+ hidden_states=hidden_states,
205
+ attention_mask=attention_mask,
206
+ position_ids=position_ids,
207
+ past_key_value=past_key_value,
208
+ output_attentions=output_attentions,
209
+ use_cache=use_cache,
210
+ )
211
+ hidden_states = residual + hidden_states
212
+ hidden_states = self.norm1(hidden_states)
213
+
214
+ # Fully Connected
215
+ residual = hidden_states
216
+ hidden_states = self.ffn_layer(hidden_states)
217
+ hidden_states = residual + hidden_states
218
+ hidden_states = self.norm2(hidden_states)
219
+
220
+ if not output_attentions:
221
+ self_attn_weights = None
222
+
223
+ if not use_cache:
224
+ present_key_value = None
225
+ return hidden_states, self_attn_weights, present_key_value
226
+
227
+
228
+ class TimerPreTrainedModel(PreTrainedModel):
229
+ config_class = TimerConfig
230
+ base_model_prefix = "model"
231
+ supports_gradient_checkpointing = True
232
+ _no_split_modules = ["TimeMoeDecoderLayer"]
233
+ _skip_keys_device_placement = "past_key_values"
234
+ _supports_flash_attn_2 = True
235
+ _supports_sdpa = False
236
+ _supports_cache_class = True
237
+
238
+ def _init_weights(self, module):
239
+ std = self.config.initializer_range
240
+ if isinstance(module, torch.nn.Linear):
241
+ module.weight.data.normal_(mean=0.0, std=std)
242
+ if module.bias is not None:
243
+ module.bias.data.zero_()
244
+ elif isinstance(module, torch.nn.Embedding):
245
+ module.weight.data.normal_(mean=0.0, std=std)
246
+ if module.padding_idx is not None:
247
+ module.weight.data[module.padding_idx].zero_()
248
+
249
+
250
+ class TimerModel(TimerPreTrainedModel):
251
+ def __init__(self, config: TimerConfig, PT_len: int):
252
+ super().__init__(config)
253
+ self.embed_layer = TimerPatchEmbedding(config)
254
+ self.prompts = []
255
+ self.prompts_token_len = PT_len
256
+ if self.prompts_token_len > 0:
257
+ for i in range(self.config.num_hidden_layers):
258
+ self.prompts.append(nn.init.xavier_uniform_(nn.Parameter(torch.randn(1, PT_len, config.hidden_size))))
259
+ self.prompts = nn.ParameterList(self.prompts)
260
+ self.layers = nn.ModuleList(
261
+ [TimerDecoderLayer(config, layer_idx)
262
+ for layer_idx in range(config.num_hidden_layers)]
263
+ )
264
+ self.norm = torch.nn.LayerNorm(config.hidden_size)
265
+ self.gradient_checkpointing = False
266
+
267
+ def forward(
268
+ self,
269
+ input_ids: torch.FloatTensor = None,
270
+ vision_embedding: torch.FloatTensor = None,
271
+ text_embedding: torch.FloatTensor = None,
272
+ attention_mask: Optional[torch.Tensor] = None,
273
+ position_ids: Optional[torch.LongTensor] = None,
274
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
275
+ inputs_embeds: Optional[torch.FloatTensor] = None,
276
+ use_cache: Optional[bool] = None,
277
+ output_attentions: Optional[bool] = None,
278
+ output_hidden_states: Optional[bool] = None,
279
+ return_dict: Optional[bool] = None,
280
+ ) -> Union[Tuple, MoeModelOutputWithPast]:
281
+ # input_ids is the input of time series, its shape is [batch_size, seq_len]
282
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
283
+ output_hidden_states = (
284
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
285
+ )
286
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
287
+
288
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
289
+
290
+ # retrieve input_ids and inputs_embeds
291
+ if input_ids is not None and inputs_embeds is not None:
292
+ raise ValueError(
293
+ "You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
294
+ elif input_ids is not None:
295
+ batch_size, seq_length = input_ids.shape
296
+ elif inputs_embeds is not None:
297
+ batch_size, seq_length, _ = inputs_embeds.shape
298
+ else:
299
+ raise ValueError(
300
+ "You have to specify either decoder_input_ids or decoder_inputs_embeds")
301
+
302
+ if inputs_embeds is None:
303
+ inputs_embeds = self.embed_layer(input_ids)
304
+ seq_length = inputs_embeds.shape[1]
305
+
306
+ if text_embedding is not None:
307
+ inputs_embeds = torch.cat((text_embedding.unsqueeze(dim=1), inputs_embeds), dim=1)
308
+ seq_length = inputs_embeds.shape[1]
309
+
310
+ if vision_embedding is not None:
311
+ inputs_embeds = torch.cat((vision_embedding.unsqueeze(dim=1), inputs_embeds), dim=1)
312
+ seq_length = inputs_embeds.shape[1]
313
+
314
+ if self.prompts_token_len > 0:
315
+ inputs_PT = self.prompts[0].repeat(inputs_embeds.size(0), 1, 1).to(inputs_embeds.device).to(inputs_embeds.dtype)
316
+ inputs_embeds = torch.cat((inputs_PT,inputs_embeds), dim=1)
317
+ seq_length = inputs_embeds.shape[1]
318
+
319
+ if self.gradient_checkpointing and self.training:
320
+ if use_cache:
321
+ use_cache = False
322
+
323
+ past_key_values_length = 0
324
+
325
+ if use_cache:
326
+ use_legacy_cache = not isinstance(past_key_values, Cache)
327
+ if use_legacy_cache:
328
+ past_key_values = DynamicCache.from_legacy_cache(
329
+ past_key_values)
330
+ past_key_values_length = past_key_values.get_usable_length(
331
+ seq_length)
332
+
333
+ if position_ids is None:
334
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
335
+ position_ids = torch.arange(
336
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
337
+ )
338
+ # position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
339
+ position_ids = position_ids.view(-1, seq_length)
340
+ else:
341
+ position_ids = position_ids.view(-1, seq_length).long()
342
+
343
+ # 4d mask is passed through the layers
344
+ attention_mask = _prepare_4d_causal_attention_mask(
345
+ attention_mask,
346
+ (batch_size, seq_length),
347
+ inputs_embeds,
348
+ past_key_values_length,
349
+ sliding_window=None,
350
+ )
351
+
352
+ hidden_states = inputs_embeds
353
+
354
+ # decoder layers
355
+ all_hidden_states = () if output_hidden_states else None
356
+ all_self_attns = () if output_attentions else None
357
+ next_decoder_cache = None
358
+
359
+ for idx, decoder_layer in enumerate(self.layers):
360
+ if self.prompts_token_len > 0:
361
+ hidden_states[:, :self.prompts_token_len, :] = self.prompts[idx].repeat(inputs_embeds.size(0),1, 1).to(hidden_states.device).to(hidden_states.dtype)
362
+
363
+ if output_hidden_states:
364
+ all_hidden_states += (hidden_states,)
365
+
366
+ if self.gradient_checkpointing and self.training:
367
+ layer_outputs = self._gradient_checkpointing_func(
368
+ decoder_layer.__call__,
369
+ hidden_states,
370
+ attention_mask,
371
+ position_ids,
372
+ past_key_values,
373
+ output_attentions,
374
+ use_cache,
375
+ )
376
+ else:
377
+ layer_outputs = decoder_layer(
378
+ hidden_states,
379
+ attention_mask=attention_mask,
380
+ position_ids=position_ids,
381
+ past_key_value=past_key_values,
382
+ output_attentions=output_attentions,
383
+ use_cache=use_cache,
384
+ )
385
+
386
+ hidden_states = layer_outputs[0]
387
+
388
+ if output_attentions:
389
+ all_self_attns += (layer_outputs[1],)
390
+
391
+ if use_cache:
392
+ next_decoder_cache = layer_outputs[2]
393
+
394
+ hidden_states = self.norm(hidden_states)
395
+ # add hidden states from the last decoder layer
396
+ if output_hidden_states:
397
+ all_hidden_states += (hidden_states,)
398
+
399
+ next_cache = None
400
+ if use_cache:
401
+ next_cache = next_decoder_cache.to_legacy_cache(
402
+ ) if use_legacy_cache else next_decoder_cache
403
+
404
+ if not return_dict:
405
+ return tuple(
406
+ v
407
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
408
+ if v is not None
409
+ )
410
+ return MoeModelOutputWithPast(
411
+ last_hidden_state=hidden_states,
412
+ past_key_values=next_cache,
413
+ hidden_states=all_hidden_states,
414
+ attentions=all_self_attns,
415
+ )
416
+
417
+
418
+ class TimerForPrediction(TimerPreTrainedModel, TSGenerationMixin):
419
+ def __init__(self, config: TimerConfig, PT_len: int):
420
+ super().__init__(config)
421
+ self.config = config
422
+ self.model = TimerModel(self.config, PT_len)
423
+ lm_head_list = []
424
+ self.output_token_len_map = {}
425
+ for i, output_token_len in enumerate(self.config.output_token_lens):
426
+ lm_head_list.append(
427
+ nn.Linear(self.config.hidden_size, output_token_len, bias=False))
428
+ self.output_token_len_map[output_token_len] = i
429
+ self.lm_heads = nn.ModuleList(lm_head_list)
430
+ self.loss_function = torch.nn.MSELoss(reduction='none')
431
+ self.post_init()
432
+
433
+ def set_decoder(self, decoder):
434
+ self.model = decoder
435
+
436
+ def get_decoder(self):
437
+ return self.model
438
+
439
+ def forward(
440
+ self,
441
+ input_ids: torch.FloatTensor = None,
442
+ vision_embedding: torch.FloatTensor = None,
443
+ text_embedding: torch.FloatTensor = None,
444
+ attention_mask: Optional[torch.Tensor] = None,
445
+ position_ids: Optional[torch.LongTensor] = None,
446
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
447
+ inputs_embeds: Optional[torch.FloatTensor] = None,
448
+ labels: Optional[torch.FloatTensor] = None,
449
+ loss_masks: Optional[torch.FloatTensor] = None,
450
+ use_cache: Optional[bool] = None,
451
+ output_attentions: Optional[bool] = None,
452
+ output_hidden_states: Optional[bool] = None,
453
+ return_dict: Optional[bool] = None,
454
+ max_output_length: Optional[int] = None,
455
+ revin: Optional[bool] = False,
456
+ ) -> Union[Tuple, MoeCausalLMOutputWithPast]:
457
+
458
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
459
+ output_hidden_states = (
460
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
461
+ )
462
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
463
+
464
+ if revin:
465
+ mean, std = input_ids.mean(dim=-1, keepdim=True), input_ids.std(dim=-1, keepdim=True)
466
+ input_ids = (input_ids - mean) / std
467
+ outputs = self.model(
468
+ input_ids=input_ids,
469
+ vision_embedding=vision_embedding,
470
+ text_embedding=text_embedding,
471
+ attention_mask=attention_mask,
472
+ position_ids=position_ids,
473
+ past_key_values=past_key_values,
474
+ inputs_embeds=inputs_embeds,
475
+ use_cache=use_cache,
476
+ output_attentions=output_attentions,
477
+ output_hidden_states=output_hidden_states,
478
+ return_dict=return_dict,
479
+ )
480
+
481
+ hidden_states = outputs[0] if not return_dict else outputs.last_hidden_state
482
+ predictions = None
483
+
484
+ loss = None
485
+ if labels is not None:
486
+ ar_loss = 0.0
487
+ for lm_head, output_token_len in zip(self.lm_heads, self.config.output_token_lens):
488
+ one_predictions = lm_head(hidden_states)
489
+ one_loss = self.calc_ar_loss(
490
+ one_predictions, labels, loss_masks, output_token_len)
491
+ ar_loss += one_loss
492
+ if predictions is None:
493
+ predictions = one_predictions
494
+ loss = ar_loss / len(self.config.output_token_lens)
495
+ else:
496
+ if max_output_length is None:
497
+ output_token_len = self.config.output_token_lens[0]
498
+ max_output_length = output_token_len
499
+ else:
500
+ output_token_len = self.config.output_token_lens[0]
501
+ for h in self.config.output_token_lens[1:]:
502
+ if h > max_output_length:
503
+ break
504
+ else:
505
+ output_token_len = h
506
+ lm_head = self.lm_heads[self.output_token_len_map[output_token_len]]
507
+ predictions = lm_head(hidden_states)[:, -1, :]
508
+ if output_token_len > max_output_length:
509
+ predictions = predictions[:, :max_output_length]
510
+ if revin:
511
+ predictions = predictions * std + mean
512
+ if not return_dict:
513
+ output = (predictions,) + outputs[1:]
514
+ return (loss) + output if loss is not None else output
515
+
516
+ return MoeCausalLMOutputWithPast(
517
+ loss=loss,
518
+ logits=predictions,
519
+ past_key_values=outputs.past_key_values,
520
+ hidden_states=outputs.hidden_states,
521
+ attentions=outputs.attentions,
522
+ )
523
+
524
+ def calc_ar_loss(self, predictions, labels, loss_masks, output_token_len):
525
+ seq_len = predictions.shape[1] * self.config.input_token_len
526
+ labels = labels[:, :seq_len -
527
+ self.config.input_token_len + output_token_len]
528
+ shift_labels = labels.unfold(
529
+ dimension=-1, size=output_token_len, step=self.config.input_token_len)
530
+
531
+ # Calculate loss with mask
532
+ losses = self.loss_function(predictions, shift_labels).mean(dim=-1)
533
+ if loss_masks is not None:
534
+ losses = losses * loss_masks
535
+ loss = losses.sum() / loss_masks.sum()
536
+ else:
537
+ loss = torch.mean(losses)
538
+
539
+ return loss
540
+
541
+ def prepare_inputs_for_generation(
542
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, revin=True, **kwargs
543
+ ):
544
+ # Omit tokens covered by past_key_values
545
+ if past_key_values is not None:
546
+ if isinstance(past_key_values, Cache):
547
+ cache_length = past_key_values.get_seq_length()
548
+ if isinstance(past_key_values, DynamicCache):
549
+ past_length = past_key_values.seen_tokens
550
+ else:
551
+ past_length = cache_length
552
+
553
+ max_cache_length = past_key_values.get_max_length()
554
+ else:
555
+ cache_length = past_length = past_key_values[0][0].shape[2]
556
+ max_cache_length = None
557
+
558
+ # Keep only the unprocessed tokens:
559
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
560
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
561
+ # input)
562
+ if attention_mask is not None and attention_mask.shape[1] > (input_ids.shape[1] // self.config.input_token_len):
563
+ input_ids = input_ids[:, -
564
+ (attention_mask.shape[1] - past_length):]
565
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
566
+ # input_ids based on the past_length.
567
+ elif past_length < (input_ids.shape[1] // self.config.input_token_len):
568
+ input_ids = input_ids[:, past_length *
569
+ self.config.input_token_len:]
570
+ # 3 - Otherwise (past_length >= (input_ids.shape[1] // self.config.input_token_len)), let's assume input_ids only has unprocessed tokens.
571
+
572
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
573
+ if (
574
+ max_cache_length is not None
575
+ and attention_mask is not None
576
+ and cache_length + (input_ids.shape[1] // self.config.input_token_len) > max_cache_length
577
+ ):
578
+ attention_mask = attention_mask[:, -max_cache_length:]
579
+
580
+ position_ids = kwargs.get("position_ids", None)
581
+ if attention_mask is not None and position_ids is None:
582
+ # create position_ids on the fly for batch generation
583
+ position_ids = attention_mask.long().cumsum(-1) - 1
584
+ position_ids.masked_fill_(attention_mask == 0, 1)
585
+ if past_key_values:
586
+ position_ids = position_ids[:, -
587
+ (input_ids.shape[1] // self.config.input_token_len):]
588
+
589
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
590
+ if inputs_embeds is not None and past_key_values is None:
591
+ model_inputs = {"inputs_embeds": inputs_embeds}
592
+ else:
593
+ model_inputs = {"input_ids": input_ids}
594
+
595
+ model_inputs.update(
596
+ {
597
+ "position_ids": position_ids,
598
+ "past_key_values": past_key_values,
599
+ "use_cache": kwargs.get("use_cache"),
600
+ "attention_mask": attention_mask,
601
+ "revin": revin
602
+ }
603
+ )
604
+ return model_inputs
readme.md ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MulTiCast
2
+ **Mul**timodal **Ti**me-series fore**Cast**ing
3
+
4
+ Requires ```python 3.10.16```
5
+
6
+ Check ```requirements.txt```
7
+
8
+ ```python
9
+ from transformers import AutoModel
10
+ model = AutoModel.from_pretrained("adnlp/MulTiCast", trust_remote_code=True)
11
+
12
+ import torch
13
+ input_ids = torch.rand((1, 56))
14
+ images = torch.rand((224,224,3))
15
+ texts = "Hello World!"
16
+
17
+ out = model.predict(input_ids=input_ids, images=images, texts=texts)
18
+ pred = out["logits"]
19
+ ```
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ accelerate==1.6.0
2
+ torch==2.6.0
3
+ numpy==2.2.4
4
+ transformers==4.40.1
5
+ matplotlib==3.10.1
6
+ safetensors==0.5.3
7
+ pillow==11.1.0
ts_generation_mixin.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ from typing import Any, Dict, List, Optional, Union, Callable
3
+ import torch
4
+ from transformers import GenerationMixin, LogitsProcessorList, StoppingCriteriaList
5
+ from transformers.generation import validate_stopping_criteria, EosTokenCriteria
6
+ from transformers.generation.utils import GenerateNonBeamOutput, GenerateEncoderDecoderOutput, GenerateDecoderOnlyOutput, GenerationConfig, GenerateOutput
7
+ from transformers.utils import ModelOutput
8
+
9
+
10
+ class TSGenerationMixin(GenerationMixin):
11
+
12
+ @torch.no_grad()
13
+ def generate(
14
+ self,
15
+ inputs: Optional[torch.Tensor] = None,
16
+ generation_config: Optional[GenerationConfig] = None,
17
+ logits_processor: Optional[LogitsProcessorList] = None,
18
+ stopping_criteria: Optional[StoppingCriteriaList] = None,
19
+ prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,
20
+ synced_gpus: Optional[bool] = None,
21
+ assistant_model: Optional["PreTrainedModel"] = None,
22
+ streamer: Optional["BaseStreamer"] = None,
23
+ negative_prompt_ids: Optional[torch.Tensor] = None,
24
+ negative_prompt_attention_mask: Optional[torch.Tensor] = None,
25
+ **kwargs,
26
+ ) -> Union[GenerateOutput, torch.LongTensor]:
27
+ if len(inputs.shape) == 2:
28
+ batch_size, cur_len = inputs.shape
29
+ if cur_len < self.config.input_token_len:
30
+ raise ValueError(
31
+ f"Input length must be at least {self.config.input_token_len}")
32
+ elif cur_len % self.config.input_token_len != 0:
33
+ new_len = (cur_len // self.config.input_token_len) * \
34
+ self.config.input_token_len
35
+ inputs = inputs[:, -new_len:]
36
+ else:
37
+ raise ValueError('Input shape must be: [batch_size, seq_len]')
38
+ return super().generate(inputs=inputs, generation_config=generation_config, logits_processor=logits_processor, stopping_criteria=stopping_criteria, prefix_allowed_tokens_fn=prefix_allowed_tokens_fn, synced_gpus=synced_gpus, assistant_model=assistant_model, streamer=streamer, negative_prompt_ids=negative_prompt_ids, negative_prompt_attention_mask=negative_prompt_attention_mask, **kwargs)
39
+
40
+
41
+ def _greedy_search(
42
+ self,
43
+ input_ids: torch.Tensor,
44
+ logits_processor: Optional[LogitsProcessorList] = None,
45
+ stopping_criteria: Optional[StoppingCriteriaList] = None,
46
+ max_length: Optional[int] = None,
47
+ pad_token_id: Optional[int] = None,
48
+ eos_token_id: Optional[Union[int, List[int]]] = None,
49
+ output_attentions: Optional[bool] = None,
50
+ output_hidden_states: Optional[bool] = None,
51
+ output_scores: Optional[bool] = None,
52
+ output_logits: Optional[bool] = None,
53
+ return_dict_in_generate: Optional[bool] = None,
54
+ synced_gpus: bool = False,
55
+ streamer: Optional["BaseStreamer"] = None,
56
+ **model_kwargs,
57
+ ) -> Union[GenerateNonBeamOutput, torch.Tensor]:
58
+ input_ids = input_ids.to(self.device)
59
+ batch_size, cur_len = input_ids.shape
60
+ # init values
61
+ logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
62
+ stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()
63
+ if max_length is not None:
64
+ warnings.warn(
65
+ "`max_length` is deprecated in this function, use"
66
+ " `stopping_criteria=StoppingCriteriaList([MaxLengthCriteria(max_length=max_length)])` instead.",
67
+ UserWarning,
68
+ )
69
+ stopping_criteria = validate_stopping_criteria(
70
+ stopping_criteria, max_length)
71
+ pad_token_id = pad_token_id if pad_token_id is not None else self.generation_config.pad_token_id
72
+ if eos_token_id is not None:
73
+ stopping_criteria.append(
74
+ EosTokenCriteria(eos_token_id=eos_token_id))
75
+ else:
76
+ # remove when the method is totally private
77
+ # need to get `eos_token_id` and add stopping criteria, so that generation does not go forever
78
+ eos_token_id = [
79
+ criteria.eos_token_id.tolist() for criteria in stopping_criteria if hasattr(criteria, "eos_token_id")
80
+ ]
81
+ eos_token_id = eos_token_id[0] if eos_token_id else None
82
+ if eos_token_id is None and self.generation_config.eos_token_id is not None:
83
+ eos_token_id = self.generation_config.eos_token_id
84
+ stopping_criteria.append(
85
+ EosTokenCriteria(eos_token_id=eos_token_id))
86
+
87
+ if isinstance(eos_token_id, int):
88
+ eos_token_id = [eos_token_id]
89
+ output_scores = output_scores if output_scores is not None else self.generation_config.output_scores
90
+ output_attentions = (
91
+ output_attentions if output_attentions is not None else self.generation_config.output_attentions
92
+ )
93
+ output_hidden_states = (
94
+ output_hidden_states if output_hidden_states is not None else self.generation_config.output_hidden_states
95
+ )
96
+ return_dict_in_generate = (
97
+ return_dict_in_generate
98
+ if return_dict_in_generate is not None
99
+ else self.generation_config.return_dict_in_generate
100
+ )
101
+
102
+ # init attention / hidden states / scores tuples
103
+ raw_logits = () if (return_dict_in_generate and output_logits) else None
104
+ scores = () if (return_dict_in_generate and output_scores) else None
105
+ decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
106
+ cross_attentions = () if (return_dict_in_generate and output_attentions) else None
107
+ decoder_hidden_states = () if (
108
+ return_dict_in_generate and output_hidden_states) else None
109
+
110
+ # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
111
+ if return_dict_in_generate and self.config.is_encoder_decoder:
112
+ encoder_attentions = model_kwargs["encoder_outputs"].get(
113
+ "attentions") if output_attentions else None
114
+ encoder_hidden_states = (
115
+ model_kwargs["encoder_outputs"].get(
116
+ "hidden_states") if output_hidden_states else None
117
+ )
118
+
119
+ # keep track of which sequences are already finished
120
+ if "inputs_embeds" in model_kwargs:
121
+ cur_len = model_kwargs["inputs_embeds"].shape[1]
122
+ this_peer_finished = False
123
+ unfinished_sequences = torch.ones(
124
+ batch_size, dtype=torch.long, device=input_ids.device)
125
+ model_kwargs["cache_position"] = torch.arange(
126
+ cur_len, device=input_ids.device)
127
+ true_seq_len = cur_len // self.config.input_token_len
128
+ model_kwargs["attention_mask"] = model_kwargs["attention_mask"][:, -true_seq_len:]
129
+ max_length = stopping_criteria.max_length
130
+ while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
131
+ # prepare model inputs
132
+ model_inputs = self.prepare_inputs_for_generation(
133
+ input_ids, **model_kwargs)
134
+
135
+ input_length = input_ids.shape[1]
136
+
137
+ # forward pass to get next token
138
+ outputs = self(
139
+ **model_inputs,
140
+ return_dict=True,
141
+ output_attentions=output_attentions,
142
+ output_hidden_states=output_hidden_states,
143
+ max_output_length=max_length - input_length,
144
+ )
145
+
146
+ if synced_gpus and this_peer_finished:
147
+ continue # don't waste resources running the code we don't need
148
+
149
+ next_token_logits = outputs.logits
150
+
151
+ # pre-process distribution
152
+ next_tokens_scores = logits_processor(input_ids, next_token_logits)
153
+
154
+ # Store scores, attentions and hidden_states when required
155
+ if return_dict_in_generate:
156
+ if output_scores:
157
+ scores += (next_tokens_scores,)
158
+ if output_logits:
159
+ raw_logits += (next_token_logits,)
160
+ if output_attentions:
161
+ decoder_attentions += (
162
+ (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (
163
+ outputs.attentions,)
164
+ )
165
+ if self.config.is_encoder_decoder:
166
+ cross_attentions += (outputs.cross_attentions,)
167
+
168
+ if output_hidden_states:
169
+ decoder_hidden_states += (
170
+ (outputs.decoder_hidden_states,)
171
+ if self.config.is_encoder_decoder
172
+ else (outputs.hidden_states,)
173
+ )
174
+
175
+ # argmax
176
+ # next_tokens = torch.argmax(next_tokens_scores, dim=-1)
177
+ next_tokens = next_tokens_scores
178
+
179
+ # finished sentences should have their next token be a padding token
180
+ if eos_token_id is not None:
181
+ if pad_token_id is None:
182
+ raise ValueError(
183
+ "If `eos_token_id` is defined, make sure that `pad_token_id` is defined.")
184
+ next_tokens = next_tokens * unfinished_sequences + \
185
+ pad_token_id * (1 - unfinished_sequences)
186
+
187
+ # update generated ids, model inputs, and length for next step
188
+ horizon_length = next_tokens.shape[1] // self.config.input_token_len
189
+
190
+ input_ids = torch.cat([input_ids, next_tokens], dim=-1)
191
+ if streamer is not None:
192
+ streamer.put(next_tokens.cpu())
193
+ model_kwargs = self._update_model_kwargs_for_generation(
194
+ outputs,
195
+ model_kwargs,
196
+ horizon_length=horizon_length,
197
+ is_encoder_decoder=self.config.is_encoder_decoder,
198
+ )
199
+ unfinished_sequences = unfinished_sequences & ~stopping_criteria(
200
+ input_ids, scores)
201
+ this_peer_finished = unfinished_sequences.max() == 0
202
+
203
+ if input_ids.shape[1] > max_length:
204
+ input_ids = input_ids[:, :max_length]
205
+
206
+ if streamer is not None:
207
+ streamer.end()
208
+
209
+ if return_dict_in_generate:
210
+ if self.config.is_encoder_decoder:
211
+ return GenerateEncoderDecoderOutput(
212
+ sequences=input_ids,
213
+ scores=scores,
214
+ logits=raw_logits,
215
+ encoder_attentions=encoder_attentions,
216
+ encoder_hidden_states=encoder_hidden_states,
217
+ decoder_attentions=decoder_attentions,
218
+ cross_attentions=cross_attentions,
219
+ decoder_hidden_states=decoder_hidden_states,
220
+ past_key_values=model_kwargs.get("past_key_values"),
221
+ )
222
+ else:
223
+ return GenerateDecoderOnlyOutput(
224
+ sequences=input_ids,
225
+ scores=scores,
226
+ logits=raw_logits,
227
+ attentions=decoder_attentions,
228
+ hidden_states=decoder_hidden_states,
229
+ past_key_values=model_kwargs.get("past_key_values"),
230
+ )
231
+ else:
232
+ return input_ids[:, -(max_length - cur_len):]
233
+
234
+ def _update_model_kwargs_for_generation(
235
+ self,
236
+ outputs: ModelOutput,
237
+ model_kwargs: Dict[str, Any],
238
+ horizon_length: int = 1,
239
+ is_encoder_decoder: bool = False,
240
+ standardize_cache_format: bool = False,
241
+ ) -> Dict[str, Any]:
242
+ # update past_key_values
243
+ model_kwargs["past_key_values"] = self._extract_past_from_model_output(
244
+ outputs, standardize_cache_format=standardize_cache_format
245
+ )
246
+ if getattr(outputs, "state", None) is not None:
247
+ model_kwargs["state"] = outputs.state
248
+
249
+ # update token_type_ids with last value
250
+ if "token_type_ids" in model_kwargs:
251
+ token_type_ids = model_kwargs["token_type_ids"]
252
+ model_kwargs["token_type_ids"] = torch.cat(
253
+ [token_type_ids, token_type_ids[:, -1].unsqueeze(-1)], dim=-1)
254
+
255
+ if not is_encoder_decoder:
256
+ # update attention mask
257
+ if "attention_mask" in model_kwargs:
258
+ attention_mask = model_kwargs["attention_mask"]
259
+ model_kwargs["attention_mask"] = torch.cat(
260
+ [attention_mask, attention_mask.new_ones((attention_mask.shape[0], horizon_length))], dim=-1
261
+ )
262
+ else:
263
+ # update decoder attention mask
264
+ if "decoder_attention_mask" in model_kwargs:
265
+ decoder_attention_mask = model_kwargs["decoder_attention_mask"]
266
+ model_kwargs["decoder_attention_mask"] = torch.cat(
267
+ [decoder_attention_mask, decoder_attention_mask.new_ones(
268
+ (decoder_attention_mask.shape[0], horizon_length))],
269
+ dim=-1,
270
+ )
271
+
272
+ if "cache_position" in model_kwargs and model_kwargs["cache_position"] is not None:
273
+ model_kwargs["cache_position"] = model_kwargs["cache_position"][-1:] + horizon_length
274
+
275
+ return model_kwargs