travis-xia commited on
Commit
cc4a3bc
·
verified ·
1 Parent(s): f614327

Upload folder using huggingface_hub

Browse files
.ipynb_checkpoints/config-checkpoint.json ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/inspire/hdd/ws-f4d69b29-e0a5-44e6-bd92-acf4de9990f0/public-project/xiacheng-240108120111/new_VideoChat-Flash-Qwen2_5-7B-1M_res224/videochat_flash-2_128",
3
+ "architectures": [
4
+ "VideoChatFlashQwenForCausalLM"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "auto_map": {
9
+ "AutoConfig": "modeling_videochat_flash.VideoChatFlashQwenConfig",
10
+ "AutoModel": "modeling_videochat_flash.VideoChatFlashQwenForCausalLM"
11
+ },
12
+ "bos_token_id": 151643,
13
+ "dual_chunk_attention_config": {
14
+ "chunk_size": 262144,
15
+ "local_size": 8192,
16
+ "original_max_position_embeddings": 262144
17
+ },
18
+ "eos_token_id": 151645,
19
+ "frame_aspect_ratio": "square",
20
+ "frame_grid_pinpoints": null,
21
+ "hidden_act": "silu",
22
+ "hidden_size": 3584,
23
+ "image_aspect_ratio": "anyres_nopad",
24
+ "image_crop_resolution": null,
25
+ "image_grid_pinpoints": [
26
+ [
27
+ 224,
28
+ 224
29
+ ],
30
+ [
31
+ 224,
32
+ 448
33
+ ],
34
+ [
35
+ 224,
36
+ 672
37
+ ],
38
+ [
39
+ 224,
40
+ 896
41
+ ],
42
+ [
43
+ 224,
44
+ 1120
45
+ ],
46
+ [
47
+ 224,
48
+ 1344
49
+ ],
50
+ [
51
+ 448,
52
+ 224
53
+ ],
54
+ [
55
+ 448,
56
+ 448
57
+ ],
58
+ [
59
+ 448,
60
+ 672
61
+ ],
62
+ [
63
+ 448,
64
+ 896
65
+ ],
66
+ [
67
+ 448,
68
+ 1120
69
+ ],
70
+ [
71
+ 448,
72
+ 1344
73
+ ],
74
+ [
75
+ 672,
76
+ 224
77
+ ],
78
+ [
79
+ 672,
80
+ 448
81
+ ],
82
+ [
83
+ 672,
84
+ 672
85
+ ],
86
+ [
87
+ 672,
88
+ 896
89
+ ],
90
+ [
91
+ 672,
92
+ 1120
93
+ ],
94
+ [
95
+ 672,
96
+ 1344
97
+ ],
98
+ [
99
+ 896,
100
+ 224
101
+ ],
102
+ [
103
+ 896,
104
+ 448
105
+ ],
106
+ [
107
+ 896,
108
+ 672
109
+ ],
110
+ [
111
+ 896,
112
+ 896
113
+ ],
114
+ [
115
+ 896,
116
+ 1120
117
+ ],
118
+ [
119
+ 896,
120
+ 1344
121
+ ],
122
+ [
123
+ 1120,
124
+ 224
125
+ ],
126
+ [
127
+ 1120,
128
+ 448
129
+ ],
130
+ [
131
+ 1120,
132
+ 672
133
+ ],
134
+ [
135
+ 1120,
136
+ 896
137
+ ],
138
+ [
139
+ 1120,
140
+ 1120
141
+ ],
142
+ [
143
+ 1120,
144
+ 1344
145
+ ],
146
+ [
147
+ 1344,
148
+ 224
149
+ ],
150
+ [
151
+ 1344,
152
+ 448
153
+ ],
154
+ [
155
+ 1344,
156
+ 672
157
+ ],
158
+ [
159
+ 1344,
160
+ 896
161
+ ],
162
+ [
163
+ 1344,
164
+ 1120
165
+ ],
166
+ [
167
+ 1344,
168
+ 1344
169
+ ]
170
+ ],
171
+ "image_split_resolution": null,
172
+ "initializer_range": 0.02,
173
+ "intermediate_size": 18944,
174
+ "llm_compress_layer_list": [
175
+ 8,
176
+ 16,
177
+ 24
178
+ ],
179
+ "llm_compress_type": "attention",
180
+ "llm_image_token_ratio_list": [
181
+ 1.0,
182
+ 0.5,
183
+ 0.25,
184
+ 0.125
185
+ ],
186
+ "max_num_pixels": 14745600000,
187
+ "max_position_embeddings": 32000,
188
+ "max_window_layers": 28,
189
+ "min_slow_num_frames": 4,
190
+ "mm_close_init": false,
191
+ "mm_hidden_size": 1024,
192
+ "mm_llm_compress": false,
193
+ "mm_local_num_frames": 4,
194
+ "mm_newline_position": "nothing",
195
+ "mm_num_compress_latents": 128,
196
+ "mm_num_compress_query_type": "learnable",
197
+ "mm_patch_merge_type": "spatial_nopad",
198
+ "mm_pos_num_frames": 8,
199
+ "mm_projector_lr": null,
200
+ "mm_projector_type": "tome16_mlp_hd64",
201
+ "mm_resampler_type": null,
202
+ "mm_spatial_pool_mode": "bilinear",
203
+ "mm_tunable_parts": "mm_vision_tower,mm_mlp_adapter,mm_language_model",
204
+ "mm_use_im_patch_token": false,
205
+ "mm_use_im_start_end": false,
206
+ "mm_vision_select_feature": "patch",
207
+ "mm_vision_select_layer": -2,
208
+ "mm_vision_tower": "umt-large",
209
+ "mm_vision_tower_lr": 2e-06,
210
+ "model_type": "videochat_flash_qwen",
211
+ "num_attention_heads": 28,
212
+ "num_hidden_layers": 28,
213
+ "num_key_value_heads": 4,
214
+ "pos_skipping_range": 4096,
215
+ "rms_norm_eps": 1e-05,
216
+ "rope_scaling": null,
217
+ "rope_theta": 10000000.0,
218
+ "sliding_window": 32768,
219
+ "tie_word_embeddings": false,
220
+ "tokenizer_model_max_length": 32768,
221
+ "tokenizer_padding_side": "right",
222
+ "torch_dtype": "bfloat16",
223
+ "transformers_version": "4.39.2",
224
+ "use_cache": true,
225
+ "use_mm_proj": true,
226
+ "use_pos_skipping": false,
227
+ "use_sliding_window": false,
228
+ "vision_encode_type": "video_image",
229
+ "vision_tower_pretrained": null,
230
+ "vocab_size": 152064
231
+ }
.ipynb_checkpoints/mm_utils-checkpoint.py ADDED
@@ -0,0 +1,855 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image
2
+ from io import BytesIO
3
+ import base64
4
+ import math
5
+ import ast
6
+ import re
7
+ import torch
8
+ from transformers import StoppingCriteria
9
+ from .constants import IMAGE_TOKEN_INDEX
10
+ import random
11
+ import os
12
+ import io
13
+ import av
14
+ import cv2
15
+ import imageio
16
+ from decord import VideoReader
17
+ import numpy as np
18
+ from torchvision.transforms.functional import pil_to_tensor
19
+
20
+
21
+ ######################## load video ########################
22
+
23
+ def get_index(num_frames, num_segments):
24
+ seg_size = float(num_frames - 1) / num_segments
25
+ start = int(seg_size / 2)
26
+ offsets = np.array([
27
+ start + int(np.round(seg_size * idx)) for idx in range(num_segments)
28
+ ])
29
+ return offsets
30
+
31
+
32
+ def pts_to_secs(pts: int, time_base: float, start_pts: int) -> float:
33
+ """
34
+ Converts a present time with the given time base and start_pts offset to seconds.
35
+
36
+ Returns:
37
+ time_in_seconds (float): The corresponding time in seconds.
38
+
39
+ https://github.com/facebookresearch/pytorchvideo/blob/main/pytorchvideo/data/utils.py#L54-L64
40
+ """
41
+ if pts == math.inf:
42
+ return math.inf
43
+
44
+ return int(pts - start_pts) * time_base
45
+
46
+
47
+ def get_pyav_video_duration(video_reader):
48
+ video_stream = video_reader.streams.video[0]
49
+ video_duration = pts_to_secs(
50
+ video_stream.duration,
51
+ video_stream.time_base,
52
+ video_stream.start_time
53
+ )
54
+ return float(video_duration)
55
+
56
+
57
+
58
+ def get_frame_indices(num_frames, vlen, sample='middle', fix_start=None, input_fps=1, min_num_frames=1, max_num_frames=-1, local_num_frames=8):
59
+
60
+ if min_num_frames > vlen:
61
+ if sample == 'dynamic_fps1':
62
+ min_num_frames = (vlen // local_num_frames) * local_num_frames
63
+ else:
64
+ min_num_frames = vlen
65
+
66
+
67
+ if sample == 'dynamic_fps1':
68
+
69
+ duration = float(vlen) / input_fps
70
+ num_segments = int(duration // local_num_frames)
71
+ if num_segments == 0:
72
+ num_frames = local_num_frames
73
+ else:
74
+ num_frames = local_num_frames * num_segments
75
+
76
+ if max_num_frames > 0:
77
+ num_frames = min(num_frames, max_num_frames)
78
+ sample = "middle" # NOTE
79
+
80
+ # logger.info(f"? is OK (img), duation={duration} frames={num_frames}!!!!")
81
+
82
+ num_frames = max(min_num_frames, num_frames)
83
+
84
+ # print(f"\033[0;31m vlen={vlen}, input_fps={input_fps} num_frames={num_frames} \033[0m")
85
+
86
+ if sample in ["rand", "middle"]: # uniform sampling
87
+ acc_samples = min(num_frames, vlen)
88
+ # split the video into `acc_samples` intervals, and sample from each interval.
89
+ intervals = np.linspace(start=0, stop=vlen, num=acc_samples + 1).astype(int)
90
+ ranges = []
91
+ for idx, interv in enumerate(intervals[:-1]):
92
+ ranges.append((interv, intervals[idx + 1] - 1))
93
+ if sample == 'rand':
94
+ try:
95
+ frame_indices = [random.choice(range(x[0], x[1])) for x in ranges]
96
+ except:
97
+ frame_indices = np.random.permutation(vlen)[:acc_samples]
98
+ frame_indices.sort()
99
+ frame_indices = list(frame_indices)
100
+ elif fix_start is not None:
101
+ frame_indices = [x[0] + fix_start for x in ranges]
102
+ elif sample == 'middle':
103
+ frame_indices = [(x[0] + x[1]) // 2 for x in ranges]
104
+ else:
105
+ raise NotImplementedError
106
+
107
+ if len(frame_indices) < num_frames: # padded with last frame
108
+ padded_frame_indices = [frame_indices[-1]] * num_frames
109
+ padded_frame_indices[:len(frame_indices)] = frame_indices
110
+ frame_indices = padded_frame_indices
111
+ elif "fps" in sample: # fps0.5, sequentially sample frames at 0.5 fps
112
+ output_fps = float(sample[3:])
113
+ duration = float(vlen) / input_fps
114
+ delta = 1 / output_fps # gap between frames, this is also the clip length each frame represents
115
+ frame_seconds = np.arange(0 + delta / 2, duration + delta / 2, delta)
116
+ frame_indices = np.around(frame_seconds * input_fps).astype(int)
117
+ frame_indices = [e for e in frame_indices if e < vlen]
118
+ if max_num_frames > 0 and len(frame_indices) > max_num_frames:
119
+ frame_indices = frame_indices[:max_num_frames]
120
+ # frame_indices = np.linspace(0 + delta / 2, duration + delta / 2, endpoint=False, num=max_num_frames)
121
+ else:
122
+ raise ValueError(f"Not support sample type: {sample}")
123
+
124
+
125
+ return frame_indices
126
+
127
+
128
+ def read_frames_av(video_path, num_frames, sample='rand', client=None, fix_start=None, min_num_frames=1, max_num_frames=-1, clip=None, local_num_frames=8):
129
+ if clip is not None:
130
+ raise NotImplementedError("av don't support clip!!!")
131
+ if 's3://' in video_path:
132
+ video_bytes = client.get(video_path)
133
+ byteio = io.BytesIO(video_bytes)
134
+ byteio.seek(0)
135
+ reader = av.open(byteio)
136
+ else:
137
+ byteio = None
138
+ reader = av.open(video_path)
139
+ frames = [f.to_rgb().to_ndarray() for f in reader.decode(video=0)]
140
+ vlen = len(frames)
141
+ duration = get_pyav_video_duration(reader)
142
+ fps = vlen / float(duration)
143
+ frame_indices = get_frame_indices(
144
+ num_frames, vlen, sample=sample, fix_start=fix_start,
145
+ input_fps=fps, min_num_frames=min_num_frames, max_num_frames=max_num_frames, local_num_frames=local_num_frames
146
+ )
147
+ frames = np.stack([frames[idx] for idx in frame_indices]) # (T, H, W, C), torch.uint8
148
+ # frames = frames.permute(0, 3, 1, 2) # (T, C, H, W), torch.uint8
149
+ if byteio != None:
150
+ byteio.close()
151
+
152
+ reader.close()
153
+
154
+ return frames, frame_indices, float(fps), duration
155
+
156
+
157
+ def read_frames_gif(
158
+ video_path, num_frames, sample='rand', fix_start=None,
159
+ min_num_frames=1, max_num_frames=-1, client=None, clip=None, local_num_frames=8
160
+ ):
161
+ if clip is not None:
162
+ raise NotImplementedError("Gif don't support clip!!!")
163
+ if 's3://' in video_path:
164
+ video_bytes = client.get(video_path)
165
+ byteio = io.BytesIO(video_bytes)
166
+ gif = imageio.get_reader(byteio)
167
+ else:
168
+ byteio = None
169
+ gif = imageio.get_reader(video_path)
170
+ vlen = len(gif)
171
+ fps = 1.
172
+ duration = vlen / fps
173
+ frame_indices = get_frame_indices(
174
+ num_frames, vlen, sample=sample, fix_start=fix_start,
175
+ min_num_frames=min_num_frames,
176
+ max_num_frames=max_num_frames, local_num_frames=local_num_frames,
177
+ input_fps=fps
178
+ )
179
+ frames = []
180
+
181
+ min_h = min_w = 100000
182
+ hw_set = set()
183
+ for index, frame in enumerate(gif):
184
+ # for index in frame_idxs:
185
+ if index in frame_indices:
186
+ frame = cv2.cvtColor(frame, cv2.COLOR_RGBA2RGB)
187
+ frame = frame.astype(np.uint8)
188
+ # # (H x W x C) to (C x H x W)
189
+ # frame = frame.permute(2, 0, 1)
190
+ frames.append(frame)
191
+ hw_set.add(frame.shape)
192
+ if frame.shape[0] < min_h:
193
+ min_h = frame.shape[0]
194
+ if frame.shape[1] < min_w:
195
+ min_w = frame.shape[1]
196
+ # print(hw_set, min_h, min_w)
197
+ if len(hw_set) > 1:
198
+ frames = [i[:min_h, :min_w] for i in frames]
199
+
200
+ frames = np.stack(frames) # .float() / 255
201
+
202
+ if byteio != None:
203
+ byteio.close()
204
+
205
+ return frames, frame_indices, float(fps), duration # for tgif
206
+
207
+
208
+
209
+ def read_frames_decord(
210
+ video_path, num_frames, sample='rand', fix_start=None, min_num_frames=1,
211
+ max_num_frames=-1, client=None, clip=None, local_num_frames=8
212
+ ):
213
+
214
+ if video_path.endswith('.avi'):
215
+ return read_frames_av(video_path=video_path, num_frames=num_frames, sample=sample,
216
+ fix_start=fix_start, min_num_frames=min_num_frames, max_num_frames=max_num_frames,
217
+ client=client, clip=clip, local_num_frames=local_num_frames)
218
+ if 's3://' in video_path:
219
+ video_bytes = client.get(video_path)
220
+ if video_bytes is None or len(video_bytes) == 0:
221
+ raise ValueError(f"Can't read byte from {video_path}!")
222
+ byteio = io.BytesIO(video_bytes)
223
+ video_reader = VideoReader(byteio, num_threads=1)
224
+ else:
225
+ byteio = None
226
+ video_reader = VideoReader(video_path, num_threads=1)
227
+ vlen = len(video_reader)
228
+ fps = video_reader.get_avg_fps()
229
+ duration = vlen / float(fps)
230
+
231
+
232
+ if clip:
233
+ start, end = clip
234
+ start = max(0, start)
235
+ end = min(duration - 0.1, end)
236
+ duration = end - start
237
+ vlen = int(duration * fps)
238
+ start_index = int(start * fps)
239
+
240
+ frame_indices = get_frame_indices(
241
+ num_frames, vlen, sample=sample, fix_start=fix_start,
242
+ input_fps=fps, min_num_frames=min_num_frames, max_num_frames=max_num_frames, local_num_frames=local_num_frames
243
+ )
244
+ if clip:
245
+ frame_indices = [f + start_index for f in frame_indices]
246
+
247
+ # print(fps, frame_indices)
248
+ frames = video_reader.get_batch(frame_indices).asnumpy() # (T, H, W, C), torch.uint8
249
+ # https://github.com/dmlc/decord/issues/208
250
+ video_reader.seek(0)
251
+
252
+ if byteio != None:
253
+ byteio.close()
254
+ # frames = frames.permute(0, 3, 1, 2) # (T, C, H, W), torch.uint8
255
+ return frames, frame_indices, float(fps), duration
256
+
257
+
258
+
259
+ def read_frames_img(
260
+ video_path, num_frames, sample='rand', fix_start=None, min_num_frames=1,
261
+ max_num_frames=-1, client=None, clip=None, local_num_frames=8
262
+ ):
263
+ def extract_frame_number(filename):
264
+ # Extract the numeric part from the filename using regular expressions
265
+ if filename.endswith('.jpg'):
266
+ match = re.search(r'_(\d+).jpg$', filename)
267
+ elif filename.endswith('.jpeg'):
268
+ match = re.search(r'_(\d+).jpeg$', filename)
269
+ elif filename.endswith('.png'):
270
+ match = re.search(r'_(\d+).png$', filename)
271
+ else:
272
+ raise NotImplementedError(f"Wrong filename: {filename}")
273
+
274
+ return int(match.group(1)) if match else -1
275
+
276
+
277
+ def sort_frames(frame_paths):
278
+ # Extract filenames from each path and sort by their numeric part
279
+ return sorted(frame_paths, key=lambda x: extract_frame_number(os.path.basename(x)))
280
+
281
+ # img_list=[]
282
+
283
+ if "s3://" in video_path:
284
+ img_list = sort_frames(client.list(video_path))
285
+ else:
286
+ img_list = sort_frames(list(os.listdir(video_path)))
287
+
288
+
289
+ if 'tvqa' in video_path.lower():
290
+ fps = 3.0
291
+ else:
292
+ fps = 1.0
293
+
294
+ if clip is not None:
295
+ start = float(clip[0])
296
+ end = float(clip[1])
297
+ start = max(0, start)
298
+ end = min(len(img_list) / fps, end)
299
+ vlen = (end - start) * fps
300
+ else:
301
+ vlen = len(img_list)
302
+
303
+ duration = vlen / fps
304
+
305
+ if min_num_frames > vlen:
306
+ if sample == 'dynamic_fps1':
307
+ min_num_frames = (vlen // local_num_frames) * local_num_frames
308
+ else:
309
+ min_num_frames = vlen
310
+
311
+ if sample == 'dynamic_fps1':
312
+ num_segments = int(duration // local_num_frames)
313
+ if num_segments == 0:
314
+ num_frames = local_num_frames
315
+ else:
316
+ num_frames = local_num_frames * num_segments
317
+ num_frames = min(num_frames, max_num_frames)
318
+ num_frames = max(min_num_frames, num_frames)
319
+
320
+ num_frames = int(num_frames)
321
+ if clip is not None:
322
+ def _get_index_by_time(start_sec, end_sec, num_segments=8, fps=1., max_frame=9999):
323
+ start_idx = max(1, round(start_sec * fps))
324
+ end_idx = min(round(end_sec * fps), max_frame)
325
+ seg_size = float(end_idx - start_idx) / (num_segments - 1)
326
+ offsets = np.array([start_idx + int(np.round(seg_size * idx)) for idx in range(num_segments)])
327
+ return offsets
328
+
329
+ frame_indices = _get_index_by_time(float(clip[0]), float(clip[1]), num_segments=num_frames, fps=fps, max_frame=len(img_list)-1)
330
+ else:
331
+ frame_indices = get_frame_indices(
332
+ num_frames, vlen, sample=sample, fix_start=fix_start,
333
+ min_num_frames=min_num_frames,
334
+ max_num_frames=max_num_frames, local_num_frames=local_num_frames
335
+ )
336
+
337
+ imgs = []
338
+ for idx in frame_indices:
339
+ frame_fname = os.path.join(video_path, img_list[idx])
340
+ if "s3://" in video_path:
341
+ img_bytes = client.get(frame_fname)
342
+ else:
343
+ with open(frame_fname, 'rb') as f:
344
+ img_bytes = f.read()
345
+ img_np = np.frombuffer(img_bytes, np.uint8)
346
+ img = cv2.imdecode(img_np, cv2.IMREAD_COLOR)
347
+ cv2.cvtColor(img, cv2.COLOR_BGR2RGB, img)
348
+ imgs.append(img)
349
+
350
+ frames = np.array(imgs, dtype=np.uint8)
351
+
352
+
353
+ return frames, frame_indices, fps, duration
354
+
355
+
356
+
357
+ VIDEO_READER_FUNCS = {
358
+ 'av': read_frames_av,
359
+ 'decord': read_frames_decord,
360
+ 'gif': read_frames_gif,
361
+ 'img': read_frames_img,
362
+ 'frame': read_frames_img
363
+ }
364
+
365
+
366
+
367
+ def load_video(video_path, max_num_frames=512, media_dict=None): #, media_dict):
368
+
369
+ if media_dict is None:
370
+ media_dict = {'video_read_type': 'decord'}
371
+
372
+ if type(video_path) != str:
373
+ assert len(video_path) == 1, video_path
374
+ video_path = video_path[0]
375
+
376
+ if 'start' in media_dict:
377
+ clip = [media_dict['start'], media_dict['end']]
378
+ else:
379
+ clip = None
380
+
381
+ if 's3://' in video_path:
382
+ from petrel_client.client import Client
383
+ client = Client(conf_path='~/petreloss.conf')
384
+ else:
385
+ client = None
386
+
387
+ frames, frame_indices, fps, duration = VIDEO_READER_FUNCS[media_dict['video_read_type']](video_path=video_path, num_frames=max_num_frames, sample='dynamic_fps1', fix_start=None, min_num_frames=64, max_num_frames=max_num_frames, client=client, clip=clip, local_num_frames=8)
388
+
389
+ sec = [str(round(f / fps, 1)) for f in frame_indices]
390
+
391
+ msg = f"\nThe video lasts for {duration:.2f} seconds, and {len(sec)} frames are uniformly sampled from it. "
392
+
393
+ return frames, msg
394
+
395
+
396
+ ######################## load video ########################
397
+
398
+
399
+ def resize_and_center_crop(image, shortest_edge_length):
400
+ # Calculate new dimensions and resize
401
+ aspect_ratio = float(image.width) / float(image.height)
402
+ if aspect_ratio > 1:
403
+ new_width = int(shortest_edge_length * aspect_ratio)
404
+ new_height = shortest_edge_length
405
+ else:
406
+ new_width = shortest_edge_length
407
+ new_height = int(shortest_edge_length / aspect_ratio)
408
+ resized_image = image.resize((new_width, new_height), Image.ANTIALIAS)
409
+
410
+ # Calculate the position and perform the center crop
411
+ left = (new_width - shortest_edge_length) / 2
412
+ top = (new_height - shortest_edge_length) / 2
413
+ right = (new_width + shortest_edge_length) / 2
414
+ bottom = (new_height + shortest_edge_length) / 2
415
+ cropped_image = resized_image.crop((left, top, right, bottom))
416
+
417
+ return cropped_image
418
+
419
+
420
+ def auto_pad_images(image, grid_params):
421
+ assert isinstance(image, Image.Image), "Input should be a Pillow Image"
422
+ assert len(grid_params) > 0, "Grid parameters should not be empty"
423
+
424
+ # Step 1: Calculate and find the closest aspect ratio
425
+ input_width, input_height = image.size
426
+ input_aspect_ratio = input_width / input_height
427
+ candidate_resolutions = [(w / h, w, h) for w in grid_params for h in grid_params]
428
+ closest_aspect_ratio = min(candidate_resolutions, key=lambda x: abs(input_aspect_ratio - x[0]))
429
+
430
+ candidate_resolutions = [(x[1], x[2]) for x in candidate_resolutions if abs(x[0] - closest_aspect_ratio[0]) < 1e-3]
431
+
432
+ target_resolution = min(candidate_resolutions, key=lambda res: abs(max(input_width, input_height) / max(res) - 1))
433
+
434
+ resize_width, resize_height = target_resolution
435
+ if input_width > input_height:
436
+ resize_height = int(resize_width / input_aspect_ratio)
437
+ else:
438
+ resize_width = int(resize_height * input_aspect_ratio)
439
+ resized_image = image.resize((resize_width, resize_height), Image.ANTIALIAS)
440
+
441
+ # Step 5: Pad the resized image if necessary to match the target resolution
442
+ pad_width = target_resolution[0] - resize_width
443
+ pad_height = target_resolution[1] - resize_height
444
+ padded_image = Image.new("RGB", target_resolution, color=(0, 0, 0))
445
+ padded_image.paste(resized_image, (pad_width // 2, pad_height // 2))
446
+
447
+ return padded_image
448
+
449
+
450
+ def extract_patches(image, patch_size, overlap_ratio):
451
+ assert isinstance(image, Image.Image), "Input should be a Pillow Image"
452
+ assert patch_size > 0, "Patch size should be greater than 0"
453
+ assert 0 <= overlap_ratio < 1, "Overlap ratio should be between 0 and 1"
454
+
455
+ W, H = image.size
456
+ patches = []
457
+
458
+ stride = int(patch_size * (1 - overlap_ratio))
459
+
460
+ num_patches_y = (H - patch_size) // stride + 1
461
+ num_patches_x = (W - patch_size) // stride + 1
462
+
463
+ y_start = (H - (num_patches_y - 1) * stride - patch_size) // 2
464
+ x_start = (W - (num_patches_x - 1) * stride - patch_size) // 2
465
+
466
+ for y in range(y_start, y_start + num_patches_y * stride, stride):
467
+ for x in range(x_start, x_start + num_patches_x * stride, stride):
468
+ patch = image.crop((x, y, x + patch_size, y + patch_size))
469
+ patches.append(patch)
470
+
471
+ return patches
472
+
473
+
474
+ def process_highres_image_crop_split(image, data_args, processor=None):
475
+ crop_resolution = data_args.image_crop_resolution
476
+ split_resolution = data_args.image_split_resolution
477
+ if processor is None:
478
+ processor = data_args.image_processor
479
+ image_crop = resize_and_center_crop(image, crop_resolution)
480
+ image_patches = extract_patches(image_crop, patch_size=split_resolution, overlap_ratio=0)
481
+ image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches]
482
+ return torch.stack(image_patches, dim=0)
483
+
484
+
485
+ def process_highres_image(image, processor, grid_pinpoints):
486
+ grid_params = [int(x) for x in grid_pinpoints.split(",")]
487
+ width_height = max(image.size)
488
+ fit_grid_params = [x for x in grid_params if x >= width_height]
489
+ if len(fit_grid_params) == 0:
490
+ select_size = max(grid_params)
491
+ else:
492
+ select_size = min(fit_grid_params)
493
+ # FIXME: always select the 448
494
+ select_size = max(grid_params)
495
+ image_padded = expand2square(image, tuple(int(x * 255) for x in processor.image_mean))
496
+
497
+ # FIXME: this seems to be a bug that it always resizes instead of padding
498
+ image_original_resize = image.resize((processor.size["shortest_edge"], processor.size["shortest_edge"]))
499
+ image_padded = image_padded.resize((select_size, select_size))
500
+ image_patches = extract_patches(image_padded, patch_size=processor.size["shortest_edge"], overlap_ratio=0)
501
+ image_patches = [image_original_resize] + image_patches
502
+ image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches]
503
+ return torch.stack(image_patches, dim=0)
504
+
505
+
506
+ def select_best_resolution(original_size, possible_resolutions, max_resolutions, patch_size):
507
+ """
508
+ Selects the best resolution from a list of possible resolutions based on the original size.
509
+
510
+ Args:
511
+ original_size (tuple): The original size of the image in the format (width, height).
512
+ possible_resolutions (list): A list of possible resolutions in the format [(width1, height1), (width2, height2), ...].
513
+
514
+ Returns:
515
+ tuple: The best fit resolution in the format (width, height).
516
+ """
517
+ original_width, original_height = original_size
518
+ best_fit = None
519
+ max_effective_resolution = 0
520
+ min_wasted_resolution = float("inf")
521
+
522
+ for width, height in possible_resolutions:
523
+ if max_resolutions != None and (width * height != patch_size * patch_size):
524
+ if (width * height+patch_size*patch_size) > max_resolutions: # NOTE 要算一个global
525
+ continue
526
+ # Calculate the downscaled size to keep the aspect ratio
527
+ scale = min(width / original_width, height / original_height)
528
+ downscaled_width, downscaled_height = int(original_width * scale), int(original_height * scale)
529
+
530
+ # Calculate effective and wasted resolutions
531
+ effective_resolution = min(downscaled_width * downscaled_height, original_width * original_height)
532
+ wasted_resolution = (width * height) - effective_resolution
533
+
534
+ if effective_resolution > max_effective_resolution or (effective_resolution == max_effective_resolution and wasted_resolution < min_wasted_resolution):
535
+ max_effective_resolution = effective_resolution
536
+ min_wasted_resolution = wasted_resolution
537
+ best_fit = (width, height)
538
+
539
+ # print(f"original_size={original_size}, possible_resolutions={possible_resolutions}, max_resolutions={max_resolutions}, best_fit={best_fit}")
540
+ assert best_fit is not None, f"Can't find suitable fit in {possible_resolutions} at max:{max_resolutions}"
541
+ return best_fit
542
+
543
+
544
+ def resize_and_pad_image(image, target_resolution):
545
+ """
546
+ Resize and pad an image to a target resolution while maintaining aspect ratio.
547
+
548
+ Args:
549
+ image (PIL.Image.Image): The input image.
550
+ target_resolution (tuple): The target resolution (width, height) of the image.
551
+
552
+ Returns:
553
+ PIL.Image.Image: The resized and padded image.
554
+ """
555
+ original_width, original_height = image.size
556
+ target_width, target_height = target_resolution
557
+
558
+ # Determine which dimension (width or height) to fill
559
+ scale_w = target_width / original_width
560
+ scale_h = target_height / original_height
561
+
562
+ if scale_w < scale_h:
563
+ # Width will be filled completely
564
+ new_width = target_width
565
+ new_height = min(math.ceil(original_height * scale_w), target_height)
566
+ else:
567
+ # Height will be filled completely
568
+ new_height = target_height
569
+ new_width = min(math.ceil(original_width * scale_h), target_width)
570
+
571
+ # Resize the image
572
+ resized_image = image.resize((new_width, new_height))
573
+
574
+ # Create a new image with the target size and paste the resized image onto it
575
+ new_image = Image.new("RGB", (target_width, target_height), (0, 0, 0))
576
+ paste_x = (target_width - new_width) // 2
577
+ paste_y = (target_height - new_height) // 2
578
+ new_image.paste(resized_image, (paste_x, paste_y))
579
+
580
+ return new_image
581
+
582
+
583
+ def divide_to_patches(image, patch_size):
584
+ """
585
+ Divides an image into patches of a specified size.
586
+
587
+ Args:
588
+ image (PIL.Image.Image): The input image.
589
+ patch_size (int): The size of each patch.
590
+
591
+ Returns:
592
+ list: A list of PIL.Image.Image objects representing the patches.
593
+ """
594
+ patches = []
595
+ width, height = image.size
596
+ for i in range(0, height, patch_size):
597
+ for j in range(0, width, patch_size):
598
+ box = (j, i, j + patch_size, i + patch_size)
599
+ patch = image.crop(box)
600
+ patches.append(patch)
601
+
602
+ return patches
603
+
604
+
605
+ def get_anyres_image_grid_shape(image_size, grid_pinpoints, patch_size, max_resolutions=None):
606
+ """
607
+ Calculate the shape of the image patch grid after the preprocessing for images of any resolution.
608
+
609
+ Args:
610
+ image_size (tuple): The size of the input image in the format (width, height).
611
+ grid_pinpoints (str): A string representation of a list of possible resolutions.
612
+ patch_size (int): The size of each image patch.
613
+
614
+ Returns:
615
+ tuple: The shape of the image patch grid in the format (width, height).
616
+ """
617
+ if isinstance(grid_pinpoints, str) and "x" in grid_pinpoints:
618
+ assert patch_size in [224, 336, 384, 448, 512], "patch_size should be in [224, 336, 384, 448, 512]"
619
+ # Use regex to extract the range from the input string
620
+ matches = re.findall(r"\((\d+)x(\d+)\)", grid_pinpoints)
621
+ range_start = tuple(map(int, matches[0]))
622
+ range_end = tuple(map(int, matches[-1]))
623
+ # Generate a matrix of tuples from (range_start[0], range_start[1]) to (range_end[0], range_end[1])
624
+ grid_pinpoints = [(i, j) for i in range(range_start[0], range_end[0] + 1) for j in range(range_start[1], range_end[1] + 1)]
625
+ # Multiply all elements by patch_size
626
+ grid_pinpoints = [[dim * patch_size for dim in pair] for pair in grid_pinpoints]
627
+ if type(grid_pinpoints) is list:
628
+ possible_resolutions = grid_pinpoints
629
+ else:
630
+ possible_resolutions = ast.literal_eval(grid_pinpoints)
631
+ width, height = select_best_resolution(image_size, possible_resolutions, max_resolutions=max_resolutions, patch_size=patch_size)
632
+
633
+ # print("get width/patch size", width, patch_size, flush=True)
634
+
635
+ return width // patch_size, height // patch_size
636
+
637
+
638
+ def process_anyres_image(image, processor, grid_pinpoints):
639
+ """
640
+ Process an image with variable resolutions.
641
+
642
+ Args:
643
+ image (PIL.Image.Image): The input image to be processed.
644
+ processor: The image processor object.
645
+ grid_pinpoints (str): A string representation of a list of possible resolutions.
646
+
647
+ Returns:
648
+ torch.Tensor: A tensor containing the processed image patches.
649
+ """
650
+ raise NotImplementedError
651
+ # Convert grid_pinpoints from string to list
652
+ if isinstance(grid_pinpoints, str) and "x" in grid_pinpoints:
653
+ try:
654
+ patch_size = processor.size[0]
655
+ except Exception as e:
656
+ patch_size = processor.size["shortest_edge"]
657
+ assert patch_size in [224, 336, 384, 448, 512], "patch_size should be in [224, 336, 384, 448, 512]"
658
+ # Use regex to extract the range from the input string
659
+ matches = re.findall(r"\((\d+)x(\d+)\)", grid_pinpoints)
660
+ range_start = tuple(map(int, matches[0]))
661
+ range_end = tuple(map(int, matches[-1]))
662
+ # Generate a matrix of tuples from (range_start[0], range_start[1]) to (range_end[0], range_end[1])
663
+ grid_pinpoints = [(i, j) for i in range(range_start[0], range_end[0] + 1) for j in range(range_start[1], range_end[1] + 1)]
664
+ # Multiply all elements by patch_size
665
+ grid_pinpoints = [[dim * patch_size for dim in pair] for pair in grid_pinpoints]
666
+
667
+ if type(grid_pinpoints) is list:
668
+ possible_resolutions = grid_pinpoints
669
+ else:
670
+ possible_resolutions = ast.literal_eval(grid_pinpoints)
671
+ best_resolution = select_best_resolution(image.size, possible_resolutions)
672
+ image_padded = resize_and_pad_image(image, best_resolution)
673
+
674
+ patches = divide_to_patches(image_padded, processor.crop_size["height"])
675
+
676
+ # FIXME: this seems to be a bug that it resizes instead of pad.
677
+ # but to keep it consistent with previous, i will keep it as it is
678
+ # TODO: uncomment below to ablate with the padding
679
+ if isinstance(processor.size, dict):
680
+ shortest_edge = processor.size["shortest_edge"]
681
+ else:
682
+ shortest_edge = min(processor.size)
683
+ image_original_resize = image.resize((shortest_edge, shortest_edge))
684
+ # image_padded_square = expand2square(image, tuple(int(x*255) for x in processor.image_mean))
685
+ # image_original_resize = image_padded_square.resize((processor.size['shortest_edge'], processor.size['shortest_edge']))
686
+
687
+ image_patches = [image_original_resize] + patches
688
+ image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches]
689
+
690
+ # print("image.size", image.size, "len(image_patches):", len(image_patches), "patch_size:", image_patches[0].shape)
691
+ return torch.stack(image_patches, dim=0)
692
+
693
+ def process_anyres_image_nopad(image, processor, grid_pinpoints):
694
+ """
695
+ Process an image with variable resolutions.
696
+
697
+ Args:
698
+ image (PIL.Image.Image): The input image to be processed.
699
+ processor: The image processor object.
700
+ grid_pinpoints (str): A string representation of a list of possible resolutions.
701
+
702
+ Returns:
703
+ torch.Tensor: A tensor containing the processed image patches.
704
+ """
705
+ # Convert grid_pinpoints from string to list
706
+ try:
707
+ patch_size = processor.size[0]
708
+ except Exception as e:
709
+ patch_size = processor.size["shortest_edge"]
710
+
711
+ assert patch_size in [224, 336, 384, 448, 512], "patch_size should be in [224, 336, 384, 448, 512]"
712
+
713
+ if isinstance(grid_pinpoints, str) and "x" in grid_pinpoints:
714
+
715
+ # Use regex to extract the range from the input string
716
+ matches = re.findall(r"\((\d+)x(\d+)\)", grid_pinpoints)
717
+ range_start = tuple(map(int, matches[0]))
718
+ range_end = tuple(map(int, matches[-1]))
719
+ # Generate a matrix of tuples from (range_start[0], range_start[1]) to (range_end[0], range_end[1])
720
+ grid_pinpoints = [(i, j) for i in range(range_start[0], range_end[0] + 1) for j in range(range_start[1], range_end[1] + 1)]
721
+ # Multiply all elements by patch_size
722
+ grid_pinpoints = [[dim * patch_size for dim in pair] for pair in grid_pinpoints]
723
+
724
+ if type(grid_pinpoints) is list:
725
+ possible_resolutions = grid_pinpoints
726
+ else:
727
+ possible_resolutions = ast.literal_eval(grid_pinpoints)
728
+ best_resolution = select_best_resolution(image.size, possible_resolutions, max_resolutions=None, patch_size=patch_size) # 目前图像无限制
729
+ # image_padded = resize_and_pad_image(image, best_resolution)
730
+
731
+ patches = divide_to_patches(image.resize(best_resolution), patch_size)
732
+
733
+ # FIXME: this seems to be a bug that it resizes instead of pad.
734
+ # but to keep it consistent with previous, i will keep it as it is
735
+ # TODO: uncomment below to ablate with the padding
736
+ if isinstance(processor.size, dict):
737
+ shortest_edge = processor.size["shortest_edge"]
738
+ else:
739
+ shortest_edge = min(processor.size)
740
+ image_original_resize = image.resize((shortest_edge, shortest_edge))
741
+ # image_padded_square = expand2square(image, tuple(int(x*255) for x in processor.image_mean))
742
+ # image_original_resize = image_padded_square.resize((processor.size['shortest_edge'], processor.size['shortest_edge']))
743
+
744
+ image_patches = [image_original_resize] + patches
745
+ image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches]
746
+
747
+ # raise ValueError(f"image.size: {image.size} len(image_patches): {len(image_patches)}, patch_size:, {image_patches[0].shape}, possible_resolutions:, {possible_resolutions}, best: {best_resolution}")
748
+ return torch.stack(image_patches, dim=0)
749
+
750
+
751
+ def load_image_from_base64(image):
752
+ return Image.open(BytesIO(base64.b64decode(image)))
753
+
754
+
755
+ def expand2square(pil_img, background_color):
756
+ width, height = pil_img.size
757
+ if width == height:
758
+ return pil_img
759
+ elif width > height:
760
+ result = Image.new(pil_img.mode, (width, width), background_color)
761
+ result.paste(pil_img, (0, (width - height) // 2))
762
+ return result
763
+ else:
764
+ result = Image.new(pil_img.mode, (height, height), background_color)
765
+ result.paste(pil_img, ((height - width) // 2, 0))
766
+ return result
767
+
768
+
769
+ def process_images(images, image_processor, model_cfg):
770
+ image_aspect_ratio = getattr(model_cfg, "image_aspect_ratio", None)
771
+ new_images = []
772
+ if image_aspect_ratio == "highres":
773
+ raise NotImplementedError
774
+ for image in images:
775
+ image = process_highres_image(image, image_processor, model_cfg.image_grid_pinpoints)
776
+ new_images.append(image)
777
+ elif "anyres" in image_aspect_ratio:
778
+ for image in images:
779
+ if "nopad" in image_aspect_ratio:
780
+ image = process_anyres_image_nopad(image, image_processor, model_cfg.image_grid_pinpoints)
781
+ else:
782
+ image = process_anyres_image(image, image_processor, model_cfg.image_grid_pinpoints)
783
+ new_images.append(image)
784
+ elif image_aspect_ratio == "crop_split":
785
+ raise NotImplementedError
786
+ for image in images:
787
+ image = process_highres_image_crop_split(image, model_cfg, image_processor)
788
+ new_images.append(image)
789
+ elif image_aspect_ratio == "pad":
790
+ for image in images:
791
+ image = expand2square(image, tuple(int(x * 255) for x in image_processor.image_mean))
792
+ image = image_processor.preprocess(image, return_tensors="pt")["pixel_values"][0]
793
+ new_images.append(image)
794
+ else:
795
+ return image_processor.preprocess(images, return_tensors="pt")["pixel_values"]
796
+ if all(x.shape == new_images[0].shape for x in new_images):
797
+ new_images = torch.stack(new_images, dim=0)
798
+ return new_images
799
+
800
+
801
+ def tokenizer_image_token(prompt, tokenizer, image_token_index=IMAGE_TOKEN_INDEX, return_tensors=None):
802
+ prompt_chunks = [tokenizer(chunk).input_ids for chunk in prompt.split("<image>")]
803
+
804
+ def insert_separator(X, sep):
805
+ return [ele for sublist in zip(X, [sep] * len(X)) for ele in sublist][:-1]
806
+
807
+ input_ids = []
808
+ offset = 0
809
+ if len(prompt_chunks) > 0 and len(prompt_chunks[0]) > 0 and prompt_chunks[0][0] == tokenizer.bos_token_id:
810
+ offset = 1
811
+ input_ids.append(prompt_chunks[0][0])
812
+
813
+ for x in insert_separator(prompt_chunks, [image_token_index] * (offset + 1)):
814
+ input_ids.extend(x[offset:])
815
+
816
+ if return_tensors is not None:
817
+ if return_tensors == "pt":
818
+ return torch.tensor(input_ids, dtype=torch.long)
819
+ raise ValueError(f"Unsupported tensor type: {return_tensors}")
820
+ return input_ids
821
+
822
+
823
+ def get_model_name_from_path(model_path):
824
+ model_path = model_path.strip("/")
825
+ model_paths = model_path.split("/")
826
+ if model_paths[-1].startswith("checkpoint-"):
827
+ return model_paths[-2] + "_" + model_paths[-1]
828
+ else:
829
+ return model_paths[-1]
830
+
831
+
832
+ class KeywordsStoppingCriteria(StoppingCriteria):
833
+ def __init__(self, keywords, tokenizer, input_ids):
834
+ self.keywords = keywords
835
+ self.keyword_ids = []
836
+ for keyword in keywords:
837
+ cur_keyword_ids = tokenizer(keyword).input_ids
838
+ if len(cur_keyword_ids) > 1 and cur_keyword_ids[0] == tokenizer.bos_token_id:
839
+ cur_keyword_ids = cur_keyword_ids[1:]
840
+ self.keyword_ids.append(torch.tensor(cur_keyword_ids))
841
+ self.tokenizer = tokenizer
842
+ self.start_len = input_ids.shape[1]
843
+
844
+ def __call__(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
845
+ assert output_ids.shape[0] == 1, "Only support batch size 1 (yet)" # TODO
846
+ offset = min(output_ids.shape[1] - self.start_len, 3)
847
+ self.keyword_ids = [keyword_id.to(output_ids.device) for keyword_id in self.keyword_ids]
848
+ for keyword_id in self.keyword_ids:
849
+ if output_ids[0, -keyword_id.shape[0] :] == keyword_id:
850
+ return True
851
+ outputs = self.tokenizer.batch_decode(output_ids[:, -offset:], skip_special_tokens=True)[0]
852
+ for keyword in self.keywords:
853
+ if keyword in outputs:
854
+ return True
855
+ return False
.ipynb_checkpoints/modeling_qwen2_flash-checkpoint.py ADDED
@@ -0,0 +1,1611 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # transformers==4.39.2 NOTE
3
+ # Borrows some implementations from https://github.com/Cooperx521/PyramidDrop, thanks!
4
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
5
+ #
6
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
7
+ # and OPT implementations in this library. It has been modified from its
8
+ # original forms to accommodate minor architectural differences compared
9
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
10
+ #
11
+ # Licensed under the Apache License, Version 2.0 (the "License");
12
+ # you may not use this file except in compliance with the License.
13
+ # You may obtain a copy of the License at
14
+ #
15
+ # http://www.apache.org/licenses/LICENSE-2.0
16
+ #
17
+ # Unless required by applicable law or agreed to in writing, software
18
+ # distributed under the License is distributed on an "AS IS" BASIS,
19
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
+ # See the License for the specific language governing permissions and
21
+ # limitations under the License.
22
+ """ PyTorch Qwen2 model."""
23
+ import inspect
24
+ import math
25
+ import warnings
26
+ from typing import List, Optional, Tuple, Union
27
+
28
+ import torch
29
+ import torch.nn.functional as F
30
+ import torch.utils.checkpoint
31
+ from torch import nn
32
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
33
+
34
+ from transformers.activations import ACT2FN
35
+ from transformers.cache_utils import Cache, DynamicCache
36
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa
37
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
38
+ from transformers.modeling_utils import PreTrainedModel
39
+ from transformers.utils import (
40
+ add_start_docstrings,
41
+ add_start_docstrings_to_model_forward,
42
+ is_flash_attn_2_available,
43
+ is_flash_attn_greater_or_equal_2_10,
44
+ logging,
45
+ replace_return_docstrings,
46
+ )
47
+ from transformers.models.qwen2.configuration_qwen2 import Qwen2Config
48
+ from .constants import IGNORE_INDEX
49
+
50
+
51
+ if is_flash_attn_2_available():
52
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
53
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
54
+
55
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
56
+
57
+
58
+ logger = logging.get_logger(__name__)
59
+
60
+
61
+ _CHECKPOINT_FOR_DOC = "Qwen/Qwen2-7B-beta"
62
+ _CONFIG_FOR_DOC = "Qwen2Config"
63
+
64
+ QWEN2_PRETRAINED_MODEL_ARCHIVE_LIST = [
65
+ "Qwen/Qwen2-7B-beta",
66
+ # See all Qwen2 models at https://huggingface.co/models?filter=qwen2
67
+ ]
68
+
69
+
70
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
71
+ def _get_unpad_data(attention_mask):
72
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
73
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
74
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
75
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
76
+ return (
77
+ indices,
78
+ cu_seqlens,
79
+ max_seqlen_in_batch,
80
+ )
81
+
82
+
83
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Qwen2
84
+ class Qwen2RMSNorm(nn.Module):
85
+ def __init__(self, hidden_size, eps=1e-6):
86
+ """
87
+ Qwen2RMSNorm is equivalent to T5LayerNorm
88
+ """
89
+ super().__init__()
90
+ self.weight = nn.Parameter(torch.ones(hidden_size))
91
+ self.variance_epsilon = eps
92
+
93
+ def forward(self, hidden_states):
94
+ input_dtype = hidden_states.dtype
95
+ hidden_states = hidden_states.to(torch.float32)
96
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
97
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
98
+ return self.weight * hidden_states.to(input_dtype)
99
+
100
+
101
+ # Copied from transformers.models.mistral.modeling_mistral.MistralRotaryEmbedding with Mistral->Qwen2
102
+ class Qwen2RotaryEmbedding(nn.Module):
103
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
104
+ super().__init__()
105
+
106
+ self.dim = dim
107
+ self.max_position_embeddings = max_position_embeddings
108
+ self.base = base
109
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
110
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
111
+
112
+ # Build here to make `torch.jit.trace` work.
113
+ self._set_cos_sin_cache(
114
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
115
+ )
116
+
117
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
118
+ self.max_seq_len_cached = seq_len
119
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
120
+
121
+ freqs = torch.outer(t, self.inv_freq)
122
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
123
+ emb = torch.cat((freqs, freqs), dim=-1)
124
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
125
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
126
+
127
+ def forward(self, x, seq_len=None):
128
+ # x: [bs, num_attention_heads, seq_len, head_size]
129
+ if seq_len > self.max_seq_len_cached:
130
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
131
+
132
+ return (
133
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
134
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
135
+ )
136
+
137
+
138
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
139
+ def rotate_half(x):
140
+ """Rotates half the hidden dims of the input."""
141
+ x1 = x[..., : x.shape[-1] // 2]
142
+ x2 = x[..., x.shape[-1] // 2 :]
143
+ return torch.cat((-x2, x1), dim=-1)
144
+
145
+
146
+ # Copied from transformers.models.mistral.modeling_mistral.apply_rotary_pos_emb
147
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
148
+ """Applies Rotary Position Embedding to the query and key tensors.
149
+
150
+ Args:
151
+ q (`torch.Tensor`): The query tensor.
152
+ k (`torch.Tensor`): The key tensor.
153
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
154
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
155
+ position_ids (`torch.Tensor`):
156
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
157
+ used to pass offsetted position ids when working with a KV-cache.
158
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
159
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
160
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
161
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
162
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
163
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
164
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
165
+ Returns:
166
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
167
+ """
168
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
169
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
170
+ q_embed = (q * cos) + (rotate_half(q) * sin)
171
+ k_embed = (k * cos) + (rotate_half(k) * sin)
172
+ return q_embed, k_embed
173
+
174
+
175
+ def apply_rotary_pos_emb2(q_pe, k_pe, cos, sin, position_ids, unsqueeze_dim=1):
176
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
177
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
178
+
179
+ #dim alignment
180
+ step = cos.shape[-1]//q_pe.shape[-1]
181
+ indices = torch.arange(0, cos.size(-1), step, device=cos.device)
182
+ cos = cos[..., indices]
183
+ sin = sin[..., indices]
184
+
185
+ q_embed = (q_pe * cos) + (rotate_half(q_pe) * sin)
186
+ k_embed = (k_pe * cos) + (rotate_half(k_pe) * sin)
187
+ return q_embed, k_embed
188
+
189
+
190
+
191
+ # Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Qwen2
192
+ class Qwen2MLP(nn.Module):
193
+ def __init__(self, config):
194
+ super().__init__()
195
+ self.config = config
196
+ self.hidden_size = config.hidden_size
197
+ self.intermediate_size = config.intermediate_size
198
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
199
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
200
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
201
+ self.act_fn = ACT2FN[config.hidden_act]
202
+
203
+ def forward(self, x):
204
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
205
+
206
+
207
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
208
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
209
+ """
210
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
211
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
212
+ """
213
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
214
+ if n_rep == 1:
215
+ return hidden_states
216
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
217
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
218
+
219
+
220
+ class Qwen2Attention(nn.Module):
221
+ """
222
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
223
+ and "Generating Long Sequences with Sparse Transformers".
224
+ """
225
+
226
+ def __init__(self, config: Qwen2Config, layer_idx: Optional[int] = None):
227
+ super().__init__()
228
+ self.config = config
229
+ self.layer_idx = layer_idx
230
+ if layer_idx is None:
231
+ logger.warning_once(
232
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
233
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
234
+ "when creating this class."
235
+ )
236
+
237
+ self.hidden_size = config.hidden_size
238
+ self.num_heads = config.num_attention_heads
239
+ self.head_dim = self.hidden_size // self.num_heads
240
+ self.num_key_value_heads = config.num_key_value_heads
241
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
242
+ self.max_position_embeddings = config.max_position_embeddings
243
+ self.rope_theta = config.rope_theta
244
+ self.is_causal = True
245
+ self.attention_dropout = config.attention_dropout
246
+
247
+ self.temperature = nn.Parameter(torch.tensor(1.0))
248
+ self.k_nope_scale_factor = nn.Parameter(torch.tensor(1.0))
249
+
250
+ if (self.head_dim * self.num_heads) != self.hidden_size:
251
+ raise ValueError(
252
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
253
+ f" and `num_heads`: {self.num_heads})."
254
+ )
255
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
256
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
257
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
258
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
259
+
260
+ self.rotary_emb = Qwen2RotaryEmbedding(
261
+ self.head_dim,
262
+ max_position_embeddings=self.max_position_embeddings,
263
+ base=self.rope_theta,
264
+ )
265
+
266
+
267
+ #MLA part modeling_deepseek.py
268
+ config.attention_bias=False
269
+
270
+ self.interval = 2
271
+ self.q_rope_dim = self.num_heads * (self.head_dim//self.interval)
272
+ self.q_nope_dim = self.num_heads * self.head_dim - self.q_rope_dim
273
+ self.k_rope_dim = self.num_key_value_heads * (self.head_dim//self.interval)
274
+ self.k_nope_dim = self.num_key_value_heads*self.head_dim - self.k_rope_dim
275
+ self.kv_lora_rank = 128 #4个kv头每个头的latentsize
276
+ self.v_head_dim = self.head_dim
277
+
278
+ self.kv_a_proj_nope = nn.Linear(self.hidden_size, self.num_key_value_heads*self.kv_lora_rank, bias=False)
279
+ self.k_proj_pe = nn.Linear(self.hidden_size,self.k_rope_dim,bias=True)
280
+ self.k_b_proj_nope = nn.Linear(self.num_key_value_heads*self.kv_lora_rank,self.num_key_value_groups*self.k_nope_dim,bias=True)
281
+ self.v_b_proj = nn.Linear(self.num_key_value_heads*self.kv_lora_rank,self.num_key_value_groups*self.num_key_value_heads*self.head_dim,bias=True)
282
+
283
+ def forward(
284
+ self,
285
+ hidden_states: torch.Tensor,
286
+ attention_mask: Optional[torch.Tensor] = None,
287
+ position_ids: Optional[torch.LongTensor] = None,
288
+ past_key_value: Optional[Cache] = None,
289
+ output_attentions: bool = False,
290
+ use_cache: bool = False,
291
+ **kwargs,
292
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
293
+ if "padding_mask" in kwargs:
294
+ warnings.warn(
295
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
296
+ )
297
+ bsz, q_len, _ = hidden_states.size()
298
+
299
+ query_states = self.q_proj(hidden_states)
300
+
301
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
302
+ # key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
303
+ # value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
304
+
305
+ mask = torch.zeros(self.head_dim, dtype=torch.bool)
306
+ mask[::self.interval] = True
307
+ q_pe = query_states[..., mask]
308
+ q_nope = query_states[..., ~mask]
309
+
310
+
311
+ compressed_kv = self.kv_a_proj_nope(hidden_states) # .view(bsz, q_len, self.num_key_value_heads,self.kv_lora_rank ) #no transpose
312
+
313
+ k_pe = self.k_proj_pe(hidden_states).view(bsz, q_len, self.num_key_value_heads, (self.head_dim//self.interval) ).transpose(1, 2)
314
+
315
+ kv_seq_len = k_pe.shape[-2]
316
+ if past_key_value is not None:
317
+ if self.layer_idx is None:
318
+ raise ValueError(
319
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
320
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
321
+ "with a layer index."
322
+ )
323
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
324
+ cos, sin = self.rotary_emb(k_pe, seq_len=kv_seq_len) #k_pe only for device and dtype,no matter shape
325
+
326
+ q_pe, k_pe = apply_rotary_pos_emb2(q_pe, k_pe, cos, sin, position_ids)
327
+
328
+ if past_key_value is not None:
329
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
330
+ compressed_kv = compressed_kv.view(bsz, q_len, self.num_key_value_heads,self.kv_lora_rank).transpose(1, 2)
331
+ k_pe, compressed_kv = past_key_value.update(k_pe, compressed_kv, self.layer_idx, cache_kwargs)
332
+
333
+ compressed_kv = compressed_kv.transpose(1,2).reshape(bsz, kv_seq_len, self.num_key_value_heads*self.kv_lora_rank)
334
+ k_nope = self.k_b_proj_nope(compressed_kv).view(bsz, kv_seq_len, self.num_heads,self.head_dim-(self.head_dim//self.interval) ).transpose(1, 2)
335
+ value_states = self.v_b_proj(compressed_kv).view(bsz, kv_seq_len, self.num_heads,self.head_dim).transpose(1, 2)
336
+ # k_nope = self.k_repeat_nope(self.k_b_proj_nope(compressed_kv)).view(bsz, kv_seq_len,self.num_heads,self.head_dim-(self.head_dim//self.interval) ).transpose(1, 2)
337
+ # value_states = self.v_repeat(self.v_b_proj(compressed_kv)).view(bsz, kv_seq_len, self.num_heads,self.head_dim).transpose(1, 2)
338
+
339
+ k_pe = repeat_kv(k_pe,self.num_key_value_groups)
340
+ # k_nope = repeat_kv(k_nope,self.num_key_value_groups)
341
+ # value_states = repeat_kv(value_states,self.num_key_value_groups)
342
+
343
+ k_nope = k_nope * self.k_nope_scale_factor.to(k_nope.dtype)
344
+
345
+ effective_scale_factor = self.temperature.to(q_pe.dtype) / math.sqrt(self.head_dim)
346
+ attn_weights_pe = torch.matmul(q_pe, k_pe.transpose(2, 3)) * effective_scale_factor
347
+ attn_weights_nope = torch.matmul(q_nope, k_nope.transpose(2, 3)) * effective_scale_factor
348
+ attn_weights = attn_weights_pe + attn_weights_nope
349
+
350
+
351
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
352
+ raise ValueError(
353
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
354
+ f" {attn_weights.size()}"
355
+ )
356
+
357
+ if attention_mask is not None:
358
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
359
+ raise ValueError(
360
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
361
+ )
362
+
363
+ attn_weights = attn_weights + attention_mask
364
+
365
+ # upcast attention to fp32
366
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(value_states.dtype)
367
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
368
+ attn_output = torch.matmul(attn_weights, value_states)
369
+
370
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.v_head_dim):
371
+ raise ValueError(
372
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
373
+ f" {attn_output.size()}"
374
+ )
375
+
376
+ attn_output = attn_output.transpose(1, 2).contiguous()
377
+ # attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
378
+
379
+ attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.v_head_dim)
380
+
381
+ attn_output = self.o_proj(attn_output)
382
+
383
+ if not output_attentions:
384
+ attn_weights = None
385
+
386
+ return attn_output, attn_weights, past_key_value
387
+
388
+ class Qwen2FlashAttention2(Qwen2Attention):
389
+ """
390
+ Qwen2 flash attention module, following Qwen2 attention module. This module inherits from `Qwen2Attention`
391
+ as the weights of the module stays untouched. The only required change would be on the forward pass
392
+ where it needs to correctly call the public API of flash attention and deal with padding tokens
393
+ in case the input contains any of them. Additionally, for sliding window attention, we apply SWA only to the bottom
394
+ config.max_window_layers layers.
395
+ """
396
+
397
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
398
+ def __init__(self, *args, **kwargs):
399
+ super().__init__(*args, **kwargs)
400
+
401
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
402
+ # 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.
403
+ # 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).
404
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
405
+
406
+ def forward(
407
+ self,
408
+ hidden_states: torch.Tensor,
409
+ attention_mask: Optional[torch.Tensor] = None,
410
+ position_ids: Optional[torch.LongTensor] = None,
411
+ past_key_value: Optional[Cache] = None,
412
+ output_attentions: bool = False,
413
+ use_cache: bool = False,
414
+ **kwargs,
415
+ ):
416
+ if "padding_mask" in kwargs:
417
+ warnings.warn(
418
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
419
+ )
420
+
421
+ # overwrite attention_mask with padding_mask
422
+ attention_mask = kwargs.pop("padding_mask")
423
+ bsz, q_len, _ = hidden_states.size()
424
+
425
+ query_states = self.q_proj(hidden_states)
426
+
427
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
428
+ # key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
429
+ # value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
430
+
431
+ mask = torch.zeros(self.head_dim, dtype=torch.bool)
432
+ mask[::self.interval] = True
433
+ q_pe = query_states[..., mask]
434
+ q_nope = query_states[..., ~mask]
435
+
436
+
437
+ compressed_kv = self.kv_a_proj_nope(hidden_states) # .view(bsz, q_len, self.num_key_value_heads,self.kv_lora_rank ) #no transpose
438
+ # print("compressed_kv",compressed_kv.shape)
439
+ # print("q_pe",q_pe.shape)
440
+ # print('hidden_states',hidden_states.shape)
441
+ k_pe = self.k_proj_pe(hidden_states).view(bsz, q_len, self.num_key_value_heads, (self.head_dim//self.interval) ).transpose(1, 2)
442
+
443
+ kv_seq_len = k_pe.shape[-2]
444
+ if past_key_value is not None:
445
+ if self.layer_idx is None:
446
+ raise ValueError(
447
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
448
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
449
+ "with a layer index."
450
+ )
451
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
452
+ cos, sin = self.rotary_emb(k_pe, seq_len=kv_seq_len) #k_pe only for device and dtype,no matter shape
453
+
454
+ q_pe, k_pe = apply_rotary_pos_emb2(q_pe, k_pe, cos, sin, position_ids)
455
+
456
+
457
+ if past_key_value is not None:
458
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
459
+ compressed_kv = compressed_kv.view(bsz, q_len, self.num_key_value_heads,self.kv_lora_rank).transpose(1, 2)
460
+ k_pe, compressed_kv = past_key_value.update(k_pe, compressed_kv, self.layer_idx, cache_kwargs)
461
+
462
+ compressed_kv = compressed_kv.transpose(1,2).reshape(bsz, kv_seq_len, self.num_key_value_heads*self.kv_lora_rank)
463
+ k_nope = self.k_b_proj_nope(compressed_kv).view(bsz, kv_seq_len, self.num_heads,self.head_dim-(self.head_dim//self.interval) ).transpose(1, 2)
464
+ value_states = self.v_b_proj(compressed_kv).view(bsz, kv_seq_len, self.num_heads,self.head_dim).transpose(1, 2)
465
+ # k_nope = self.k_repeat_nope(self.k_b_proj_nope(compressed_kv)).view(bsz, kv_seq_len,self.num_heads,self.head_dim-(self.head_dim//self.interval) ).transpose(1, 2)
466
+ # value_states = self.v_repeat(self.v_b_proj(compressed_kv)).view(bsz, kv_seq_len, self.num_heads,self.head_dim).transpose(1, 2)
467
+
468
+ k_pe = repeat_kv(k_pe,self.num_key_value_groups)
469
+ # k_nope = repeat_kv(k_nope,self.num_key_value_groups)
470
+ # value_states = repeat_kv(value_states,self.num_key_value_groups)
471
+
472
+ k_nope = k_nope * self.k_nope_scale_factor.to(k_nope.dtype)
473
+
474
+ query_states = q_pe.new_empty(bsz, self.num_heads, q_len, self.head_dim)
475
+ query_states[:, :, :, mask] = q_pe
476
+ query_states[:, :, :, ~mask] = q_nope
477
+
478
+ key_states = k_pe.new_empty(bsz, self.num_heads, kv_seq_len, self.head_dim)
479
+ key_states[:, :, :, mask] = k_pe
480
+ key_states[:, :, :, ~mask] = k_nope
481
+
482
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
483
+ # to be able to avoid many of these transpose/reshape/view.
484
+ query_states = query_states.transpose(1, 2)
485
+ key_states = key_states.transpose(1, 2)
486
+ value_states = value_states.transpose(1, 2)
487
+
488
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
489
+
490
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
491
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
492
+ # cast them back in float16 just to be sure everything works as expected.
493
+ input_dtype = query_states.dtype
494
+ if input_dtype == torch.float32:
495
+ if torch.is_autocast_enabled():
496
+ target_dtype = torch.get_autocast_gpu_dtype()
497
+ # Handle the case where the model is quantized
498
+ elif hasattr(self.config, "_pre_quantization_dtype"):
499
+ target_dtype = self.config._pre_quantization_dtype
500
+ else:
501
+ target_dtype = self.q_proj.weight.dtype
502
+
503
+ logger.warning_once(
504
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
505
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
506
+ f" {target_dtype}."
507
+ )
508
+
509
+ query_states = query_states.to(target_dtype)
510
+ key_states = key_states.to(target_dtype)
511
+ value_states = value_states.to(target_dtype)
512
+
513
+
514
+ current_softmax_scale = self.head_dim ** (-0.5)
515
+ effective_softmax_scale = current_softmax_scale * self.temperature.to(query_states.dtype)
516
+
517
+ attn_output = self._flash_attention_forward(
518
+ query_states,
519
+ key_states,
520
+ value_states,
521
+ attention_mask,
522
+ q_len,
523
+ dropout=dropout_rate,
524
+ softmax_scale= effective_softmax_scale.item(), # 将标量张量转换为浮点数
525
+ )
526
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
527
+ attn_output = self.o_proj(attn_output)
528
+
529
+ if not output_attentions:
530
+ attn_weights = None
531
+
532
+ return attn_output, attn_weights, past_key_value
533
+
534
+
535
+ def _flash_attention_forward(
536
+ self,
537
+ query_states,
538
+ key_states,
539
+ value_states,
540
+ attention_mask,
541
+ query_length,
542
+ dropout=0.0,
543
+ softmax_scale=None,
544
+ ):
545
+ """
546
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
547
+ first unpad the input, then computes the attention scores and pad the final attention scores.
548
+
549
+ Args:
550
+ query_states (`torch.Tensor`):
551
+ Input query states to be passed to Flash Attention API
552
+ key_states (`torch.Tensor`):
553
+ Input key states to be passed to Flash Attention API
554
+ value_states (`torch.Tensor`):
555
+ Input value states to be passed to Flash Attention API
556
+ attention_mask (`torch.Tensor`):
557
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
558
+ position of padding tokens and 1 for the position of non-padding tokens.
559
+ dropout (`int`, *optional*):
560
+ Attention dropout
561
+ softmax_scale (`float`, *optional*):
562
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
563
+ """
564
+ if not self._flash_attn_uses_top_left_mask:
565
+ causal = self.is_causal
566
+ else:
567
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in DeepseekV3FlashAttention2 __init__.
568
+ causal = self.is_causal and query_length != 1
569
+
570
+ # Contains at least one padding token in the sequence
571
+ if attention_mask is not None:
572
+ batch_size = query_states.shape[0]
573
+ (
574
+ query_states,
575
+ key_states,
576
+ value_states,
577
+ indices_q,
578
+ cu_seq_lens,
579
+ max_seq_lens,
580
+ ) = self._upad_input(
581
+ query_states, key_states, value_states, attention_mask, query_length
582
+ )
583
+
584
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
585
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
586
+
587
+ attn_output_unpad = flash_attn_varlen_func(
588
+ query_states,
589
+ key_states,
590
+ value_states,
591
+ cu_seqlens_q=cu_seqlens_q,
592
+ cu_seqlens_k=cu_seqlens_k,
593
+ max_seqlen_q=max_seqlen_in_batch_q,
594
+ max_seqlen_k=max_seqlen_in_batch_k,
595
+ dropout_p=dropout,
596
+ softmax_scale=softmax_scale,
597
+ causal=causal,
598
+ )
599
+
600
+ attn_output = pad_input(
601
+ attn_output_unpad, indices_q, batch_size, query_length
602
+ )
603
+ else:
604
+ attn_output = flash_attn_func(
605
+ query_states,
606
+ key_states,
607
+ value_states,
608
+ dropout,
609
+ softmax_scale=softmax_scale,
610
+ causal=causal,
611
+ )
612
+
613
+ return attn_output
614
+
615
+ def _upad_input(
616
+ self, query_layer, key_layer, value_layer, attention_mask, query_length
617
+ ):
618
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
619
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
620
+
621
+ key_layer = index_first_axis(
622
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
623
+ indices_k,
624
+ )
625
+ value_layer = index_first_axis(
626
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
627
+ indices_k,
628
+ )
629
+ if query_length == kv_seq_len:
630
+ query_layer = index_first_axis(
631
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
632
+ indices_k,
633
+ )
634
+ cu_seqlens_q = cu_seqlens_k
635
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
636
+ indices_q = indices_k
637
+ elif query_length == 1:
638
+ max_seqlen_in_batch_q = 1
639
+ cu_seqlens_q = torch.arange(
640
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
641
+ ) # There is a memcpy here, that is very bad.
642
+ indices_q = cu_seqlens_q[:-1]
643
+ query_layer = query_layer.squeeze(1)
644
+ else:
645
+ # The -q_len: slice assumes left padding.
646
+ attention_mask = attention_mask[:, -query_length:]
647
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
648
+ query_layer, attention_mask
649
+ )
650
+
651
+ return (
652
+ query_layer,
653
+ key_layer,
654
+ value_layer,
655
+ indices_q,
656
+ (cu_seqlens_q, cu_seqlens_k),
657
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
658
+ )
659
+
660
+ # Copied from transformers.models.mistral.modeling_mistral.MistralSdpaAttention with Mistral->Qwen2
661
+ class Qwen2SdpaAttention(Qwen2Attention):
662
+ """
663
+ Qwen2 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
664
+ `Qwen2Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
665
+ SDPA API.
666
+ """
667
+
668
+ # Adapted from Qwen2Attention.forward
669
+ def forward(
670
+ self,
671
+ hidden_states: torch.Tensor,
672
+ attention_mask: Optional[torch.Tensor] = None,
673
+ position_ids: Optional[torch.LongTensor] = None,
674
+ past_key_value: Optional[Cache] = None,
675
+ output_attentions: bool = False,
676
+ use_cache: bool = False,
677
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
678
+ if output_attentions:
679
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
680
+ logger.warning_once(
681
+ "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, "
682
+ '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.'
683
+ )
684
+ return super().forward(
685
+ hidden_states=hidden_states,
686
+ attention_mask=attention_mask,
687
+ position_ids=position_ids,
688
+ past_key_value=past_key_value,
689
+ output_attentions=output_attentions,
690
+ use_cache=use_cache,
691
+ )
692
+
693
+ bsz, q_len, _ = hidden_states.size()
694
+
695
+ query_states = self.q_proj(hidden_states)
696
+
697
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
698
+ # key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
699
+ # value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
700
+
701
+ mask = torch.zeros(self.head_dim, dtype=torch.bool)
702
+ mask[::self.interval] = True
703
+ q_pe = query_states[..., mask]
704
+ q_nope = query_states[..., ~mask]
705
+
706
+
707
+ compressed_kv = self.kv_a_proj_nope(hidden_states) # .view(bsz, q_len, self.num_key_value_heads,self.kv_lora_rank ) #no transpose
708
+ # print("compressed_kv",compressed_kv.shape)
709
+ # print("q_pe",q_pe.shape)
710
+ # print('hidden_states',hidden_states.shape)
711
+ k_pe = self.k_proj_pe(hidden_states).view(bsz, q_len, self.num_key_value_heads, (self.head_dim//self.interval) ).transpose(1, 2)
712
+
713
+ kv_seq_len = k_pe.shape[-2]#就是q_len了
714
+ if past_key_value is not None:
715
+ if self.layer_idx is None:
716
+ raise ValueError(
717
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
718
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
719
+ "with a layer index."
720
+ )
721
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
722
+ cos, sin = self.rotary_emb(k_pe, seq_len=kv_seq_len) #k_pe only for device and dtype,no matter shape
723
+
724
+ q_pe, k_pe = apply_rotary_pos_emb2(q_pe, k_pe, cos, sin, position_ids)
725
+
726
+ if past_key_value is not None:
727
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
728
+ compressed_kv = compressed_kv.view(bsz, q_len, self.num_key_value_heads,self.kv_lora_rank).transpose(1, 2)
729
+ k_pe, compressed_kv = past_key_value.update(k_pe, compressed_kv, self.layer_idx, cache_kwargs)
730
+
731
+ compressed_kv = compressed_kv.transpose(1,2).reshape(bsz, kv_seq_len, self.num_key_value_heads*self.kv_lora_rank)
732
+ k_nope = self.k_b_proj_nope(compressed_kv).view(bsz, kv_seq_len, self.num_heads,self.head_dim-(self.head_dim//self.interval) ).transpose(1, 2)
733
+ value_states = self.v_b_proj(compressed_kv).view(bsz, kv_seq_len, self.num_heads,self.head_dim).transpose(1, 2)
734
+ # k_nope = self.k_repeat_nope(self.k_b_proj_nope(compressed_kv)).view(bsz, kv_seq_len,self.num_heads,self.head_dim-(self.head_dim//self.interval) ).transpose(1, 2)
735
+ # value_states = self.v_repeat(self.v_b_proj(compressed_kv)).view(bsz, kv_seq_len, self.num_heads,self.head_dim).transpose(1, 2)
736
+
737
+ k_pe = repeat_kv(k_pe,self.num_key_value_groups)
738
+ # k_nope = repeat_kv(k_nope,self.num_key_value_groups)
739
+ # value_states = repeat_kv(value_states,self.num_key_value_groups)
740
+
741
+ k_nope = k_nope * self.k_nope_scale_factor.to(k_nope.dtype)
742
+
743
+ query_states = q_pe.new_empty(bsz, self.num_heads, q_len, self.head_dim)
744
+ query_states[:, :, :, mask] = q_pe
745
+ query_states[:, :, :, ~mask] = q_nope
746
+
747
+ key_states = k_pe.new_empty(bsz, self.num_heads, kv_seq_len, self.head_dim)
748
+ key_states[:, :, :, mask] = k_pe
749
+ key_states[:, :, :, ~mask] = k_nope
750
+
751
+ if attention_mask is not None:
752
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
753
+ raise ValueError(
754
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
755
+ )
756
+
757
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
758
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
759
+ if query_states.device.type == "cuda" and attention_mask is not None:
760
+ query_states = query_states.contiguous()
761
+ key_states = key_states.contiguous()
762
+ value_states = value_states.contiguous()
763
+
764
+ sdpa_effective_scale = (self.head_dim ** (-0.5)) * self.temperature.to(query_states.dtype)
765
+
766
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
767
+ query_states,
768
+ key_states,
769
+ value_states,
770
+ attn_mask=attention_mask,
771
+ dropout_p=self.attention_dropout if self.training else 0.0,
772
+ # 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.
773
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
774
+ scale=sdpa_effective_scale.item(), # 将标量张量转换为浮点数
775
+ )
776
+
777
+ attn_output = attn_output.transpose(1, 2).contiguous()
778
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
779
+
780
+ attn_output = self.o_proj(attn_output)
781
+
782
+ return attn_output, None, past_key_value
783
+
784
+
785
+
786
+ QWEN2_ATTENTION_CLASSES = {
787
+ "eager": Qwen2Attention,
788
+ "flash_attention_2": Qwen2FlashAttention2,
789
+ "sdpa": Qwen2SdpaAttention,
790
+ }
791
+
792
+
793
+ class Qwen2DecoderLayer(nn.Module):
794
+ def __init__(self, config: Qwen2Config, layer_idx: int):
795
+ super().__init__()
796
+ self.hidden_size = config.hidden_size
797
+
798
+ if config.use_sliding_window and config._attn_implementation != "flash_attention_2":
799
+ logger.warning_once(
800
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
801
+ "unexpected results may be encountered."
802
+ )
803
+ self.self_attn = QWEN2_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
804
+
805
+ self.mlp = Qwen2MLP(config)
806
+ self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
807
+ self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
808
+
809
+ def forward(
810
+ self,
811
+ hidden_states: torch.Tensor,
812
+ attention_mask: Optional[torch.Tensor] = None,
813
+ position_ids: Optional[torch.LongTensor] = None,
814
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
815
+ output_attentions: Optional[bool] = False,
816
+ use_cache: Optional[bool] = False,
817
+ **kwargs,
818
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
819
+ if "padding_mask" in kwargs:
820
+ warnings.warn(
821
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. "
822
+ "Please make sure use `attention_mask` instead.`"
823
+ )
824
+ """
825
+ Args:
826
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
827
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
828
+ `(batch, sequence_length)` where padding elements are indicated by 0.
829
+ output_attentions (`bool`, *optional*):
830
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
831
+ returned tensors for more detail.
832
+ use_cache (`bool`, *optional*):
833
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
834
+ (see `past_key_values`).
835
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
836
+ """
837
+
838
+ residual = hidden_states
839
+
840
+ hidden_states = self.input_layernorm(hidden_states)
841
+
842
+ # Self Attention
843
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
844
+ hidden_states=hidden_states,
845
+ attention_mask=attention_mask,
846
+ position_ids=position_ids,
847
+ past_key_value=past_key_value,
848
+ output_attentions=output_attentions,
849
+ use_cache=use_cache,
850
+ )
851
+ hidden_states = residual + hidden_states
852
+
853
+ # Fully Connected
854
+ residual = hidden_states
855
+ hidden_states = self.post_attention_layernorm(hidden_states)
856
+ hidden_states = self.mlp(hidden_states)
857
+ hidden_states = residual + hidden_states
858
+
859
+ outputs = (hidden_states,)
860
+
861
+ if output_attentions:
862
+ outputs += (self_attn_weights,)
863
+
864
+ if use_cache:
865
+ outputs += (present_key_value,)
866
+
867
+ return outputs
868
+
869
+
870
+ QWEN2_START_DOCSTRING = r"""
871
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
872
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
873
+ etc.)
874
+
875
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
876
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
877
+ and behavior.
878
+
879
+ Parameters:
880
+ config ([`Qwen2Config`]):
881
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
882
+ load the weights associated with the model, only the configuration. Check out the
883
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
884
+ """
885
+
886
+
887
+ @add_start_docstrings(
888
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
889
+ QWEN2_START_DOCSTRING,
890
+ )
891
+ class Qwen2PreTrainedModel(PreTrainedModel):
892
+ config_class = Qwen2Config
893
+ base_model_prefix = "model"
894
+ supports_gradient_checkpointing = True
895
+ _no_split_modules = ["Qwen2DecoderLayer"]
896
+ _skip_keys_device_placement = "past_key_values"
897
+ _supports_flash_attn_2 = True
898
+ _supports_sdpa = True
899
+ _supports_cache_class = True
900
+
901
+ def _init_weights(self, module):
902
+ std = self.config.initializer_range
903
+ if isinstance(module, nn.Linear):
904
+ module.weight.data.normal_(mean=0.0, std=std)
905
+ if module.bias is not None:
906
+ module.bias.data.zero_()
907
+ elif isinstance(module, nn.Embedding):
908
+ module.weight.data.normal_(mean=0.0, std=std)
909
+ if module.padding_idx is not None:
910
+ module.weight.data[module.padding_idx].zero_()
911
+
912
+
913
+ QWEN2_INPUTS_DOCSTRING = r"""
914
+ Args:
915
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
916
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
917
+ it.
918
+
919
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
920
+ [`PreTrainedTokenizer.__call__`] for details.
921
+
922
+ [What are input IDs?](../glossary#input-ids)
923
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
924
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
925
+
926
+ - 1 for tokens that are **not masked**,
927
+ - 0 for tokens that are **masked**.
928
+
929
+ [What are attention masks?](../glossary#attention-mask)
930
+
931
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
932
+ [`PreTrainedTokenizer.__call__`] for details.
933
+
934
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
935
+ `past_key_values`).
936
+
937
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
938
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
939
+ information on the default strategy.
940
+
941
+ - 1 indicates the head is **not masked**,
942
+ - 0 indicates the head is **masked**.
943
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
944
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
945
+ config.n_positions - 1]`.
946
+
947
+ [What are position IDs?](../glossary#position-ids)
948
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
949
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
950
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
951
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
952
+
953
+ Two formats are allowed:
954
+ - a [`~cache_utils.Cache`] instance;
955
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
956
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
957
+ cache format.
958
+
959
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
960
+ legacy cache format will be returned.
961
+
962
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
963
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
964
+ of shape `(batch_size, sequence_length)`.
965
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
966
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
967
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
968
+ model's internal embedding lookup matrix.
969
+ use_cache (`bool`, *optional*):
970
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
971
+ `past_key_values`).
972
+ output_attentions (`bool`, *optional*):
973
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
974
+ tensors for more detail.
975
+ output_hidden_states (`bool`, *optional*):
976
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
977
+ more detail.
978
+ return_dict (`bool`, *optional*):
979
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
980
+ """
981
+
982
+
983
+ @add_start_docstrings(
984
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
985
+ QWEN2_START_DOCSTRING,
986
+ )
987
+ class Qwen2Model_Flash(Qwen2PreTrainedModel):
988
+ """
989
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]
990
+
991
+ Args:
992
+ config: Qwen2Config
993
+ """
994
+
995
+ def __init__(self, config: Qwen2Config):
996
+ super().__init__(config)
997
+ self.padding_idx = config.pad_token_id
998
+ self.vocab_size = config.vocab_size
999
+
1000
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1001
+ self.layers = nn.ModuleList(
1002
+ [Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1003
+ )
1004
+ self._attn_implementation = config._attn_implementation
1005
+ self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1006
+
1007
+ self.gradient_checkpointing = False
1008
+
1009
+ # Initialize weights and apply final processing
1010
+ self.post_init()
1011
+
1012
+ def get_input_embeddings(self):
1013
+ return self.embed_tokens
1014
+
1015
+ def set_input_embeddings(self, value):
1016
+ self.embed_tokens = value
1017
+
1018
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1019
+ def forward(
1020
+ self,
1021
+ input_ids: torch.LongTensor = None,
1022
+ attention_mask: Optional[torch.Tensor] = None,
1023
+ position_ids: Optional[torch.LongTensor] = None,
1024
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1025
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1026
+ use_cache: Optional[bool] = None,
1027
+ output_attentions: Optional[bool] = None,
1028
+ output_hidden_states: Optional[bool] = None,
1029
+ return_dict: Optional[bool] = None,
1030
+ labels: Optional[torch.Tensor] = None,
1031
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1032
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1033
+ output_hidden_states = (
1034
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1035
+ )
1036
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1037
+
1038
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1039
+
1040
+ # retrieve input_ids and inputs_embeds
1041
+ if input_ids is not None and inputs_embeds is not None:
1042
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
1043
+ elif input_ids is not None:
1044
+ batch_size, seq_length = input_ids.shape
1045
+ elif inputs_embeds is not None:
1046
+ batch_size, seq_length, _ = inputs_embeds.shape
1047
+ else:
1048
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
1049
+
1050
+ if self.gradient_checkpointing and self.training:
1051
+ if use_cache:
1052
+ logger.warning_once(
1053
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1054
+ )
1055
+ use_cache = False
1056
+
1057
+ past_key_values_length = 0
1058
+
1059
+ if use_cache:
1060
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1061
+ if use_legacy_cache:
1062
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1063
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1064
+
1065
+ if position_ids is None:
1066
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1067
+ position_ids = torch.arange(
1068
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1069
+ )
1070
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1071
+ else:
1072
+ position_ids = position_ids.view(-1, seq_length).long()
1073
+
1074
+ if inputs_embeds is None:
1075
+ inputs_embeds = self.embed_tokens(input_ids)
1076
+
1077
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
1078
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1079
+ if is_padding_right:
1080
+ raise ValueError(
1081
+ "You are attempting to perform batched generation with padding_side='right'"
1082
+ " this may lead to unexpected behaviour for Flash Attention version of Qwen2. Make sure to "
1083
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1084
+ )
1085
+
1086
+ if self._attn_implementation == "flash_attention_2":
1087
+ # 2d mask is passed through the layers
1088
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1089
+ elif self._attn_implementation == "sdpa" and not output_attentions:
1090
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1091
+ # the manual implementation that requires a 4D causal mask in all cases.
1092
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1093
+ attention_mask,
1094
+ (batch_size, seq_length),
1095
+ inputs_embeds,
1096
+ past_key_values_length,
1097
+ )
1098
+ else:
1099
+ # 4d mask is passed through the layers
1100
+ attention_mask = _prepare_4d_causal_attention_mask(
1101
+ attention_mask,
1102
+ (batch_size, seq_length),
1103
+ inputs_embeds,
1104
+ past_key_values_length,
1105
+ sliding_window=self.config.sliding_window,
1106
+ )
1107
+
1108
+ hidden_states = inputs_embeds
1109
+
1110
+ # decoder layers
1111
+ all_hidden_states = () if output_hidden_states else None
1112
+ all_self_attns = () if output_attentions else None
1113
+ next_decoder_cache = None
1114
+
1115
+ for layer_idx, decoder_layer in enumerate(self.layers):
1116
+ if output_hidden_states:
1117
+ all_hidden_states += (hidden_states,)
1118
+
1119
+ if self.gradient_checkpointing and self.training:
1120
+ layer_outputs = self._gradient_checkpointing_func(
1121
+ decoder_layer.__call__,
1122
+ hidden_states,
1123
+ attention_mask,
1124
+ position_ids,
1125
+ past_key_values,
1126
+ output_attentions,
1127
+ use_cache,
1128
+ )
1129
+ else:
1130
+ layer_outputs = decoder_layer(
1131
+ hidden_states,
1132
+ attention_mask=attention_mask,
1133
+ position_ids=position_ids,
1134
+ past_key_value=past_key_values,
1135
+ output_attentions=output_attentions,
1136
+ use_cache=use_cache,
1137
+ )
1138
+
1139
+ hidden_states = layer_outputs[0]
1140
+
1141
+ if use_cache:
1142
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1143
+
1144
+ if output_attentions:
1145
+ all_self_attns += (layer_outputs[1],)
1146
+
1147
+ ###### copy from pdrop #########
1148
+ # rank & drop after specific layer
1149
+ # only drop in prefill stage when inference
1150
+ rank_layer = layer_idx+1
1151
+ if rank_layer in self.llm_compress_layer_list:
1152
+ if hidden_states.shape[1] != 1: # prefill stage or training
1153
+ stage = self.llm_compress_layer_list.index(rank_layer) # determine current stage
1154
+ (
1155
+ position_ids,
1156
+ attention_mask,
1157
+ hidden_states,
1158
+ labels # update labels and return
1159
+ ) = self.video_level_compress(
1160
+ cur_num = stage,
1161
+ rank_layer = rank_layer,
1162
+ features = hidden_states,
1163
+ position_ids=position_ids,
1164
+ attention_mask=attention_mask,
1165
+ labels = labels
1166
+ )
1167
+
1168
+ # process attention_mask again after updating
1169
+ if self._attn_implementation == "flash_attention_2":
1170
+ # 2d mask is passed through the layers
1171
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1172
+ elif self._attn_implementation == "sdpa" and not output_attentions:
1173
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1174
+ # the manual implementation that requires a 4D causal mask in all cases.
1175
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1176
+ attention_mask,
1177
+ (batch_size, hidden_states.shape[1]),
1178
+ hidden_states,
1179
+ past_key_values_length,
1180
+ )
1181
+ else:
1182
+ # 4d mask is passed through the layers
1183
+ attention_mask = _prepare_4d_causal_attention_mask(
1184
+ attention_mask,
1185
+ (batch_size, hidden_states.shape[1]),
1186
+ hidden_states,
1187
+ past_key_values_length,
1188
+ sliding_window=self.config.sliding_window,
1189
+ )
1190
+
1191
+ else:
1192
+ # update position_ids in decoding stage when inference
1193
+ stage = self.llm_compress_layer_list.index(rank_layer) # determine current stage
1194
+ cur_visual_length = [int(cur_image_token * self.llm_image_token_ratio_list[stage]) for cur_image_token in self.num_image_token_lens]
1195
+ next_visual_length = [int(cur_image_token * self.llm_image_token_ratio_list[stage + 1]) for cur_image_token in self.num_image_token_lens]
1196
+ new_position_ids = []
1197
+ for idx, cur_position_ids in enumerate(position_ids):
1198
+ cur_position_ids = cur_position_ids - (cur_visual_length[idx] - next_visual_length[idx])
1199
+ new_position_ids.append(cur_position_ids)
1200
+ assert idx == 0, idx
1201
+ position_ids = torch.tensor(new_position_ids, dtype=torch.long).unsqueeze(0)
1202
+
1203
+ #################
1204
+
1205
+ hidden_states = self.norm(hidden_states)
1206
+
1207
+ # add hidden states from the last decoder layer
1208
+ if output_hidden_states:
1209
+ all_hidden_states += (hidden_states,)
1210
+
1211
+ next_cache = None
1212
+ if use_cache:
1213
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1214
+
1215
+ if not return_dict:
1216
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None), labels
1217
+ return BaseModelOutputWithPast(
1218
+ last_hidden_state=hidden_states,
1219
+ past_key_values=next_cache,
1220
+ hidden_states=all_hidden_states,
1221
+ attentions=all_self_attns,
1222
+ ), labels
1223
+
1224
+
1225
+ # implementation of pdrop
1226
+ def video_level_compress(
1227
+ self, cur_num, rank_layer, features ,
1228
+ position_ids, attention_mask, labels
1229
+ ):
1230
+
1231
+ if self.llm_compress_type == 'uniform0_attention':
1232
+ if cur_num == 0:
1233
+ llm_compress_type = 'uniform'
1234
+ else:
1235
+ llm_compress_type = 'attention'
1236
+ else:
1237
+ llm_compress_type = self.llm_compress_type
1238
+
1239
+ _labels = labels
1240
+ _position_ids = position_ids
1241
+ _attention_mask = attention_mask
1242
+
1243
+ if position_ids is None:
1244
+ position_ids = torch.arange(0, features.shape[1], dtype=torch.long, device=features.device).unsqueeze(0)
1245
+
1246
+ if getattr(self.config, 'tokenizer_padding_side', 'right') == "right":
1247
+
1248
+ batch_size = features.shape[0]
1249
+ image_tokens = [int(cur_image_token * self.llm_image_token_ratio_list[cur_num]) for cur_image_token in self.num_image_token_lens]
1250
+ keep_length = [int(cur_image_token * self.llm_image_token_ratio_list[cur_num + 1]) for cur_image_token in self.num_image_token_lens]
1251
+
1252
+ features_list = []
1253
+ attention_mask_list = []
1254
+ labels_list = []
1255
+
1256
+ if attention_mask is None:
1257
+ attention_mask = torch.ones((batch_size,features.shape[1]), dtype=torch.bool, device=features.device)
1258
+ else:
1259
+ attention_mask = attention_mask.bool()
1260
+ if labels is None:
1261
+ labels = torch.full((batch_size,features.shape[1]), IGNORE_INDEX, device=features.device)
1262
+
1263
+
1264
+ if 'attention' in llm_compress_type:
1265
+ # obtain query_states and key_states to calculate attention map
1266
+ hidden_states= features.clone().detach()
1267
+
1268
+ self_attn = self.layers[rank_layer].self_attn
1269
+ hidden_states = self.layers[rank_layer].input_layernorm(hidden_states)
1270
+
1271
+ num_heads = self_attn.num_heads
1272
+ num_key_value_heads = self_attn.num_key_value_heads
1273
+ head_dim = self_attn.head_dim
1274
+
1275
+ bsz, q_len, _ = hidden_states.size()
1276
+
1277
+ query_states = self_attn.q_proj(hidden_states)
1278
+ key_states = self_attn.k_proj(hidden_states)
1279
+ value_states = self_attn.v_proj(hidden_states)
1280
+
1281
+ query_states = query_states.view(bsz, q_len, num_heads, head_dim).transpose(1, 2)
1282
+ key_states = key_states.view(bsz, q_len, num_key_value_heads, head_dim).transpose(1, 2)
1283
+ value_states = value_states.view(bsz, q_len, num_key_value_heads, head_dim).transpose(1, 2)
1284
+
1285
+ kv_seq_len = key_states.shape[-2]
1286
+ cos, sin = self_attn.rotary_emb(value_states, seq_len=kv_seq_len)
1287
+
1288
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
1289
+ key_states = repeat_kv(key_states, self_attn.num_key_value_groups)
1290
+
1291
+ # attention_mask
1292
+ eager_attention_mask = _prepare_4d_causal_attention_mask(
1293
+ attention_mask, (batch_size, q_len), hidden_states, past_key_values_length=0
1294
+ ).to(device=query_states.device)
1295
+
1296
+ # take valid features
1297
+ features = [cur_features[cur_attention_mask] for cur_features, cur_attention_mask in zip(features, attention_mask)]
1298
+ labels = [cur_labels[cur_attention_mask] for cur_labels, cur_attention_mask in zip(labels, attention_mask)]
1299
+ attention_mask = [cur_attention_mask[cur_attention_mask] for cur_attention_mask, cur_attention_mask in zip(attention_mask, attention_mask)]
1300
+
1301
+ # rank & drop
1302
+ for i in range(batch_size):
1303
+ image_index = self.first_image_token_position[i]
1304
+ if image_index == -1:
1305
+ cur_input_embeds = features[i]
1306
+ features_list.append(cur_input_embeds)
1307
+ attention_mask_list.append(attention_mask[i])
1308
+ labels_list.append(labels[i])
1309
+ continue
1310
+
1311
+ if 'attention' in llm_compress_type:
1312
+
1313
+ # obtain current states
1314
+ cur_key_states = key_states[i]
1315
+ cur_query_states = query_states[i]
1316
+ cur_eager_attention_mask = eager_attention_mask[i]
1317
+
1318
+ # choose last instruction token as query
1319
+ if self.training:
1320
+ answer_index = torch.where(labels[i] != -100)[0].tolist()
1321
+ index_before_answer = []
1322
+ for index in answer_index:
1323
+ if labels[i][index-1] == -100:
1324
+ index_before_answer.append(index-1)
1325
+ if index_before_answer == []:
1326
+ cur_input_embeds = features[i]
1327
+ features_list.append(cur_input_embeds)
1328
+ attention_mask_list.append(attention_mask[i])
1329
+ labels_list.append(labels[i])
1330
+ continue
1331
+
1332
+ index_before_answer=torch.tensor(index_before_answer,device=labels[0].device)
1333
+ text_query_states = cur_query_states[:,index_before_answer,:]
1334
+ text_eager_attention_mask = cur_eager_attention_mask[:,index_before_answer,:]
1335
+
1336
+ else:
1337
+ prompt_total_len = self.text_prompt_lens[i] + image_tokens[i]
1338
+ text_query_states = cur_query_states[:,prompt_total_len-1,:].unsqueeze(1)
1339
+ text_eager_attention_mask = cur_eager_attention_mask[:,prompt_total_len-1,:].unsqueeze(1)
1340
+
1341
+ # calculate attention map
1342
+ attn_weights = torch.matmul(text_query_states, cur_key_states.transpose(1, 2)) / math.sqrt(head_dim) #(num_head, text_token,seq_len)
1343
+ attn_weights = attn_weights + text_eager_attention_mask
1344
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype) #(num_head, text_token,seq_len)
1345
+
1346
+ attention_avg_head = torch.mean(attn_weights, dim=0) # ave across heads
1347
+ attention_avg_head = attention_avg_head[:,image_index:image_index+image_tokens[i]] # select image token as keys
1348
+ attention_avg_text = torch.mean(attention_avg_head, dim=0) # (576)
1349
+
1350
+ if llm_compress_type == 'attention':
1351
+ top_rank_index = attention_avg_text.topk(keep_length[i]).indices
1352
+ else:
1353
+ raise NotImplementedError(llm_compress_type)
1354
+
1355
+ elif llm_compress_type == 'uniform':
1356
+ top_rank_index = torch.linspace(0, image_tokens[i]-1, keep_length[i], dtype=torch.long)
1357
+ else:
1358
+ raise NotImplementedError(llm_compress_type)
1359
+
1360
+ top_rank_index = top_rank_index + image_index
1361
+ top_rank_index= top_rank_index.sort().values
1362
+
1363
+ start_index = image_index + image_tokens[i]
1364
+ new_input_embeds = torch.cat([features[i][ :image_index, :] ,features[i][ top_rank_index, :], features[i][start_index:, :]], dim=0)
1365
+
1366
+ new_labels = torch.cat([labels[i][ :image_index],labels[i][ top_rank_index], labels[i][start_index:]], dim=0)
1367
+ new_attention_mask = torch.cat([attention_mask[i][:image_index], attention_mask[i][top_rank_index], attention_mask[i][start_index:]], dim=0)
1368
+
1369
+ features_list.append(new_input_embeds)
1370
+ attention_mask_list.append(new_attention_mask)
1371
+ labels_list.append(new_labels)
1372
+
1373
+ # Truncate sequences to max length as image embeddings can make the sequence longer
1374
+ tokenizer_model_max_length = getattr(self.config, 'tokenizer_model_max_length', None)
1375
+ if tokenizer_model_max_length is not None:
1376
+ new_input_embeds = [x[:tokenizer_model_max_length] for x in features_list]
1377
+ new_attention_mask = [x[:tokenizer_model_max_length] for x in attention_mask_list]
1378
+ new_labels = [x[:tokenizer_model_max_length] for x in labels_list]
1379
+
1380
+ max_len = max(x.shape[0] for x in new_input_embeds)
1381
+
1382
+ # padding the sequences to form batch
1383
+ embeds_padded=[]
1384
+ labels_paded=[]
1385
+ attention_mask_padded=[]
1386
+ position_ids = torch.zeros((batch_size, max_len), dtype=position_ids.dtype, device=position_ids.device)
1387
+ for i, (cur_new_embed, cur_new_labels) in enumerate(zip(new_input_embeds, new_labels)):
1388
+ cur_len_emb=cur_new_embed.shape[0]
1389
+ dif=max_len - cur_len_emb # padding to longest seq
1390
+
1391
+ cur_new_embed = torch.cat([cur_new_embed,torch.zeros((dif, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device)],dim=0)
1392
+ cur_new_labels = torch.cat([cur_new_labels,torch.full((dif,),IGNORE_INDEX,dtype=cur_new_labels.dtype, device=cur_new_labels.device)],dim=0)
1393
+ cur_attention_mask = new_attention_mask[i]
1394
+ cur_attention_mask = torch.cat([cur_attention_mask,torch.full((dif,),False, dtype=cur_attention_mask.dtype, device=cur_attention_mask.device)],dim=0)
1395
+
1396
+ embeds_padded.append(cur_new_embed)
1397
+ labels_paded.append(cur_new_labels)
1398
+ attention_mask_padded.append(cur_attention_mask)
1399
+
1400
+ cur_len = new_attention_mask[i].sum().item()
1401
+ position_ids[i, :cur_len] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
1402
+
1403
+
1404
+ new_input_embeds = torch.stack(embeds_padded,dim=0)
1405
+ new_input_embeds = new_input_embeds.to(features[0].dtype)
1406
+
1407
+ new_attention_mask = torch.stack(attention_mask_padded,dim=0)
1408
+ new_labels = torch.stack(labels_paded,dim=0)
1409
+
1410
+ if _position_ids is None:
1411
+ position_ids = None
1412
+ if _labels is None:
1413
+ new_labels = None
1414
+
1415
+ if _attention_mask is None:
1416
+ new_attention_mask = None
1417
+ else:
1418
+ new_attention_mask = new_attention_mask.to(dtype=_attention_mask.dtype)
1419
+
1420
+ return position_ids, new_attention_mask, new_input_embeds, new_labels
1421
+
1422
+ else:
1423
+ raise ValueError(f"Unexpected tokenizer_padding_side: {self.config.tokenizer_padding_side}")
1424
+
1425
+
1426
+ class Qwen2ForCausalLM_Flash(Qwen2PreTrainedModel):
1427
+ _tied_weights_keys = ["lm_head.weight"]
1428
+
1429
+ def __init__(self, config):
1430
+ super().__init__(config)
1431
+ self.model = Qwen2Model_Flash(config)
1432
+ self.vocab_size = config.vocab_size
1433
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1434
+
1435
+ # Initialize weights and apply final processing
1436
+ self.post_init()
1437
+
1438
+ def get_input_embeddings(self):
1439
+ return self.model.embed_tokens
1440
+
1441
+ def set_input_embeddings(self, value):
1442
+ self.model.embed_tokens = value
1443
+
1444
+ def get_output_embeddings(self):
1445
+ return self.lm_head
1446
+
1447
+ def set_output_embeddings(self, new_embeddings):
1448
+ self.lm_head = new_embeddings
1449
+
1450
+ def set_decoder(self, decoder):
1451
+ self.model = decoder
1452
+
1453
+ def get_decoder(self):
1454
+ return self.model
1455
+
1456
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1457
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1458
+ def forward(
1459
+ self,
1460
+ input_ids: torch.LongTensor = None,
1461
+ attention_mask: Optional[torch.Tensor] = None,
1462
+ position_ids: Optional[torch.LongTensor] = None,
1463
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1464
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1465
+ labels: Optional[torch.LongTensor] = None,
1466
+ use_cache: Optional[bool] = None,
1467
+ output_attentions: Optional[bool] = None,
1468
+ output_hidden_states: Optional[bool] = None,
1469
+ return_dict: Optional[bool] = None,
1470
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1471
+ r"""
1472
+ Args:
1473
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1474
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1475
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1476
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1477
+
1478
+ Returns:
1479
+
1480
+ Example:
1481
+
1482
+ ```python
1483
+ >>> from transformers import AutoTokenizer, Qwen2ForCausalLM
1484
+
1485
+ >>> model = Qwen2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1486
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1487
+
1488
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1489
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1490
+
1491
+ >>> # Generate
1492
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1493
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1494
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1495
+ ```"""
1496
+
1497
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1498
+ output_hidden_states = (
1499
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1500
+ )
1501
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1502
+
1503
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1504
+ outputs, labels = self.model(
1505
+ input_ids=input_ids,
1506
+ attention_mask=attention_mask,
1507
+ position_ids=position_ids,
1508
+ past_key_values=past_key_values,
1509
+ inputs_embeds=inputs_embeds,
1510
+ use_cache=use_cache,
1511
+ output_attentions=output_attentions,
1512
+ output_hidden_states=output_hidden_states,
1513
+ return_dict=return_dict,
1514
+ labels=labels
1515
+ )
1516
+
1517
+ hidden_states = outputs[0]
1518
+ logits = self.lm_head(hidden_states)
1519
+ logits = logits.float()
1520
+
1521
+ loss = None
1522
+ if labels is not None:
1523
+ # Shift so that tokens < n predict n
1524
+ shift_logits = logits[..., :-1, :].contiguous()
1525
+ shift_labels = labels[..., 1:].contiguous()
1526
+ # Flatten the tokens
1527
+ loss_fct = CrossEntropyLoss()
1528
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1529
+ shift_labels = shift_labels.view(-1)
1530
+ # Enable model parallelism
1531
+ shift_labels = shift_labels.to(shift_logits.device)
1532
+ loss = loss_fct(shift_logits, shift_labels)
1533
+
1534
+ if not return_dict:
1535
+ output = (logits,) + outputs[1:]
1536
+ return (loss,) + output if loss is not None else output
1537
+
1538
+ return CausalLMOutputWithPast(
1539
+ loss=loss,
1540
+ logits=logits,
1541
+ past_key_values=outputs.past_key_values,
1542
+ hidden_states=outputs.hidden_states,
1543
+ attentions=outputs.attentions,
1544
+ )
1545
+
1546
+ def prepare_inputs_for_generation(
1547
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1548
+ ):
1549
+ # Omit tokens covered by past_key_values
1550
+ if past_key_values is not None:
1551
+ if isinstance(past_key_values, Cache):
1552
+ cache_length = past_key_values.get_seq_length()
1553
+ past_length = past_key_values.seen_tokens
1554
+ max_cache_length = past_key_values.get_max_length()
1555
+ else:
1556
+ cache_length = past_length = past_key_values[0][0].shape[2]
1557
+ max_cache_length = None
1558
+
1559
+ # Keep only the unprocessed tokens:
1560
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1561
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1562
+ # input)
1563
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1564
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1565
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1566
+ # input_ids based on the past_length.
1567
+ elif past_length < input_ids.shape[1]:
1568
+ input_ids = input_ids[:, past_length:]
1569
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1570
+
1571
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1572
+ if (
1573
+ max_cache_length is not None
1574
+ and attention_mask is not None
1575
+ and cache_length + input_ids.shape[1] > max_cache_length
1576
+ ):
1577
+ attention_mask = attention_mask[:, -max_cache_length:]
1578
+
1579
+ position_ids = kwargs.get("position_ids", None)
1580
+ if attention_mask is not None and position_ids is None:
1581
+ # create position_ids on the fly for batch generation
1582
+ position_ids = attention_mask.long().cumsum(-1) - 1
1583
+ position_ids.masked_fill_(attention_mask == 0, 1)
1584
+ if past_key_values:
1585
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1586
+
1587
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1588
+ if inputs_embeds is not None and past_key_values is None:
1589
+ model_inputs = {"inputs_embeds": inputs_embeds}
1590
+ else:
1591
+ model_inputs = {"input_ids": input_ids}
1592
+
1593
+ model_inputs.update(
1594
+ {
1595
+ "position_ids": position_ids,
1596
+ "past_key_values": past_key_values,
1597
+ "use_cache": kwargs.get("use_cache"),
1598
+ "attention_mask": attention_mask,
1599
+ }
1600
+ )
1601
+ return model_inputs
1602
+
1603
+ @staticmethod
1604
+ def _reorder_cache(past_key_values, beam_idx):
1605
+ reordered_past = ()
1606
+ for layer_past in past_key_values:
1607
+ reordered_past += (
1608
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1609
+ )
1610
+ return reordered_past
1611
+
.ipynb_checkpoints/modeling_videochat_flash-checkpoint.py ADDED
@@ -0,0 +1,732 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from abc import ABC, abstractmethod
16
+ import re
17
+ import torch
18
+ import torch.nn as nn
19
+ import random
20
+ from typing import List, Optional, Tuple, Union, Dict
21
+
22
+ from transformers import AutoConfig, AutoModelForCausalLM
23
+ from transformers.modeling_outputs import CausalLMOutputWithPast
24
+ from transformers.generation.utils import GenerateOutput
25
+ from transformers import Qwen2Config
26
+
27
+ from .vision_tower_builder import build_vision_tower
28
+ from .mm_projector_builder import build_vision_projector
29
+
30
+ from .constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, DEFAULT_IMAGE_TOKEN
31
+ from .conversation import conv_templates, SeparatorStyle
32
+ from .mm_utils import tokenizer_image_token, KeywordsStoppingCriteria, get_anyres_image_grid_shape, load_video
33
+ # from .modeling_qwen2_flash import Qwen2Model_Flash, Qwen2ForCausalLM_Flash
34
+ # from .modeling_qwen2_flash_v7 import Qwen2Model_Flash, Qwen2ForCausalLM_Flash
35
+ from .modeling_qwen2_flash import Qwen2Model_Flash, Qwen2ForCausalLM_Flash
36
+
37
+
38
+ class LlavaMetaModel:
39
+
40
+ def __init__(self, config):
41
+ super(LlavaMetaModel, self).__init__(config)
42
+
43
+ if hasattr(config, "mm_vision_tower"):
44
+ delay_load = getattr(config, "delay_load", False)
45
+ self.vision_tower = build_vision_tower(config, delay_load=delay_load)
46
+ self.mm_projector = build_vision_projector(config, vision_cfg=self.vision_tower.config)
47
+
48
+ if "unpad" in getattr(config, "mm_patch_merge_type", ""):
49
+ self.image_newline = nn.Parameter(torch.empty(config.hidden_size, dtype=self.dtype))
50
+ if "nopad" in getattr(config, "mm_patch_merge_type", "") and getattr(self.config, "mm_newline_position", "nothing") != "nothing":
51
+ self.frame_newline = nn.Parameter(torch.empty(config.hidden_size, dtype=self.dtype))
52
+
53
+ def get_vision_tower(self):
54
+ vision_tower = getattr(self, "vision_tower", None)
55
+ if type(vision_tower) is list:
56
+ vision_tower = vision_tower[0]
57
+ return vision_tower
58
+
59
+ def initialize_vision_modules(self, model_args, fsdp=None):
60
+ vision_tower = model_args.vision_tower
61
+ mm_vision_select_layer = model_args.mm_vision_select_layer
62
+ mm_vision_select_feature = model_args.mm_vision_select_feature
63
+ pretrain_mm_mlp_adapter = model_args.pretrain_mm_mlp_adapter
64
+ mm_patch_merge_type = model_args.mm_patch_merge_type
65
+
66
+ self.config.mm_vision_tower = vision_tower
67
+ self.config.vision_tower_pretrained = getattr(model_args, "vision_tower_pretrained", "")
68
+
69
+ if self.get_vision_tower() is None:
70
+ vision_tower = build_vision_tower(model_args)
71
+
72
+ if fsdp is not None and len(fsdp) > 0:
73
+ self.vision_tower = [vision_tower]
74
+ else:
75
+ self.vision_tower = vision_tower
76
+ else:
77
+ if fsdp is not None and len(fsdp) > 0:
78
+ vision_tower = self.vision_tower[0]
79
+ else:
80
+ vision_tower = self.vision_tower
81
+ vision_tower.load_model()
82
+
83
+
84
+
85
+ self.config.use_mm_proj = True
86
+ self.config.mm_projector_type = getattr(model_args, "mm_projector_type", "linear")
87
+ self.config.mm_vision_select_layer = mm_vision_select_layer
88
+ self.config.mm_vision_select_feature = mm_vision_select_feature
89
+ self.config.mm_patch_merge_type = mm_patch_merge_type
90
+
91
+ if getattr(self, "mm_projector", None) is None:
92
+ self.mm_projector = build_vision_projector(self.config, vision_cfg=vision_tower.config)
93
+
94
+ if "unpad" in mm_patch_merge_type:
95
+ embed_std = 1 / torch.sqrt(torch.tensor(self.config.hidden_size, dtype=self.dtype))
96
+ self.image_newline = nn.Parameter(torch.randn(self.config.hidden_size, dtype=self.dtype) * embed_std)
97
+ if "nopad" in getattr(self.config, "mm_patch_merge_type", "") and getattr(self.config, "mm_newline_position", "nothing") != "nothing":
98
+ embed_std = 1 / torch.sqrt(torch.tensor(self.config.hidden_size, dtype=self.dtype))
99
+ self.frame_newline = nn.Parameter(torch.randn(self.config.hidden_size, dtype=self.dtype) * embed_std)
100
+ else:
101
+ # In case it is frozen by LoRA
102
+ for p in self.mm_projector.parameters():
103
+ p.requires_grad = True
104
+
105
+ if pretrain_mm_mlp_adapter is not None:
106
+ mm_projector_weights = torch.load(pretrain_mm_mlp_adapter, map_location="cpu")
107
+
108
+ def get_w(weights, keyword):
109
+ return {k.split(keyword + ".")[1]: v for k, v in weights.items() if keyword in k}
110
+
111
+ if self.config.mm_projector_type =='lxh_qformer':
112
+ incompatible_keys = self.mm_projector.load_state_dict(get_w(mm_projector_weights, "mm_projector"), strict=False)
113
+ else:
114
+ incompatible_keys = self.mm_projector.load_state_dict(get_w(mm_projector_weights, "mm_projector"))
115
+ print(f"Loaded mm projector weights from {pretrain_mm_mlp_adapter}. Incompatible keys: {incompatible_keys}")
116
+
117
+
118
+ class LlavaMetaForCausalLM(ABC):
119
+
120
+ @abstractmethod
121
+ def get_model(self):
122
+ pass
123
+
124
+ def get_vision_tower(self):
125
+ return self.get_model().get_vision_tower()
126
+
127
+
128
+ def encode_video_image(self, images_list, video_idx_in_batch):
129
+ # video encoder编码后按图像的connector处理
130
+ bs = len(images_list)
131
+
132
+ concat_images = []
133
+ concat_videos = []
134
+ for idx, image in enumerate(images_list):
135
+ if idx in video_idx_in_batch:
136
+ concat_videos.append(image)
137
+ else:
138
+ concat_images.append(image)
139
+ # print(concat_videos[0].shape)
140
+ has_image = len(concat_images) > 0
141
+ has_video = len(concat_videos) > 0
142
+
143
+ mm_local_num_frames = getattr(self.config, "mm_local_num_frames", -1)
144
+ assert mm_local_num_frames != -1
145
+ if has_image:
146
+ image_split_sizes = [image.shape[0] for image in concat_images]
147
+ concat_images = torch.cat([image.unsqueeze(1) for image in concat_images], dim=0)
148
+ # print("input vit image.shape:", concat_images.shape)
149
+ images_features = self.get_model().get_vision_tower()(concat_images) # B_i, N, D
150
+ images_features = torch.split(images_features, image_split_sizes)
151
+
152
+ if has_video:
153
+ video_split_sizes = [video.shape[0] // mm_local_num_frames for video in concat_videos]
154
+ concat_videos = torch.cat([video.reshape(video.shape[0] // mm_local_num_frames, mm_local_num_frames, video.shape[1], video.shape[2], video.shape[3]) for video in concat_videos], dim=0)
155
+ # print("input vit video.shape:", concat_videos.shape)
156
+ videos_features = self.get_model().get_vision_tower()(concat_videos) # B_v, N, D
157
+ videos_features = [v.reshape(-1, v.shape[-2] // mm_local_num_frames, v.shape[-1]) for v in torch.split(videos_features, video_split_sizes)]
158
+
159
+
160
+ all_videos_or_images_features = []
161
+ img_idx = 0
162
+ vid_idx = 0
163
+
164
+ for idx in range(bs):
165
+
166
+ if idx in video_idx_in_batch:
167
+ feat = self.get_model().mm_projector(videos_features[vid_idx], compress=True, local_num_frames=getattr(self.config, "mm_local_num_frames", -1))
168
+
169
+ vid_idx += 1
170
+ else:
171
+ feat = self.get_model().mm_projector(images_features[img_idx], compress=False)
172
+ img_idx += 1
173
+ # print("video_idx_in_batch:", video_idx_in_batch)
174
+ all_videos_or_images_features.append(feat)
175
+
176
+ if has_video:
177
+ assert vid_idx == len(videos_features), f"vid: {vid_idx} != {len(videos_features)}"
178
+ if has_image:
179
+ assert img_idx == len(images_features), f"img: {img_idx} != {len(images_features)}"
180
+
181
+ return all_videos_or_images_features
182
+
183
+
184
+
185
+ def prepare_inputs_labels_for_multimodal(self, input_ids, position_ids, attention_mask, past_key_values, labels, images, modalities=["image"], image_sizes=None):
186
+ assert type(modalities) is list, modalities
187
+ mm_llm_compress = getattr(self.config, "mm_llm_compress", False)
188
+
189
+ if mm_llm_compress:
190
+ self.model.llm_compress_type = getattr(self.config, "llm_compress_type", "attention")
191
+ self.model.llm_compress_layer_list = getattr(self.config, "llm_compress_layer_list", [8, 16, 24])
192
+ self.model.llm_image_token_ratio_list = getattr(self.config, "llm_image_token_ratio_list", [1.0, 0.5, 0.25, 0.125])
193
+ first_image_token_position = []
194
+ text_prompt_lens = []
195
+ else:
196
+ self.model.llm_compress_type = "attention"
197
+ self.model.llm_compress_layer_list = []
198
+ self.model.llm_image_token_ratio_list = []
199
+ first_image_token_position = []
200
+ text_prompt_lens = []
201
+
202
+ if images is None:
203
+ return input_ids, position_ids, attention_mask, past_key_values, None, labels
204
+
205
+ vision_tower = self.get_vision_tower()
206
+ # rank_print(modalities)
207
+ if vision_tower is None or images is None or input_ids.shape[1] == 1:
208
+ return input_ids, position_ids, attention_mask, past_key_values, None, labels
209
+
210
+ if type(images) is list or images.ndim == 5:
211
+ if type(images) is list:
212
+ images = [x.unsqueeze(0) if x.ndim == 3 else x for x in images]
213
+
214
+ video_idx_in_batch = []
215
+ for _ in range(len(modalities)):
216
+ if modalities[_] == "video":
217
+ video_idx_in_batch.append(_)
218
+
219
+ images_list = []
220
+ for image in images:
221
+ if image.ndim == 4:
222
+ images_list.append(image)
223
+ else:
224
+ images_list.append(image.unsqueeze(0))
225
+
226
+
227
+ vision_encode_type = getattr(self.config, "vision_encode_type", "image")
228
+ mm_patch_merge_type = getattr(self.config, "mm_patch_merge_type", "flat")
229
+ image_aspect_ratio = getattr(self.config, "image_aspect_ratio", "square")
230
+ frame_aspect_ratio = getattr(self.config, "frame_aspect_ratio", "square")
231
+ mm_newline_position = getattr(self.config, "mm_newline_position", "nothing")
232
+
233
+
234
+ if vision_encode_type == "video_image": # video backbone, process video with compress
235
+ image_features = self.encode_video_image(images_list, video_idx_in_batch=video_idx_in_batch)
236
+ else:
237
+ raise NotImplementedError(vision_encode_type)
238
+
239
+
240
+ if mm_patch_merge_type == "flat":
241
+ image_features = [x.flatten(0, 1) for x in image_features]
242
+ elif mm_patch_merge_type.startswith("spatial"):
243
+ new_image_features = []
244
+ for image_idx, image_feature in enumerate(image_features):
245
+
246
+ if image_idx in video_idx_in_batch: # video operations
247
+
248
+ if "anyres" in frame_aspect_ratio:
249
+ raise NotImplementedError
250
+ else:
251
+ frame_feature = image_feature
252
+
253
+ if "pad" in mm_patch_merge_type:
254
+ if mm_newline_position == 'one_token':
255
+ frame_feature = frame_feature.flatten(0, 1)
256
+ if "unpad" in mm_patch_merge_type:
257
+ frame_feature = torch.cat((frame_feature, self.model.image_newline[None].to(frame_feature.device)), dim=0)
258
+ else:
259
+ frame_feature = torch.cat((frame_feature, self.model.frame_newline[None].to(frame_feature.device)), dim=0)
260
+ elif mm_newline_position == 'nothing':
261
+ frame_feature = frame_feature.flatten(0, 1)
262
+ else:
263
+ raise NotImplementedError("add pad please!!")
264
+ else:
265
+ frame_feature = frame_feature.flatten(0, 1)
266
+
267
+ # print(f"final video frame_feature.shape: {frame_feature.shape}")
268
+ image_feature = frame_feature
269
+
270
+ elif image_feature.shape[0] > 1: # multi patches and multi images operations
271
+ base_image_feature = image_feature[0]
272
+ image_feature = image_feature[1:]
273
+ origin_size = image_feature.shape
274
+
275
+ height = width = self.get_model().mm_projector.num_image_patches_per_side
276
+ assert height * width == base_image_feature.shape[0], f"height:{height}, width: {width}, base_image_feature: {base_image_feature.shape}"
277
+
278
+ if "anyres_max" in image_aspect_ratio:
279
+ matched_anyres_max_num_patches = re.match(r"anyres_max_(\d+)", image_aspect_ratio)
280
+ if matched_anyres_max_num_patches:
281
+ max_num_patches = int(matched_anyres_max_num_patches.group(1))
282
+
283
+ if "anyres" in image_aspect_ratio:
284
+ if hasattr(self.get_vision_tower(), "image_size"):
285
+ vision_tower_image_size = self.get_vision_tower().image_size
286
+ else:
287
+ raise ValueError("vision_tower_image_size is not found in the vision tower.")
288
+ try:
289
+ num_patch_width, num_patch_height = get_anyres_image_grid_shape(image_sizes[image_idx], self.config.image_grid_pinpoints, vision_tower_image_size, max_resolutions=None)
290
+ except Exception as e:
291
+ print(f"Error: {e}")
292
+ raise e
293
+ # num_patch_width, num_patch_height = 2, 2
294
+
295
+ image_feature = image_feature.view(num_patch_height, num_patch_width, height, width, -1)
296
+ else:
297
+ raise NotImplementedError(image_aspect_ratio)
298
+ image_feature = image_feature.view(2, 2, height, width, -1)
299
+
300
+ if "maxpool2x2" in mm_patch_merge_type:
301
+ raise NotImplementedError
302
+ elif "unpad" in mm_patch_merge_type and "anyres_max" in image_aspect_ratio and matched_anyres_max_num_patches:
303
+ raise NotImplementedError
304
+ elif "unpad" in mm_patch_merge_type:
305
+ raise NotImplementedError
306
+ else:
307
+ image_feature = image_feature.permute(0, 2, 1, 3, 4).contiguous()
308
+ image_feature = image_feature.flatten(0, 3)
309
+ if "nobase" in mm_patch_merge_type:
310
+ pass
311
+ else:
312
+ try:
313
+ image_feature = torch.cat((base_image_feature, image_feature), dim=0)
314
+ except Exception as e:
315
+ raise ValueError(f"{num_patch_width} {num_patch_height} now: base_image_feature: {base_image_feature.shape}, {image_feature.shape}, image_sizes[image_idx]: {image_sizes[image_idx]}, origin_size: {origin_size}, {image_sizes[image_idx]}, {self.config.image_grid_pinpoints}, {vision_tower_image_size}")
316
+ else: # single image operations
317
+ image_feature = image_feature[0]
318
+ if "unpad" in mm_patch_merge_type:
319
+ image_feature = torch.cat((image_feature, self.model.image_newline[None]), dim=0)
320
+
321
+ # print(f"image/video_feature.shape: {image_feature.shape}")
322
+ new_image_features.append(image_feature)
323
+ image_features = new_image_features
324
+ else:
325
+ raise ValueError(f"Unexpected mm_patch_merge_type: {self.config.mm_patch_merge_type}")
326
+ else:
327
+ # raise NotImplementedError(f"images.shape={images.shape}, modalities={modalities}")
328
+ image_features = self.encode_image(images)
329
+
330
+ # TODO: image start / end is not implemented here to support pretraining.
331
+ if getattr(self.config, "tune_mm_mlp_adapter", False) and getattr(self.config, "mm_use_im_start_end", False):
332
+ raise NotImplementedError
333
+ # print(f"Total images len(image_features: {len(image_features)}")
334
+
335
+ # Let's just add dummy tensors if they do not exist,
336
+ # it is a headache to deal with None all the time.
337
+ # But it is not ideal, and if you have a better idea,
338
+ # please open an issue / submit a PR, thanks.
339
+ _labels = labels
340
+ _position_ids = position_ids
341
+ _attention_mask = attention_mask
342
+ if attention_mask is None:
343
+ attention_mask = torch.ones_like(input_ids, dtype=torch.bool)
344
+ else:
345
+ attention_mask = attention_mask.bool()
346
+ if position_ids is None:
347
+ position_ids = torch.arange(0, input_ids.shape[1], dtype=torch.long, device=input_ids.device)
348
+ if labels is None:
349
+ labels = torch.full_like(input_ids, IGNORE_INDEX)
350
+
351
+
352
+ input_ids = [cur_input_ids[cur_attention_mask] for cur_input_ids, cur_attention_mask in zip(input_ids, attention_mask)]
353
+ labels = [cur_labels[cur_attention_mask] for cur_labels, cur_attention_mask in zip(labels, attention_mask)]
354
+
355
+ new_input_embeds = []
356
+ new_labels = []
357
+ cur_image_idx = 0
358
+
359
+ mm_llm_compress = getattr(self.config, "mm_llm_compress", False)
360
+
361
+ if mm_llm_compress:
362
+ self.model.llm_compress_type = getattr(self.config, "llm_compress_type", "attention")
363
+ self.model.llm_compress_layer_list = getattr(self.config, "llm_compress_layer_list", [8, 16, 24])
364
+ self.model.llm_image_token_ratio_list = getattr(self.config, "llm_image_token_ratio_list", [1.0, 0.5, 0.25, 0.125])
365
+ first_image_token_position = []
366
+ text_prompt_lens = []
367
+ else:
368
+ self.model.llm_compress_type = "attention"
369
+ self.model.llm_compress_layer_list = []
370
+ self.model.llm_image_token_ratio_list = []
371
+ first_image_token_position = []
372
+ text_prompt_lens = []
373
+
374
+ # rank_print("Inserting Images embedding")
375
+ for batch_idx, cur_input_ids in enumerate(input_ids):
376
+ num_images = (cur_input_ids == IMAGE_TOKEN_INDEX).sum()
377
+
378
+ if mm_llm_compress:
379
+ ####### copy from pdrop, only support single image/video NOTE ##################
380
+ # record image position for further dropping
381
+ image_index = torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0].tolist()
382
+ assert len(image_index) == 1, f"Only support singe/video: {image_index}"
383
+ if image_index == []:
384
+ first_image_token_position.append(-1)
385
+ else:
386
+ first_image_token_position.append(image_index[0])
387
+
388
+
389
+ # record input instruction length in inference mode
390
+ if not self.training:
391
+ if image_index == []:
392
+ assert num_images == 0, num_images
393
+ else:
394
+ assert num_images == 1, f"num_images={num_images}"
395
+ text_prompt_lens.append(cur_input_ids.shape[0] - num_images) # consider image place holder
396
+
397
+ ###############################################
398
+
399
+ # print(f"num_images={num_images}")
400
+ if num_images == 0:
401
+ cur_image_features = image_features[cur_image_idx]
402
+ cur_input_embeds_1 = self.get_model().embed_tokens(cur_input_ids)
403
+ cur_input_embeds = torch.cat([cur_input_embeds_1, cur_image_features[0:0]], dim=0)
404
+ new_input_embeds.append(cur_input_embeds)
405
+ new_labels.append(labels[batch_idx])
406
+ cur_image_idx += 1
407
+ continue
408
+
409
+ image_token_indices = [-1] + torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0].tolist() + [cur_input_ids.shape[0]]
410
+ cur_input_ids_noim = []
411
+ cur_labels = labels[batch_idx]
412
+ cur_labels_noim = []
413
+ for i in range(len(image_token_indices) - 1):
414
+ cur_input_ids_noim.append(cur_input_ids[image_token_indices[i] + 1 : image_token_indices[i + 1]])
415
+ cur_labels_noim.append(cur_labels[image_token_indices[i] + 1 : image_token_indices[i + 1]])
416
+ split_sizes = [x.shape[0] for x in cur_labels_noim]
417
+ cur_input_embeds = self.get_model().embed_tokens(torch.cat(cur_input_ids_noim))
418
+ cur_input_embeds_no_im = torch.split(cur_input_embeds, split_sizes, dim=0)
419
+ cur_new_input_embeds = []
420
+ cur_new_labels = []
421
+
422
+ for i in range(num_images + 1):
423
+ cur_new_input_embeds.append(cur_input_embeds_no_im[i])
424
+ cur_new_labels.append(cur_labels_noim[i])
425
+ if i < num_images:
426
+ try:
427
+ cur_image_features = image_features[cur_image_idx]
428
+ except IndexError:
429
+ print(f"cur_image_idx={cur_image_idx} is not ok")
430
+ cur_image_features = image_features[cur_image_idx - 1]
431
+ cur_image_idx += 1
432
+ cur_new_input_embeds.append(cur_image_features)
433
+ cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=cur_labels.device, dtype=cur_labels.dtype))
434
+
435
+ cur_new_input_embeds = [x.to(self.device) for x in cur_new_input_embeds]
436
+
437
+ # import pdb; pdb.set_trace()
438
+ cur_new_input_embeds = torch.cat(cur_new_input_embeds)
439
+ cur_new_labels = torch.cat(cur_new_labels)
440
+
441
+ new_input_embeds.append(cur_new_input_embeds)
442
+ new_labels.append(cur_new_labels)
443
+
444
+
445
+ if mm_llm_compress:
446
+ self.model.first_image_token_position = first_image_token_position
447
+ self.model.text_prompt_lens = text_prompt_lens
448
+ self.model.num_image_token_lens = [image_feature.shape[0] for image_feature in image_features]
449
+
450
+ # Truncate sequences to max length as image embeddings can make the sequence longer
451
+ tokenizer_model_max_length = getattr(self.config, "tokenizer_model_max_length", None)
452
+ # rank_print("Finishing Inserting")
453
+
454
+ new_input_embeds = [x[:tokenizer_model_max_length] for x, modality in zip(new_input_embeds, modalities)]
455
+ new_labels = [x[:tokenizer_model_max_length] for x, modality in zip(new_labels, modalities)]
456
+
457
+ # Combine them
458
+ max_len = max(x.shape[0] for x in new_input_embeds)
459
+ batch_size = len(new_input_embeds)
460
+
461
+ new_input_embeds_padded = []
462
+ new_labels_padded = torch.full((batch_size, max_len), IGNORE_INDEX, dtype=new_labels[0].dtype, device=new_labels[0].device)
463
+ attention_mask = torch.zeros((batch_size, max_len), dtype=attention_mask.dtype, device=attention_mask.device)
464
+ position_ids = torch.zeros((batch_size, max_len), dtype=position_ids.dtype, device=position_ids.device)
465
+ # print("Prepare pos id")
466
+
467
+ for i, (cur_new_embed, cur_new_labels) in enumerate(zip(new_input_embeds, new_labels)):
468
+ cur_len = cur_new_embed.shape[0]
469
+ if getattr(self.config, "tokenizer_padding_side", "right") == "left":
470
+ new_input_embeds_padded.append(torch.cat((torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device), cur_new_embed), dim=0))
471
+ if cur_len > 0:
472
+ new_labels_padded[i, -cur_len:] = cur_new_labels
473
+ attention_mask[i, -cur_len:] = True
474
+ position_ids[i, -cur_len:] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
475
+ else:
476
+ new_input_embeds_padded.append(torch.cat((cur_new_embed, torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device)), dim=0))
477
+ if cur_len > 0:
478
+ new_labels_padded[i, :cur_len] = cur_new_labels
479
+ attention_mask[i, :cur_len] = True
480
+ position_ids[i, :cur_len] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
481
+
482
+ new_input_embeds = torch.stack(new_input_embeds_padded, dim=0)
483
+ # print("tokenizer padding")
484
+
485
+ if _labels is None:
486
+ new_labels = None
487
+ else:
488
+ new_labels = new_labels_padded
489
+
490
+ if _attention_mask is None:
491
+ attention_mask = None
492
+ else:
493
+ attention_mask = attention_mask.to(dtype=_attention_mask.dtype)
494
+
495
+ if _position_ids is None:
496
+ position_ids = None
497
+ if getattr(self.config, "use_pos_skipping", False) and self.training:
498
+ position_ids = torch.arange(new_input_embeds.size(1), device=new_input_embeds.device).unsqueeze(0).to(new_input_embeds.device)
499
+ split_position = random.randint(0, new_input_embeds.size(1))
500
+ left_add = random.randint(0, self.config.pos_skipping_range)
501
+ right_add = random.randint(left_add, self.config.pos_skipping_range)
502
+ position_ids[:, :split_position] += left_add
503
+ position_ids[:, split_position:] += right_add
504
+ # import pdb; pdb.set_trace()
505
+ # print("Finish preparing")
506
+ return None, position_ids, attention_mask, past_key_values, new_input_embeds, new_labels
507
+
508
+ def initialize_vision_tokenizer(self, model_args, tokenizer):
509
+ if model_args.mm_use_im_patch_token:
510
+ tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
511
+ self.resize_token_embeddings(len(tokenizer))
512
+
513
+ if model_args.mm_use_im_start_end:
514
+ num_new_tokens = tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
515
+ self.resize_token_embeddings(len(tokenizer))
516
+
517
+ if num_new_tokens > 0:
518
+ input_embeddings = self.get_input_embeddings().weight.data
519
+ output_embeddings = self.get_output_embeddings().weight.data
520
+
521
+ input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
522
+ output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
523
+
524
+ input_embeddings[-num_new_tokens:] = input_embeddings_avg
525
+ output_embeddings[-num_new_tokens:] = output_embeddings_avg
526
+
527
+ if model_args.tune_mm_mlp_adapter:
528
+ for p in self.get_input_embeddings().parameters():
529
+ p.requires_grad = True
530
+ for p in self.get_output_embeddings().parameters():
531
+ p.requires_grad = False
532
+
533
+ if model_args.pretrain_mm_mlp_adapter:
534
+ mm_projector_weights = torch.load(model_args.pretrain_mm_mlp_adapter, map_location="cpu")
535
+ embed_tokens_weight = mm_projector_weights["model.embed_tokens.weight"]
536
+ assert num_new_tokens == 2
537
+ if input_embeddings.shape == embed_tokens_weight.shape:
538
+ input_embeddings[-num_new_tokens:] = embed_tokens_weight[-num_new_tokens:]
539
+ elif embed_tokens_weight.shape[0] == num_new_tokens:
540
+ input_embeddings[-num_new_tokens:] = embed_tokens_weight
541
+ else:
542
+ raise ValueError(f"Unexpected embed_tokens_weight shape. Pretrained: {embed_tokens_weight.shape}. Current: {input_embeddings.shape}. Numer of new tokens: {num_new_tokens}.")
543
+ elif model_args.mm_use_im_patch_token:
544
+ if model_args.tune_mm_mlp_adapter:
545
+ for p in self.get_input_embeddings().parameters():
546
+ p.requires_grad = False
547
+ for p in self.get_output_embeddings().parameters():
548
+ p.requires_grad = False
549
+
550
+
551
+
552
+ class VideoChatFlashQwenConfig(Qwen2Config):
553
+ model_type = "videochat_flash_qwen"
554
+
555
+
556
+ class VideoChatFlashQwenModel(LlavaMetaModel, Qwen2Model_Flash):
557
+ config_class = VideoChatFlashQwenConfig
558
+
559
+ def __init__(self, config: VideoChatFlashQwenConfig):
560
+ super(VideoChatFlashQwenModel, self).__init__(config)
561
+
562
+
563
+ class VideoChatFlashQwenForCausalLM(LlavaMetaForCausalLM, Qwen2ForCausalLM_Flash):
564
+ config_class = VideoChatFlashQwenConfig
565
+
566
+ def __init__(self, config):
567
+ # super(Qwen2ForCausalLM, self).__init__(config)
568
+ Qwen2ForCausalLM_Flash.__init__(self, config)
569
+ config.model_type = "videochat_flash_qwen"
570
+ # config.rope_scaling = None
571
+
572
+ self.model = VideoChatFlashQwenModel(config)
573
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
574
+ # Initialize weights and apply final processing
575
+ self.post_init()
576
+
577
+ def get_model(self):
578
+ return self.model
579
+
580
+ def forward(
581
+ self,
582
+ input_ids: torch.LongTensor = None,
583
+ attention_mask: Optional[torch.Tensor] = None,
584
+ position_ids: Optional[torch.LongTensor] = None,
585
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
586
+ inputs_embeds: Optional[torch.FloatTensor] = None,
587
+ labels: Optional[torch.LongTensor] = None,
588
+ use_cache: Optional[bool] = None,
589
+ output_attentions: Optional[bool] = None,
590
+ output_hidden_states: Optional[bool] = None,
591
+ images: Optional[torch.FloatTensor] = None,
592
+ image_sizes: Optional[List[List[int]]] = None,
593
+ return_dict: Optional[bool] = None,
594
+ modalities: Optional[List[str]] = ["image"],
595
+ dpo_forward: Optional[bool] = False,
596
+ cache_position=None,
597
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
598
+
599
+ if inputs_embeds is None:
600
+ (input_ids, position_ids, attention_mask, past_key_values, inputs_embeds, labels) = self.prepare_inputs_labels_for_multimodal(input_ids, position_ids, attention_mask, past_key_values, labels, images, modalities, image_sizes)
601
+
602
+ # print("inputs_embeds.shape:", inputs_embeds.shape)
603
+ if dpo_forward:
604
+ raise NotImplementedError
605
+ else:
606
+ return super().forward(
607
+ input_ids=input_ids,
608
+ attention_mask=attention_mask,
609
+ position_ids=position_ids,
610
+ past_key_values=past_key_values,
611
+ inputs_embeds=inputs_embeds,
612
+ labels=labels,
613
+ use_cache=use_cache,
614
+ output_attentions=output_attentions,
615
+ output_hidden_states=output_hidden_states,
616
+ return_dict=return_dict,
617
+ )
618
+
619
+ @torch.no_grad()
620
+ def generate(
621
+ self,
622
+ inputs: Optional[torch.Tensor] = None,
623
+ images: Optional[torch.Tensor] = None,
624
+ image_sizes: Optional[torch.Tensor] = None,
625
+ modalities: Optional[List[str]] = ["image"],
626
+ **kwargs,
627
+ ) -> Union[GenerateOutput, torch.LongTensor]:
628
+ position_ids = kwargs.pop("position_ids", None)
629
+ attention_mask = kwargs.pop("attention_mask", None)
630
+ if "inputs_embeds" in kwargs:
631
+ raise NotImplementedError("`inputs_embeds` is not supported")
632
+
633
+ if images is not None:
634
+ (inputs, position_ids, attention_mask, _, inputs_embeds, _) = self.prepare_inputs_labels_for_multimodal(inputs, position_ids, attention_mask, None, None, images, modalities, image_sizes=image_sizes)
635
+ else:
636
+ self.model.image_token_posi = [-1]
637
+ self.model.prompt_len = None
638
+ self.model.image_tokens = [0]
639
+ inputs_embeds = self.get_model().embed_tokens(inputs)
640
+
641
+ return super().generate(position_ids=position_ids, attention_mask=attention_mask, inputs_embeds=inputs_embeds, **kwargs)
642
+
643
+ @torch.no_grad()
644
+ def chat(self,
645
+ video_path,
646
+ tokenizer,
647
+ user_prompt,
648
+ chat_history=None,
649
+ return_history=True,
650
+ max_num_frames=512,
651
+ media_dict=None,
652
+ generation_config={}):
653
+
654
+ frames, time_msg = load_video(video_path, max_num_frames=max_num_frames, media_dict=media_dict)
655
+
656
+ image_sizes = [frames[0].shape[:2]]
657
+
658
+ frames = [self.get_vision_tower().image_processor.preprocess(frames, return_tensors="pt")["pixel_values"].to(self.model.dtype).cuda()]
659
+
660
+ conv = conv_templates["qwen_2"].copy()
661
+
662
+ if chat_history is None or len(chat_history) == 0:
663
+ user_prompt = f'{DEFAULT_IMAGE_TOKEN}\n{time_msg.strip()} {user_prompt}'
664
+ else:
665
+ assert DEFAULT_IMAGE_TOKEN in chat_history[0]['content'], chat_history
666
+ for msg in chat_history:
667
+ conv.append_message(msg['role'], msg['content'])
668
+
669
+ conv.append_message(conv.roles[0], user_prompt)
670
+ conv.append_message(conv.roles[1], None)
671
+
672
+ prompt = conv.get_prompt()
673
+
674
+ input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).cuda()
675
+
676
+ if tokenizer.pad_token_id is None:
677
+ if "qwen" in tokenizer.name_or_path.lower():
678
+ print("Setting pad token to bos token for qwen model.")
679
+ tokenizer.pad_token_id = 151643
680
+
681
+ attention_masks = input_ids.ne(tokenizer.pad_token_id).long().cuda()
682
+
683
+ stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
684
+ keywords = [stop_str]
685
+ stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
686
+
687
+ with torch.inference_mode():
688
+ output_ids = self.generate(
689
+ inputs=input_ids,
690
+ images=frames,
691
+ attention_mask=attention_masks,
692
+ modalities=["video"],
693
+ image_sizes=image_sizes,
694
+ use_cache=True,
695
+ stopping_criteria=[stopping_criteria],
696
+ **generation_config
697
+ )
698
+
699
+ outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
700
+ if outputs.endswith(stop_str):
701
+ outputs = outputs[: -len(stop_str)]
702
+
703
+ outputs = outputs.strip()
704
+
705
+ # print(f"\033[91m== Question: \033[0m\n{prompt}\n")
706
+ # print(f"\033[91m== Response: \033[0m\n{outputs}\n")
707
+
708
+ if chat_history is None:
709
+ chat_history = []
710
+
711
+ chat_history.append({"role":conv.roles[0], "content":user_prompt})
712
+ chat_history.append({"role":conv.roles[1], "content":outputs})
713
+ if return_history:
714
+ return outputs, chat_history
715
+ else:
716
+ return outputs
717
+
718
+
719
+
720
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
721
+ images = kwargs.pop("images", None)
722
+ image_sizes = kwargs.pop("image_sizes", None)
723
+ inputs = super().prepare_inputs_for_generation(input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs)
724
+ if images is not None:
725
+ inputs["images"] = images
726
+ if image_sizes is not None:
727
+ inputs["image_sizes"] = image_sizes
728
+ return inputs
729
+
730
+
731
+ AutoConfig.register("videochat_flash_qwen", VideoChatFlashQwenConfig)
732
+ AutoModelForCausalLM.register(VideoChatFlashQwenConfig, VideoChatFlashQwenForCausalLM)
added_tokens.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</tool_call>": 151658,
3
+ "<tool_call>": 151657,
4
+ "<|box_end|>": 151649,
5
+ "<|box_start|>": 151648,
6
+ "<|endoftext|>": 151643,
7
+ "<|file_sep|>": 151664,
8
+ "<|fim_middle|>": 151660,
9
+ "<|fim_pad|>": 151662,
10
+ "<|fim_prefix|>": 151659,
11
+ "<|fim_suffix|>": 151661,
12
+ "<|im_end|>": 151645,
13
+ "<|im_start|>": 151644,
14
+ "<|image_pad|>": 151655,
15
+ "<|object_ref_end|>": 151647,
16
+ "<|object_ref_start|>": 151646,
17
+ "<|quad_end|>": 151651,
18
+ "<|quad_start|>": 151650,
19
+ "<|repo_name|>": 151663,
20
+ "<|video_pad|>": 151656,
21
+ "<|vision_end|>": 151653,
22
+ "<|vision_pad|>": 151654,
23
+ "<|vision_start|>": 151652
24
+ }
config.json ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/inspire/hdd/ws-f4d69b29-e0a5-44e6-bd92-acf4de9990f0/public-project/xiacheng-240108120111/new_VideoChat-Flash-Qwen2_5-7B-1M_res224/videochat_flash-2_128",
3
+ "architectures": [
4
+ "VideoChatFlashQwenForCausalLM"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "auto_map": {
9
+ "AutoConfig": "modeling_videochat_flash.VideoChatFlashQwenConfig",
10
+ "AutoModel": "modeling_videochat_flash.VideoChatFlashQwenForCausalLM"
11
+ },
12
+ "bos_token_id": 151643,
13
+ "dual_chunk_attention_config": {
14
+ "chunk_size": 262144,
15
+ "local_size": 8192,
16
+ "original_max_position_embeddings": 262144
17
+ },
18
+ "eos_token_id": 151645,
19
+ "frame_aspect_ratio": "square",
20
+ "frame_grid_pinpoints": null,
21
+ "hidden_act": "silu",
22
+ "hidden_size": 3584,
23
+ "image_aspect_ratio": "anyres_nopad",
24
+ "image_crop_resolution": null,
25
+ "image_grid_pinpoints": [
26
+ [
27
+ 224,
28
+ 224
29
+ ],
30
+ [
31
+ 224,
32
+ 448
33
+ ],
34
+ [
35
+ 224,
36
+ 672
37
+ ],
38
+ [
39
+ 224,
40
+ 896
41
+ ],
42
+ [
43
+ 224,
44
+ 1120
45
+ ],
46
+ [
47
+ 224,
48
+ 1344
49
+ ],
50
+ [
51
+ 448,
52
+ 224
53
+ ],
54
+ [
55
+ 448,
56
+ 448
57
+ ],
58
+ [
59
+ 448,
60
+ 672
61
+ ],
62
+ [
63
+ 448,
64
+ 896
65
+ ],
66
+ [
67
+ 448,
68
+ 1120
69
+ ],
70
+ [
71
+ 448,
72
+ 1344
73
+ ],
74
+ [
75
+ 672,
76
+ 224
77
+ ],
78
+ [
79
+ 672,
80
+ 448
81
+ ],
82
+ [
83
+ 672,
84
+ 672
85
+ ],
86
+ [
87
+ 672,
88
+ 896
89
+ ],
90
+ [
91
+ 672,
92
+ 1120
93
+ ],
94
+ [
95
+ 672,
96
+ 1344
97
+ ],
98
+ [
99
+ 896,
100
+ 224
101
+ ],
102
+ [
103
+ 896,
104
+ 448
105
+ ],
106
+ [
107
+ 896,
108
+ 672
109
+ ],
110
+ [
111
+ 896,
112
+ 896
113
+ ],
114
+ [
115
+ 896,
116
+ 1120
117
+ ],
118
+ [
119
+ 896,
120
+ 1344
121
+ ],
122
+ [
123
+ 1120,
124
+ 224
125
+ ],
126
+ [
127
+ 1120,
128
+ 448
129
+ ],
130
+ [
131
+ 1120,
132
+ 672
133
+ ],
134
+ [
135
+ 1120,
136
+ 896
137
+ ],
138
+ [
139
+ 1120,
140
+ 1120
141
+ ],
142
+ [
143
+ 1120,
144
+ 1344
145
+ ],
146
+ [
147
+ 1344,
148
+ 224
149
+ ],
150
+ [
151
+ 1344,
152
+ 448
153
+ ],
154
+ [
155
+ 1344,
156
+ 672
157
+ ],
158
+ [
159
+ 1344,
160
+ 896
161
+ ],
162
+ [
163
+ 1344,
164
+ 1120
165
+ ],
166
+ [
167
+ 1344,
168
+ 1344
169
+ ]
170
+ ],
171
+ "image_split_resolution": null,
172
+ "initializer_range": 0.02,
173
+ "intermediate_size": 18944,
174
+ "llm_compress_layer_list": [
175
+ 8,
176
+ 16,
177
+ 24
178
+ ],
179
+ "llm_compress_type": "attention",
180
+ "llm_image_token_ratio_list": [
181
+ 1.0,
182
+ 0.5,
183
+ 0.25,
184
+ 0.125
185
+ ],
186
+ "max_num_pixels": 14745600000,
187
+ "max_position_embeddings": 32000,
188
+ "max_window_layers": 28,
189
+ "min_slow_num_frames": 4,
190
+ "mm_close_init": false,
191
+ "mm_hidden_size": 1024,
192
+ "mm_llm_compress": false,
193
+ "mm_local_num_frames": 4,
194
+ "mm_newline_position": "nothing",
195
+ "mm_num_compress_latents": 128,
196
+ "mm_num_compress_query_type": "learnable",
197
+ "mm_patch_merge_type": "spatial_nopad",
198
+ "mm_pos_num_frames": 8,
199
+ "mm_projector_lr": null,
200
+ "mm_projector_type": "tome16_mlp_hd64",
201
+ "mm_resampler_type": null,
202
+ "mm_spatial_pool_mode": "bilinear",
203
+ "mm_tunable_parts": "mm_vision_tower,mm_mlp_adapter,mm_language_model",
204
+ "mm_use_im_patch_token": false,
205
+ "mm_use_im_start_end": false,
206
+ "mm_vision_select_feature": "patch",
207
+ "mm_vision_select_layer": -2,
208
+ "mm_vision_tower": "umt-large",
209
+ "mm_vision_tower_lr": 2e-06,
210
+ "model_type": "videochat_flash_qwen",
211
+ "num_attention_heads": 28,
212
+ "num_hidden_layers": 28,
213
+ "num_key_value_heads": 4,
214
+ "pos_skipping_range": 4096,
215
+ "rms_norm_eps": 1e-05,
216
+ "rope_scaling": null,
217
+ "rope_theta": 10000000.0,
218
+ "sliding_window": 32768,
219
+ "tie_word_embeddings": false,
220
+ "tokenizer_model_max_length": 32768,
221
+ "tokenizer_padding_side": "right",
222
+ "torch_dtype": "bfloat16",
223
+ "transformers_version": "4.39.2",
224
+ "use_cache": true,
225
+ "use_mm_proj": true,
226
+ "use_pos_skipping": false,
227
+ "use_sliding_window": false,
228
+ "vision_encode_type": "video_image",
229
+ "vision_tower_pretrained": null,
230
+ "vocab_size": 152064
231
+ }
constants.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CONTROLLER_HEART_BEAT_EXPIRATION = 30
2
+ WORKER_HEART_BEAT_INTERVAL = 15
3
+
4
+ LOGDIR = "."
5
+
6
+ # Model Constants
7
+ IGNORE_INDEX = -100
8
+ IMAGE_TOKEN_INDEX = -200
9
+ DEFAULT_IMAGE_TOKEN = "<image>"
10
+ DEFAULT_IMAGE_PATCH_TOKEN = "<im_patch>"
11
+ DEFAULT_IM_START_TOKEN = "<im_start>"
12
+ DEFAULT_IM_END_TOKEN = "<im_end>"
conversation.py ADDED
@@ -0,0 +1,592 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dataclasses
2
+ from enum import auto, Enum
3
+ from typing import List, Any, Dict, Union, Tuple
4
+ import re
5
+ import base64
6
+ from io import BytesIO
7
+ from PIL import Image
8
+ from transformers import AutoTokenizer
9
+
10
+
11
+ class SeparatorStyle(Enum):
12
+ """Different separator style."""
13
+
14
+ SINGLE = auto()
15
+ TWO = auto()
16
+ MPT = auto()
17
+ PLAIN = auto()
18
+ CHATML = auto()
19
+ LLAMA_2 = auto()
20
+ LLAMA_3 = auto()
21
+ QWEN = auto()
22
+ GEMMA = auto()
23
+
24
+
25
+ @dataclasses.dataclass
26
+ class Conversation:
27
+ """A class that keeps all conversation history."""
28
+
29
+ system: str
30
+ roles: List[str]
31
+ messages: List[List[str]]
32
+ offset: int
33
+ sep_style: SeparatorStyle = SeparatorStyle.SINGLE
34
+ sep: str = "###"
35
+ sep2: str = None
36
+ version: str = "Unknown"
37
+
38
+ tokenizer_id: str = ""
39
+ tokenizer: Any = None
40
+ # Stop criteria (the default one is EOS token)
41
+ stop_str: Union[str, List[str]] = None
42
+ # Stops generation if meeting any token in this list
43
+ stop_token_ids: List[int] = None
44
+
45
+ skip_next: bool = False
46
+
47
+ def get_prompt(self):
48
+ messages = self.messages
49
+ if len(messages) > 0 and type(messages[0][1]) is tuple:
50
+ messages = self.messages.copy()
51
+ init_role, init_msg = messages[0].copy()
52
+ init_msg = init_msg[0]
53
+ if "mmtag" in self.version:
54
+ init_msg = init_msg.replace("<image>", "").strip()
55
+ messages[0] = (init_role, init_msg)
56
+ messages.insert(0, (self.roles[0], "<Image><image></Image>"))
57
+ messages.insert(1, (self.roles[1], "Received."))
58
+ elif not init_msg.startswith("<image>"):
59
+ init_msg = init_msg.replace("<image>", "").strip()
60
+ messages[0] = (init_role, "<image>\n" + init_msg)
61
+ else:
62
+ messages[0] = (init_role, init_msg)
63
+
64
+ if self.sep_style == SeparatorStyle.SINGLE:
65
+ ret = self.system + self.sep
66
+ for role, message in messages:
67
+ if message:
68
+ if type(message) is tuple:
69
+ message, _, _ = message
70
+ ret += role + ": " + message + self.sep
71
+ else:
72
+ ret += role + ":"
73
+
74
+ elif self.sep_style == SeparatorStyle.TWO:
75
+ seps = [self.sep, self.sep2]
76
+ ret = self.system + seps[0]
77
+ for i, (role, message) in enumerate(messages):
78
+ if message:
79
+ if type(message) is tuple:
80
+ message, _, _ = message
81
+ ret += role + ": " + message + seps[i % 2]
82
+ else:
83
+ ret += role + ":"
84
+
85
+ elif self.sep_style == SeparatorStyle.CHATML:
86
+ ret = "" if self.system == "" else self.system + self.sep + "\n"
87
+ for role, message in messages:
88
+ if message:
89
+ if type(message) is tuple:
90
+ message, images, _ = message
91
+ message = "<image>" * len(images) + message
92
+ ret += role + "\n" + message + self.sep + "\n"
93
+ else:
94
+ ret += role + "\n"
95
+ return ret
96
+
97
+ elif self.sep_style == SeparatorStyle.LLAMA_3:
98
+ chat_template_messages = [{"role": "system", "content": self.system}]
99
+ for role, message in messages:
100
+ if message:
101
+ if type(message) is tuple:
102
+ message, images = message
103
+ message = "<image>" * len(images) + message
104
+ chat_template_messages.append({"role": role, "content": message})
105
+
106
+ # print(chat_template_messages)
107
+ return self.tokenizer.apply_chat_template(chat_template_messages, tokenize=False, add_generation_prompt=True)
108
+ # ret = "" if self.system == "" else self.system + self.sep + "\n"
109
+ # for role, message in messages:
110
+ # if message:
111
+ # if type(message) is tuple:
112
+ # message, images = message
113
+ # message = "<image>" * len(images) + message
114
+ # ret += role + "\n" + message + self.sep + "\n"
115
+ # else:
116
+ # ret += role + "\n"
117
+ # return ret
118
+
119
+ elif self.sep_style == SeparatorStyle.MPT:
120
+ ret = self.system + self.sep
121
+ for role, message in messages:
122
+ if message:
123
+ if type(message) is tuple:
124
+ message, _, _ = message
125
+ ret += role + message + self.sep
126
+ else:
127
+ ret += role
128
+
129
+ elif self.sep_style == SeparatorStyle.GEMMA:
130
+ ret = ""
131
+ for i, (role, message) in enumerate(messages):
132
+ assert role == self.roles[i % 2], "Conversation should alternate user/assistant/user/assistant/..."
133
+ if message:
134
+ if type(message) is tuple:
135
+ message, _, _ = message
136
+ ret += role + message + self.sep
137
+ else:
138
+ ret += role
139
+
140
+ elif self.sep_style == SeparatorStyle.LLAMA_2:
141
+ wrap_sys = lambda msg: f"<<SYS>>\n{msg}\n<</SYS>>\n\n" if len(msg) > 0 else msg
142
+ wrap_inst = lambda msg: f"[INST] {msg} [/INST]"
143
+ ret = ""
144
+
145
+ for i, (role, message) in enumerate(messages):
146
+ if i == 0:
147
+ assert message, "first message should not be none"
148
+ assert role == self.roles[0], "first message should come from user"
149
+ if message:
150
+ if type(message) is tuple:
151
+ message, _, _ = message
152
+ if i == 0:
153
+ message = wrap_sys(self.system) + message
154
+ if i % 2 == 0:
155
+ message = wrap_inst(message)
156
+ ret += self.sep + message
157
+ else:
158
+ ret += " " + message + " " + self.sep2
159
+ else:
160
+ ret += ""
161
+ ret = ret.lstrip(self.sep)
162
+
163
+ elif self.sep_style == SeparatorStyle.PLAIN:
164
+ seps = [self.sep, self.sep2]
165
+ ret = self.system
166
+ for i, (role, message) in enumerate(messages):
167
+ if message:
168
+ if type(message) is tuple:
169
+ message, _, _ = message
170
+ ret += message + seps[i % 2]
171
+ else:
172
+ ret += ""
173
+ else:
174
+ raise ValueError(f"Invalid style: {self.sep_style}")
175
+
176
+ return ret
177
+
178
+ def append_message(self, role, message):
179
+ self.messages.append([role, message])
180
+
181
+ def process_image(self, image, image_process_mode, return_pil=False, image_format="PNG"):
182
+ if image_process_mode == "Pad":
183
+
184
+ def expand2square(pil_img, background_color=(122, 116, 104)):
185
+ width, height = pil_img.size
186
+ if width == height:
187
+ return pil_img
188
+ elif width > height:
189
+ result = Image.new(pil_img.mode, (width, width), background_color)
190
+ result.paste(pil_img, (0, (width - height) // 2))
191
+ return result
192
+ else:
193
+ result = Image.new(pil_img.mode, (height, height), background_color)
194
+ result.paste(pil_img, ((height - width) // 2, 0))
195
+ return result
196
+
197
+ image = expand2square(image)
198
+ elif image_process_mode in ["Default", "Crop"]:
199
+ pass
200
+ elif image_process_mode == "Resize":
201
+ image = image.resize((336, 336))
202
+ else:
203
+ raise ValueError(f"Invalid image_process_mode: {image_process_mode}")
204
+
205
+ if type(image) is not Image.Image:
206
+ image = Image.open(image).convert("RGB")
207
+
208
+ max_hw, min_hw = max(image.size), min(image.size)
209
+ aspect_ratio = max_hw / min_hw
210
+ max_len, min_len = 672, 448
211
+ shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
212
+ longest_edge = int(shortest_edge * aspect_ratio)
213
+ W, H = image.size
214
+ if H > W:
215
+ H, W = longest_edge, shortest_edge
216
+ else:
217
+ H, W = shortest_edge, longest_edge
218
+ image = image.resize((W, H))
219
+ if return_pil:
220
+ return image
221
+ else:
222
+ buffered = BytesIO()
223
+ image.save(buffered, format=image_format)
224
+ img_b64_str = base64.b64encode(buffered.getvalue()).decode()
225
+ return img_b64_str
226
+
227
+ def get_images(self, return_pil=False, return_path=False):
228
+ images = []
229
+ for i, (role, msg) in enumerate(self.messages[self.offset :]):
230
+ if i % 2 == 0:
231
+ if type(msg) is tuple:
232
+ msg, image, image_process_mode = msg
233
+ if type(image) != list:
234
+ image = [image]
235
+ for img in image:
236
+ if not return_path and self.is_image_file(img):
237
+ img = self.process_image(img, image_process_mode, return_pil=return_pil)
238
+ else:
239
+ images.append(img)
240
+ return images
241
+
242
+ def is_image_file(self, filename):
243
+ image_extensions = [".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tiff", ".webp"]
244
+ return any(filename.lower().endswith(ext) for ext in image_extensions)
245
+
246
+ def is_video_file(self, filename):
247
+ video_extensions = [".mp4", ".mov", ".avi", ".mkv", ".wmv", ".flv", ".mpeg", ".mpg"]
248
+ return any(filename.lower().endswith(ext) for ext in video_extensions)
249
+
250
+ def to_gradio_chatbot(self):
251
+ ret = []
252
+ for i, (role, msg) in enumerate(self.messages[self.offset :]):
253
+ if i % 2 == 0:
254
+ if type(msg) is tuple:
255
+ msg, image, image_process_mode = msg
256
+ if type(image) != list:
257
+ image = [image]
258
+ if len(image) == 1:
259
+ msg = "<image>\n" + msg.replace("<image>", "").strip()
260
+ else:
261
+ msg = re.sub(r"(<image>)\n(?=<image>)", r"\1 ", msg)
262
+
263
+ img_str_list = []
264
+ for img in image:
265
+ if self.is_image_file(img):
266
+ img_b64_str = self.process_image(img, "Default", return_pil=False, image_format="JPEG")
267
+ img_str = f'<img src="data:image/jpeg;base64,{img_b64_str}" style="max-width: 256px; max-height: 256px; width: auto; height: auto; object-fit: contain;"/>'
268
+ img_str_list.append(img_str)
269
+ elif self.is_video_file(img):
270
+ ret.append(((img,), None))
271
+
272
+ msg = msg.strip()
273
+ img_place_holder = ""
274
+ for img_str in img_str_list:
275
+ img_place_holder += f"{img_str}\n\n"
276
+
277
+ if len(img_str_list) > 0:
278
+ msg = f"{img_place_holder}\n\n{msg}"
279
+
280
+ if len(msg) > 0:
281
+ ret.append([msg, None])
282
+ else:
283
+ ret.append([msg, None])
284
+ else:
285
+ ret[-1][-1] = msg
286
+ return ret
287
+
288
+ def copy(self):
289
+ return Conversation(system=self.system, roles=self.roles, messages=[[x, y] for x, y in self.messages], offset=self.offset, sep_style=self.sep_style, sep=self.sep, sep2=self.sep2, version=self.version)
290
+
291
+ def dict(self):
292
+ if len(self.get_images()) > 0:
293
+ return {
294
+ "system": self.system,
295
+ "roles": self.roles,
296
+ "messages": [[x, y[0] if type(y) is tuple else y] for x, y in self.messages],
297
+ "offset": self.offset,
298
+ "sep": self.sep,
299
+ "sep2": self.sep2,
300
+ }
301
+ return {
302
+ "system": self.system,
303
+ "roles": self.roles,
304
+ "messages": self.messages,
305
+ "offset": self.offset,
306
+ "sep": self.sep,
307
+ "sep2": self.sep2,
308
+ }
309
+
310
+
311
+ conv_vicuna_v0 = Conversation(
312
+ system="A chat between a curious human and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the human's questions.",
313
+ roles=("Human", "Assistant"),
314
+ messages=[
315
+ ["Human", "What are the key differences between renewable and non-renewable energy sources?"],
316
+ [
317
+ "Assistant",
318
+ "Renewable energy sources are those that can be replenished naturally in a relatively "
319
+ "short amount of time, such as solar, wind, hydro, geothermal, and biomass. "
320
+ "Non-renewable energy sources, on the other hand, are finite and will eventually be "
321
+ "depleted, such as coal, oil, and natural gas. Here are some key differences between "
322
+ "renewable and non-renewable energy sources:\n"
323
+ "1. Availability: Renewable energy sources are virtually inexhaustible, while non-renewable "
324
+ "energy sources are finite and will eventually run out.\n"
325
+ "2. Environmental impact: Renewable energy sources have a much lower environmental impact "
326
+ "than non-renewable sources, which can lead to air and water pollution, greenhouse gas emissions, "
327
+ "and other negative effects.\n"
328
+ "3. Cost: Renewable energy sources can be more expensive to initially set up, but they typically "
329
+ "have lower operational costs than non-renewable sources.\n"
330
+ "4. Reliability: Renewable energy sources are often more reliable and can be used in more remote "
331
+ "locations than non-renewable sources.\n"
332
+ "5. Flexibility: Renewable energy sources are often more flexible and can be adapted to different "
333
+ "situations and needs, while non-renewable sources are more rigid and inflexible.\n"
334
+ "6. Sustainability: Renewable energy sources are more sustainable over the long term, while "
335
+ "non-renewable sources are not, and their depletion can lead to economic and social instability.\n",
336
+ ],
337
+ ],
338
+ offset=2,
339
+ sep_style=SeparatorStyle.SINGLE,
340
+ sep="###",
341
+ )
342
+
343
+ conv_vicuna_v1 = Conversation(
344
+ system="A chat between a curious user and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the user's questions.",
345
+ roles=("USER", "ASSISTANT"),
346
+ version="v1",
347
+ messages=[],
348
+ offset=0,
349
+ sep_style=SeparatorStyle.TWO,
350
+ sep=" ",
351
+ sep2="</s>",
352
+ )
353
+
354
+ conv_llama_2 = Conversation(
355
+ system="""You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.
356
+
357
+ If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.""",
358
+ roles=("USER", "ASSISTANT"),
359
+ version="llama_v2",
360
+ messages=[],
361
+ offset=0,
362
+ sep_style=SeparatorStyle.LLAMA_2,
363
+ sep="<s>",
364
+ sep2="</s>",
365
+ )
366
+
367
+ conv_llava_llama_2 = Conversation(
368
+ system="You are a helpful language and vision assistant. " "You are able to understand the visual content that the user provides, " "and assist the user with a variety of tasks using natural language.",
369
+ roles=("USER", "ASSISTANT"),
370
+ version="llama_v2",
371
+ messages=[],
372
+ offset=0,
373
+ sep_style=SeparatorStyle.LLAMA_2,
374
+ sep="<s>",
375
+ sep2="</s>",
376
+ )
377
+
378
+ # conv_llava_llama_3 = Conversation(
379
+ # system="You are a helpful language and vision assistant. " "You are able to understand the visual content that the user provides, " "and assist the user with a variety of tasks using natural language.",
380
+ # roles=("user", "assistant"),
381
+ # version="llama_v3",
382
+ # messages=[],
383
+ # offset=0,
384
+ # sep="<|eot_id|>",
385
+ # sep_style=SeparatorStyle.LLAMA_3,
386
+ # tokenizer_id="meta-llama/Meta-Llama-3-8B-Instruct",
387
+ # tokenizer=AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct"),
388
+ # stop_token_ids=[128009],
389
+ # )
390
+
391
+ conv_mistral_instruct = Conversation(
392
+ system="",
393
+ roles=("USER", "ASSISTANT"),
394
+ version="llama_v2",
395
+ messages=[],
396
+ offset=0,
397
+ sep_style=SeparatorStyle.LLAMA_2,
398
+ sep="",
399
+ sep2="</s>",
400
+ )
401
+
402
+ conv_llava_llama_2_simple = Conversation(
403
+ system="Answer the questions about the visual content that the user provides.",
404
+ roles=("USER", "ASSISTANT"),
405
+ version="llama_v2",
406
+ messages=[],
407
+ offset=0,
408
+ sep_style=SeparatorStyle.LLAMA_2,
409
+ sep="<s>",
410
+ sep2="</s>",
411
+ )
412
+
413
+ conv_llava_llama_2_mmtag = Conversation(
414
+ system="Answer the questions about the visual content that the user provides." "The visual content will be provided with the following format: <Image>visual content</Image>.",
415
+ roles=("USER", "ASSISTANT"),
416
+ version="llama_v2_mmtag",
417
+ messages=[],
418
+ offset=0,
419
+ sep_style=SeparatorStyle.LLAMA_2,
420
+ sep="<s>",
421
+ sep2="</s>",
422
+ )
423
+
424
+ conv_mpt = Conversation(
425
+ system="""<|im_start|>system
426
+ A conversation between a user and an LLM-based AI assistant. The assistant gives helpful and honest answers.""",
427
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
428
+ version="mpt",
429
+ messages=[],
430
+ offset=0,
431
+ sep_style=SeparatorStyle.MPT,
432
+ sep="<|im_end|>",
433
+ )
434
+
435
+ conv_qwen = Conversation(
436
+ system="""<|im_start|>system
437
+ You are a helpful assistant.""",
438
+ roles=("<|im_start|>user", "<|im_start|>assistant"),
439
+ version="qwen",
440
+ messages=[],
441
+ offset=0,
442
+ sep_style=SeparatorStyle.CHATML,
443
+ sep="<|im_end|>",
444
+ )
445
+
446
+
447
+
448
+ conv_internlm_2 = Conversation(
449
+ system="""<|im_start|>system
450
+ You are a helpful assistant.""",
451
+ roles=("<|im_start|>user", "<|im_start|>assistant"),
452
+ version="internlm_2",
453
+ messages=[],
454
+ offset=0,
455
+ sep_style=SeparatorStyle.CHATML,
456
+ sep="<|im_end|>",
457
+ )
458
+
459
+ conv_gemma_instruct = Conversation(system="", roles=("<start_of_turn>user\n", "<start_of_turn>model\n"), version="gemma", messages=[], offset=0, sep_style=SeparatorStyle.GEMMA, sep="<end_of_turn>\n")
460
+
461
+ conv_llava_plain = Conversation(
462
+ system="",
463
+ roles=("", ""),
464
+ messages=[],
465
+ offset=0,
466
+ sep_style=SeparatorStyle.PLAIN,
467
+ sep="\n",
468
+ )
469
+
470
+ conv_llava_v0 = Conversation(
471
+ system="A chat between a curious human and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the human's questions.",
472
+ roles=("Human", "Assistant"),
473
+ messages=[],
474
+ offset=0,
475
+ sep_style=SeparatorStyle.SINGLE,
476
+ sep="###",
477
+ )
478
+
479
+ conv_llava_v0_mmtag = Conversation(
480
+ system="A chat between a curious user and an artificial intelligence assistant. "
481
+ "The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
482
+ "The visual content will be provided with the following format: <Image>visual content</Image>.",
483
+ roles=("Human", "Assistant"),
484
+ messages=[],
485
+ offset=0,
486
+ sep_style=SeparatorStyle.SINGLE,
487
+ sep="###",
488
+ version="v0_mmtag",
489
+ )
490
+
491
+ conv_llava_v1 = Conversation(
492
+ system="A chat between a curious human and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the human's questions.",
493
+ roles=("USER", "ASSISTANT"),
494
+ version="v1",
495
+ messages=[],
496
+ offset=0,
497
+ sep_style=SeparatorStyle.TWO,
498
+ sep=" ",
499
+ sep2="</s>",
500
+ )
501
+
502
+ conv_llava_v1_mmtag = Conversation(
503
+ system="A chat between a curious user and an artificial intelligence assistant. "
504
+ "The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
505
+ "The visual content will be provided with the following format: <Image>visual content</Image>.",
506
+ roles=("USER", "ASSISTANT"),
507
+ messages=[],
508
+ offset=0,
509
+ sep_style=SeparatorStyle.TWO,
510
+ sep=" ",
511
+ sep2="</s>",
512
+ version="v1_mmtag",
513
+ )
514
+
515
+ conv_mistral_orca = Conversation(
516
+ system="""<|im_start|>system
517
+ You are MistralOrca, a large language model trained by Alignment Lab AI. Write out your reasoning step-by-step to be sure you get the right answers!""",
518
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
519
+ version="mpt",
520
+ messages=[],
521
+ offset=0,
522
+ sep_style=SeparatorStyle.MPT,
523
+ sep="<|im_end|>",
524
+ )
525
+
526
+ conv_mistral_zephyr = Conversation(
527
+ system="""<|system|>
528
+ You are a helpful AI assistant.""",
529
+ roles=("<|user|>\n", "<|assistant|>\n"),
530
+ version="mpt",
531
+ messages=[],
532
+ offset=0,
533
+ sep_style=SeparatorStyle.MPT,
534
+ sep="</s>",
535
+ )
536
+
537
+ conv_mistral_direct = Conversation(
538
+ system="""<|im_start|>system
539
+ Answer the questions.""",
540
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
541
+ version="mpt",
542
+ messages=[],
543
+ offset=0,
544
+ sep_style=SeparatorStyle.MPT,
545
+ sep="<|im_end|>",
546
+ )
547
+
548
+ conv_chatml_direct = Conversation(
549
+ system="""<|im_start|>system
550
+ Answer the questions.""",
551
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
552
+ version="mpt",
553
+ messages=[],
554
+ offset=0,
555
+ sep_style=SeparatorStyle.MPT,
556
+ sep="<|im_end|>",
557
+ )
558
+
559
+ default_conversation = conv_vicuna_v0
560
+ conv_templates = {
561
+ "default": conv_vicuna_v0,
562
+ "v0": conv_vicuna_v0,
563
+ "v1": conv_vicuna_v1,
564
+ "vicuna_v1": conv_vicuna_v1,
565
+ "llama_2": conv_llama_2,
566
+ "mistral_instruct": conv_mistral_instruct,
567
+ "mistral_orca": conv_mistral_orca,
568
+ "mistral_zephyr": conv_mistral_zephyr,
569
+ "mistral_direct": conv_mistral_direct,
570
+ "plain": conv_llava_plain,
571
+ "v0_plain": conv_llava_plain,
572
+ "chatml_direct": conv_chatml_direct,
573
+ "llava_v0": conv_llava_v0,
574
+ "llava_v0_mmtag": conv_llava_v0_mmtag,
575
+ "llava_v1": conv_llava_v1,
576
+ "llava_v1_mmtag": conv_llava_v1_mmtag,
577
+ "llava_llama_2": conv_llava_llama_2,
578
+ # "llava_llama_3": conv_llava_llama_3,
579
+ "llava_llama_2_simple": conv_llava_llama_2_simple,
580
+ "llava_llama_2_mmtag": conv_llava_llama_2_mmtag,
581
+ "llava_mistral_instruct": conv_mistral_instruct,
582
+ "mpt": conv_mpt,
583
+ "qwen_1_5": conv_qwen,
584
+ "qwen_2": conv_qwen,
585
+ "internlm_2": conv_internlm_2,
586
+ "gemma_instruct": conv_gemma_instruct,
587
+ }
588
+
589
+
590
+ if __name__ == "__main__":
591
+ print(default_conversation.get_prompt())
592
+ print(default_conversation)
generation_config.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_attn_implementation": "flash_attention_2",
3
+ "bos_token_id": 151643,
4
+ "do_sample": true,
5
+ "eos_token_id": [
6
+ 151645,
7
+ 151643
8
+ ],
9
+ "pad_token_id": 151643,
10
+ "repetition_penalty": 1.05,
11
+ "temperature": 0.7,
12
+ "top_k": 20,
13
+ "top_p": 0.8,
14
+ "transformers_version": "4.39.2"
15
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
mm_projector_builder.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from typing import Callable, Tuple
4
+
5
+
6
+ def bipartite_soft_matching(
7
+ metric: torch.Tensor,
8
+ r: int,
9
+ ) -> Tuple[Callable, Callable]:
10
+ """
11
+ Applies ToMe with a balanced matching set (50%, 50%).
12
+
13
+ Input size is [batch, tokens, channels].
14
+ r indicates the number of tokens to remove (max 50% of tokens).
15
+ """
16
+ protected = 0
17
+
18
+ t = metric.shape[1]
19
+ r = min(r, (t - protected) // 2)
20
+
21
+ assert r > 0, r
22
+
23
+ with torch.no_grad():
24
+ metric = metric / metric.norm(dim=-1, keepdim=True)
25
+ a, b = metric[..., ::2, :], metric[..., 1::2, :]
26
+ scores = a @ b.transpose(-1, -2)
27
+
28
+ node_max, node_idx = scores.max(dim=-1)
29
+ edge_idx = node_max.argsort(dim=-1, descending=True)[..., None]
30
+
31
+ unm_idx = edge_idx[..., r:, :] # Unmerged Tokens
32
+ src_idx = edge_idx[..., :r, :] # Merged Tokens
33
+ dst_idx = node_idx[..., None].gather(dim=-2, index=src_idx)
34
+
35
+ def merge(x: torch.Tensor, mode="mean") -> torch.Tensor:
36
+ src, dst = x[..., ::2, :], x[..., 1::2, :]
37
+ n, t1, c = src.shape
38
+ unm = src.gather(dim=-2, index=unm_idx.expand(n, t1 - r, c))
39
+ src = src.gather(dim=-2, index=src_idx.expand(n, r, c))
40
+ dst = dst.scatter_add(-2, dst_idx.expand(n, r, c), src) # , reduce=mode)
41
+
42
+ return torch.cat([unm, dst], dim=1)
43
+
44
+ def unmerge(x: torch.Tensor) -> torch.Tensor:
45
+ unm_len = unm_idx.shape[1]
46
+ unm, dst = x[..., :unm_len, :], x[..., unm_len:, :]
47
+ n, _, c = unm.shape
48
+
49
+ src = dst.gather(dim=-2, index=dst_idx.expand(n, r, c))
50
+
51
+ out = torch.zeros(n, metric.shape[1], c, device=x.device, dtype=x.dtype)
52
+
53
+ out[..., 1::2, :] = dst
54
+ out.scatter_(dim=-2, index=(2 * unm_idx).expand(n, unm_len, c), src=unm)
55
+ out.scatter_(dim=-2, index=(2 * src_idx).expand(n, r, c), src=src)
56
+
57
+ return out
58
+
59
+ return merge, unmerge
60
+
61
+
62
+ def merge_wavg(
63
+ merge: Callable, x: torch.Tensor, size: torch.Tensor = None
64
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
65
+ """
66
+ Applies the merge function by taking a weighted average based on token size.
67
+ Returns the merged tensor and the new token sizes.
68
+ """
69
+ if size is None:
70
+ size = torch.ones_like(x[..., 0, None])
71
+
72
+ x = merge(x * size, mode="sum")
73
+ size = merge(size, mode="sum")
74
+
75
+ x = x / size
76
+ return x, size
77
+
78
+
79
+
80
+
81
+ class ToMe16_mlp_hd64(nn.Module):
82
+ def __init__(self, config, vision_cfg):
83
+ super().__init__()
84
+ self._config = config
85
+ self.mm_hidden_size = config.mm_hidden_size
86
+ self.hw = vision_cfg.image_size // vision_cfg.patch_size
87
+ self.num_attention_heads = vision_cfg.num_attention_heads
88
+ self.mlp = nn.Sequential(nn.Linear(config.mm_hidden_size, config.hidden_size),
89
+ nn.GELU(),
90
+ nn.Linear(config.hidden_size, config.hidden_size))
91
+ self.max_pos_hw = self.hw
92
+ self.max_pos_num_frames = config.mm_pos_num_frames
93
+ self.num_image_patches_per_side = 8
94
+ self.num_frame_patches_per_side = 4
95
+
96
+ def merge_tokens(self, x, target_num_token):
97
+ r"""
98
+ x = torch.randn(10, 2560, c)
99
+ x = merge_tokens(x, r_merge_list=[1280])
100
+ """
101
+ size = None
102
+ b, p, c = x.shape
103
+ tmp_p = p
104
+ r_merge_list = []
105
+ assert tmp_p > target_num_token, f"{tmp_p} should greater than {target_num_token}"
106
+ while tmp_p != target_num_token:
107
+ if tmp_p - target_num_token <= (tmp_p // 2):
108
+ r_merge_list.append(tmp_p - target_num_token)
109
+ break
110
+ else:
111
+ r_merge_list.append(tmp_p // 2)
112
+ tmp_p = tmp_p - (tmp_p // 2)
113
+
114
+
115
+ head = self.num_attention_heads
116
+
117
+ dim = c // head
118
+ for r in r_merge_list:
119
+ metric = x.reshape(b, p, head, dim).mean(2) # [b, p, c//head]
120
+ merge, _ = bipartite_soft_matching(
121
+ metric,
122
+ r
123
+ )
124
+ x, size = merge_wavg(merge, x, size)
125
+ _, p, _ = x.shape
126
+
127
+ return x
128
+
129
+
130
+
131
+ def forward(self, x, compress=False, local_num_frames=-1): # 单帧64
132
+ height = width = self.hw
133
+ assert height * width == x.shape[1]
134
+
135
+ if local_num_frames != -1 and local_num_frames != 1:
136
+ assert compress is True
137
+ if compress:
138
+ if local_num_frames != -1:
139
+ num_frames = local_num_frames
140
+ x = x.reshape(x.shape[0] // local_num_frames, -1, x.shape[-1])
141
+ else:
142
+ num_frames = x.shape[0]
143
+ x = x.reshape(1, -1, x.shape[-1])
144
+ num_tome_tokens = 16 * num_frames
145
+ else:
146
+ num_tome_tokens = 64
147
+
148
+ x = self.merge_tokens(x, target_num_token=num_tome_tokens)
149
+ x = self.mlp(x)
150
+ return x
151
+
152
+ @property
153
+ def config(self):
154
+ return {"mm_projector_type": "tome16_mlp_hd64"}
155
+
156
+
157
+
158
+
159
+ def build_vision_projector(config, delay_load=False, **kwargs):
160
+ projector_type = getattr(config, "mm_projector_type", "linear")
161
+
162
+ if projector_type == 'tome16_mlp_hd64':
163
+ return ToMe16_mlp_hd64(config, kwargs["vision_cfg"])
164
+
165
+ raise ValueError(f"Unknown projector type: {projector_type}")
mm_utils.py ADDED
@@ -0,0 +1,855 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image
2
+ from io import BytesIO
3
+ import base64
4
+ import math
5
+ import ast
6
+ import re
7
+ import torch
8
+ from transformers import StoppingCriteria
9
+ from .constants import IMAGE_TOKEN_INDEX
10
+ import random
11
+ import os
12
+ import io
13
+ import av
14
+ import cv2
15
+ import imageio
16
+ from decord import VideoReader
17
+ import numpy as np
18
+ from torchvision.transforms.functional import pil_to_tensor
19
+
20
+
21
+ ######################## load video ########################
22
+
23
+ def get_index(num_frames, num_segments):
24
+ seg_size = float(num_frames - 1) / num_segments
25
+ start = int(seg_size / 2)
26
+ offsets = np.array([
27
+ start + int(np.round(seg_size * idx)) for idx in range(num_segments)
28
+ ])
29
+ return offsets
30
+
31
+
32
+ def pts_to_secs(pts: int, time_base: float, start_pts: int) -> float:
33
+ """
34
+ Converts a present time with the given time base and start_pts offset to seconds.
35
+
36
+ Returns:
37
+ time_in_seconds (float): The corresponding time in seconds.
38
+
39
+ https://github.com/facebookresearch/pytorchvideo/blob/main/pytorchvideo/data/utils.py#L54-L64
40
+ """
41
+ if pts == math.inf:
42
+ return math.inf
43
+
44
+ return int(pts - start_pts) * time_base
45
+
46
+
47
+ def get_pyav_video_duration(video_reader):
48
+ video_stream = video_reader.streams.video[0]
49
+ video_duration = pts_to_secs(
50
+ video_stream.duration,
51
+ video_stream.time_base,
52
+ video_stream.start_time
53
+ )
54
+ return float(video_duration)
55
+
56
+
57
+
58
+ def get_frame_indices(num_frames, vlen, sample='middle', fix_start=None, input_fps=1, min_num_frames=1, max_num_frames=-1, local_num_frames=8):
59
+
60
+ if min_num_frames > vlen:
61
+ if sample == 'dynamic_fps1':
62
+ min_num_frames = (vlen // local_num_frames) * local_num_frames
63
+ else:
64
+ min_num_frames = vlen
65
+
66
+
67
+ if sample == 'dynamic_fps1':
68
+
69
+ duration = float(vlen) / input_fps
70
+ num_segments = int(duration // local_num_frames)
71
+ if num_segments == 0:
72
+ num_frames = local_num_frames
73
+ else:
74
+ num_frames = local_num_frames * num_segments
75
+
76
+ if max_num_frames > 0:
77
+ num_frames = min(num_frames, max_num_frames)
78
+ sample = "middle" # NOTE
79
+
80
+ # logger.info(f"? is OK (img), duation={duration} frames={num_frames}!!!!")
81
+
82
+ num_frames = max(min_num_frames, num_frames)
83
+
84
+ # print(f"\033[0;31m vlen={vlen}, input_fps={input_fps} num_frames={num_frames} \033[0m")
85
+
86
+ if sample in ["rand", "middle"]: # uniform sampling
87
+ acc_samples = min(num_frames, vlen)
88
+ # split the video into `acc_samples` intervals, and sample from each interval.
89
+ intervals = np.linspace(start=0, stop=vlen, num=acc_samples + 1).astype(int)
90
+ ranges = []
91
+ for idx, interv in enumerate(intervals[:-1]):
92
+ ranges.append((interv, intervals[idx + 1] - 1))
93
+ if sample == 'rand':
94
+ try:
95
+ frame_indices = [random.choice(range(x[0], x[1])) for x in ranges]
96
+ except:
97
+ frame_indices = np.random.permutation(vlen)[:acc_samples]
98
+ frame_indices.sort()
99
+ frame_indices = list(frame_indices)
100
+ elif fix_start is not None:
101
+ frame_indices = [x[0] + fix_start for x in ranges]
102
+ elif sample == 'middle':
103
+ frame_indices = [(x[0] + x[1]) // 2 for x in ranges]
104
+ else:
105
+ raise NotImplementedError
106
+
107
+ if len(frame_indices) < num_frames: # padded with last frame
108
+ padded_frame_indices = [frame_indices[-1]] * num_frames
109
+ padded_frame_indices[:len(frame_indices)] = frame_indices
110
+ frame_indices = padded_frame_indices
111
+ elif "fps" in sample: # fps0.5, sequentially sample frames at 0.5 fps
112
+ output_fps = float(sample[3:])
113
+ duration = float(vlen) / input_fps
114
+ delta = 1 / output_fps # gap between frames, this is also the clip length each frame represents
115
+ frame_seconds = np.arange(0 + delta / 2, duration + delta / 2, delta)
116
+ frame_indices = np.around(frame_seconds * input_fps).astype(int)
117
+ frame_indices = [e for e in frame_indices if e < vlen]
118
+ if max_num_frames > 0 and len(frame_indices) > max_num_frames:
119
+ frame_indices = frame_indices[:max_num_frames]
120
+ # frame_indices = np.linspace(0 + delta / 2, duration + delta / 2, endpoint=False, num=max_num_frames)
121
+ else:
122
+ raise ValueError(f"Not support sample type: {sample}")
123
+
124
+
125
+ return frame_indices
126
+
127
+
128
+ def read_frames_av(video_path, num_frames, sample='rand', client=None, fix_start=None, min_num_frames=1, max_num_frames=-1, clip=None, local_num_frames=8):
129
+ if clip is not None:
130
+ raise NotImplementedError("av don't support clip!!!")
131
+ if 's3://' in video_path:
132
+ video_bytes = client.get(video_path)
133
+ byteio = io.BytesIO(video_bytes)
134
+ byteio.seek(0)
135
+ reader = av.open(byteio)
136
+ else:
137
+ byteio = None
138
+ reader = av.open(video_path)
139
+ frames = [f.to_rgb().to_ndarray() for f in reader.decode(video=0)]
140
+ vlen = len(frames)
141
+ duration = get_pyav_video_duration(reader)
142
+ fps = vlen / float(duration)
143
+ frame_indices = get_frame_indices(
144
+ num_frames, vlen, sample=sample, fix_start=fix_start,
145
+ input_fps=fps, min_num_frames=min_num_frames, max_num_frames=max_num_frames, local_num_frames=local_num_frames
146
+ )
147
+ frames = np.stack([frames[idx] for idx in frame_indices]) # (T, H, W, C), torch.uint8
148
+ # frames = frames.permute(0, 3, 1, 2) # (T, C, H, W), torch.uint8
149
+ if byteio != None:
150
+ byteio.close()
151
+
152
+ reader.close()
153
+
154
+ return frames, frame_indices, float(fps), duration
155
+
156
+
157
+ def read_frames_gif(
158
+ video_path, num_frames, sample='rand', fix_start=None,
159
+ min_num_frames=1, max_num_frames=-1, client=None, clip=None, local_num_frames=8
160
+ ):
161
+ if clip is not None:
162
+ raise NotImplementedError("Gif don't support clip!!!")
163
+ if 's3://' in video_path:
164
+ video_bytes = client.get(video_path)
165
+ byteio = io.BytesIO(video_bytes)
166
+ gif = imageio.get_reader(byteio)
167
+ else:
168
+ byteio = None
169
+ gif = imageio.get_reader(video_path)
170
+ vlen = len(gif)
171
+ fps = 1.
172
+ duration = vlen / fps
173
+ frame_indices = get_frame_indices(
174
+ num_frames, vlen, sample=sample, fix_start=fix_start,
175
+ min_num_frames=min_num_frames,
176
+ max_num_frames=max_num_frames, local_num_frames=local_num_frames,
177
+ input_fps=fps
178
+ )
179
+ frames = []
180
+
181
+ min_h = min_w = 100000
182
+ hw_set = set()
183
+ for index, frame in enumerate(gif):
184
+ # for index in frame_idxs:
185
+ if index in frame_indices:
186
+ frame = cv2.cvtColor(frame, cv2.COLOR_RGBA2RGB)
187
+ frame = frame.astype(np.uint8)
188
+ # # (H x W x C) to (C x H x W)
189
+ # frame = frame.permute(2, 0, 1)
190
+ frames.append(frame)
191
+ hw_set.add(frame.shape)
192
+ if frame.shape[0] < min_h:
193
+ min_h = frame.shape[0]
194
+ if frame.shape[1] < min_w:
195
+ min_w = frame.shape[1]
196
+ # print(hw_set, min_h, min_w)
197
+ if len(hw_set) > 1:
198
+ frames = [i[:min_h, :min_w] for i in frames]
199
+
200
+ frames = np.stack(frames) # .float() / 255
201
+
202
+ if byteio != None:
203
+ byteio.close()
204
+
205
+ return frames, frame_indices, float(fps), duration # for tgif
206
+
207
+
208
+
209
+ def read_frames_decord(
210
+ video_path, num_frames, sample='rand', fix_start=None, min_num_frames=1,
211
+ max_num_frames=-1, client=None, clip=None, local_num_frames=8
212
+ ):
213
+
214
+ if video_path.endswith('.avi'):
215
+ return read_frames_av(video_path=video_path, num_frames=num_frames, sample=sample,
216
+ fix_start=fix_start, min_num_frames=min_num_frames, max_num_frames=max_num_frames,
217
+ client=client, clip=clip, local_num_frames=local_num_frames)
218
+ if 's3://' in video_path:
219
+ video_bytes = client.get(video_path)
220
+ if video_bytes is None or len(video_bytes) == 0:
221
+ raise ValueError(f"Can't read byte from {video_path}!")
222
+ byteio = io.BytesIO(video_bytes)
223
+ video_reader = VideoReader(byteio, num_threads=1)
224
+ else:
225
+ byteio = None
226
+ video_reader = VideoReader(video_path, num_threads=1)
227
+ vlen = len(video_reader)
228
+ fps = video_reader.get_avg_fps()
229
+ duration = vlen / float(fps)
230
+
231
+
232
+ if clip:
233
+ start, end = clip
234
+ start = max(0, start)
235
+ end = min(duration - 0.1, end)
236
+ duration = end - start
237
+ vlen = int(duration * fps)
238
+ start_index = int(start * fps)
239
+
240
+ frame_indices = get_frame_indices(
241
+ num_frames, vlen, sample=sample, fix_start=fix_start,
242
+ input_fps=fps, min_num_frames=min_num_frames, max_num_frames=max_num_frames, local_num_frames=local_num_frames
243
+ )
244
+ if clip:
245
+ frame_indices = [f + start_index for f in frame_indices]
246
+
247
+ # print(fps, frame_indices)
248
+ frames = video_reader.get_batch(frame_indices).asnumpy() # (T, H, W, C), torch.uint8
249
+ # https://github.com/dmlc/decord/issues/208
250
+ video_reader.seek(0)
251
+
252
+ if byteio != None:
253
+ byteio.close()
254
+ # frames = frames.permute(0, 3, 1, 2) # (T, C, H, W), torch.uint8
255
+ return frames, frame_indices, float(fps), duration
256
+
257
+
258
+
259
+ def read_frames_img(
260
+ video_path, num_frames, sample='rand', fix_start=None, min_num_frames=1,
261
+ max_num_frames=-1, client=None, clip=None, local_num_frames=8
262
+ ):
263
+ def extract_frame_number(filename):
264
+ # Extract the numeric part from the filename using regular expressions
265
+ if filename.endswith('.jpg'):
266
+ match = re.search(r'_(\d+).jpg$', filename)
267
+ elif filename.endswith('.jpeg'):
268
+ match = re.search(r'_(\d+).jpeg$', filename)
269
+ elif filename.endswith('.png'):
270
+ match = re.search(r'_(\d+).png$', filename)
271
+ else:
272
+ raise NotImplementedError(f"Wrong filename: {filename}")
273
+
274
+ return int(match.group(1)) if match else -1
275
+
276
+
277
+ def sort_frames(frame_paths):
278
+ # Extract filenames from each path and sort by their numeric part
279
+ return sorted(frame_paths, key=lambda x: extract_frame_number(os.path.basename(x)))
280
+
281
+ # img_list=[]
282
+
283
+ if "s3://" in video_path:
284
+ img_list = sort_frames(client.list(video_path))
285
+ else:
286
+ img_list = sort_frames(list(os.listdir(video_path)))
287
+
288
+
289
+ if 'tvqa' in video_path.lower():
290
+ fps = 3.0
291
+ else:
292
+ fps = 1.0
293
+
294
+ if clip is not None:
295
+ start = float(clip[0])
296
+ end = float(clip[1])
297
+ start = max(0, start)
298
+ end = min(len(img_list) / fps, end)
299
+ vlen = (end - start) * fps
300
+ else:
301
+ vlen = len(img_list)
302
+
303
+ duration = vlen / fps
304
+
305
+ if min_num_frames > vlen:
306
+ if sample == 'dynamic_fps1':
307
+ min_num_frames = (vlen // local_num_frames) * local_num_frames
308
+ else:
309
+ min_num_frames = vlen
310
+
311
+ if sample == 'dynamic_fps1':
312
+ num_segments = int(duration // local_num_frames)
313
+ if num_segments == 0:
314
+ num_frames = local_num_frames
315
+ else:
316
+ num_frames = local_num_frames * num_segments
317
+ num_frames = min(num_frames, max_num_frames)
318
+ num_frames = max(min_num_frames, num_frames)
319
+
320
+ num_frames = int(num_frames)
321
+ if clip is not None:
322
+ def _get_index_by_time(start_sec, end_sec, num_segments=8, fps=1., max_frame=9999):
323
+ start_idx = max(1, round(start_sec * fps))
324
+ end_idx = min(round(end_sec * fps), max_frame)
325
+ seg_size = float(end_idx - start_idx) / (num_segments - 1)
326
+ offsets = np.array([start_idx + int(np.round(seg_size * idx)) for idx in range(num_segments)])
327
+ return offsets
328
+
329
+ frame_indices = _get_index_by_time(float(clip[0]), float(clip[1]), num_segments=num_frames, fps=fps, max_frame=len(img_list)-1)
330
+ else:
331
+ frame_indices = get_frame_indices(
332
+ num_frames, vlen, sample=sample, fix_start=fix_start,
333
+ min_num_frames=min_num_frames,
334
+ max_num_frames=max_num_frames, local_num_frames=local_num_frames
335
+ )
336
+
337
+ imgs = []
338
+ for idx in frame_indices:
339
+ frame_fname = os.path.join(video_path, img_list[idx])
340
+ if "s3://" in video_path:
341
+ img_bytes = client.get(frame_fname)
342
+ else:
343
+ with open(frame_fname, 'rb') as f:
344
+ img_bytes = f.read()
345
+ img_np = np.frombuffer(img_bytes, np.uint8)
346
+ img = cv2.imdecode(img_np, cv2.IMREAD_COLOR)
347
+ cv2.cvtColor(img, cv2.COLOR_BGR2RGB, img)
348
+ imgs.append(img)
349
+
350
+ frames = np.array(imgs, dtype=np.uint8)
351
+
352
+
353
+ return frames, frame_indices, fps, duration
354
+
355
+
356
+
357
+ VIDEO_READER_FUNCS = {
358
+ 'av': read_frames_av,
359
+ 'decord': read_frames_decord,
360
+ 'gif': read_frames_gif,
361
+ 'img': read_frames_img,
362
+ 'frame': read_frames_img
363
+ }
364
+
365
+
366
+
367
+ def load_video(video_path, max_num_frames=512, media_dict=None): #, media_dict):
368
+
369
+ if media_dict is None:
370
+ media_dict = {'video_read_type': 'decord'}
371
+
372
+ if type(video_path) != str:
373
+ assert len(video_path) == 1, video_path
374
+ video_path = video_path[0]
375
+
376
+ if 'start' in media_dict:
377
+ clip = [media_dict['start'], media_dict['end']]
378
+ else:
379
+ clip = None
380
+
381
+ if 's3://' in video_path:
382
+ from petrel_client.client import Client
383
+ client = Client(conf_path='~/petreloss.conf')
384
+ else:
385
+ client = None
386
+
387
+ frames, frame_indices, fps, duration = VIDEO_READER_FUNCS[media_dict['video_read_type']](video_path=video_path, num_frames=max_num_frames, sample='dynamic_fps1', fix_start=None, min_num_frames=64, max_num_frames=max_num_frames, client=client, clip=clip, local_num_frames=8)
388
+
389
+ sec = [str(round(f / fps, 1)) for f in frame_indices]
390
+
391
+ msg = f"\nThe video lasts for {duration:.2f} seconds, and {len(sec)} frames are uniformly sampled from it. "
392
+
393
+ return frames, msg
394
+
395
+
396
+ ######################## load video ########################
397
+
398
+
399
+ def resize_and_center_crop(image, shortest_edge_length):
400
+ # Calculate new dimensions and resize
401
+ aspect_ratio = float(image.width) / float(image.height)
402
+ if aspect_ratio > 1:
403
+ new_width = int(shortest_edge_length * aspect_ratio)
404
+ new_height = shortest_edge_length
405
+ else:
406
+ new_width = shortest_edge_length
407
+ new_height = int(shortest_edge_length / aspect_ratio)
408
+ resized_image = image.resize((new_width, new_height), Image.ANTIALIAS)
409
+
410
+ # Calculate the position and perform the center crop
411
+ left = (new_width - shortest_edge_length) / 2
412
+ top = (new_height - shortest_edge_length) / 2
413
+ right = (new_width + shortest_edge_length) / 2
414
+ bottom = (new_height + shortest_edge_length) / 2
415
+ cropped_image = resized_image.crop((left, top, right, bottom))
416
+
417
+ return cropped_image
418
+
419
+
420
+ def auto_pad_images(image, grid_params):
421
+ assert isinstance(image, Image.Image), "Input should be a Pillow Image"
422
+ assert len(grid_params) > 0, "Grid parameters should not be empty"
423
+
424
+ # Step 1: Calculate and find the closest aspect ratio
425
+ input_width, input_height = image.size
426
+ input_aspect_ratio = input_width / input_height
427
+ candidate_resolutions = [(w / h, w, h) for w in grid_params for h in grid_params]
428
+ closest_aspect_ratio = min(candidate_resolutions, key=lambda x: abs(input_aspect_ratio - x[0]))
429
+
430
+ candidate_resolutions = [(x[1], x[2]) for x in candidate_resolutions if abs(x[0] - closest_aspect_ratio[0]) < 1e-3]
431
+
432
+ target_resolution = min(candidate_resolutions, key=lambda res: abs(max(input_width, input_height) / max(res) - 1))
433
+
434
+ resize_width, resize_height = target_resolution
435
+ if input_width > input_height:
436
+ resize_height = int(resize_width / input_aspect_ratio)
437
+ else:
438
+ resize_width = int(resize_height * input_aspect_ratio)
439
+ resized_image = image.resize((resize_width, resize_height), Image.ANTIALIAS)
440
+
441
+ # Step 5: Pad the resized image if necessary to match the target resolution
442
+ pad_width = target_resolution[0] - resize_width
443
+ pad_height = target_resolution[1] - resize_height
444
+ padded_image = Image.new("RGB", target_resolution, color=(0, 0, 0))
445
+ padded_image.paste(resized_image, (pad_width // 2, pad_height // 2))
446
+
447
+ return padded_image
448
+
449
+
450
+ def extract_patches(image, patch_size, overlap_ratio):
451
+ assert isinstance(image, Image.Image), "Input should be a Pillow Image"
452
+ assert patch_size > 0, "Patch size should be greater than 0"
453
+ assert 0 <= overlap_ratio < 1, "Overlap ratio should be between 0 and 1"
454
+
455
+ W, H = image.size
456
+ patches = []
457
+
458
+ stride = int(patch_size * (1 - overlap_ratio))
459
+
460
+ num_patches_y = (H - patch_size) // stride + 1
461
+ num_patches_x = (W - patch_size) // stride + 1
462
+
463
+ y_start = (H - (num_patches_y - 1) * stride - patch_size) // 2
464
+ x_start = (W - (num_patches_x - 1) * stride - patch_size) // 2
465
+
466
+ for y in range(y_start, y_start + num_patches_y * stride, stride):
467
+ for x in range(x_start, x_start + num_patches_x * stride, stride):
468
+ patch = image.crop((x, y, x + patch_size, y + patch_size))
469
+ patches.append(patch)
470
+
471
+ return patches
472
+
473
+
474
+ def process_highres_image_crop_split(image, data_args, processor=None):
475
+ crop_resolution = data_args.image_crop_resolution
476
+ split_resolution = data_args.image_split_resolution
477
+ if processor is None:
478
+ processor = data_args.image_processor
479
+ image_crop = resize_and_center_crop(image, crop_resolution)
480
+ image_patches = extract_patches(image_crop, patch_size=split_resolution, overlap_ratio=0)
481
+ image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches]
482
+ return torch.stack(image_patches, dim=0)
483
+
484
+
485
+ def process_highres_image(image, processor, grid_pinpoints):
486
+ grid_params = [int(x) for x in grid_pinpoints.split(",")]
487
+ width_height = max(image.size)
488
+ fit_grid_params = [x for x in grid_params if x >= width_height]
489
+ if len(fit_grid_params) == 0:
490
+ select_size = max(grid_params)
491
+ else:
492
+ select_size = min(fit_grid_params)
493
+ # FIXME: always select the 448
494
+ select_size = max(grid_params)
495
+ image_padded = expand2square(image, tuple(int(x * 255) for x in processor.image_mean))
496
+
497
+ # FIXME: this seems to be a bug that it always resizes instead of padding
498
+ image_original_resize = image.resize((processor.size["shortest_edge"], processor.size["shortest_edge"]))
499
+ image_padded = image_padded.resize((select_size, select_size))
500
+ image_patches = extract_patches(image_padded, patch_size=processor.size["shortest_edge"], overlap_ratio=0)
501
+ image_patches = [image_original_resize] + image_patches
502
+ image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches]
503
+ return torch.stack(image_patches, dim=0)
504
+
505
+
506
+ def select_best_resolution(original_size, possible_resolutions, max_resolutions, patch_size):
507
+ """
508
+ Selects the best resolution from a list of possible resolutions based on the original size.
509
+
510
+ Args:
511
+ original_size (tuple): The original size of the image in the format (width, height).
512
+ possible_resolutions (list): A list of possible resolutions in the format [(width1, height1), (width2, height2), ...].
513
+
514
+ Returns:
515
+ tuple: The best fit resolution in the format (width, height).
516
+ """
517
+ original_width, original_height = original_size
518
+ best_fit = None
519
+ max_effective_resolution = 0
520
+ min_wasted_resolution = float("inf")
521
+
522
+ for width, height in possible_resolutions:
523
+ if max_resolutions != None and (width * height != patch_size * patch_size):
524
+ if (width * height+patch_size*patch_size) > max_resolutions: # NOTE 要算一个global
525
+ continue
526
+ # Calculate the downscaled size to keep the aspect ratio
527
+ scale = min(width / original_width, height / original_height)
528
+ downscaled_width, downscaled_height = int(original_width * scale), int(original_height * scale)
529
+
530
+ # Calculate effective and wasted resolutions
531
+ effective_resolution = min(downscaled_width * downscaled_height, original_width * original_height)
532
+ wasted_resolution = (width * height) - effective_resolution
533
+
534
+ if effective_resolution > max_effective_resolution or (effective_resolution == max_effective_resolution and wasted_resolution < min_wasted_resolution):
535
+ max_effective_resolution = effective_resolution
536
+ min_wasted_resolution = wasted_resolution
537
+ best_fit = (width, height)
538
+
539
+ # print(f"original_size={original_size}, possible_resolutions={possible_resolutions}, max_resolutions={max_resolutions}, best_fit={best_fit}")
540
+ assert best_fit is not None, f"Can't find suitable fit in {possible_resolutions} at max:{max_resolutions}"
541
+ return best_fit
542
+
543
+
544
+ def resize_and_pad_image(image, target_resolution):
545
+ """
546
+ Resize and pad an image to a target resolution while maintaining aspect ratio.
547
+
548
+ Args:
549
+ image (PIL.Image.Image): The input image.
550
+ target_resolution (tuple): The target resolution (width, height) of the image.
551
+
552
+ Returns:
553
+ PIL.Image.Image: The resized and padded image.
554
+ """
555
+ original_width, original_height = image.size
556
+ target_width, target_height = target_resolution
557
+
558
+ # Determine which dimension (width or height) to fill
559
+ scale_w = target_width / original_width
560
+ scale_h = target_height / original_height
561
+
562
+ if scale_w < scale_h:
563
+ # Width will be filled completely
564
+ new_width = target_width
565
+ new_height = min(math.ceil(original_height * scale_w), target_height)
566
+ else:
567
+ # Height will be filled completely
568
+ new_height = target_height
569
+ new_width = min(math.ceil(original_width * scale_h), target_width)
570
+
571
+ # Resize the image
572
+ resized_image = image.resize((new_width, new_height))
573
+
574
+ # Create a new image with the target size and paste the resized image onto it
575
+ new_image = Image.new("RGB", (target_width, target_height), (0, 0, 0))
576
+ paste_x = (target_width - new_width) // 2
577
+ paste_y = (target_height - new_height) // 2
578
+ new_image.paste(resized_image, (paste_x, paste_y))
579
+
580
+ return new_image
581
+
582
+
583
+ def divide_to_patches(image, patch_size):
584
+ """
585
+ Divides an image into patches of a specified size.
586
+
587
+ Args:
588
+ image (PIL.Image.Image): The input image.
589
+ patch_size (int): The size of each patch.
590
+
591
+ Returns:
592
+ list: A list of PIL.Image.Image objects representing the patches.
593
+ """
594
+ patches = []
595
+ width, height = image.size
596
+ for i in range(0, height, patch_size):
597
+ for j in range(0, width, patch_size):
598
+ box = (j, i, j + patch_size, i + patch_size)
599
+ patch = image.crop(box)
600
+ patches.append(patch)
601
+
602
+ return patches
603
+
604
+
605
+ def get_anyres_image_grid_shape(image_size, grid_pinpoints, patch_size, max_resolutions=None):
606
+ """
607
+ Calculate the shape of the image patch grid after the preprocessing for images of any resolution.
608
+
609
+ Args:
610
+ image_size (tuple): The size of the input image in the format (width, height).
611
+ grid_pinpoints (str): A string representation of a list of possible resolutions.
612
+ patch_size (int): The size of each image patch.
613
+
614
+ Returns:
615
+ tuple: The shape of the image patch grid in the format (width, height).
616
+ """
617
+ if isinstance(grid_pinpoints, str) and "x" in grid_pinpoints:
618
+ assert patch_size in [224, 336, 384, 448, 512], "patch_size should be in [224, 336, 384, 448, 512]"
619
+ # Use regex to extract the range from the input string
620
+ matches = re.findall(r"\((\d+)x(\d+)\)", grid_pinpoints)
621
+ range_start = tuple(map(int, matches[0]))
622
+ range_end = tuple(map(int, matches[-1]))
623
+ # Generate a matrix of tuples from (range_start[0], range_start[1]) to (range_end[0], range_end[1])
624
+ grid_pinpoints = [(i, j) for i in range(range_start[0], range_end[0] + 1) for j in range(range_start[1], range_end[1] + 1)]
625
+ # Multiply all elements by patch_size
626
+ grid_pinpoints = [[dim * patch_size for dim in pair] for pair in grid_pinpoints]
627
+ if type(grid_pinpoints) is list:
628
+ possible_resolutions = grid_pinpoints
629
+ else:
630
+ possible_resolutions = ast.literal_eval(grid_pinpoints)
631
+ width, height = select_best_resolution(image_size, possible_resolutions, max_resolutions=max_resolutions, patch_size=patch_size)
632
+
633
+ # print("get width/patch size", width, patch_size, flush=True)
634
+
635
+ return width // patch_size, height // patch_size
636
+
637
+
638
+ def process_anyres_image(image, processor, grid_pinpoints):
639
+ """
640
+ Process an image with variable resolutions.
641
+
642
+ Args:
643
+ image (PIL.Image.Image): The input image to be processed.
644
+ processor: The image processor object.
645
+ grid_pinpoints (str): A string representation of a list of possible resolutions.
646
+
647
+ Returns:
648
+ torch.Tensor: A tensor containing the processed image patches.
649
+ """
650
+ raise NotImplementedError
651
+ # Convert grid_pinpoints from string to list
652
+ if isinstance(grid_pinpoints, str) and "x" in grid_pinpoints:
653
+ try:
654
+ patch_size = processor.size[0]
655
+ except Exception as e:
656
+ patch_size = processor.size["shortest_edge"]
657
+ assert patch_size in [224, 336, 384, 448, 512], "patch_size should be in [224, 336, 384, 448, 512]"
658
+ # Use regex to extract the range from the input string
659
+ matches = re.findall(r"\((\d+)x(\d+)\)", grid_pinpoints)
660
+ range_start = tuple(map(int, matches[0]))
661
+ range_end = tuple(map(int, matches[-1]))
662
+ # Generate a matrix of tuples from (range_start[0], range_start[1]) to (range_end[0], range_end[1])
663
+ grid_pinpoints = [(i, j) for i in range(range_start[0], range_end[0] + 1) for j in range(range_start[1], range_end[1] + 1)]
664
+ # Multiply all elements by patch_size
665
+ grid_pinpoints = [[dim * patch_size for dim in pair] for pair in grid_pinpoints]
666
+
667
+ if type(grid_pinpoints) is list:
668
+ possible_resolutions = grid_pinpoints
669
+ else:
670
+ possible_resolutions = ast.literal_eval(grid_pinpoints)
671
+ best_resolution = select_best_resolution(image.size, possible_resolutions)
672
+ image_padded = resize_and_pad_image(image, best_resolution)
673
+
674
+ patches = divide_to_patches(image_padded, processor.crop_size["height"])
675
+
676
+ # FIXME: this seems to be a bug that it resizes instead of pad.
677
+ # but to keep it consistent with previous, i will keep it as it is
678
+ # TODO: uncomment below to ablate with the padding
679
+ if isinstance(processor.size, dict):
680
+ shortest_edge = processor.size["shortest_edge"]
681
+ else:
682
+ shortest_edge = min(processor.size)
683
+ image_original_resize = image.resize((shortest_edge, shortest_edge))
684
+ # image_padded_square = expand2square(image, tuple(int(x*255) for x in processor.image_mean))
685
+ # image_original_resize = image_padded_square.resize((processor.size['shortest_edge'], processor.size['shortest_edge']))
686
+
687
+ image_patches = [image_original_resize] + patches
688
+ image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches]
689
+
690
+ # print("image.size", image.size, "len(image_patches):", len(image_patches), "patch_size:", image_patches[0].shape)
691
+ return torch.stack(image_patches, dim=0)
692
+
693
+ def process_anyres_image_nopad(image, processor, grid_pinpoints):
694
+ """
695
+ Process an image with variable resolutions.
696
+
697
+ Args:
698
+ image (PIL.Image.Image): The input image to be processed.
699
+ processor: The image processor object.
700
+ grid_pinpoints (str): A string representation of a list of possible resolutions.
701
+
702
+ Returns:
703
+ torch.Tensor: A tensor containing the processed image patches.
704
+ """
705
+ # Convert grid_pinpoints from string to list
706
+ try:
707
+ patch_size = processor.size[0]
708
+ except Exception as e:
709
+ patch_size = processor.size["shortest_edge"]
710
+
711
+ assert patch_size in [224, 336, 384, 448, 512], "patch_size should be in [224, 336, 384, 448, 512]"
712
+
713
+ if isinstance(grid_pinpoints, str) and "x" in grid_pinpoints:
714
+
715
+ # Use regex to extract the range from the input string
716
+ matches = re.findall(r"\((\d+)x(\d+)\)", grid_pinpoints)
717
+ range_start = tuple(map(int, matches[0]))
718
+ range_end = tuple(map(int, matches[-1]))
719
+ # Generate a matrix of tuples from (range_start[0], range_start[1]) to (range_end[0], range_end[1])
720
+ grid_pinpoints = [(i, j) for i in range(range_start[0], range_end[0] + 1) for j in range(range_start[1], range_end[1] + 1)]
721
+ # Multiply all elements by patch_size
722
+ grid_pinpoints = [[dim * patch_size for dim in pair] for pair in grid_pinpoints]
723
+
724
+ if type(grid_pinpoints) is list:
725
+ possible_resolutions = grid_pinpoints
726
+ else:
727
+ possible_resolutions = ast.literal_eval(grid_pinpoints)
728
+ best_resolution = select_best_resolution(image.size, possible_resolutions, max_resolutions=None, patch_size=patch_size) # 目前图像无限制
729
+ # image_padded = resize_and_pad_image(image, best_resolution)
730
+
731
+ patches = divide_to_patches(image.resize(best_resolution), patch_size)
732
+
733
+ # FIXME: this seems to be a bug that it resizes instead of pad.
734
+ # but to keep it consistent with previous, i will keep it as it is
735
+ # TODO: uncomment below to ablate with the padding
736
+ if isinstance(processor.size, dict):
737
+ shortest_edge = processor.size["shortest_edge"]
738
+ else:
739
+ shortest_edge = min(processor.size)
740
+ image_original_resize = image.resize((shortest_edge, shortest_edge))
741
+ # image_padded_square = expand2square(image, tuple(int(x*255) for x in processor.image_mean))
742
+ # image_original_resize = image_padded_square.resize((processor.size['shortest_edge'], processor.size['shortest_edge']))
743
+
744
+ image_patches = [image_original_resize] + patches
745
+ image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches]
746
+
747
+ # raise ValueError(f"image.size: {image.size} len(image_patches): {len(image_patches)}, patch_size:, {image_patches[0].shape}, possible_resolutions:, {possible_resolutions}, best: {best_resolution}")
748
+ return torch.stack(image_patches, dim=0)
749
+
750
+
751
+ def load_image_from_base64(image):
752
+ return Image.open(BytesIO(base64.b64decode(image)))
753
+
754
+
755
+ def expand2square(pil_img, background_color):
756
+ width, height = pil_img.size
757
+ if width == height:
758
+ return pil_img
759
+ elif width > height:
760
+ result = Image.new(pil_img.mode, (width, width), background_color)
761
+ result.paste(pil_img, (0, (width - height) // 2))
762
+ return result
763
+ else:
764
+ result = Image.new(pil_img.mode, (height, height), background_color)
765
+ result.paste(pil_img, ((height - width) // 2, 0))
766
+ return result
767
+
768
+
769
+ def process_images(images, image_processor, model_cfg):
770
+ image_aspect_ratio = getattr(model_cfg, "image_aspect_ratio", None)
771
+ new_images = []
772
+ if image_aspect_ratio == "highres":
773
+ raise NotImplementedError
774
+ for image in images:
775
+ image = process_highres_image(image, image_processor, model_cfg.image_grid_pinpoints)
776
+ new_images.append(image)
777
+ elif "anyres" in image_aspect_ratio:
778
+ for image in images:
779
+ if "nopad" in image_aspect_ratio:
780
+ image = process_anyres_image_nopad(image, image_processor, model_cfg.image_grid_pinpoints)
781
+ else:
782
+ image = process_anyres_image(image, image_processor, model_cfg.image_grid_pinpoints)
783
+ new_images.append(image)
784
+ elif image_aspect_ratio == "crop_split":
785
+ raise NotImplementedError
786
+ for image in images:
787
+ image = process_highres_image_crop_split(image, model_cfg, image_processor)
788
+ new_images.append(image)
789
+ elif image_aspect_ratio == "pad":
790
+ for image in images:
791
+ image = expand2square(image, tuple(int(x * 255) for x in image_processor.image_mean))
792
+ image = image_processor.preprocess(image, return_tensors="pt")["pixel_values"][0]
793
+ new_images.append(image)
794
+ else:
795
+ return image_processor.preprocess(images, return_tensors="pt")["pixel_values"]
796
+ if all(x.shape == new_images[0].shape for x in new_images):
797
+ new_images = torch.stack(new_images, dim=0)
798
+ return new_images
799
+
800
+
801
+ def tokenizer_image_token(prompt, tokenizer, image_token_index=IMAGE_TOKEN_INDEX, return_tensors=None):
802
+ prompt_chunks = [tokenizer(chunk).input_ids for chunk in prompt.split("<image>")]
803
+
804
+ def insert_separator(X, sep):
805
+ return [ele for sublist in zip(X, [sep] * len(X)) for ele in sublist][:-1]
806
+
807
+ input_ids = []
808
+ offset = 0
809
+ if len(prompt_chunks) > 0 and len(prompt_chunks[0]) > 0 and prompt_chunks[0][0] == tokenizer.bos_token_id:
810
+ offset = 1
811
+ input_ids.append(prompt_chunks[0][0])
812
+
813
+ for x in insert_separator(prompt_chunks, [image_token_index] * (offset + 1)):
814
+ input_ids.extend(x[offset:])
815
+
816
+ if return_tensors is not None:
817
+ if return_tensors == "pt":
818
+ return torch.tensor(input_ids, dtype=torch.long)
819
+ raise ValueError(f"Unsupported tensor type: {return_tensors}")
820
+ return input_ids
821
+
822
+
823
+ def get_model_name_from_path(model_path):
824
+ model_path = model_path.strip("/")
825
+ model_paths = model_path.split("/")
826
+ if model_paths[-1].startswith("checkpoint-"):
827
+ return model_paths[-2] + "_" + model_paths[-1]
828
+ else:
829
+ return model_paths[-1]
830
+
831
+
832
+ class KeywordsStoppingCriteria(StoppingCriteria):
833
+ def __init__(self, keywords, tokenizer, input_ids):
834
+ self.keywords = keywords
835
+ self.keyword_ids = []
836
+ for keyword in keywords:
837
+ cur_keyword_ids = tokenizer(keyword).input_ids
838
+ if len(cur_keyword_ids) > 1 and cur_keyword_ids[0] == tokenizer.bos_token_id:
839
+ cur_keyword_ids = cur_keyword_ids[1:]
840
+ self.keyword_ids.append(torch.tensor(cur_keyword_ids))
841
+ self.tokenizer = tokenizer
842
+ self.start_len = input_ids.shape[1]
843
+
844
+ def __call__(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
845
+ assert output_ids.shape[0] == 1, "Only support batch size 1 (yet)" # TODO
846
+ offset = min(output_ids.shape[1] - self.start_len, 3)
847
+ self.keyword_ids = [keyword_id.to(output_ids.device) for keyword_id in self.keyword_ids]
848
+ for keyword_id in self.keyword_ids:
849
+ if output_ids[0, -keyword_id.shape[0] :] == keyword_id:
850
+ return True
851
+ outputs = self.tokenizer.batch_decode(output_ids[:, -offset:], skip_special_tokens=True)[0]
852
+ for keyword in self.keywords:
853
+ if keyword in outputs:
854
+ return True
855
+ return False
model-00001-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:938fc7aad881ffea9cc8f9a5d57b24ebbe3cbaafeb0ef1b4f6649be71a6b8057
3
+ size 4976862020
model-00002-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bc343fc770d15834c87e32e1266a638ce99378768f97a9a2f167489911e52bd2
3
+ size 4907183960
model-00003-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b3db36826d2f7a41babcdb3a982c9ffbe104e5f87229f1e3bc71692ce866d4f5
3
+ size 4995708332
model-00004-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6c8e978c21fa37f46e61ce180028db5b3ad3cb7baba61a24d18cc4a7a54bb330
3
+ size 1274188592
model.safetensors.index.json ADDED
@@ -0,0 +1,905 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 16153832560
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "model-00004-of-00004.safetensors",
7
+ "model.embed_tokens.weight": "model-00001-of-00004.safetensors",
8
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00004.safetensors",
9
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
10
+ "model.layers.0.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
11
+ "model.layers.0.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
12
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
13
+ "model.layers.0.self_attn.k_b_proj_nope.bias": "model-00001-of-00004.safetensors",
14
+ "model.layers.0.self_attn.k_b_proj_nope.weight": "model-00001-of-00004.safetensors",
15
+ "model.layers.0.self_attn.k_nope_scale_factor": "model-00001-of-00004.safetensors",
16
+ "model.layers.0.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
17
+ "model.layers.0.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
18
+ "model.layers.0.self_attn.k_proj_pe.bias": "model-00001-of-00004.safetensors",
19
+ "model.layers.0.self_attn.k_proj_pe.weight": "model-00001-of-00004.safetensors",
20
+ "model.layers.0.self_attn.kv_a_proj_nope.weight": "model-00001-of-00004.safetensors",
21
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
22
+ "model.layers.0.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
23
+ "model.layers.0.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
24
+ "model.layers.0.self_attn.temperature": "model-00001-of-00004.safetensors",
25
+ "model.layers.0.self_attn.v_b_proj.bias": "model-00001-of-00004.safetensors",
26
+ "model.layers.0.self_attn.v_b_proj.weight": "model-00001-of-00004.safetensors",
27
+ "model.layers.0.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
28
+ "model.layers.0.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
29
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00004.safetensors",
30
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
31
+ "model.layers.1.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
32
+ "model.layers.1.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
33
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
34
+ "model.layers.1.self_attn.k_b_proj_nope.bias": "model-00001-of-00004.safetensors",
35
+ "model.layers.1.self_attn.k_b_proj_nope.weight": "model-00001-of-00004.safetensors",
36
+ "model.layers.1.self_attn.k_nope_scale_factor": "model-00001-of-00004.safetensors",
37
+ "model.layers.1.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
38
+ "model.layers.1.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
39
+ "model.layers.1.self_attn.k_proj_pe.bias": "model-00001-of-00004.safetensors",
40
+ "model.layers.1.self_attn.k_proj_pe.weight": "model-00001-of-00004.safetensors",
41
+ "model.layers.1.self_attn.kv_a_proj_nope.weight": "model-00001-of-00004.safetensors",
42
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
43
+ "model.layers.1.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
44
+ "model.layers.1.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
45
+ "model.layers.1.self_attn.temperature": "model-00001-of-00004.safetensors",
46
+ "model.layers.1.self_attn.v_b_proj.bias": "model-00001-of-00004.safetensors",
47
+ "model.layers.1.self_attn.v_b_proj.weight": "model-00001-of-00004.safetensors",
48
+ "model.layers.1.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
49
+ "model.layers.1.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
50
+ "model.layers.10.input_layernorm.weight": "model-00002-of-00004.safetensors",
51
+ "model.layers.10.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
52
+ "model.layers.10.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
53
+ "model.layers.10.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
54
+ "model.layers.10.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
55
+ "model.layers.10.self_attn.k_b_proj_nope.bias": "model-00002-of-00004.safetensors",
56
+ "model.layers.10.self_attn.k_b_proj_nope.weight": "model-00002-of-00004.safetensors",
57
+ "model.layers.10.self_attn.k_nope_scale_factor": "model-00002-of-00004.safetensors",
58
+ "model.layers.10.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
59
+ "model.layers.10.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
60
+ "model.layers.10.self_attn.k_proj_pe.bias": "model-00002-of-00004.safetensors",
61
+ "model.layers.10.self_attn.k_proj_pe.weight": "model-00002-of-00004.safetensors",
62
+ "model.layers.10.self_attn.kv_a_proj_nope.weight": "model-00002-of-00004.safetensors",
63
+ "model.layers.10.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
64
+ "model.layers.10.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
65
+ "model.layers.10.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
66
+ "model.layers.10.self_attn.temperature": "model-00002-of-00004.safetensors",
67
+ "model.layers.10.self_attn.v_b_proj.bias": "model-00002-of-00004.safetensors",
68
+ "model.layers.10.self_attn.v_b_proj.weight": "model-00002-of-00004.safetensors",
69
+ "model.layers.10.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
70
+ "model.layers.10.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
71
+ "model.layers.11.input_layernorm.weight": "model-00002-of-00004.safetensors",
72
+ "model.layers.11.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
73
+ "model.layers.11.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
74
+ "model.layers.11.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
75
+ "model.layers.11.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
76
+ "model.layers.11.self_attn.k_b_proj_nope.bias": "model-00002-of-00004.safetensors",
77
+ "model.layers.11.self_attn.k_b_proj_nope.weight": "model-00002-of-00004.safetensors",
78
+ "model.layers.11.self_attn.k_nope_scale_factor": "model-00002-of-00004.safetensors",
79
+ "model.layers.11.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
80
+ "model.layers.11.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
81
+ "model.layers.11.self_attn.k_proj_pe.bias": "model-00002-of-00004.safetensors",
82
+ "model.layers.11.self_attn.k_proj_pe.weight": "model-00002-of-00004.safetensors",
83
+ "model.layers.11.self_attn.kv_a_proj_nope.weight": "model-00002-of-00004.safetensors",
84
+ "model.layers.11.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
85
+ "model.layers.11.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
86
+ "model.layers.11.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
87
+ "model.layers.11.self_attn.temperature": "model-00002-of-00004.safetensors",
88
+ "model.layers.11.self_attn.v_b_proj.bias": "model-00002-of-00004.safetensors",
89
+ "model.layers.11.self_attn.v_b_proj.weight": "model-00002-of-00004.safetensors",
90
+ "model.layers.11.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
91
+ "model.layers.11.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
92
+ "model.layers.12.input_layernorm.weight": "model-00002-of-00004.safetensors",
93
+ "model.layers.12.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
94
+ "model.layers.12.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
95
+ "model.layers.12.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
96
+ "model.layers.12.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
97
+ "model.layers.12.self_attn.k_b_proj_nope.bias": "model-00002-of-00004.safetensors",
98
+ "model.layers.12.self_attn.k_b_proj_nope.weight": "model-00002-of-00004.safetensors",
99
+ "model.layers.12.self_attn.k_nope_scale_factor": "model-00002-of-00004.safetensors",
100
+ "model.layers.12.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
101
+ "model.layers.12.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
102
+ "model.layers.12.self_attn.k_proj_pe.bias": "model-00002-of-00004.safetensors",
103
+ "model.layers.12.self_attn.k_proj_pe.weight": "model-00002-of-00004.safetensors",
104
+ "model.layers.12.self_attn.kv_a_proj_nope.weight": "model-00002-of-00004.safetensors",
105
+ "model.layers.12.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
106
+ "model.layers.12.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
107
+ "model.layers.12.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
108
+ "model.layers.12.self_attn.temperature": "model-00002-of-00004.safetensors",
109
+ "model.layers.12.self_attn.v_b_proj.bias": "model-00002-of-00004.safetensors",
110
+ "model.layers.12.self_attn.v_b_proj.weight": "model-00002-of-00004.safetensors",
111
+ "model.layers.12.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
112
+ "model.layers.12.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
113
+ "model.layers.13.input_layernorm.weight": "model-00002-of-00004.safetensors",
114
+ "model.layers.13.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
115
+ "model.layers.13.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
116
+ "model.layers.13.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
117
+ "model.layers.13.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
118
+ "model.layers.13.self_attn.k_b_proj_nope.bias": "model-00002-of-00004.safetensors",
119
+ "model.layers.13.self_attn.k_b_proj_nope.weight": "model-00002-of-00004.safetensors",
120
+ "model.layers.13.self_attn.k_nope_scale_factor": "model-00002-of-00004.safetensors",
121
+ "model.layers.13.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
122
+ "model.layers.13.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
123
+ "model.layers.13.self_attn.k_proj_pe.bias": "model-00002-of-00004.safetensors",
124
+ "model.layers.13.self_attn.k_proj_pe.weight": "model-00002-of-00004.safetensors",
125
+ "model.layers.13.self_attn.kv_a_proj_nope.weight": "model-00002-of-00004.safetensors",
126
+ "model.layers.13.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
127
+ "model.layers.13.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
128
+ "model.layers.13.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
129
+ "model.layers.13.self_attn.temperature": "model-00002-of-00004.safetensors",
130
+ "model.layers.13.self_attn.v_b_proj.bias": "model-00002-of-00004.safetensors",
131
+ "model.layers.13.self_attn.v_b_proj.weight": "model-00002-of-00004.safetensors",
132
+ "model.layers.13.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
133
+ "model.layers.13.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
134
+ "model.layers.14.input_layernorm.weight": "model-00002-of-00004.safetensors",
135
+ "model.layers.14.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
136
+ "model.layers.14.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
137
+ "model.layers.14.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
138
+ "model.layers.14.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
139
+ "model.layers.14.self_attn.k_b_proj_nope.bias": "model-00002-of-00004.safetensors",
140
+ "model.layers.14.self_attn.k_b_proj_nope.weight": "model-00002-of-00004.safetensors",
141
+ "model.layers.14.self_attn.k_nope_scale_factor": "model-00002-of-00004.safetensors",
142
+ "model.layers.14.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
143
+ "model.layers.14.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
144
+ "model.layers.14.self_attn.k_proj_pe.bias": "model-00002-of-00004.safetensors",
145
+ "model.layers.14.self_attn.k_proj_pe.weight": "model-00002-of-00004.safetensors",
146
+ "model.layers.14.self_attn.kv_a_proj_nope.weight": "model-00002-of-00004.safetensors",
147
+ "model.layers.14.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
148
+ "model.layers.14.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
149
+ "model.layers.14.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
150
+ "model.layers.14.self_attn.temperature": "model-00002-of-00004.safetensors",
151
+ "model.layers.14.self_attn.v_b_proj.bias": "model-00002-of-00004.safetensors",
152
+ "model.layers.14.self_attn.v_b_proj.weight": "model-00002-of-00004.safetensors",
153
+ "model.layers.14.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
154
+ "model.layers.14.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
155
+ "model.layers.15.input_layernorm.weight": "model-00002-of-00004.safetensors",
156
+ "model.layers.15.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
157
+ "model.layers.15.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
158
+ "model.layers.15.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
159
+ "model.layers.15.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
160
+ "model.layers.15.self_attn.k_b_proj_nope.bias": "model-00002-of-00004.safetensors",
161
+ "model.layers.15.self_attn.k_b_proj_nope.weight": "model-00002-of-00004.safetensors",
162
+ "model.layers.15.self_attn.k_nope_scale_factor": "model-00002-of-00004.safetensors",
163
+ "model.layers.15.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
164
+ "model.layers.15.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
165
+ "model.layers.15.self_attn.k_proj_pe.bias": "model-00002-of-00004.safetensors",
166
+ "model.layers.15.self_attn.k_proj_pe.weight": "model-00002-of-00004.safetensors",
167
+ "model.layers.15.self_attn.kv_a_proj_nope.weight": "model-00002-of-00004.safetensors",
168
+ "model.layers.15.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
169
+ "model.layers.15.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
170
+ "model.layers.15.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
171
+ "model.layers.15.self_attn.temperature": "model-00002-of-00004.safetensors",
172
+ "model.layers.15.self_attn.v_b_proj.bias": "model-00002-of-00004.safetensors",
173
+ "model.layers.15.self_attn.v_b_proj.weight": "model-00002-of-00004.safetensors",
174
+ "model.layers.15.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
175
+ "model.layers.15.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
176
+ "model.layers.16.input_layernorm.weight": "model-00002-of-00004.safetensors",
177
+ "model.layers.16.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
178
+ "model.layers.16.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
179
+ "model.layers.16.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
180
+ "model.layers.16.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
181
+ "model.layers.16.self_attn.k_b_proj_nope.bias": "model-00002-of-00004.safetensors",
182
+ "model.layers.16.self_attn.k_b_proj_nope.weight": "model-00002-of-00004.safetensors",
183
+ "model.layers.16.self_attn.k_nope_scale_factor": "model-00002-of-00004.safetensors",
184
+ "model.layers.16.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
185
+ "model.layers.16.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
186
+ "model.layers.16.self_attn.k_proj_pe.bias": "model-00002-of-00004.safetensors",
187
+ "model.layers.16.self_attn.k_proj_pe.weight": "model-00002-of-00004.safetensors",
188
+ "model.layers.16.self_attn.kv_a_proj_nope.weight": "model-00002-of-00004.safetensors",
189
+ "model.layers.16.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
190
+ "model.layers.16.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
191
+ "model.layers.16.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
192
+ "model.layers.16.self_attn.temperature": "model-00002-of-00004.safetensors",
193
+ "model.layers.16.self_attn.v_b_proj.bias": "model-00002-of-00004.safetensors",
194
+ "model.layers.16.self_attn.v_b_proj.weight": "model-00002-of-00004.safetensors",
195
+ "model.layers.16.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
196
+ "model.layers.16.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
197
+ "model.layers.17.input_layernorm.weight": "model-00002-of-00004.safetensors",
198
+ "model.layers.17.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
199
+ "model.layers.17.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
200
+ "model.layers.17.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
201
+ "model.layers.17.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
202
+ "model.layers.17.self_attn.k_b_proj_nope.bias": "model-00002-of-00004.safetensors",
203
+ "model.layers.17.self_attn.k_b_proj_nope.weight": "model-00002-of-00004.safetensors",
204
+ "model.layers.17.self_attn.k_nope_scale_factor": "model-00002-of-00004.safetensors",
205
+ "model.layers.17.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
206
+ "model.layers.17.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
207
+ "model.layers.17.self_attn.k_proj_pe.bias": "model-00002-of-00004.safetensors",
208
+ "model.layers.17.self_attn.k_proj_pe.weight": "model-00002-of-00004.safetensors",
209
+ "model.layers.17.self_attn.kv_a_proj_nope.weight": "model-00002-of-00004.safetensors",
210
+ "model.layers.17.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
211
+ "model.layers.17.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
212
+ "model.layers.17.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
213
+ "model.layers.17.self_attn.temperature": "model-00002-of-00004.safetensors",
214
+ "model.layers.17.self_attn.v_b_proj.bias": "model-00002-of-00004.safetensors",
215
+ "model.layers.17.self_attn.v_b_proj.weight": "model-00002-of-00004.safetensors",
216
+ "model.layers.17.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
217
+ "model.layers.17.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
218
+ "model.layers.18.input_layernorm.weight": "model-00003-of-00004.safetensors",
219
+ "model.layers.18.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
220
+ "model.layers.18.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
221
+ "model.layers.18.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
222
+ "model.layers.18.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
223
+ "model.layers.18.self_attn.k_b_proj_nope.bias": "model-00002-of-00004.safetensors",
224
+ "model.layers.18.self_attn.k_b_proj_nope.weight": "model-00002-of-00004.safetensors",
225
+ "model.layers.18.self_attn.k_nope_scale_factor": "model-00002-of-00004.safetensors",
226
+ "model.layers.18.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
227
+ "model.layers.18.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
228
+ "model.layers.18.self_attn.k_proj_pe.bias": "model-00002-of-00004.safetensors",
229
+ "model.layers.18.self_attn.k_proj_pe.weight": "model-00002-of-00004.safetensors",
230
+ "model.layers.18.self_attn.kv_a_proj_nope.weight": "model-00002-of-00004.safetensors",
231
+ "model.layers.18.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
232
+ "model.layers.18.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
233
+ "model.layers.18.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
234
+ "model.layers.18.self_attn.temperature": "model-00002-of-00004.safetensors",
235
+ "model.layers.18.self_attn.v_b_proj.bias": "model-00002-of-00004.safetensors",
236
+ "model.layers.18.self_attn.v_b_proj.weight": "model-00002-of-00004.safetensors",
237
+ "model.layers.18.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
238
+ "model.layers.18.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
239
+ "model.layers.19.input_layernorm.weight": "model-00003-of-00004.safetensors",
240
+ "model.layers.19.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
241
+ "model.layers.19.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
242
+ "model.layers.19.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
243
+ "model.layers.19.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
244
+ "model.layers.19.self_attn.k_b_proj_nope.bias": "model-00003-of-00004.safetensors",
245
+ "model.layers.19.self_attn.k_b_proj_nope.weight": "model-00003-of-00004.safetensors",
246
+ "model.layers.19.self_attn.k_nope_scale_factor": "model-00003-of-00004.safetensors",
247
+ "model.layers.19.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
248
+ "model.layers.19.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
249
+ "model.layers.19.self_attn.k_proj_pe.bias": "model-00003-of-00004.safetensors",
250
+ "model.layers.19.self_attn.k_proj_pe.weight": "model-00003-of-00004.safetensors",
251
+ "model.layers.19.self_attn.kv_a_proj_nope.weight": "model-00003-of-00004.safetensors",
252
+ "model.layers.19.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
253
+ "model.layers.19.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
254
+ "model.layers.19.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
255
+ "model.layers.19.self_attn.temperature": "model-00003-of-00004.safetensors",
256
+ "model.layers.19.self_attn.v_b_proj.bias": "model-00003-of-00004.safetensors",
257
+ "model.layers.19.self_attn.v_b_proj.weight": "model-00003-of-00004.safetensors",
258
+ "model.layers.19.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
259
+ "model.layers.19.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
260
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00004.safetensors",
261
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
262
+ "model.layers.2.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
263
+ "model.layers.2.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
264
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
265
+ "model.layers.2.self_attn.k_b_proj_nope.bias": "model-00001-of-00004.safetensors",
266
+ "model.layers.2.self_attn.k_b_proj_nope.weight": "model-00001-of-00004.safetensors",
267
+ "model.layers.2.self_attn.k_nope_scale_factor": "model-00001-of-00004.safetensors",
268
+ "model.layers.2.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
269
+ "model.layers.2.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
270
+ "model.layers.2.self_attn.k_proj_pe.bias": "model-00001-of-00004.safetensors",
271
+ "model.layers.2.self_attn.k_proj_pe.weight": "model-00001-of-00004.safetensors",
272
+ "model.layers.2.self_attn.kv_a_proj_nope.weight": "model-00001-of-00004.safetensors",
273
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
274
+ "model.layers.2.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
275
+ "model.layers.2.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
276
+ "model.layers.2.self_attn.temperature": "model-00001-of-00004.safetensors",
277
+ "model.layers.2.self_attn.v_b_proj.bias": "model-00001-of-00004.safetensors",
278
+ "model.layers.2.self_attn.v_b_proj.weight": "model-00001-of-00004.safetensors",
279
+ "model.layers.2.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
280
+ "model.layers.2.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
281
+ "model.layers.20.input_layernorm.weight": "model-00003-of-00004.safetensors",
282
+ "model.layers.20.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
283
+ "model.layers.20.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
284
+ "model.layers.20.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
285
+ "model.layers.20.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
286
+ "model.layers.20.self_attn.k_b_proj_nope.bias": "model-00003-of-00004.safetensors",
287
+ "model.layers.20.self_attn.k_b_proj_nope.weight": "model-00003-of-00004.safetensors",
288
+ "model.layers.20.self_attn.k_nope_scale_factor": "model-00003-of-00004.safetensors",
289
+ "model.layers.20.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
290
+ "model.layers.20.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
291
+ "model.layers.20.self_attn.k_proj_pe.bias": "model-00003-of-00004.safetensors",
292
+ "model.layers.20.self_attn.k_proj_pe.weight": "model-00003-of-00004.safetensors",
293
+ "model.layers.20.self_attn.kv_a_proj_nope.weight": "model-00003-of-00004.safetensors",
294
+ "model.layers.20.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
295
+ "model.layers.20.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
296
+ "model.layers.20.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
297
+ "model.layers.20.self_attn.temperature": "model-00003-of-00004.safetensors",
298
+ "model.layers.20.self_attn.v_b_proj.bias": "model-00003-of-00004.safetensors",
299
+ "model.layers.20.self_attn.v_b_proj.weight": "model-00003-of-00004.safetensors",
300
+ "model.layers.20.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
301
+ "model.layers.20.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
302
+ "model.layers.21.input_layernorm.weight": "model-00003-of-00004.safetensors",
303
+ "model.layers.21.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
304
+ "model.layers.21.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
305
+ "model.layers.21.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
306
+ "model.layers.21.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
307
+ "model.layers.21.self_attn.k_b_proj_nope.bias": "model-00003-of-00004.safetensors",
308
+ "model.layers.21.self_attn.k_b_proj_nope.weight": "model-00003-of-00004.safetensors",
309
+ "model.layers.21.self_attn.k_nope_scale_factor": "model-00003-of-00004.safetensors",
310
+ "model.layers.21.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
311
+ "model.layers.21.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
312
+ "model.layers.21.self_attn.k_proj_pe.bias": "model-00003-of-00004.safetensors",
313
+ "model.layers.21.self_attn.k_proj_pe.weight": "model-00003-of-00004.safetensors",
314
+ "model.layers.21.self_attn.kv_a_proj_nope.weight": "model-00003-of-00004.safetensors",
315
+ "model.layers.21.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
316
+ "model.layers.21.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
317
+ "model.layers.21.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
318
+ "model.layers.21.self_attn.temperature": "model-00003-of-00004.safetensors",
319
+ "model.layers.21.self_attn.v_b_proj.bias": "model-00003-of-00004.safetensors",
320
+ "model.layers.21.self_attn.v_b_proj.weight": "model-00003-of-00004.safetensors",
321
+ "model.layers.21.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
322
+ "model.layers.21.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
323
+ "model.layers.22.input_layernorm.weight": "model-00003-of-00004.safetensors",
324
+ "model.layers.22.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
325
+ "model.layers.22.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
326
+ "model.layers.22.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
327
+ "model.layers.22.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
328
+ "model.layers.22.self_attn.k_b_proj_nope.bias": "model-00003-of-00004.safetensors",
329
+ "model.layers.22.self_attn.k_b_proj_nope.weight": "model-00003-of-00004.safetensors",
330
+ "model.layers.22.self_attn.k_nope_scale_factor": "model-00003-of-00004.safetensors",
331
+ "model.layers.22.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
332
+ "model.layers.22.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
333
+ "model.layers.22.self_attn.k_proj_pe.bias": "model-00003-of-00004.safetensors",
334
+ "model.layers.22.self_attn.k_proj_pe.weight": "model-00003-of-00004.safetensors",
335
+ "model.layers.22.self_attn.kv_a_proj_nope.weight": "model-00003-of-00004.safetensors",
336
+ "model.layers.22.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
337
+ "model.layers.22.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
338
+ "model.layers.22.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
339
+ "model.layers.22.self_attn.temperature": "model-00003-of-00004.safetensors",
340
+ "model.layers.22.self_attn.v_b_proj.bias": "model-00003-of-00004.safetensors",
341
+ "model.layers.22.self_attn.v_b_proj.weight": "model-00003-of-00004.safetensors",
342
+ "model.layers.22.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
343
+ "model.layers.22.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
344
+ "model.layers.23.input_layernorm.weight": "model-00003-of-00004.safetensors",
345
+ "model.layers.23.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
346
+ "model.layers.23.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
347
+ "model.layers.23.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
348
+ "model.layers.23.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
349
+ "model.layers.23.self_attn.k_b_proj_nope.bias": "model-00003-of-00004.safetensors",
350
+ "model.layers.23.self_attn.k_b_proj_nope.weight": "model-00003-of-00004.safetensors",
351
+ "model.layers.23.self_attn.k_nope_scale_factor": "model-00003-of-00004.safetensors",
352
+ "model.layers.23.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
353
+ "model.layers.23.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
354
+ "model.layers.23.self_attn.k_proj_pe.bias": "model-00003-of-00004.safetensors",
355
+ "model.layers.23.self_attn.k_proj_pe.weight": "model-00003-of-00004.safetensors",
356
+ "model.layers.23.self_attn.kv_a_proj_nope.weight": "model-00003-of-00004.safetensors",
357
+ "model.layers.23.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
358
+ "model.layers.23.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
359
+ "model.layers.23.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
360
+ "model.layers.23.self_attn.temperature": "model-00003-of-00004.safetensors",
361
+ "model.layers.23.self_attn.v_b_proj.bias": "model-00003-of-00004.safetensors",
362
+ "model.layers.23.self_attn.v_b_proj.weight": "model-00003-of-00004.safetensors",
363
+ "model.layers.23.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
364
+ "model.layers.23.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
365
+ "model.layers.24.input_layernorm.weight": "model-00003-of-00004.safetensors",
366
+ "model.layers.24.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
367
+ "model.layers.24.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
368
+ "model.layers.24.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
369
+ "model.layers.24.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
370
+ "model.layers.24.self_attn.k_b_proj_nope.bias": "model-00003-of-00004.safetensors",
371
+ "model.layers.24.self_attn.k_b_proj_nope.weight": "model-00003-of-00004.safetensors",
372
+ "model.layers.24.self_attn.k_nope_scale_factor": "model-00003-of-00004.safetensors",
373
+ "model.layers.24.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
374
+ "model.layers.24.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
375
+ "model.layers.24.self_attn.k_proj_pe.bias": "model-00003-of-00004.safetensors",
376
+ "model.layers.24.self_attn.k_proj_pe.weight": "model-00003-of-00004.safetensors",
377
+ "model.layers.24.self_attn.kv_a_proj_nope.weight": "model-00003-of-00004.safetensors",
378
+ "model.layers.24.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
379
+ "model.layers.24.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
380
+ "model.layers.24.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
381
+ "model.layers.24.self_attn.temperature": "model-00003-of-00004.safetensors",
382
+ "model.layers.24.self_attn.v_b_proj.bias": "model-00003-of-00004.safetensors",
383
+ "model.layers.24.self_attn.v_b_proj.weight": "model-00003-of-00004.safetensors",
384
+ "model.layers.24.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
385
+ "model.layers.24.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
386
+ "model.layers.25.input_layernorm.weight": "model-00003-of-00004.safetensors",
387
+ "model.layers.25.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
388
+ "model.layers.25.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
389
+ "model.layers.25.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
390
+ "model.layers.25.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
391
+ "model.layers.25.self_attn.k_b_proj_nope.bias": "model-00003-of-00004.safetensors",
392
+ "model.layers.25.self_attn.k_b_proj_nope.weight": "model-00003-of-00004.safetensors",
393
+ "model.layers.25.self_attn.k_nope_scale_factor": "model-00003-of-00004.safetensors",
394
+ "model.layers.25.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
395
+ "model.layers.25.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
396
+ "model.layers.25.self_attn.k_proj_pe.bias": "model-00003-of-00004.safetensors",
397
+ "model.layers.25.self_attn.k_proj_pe.weight": "model-00003-of-00004.safetensors",
398
+ "model.layers.25.self_attn.kv_a_proj_nope.weight": "model-00003-of-00004.safetensors",
399
+ "model.layers.25.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
400
+ "model.layers.25.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
401
+ "model.layers.25.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
402
+ "model.layers.25.self_attn.temperature": "model-00003-of-00004.safetensors",
403
+ "model.layers.25.self_attn.v_b_proj.bias": "model-00003-of-00004.safetensors",
404
+ "model.layers.25.self_attn.v_b_proj.weight": "model-00003-of-00004.safetensors",
405
+ "model.layers.25.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
406
+ "model.layers.25.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
407
+ "model.layers.26.input_layernorm.weight": "model-00003-of-00004.safetensors",
408
+ "model.layers.26.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
409
+ "model.layers.26.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
410
+ "model.layers.26.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
411
+ "model.layers.26.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
412
+ "model.layers.26.self_attn.k_b_proj_nope.bias": "model-00003-of-00004.safetensors",
413
+ "model.layers.26.self_attn.k_b_proj_nope.weight": "model-00003-of-00004.safetensors",
414
+ "model.layers.26.self_attn.k_nope_scale_factor": "model-00003-of-00004.safetensors",
415
+ "model.layers.26.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
416
+ "model.layers.26.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
417
+ "model.layers.26.self_attn.k_proj_pe.bias": "model-00003-of-00004.safetensors",
418
+ "model.layers.26.self_attn.k_proj_pe.weight": "model-00003-of-00004.safetensors",
419
+ "model.layers.26.self_attn.kv_a_proj_nope.weight": "model-00003-of-00004.safetensors",
420
+ "model.layers.26.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
421
+ "model.layers.26.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
422
+ "model.layers.26.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
423
+ "model.layers.26.self_attn.temperature": "model-00003-of-00004.safetensors",
424
+ "model.layers.26.self_attn.v_b_proj.bias": "model-00003-of-00004.safetensors",
425
+ "model.layers.26.self_attn.v_b_proj.weight": "model-00003-of-00004.safetensors",
426
+ "model.layers.26.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
427
+ "model.layers.26.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
428
+ "model.layers.27.input_layernorm.weight": "model-00003-of-00004.safetensors",
429
+ "model.layers.27.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
430
+ "model.layers.27.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
431
+ "model.layers.27.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
432
+ "model.layers.27.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
433
+ "model.layers.27.self_attn.k_b_proj_nope.bias": "model-00003-of-00004.safetensors",
434
+ "model.layers.27.self_attn.k_b_proj_nope.weight": "model-00003-of-00004.safetensors",
435
+ "model.layers.27.self_attn.k_nope_scale_factor": "model-00003-of-00004.safetensors",
436
+ "model.layers.27.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
437
+ "model.layers.27.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
438
+ "model.layers.27.self_attn.k_proj_pe.bias": "model-00003-of-00004.safetensors",
439
+ "model.layers.27.self_attn.k_proj_pe.weight": "model-00003-of-00004.safetensors",
440
+ "model.layers.27.self_attn.kv_a_proj_nope.weight": "model-00003-of-00004.safetensors",
441
+ "model.layers.27.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
442
+ "model.layers.27.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
443
+ "model.layers.27.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
444
+ "model.layers.27.self_attn.temperature": "model-00003-of-00004.safetensors",
445
+ "model.layers.27.self_attn.v_b_proj.bias": "model-00003-of-00004.safetensors",
446
+ "model.layers.27.self_attn.v_b_proj.weight": "model-00003-of-00004.safetensors",
447
+ "model.layers.27.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
448
+ "model.layers.27.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
449
+ "model.layers.3.input_layernorm.weight": "model-00001-of-00004.safetensors",
450
+ "model.layers.3.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
451
+ "model.layers.3.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
452
+ "model.layers.3.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
453
+ "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
454
+ "model.layers.3.self_attn.k_b_proj_nope.bias": "model-00001-of-00004.safetensors",
455
+ "model.layers.3.self_attn.k_b_proj_nope.weight": "model-00001-of-00004.safetensors",
456
+ "model.layers.3.self_attn.k_nope_scale_factor": "model-00001-of-00004.safetensors",
457
+ "model.layers.3.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
458
+ "model.layers.3.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
459
+ "model.layers.3.self_attn.k_proj_pe.bias": "model-00001-of-00004.safetensors",
460
+ "model.layers.3.self_attn.k_proj_pe.weight": "model-00001-of-00004.safetensors",
461
+ "model.layers.3.self_attn.kv_a_proj_nope.weight": "model-00001-of-00004.safetensors",
462
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
463
+ "model.layers.3.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
464
+ "model.layers.3.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
465
+ "model.layers.3.self_attn.temperature": "model-00001-of-00004.safetensors",
466
+ "model.layers.3.self_attn.v_b_proj.bias": "model-00001-of-00004.safetensors",
467
+ "model.layers.3.self_attn.v_b_proj.weight": "model-00001-of-00004.safetensors",
468
+ "model.layers.3.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
469
+ "model.layers.3.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
470
+ "model.layers.4.input_layernorm.weight": "model-00001-of-00004.safetensors",
471
+ "model.layers.4.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
472
+ "model.layers.4.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
473
+ "model.layers.4.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
474
+ "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
475
+ "model.layers.4.self_attn.k_b_proj_nope.bias": "model-00001-of-00004.safetensors",
476
+ "model.layers.4.self_attn.k_b_proj_nope.weight": "model-00001-of-00004.safetensors",
477
+ "model.layers.4.self_attn.k_nope_scale_factor": "model-00001-of-00004.safetensors",
478
+ "model.layers.4.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
479
+ "model.layers.4.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
480
+ "model.layers.4.self_attn.k_proj_pe.bias": "model-00001-of-00004.safetensors",
481
+ "model.layers.4.self_attn.k_proj_pe.weight": "model-00001-of-00004.safetensors",
482
+ "model.layers.4.self_attn.kv_a_proj_nope.weight": "model-00001-of-00004.safetensors",
483
+ "model.layers.4.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
484
+ "model.layers.4.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
485
+ "model.layers.4.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
486
+ "model.layers.4.self_attn.temperature": "model-00001-of-00004.safetensors",
487
+ "model.layers.4.self_attn.v_b_proj.bias": "model-00001-of-00004.safetensors",
488
+ "model.layers.4.self_attn.v_b_proj.weight": "model-00001-of-00004.safetensors",
489
+ "model.layers.4.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
490
+ "model.layers.4.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
491
+ "model.layers.5.input_layernorm.weight": "model-00001-of-00004.safetensors",
492
+ "model.layers.5.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
493
+ "model.layers.5.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
494
+ "model.layers.5.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
495
+ "model.layers.5.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
496
+ "model.layers.5.self_attn.k_b_proj_nope.bias": "model-00001-of-00004.safetensors",
497
+ "model.layers.5.self_attn.k_b_proj_nope.weight": "model-00001-of-00004.safetensors",
498
+ "model.layers.5.self_attn.k_nope_scale_factor": "model-00001-of-00004.safetensors",
499
+ "model.layers.5.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
500
+ "model.layers.5.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
501
+ "model.layers.5.self_attn.k_proj_pe.bias": "model-00001-of-00004.safetensors",
502
+ "model.layers.5.self_attn.k_proj_pe.weight": "model-00001-of-00004.safetensors",
503
+ "model.layers.5.self_attn.kv_a_proj_nope.weight": "model-00001-of-00004.safetensors",
504
+ "model.layers.5.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
505
+ "model.layers.5.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
506
+ "model.layers.5.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
507
+ "model.layers.5.self_attn.temperature": "model-00001-of-00004.safetensors",
508
+ "model.layers.5.self_attn.v_b_proj.bias": "model-00001-of-00004.safetensors",
509
+ "model.layers.5.self_attn.v_b_proj.weight": "model-00001-of-00004.safetensors",
510
+ "model.layers.5.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
511
+ "model.layers.5.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
512
+ "model.layers.6.input_layernorm.weight": "model-00001-of-00004.safetensors",
513
+ "model.layers.6.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
514
+ "model.layers.6.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
515
+ "model.layers.6.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
516
+ "model.layers.6.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
517
+ "model.layers.6.self_attn.k_b_proj_nope.bias": "model-00001-of-00004.safetensors",
518
+ "model.layers.6.self_attn.k_b_proj_nope.weight": "model-00001-of-00004.safetensors",
519
+ "model.layers.6.self_attn.k_nope_scale_factor": "model-00001-of-00004.safetensors",
520
+ "model.layers.6.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
521
+ "model.layers.6.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
522
+ "model.layers.6.self_attn.k_proj_pe.bias": "model-00001-of-00004.safetensors",
523
+ "model.layers.6.self_attn.k_proj_pe.weight": "model-00001-of-00004.safetensors",
524
+ "model.layers.6.self_attn.kv_a_proj_nope.weight": "model-00001-of-00004.safetensors",
525
+ "model.layers.6.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
526
+ "model.layers.6.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
527
+ "model.layers.6.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
528
+ "model.layers.6.self_attn.temperature": "model-00001-of-00004.safetensors",
529
+ "model.layers.6.self_attn.v_b_proj.bias": "model-00001-of-00004.safetensors",
530
+ "model.layers.6.self_attn.v_b_proj.weight": "model-00001-of-00004.safetensors",
531
+ "model.layers.6.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
532
+ "model.layers.6.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
533
+ "model.layers.7.input_layernorm.weight": "model-00001-of-00004.safetensors",
534
+ "model.layers.7.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
535
+ "model.layers.7.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
536
+ "model.layers.7.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
537
+ "model.layers.7.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
538
+ "model.layers.7.self_attn.k_b_proj_nope.bias": "model-00001-of-00004.safetensors",
539
+ "model.layers.7.self_attn.k_b_proj_nope.weight": "model-00001-of-00004.safetensors",
540
+ "model.layers.7.self_attn.k_nope_scale_factor": "model-00001-of-00004.safetensors",
541
+ "model.layers.7.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
542
+ "model.layers.7.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
543
+ "model.layers.7.self_attn.k_proj_pe.bias": "model-00001-of-00004.safetensors",
544
+ "model.layers.7.self_attn.k_proj_pe.weight": "model-00001-of-00004.safetensors",
545
+ "model.layers.7.self_attn.kv_a_proj_nope.weight": "model-00001-of-00004.safetensors",
546
+ "model.layers.7.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
547
+ "model.layers.7.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
548
+ "model.layers.7.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
549
+ "model.layers.7.self_attn.temperature": "model-00001-of-00004.safetensors",
550
+ "model.layers.7.self_attn.v_b_proj.bias": "model-00001-of-00004.safetensors",
551
+ "model.layers.7.self_attn.v_b_proj.weight": "model-00001-of-00004.safetensors",
552
+ "model.layers.7.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
553
+ "model.layers.7.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
554
+ "model.layers.8.input_layernorm.weight": "model-00002-of-00004.safetensors",
555
+ "model.layers.8.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
556
+ "model.layers.8.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
557
+ "model.layers.8.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
558
+ "model.layers.8.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
559
+ "model.layers.8.self_attn.k_b_proj_nope.bias": "model-00001-of-00004.safetensors",
560
+ "model.layers.8.self_attn.k_b_proj_nope.weight": "model-00001-of-00004.safetensors",
561
+ "model.layers.8.self_attn.k_nope_scale_factor": "model-00001-of-00004.safetensors",
562
+ "model.layers.8.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
563
+ "model.layers.8.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
564
+ "model.layers.8.self_attn.k_proj_pe.bias": "model-00001-of-00004.safetensors",
565
+ "model.layers.8.self_attn.k_proj_pe.weight": "model-00001-of-00004.safetensors",
566
+ "model.layers.8.self_attn.kv_a_proj_nope.weight": "model-00001-of-00004.safetensors",
567
+ "model.layers.8.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
568
+ "model.layers.8.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
569
+ "model.layers.8.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
570
+ "model.layers.8.self_attn.temperature": "model-00001-of-00004.safetensors",
571
+ "model.layers.8.self_attn.v_b_proj.bias": "model-00001-of-00004.safetensors",
572
+ "model.layers.8.self_attn.v_b_proj.weight": "model-00001-of-00004.safetensors",
573
+ "model.layers.8.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
574
+ "model.layers.8.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
575
+ "model.layers.9.input_layernorm.weight": "model-00002-of-00004.safetensors",
576
+ "model.layers.9.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
577
+ "model.layers.9.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
578
+ "model.layers.9.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
579
+ "model.layers.9.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
580
+ "model.layers.9.self_attn.k_b_proj_nope.bias": "model-00002-of-00004.safetensors",
581
+ "model.layers.9.self_attn.k_b_proj_nope.weight": "model-00002-of-00004.safetensors",
582
+ "model.layers.9.self_attn.k_nope_scale_factor": "model-00002-of-00004.safetensors",
583
+ "model.layers.9.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
584
+ "model.layers.9.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
585
+ "model.layers.9.self_attn.k_proj_pe.bias": "model-00002-of-00004.safetensors",
586
+ "model.layers.9.self_attn.k_proj_pe.weight": "model-00002-of-00004.safetensors",
587
+ "model.layers.9.self_attn.kv_a_proj_nope.weight": "model-00002-of-00004.safetensors",
588
+ "model.layers.9.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
589
+ "model.layers.9.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
590
+ "model.layers.9.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
591
+ "model.layers.9.self_attn.temperature": "model-00002-of-00004.safetensors",
592
+ "model.layers.9.self_attn.v_b_proj.bias": "model-00002-of-00004.safetensors",
593
+ "model.layers.9.self_attn.v_b_proj.weight": "model-00002-of-00004.safetensors",
594
+ "model.layers.9.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
595
+ "model.layers.9.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
596
+ "model.mm_projector.mlp.0.bias": "model-00004-of-00004.safetensors",
597
+ "model.mm_projector.mlp.0.weight": "model-00004-of-00004.safetensors",
598
+ "model.mm_projector.mlp.2.bias": "model-00004-of-00004.safetensors",
599
+ "model.mm_projector.mlp.2.weight": "model-00004-of-00004.safetensors",
600
+ "model.norm.weight": "model-00003-of-00004.safetensors",
601
+ "model.vision_tower.vision_tower.encoder.blocks.0.attn.proj.bias": "model-00003-of-00004.safetensors",
602
+ "model.vision_tower.vision_tower.encoder.blocks.0.attn.proj.weight": "model-00003-of-00004.safetensors",
603
+ "model.vision_tower.vision_tower.encoder.blocks.0.attn.q_bias": "model-00003-of-00004.safetensors",
604
+ "model.vision_tower.vision_tower.encoder.blocks.0.attn.qkv.weight": "model-00003-of-00004.safetensors",
605
+ "model.vision_tower.vision_tower.encoder.blocks.0.attn.v_bias": "model-00003-of-00004.safetensors",
606
+ "model.vision_tower.vision_tower.encoder.blocks.0.mlp.fc1.bias": "model-00003-of-00004.safetensors",
607
+ "model.vision_tower.vision_tower.encoder.blocks.0.mlp.fc1.weight": "model-00003-of-00004.safetensors",
608
+ "model.vision_tower.vision_tower.encoder.blocks.0.mlp.fc2.bias": "model-00003-of-00004.safetensors",
609
+ "model.vision_tower.vision_tower.encoder.blocks.0.mlp.fc2.weight": "model-00003-of-00004.safetensors",
610
+ "model.vision_tower.vision_tower.encoder.blocks.0.norm1.bias": "model-00003-of-00004.safetensors",
611
+ "model.vision_tower.vision_tower.encoder.blocks.0.norm1.weight": "model-00003-of-00004.safetensors",
612
+ "model.vision_tower.vision_tower.encoder.blocks.0.norm2.bias": "model-00003-of-00004.safetensors",
613
+ "model.vision_tower.vision_tower.encoder.blocks.0.norm2.weight": "model-00003-of-00004.safetensors",
614
+ "model.vision_tower.vision_tower.encoder.blocks.1.attn.proj.bias": "model-00003-of-00004.safetensors",
615
+ "model.vision_tower.vision_tower.encoder.blocks.1.attn.proj.weight": "model-00003-of-00004.safetensors",
616
+ "model.vision_tower.vision_tower.encoder.blocks.1.attn.q_bias": "model-00003-of-00004.safetensors",
617
+ "model.vision_tower.vision_tower.encoder.blocks.1.attn.qkv.weight": "model-00003-of-00004.safetensors",
618
+ "model.vision_tower.vision_tower.encoder.blocks.1.attn.v_bias": "model-00003-of-00004.safetensors",
619
+ "model.vision_tower.vision_tower.encoder.blocks.1.mlp.fc1.bias": "model-00003-of-00004.safetensors",
620
+ "model.vision_tower.vision_tower.encoder.blocks.1.mlp.fc1.weight": "model-00003-of-00004.safetensors",
621
+ "model.vision_tower.vision_tower.encoder.blocks.1.mlp.fc2.bias": "model-00003-of-00004.safetensors",
622
+ "model.vision_tower.vision_tower.encoder.blocks.1.mlp.fc2.weight": "model-00003-of-00004.safetensors",
623
+ "model.vision_tower.vision_tower.encoder.blocks.1.norm1.bias": "model-00003-of-00004.safetensors",
624
+ "model.vision_tower.vision_tower.encoder.blocks.1.norm1.weight": "model-00003-of-00004.safetensors",
625
+ "model.vision_tower.vision_tower.encoder.blocks.1.norm2.bias": "model-00003-of-00004.safetensors",
626
+ "model.vision_tower.vision_tower.encoder.blocks.1.norm2.weight": "model-00003-of-00004.safetensors",
627
+ "model.vision_tower.vision_tower.encoder.blocks.10.attn.proj.bias": "model-00003-of-00004.safetensors",
628
+ "model.vision_tower.vision_tower.encoder.blocks.10.attn.proj.weight": "model-00003-of-00004.safetensors",
629
+ "model.vision_tower.vision_tower.encoder.blocks.10.attn.q_bias": "model-00003-of-00004.safetensors",
630
+ "model.vision_tower.vision_tower.encoder.blocks.10.attn.qkv.weight": "model-00003-of-00004.safetensors",
631
+ "model.vision_tower.vision_tower.encoder.blocks.10.attn.v_bias": "model-00003-of-00004.safetensors",
632
+ "model.vision_tower.vision_tower.encoder.blocks.10.mlp.fc1.bias": "model-00003-of-00004.safetensors",
633
+ "model.vision_tower.vision_tower.encoder.blocks.10.mlp.fc1.weight": "model-00003-of-00004.safetensors",
634
+ "model.vision_tower.vision_tower.encoder.blocks.10.mlp.fc2.bias": "model-00003-of-00004.safetensors",
635
+ "model.vision_tower.vision_tower.encoder.blocks.10.mlp.fc2.weight": "model-00003-of-00004.safetensors",
636
+ "model.vision_tower.vision_tower.encoder.blocks.10.norm1.bias": "model-00003-of-00004.safetensors",
637
+ "model.vision_tower.vision_tower.encoder.blocks.10.norm1.weight": "model-00003-of-00004.safetensors",
638
+ "model.vision_tower.vision_tower.encoder.blocks.10.norm2.bias": "model-00003-of-00004.safetensors",
639
+ "model.vision_tower.vision_tower.encoder.blocks.10.norm2.weight": "model-00003-of-00004.safetensors",
640
+ "model.vision_tower.vision_tower.encoder.blocks.11.attn.proj.bias": "model-00003-of-00004.safetensors",
641
+ "model.vision_tower.vision_tower.encoder.blocks.11.attn.proj.weight": "model-00003-of-00004.safetensors",
642
+ "model.vision_tower.vision_tower.encoder.blocks.11.attn.q_bias": "model-00003-of-00004.safetensors",
643
+ "model.vision_tower.vision_tower.encoder.blocks.11.attn.qkv.weight": "model-00003-of-00004.safetensors",
644
+ "model.vision_tower.vision_tower.encoder.blocks.11.attn.v_bias": "model-00003-of-00004.safetensors",
645
+ "model.vision_tower.vision_tower.encoder.blocks.11.mlp.fc1.bias": "model-00003-of-00004.safetensors",
646
+ "model.vision_tower.vision_tower.encoder.blocks.11.mlp.fc1.weight": "model-00003-of-00004.safetensors",
647
+ "model.vision_tower.vision_tower.encoder.blocks.11.mlp.fc2.bias": "model-00003-of-00004.safetensors",
648
+ "model.vision_tower.vision_tower.encoder.blocks.11.mlp.fc2.weight": "model-00003-of-00004.safetensors",
649
+ "model.vision_tower.vision_tower.encoder.blocks.11.norm1.bias": "model-00003-of-00004.safetensors",
650
+ "model.vision_tower.vision_tower.encoder.blocks.11.norm1.weight": "model-00003-of-00004.safetensors",
651
+ "model.vision_tower.vision_tower.encoder.blocks.11.norm2.bias": "model-00003-of-00004.safetensors",
652
+ "model.vision_tower.vision_tower.encoder.blocks.11.norm2.weight": "model-00003-of-00004.safetensors",
653
+ "model.vision_tower.vision_tower.encoder.blocks.12.attn.proj.bias": "model-00003-of-00004.safetensors",
654
+ "model.vision_tower.vision_tower.encoder.blocks.12.attn.proj.weight": "model-00003-of-00004.safetensors",
655
+ "model.vision_tower.vision_tower.encoder.blocks.12.attn.q_bias": "model-00003-of-00004.safetensors",
656
+ "model.vision_tower.vision_tower.encoder.blocks.12.attn.qkv.weight": "model-00003-of-00004.safetensors",
657
+ "model.vision_tower.vision_tower.encoder.blocks.12.attn.v_bias": "model-00003-of-00004.safetensors",
658
+ "model.vision_tower.vision_tower.encoder.blocks.12.mlp.fc1.bias": "model-00003-of-00004.safetensors",
659
+ "model.vision_tower.vision_tower.encoder.blocks.12.mlp.fc1.weight": "model-00003-of-00004.safetensors",
660
+ "model.vision_tower.vision_tower.encoder.blocks.12.mlp.fc2.bias": "model-00003-of-00004.safetensors",
661
+ "model.vision_tower.vision_tower.encoder.blocks.12.mlp.fc2.weight": "model-00003-of-00004.safetensors",
662
+ "model.vision_tower.vision_tower.encoder.blocks.12.norm1.bias": "model-00003-of-00004.safetensors",
663
+ "model.vision_tower.vision_tower.encoder.blocks.12.norm1.weight": "model-00003-of-00004.safetensors",
664
+ "model.vision_tower.vision_tower.encoder.blocks.12.norm2.bias": "model-00003-of-00004.safetensors",
665
+ "model.vision_tower.vision_tower.encoder.blocks.12.norm2.weight": "model-00003-of-00004.safetensors",
666
+ "model.vision_tower.vision_tower.encoder.blocks.13.attn.proj.bias": "model-00003-of-00004.safetensors",
667
+ "model.vision_tower.vision_tower.encoder.blocks.13.attn.proj.weight": "model-00003-of-00004.safetensors",
668
+ "model.vision_tower.vision_tower.encoder.blocks.13.attn.q_bias": "model-00003-of-00004.safetensors",
669
+ "model.vision_tower.vision_tower.encoder.blocks.13.attn.qkv.weight": "model-00003-of-00004.safetensors",
670
+ "model.vision_tower.vision_tower.encoder.blocks.13.attn.v_bias": "model-00003-of-00004.safetensors",
671
+ "model.vision_tower.vision_tower.encoder.blocks.13.mlp.fc1.bias": "model-00003-of-00004.safetensors",
672
+ "model.vision_tower.vision_tower.encoder.blocks.13.mlp.fc1.weight": "model-00003-of-00004.safetensors",
673
+ "model.vision_tower.vision_tower.encoder.blocks.13.mlp.fc2.bias": "model-00003-of-00004.safetensors",
674
+ "model.vision_tower.vision_tower.encoder.blocks.13.mlp.fc2.weight": "model-00003-of-00004.safetensors",
675
+ "model.vision_tower.vision_tower.encoder.blocks.13.norm1.bias": "model-00003-of-00004.safetensors",
676
+ "model.vision_tower.vision_tower.encoder.blocks.13.norm1.weight": "model-00003-of-00004.safetensors",
677
+ "model.vision_tower.vision_tower.encoder.blocks.13.norm2.bias": "model-00003-of-00004.safetensors",
678
+ "model.vision_tower.vision_tower.encoder.blocks.13.norm2.weight": "model-00003-of-00004.safetensors",
679
+ "model.vision_tower.vision_tower.encoder.blocks.14.attn.proj.bias": "model-00003-of-00004.safetensors",
680
+ "model.vision_tower.vision_tower.encoder.blocks.14.attn.proj.weight": "model-00003-of-00004.safetensors",
681
+ "model.vision_tower.vision_tower.encoder.blocks.14.attn.q_bias": "model-00003-of-00004.safetensors",
682
+ "model.vision_tower.vision_tower.encoder.blocks.14.attn.qkv.weight": "model-00003-of-00004.safetensors",
683
+ "model.vision_tower.vision_tower.encoder.blocks.14.attn.v_bias": "model-00003-of-00004.safetensors",
684
+ "model.vision_tower.vision_tower.encoder.blocks.14.mlp.fc1.bias": "model-00003-of-00004.safetensors",
685
+ "model.vision_tower.vision_tower.encoder.blocks.14.mlp.fc1.weight": "model-00003-of-00004.safetensors",
686
+ "model.vision_tower.vision_tower.encoder.blocks.14.mlp.fc2.bias": "model-00003-of-00004.safetensors",
687
+ "model.vision_tower.vision_tower.encoder.blocks.14.mlp.fc2.weight": "model-00003-of-00004.safetensors",
688
+ "model.vision_tower.vision_tower.encoder.blocks.14.norm1.bias": "model-00003-of-00004.safetensors",
689
+ "model.vision_tower.vision_tower.encoder.blocks.14.norm1.weight": "model-00003-of-00004.safetensors",
690
+ "model.vision_tower.vision_tower.encoder.blocks.14.norm2.bias": "model-00003-of-00004.safetensors",
691
+ "model.vision_tower.vision_tower.encoder.blocks.14.norm2.weight": "model-00003-of-00004.safetensors",
692
+ "model.vision_tower.vision_tower.encoder.blocks.15.attn.proj.bias": "model-00003-of-00004.safetensors",
693
+ "model.vision_tower.vision_tower.encoder.blocks.15.attn.proj.weight": "model-00003-of-00004.safetensors",
694
+ "model.vision_tower.vision_tower.encoder.blocks.15.attn.q_bias": "model-00003-of-00004.safetensors",
695
+ "model.vision_tower.vision_tower.encoder.blocks.15.attn.qkv.weight": "model-00003-of-00004.safetensors",
696
+ "model.vision_tower.vision_tower.encoder.blocks.15.attn.v_bias": "model-00003-of-00004.safetensors",
697
+ "model.vision_tower.vision_tower.encoder.blocks.15.mlp.fc1.bias": "model-00003-of-00004.safetensors",
698
+ "model.vision_tower.vision_tower.encoder.blocks.15.mlp.fc1.weight": "model-00003-of-00004.safetensors",
699
+ "model.vision_tower.vision_tower.encoder.blocks.15.mlp.fc2.bias": "model-00003-of-00004.safetensors",
700
+ "model.vision_tower.vision_tower.encoder.blocks.15.mlp.fc2.weight": "model-00003-of-00004.safetensors",
701
+ "model.vision_tower.vision_tower.encoder.blocks.15.norm1.bias": "model-00003-of-00004.safetensors",
702
+ "model.vision_tower.vision_tower.encoder.blocks.15.norm1.weight": "model-00003-of-00004.safetensors",
703
+ "model.vision_tower.vision_tower.encoder.blocks.15.norm2.bias": "model-00003-of-00004.safetensors",
704
+ "model.vision_tower.vision_tower.encoder.blocks.15.norm2.weight": "model-00003-of-00004.safetensors",
705
+ "model.vision_tower.vision_tower.encoder.blocks.16.attn.proj.bias": "model-00003-of-00004.safetensors",
706
+ "model.vision_tower.vision_tower.encoder.blocks.16.attn.proj.weight": "model-00003-of-00004.safetensors",
707
+ "model.vision_tower.vision_tower.encoder.blocks.16.attn.q_bias": "model-00003-of-00004.safetensors",
708
+ "model.vision_tower.vision_tower.encoder.blocks.16.attn.qkv.weight": "model-00003-of-00004.safetensors",
709
+ "model.vision_tower.vision_tower.encoder.blocks.16.attn.v_bias": "model-00003-of-00004.safetensors",
710
+ "model.vision_tower.vision_tower.encoder.blocks.16.mlp.fc1.bias": "model-00003-of-00004.safetensors",
711
+ "model.vision_tower.vision_tower.encoder.blocks.16.mlp.fc1.weight": "model-00003-of-00004.safetensors",
712
+ "model.vision_tower.vision_tower.encoder.blocks.16.mlp.fc2.bias": "model-00003-of-00004.safetensors",
713
+ "model.vision_tower.vision_tower.encoder.blocks.16.mlp.fc2.weight": "model-00003-of-00004.safetensors",
714
+ "model.vision_tower.vision_tower.encoder.blocks.16.norm1.bias": "model-00003-of-00004.safetensors",
715
+ "model.vision_tower.vision_tower.encoder.blocks.16.norm1.weight": "model-00003-of-00004.safetensors",
716
+ "model.vision_tower.vision_tower.encoder.blocks.16.norm2.bias": "model-00003-of-00004.safetensors",
717
+ "model.vision_tower.vision_tower.encoder.blocks.16.norm2.weight": "model-00003-of-00004.safetensors",
718
+ "model.vision_tower.vision_tower.encoder.blocks.17.attn.proj.bias": "model-00004-of-00004.safetensors",
719
+ "model.vision_tower.vision_tower.encoder.blocks.17.attn.proj.weight": "model-00004-of-00004.safetensors",
720
+ "model.vision_tower.vision_tower.encoder.blocks.17.attn.q_bias": "model-00003-of-00004.safetensors",
721
+ "model.vision_tower.vision_tower.encoder.blocks.17.attn.qkv.weight": "model-00004-of-00004.safetensors",
722
+ "model.vision_tower.vision_tower.encoder.blocks.17.attn.v_bias": "model-00003-of-00004.safetensors",
723
+ "model.vision_tower.vision_tower.encoder.blocks.17.mlp.fc1.bias": "model-00004-of-00004.safetensors",
724
+ "model.vision_tower.vision_tower.encoder.blocks.17.mlp.fc1.weight": "model-00004-of-00004.safetensors",
725
+ "model.vision_tower.vision_tower.encoder.blocks.17.mlp.fc2.bias": "model-00004-of-00004.safetensors",
726
+ "model.vision_tower.vision_tower.encoder.blocks.17.mlp.fc2.weight": "model-00004-of-00004.safetensors",
727
+ "model.vision_tower.vision_tower.encoder.blocks.17.norm1.bias": "model-00003-of-00004.safetensors",
728
+ "model.vision_tower.vision_tower.encoder.blocks.17.norm1.weight": "model-00003-of-00004.safetensors",
729
+ "model.vision_tower.vision_tower.encoder.blocks.17.norm2.bias": "model-00004-of-00004.safetensors",
730
+ "model.vision_tower.vision_tower.encoder.blocks.17.norm2.weight": "model-00004-of-00004.safetensors",
731
+ "model.vision_tower.vision_tower.encoder.blocks.18.attn.proj.bias": "model-00004-of-00004.safetensors",
732
+ "model.vision_tower.vision_tower.encoder.blocks.18.attn.proj.weight": "model-00004-of-00004.safetensors",
733
+ "model.vision_tower.vision_tower.encoder.blocks.18.attn.q_bias": "model-00004-of-00004.safetensors",
734
+ "model.vision_tower.vision_tower.encoder.blocks.18.attn.qkv.weight": "model-00004-of-00004.safetensors",
735
+ "model.vision_tower.vision_tower.encoder.blocks.18.attn.v_bias": "model-00004-of-00004.safetensors",
736
+ "model.vision_tower.vision_tower.encoder.blocks.18.mlp.fc1.bias": "model-00004-of-00004.safetensors",
737
+ "model.vision_tower.vision_tower.encoder.blocks.18.mlp.fc1.weight": "model-00004-of-00004.safetensors",
738
+ "model.vision_tower.vision_tower.encoder.blocks.18.mlp.fc2.bias": "model-00004-of-00004.safetensors",
739
+ "model.vision_tower.vision_tower.encoder.blocks.18.mlp.fc2.weight": "model-00004-of-00004.safetensors",
740
+ "model.vision_tower.vision_tower.encoder.blocks.18.norm1.bias": "model-00004-of-00004.safetensors",
741
+ "model.vision_tower.vision_tower.encoder.blocks.18.norm1.weight": "model-00004-of-00004.safetensors",
742
+ "model.vision_tower.vision_tower.encoder.blocks.18.norm2.bias": "model-00004-of-00004.safetensors",
743
+ "model.vision_tower.vision_tower.encoder.blocks.18.norm2.weight": "model-00004-of-00004.safetensors",
744
+ "model.vision_tower.vision_tower.encoder.blocks.19.attn.proj.bias": "model-00004-of-00004.safetensors",
745
+ "model.vision_tower.vision_tower.encoder.blocks.19.attn.proj.weight": "model-00004-of-00004.safetensors",
746
+ "model.vision_tower.vision_tower.encoder.blocks.19.attn.q_bias": "model-00004-of-00004.safetensors",
747
+ "model.vision_tower.vision_tower.encoder.blocks.19.attn.qkv.weight": "model-00004-of-00004.safetensors",
748
+ "model.vision_tower.vision_tower.encoder.blocks.19.attn.v_bias": "model-00004-of-00004.safetensors",
749
+ "model.vision_tower.vision_tower.encoder.blocks.19.mlp.fc1.bias": "model-00004-of-00004.safetensors",
750
+ "model.vision_tower.vision_tower.encoder.blocks.19.mlp.fc1.weight": "model-00004-of-00004.safetensors",
751
+ "model.vision_tower.vision_tower.encoder.blocks.19.mlp.fc2.bias": "model-00004-of-00004.safetensors",
752
+ "model.vision_tower.vision_tower.encoder.blocks.19.mlp.fc2.weight": "model-00004-of-00004.safetensors",
753
+ "model.vision_tower.vision_tower.encoder.blocks.19.norm1.bias": "model-00004-of-00004.safetensors",
754
+ "model.vision_tower.vision_tower.encoder.blocks.19.norm1.weight": "model-00004-of-00004.safetensors",
755
+ "model.vision_tower.vision_tower.encoder.blocks.19.norm2.bias": "model-00004-of-00004.safetensors",
756
+ "model.vision_tower.vision_tower.encoder.blocks.19.norm2.weight": "model-00004-of-00004.safetensors",
757
+ "model.vision_tower.vision_tower.encoder.blocks.2.attn.proj.bias": "model-00003-of-00004.safetensors",
758
+ "model.vision_tower.vision_tower.encoder.blocks.2.attn.proj.weight": "model-00003-of-00004.safetensors",
759
+ "model.vision_tower.vision_tower.encoder.blocks.2.attn.q_bias": "model-00003-of-00004.safetensors",
760
+ "model.vision_tower.vision_tower.encoder.blocks.2.attn.qkv.weight": "model-00003-of-00004.safetensors",
761
+ "model.vision_tower.vision_tower.encoder.blocks.2.attn.v_bias": "model-00003-of-00004.safetensors",
762
+ "model.vision_tower.vision_tower.encoder.blocks.2.mlp.fc1.bias": "model-00003-of-00004.safetensors",
763
+ "model.vision_tower.vision_tower.encoder.blocks.2.mlp.fc1.weight": "model-00003-of-00004.safetensors",
764
+ "model.vision_tower.vision_tower.encoder.blocks.2.mlp.fc2.bias": "model-00003-of-00004.safetensors",
765
+ "model.vision_tower.vision_tower.encoder.blocks.2.mlp.fc2.weight": "model-00003-of-00004.safetensors",
766
+ "model.vision_tower.vision_tower.encoder.blocks.2.norm1.bias": "model-00003-of-00004.safetensors",
767
+ "model.vision_tower.vision_tower.encoder.blocks.2.norm1.weight": "model-00003-of-00004.safetensors",
768
+ "model.vision_tower.vision_tower.encoder.blocks.2.norm2.bias": "model-00003-of-00004.safetensors",
769
+ "model.vision_tower.vision_tower.encoder.blocks.2.norm2.weight": "model-00003-of-00004.safetensors",
770
+ "model.vision_tower.vision_tower.encoder.blocks.20.attn.proj.bias": "model-00004-of-00004.safetensors",
771
+ "model.vision_tower.vision_tower.encoder.blocks.20.attn.proj.weight": "model-00004-of-00004.safetensors",
772
+ "model.vision_tower.vision_tower.encoder.blocks.20.attn.q_bias": "model-00004-of-00004.safetensors",
773
+ "model.vision_tower.vision_tower.encoder.blocks.20.attn.qkv.weight": "model-00004-of-00004.safetensors",
774
+ "model.vision_tower.vision_tower.encoder.blocks.20.attn.v_bias": "model-00004-of-00004.safetensors",
775
+ "model.vision_tower.vision_tower.encoder.blocks.20.mlp.fc1.bias": "model-00004-of-00004.safetensors",
776
+ "model.vision_tower.vision_tower.encoder.blocks.20.mlp.fc1.weight": "model-00004-of-00004.safetensors",
777
+ "model.vision_tower.vision_tower.encoder.blocks.20.mlp.fc2.bias": "model-00004-of-00004.safetensors",
778
+ "model.vision_tower.vision_tower.encoder.blocks.20.mlp.fc2.weight": "model-00004-of-00004.safetensors",
779
+ "model.vision_tower.vision_tower.encoder.blocks.20.norm1.bias": "model-00004-of-00004.safetensors",
780
+ "model.vision_tower.vision_tower.encoder.blocks.20.norm1.weight": "model-00004-of-00004.safetensors",
781
+ "model.vision_tower.vision_tower.encoder.blocks.20.norm2.bias": "model-00004-of-00004.safetensors",
782
+ "model.vision_tower.vision_tower.encoder.blocks.20.norm2.weight": "model-00004-of-00004.safetensors",
783
+ "model.vision_tower.vision_tower.encoder.blocks.21.attn.proj.bias": "model-00004-of-00004.safetensors",
784
+ "model.vision_tower.vision_tower.encoder.blocks.21.attn.proj.weight": "model-00004-of-00004.safetensors",
785
+ "model.vision_tower.vision_tower.encoder.blocks.21.attn.q_bias": "model-00004-of-00004.safetensors",
786
+ "model.vision_tower.vision_tower.encoder.blocks.21.attn.qkv.weight": "model-00004-of-00004.safetensors",
787
+ "model.vision_tower.vision_tower.encoder.blocks.21.attn.v_bias": "model-00004-of-00004.safetensors",
788
+ "model.vision_tower.vision_tower.encoder.blocks.21.mlp.fc1.bias": "model-00004-of-00004.safetensors",
789
+ "model.vision_tower.vision_tower.encoder.blocks.21.mlp.fc1.weight": "model-00004-of-00004.safetensors",
790
+ "model.vision_tower.vision_tower.encoder.blocks.21.mlp.fc2.bias": "model-00004-of-00004.safetensors",
791
+ "model.vision_tower.vision_tower.encoder.blocks.21.mlp.fc2.weight": "model-00004-of-00004.safetensors",
792
+ "model.vision_tower.vision_tower.encoder.blocks.21.norm1.bias": "model-00004-of-00004.safetensors",
793
+ "model.vision_tower.vision_tower.encoder.blocks.21.norm1.weight": "model-00004-of-00004.safetensors",
794
+ "model.vision_tower.vision_tower.encoder.blocks.21.norm2.bias": "model-00004-of-00004.safetensors",
795
+ "model.vision_tower.vision_tower.encoder.blocks.21.norm2.weight": "model-00004-of-00004.safetensors",
796
+ "model.vision_tower.vision_tower.encoder.blocks.22.attn.proj.bias": "model-00004-of-00004.safetensors",
797
+ "model.vision_tower.vision_tower.encoder.blocks.22.attn.proj.weight": "model-00004-of-00004.safetensors",
798
+ "model.vision_tower.vision_tower.encoder.blocks.22.attn.q_bias": "model-00004-of-00004.safetensors",
799
+ "model.vision_tower.vision_tower.encoder.blocks.22.attn.qkv.weight": "model-00004-of-00004.safetensors",
800
+ "model.vision_tower.vision_tower.encoder.blocks.22.attn.v_bias": "model-00004-of-00004.safetensors",
801
+ "model.vision_tower.vision_tower.encoder.blocks.22.mlp.fc1.bias": "model-00004-of-00004.safetensors",
802
+ "model.vision_tower.vision_tower.encoder.blocks.22.mlp.fc1.weight": "model-00004-of-00004.safetensors",
803
+ "model.vision_tower.vision_tower.encoder.blocks.22.mlp.fc2.bias": "model-00004-of-00004.safetensors",
804
+ "model.vision_tower.vision_tower.encoder.blocks.22.mlp.fc2.weight": "model-00004-of-00004.safetensors",
805
+ "model.vision_tower.vision_tower.encoder.blocks.22.norm1.bias": "model-00004-of-00004.safetensors",
806
+ "model.vision_tower.vision_tower.encoder.blocks.22.norm1.weight": "model-00004-of-00004.safetensors",
807
+ "model.vision_tower.vision_tower.encoder.blocks.22.norm2.bias": "model-00004-of-00004.safetensors",
808
+ "model.vision_tower.vision_tower.encoder.blocks.22.norm2.weight": "model-00004-of-00004.safetensors",
809
+ "model.vision_tower.vision_tower.encoder.blocks.3.attn.proj.bias": "model-00003-of-00004.safetensors",
810
+ "model.vision_tower.vision_tower.encoder.blocks.3.attn.proj.weight": "model-00003-of-00004.safetensors",
811
+ "model.vision_tower.vision_tower.encoder.blocks.3.attn.q_bias": "model-00003-of-00004.safetensors",
812
+ "model.vision_tower.vision_tower.encoder.blocks.3.attn.qkv.weight": "model-00003-of-00004.safetensors",
813
+ "model.vision_tower.vision_tower.encoder.blocks.3.attn.v_bias": "model-00003-of-00004.safetensors",
814
+ "model.vision_tower.vision_tower.encoder.blocks.3.mlp.fc1.bias": "model-00003-of-00004.safetensors",
815
+ "model.vision_tower.vision_tower.encoder.blocks.3.mlp.fc1.weight": "model-00003-of-00004.safetensors",
816
+ "model.vision_tower.vision_tower.encoder.blocks.3.mlp.fc2.bias": "model-00003-of-00004.safetensors",
817
+ "model.vision_tower.vision_tower.encoder.blocks.3.mlp.fc2.weight": "model-00003-of-00004.safetensors",
818
+ "model.vision_tower.vision_tower.encoder.blocks.3.norm1.bias": "model-00003-of-00004.safetensors",
819
+ "model.vision_tower.vision_tower.encoder.blocks.3.norm1.weight": "model-00003-of-00004.safetensors",
820
+ "model.vision_tower.vision_tower.encoder.blocks.3.norm2.bias": "model-00003-of-00004.safetensors",
821
+ "model.vision_tower.vision_tower.encoder.blocks.3.norm2.weight": "model-00003-of-00004.safetensors",
822
+ "model.vision_tower.vision_tower.encoder.blocks.4.attn.proj.bias": "model-00003-of-00004.safetensors",
823
+ "model.vision_tower.vision_tower.encoder.blocks.4.attn.proj.weight": "model-00003-of-00004.safetensors",
824
+ "model.vision_tower.vision_tower.encoder.blocks.4.attn.q_bias": "model-00003-of-00004.safetensors",
825
+ "model.vision_tower.vision_tower.encoder.blocks.4.attn.qkv.weight": "model-00003-of-00004.safetensors",
826
+ "model.vision_tower.vision_tower.encoder.blocks.4.attn.v_bias": "model-00003-of-00004.safetensors",
827
+ "model.vision_tower.vision_tower.encoder.blocks.4.mlp.fc1.bias": "model-00003-of-00004.safetensors",
828
+ "model.vision_tower.vision_tower.encoder.blocks.4.mlp.fc1.weight": "model-00003-of-00004.safetensors",
829
+ "model.vision_tower.vision_tower.encoder.blocks.4.mlp.fc2.bias": "model-00003-of-00004.safetensors",
830
+ "model.vision_tower.vision_tower.encoder.blocks.4.mlp.fc2.weight": "model-00003-of-00004.safetensors",
831
+ "model.vision_tower.vision_tower.encoder.blocks.4.norm1.bias": "model-00003-of-00004.safetensors",
832
+ "model.vision_tower.vision_tower.encoder.blocks.4.norm1.weight": "model-00003-of-00004.safetensors",
833
+ "model.vision_tower.vision_tower.encoder.blocks.4.norm2.bias": "model-00003-of-00004.safetensors",
834
+ "model.vision_tower.vision_tower.encoder.blocks.4.norm2.weight": "model-00003-of-00004.safetensors",
835
+ "model.vision_tower.vision_tower.encoder.blocks.5.attn.proj.bias": "model-00003-of-00004.safetensors",
836
+ "model.vision_tower.vision_tower.encoder.blocks.5.attn.proj.weight": "model-00003-of-00004.safetensors",
837
+ "model.vision_tower.vision_tower.encoder.blocks.5.attn.q_bias": "model-00003-of-00004.safetensors",
838
+ "model.vision_tower.vision_tower.encoder.blocks.5.attn.qkv.weight": "model-00003-of-00004.safetensors",
839
+ "model.vision_tower.vision_tower.encoder.blocks.5.attn.v_bias": "model-00003-of-00004.safetensors",
840
+ "model.vision_tower.vision_tower.encoder.blocks.5.mlp.fc1.bias": "model-00003-of-00004.safetensors",
841
+ "model.vision_tower.vision_tower.encoder.blocks.5.mlp.fc1.weight": "model-00003-of-00004.safetensors",
842
+ "model.vision_tower.vision_tower.encoder.blocks.5.mlp.fc2.bias": "model-00003-of-00004.safetensors",
843
+ "model.vision_tower.vision_tower.encoder.blocks.5.mlp.fc2.weight": "model-00003-of-00004.safetensors",
844
+ "model.vision_tower.vision_tower.encoder.blocks.5.norm1.bias": "model-00003-of-00004.safetensors",
845
+ "model.vision_tower.vision_tower.encoder.blocks.5.norm1.weight": "model-00003-of-00004.safetensors",
846
+ "model.vision_tower.vision_tower.encoder.blocks.5.norm2.bias": "model-00003-of-00004.safetensors",
847
+ "model.vision_tower.vision_tower.encoder.blocks.5.norm2.weight": "model-00003-of-00004.safetensors",
848
+ "model.vision_tower.vision_tower.encoder.blocks.6.attn.proj.bias": "model-00003-of-00004.safetensors",
849
+ "model.vision_tower.vision_tower.encoder.blocks.6.attn.proj.weight": "model-00003-of-00004.safetensors",
850
+ "model.vision_tower.vision_tower.encoder.blocks.6.attn.q_bias": "model-00003-of-00004.safetensors",
851
+ "model.vision_tower.vision_tower.encoder.blocks.6.attn.qkv.weight": "model-00003-of-00004.safetensors",
852
+ "model.vision_tower.vision_tower.encoder.blocks.6.attn.v_bias": "model-00003-of-00004.safetensors",
853
+ "model.vision_tower.vision_tower.encoder.blocks.6.mlp.fc1.bias": "model-00003-of-00004.safetensors",
854
+ "model.vision_tower.vision_tower.encoder.blocks.6.mlp.fc1.weight": "model-00003-of-00004.safetensors",
855
+ "model.vision_tower.vision_tower.encoder.blocks.6.mlp.fc2.bias": "model-00003-of-00004.safetensors",
856
+ "model.vision_tower.vision_tower.encoder.blocks.6.mlp.fc2.weight": "model-00003-of-00004.safetensors",
857
+ "model.vision_tower.vision_tower.encoder.blocks.6.norm1.bias": "model-00003-of-00004.safetensors",
858
+ "model.vision_tower.vision_tower.encoder.blocks.6.norm1.weight": "model-00003-of-00004.safetensors",
859
+ "model.vision_tower.vision_tower.encoder.blocks.6.norm2.bias": "model-00003-of-00004.safetensors",
860
+ "model.vision_tower.vision_tower.encoder.blocks.6.norm2.weight": "model-00003-of-00004.safetensors",
861
+ "model.vision_tower.vision_tower.encoder.blocks.7.attn.proj.bias": "model-00003-of-00004.safetensors",
862
+ "model.vision_tower.vision_tower.encoder.blocks.7.attn.proj.weight": "model-00003-of-00004.safetensors",
863
+ "model.vision_tower.vision_tower.encoder.blocks.7.attn.q_bias": "model-00003-of-00004.safetensors",
864
+ "model.vision_tower.vision_tower.encoder.blocks.7.attn.qkv.weight": "model-00003-of-00004.safetensors",
865
+ "model.vision_tower.vision_tower.encoder.blocks.7.attn.v_bias": "model-00003-of-00004.safetensors",
866
+ "model.vision_tower.vision_tower.encoder.blocks.7.mlp.fc1.bias": "model-00003-of-00004.safetensors",
867
+ "model.vision_tower.vision_tower.encoder.blocks.7.mlp.fc1.weight": "model-00003-of-00004.safetensors",
868
+ "model.vision_tower.vision_tower.encoder.blocks.7.mlp.fc2.bias": "model-00003-of-00004.safetensors",
869
+ "model.vision_tower.vision_tower.encoder.blocks.7.mlp.fc2.weight": "model-00003-of-00004.safetensors",
870
+ "model.vision_tower.vision_tower.encoder.blocks.7.norm1.bias": "model-00003-of-00004.safetensors",
871
+ "model.vision_tower.vision_tower.encoder.blocks.7.norm1.weight": "model-00003-of-00004.safetensors",
872
+ "model.vision_tower.vision_tower.encoder.blocks.7.norm2.bias": "model-00003-of-00004.safetensors",
873
+ "model.vision_tower.vision_tower.encoder.blocks.7.norm2.weight": "model-00003-of-00004.safetensors",
874
+ "model.vision_tower.vision_tower.encoder.blocks.8.attn.proj.bias": "model-00003-of-00004.safetensors",
875
+ "model.vision_tower.vision_tower.encoder.blocks.8.attn.proj.weight": "model-00003-of-00004.safetensors",
876
+ "model.vision_tower.vision_tower.encoder.blocks.8.attn.q_bias": "model-00003-of-00004.safetensors",
877
+ "model.vision_tower.vision_tower.encoder.blocks.8.attn.qkv.weight": "model-00003-of-00004.safetensors",
878
+ "model.vision_tower.vision_tower.encoder.blocks.8.attn.v_bias": "model-00003-of-00004.safetensors",
879
+ "model.vision_tower.vision_tower.encoder.blocks.8.mlp.fc1.bias": "model-00003-of-00004.safetensors",
880
+ "model.vision_tower.vision_tower.encoder.blocks.8.mlp.fc1.weight": "model-00003-of-00004.safetensors",
881
+ "model.vision_tower.vision_tower.encoder.blocks.8.mlp.fc2.bias": "model-00003-of-00004.safetensors",
882
+ "model.vision_tower.vision_tower.encoder.blocks.8.mlp.fc2.weight": "model-00003-of-00004.safetensors",
883
+ "model.vision_tower.vision_tower.encoder.blocks.8.norm1.bias": "model-00003-of-00004.safetensors",
884
+ "model.vision_tower.vision_tower.encoder.blocks.8.norm1.weight": "model-00003-of-00004.safetensors",
885
+ "model.vision_tower.vision_tower.encoder.blocks.8.norm2.bias": "model-00003-of-00004.safetensors",
886
+ "model.vision_tower.vision_tower.encoder.blocks.8.norm2.weight": "model-00003-of-00004.safetensors",
887
+ "model.vision_tower.vision_tower.encoder.blocks.9.attn.proj.bias": "model-00003-of-00004.safetensors",
888
+ "model.vision_tower.vision_tower.encoder.blocks.9.attn.proj.weight": "model-00003-of-00004.safetensors",
889
+ "model.vision_tower.vision_tower.encoder.blocks.9.attn.q_bias": "model-00003-of-00004.safetensors",
890
+ "model.vision_tower.vision_tower.encoder.blocks.9.attn.qkv.weight": "model-00003-of-00004.safetensors",
891
+ "model.vision_tower.vision_tower.encoder.blocks.9.attn.v_bias": "model-00003-of-00004.safetensors",
892
+ "model.vision_tower.vision_tower.encoder.blocks.9.mlp.fc1.bias": "model-00003-of-00004.safetensors",
893
+ "model.vision_tower.vision_tower.encoder.blocks.9.mlp.fc1.weight": "model-00003-of-00004.safetensors",
894
+ "model.vision_tower.vision_tower.encoder.blocks.9.mlp.fc2.bias": "model-00003-of-00004.safetensors",
895
+ "model.vision_tower.vision_tower.encoder.blocks.9.mlp.fc2.weight": "model-00003-of-00004.safetensors",
896
+ "model.vision_tower.vision_tower.encoder.blocks.9.norm1.bias": "model-00003-of-00004.safetensors",
897
+ "model.vision_tower.vision_tower.encoder.blocks.9.norm1.weight": "model-00003-of-00004.safetensors",
898
+ "model.vision_tower.vision_tower.encoder.blocks.9.norm2.bias": "model-00003-of-00004.safetensors",
899
+ "model.vision_tower.vision_tower.encoder.blocks.9.norm2.weight": "model-00003-of-00004.safetensors",
900
+ "model.vision_tower.vision_tower.encoder.patch_embed.proj.bias": "model-00003-of-00004.safetensors",
901
+ "model.vision_tower.vision_tower.encoder.patch_embed.proj.weight": "model-00003-of-00004.safetensors",
902
+ "model.vision_tower.vision_tower.encoder.vision_layernorm.bias": "model-00004-of-00004.safetensors",
903
+ "model.vision_tower.vision_tower.encoder.vision_layernorm.weight": "model-00004-of-00004.safetensors"
904
+ }
905
+ }
modeling_qwen2_flash.py ADDED
@@ -0,0 +1,1611 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # transformers==4.39.2 NOTE
3
+ # Borrows some implementations from https://github.com/Cooperx521/PyramidDrop, thanks!
4
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
5
+ #
6
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
7
+ # and OPT implementations in this library. It has been modified from its
8
+ # original forms to accommodate minor architectural differences compared
9
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
10
+ #
11
+ # Licensed under the Apache License, Version 2.0 (the "License");
12
+ # you may not use this file except in compliance with the License.
13
+ # You may obtain a copy of the License at
14
+ #
15
+ # http://www.apache.org/licenses/LICENSE-2.0
16
+ #
17
+ # Unless required by applicable law or agreed to in writing, software
18
+ # distributed under the License is distributed on an "AS IS" BASIS,
19
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
+ # See the License for the specific language governing permissions and
21
+ # limitations under the License.
22
+ """ PyTorch Qwen2 model."""
23
+ import inspect
24
+ import math
25
+ import warnings
26
+ from typing import List, Optional, Tuple, Union
27
+
28
+ import torch
29
+ import torch.nn.functional as F
30
+ import torch.utils.checkpoint
31
+ from torch import nn
32
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
33
+
34
+ from transformers.activations import ACT2FN
35
+ from transformers.cache_utils import Cache, DynamicCache
36
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa
37
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
38
+ from transformers.modeling_utils import PreTrainedModel
39
+ from transformers.utils import (
40
+ add_start_docstrings,
41
+ add_start_docstrings_to_model_forward,
42
+ is_flash_attn_2_available,
43
+ is_flash_attn_greater_or_equal_2_10,
44
+ logging,
45
+ replace_return_docstrings,
46
+ )
47
+ from transformers.models.qwen2.configuration_qwen2 import Qwen2Config
48
+ from .constants import IGNORE_INDEX
49
+
50
+
51
+ if is_flash_attn_2_available():
52
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
53
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
54
+
55
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
56
+
57
+
58
+ logger = logging.get_logger(__name__)
59
+
60
+
61
+ _CHECKPOINT_FOR_DOC = "Qwen/Qwen2-7B-beta"
62
+ _CONFIG_FOR_DOC = "Qwen2Config"
63
+
64
+ QWEN2_PRETRAINED_MODEL_ARCHIVE_LIST = [
65
+ "Qwen/Qwen2-7B-beta",
66
+ # See all Qwen2 models at https://huggingface.co/models?filter=qwen2
67
+ ]
68
+
69
+
70
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
71
+ def _get_unpad_data(attention_mask):
72
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
73
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
74
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
75
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
76
+ return (
77
+ indices,
78
+ cu_seqlens,
79
+ max_seqlen_in_batch,
80
+ )
81
+
82
+
83
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Qwen2
84
+ class Qwen2RMSNorm(nn.Module):
85
+ def __init__(self, hidden_size, eps=1e-6):
86
+ """
87
+ Qwen2RMSNorm is equivalent to T5LayerNorm
88
+ """
89
+ super().__init__()
90
+ self.weight = nn.Parameter(torch.ones(hidden_size))
91
+ self.variance_epsilon = eps
92
+
93
+ def forward(self, hidden_states):
94
+ input_dtype = hidden_states.dtype
95
+ hidden_states = hidden_states.to(torch.float32)
96
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
97
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
98
+ return self.weight * hidden_states.to(input_dtype)
99
+
100
+
101
+ # Copied from transformers.models.mistral.modeling_mistral.MistralRotaryEmbedding with Mistral->Qwen2
102
+ class Qwen2RotaryEmbedding(nn.Module):
103
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
104
+ super().__init__()
105
+
106
+ self.dim = dim
107
+ self.max_position_embeddings = max_position_embeddings
108
+ self.base = base
109
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
110
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
111
+
112
+ # Build here to make `torch.jit.trace` work.
113
+ self._set_cos_sin_cache(
114
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
115
+ )
116
+
117
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
118
+ self.max_seq_len_cached = seq_len
119
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
120
+
121
+ freqs = torch.outer(t, self.inv_freq)
122
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
123
+ emb = torch.cat((freqs, freqs), dim=-1)
124
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
125
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
126
+
127
+ def forward(self, x, seq_len=None):
128
+ # x: [bs, num_attention_heads, seq_len, head_size]
129
+ if seq_len > self.max_seq_len_cached:
130
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
131
+
132
+ return (
133
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
134
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
135
+ )
136
+
137
+
138
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
139
+ def rotate_half(x):
140
+ """Rotates half the hidden dims of the input."""
141
+ x1 = x[..., : x.shape[-1] // 2]
142
+ x2 = x[..., x.shape[-1] // 2 :]
143
+ return torch.cat((-x2, x1), dim=-1)
144
+
145
+
146
+ # Copied from transformers.models.mistral.modeling_mistral.apply_rotary_pos_emb
147
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
148
+ """Applies Rotary Position Embedding to the query and key tensors.
149
+
150
+ Args:
151
+ q (`torch.Tensor`): The query tensor.
152
+ k (`torch.Tensor`): The key tensor.
153
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
154
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
155
+ position_ids (`torch.Tensor`):
156
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
157
+ used to pass offsetted position ids when working with a KV-cache.
158
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
159
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
160
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
161
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
162
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
163
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
164
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
165
+ Returns:
166
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
167
+ """
168
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
169
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
170
+ q_embed = (q * cos) + (rotate_half(q) * sin)
171
+ k_embed = (k * cos) + (rotate_half(k) * sin)
172
+ return q_embed, k_embed
173
+
174
+
175
+ def apply_rotary_pos_emb2(q_pe, k_pe, cos, sin, position_ids, unsqueeze_dim=1):
176
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
177
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
178
+
179
+ #dim alignment
180
+ step = cos.shape[-1]//q_pe.shape[-1]
181
+ indices = torch.arange(0, cos.size(-1), step, device=cos.device)
182
+ cos = cos[..., indices]
183
+ sin = sin[..., indices]
184
+
185
+ q_embed = (q_pe * cos) + (rotate_half(q_pe) * sin)
186
+ k_embed = (k_pe * cos) + (rotate_half(k_pe) * sin)
187
+ return q_embed, k_embed
188
+
189
+
190
+
191
+ # Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Qwen2
192
+ class Qwen2MLP(nn.Module):
193
+ def __init__(self, config):
194
+ super().__init__()
195
+ self.config = config
196
+ self.hidden_size = config.hidden_size
197
+ self.intermediate_size = config.intermediate_size
198
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
199
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
200
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
201
+ self.act_fn = ACT2FN[config.hidden_act]
202
+
203
+ def forward(self, x):
204
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
205
+
206
+
207
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
208
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
209
+ """
210
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
211
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
212
+ """
213
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
214
+ if n_rep == 1:
215
+ return hidden_states
216
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
217
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
218
+
219
+
220
+ class Qwen2Attention(nn.Module):
221
+ """
222
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
223
+ and "Generating Long Sequences with Sparse Transformers".
224
+ """
225
+
226
+ def __init__(self, config: Qwen2Config, layer_idx: Optional[int] = None):
227
+ super().__init__()
228
+ self.config = config
229
+ self.layer_idx = layer_idx
230
+ if layer_idx is None:
231
+ logger.warning_once(
232
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
233
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
234
+ "when creating this class."
235
+ )
236
+
237
+ self.hidden_size = config.hidden_size
238
+ self.num_heads = config.num_attention_heads
239
+ self.head_dim = self.hidden_size // self.num_heads
240
+ self.num_key_value_heads = config.num_key_value_heads
241
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
242
+ self.max_position_embeddings = config.max_position_embeddings
243
+ self.rope_theta = config.rope_theta
244
+ self.is_causal = True
245
+ self.attention_dropout = config.attention_dropout
246
+
247
+ self.temperature = nn.Parameter(torch.tensor(1.0))
248
+ self.k_nope_scale_factor = nn.Parameter(torch.tensor(1.0))
249
+
250
+ if (self.head_dim * self.num_heads) != self.hidden_size:
251
+ raise ValueError(
252
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
253
+ f" and `num_heads`: {self.num_heads})."
254
+ )
255
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
256
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
257
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
258
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
259
+
260
+ self.rotary_emb = Qwen2RotaryEmbedding(
261
+ self.head_dim,
262
+ max_position_embeddings=self.max_position_embeddings,
263
+ base=self.rope_theta,
264
+ )
265
+
266
+
267
+ #MLA part modeling_deepseek.py
268
+ config.attention_bias=False
269
+
270
+ self.interval = 2
271
+ self.q_rope_dim = self.num_heads * (self.head_dim//self.interval)
272
+ self.q_nope_dim = self.num_heads * self.head_dim - self.q_rope_dim
273
+ self.k_rope_dim = self.num_key_value_heads * (self.head_dim//self.interval)
274
+ self.k_nope_dim = self.num_key_value_heads*self.head_dim - self.k_rope_dim
275
+ self.kv_lora_rank = 128 #4个kv头每个头的latentsize
276
+ self.v_head_dim = self.head_dim
277
+
278
+ self.kv_a_proj_nope = nn.Linear(self.hidden_size, self.num_key_value_heads*self.kv_lora_rank, bias=False)
279
+ self.k_proj_pe = nn.Linear(self.hidden_size,self.k_rope_dim,bias=True)
280
+ self.k_b_proj_nope = nn.Linear(self.num_key_value_heads*self.kv_lora_rank,self.num_key_value_groups*self.k_nope_dim,bias=True)
281
+ self.v_b_proj = nn.Linear(self.num_key_value_heads*self.kv_lora_rank,self.num_key_value_groups*self.num_key_value_heads*self.head_dim,bias=True)
282
+
283
+ def forward(
284
+ self,
285
+ hidden_states: torch.Tensor,
286
+ attention_mask: Optional[torch.Tensor] = None,
287
+ position_ids: Optional[torch.LongTensor] = None,
288
+ past_key_value: Optional[Cache] = None,
289
+ output_attentions: bool = False,
290
+ use_cache: bool = False,
291
+ **kwargs,
292
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
293
+ if "padding_mask" in kwargs:
294
+ warnings.warn(
295
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
296
+ )
297
+ bsz, q_len, _ = hidden_states.size()
298
+
299
+ query_states = self.q_proj(hidden_states)
300
+
301
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
302
+ # key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
303
+ # value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
304
+
305
+ mask = torch.zeros(self.head_dim, dtype=torch.bool)
306
+ mask[::self.interval] = True
307
+ q_pe = query_states[..., mask]
308
+ q_nope = query_states[..., ~mask]
309
+
310
+
311
+ compressed_kv = self.kv_a_proj_nope(hidden_states) # .view(bsz, q_len, self.num_key_value_heads,self.kv_lora_rank ) #no transpose
312
+
313
+ k_pe = self.k_proj_pe(hidden_states).view(bsz, q_len, self.num_key_value_heads, (self.head_dim//self.interval) ).transpose(1, 2)
314
+
315
+ kv_seq_len = k_pe.shape[-2]
316
+ if past_key_value is not None:
317
+ if self.layer_idx is None:
318
+ raise ValueError(
319
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
320
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
321
+ "with a layer index."
322
+ )
323
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
324
+ cos, sin = self.rotary_emb(k_pe, seq_len=kv_seq_len) #k_pe only for device and dtype,no matter shape
325
+
326
+ q_pe, k_pe = apply_rotary_pos_emb2(q_pe, k_pe, cos, sin, position_ids)
327
+
328
+ if past_key_value is not None:
329
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
330
+ compressed_kv = compressed_kv.view(bsz, q_len, self.num_key_value_heads,self.kv_lora_rank).transpose(1, 2)
331
+ k_pe, compressed_kv = past_key_value.update(k_pe, compressed_kv, self.layer_idx, cache_kwargs)
332
+
333
+ compressed_kv = compressed_kv.transpose(1,2).reshape(bsz, kv_seq_len, self.num_key_value_heads*self.kv_lora_rank)
334
+ k_nope = self.k_b_proj_nope(compressed_kv).view(bsz, kv_seq_len, self.num_heads,self.head_dim-(self.head_dim//self.interval) ).transpose(1, 2)
335
+ value_states = self.v_b_proj(compressed_kv).view(bsz, kv_seq_len, self.num_heads,self.head_dim).transpose(1, 2)
336
+ # k_nope = self.k_repeat_nope(self.k_b_proj_nope(compressed_kv)).view(bsz, kv_seq_len,self.num_heads,self.head_dim-(self.head_dim//self.interval) ).transpose(1, 2)
337
+ # value_states = self.v_repeat(self.v_b_proj(compressed_kv)).view(bsz, kv_seq_len, self.num_heads,self.head_dim).transpose(1, 2)
338
+
339
+ k_pe = repeat_kv(k_pe,self.num_key_value_groups)
340
+ # k_nope = repeat_kv(k_nope,self.num_key_value_groups)
341
+ # value_states = repeat_kv(value_states,self.num_key_value_groups)
342
+
343
+ k_nope = k_nope * self.k_nope_scale_factor.to(k_nope.dtype)
344
+
345
+ effective_scale_factor = self.temperature.to(q_pe.dtype) / math.sqrt(self.head_dim)
346
+ attn_weights_pe = torch.matmul(q_pe, k_pe.transpose(2, 3)) * effective_scale_factor
347
+ attn_weights_nope = torch.matmul(q_nope, k_nope.transpose(2, 3)) * effective_scale_factor
348
+ attn_weights = attn_weights_pe + attn_weights_nope
349
+
350
+
351
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
352
+ raise ValueError(
353
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
354
+ f" {attn_weights.size()}"
355
+ )
356
+
357
+ if attention_mask is not None:
358
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
359
+ raise ValueError(
360
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
361
+ )
362
+
363
+ attn_weights = attn_weights + attention_mask
364
+
365
+ # upcast attention to fp32
366
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(value_states.dtype)
367
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
368
+ attn_output = torch.matmul(attn_weights, value_states)
369
+
370
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.v_head_dim):
371
+ raise ValueError(
372
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
373
+ f" {attn_output.size()}"
374
+ )
375
+
376
+ attn_output = attn_output.transpose(1, 2).contiguous()
377
+ # attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
378
+
379
+ attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.v_head_dim)
380
+
381
+ attn_output = self.o_proj(attn_output)
382
+
383
+ if not output_attentions:
384
+ attn_weights = None
385
+
386
+ return attn_output, attn_weights, past_key_value
387
+
388
+ class Qwen2FlashAttention2(Qwen2Attention):
389
+ """
390
+ Qwen2 flash attention module, following Qwen2 attention module. This module inherits from `Qwen2Attention`
391
+ as the weights of the module stays untouched. The only required change would be on the forward pass
392
+ where it needs to correctly call the public API of flash attention and deal with padding tokens
393
+ in case the input contains any of them. Additionally, for sliding window attention, we apply SWA only to the bottom
394
+ config.max_window_layers layers.
395
+ """
396
+
397
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
398
+ def __init__(self, *args, **kwargs):
399
+ super().__init__(*args, **kwargs)
400
+
401
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
402
+ # 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.
403
+ # 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).
404
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
405
+
406
+ def forward(
407
+ self,
408
+ hidden_states: torch.Tensor,
409
+ attention_mask: Optional[torch.Tensor] = None,
410
+ position_ids: Optional[torch.LongTensor] = None,
411
+ past_key_value: Optional[Cache] = None,
412
+ output_attentions: bool = False,
413
+ use_cache: bool = False,
414
+ **kwargs,
415
+ ):
416
+ if "padding_mask" in kwargs:
417
+ warnings.warn(
418
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
419
+ )
420
+
421
+ # overwrite attention_mask with padding_mask
422
+ attention_mask = kwargs.pop("padding_mask")
423
+ bsz, q_len, _ = hidden_states.size()
424
+
425
+ query_states = self.q_proj(hidden_states)
426
+
427
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
428
+ # key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
429
+ # value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
430
+
431
+ mask = torch.zeros(self.head_dim, dtype=torch.bool)
432
+ mask[::self.interval] = True
433
+ q_pe = query_states[..., mask]
434
+ q_nope = query_states[..., ~mask]
435
+
436
+
437
+ compressed_kv = self.kv_a_proj_nope(hidden_states) # .view(bsz, q_len, self.num_key_value_heads,self.kv_lora_rank ) #no transpose
438
+ # print("compressed_kv",compressed_kv.shape)
439
+ # print("q_pe",q_pe.shape)
440
+ # print('hidden_states',hidden_states.shape)
441
+ k_pe = self.k_proj_pe(hidden_states).view(bsz, q_len, self.num_key_value_heads, (self.head_dim//self.interval) ).transpose(1, 2)
442
+
443
+ kv_seq_len = k_pe.shape[-2]
444
+ if past_key_value is not None:
445
+ if self.layer_idx is None:
446
+ raise ValueError(
447
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
448
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
449
+ "with a layer index."
450
+ )
451
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
452
+ cos, sin = self.rotary_emb(k_pe, seq_len=kv_seq_len) #k_pe only for device and dtype,no matter shape
453
+
454
+ q_pe, k_pe = apply_rotary_pos_emb2(q_pe, k_pe, cos, sin, position_ids)
455
+
456
+
457
+ if past_key_value is not None:
458
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
459
+ compressed_kv = compressed_kv.view(bsz, q_len, self.num_key_value_heads,self.kv_lora_rank).transpose(1, 2)
460
+ k_pe, compressed_kv = past_key_value.update(k_pe, compressed_kv, self.layer_idx, cache_kwargs)
461
+
462
+ compressed_kv = compressed_kv.transpose(1,2).reshape(bsz, kv_seq_len, self.num_key_value_heads*self.kv_lora_rank)
463
+ k_nope = self.k_b_proj_nope(compressed_kv).view(bsz, kv_seq_len, self.num_heads,self.head_dim-(self.head_dim//self.interval) ).transpose(1, 2)
464
+ value_states = self.v_b_proj(compressed_kv).view(bsz, kv_seq_len, self.num_heads,self.head_dim).transpose(1, 2)
465
+ # k_nope = self.k_repeat_nope(self.k_b_proj_nope(compressed_kv)).view(bsz, kv_seq_len,self.num_heads,self.head_dim-(self.head_dim//self.interval) ).transpose(1, 2)
466
+ # value_states = self.v_repeat(self.v_b_proj(compressed_kv)).view(bsz, kv_seq_len, self.num_heads,self.head_dim).transpose(1, 2)
467
+
468
+ k_pe = repeat_kv(k_pe,self.num_key_value_groups)
469
+ # k_nope = repeat_kv(k_nope,self.num_key_value_groups)
470
+ # value_states = repeat_kv(value_states,self.num_key_value_groups)
471
+
472
+ k_nope = k_nope * self.k_nope_scale_factor.to(k_nope.dtype)
473
+
474
+ query_states = q_pe.new_empty(bsz, self.num_heads, q_len, self.head_dim)
475
+ query_states[:, :, :, mask] = q_pe
476
+ query_states[:, :, :, ~mask] = q_nope
477
+
478
+ key_states = k_pe.new_empty(bsz, self.num_heads, kv_seq_len, self.head_dim)
479
+ key_states[:, :, :, mask] = k_pe
480
+ key_states[:, :, :, ~mask] = k_nope
481
+
482
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
483
+ # to be able to avoid many of these transpose/reshape/view.
484
+ query_states = query_states.transpose(1, 2)
485
+ key_states = key_states.transpose(1, 2)
486
+ value_states = value_states.transpose(1, 2)
487
+
488
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
489
+
490
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
491
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
492
+ # cast them back in float16 just to be sure everything works as expected.
493
+ input_dtype = query_states.dtype
494
+ if input_dtype == torch.float32:
495
+ if torch.is_autocast_enabled():
496
+ target_dtype = torch.get_autocast_gpu_dtype()
497
+ # Handle the case where the model is quantized
498
+ elif hasattr(self.config, "_pre_quantization_dtype"):
499
+ target_dtype = self.config._pre_quantization_dtype
500
+ else:
501
+ target_dtype = self.q_proj.weight.dtype
502
+
503
+ logger.warning_once(
504
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
505
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
506
+ f" {target_dtype}."
507
+ )
508
+
509
+ query_states = query_states.to(target_dtype)
510
+ key_states = key_states.to(target_dtype)
511
+ value_states = value_states.to(target_dtype)
512
+
513
+
514
+ current_softmax_scale = self.head_dim ** (-0.5)
515
+ effective_softmax_scale = current_softmax_scale * self.temperature.to(query_states.dtype)
516
+
517
+ attn_output = self._flash_attention_forward(
518
+ query_states,
519
+ key_states,
520
+ value_states,
521
+ attention_mask,
522
+ q_len,
523
+ dropout=dropout_rate,
524
+ softmax_scale= effective_softmax_scale.item(), # 将标量张量转换为浮点数
525
+ )
526
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
527
+ attn_output = self.o_proj(attn_output)
528
+
529
+ if not output_attentions:
530
+ attn_weights = None
531
+
532
+ return attn_output, attn_weights, past_key_value
533
+
534
+
535
+ def _flash_attention_forward(
536
+ self,
537
+ query_states,
538
+ key_states,
539
+ value_states,
540
+ attention_mask,
541
+ query_length,
542
+ dropout=0.0,
543
+ softmax_scale=None,
544
+ ):
545
+ """
546
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
547
+ first unpad the input, then computes the attention scores and pad the final attention scores.
548
+
549
+ Args:
550
+ query_states (`torch.Tensor`):
551
+ Input query states to be passed to Flash Attention API
552
+ key_states (`torch.Tensor`):
553
+ Input key states to be passed to Flash Attention API
554
+ value_states (`torch.Tensor`):
555
+ Input value states to be passed to Flash Attention API
556
+ attention_mask (`torch.Tensor`):
557
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
558
+ position of padding tokens and 1 for the position of non-padding tokens.
559
+ dropout (`int`, *optional*):
560
+ Attention dropout
561
+ softmax_scale (`float`, *optional*):
562
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
563
+ """
564
+ if not self._flash_attn_uses_top_left_mask:
565
+ causal = self.is_causal
566
+ else:
567
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in DeepseekV3FlashAttention2 __init__.
568
+ causal = self.is_causal and query_length != 1
569
+
570
+ # Contains at least one padding token in the sequence
571
+ if attention_mask is not None:
572
+ batch_size = query_states.shape[0]
573
+ (
574
+ query_states,
575
+ key_states,
576
+ value_states,
577
+ indices_q,
578
+ cu_seq_lens,
579
+ max_seq_lens,
580
+ ) = self._upad_input(
581
+ query_states, key_states, value_states, attention_mask, query_length
582
+ )
583
+
584
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
585
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
586
+
587
+ attn_output_unpad = flash_attn_varlen_func(
588
+ query_states,
589
+ key_states,
590
+ value_states,
591
+ cu_seqlens_q=cu_seqlens_q,
592
+ cu_seqlens_k=cu_seqlens_k,
593
+ max_seqlen_q=max_seqlen_in_batch_q,
594
+ max_seqlen_k=max_seqlen_in_batch_k,
595
+ dropout_p=dropout,
596
+ softmax_scale=softmax_scale,
597
+ causal=causal,
598
+ )
599
+
600
+ attn_output = pad_input(
601
+ attn_output_unpad, indices_q, batch_size, query_length
602
+ )
603
+ else:
604
+ attn_output = flash_attn_func(
605
+ query_states,
606
+ key_states,
607
+ value_states,
608
+ dropout,
609
+ softmax_scale=softmax_scale,
610
+ causal=causal,
611
+ )
612
+
613
+ return attn_output
614
+
615
+ def _upad_input(
616
+ self, query_layer, key_layer, value_layer, attention_mask, query_length
617
+ ):
618
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
619
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
620
+
621
+ key_layer = index_first_axis(
622
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
623
+ indices_k,
624
+ )
625
+ value_layer = index_first_axis(
626
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
627
+ indices_k,
628
+ )
629
+ if query_length == kv_seq_len:
630
+ query_layer = index_first_axis(
631
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
632
+ indices_k,
633
+ )
634
+ cu_seqlens_q = cu_seqlens_k
635
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
636
+ indices_q = indices_k
637
+ elif query_length == 1:
638
+ max_seqlen_in_batch_q = 1
639
+ cu_seqlens_q = torch.arange(
640
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
641
+ ) # There is a memcpy here, that is very bad.
642
+ indices_q = cu_seqlens_q[:-1]
643
+ query_layer = query_layer.squeeze(1)
644
+ else:
645
+ # The -q_len: slice assumes left padding.
646
+ attention_mask = attention_mask[:, -query_length:]
647
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
648
+ query_layer, attention_mask
649
+ )
650
+
651
+ return (
652
+ query_layer,
653
+ key_layer,
654
+ value_layer,
655
+ indices_q,
656
+ (cu_seqlens_q, cu_seqlens_k),
657
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
658
+ )
659
+
660
+ # Copied from transformers.models.mistral.modeling_mistral.MistralSdpaAttention with Mistral->Qwen2
661
+ class Qwen2SdpaAttention(Qwen2Attention):
662
+ """
663
+ Qwen2 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
664
+ `Qwen2Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
665
+ SDPA API.
666
+ """
667
+
668
+ # Adapted from Qwen2Attention.forward
669
+ def forward(
670
+ self,
671
+ hidden_states: torch.Tensor,
672
+ attention_mask: Optional[torch.Tensor] = None,
673
+ position_ids: Optional[torch.LongTensor] = None,
674
+ past_key_value: Optional[Cache] = None,
675
+ output_attentions: bool = False,
676
+ use_cache: bool = False,
677
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
678
+ if output_attentions:
679
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
680
+ logger.warning_once(
681
+ "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, "
682
+ '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.'
683
+ )
684
+ return super().forward(
685
+ hidden_states=hidden_states,
686
+ attention_mask=attention_mask,
687
+ position_ids=position_ids,
688
+ past_key_value=past_key_value,
689
+ output_attentions=output_attentions,
690
+ use_cache=use_cache,
691
+ )
692
+
693
+ bsz, q_len, _ = hidden_states.size()
694
+
695
+ query_states = self.q_proj(hidden_states)
696
+
697
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
698
+ # key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
699
+ # value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
700
+
701
+ mask = torch.zeros(self.head_dim, dtype=torch.bool)
702
+ mask[::self.interval] = True
703
+ q_pe = query_states[..., mask]
704
+ q_nope = query_states[..., ~mask]
705
+
706
+
707
+ compressed_kv = self.kv_a_proj_nope(hidden_states) # .view(bsz, q_len, self.num_key_value_heads,self.kv_lora_rank ) #no transpose
708
+ # print("compressed_kv",compressed_kv.shape)
709
+ # print("q_pe",q_pe.shape)
710
+ # print('hidden_states',hidden_states.shape)
711
+ k_pe = self.k_proj_pe(hidden_states).view(bsz, q_len, self.num_key_value_heads, (self.head_dim//self.interval) ).transpose(1, 2)
712
+
713
+ kv_seq_len = k_pe.shape[-2]#就是q_len了
714
+ if past_key_value is not None:
715
+ if self.layer_idx is None:
716
+ raise ValueError(
717
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
718
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
719
+ "with a layer index."
720
+ )
721
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
722
+ cos, sin = self.rotary_emb(k_pe, seq_len=kv_seq_len) #k_pe only for device and dtype,no matter shape
723
+
724
+ q_pe, k_pe = apply_rotary_pos_emb2(q_pe, k_pe, cos, sin, position_ids)
725
+
726
+ if past_key_value is not None:
727
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
728
+ compressed_kv = compressed_kv.view(bsz, q_len, self.num_key_value_heads,self.kv_lora_rank).transpose(1, 2)
729
+ k_pe, compressed_kv = past_key_value.update(k_pe, compressed_kv, self.layer_idx, cache_kwargs)
730
+
731
+ compressed_kv = compressed_kv.transpose(1,2).reshape(bsz, kv_seq_len, self.num_key_value_heads*self.kv_lora_rank)
732
+ k_nope = self.k_b_proj_nope(compressed_kv).view(bsz, kv_seq_len, self.num_heads,self.head_dim-(self.head_dim//self.interval) ).transpose(1, 2)
733
+ value_states = self.v_b_proj(compressed_kv).view(bsz, kv_seq_len, self.num_heads,self.head_dim).transpose(1, 2)
734
+ # k_nope = self.k_repeat_nope(self.k_b_proj_nope(compressed_kv)).view(bsz, kv_seq_len,self.num_heads,self.head_dim-(self.head_dim//self.interval) ).transpose(1, 2)
735
+ # value_states = self.v_repeat(self.v_b_proj(compressed_kv)).view(bsz, kv_seq_len, self.num_heads,self.head_dim).transpose(1, 2)
736
+
737
+ k_pe = repeat_kv(k_pe,self.num_key_value_groups)
738
+ # k_nope = repeat_kv(k_nope,self.num_key_value_groups)
739
+ # value_states = repeat_kv(value_states,self.num_key_value_groups)
740
+
741
+ k_nope = k_nope * self.k_nope_scale_factor.to(k_nope.dtype)
742
+
743
+ query_states = q_pe.new_empty(bsz, self.num_heads, q_len, self.head_dim)
744
+ query_states[:, :, :, mask] = q_pe
745
+ query_states[:, :, :, ~mask] = q_nope
746
+
747
+ key_states = k_pe.new_empty(bsz, self.num_heads, kv_seq_len, self.head_dim)
748
+ key_states[:, :, :, mask] = k_pe
749
+ key_states[:, :, :, ~mask] = k_nope
750
+
751
+ if attention_mask is not None:
752
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
753
+ raise ValueError(
754
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
755
+ )
756
+
757
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
758
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
759
+ if query_states.device.type == "cuda" and attention_mask is not None:
760
+ query_states = query_states.contiguous()
761
+ key_states = key_states.contiguous()
762
+ value_states = value_states.contiguous()
763
+
764
+ sdpa_effective_scale = (self.head_dim ** (-0.5)) * self.temperature.to(query_states.dtype)
765
+
766
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
767
+ query_states,
768
+ key_states,
769
+ value_states,
770
+ attn_mask=attention_mask,
771
+ dropout_p=self.attention_dropout if self.training else 0.0,
772
+ # 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.
773
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
774
+ scale=sdpa_effective_scale.item(), # 将标量张量转换为浮点数
775
+ )
776
+
777
+ attn_output = attn_output.transpose(1, 2).contiguous()
778
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
779
+
780
+ attn_output = self.o_proj(attn_output)
781
+
782
+ return attn_output, None, past_key_value
783
+
784
+
785
+
786
+ QWEN2_ATTENTION_CLASSES = {
787
+ "eager": Qwen2Attention,
788
+ "flash_attention_2": Qwen2FlashAttention2,
789
+ "sdpa": Qwen2SdpaAttention,
790
+ }
791
+
792
+
793
+ class Qwen2DecoderLayer(nn.Module):
794
+ def __init__(self, config: Qwen2Config, layer_idx: int):
795
+ super().__init__()
796
+ self.hidden_size = config.hidden_size
797
+
798
+ if config.use_sliding_window and config._attn_implementation != "flash_attention_2":
799
+ logger.warning_once(
800
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
801
+ "unexpected results may be encountered."
802
+ )
803
+ self.self_attn = QWEN2_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
804
+
805
+ self.mlp = Qwen2MLP(config)
806
+ self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
807
+ self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
808
+
809
+ def forward(
810
+ self,
811
+ hidden_states: torch.Tensor,
812
+ attention_mask: Optional[torch.Tensor] = None,
813
+ position_ids: Optional[torch.LongTensor] = None,
814
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
815
+ output_attentions: Optional[bool] = False,
816
+ use_cache: Optional[bool] = False,
817
+ **kwargs,
818
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
819
+ if "padding_mask" in kwargs:
820
+ warnings.warn(
821
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. "
822
+ "Please make sure use `attention_mask` instead.`"
823
+ )
824
+ """
825
+ Args:
826
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
827
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
828
+ `(batch, sequence_length)` where padding elements are indicated by 0.
829
+ output_attentions (`bool`, *optional*):
830
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
831
+ returned tensors for more detail.
832
+ use_cache (`bool`, *optional*):
833
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
834
+ (see `past_key_values`).
835
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
836
+ """
837
+
838
+ residual = hidden_states
839
+
840
+ hidden_states = self.input_layernorm(hidden_states)
841
+
842
+ # Self Attention
843
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
844
+ hidden_states=hidden_states,
845
+ attention_mask=attention_mask,
846
+ position_ids=position_ids,
847
+ past_key_value=past_key_value,
848
+ output_attentions=output_attentions,
849
+ use_cache=use_cache,
850
+ )
851
+ hidden_states = residual + hidden_states
852
+
853
+ # Fully Connected
854
+ residual = hidden_states
855
+ hidden_states = self.post_attention_layernorm(hidden_states)
856
+ hidden_states = self.mlp(hidden_states)
857
+ hidden_states = residual + hidden_states
858
+
859
+ outputs = (hidden_states,)
860
+
861
+ if output_attentions:
862
+ outputs += (self_attn_weights,)
863
+
864
+ if use_cache:
865
+ outputs += (present_key_value,)
866
+
867
+ return outputs
868
+
869
+
870
+ QWEN2_START_DOCSTRING = r"""
871
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
872
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
873
+ etc.)
874
+
875
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
876
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
877
+ and behavior.
878
+
879
+ Parameters:
880
+ config ([`Qwen2Config`]):
881
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
882
+ load the weights associated with the model, only the configuration. Check out the
883
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
884
+ """
885
+
886
+
887
+ @add_start_docstrings(
888
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
889
+ QWEN2_START_DOCSTRING,
890
+ )
891
+ class Qwen2PreTrainedModel(PreTrainedModel):
892
+ config_class = Qwen2Config
893
+ base_model_prefix = "model"
894
+ supports_gradient_checkpointing = True
895
+ _no_split_modules = ["Qwen2DecoderLayer"]
896
+ _skip_keys_device_placement = "past_key_values"
897
+ _supports_flash_attn_2 = True
898
+ _supports_sdpa = True
899
+ _supports_cache_class = True
900
+
901
+ def _init_weights(self, module):
902
+ std = self.config.initializer_range
903
+ if isinstance(module, nn.Linear):
904
+ module.weight.data.normal_(mean=0.0, std=std)
905
+ if module.bias is not None:
906
+ module.bias.data.zero_()
907
+ elif isinstance(module, nn.Embedding):
908
+ module.weight.data.normal_(mean=0.0, std=std)
909
+ if module.padding_idx is not None:
910
+ module.weight.data[module.padding_idx].zero_()
911
+
912
+
913
+ QWEN2_INPUTS_DOCSTRING = r"""
914
+ Args:
915
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
916
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
917
+ it.
918
+
919
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
920
+ [`PreTrainedTokenizer.__call__`] for details.
921
+
922
+ [What are input IDs?](../glossary#input-ids)
923
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
924
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
925
+
926
+ - 1 for tokens that are **not masked**,
927
+ - 0 for tokens that are **masked**.
928
+
929
+ [What are attention masks?](../glossary#attention-mask)
930
+
931
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
932
+ [`PreTrainedTokenizer.__call__`] for details.
933
+
934
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
935
+ `past_key_values`).
936
+
937
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
938
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
939
+ information on the default strategy.
940
+
941
+ - 1 indicates the head is **not masked**,
942
+ - 0 indicates the head is **masked**.
943
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
944
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
945
+ config.n_positions - 1]`.
946
+
947
+ [What are position IDs?](../glossary#position-ids)
948
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
949
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
950
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
951
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
952
+
953
+ Two formats are allowed:
954
+ - a [`~cache_utils.Cache`] instance;
955
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
956
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
957
+ cache format.
958
+
959
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
960
+ legacy cache format will be returned.
961
+
962
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
963
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
964
+ of shape `(batch_size, sequence_length)`.
965
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
966
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
967
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
968
+ model's internal embedding lookup matrix.
969
+ use_cache (`bool`, *optional*):
970
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
971
+ `past_key_values`).
972
+ output_attentions (`bool`, *optional*):
973
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
974
+ tensors for more detail.
975
+ output_hidden_states (`bool`, *optional*):
976
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
977
+ more detail.
978
+ return_dict (`bool`, *optional*):
979
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
980
+ """
981
+
982
+
983
+ @add_start_docstrings(
984
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
985
+ QWEN2_START_DOCSTRING,
986
+ )
987
+ class Qwen2Model_Flash(Qwen2PreTrainedModel):
988
+ """
989
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]
990
+
991
+ Args:
992
+ config: Qwen2Config
993
+ """
994
+
995
+ def __init__(self, config: Qwen2Config):
996
+ super().__init__(config)
997
+ self.padding_idx = config.pad_token_id
998
+ self.vocab_size = config.vocab_size
999
+
1000
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1001
+ self.layers = nn.ModuleList(
1002
+ [Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1003
+ )
1004
+ self._attn_implementation = config._attn_implementation
1005
+ self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1006
+
1007
+ self.gradient_checkpointing = False
1008
+
1009
+ # Initialize weights and apply final processing
1010
+ self.post_init()
1011
+
1012
+ def get_input_embeddings(self):
1013
+ return self.embed_tokens
1014
+
1015
+ def set_input_embeddings(self, value):
1016
+ self.embed_tokens = value
1017
+
1018
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1019
+ def forward(
1020
+ self,
1021
+ input_ids: torch.LongTensor = None,
1022
+ attention_mask: Optional[torch.Tensor] = None,
1023
+ position_ids: Optional[torch.LongTensor] = None,
1024
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1025
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1026
+ use_cache: Optional[bool] = None,
1027
+ output_attentions: Optional[bool] = None,
1028
+ output_hidden_states: Optional[bool] = None,
1029
+ return_dict: Optional[bool] = None,
1030
+ labels: Optional[torch.Tensor] = None,
1031
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1032
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1033
+ output_hidden_states = (
1034
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1035
+ )
1036
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1037
+
1038
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1039
+
1040
+ # retrieve input_ids and inputs_embeds
1041
+ if input_ids is not None and inputs_embeds is not None:
1042
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
1043
+ elif input_ids is not None:
1044
+ batch_size, seq_length = input_ids.shape
1045
+ elif inputs_embeds is not None:
1046
+ batch_size, seq_length, _ = inputs_embeds.shape
1047
+ else:
1048
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
1049
+
1050
+ if self.gradient_checkpointing and self.training:
1051
+ if use_cache:
1052
+ logger.warning_once(
1053
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1054
+ )
1055
+ use_cache = False
1056
+
1057
+ past_key_values_length = 0
1058
+
1059
+ if use_cache:
1060
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1061
+ if use_legacy_cache:
1062
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1063
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1064
+
1065
+ if position_ids is None:
1066
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1067
+ position_ids = torch.arange(
1068
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1069
+ )
1070
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1071
+ else:
1072
+ position_ids = position_ids.view(-1, seq_length).long()
1073
+
1074
+ if inputs_embeds is None:
1075
+ inputs_embeds = self.embed_tokens(input_ids)
1076
+
1077
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
1078
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1079
+ if is_padding_right:
1080
+ raise ValueError(
1081
+ "You are attempting to perform batched generation with padding_side='right'"
1082
+ " this may lead to unexpected behaviour for Flash Attention version of Qwen2. Make sure to "
1083
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1084
+ )
1085
+
1086
+ if self._attn_implementation == "flash_attention_2":
1087
+ # 2d mask is passed through the layers
1088
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1089
+ elif self._attn_implementation == "sdpa" and not output_attentions:
1090
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1091
+ # the manual implementation that requires a 4D causal mask in all cases.
1092
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1093
+ attention_mask,
1094
+ (batch_size, seq_length),
1095
+ inputs_embeds,
1096
+ past_key_values_length,
1097
+ )
1098
+ else:
1099
+ # 4d mask is passed through the layers
1100
+ attention_mask = _prepare_4d_causal_attention_mask(
1101
+ attention_mask,
1102
+ (batch_size, seq_length),
1103
+ inputs_embeds,
1104
+ past_key_values_length,
1105
+ sliding_window=self.config.sliding_window,
1106
+ )
1107
+
1108
+ hidden_states = inputs_embeds
1109
+
1110
+ # decoder layers
1111
+ all_hidden_states = () if output_hidden_states else None
1112
+ all_self_attns = () if output_attentions else None
1113
+ next_decoder_cache = None
1114
+
1115
+ for layer_idx, decoder_layer in enumerate(self.layers):
1116
+ if output_hidden_states:
1117
+ all_hidden_states += (hidden_states,)
1118
+
1119
+ if self.gradient_checkpointing and self.training:
1120
+ layer_outputs = self._gradient_checkpointing_func(
1121
+ decoder_layer.__call__,
1122
+ hidden_states,
1123
+ attention_mask,
1124
+ position_ids,
1125
+ past_key_values,
1126
+ output_attentions,
1127
+ use_cache,
1128
+ )
1129
+ else:
1130
+ layer_outputs = decoder_layer(
1131
+ hidden_states,
1132
+ attention_mask=attention_mask,
1133
+ position_ids=position_ids,
1134
+ past_key_value=past_key_values,
1135
+ output_attentions=output_attentions,
1136
+ use_cache=use_cache,
1137
+ )
1138
+
1139
+ hidden_states = layer_outputs[0]
1140
+
1141
+ if use_cache:
1142
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1143
+
1144
+ if output_attentions:
1145
+ all_self_attns += (layer_outputs[1],)
1146
+
1147
+ ###### copy from pdrop #########
1148
+ # rank & drop after specific layer
1149
+ # only drop in prefill stage when inference
1150
+ rank_layer = layer_idx+1
1151
+ if rank_layer in self.llm_compress_layer_list:
1152
+ if hidden_states.shape[1] != 1: # prefill stage or training
1153
+ stage = self.llm_compress_layer_list.index(rank_layer) # determine current stage
1154
+ (
1155
+ position_ids,
1156
+ attention_mask,
1157
+ hidden_states,
1158
+ labels # update labels and return
1159
+ ) = self.video_level_compress(
1160
+ cur_num = stage,
1161
+ rank_layer = rank_layer,
1162
+ features = hidden_states,
1163
+ position_ids=position_ids,
1164
+ attention_mask=attention_mask,
1165
+ labels = labels
1166
+ )
1167
+
1168
+ # process attention_mask again after updating
1169
+ if self._attn_implementation == "flash_attention_2":
1170
+ # 2d mask is passed through the layers
1171
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1172
+ elif self._attn_implementation == "sdpa" and not output_attentions:
1173
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1174
+ # the manual implementation that requires a 4D causal mask in all cases.
1175
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1176
+ attention_mask,
1177
+ (batch_size, hidden_states.shape[1]),
1178
+ hidden_states,
1179
+ past_key_values_length,
1180
+ )
1181
+ else:
1182
+ # 4d mask is passed through the layers
1183
+ attention_mask = _prepare_4d_causal_attention_mask(
1184
+ attention_mask,
1185
+ (batch_size, hidden_states.shape[1]),
1186
+ hidden_states,
1187
+ past_key_values_length,
1188
+ sliding_window=self.config.sliding_window,
1189
+ )
1190
+
1191
+ else:
1192
+ # update position_ids in decoding stage when inference
1193
+ stage = self.llm_compress_layer_list.index(rank_layer) # determine current stage
1194
+ cur_visual_length = [int(cur_image_token * self.llm_image_token_ratio_list[stage]) for cur_image_token in self.num_image_token_lens]
1195
+ next_visual_length = [int(cur_image_token * self.llm_image_token_ratio_list[stage + 1]) for cur_image_token in self.num_image_token_lens]
1196
+ new_position_ids = []
1197
+ for idx, cur_position_ids in enumerate(position_ids):
1198
+ cur_position_ids = cur_position_ids - (cur_visual_length[idx] - next_visual_length[idx])
1199
+ new_position_ids.append(cur_position_ids)
1200
+ assert idx == 0, idx
1201
+ position_ids = torch.tensor(new_position_ids, dtype=torch.long).unsqueeze(0)
1202
+
1203
+ #################
1204
+
1205
+ hidden_states = self.norm(hidden_states)
1206
+
1207
+ # add hidden states from the last decoder layer
1208
+ if output_hidden_states:
1209
+ all_hidden_states += (hidden_states,)
1210
+
1211
+ next_cache = None
1212
+ if use_cache:
1213
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1214
+
1215
+ if not return_dict:
1216
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None), labels
1217
+ return BaseModelOutputWithPast(
1218
+ last_hidden_state=hidden_states,
1219
+ past_key_values=next_cache,
1220
+ hidden_states=all_hidden_states,
1221
+ attentions=all_self_attns,
1222
+ ), labels
1223
+
1224
+
1225
+ # implementation of pdrop
1226
+ def video_level_compress(
1227
+ self, cur_num, rank_layer, features ,
1228
+ position_ids, attention_mask, labels
1229
+ ):
1230
+
1231
+ if self.llm_compress_type == 'uniform0_attention':
1232
+ if cur_num == 0:
1233
+ llm_compress_type = 'uniform'
1234
+ else:
1235
+ llm_compress_type = 'attention'
1236
+ else:
1237
+ llm_compress_type = self.llm_compress_type
1238
+
1239
+ _labels = labels
1240
+ _position_ids = position_ids
1241
+ _attention_mask = attention_mask
1242
+
1243
+ if position_ids is None:
1244
+ position_ids = torch.arange(0, features.shape[1], dtype=torch.long, device=features.device).unsqueeze(0)
1245
+
1246
+ if getattr(self.config, 'tokenizer_padding_side', 'right') == "right":
1247
+
1248
+ batch_size = features.shape[0]
1249
+ image_tokens = [int(cur_image_token * self.llm_image_token_ratio_list[cur_num]) for cur_image_token in self.num_image_token_lens]
1250
+ keep_length = [int(cur_image_token * self.llm_image_token_ratio_list[cur_num + 1]) for cur_image_token in self.num_image_token_lens]
1251
+
1252
+ features_list = []
1253
+ attention_mask_list = []
1254
+ labels_list = []
1255
+
1256
+ if attention_mask is None:
1257
+ attention_mask = torch.ones((batch_size,features.shape[1]), dtype=torch.bool, device=features.device)
1258
+ else:
1259
+ attention_mask = attention_mask.bool()
1260
+ if labels is None:
1261
+ labels = torch.full((batch_size,features.shape[1]), IGNORE_INDEX, device=features.device)
1262
+
1263
+
1264
+ if 'attention' in llm_compress_type:
1265
+ # obtain query_states and key_states to calculate attention map
1266
+ hidden_states= features.clone().detach()
1267
+
1268
+ self_attn = self.layers[rank_layer].self_attn
1269
+ hidden_states = self.layers[rank_layer].input_layernorm(hidden_states)
1270
+
1271
+ num_heads = self_attn.num_heads
1272
+ num_key_value_heads = self_attn.num_key_value_heads
1273
+ head_dim = self_attn.head_dim
1274
+
1275
+ bsz, q_len, _ = hidden_states.size()
1276
+
1277
+ query_states = self_attn.q_proj(hidden_states)
1278
+ key_states = self_attn.k_proj(hidden_states)
1279
+ value_states = self_attn.v_proj(hidden_states)
1280
+
1281
+ query_states = query_states.view(bsz, q_len, num_heads, head_dim).transpose(1, 2)
1282
+ key_states = key_states.view(bsz, q_len, num_key_value_heads, head_dim).transpose(1, 2)
1283
+ value_states = value_states.view(bsz, q_len, num_key_value_heads, head_dim).transpose(1, 2)
1284
+
1285
+ kv_seq_len = key_states.shape[-2]
1286
+ cos, sin = self_attn.rotary_emb(value_states, seq_len=kv_seq_len)
1287
+
1288
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
1289
+ key_states = repeat_kv(key_states, self_attn.num_key_value_groups)
1290
+
1291
+ # attention_mask
1292
+ eager_attention_mask = _prepare_4d_causal_attention_mask(
1293
+ attention_mask, (batch_size, q_len), hidden_states, past_key_values_length=0
1294
+ ).to(device=query_states.device)
1295
+
1296
+ # take valid features
1297
+ features = [cur_features[cur_attention_mask] for cur_features, cur_attention_mask in zip(features, attention_mask)]
1298
+ labels = [cur_labels[cur_attention_mask] for cur_labels, cur_attention_mask in zip(labels, attention_mask)]
1299
+ attention_mask = [cur_attention_mask[cur_attention_mask] for cur_attention_mask, cur_attention_mask in zip(attention_mask, attention_mask)]
1300
+
1301
+ # rank & drop
1302
+ for i in range(batch_size):
1303
+ image_index = self.first_image_token_position[i]
1304
+ if image_index == -1:
1305
+ cur_input_embeds = features[i]
1306
+ features_list.append(cur_input_embeds)
1307
+ attention_mask_list.append(attention_mask[i])
1308
+ labels_list.append(labels[i])
1309
+ continue
1310
+
1311
+ if 'attention' in llm_compress_type:
1312
+
1313
+ # obtain current states
1314
+ cur_key_states = key_states[i]
1315
+ cur_query_states = query_states[i]
1316
+ cur_eager_attention_mask = eager_attention_mask[i]
1317
+
1318
+ # choose last instruction token as query
1319
+ if self.training:
1320
+ answer_index = torch.where(labels[i] != -100)[0].tolist()
1321
+ index_before_answer = []
1322
+ for index in answer_index:
1323
+ if labels[i][index-1] == -100:
1324
+ index_before_answer.append(index-1)
1325
+ if index_before_answer == []:
1326
+ cur_input_embeds = features[i]
1327
+ features_list.append(cur_input_embeds)
1328
+ attention_mask_list.append(attention_mask[i])
1329
+ labels_list.append(labels[i])
1330
+ continue
1331
+
1332
+ index_before_answer=torch.tensor(index_before_answer,device=labels[0].device)
1333
+ text_query_states = cur_query_states[:,index_before_answer,:]
1334
+ text_eager_attention_mask = cur_eager_attention_mask[:,index_before_answer,:]
1335
+
1336
+ else:
1337
+ prompt_total_len = self.text_prompt_lens[i] + image_tokens[i]
1338
+ text_query_states = cur_query_states[:,prompt_total_len-1,:].unsqueeze(1)
1339
+ text_eager_attention_mask = cur_eager_attention_mask[:,prompt_total_len-1,:].unsqueeze(1)
1340
+
1341
+ # calculate attention map
1342
+ attn_weights = torch.matmul(text_query_states, cur_key_states.transpose(1, 2)) / math.sqrt(head_dim) #(num_head, text_token,seq_len)
1343
+ attn_weights = attn_weights + text_eager_attention_mask
1344
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype) #(num_head, text_token,seq_len)
1345
+
1346
+ attention_avg_head = torch.mean(attn_weights, dim=0) # ave across heads
1347
+ attention_avg_head = attention_avg_head[:,image_index:image_index+image_tokens[i]] # select image token as keys
1348
+ attention_avg_text = torch.mean(attention_avg_head, dim=0) # (576)
1349
+
1350
+ if llm_compress_type == 'attention':
1351
+ top_rank_index = attention_avg_text.topk(keep_length[i]).indices
1352
+ else:
1353
+ raise NotImplementedError(llm_compress_type)
1354
+
1355
+ elif llm_compress_type == 'uniform':
1356
+ top_rank_index = torch.linspace(0, image_tokens[i]-1, keep_length[i], dtype=torch.long)
1357
+ else:
1358
+ raise NotImplementedError(llm_compress_type)
1359
+
1360
+ top_rank_index = top_rank_index + image_index
1361
+ top_rank_index= top_rank_index.sort().values
1362
+
1363
+ start_index = image_index + image_tokens[i]
1364
+ new_input_embeds = torch.cat([features[i][ :image_index, :] ,features[i][ top_rank_index, :], features[i][start_index:, :]], dim=0)
1365
+
1366
+ new_labels = torch.cat([labels[i][ :image_index],labels[i][ top_rank_index], labels[i][start_index:]], dim=0)
1367
+ new_attention_mask = torch.cat([attention_mask[i][:image_index], attention_mask[i][top_rank_index], attention_mask[i][start_index:]], dim=0)
1368
+
1369
+ features_list.append(new_input_embeds)
1370
+ attention_mask_list.append(new_attention_mask)
1371
+ labels_list.append(new_labels)
1372
+
1373
+ # Truncate sequences to max length as image embeddings can make the sequence longer
1374
+ tokenizer_model_max_length = getattr(self.config, 'tokenizer_model_max_length', None)
1375
+ if tokenizer_model_max_length is not None:
1376
+ new_input_embeds = [x[:tokenizer_model_max_length] for x in features_list]
1377
+ new_attention_mask = [x[:tokenizer_model_max_length] for x in attention_mask_list]
1378
+ new_labels = [x[:tokenizer_model_max_length] for x in labels_list]
1379
+
1380
+ max_len = max(x.shape[0] for x in new_input_embeds)
1381
+
1382
+ # padding the sequences to form batch
1383
+ embeds_padded=[]
1384
+ labels_paded=[]
1385
+ attention_mask_padded=[]
1386
+ position_ids = torch.zeros((batch_size, max_len), dtype=position_ids.dtype, device=position_ids.device)
1387
+ for i, (cur_new_embed, cur_new_labels) in enumerate(zip(new_input_embeds, new_labels)):
1388
+ cur_len_emb=cur_new_embed.shape[0]
1389
+ dif=max_len - cur_len_emb # padding to longest seq
1390
+
1391
+ cur_new_embed = torch.cat([cur_new_embed,torch.zeros((dif, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device)],dim=0)
1392
+ cur_new_labels = torch.cat([cur_new_labels,torch.full((dif,),IGNORE_INDEX,dtype=cur_new_labels.dtype, device=cur_new_labels.device)],dim=0)
1393
+ cur_attention_mask = new_attention_mask[i]
1394
+ cur_attention_mask = torch.cat([cur_attention_mask,torch.full((dif,),False, dtype=cur_attention_mask.dtype, device=cur_attention_mask.device)],dim=0)
1395
+
1396
+ embeds_padded.append(cur_new_embed)
1397
+ labels_paded.append(cur_new_labels)
1398
+ attention_mask_padded.append(cur_attention_mask)
1399
+
1400
+ cur_len = new_attention_mask[i].sum().item()
1401
+ position_ids[i, :cur_len] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
1402
+
1403
+
1404
+ new_input_embeds = torch.stack(embeds_padded,dim=0)
1405
+ new_input_embeds = new_input_embeds.to(features[0].dtype)
1406
+
1407
+ new_attention_mask = torch.stack(attention_mask_padded,dim=0)
1408
+ new_labels = torch.stack(labels_paded,dim=0)
1409
+
1410
+ if _position_ids is None:
1411
+ position_ids = None
1412
+ if _labels is None:
1413
+ new_labels = None
1414
+
1415
+ if _attention_mask is None:
1416
+ new_attention_mask = None
1417
+ else:
1418
+ new_attention_mask = new_attention_mask.to(dtype=_attention_mask.dtype)
1419
+
1420
+ return position_ids, new_attention_mask, new_input_embeds, new_labels
1421
+
1422
+ else:
1423
+ raise ValueError(f"Unexpected tokenizer_padding_side: {self.config.tokenizer_padding_side}")
1424
+
1425
+
1426
+ class Qwen2ForCausalLM_Flash(Qwen2PreTrainedModel):
1427
+ _tied_weights_keys = ["lm_head.weight"]
1428
+
1429
+ def __init__(self, config):
1430
+ super().__init__(config)
1431
+ self.model = Qwen2Model_Flash(config)
1432
+ self.vocab_size = config.vocab_size
1433
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1434
+
1435
+ # Initialize weights and apply final processing
1436
+ self.post_init()
1437
+
1438
+ def get_input_embeddings(self):
1439
+ return self.model.embed_tokens
1440
+
1441
+ def set_input_embeddings(self, value):
1442
+ self.model.embed_tokens = value
1443
+
1444
+ def get_output_embeddings(self):
1445
+ return self.lm_head
1446
+
1447
+ def set_output_embeddings(self, new_embeddings):
1448
+ self.lm_head = new_embeddings
1449
+
1450
+ def set_decoder(self, decoder):
1451
+ self.model = decoder
1452
+
1453
+ def get_decoder(self):
1454
+ return self.model
1455
+
1456
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1457
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1458
+ def forward(
1459
+ self,
1460
+ input_ids: torch.LongTensor = None,
1461
+ attention_mask: Optional[torch.Tensor] = None,
1462
+ position_ids: Optional[torch.LongTensor] = None,
1463
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1464
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1465
+ labels: Optional[torch.LongTensor] = None,
1466
+ use_cache: Optional[bool] = None,
1467
+ output_attentions: Optional[bool] = None,
1468
+ output_hidden_states: Optional[bool] = None,
1469
+ return_dict: Optional[bool] = None,
1470
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1471
+ r"""
1472
+ Args:
1473
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1474
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1475
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1476
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1477
+
1478
+ Returns:
1479
+
1480
+ Example:
1481
+
1482
+ ```python
1483
+ >>> from transformers import AutoTokenizer, Qwen2ForCausalLM
1484
+
1485
+ >>> model = Qwen2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1486
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1487
+
1488
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1489
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1490
+
1491
+ >>> # Generate
1492
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1493
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1494
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1495
+ ```"""
1496
+
1497
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1498
+ output_hidden_states = (
1499
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1500
+ )
1501
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1502
+
1503
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1504
+ outputs, labels = self.model(
1505
+ input_ids=input_ids,
1506
+ attention_mask=attention_mask,
1507
+ position_ids=position_ids,
1508
+ past_key_values=past_key_values,
1509
+ inputs_embeds=inputs_embeds,
1510
+ use_cache=use_cache,
1511
+ output_attentions=output_attentions,
1512
+ output_hidden_states=output_hidden_states,
1513
+ return_dict=return_dict,
1514
+ labels=labels
1515
+ )
1516
+
1517
+ hidden_states = outputs[0]
1518
+ logits = self.lm_head(hidden_states)
1519
+ logits = logits.float()
1520
+
1521
+ loss = None
1522
+ if labels is not None:
1523
+ # Shift so that tokens < n predict n
1524
+ shift_logits = logits[..., :-1, :].contiguous()
1525
+ shift_labels = labels[..., 1:].contiguous()
1526
+ # Flatten the tokens
1527
+ loss_fct = CrossEntropyLoss()
1528
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1529
+ shift_labels = shift_labels.view(-1)
1530
+ # Enable model parallelism
1531
+ shift_labels = shift_labels.to(shift_logits.device)
1532
+ loss = loss_fct(shift_logits, shift_labels)
1533
+
1534
+ if not return_dict:
1535
+ output = (logits,) + outputs[1:]
1536
+ return (loss,) + output if loss is not None else output
1537
+
1538
+ return CausalLMOutputWithPast(
1539
+ loss=loss,
1540
+ logits=logits,
1541
+ past_key_values=outputs.past_key_values,
1542
+ hidden_states=outputs.hidden_states,
1543
+ attentions=outputs.attentions,
1544
+ )
1545
+
1546
+ def prepare_inputs_for_generation(
1547
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1548
+ ):
1549
+ # Omit tokens covered by past_key_values
1550
+ if past_key_values is not None:
1551
+ if isinstance(past_key_values, Cache):
1552
+ cache_length = past_key_values.get_seq_length()
1553
+ past_length = past_key_values.seen_tokens
1554
+ max_cache_length = past_key_values.get_max_length()
1555
+ else:
1556
+ cache_length = past_length = past_key_values[0][0].shape[2]
1557
+ max_cache_length = None
1558
+
1559
+ # Keep only the unprocessed tokens:
1560
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1561
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1562
+ # input)
1563
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1564
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1565
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1566
+ # input_ids based on the past_length.
1567
+ elif past_length < input_ids.shape[1]:
1568
+ input_ids = input_ids[:, past_length:]
1569
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1570
+
1571
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1572
+ if (
1573
+ max_cache_length is not None
1574
+ and attention_mask is not None
1575
+ and cache_length + input_ids.shape[1] > max_cache_length
1576
+ ):
1577
+ attention_mask = attention_mask[:, -max_cache_length:]
1578
+
1579
+ position_ids = kwargs.get("position_ids", None)
1580
+ if attention_mask is not None and position_ids is None:
1581
+ # create position_ids on the fly for batch generation
1582
+ position_ids = attention_mask.long().cumsum(-1) - 1
1583
+ position_ids.masked_fill_(attention_mask == 0, 1)
1584
+ if past_key_values:
1585
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1586
+
1587
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1588
+ if inputs_embeds is not None and past_key_values is None:
1589
+ model_inputs = {"inputs_embeds": inputs_embeds}
1590
+ else:
1591
+ model_inputs = {"input_ids": input_ids}
1592
+
1593
+ model_inputs.update(
1594
+ {
1595
+ "position_ids": position_ids,
1596
+ "past_key_values": past_key_values,
1597
+ "use_cache": kwargs.get("use_cache"),
1598
+ "attention_mask": attention_mask,
1599
+ }
1600
+ )
1601
+ return model_inputs
1602
+
1603
+ @staticmethod
1604
+ def _reorder_cache(past_key_values, beam_idx):
1605
+ reordered_past = ()
1606
+ for layer_past in past_key_values:
1607
+ reordered_past += (
1608
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1609
+ )
1610
+ return reordered_past
1611
+
modeling_videochat_flash.py ADDED
@@ -0,0 +1,732 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from abc import ABC, abstractmethod
16
+ import re
17
+ import torch
18
+ import torch.nn as nn
19
+ import random
20
+ from typing import List, Optional, Tuple, Union, Dict
21
+
22
+ from transformers import AutoConfig, AutoModelForCausalLM
23
+ from transformers.modeling_outputs import CausalLMOutputWithPast
24
+ from transformers.generation.utils import GenerateOutput
25
+ from transformers import Qwen2Config
26
+
27
+ from .vision_tower_builder import build_vision_tower
28
+ from .mm_projector_builder import build_vision_projector
29
+
30
+ from .constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, DEFAULT_IMAGE_TOKEN
31
+ from .conversation import conv_templates, SeparatorStyle
32
+ from .mm_utils import tokenizer_image_token, KeywordsStoppingCriteria, get_anyres_image_grid_shape, load_video
33
+ # from .modeling_qwen2_flash import Qwen2Model_Flash, Qwen2ForCausalLM_Flash
34
+ # from .modeling_qwen2_flash_v7 import Qwen2Model_Flash, Qwen2ForCausalLM_Flash
35
+ from .modeling_qwen2_flash import Qwen2Model_Flash, Qwen2ForCausalLM_Flash
36
+
37
+
38
+ class LlavaMetaModel:
39
+
40
+ def __init__(self, config):
41
+ super(LlavaMetaModel, self).__init__(config)
42
+
43
+ if hasattr(config, "mm_vision_tower"):
44
+ delay_load = getattr(config, "delay_load", False)
45
+ self.vision_tower = build_vision_tower(config, delay_load=delay_load)
46
+ self.mm_projector = build_vision_projector(config, vision_cfg=self.vision_tower.config)
47
+
48
+ if "unpad" in getattr(config, "mm_patch_merge_type", ""):
49
+ self.image_newline = nn.Parameter(torch.empty(config.hidden_size, dtype=self.dtype))
50
+ if "nopad" in getattr(config, "mm_patch_merge_type", "") and getattr(self.config, "mm_newline_position", "nothing") != "nothing":
51
+ self.frame_newline = nn.Parameter(torch.empty(config.hidden_size, dtype=self.dtype))
52
+
53
+ def get_vision_tower(self):
54
+ vision_tower = getattr(self, "vision_tower", None)
55
+ if type(vision_tower) is list:
56
+ vision_tower = vision_tower[0]
57
+ return vision_tower
58
+
59
+ def initialize_vision_modules(self, model_args, fsdp=None):
60
+ vision_tower = model_args.vision_tower
61
+ mm_vision_select_layer = model_args.mm_vision_select_layer
62
+ mm_vision_select_feature = model_args.mm_vision_select_feature
63
+ pretrain_mm_mlp_adapter = model_args.pretrain_mm_mlp_adapter
64
+ mm_patch_merge_type = model_args.mm_patch_merge_type
65
+
66
+ self.config.mm_vision_tower = vision_tower
67
+ self.config.vision_tower_pretrained = getattr(model_args, "vision_tower_pretrained", "")
68
+
69
+ if self.get_vision_tower() is None:
70
+ vision_tower = build_vision_tower(model_args)
71
+
72
+ if fsdp is not None and len(fsdp) > 0:
73
+ self.vision_tower = [vision_tower]
74
+ else:
75
+ self.vision_tower = vision_tower
76
+ else:
77
+ if fsdp is not None and len(fsdp) > 0:
78
+ vision_tower = self.vision_tower[0]
79
+ else:
80
+ vision_tower = self.vision_tower
81
+ vision_tower.load_model()
82
+
83
+
84
+
85
+ self.config.use_mm_proj = True
86
+ self.config.mm_projector_type = getattr(model_args, "mm_projector_type", "linear")
87
+ self.config.mm_vision_select_layer = mm_vision_select_layer
88
+ self.config.mm_vision_select_feature = mm_vision_select_feature
89
+ self.config.mm_patch_merge_type = mm_patch_merge_type
90
+
91
+ if getattr(self, "mm_projector", None) is None:
92
+ self.mm_projector = build_vision_projector(self.config, vision_cfg=vision_tower.config)
93
+
94
+ if "unpad" in mm_patch_merge_type:
95
+ embed_std = 1 / torch.sqrt(torch.tensor(self.config.hidden_size, dtype=self.dtype))
96
+ self.image_newline = nn.Parameter(torch.randn(self.config.hidden_size, dtype=self.dtype) * embed_std)
97
+ if "nopad" in getattr(self.config, "mm_patch_merge_type", "") and getattr(self.config, "mm_newline_position", "nothing") != "nothing":
98
+ embed_std = 1 / torch.sqrt(torch.tensor(self.config.hidden_size, dtype=self.dtype))
99
+ self.frame_newline = nn.Parameter(torch.randn(self.config.hidden_size, dtype=self.dtype) * embed_std)
100
+ else:
101
+ # In case it is frozen by LoRA
102
+ for p in self.mm_projector.parameters():
103
+ p.requires_grad = True
104
+
105
+ if pretrain_mm_mlp_adapter is not None:
106
+ mm_projector_weights = torch.load(pretrain_mm_mlp_adapter, map_location="cpu")
107
+
108
+ def get_w(weights, keyword):
109
+ return {k.split(keyword + ".")[1]: v for k, v in weights.items() if keyword in k}
110
+
111
+ if self.config.mm_projector_type =='lxh_qformer':
112
+ incompatible_keys = self.mm_projector.load_state_dict(get_w(mm_projector_weights, "mm_projector"), strict=False)
113
+ else:
114
+ incompatible_keys = self.mm_projector.load_state_dict(get_w(mm_projector_weights, "mm_projector"))
115
+ print(f"Loaded mm projector weights from {pretrain_mm_mlp_adapter}. Incompatible keys: {incompatible_keys}")
116
+
117
+
118
+ class LlavaMetaForCausalLM(ABC):
119
+
120
+ @abstractmethod
121
+ def get_model(self):
122
+ pass
123
+
124
+ def get_vision_tower(self):
125
+ return self.get_model().get_vision_tower()
126
+
127
+
128
+ def encode_video_image(self, images_list, video_idx_in_batch):
129
+ # video encoder编码后按图像的connector处理
130
+ bs = len(images_list)
131
+
132
+ concat_images = []
133
+ concat_videos = []
134
+ for idx, image in enumerate(images_list):
135
+ if idx in video_idx_in_batch:
136
+ concat_videos.append(image)
137
+ else:
138
+ concat_images.append(image)
139
+ # print(concat_videos[0].shape)
140
+ has_image = len(concat_images) > 0
141
+ has_video = len(concat_videos) > 0
142
+
143
+ mm_local_num_frames = getattr(self.config, "mm_local_num_frames", -1)
144
+ assert mm_local_num_frames != -1
145
+ if has_image:
146
+ image_split_sizes = [image.shape[0] for image in concat_images]
147
+ concat_images = torch.cat([image.unsqueeze(1) for image in concat_images], dim=0)
148
+ # print("input vit image.shape:", concat_images.shape)
149
+ images_features = self.get_model().get_vision_tower()(concat_images) # B_i, N, D
150
+ images_features = torch.split(images_features, image_split_sizes)
151
+
152
+ if has_video:
153
+ video_split_sizes = [video.shape[0] // mm_local_num_frames for video in concat_videos]
154
+ concat_videos = torch.cat([video.reshape(video.shape[0] // mm_local_num_frames, mm_local_num_frames, video.shape[1], video.shape[2], video.shape[3]) for video in concat_videos], dim=0)
155
+ # print("input vit video.shape:", concat_videos.shape)
156
+ videos_features = self.get_model().get_vision_tower()(concat_videos) # B_v, N, D
157
+ videos_features = [v.reshape(-1, v.shape[-2] // mm_local_num_frames, v.shape[-1]) for v in torch.split(videos_features, video_split_sizes)]
158
+
159
+
160
+ all_videos_or_images_features = []
161
+ img_idx = 0
162
+ vid_idx = 0
163
+
164
+ for idx in range(bs):
165
+
166
+ if idx in video_idx_in_batch:
167
+ feat = self.get_model().mm_projector(videos_features[vid_idx], compress=True, local_num_frames=getattr(self.config, "mm_local_num_frames", -1))
168
+
169
+ vid_idx += 1
170
+ else:
171
+ feat = self.get_model().mm_projector(images_features[img_idx], compress=False)
172
+ img_idx += 1
173
+ # print("video_idx_in_batch:", video_idx_in_batch)
174
+ all_videos_or_images_features.append(feat)
175
+
176
+ if has_video:
177
+ assert vid_idx == len(videos_features), f"vid: {vid_idx} != {len(videos_features)}"
178
+ if has_image:
179
+ assert img_idx == len(images_features), f"img: {img_idx} != {len(images_features)}"
180
+
181
+ return all_videos_or_images_features
182
+
183
+
184
+
185
+ def prepare_inputs_labels_for_multimodal(self, input_ids, position_ids, attention_mask, past_key_values, labels, images, modalities=["image"], image_sizes=None):
186
+ assert type(modalities) is list, modalities
187
+ mm_llm_compress = getattr(self.config, "mm_llm_compress", False)
188
+
189
+ if mm_llm_compress:
190
+ self.model.llm_compress_type = getattr(self.config, "llm_compress_type", "attention")
191
+ self.model.llm_compress_layer_list = getattr(self.config, "llm_compress_layer_list", [8, 16, 24])
192
+ self.model.llm_image_token_ratio_list = getattr(self.config, "llm_image_token_ratio_list", [1.0, 0.5, 0.25, 0.125])
193
+ first_image_token_position = []
194
+ text_prompt_lens = []
195
+ else:
196
+ self.model.llm_compress_type = "attention"
197
+ self.model.llm_compress_layer_list = []
198
+ self.model.llm_image_token_ratio_list = []
199
+ first_image_token_position = []
200
+ text_prompt_lens = []
201
+
202
+ if images is None:
203
+ return input_ids, position_ids, attention_mask, past_key_values, None, labels
204
+
205
+ vision_tower = self.get_vision_tower()
206
+ # rank_print(modalities)
207
+ if vision_tower is None or images is None or input_ids.shape[1] == 1:
208
+ return input_ids, position_ids, attention_mask, past_key_values, None, labels
209
+
210
+ if type(images) is list or images.ndim == 5:
211
+ if type(images) is list:
212
+ images = [x.unsqueeze(0) if x.ndim == 3 else x for x in images]
213
+
214
+ video_idx_in_batch = []
215
+ for _ in range(len(modalities)):
216
+ if modalities[_] == "video":
217
+ video_idx_in_batch.append(_)
218
+
219
+ images_list = []
220
+ for image in images:
221
+ if image.ndim == 4:
222
+ images_list.append(image)
223
+ else:
224
+ images_list.append(image.unsqueeze(0))
225
+
226
+
227
+ vision_encode_type = getattr(self.config, "vision_encode_type", "image")
228
+ mm_patch_merge_type = getattr(self.config, "mm_patch_merge_type", "flat")
229
+ image_aspect_ratio = getattr(self.config, "image_aspect_ratio", "square")
230
+ frame_aspect_ratio = getattr(self.config, "frame_aspect_ratio", "square")
231
+ mm_newline_position = getattr(self.config, "mm_newline_position", "nothing")
232
+
233
+
234
+ if vision_encode_type == "video_image": # video backbone, process video with compress
235
+ image_features = self.encode_video_image(images_list, video_idx_in_batch=video_idx_in_batch)
236
+ else:
237
+ raise NotImplementedError(vision_encode_type)
238
+
239
+
240
+ if mm_patch_merge_type == "flat":
241
+ image_features = [x.flatten(0, 1) for x in image_features]
242
+ elif mm_patch_merge_type.startswith("spatial"):
243
+ new_image_features = []
244
+ for image_idx, image_feature in enumerate(image_features):
245
+
246
+ if image_idx in video_idx_in_batch: # video operations
247
+
248
+ if "anyres" in frame_aspect_ratio:
249
+ raise NotImplementedError
250
+ else:
251
+ frame_feature = image_feature
252
+
253
+ if "pad" in mm_patch_merge_type:
254
+ if mm_newline_position == 'one_token':
255
+ frame_feature = frame_feature.flatten(0, 1)
256
+ if "unpad" in mm_patch_merge_type:
257
+ frame_feature = torch.cat((frame_feature, self.model.image_newline[None].to(frame_feature.device)), dim=0)
258
+ else:
259
+ frame_feature = torch.cat((frame_feature, self.model.frame_newline[None].to(frame_feature.device)), dim=0)
260
+ elif mm_newline_position == 'nothing':
261
+ frame_feature = frame_feature.flatten(0, 1)
262
+ else:
263
+ raise NotImplementedError("add pad please!!")
264
+ else:
265
+ frame_feature = frame_feature.flatten(0, 1)
266
+
267
+ # print(f"final video frame_feature.shape: {frame_feature.shape}")
268
+ image_feature = frame_feature
269
+
270
+ elif image_feature.shape[0] > 1: # multi patches and multi images operations
271
+ base_image_feature = image_feature[0]
272
+ image_feature = image_feature[1:]
273
+ origin_size = image_feature.shape
274
+
275
+ height = width = self.get_model().mm_projector.num_image_patches_per_side
276
+ assert height * width == base_image_feature.shape[0], f"height:{height}, width: {width}, base_image_feature: {base_image_feature.shape}"
277
+
278
+ if "anyres_max" in image_aspect_ratio:
279
+ matched_anyres_max_num_patches = re.match(r"anyres_max_(\d+)", image_aspect_ratio)
280
+ if matched_anyres_max_num_patches:
281
+ max_num_patches = int(matched_anyres_max_num_patches.group(1))
282
+
283
+ if "anyres" in image_aspect_ratio:
284
+ if hasattr(self.get_vision_tower(), "image_size"):
285
+ vision_tower_image_size = self.get_vision_tower().image_size
286
+ else:
287
+ raise ValueError("vision_tower_image_size is not found in the vision tower.")
288
+ try:
289
+ num_patch_width, num_patch_height = get_anyres_image_grid_shape(image_sizes[image_idx], self.config.image_grid_pinpoints, vision_tower_image_size, max_resolutions=None)
290
+ except Exception as e:
291
+ print(f"Error: {e}")
292
+ raise e
293
+ # num_patch_width, num_patch_height = 2, 2
294
+
295
+ image_feature = image_feature.view(num_patch_height, num_patch_width, height, width, -1)
296
+ else:
297
+ raise NotImplementedError(image_aspect_ratio)
298
+ image_feature = image_feature.view(2, 2, height, width, -1)
299
+
300
+ if "maxpool2x2" in mm_patch_merge_type:
301
+ raise NotImplementedError
302
+ elif "unpad" in mm_patch_merge_type and "anyres_max" in image_aspect_ratio and matched_anyres_max_num_patches:
303
+ raise NotImplementedError
304
+ elif "unpad" in mm_patch_merge_type:
305
+ raise NotImplementedError
306
+ else:
307
+ image_feature = image_feature.permute(0, 2, 1, 3, 4).contiguous()
308
+ image_feature = image_feature.flatten(0, 3)
309
+ if "nobase" in mm_patch_merge_type:
310
+ pass
311
+ else:
312
+ try:
313
+ image_feature = torch.cat((base_image_feature, image_feature), dim=0)
314
+ except Exception as e:
315
+ raise ValueError(f"{num_patch_width} {num_patch_height} now: base_image_feature: {base_image_feature.shape}, {image_feature.shape}, image_sizes[image_idx]: {image_sizes[image_idx]}, origin_size: {origin_size}, {image_sizes[image_idx]}, {self.config.image_grid_pinpoints}, {vision_tower_image_size}")
316
+ else: # single image operations
317
+ image_feature = image_feature[0]
318
+ if "unpad" in mm_patch_merge_type:
319
+ image_feature = torch.cat((image_feature, self.model.image_newline[None]), dim=0)
320
+
321
+ # print(f"image/video_feature.shape: {image_feature.shape}")
322
+ new_image_features.append(image_feature)
323
+ image_features = new_image_features
324
+ else:
325
+ raise ValueError(f"Unexpected mm_patch_merge_type: {self.config.mm_patch_merge_type}")
326
+ else:
327
+ # raise NotImplementedError(f"images.shape={images.shape}, modalities={modalities}")
328
+ image_features = self.encode_image(images)
329
+
330
+ # TODO: image start / end is not implemented here to support pretraining.
331
+ if getattr(self.config, "tune_mm_mlp_adapter", False) and getattr(self.config, "mm_use_im_start_end", False):
332
+ raise NotImplementedError
333
+ # print(f"Total images len(image_features: {len(image_features)}")
334
+
335
+ # Let's just add dummy tensors if they do not exist,
336
+ # it is a headache to deal with None all the time.
337
+ # But it is not ideal, and if you have a better idea,
338
+ # please open an issue / submit a PR, thanks.
339
+ _labels = labels
340
+ _position_ids = position_ids
341
+ _attention_mask = attention_mask
342
+ if attention_mask is None:
343
+ attention_mask = torch.ones_like(input_ids, dtype=torch.bool)
344
+ else:
345
+ attention_mask = attention_mask.bool()
346
+ if position_ids is None:
347
+ position_ids = torch.arange(0, input_ids.shape[1], dtype=torch.long, device=input_ids.device)
348
+ if labels is None:
349
+ labels = torch.full_like(input_ids, IGNORE_INDEX)
350
+
351
+
352
+ input_ids = [cur_input_ids[cur_attention_mask] for cur_input_ids, cur_attention_mask in zip(input_ids, attention_mask)]
353
+ labels = [cur_labels[cur_attention_mask] for cur_labels, cur_attention_mask in zip(labels, attention_mask)]
354
+
355
+ new_input_embeds = []
356
+ new_labels = []
357
+ cur_image_idx = 0
358
+
359
+ mm_llm_compress = getattr(self.config, "mm_llm_compress", False)
360
+
361
+ if mm_llm_compress:
362
+ self.model.llm_compress_type = getattr(self.config, "llm_compress_type", "attention")
363
+ self.model.llm_compress_layer_list = getattr(self.config, "llm_compress_layer_list", [8, 16, 24])
364
+ self.model.llm_image_token_ratio_list = getattr(self.config, "llm_image_token_ratio_list", [1.0, 0.5, 0.25, 0.125])
365
+ first_image_token_position = []
366
+ text_prompt_lens = []
367
+ else:
368
+ self.model.llm_compress_type = "attention"
369
+ self.model.llm_compress_layer_list = []
370
+ self.model.llm_image_token_ratio_list = []
371
+ first_image_token_position = []
372
+ text_prompt_lens = []
373
+
374
+ # rank_print("Inserting Images embedding")
375
+ for batch_idx, cur_input_ids in enumerate(input_ids):
376
+ num_images = (cur_input_ids == IMAGE_TOKEN_INDEX).sum()
377
+
378
+ if mm_llm_compress:
379
+ ####### copy from pdrop, only support single image/video NOTE ##################
380
+ # record image position for further dropping
381
+ image_index = torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0].tolist()
382
+ assert len(image_index) == 1, f"Only support singe/video: {image_index}"
383
+ if image_index == []:
384
+ first_image_token_position.append(-1)
385
+ else:
386
+ first_image_token_position.append(image_index[0])
387
+
388
+
389
+ # record input instruction length in inference mode
390
+ if not self.training:
391
+ if image_index == []:
392
+ assert num_images == 0, num_images
393
+ else:
394
+ assert num_images == 1, f"num_images={num_images}"
395
+ text_prompt_lens.append(cur_input_ids.shape[0] - num_images) # consider image place holder
396
+
397
+ ###############################################
398
+
399
+ # print(f"num_images={num_images}")
400
+ if num_images == 0:
401
+ cur_image_features = image_features[cur_image_idx]
402
+ cur_input_embeds_1 = self.get_model().embed_tokens(cur_input_ids)
403
+ cur_input_embeds = torch.cat([cur_input_embeds_1, cur_image_features[0:0]], dim=0)
404
+ new_input_embeds.append(cur_input_embeds)
405
+ new_labels.append(labels[batch_idx])
406
+ cur_image_idx += 1
407
+ continue
408
+
409
+ image_token_indices = [-1] + torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0].tolist() + [cur_input_ids.shape[0]]
410
+ cur_input_ids_noim = []
411
+ cur_labels = labels[batch_idx]
412
+ cur_labels_noim = []
413
+ for i in range(len(image_token_indices) - 1):
414
+ cur_input_ids_noim.append(cur_input_ids[image_token_indices[i] + 1 : image_token_indices[i + 1]])
415
+ cur_labels_noim.append(cur_labels[image_token_indices[i] + 1 : image_token_indices[i + 1]])
416
+ split_sizes = [x.shape[0] for x in cur_labels_noim]
417
+ cur_input_embeds = self.get_model().embed_tokens(torch.cat(cur_input_ids_noim))
418
+ cur_input_embeds_no_im = torch.split(cur_input_embeds, split_sizes, dim=0)
419
+ cur_new_input_embeds = []
420
+ cur_new_labels = []
421
+
422
+ for i in range(num_images + 1):
423
+ cur_new_input_embeds.append(cur_input_embeds_no_im[i])
424
+ cur_new_labels.append(cur_labels_noim[i])
425
+ if i < num_images:
426
+ try:
427
+ cur_image_features = image_features[cur_image_idx]
428
+ except IndexError:
429
+ print(f"cur_image_idx={cur_image_idx} is not ok")
430
+ cur_image_features = image_features[cur_image_idx - 1]
431
+ cur_image_idx += 1
432
+ cur_new_input_embeds.append(cur_image_features)
433
+ cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=cur_labels.device, dtype=cur_labels.dtype))
434
+
435
+ cur_new_input_embeds = [x.to(self.device) for x in cur_new_input_embeds]
436
+
437
+ # import pdb; pdb.set_trace()
438
+ cur_new_input_embeds = torch.cat(cur_new_input_embeds)
439
+ cur_new_labels = torch.cat(cur_new_labels)
440
+
441
+ new_input_embeds.append(cur_new_input_embeds)
442
+ new_labels.append(cur_new_labels)
443
+
444
+
445
+ if mm_llm_compress:
446
+ self.model.first_image_token_position = first_image_token_position
447
+ self.model.text_prompt_lens = text_prompt_lens
448
+ self.model.num_image_token_lens = [image_feature.shape[0] for image_feature in image_features]
449
+
450
+ # Truncate sequences to max length as image embeddings can make the sequence longer
451
+ tokenizer_model_max_length = getattr(self.config, "tokenizer_model_max_length", None)
452
+ # rank_print("Finishing Inserting")
453
+
454
+ new_input_embeds = [x[:tokenizer_model_max_length] for x, modality in zip(new_input_embeds, modalities)]
455
+ new_labels = [x[:tokenizer_model_max_length] for x, modality in zip(new_labels, modalities)]
456
+
457
+ # Combine them
458
+ max_len = max(x.shape[0] for x in new_input_embeds)
459
+ batch_size = len(new_input_embeds)
460
+
461
+ new_input_embeds_padded = []
462
+ new_labels_padded = torch.full((batch_size, max_len), IGNORE_INDEX, dtype=new_labels[0].dtype, device=new_labels[0].device)
463
+ attention_mask = torch.zeros((batch_size, max_len), dtype=attention_mask.dtype, device=attention_mask.device)
464
+ position_ids = torch.zeros((batch_size, max_len), dtype=position_ids.dtype, device=position_ids.device)
465
+ # print("Prepare pos id")
466
+
467
+ for i, (cur_new_embed, cur_new_labels) in enumerate(zip(new_input_embeds, new_labels)):
468
+ cur_len = cur_new_embed.shape[0]
469
+ if getattr(self.config, "tokenizer_padding_side", "right") == "left":
470
+ new_input_embeds_padded.append(torch.cat((torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device), cur_new_embed), dim=0))
471
+ if cur_len > 0:
472
+ new_labels_padded[i, -cur_len:] = cur_new_labels
473
+ attention_mask[i, -cur_len:] = True
474
+ position_ids[i, -cur_len:] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
475
+ else:
476
+ new_input_embeds_padded.append(torch.cat((cur_new_embed, torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device)), dim=0))
477
+ if cur_len > 0:
478
+ new_labels_padded[i, :cur_len] = cur_new_labels
479
+ attention_mask[i, :cur_len] = True
480
+ position_ids[i, :cur_len] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
481
+
482
+ new_input_embeds = torch.stack(new_input_embeds_padded, dim=0)
483
+ # print("tokenizer padding")
484
+
485
+ if _labels is None:
486
+ new_labels = None
487
+ else:
488
+ new_labels = new_labels_padded
489
+
490
+ if _attention_mask is None:
491
+ attention_mask = None
492
+ else:
493
+ attention_mask = attention_mask.to(dtype=_attention_mask.dtype)
494
+
495
+ if _position_ids is None:
496
+ position_ids = None
497
+ if getattr(self.config, "use_pos_skipping", False) and self.training:
498
+ position_ids = torch.arange(new_input_embeds.size(1), device=new_input_embeds.device).unsqueeze(0).to(new_input_embeds.device)
499
+ split_position = random.randint(0, new_input_embeds.size(1))
500
+ left_add = random.randint(0, self.config.pos_skipping_range)
501
+ right_add = random.randint(left_add, self.config.pos_skipping_range)
502
+ position_ids[:, :split_position] += left_add
503
+ position_ids[:, split_position:] += right_add
504
+ # import pdb; pdb.set_trace()
505
+ # print("Finish preparing")
506
+ return None, position_ids, attention_mask, past_key_values, new_input_embeds, new_labels
507
+
508
+ def initialize_vision_tokenizer(self, model_args, tokenizer):
509
+ if model_args.mm_use_im_patch_token:
510
+ tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
511
+ self.resize_token_embeddings(len(tokenizer))
512
+
513
+ if model_args.mm_use_im_start_end:
514
+ num_new_tokens = tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
515
+ self.resize_token_embeddings(len(tokenizer))
516
+
517
+ if num_new_tokens > 0:
518
+ input_embeddings = self.get_input_embeddings().weight.data
519
+ output_embeddings = self.get_output_embeddings().weight.data
520
+
521
+ input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
522
+ output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
523
+
524
+ input_embeddings[-num_new_tokens:] = input_embeddings_avg
525
+ output_embeddings[-num_new_tokens:] = output_embeddings_avg
526
+
527
+ if model_args.tune_mm_mlp_adapter:
528
+ for p in self.get_input_embeddings().parameters():
529
+ p.requires_grad = True
530
+ for p in self.get_output_embeddings().parameters():
531
+ p.requires_grad = False
532
+
533
+ if model_args.pretrain_mm_mlp_adapter:
534
+ mm_projector_weights = torch.load(model_args.pretrain_mm_mlp_adapter, map_location="cpu")
535
+ embed_tokens_weight = mm_projector_weights["model.embed_tokens.weight"]
536
+ assert num_new_tokens == 2
537
+ if input_embeddings.shape == embed_tokens_weight.shape:
538
+ input_embeddings[-num_new_tokens:] = embed_tokens_weight[-num_new_tokens:]
539
+ elif embed_tokens_weight.shape[0] == num_new_tokens:
540
+ input_embeddings[-num_new_tokens:] = embed_tokens_weight
541
+ else:
542
+ raise ValueError(f"Unexpected embed_tokens_weight shape. Pretrained: {embed_tokens_weight.shape}. Current: {input_embeddings.shape}. Numer of new tokens: {num_new_tokens}.")
543
+ elif model_args.mm_use_im_patch_token:
544
+ if model_args.tune_mm_mlp_adapter:
545
+ for p in self.get_input_embeddings().parameters():
546
+ p.requires_grad = False
547
+ for p in self.get_output_embeddings().parameters():
548
+ p.requires_grad = False
549
+
550
+
551
+
552
+ class VideoChatFlashQwenConfig(Qwen2Config):
553
+ model_type = "videochat_flash_qwen"
554
+
555
+
556
+ class VideoChatFlashQwenModel(LlavaMetaModel, Qwen2Model_Flash):
557
+ config_class = VideoChatFlashQwenConfig
558
+
559
+ def __init__(self, config: VideoChatFlashQwenConfig):
560
+ super(VideoChatFlashQwenModel, self).__init__(config)
561
+
562
+
563
+ class VideoChatFlashQwenForCausalLM(LlavaMetaForCausalLM, Qwen2ForCausalLM_Flash):
564
+ config_class = VideoChatFlashQwenConfig
565
+
566
+ def __init__(self, config):
567
+ # super(Qwen2ForCausalLM, self).__init__(config)
568
+ Qwen2ForCausalLM_Flash.__init__(self, config)
569
+ config.model_type = "videochat_flash_qwen"
570
+ # config.rope_scaling = None
571
+
572
+ self.model = VideoChatFlashQwenModel(config)
573
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
574
+ # Initialize weights and apply final processing
575
+ self.post_init()
576
+
577
+ def get_model(self):
578
+ return self.model
579
+
580
+ def forward(
581
+ self,
582
+ input_ids: torch.LongTensor = None,
583
+ attention_mask: Optional[torch.Tensor] = None,
584
+ position_ids: Optional[torch.LongTensor] = None,
585
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
586
+ inputs_embeds: Optional[torch.FloatTensor] = None,
587
+ labels: Optional[torch.LongTensor] = None,
588
+ use_cache: Optional[bool] = None,
589
+ output_attentions: Optional[bool] = None,
590
+ output_hidden_states: Optional[bool] = None,
591
+ images: Optional[torch.FloatTensor] = None,
592
+ image_sizes: Optional[List[List[int]]] = None,
593
+ return_dict: Optional[bool] = None,
594
+ modalities: Optional[List[str]] = ["image"],
595
+ dpo_forward: Optional[bool] = False,
596
+ cache_position=None,
597
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
598
+
599
+ if inputs_embeds is None:
600
+ (input_ids, position_ids, attention_mask, past_key_values, inputs_embeds, labels) = self.prepare_inputs_labels_for_multimodal(input_ids, position_ids, attention_mask, past_key_values, labels, images, modalities, image_sizes)
601
+
602
+ # print("inputs_embeds.shape:", inputs_embeds.shape)
603
+ if dpo_forward:
604
+ raise NotImplementedError
605
+ else:
606
+ return super().forward(
607
+ input_ids=input_ids,
608
+ attention_mask=attention_mask,
609
+ position_ids=position_ids,
610
+ past_key_values=past_key_values,
611
+ inputs_embeds=inputs_embeds,
612
+ labels=labels,
613
+ use_cache=use_cache,
614
+ output_attentions=output_attentions,
615
+ output_hidden_states=output_hidden_states,
616
+ return_dict=return_dict,
617
+ )
618
+
619
+ @torch.no_grad()
620
+ def generate(
621
+ self,
622
+ inputs: Optional[torch.Tensor] = None,
623
+ images: Optional[torch.Tensor] = None,
624
+ image_sizes: Optional[torch.Tensor] = None,
625
+ modalities: Optional[List[str]] = ["image"],
626
+ **kwargs,
627
+ ) -> Union[GenerateOutput, torch.LongTensor]:
628
+ position_ids = kwargs.pop("position_ids", None)
629
+ attention_mask = kwargs.pop("attention_mask", None)
630
+ if "inputs_embeds" in kwargs:
631
+ raise NotImplementedError("`inputs_embeds` is not supported")
632
+
633
+ if images is not None:
634
+ (inputs, position_ids, attention_mask, _, inputs_embeds, _) = self.prepare_inputs_labels_for_multimodal(inputs, position_ids, attention_mask, None, None, images, modalities, image_sizes=image_sizes)
635
+ else:
636
+ self.model.image_token_posi = [-1]
637
+ self.model.prompt_len = None
638
+ self.model.image_tokens = [0]
639
+ inputs_embeds = self.get_model().embed_tokens(inputs)
640
+
641
+ return super().generate(position_ids=position_ids, attention_mask=attention_mask, inputs_embeds=inputs_embeds, **kwargs)
642
+
643
+ @torch.no_grad()
644
+ def chat(self,
645
+ video_path,
646
+ tokenizer,
647
+ user_prompt,
648
+ chat_history=None,
649
+ return_history=True,
650
+ max_num_frames=512,
651
+ media_dict=None,
652
+ generation_config={}):
653
+
654
+ frames, time_msg = load_video(video_path, max_num_frames=max_num_frames, media_dict=media_dict)
655
+
656
+ image_sizes = [frames[0].shape[:2]]
657
+
658
+ frames = [self.get_vision_tower().image_processor.preprocess(frames, return_tensors="pt")["pixel_values"].to(self.model.dtype).cuda()]
659
+
660
+ conv = conv_templates["qwen_2"].copy()
661
+
662
+ if chat_history is None or len(chat_history) == 0:
663
+ user_prompt = f'{DEFAULT_IMAGE_TOKEN}\n{time_msg.strip()} {user_prompt}'
664
+ else:
665
+ assert DEFAULT_IMAGE_TOKEN in chat_history[0]['content'], chat_history
666
+ for msg in chat_history:
667
+ conv.append_message(msg['role'], msg['content'])
668
+
669
+ conv.append_message(conv.roles[0], user_prompt)
670
+ conv.append_message(conv.roles[1], None)
671
+
672
+ prompt = conv.get_prompt()
673
+
674
+ input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).cuda()
675
+
676
+ if tokenizer.pad_token_id is None:
677
+ if "qwen" in tokenizer.name_or_path.lower():
678
+ print("Setting pad token to bos token for qwen model.")
679
+ tokenizer.pad_token_id = 151643
680
+
681
+ attention_masks = input_ids.ne(tokenizer.pad_token_id).long().cuda()
682
+
683
+ stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
684
+ keywords = [stop_str]
685
+ stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
686
+
687
+ with torch.inference_mode():
688
+ output_ids = self.generate(
689
+ inputs=input_ids,
690
+ images=frames,
691
+ attention_mask=attention_masks,
692
+ modalities=["video"],
693
+ image_sizes=image_sizes,
694
+ use_cache=True,
695
+ stopping_criteria=[stopping_criteria],
696
+ **generation_config
697
+ )
698
+
699
+ outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
700
+ if outputs.endswith(stop_str):
701
+ outputs = outputs[: -len(stop_str)]
702
+
703
+ outputs = outputs.strip()
704
+
705
+ # print(f"\033[91m== Question: \033[0m\n{prompt}\n")
706
+ # print(f"\033[91m== Response: \033[0m\n{outputs}\n")
707
+
708
+ if chat_history is None:
709
+ chat_history = []
710
+
711
+ chat_history.append({"role":conv.roles[0], "content":user_prompt})
712
+ chat_history.append({"role":conv.roles[1], "content":outputs})
713
+ if return_history:
714
+ return outputs, chat_history
715
+ else:
716
+ return outputs
717
+
718
+
719
+
720
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
721
+ images = kwargs.pop("images", None)
722
+ image_sizes = kwargs.pop("image_sizes", None)
723
+ inputs = super().prepare_inputs_for_generation(input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs)
724
+ if images is not None:
725
+ inputs["images"] = images
726
+ if image_sizes is not None:
727
+ inputs["image_sizes"] = image_sizes
728
+ return inputs
729
+
730
+
731
+ AutoConfig.register("videochat_flash_qwen", VideoChatFlashQwenConfig)
732
+ AutoModelForCausalLM.register(VideoChatFlashQwenConfig, VideoChatFlashQwenForCausalLM)
optimizer.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1c139f326bed12c26e5166039d19cce59a82907b0d4745c3af00791751efaae8
3
+ size 618244858
rng_state_0.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bbe0d720c4c75a6a04213fa3b64bacbe794718a53e2b56ebb67a1a795014dfad
3
+ size 15024
rng_state_1.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:72452d3138d0ca2ff89429e3294a834ae7a68e8596fc757735ca56ae52509d57
3
+ size 15024
rng_state_2.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f36e306fb8ebcf53a167bfd6c9af74db410a269ada1e619e3e816f5269543b9d
3
+ size 15024
rng_state_3.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bb47ce0c6f815a6f8302b0e3819b4c2315ca71dae3138d97fdceb765cdd0a039
3
+ size 15024
scheduler.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:20ef42ba4ce1f9c15d3f5bb2e9cf2d3c5f4cda618dfacab977d4dbd9eda23d73
3
+ size 1064
special_tokens_map.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>",
5
+ "<|object_ref_start|>",
6
+ "<|object_ref_end|>",
7
+ "<|box_start|>",
8
+ "<|box_end|>",
9
+ "<|quad_start|>",
10
+ "<|quad_end|>",
11
+ "<|vision_start|>",
12
+ "<|vision_end|>",
13
+ "<|vision_pad|>",
14
+ "<|image_pad|>",
15
+ "<|video_pad|>"
16
+ ],
17
+ "eos_token": {
18
+ "content": "<|im_end|>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ },
24
+ "pad_token": {
25
+ "content": "<|endoftext|>",
26
+ "lstrip": false,
27
+ "normalized": false,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ }
31
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_prefix_space": false,
4
+ "added_tokens_decoder": {
5
+ "151643": {
6
+ "content": "<|endoftext|>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "151644": {
14
+ "content": "<|im_start|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "151645": {
22
+ "content": "<|im_end|>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "151646": {
30
+ "content": "<|object_ref_start|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "151647": {
38
+ "content": "<|object_ref_end|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "151648": {
46
+ "content": "<|box_start|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "151649": {
54
+ "content": "<|box_end|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "151650": {
62
+ "content": "<|quad_start|>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "151651": {
70
+ "content": "<|quad_end|>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "151652": {
78
+ "content": "<|vision_start|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "151653": {
86
+ "content": "<|vision_end|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "151654": {
94
+ "content": "<|vision_pad|>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": false,
98
+ "single_word": false,
99
+ "special": true
100
+ },
101
+ "151655": {
102
+ "content": "<|image_pad|>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": false,
106
+ "single_word": false,
107
+ "special": true
108
+ },
109
+ "151656": {
110
+ "content": "<|video_pad|>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": false,
114
+ "single_word": false,
115
+ "special": true
116
+ },
117
+ "151657": {
118
+ "content": "<tool_call>",
119
+ "lstrip": false,
120
+ "normalized": false,
121
+ "rstrip": false,
122
+ "single_word": false,
123
+ "special": false
124
+ },
125
+ "151658": {
126
+ "content": "</tool_call>",
127
+ "lstrip": false,
128
+ "normalized": false,
129
+ "rstrip": false,
130
+ "single_word": false,
131
+ "special": false
132
+ },
133
+ "151659": {
134
+ "content": "<|fim_prefix|>",
135
+ "lstrip": false,
136
+ "normalized": false,
137
+ "rstrip": false,
138
+ "single_word": false,
139
+ "special": false
140
+ },
141
+ "151660": {
142
+ "content": "<|fim_middle|>",
143
+ "lstrip": false,
144
+ "normalized": false,
145
+ "rstrip": false,
146
+ "single_word": false,
147
+ "special": false
148
+ },
149
+ "151661": {
150
+ "content": "<|fim_suffix|>",
151
+ "lstrip": false,
152
+ "normalized": false,
153
+ "rstrip": false,
154
+ "single_word": false,
155
+ "special": false
156
+ },
157
+ "151662": {
158
+ "content": "<|fim_pad|>",
159
+ "lstrip": false,
160
+ "normalized": false,
161
+ "rstrip": false,
162
+ "single_word": false,
163
+ "special": false
164
+ },
165
+ "151663": {
166
+ "content": "<|repo_name|>",
167
+ "lstrip": false,
168
+ "normalized": false,
169
+ "rstrip": false,
170
+ "single_word": false,
171
+ "special": false
172
+ },
173
+ "151664": {
174
+ "content": "<|file_sep|>",
175
+ "lstrip": false,
176
+ "normalized": false,
177
+ "rstrip": false,
178
+ "single_word": false,
179
+ "special": false
180
+ }
181
+ },
182
+ "additional_special_tokens": [
183
+ "<|im_start|>",
184
+ "<|im_end|>",
185
+ "<|object_ref_start|>",
186
+ "<|object_ref_end|>",
187
+ "<|box_start|>",
188
+ "<|box_end|>",
189
+ "<|quad_start|>",
190
+ "<|quad_end|>",
191
+ "<|vision_start|>",
192
+ "<|vision_end|>",
193
+ "<|vision_pad|>",
194
+ "<|image_pad|>",
195
+ "<|video_pad|>"
196
+ ],
197
+ "bos_token": null,
198
+ "chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0]['role'] == 'system' %}\n {{- messages[0]['content'] }}\n {%- else %}\n {{- 'You are a helpful assistant.' }}\n {%- endif %}\n {{- \"\\n\\n# Tools\\n\\nYou may call one or more functions to assist with the user query.\\n\\nYou are provided with function signatures within <tools></tools> XML tags:\\n<tools>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n</tools>\\n\\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\\n<tool_call>\\n{\\\"name\\\": <function-name>, \\\"arguments\\\": <args-json-object>}\\n</tool_call><|im_end|>\\n\" }}\n{%- else %}\n {%- if messages[0]['role'] == 'system' %}\n {{- '<|im_start|>system\\n' + messages[0]['content'] + '<|im_end|>\\n' }}\n {%- else %}\n {{- '<|im_start|>system\\nYou are a helpful assistant.<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- for message in messages %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) or (message.role == \"assistant\" and not message.tool_calls) %}\n {{- '<|im_start|>' + message.role + '\\n' + message.content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {{- '<|im_start|>' + message.role }}\n {%- if message.content %}\n {{- '\\n' + message.content }}\n {%- endif %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '\\n<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {{- tool_call.arguments | tojson }}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- message.content }}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n{%- endif %}\n",
199
+ "clean_up_tokenization_spaces": false,
200
+ "eos_token": "<|im_end|>",
201
+ "errors": "replace",
202
+ "model_max_length": 32768,
203
+ "pad_token": "<|endoftext|>",
204
+ "padding_side": "left",
205
+ "split_special_tokens": false,
206
+ "tokenizer_class": "Qwen2Tokenizer",
207
+ "unk_token": null
208
+ }
trainer_state.json ADDED
@@ -0,0 +1,3381 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "best_metric": null,
3
+ "best_model_checkpoint": null,
4
+ "epoch": 1.2752814586031682,
5
+ "eval_steps": 500,
6
+ "global_step": 4800,
7
+ "is_hyper_param_search": false,
8
+ "is_local_process_zero": true,
9
+ "is_world_process_zero": true,
10
+ "log_history": [
11
+ {
12
+ "epoch": 0.0,
13
+ "grad_norm": 32.0,
14
+ "learning_rate": 2.6525198938992043e-06,
15
+ "loss": 3.1809,
16
+ "step": 10
17
+ },
18
+ {
19
+ "epoch": 0.01,
20
+ "grad_norm": 20.625,
21
+ "learning_rate": 5.305039787798409e-06,
22
+ "loss": 3.061,
23
+ "step": 20
24
+ },
25
+ {
26
+ "epoch": 0.01,
27
+ "grad_norm": 11.1875,
28
+ "learning_rate": 7.957559681697613e-06,
29
+ "loss": 2.678,
30
+ "step": 30
31
+ },
32
+ {
33
+ "epoch": 0.01,
34
+ "grad_norm": 5.21875,
35
+ "learning_rate": 1.0610079575596817e-05,
36
+ "loss": 2.3038,
37
+ "step": 40
38
+ },
39
+ {
40
+ "epoch": 0.01,
41
+ "grad_norm": 2.8125,
42
+ "learning_rate": 1.3262599469496024e-05,
43
+ "loss": 1.8983,
44
+ "step": 50
45
+ },
46
+ {
47
+ "epoch": 0.02,
48
+ "grad_norm": 2.015625,
49
+ "learning_rate": 1.5915119363395225e-05,
50
+ "loss": 1.6833,
51
+ "step": 60
52
+ },
53
+ {
54
+ "epoch": 0.02,
55
+ "grad_norm": 2.234375,
56
+ "learning_rate": 1.856763925729443e-05,
57
+ "loss": 1.4026,
58
+ "step": 70
59
+ },
60
+ {
61
+ "epoch": 0.02,
62
+ "grad_norm": 1.09375,
63
+ "learning_rate": 2.1220159151193635e-05,
64
+ "loss": 1.367,
65
+ "step": 80
66
+ },
67
+ {
68
+ "epoch": 0.02,
69
+ "grad_norm": 1.296875,
70
+ "learning_rate": 2.3872679045092838e-05,
71
+ "loss": 1.2439,
72
+ "step": 90
73
+ },
74
+ {
75
+ "epoch": 0.03,
76
+ "grad_norm": 1.09375,
77
+ "learning_rate": 2.6525198938992047e-05,
78
+ "loss": 1.3593,
79
+ "step": 100
80
+ },
81
+ {
82
+ "epoch": 0.03,
83
+ "grad_norm": 4.125,
84
+ "learning_rate": 2.9177718832891247e-05,
85
+ "loss": 1.1539,
86
+ "step": 110
87
+ },
88
+ {
89
+ "epoch": 0.03,
90
+ "grad_norm": 0.80078125,
91
+ "learning_rate": 3.183023872679045e-05,
92
+ "loss": 1.1754,
93
+ "step": 120
94
+ },
95
+ {
96
+ "epoch": 0.03,
97
+ "grad_norm": 1.0859375,
98
+ "learning_rate": 3.4482758620689657e-05,
99
+ "loss": 1.1469,
100
+ "step": 130
101
+ },
102
+ {
103
+ "epoch": 0.04,
104
+ "grad_norm": 13.5625,
105
+ "learning_rate": 3.713527851458886e-05,
106
+ "loss": 1.1146,
107
+ "step": 140
108
+ },
109
+ {
110
+ "epoch": 0.04,
111
+ "grad_norm": 0.76953125,
112
+ "learning_rate": 3.978779840848806e-05,
113
+ "loss": 1.0821,
114
+ "step": 150
115
+ },
116
+ {
117
+ "epoch": 0.04,
118
+ "grad_norm": 1.6015625,
119
+ "learning_rate": 4.244031830238727e-05,
120
+ "loss": 1.0989,
121
+ "step": 160
122
+ },
123
+ {
124
+ "epoch": 0.05,
125
+ "grad_norm": 0.98828125,
126
+ "learning_rate": 4.5092838196286476e-05,
127
+ "loss": 1.0884,
128
+ "step": 170
129
+ },
130
+ {
131
+ "epoch": 0.05,
132
+ "grad_norm": 1.3203125,
133
+ "learning_rate": 4.7745358090185675e-05,
134
+ "loss": 1.0575,
135
+ "step": 180
136
+ },
137
+ {
138
+ "epoch": 0.05,
139
+ "grad_norm": 0.74609375,
140
+ "learning_rate": 5.039787798408488e-05,
141
+ "loss": 1.058,
142
+ "step": 190
143
+ },
144
+ {
145
+ "epoch": 0.05,
146
+ "grad_norm": 0.66796875,
147
+ "learning_rate": 5.3050397877984095e-05,
148
+ "loss": 1.0439,
149
+ "step": 200
150
+ },
151
+ {
152
+ "epoch": 0.06,
153
+ "grad_norm": 0.828125,
154
+ "learning_rate": 5.570291777188329e-05,
155
+ "loss": 1.039,
156
+ "step": 210
157
+ },
158
+ {
159
+ "epoch": 0.06,
160
+ "grad_norm": 0.7578125,
161
+ "learning_rate": 5.8355437665782494e-05,
162
+ "loss": 1.0046,
163
+ "step": 220
164
+ },
165
+ {
166
+ "epoch": 0.06,
167
+ "grad_norm": 0.9296875,
168
+ "learning_rate": 6.100795755968171e-05,
169
+ "loss": 1.0393,
170
+ "step": 230
171
+ },
172
+ {
173
+ "epoch": 0.06,
174
+ "grad_norm": 0.765625,
175
+ "learning_rate": 6.36604774535809e-05,
176
+ "loss": 1.0312,
177
+ "step": 240
178
+ },
179
+ {
180
+ "epoch": 0.07,
181
+ "grad_norm": 0.734375,
182
+ "learning_rate": 6.631299734748011e-05,
183
+ "loss": 1.0024,
184
+ "step": 250
185
+ },
186
+ {
187
+ "epoch": 0.07,
188
+ "grad_norm": 1.859375,
189
+ "learning_rate": 6.896551724137931e-05,
190
+ "loss": 1.0026,
191
+ "step": 260
192
+ },
193
+ {
194
+ "epoch": 0.07,
195
+ "grad_norm": 0.6953125,
196
+ "learning_rate": 7.161803713527851e-05,
197
+ "loss": 0.9781,
198
+ "step": 270
199
+ },
200
+ {
201
+ "epoch": 0.07,
202
+ "grad_norm": 0.84765625,
203
+ "learning_rate": 7.427055702917773e-05,
204
+ "loss": 1.0299,
205
+ "step": 280
206
+ },
207
+ {
208
+ "epoch": 0.08,
209
+ "grad_norm": 0.7421875,
210
+ "learning_rate": 7.692307692307693e-05,
211
+ "loss": 1.015,
212
+ "step": 290
213
+ },
214
+ {
215
+ "epoch": 0.08,
216
+ "grad_norm": 0.671875,
217
+ "learning_rate": 7.957559681697613e-05,
218
+ "loss": 0.9827,
219
+ "step": 300
220
+ },
221
+ {
222
+ "epoch": 0.08,
223
+ "grad_norm": 0.71875,
224
+ "learning_rate": 8.222811671087534e-05,
225
+ "loss": 1.016,
226
+ "step": 310
227
+ },
228
+ {
229
+ "epoch": 0.09,
230
+ "grad_norm": 1.328125,
231
+ "learning_rate": 8.488063660477454e-05,
232
+ "loss": 0.9765,
233
+ "step": 320
234
+ },
235
+ {
236
+ "epoch": 0.09,
237
+ "grad_norm": 0.7109375,
238
+ "learning_rate": 8.753315649867374e-05,
239
+ "loss": 0.9611,
240
+ "step": 330
241
+ },
242
+ {
243
+ "epoch": 0.09,
244
+ "grad_norm": 1.2421875,
245
+ "learning_rate": 9.018567639257295e-05,
246
+ "loss": 0.9964,
247
+ "step": 340
248
+ },
249
+ {
250
+ "epoch": 0.09,
251
+ "grad_norm": 0.6328125,
252
+ "learning_rate": 9.283819628647215e-05,
253
+ "loss": 0.9743,
254
+ "step": 350
255
+ },
256
+ {
257
+ "epoch": 0.1,
258
+ "grad_norm": 0.671875,
259
+ "learning_rate": 9.549071618037135e-05,
260
+ "loss": 1.0025,
261
+ "step": 360
262
+ },
263
+ {
264
+ "epoch": 0.1,
265
+ "grad_norm": 0.6640625,
266
+ "learning_rate": 9.814323607427056e-05,
267
+ "loss": 0.9455,
268
+ "step": 370
269
+ },
270
+ {
271
+ "epoch": 0.1,
272
+ "grad_norm": 0.75,
273
+ "learning_rate": 9.999995654981736e-05,
274
+ "loss": 0.9878,
275
+ "step": 380
276
+ },
277
+ {
278
+ "epoch": 0.1,
279
+ "grad_norm": 0.6328125,
280
+ "learning_rate": 9.999918410422651e-05,
281
+ "loss": 0.9415,
282
+ "step": 390
283
+ },
284
+ {
285
+ "epoch": 0.11,
286
+ "grad_norm": 0.72265625,
287
+ "learning_rate": 9.999744611619098e-05,
288
+ "loss": 0.9682,
289
+ "step": 400
290
+ },
291
+ {
292
+ "epoch": 0.11,
293
+ "grad_norm": 0.65234375,
294
+ "learning_rate": 9.999474261927337e-05,
295
+ "loss": 0.9396,
296
+ "step": 410
297
+ },
298
+ {
299
+ "epoch": 0.11,
300
+ "grad_norm": 0.62890625,
301
+ "learning_rate": 9.999107366568136e-05,
302
+ "loss": 0.968,
303
+ "step": 420
304
+ },
305
+ {
306
+ "epoch": 0.11,
307
+ "grad_norm": 0.68359375,
308
+ "learning_rate": 9.998643932626668e-05,
309
+ "loss": 0.954,
310
+ "step": 430
311
+ },
312
+ {
313
+ "epoch": 0.12,
314
+ "grad_norm": 0.64453125,
315
+ "learning_rate": 9.998083969052385e-05,
316
+ "loss": 0.9338,
317
+ "step": 440
318
+ },
319
+ {
320
+ "epoch": 0.12,
321
+ "grad_norm": 0.640625,
322
+ "learning_rate": 9.997427486658833e-05,
323
+ "loss": 0.9557,
324
+ "step": 450
325
+ },
326
+ {
327
+ "epoch": 0.12,
328
+ "grad_norm": 0.68359375,
329
+ "learning_rate": 9.996674498123451e-05,
330
+ "loss": 0.96,
331
+ "step": 460
332
+ },
333
+ {
334
+ "epoch": 0.12,
335
+ "grad_norm": 0.6484375,
336
+ "learning_rate": 9.995825017987326e-05,
337
+ "loss": 0.929,
338
+ "step": 470
339
+ },
340
+ {
341
+ "epoch": 0.13,
342
+ "grad_norm": 0.6484375,
343
+ "learning_rate": 9.994879062654908e-05,
344
+ "loss": 0.9483,
345
+ "step": 480
346
+ },
347
+ {
348
+ "epoch": 0.13,
349
+ "grad_norm": 0.609375,
350
+ "learning_rate": 9.993836650393696e-05,
351
+ "loss": 0.9466,
352
+ "step": 490
353
+ },
354
+ {
355
+ "epoch": 0.13,
356
+ "grad_norm": 0.59765625,
357
+ "learning_rate": 9.992697801333882e-05,
358
+ "loss": 0.9801,
359
+ "step": 500
360
+ },
361
+ {
362
+ "epoch": 0.14,
363
+ "grad_norm": 0.56640625,
364
+ "learning_rate": 9.991462537467966e-05,
365
+ "loss": 0.9749,
366
+ "step": 510
367
+ },
368
+ {
369
+ "epoch": 0.14,
370
+ "grad_norm": 0.61328125,
371
+ "learning_rate": 9.990130882650336e-05,
372
+ "loss": 0.9292,
373
+ "step": 520
374
+ },
375
+ {
376
+ "epoch": 0.14,
377
+ "grad_norm": 0.61328125,
378
+ "learning_rate": 9.988702862596793e-05,
379
+ "loss": 0.9312,
380
+ "step": 530
381
+ },
382
+ {
383
+ "epoch": 0.14,
384
+ "grad_norm": 0.578125,
385
+ "learning_rate": 9.987178504884067e-05,
386
+ "loss": 0.945,
387
+ "step": 540
388
+ },
389
+ {
390
+ "epoch": 0.15,
391
+ "grad_norm": 0.65234375,
392
+ "learning_rate": 9.98555783894928e-05,
393
+ "loss": 0.961,
394
+ "step": 550
395
+ },
396
+ {
397
+ "epoch": 0.15,
398
+ "grad_norm": 0.65625,
399
+ "learning_rate": 9.98384089608938e-05,
400
+ "loss": 0.9394,
401
+ "step": 560
402
+ },
403
+ {
404
+ "epoch": 0.15,
405
+ "grad_norm": 0.58984375,
406
+ "learning_rate": 9.982027709460527e-05,
407
+ "loss": 0.9551,
408
+ "step": 570
409
+ },
410
+ {
411
+ "epoch": 0.15,
412
+ "grad_norm": 0.52734375,
413
+ "learning_rate": 9.98011831407747e-05,
414
+ "loss": 0.9313,
415
+ "step": 580
416
+ },
417
+ {
418
+ "epoch": 0.16,
419
+ "grad_norm": 0.63671875,
420
+ "learning_rate": 9.978112746812853e-05,
421
+ "loss": 0.9452,
422
+ "step": 590
423
+ },
424
+ {
425
+ "epoch": 0.16,
426
+ "grad_norm": 0.65625,
427
+ "learning_rate": 9.976011046396518e-05,
428
+ "loss": 0.9377,
429
+ "step": 600
430
+ },
431
+ {
432
+ "epoch": 0.16,
433
+ "grad_norm": 0.61328125,
434
+ "learning_rate": 9.973813253414745e-05,
435
+ "loss": 0.9432,
436
+ "step": 610
437
+ },
438
+ {
439
+ "epoch": 0.16,
440
+ "grad_norm": 0.625,
441
+ "learning_rate": 9.971519410309473e-05,
442
+ "loss": 0.9608,
443
+ "step": 620
444
+ },
445
+ {
446
+ "epoch": 0.17,
447
+ "grad_norm": 0.67578125,
448
+ "learning_rate": 9.969129561377484e-05,
449
+ "loss": 0.9389,
450
+ "step": 630
451
+ },
452
+ {
453
+ "epoch": 0.17,
454
+ "grad_norm": 0.6328125,
455
+ "learning_rate": 9.966643752769542e-05,
456
+ "loss": 0.8911,
457
+ "step": 640
458
+ },
459
+ {
460
+ "epoch": 0.17,
461
+ "grad_norm": 0.57421875,
462
+ "learning_rate": 9.964062032489505e-05,
463
+ "loss": 0.9216,
464
+ "step": 650
465
+ },
466
+ {
467
+ "epoch": 0.18,
468
+ "grad_norm": 0.546875,
469
+ "learning_rate": 9.961384450393397e-05,
470
+ "loss": 0.9208,
471
+ "step": 660
472
+ },
473
+ {
474
+ "epoch": 0.18,
475
+ "grad_norm": 0.59375,
476
+ "learning_rate": 9.958611058188445e-05,
477
+ "loss": 0.9267,
478
+ "step": 670
479
+ },
480
+ {
481
+ "epoch": 0.18,
482
+ "grad_norm": 0.58984375,
483
+ "learning_rate": 9.955741909432082e-05,
484
+ "loss": 0.9916,
485
+ "step": 680
486
+ },
487
+ {
488
+ "epoch": 0.18,
489
+ "grad_norm": 0.56640625,
490
+ "learning_rate": 9.952777059530906e-05,
491
+ "loss": 0.9112,
492
+ "step": 690
493
+ },
494
+ {
495
+ "epoch": 0.19,
496
+ "grad_norm": 0.578125,
497
+ "learning_rate": 9.949716565739625e-05,
498
+ "loss": 0.9242,
499
+ "step": 700
500
+ },
501
+ {
502
+ "epoch": 0.19,
503
+ "grad_norm": 0.5703125,
504
+ "learning_rate": 9.946560487159932e-05,
505
+ "loss": 0.9561,
506
+ "step": 710
507
+ },
508
+ {
509
+ "epoch": 0.19,
510
+ "grad_norm": 0.609375,
511
+ "learning_rate": 9.943308884739382e-05,
512
+ "loss": 0.9406,
513
+ "step": 720
514
+ },
515
+ {
516
+ "epoch": 0.19,
517
+ "grad_norm": 0.63671875,
518
+ "learning_rate": 9.9399618212702e-05,
519
+ "loss": 0.9006,
520
+ "step": 730
521
+ },
522
+ {
523
+ "epoch": 0.2,
524
+ "grad_norm": 0.59375,
525
+ "learning_rate": 9.93651936138808e-05,
526
+ "loss": 0.9676,
527
+ "step": 740
528
+ },
529
+ {
530
+ "epoch": 0.2,
531
+ "grad_norm": 0.54296875,
532
+ "learning_rate": 9.932981571570926e-05,
533
+ "loss": 0.9274,
534
+ "step": 750
535
+ },
536
+ {
537
+ "epoch": 0.2,
538
+ "grad_norm": 0.578125,
539
+ "learning_rate": 9.929348520137581e-05,
540
+ "loss": 0.9335,
541
+ "step": 760
542
+ },
543
+ {
544
+ "epoch": 0.2,
545
+ "grad_norm": 0.5703125,
546
+ "learning_rate": 9.925620277246493e-05,
547
+ "loss": 0.9312,
548
+ "step": 770
549
+ },
550
+ {
551
+ "epoch": 0.21,
552
+ "grad_norm": 0.6015625,
553
+ "learning_rate": 9.921796914894375e-05,
554
+ "loss": 0.928,
555
+ "step": 780
556
+ },
557
+ {
558
+ "epoch": 0.21,
559
+ "grad_norm": 0.6328125,
560
+ "learning_rate": 9.917878506914804e-05,
561
+ "loss": 0.9511,
562
+ "step": 790
563
+ },
564
+ {
565
+ "epoch": 0.21,
566
+ "grad_norm": 0.5546875,
567
+ "learning_rate": 9.913865128976799e-05,
568
+ "loss": 0.9327,
569
+ "step": 800
570
+ },
571
+ {
572
+ "epoch": 0.22,
573
+ "grad_norm": 0.53515625,
574
+ "learning_rate": 9.909756858583358e-05,
575
+ "loss": 0.9288,
576
+ "step": 810
577
+ },
578
+ {
579
+ "epoch": 0.22,
580
+ "grad_norm": 0.6171875,
581
+ "learning_rate": 9.905553775069969e-05,
582
+ "loss": 0.9358,
583
+ "step": 820
584
+ },
585
+ {
586
+ "epoch": 0.22,
587
+ "grad_norm": 0.58203125,
588
+ "learning_rate": 9.901255959603061e-05,
589
+ "loss": 0.9137,
590
+ "step": 830
591
+ },
592
+ {
593
+ "epoch": 0.22,
594
+ "grad_norm": 0.53515625,
595
+ "learning_rate": 9.896863495178458e-05,
596
+ "loss": 0.9261,
597
+ "step": 840
598
+ },
599
+ {
600
+ "epoch": 0.23,
601
+ "grad_norm": 0.56640625,
602
+ "learning_rate": 9.892376466619759e-05,
603
+ "loss": 0.9326,
604
+ "step": 850
605
+ },
606
+ {
607
+ "epoch": 0.23,
608
+ "grad_norm": 0.5390625,
609
+ "learning_rate": 9.887794960576709e-05,
610
+ "loss": 0.9564,
611
+ "step": 860
612
+ },
613
+ {
614
+ "epoch": 0.23,
615
+ "grad_norm": 0.62890625,
616
+ "learning_rate": 9.88311906552352e-05,
617
+ "loss": 0.9746,
618
+ "step": 870
619
+ },
620
+ {
621
+ "epoch": 0.23,
622
+ "grad_norm": 0.64453125,
623
+ "learning_rate": 9.878348871757172e-05,
624
+ "loss": 0.9124,
625
+ "step": 880
626
+ },
627
+ {
628
+ "epoch": 0.24,
629
+ "grad_norm": 0.55859375,
630
+ "learning_rate": 9.873484471395657e-05,
631
+ "loss": 0.9387,
632
+ "step": 890
633
+ },
634
+ {
635
+ "epoch": 0.24,
636
+ "grad_norm": 0.58984375,
637
+ "learning_rate": 9.868525958376211e-05,
638
+ "loss": 0.9203,
639
+ "step": 900
640
+ },
641
+ {
642
+ "epoch": 0.24,
643
+ "grad_norm": 0.59765625,
644
+ "learning_rate": 9.863473428453489e-05,
645
+ "loss": 0.9368,
646
+ "step": 910
647
+ },
648
+ {
649
+ "epoch": 0.24,
650
+ "grad_norm": 0.609375,
651
+ "learning_rate": 9.858326979197725e-05,
652
+ "loss": 0.9269,
653
+ "step": 920
654
+ },
655
+ {
656
+ "epoch": 0.25,
657
+ "grad_norm": 0.59765625,
658
+ "learning_rate": 9.853086709992847e-05,
659
+ "loss": 0.9522,
660
+ "step": 930
661
+ },
662
+ {
663
+ "epoch": 0.25,
664
+ "grad_norm": 0.62890625,
665
+ "learning_rate": 9.84775272203455e-05,
666
+ "loss": 0.8991,
667
+ "step": 940
668
+ },
669
+ {
670
+ "epoch": 0.25,
671
+ "grad_norm": 0.609375,
672
+ "learning_rate": 9.842325118328355e-05,
673
+ "loss": 0.9445,
674
+ "step": 950
675
+ },
676
+ {
677
+ "epoch": 0.26,
678
+ "grad_norm": 0.5234375,
679
+ "learning_rate": 9.836804003687601e-05,
680
+ "loss": 0.89,
681
+ "step": 960
682
+ },
683
+ {
684
+ "epoch": 0.26,
685
+ "grad_norm": 0.56640625,
686
+ "learning_rate": 9.831189484731444e-05,
687
+ "loss": 0.9024,
688
+ "step": 970
689
+ },
690
+ {
691
+ "epoch": 0.26,
692
+ "grad_norm": 0.5859375,
693
+ "learning_rate": 9.825481669882779e-05,
694
+ "loss": 0.9287,
695
+ "step": 980
696
+ },
697
+ {
698
+ "epoch": 0.26,
699
+ "grad_norm": 0.578125,
700
+ "learning_rate": 9.819680669366152e-05,
701
+ "loss": 0.9556,
702
+ "step": 990
703
+ },
704
+ {
705
+ "epoch": 0.27,
706
+ "grad_norm": 0.53515625,
707
+ "learning_rate": 9.813786595205638e-05,
708
+ "loss": 0.9178,
709
+ "step": 1000
710
+ },
711
+ {
712
+ "epoch": 0.27,
713
+ "grad_norm": 0.58203125,
714
+ "learning_rate": 9.80779956122267e-05,
715
+ "loss": 0.9137,
716
+ "step": 1010
717
+ },
718
+ {
719
+ "epoch": 0.27,
720
+ "grad_norm": 0.62109375,
721
+ "learning_rate": 9.801719683033841e-05,
722
+ "loss": 0.9491,
723
+ "step": 1020
724
+ },
725
+ {
726
+ "epoch": 0.27,
727
+ "grad_norm": 0.59765625,
728
+ "learning_rate": 9.795547078048677e-05,
729
+ "loss": 0.8831,
730
+ "step": 1030
731
+ },
732
+ {
733
+ "epoch": 0.28,
734
+ "grad_norm": 0.671875,
735
+ "learning_rate": 9.789281865467366e-05,
736
+ "loss": 0.8694,
737
+ "step": 1040
738
+ },
739
+ {
740
+ "epoch": 0.28,
741
+ "grad_norm": 0.53515625,
742
+ "learning_rate": 9.782924166278455e-05,
743
+ "loss": 0.9005,
744
+ "step": 1050
745
+ },
746
+ {
747
+ "epoch": 0.28,
748
+ "grad_norm": 0.58203125,
749
+ "learning_rate": 9.776474103256517e-05,
750
+ "loss": 0.8902,
751
+ "step": 1060
752
+ },
753
+ {
754
+ "epoch": 0.28,
755
+ "grad_norm": 0.76171875,
756
+ "learning_rate": 9.769931800959775e-05,
757
+ "loss": 0.9136,
758
+ "step": 1070
759
+ },
760
+ {
761
+ "epoch": 0.29,
762
+ "grad_norm": 0.6328125,
763
+ "learning_rate": 9.763297385727702e-05,
764
+ "loss": 0.8951,
765
+ "step": 1080
766
+ },
767
+ {
768
+ "epoch": 0.29,
769
+ "grad_norm": 0.5859375,
770
+ "learning_rate": 9.75657098567858e-05,
771
+ "loss": 0.9387,
772
+ "step": 1090
773
+ },
774
+ {
775
+ "epoch": 0.29,
776
+ "grad_norm": 0.5859375,
777
+ "learning_rate": 9.749752730707022e-05,
778
+ "loss": 0.9281,
779
+ "step": 1100
780
+ },
781
+ {
782
+ "epoch": 0.29,
783
+ "grad_norm": 0.59375,
784
+ "learning_rate": 9.742842752481469e-05,
785
+ "loss": 0.9463,
786
+ "step": 1110
787
+ },
788
+ {
789
+ "epoch": 0.3,
790
+ "grad_norm": 0.55078125,
791
+ "learning_rate": 9.735841184441642e-05,
792
+ "loss": 0.9071,
793
+ "step": 1120
794
+ },
795
+ {
796
+ "epoch": 0.3,
797
+ "grad_norm": 0.5390625,
798
+ "learning_rate": 9.728748161795975e-05,
799
+ "loss": 0.9023,
800
+ "step": 1130
801
+ },
802
+ {
803
+ "epoch": 0.3,
804
+ "grad_norm": 0.61328125,
805
+ "learning_rate": 9.721563821518985e-05,
806
+ "loss": 0.8959,
807
+ "step": 1140
808
+ },
809
+ {
810
+ "epoch": 0.31,
811
+ "grad_norm": 0.578125,
812
+ "learning_rate": 9.71428830234865e-05,
813
+ "loss": 0.8821,
814
+ "step": 1150
815
+ },
816
+ {
817
+ "epoch": 0.31,
818
+ "grad_norm": 0.5625,
819
+ "learning_rate": 9.706921744783711e-05,
820
+ "loss": 0.9091,
821
+ "step": 1160
822
+ },
823
+ {
824
+ "epoch": 0.31,
825
+ "grad_norm": 0.55859375,
826
+ "learning_rate": 9.699464291080971e-05,
827
+ "loss": 0.9106,
828
+ "step": 1170
829
+ },
830
+ {
831
+ "epoch": 0.31,
832
+ "grad_norm": 0.5234375,
833
+ "learning_rate": 9.691916085252542e-05,
834
+ "loss": 0.9162,
835
+ "step": 1180
836
+ },
837
+ {
838
+ "epoch": 0.32,
839
+ "grad_norm": 0.5703125,
840
+ "learning_rate": 9.684277273063063e-05,
841
+ "loss": 0.8817,
842
+ "step": 1190
843
+ },
844
+ {
845
+ "epoch": 0.32,
846
+ "grad_norm": 0.5703125,
847
+ "learning_rate": 9.676548002026891e-05,
848
+ "loss": 0.927,
849
+ "step": 1200
850
+ },
851
+ {
852
+ "epoch": 0.32,
853
+ "grad_norm": 0.55859375,
854
+ "learning_rate": 9.668728421405244e-05,
855
+ "loss": 0.9056,
856
+ "step": 1210
857
+ },
858
+ {
859
+ "epoch": 0.32,
860
+ "grad_norm": 0.59765625,
861
+ "learning_rate": 9.660818682203329e-05,
862
+ "loss": 0.9427,
863
+ "step": 1220
864
+ },
865
+ {
866
+ "epoch": 0.33,
867
+ "grad_norm": 0.6015625,
868
+ "learning_rate": 9.652818937167414e-05,
869
+ "loss": 0.8913,
870
+ "step": 1230
871
+ },
872
+ {
873
+ "epoch": 0.33,
874
+ "grad_norm": 0.63671875,
875
+ "learning_rate": 9.644729340781891e-05,
876
+ "loss": 0.8917,
877
+ "step": 1240
878
+ },
879
+ {
880
+ "epoch": 0.33,
881
+ "grad_norm": 0.54296875,
882
+ "learning_rate": 9.636550049266279e-05,
883
+ "loss": 0.9113,
884
+ "step": 1250
885
+ },
886
+ {
887
+ "epoch": 0.33,
888
+ "grad_norm": 0.54296875,
889
+ "learning_rate": 9.628281220572219e-05,
890
+ "loss": 0.8855,
891
+ "step": 1260
892
+ },
893
+ {
894
+ "epoch": 0.34,
895
+ "grad_norm": 0.59765625,
896
+ "learning_rate": 9.61992301438042e-05,
897
+ "loss": 0.8983,
898
+ "step": 1270
899
+ },
900
+ {
901
+ "epoch": 0.34,
902
+ "grad_norm": 0.58203125,
903
+ "learning_rate": 9.611475592097573e-05,
904
+ "loss": 0.8913,
905
+ "step": 1280
906
+ },
907
+ {
908
+ "epoch": 0.34,
909
+ "grad_norm": 0.62109375,
910
+ "learning_rate": 9.60293911685323e-05,
911
+ "loss": 0.9059,
912
+ "step": 1290
913
+ },
914
+ {
915
+ "epoch": 0.35,
916
+ "grad_norm": 0.546875,
917
+ "learning_rate": 9.59431375349667e-05,
918
+ "loss": 0.885,
919
+ "step": 1300
920
+ },
921
+ {
922
+ "epoch": 0.35,
923
+ "grad_norm": 0.57421875,
924
+ "learning_rate": 9.585599668593697e-05,
925
+ "loss": 0.8822,
926
+ "step": 1310
927
+ },
928
+ {
929
+ "epoch": 0.35,
930
+ "grad_norm": 0.58203125,
931
+ "learning_rate": 9.576797030423433e-05,
932
+ "loss": 0.8779,
933
+ "step": 1320
934
+ },
935
+ {
936
+ "epoch": 0.35,
937
+ "grad_norm": 0.60546875,
938
+ "learning_rate": 9.56790600897507e-05,
939
+ "loss": 0.8948,
940
+ "step": 1330
941
+ },
942
+ {
943
+ "epoch": 0.36,
944
+ "grad_norm": 0.55078125,
945
+ "learning_rate": 9.558926775944578e-05,
946
+ "loss": 0.9469,
947
+ "step": 1340
948
+ },
949
+ {
950
+ "epoch": 0.36,
951
+ "grad_norm": 0.53515625,
952
+ "learning_rate": 9.549859504731403e-05,
953
+ "loss": 0.9131,
954
+ "step": 1350
955
+ },
956
+ {
957
+ "epoch": 0.36,
958
+ "grad_norm": 0.56640625,
959
+ "learning_rate": 9.540704370435103e-05,
960
+ "loss": 0.8824,
961
+ "step": 1360
962
+ },
963
+ {
964
+ "epoch": 0.36,
965
+ "grad_norm": 0.58984375,
966
+ "learning_rate": 9.53146154985198e-05,
967
+ "loss": 0.9077,
968
+ "step": 1370
969
+ },
970
+ {
971
+ "epoch": 0.37,
972
+ "grad_norm": 0.5859375,
973
+ "learning_rate": 9.522131221471658e-05,
974
+ "loss": 0.9165,
975
+ "step": 1380
976
+ },
977
+ {
978
+ "epoch": 0.37,
979
+ "grad_norm": 0.62890625,
980
+ "learning_rate": 9.512713565473637e-05,
981
+ "loss": 0.8911,
982
+ "step": 1390
983
+ },
984
+ {
985
+ "epoch": 0.37,
986
+ "grad_norm": 0.609375,
987
+ "learning_rate": 9.503208763723816e-05,
988
+ "loss": 0.8966,
989
+ "step": 1400
990
+ },
991
+ {
992
+ "epoch": 0.37,
993
+ "grad_norm": 0.609375,
994
+ "learning_rate": 9.493616999770984e-05,
995
+ "loss": 0.8911,
996
+ "step": 1410
997
+ },
998
+ {
999
+ "epoch": 0.38,
1000
+ "grad_norm": 0.6015625,
1001
+ "learning_rate": 9.483938458843267e-05,
1002
+ "loss": 0.9013,
1003
+ "step": 1420
1004
+ },
1005
+ {
1006
+ "epoch": 0.38,
1007
+ "grad_norm": 0.6015625,
1008
+ "learning_rate": 9.474173327844554e-05,
1009
+ "loss": 0.8688,
1010
+ "step": 1430
1011
+ },
1012
+ {
1013
+ "epoch": 0.38,
1014
+ "grad_norm": 0.58984375,
1015
+ "learning_rate": 9.464321795350891e-05,
1016
+ "loss": 0.886,
1017
+ "step": 1440
1018
+ },
1019
+ {
1020
+ "epoch": 0.39,
1021
+ "grad_norm": 0.5546875,
1022
+ "learning_rate": 9.454384051606841e-05,
1023
+ "loss": 0.8946,
1024
+ "step": 1450
1025
+ },
1026
+ {
1027
+ "epoch": 0.39,
1028
+ "grad_norm": 0.62109375,
1029
+ "learning_rate": 9.4443602885218e-05,
1030
+ "loss": 0.9075,
1031
+ "step": 1460
1032
+ },
1033
+ {
1034
+ "epoch": 0.39,
1035
+ "grad_norm": 0.56640625,
1036
+ "learning_rate": 9.434250699666305e-05,
1037
+ "loss": 0.884,
1038
+ "step": 1470
1039
+ },
1040
+ {
1041
+ "epoch": 0.39,
1042
+ "grad_norm": 0.5625,
1043
+ "learning_rate": 9.424055480268282e-05,
1044
+ "loss": 0.886,
1045
+ "step": 1480
1046
+ },
1047
+ {
1048
+ "epoch": 0.4,
1049
+ "grad_norm": 0.515625,
1050
+ "learning_rate": 9.413774827209283e-05,
1051
+ "loss": 0.859,
1052
+ "step": 1490
1053
+ },
1054
+ {
1055
+ "epoch": 0.4,
1056
+ "grad_norm": 0.65625,
1057
+ "learning_rate": 9.403408939020688e-05,
1058
+ "loss": 0.9026,
1059
+ "step": 1500
1060
+ },
1061
+ {
1062
+ "epoch": 0.4,
1063
+ "grad_norm": 0.62890625,
1064
+ "learning_rate": 9.392958015879862e-05,
1065
+ "loss": 0.8912,
1066
+ "step": 1510
1067
+ },
1068
+ {
1069
+ "epoch": 0.4,
1070
+ "grad_norm": 0.52734375,
1071
+ "learning_rate": 9.382422259606299e-05,
1072
+ "loss": 0.8833,
1073
+ "step": 1520
1074
+ },
1075
+ {
1076
+ "epoch": 0.41,
1077
+ "grad_norm": 0.55078125,
1078
+ "learning_rate": 9.371801873657714e-05,
1079
+ "loss": 0.8999,
1080
+ "step": 1530
1081
+ },
1082
+ {
1083
+ "epoch": 0.41,
1084
+ "grad_norm": 0.65625,
1085
+ "learning_rate": 9.361097063126123e-05,
1086
+ "loss": 0.867,
1087
+ "step": 1540
1088
+ },
1089
+ {
1090
+ "epoch": 0.41,
1091
+ "grad_norm": 0.55859375,
1092
+ "learning_rate": 9.350308034733876e-05,
1093
+ "loss": 0.8837,
1094
+ "step": 1550
1095
+ },
1096
+ {
1097
+ "epoch": 0.41,
1098
+ "grad_norm": 0.55859375,
1099
+ "learning_rate": 9.339434996829671e-05,
1100
+ "loss": 0.9047,
1101
+ "step": 1560
1102
+ },
1103
+ {
1104
+ "epoch": 0.42,
1105
+ "grad_norm": 0.5546875,
1106
+ "learning_rate": 9.328478159384528e-05,
1107
+ "loss": 0.9031,
1108
+ "step": 1570
1109
+ },
1110
+ {
1111
+ "epoch": 0.42,
1112
+ "grad_norm": 0.65625,
1113
+ "learning_rate": 9.317437733987728e-05,
1114
+ "loss": 0.9045,
1115
+ "step": 1580
1116
+ },
1117
+ {
1118
+ "epoch": 0.42,
1119
+ "grad_norm": 0.59765625,
1120
+ "learning_rate": 9.30631393384274e-05,
1121
+ "loss": 0.8824,
1122
+ "step": 1590
1123
+ },
1124
+ {
1125
+ "epoch": 0.43,
1126
+ "grad_norm": 0.5703125,
1127
+ "learning_rate": 9.295106973763092e-05,
1128
+ "loss": 0.884,
1129
+ "step": 1600
1130
+ },
1131
+ {
1132
+ "epoch": 0.43,
1133
+ "grad_norm": 0.62109375,
1134
+ "learning_rate": 9.283817070168228e-05,
1135
+ "loss": 0.8711,
1136
+ "step": 1610
1137
+ },
1138
+ {
1139
+ "epoch": 0.43,
1140
+ "grad_norm": 0.59765625,
1141
+ "learning_rate": 9.272444441079328e-05,
1142
+ "loss": 0.9078,
1143
+ "step": 1620
1144
+ },
1145
+ {
1146
+ "epoch": 0.43,
1147
+ "grad_norm": 0.578125,
1148
+ "learning_rate": 9.260989306115097e-05,
1149
+ "loss": 0.9101,
1150
+ "step": 1630
1151
+ },
1152
+ {
1153
+ "epoch": 0.44,
1154
+ "grad_norm": 0.63671875,
1155
+ "learning_rate": 9.249451886487527e-05,
1156
+ "loss": 0.8564,
1157
+ "step": 1640
1158
+ },
1159
+ {
1160
+ "epoch": 0.44,
1161
+ "grad_norm": 0.5234375,
1162
+ "learning_rate": 9.237832404997619e-05,
1163
+ "loss": 0.8943,
1164
+ "step": 1650
1165
+ },
1166
+ {
1167
+ "epoch": 0.44,
1168
+ "grad_norm": 0.58203125,
1169
+ "learning_rate": 9.226131086031084e-05,
1170
+ "loss": 0.88,
1171
+ "step": 1660
1172
+ },
1173
+ {
1174
+ "epoch": 0.44,
1175
+ "grad_norm": 0.640625,
1176
+ "learning_rate": 9.214348155554017e-05,
1177
+ "loss": 0.9152,
1178
+ "step": 1670
1179
+ },
1180
+ {
1181
+ "epoch": 0.45,
1182
+ "grad_norm": 0.56640625,
1183
+ "learning_rate": 9.202483841108516e-05,
1184
+ "loss": 0.9052,
1185
+ "step": 1680
1186
+ },
1187
+ {
1188
+ "epoch": 0.45,
1189
+ "grad_norm": 0.58984375,
1190
+ "learning_rate": 9.190538371808306e-05,
1191
+ "loss": 0.9448,
1192
+ "step": 1690
1193
+ },
1194
+ {
1195
+ "epoch": 0.45,
1196
+ "grad_norm": 0.58984375,
1197
+ "learning_rate": 9.178511978334302e-05,
1198
+ "loss": 0.9137,
1199
+ "step": 1700
1200
+ },
1201
+ {
1202
+ "epoch": 0.45,
1203
+ "grad_norm": 0.53515625,
1204
+ "learning_rate": 9.166404892930163e-05,
1205
+ "loss": 0.8743,
1206
+ "step": 1710
1207
+ },
1208
+ {
1209
+ "epoch": 0.46,
1210
+ "grad_norm": 0.55859375,
1211
+ "learning_rate": 9.154217349397797e-05,
1212
+ "loss": 0.8898,
1213
+ "step": 1720
1214
+ },
1215
+ {
1216
+ "epoch": 0.46,
1217
+ "grad_norm": 0.5078125,
1218
+ "learning_rate": 9.141949583092862e-05,
1219
+ "loss": 0.8972,
1220
+ "step": 1730
1221
+ },
1222
+ {
1223
+ "epoch": 0.46,
1224
+ "grad_norm": 0.59765625,
1225
+ "learning_rate": 9.129601830920199e-05,
1226
+ "loss": 0.9058,
1227
+ "step": 1740
1228
+ },
1229
+ {
1230
+ "epoch": 0.46,
1231
+ "grad_norm": 0.5625,
1232
+ "learning_rate": 9.117174331329279e-05,
1233
+ "loss": 0.8856,
1234
+ "step": 1750
1235
+ },
1236
+ {
1237
+ "epoch": 0.47,
1238
+ "grad_norm": 0.63671875,
1239
+ "learning_rate": 9.104667324309584e-05,
1240
+ "loss": 0.9284,
1241
+ "step": 1760
1242
+ },
1243
+ {
1244
+ "epoch": 0.47,
1245
+ "grad_norm": 0.55078125,
1246
+ "learning_rate": 9.09208105138598e-05,
1247
+ "loss": 0.8588,
1248
+ "step": 1770
1249
+ },
1250
+ {
1251
+ "epoch": 0.47,
1252
+ "grad_norm": 0.60546875,
1253
+ "learning_rate": 9.079415755614043e-05,
1254
+ "loss": 0.864,
1255
+ "step": 1780
1256
+ },
1257
+ {
1258
+ "epoch": 0.48,
1259
+ "grad_norm": 0.625,
1260
+ "learning_rate": 9.066671681575381e-05,
1261
+ "loss": 0.8598,
1262
+ "step": 1790
1263
+ },
1264
+ {
1265
+ "epoch": 0.48,
1266
+ "grad_norm": 0.53125,
1267
+ "learning_rate": 9.053849075372896e-05,
1268
+ "loss": 0.8958,
1269
+ "step": 1800
1270
+ },
1271
+ {
1272
+ "epoch": 0.48,
1273
+ "grad_norm": 0.55859375,
1274
+ "learning_rate": 9.04094818462604e-05,
1275
+ "loss": 0.8825,
1276
+ "step": 1810
1277
+ },
1278
+ {
1279
+ "epoch": 0.48,
1280
+ "grad_norm": 0.53125,
1281
+ "learning_rate": 9.027969258466028e-05,
1282
+ "loss": 0.8588,
1283
+ "step": 1820
1284
+ },
1285
+ {
1286
+ "epoch": 0.49,
1287
+ "grad_norm": 0.625,
1288
+ "learning_rate": 9.014912547531035e-05,
1289
+ "loss": 0.8823,
1290
+ "step": 1830
1291
+ },
1292
+ {
1293
+ "epoch": 0.49,
1294
+ "grad_norm": 0.5859375,
1295
+ "learning_rate": 9.001778303961347e-05,
1296
+ "loss": 0.8756,
1297
+ "step": 1840
1298
+ },
1299
+ {
1300
+ "epoch": 0.49,
1301
+ "grad_norm": 0.609375,
1302
+ "learning_rate": 8.988566781394494e-05,
1303
+ "loss": 0.8584,
1304
+ "step": 1850
1305
+ },
1306
+ {
1307
+ "epoch": 0.49,
1308
+ "grad_norm": 0.63671875,
1309
+ "learning_rate": 8.975278234960356e-05,
1310
+ "loss": 0.8751,
1311
+ "step": 1860
1312
+ },
1313
+ {
1314
+ "epoch": 0.5,
1315
+ "grad_norm": 0.578125,
1316
+ "learning_rate": 8.961912921276233e-05,
1317
+ "loss": 0.8916,
1318
+ "step": 1870
1319
+ },
1320
+ {
1321
+ "epoch": 0.5,
1322
+ "grad_norm": 0.5625,
1323
+ "learning_rate": 8.948471098441888e-05,
1324
+ "loss": 0.9203,
1325
+ "step": 1880
1326
+ },
1327
+ {
1328
+ "epoch": 0.5,
1329
+ "grad_norm": 0.58984375,
1330
+ "learning_rate": 8.93495302603457e-05,
1331
+ "loss": 0.8742,
1332
+ "step": 1890
1333
+ },
1334
+ {
1335
+ "epoch": 0.5,
1336
+ "grad_norm": 0.5546875,
1337
+ "learning_rate": 8.921358965103987e-05,
1338
+ "loss": 0.8846,
1339
+ "step": 1900
1340
+ },
1341
+ {
1342
+ "epoch": 0.51,
1343
+ "grad_norm": 0.5234375,
1344
+ "learning_rate": 8.907689178167284e-05,
1345
+ "loss": 0.9182,
1346
+ "step": 1910
1347
+ },
1348
+ {
1349
+ "epoch": 0.51,
1350
+ "grad_norm": 0.6640625,
1351
+ "learning_rate": 8.893943929203956e-05,
1352
+ "loss": 0.8928,
1353
+ "step": 1920
1354
+ },
1355
+ {
1356
+ "epoch": 0.51,
1357
+ "grad_norm": 0.7109375,
1358
+ "learning_rate": 8.880123483650761e-05,
1359
+ "loss": 0.877,
1360
+ "step": 1930
1361
+ },
1362
+ {
1363
+ "epoch": 0.52,
1364
+ "grad_norm": 0.62890625,
1365
+ "learning_rate": 8.866228108396589e-05,
1366
+ "loss": 0.9393,
1367
+ "step": 1940
1368
+ },
1369
+ {
1370
+ "epoch": 0.52,
1371
+ "grad_norm": 0.578125,
1372
+ "learning_rate": 8.852258071777311e-05,
1373
+ "loss": 0.8798,
1374
+ "step": 1950
1375
+ },
1376
+ {
1377
+ "epoch": 0.52,
1378
+ "grad_norm": 0.56640625,
1379
+ "learning_rate": 8.838213643570596e-05,
1380
+ "loss": 0.9169,
1381
+ "step": 1960
1382
+ },
1383
+ {
1384
+ "epoch": 0.52,
1385
+ "grad_norm": 0.55859375,
1386
+ "learning_rate": 8.8240950949907e-05,
1387
+ "loss": 0.9119,
1388
+ "step": 1970
1389
+ },
1390
+ {
1391
+ "epoch": 0.53,
1392
+ "grad_norm": 0.59765625,
1393
+ "learning_rate": 8.80990269868323e-05,
1394
+ "loss": 0.8856,
1395
+ "step": 1980
1396
+ },
1397
+ {
1398
+ "epoch": 0.53,
1399
+ "grad_norm": 0.55859375,
1400
+ "learning_rate": 8.79563672871988e-05,
1401
+ "loss": 0.8635,
1402
+ "step": 1990
1403
+ },
1404
+ {
1405
+ "epoch": 0.53,
1406
+ "grad_norm": 0.56640625,
1407
+ "learning_rate": 8.781297460593134e-05,
1408
+ "loss": 0.9004,
1409
+ "step": 2000
1410
+ },
1411
+ {
1412
+ "epoch": 0.53,
1413
+ "grad_norm": 0.55859375,
1414
+ "learning_rate": 8.766885171210952e-05,
1415
+ "loss": 0.8884,
1416
+ "step": 2010
1417
+ },
1418
+ {
1419
+ "epoch": 0.54,
1420
+ "grad_norm": 0.609375,
1421
+ "learning_rate": 8.752400138891417e-05,
1422
+ "loss": 0.8833,
1423
+ "step": 2020
1424
+ },
1425
+ {
1426
+ "epoch": 0.54,
1427
+ "grad_norm": 0.5859375,
1428
+ "learning_rate": 8.737842643357364e-05,
1429
+ "loss": 0.8642,
1430
+ "step": 2030
1431
+ },
1432
+ {
1433
+ "epoch": 0.54,
1434
+ "grad_norm": 0.52734375,
1435
+ "learning_rate": 8.723212965730977e-05,
1436
+ "loss": 0.9122,
1437
+ "step": 2040
1438
+ },
1439
+ {
1440
+ "epoch": 0.54,
1441
+ "grad_norm": 0.6015625,
1442
+ "learning_rate": 8.708511388528359e-05,
1443
+ "loss": 0.8477,
1444
+ "step": 2050
1445
+ },
1446
+ {
1447
+ "epoch": 0.55,
1448
+ "grad_norm": 0.6484375,
1449
+ "learning_rate": 8.693738195654083e-05,
1450
+ "loss": 0.8899,
1451
+ "step": 2060
1452
+ },
1453
+ {
1454
+ "epoch": 0.55,
1455
+ "grad_norm": 0.578125,
1456
+ "learning_rate": 8.678893672395694e-05,
1457
+ "loss": 0.8998,
1458
+ "step": 2070
1459
+ },
1460
+ {
1461
+ "epoch": 0.55,
1462
+ "grad_norm": 0.61328125,
1463
+ "learning_rate": 8.663978105418218e-05,
1464
+ "loss": 0.9143,
1465
+ "step": 2080
1466
+ },
1467
+ {
1468
+ "epoch": 0.56,
1469
+ "grad_norm": 0.6015625,
1470
+ "learning_rate": 8.648991782758615e-05,
1471
+ "loss": 0.8821,
1472
+ "step": 2090
1473
+ },
1474
+ {
1475
+ "epoch": 0.56,
1476
+ "grad_norm": 0.5703125,
1477
+ "learning_rate": 8.633934993820221e-05,
1478
+ "loss": 0.9078,
1479
+ "step": 2100
1480
+ },
1481
+ {
1482
+ "epoch": 0.56,
1483
+ "grad_norm": 0.54296875,
1484
+ "learning_rate": 8.618808029367154e-05,
1485
+ "loss": 0.8885,
1486
+ "step": 2110
1487
+ },
1488
+ {
1489
+ "epoch": 0.56,
1490
+ "grad_norm": 0.6015625,
1491
+ "learning_rate": 8.603611181518707e-05,
1492
+ "loss": 0.9024,
1493
+ "step": 2120
1494
+ },
1495
+ {
1496
+ "epoch": 0.57,
1497
+ "grad_norm": 0.54296875,
1498
+ "learning_rate": 8.5883447437437e-05,
1499
+ "loss": 0.88,
1500
+ "step": 2130
1501
+ },
1502
+ {
1503
+ "epoch": 0.57,
1504
+ "grad_norm": 0.5625,
1505
+ "learning_rate": 8.57300901085482e-05,
1506
+ "loss": 0.9063,
1507
+ "step": 2140
1508
+ },
1509
+ {
1510
+ "epoch": 0.57,
1511
+ "grad_norm": 0.5703125,
1512
+ "learning_rate": 8.557604279002916e-05,
1513
+ "loss": 0.9013,
1514
+ "step": 2150
1515
+ },
1516
+ {
1517
+ "epoch": 0.57,
1518
+ "grad_norm": 0.5390625,
1519
+ "learning_rate": 8.542130845671295e-05,
1520
+ "loss": 0.8753,
1521
+ "step": 2160
1522
+ },
1523
+ {
1524
+ "epoch": 0.58,
1525
+ "grad_norm": 0.5546875,
1526
+ "learning_rate": 8.526589009669962e-05,
1527
+ "loss": 0.8851,
1528
+ "step": 2170
1529
+ },
1530
+ {
1531
+ "epoch": 0.58,
1532
+ "grad_norm": 0.59375,
1533
+ "learning_rate": 8.510979071129866e-05,
1534
+ "loss": 0.8912,
1535
+ "step": 2180
1536
+ },
1537
+ {
1538
+ "epoch": 0.58,
1539
+ "grad_norm": 0.58984375,
1540
+ "learning_rate": 8.495301331497086e-05,
1541
+ "loss": 0.883,
1542
+ "step": 2190
1543
+ },
1544
+ {
1545
+ "epoch": 0.58,
1546
+ "grad_norm": 0.5234375,
1547
+ "learning_rate": 8.479556093527024e-05,
1548
+ "loss": 0.9103,
1549
+ "step": 2200
1550
+ },
1551
+ {
1552
+ "epoch": 0.59,
1553
+ "grad_norm": 0.55078125,
1554
+ "learning_rate": 8.463743661278555e-05,
1555
+ "loss": 0.9223,
1556
+ "step": 2210
1557
+ },
1558
+ {
1559
+ "epoch": 0.59,
1560
+ "grad_norm": 0.58203125,
1561
+ "learning_rate": 8.44786434010815e-05,
1562
+ "loss": 0.8709,
1563
+ "step": 2220
1564
+ },
1565
+ {
1566
+ "epoch": 0.59,
1567
+ "grad_norm": 0.5625,
1568
+ "learning_rate": 8.431918436663985e-05,
1569
+ "loss": 0.8921,
1570
+ "step": 2230
1571
+ },
1572
+ {
1573
+ "epoch": 0.6,
1574
+ "grad_norm": 0.5390625,
1575
+ "learning_rate": 8.415906258880017e-05,
1576
+ "loss": 0.9002,
1577
+ "step": 2240
1578
+ },
1579
+ {
1580
+ "epoch": 0.6,
1581
+ "grad_norm": 0.57421875,
1582
+ "learning_rate": 8.399828115970037e-05,
1583
+ "loss": 0.8349,
1584
+ "step": 2250
1585
+ },
1586
+ {
1587
+ "epoch": 0.6,
1588
+ "grad_norm": 0.5625,
1589
+ "learning_rate": 8.383684318421699e-05,
1590
+ "loss": 0.8778,
1591
+ "step": 2260
1592
+ },
1593
+ {
1594
+ "epoch": 0.6,
1595
+ "grad_norm": 0.57421875,
1596
+ "learning_rate": 8.367475177990524e-05,
1597
+ "loss": 0.8848,
1598
+ "step": 2270
1599
+ },
1600
+ {
1601
+ "epoch": 0.61,
1602
+ "grad_norm": 0.53125,
1603
+ "learning_rate": 8.351201007693887e-05,
1604
+ "loss": 0.9178,
1605
+ "step": 2280
1606
+ },
1607
+ {
1608
+ "epoch": 0.61,
1609
+ "grad_norm": 0.5546875,
1610
+ "learning_rate": 8.334862121804954e-05,
1611
+ "loss": 0.9152,
1612
+ "step": 2290
1613
+ },
1614
+ {
1615
+ "epoch": 0.61,
1616
+ "grad_norm": 0.56640625,
1617
+ "learning_rate": 8.318458835846633e-05,
1618
+ "loss": 0.869,
1619
+ "step": 2300
1620
+ },
1621
+ {
1622
+ "epoch": 0.61,
1623
+ "grad_norm": 0.62109375,
1624
+ "learning_rate": 8.301991466585465e-05,
1625
+ "loss": 0.8596,
1626
+ "step": 2310
1627
+ },
1628
+ {
1629
+ "epoch": 0.62,
1630
+ "grad_norm": 0.52734375,
1631
+ "learning_rate": 8.285460332025528e-05,
1632
+ "loss": 0.8982,
1633
+ "step": 2320
1634
+ },
1635
+ {
1636
+ "epoch": 0.62,
1637
+ "grad_norm": 0.59765625,
1638
+ "learning_rate": 8.268865751402263e-05,
1639
+ "loss": 0.9094,
1640
+ "step": 2330
1641
+ },
1642
+ {
1643
+ "epoch": 0.62,
1644
+ "grad_norm": 0.55078125,
1645
+ "learning_rate": 8.252208045176342e-05,
1646
+ "loss": 0.9044,
1647
+ "step": 2340
1648
+ },
1649
+ {
1650
+ "epoch": 0.62,
1651
+ "grad_norm": 0.62109375,
1652
+ "learning_rate": 8.235487535027464e-05,
1653
+ "loss": 0.8498,
1654
+ "step": 2350
1655
+ },
1656
+ {
1657
+ "epoch": 0.63,
1658
+ "grad_norm": 0.578125,
1659
+ "learning_rate": 8.218704543848142e-05,
1660
+ "loss": 0.901,
1661
+ "step": 2360
1662
+ },
1663
+ {
1664
+ "epoch": 0.63,
1665
+ "grad_norm": 0.59765625,
1666
+ "learning_rate": 8.201859395737466e-05,
1667
+ "loss": 0.9032,
1668
+ "step": 2370
1669
+ },
1670
+ {
1671
+ "epoch": 0.63,
1672
+ "grad_norm": 0.56640625,
1673
+ "learning_rate": 8.184952415994862e-05,
1674
+ "loss": 0.8685,
1675
+ "step": 2380
1676
+ },
1677
+ {
1678
+ "epoch": 0.63,
1679
+ "grad_norm": 0.5859375,
1680
+ "learning_rate": 8.167983931113783e-05,
1681
+ "loss": 0.8949,
1682
+ "step": 2390
1683
+ },
1684
+ {
1685
+ "epoch": 0.64,
1686
+ "grad_norm": 0.55859375,
1687
+ "learning_rate": 8.150954268775425e-05,
1688
+ "loss": 0.9209,
1689
+ "step": 2400
1690
+ },
1691
+ {
1692
+ "epoch": 0.64,
1693
+ "grad_norm": 0.578125,
1694
+ "learning_rate": 8.133863757842392e-05,
1695
+ "loss": 0.8731,
1696
+ "step": 2410
1697
+ },
1698
+ {
1699
+ "epoch": 0.64,
1700
+ "grad_norm": 0.609375,
1701
+ "learning_rate": 8.116712728352342e-05,
1702
+ "loss": 0.8707,
1703
+ "step": 2420
1704
+ },
1705
+ {
1706
+ "epoch": 0.65,
1707
+ "grad_norm": 0.54296875,
1708
+ "learning_rate": 8.09950151151162e-05,
1709
+ "loss": 0.8692,
1710
+ "step": 2430
1711
+ },
1712
+ {
1713
+ "epoch": 0.65,
1714
+ "grad_norm": 0.51953125,
1715
+ "learning_rate": 8.082230439688856e-05,
1716
+ "loss": 0.909,
1717
+ "step": 2440
1718
+ },
1719
+ {
1720
+ "epoch": 0.65,
1721
+ "grad_norm": 0.61328125,
1722
+ "learning_rate": 8.064899846408549e-05,
1723
+ "loss": 0.8875,
1724
+ "step": 2450
1725
+ },
1726
+ {
1727
+ "epoch": 0.65,
1728
+ "grad_norm": 0.578125,
1729
+ "learning_rate": 8.047510066344632e-05,
1730
+ "loss": 0.8416,
1731
+ "step": 2460
1732
+ },
1733
+ {
1734
+ "epoch": 0.66,
1735
+ "grad_norm": 0.59375,
1736
+ "learning_rate": 8.030061435313998e-05,
1737
+ "loss": 0.8862,
1738
+ "step": 2470
1739
+ },
1740
+ {
1741
+ "epoch": 0.66,
1742
+ "grad_norm": 0.60546875,
1743
+ "learning_rate": 8.012554290270022e-05,
1744
+ "loss": 0.8321,
1745
+ "step": 2480
1746
+ },
1747
+ {
1748
+ "epoch": 0.66,
1749
+ "grad_norm": 0.57421875,
1750
+ "learning_rate": 7.994988969296056e-05,
1751
+ "loss": 0.8797,
1752
+ "step": 2490
1753
+ },
1754
+ {
1755
+ "epoch": 0.66,
1756
+ "grad_norm": 0.55859375,
1757
+ "learning_rate": 7.977365811598891e-05,
1758
+ "loss": 0.9202,
1759
+ "step": 2500
1760
+ },
1761
+ {
1762
+ "epoch": 0.67,
1763
+ "grad_norm": 0.55859375,
1764
+ "learning_rate": 7.959685157502214e-05,
1765
+ "loss": 0.8651,
1766
+ "step": 2510
1767
+ },
1768
+ {
1769
+ "epoch": 0.67,
1770
+ "grad_norm": 0.6171875,
1771
+ "learning_rate": 7.941947348440043e-05,
1772
+ "loss": 0.8979,
1773
+ "step": 2520
1774
+ },
1775
+ {
1776
+ "epoch": 0.67,
1777
+ "grad_norm": 0.5625,
1778
+ "learning_rate": 7.924152726950113e-05,
1779
+ "loss": 0.9025,
1780
+ "step": 2530
1781
+ },
1782
+ {
1783
+ "epoch": 0.67,
1784
+ "grad_norm": 0.69921875,
1785
+ "learning_rate": 7.90630163666728e-05,
1786
+ "loss": 0.8757,
1787
+ "step": 2540
1788
+ },
1789
+ {
1790
+ "epoch": 0.68,
1791
+ "grad_norm": 0.59765625,
1792
+ "learning_rate": 7.888394422316871e-05,
1793
+ "loss": 0.8417,
1794
+ "step": 2550
1795
+ },
1796
+ {
1797
+ "epoch": 0.68,
1798
+ "grad_norm": 0.5859375,
1799
+ "learning_rate": 7.870431429708048e-05,
1800
+ "loss": 0.8608,
1801
+ "step": 2560
1802
+ },
1803
+ {
1804
+ "epoch": 0.68,
1805
+ "grad_norm": 0.55859375,
1806
+ "learning_rate": 7.852413005727102e-05,
1807
+ "loss": 0.8848,
1808
+ "step": 2570
1809
+ },
1810
+ {
1811
+ "epoch": 0.69,
1812
+ "grad_norm": 0.5546875,
1813
+ "learning_rate": 7.834339498330774e-05,
1814
+ "loss": 0.874,
1815
+ "step": 2580
1816
+ },
1817
+ {
1818
+ "epoch": 0.69,
1819
+ "grad_norm": 0.5546875,
1820
+ "learning_rate": 7.81621125653953e-05,
1821
+ "loss": 0.893,
1822
+ "step": 2590
1823
+ },
1824
+ {
1825
+ "epoch": 0.69,
1826
+ "grad_norm": 0.53125,
1827
+ "learning_rate": 7.798028630430822e-05,
1828
+ "loss": 0.89,
1829
+ "step": 2600
1830
+ },
1831
+ {
1832
+ "epoch": 0.69,
1833
+ "grad_norm": 0.51953125,
1834
+ "learning_rate": 7.779791971132323e-05,
1835
+ "loss": 0.8996,
1836
+ "step": 2610
1837
+ },
1838
+ {
1839
+ "epoch": 0.7,
1840
+ "grad_norm": 0.50390625,
1841
+ "learning_rate": 7.761501630815153e-05,
1842
+ "loss": 0.8793,
1843
+ "step": 2620
1844
+ },
1845
+ {
1846
+ "epoch": 0.7,
1847
+ "grad_norm": 0.55078125,
1848
+ "learning_rate": 7.743157962687074e-05,
1849
+ "loss": 0.9115,
1850
+ "step": 2630
1851
+ },
1852
+ {
1853
+ "epoch": 0.7,
1854
+ "grad_norm": 0.54296875,
1855
+ "learning_rate": 7.724761320985667e-05,
1856
+ "loss": 0.8751,
1857
+ "step": 2640
1858
+ },
1859
+ {
1860
+ "epoch": 0.7,
1861
+ "grad_norm": 0.52734375,
1862
+ "learning_rate": 7.7063120609715e-05,
1863
+ "loss": 0.8932,
1864
+ "step": 2650
1865
+ },
1866
+ {
1867
+ "epoch": 0.71,
1868
+ "grad_norm": 0.6328125,
1869
+ "learning_rate": 7.687810538921258e-05,
1870
+ "loss": 0.8566,
1871
+ "step": 2660
1872
+ },
1873
+ {
1874
+ "epoch": 0.71,
1875
+ "grad_norm": 0.5703125,
1876
+ "learning_rate": 7.669257112120868e-05,
1877
+ "loss": 0.8788,
1878
+ "step": 2670
1879
+ },
1880
+ {
1881
+ "epoch": 0.71,
1882
+ "grad_norm": 0.6953125,
1883
+ "learning_rate": 7.650652138858598e-05,
1884
+ "loss": 0.876,
1885
+ "step": 2680
1886
+ },
1887
+ {
1888
+ "epoch": 0.71,
1889
+ "grad_norm": 0.578125,
1890
+ "learning_rate": 7.631995978418136e-05,
1891
+ "loss": 0.8683,
1892
+ "step": 2690
1893
+ },
1894
+ {
1895
+ "epoch": 0.72,
1896
+ "grad_norm": 0.54296875,
1897
+ "learning_rate": 7.61328899107166e-05,
1898
+ "loss": 0.8664,
1899
+ "step": 2700
1900
+ },
1901
+ {
1902
+ "epoch": 0.72,
1903
+ "grad_norm": 0.6484375,
1904
+ "learning_rate": 7.594531538072869e-05,
1905
+ "loss": 0.8716,
1906
+ "step": 2710
1907
+ },
1908
+ {
1909
+ "epoch": 0.72,
1910
+ "grad_norm": 0.54296875,
1911
+ "learning_rate": 7.575723981650014e-05,
1912
+ "loss": 0.846,
1913
+ "step": 2720
1914
+ },
1915
+ {
1916
+ "epoch": 0.73,
1917
+ "grad_norm": 0.52734375,
1918
+ "learning_rate": 7.556866684998901e-05,
1919
+ "loss": 0.9136,
1920
+ "step": 2730
1921
+ },
1922
+ {
1923
+ "epoch": 0.73,
1924
+ "grad_norm": 0.546875,
1925
+ "learning_rate": 7.53796001227588e-05,
1926
+ "loss": 0.9108,
1927
+ "step": 2740
1928
+ },
1929
+ {
1930
+ "epoch": 0.73,
1931
+ "grad_norm": 0.57421875,
1932
+ "learning_rate": 7.519004328590808e-05,
1933
+ "loss": 0.8732,
1934
+ "step": 2750
1935
+ },
1936
+ {
1937
+ "epoch": 0.73,
1938
+ "grad_norm": 0.52734375,
1939
+ "learning_rate": 7.500000000000001e-05,
1940
+ "loss": 0.8896,
1941
+ "step": 2760
1942
+ },
1943
+ {
1944
+ "epoch": 0.74,
1945
+ "grad_norm": 0.51953125,
1946
+ "learning_rate": 7.480947393499164e-05,
1947
+ "loss": 0.893,
1948
+ "step": 2770
1949
+ },
1950
+ {
1951
+ "epoch": 0.74,
1952
+ "grad_norm": 0.52734375,
1953
+ "learning_rate": 7.461846877016313e-05,
1954
+ "loss": 0.8773,
1955
+ "step": 2780
1956
+ },
1957
+ {
1958
+ "epoch": 0.74,
1959
+ "grad_norm": 0.50390625,
1960
+ "learning_rate": 7.442698819404646e-05,
1961
+ "loss": 0.8436,
1962
+ "step": 2790
1963
+ },
1964
+ {
1965
+ "epoch": 0.74,
1966
+ "grad_norm": 0.5234375,
1967
+ "learning_rate": 7.423503590435448e-05,
1968
+ "loss": 0.8713,
1969
+ "step": 2800
1970
+ },
1971
+ {
1972
+ "epoch": 0.75,
1973
+ "grad_norm": 0.55078125,
1974
+ "learning_rate": 7.404261560790936e-05,
1975
+ "loss": 0.8677,
1976
+ "step": 2810
1977
+ },
1978
+ {
1979
+ "epoch": 0.75,
1980
+ "grad_norm": 0.59375,
1981
+ "learning_rate": 7.384973102057093e-05,
1982
+ "loss": 0.8843,
1983
+ "step": 2820
1984
+ },
1985
+ {
1986
+ "epoch": 0.75,
1987
+ "grad_norm": 0.52734375,
1988
+ "learning_rate": 7.365638586716518e-05,
1989
+ "loss": 0.8784,
1990
+ "step": 2830
1991
+ },
1992
+ {
1993
+ "epoch": 0.75,
1994
+ "grad_norm": 0.71484375,
1995
+ "learning_rate": 7.346258388141202e-05,
1996
+ "loss": 0.923,
1997
+ "step": 2840
1998
+ },
1999
+ {
2000
+ "epoch": 0.76,
2001
+ "grad_norm": 0.62109375,
2002
+ "learning_rate": 7.32683288058534e-05,
2003
+ "loss": 0.8936,
2004
+ "step": 2850
2005
+ },
2006
+ {
2007
+ "epoch": 0.76,
2008
+ "grad_norm": 0.5234375,
2009
+ "learning_rate": 7.307362439178095e-05,
2010
+ "loss": 0.8731,
2011
+ "step": 2860
2012
+ },
2013
+ {
2014
+ "epoch": 0.76,
2015
+ "grad_norm": 0.58203125,
2016
+ "learning_rate": 7.287847439916352e-05,
2017
+ "loss": 0.8437,
2018
+ "step": 2870
2019
+ },
2020
+ {
2021
+ "epoch": 0.77,
2022
+ "grad_norm": 0.57421875,
2023
+ "learning_rate": 7.268288259657466e-05,
2024
+ "loss": 0.9006,
2025
+ "step": 2880
2026
+ },
2027
+ {
2028
+ "epoch": 0.77,
2029
+ "grad_norm": 0.60546875,
2030
+ "learning_rate": 7.248685276111973e-05,
2031
+ "loss": 0.895,
2032
+ "step": 2890
2033
+ },
2034
+ {
2035
+ "epoch": 0.77,
2036
+ "grad_norm": 0.53125,
2037
+ "learning_rate": 7.229038867836303e-05,
2038
+ "loss": 0.8383,
2039
+ "step": 2900
2040
+ },
2041
+ {
2042
+ "epoch": 0.77,
2043
+ "grad_norm": 0.546875,
2044
+ "learning_rate": 7.209349414225469e-05,
2045
+ "loss": 0.8743,
2046
+ "step": 2910
2047
+ },
2048
+ {
2049
+ "epoch": 0.78,
2050
+ "grad_norm": 0.578125,
2051
+ "learning_rate": 7.18961729550574e-05,
2052
+ "loss": 0.8778,
2053
+ "step": 2920
2054
+ },
2055
+ {
2056
+ "epoch": 0.78,
2057
+ "grad_norm": 0.578125,
2058
+ "learning_rate": 7.169842892727294e-05,
2059
+ "loss": 0.8528,
2060
+ "step": 2930
2061
+ },
2062
+ {
2063
+ "epoch": 0.78,
2064
+ "grad_norm": 0.57421875,
2065
+ "learning_rate": 7.150026587756869e-05,
2066
+ "loss": 0.8365,
2067
+ "step": 2940
2068
+ },
2069
+ {
2070
+ "epoch": 0.78,
2071
+ "grad_norm": 0.55078125,
2072
+ "learning_rate": 7.130168763270378e-05,
2073
+ "loss": 0.8995,
2074
+ "step": 2950
2075
+ },
2076
+ {
2077
+ "epoch": 0.79,
2078
+ "grad_norm": 0.58203125,
2079
+ "learning_rate": 7.110269802745528e-05,
2080
+ "loss": 0.9097,
2081
+ "step": 2960
2082
+ },
2083
+ {
2084
+ "epoch": 0.79,
2085
+ "grad_norm": 0.5234375,
2086
+ "learning_rate": 7.090330090454412e-05,
2087
+ "loss": 0.9085,
2088
+ "step": 2970
2089
+ },
2090
+ {
2091
+ "epoch": 0.79,
2092
+ "grad_norm": 0.56640625,
2093
+ "learning_rate": 7.07035001145608e-05,
2094
+ "loss": 0.8339,
2095
+ "step": 2980
2096
+ },
2097
+ {
2098
+ "epoch": 0.79,
2099
+ "grad_norm": 0.5703125,
2100
+ "learning_rate": 7.050329951589115e-05,
2101
+ "loss": 0.8567,
2102
+ "step": 2990
2103
+ },
2104
+ {
2105
+ "epoch": 0.8,
2106
+ "grad_norm": 0.56640625,
2107
+ "learning_rate": 7.03027029746418e-05,
2108
+ "loss": 0.8881,
2109
+ "step": 3000
2110
+ },
2111
+ {
2112
+ "epoch": 0.8,
2113
+ "grad_norm": 0.5078125,
2114
+ "learning_rate": 7.010171436456543e-05,
2115
+ "loss": 0.8756,
2116
+ "step": 3010
2117
+ },
2118
+ {
2119
+ "epoch": 0.8,
2120
+ "grad_norm": 0.578125,
2121
+ "learning_rate": 6.990033756698605e-05,
2122
+ "loss": 0.9274,
2123
+ "step": 3020
2124
+ },
2125
+ {
2126
+ "epoch": 0.81,
2127
+ "grad_norm": 0.54296875,
2128
+ "learning_rate": 6.969857647072404e-05,
2129
+ "loss": 0.8851,
2130
+ "step": 3030
2131
+ },
2132
+ {
2133
+ "epoch": 0.81,
2134
+ "grad_norm": 0.5625,
2135
+ "learning_rate": 6.949643497202102e-05,
2136
+ "loss": 0.8373,
2137
+ "step": 3040
2138
+ },
2139
+ {
2140
+ "epoch": 0.81,
2141
+ "grad_norm": 0.703125,
2142
+ "learning_rate": 6.929391697446462e-05,
2143
+ "loss": 0.9072,
2144
+ "step": 3050
2145
+ },
2146
+ {
2147
+ "epoch": 0.81,
2148
+ "grad_norm": 0.5234375,
2149
+ "learning_rate": 6.909102638891312e-05,
2150
+ "loss": 0.8649,
2151
+ "step": 3060
2152
+ },
2153
+ {
2154
+ "epoch": 0.82,
2155
+ "grad_norm": 0.52734375,
2156
+ "learning_rate": 6.888776713341985e-05,
2157
+ "loss": 0.8854,
2158
+ "step": 3070
2159
+ },
2160
+ {
2161
+ "epoch": 0.82,
2162
+ "grad_norm": 0.546875,
2163
+ "learning_rate": 6.868414313315769e-05,
2164
+ "loss": 0.8658,
2165
+ "step": 3080
2166
+ },
2167
+ {
2168
+ "epoch": 0.82,
2169
+ "grad_norm": 0.5859375,
2170
+ "learning_rate": 6.848015832034306e-05,
2171
+ "loss": 0.8818,
2172
+ "step": 3090
2173
+ },
2174
+ {
2175
+ "epoch": 0.82,
2176
+ "grad_norm": 0.54296875,
2177
+ "learning_rate": 6.827581663416018e-05,
2178
+ "loss": 0.868,
2179
+ "step": 3100
2180
+ },
2181
+ {
2182
+ "epoch": 0.83,
2183
+ "grad_norm": 0.59765625,
2184
+ "learning_rate": 6.807112202068482e-05,
2185
+ "loss": 0.858,
2186
+ "step": 3110
2187
+ },
2188
+ {
2189
+ "epoch": 0.83,
2190
+ "grad_norm": 0.50390625,
2191
+ "learning_rate": 6.786607843280824e-05,
2192
+ "loss": 0.8519,
2193
+ "step": 3120
2194
+ },
2195
+ {
2196
+ "epoch": 0.83,
2197
+ "grad_norm": 0.59765625,
2198
+ "learning_rate": 6.766068983016083e-05,
2199
+ "loss": 0.8511,
2200
+ "step": 3130
2201
+ },
2202
+ {
2203
+ "epoch": 0.83,
2204
+ "grad_norm": 0.5234375,
2205
+ "learning_rate": 6.745496017903555e-05,
2206
+ "loss": 0.86,
2207
+ "step": 3140
2208
+ },
2209
+ {
2210
+ "epoch": 0.84,
2211
+ "grad_norm": 0.57421875,
2212
+ "learning_rate": 6.724889345231145e-05,
2213
+ "loss": 0.8832,
2214
+ "step": 3150
2215
+ },
2216
+ {
2217
+ "epoch": 0.84,
2218
+ "grad_norm": 0.5390625,
2219
+ "learning_rate": 6.704249362937686e-05,
2220
+ "loss": 0.8669,
2221
+ "step": 3160
2222
+ },
2223
+ {
2224
+ "epoch": 0.84,
2225
+ "grad_norm": 0.48828125,
2226
+ "learning_rate": 6.683576469605266e-05,
2227
+ "loss": 0.8812,
2228
+ "step": 3170
2229
+ },
2230
+ {
2231
+ "epoch": 0.84,
2232
+ "grad_norm": 0.515625,
2233
+ "learning_rate": 6.662871064451514e-05,
2234
+ "loss": 0.8651,
2235
+ "step": 3180
2236
+ },
2237
+ {
2238
+ "epoch": 0.85,
2239
+ "grad_norm": 0.5546875,
2240
+ "learning_rate": 6.642133547321909e-05,
2241
+ "loss": 0.8834,
2242
+ "step": 3190
2243
+ },
2244
+ {
2245
+ "epoch": 0.85,
2246
+ "grad_norm": 0.55078125,
2247
+ "learning_rate": 6.621364318682041e-05,
2248
+ "loss": 0.8587,
2249
+ "step": 3200
2250
+ },
2251
+ {
2252
+ "epoch": 0.85,
2253
+ "grad_norm": 0.6015625,
2254
+ "learning_rate": 6.600563779609896e-05,
2255
+ "loss": 0.8413,
2256
+ "step": 3210
2257
+ },
2258
+ {
2259
+ "epoch": 0.86,
2260
+ "grad_norm": 0.6484375,
2261
+ "learning_rate": 6.57973233178809e-05,
2262
+ "loss": 0.8504,
2263
+ "step": 3220
2264
+ },
2265
+ {
2266
+ "epoch": 0.86,
2267
+ "grad_norm": 0.578125,
2268
+ "learning_rate": 6.558870377496132e-05,
2269
+ "loss": 0.8708,
2270
+ "step": 3230
2271
+ },
2272
+ {
2273
+ "epoch": 0.86,
2274
+ "grad_norm": 0.5546875,
2275
+ "learning_rate": 6.537978319602642e-05,
2276
+ "loss": 0.8541,
2277
+ "step": 3240
2278
+ },
2279
+ {
2280
+ "epoch": 0.86,
2281
+ "grad_norm": 0.5546875,
2282
+ "learning_rate": 6.517056561557577e-05,
2283
+ "loss": 0.8685,
2284
+ "step": 3250
2285
+ },
2286
+ {
2287
+ "epoch": 0.87,
2288
+ "grad_norm": 0.546875,
2289
+ "learning_rate": 6.496105507384436e-05,
2290
+ "loss": 0.886,
2291
+ "step": 3260
2292
+ },
2293
+ {
2294
+ "epoch": 0.87,
2295
+ "grad_norm": 0.5546875,
2296
+ "learning_rate": 6.475125561672465e-05,
2297
+ "loss": 0.91,
2298
+ "step": 3270
2299
+ },
2300
+ {
2301
+ "epoch": 0.87,
2302
+ "grad_norm": 0.58203125,
2303
+ "learning_rate": 6.454117129568834e-05,
2304
+ "loss": 0.8431,
2305
+ "step": 3280
2306
+ },
2307
+ {
2308
+ "epoch": 0.87,
2309
+ "grad_norm": 0.51953125,
2310
+ "learning_rate": 6.433080616770823e-05,
2311
+ "loss": 0.8972,
2312
+ "step": 3290
2313
+ },
2314
+ {
2315
+ "epoch": 0.88,
2316
+ "grad_norm": 0.55859375,
2317
+ "learning_rate": 6.412016429517981e-05,
2318
+ "loss": 0.8754,
2319
+ "step": 3300
2320
+ },
2321
+ {
2322
+ "epoch": 0.88,
2323
+ "grad_norm": 0.5390625,
2324
+ "learning_rate": 6.390924974584284e-05,
2325
+ "loss": 0.8314,
2326
+ "step": 3310
2327
+ },
2328
+ {
2329
+ "epoch": 0.88,
2330
+ "grad_norm": 0.5703125,
2331
+ "learning_rate": 6.369806659270273e-05,
2332
+ "loss": 0.8456,
2333
+ "step": 3320
2334
+ },
2335
+ {
2336
+ "epoch": 0.88,
2337
+ "grad_norm": 0.53125,
2338
+ "learning_rate": 6.348661891395203e-05,
2339
+ "loss": 0.8493,
2340
+ "step": 3330
2341
+ },
2342
+ {
2343
+ "epoch": 0.89,
2344
+ "grad_norm": 0.53125,
2345
+ "learning_rate": 6.32749107928915e-05,
2346
+ "loss": 0.8581,
2347
+ "step": 3340
2348
+ },
2349
+ {
2350
+ "epoch": 0.89,
2351
+ "grad_norm": 0.58203125,
2352
+ "learning_rate": 6.306294631785143e-05,
2353
+ "loss": 0.8448,
2354
+ "step": 3350
2355
+ },
2356
+ {
2357
+ "epoch": 0.89,
2358
+ "grad_norm": 0.6328125,
2359
+ "learning_rate": 6.285072958211255e-05,
2360
+ "loss": 0.8878,
2361
+ "step": 3360
2362
+ },
2363
+ {
2364
+ "epoch": 0.9,
2365
+ "grad_norm": 0.5078125,
2366
+ "learning_rate": 6.263826468382703e-05,
2367
+ "loss": 0.8559,
2368
+ "step": 3370
2369
+ },
2370
+ {
2371
+ "epoch": 0.9,
2372
+ "grad_norm": 0.55078125,
2373
+ "learning_rate": 6.24255557259394e-05,
2374
+ "loss": 0.8942,
2375
+ "step": 3380
2376
+ },
2377
+ {
2378
+ "epoch": 0.9,
2379
+ "grad_norm": 0.56640625,
2380
+ "learning_rate": 6.221260681610722e-05,
2381
+ "loss": 0.9104,
2382
+ "step": 3390
2383
+ },
2384
+ {
2385
+ "epoch": 0.9,
2386
+ "grad_norm": 0.609375,
2387
+ "learning_rate": 6.199942206662179e-05,
2388
+ "loss": 0.8854,
2389
+ "step": 3400
2390
+ },
2391
+ {
2392
+ "epoch": 0.91,
2393
+ "grad_norm": 0.54296875,
2394
+ "learning_rate": 6.178600559432881e-05,
2395
+ "loss": 0.8739,
2396
+ "step": 3410
2397
+ },
2398
+ {
2399
+ "epoch": 0.91,
2400
+ "grad_norm": 0.58984375,
2401
+ "learning_rate": 6.157236152054875e-05,
2402
+ "loss": 0.8904,
2403
+ "step": 3420
2404
+ },
2405
+ {
2406
+ "epoch": 0.91,
2407
+ "grad_norm": 0.609375,
2408
+ "learning_rate": 6.135849397099737e-05,
2409
+ "loss": 0.8879,
2410
+ "step": 3430
2411
+ },
2412
+ {
2413
+ "epoch": 0.91,
2414
+ "grad_norm": 0.640625,
2415
+ "learning_rate": 6.1144407075706e-05,
2416
+ "loss": 0.8901,
2417
+ "step": 3440
2418
+ },
2419
+ {
2420
+ "epoch": 0.92,
2421
+ "grad_norm": 0.5078125,
2422
+ "learning_rate": 6.093010496894179e-05,
2423
+ "loss": 0.8733,
2424
+ "step": 3450
2425
+ },
2426
+ {
2427
+ "epoch": 0.92,
2428
+ "grad_norm": 0.55078125,
2429
+ "learning_rate": 6.071559178912786e-05,
2430
+ "loss": 0.897,
2431
+ "step": 3460
2432
+ },
2433
+ {
2434
+ "epoch": 0.92,
2435
+ "grad_norm": 0.5234375,
2436
+ "learning_rate": 6.050087167876342e-05,
2437
+ "loss": 0.8758,
2438
+ "step": 3470
2439
+ },
2440
+ {
2441
+ "epoch": 0.92,
2442
+ "grad_norm": 0.56640625,
2443
+ "learning_rate": 6.0285948784343717e-05,
2444
+ "loss": 0.871,
2445
+ "step": 3480
2446
+ },
2447
+ {
2448
+ "epoch": 0.93,
2449
+ "grad_norm": 0.54296875,
2450
+ "learning_rate": 6.007082725628004e-05,
2451
+ "loss": 0.8775,
2452
+ "step": 3490
2453
+ },
2454
+ {
2455
+ "epoch": 0.93,
2456
+ "grad_norm": 0.54296875,
2457
+ "learning_rate": 5.985551124881947e-05,
2458
+ "loss": 0.883,
2459
+ "step": 3500
2460
+ },
2461
+ {
2462
+ "epoch": 0.93,
2463
+ "grad_norm": 0.5546875,
2464
+ "learning_rate": 5.9640004919964784e-05,
2465
+ "loss": 0.873,
2466
+ "step": 3510
2467
+ },
2468
+ {
2469
+ "epoch": 0.94,
2470
+ "grad_norm": 0.51171875,
2471
+ "learning_rate": 5.9424312431394e-05,
2472
+ "loss": 0.8611,
2473
+ "step": 3520
2474
+ },
2475
+ {
2476
+ "epoch": 0.94,
2477
+ "grad_norm": 0.625,
2478
+ "learning_rate": 5.920843794838018e-05,
2479
+ "loss": 0.8757,
2480
+ "step": 3530
2481
+ },
2482
+ {
2483
+ "epoch": 0.94,
2484
+ "grad_norm": 0.61328125,
2485
+ "learning_rate": 5.899238563971083e-05,
2486
+ "loss": 0.8755,
2487
+ "step": 3540
2488
+ },
2489
+ {
2490
+ "epoch": 0.94,
2491
+ "grad_norm": 0.57421875,
2492
+ "learning_rate": 5.877615967760757e-05,
2493
+ "loss": 0.8437,
2494
+ "step": 3550
2495
+ },
2496
+ {
2497
+ "epoch": 0.95,
2498
+ "grad_norm": 0.56640625,
2499
+ "learning_rate": 5.8559764237645355e-05,
2500
+ "loss": 0.8527,
2501
+ "step": 3560
2502
+ },
2503
+ {
2504
+ "epoch": 0.95,
2505
+ "grad_norm": 0.54296875,
2506
+ "learning_rate": 5.834320349867207e-05,
2507
+ "loss": 0.8704,
2508
+ "step": 3570
2509
+ },
2510
+ {
2511
+ "epoch": 0.95,
2512
+ "grad_norm": 0.58203125,
2513
+ "learning_rate": 5.8126481642727626e-05,
2514
+ "loss": 0.8765,
2515
+ "step": 3580
2516
+ },
2517
+ {
2518
+ "epoch": 0.95,
2519
+ "grad_norm": 0.51171875,
2520
+ "learning_rate": 5.790960285496336e-05,
2521
+ "loss": 0.8725,
2522
+ "step": 3590
2523
+ },
2524
+ {
2525
+ "epoch": 0.96,
2526
+ "grad_norm": 0.58203125,
2527
+ "learning_rate": 5.7692571323561095e-05,
2528
+ "loss": 0.9189,
2529
+ "step": 3600
2530
+ },
2531
+ {
2532
+ "epoch": 0.96,
2533
+ "grad_norm": 0.53125,
2534
+ "learning_rate": 5.7475391239652344e-05,
2535
+ "loss": 0.8588,
2536
+ "step": 3610
2537
+ },
2538
+ {
2539
+ "epoch": 0.96,
2540
+ "grad_norm": 0.59375,
2541
+ "learning_rate": 5.725806679723731e-05,
2542
+ "loss": 0.8532,
2543
+ "step": 3620
2544
+ },
2545
+ {
2546
+ "epoch": 0.96,
2547
+ "grad_norm": 0.55859375,
2548
+ "learning_rate": 5.7040602193103945e-05,
2549
+ "loss": 0.8366,
2550
+ "step": 3630
2551
+ },
2552
+ {
2553
+ "epoch": 0.97,
2554
+ "grad_norm": 0.60546875,
2555
+ "learning_rate": 5.6823001626746875e-05,
2556
+ "loss": 0.8492,
2557
+ "step": 3640
2558
+ },
2559
+ {
2560
+ "epoch": 0.97,
2561
+ "grad_norm": 0.54296875,
2562
+ "learning_rate": 5.660526930028638e-05,
2563
+ "loss": 0.8658,
2564
+ "step": 3650
2565
+ },
2566
+ {
2567
+ "epoch": 0.97,
2568
+ "grad_norm": 0.5859375,
2569
+ "learning_rate": 5.638740941838705e-05,
2570
+ "loss": 0.8488,
2571
+ "step": 3660
2572
+ },
2573
+ {
2574
+ "epoch": 0.98,
2575
+ "grad_norm": 0.52734375,
2576
+ "learning_rate": 5.6169426188176856e-05,
2577
+ "loss": 0.8787,
2578
+ "step": 3670
2579
+ },
2580
+ {
2581
+ "epoch": 0.98,
2582
+ "grad_norm": 0.59765625,
2583
+ "learning_rate": 5.595132381916569e-05,
2584
+ "loss": 0.8747,
2585
+ "step": 3680
2586
+ },
2587
+ {
2588
+ "epoch": 0.98,
2589
+ "grad_norm": 0.59765625,
2590
+ "learning_rate": 5.573310652316417e-05,
2591
+ "loss": 0.8669,
2592
+ "step": 3690
2593
+ },
2594
+ {
2595
+ "epoch": 0.98,
2596
+ "grad_norm": 0.578125,
2597
+ "learning_rate": 5.551477851420228e-05,
2598
+ "loss": 0.8701,
2599
+ "step": 3700
2600
+ },
2601
+ {
2602
+ "epoch": 0.99,
2603
+ "grad_norm": 0.5625,
2604
+ "learning_rate": 5.529634400844802e-05,
2605
+ "loss": 0.9148,
2606
+ "step": 3710
2607
+ },
2608
+ {
2609
+ "epoch": 0.99,
2610
+ "grad_norm": 0.69140625,
2611
+ "learning_rate": 5.507780722412593e-05,
2612
+ "loss": 0.8568,
2613
+ "step": 3720
2614
+ },
2615
+ {
2616
+ "epoch": 0.99,
2617
+ "grad_norm": 0.5625,
2618
+ "learning_rate": 5.485917238143575e-05,
2619
+ "loss": 0.8911,
2620
+ "step": 3730
2621
+ },
2622
+ {
2623
+ "epoch": 0.99,
2624
+ "grad_norm": 0.62109375,
2625
+ "learning_rate": 5.4640443702470746e-05,
2626
+ "loss": 0.8899,
2627
+ "step": 3740
2628
+ },
2629
+ {
2630
+ "epoch": 1.0,
2631
+ "grad_norm": 0.54296875,
2632
+ "learning_rate": 5.442162541113631e-05,
2633
+ "loss": 0.8748,
2634
+ "step": 3750
2635
+ },
2636
+ {
2637
+ "epoch": 1.0,
2638
+ "grad_norm": 0.5234375,
2639
+ "learning_rate": 5.420272173306837e-05,
2640
+ "loss": 0.8457,
2641
+ "step": 3760
2642
+ },
2643
+ {
2644
+ "epoch": 1.0,
2645
+ "grad_norm": 0.48046875,
2646
+ "learning_rate": 5.398373689555175e-05,
2647
+ "loss": 0.8657,
2648
+ "step": 3770
2649
+ },
2650
+ {
2651
+ "epoch": 1.0,
2652
+ "grad_norm": 0.53515625,
2653
+ "learning_rate": 5.3764675127438555e-05,
2654
+ "loss": 0.8191,
2655
+ "step": 3780
2656
+ },
2657
+ {
2658
+ "epoch": 1.01,
2659
+ "grad_norm": 0.5625,
2660
+ "learning_rate": 5.354554065906654e-05,
2661
+ "loss": 0.8608,
2662
+ "step": 3790
2663
+ },
2664
+ {
2665
+ "epoch": 1.01,
2666
+ "grad_norm": 0.5546875,
2667
+ "learning_rate": 5.332633772217732e-05,
2668
+ "loss": 0.8268,
2669
+ "step": 3800
2670
+ },
2671
+ {
2672
+ "epoch": 1.01,
2673
+ "grad_norm": 0.5703125,
2674
+ "learning_rate": 5.3107070549834825e-05,
2675
+ "loss": 0.8448,
2676
+ "step": 3810
2677
+ },
2678
+ {
2679
+ "epoch": 1.01,
2680
+ "grad_norm": 0.53125,
2681
+ "learning_rate": 5.288774337634332e-05,
2682
+ "loss": 0.861,
2683
+ "step": 3820
2684
+ },
2685
+ {
2686
+ "epoch": 1.02,
2687
+ "grad_norm": 0.515625,
2688
+ "learning_rate": 5.266836043716588e-05,
2689
+ "loss": 0.8796,
2690
+ "step": 3830
2691
+ },
2692
+ {
2693
+ "epoch": 1.02,
2694
+ "grad_norm": 0.53515625,
2695
+ "learning_rate": 5.244892596884238e-05,
2696
+ "loss": 0.8296,
2697
+ "step": 3840
2698
+ },
2699
+ {
2700
+ "epoch": 1.02,
2701
+ "grad_norm": 0.51953125,
2702
+ "learning_rate": 5.2229444208907854e-05,
2703
+ "loss": 0.8553,
2704
+ "step": 3850
2705
+ },
2706
+ {
2707
+ "epoch": 1.03,
2708
+ "grad_norm": 0.5,
2709
+ "learning_rate": 5.200991939581054e-05,
2710
+ "loss": 0.824,
2711
+ "step": 3860
2712
+ },
2713
+ {
2714
+ "epoch": 1.03,
2715
+ "grad_norm": 0.51953125,
2716
+ "learning_rate": 5.179035576883014e-05,
2717
+ "loss": 0.8138,
2718
+ "step": 3870
2719
+ },
2720
+ {
2721
+ "epoch": 1.03,
2722
+ "grad_norm": 0.59375,
2723
+ "learning_rate": 5.157075756799583e-05,
2724
+ "loss": 0.8693,
2725
+ "step": 3880
2726
+ },
2727
+ {
2728
+ "epoch": 1.03,
2729
+ "grad_norm": 0.55859375,
2730
+ "learning_rate": 5.135112903400452e-05,
2731
+ "loss": 0.8124,
2732
+ "step": 3890
2733
+ },
2734
+ {
2735
+ "epoch": 1.04,
2736
+ "grad_norm": 0.578125,
2737
+ "learning_rate": 5.1131474408138826e-05,
2738
+ "loss": 0.8397,
2739
+ "step": 3900
2740
+ },
2741
+ {
2742
+ "epoch": 1.04,
2743
+ "grad_norm": 0.55078125,
2744
+ "learning_rate": 5.0911797932185265e-05,
2745
+ "loss": 0.8586,
2746
+ "step": 3910
2747
+ },
2748
+ {
2749
+ "epoch": 1.04,
2750
+ "grad_norm": 0.5234375,
2751
+ "learning_rate": 5.069210384835229e-05,
2752
+ "loss": 0.8286,
2753
+ "step": 3920
2754
+ },
2755
+ {
2756
+ "epoch": 1.04,
2757
+ "grad_norm": 0.57421875,
2758
+ "learning_rate": 5.047239639918839e-05,
2759
+ "loss": 0.8211,
2760
+ "step": 3930
2761
+ },
2762
+ {
2763
+ "epoch": 1.05,
2764
+ "grad_norm": 0.55078125,
2765
+ "learning_rate": 5.025267982750014e-05,
2766
+ "loss": 0.792,
2767
+ "step": 3940
2768
+ },
2769
+ {
2770
+ "epoch": 1.05,
2771
+ "grad_norm": 0.546875,
2772
+ "learning_rate": 5.003295837627031e-05,
2773
+ "loss": 0.8346,
2774
+ "step": 3950
2775
+ },
2776
+ {
2777
+ "epoch": 1.05,
2778
+ "grad_norm": 0.5234375,
2779
+ "learning_rate": 4.981323628857586e-05,
2780
+ "loss": 0.8579,
2781
+ "step": 3960
2782
+ },
2783
+ {
2784
+ "epoch": 1.05,
2785
+ "grad_norm": 0.55859375,
2786
+ "learning_rate": 4.959351780750607e-05,
2787
+ "loss": 0.8414,
2788
+ "step": 3970
2789
+ },
2790
+ {
2791
+ "epoch": 1.06,
2792
+ "grad_norm": 0.5703125,
2793
+ "learning_rate": 4.9373807176080596e-05,
2794
+ "loss": 0.8241,
2795
+ "step": 3980
2796
+ },
2797
+ {
2798
+ "epoch": 1.06,
2799
+ "grad_norm": 0.55078125,
2800
+ "learning_rate": 4.91541086371674e-05,
2801
+ "loss": 0.8419,
2802
+ "step": 3990
2803
+ },
2804
+ {
2805
+ "epoch": 1.06,
2806
+ "grad_norm": 0.52734375,
2807
+ "learning_rate": 4.893442643340108e-05,
2808
+ "loss": 0.8145,
2809
+ "step": 4000
2810
+ },
2811
+ {
2812
+ "epoch": 1.07,
2813
+ "grad_norm": 0.69921875,
2814
+ "learning_rate": 4.871476480710067e-05,
2815
+ "loss": 0.8639,
2816
+ "step": 4010
2817
+ },
2818
+ {
2819
+ "epoch": 1.07,
2820
+ "grad_norm": 0.5703125,
2821
+ "learning_rate": 4.849512800018786e-05,
2822
+ "loss": 0.8183,
2823
+ "step": 4020
2824
+ },
2825
+ {
2826
+ "epoch": 1.07,
2827
+ "grad_norm": 0.60546875,
2828
+ "learning_rate": 4.8275520254105036e-05,
2829
+ "loss": 0.8564,
2830
+ "step": 4030
2831
+ },
2832
+ {
2833
+ "epoch": 1.07,
2834
+ "grad_norm": 0.52734375,
2835
+ "learning_rate": 4.805594580973343e-05,
2836
+ "loss": 0.7912,
2837
+ "step": 4040
2838
+ },
2839
+ {
2840
+ "epoch": 1.08,
2841
+ "grad_norm": 0.5625,
2842
+ "learning_rate": 4.783640890731114e-05,
2843
+ "loss": 0.8293,
2844
+ "step": 4050
2845
+ },
2846
+ {
2847
+ "epoch": 1.08,
2848
+ "grad_norm": 0.55078125,
2849
+ "learning_rate": 4.7616913786351314e-05,
2850
+ "loss": 0.806,
2851
+ "step": 4060
2852
+ },
2853
+ {
2854
+ "epoch": 1.08,
2855
+ "grad_norm": 0.5390625,
2856
+ "learning_rate": 4.739746468556017e-05,
2857
+ "loss": 0.8086,
2858
+ "step": 4070
2859
+ },
2860
+ {
2861
+ "epoch": 1.08,
2862
+ "grad_norm": 0.5234375,
2863
+ "learning_rate": 4.717806584275536e-05,
2864
+ "loss": 0.8255,
2865
+ "step": 4080
2866
+ },
2867
+ {
2868
+ "epoch": 1.09,
2869
+ "grad_norm": 0.55859375,
2870
+ "learning_rate": 4.695872149478389e-05,
2871
+ "loss": 0.8272,
2872
+ "step": 4090
2873
+ },
2874
+ {
2875
+ "epoch": 1.09,
2876
+ "grad_norm": 0.52734375,
2877
+ "learning_rate": 4.673943587744043e-05,
2878
+ "loss": 0.8277,
2879
+ "step": 4100
2880
+ },
2881
+ {
2882
+ "epoch": 1.09,
2883
+ "grad_norm": 0.54296875,
2884
+ "learning_rate": 4.6520213225385504e-05,
2885
+ "loss": 0.8747,
2886
+ "step": 4110
2887
+ },
2888
+ {
2889
+ "epoch": 1.09,
2890
+ "grad_norm": 0.56640625,
2891
+ "learning_rate": 4.6301057772063706e-05,
2892
+ "loss": 0.8103,
2893
+ "step": 4120
2894
+ },
2895
+ {
2896
+ "epoch": 1.1,
2897
+ "grad_norm": 0.6171875,
2898
+ "learning_rate": 4.6081973749621946e-05,
2899
+ "loss": 0.8241,
2900
+ "step": 4130
2901
+ },
2902
+ {
2903
+ "epoch": 1.1,
2904
+ "grad_norm": 0.55078125,
2905
+ "learning_rate": 4.58629653888277e-05,
2906
+ "loss": 0.8587,
2907
+ "step": 4140
2908
+ },
2909
+ {
2910
+ "epoch": 1.1,
2911
+ "grad_norm": 0.5703125,
2912
+ "learning_rate": 4.5644036918987357e-05,
2913
+ "loss": 0.8213,
2914
+ "step": 4150
2915
+ },
2916
+ {
2917
+ "epoch": 1.11,
2918
+ "grad_norm": 0.52734375,
2919
+ "learning_rate": 4.54251925678645e-05,
2920
+ "loss": 0.8299,
2921
+ "step": 4160
2922
+ },
2923
+ {
2924
+ "epoch": 1.11,
2925
+ "grad_norm": 0.55078125,
2926
+ "learning_rate": 4.52064365615983e-05,
2927
+ "loss": 0.835,
2928
+ "step": 4170
2929
+ },
2930
+ {
2931
+ "epoch": 1.11,
2932
+ "grad_norm": 0.61328125,
2933
+ "learning_rate": 4.498777312462181e-05,
2934
+ "loss": 0.829,
2935
+ "step": 4180
2936
+ },
2937
+ {
2938
+ "epoch": 1.11,
2939
+ "grad_norm": 0.5703125,
2940
+ "learning_rate": 4.476920647958062e-05,
2941
+ "loss": 0.8444,
2942
+ "step": 4190
2943
+ },
2944
+ {
2945
+ "epoch": 1.12,
2946
+ "grad_norm": 0.57421875,
2947
+ "learning_rate": 4.4550740847251e-05,
2948
+ "loss": 0.842,
2949
+ "step": 4200
2950
+ },
2951
+ {
2952
+ "epoch": 1.12,
2953
+ "grad_norm": 0.5703125,
2954
+ "learning_rate": 4.4332380446458606e-05,
2955
+ "loss": 0.8427,
2956
+ "step": 4210
2957
+ },
2958
+ {
2959
+ "epoch": 1.12,
2960
+ "grad_norm": 0.53125,
2961
+ "learning_rate": 4.411412949399696e-05,
2962
+ "loss": 0.861,
2963
+ "step": 4220
2964
+ },
2965
+ {
2966
+ "epoch": 1.12,
2967
+ "grad_norm": 0.53125,
2968
+ "learning_rate": 4.389599220454601e-05,
2969
+ "loss": 0.8454,
2970
+ "step": 4230
2971
+ },
2972
+ {
2973
+ "epoch": 1.13,
2974
+ "grad_norm": 0.51953125,
2975
+ "learning_rate": 4.3677972790590725e-05,
2976
+ "loss": 0.8562,
2977
+ "step": 4240
2978
+ },
2979
+ {
2980
+ "epoch": 1.13,
2981
+ "grad_norm": 0.62109375,
2982
+ "learning_rate": 4.346007546233978e-05,
2983
+ "loss": 0.8427,
2984
+ "step": 4250
2985
+ },
2986
+ {
2987
+ "epoch": 1.13,
2988
+ "grad_norm": 0.5546875,
2989
+ "learning_rate": 4.324230442764416e-05,
2990
+ "loss": 0.8321,
2991
+ "step": 4260
2992
+ },
2993
+ {
2994
+ "epoch": 1.13,
2995
+ "grad_norm": 0.55078125,
2996
+ "learning_rate": 4.3024663891916126e-05,
2997
+ "loss": 0.8642,
2998
+ "step": 4270
2999
+ },
3000
+ {
3001
+ "epoch": 1.14,
3002
+ "grad_norm": 0.53125,
3003
+ "learning_rate": 4.280715805804768e-05,
3004
+ "loss": 0.8052,
3005
+ "step": 4280
3006
+ },
3007
+ {
3008
+ "epoch": 1.14,
3009
+ "grad_norm": 0.5859375,
3010
+ "learning_rate": 4.258979112632969e-05,
3011
+ "loss": 0.8452,
3012
+ "step": 4290
3013
+ },
3014
+ {
3015
+ "epoch": 1.14,
3016
+ "grad_norm": 0.53515625,
3017
+ "learning_rate": 4.2372567294370605e-05,
3018
+ "loss": 0.8544,
3019
+ "step": 4300
3020
+ },
3021
+ {
3022
+ "epoch": 1.15,
3023
+ "grad_norm": 0.55078125,
3024
+ "learning_rate": 4.215549075701549e-05,
3025
+ "loss": 0.806,
3026
+ "step": 4310
3027
+ },
3028
+ {
3029
+ "epoch": 1.15,
3030
+ "grad_norm": 0.58984375,
3031
+ "learning_rate": 4.193856570626496e-05,
3032
+ "loss": 0.822,
3033
+ "step": 4320
3034
+ },
3035
+ {
3036
+ "epoch": 1.15,
3037
+ "grad_norm": 0.52734375,
3038
+ "learning_rate": 4.172179633119425e-05,
3039
+ "loss": 0.8729,
3040
+ "step": 4330
3041
+ },
3042
+ {
3043
+ "epoch": 1.15,
3044
+ "grad_norm": 0.53515625,
3045
+ "learning_rate": 4.150518681787227e-05,
3046
+ "loss": 0.8257,
3047
+ "step": 4340
3048
+ },
3049
+ {
3050
+ "epoch": 1.16,
3051
+ "grad_norm": 0.65625,
3052
+ "learning_rate": 4.128874134928093e-05,
3053
+ "loss": 0.8132,
3054
+ "step": 4350
3055
+ },
3056
+ {
3057
+ "epoch": 1.16,
3058
+ "grad_norm": 0.5234375,
3059
+ "learning_rate": 4.1072464105234125e-05,
3060
+ "loss": 0.8559,
3061
+ "step": 4360
3062
+ },
3063
+ {
3064
+ "epoch": 1.16,
3065
+ "grad_norm": 0.51953125,
3066
+ "learning_rate": 4.085635926229721e-05,
3067
+ "loss": 0.8083,
3068
+ "step": 4370
3069
+ },
3070
+ {
3071
+ "epoch": 1.16,
3072
+ "grad_norm": 0.54296875,
3073
+ "learning_rate": 4.0640430993706216e-05,
3074
+ "loss": 0.8278,
3075
+ "step": 4380
3076
+ },
3077
+ {
3078
+ "epoch": 1.17,
3079
+ "grad_norm": 0.59765625,
3080
+ "learning_rate": 4.0424683469287396e-05,
3081
+ "loss": 0.7725,
3082
+ "step": 4390
3083
+ },
3084
+ {
3085
+ "epoch": 1.17,
3086
+ "grad_norm": 0.5625,
3087
+ "learning_rate": 4.020912085537655e-05,
3088
+ "loss": 0.7942,
3089
+ "step": 4400
3090
+ },
3091
+ {
3092
+ "epoch": 1.17,
3093
+ "grad_norm": 0.5625,
3094
+ "learning_rate": 3.999374731473869e-05,
3095
+ "loss": 0.8464,
3096
+ "step": 4410
3097
+ },
3098
+ {
3099
+ "epoch": 1.17,
3100
+ "grad_norm": 0.5703125,
3101
+ "learning_rate": 3.9778567006487556e-05,
3102
+ "loss": 0.8273,
3103
+ "step": 4420
3104
+ },
3105
+ {
3106
+ "epoch": 1.18,
3107
+ "grad_norm": 0.546875,
3108
+ "learning_rate": 3.95635840860054e-05,
3109
+ "loss": 0.8028,
3110
+ "step": 4430
3111
+ },
3112
+ {
3113
+ "epoch": 1.18,
3114
+ "grad_norm": 0.60546875,
3115
+ "learning_rate": 3.934880270486266e-05,
3116
+ "loss": 0.8334,
3117
+ "step": 4440
3118
+ },
3119
+ {
3120
+ "epoch": 1.18,
3121
+ "grad_norm": 0.63671875,
3122
+ "learning_rate": 3.913422701073779e-05,
3123
+ "loss": 0.8064,
3124
+ "step": 4450
3125
+ },
3126
+ {
3127
+ "epoch": 1.18,
3128
+ "grad_norm": 0.5703125,
3129
+ "learning_rate": 3.8919861147337214e-05,
3130
+ "loss": 0.8653,
3131
+ "step": 4460
3132
+ },
3133
+ {
3134
+ "epoch": 1.19,
3135
+ "grad_norm": 0.53125,
3136
+ "learning_rate": 3.8705709254315295e-05,
3137
+ "loss": 0.8444,
3138
+ "step": 4470
3139
+ },
3140
+ {
3141
+ "epoch": 1.19,
3142
+ "grad_norm": 0.5859375,
3143
+ "learning_rate": 3.8491775467194366e-05,
3144
+ "loss": 0.8423,
3145
+ "step": 4480
3146
+ },
3147
+ {
3148
+ "epoch": 1.19,
3149
+ "grad_norm": 0.5078125,
3150
+ "learning_rate": 3.8278063917284865e-05,
3151
+ "loss": 0.8153,
3152
+ "step": 4490
3153
+ },
3154
+ {
3155
+ "epoch": 1.2,
3156
+ "grad_norm": 0.50390625,
3157
+ "learning_rate": 3.8064578731605567e-05,
3158
+ "loss": 0.8343,
3159
+ "step": 4500
3160
+ },
3161
+ {
3162
+ "epoch": 1.2,
3163
+ "grad_norm": 0.60546875,
3164
+ "learning_rate": 3.785132403280394e-05,
3165
+ "loss": 0.8433,
3166
+ "step": 4510
3167
+ },
3168
+ {
3169
+ "epoch": 1.2,
3170
+ "grad_norm": 0.59765625,
3171
+ "learning_rate": 3.763830393907645e-05,
3172
+ "loss": 0.8163,
3173
+ "step": 4520
3174
+ },
3175
+ {
3176
+ "epoch": 1.2,
3177
+ "grad_norm": 0.58203125,
3178
+ "learning_rate": 3.7425522564089035e-05,
3179
+ "loss": 0.8307,
3180
+ "step": 4530
3181
+ },
3182
+ {
3183
+ "epoch": 1.21,
3184
+ "grad_norm": 0.59765625,
3185
+ "learning_rate": 3.7212984016897725e-05,
3186
+ "loss": 0.8196,
3187
+ "step": 4540
3188
+ },
3189
+ {
3190
+ "epoch": 1.21,
3191
+ "grad_norm": 0.5625,
3192
+ "learning_rate": 3.70006924018693e-05,
3193
+ "loss": 0.8313,
3194
+ "step": 4550
3195
+ },
3196
+ {
3197
+ "epoch": 1.21,
3198
+ "grad_norm": 0.55859375,
3199
+ "learning_rate": 3.678865181860193e-05,
3200
+ "loss": 0.8161,
3201
+ "step": 4560
3202
+ },
3203
+ {
3204
+ "epoch": 1.21,
3205
+ "grad_norm": 0.5859375,
3206
+ "learning_rate": 3.657686636184609e-05,
3207
+ "loss": 0.8393,
3208
+ "step": 4570
3209
+ },
3210
+ {
3211
+ "epoch": 1.22,
3212
+ "grad_norm": 0.5546875,
3213
+ "learning_rate": 3.636534012142548e-05,
3214
+ "loss": 0.7766,
3215
+ "step": 4580
3216
+ },
3217
+ {
3218
+ "epoch": 1.22,
3219
+ "grad_norm": 0.55078125,
3220
+ "learning_rate": 3.615407718215803e-05,
3221
+ "loss": 0.8407,
3222
+ "step": 4590
3223
+ },
3224
+ {
3225
+ "epoch": 1.22,
3226
+ "grad_norm": 0.6171875,
3227
+ "learning_rate": 3.594308162377701e-05,
3228
+ "loss": 0.8209,
3229
+ "step": 4600
3230
+ },
3231
+ {
3232
+ "epoch": 1.22,
3233
+ "grad_norm": 0.62109375,
3234
+ "learning_rate": 3.573235752085224e-05,
3235
+ "loss": 0.8155,
3236
+ "step": 4610
3237
+ },
3238
+ {
3239
+ "epoch": 1.23,
3240
+ "grad_norm": 0.5,
3241
+ "learning_rate": 3.552190894271142e-05,
3242
+ "loss": 0.8224,
3243
+ "step": 4620
3244
+ },
3245
+ {
3246
+ "epoch": 1.23,
3247
+ "grad_norm": 0.55859375,
3248
+ "learning_rate": 3.531173995336159e-05,
3249
+ "loss": 0.7922,
3250
+ "step": 4630
3251
+ },
3252
+ {
3253
+ "epoch": 1.23,
3254
+ "grad_norm": 0.54296875,
3255
+ "learning_rate": 3.5101854611410564e-05,
3256
+ "loss": 0.8238,
3257
+ "step": 4640
3258
+ },
3259
+ {
3260
+ "epoch": 1.24,
3261
+ "grad_norm": 0.58984375,
3262
+ "learning_rate": 3.489225696998859e-05,
3263
+ "loss": 0.8224,
3264
+ "step": 4650
3265
+ },
3266
+ {
3267
+ "epoch": 1.24,
3268
+ "grad_norm": 0.5703125,
3269
+ "learning_rate": 3.4682951076670115e-05,
3270
+ "loss": 0.8085,
3271
+ "step": 4660
3272
+ },
3273
+ {
3274
+ "epoch": 1.24,
3275
+ "grad_norm": 0.55078125,
3276
+ "learning_rate": 3.4473940973395557e-05,
3277
+ "loss": 0.8468,
3278
+ "step": 4670
3279
+ },
3280
+ {
3281
+ "epoch": 1.24,
3282
+ "grad_norm": 0.5234375,
3283
+ "learning_rate": 3.426523069639332e-05,
3284
+ "loss": 0.8559,
3285
+ "step": 4680
3286
+ },
3287
+ {
3288
+ "epoch": 1.25,
3289
+ "grad_norm": 0.546875,
3290
+ "learning_rate": 3.405682427610178e-05,
3291
+ "loss": 0.7942,
3292
+ "step": 4690
3293
+ },
3294
+ {
3295
+ "epoch": 1.25,
3296
+ "grad_norm": 0.58203125,
3297
+ "learning_rate": 3.3848725737091494e-05,
3298
+ "loss": 0.8467,
3299
+ "step": 4700
3300
+ },
3301
+ {
3302
+ "epoch": 1.25,
3303
+ "grad_norm": 0.58203125,
3304
+ "learning_rate": 3.36409390979875e-05,
3305
+ "loss": 0.8414,
3306
+ "step": 4710
3307
+ },
3308
+ {
3309
+ "epoch": 1.25,
3310
+ "grad_norm": 0.58203125,
3311
+ "learning_rate": 3.3433468371391655e-05,
3312
+ "loss": 0.8361,
3313
+ "step": 4720
3314
+ },
3315
+ {
3316
+ "epoch": 1.26,
3317
+ "grad_norm": 0.546875,
3318
+ "learning_rate": 3.3226317563805185e-05,
3319
+ "loss": 0.8313,
3320
+ "step": 4730
3321
+ },
3322
+ {
3323
+ "epoch": 1.26,
3324
+ "grad_norm": 0.61328125,
3325
+ "learning_rate": 3.3019490675551294e-05,
3326
+ "loss": 0.8413,
3327
+ "step": 4740
3328
+ },
3329
+ {
3330
+ "epoch": 1.26,
3331
+ "grad_norm": 0.51953125,
3332
+ "learning_rate": 3.2812991700697985e-05,
3333
+ "loss": 0.8183,
3334
+ "step": 4750
3335
+ },
3336
+ {
3337
+ "epoch": 1.26,
3338
+ "grad_norm": 0.61328125,
3339
+ "learning_rate": 3.2606824626980794e-05,
3340
+ "loss": 0.8272,
3341
+ "step": 4760
3342
+ },
3343
+ {
3344
+ "epoch": 1.27,
3345
+ "grad_norm": 0.53515625,
3346
+ "learning_rate": 3.2400993435725916e-05,
3347
+ "loss": 0.8072,
3348
+ "step": 4770
3349
+ },
3350
+ {
3351
+ "epoch": 1.27,
3352
+ "grad_norm": 0.53125,
3353
+ "learning_rate": 3.219550210177321e-05,
3354
+ "loss": 0.8177,
3355
+ "step": 4780
3356
+ },
3357
+ {
3358
+ "epoch": 1.27,
3359
+ "grad_norm": 0.52734375,
3360
+ "learning_rate": 3.199035459339958e-05,
3361
+ "loss": 0.8271,
3362
+ "step": 4790
3363
+ },
3364
+ {
3365
+ "epoch": 1.28,
3366
+ "grad_norm": 0.56640625,
3367
+ "learning_rate": 3.1785554872242176e-05,
3368
+ "loss": 0.8072,
3369
+ "step": 4800
3370
+ }
3371
+ ],
3372
+ "logging_steps": 10,
3373
+ "max_steps": 7526,
3374
+ "num_input_tokens_seen": 0,
3375
+ "num_train_epochs": 2,
3376
+ "save_steps": 100,
3377
+ "total_flos": 2.843204097241252e+19,
3378
+ "train_batch_size": 1,
3379
+ "trial_name": null,
3380
+ "trial_params": null
3381
+ }
training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8246a372def9594e5feb57f7a79250facf590b641213f42f417b7c82a9add6e8
3
+ size 4920
vision_tower_builder.py ADDED
@@ -0,0 +1,632 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Tuple, Union, Dict
2
+ from dataclasses import dataclass
3
+ from functools import partial, reduce
4
+ from PIL import Image
5
+ import os
6
+ from transformers.image_processing_utils import BatchFeature, get_size_dict
7
+ from transformers.image_transforms import (
8
+ convert_to_rgb,
9
+ normalize,
10
+ rescale,
11
+ resize,
12
+ to_channel_dimension_format,
13
+ )
14
+ from transformers.image_utils import (
15
+ ChannelDimension,
16
+ PILImageResampling,
17
+ to_numpy_array,
18
+ )
19
+ import numpy as np
20
+ import torch
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+ import torch.utils.checkpoint as checkpoint
24
+ from functools import partial
25
+ try:
26
+ from flash_attn import flash_attn_qkvpacked_func
27
+ use_flash_attn = True
28
+ except:
29
+ use_flash_attn = False
30
+ print("You need to install flash_attn to be faster!")
31
+
32
+ try:
33
+ from timm.layers import drop_path, to_2tuple, trunc_normal_
34
+ except:
35
+ from timm.models.layers import drop_path, trunc_normal_, to_2tuple
36
+
37
+
38
+
39
+ class DropPath(nn.Module):
40
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
41
+ """
42
+ def __init__(self, drop_prob=None):
43
+ super(DropPath, self).__init__()
44
+ self.drop_prob = drop_prob
45
+
46
+ def forward(self, x):
47
+ return drop_path(x, self.drop_prob, self.training)
48
+
49
+ def extra_repr(self) -> str:
50
+ return 'p={}'.format(self.drop_prob)
51
+
52
+
53
+ class Mlp(nn.Module):
54
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
55
+ super().__init__()
56
+ out_features = out_features or in_features
57
+ hidden_features = hidden_features or in_features
58
+ self.fc1 = nn.Linear(in_features, hidden_features)
59
+ self.act = act_layer()
60
+ self.fc2 = nn.Linear(hidden_features, out_features)
61
+ self.drop = nn.Dropout(drop)
62
+
63
+ def forward(self, x):
64
+ x = self.fc1(x)
65
+ x = self.act(x)
66
+ x = self.drop(x)
67
+ x = self.fc2(x)
68
+ x = self.drop(x)
69
+ return x
70
+
71
+ class Attention(nn.Module):
72
+ def __init__(
73
+ self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.,
74
+ proj_drop=0., attn_head_dim=None,
75
+ attn_type='flash_v2'):
76
+
77
+ if use_flash_attn:
78
+ attn_type = attn_type
79
+ else:
80
+ attn_type = 'origin'
81
+
82
+ print(attn_type)
83
+
84
+ super().__init__()
85
+ self.num_heads = num_heads
86
+ head_dim = dim // num_heads
87
+ if attn_head_dim is not None:
88
+ head_dim = attn_head_dim
89
+ all_head_dim = head_dim * self.num_heads
90
+ self.scale = qk_scale or head_dim ** -0.5
91
+
92
+ self.qkv = nn.Linear(dim, all_head_dim * 3, bias=False)
93
+ if qkv_bias:
94
+ self.q_bias = nn.Parameter(torch.zeros(all_head_dim))
95
+ self.v_bias = nn.Parameter(torch.zeros(all_head_dim))
96
+ else:
97
+ self.q_bias = None
98
+ self.v_bias = None
99
+
100
+ if attn_type not in ['origin', 'flash_v2']:
101
+ raise NotImplementedError(f"Not support attn_type: {attn_type}")
102
+
103
+ # print('umt:', f'attn_type: {attn_type}')
104
+
105
+ self.attn_type = attn_type
106
+ if attn_type == 'flash_v2':
107
+ self.attn_drop = attn_drop
108
+ else:
109
+ self.attn_drop = nn.Dropout(attn_drop)
110
+ self.proj = nn.Linear(all_head_dim, dim)
111
+ self.proj_drop = nn.Dropout(proj_drop)
112
+
113
+ def forward(self, x):
114
+ B, N, C = x.shape
115
+ qkv_bias = None
116
+ if self.q_bias is not None:
117
+ qkv_bias = torch.cat((self.q_bias, torch.zeros_like(self.v_bias, requires_grad=False), self.v_bias))
118
+ # qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
119
+ qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias)
120
+
121
+ if self.attn_type == 'flash_v2':
122
+ qkv = qkv.reshape(B, N, 3, self.num_heads, -1)
123
+ x = flash_attn_qkvpacked_func(qkv, dropout_p=self.attn_drop, softmax_scale=self.scale, causal=False).reshape(B, N, -1)
124
+ else:
125
+ qkv = qkv.reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)
126
+ q, k, v = qkv[0], qkv[1], qkv[
127
+ 2] # make torchscript happy (cannot use tensor as tuple)
128
+ # B num_heads N head_dim
129
+
130
+ q = q * self.scale
131
+ attn = (q @ k.transpose(-2, -1))
132
+
133
+ attn = attn.softmax(dim=-1)
134
+ attn = self.attn_drop(attn)
135
+
136
+ x = (attn @ v).transpose(1, 2).reshape(B, N, -1)
137
+
138
+ x = self.proj(x)
139
+ x = self.proj_drop(x)
140
+ return x
141
+
142
+
143
+
144
+
145
+ class Block(nn.Module):
146
+ def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
147
+ drop_path=0., init_values=None, act_layer=nn.GELU, norm_layer=nn.LayerNorm,
148
+ attn_head_dim=None):
149
+ super().__init__()
150
+ self.norm1 = norm_layer(dim)
151
+ self.attn = Attention(
152
+ dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,
153
+ attn_drop=attn_drop, proj_drop=drop, attn_head_dim=attn_head_dim)
154
+ # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
155
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
156
+ self.norm2 = norm_layer(dim)
157
+ mlp_hidden_dim = int(dim * mlp_ratio)
158
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
159
+
160
+ if init_values > 0:
161
+ self.gamma_1 = nn.Parameter(init_values * torch.ones((dim)),requires_grad=True)
162
+ self.gamma_2 = nn.Parameter(init_values * torch.ones((dim)),requires_grad=True)
163
+ else:
164
+ self.gamma_1, self.gamma_2 = None, None
165
+
166
+ def forward(self, x):
167
+ if self.gamma_1 is None:
168
+ x = x + self.drop_path(self.attn(self.norm1(x)))
169
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
170
+ else:
171
+ x = x + self.drop_path(self.gamma_1 * self.attn(self.norm1(x)))
172
+ x = x + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x)))
173
+ return x
174
+
175
+
176
+ class PatchEmbed(nn.Module):
177
+ """ Image to Patch Embedding
178
+ """
179
+ def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, num_frames=16, tubelet_size=2):
180
+ super().__init__()
181
+ img_size = to_2tuple(img_size)
182
+ patch_size = to_2tuple(patch_size)
183
+ self.tubelet_size = int(tubelet_size)
184
+ num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0]) * (num_frames // self.tubelet_size)
185
+ self.img_size = img_size
186
+ self.patch_size = patch_size
187
+ self.num_patches = num_patches
188
+ self.proj = nn.Conv3d(
189
+ in_channels=in_chans, out_channels=embed_dim,
190
+ kernel_size=(self.tubelet_size, patch_size[0], patch_size[1]),
191
+ stride=(self.tubelet_size, patch_size[0], patch_size[1])
192
+ )
193
+ # print('umt:', f'Num of patches: {num_patches}')
194
+
195
+ def forward(self, x, **kwargs):
196
+ B, C, T, H, W = x.shape
197
+ # FIXME look at relaxing size constraints
198
+ # assert H == self.img_size[0] and W == self.img_size[1], \
199
+ # f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
200
+ x = self.proj(x).flatten(2).transpose(1, 2)
201
+ return x
202
+
203
+ # sin-cos position encoding
204
+ # https://github.com/jadore801120/attention-is-all-you-need-pytorch/blob/master/transformer/Models.py#L31
205
+ def get_sinusoid_encoding_table(n_position, d_hid, ckpt_num_frame=-1, cur_frame=12):
206
+ ''' Sinusoid position encoding table '''
207
+ # TODO: make it with torch instead of numpy
208
+ def get_position_angle_vec(position):
209
+ return [position / np.power(10000, 2 * (hid_j // 2) / d_hid) for hid_j in range(d_hid)]
210
+
211
+ if ckpt_num_frame != -1 and ckpt_num_frame != cur_frame:
212
+ # print('umt:', f"Interpolate position embedding")
213
+ # print('umt:', f"Testing frame: {cur_frame}")
214
+ # print('umt:', f"Checkpoint frame: {ckpt_num_frame}")
215
+
216
+ T = ckpt_num_frame # checkpoint frame
217
+ new_T = cur_frame # testing frame
218
+ n_position = n_position // new_T * T # generate checkpoint position embedding
219
+ sinusoid_table = np.array([get_position_angle_vec(pos_i) for pos_i in range(n_position)])
220
+ sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # dim 2i
221
+ sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # dim 2i+1
222
+ sinusoid_table = torch.tensor(sinusoid_table, dtype=torch.float, requires_grad=False).unsqueeze(0)
223
+ # interpolate
224
+ P = int((n_position // T) ** 0.5)
225
+ C = d_hid
226
+ sinusoid_table = sinusoid_table.reshape(-1, T, P, P, C)
227
+ sinusoid_table = sinusoid_table.permute(0, 2, 3, 4, 1).reshape(-1, C, T) # BHW, C, T
228
+ sinusoid_table = torch.nn.functional.interpolate(sinusoid_table, size=new_T, mode='linear')
229
+ sinusoid_table = sinusoid_table.reshape(1, P, P, C, new_T).permute(0, 4, 1, 2, 3) # B, T, H, W, C
230
+ sinusoid_table = sinusoid_table.flatten(1, 3)
231
+ return sinusoid_table
232
+ else:
233
+ sinusoid_table = np.array([get_position_angle_vec(pos_i) for pos_i in range(n_position)])
234
+ sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # dim 2i
235
+ sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # dim 2i+1
236
+ return torch.tensor(sinusoid_table, dtype=torch.float, requires_grad=False).unsqueeze(0)
237
+
238
+
239
+ def get_sinusoid_encoding_table2(n_position=784, d_hid=1024, cur_frame=8, ckpt_num_frame=4, pre_n_position=784):
240
+ ''' Sinusoid position encoding table '''
241
+ # TODO: make it with torch instead of numpy
242
+ def get_position_angle_vec(position):
243
+ return [position / np.power(10000, 2 * (hid_j // 2) / d_hid) for hid_j in range(d_hid)]
244
+
245
+ # generate checkpoint position embedding
246
+ sinusoid_table = np.array([get_position_angle_vec(pos_i) for pos_i in range(pre_n_position)])
247
+ sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # dim 2i
248
+ sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # dim 2i+1
249
+ sinusoid_table = torch.tensor(sinusoid_table, dtype=torch.float, requires_grad=False).unsqueeze(0)
250
+
251
+ # print(f"n_position: {n_position}")
252
+ # print(f"pre_n_position: {pre_n_position}")
253
+
254
+ if n_position != pre_n_position:
255
+ T = ckpt_num_frame # checkpoint frame
256
+ P = 14 # checkpoint size
257
+ C = d_hid
258
+ new_P = int((n_position // cur_frame) ** 0.5) # testing size
259
+ # print(f'Pretraining uses 14x14, but current version is {new_P}x{new_P}')
260
+ # print(f'Interpolate the position embedding')
261
+ sinusoid_table = sinusoid_table.reshape(-1, T, P, P, C)
262
+ sinusoid_table = sinusoid_table.reshape(-1, P, P, C).permute(0, 3, 1, 2)
263
+ sinusoid_table = torch.nn.functional.interpolate(
264
+ sinusoid_table, size=(new_P, new_P), mode='bicubic', align_corners=False)
265
+ # BT, C, H, W -> BT, H, W, C -> B, T, H, W, C
266
+ sinusoid_table = sinusoid_table.permute(0, 2, 3, 1).reshape(-1, T, new_P, new_P, C)
267
+ sinusoid_table = sinusoid_table.flatten(1, 3) # B, THW, C
268
+
269
+ if cur_frame != ckpt_num_frame:
270
+ # print(f'Pretraining uses 4 frames, but current frame is {cur_frame}')
271
+ # print(f'Interpolate the position embedding')
272
+ T = ckpt_num_frame # checkpoint frame
273
+ new_T = cur_frame # testing frame
274
+ # interpolate
275
+ P = int((n_position // cur_frame) ** 0.5) # testing size
276
+ C = d_hid
277
+ sinusoid_table = sinusoid_table.reshape(-1, T, P, P, C)
278
+ sinusoid_table = sinusoid_table.permute(0, 2, 3, 4, 1).reshape(-1, C, T) # BHW, C, T
279
+ sinusoid_table = torch.nn.functional.interpolate(sinusoid_table, size=new_T, mode='linear')
280
+ sinusoid_table = sinusoid_table.reshape(1, P, P, C, new_T).permute(0, 4, 1, 2, 3) # B, T, H, W, C
281
+ sinusoid_table = sinusoid_table.flatten(1, 3) # B, THW, C
282
+
283
+ return sinusoid_table
284
+
285
+
286
+ class PretrainVisionTransformerEncoder(nn.Module):
287
+ """ Vision Transformer with support for patch or hybrid CNN input stage
288
+ """
289
+ def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, depth=12,
290
+ num_heads=12, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0.,
291
+ drop_path_rate=0., norm_layer=nn.LayerNorm, init_values=None, num_frames=8, tubelet_size=1,
292
+ use_learnable_pos_emb=False,
293
+ use_checkpoint=False, checkpoint_num=0,
294
+ ckpt_num_frame=-1, with_ln=True, return_index=-1
295
+ ):
296
+ super().__init__()
297
+ self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
298
+ self.patch_embed = PatchEmbed(
299
+ img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim,
300
+ num_frames=num_frames, tubelet_size=tubelet_size
301
+ )
302
+ num_patches = self.patch_embed.num_patches
303
+ self.depth = depth + return_index + 1
304
+ self.use_checkpoint = use_checkpoint
305
+ self.checkpoint_num = checkpoint_num
306
+ # print('umt:', f"Use checkpoint: {use_checkpoint}")
307
+ # print('umt:', f"Checkpoint number: {checkpoint_num}")
308
+ # print('UMT:', f"Real runing depth: {self.depth}")
309
+
310
+ # TODO: Add the cls token
311
+ if use_learnable_pos_emb:
312
+ self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))
313
+ self.img_pos_embed = nn.Parameter(torch.zeros(1, num_patches//(num_frames//tubelet_size) + 1, embed_dim))
314
+ else:
315
+ # sine-cosine positional embeddings
316
+ if img_size != 224:
317
+ self.pos_embed = get_sinusoid_encoding_table2(num_patches, embed_dim, ckpt_num_frame=ckpt_num_frame, cur_frame=num_frames//tubelet_size)
318
+ self.img_pos_embed = get_sinusoid_encoding_table2(num_patches//(num_frames//tubelet_size), embed_dim, cur_frame=1, ckpt_num_frame=1, pre_n_position=14*14)
319
+ else:
320
+ self.pos_embed = get_sinusoid_encoding_table(num_patches, embed_dim, ckpt_num_frame=ckpt_num_frame, cur_frame=num_frames//tubelet_size)
321
+ self.img_pos_embed = get_sinusoid_encoding_table(num_patches//(num_frames//tubelet_size), embed_dim)
322
+
323
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
324
+ self.blocks = nn.ModuleList([
325
+ Block(
326
+ dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
327
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer,
328
+ init_values=init_values)
329
+ for i in range(self.depth)])
330
+
331
+ if with_ln:
332
+ self.vision_layernorm = nn.LayerNorm(embed_dim, eps=1e-12)
333
+ else:
334
+ self.vision_layernorm = nn.Identity()
335
+
336
+ if use_learnable_pos_emb:
337
+ trunc_normal_(self.pos_embed, std=.02)
338
+
339
+ @torch.jit.ignore
340
+ def no_weight_decay(self):
341
+ return {'pos_embed', 'cls_token'}
342
+
343
+ def forward_features(self, x, use_image=False):
344
+ x = self.patch_embed(x)
345
+
346
+ if use_image:
347
+ x = x + self.img_pos_embed.type_as(x).to(x.device).clone().detach()
348
+ else:
349
+ x = x + self.pos_embed.type_as(x).to(x.device).clone().detach()
350
+
351
+ B, _, C = x.shape
352
+ x_vis = x
353
+
354
+ for idx, blk in enumerate(self.blocks):
355
+ if self.use_checkpoint and idx < self.checkpoint_num:
356
+ x_vis = checkpoint.checkpoint(blk, x_vis)
357
+ else:
358
+ x_vis = blk(x_vis)
359
+
360
+ # with ln ot not
361
+ x_vis = self.vision_layernorm(x_vis)
362
+ return x_vis
363
+
364
+ def forward(self, x, use_image=False):
365
+ x_vis = self.forward_features(x, use_image)
366
+ return x_vis
367
+
368
+
369
+ class PretrainVisionTransformer(nn.Module):
370
+ """ Vision Transformer with support for patch or hybrid CNN input stage
371
+ """
372
+ def __init__(self,
373
+ img_size=224,
374
+ patch_size=16,
375
+ encoder_in_chans=3,
376
+ encoder_embed_dim=768,
377
+ encoder_depth=12,
378
+ encoder_num_heads=12,
379
+ mlp_ratio=4.,
380
+ qkv_bias=True,
381
+ qk_scale=None,
382
+ drop_rate=0.,
383
+ attn_drop_rate=0.,
384
+ drop_path_rate=0.,
385
+ norm_layer=partial(nn.LayerNorm, eps=1e-6),
386
+ init_values=0.,
387
+ use_learnable_pos_emb=False,
388
+ num_frames=8,
389
+ tubelet_size=1,
390
+ use_checkpoint=False,
391
+ checkpoint_num=0,
392
+ ckpt_num_frame=4, # the pretrained model uses 4 frames
393
+ return_index=-1,
394
+ with_ln=False
395
+ ):
396
+ super().__init__()
397
+
398
+ self.encoder = PretrainVisionTransformerEncoder(
399
+ img_size=img_size,
400
+ patch_size=patch_size,
401
+ in_chans=encoder_in_chans,
402
+ embed_dim=encoder_embed_dim,
403
+ depth=encoder_depth,
404
+ num_heads=encoder_num_heads,
405
+ mlp_ratio=mlp_ratio,
406
+ qkv_bias=qkv_bias,
407
+ qk_scale=qk_scale,
408
+ drop_rate=drop_rate,
409
+ attn_drop_rate=attn_drop_rate,
410
+ drop_path_rate=drop_path_rate,
411
+ norm_layer=norm_layer,
412
+ init_values=init_values,
413
+ num_frames=num_frames,
414
+ tubelet_size=tubelet_size,
415
+ use_learnable_pos_emb=use_learnable_pos_emb,
416
+ use_checkpoint=use_checkpoint,
417
+ checkpoint_num=checkpoint_num,
418
+ ckpt_num_frame=ckpt_num_frame,
419
+ with_ln=with_ln,
420
+ return_index=return_index
421
+ )
422
+ # print('umt:', f'With LN: {with_ln}')
423
+ # print('UMT:', f'Total {encoder_depth} layer')
424
+ # print('UMT:', f'Return {encoder_depth+return_index+1}-th layer')
425
+
426
+ self.apply(self._init_weights)
427
+
428
+ def _init_weights(self, m):
429
+ if isinstance(m, nn.Linear):
430
+ nn.init.xavier_uniform_(m.weight)
431
+ if isinstance(m, nn.Linear) and m.bias is not None:
432
+ nn.init.constant_(m.bias, 0)
433
+ elif isinstance(m, nn.LayerNorm):
434
+ nn.init.constant_(m.bias, 0)
435
+ nn.init.constant_(m.weight, 1.0)
436
+
437
+ @torch.jit.ignore
438
+ def no_weight_decay(self):
439
+ return {'pos_embed', 'cls_token', 'clip_pos_embed'}
440
+
441
+ def forward(self, x, use_image=False):
442
+ T = x.shape[2]
443
+ x_vis = self.encoder(x, use_image) # [B, N_vis, C_e]
444
+ B, TL, C = x_vis.shape
445
+ x_vis = x_vis.view(B, T, TL // T, C)
446
+
447
+ return x_vis
448
+
449
+
450
+
451
+
452
+
453
+
454
+
455
+ class UMTImageProcessor:
456
+ def __init__(self, image_mean=(0.485, 0.456, 0.406), image_std=(0.229, 0.224, 0.225), size=(224, 224), crop_size: Dict[str, int] = None, resample=PILImageResampling.BICUBIC, rescale_factor=1 / 255, data_format=ChannelDimension.FIRST):
457
+ crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
458
+ crop_size = get_size_dict(crop_size, default_to_square=True, param_name="crop_size")
459
+
460
+ self.image_mean = image_mean
461
+ self.image_std = image_std
462
+ self.size = size
463
+ self.resample = resample
464
+ self.rescale_factor = rescale_factor
465
+ self.data_format = data_format
466
+ self.crop_size = crop_size
467
+
468
+ def preprocess(self, images, return_tensors, target_size=None):
469
+ if isinstance(images, Image.Image):
470
+ images = [images]
471
+ else:
472
+ # to adapt video data
473
+ images = [to_numpy_array(image) for image in images]
474
+ assert isinstance(images, list)
475
+
476
+ if target_size is None:
477
+ target_size = self.size
478
+
479
+ transforms = [
480
+ convert_to_rgb,
481
+ to_numpy_array,
482
+ partial(resize, size=target_size, resample=self.resample, data_format=self.data_format),
483
+ partial(rescale, scale=self.rescale_factor, data_format=self.data_format),
484
+ partial(normalize, mean=self.image_mean, std=self.image_std, data_format=self.data_format),
485
+ partial(to_channel_dimension_format, channel_dim=self.data_format, input_channel_dim=self.data_format),
486
+ ]
487
+
488
+ images = reduce(lambda x, f: [*map(f, x)], transforms, images)
489
+ data = {"pixel_values": images}
490
+
491
+ return BatchFeature(data=data, tensor_type=return_tensors)
492
+
493
+
494
+ class UMTVisionConfig:
495
+ model_type = "umt_vision_model"
496
+
497
+ def __init__(
498
+ self,
499
+ num_frames=4,
500
+ hidden_size=1024,
501
+ num_hidden_layers=24,
502
+ num_attention_heads=16,
503
+ num_channels=3,
504
+ image_size=224,
505
+ patch_size=16,
506
+ return_idx=-2
507
+ # **kwargs,
508
+ ):
509
+ # super().__init__(**kwargs)
510
+ self.num_frames = num_frames
511
+ self.hidden_size = hidden_size
512
+ self.num_hidden_layers = num_hidden_layers
513
+ self.num_attention_heads = num_attention_heads
514
+ self.num_channels = num_channels
515
+ self.patch_size = patch_size
516
+ self.image_size = image_size
517
+ self.return_idx = return_idx
518
+
519
+
520
+ def build_vit(config, pt_type='origin'):
521
+ model = PretrainVisionTransformer(
522
+ img_size=config.image_size,
523
+ patch_size=16,
524
+ encoder_embed_dim=1024,
525
+ encoder_depth=24,
526
+ encoder_num_heads=16,
527
+ drop_path_rate=0.,
528
+ num_frames=config.num_frames,
529
+ tubelet_size=1,
530
+ use_checkpoint=False,
531
+ checkpoint_num=24,
532
+ return_index=config.return_idx,
533
+ with_ln=True, # merge vision_layernorm in it
534
+ )
535
+
536
+ # no need to load pt
537
+
538
+ return model
539
+
540
+
541
+
542
+ class UMTVisionTower(nn.Module):
543
+ def __init__(self, vision_tower, vision_tower_cfg, delay_load=False, pt_type='origin', image_size=224):
544
+ super().__init__()
545
+
546
+ self.is_loaded = False
547
+ self.pt_type = pt_type
548
+
549
+ self.config = UMTVisionConfig(num_frames=vision_tower_cfg.mm_local_num_frames, return_idx=vision_tower_cfg.mm_vision_select_layer, image_size=image_size)
550
+
551
+ self.vision_tower_name = vision_tower
552
+
553
+ self.image_processor = UMTImageProcessor(size=(image_size, image_size))
554
+
555
+ if not delay_load:
556
+ print(f"Loading vision tower: {vision_tower}")
557
+ self.load_model()
558
+ elif getattr(vision_tower_cfg, "unfreeze_mm_vision_tower", False):
559
+ # TODO: better detector is needed.
560
+ print(f"The checkpoint seems to contain `vision_tower` weights: `unfreeze_mm_vision_tower`: True.")
561
+ self.load_model()
562
+ elif hasattr(vision_tower_cfg, "mm_tunable_parts") and "mm_vision_tower" in vision_tower_cfg.mm_tunable_parts:
563
+ print(f"The checkpoint seems to contain `vision_tower` weights: `mm_tunable_parts` contains `mm_vision_tower`.")
564
+ self.load_model()
565
+ else:
566
+ self.cfg_only = self.config
567
+
568
+ def load_model(self, device_map=None):
569
+ if self.is_loaded:
570
+ print("{} is already loaded, `load_model` called again, skipping.".format(self.vision_tower_name))
571
+ return
572
+
573
+ self.vision_tower = build_vit(self.config, pt_type=self.pt_type)
574
+ self.vision_tower.requires_grad_(False)
575
+
576
+ self.is_loaded = True
577
+
578
+ def forward(self, images):
579
+ if type(images) is list:
580
+ raise NotImplementedError
581
+ else:
582
+ # input: B T C H W
583
+ # output: B T*L C
584
+ T = images.shape[1]
585
+ images = images.permute(0, 2, 1, 3, 4)
586
+ image_embeds = self.vision_tower(images, use_image=(T == 1))
587
+ B, T, L, C = image_embeds.shape
588
+ image_embeds = image_embeds.reshape(B, -1, C)
589
+
590
+ return image_embeds
591
+
592
+ @property
593
+ def dummy_feature(self):
594
+ return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
595
+
596
+ @property
597
+ def dtype(self):
598
+ for p in self.vision_tower.parameters():
599
+ return p.dtype
600
+
601
+ @property
602
+ def device(self):
603
+ for p in self.vision_tower.parameters():
604
+ return p.device
605
+
606
+ @property
607
+ def hidden_size(self):
608
+ return self.config.hidden_size
609
+
610
+ @property
611
+ def num_patches(self):
612
+ return (self.config.image_size // self.config.patch_size) ** 2
613
+
614
+ @property
615
+ def num_patches_per_side(self):
616
+ return self.config.image_size // self.config.patch_size
617
+
618
+ @property
619
+ def image_size(self):
620
+ return self.config.image_size
621
+
622
+
623
+ def build_vision_tower(vision_tower_cfg, **kwargs):
624
+ vision_tower = getattr(vision_tower_cfg, "mm_vision_tower", getattr(vision_tower_cfg, "vision_tower", None))
625
+
626
+
627
+ if "umt-hd" in vision_tower:
628
+ return UMTVisionTower(vision_tower, vision_tower_cfg=vision_tower_cfg, image_size=448, **kwargs)
629
+ elif "umt" in vision_tower:
630
+ return UMTVisionTower(vision_tower, vision_tower_cfg=vision_tower_cfg, **kwargs)
631
+
632
+ raise ValueError(f"Unknown vision tower: {vision_tower}")
vocab.json ADDED
The diff for this file is too large to render. See raw diff