Zeknes commited on
Commit
86555ea
·
verified ·
1 Parent(s): c4a2e01

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,3 +1,7 @@
1
- ---
2
- license: mit
3
- ---
 
 
 
 
 
1
+ ---
2
+ language: en
3
+ tags:
4
+ - mlx
5
+ pipeline_tag: image-text-to-text
6
+ library_name: mlx
7
+ ---
added_tokens.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</think>": 151668,
3
+ "</tool_call>": 151658,
4
+ "</tool_response>": 151666,
5
+ "<think>": 151667,
6
+ "<tool_call>": 151657,
7
+ "<tool_response>": 151665,
8
+ "<|box_end|>": 151649,
9
+ "<|box_start|>": 151648,
10
+ "<|endoftext|>": 151643,
11
+ "<|file_sep|>": 151664,
12
+ "<|fim_middle|>": 151660,
13
+ "<|fim_pad|>": 151662,
14
+ "<|fim_prefix|>": 151659,
15
+ "<|fim_suffix|>": 151661,
16
+ "<|im_end|>": 151645,
17
+ "<|im_start|>": 151644,
18
+ "<|image_pad|>": 151655,
19
+ "<|object_ref_end|>": 151647,
20
+ "<|object_ref_start|>": 151646,
21
+ "<|quad_end|>": 151651,
22
+ "<|quad_start|>": 151650,
23
+ "<|repo_name|>": 151663,
24
+ "<|video_pad|>": 151656,
25
+ "<|vision_end|>": 151653,
26
+ "<|vision_pad|>": 151654,
27
+ "<|vision_start|>": 151652
28
+ }
chat_template.jinja ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- if tools %}
2
+ {{- '<|im_start|>system\n' }}
3
+ {%- if messages[0].role == 'system' %}
4
+ {%- if messages[0].content is string %}
5
+ {{- messages[0].content }}
6
+ {%- else %}
7
+ {%- for content in messages[0].content %}
8
+ {%- if 'text' in content %}
9
+ {{- content.text }}
10
+ {%- endif %}
11
+ {%- endfor %}
12
+ {%- endif %}
13
+ {{- '\n\n' }}
14
+ {%- endif %}
15
+ {{- "# 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>" }}
16
+ {%- for tool in tools %}
17
+ {{- "\n" }}
18
+ {{- tool | tojson }}
19
+ {%- endfor %}
20
+ {{- "\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" }}
21
+ {%- else %}
22
+ {%- if messages[0].role == 'system' %}
23
+ {{- '<|im_start|>system\n' }}
24
+ {%- if messages[0].content is string %}
25
+ {{- messages[0].content }}
26
+ {%- else %}
27
+ {%- for content in messages[0].content %}
28
+ {%- if 'text' in content %}
29
+ {{- content.text }}
30
+ {%- endif %}
31
+ {%- endfor %}
32
+ {%- endif %}
33
+ {{- '<|im_end|>\n' }}
34
+ {%- endif %}
35
+ {%- endif %}
36
+ {%- set image_count = namespace(value=0) %}
37
+ {%- set video_count = namespace(value=0) %}
38
+ {%- for message in messages %}
39
+ {%- if message.role == "user" %}
40
+ {{- '<|im_start|>' + message.role + '\n' }}
41
+ {%- if message.content is string %}
42
+ {{- message.content }}
43
+ {%- else %}
44
+ {%- for content in message.content %}
45
+ {%- if content.type == 'image' or 'image' in content or 'image_url' in content %}
46
+ {%- set image_count.value = image_count.value + 1 %}
47
+ {%- if add_vision_id %}Picture {{ image_count.value }}: {% endif -%}
48
+ <|vision_start|><|image_pad|><|vision_end|>
49
+ {%- elif content.type == 'video' or 'video' in content %}
50
+ {%- set video_count.value = video_count.value + 1 %}
51
+ {%- if add_vision_id %}Video {{ video_count.value }}: {% endif -%}
52
+ <|vision_start|><|video_pad|><|vision_end|>
53
+ {%- elif 'text' in content %}
54
+ {{- content.text }}
55
+ {%- endif %}
56
+ {%- endfor %}
57
+ {%- endif %}
58
+ {{- '<|im_end|>\n' }}
59
+ {%- elif message.role == "assistant" %}
60
+ {{- '<|im_start|>' + message.role + '\n' }}
61
+ {%- if message.content is string %}
62
+ {{- message.content }}
63
+ {%- else %}
64
+ {%- for content_item in message.content %}
65
+ {%- if 'text' in content_item %}
66
+ {{- content_item.text }}
67
+ {%- endif %}
68
+ {%- endfor %}
69
+ {%- endif %}
70
+ {%- if message.tool_calls %}
71
+ {%- for tool_call in message.tool_calls %}
72
+ {%- if (loop.first and message.content) or (not loop.first) %}
73
+ {{- '\n' }}
74
+ {%- endif %}
75
+ {%- if tool_call.function %}
76
+ {%- set tool_call = tool_call.function %}
77
+ {%- endif %}
78
+ {{- '<tool_call>\n{"name": "' }}
79
+ {{- tool_call.name }}
80
+ {{- '", "arguments": ' }}
81
+ {%- if tool_call.arguments is string %}
82
+ {{- tool_call.arguments }}
83
+ {%- else %}
84
+ {{- tool_call.arguments | tojson }}
85
+ {%- endif %}
86
+ {{- '}\n</tool_call>' }}
87
+ {%- endfor %}
88
+ {%- endif %}
89
+ {{- '<|im_end|>\n' }}
90
+ {%- elif message.role == "tool" %}
91
+ {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
92
+ {{- '<|im_start|>user' }}
93
+ {%- endif %}
94
+ {{- '\n<tool_response>\n' }}
95
+ {%- if message.content is string %}
96
+ {{- message.content }}
97
+ {%- else %}
98
+ {%- for content in message.content %}
99
+ {%- if content.type == 'image' or 'image' in content or 'image_url' in content %}
100
+ {%- set image_count.value = image_count.value + 1 %}
101
+ {%- if add_vision_id %}Picture {{ image_count.value }}: {% endif -%}
102
+ <|vision_start|><|image_pad|><|vision_end|>
103
+ {%- elif content.type == 'video' or 'video' in content %}
104
+ {%- set video_count.value = video_count.value + 1 %}
105
+ {%- if add_vision_id %}Video {{ video_count.value }}: {% endif -%}
106
+ <|vision_start|><|video_pad|><|vision_end|>
107
+ {%- elif 'text' in content %}
108
+ {{- content.text }}
109
+ {%- endif %}
110
+ {%- endfor %}
111
+ {%- endif %}
112
+ {{- '\n</tool_response>' }}
113
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
114
+ {{- '<|im_end|>\n' }}
115
+ {%- endif %}
116
+ {%- endif %}
117
+ {%- endfor %}
118
+ {%- if add_generation_prompt %}
119
+ {{- '<|im_start|>assistant\n' }}
120
+ {%- endif %}
config.json ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Qwen3VLForConditionalGeneration"
4
+ ],
5
+ "dtype": "bfloat16",
6
+ "eos_token_id": [
7
+ 151645,
8
+ 151643
9
+ ],
10
+ "hidden_size": 4096,
11
+ "image_token_id": 151655,
12
+ "model_type": "qwen3_vl",
13
+ "pad_token_id": 151643,
14
+ "quantization": {
15
+ "group_size": 64,
16
+ "bits": 4,
17
+ "mode": "affine"
18
+ },
19
+ "quantization_config": {
20
+ "group_size": 64,
21
+ "bits": 4,
22
+ "mode": "affine"
23
+ },
24
+ "text_config": {
25
+ "attention_bias": false,
26
+ "attention_dropout": 0.0,
27
+ "bos_token_id": 151643,
28
+ "dtype": "float32",
29
+ "eos_token_id": 151645,
30
+ "head_dim": 128,
31
+ "hidden_act": "silu",
32
+ "hidden_size": 4096,
33
+ "initializer_range": 0.02,
34
+ "intermediate_size": 12288,
35
+ "max_position_embeddings": 262144,
36
+ "model_type": "qwen3_vl_text",
37
+ "num_attention_heads": 32,
38
+ "num_hidden_layers": 36,
39
+ "num_key_value_heads": 8,
40
+ "pad_token_id": 151643,
41
+ "rms_norm_eps": 1e-06,
42
+ "rope_scaling": {
43
+ "mrope_interleaved": true,
44
+ "mrope_section": [
45
+ 24,
46
+ 20,
47
+ 20
48
+ ],
49
+ "rope_type": "default"
50
+ },
51
+ "rope_theta": 5000000,
52
+ "use_cache": false,
53
+ "vocab_size": 151936
54
+ },
55
+ "tie_word_embeddings": false,
56
+ "transformers_version": "4.57.0",
57
+ "video_token_id": 151656,
58
+ "vision_config": {
59
+ "deepstack_visual_indexes": [
60
+ 8,
61
+ 16,
62
+ 24
63
+ ],
64
+ "depth": 27,
65
+ "dtype": "float32",
66
+ "hidden_act": "gelu_pytorch_tanh",
67
+ "hidden_size": 1152,
68
+ "in_channels": 3,
69
+ "initializer_range": 0.02,
70
+ "intermediate_size": 4304,
71
+ "model_type": "qwen3_vl",
72
+ "num_heads": 16,
73
+ "num_position_embeddings": 2304,
74
+ "out_hidden_size": 4096,
75
+ "pad_token_id": 151643,
76
+ "patch_size": 16,
77
+ "spatial_merge_size": 2,
78
+ "temporal_patch_size": 2
79
+ },
80
+ "vision_end_token_id": 151653,
81
+ "vision_start_token_id": 151652
82
+ }
configuration.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"framework":"Pytorch","task":"multi-modal-embedding"}
generation_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 151643,
3
+ "do_sample": true,
4
+ "eos_token_id": [
5
+ 151645,
6
+ 151643
7
+ ],
8
+ "pad_token_id": 151643,
9
+ "temperature": 0.7,
10
+ "top_k": 20,
11
+ "top_p": 0.8,
12
+ "transformers_version": "4.57.0"
13
+ }
model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:341243c08096a3e53120ea36ebeea2202b91e9de4d3510c864dd9fbee9af6648
3
+ size 5363990335
model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:87e3d1f6fb18a8c46a16e32d145ce2225d6996aa86f5c25ecee8c9cabe8ca055
3
+ size 2061968516
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
preprocessor_config.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "size": {
3
+ "longest_edge": 16777216,
4
+ "shortest_edge": 65536
5
+ },
6
+ "patch_size": 16,
7
+ "temporal_patch_size": 2,
8
+ "image_mean": [
9
+ 0.5,
10
+ 0.5,
11
+ 0.5
12
+ ],
13
+ "image_std": [
14
+ 0.5,
15
+ 0.5,
16
+ 0.5
17
+ ],
18
+ "processor_class": "Qwen3VLProcessor",
19
+ "image_processor_type": "Qwen2VLImageProcessorFast",
20
+ "input_data_format": null,
21
+ "max_pixels": 1310720,
22
+ "merge_size": 2,
23
+ "min_pixels": 4095,
24
+ "pad_size": null,
25
+ "processor_class": "Qwen3VLProcessor",
26
+ "resample": 3,
27
+ "rescale_factor": 0.00392156862745098,
28
+ "return_tensors": null
29
+ }
processor_config.json ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "image_processor": {
3
+ "do_convert_rgb": true,
4
+ "do_normalize": true,
5
+ "do_rescale": true,
6
+ "do_resize": true,
7
+ "image_mean": [
8
+ 0.5,
9
+ 0.5,
10
+ 0.5
11
+ ],
12
+ "image_processor_type": "Qwen2VLImageProcessor",
13
+ "image_std": [
14
+ 0.5,
15
+ 0.5,
16
+ 0.5
17
+ ],
18
+ "merge_size": 2,
19
+ "patch_size": 16,
20
+ "resample": 3,
21
+ "rescale_factor": 0.00392156862745098,
22
+ "size": {
23
+ "longest_edge": 1310720,
24
+ "shortest_edge": 4095
25
+ },
26
+ "temporal_patch_size": 2
27
+ },
28
+ "processor_class": "Qwen3VLProcessor",
29
+ "video_processor": {
30
+ "data_format": "channels_first",
31
+ "default_to_square": true,
32
+ "do_convert_rgb": true,
33
+ "do_normalize": true,
34
+ "do_rescale": true,
35
+ "do_resize": true,
36
+ "do_sample_frames": true,
37
+ "fps": 2,
38
+ "image_mean": [
39
+ 0.5,
40
+ 0.5,
41
+ 0.5
42
+ ],
43
+ "image_std": [
44
+ 0.5,
45
+ 0.5,
46
+ 0.5
47
+ ],
48
+ "max_frames": 768,
49
+ "merge_size": 2,
50
+ "min_frames": 4,
51
+ "patch_size": 16,
52
+ "resample": 3,
53
+ "rescale_factor": 0.00392156862745098,
54
+ "return_metadata": false,
55
+ "size": {
56
+ "longest_edge": 25165824,
57
+ "shortest_edge": 4096
58
+ },
59
+ "temporal_patch_size": 2,
60
+ "video_processor_type": "Qwen3VLVideoProcessor"
61
+ }
62
+ }
scripts/qwen3_vl_reranker.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ import logging
4
+
5
+ from PIL import Image
6
+ from scipy import special
7
+ from typing import List
8
+ from qwen_vl_utils import process_vision_info
9
+ from transformers import Qwen3VLForConditionalGeneration, AutoProcessor
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+ MAX_LENGTH = 8192
14
+ IMAGE_BASE_FACTOR = 16
15
+ IMAGE_FACTOR = IMAGE_BASE_FACTOR * 2
16
+ MIN_PIXELS = 4 * IMAGE_FACTOR * IMAGE_FACTOR # 4 tokens
17
+ MAX_PIXELS = 1280 * IMAGE_FACTOR * IMAGE_FACTOR # 1280 tokens
18
+ MAX_RATIO = 200
19
+
20
+ FRAME_FACTOR = 2
21
+ FPS = 1
22
+ MIN_FRAMES = 2
23
+ MAX_FRAMES = 64
24
+ MIN_TOTAL_PIXELS = 1 * FRAME_FACTOR * MIN_PIXELS # 1 frames
25
+ MAX_TOTAL_PIXELS = 4 * FRAME_FACTOR * MAX_PIXELS # 4 frames
26
+
27
+
28
+ def sample_frames(frames, num_segments, max_segments):
29
+ duration = len(frames)
30
+ frame_id_array = np.linspace(0, duration - 1, num_segments, dtype=int)
31
+ frame_id_list = frame_id_array.tolist()
32
+ last_frame_id = frame_id_list[-1]
33
+
34
+ sampled_frames = []
35
+ for frame_idx in frame_id_list:
36
+ try:
37
+ single_frame_path = frames[frame_idx]
38
+ except:
39
+ break
40
+ sampled_frames.append(single_frame_path)
41
+ # Pad with last frame if total frames less than num_segments
42
+ while len(sampled_frames) < num_segments:
43
+ sampled_frames.append(frames[last_frame_id])
44
+ return sampled_frames[:max_segments]
45
+
46
+ class Qwen3VLReranker():
47
+ def __init__(
48
+ self,
49
+ model_name_or_path: str,
50
+ max_length: int = MAX_LENGTH,
51
+ min_pixels: int = MIN_PIXELS,
52
+ max_pixels: int = MAX_PIXELS,
53
+ total_pixels: int = MAX_TOTAL_PIXELS,
54
+ fps: float = FPS,
55
+ num_frames: int = MAX_FRAMES,
56
+ max_frames: int = MAX_FRAMES,
57
+ default_instruction: str = "Given a search query, retrieve relevant candidates that answer the query.",
58
+ **kwargs,
59
+ ):
60
+
61
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
62
+
63
+ self.max_length = max_length
64
+ self.min_pixels = min_pixels
65
+ self.max_pixels = max_pixels
66
+ self.total_pixels = total_pixels
67
+ self.fps = fps
68
+ self.num_frames = num_frames
69
+ self.max_frames = max_frames
70
+
71
+ self.default_instruction = default_instruction
72
+
73
+ lm = Qwen3VLForConditionalGeneration.from_pretrained(
74
+ model_name_or_path,
75
+ trust_remote_code=True, **kwargs
76
+ ).to(self.device)
77
+
78
+ self.model = lm.model
79
+ self.processor = AutoProcessor.from_pretrained(
80
+ model_name_or_path, trust_remote_code=True,
81
+ padding_side='left'
82
+ )
83
+ self.model.eval()
84
+
85
+ token_true_id = self.processor.tokenizer.get_vocab()["yes"]
86
+ token_false_id = self.processor.tokenizer.get_vocab()["no"]
87
+ self.score_linear = self.get_binary_linear(lm, token_true_id, token_false_id)
88
+ self.score_linear.eval()
89
+ self.score_linear.to(self.device).to(self.model.dtype)
90
+
91
+ def get_binary_linear(self, model, token_yes, token_no):
92
+
93
+ lm_head_weights = model.lm_head.weight.data
94
+
95
+ weight_yes = lm_head_weights[token_yes]
96
+ weight_no = lm_head_weights[token_no]
97
+
98
+ D = weight_yes.size()[0]
99
+ linear_layer = torch.nn.Linear(D, 1, bias=False)
100
+ with torch.no_grad():
101
+ linear_layer.weight[0] = weight_yes - weight_no
102
+ return linear_layer
103
+
104
+ @torch.no_grad()
105
+ def compute_scores(self, inputs):
106
+ batch_scores = self.model(**inputs).last_hidden_state[:, -1]
107
+ scores = self.score_linear(batch_scores)
108
+ scores = torch.sigmoid(scores).squeeze(-1).cpu().detach().tolist()
109
+ return scores
110
+
111
+ def truncate_tokens_optimized(
112
+ self,
113
+ tokens: List[str],
114
+ max_length: int,
115
+ special_tokens: List[str]
116
+ ) -> List[str]:
117
+ if len(tokens) <= max_length:
118
+ return tokens
119
+
120
+ special_tokens_set = set(special_tokens)
121
+
122
+ # Calculate budget: how many non-special tokens we can keep
123
+ num_special = sum(1 for token in tokens if token in special_tokens_set)
124
+ num_non_special_to_keep = max_length - num_special
125
+
126
+ # Build final list according to budget
127
+ final_tokens = []
128
+ non_special_kept_count = 0
129
+ for token in tokens:
130
+ if token in special_tokens_set:
131
+ final_tokens.append(token)
132
+ elif non_special_kept_count < num_non_special_to_keep:
133
+ final_tokens.append(token)
134
+ non_special_kept_count += 1
135
+
136
+ return final_tokens
137
+
138
+ def tokenize(self, pairs: list, **kwargs):
139
+ max_length = self.max_length
140
+ text = self.processor.apply_chat_template(pairs, tokenize=False, add_generation_prompt=True)
141
+ try:
142
+ images, videos, video_kwargs = process_vision_info(
143
+ pairs, image_patch_size=16,
144
+ return_video_kwargs=True,
145
+ return_video_metadata=True
146
+ )
147
+ except Exception as e:
148
+ logger.error(f"Error in processing vision info: {e}")
149
+ images = None
150
+ videos = None
151
+ video_kwargs = {'do_sample_frames': False}
152
+ text = self.processor.apply_chat_template(
153
+ [{'role': 'user', 'content': [{'type': 'text', 'text': 'NULL'}]}],
154
+ add_generation_prompt=True, tokenize=False
155
+ )
156
+
157
+ if videos is not None:
158
+ videos, video_metadatas = zip(*videos)
159
+ videos, video_metadatas = list(videos), list(video_metadatas)
160
+ else:
161
+ video_metadatas = None
162
+ inputs = self.processor(
163
+ text=text,
164
+ images=images,
165
+ videos=videos,
166
+ video_metadata=video_metadatas,
167
+ truncation=False,
168
+ padding=False,
169
+ do_resize=False,
170
+ **video_kwargs
171
+ )
172
+ for i, ele in enumerate(inputs['input_ids']):
173
+ inputs['input_ids'][i] = self.truncate_tokens_optimized(
174
+ inputs['input_ids'][i][:-5], max_length,
175
+ self.processor.tokenizer.all_special_ids
176
+ ) + inputs['input_ids'][i][-5:]
177
+ temp_inputs = self.processor.tokenizer.pad(
178
+ {'input_ids': inputs['input_ids']}, padding=True,
179
+ return_tensors="pt", max_length=self.max_length
180
+ )
181
+ for key in temp_inputs:
182
+ inputs[key] = temp_inputs[key]
183
+ return inputs
184
+
185
+ def format_mm_content(
186
+ self,
187
+ text, image, video,
188
+ prefix='Query:',
189
+ fps=None, max_frames=None,
190
+ ):
191
+ content = []
192
+
193
+ content.append({'type': 'text', 'text': prefix})
194
+ if not text and not image and not video:
195
+ content.append({'type': 'text', 'text': "NULL"})
196
+ return content
197
+
198
+ if video:
199
+ video_content = None
200
+ video_kwargs = { 'total_pixels': self.total_pixels }
201
+ if isinstance(video, list):
202
+ video_content = video
203
+ if self.num_frames is not None or self.max_frames is not None:
204
+ video_content = self._sample_frames(video_content, self.num_frames, self.max_frames)
205
+ video_content = [
206
+ ('file://' + ele if isinstance(ele, str) else ele)
207
+ for ele in video_content
208
+ ]
209
+ elif isinstance(video, str):
210
+ video_content = video if video.startswith(('http://', 'https://')) else 'file://' + video
211
+ video_kwargs = {'fps': fps or self.fps, 'max_frames': max_frames or self.max_frames,}
212
+ else:
213
+ raise TypeError(f"Unrecognized video type: {type(video)}")
214
+
215
+ if video_content:
216
+ content.append({
217
+ 'type': 'video', 'video': video_content,
218
+ **video_kwargs
219
+ })
220
+
221
+ if image:
222
+ image_content = None
223
+ if isinstance(image, Image.Image):
224
+ image_content = image
225
+ elif isinstance(image, str):
226
+ image_content = image if image.startswith(('http', 'oss')) else 'file://' + image
227
+ else:
228
+ raise TypeError(f"Unrecognized image type: {type(image)}")
229
+
230
+ if image_content:
231
+ content.append({
232
+ 'type': 'image', 'image': image_content,
233
+ "min_pixels": self.min_pixels,
234
+ "max_pixels": self.max_pixels
235
+ })
236
+
237
+ if text:
238
+ content.append({'type': 'text', 'text': text})
239
+ return content
240
+
241
+ def format_mm_instruction(
242
+ self,
243
+ query_text, query_image, query_video,
244
+ doc_text, doc_image, doc_video,
245
+ instruction=None,
246
+ fps=None, max_frames=None
247
+ ):
248
+ inputs = []
249
+ inputs.append({
250
+ "role": "system",
251
+ "content": [{
252
+ "type": "text",
253
+ "text": "Judge whether the Document meets the requirements based on the Query and the Instruct provided. Note that the answer can only be \"yes\" or \"no\"."
254
+ }
255
+ ]
256
+ })
257
+ if isinstance(query_text, tuple):
258
+ instruct, query_text = query_text
259
+ else:
260
+ instruct = instruction
261
+ contents = []
262
+ contents.append({
263
+ "type": "text",
264
+ "text": '<Instruct>: ' + instruct
265
+ })
266
+ query_content = self.format_mm_content(
267
+ query_text, query_image, query_video, prefix='<Query>:',
268
+ fps=fps, max_frames=max_frames
269
+ )
270
+ contents.extend(query_content)
271
+ doc_content = self.format_mm_content(
272
+ doc_text, doc_image, doc_video, prefix='\n<Document>:',
273
+ fps=fps, max_frames=max_frames
274
+ )
275
+ contents.extend(doc_content)
276
+ inputs.append({
277
+ "role": "user",
278
+ "content": contents
279
+ })
280
+ return inputs
281
+
282
+ def process(
283
+ self,
284
+ inputs,
285
+ ) -> list[torch.Tensor]:
286
+ instruction = inputs.get('instruction', self.default_instruction)
287
+
288
+ query = inputs.get("query", {})
289
+ documents = inputs.get("documents", [])
290
+ if not query or not documents:
291
+ return []
292
+
293
+ pairs = [self.format_mm_instruction(
294
+ query.get('text', None),
295
+ query.get('image', None),
296
+ query.get('video', None),
297
+ document.get('text', None),
298
+ document.get('image', None),
299
+ document.get('video', None),
300
+ instruction=instruction,
301
+ fps=inputs.get('fps', self.fps),
302
+ max_frames=inputs.get('max_frames', self.max_frames)
303
+ ) for document in documents]
304
+
305
+ final_scores = []
306
+ for pair in pairs:
307
+ inputs = self.tokenize([pair])
308
+ inputs = inputs.to(self.model.device)
309
+ scores = self.compute_scores(inputs)
310
+ final_scores.extend(scores)
311
+ return final_scores
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
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:be75606093db2094d7cd20f3c2f385c212750648bd6ea4fb2bf507a6a4c55506
3
+ size 11422650
tokenizer_config.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "backend": "tokenizers",
4
+ "bos_token": null,
5
+ "clean_up_tokenization_spaces": false,
6
+ "eos_token": "<|im_end|>",
7
+ "errors": "replace",
8
+ "is_local": true,
9
+ "model_max_length": 262144,
10
+ "pad_token": "<|endoftext|>",
11
+ "processor_class": "Qwen3VLProcessor",
12
+ "split_special_tokens": false,
13
+ "strict": true,
14
+ "tokenizer_class": "Qwen2Tokenizer",
15
+ "unk_token": null
16
+ }
video_preprocessor_config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "crop_size": null,
3
+ "data_format": "channels_first",
4
+ "default_to_square": true,
5
+ "device": null,
6
+ "do_center_crop": null,
7
+ "do_convert_rgb": true,
8
+ "do_normalize": true,
9
+ "do_rescale": true,
10
+ "do_resize": true,
11
+ "do_sample_frames": true,
12
+ "fps": 2,
13
+ "image_mean": [
14
+ 0.5,
15
+ 0.5,
16
+ 0.5
17
+ ],
18
+ "image_std": [
19
+ 0.5,
20
+ 0.5,
21
+ 0.5
22
+ ],
23
+ "input_data_format": null,
24
+ "max_frames": 768,
25
+ "merge_size": 2,
26
+ "min_frames": 4,
27
+ "num_frames": null,
28
+ "pad_size": null,
29
+ "patch_size": 16,
30
+ "processor_class": "Qwen3VLProcessor",
31
+ "resample": 3,
32
+ "rescale_factor": 0.00392156862745098,
33
+ "return_metadata": false,
34
+ "size": {
35
+ "longest_edge": 25165824,
36
+ "shortest_edge": 4096
37
+ },
38
+ "temporal_patch_size": 2,
39
+ "video_metadata": null,
40
+ "video_processor_type": "Qwen3VLVideoProcessor"
41
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff