adnlp commited on
Commit
01e3bfb
·
verified ·
1 Parent(s): 913e703

Upload 22 files

Browse files
MultiModalTimer.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from PIL import Image
3
+ import torch
4
+ from torch import nn
5
+ from torch.utils.data import Dataset
6
+ from transformers import PreTrainedModel, PretrainedConfig
7
+
8
+ # CLIP
9
+ from models.modeling_clipPT import CLIPVisionTransformer
10
+ from transformers import CLIPImageProcessor
11
+
12
+ # Qwen
13
+ from transformers import AutoTokenizer
14
+ from models.modeling_qwen2 import Qwen2Model
15
+
16
+ # Timer
17
+ from models.modeling_timer import TimerForPrediction
18
+
19
+ class MultiModalTimerConfig(PretrainedConfig):
20
+ def __init__(
21
+ self,
22
+ forecasting_length = None,
23
+ vision_model_name = None,
24
+ text_model_name = None,
25
+ vision_model_prompt_len = None,
26
+ text_model_prompt_len = None,
27
+ timer_prompt_len = None,
28
+ **kwargs
29
+ ):
30
+ super().__init__(**kwargs)
31
+ self.forecasting_length = forecasting_length
32
+ self.vision_model_name = vision_model_name
33
+ self.text_model_name = text_model_name
34
+
35
+ self.vision_model_prompt_len = vision_model_prompt_len if vision_model_prompt_len is not None else 10
36
+ self.text_model_prompt_len = text_model_prompt_len if text_model_prompt_len is not None else 4
37
+ self.timer_prompt_len = timer_prompt_len if timer_prompt_len is not None else 4
38
+
39
+ class MultiModalTimerModel(PreTrainedModel):
40
+
41
+ config_class = MultiModalTimerConfig
42
+
43
+ def __init__(self, config):
44
+ super().__init__(config)
45
+ self.config = config
46
+
47
+ # Vision Model
48
+ if config.vision_model_name is None:
49
+ pass
50
+ elif config.vision_model_name == 'CLIP':
51
+ from transformers import AutoModel
52
+ vision_model = AutoModel.from_pretrained("openai/clip-vit-base-patch32").vision_model
53
+ state_dict = vision_model.state_dict()
54
+ state_dict = {k: v.to(torch.bfloat16) for k, v in state_dict.items()}
55
+ self.vision_model = CLIPVisionTransformer(vision_model.config, config.vision_model_prompt_len)
56
+ self.vision_model.load_state_dict(state_dict, strict=False)
57
+ for name, param in self.vision_model.named_parameters(): # Freeze layers other than prompts
58
+ if "encoder.prompts" in name:
59
+ param.requires_grad = True
60
+ else:
61
+ param.requires_grad = False
62
+ else:
63
+ pass
64
+
65
+ # Text Model
66
+ if config.text_model_name is None:
67
+ pass
68
+ elif config.text_model_name == 'Qwen':
69
+ self.tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-1.5B-Instruct")
70
+ from transformers import AutoModelForCausalLM
71
+ text_model = AutoModelForCausalLM.from_pretrained(
72
+ "Qwen/Qwen2-1.5B-Instruct",
73
+ torch_dtype=torch.bfloat16,
74
+ device_map="cpu",
75
+ attn_implementation="sdpa"
76
+ ).model
77
+ state_dict = text_model.state_dict()
78
+ self.text_model = Qwen2Model(text_model.config, config.text_model_prompt_len)
79
+ self.text_model.load_state_dict(state_dict, strict=False)
80
+ for name, param in self.text_model.named_parameters(): # Freeze layers other than prompts
81
+ if "prompts" in name:
82
+ param.requires_grad = True
83
+ else:
84
+ param.requires_grad = False
85
+ else:
86
+ pass
87
+
88
+ # Timer
89
+ from transformers import AutoModelForCausalLM
90
+ timer = AutoModelForCausalLM.from_pretrained('thuml/timer-base-84m', trust_remote_code=True)
91
+ state_dict = timer.state_dict()
92
+ self.timer = TimerForPrediction(timer.config, config.timer_prompt_len)
93
+ self.timer.load_state_dict(state_dict, strict=False)
94
+ for name, param in self.timer.named_parameters(): # Freeze layers other than prompts
95
+ if "model.prompts" in name:
96
+ param.requires_grad = True
97
+ else:
98
+ param.requires_grad = False
99
+
100
+ # Vision Interaction Layer
101
+ if config.vision_model_name is None:
102
+ pass
103
+ else:
104
+ self.vision_interaction_layer = nn.Linear(self.vision_model.config.hidden_size, self.timer.config.hidden_size)
105
+
106
+ # Text Interaction Layer
107
+ if config.text_model_name is None:
108
+ pass
109
+ else:
110
+ self.text_interaction_layer = nn.Linear(self.text_model.config.hidden_size, self.timer.config.hidden_size)
111
+
112
+ def forward(self, input_ids = None, images = None, texts = None, labels = None):
113
+ if self.config.vision_model_name is None and images is None:
114
+ vision_embedding = None
115
+ else:
116
+ vision_embedding = self.vision_model(images)
117
+ vision_embedding = vision_embedding.pooler_output
118
+ vision_embedding = self.vision_interaction_layer(vision_embedding)
119
+
120
+ if self.config.text_model_name is None and all(x is None for x in texts):
121
+ text_embedding = None
122
+ else:
123
+ tokenized_texts = self.tokenizer(texts, return_tensors="pt").to(input_ids.device)
124
+ text_embedding = self.text_model(**tokenized_texts)
125
+ text_embedding = text_embedding.last_hidden_state[:, 0 , :]
126
+ text_embedding = self.text_interaction_layer(text_embedding)
127
+
128
+ out = self.timer(input_ids=input_ids, vision_embedding=vision_embedding, text_embedding=text_embedding)
129
+ out = out["logits"]
130
+
131
+ if labels is not None:
132
+ if self.config.forecasting_length == out.shape[-1]:
133
+ loss = torch.mean(torch.square(out-labels)) # MSE
134
+ else: # pretrained Timer has 96 forecasting length. This is in case of shorter forecasting length. Forecasting length larger than 96 will occure an error.
135
+ loss = torch.mean(torch.square(out[:, :self.config.forecasting_length]-labels))
136
+ else:
137
+ loss = None
138
+
139
+ return {
140
+ "loss": loss,
141
+ "logits": out
142
+ }
143
+
144
+ class MultiModalTimerDataset(Dataset): # need to refactored
145
+ def __init__(self, dataset_path, vision_model_name = None, dataset_text = None, forecasting_length: int = 96):
146
+
147
+ self.dataset_path = dataset_path
148
+ self.vision_model_name = vision_model_name
149
+ self.dataset_text = dataset_text
150
+
151
+ if vision_model_name is None:
152
+ pass
153
+ elif vision_model_name == 'CLIP':
154
+ self.processor = CLIPImageProcessor()
155
+ else:
156
+ pass
157
+
158
+ self.inputs = torch.load(os.path.join(dataset_path, "inputs.pt"))
159
+ if forecasting_length:
160
+ self.targets = torch.load(os.path.join(dataset_path, f"targets_{forecasting_length}.pt"))
161
+ else:
162
+ self.targets = torch.load(os.path.join(dataset_path, "targets.pt"))
163
+ self.keys = list(self.targets.keys())
164
+
165
+ def __len__(self):
166
+ return len(self.keys)
167
+
168
+ def __getitem__(self, idx):
169
+ img_name = self.keys[idx]
170
+
171
+ if self.vision_model_name is None:
172
+ images = None
173
+ else:
174
+ img_path = os.path.join(self.dataset_path, 'img', img_name)
175
+ images = Image.open(img_path).convert("RGB")
176
+ images = self.processor.preprocess(images)['pixel_values'][0]
177
+
178
+ input_tensor = self.inputs[img_name].float().squeeze()
179
+ target_tensor = self.targets[img_name].float().squeeze()
180
+
181
+ return {
182
+ "input_ids": input_tensor,
183
+ "images": images,
184
+ "texts": self.dataset_text,
185
+ "labels": target_tensor
186
+ }
app.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from MultiModalTimer import MultiModalTimerConfig, MultiModalTimerModel
2
+ from safetensors.torch import load_file
3
+ import gradio as gr
4
+ import torch
5
+ import numpy as np
6
+ import matplotlib.pyplot as plt
7
+ import io
8
+ from PIL import Image
9
+
10
+ from transformers import CLIPImageProcessor
11
+
12
+ inputs = {
13
+ "NN5 Daily": [
14
+ "0.3910, 1.7167, 1.1042, -0.6679, -0.0730, -0.5204, -0.2152, 0.6485, 2.8109, 1.4125, -0.2568, 0.7014, 1.2558, 2.9853, -0.9938, -1.0800, -0.2318, -0.9222, -0.6326, -0.1353, 1.3316, -1.1879, 0.3443, -1.3457, -0.6679, -0.6450, -0.7810, -0.9419, -0.1787, -1.2575, 0.7232, -0.0730, -0.5599, -0.8962, -0.7987, 0.1450, 1.1177, 0.4772, -0.9699, -0.7748, -0.7634, -0.6741, -0.1602, 1.2849, 2.1974, 0.2062, -0.3564, -0.5547, -0.5588, 0.1626, 1.1073, 0.4575, -0.7198, -0.5443, -0.6357, -0.8070",
15
+ "0.5456, 1.4991, 1.1747, -0.6072, -0.1441, 0.3698, -0.3747, 0.3952, 1.3213, 2.2103, -0.2672, 1.3604, 1.3135, 2.1556, -1.9260, -1.8713, -0.5368, -1.2031, 0.4577, 0.0024, 1.6632, -1.3907, -0.0855, -0.0914, -1.1113, -0.3629, -1.3047, -0.7185, -0.3414, 0.7820, 0.4909, -0.6033, -0.2496, -0.7478, -0.3942, 0.2901, 0.3600, 0.7508, -0.7439, -0.6404, -0.7088, -0.6462, 0.5163, 1.2275, 0.4850, -2.0940, -1.6876, -0.3199, -0.1988, 0.4206, 1.4014, 1.3916, 0.0591, -0.5935, -0.1773, -0.5017",
16
+ "0.6767, -0.7404, -0.0247, -0.5122, 0.1192, 0.8660, 3.3852, 1.7256, -0.4448, 0.4084, 1.4521, 1.7801, -1.4599, -1.1773, -0.2282, -1.0087, 0.0907, -0.0234, 1.0890, -1.3394, 0.5938, -0.1453, -1.1928, -0.4085, -0.7144, -0.1673, -0.0182, 0.8453, 0.3980, -1.0645, -0.4875, -0.6755, -0.3086, 0.3358, 1.1383, 0.2074, -1.0554, -0.4357, -0.4759, -0.3631, 0.1529, 1.1953, 0.1633, -0.9932, -0.3177, -0.6457, -0.6807, -0.2412, -1.5286, 2.7797, -0.5757, -0.0986, -1.3899, -0.2995, 0.5471, 1.2926"
17
+ ],
18
+ "Australian Electricity": [
19
+ "0.1561, 0.0250, -0.1232, -0.3055, -0.3450, -0.6220, -0.9393, -1.1442, -1.3506, -1.5285, -1.6454, -1.7910, -1.8572, -1.8765, -1.8602, -1.7844, -1.5492, -1.3167, -0.8213, -0.3058, 0.1053, 0.4125, 0.6468, 0.7649, 0.8247, 0.8206, 0.8007, 0.8021, 0.8096, 0.8684, 0.8706, 0.8588, 0.8742, 0.9041, 0.8933, 0.8302, 0.8022, 0.8173, 0.8135, 0.7948, 0.6960, 0.6982, 0.9220, 0.9045, 0.7065, 0.6502, 0.6367, 0.4564",
20
+ "-0.3264, -0.3155, -0.3910, -0.2909, -0.3695, -0.4594, -0.6087, -0.7602, -0.9589, -1.2557, -1.5857, -1.8475, -1.9940, -2.0640, -2.0380, -1.8492, -1.6252, -1.1220, -0.5189, -0.2555, 0.1371, 0.3406, 0.4399, 0.6321, 0.7476, 0.8676, 0.9294, 0.9488, 1.0222, 1.0061, 1.0013, 1.0430, 1.0417, 1.0566, 1.0340, 0.9836, 0.9892, 0.9969, 0.9595, 0.8409, 0.7677, 0.6153, 0.5256, 0.4210, 0.5014, 0.4849, 0.3080, -0.0058",
21
+ "0.5091, 0.1714, -0.2558, -0.6192, -0.9358, -1.1645, -1.3079, -1.3875, -1.4657, -1.6180, -1.6260, -1.5982, -1.5640, -1.5354, -1.4960, -1.3395, -1.1070, -0.5613, 0.2179, 1.1485, 1.7363, 1.8791, 1.6987, 1.3585, 1.1350, 0.8669, 0.7281, 0.5676, 0.4495, 0.2027, 0.0901, -0.0161, -0.0750, -0.0981, -0.0711, 0.0944, 0.0466, 0.1898, 0.2478, 0.3899, 0.5053, 0.5426, 0.6315, 0.6308, 0.8361, 1.0080, 1.0234, 0.9366"
22
+ ],
23
+ "CIF 2016": [
24
+ "-2.1365, -0.6420, -0.9545, -0.4169, 0.5554, -0.5115, 0.2702, -0.1587, 1.0649, 1.3542, 0.6126, 0.9629",
25
+ "1.5888, 1.3587, 0.6136, 0.7122, 0.6355, -0.4164, -0.7670, -1.0409, -1.0300, 0.0219, -1.5559, -0.1205",
26
+ "1.3580, 1.1319, 1.5850, 0.7912, 0.0083, -0.0066, -0.3669, -0.6251, -0.5215, -1.3642, -0.7737, -1.2164"
27
+ ],
28
+ "Tourism Monthly": [
29
+ "-0.7495, -0.8636, -0.9378, -0.7584, -0.3905, -0.1575, 0.3522, 1.9419, 1.9991, 0.5223, -0.2807, -0.8089, -0.7009, -0.8471, -0.9227, -0.6670, -0.4053, -0.1508, 0.3640, 1.8908, 1.9565, 0.5652, -0.1896, -0.7617",
30
+ "0.8332, 1.4813, 0.1061, -0.4110, -1.0407, -1.1521, -0.8156, -0.8842, -0.9908, 0.0014, 0.8833, 1.5613, 1.3095, 1.6260, 0.2534, -0.4883, -1.0412, -1.1210, -0.7034, -0.8304, -0.8239, -0.0673, 0.7531, 1.5613",
31
+ "0.8778, -0.0008, -0.6814, -0.7851, -0.7828, -0.6682, -0.8473, -0.9634, -0.4615, 0.1523, 2.3755, 1.0437, 1.5980, 0.1482, -0.1063, -0.7360, -0.7700, -0.7560, -0.7145, -0.8552, -0.4242, 0.2896, 2.2307, 0.8371"
32
+ ]
33
+ }
34
+
35
+ targets = {
36
+ "NN5 Daily": [
37
+ [-0.5433, 0.6589, 0.4668, -0.6959, -0.5474, -0.7685, -0.7125, -0.0273, 1.3170, 0.5883, -0.7675, -0.5163, -0.6035, -0.5028, 0.0505, 0.5530, 0.5810, -0.8049, -0.5370, -0.6149, -0.5609, 0.2166, 1.3202, 0.5852, -0.5921, -0.5038, -0.7301, -0.7644, 0.2011, 0.6942, 0.5052, -0.7644, -0.7644, -0.7364, -0.3896, 0.1917, 1.1084, 0.3827, -0.6679, -0.5568, -0.5910, -0.4052, 0.3599, 1.0617, 1.0461, -0.6326, -0.6990, -0.9056, -0.6159, 0.2696, 1.5299, 0.8032, -1.1879, -0.8153, -0.4872, -0.3491],
38
+ [0.6140, 1.0575, 0.2213, -0.3903, -0.5388, -0.6677, -0.4196, 0.1841, 1.6300, 0.4147, -0.5505, -0.4469, -0.3903, -0.3786, 0.5886, 1.0321, 0.3053, -0.5368, -0.6443, -0.5700, -0.5290, 0.1587, 1.6437, 1.1435, -0.6404, -0.1988, -0.6423, -0.4489, 0.1880, 0.9872, 1.1044, -0.7654, -0.2320, -0.6931, -0.9725, 0.3014, 1.3447, 0.8895, -0.5446, -0.0445, -0.3336, -0.6482, 0.7097, 1.7238, 1.3037, -0.3551, -0.4919, -0.5544, -0.4196, 0.4753, 1.4795, 1.3760, -0.4430, -0.0347, 0.2330, -0.4079],
39
+ [0.2800, -0.9634, -0.2114, -0.6185, -0.4473, 0.4408, 1.3276, 0.4408, -1.0165, -0.6470, -0.4103, -0.7404, -0.2490, 1.0709, 0.6690, -1.0528, -0.4655, -0.7365, -0.3981, 0.0907, 1.4754, 1.0359, -0.9400, -0.3449, -0.6418, 0.0155, 0.5717, 1.2355, 0.4589, -0.9776, -0.1867, -0.6587, -0.3358, 0.2644, 1.4145, 0.3189, -1.1708, -0.2412, -0.5848, -0.1077, 0.5951, 0.8777, 0.6599, -1.1565, -0.5122, -0.5666, -0.2931, 0.1983, 1.8410, 1.1370, -1.2330, -0.2840, 0.0090, 0.2411, 0.5912, 1.2822]
40
+ ],
41
+ "Australian Electricity": [
42
+ [0.2418, 0.1000, -0.0648, -0.2259, -0.2967, -0.5842, -0.9359, -1.1101, -1.3467, -1.5249, -1.7000, -1.7966, -1.8497, -1.8812, -1.9009, -1.8194, -1.6176, -1.3769, -0.8809, -0.4156, 0.0521, 0.3505, 0.6003, 0.7191, 0.8154, 0.8006, 0.7769, 0.7888, 0.8156, 0.8311, 0.8516, 0.8480, 0.8405, 0.9085, 0.8990, 0.9031, 0.9135, 0.9160, 0.8557, 0.8282, 0.7075, 0.7170, 0.9111, 0.9671, 0.7844, 0.7513, 0.6663, 0.5040],
43
+ [-0.2806, -0.2256, -0.3062, -0.2318, -0.3017, -0.4339, -0.5957, -0.7385, -0.9333, -1.2554, -1.5583, -1.8179, -1.9639, -2.0259, -2.0105, -1.8515, -1.5978, -1.1026, -0.5616, -0.2580, 0.0937, 0.3312, 0.3877, 0.5459, 0.6491, 0.7382, 0.7652, 0.7550, 0.8130, 0.7863, 0.7734, 0.7761, 0.7552, 0.7527, 0.7178, 0.6544, 0.6689, 0.6651, 0.6142, 0.4929, 0.3658, 0.1463, 0.0122, -0.0509, 0.0453, 0.0132, -0.1152, -0.3515],
44
+ [0.6565, 0.3575, -0.0906, -0.4682, -0.7850, -1.0572, -1.2190, -1.3699, -1.4444, -1.4917, -1.4912, -1.4580, -1.4893, -1.4474, -1.3971, -1.2866, -1.0777, -0.6444, -0.0932, 0.5655, 1.0824, 1.1828, 1.1444, 1.1274, 0.9795, 0.7276, 0.5866, 0.4147, 0.1967, 0.0191, -0.1381, -0.2384, -0.3049, -0.3523, -0.3015, -0.1735, -0.1186, -0.0017, 0.1577, 0.2584, 0.3643, 0.5303, 0.6169, 0.6950, 0.8434, 0.9273, 0.8578, 0.7277]
45
+ ],
46
+ "CIF 2016": [
47
+ [0.7780, 1.4980, 0.9115, 0.5034, 1.8105, 1.6583, 1.6255, 1.9613, 1.6311, 2.2943, 2.4116, 2.4785],
48
+ [-1.1615, -0.6684, -1.1396, -0.8766, -0.1863, -0.5040, -1.4683, -1.6765, -1.7312, -0.9862, -0.7341, -0.5807],
49
+ [-0.9360, -1.0646, -1.2660, -1.1586, -1.7037, -2.1642, -2.2156, -2.0456, -2.1657, -2.6387, -2.3959, -2.3520]
50
+ ],
51
+ "Tourism Monthly": [
52
+ [-0.7218, -0.8162, -0.8599, -0.6781, -0.1500, 0.0297, 0.5061, 2.2237, 1.9718, 0.7502, -0.0718, -0.7254, -0.5999, -0.8048, -0.8552, -0.5962, -0.2393, -0.0513, 0.5497, 2.0177, 2.3518, 0.6854, -0.1190, -0.7002],
53
+ [1.4626, 1.6710, 0.9104, -0.5530, -0.9392, -1.0148, -0.6596, -0.7959, -0.7170, 0.1262, 1.1316, 1.9928, 1.8925, 2.1458, 0.7225, -0.1372, -0.8087, -0.8994, -0.5187, -0.6408, -0.5757, 0.1131, 1.2596, 2.4437],
54
+ [0.7737, 0.2534, -0.4698, -0.8390, -0.7692, -0.6648, -0.7311, -0.8054, -0.3891, 0.8623, 2.7314, 1.3378, 1.2805, 0.5682, -0.4299, -0.7511, -0.8982, -0.6067, -0.6572, -0.8337, -0.2564, 0.5460, 2.5010, 1.5309]
55
+ ]
56
+ }
57
+
58
+ descriptions = {
59
+ "NN5 Daily": "Daily cash withdrawal volumes from automated teller machines (ATMs) in the United Kingdom, originally used in the NN5 forecasting competition.",
60
+ "Australian Electricity": "Half-hourly electricity demand data across five Australian states.",
61
+ "CIF 2016": "Monthly banking time series used in the CIF 2016 forecasting challenge, reflecting customer financial behaviours.",
62
+ "Tourism Monthly": "Monthly tourism-related time series used in the Kaggle Tourism forecasting competition, covering various regions and visitor types."
63
+ }
64
+
65
+ models = {}
66
+ # for dataset in ["NN5_Daily", "Australian_Electricity", "CIF_2016", "Tourism_Monthly"]:
67
+ for dataset in ["NN5_Daily", "Australian_Electricity"]:
68
+ config = MultiModalTimerConfig.from_pretrained(f"ckpt/CLIPQwenTimer/{dataset}/config.json")
69
+ model = MultiModalTimerModel(config)
70
+ state_dict = load_file(f"ckpt/CLIPQwenTimer/{dataset}/model.safetensors")
71
+ model.load_state_dict(state_dict, strict=False)
72
+
73
+ # device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
74
+ device = torch.device("cpu")
75
+ model.to(device)
76
+
77
+ models[dataset.replace("_", " ")] = model
78
+
79
+ context_length = {
80
+ "NN5 Daily": 56,
81
+ "Australian Electricity": 48,
82
+ "CIF 2016": 12,
83
+ "Tourism Monthly": 24
84
+ }
85
+
86
+ def predict(dataset, example, inputs, text):
87
+ inputs = np.array([float(x.strip()) for x in inputs.split(',')])
88
+ mean = np.mean(inputs)
89
+ std = np.std(inputs)
90
+ inputs = (inputs-mean)/std
91
+ input_ids = torch.tensor(inputs).to(torch.float32).to(device)
92
+ input_ids = input_ids.unsqueeze(0)
93
+
94
+ plt.figure(figsize=(384/100, 384/100), dpi=100)
95
+ plt.plot(inputs, color="black", linestyle="-", linewidth=1, marker="*", markersize=1)
96
+ plt.xticks([])
97
+ plt.yticks([])
98
+ plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
99
+ plt.margins(0,0)
100
+
101
+ buf = io.BytesIO()
102
+ plt.savefig(buf, format='png')
103
+ buf.seek(0)
104
+ plot_img = Image.open(buf).convert('RGB')
105
+
106
+ processor = CLIPImageProcessor()
107
+ images = processor.preprocess(plot_img)['pixel_values'][0]
108
+ images = torch.tensor(images).to(device)
109
+ images = images.unsqueeze(0)
110
+
111
+ text = None if text == '' else text
112
+
113
+ out = models[dataset](**{'input_ids': input_ids, 'images': images, 'texts': text})['logits']
114
+
115
+ cl = context_length[dataset]
116
+ out = out[0, :cl]
117
+
118
+ plt.style.use("seaborn-v0_8")
119
+ fig, ax = plt.subplots()
120
+ ax.plot(range(cl), inputs, color="black", alpha=0.7, linewidth=3, label='Input')
121
+ if example == "Custom":
122
+ pass
123
+ else:
124
+ ax.plot(range(cl, 2*cl), targets[dataset][int(example)-1], color='C0', alpha=0.7, linewidth=3, label='True')
125
+ ax.plot(range(cl, 2*cl), out.detach().cpu().numpy(), color='C2', alpha=0.7, linewidth=3, label='Forecast')
126
+ ax.legend()
127
+
128
+ buf = io.BytesIO()
129
+ fig.savefig(buf, format='png')
130
+ buf.seek(0)
131
+ forecast_img = Image.open(buf).convert('RGB')
132
+
133
+ # return plot_img, out, forecast_img
134
+ return forecast_img
135
+
136
+ def make_input_example_dropdown(example, done):
137
+ if done:
138
+ return example, True
139
+ else:
140
+ return gr.Dropdown(["1", "2", "3", "Custom"], label="Input Examples", value=None, interactive=True), True
141
+
142
+ def update_options(dataset, example):
143
+ if example == "1":
144
+ time_series = inputs[dataset][0]
145
+ desc = descriptions[dataset]
146
+ placeholder = None
147
+ interactive = False
148
+ elif example == "2":
149
+ time_series = inputs[dataset][1]
150
+ desc = descriptions[dataset]
151
+ placeholder = None
152
+ interactive = False
153
+ elif example == "3":
154
+ time_series = inputs[dataset][2]
155
+ desc = descriptions[dataset]
156
+ placeholder = None
157
+ interactive = False
158
+ elif example == "Custom":
159
+ time_series = ""
160
+ desc = ""
161
+ placeholder = f"Please Enter {context_length[dataset]} Time Steps Long Time Series Input."
162
+ interactive = True
163
+ else:
164
+ time_series = ""
165
+ desc = ""
166
+ placeholder = None
167
+ interactive = False
168
+
169
+ return gr.Textbox(value=time_series, label="Time Series Input", placeholder=placeholder, interactive=interactive), gr.Textbox(value=desc, label="Dataset Description", interactive=interactive)
170
+
171
+ with gr.Blocks() as demo:
172
+ with gr.Row():
173
+ with gr.Column():
174
+ # dataset_dropdown = gr.Dropdown(["NN5 Daily", "Australian Electricity", "CIF 2016", "Tourism Monthly"], value=None, label="Datasets", interactive=True)
175
+ dataset_dropdown = gr.Dropdown(["NN5 Daily", "Australian Electricity"], value=None, label="Datasets", interactive=True)
176
+ input_example_dropdown = gr.Dropdown([], label="Input Examples", value=None, interactive=False)
177
+ done = gr.State(False)
178
+
179
+ time_series_textbox = gr.Textbox(label="Time Series Input")
180
+ dataset_description_textbox = gr.Textbox(label="Dataset Description")
181
+
182
+ dataset_dropdown.change(make_input_example_dropdown, inputs=[input_example_dropdown, done], outputs=[input_example_dropdown, done])
183
+ dataset_dropdown.change(update_options, inputs=[dataset_dropdown, input_example_dropdown], outputs=[time_series_textbox, dataset_description_textbox])
184
+ input_example_dropdown.change(update_options, inputs=[dataset_dropdown, input_example_dropdown], outputs=[time_series_textbox, dataset_description_textbox])
185
+
186
+ btn = gr.Button("Run")
187
+ with gr.Column():
188
+ forecast_image = gr.Image(label="Forecast")
189
+
190
+ btn.click(predict, inputs=[dataset_dropdown, input_example_dropdown, time_series_textbox, dataset_description_textbox], outputs=forecast_image)
191
+
192
+ demo.launch(ssr_mode=False)
ckpt/CLIPQwenTimer/Australian_Electricity/config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "forecasting_length": 48,
3
+ "text_model_name": "Qwen",
4
+ "text_model_prompt_len": 4,
5
+ "timer_prompt_len": 4,
6
+ "transformers_version": "4.40.1",
7
+ "vision_model_name": "CLIP",
8
+ "vision_model_prompt_len": 10
9
+ }
ckpt/CLIPQwenTimer/Australian_Electricity/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3974a01b497fa5149d2f1702cc5daa736a98a4ed32c081f6cad28be807fd680e
3
+ size 10638152
ckpt/CLIPQwenTimer/CIF_2016/config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "forecasting_length": 12,
3
+ "text_model_name": "Qwen",
4
+ "text_model_prompt_len": 4,
5
+ "timer_prompt_len": 4,
6
+ "transformers_version": "4.40.1",
7
+ "vision_model_name": "CLIP",
8
+ "vision_model_prompt_len": 10
9
+ }
ckpt/CLIPQwenTimer/CIF_2016/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ed3fced554180a08675776ec0508ae2f39a65e778aaca9c69c333e239a7be6a8
3
+ size 10638152
ckpt/CLIPQwenTimer/NN5_Daily/config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "forecasting_length": 56,
3
+ "text_model_name": "Qwen",
4
+ "text_model_prompt_len": 4,
5
+ "timer_prompt_len": 4,
6
+ "transformers_version": "4.40.1",
7
+ "vision_model_name": "CLIP",
8
+ "vision_model_prompt_len": 10
9
+ }
ckpt/CLIPQwenTimer/NN5_Daily/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d3a4e052bdb44da28792f4b0b24ce5d141143c8ff1da2148fb4b05d0b80c0e76
3
+ size 10638152
ckpt/CLIPQwenTimer/Tourism_Monthly/config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "forecasting_length": 24,
3
+ "text_model_name": "Qwen",
4
+ "text_model_prompt_len": 4,
5
+ "timer_prompt_len": 4,
6
+ "transformers_version": "4.40.1",
7
+ "vision_model_name": "CLIP",
8
+ "vision_model_prompt_len": 10
9
+ }
ckpt/CLIPQwenTimer/Tourism_Monthly/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1978e7504e9166e38fab24579d4ce3dd74bd20cf8e9c6bdf142a56df0c234d7b
3
+ size 10638152
models/__pycache__/configuration_timer.cpython-310.pyc ADDED
Binary file (1.35 kB). View file
 
models/__pycache__/modeling_clipPT.cpython-310.pyc ADDED
Binary file (44.2 kB). View file
 
models/__pycache__/modeling_qwen2.cpython-310.pyc ADDED
Binary file (39.7 kB). View file
 
models/__pycache__/modeling_timer.cpython-310.pyc ADDED
Binary file (16.1 kB). View file
 
models/__pycache__/ts_generation_mixin.cpython-310.pyc ADDED
Binary file (6.38 kB). View file
 
models/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
+ )
models/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
+ )
models/modeling_qwen2.py ADDED
@@ -0,0 +1,1416 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_2_available,
41
+ is_flash_attn_greater_or_equal_2_10,
42
+ logging,
43
+ replace_return_docstrings,
44
+ )
45
+ from transformers.models.qwen2.configuration_qwen2 import Qwen2Config
46
+
47
+
48
+ if is_flash_attn_2_available():
49
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
50
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
51
+
52
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
53
+
54
+
55
+ logger = logging.get_logger(__name__)
56
+
57
+
58
+ _CHECKPOINT_FOR_DOC = "Qwen/Qwen2-7B-beta"
59
+ _CONFIG_FOR_DOC = "Qwen2Config"
60
+
61
+
62
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
63
+ def _get_unpad_data(attention_mask):
64
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
65
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
66
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
67
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
68
+ return (
69
+ indices,
70
+ cu_seqlens,
71
+ max_seqlen_in_batch,
72
+ )
73
+
74
+
75
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Qwen2
76
+ class Qwen2RMSNorm(nn.Module):
77
+ def __init__(self, hidden_size, eps=1e-6):
78
+ """
79
+ Qwen2RMSNorm is equivalent to T5LayerNorm
80
+ """
81
+ super().__init__()
82
+ self.weight = nn.Parameter(torch.ones(hidden_size))
83
+ self.variance_epsilon = eps
84
+
85
+ def forward(self, hidden_states):
86
+ input_dtype = hidden_states.dtype
87
+ hidden_states = hidden_states.to(torch.float32)
88
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
89
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
90
+ return self.weight * hidden_states.to(input_dtype)
91
+
92
+
93
+ # Copied from transformers.models.mistral.modeling_mistral.MistralRotaryEmbedding with Mistral->Qwen2
94
+ class Qwen2RotaryEmbedding(nn.Module):
95
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
96
+ super().__init__()
97
+
98
+ self.dim = dim
99
+ self.max_position_embeddings = max_position_embeddings
100
+ self.base = base
101
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
102
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
103
+
104
+ # Build here to make `torch.jit.trace` work.
105
+ self._set_cos_sin_cache(
106
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
107
+ )
108
+
109
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
110
+ self.max_seq_len_cached = seq_len
111
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
112
+
113
+ freqs = torch.outer(t, self.inv_freq)
114
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
115
+ emb = torch.cat((freqs, freqs), dim=-1)
116
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
117
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
118
+
119
+ def forward(self, x, seq_len=None):
120
+ # x: [bs, num_attention_heads, seq_len, head_size]
121
+ if seq_len > self.max_seq_len_cached:
122
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
123
+
124
+ return (
125
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
126
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
127
+ )
128
+
129
+
130
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
131
+ def rotate_half(x):
132
+ """Rotates half the hidden dims of the input."""
133
+ x1 = x[..., : x.shape[-1] // 2]
134
+ x2 = x[..., x.shape[-1] // 2 :]
135
+ return torch.cat((-x2, x1), dim=-1)
136
+
137
+
138
+ # Copied from transformers.models.mistral.modeling_mistral.apply_rotary_pos_emb
139
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
140
+ """Applies Rotary Position Embedding to the query and key tensors.
141
+
142
+ Args:
143
+ q (`torch.Tensor`): The query tensor.
144
+ k (`torch.Tensor`): The key tensor.
145
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
146
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
147
+ position_ids (`torch.Tensor`):
148
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
149
+ used to pass offsetted position ids when working with a KV-cache.
150
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
151
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
152
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
153
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
154
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
155
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
156
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
157
+ Returns:
158
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
159
+ """
160
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
161
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
162
+ q_embed = (q * cos) + (rotate_half(q) * sin)
163
+ k_embed = (k * cos) + (rotate_half(k) * sin)
164
+ return q_embed, k_embed
165
+
166
+
167
+ # Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Qwen2
168
+ class Qwen2MLP(nn.Module):
169
+ def __init__(self, config):
170
+ super().__init__()
171
+ self.config = config
172
+ self.hidden_size = config.hidden_size
173
+ self.intermediate_size = config.intermediate_size
174
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
175
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
176
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
177
+ self.act_fn = ACT2FN[config.hidden_act]
178
+
179
+ def forward(self, x):
180
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
181
+
182
+
183
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
184
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
185
+ """
186
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
187
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
188
+ """
189
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
190
+ if n_rep == 1:
191
+ return hidden_states
192
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
193
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
194
+
195
+
196
+ class Qwen2Attention(nn.Module):
197
+ """
198
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
199
+ and "Generating Long Sequences with Sparse Transformers".
200
+ """
201
+
202
+ def __init__(self, config: Qwen2Config, layer_idx: Optional[int] = None):
203
+ super().__init__()
204
+ self.config = config
205
+ self.layer_idx = layer_idx
206
+ if layer_idx is None:
207
+ logger.warning_once(
208
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
209
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
210
+ "when creating this class."
211
+ )
212
+
213
+ self.hidden_size = config.hidden_size
214
+ self.num_heads = config.num_attention_heads
215
+ self.head_dim = self.hidden_size // self.num_heads
216
+ self.num_key_value_heads = config.num_key_value_heads
217
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
218
+ self.max_position_embeddings = config.max_position_embeddings
219
+ self.rope_theta = config.rope_theta
220
+ self.is_causal = True
221
+ self.attention_dropout = config.attention_dropout
222
+
223
+ if (self.head_dim * self.num_heads) != self.hidden_size:
224
+ raise ValueError(
225
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
226
+ f" and `num_heads`: {self.num_heads})."
227
+ )
228
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
229
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
230
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
231
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
232
+
233
+ self.rotary_emb = Qwen2RotaryEmbedding(
234
+ self.head_dim,
235
+ max_position_embeddings=self.max_position_embeddings,
236
+ base=self.rope_theta,
237
+ )
238
+
239
+ def forward(
240
+ self,
241
+ hidden_states: torch.Tensor,
242
+ attention_mask: Optional[torch.Tensor] = None,
243
+ position_ids: Optional[torch.LongTensor] = None,
244
+ past_key_value: Optional[Cache] = None,
245
+ output_attentions: bool = False,
246
+ use_cache: bool = False,
247
+ **kwargs,
248
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
249
+ if "padding_mask" in kwargs:
250
+ warnings.warn(
251
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
252
+ )
253
+ bsz, q_len, _ = hidden_states.size()
254
+
255
+ query_states = self.q_proj(hidden_states)
256
+ key_states = self.k_proj(hidden_states)
257
+ value_states = self.v_proj(hidden_states)
258
+
259
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
260
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
261
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
262
+
263
+ kv_seq_len = key_states.shape[-2]
264
+ if past_key_value is not None:
265
+ if self.layer_idx is None:
266
+ raise ValueError(
267
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
268
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
269
+ "with a layer index."
270
+ )
271
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
272
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
273
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
274
+
275
+ if past_key_value is not None:
276
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
277
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
278
+
279
+ # repeat k/v heads if n_kv_heads < n_heads
280
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
281
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
282
+
283
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
284
+
285
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
286
+ raise ValueError(
287
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
288
+ f" {attn_weights.size()}"
289
+ )
290
+
291
+ if attention_mask is not None:
292
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
293
+ raise ValueError(
294
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
295
+ )
296
+
297
+ attn_weights = attn_weights + attention_mask
298
+
299
+ # upcast attention to fp32
300
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
301
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
302
+ attn_output = torch.matmul(attn_weights, value_states)
303
+
304
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
305
+ raise ValueError(
306
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
307
+ f" {attn_output.size()}"
308
+ )
309
+
310
+ attn_output = attn_output.transpose(1, 2).contiguous()
311
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
312
+
313
+ attn_output = self.o_proj(attn_output)
314
+
315
+ if not output_attentions:
316
+ attn_weights = None
317
+
318
+ return attn_output, attn_weights, past_key_value
319
+
320
+
321
+ class Qwen2FlashAttention2(Qwen2Attention):
322
+ """
323
+ Qwen2 flash attention module, following Qwen2 attention module. This module inherits from `Qwen2Attention`
324
+ as the weights of the module stays untouched. The only required change would be on the forward pass
325
+ where it needs to correctly call the public API of flash attention and deal with padding tokens
326
+ in case the input contains any of them. Additionally, for sliding window attention, we apply SWA only to the bottom
327
+ config.max_window_layers layers.
328
+ """
329
+
330
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
331
+ def __init__(self, *args, **kwargs):
332
+ super().__init__(*args, **kwargs)
333
+
334
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
335
+ # 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.
336
+ # 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).
337
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
338
+
339
+ def forward(
340
+ self,
341
+ hidden_states: torch.Tensor,
342
+ attention_mask: Optional[torch.Tensor] = None,
343
+ position_ids: Optional[torch.LongTensor] = None,
344
+ past_key_value: Optional[Cache] = None,
345
+ output_attentions: bool = False,
346
+ use_cache: bool = False,
347
+ **kwargs,
348
+ ):
349
+ if "padding_mask" in kwargs:
350
+ warnings.warn(
351
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
352
+ )
353
+
354
+ # overwrite attention_mask with padding_mask
355
+ attention_mask = kwargs.pop("padding_mask")
356
+ bsz, q_len, _ = hidden_states.size()
357
+
358
+ query_states = self.q_proj(hidden_states)
359
+ key_states = self.k_proj(hidden_states)
360
+ value_states = self.v_proj(hidden_states)
361
+
362
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
363
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
364
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
365
+
366
+ kv_seq_len = key_states.shape[-2]
367
+ if past_key_value is not None:
368
+ if self.layer_idx is None:
369
+ raise ValueError(
370
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
371
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
372
+ "with a layer index."
373
+ )
374
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
375
+
376
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
377
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
378
+ cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
379
+
380
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
381
+
382
+ use_sliding_windows = (
383
+ _flash_supports_window_size
384
+ and getattr(self.config, "sliding_window", None) is not None
385
+ and kv_seq_len > self.config.sliding_window
386
+ and self.config.use_sliding_window
387
+ )
388
+
389
+ if not _flash_supports_window_size:
390
+ logger.warning_once(
391
+ "The current flash attention version does not support sliding window attention, for a more memory efficient implementation"
392
+ " make sure to upgrade flash-attn library."
393
+ )
394
+
395
+ if past_key_value is not None:
396
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
397
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
398
+ if (
399
+ getattr(self.config, "sliding_window", None) is not None
400
+ and kv_seq_len > self.config.sliding_window
401
+ and cache_has_contents
402
+ ):
403
+ slicing_tokens = 1 - self.config.sliding_window
404
+
405
+ past_key = past_key_value[self.layer_idx][0]
406
+ past_value = past_key_value[self.layer_idx][1]
407
+
408
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
409
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
410
+
411
+ if past_key.shape[-2] != self.config.sliding_window - 1:
412
+ raise ValueError(
413
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
414
+ f" {past_key.shape}"
415
+ )
416
+
417
+ if attention_mask is not None:
418
+ attention_mask = attention_mask[:, slicing_tokens:]
419
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
420
+
421
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
422
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
423
+
424
+ # repeat k/v heads if n_kv_heads < n_heads
425
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
426
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
427
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
428
+
429
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
430
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
431
+ # cast them back in float16 just to be sure everything works as expected.
432
+ input_dtype = query_states.dtype
433
+ if input_dtype == torch.float32:
434
+ if torch.is_autocast_enabled():
435
+ target_dtype = torch.get_autocast_gpu_dtype()
436
+ # Handle the case where the model is quantized
437
+ elif hasattr(self.config, "_pre_quantization_dtype"):
438
+ target_dtype = self.config._pre_quantization_dtype
439
+ else:
440
+ target_dtype = self.q_proj.weight.dtype
441
+
442
+ logger.warning_once(
443
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
444
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
445
+ f" {target_dtype}."
446
+ )
447
+
448
+ query_states = query_states.to(target_dtype)
449
+ key_states = key_states.to(target_dtype)
450
+ value_states = value_states.to(target_dtype)
451
+
452
+ # Reashape to the expected shape for Flash Attention
453
+ query_states = query_states.transpose(1, 2)
454
+ key_states = key_states.transpose(1, 2)
455
+ value_states = value_states.transpose(1, 2)
456
+
457
+ attn_output = self._flash_attention_forward(
458
+ query_states,
459
+ key_states,
460
+ value_states,
461
+ attention_mask,
462
+ q_len,
463
+ dropout=dropout_rate,
464
+ use_sliding_windows=use_sliding_windows,
465
+ )
466
+
467
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
468
+ attn_output = self.o_proj(attn_output)
469
+
470
+ if not output_attentions:
471
+ attn_weights = None
472
+
473
+ return attn_output, attn_weights, past_key_value
474
+
475
+ def _flash_attention_forward(
476
+ self,
477
+ query_states,
478
+ key_states,
479
+ value_states,
480
+ attention_mask,
481
+ query_length,
482
+ dropout=0.0,
483
+ softmax_scale=None,
484
+ use_sliding_windows=False,
485
+ ):
486
+ """
487
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
488
+ first unpad the input, then computes the attention scores and pad the final attention scores.
489
+
490
+ Args:
491
+ query_states (`torch.Tensor`):
492
+ Input query states to be passed to Flash Attention API
493
+ key_states (`torch.Tensor`):
494
+ Input key states to be passed to Flash Attention API
495
+ value_states (`torch.Tensor`):
496
+ Input value states to be passed to Flash Attention API
497
+ attention_mask (`torch.Tensor`):
498
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
499
+ position of padding tokens and 1 for the position of non-padding tokens.
500
+ dropout (`float`):
501
+ Attention dropout
502
+ softmax_scale (`float`, *optional*):
503
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
504
+ use_sliding_windows (`bool`, *optional*):
505
+ Whether to activate sliding window attention.
506
+ """
507
+ if not self._flash_attn_uses_top_left_mask:
508
+ causal = self.is_causal
509
+ else:
510
+ # 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__.
511
+ causal = self.is_causal and query_length != 1
512
+
513
+ # Decide whether to use SWA or not by layer index.
514
+ if use_sliding_windows and self.layer_idx >= self.config.max_window_layers:
515
+ use_sliding_windows = False
516
+
517
+ # Contains at least one padding token in the sequence
518
+ if attention_mask is not None:
519
+ batch_size = query_states.shape[0]
520
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
521
+ query_states, key_states, value_states, attention_mask, query_length
522
+ )
523
+
524
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
525
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
526
+
527
+ if not use_sliding_windows:
528
+ attn_output_unpad = flash_attn_varlen_func(
529
+ query_states,
530
+ key_states,
531
+ value_states,
532
+ cu_seqlens_q=cu_seqlens_q,
533
+ cu_seqlens_k=cu_seqlens_k,
534
+ max_seqlen_q=max_seqlen_in_batch_q,
535
+ max_seqlen_k=max_seqlen_in_batch_k,
536
+ dropout_p=dropout,
537
+ softmax_scale=softmax_scale,
538
+ causal=causal,
539
+ )
540
+ else:
541
+ attn_output_unpad = flash_attn_varlen_func(
542
+ query_states,
543
+ key_states,
544
+ value_states,
545
+ cu_seqlens_q=cu_seqlens_q,
546
+ cu_seqlens_k=cu_seqlens_k,
547
+ max_seqlen_q=max_seqlen_in_batch_q,
548
+ max_seqlen_k=max_seqlen_in_batch_k,
549
+ dropout_p=dropout,
550
+ softmax_scale=softmax_scale,
551
+ causal=causal,
552
+ window_size=(self.config.sliding_window, self.config.sliding_window),
553
+ )
554
+
555
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
556
+ else:
557
+ if not use_sliding_windows:
558
+ attn_output = flash_attn_func(
559
+ query_states,
560
+ key_states,
561
+ value_states,
562
+ dropout,
563
+ softmax_scale=softmax_scale,
564
+ causal=causal,
565
+ )
566
+ else:
567
+ attn_output = flash_attn_func(
568
+ query_states,
569
+ key_states,
570
+ value_states,
571
+ dropout,
572
+ softmax_scale=softmax_scale,
573
+ causal=causal,
574
+ window_size=(self.config.sliding_window, self.config.sliding_window),
575
+ )
576
+
577
+ return attn_output
578
+
579
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._upad_input
580
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
581
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
582
+
583
+ # On the first iteration we need to properly re-create the padding mask
584
+ # by slicing it on the proper place
585
+ if kv_seq_len != attention_mask.shape[-1]:
586
+ attention_mask_num_tokens = attention_mask.shape[-1]
587
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
588
+
589
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
590
+
591
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
592
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
593
+
594
+ if query_length == kv_seq_len:
595
+ query_layer = index_first_axis(
596
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
597
+ )
598
+ cu_seqlens_q = cu_seqlens_k
599
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
600
+ indices_q = indices_k
601
+ elif query_length == 1:
602
+ max_seqlen_in_batch_q = 1
603
+ cu_seqlens_q = torch.arange(
604
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
605
+ ) # There is a memcpy here, that is very bad.
606
+ indices_q = cu_seqlens_q[:-1]
607
+ query_layer = query_layer.squeeze(1)
608
+ else:
609
+ # The -q_len: slice assumes left padding.
610
+ attention_mask = attention_mask[:, -query_length:]
611
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
612
+
613
+ return (
614
+ query_layer,
615
+ key_layer,
616
+ value_layer,
617
+ indices_q,
618
+ (cu_seqlens_q, cu_seqlens_k),
619
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
620
+ )
621
+
622
+
623
+ # Copied from transformers.models.mistral.modeling_mistral.MistralSdpaAttention with Mistral->Qwen2
624
+ class Qwen2SdpaAttention(Qwen2Attention):
625
+ """
626
+ Qwen2 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
627
+ `Qwen2Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
628
+ SDPA API.
629
+ """
630
+
631
+ # Adapted from Qwen2Attention.forward
632
+ def forward(
633
+ self,
634
+ hidden_states: torch.Tensor,
635
+ attention_mask: Optional[torch.Tensor] = None,
636
+ position_ids: Optional[torch.LongTensor] = None,
637
+ past_key_value: Optional[Cache] = None,
638
+ output_attentions: bool = False,
639
+ use_cache: bool = False,
640
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
641
+ if output_attentions:
642
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
643
+ logger.warning_once(
644
+ "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, "
645
+ '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.'
646
+ )
647
+ return super().forward(
648
+ hidden_states=hidden_states,
649
+ attention_mask=attention_mask,
650
+ position_ids=position_ids,
651
+ past_key_value=past_key_value,
652
+ output_attentions=output_attentions,
653
+ use_cache=use_cache,
654
+ )
655
+
656
+ bsz, q_len, _ = hidden_states.size()
657
+
658
+ query_states = self.q_proj(hidden_states)
659
+ key_states = self.k_proj(hidden_states)
660
+ value_states = self.v_proj(hidden_states)
661
+
662
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
663
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
664
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
665
+
666
+ kv_seq_len = key_states.shape[-2]
667
+ if past_key_value is not None:
668
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
669
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
670
+
671
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
672
+
673
+ if past_key_value is not None:
674
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
675
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
676
+
677
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
678
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
679
+
680
+ if attention_mask is not None:
681
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
682
+ raise ValueError(
683
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
684
+ )
685
+
686
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
687
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
688
+ if query_states.device.type == "cuda" and attention_mask is not None:
689
+ query_states = query_states.contiguous()
690
+ key_states = key_states.contiguous()
691
+ value_states = value_states.contiguous()
692
+
693
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
694
+ query_states,
695
+ key_states,
696
+ value_states,
697
+ attn_mask=attention_mask,
698
+ dropout_p=self.attention_dropout if self.training else 0.0,
699
+ # 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.
700
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
701
+ )
702
+
703
+ attn_output = attn_output.transpose(1, 2).contiguous()
704
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
705
+
706
+ attn_output = self.o_proj(attn_output)
707
+
708
+ return attn_output, None, past_key_value
709
+
710
+
711
+ QWEN2_ATTENTION_CLASSES = {
712
+ "eager": Qwen2Attention,
713
+ "flash_attention_2": Qwen2FlashAttention2,
714
+ "sdpa": Qwen2SdpaAttention,
715
+ }
716
+
717
+
718
+ class Qwen2DecoderLayer(nn.Module):
719
+ def __init__(self, config: Qwen2Config, layer_idx: int):
720
+ super().__init__()
721
+ self.hidden_size = config.hidden_size
722
+
723
+ if config.use_sliding_window and config._attn_implementation != "flash_attention_2":
724
+ logger.warning_once(
725
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
726
+ "unexpected results may be encountered."
727
+ )
728
+ self.self_attn = QWEN2_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
729
+
730
+ self.mlp = Qwen2MLP(config)
731
+ self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
732
+ self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
733
+
734
+ def forward(
735
+ self,
736
+ hidden_states: torch.Tensor,
737
+ attention_mask: Optional[torch.Tensor] = None,
738
+ position_ids: Optional[torch.LongTensor] = None,
739
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
740
+ output_attentions: Optional[bool] = False,
741
+ use_cache: Optional[bool] = False,
742
+ **kwargs,
743
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
744
+ if "padding_mask" in kwargs:
745
+ warnings.warn(
746
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. "
747
+ "Please make sure use `attention_mask` instead.`"
748
+ )
749
+ """
750
+ Args:
751
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
752
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
753
+ `(batch, sequence_length)` where padding elements are indicated by 0.
754
+ output_attentions (`bool`, *optional*):
755
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
756
+ returned tensors for more detail.
757
+ use_cache (`bool`, *optional*):
758
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
759
+ (see `past_key_values`).
760
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
761
+ """
762
+
763
+ residual = hidden_states
764
+
765
+ hidden_states = self.input_layernorm(hidden_states)
766
+
767
+ # Self Attention
768
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
769
+ hidden_states=hidden_states,
770
+ attention_mask=attention_mask,
771
+ position_ids=position_ids,
772
+ past_key_value=past_key_value,
773
+ output_attentions=output_attentions,
774
+ use_cache=use_cache,
775
+ )
776
+ hidden_states = residual + hidden_states
777
+
778
+ # Fully Connected
779
+ residual = hidden_states
780
+ hidden_states = self.post_attention_layernorm(hidden_states)
781
+ hidden_states = self.mlp(hidden_states)
782
+ hidden_states = residual + hidden_states
783
+
784
+ outputs = (hidden_states,)
785
+
786
+ if output_attentions:
787
+ outputs += (self_attn_weights,)
788
+
789
+ if use_cache:
790
+ outputs += (present_key_value,)
791
+
792
+ return outputs
793
+
794
+
795
+ QWEN2_START_DOCSTRING = r"""
796
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
797
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
798
+ etc.)
799
+
800
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
801
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
802
+ and behavior.
803
+
804
+ Parameters:
805
+ config ([`Qwen2Config`]):
806
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
807
+ load the weights associated with the model, only the configuration. Check out the
808
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
809
+ """
810
+
811
+
812
+ @add_start_docstrings(
813
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
814
+ QWEN2_START_DOCSTRING,
815
+ )
816
+ class Qwen2PreTrainedModel(PreTrainedModel):
817
+ config_class = Qwen2Config
818
+ base_model_prefix = "model"
819
+ supports_gradient_checkpointing = True
820
+ _no_split_modules = ["Qwen2DecoderLayer"]
821
+ _skip_keys_device_placement = "past_key_values"
822
+ _supports_flash_attn_2 = True
823
+ _supports_sdpa = True
824
+ _supports_cache_class = True
825
+
826
+ def _init_weights(self, module):
827
+ std = self.config.initializer_range
828
+ if isinstance(module, nn.Linear):
829
+ module.weight.data.normal_(mean=0.0, std=std)
830
+ if module.bias is not None:
831
+ module.bias.data.zero_()
832
+ elif isinstance(module, nn.Embedding):
833
+ module.weight.data.normal_(mean=0.0, std=std)
834
+ if module.padding_idx is not None:
835
+ module.weight.data[module.padding_idx].zero_()
836
+
837
+
838
+ QWEN2_INPUTS_DOCSTRING = r"""
839
+ Args:
840
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
841
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
842
+ it.
843
+
844
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
845
+ [`PreTrainedTokenizer.__call__`] for details.
846
+
847
+ [What are input IDs?](../glossary#input-ids)
848
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
849
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
850
+
851
+ - 1 for tokens that are **not masked**,
852
+ - 0 for tokens that are **masked**.
853
+
854
+ [What are attention masks?](../glossary#attention-mask)
855
+
856
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
857
+ [`PreTrainedTokenizer.__call__`] for details.
858
+
859
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
860
+ `past_key_values`).
861
+
862
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
863
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
864
+ information on the default strategy.
865
+
866
+ - 1 indicates the head is **not masked**,
867
+ - 0 indicates the head is **masked**.
868
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
869
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
870
+ config.n_positions - 1]`.
871
+
872
+ [What are position IDs?](../glossary#position-ids)
873
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
874
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
875
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
876
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
877
+
878
+ Two formats are allowed:
879
+ - a [`~cache_utils.Cache`] instance;
880
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
881
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
882
+ cache format.
883
+
884
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
885
+ legacy cache format will be returned.
886
+
887
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
888
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
889
+ of shape `(batch_size, sequence_length)`.
890
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
891
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
892
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
893
+ model's internal embedding lookup matrix.
894
+ use_cache (`bool`, *optional*):
895
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
896
+ `past_key_values`).
897
+ output_attentions (`bool`, *optional*):
898
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
899
+ tensors for more detail.
900
+ output_hidden_states (`bool`, *optional*):
901
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
902
+ more detail.
903
+ return_dict (`bool`, *optional*):
904
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
905
+ """
906
+
907
+
908
+ @add_start_docstrings(
909
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
910
+ QWEN2_START_DOCSTRING,
911
+ )
912
+ class Qwen2Model(Qwen2PreTrainedModel):
913
+ """
914
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]
915
+
916
+ Args:
917
+ config: Qwen2Config
918
+ """
919
+
920
+ def __init__(self, config: Qwen2Config, PT_len):
921
+ super().__init__(config)
922
+ self.padding_idx = config.pad_token_id
923
+ self.vocab_size = config.vocab_size
924
+
925
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
926
+
927
+ self.prompts = []
928
+ self.prompts_token_len = PT_len
929
+ import torch.nn.init as init
930
+ if self.prompts_token_len > 0:
931
+ for i in range(config.num_hidden_layers):
932
+ self.prompts.append(init.xavier_uniform_(nn.Parameter(torch.randn(1,PT_len,config.hidden_size))))
933
+ self.prompts = nn.ParameterList(self.prompts)
934
+ self.layers = nn.ModuleList(
935
+ [Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
936
+ )
937
+ self._attn_implementation = config._attn_implementation
938
+ self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
939
+
940
+ self.gradient_checkpointing = False
941
+ # Initialize weights and apply final processing
942
+ self.post_init()
943
+
944
+ def get_input_embeddings(self):
945
+ return self.embed_tokens
946
+
947
+ def set_input_embeddings(self, value):
948
+ self.embed_tokens = value
949
+
950
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
951
+ def forward(
952
+ self,
953
+ input_ids: torch.LongTensor = None,
954
+ attention_mask: Optional[torch.Tensor] = None,
955
+ position_ids: Optional[torch.LongTensor] = None,
956
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
957
+ inputs_embeds: Optional[torch.FloatTensor] = None,
958
+ use_cache: Optional[bool] = None,
959
+ output_attentions: Optional[bool] = None,
960
+ output_hidden_states: Optional[bool] = None,
961
+ return_dict: Optional[bool] = None,
962
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
963
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
964
+ output_hidden_states = (
965
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
966
+ )
967
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
968
+
969
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
970
+
971
+ # retrieve input_ids and inputs_embeds
972
+ if input_ids is not None and inputs_embeds is not None:
973
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
974
+ elif input_ids is not None:
975
+ batch_size, seq_length = input_ids.shape
976
+ elif inputs_embeds is not None:
977
+ batch_size, seq_length, _ = inputs_embeds.shape
978
+ else:
979
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
980
+
981
+ if self.prompts_token_len > 0:
982
+ seq_length += self.prompts_token_len
983
+
984
+ if self.gradient_checkpointing and self.training:
985
+ if use_cache:
986
+ logger.warning_once(
987
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
988
+ )
989
+ use_cache = False
990
+
991
+ past_key_values_length = 0
992
+
993
+ if use_cache:
994
+ use_legacy_cache = not isinstance(past_key_values, Cache)
995
+ if use_legacy_cache:
996
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
997
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
998
+
999
+ if position_ids is None:
1000
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1001
+ position_ids = torch.arange(
1002
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1003
+ )
1004
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1005
+ else:
1006
+ position_ids = position_ids.view(-1, seq_length).long()
1007
+
1008
+ if inputs_embeds is None:
1009
+ inputs_embeds = self.embed_tokens(input_ids)
1010
+
1011
+ # prompt token
1012
+ if self.prompts_token_len > 0:
1013
+ inputs_PT = self.prompts[0].repeat(inputs_embeds.size(0), 1, 1).to(inputs_embeds.device).to(inputs_embeds.dtype)
1014
+ inputs_embeds = torch.cat((inputs_PT,inputs_embeds), dim=1)
1015
+
1016
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
1017
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1018
+ if is_padding_right:
1019
+ raise ValueError(
1020
+ "You are attempting to perform batched generation with padding_side='right'"
1021
+ " this may lead to unexpected behaviour for Flash Attention version of Qwen2. Make sure to "
1022
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1023
+ )
1024
+
1025
+ if self._attn_implementation == "flash_attention_2":
1026
+ # 2d mask is passed through the layers
1027
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1028
+ elif self._attn_implementation == "sdpa" and not output_attentions:
1029
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1030
+ # the manual implementation that requires a 4D causal mask in all cases.
1031
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1032
+ attention_mask,
1033
+ (batch_size, seq_length),
1034
+ inputs_embeds,
1035
+ past_key_values_length,
1036
+ sliding_window=self.config.sliding_window,
1037
+ )
1038
+ else:
1039
+ # 4d mask is passed through the layers
1040
+ attention_mask = _prepare_4d_causal_attention_mask(
1041
+ attention_mask,
1042
+ (batch_size, seq_length),
1043
+ inputs_embeds,
1044
+ past_key_values_length,
1045
+ sliding_window=self.config.sliding_window,
1046
+ )
1047
+
1048
+ hidden_states = inputs_embeds
1049
+
1050
+ # decoder layers
1051
+ all_hidden_states = () if output_hidden_states else None
1052
+ all_self_attns = () if output_attentions else None
1053
+ next_decoder_cache = None
1054
+
1055
+ for idx, decoder_layer in enumerate(self.layers):
1056
+ if self.prompts_token_len > 0:
1057
+ # hidden_states[:, :self.prompts_token_len, :] = self.prompts[idx].repeat(inputs_embeds.size(0),1, 1).to(hidden_states.device).to(hidden_states.dtype)
1058
+ hidden_states[:, :self.prompts_token_len, :] = self.prompts[idx].repeat(inputs_embeds.size(0),1, 1)
1059
+ if output_hidden_states:
1060
+ all_hidden_states += (hidden_states,)
1061
+
1062
+ if self.gradient_checkpointing and self.training:
1063
+ layer_outputs = self._gradient_checkpointing_func(
1064
+ decoder_layer.__call__,
1065
+ hidden_states,
1066
+ attention_mask,
1067
+ position_ids,
1068
+ past_key_values,
1069
+ output_attentions,
1070
+ use_cache,
1071
+ )
1072
+ else:
1073
+ layer_outputs = decoder_layer(
1074
+ hidden_states,
1075
+ attention_mask=attention_mask,
1076
+ position_ids=position_ids,
1077
+ past_key_value=past_key_values,
1078
+ output_attentions=output_attentions,
1079
+ use_cache=use_cache,
1080
+ )
1081
+
1082
+ hidden_states = layer_outputs[0]
1083
+
1084
+ if use_cache:
1085
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1086
+
1087
+ if output_attentions:
1088
+ all_self_attns += (layer_outputs[1],)
1089
+
1090
+ hidden_states = self.norm(hidden_states)
1091
+
1092
+ # add hidden states from the last decoder layer
1093
+ if output_hidden_states:
1094
+ all_hidden_states += (hidden_states,)
1095
+
1096
+ next_cache = None
1097
+ if use_cache:
1098
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1099
+
1100
+ if not return_dict:
1101
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1102
+ return BaseModelOutputWithPast(
1103
+ last_hidden_state=hidden_states,
1104
+ past_key_values=next_cache,
1105
+ hidden_states=all_hidden_states,
1106
+ attentions=all_self_attns,
1107
+ )
1108
+
1109
+
1110
+ class Qwen2ForCausalLM(Qwen2PreTrainedModel):
1111
+ _tied_weights_keys = ["lm_head.weight"]
1112
+
1113
+ def __init__(self, config):
1114
+ super().__init__(config)
1115
+ self.model = Qwen2Model(config)
1116
+ self.vocab_size = config.vocab_size
1117
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1118
+
1119
+ # Initialize weights and apply final processing
1120
+ self.post_init()
1121
+
1122
+ def get_input_embeddings(self):
1123
+ return self.model.embed_tokens
1124
+
1125
+ def set_input_embeddings(self, value):
1126
+ self.model.embed_tokens = value
1127
+
1128
+ def get_output_embeddings(self):
1129
+ return self.lm_head
1130
+
1131
+ def set_output_embeddings(self, new_embeddings):
1132
+ self.lm_head = new_embeddings
1133
+
1134
+ def set_decoder(self, decoder):
1135
+ self.model = decoder
1136
+
1137
+ def get_decoder(self):
1138
+ return self.model
1139
+
1140
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1141
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1142
+ def forward(
1143
+ self,
1144
+ input_ids: torch.LongTensor = None,
1145
+ attention_mask: Optional[torch.Tensor] = None,
1146
+ position_ids: Optional[torch.LongTensor] = None,
1147
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1148
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1149
+ labels: Optional[torch.LongTensor] = None,
1150
+ use_cache: Optional[bool] = None,
1151
+ output_attentions: Optional[bool] = None,
1152
+ output_hidden_states: Optional[bool] = None,
1153
+ return_dict: Optional[bool] = None,
1154
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1155
+ r"""
1156
+ Args:
1157
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1158
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1159
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1160
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1161
+
1162
+ Returns:
1163
+
1164
+ Example:
1165
+
1166
+ ```python
1167
+ >>> from transformers import AutoTokenizer, Qwen2ForCausalLM
1168
+
1169
+ >>> model = Qwen2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1170
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1171
+
1172
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1173
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1174
+
1175
+ >>> # Generate
1176
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1177
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1178
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1179
+ ```"""
1180
+
1181
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1182
+ output_hidden_states = (
1183
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1184
+ )
1185
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1186
+
1187
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1188
+ outputs = self.model(
1189
+ input_ids=input_ids,
1190
+ attention_mask=attention_mask,
1191
+ position_ids=position_ids,
1192
+ past_key_values=past_key_values,
1193
+ inputs_embeds=inputs_embeds,
1194
+ use_cache=use_cache,
1195
+ output_attentions=output_attentions,
1196
+ output_hidden_states=output_hidden_states,
1197
+ return_dict=return_dict,
1198
+ )
1199
+
1200
+ hidden_states = outputs[0]
1201
+ logits = self.lm_head(hidden_states)
1202
+ logits = logits.float()
1203
+
1204
+ loss = None
1205
+ if labels is not None:
1206
+ # Shift so that tokens < n predict n
1207
+ shift_logits = logits[..., :-1, :].contiguous()
1208
+ shift_labels = labels[..., 1:].contiguous()
1209
+ # Flatten the tokens
1210
+ loss_fct = CrossEntropyLoss()
1211
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1212
+ shift_labels = shift_labels.view(-1)
1213
+ # Enable model parallelism
1214
+ shift_labels = shift_labels.to(shift_logits.device)
1215
+ loss = loss_fct(shift_logits, shift_labels)
1216
+
1217
+ if not return_dict:
1218
+ output = (logits,) + outputs[1:]
1219
+ return (loss,) + output if loss is not None else output
1220
+
1221
+ return CausalLMOutputWithPast(
1222
+ loss=loss,
1223
+ logits=logits,
1224
+ past_key_values=outputs.past_key_values,
1225
+ hidden_states=outputs.hidden_states,
1226
+ attentions=outputs.attentions,
1227
+ )
1228
+
1229
+ def prepare_inputs_for_generation(
1230
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1231
+ ):
1232
+ # Omit tokens covered by past_key_values
1233
+ if past_key_values is not None:
1234
+ if isinstance(past_key_values, Cache):
1235
+ cache_length = past_key_values.get_seq_length()
1236
+ past_length = past_key_values.seen_tokens
1237
+ max_cache_length = past_key_values.get_max_length()
1238
+ else:
1239
+ cache_length = past_length = past_key_values[0][0].shape[2]
1240
+ max_cache_length = None
1241
+
1242
+ # Keep only the unprocessed tokens:
1243
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1244
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1245
+ # input)
1246
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1247
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1248
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1249
+ # input_ids based on the past_length.
1250
+ elif past_length < input_ids.shape[1]:
1251
+ input_ids = input_ids[:, past_length:]
1252
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1253
+
1254
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1255
+ if (
1256
+ max_cache_length is not None
1257
+ and attention_mask is not None
1258
+ and cache_length + input_ids.shape[1] > max_cache_length
1259
+ ):
1260
+ attention_mask = attention_mask[:, -max_cache_length:]
1261
+
1262
+ position_ids = kwargs.get("position_ids", None)
1263
+ if attention_mask is not None and position_ids is None:
1264
+ # create position_ids on the fly for batch generation
1265
+ position_ids = attention_mask.long().cumsum(-1) - 1
1266
+ position_ids.masked_fill_(attention_mask == 0, 1)
1267
+ if past_key_values:
1268
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1269
+
1270
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1271
+ if inputs_embeds is not None and past_key_values is None:
1272
+ model_inputs = {"inputs_embeds": inputs_embeds}
1273
+ else:
1274
+ model_inputs = {"input_ids": input_ids}
1275
+
1276
+ model_inputs.update(
1277
+ {
1278
+ "position_ids": position_ids,
1279
+ "past_key_values": past_key_values,
1280
+ "use_cache": kwargs.get("use_cache"),
1281
+ "attention_mask": attention_mask,
1282
+ }
1283
+ )
1284
+ return model_inputs
1285
+
1286
+ @staticmethod
1287
+ def _reorder_cache(past_key_values, beam_idx):
1288
+ reordered_past = ()
1289
+ for layer_past in past_key_values:
1290
+ reordered_past += (
1291
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1292
+ )
1293
+ return reordered_past
1294
+
1295
+
1296
+ @add_start_docstrings(
1297
+ """
1298
+ The Qwen2 Model transformer with a sequence classification head on top (linear layer).
1299
+
1300
+ [`Qwen2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1301
+ (e.g. GPT-2) do.
1302
+
1303
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1304
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1305
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1306
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1307
+ each row of the batch).
1308
+ """,
1309
+ QWEN2_START_DOCSTRING,
1310
+ )
1311
+ class Qwen2ForSequenceClassification(Qwen2PreTrainedModel):
1312
+ def __init__(self, config):
1313
+ super().__init__(config)
1314
+ self.num_labels = config.num_labels
1315
+ self.model = Qwen2Model(config)
1316
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1317
+
1318
+ # Initialize weights and apply final processing
1319
+ self.post_init()
1320
+
1321
+ def get_input_embeddings(self):
1322
+ return self.model.embed_tokens
1323
+
1324
+ def set_input_embeddings(self, value):
1325
+ self.model.embed_tokens = value
1326
+
1327
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1328
+ def forward(
1329
+ self,
1330
+ input_ids: torch.LongTensor = None,
1331
+ attention_mask: Optional[torch.Tensor] = None,
1332
+ position_ids: Optional[torch.LongTensor] = None,
1333
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1334
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1335
+ labels: Optional[torch.LongTensor] = None,
1336
+ use_cache: Optional[bool] = None,
1337
+ output_attentions: Optional[bool] = None,
1338
+ output_hidden_states: Optional[bool] = None,
1339
+ return_dict: Optional[bool] = None,
1340
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1341
+ r"""
1342
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1343
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1344
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1345
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1346
+ """
1347
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1348
+
1349
+ transformer_outputs = self.model(
1350
+ input_ids,
1351
+ attention_mask=attention_mask,
1352
+ position_ids=position_ids,
1353
+ past_key_values=past_key_values,
1354
+ inputs_embeds=inputs_embeds,
1355
+ use_cache=use_cache,
1356
+ output_attentions=output_attentions,
1357
+ output_hidden_states=output_hidden_states,
1358
+ return_dict=return_dict,
1359
+ )
1360
+ hidden_states = transformer_outputs[0]
1361
+ logits = self.score(hidden_states)
1362
+
1363
+ if input_ids is not None:
1364
+ batch_size = input_ids.shape[0]
1365
+ else:
1366
+ batch_size = inputs_embeds.shape[0]
1367
+
1368
+ if self.config.pad_token_id is None and batch_size != 1:
1369
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1370
+ if self.config.pad_token_id is None:
1371
+ sequence_lengths = -1
1372
+ else:
1373
+ if input_ids is not None:
1374
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1375
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1376
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1377
+ sequence_lengths = sequence_lengths.to(logits.device)
1378
+ else:
1379
+ sequence_lengths = -1
1380
+
1381
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1382
+
1383
+ loss = None
1384
+ if labels is not None:
1385
+ labels = labels.to(logits.device)
1386
+ if self.config.problem_type is None:
1387
+ if self.num_labels == 1:
1388
+ self.config.problem_type = "regression"
1389
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1390
+ self.config.problem_type = "single_label_classification"
1391
+ else:
1392
+ self.config.problem_type = "multi_label_classification"
1393
+
1394
+ if self.config.problem_type == "regression":
1395
+ loss_fct = MSELoss()
1396
+ if self.num_labels == 1:
1397
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1398
+ else:
1399
+ loss = loss_fct(pooled_logits, labels)
1400
+ elif self.config.problem_type == "single_label_classification":
1401
+ loss_fct = CrossEntropyLoss()
1402
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1403
+ elif self.config.problem_type == "multi_label_classification":
1404
+ loss_fct = BCEWithLogitsLoss()
1405
+ loss = loss_fct(pooled_logits, labels)
1406
+ if not return_dict:
1407
+ output = (pooled_logits,) + transformer_outputs[1:]
1408
+ return ((loss,) + output) if loss is not None else output
1409
+
1410
+ return SequenceClassifierOutputWithPast(
1411
+ loss=loss,
1412
+ logits=pooled_logits,
1413
+ past_key_values=transformer_outputs.past_key_values,
1414
+ hidden_states=transformer_outputs.hidden_states,
1415
+ attentions=transformer_outputs.attentions,
1416
+ )
models/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
models/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
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ gradio==5.42.0
2
+ accelerate==1.6.0
3
+ torch==2.6.0
4
+ numpy==2.2.4
5
+ transformers==4.40.1
6
+ matplotlib==3.10.1
7
+ safetensors==0.5.3
8
+ pillow==11.1.0
runtime.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ python-3.10.16