alpharomercoma commited on
Commit
0aaa1f3
·
verified ·
1 Parent(s): 335b35b

Upload folder using huggingface_hub

Browse files
lora_adapter/README.md ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ base_model: LiquidAI/LFM3-VL-2B
3
+ library_name: peft
4
+ pipeline_tag: text-generation
5
+ tags:
6
+ - base_model:adapter:LiquidAI/LFM3-VL-2B
7
+ - lora
8
+ - sft
9
+ - transformers
10
+ - trl
11
+ ---
12
+
13
+ # Model Card for Model ID
14
+
15
+ <!-- Provide a quick summary of what the model is/does. -->
16
+
17
+
18
+
19
+ ## Model Details
20
+
21
+ ### Model Description
22
+
23
+ <!-- Provide a longer summary of what this model is. -->
24
+
25
+
26
+
27
+ - **Developed by:** [More Information Needed]
28
+ - **Funded by [optional]:** [More Information Needed]
29
+ - **Shared by [optional]:** [More Information Needed]
30
+ - **Model type:** [More Information Needed]
31
+ - **Language(s) (NLP):** [More Information Needed]
32
+ - **License:** [More Information Needed]
33
+ - **Finetuned from model [optional]:** [More Information Needed]
34
+
35
+ ### Model Sources [optional]
36
+
37
+ <!-- Provide the basic links for the model. -->
38
+
39
+ - **Repository:** [More Information Needed]
40
+ - **Paper [optional]:** [More Information Needed]
41
+ - **Demo [optional]:** [More Information Needed]
42
+
43
+ ## Uses
44
+
45
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
46
+
47
+ ### Direct Use
48
+
49
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
50
+
51
+ [More Information Needed]
52
+
53
+ ### Downstream Use [optional]
54
+
55
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
56
+
57
+ [More Information Needed]
58
+
59
+ ### Out-of-Scope Use
60
+
61
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
62
+
63
+ [More Information Needed]
64
+
65
+ ## Bias, Risks, and Limitations
66
+
67
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
68
+
69
+ [More Information Needed]
70
+
71
+ ### Recommendations
72
+
73
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
74
+
75
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
76
+
77
+ ## How to Get Started with the Model
78
+
79
+ Use the code below to get started with the model.
80
+
81
+ [More Information Needed]
82
+
83
+ ## Training Details
84
+
85
+ ### Training Data
86
+
87
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
88
+
89
+ [More Information Needed]
90
+
91
+ ### Training Procedure
92
+
93
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
94
+
95
+ #### Preprocessing [optional]
96
+
97
+ [More Information Needed]
98
+
99
+
100
+ #### Training Hyperparameters
101
+
102
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
103
+
104
+ #### Speeds, Sizes, Times [optional]
105
+
106
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
107
+
108
+ [More Information Needed]
109
+
110
+ ## Evaluation
111
+
112
+ <!-- This section describes the evaluation protocols and provides the results. -->
113
+
114
+ ### Testing Data, Factors & Metrics
115
+
116
+ #### Testing Data
117
+
118
+ <!-- This should link to a Dataset Card if possible. -->
119
+
120
+ [More Information Needed]
121
+
122
+ #### Factors
123
+
124
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
125
+
126
+ [More Information Needed]
127
+
128
+ #### Metrics
129
+
130
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
131
+
132
+ [More Information Needed]
133
+
134
+ ### Results
135
+
136
+ [More Information Needed]
137
+
138
+ #### Summary
139
+
140
+
141
+
142
+ ## Model Examination [optional]
143
+
144
+ <!-- Relevant interpretability work for the model goes here -->
145
+
146
+ [More Information Needed]
147
+
148
+ ## Environmental Impact
149
+
150
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
151
+
152
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
153
+
154
+ - **Hardware Type:** [More Information Needed]
155
+ - **Hours used:** [More Information Needed]
156
+ - **Cloud Provider:** [More Information Needed]
157
+ - **Compute Region:** [More Information Needed]
158
+ - **Carbon Emitted:** [More Information Needed]
159
+
160
+ ## Technical Specifications [optional]
161
+
162
+ ### Model Architecture and Objective
163
+
164
+ [More Information Needed]
165
+
166
+ ### Compute Infrastructure
167
+
168
+ [More Information Needed]
169
+
170
+ #### Hardware
171
+
172
+ [More Information Needed]
173
+
174
+ #### Software
175
+
176
+ [More Information Needed]
177
+
178
+ ## Citation [optional]
179
+
180
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
181
+
182
+ **BibTeX:**
183
+
184
+ [More Information Needed]
185
+
186
+ **APA:**
187
+
188
+ [More Information Needed]
189
+
190
+ ## Glossary [optional]
191
+
192
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
193
+
194
+ [More Information Needed]
195
+
196
+ ## More Information [optional]
197
+
198
+ [More Information Needed]
199
+
200
+ ## Model Card Authors [optional]
201
+
202
+ [More Information Needed]
203
+
204
+ ## Model Card Contact
205
+
206
+ [More Information Needed]
207
+ ### Framework versions
208
+
209
+ - PEFT 0.21.2
lora_adapter/adapter_config.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "alora_invocation_tokens": null,
3
+ "alpha_pattern": {},
4
+ "arrow_config": null,
5
+ "auto_mapping": null,
6
+ "base_model_name_or_path": "LiquidAI/LFM3-VL-2B",
7
+ "bias": "none",
8
+ "corda_config": null,
9
+ "ensure_weight_tying": false,
10
+ "eva_config": null,
11
+ "exclude_modules": null,
12
+ "fan_in_fan_out": false,
13
+ "inference_mode": true,
14
+ "init_lora_weights": true,
15
+ "kasa_config": null,
16
+ "layer_replication": null,
17
+ "layers_pattern": null,
18
+ "layers_to_transform": null,
19
+ "loftq_config": {},
20
+ "lora_alpha": 128,
21
+ "lora_bias": false,
22
+ "lora_dropout": 0.05,
23
+ "lora_ga_config": null,
24
+ "megatron_config": null,
25
+ "megatron_core": "megatron.core",
26
+ "modules_to_save": null,
27
+ "monteclora_config": null,
28
+ "peft_type": "LORA",
29
+ "peft_version": "0.21.2",
30
+ "qalora_group_size": 16,
31
+ "r": 64,
32
+ "rank_pattern": {},
33
+ "revision": null,
34
+ "target_modules": ".*language_model.*\\.(q_proj|k_proj|v_proj|o_proj|gate_proj|in_proj|out_proj|w1|w2|w3)",
35
+ "target_parameters": null,
36
+ "task_type": "CAUSAL_LM",
37
+ "trainable_token_indices": null,
38
+ "use_bdlora": null,
39
+ "use_dora": false,
40
+ "use_qalora": false,
41
+ "use_rslora": false,
42
+ "velora_config": null
43
+ }
lora_adapter/adapter_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e34c334875131cb7cb64ad9900ff30649fbedffc6ac5e669a4ecb762c9473e2d
3
+ size 263545648
lora_adapter/chat_template.jinja ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {{- bos_token -}}
2
+ {%- set preserve_thinking = preserve_thinking | default(false) -%}
3
+ {%- set enable_thinking = enable_thinking | default(true) -%}
4
+
5
+ {%- macro render_value(v) -%}
6
+ {%- if v is string -%}
7
+ {{- v -}}
8
+ {%- elif v is boolean -%}
9
+ {{- "true" if v else "false" -}}
10
+ {%- elif v is none -%}
11
+ {{- "null" -}}
12
+ {%- elif v is mapping or (v is sequence and v is not string) -%}
13
+ {{- v | tojson -}}
14
+ {%- else -%}
15
+ {{- v -}}
16
+ {%- endif -%}
17
+ {%- endmacro -%}
18
+
19
+ {%- macro parse_content(content) -%}
20
+ {%- if content is string -%}
21
+ {{- content -}}
22
+ {%- elif content is mapping and content.get("type") == "image" -%}
23
+ {{- "<|vision_start|><|image|><|vision_end|>" -}}
24
+ {%- elif content is mapping and content.get("type") == "video" -%}
25
+ {{- "<|vision_start|><|video|><|vision_end|>" -}}
26
+ {%- elif content is mapping and content.get("type") == "text" -%}
27
+ {{- (content.get("text") or "") | string -}}
28
+ {%- elif content is mapping -%}
29
+ {{- content | tojson -}}
30
+ {%- elif content is iterable -%}
31
+ {%- set _ns = namespace(result="") -%}
32
+ {%- for item in content -%}
33
+ {%- if item is string -%}
34
+ {%- set _ns.result = _ns.result + item -%}
35
+ {%- elif item is mapping and item.get("type") == "image" -%}
36
+ {%- set _ns.result = _ns.result + "<|vision_start|><|image|><|vision_end|>" -%}
37
+ {%- elif item is mapping and item.get("type") == "video" -%}
38
+ {%- set _ns.result = _ns.result + "<|vision_start|><|video|><|vision_end|>" -%}
39
+ {%- elif item is mapping and item.get("type") == "text" -%}
40
+ {%- set _ns.result = _ns.result + ((item.get("text") or "") | string) -%}
41
+ {%- else -%}
42
+ {%- set _ns.result = _ns.result + (item | tojson) -%}
43
+ {%- endif -%}
44
+ {%- endfor -%}
45
+ {{- _ns.result -}}
46
+ {%- elif content is not none -%}
47
+ {{- content | tojson -}}
48
+ {%- endif -%}
49
+ {%- endmacro -%}
50
+
51
+ {%- macro render_tool_calls(tool_calls) -%}
52
+ {%- for tool_call in tool_calls -%}
53
+ {%- if not loop.first -%}{{- "\n\n" -}}{%- endif -%}
54
+ {%- set func = tool_call["function"] if "function" in tool_call else tool_call -%}
55
+ {%- set func_args = func.get("arguments") -%}
56
+ {%- if func_args is string and (func_args | trim) not in ["", "{}", "null"] -%}
57
+ {{- raise_exception("Tool call arguments must be a mapping, got a JSON-encoded string: parse arguments with json.loads() before applying the chat template") -}}
58
+ {%- endif -%}
59
+ {{- "<tool_call>\n<function=" + func["name"] + ">\n" -}}
60
+ {%- if func_args is mapping -%}
61
+ {%- for arg_name, arg_value in func_args.items() -%}
62
+ {{- "<parameter=" + arg_name + ">\n" + render_value(arg_value) + "\n</parameter>\n" -}}
63
+ {%- endfor -%}
64
+ {%- endif -%}
65
+ {{- "</function>\n</tool_call>" -}}
66
+ {%- endfor -%}
67
+ {%- endmacro -%}
68
+
69
+ {%- macro tool_to_json(tool) -%}
70
+ {%- set fn = tool.function if tool.function is defined else tool -%}
71
+ {%- set ns_t = namespace(first=true) -%}
72
+ {{- "{" -}}
73
+ {%- for k, v in fn.items() -%}
74
+ {%- if k != "defer_loading" -%}
75
+ {%- if not ns_t.first -%}{{- ", " -}}{%- endif -%}
76
+ {%- set ns_t.first = false -%}
77
+ {{- k | tojson -}}{{- ": " -}}{{- v | tojson -}}
78
+ {%- endif -%}
79
+ {%- endfor -%}
80
+ {{- "}" -}}
81
+ {%- endmacro -%}
82
+
83
+ {%- macro is_tool_reference(item) -%}
84
+ {{- "1" if item is mapping and item.get("type") == "tool_reference" else "" -}}
85
+ {%- endmacro -%}
86
+
87
+ {%- macro referenced_tool_to_json(name) -%}
88
+ {%- set _ns = namespace(found=none) -%}
89
+ {%- for tool in tools or [] -%}
90
+ {%- set fn = tool.function if tool.function is defined else tool -%}
91
+ {%- if fn.name == name -%}
92
+ {%- set _ns.found = fn -%}
93
+ {%- endif -%}
94
+ {%- endfor -%}
95
+ {%- if _ns.found is none -%}
96
+ {{- raise_exception("Tool reference '" + name | string + "' not found in available tools. Every tool referenced by a tool_reference must be in `tools` on every request.") -}}
97
+ {%- endif -%}
98
+ {{- tool_to_json(_ns.found) -}}
99
+ {%- endmacro -%}
100
+
101
+ {%- macro render_tool_response(content) -%}
102
+ {%- if content is string and "<tool_response>" in content -%}
103
+ {{- content -}}
104
+ {%- else -%}
105
+ {{- "<tool_response>\n" -}}
106
+ {%- if content is string -%}
107
+ {{- content -}}
108
+ {%- elif content is mapping -%}
109
+ {{- parse_content(content) -}}
110
+ {%- elif content is iterable -%}
111
+ {%- for item in content -%}
112
+ {%- if not loop.first -%}{{- "\n" -}}{%- endif -%}
113
+ {%- if is_tool_reference(item) -%}
114
+ {%- if loop.first or not is_tool_reference(loop.previtem) -%}
115
+ {{- "<additional_tools>\n" -}}
116
+ {%- endif -%}
117
+ {{- referenced_tool_to_json(item.name) -}}
118
+ {%- if loop.last or not is_tool_reference(loop.nextitem) -%}
119
+ {{- "\n</additional_tools>" -}}
120
+ {%- endif -%}
121
+ {%- elif item is mapping and item.result is defined and item.result is mapping and item.result.tools is defined -%}
122
+ {{- "<additional_tools>\n" -}}
123
+ {%- set _tl = item.result.tools -%}
124
+ {%- if _tl is string -%}
125
+ {{- _tl -}}
126
+ {%- elif _tl is mapping -%}
127
+ {{- tool_to_json(_tl) -}}
128
+ {%- else -%}
129
+ {%- for t in _tl -%}
130
+ {%- if not loop.first -%}{{- "\n" -}}{%- endif -%}
131
+ {{- tool_to_json(t) -}}
132
+ {%- endfor -%}
133
+ {%- endif -%}
134
+ {{- "\n</additional_tools>" -}}
135
+ {%- else -%}
136
+ {{- parse_content(item) -}}
137
+ {%- endif -%}
138
+ {%- endfor -%}
139
+ {%- elif content is not none -%}
140
+ {{- content | tojson -}}
141
+ {%- endif -%}
142
+ {{- "\n</tool_response>" -}}
143
+ {%- endif -%}
144
+ {%- endmacro -%}
145
+
146
+ {%- set ns = namespace(system_prompt="", last_user_index=-1) -%}
147
+ {%- if messages and messages[0]["role"] == "system" -%}
148
+ {%- if messages[0].get("content") -%}
149
+ {%- set ns.system_prompt = parse_content(messages[0]["content"]) -%}
150
+ {%- endif -%}
151
+ {%- set messages = messages[1:] -%}
152
+ {%- endif -%}
153
+ {%- if tools -%}
154
+ {%- set tools_ns = namespace(lines=[]) -%}
155
+ {%- for tool in tools -%}
156
+ {%- set fn = tool.function if tool.function is defined else tool -%}
157
+ {%- set _dyn = (fn.defer_loading is defined and fn.defer_loading) or (tool.defer_loading is defined and tool.defer_loading) -%}
158
+ {%- if not _dyn -%}
159
+ {%- set tools_ns.lines = tools_ns.lines + [tool_to_json(fn)] -%}
160
+ {%- endif -%}
161
+ {%- endfor -%}
162
+ {%- if tools_ns.lines -%}
163
+ {%- set ns.system_prompt = ns.system_prompt + ("\n\n" if ns.system_prompt else "") + "<tools>\n" + (tools_ns.lines | join("\n")) + "\n</tools>" -%}
164
+ {%- endif -%}
165
+ {%- endif -%}
166
+ {%- if ns.system_prompt -%}
167
+ {{- "<|im_start|>system\n" + ns.system_prompt + "<|im_end|>\n" -}}
168
+ {%- endif -%}
169
+ {%- for message in messages -%}
170
+ {%- if message["role"] == "user" -%}
171
+ {%- set ns.last_user_index = loop.index0 -%}
172
+ {%- endif -%}
173
+ {%- endfor -%}
174
+ {%- set carry = namespace(pending=[]) -%}
175
+ {%- for message in messages -%}
176
+ {%- set _next = messages[loop.index0 + 1] if not loop.last else none -%}
177
+ {%- set _merge = message.role == "tool" and not message.get("additional_tools")
178
+ and _next is not none and _next.role == "tool" and not _next.get("additional_tools")
179
+ and message.get("tool_call_id") and _next.get("tool_call_id") == message.get("tool_call_id") -%}
180
+ {%- set _items = [] -%}
181
+ {%- if message.role == "tool" and not message.get("additional_tools") -%}
182
+ {%- set _c = message.get("content") -%}
183
+ {%- if _c is string -%}
184
+ {%- set _items = [{"type": "text", "text": _c}] if _c else [] -%}
185
+ {%- elif _c is mapping -%}
186
+ {%- set _items = [_c] -%}
187
+ {%- elif _c is iterable -%}
188
+ {%- set _items = _c | list -%}
189
+ {%- elif _c is not none -%}
190
+ {%- set _items = [_c] -%}
191
+ {%- endif -%}
192
+ {%- endif -%}
193
+ {%- if _merge -%}
194
+ {%- set carry.pending = carry.pending + _items -%}
195
+ {%- else -%}
196
+ {{- "<|im_start|>" + message.role + "\n" -}}
197
+ {%- if message.role == "assistant" -%}
198
+ {%- generation -%}
199
+ {%- set thinking = message.thinking if message.thinking is defined else message.reasoning if message.reasoning is defined else message.reasoning_content -%}
200
+ {%- set keep_thinking = preserve_thinking or loop.index0 > ns.last_user_index -%}
201
+ {%- if thinking is defined and keep_thinking -%}
202
+ {{- "<think>" + (thinking or "") + "</think>" -}}
203
+ {%- elif keep_thinking and "</think>" not in (message.get("content") if message.get("content") is string else "") -%}
204
+ {{- "<think></think>" -}}
205
+ {%- endif -%}
206
+ {%- set _cfm_tag = "CONTINUE_FINAL_MESSAGE_TAG " -%}
207
+ {%- set _has_cfm = false -%}
208
+ {%- set content = "" -%}
209
+ {%- if message.get("content") -%}
210
+ {%- set content = parse_content(message.content) -%}
211
+ {%- endif -%}
212
+ {%- if not keep_thinking -%}
213
+ {%- if "</think>" in content -%}
214
+ {%- set content = content.split("</think>")[-1] | trim -%}
215
+ {%- endif -%}
216
+ {%- set content = "<think></think>" + content -%}
217
+ {%- endif -%}
218
+ {%- if content.endswith(_cfm_tag) -%}
219
+ {%- set _has_cfm = true -%}
220
+ {%- set _trunc_len = (content | length) - (_cfm_tag | length) -%}
221
+ {%- set content = content[:_trunc_len] -%}
222
+ {%- endif -%}
223
+ {{- content -}}
224
+ {%- if message.tool_calls -%}
225
+ {{- render_tool_calls(message.tool_calls) -}}
226
+ {%- endif -%}
227
+ {%- if _has_cfm -%}
228
+ {{- _cfm_tag -}}
229
+ {%- endif -%}
230
+ {{- "<|im_end|>\n" -}}
231
+ {%- endgeneration -%}
232
+ {%- elif message.role == "tool" -%}
233
+ {%- if message.get("additional_tools") -%}
234
+ {%- set _at = message["additional_tools"] -%}
235
+ {%- if _at is mapping or (_at is sequence and _at is not string) -%}
236
+ {%- set _src = _at -%}
237
+ {%- else -%}
238
+ {%- set _src = message.get("content") -%}
239
+ {%- endif -%}
240
+ {%- if _src is string and "<tool_response>" in _src -%}
241
+ {{- _src -}}
242
+ {%- elif _src is string and "<additional_tools>" in _src -%}
243
+ {{- "<tool_response>\n" + _src + "\n</tool_response>" -}}
244
+ {%- elif _src -%}
245
+ {{- "<tool_response>\n<additional_tools>\n" -}}
246
+ {%- if _src is string -%}
247
+ {{- _src -}}
248
+ {%- elif _src is mapping -%}
249
+ {{- tool_to_json(_src) -}}
250
+ {%- else -%}
251
+ {%- for t in _src -%}
252
+ {%- if not loop.first -%}{{- "\n" -}}{%- endif -%}
253
+ {{- tool_to_json(t) -}}
254
+ {%- endfor -%}
255
+ {%- endif -%}
256
+ {{- "\n</additional_tools>\n</tool_response>" -}}
257
+ {%- endif -%}
258
+ {%- elif carry.pending -%}
259
+ {{- render_tool_response(carry.pending + _items) -}}
260
+ {%- set carry.pending = [] -%}
261
+ {%- else -%}
262
+ {{- render_tool_response("" if message.get("content") is none else message.get("content")) -}}
263
+ {%- endif -%}
264
+ {{- "<|im_end|>\n" -}}
265
+ {%- else %}
266
+ {%- if message.get("content") -%}
267
+ {{- parse_content(message["content"]) -}}
268
+ {%- endif -%}
269
+ {{- "<|im_end|>\n" -}}
270
+ {%- endif %}
271
+ {%- endif -%}
272
+ {%- endfor -%}
273
+ {%- if add_generation_prompt -%}
274
+ {{- "<|im_start|>assistant\n" -}}
275
+ {%- if enable_thinking -%}
276
+ {{- "<think>" -}}
277
+ {%- else -%}
278
+ {{- "<think></think>" -}}
279
+ {%- endif -%}
280
+ {%- endif -%}
lora_adapter/image_processing_lfm3_vl.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Team. All rights reserved.
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
+ import math
15
+ import warnings
16
+ from collections.abc import Iterable
17
+
18
+ import torch
19
+ from torchvision.transforms.v2 import functional as tvF
20
+
21
+ from transformers.image_processing_backends import TorchvisionBackend
22
+ from transformers.image_processing_utils import BatchFeature
23
+ from transformers.image_transforms import group_images_by_shape, reorder_images
24
+ from transformers.image_utils import ImageInput, PILImageResampling, SizeDict
25
+ from transformers.processing_utils import ImagesKwargs, Unpack
26
+ from transformers.utils import TensorType, auto_docstring
27
+
28
+
29
+ class Lfm3VlImageProcessorKwargs(ImagesKwargs, total=False):
30
+ r"""
31
+ min_pixels (`int`, *optional*, defaults to `56 * 56`):
32
+ The min pixels of the image to resize the image.
33
+ max_pixels (`int`, *optional*, defaults to `28 * 28 * 1280`):
34
+ The max pixels of the image to resize the image.
35
+ patch_size (`int`, *optional*, defaults to 14):
36
+ The spatial patch size of the vision encoder.
37
+ temporal_patch_size (`int`, *optional*, defaults to 2):
38
+ The temporal patch size of the vision encoder.
39
+ merge_size (`int`, *optional*, defaults to 2):
40
+ The merge size of the vision encoder to llm encoder.
41
+ """
42
+
43
+ min_pixels: int
44
+ max_pixels: int
45
+ patch_size: int
46
+ temporal_patch_size: int
47
+ merge_size: int
48
+
49
+
50
+ def smart_resize(
51
+ height: int, width: int, factor: int = 28, min_pixels: int = 56 * 56, max_pixels: int = 14 * 14 * 4 * 1280
52
+ ):
53
+ """Rescales the image so that the following conditions are met:
54
+
55
+ 1. Both dimensions (height and width) are divisible by 'factor'.
56
+
57
+ 2. The total number of pixels is within the range ['min_pixels', 'max_pixels'].
58
+
59
+ 3. The aspect ratio of the image is maintained as closely as possible.
60
+
61
+ """
62
+ if max(height, width) / min(height, width) > 200:
63
+ raise ValueError(
64
+ f"absolute aspect ratio must be smaller than 200, got {max(height, width) / min(height, width)}"
65
+ )
66
+ h_bar = round(height / factor) * factor
67
+ w_bar = round(width / factor) * factor
68
+ if h_bar * w_bar > max_pixels:
69
+ beta = math.sqrt((height * width) / max_pixels)
70
+ h_bar = max(factor, math.floor(height / beta / factor) * factor)
71
+ w_bar = max(factor, math.floor(width / beta / factor) * factor)
72
+ elif h_bar * w_bar < min_pixels:
73
+ beta = math.sqrt(min_pixels / (height * width))
74
+ h_bar = math.ceil(height * beta / factor) * factor
75
+ w_bar = math.ceil(width * beta / factor) * factor
76
+ return h_bar, w_bar
77
+
78
+
79
+ @auto_docstring
80
+ class Lfm3VlImageProcessor(TorchvisionBackend):
81
+ do_resize = True
82
+ resample = PILImageResampling.BICUBIC
83
+ size = {"shortest_edge": 65_536, "longest_edge": 16_777_216}
84
+ default_to_square = False
85
+ do_rescale = True
86
+ do_normalize = True
87
+ image_mean = [0.5, 0.5, 0.5]
88
+ image_std = [0.5, 0.5, 0.5]
89
+ do_convert_rgb = True
90
+ patch_size = 16
91
+ temporal_patch_size = 2
92
+ merge_size = 2
93
+ valid_kwargs = Lfm3VlImageProcessorKwargs
94
+ model_input_names = ["pixel_values", "image_grid_thw"]
95
+
96
+ def __init__(self, **kwargs: Unpack[Lfm3VlImageProcessorKwargs]):
97
+ # backward compatibility: override size with min_pixels and max_pixels if they are provided
98
+ size = kwargs.pop("size", None)
99
+ size = dict(self.size) if size is None else size
100
+ if (min_pixels := kwargs.pop("min_pixels", None)) is not None:
101
+ size["shortest_edge"] = min_pixels
102
+ size.pop("min_pixels", None)
103
+ if (max_pixels := kwargs.pop("max_pixels", None)) is not None:
104
+ size["longest_edge"] = max_pixels
105
+ size.pop("max_pixels", None)
106
+ super().__init__(size=size, **kwargs)
107
+
108
+ def _standardize_kwargs(
109
+ self,
110
+ size: int | Iterable[int] | dict[str, int] | SizeDict | None = None,
111
+ min_pixels: int | None = None,
112
+ max_pixels: int | None = None,
113
+ **kwargs,
114
+ ) -> dict:
115
+ if min_pixels is not None or max_pixels is not None:
116
+ warnings.warn(
117
+ "Passing `min_pixels` and `max_pixels` to a processor call is deprecated and will be removed in v5.23. "
118
+ "Pass in `size={'longest_edge': xxx, 'shortest_edge': xxx} to override the target size.`",
119
+ FutureWarning,
120
+ )
121
+
122
+ size_dict = dict(size) if isinstance(size, (dict, SizeDict)) else {}
123
+ if min_pixels is not None:
124
+ size_dict["shortest_edge"] = min_pixels
125
+ if max_pixels is not None:
126
+ size_dict["longest_edge"] = max_pixels
127
+ size = SizeDict(**size_dict)
128
+ return super()._standardize_kwargs(size=size, **kwargs)
129
+
130
+ @auto_docstring
131
+ def preprocess(
132
+ self,
133
+ images: ImageInput,
134
+ **kwargs: Unpack[Lfm3VlImageProcessorKwargs],
135
+ ) -> BatchFeature:
136
+ return super().preprocess(images, **kwargs)
137
+
138
+ def resize(
139
+ self,
140
+ images: "torch.Tensor",
141
+ size: SizeDict,
142
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None",
143
+ factor: int,
144
+ **kwargs,
145
+ ) -> "torch.Tensor":
146
+ """Resize dynamically based on input image aspect ratio."""
147
+ if not size.shortest_edge or not size.longest_edge:
148
+ raise ValueError(f"`size` dict must contain 'shortest_edge' and 'longest_edge' keys but got {size}.")
149
+
150
+ height, width = images.shape[-2:]
151
+ resized_height, resized_width = smart_resize(
152
+ height,
153
+ width,
154
+ factor=factor,
155
+ min_pixels=size.shortest_edge,
156
+ max_pixels=size.longest_edge,
157
+ )
158
+ return super().resize(
159
+ image=images,
160
+ size=SizeDict(height=resized_height, width=resized_width),
161
+ resample=resample,
162
+ )
163
+
164
+ def patchify(
165
+ self,
166
+ images: "torch.Tensor",
167
+ patch_size: int,
168
+ merge_size: int,
169
+ temporal_patch_size: int,
170
+ ) -> tuple["torch.Tensor", int, int]:
171
+ """Patchifies each image into flat layout of shape (`seq_len`, `patch_dim`) so we can concat dynamically shaped pixels."""
172
+ batch_size, channel, resized_height, resized_width = images.shape
173
+ grid_h, grid_w = resized_height // patch_size, resized_width // patch_size
174
+ patches = images.reshape(
175
+ batch_size,
176
+ channel,
177
+ grid_h // merge_size,
178
+ merge_size,
179
+ patch_size,
180
+ grid_w // merge_size,
181
+ merge_size,
182
+ patch_size,
183
+ )
184
+ # Reorder dimensions to group grid and patch information for subsequent flattening.
185
+ # [batch, grid_h/merge, grid_w/merge, merge, merge, channel, patch, patch]
186
+ patches = patches.permute(0, 2, 5, 3, 6, 1, 4, 7)
187
+
188
+ flatten_patches = (
189
+ patches.unsqueeze(6)
190
+ .expand(-1, -1, -1, -1, -1, -1, temporal_patch_size, -1, -1)
191
+ .reshape(
192
+ batch_size,
193
+ grid_h * grid_w,
194
+ channel * temporal_patch_size * patch_size * patch_size,
195
+ )
196
+ )
197
+ return flatten_patches, grid_h, grid_w
198
+
199
+ def _preprocess(
200
+ self,
201
+ images: list["torch.Tensor"],
202
+ do_resize: bool,
203
+ size: SizeDict,
204
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None",
205
+ do_rescale: bool,
206
+ rescale_factor: float,
207
+ do_normalize: bool,
208
+ image_mean: float | list[float] | None,
209
+ image_std: float | list[float] | None,
210
+ patch_size: int,
211
+ temporal_patch_size: int,
212
+ merge_size: int,
213
+ disable_grouping: bool | None,
214
+ return_tensors: str | TensorType | None,
215
+ **kwargs,
216
+ ) -> BatchFeature:
217
+ grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
218
+ resized_images_grouped = {}
219
+ for shape, stacked_images in grouped_images.items():
220
+ if do_resize:
221
+ stacked_images = self.resize(
222
+ images=stacked_images,
223
+ size=size,
224
+ resample=resample,
225
+ factor=patch_size * merge_size,
226
+ )
227
+ resized_images_grouped[shape] = stacked_images
228
+ resized_images = reorder_images(resized_images_grouped, grouped_images_index)
229
+
230
+ grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping)
231
+ processed_images_grouped = {}
232
+ processed_grids = {}
233
+ for shape, stacked_images in grouped_images.items():
234
+ stacked_images = self.rescale_and_normalize(
235
+ stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
236
+ )
237
+ patches, grid_h, grid_w = self.patchify(
238
+ stacked_images,
239
+ patch_size=patch_size,
240
+ merge_size=merge_size,
241
+ temporal_patch_size=temporal_patch_size,
242
+ )
243
+
244
+ processed_images_grouped[shape] = patches
245
+ processed_grids[shape] = [[1, grid_h, grid_w]] * len(stacked_images)
246
+
247
+ processed_images = reorder_images(processed_images_grouped, grouped_images_index)
248
+ processed_grids_ordered = reorder_images(processed_grids, grouped_images_index)
249
+ pixel_values = processed_images[0] if len(processed_images) == 1 else torch.cat(processed_images, dim=0)
250
+ image_grid_thw = torch.tensor(processed_grids_ordered, dtype=torch.long)
251
+
252
+ return BatchFeature(
253
+ data={"pixel_values": pixel_values, "image_grid_thw": image_grid_thw}, tensor_type=return_tensors
254
+ )
255
+
256
+ def get_number_of_image_patches(self, height: int, width: int, images_kwargs: dict | None = None) -> int:
257
+ """
258
+ A utility that returns number of image patches for a given image size.
259
+
260
+ Note: Do not remove this method! It is used by vLLM to infer the number of patches and placeholders
261
+ without an image input.
262
+
263
+ Args:
264
+ height (`int`):
265
+ Height of the input image.
266
+ width (`int`):
267
+ Width of the input image.
268
+ images_kwargs (`dict`, *optional*)
269
+ Any kwargs to override defaults of the image processor.
270
+ Returns:
271
+ `int`: Number of image patches per image.
272
+ """
273
+ # `size` is the supported override (`min_pixels` / `max_pixels` are deprecated): count with the budget the
274
+ # preprocessing applies
275
+ images_kwargs = dict(images_kwargs or {})
276
+ size = images_kwargs.pop("size", None) or self.size
277
+ images_kwargs.setdefault("min_pixels", size["shortest_edge"])
278
+ images_kwargs.setdefault("max_pixels", size["longest_edge"])
279
+ images_kwargs = images_kwargs or {}
280
+ min_pixels = images_kwargs["min_pixels"] if "min_pixels" in images_kwargs else self.size["shortest_edge"]
281
+ max_pixels = images_kwargs["max_pixels"] if "max_pixels" in images_kwargs else self.size["longest_edge"]
282
+ patch_size = images_kwargs.get("patch_size", self.patch_size)
283
+ merge_size = images_kwargs.get("merge_size", self.merge_size)
284
+
285
+ factor = patch_size * merge_size
286
+ resized_height, resized_width = smart_resize(
287
+ height, width, factor, min_pixels=min_pixels, max_pixels=max_pixels
288
+ )
289
+ grid_h, grid_w = resized_height // patch_size, resized_width // patch_size
290
+ return grid_h * grid_w
291
+
292
+
293
+ __all__ = ["Lfm3VlImageProcessor"]
lora_adapter/processing_lfm3_vl.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Team. All rights reserved.
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
+ import math
15
+
16
+ import numpy as np
17
+
18
+ from transformers.image_utils import is_pil_image, is_valid_image, make_flat_list_of_images
19
+ from transformers.processing_utils import MultiModalData, ProcessingKwargs, ProcessorMixin
20
+ from transformers.utils import auto_docstring, is_numpy_array, is_torch_tensor, logging
21
+ from transformers.video_utils import VideoMetadata, is_valid_video, make_batched_videos
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+
27
+ class Lfm3VlProcessorKwargs(ProcessingKwargs, total=False):
28
+ _defaults = {
29
+ "text_kwargs": {
30
+ "padding": False,
31
+ "return_token_type_ids": False,
32
+ "return_mm_token_type_ids": False,
33
+ },
34
+ "videos_kwargs": {"return_metadata": True},
35
+ }
36
+
37
+
38
+ def _check_video_fps(metadata: VideoMetadata) -> None:
39
+ if metadata.fps is not None and not (math.isfinite(metadata.fps) and metadata.fps > 0):
40
+ raise ValueError(f"`video_metadata.fps` must be a positive number, got {metadata.fps}")
41
+
42
+
43
+ def _media_per_prompt(media, is_item) -> list[int] | None:
44
+ # rows name the prompt that owns them while the expansion consumes media in flat order; a row is a list of whole
45
+ # items or one stacked batch, and a list of single frames is one video, not a row
46
+ if not isinstance(media, (list, tuple)):
47
+ return None
48
+ counts = []
49
+ for row in media:
50
+ if isinstance(row, (list, tuple)) and all(is_item(item) for item in row):
51
+ counts.append(len(row))
52
+ elif (is_numpy_array(row) or is_torch_tensor(row)) and row.ndim == 4 and (len(row) == 0 or is_item(row[0])):
53
+ counts.append(len(row))
54
+ else:
55
+ return None
56
+ return counts
57
+
58
+
59
+ def _check_vision_placeholder_counts(processor, prompts, images, videos) -> None:
60
+ for name, token, media, flatten, is_item in (
61
+ (
62
+ "images",
63
+ processor.image_token,
64
+ images,
65
+ make_flat_list_of_images,
66
+ lambda item: is_valid_image(item) and (is_pil_image(item) or item.ndim == 3),
67
+ ),
68
+ (
69
+ "videos",
70
+ processor.video_token,
71
+ videos,
72
+ make_batched_videos,
73
+ lambda item: isinstance(item, str) or (not is_pil_image(item) and is_valid_video(item)),
74
+ ),
75
+ ):
76
+ num_placeholders = sum(prompt.count(token) for prompt in prompts)
77
+ num_media = 0 if media is None else len(flatten(media))
78
+ if num_placeholders != num_media:
79
+ raise ValueError(f"Found {num_placeholders} {token} tokens in the text but received {num_media} {name}")
80
+ # one prompt cannot take another's media
81
+ per_prompt = _media_per_prompt(media, is_item) if len(prompts) > 1 else None
82
+ in_text = [prompt.count(token) for prompt in prompts]
83
+ if per_prompt is not None and per_prompt != in_text:
84
+ raise ValueError(f"Found {in_text} {token} tokens per prompt but received {per_prompt} {name} per prompt")
85
+
86
+
87
+ @auto_docstring
88
+ class Lfm3VlProcessor(ProcessorMixin):
89
+ valid_processor_kwargs = Lfm3VlProcessorKwargs
90
+
91
+ def __init__(self, image_processor=None, tokenizer=None, video_processor=None, chat_template=None, **kwargs):
92
+ self.image_token = getattr(tokenizer, "image_token", "<|image|>")
93
+ self.video_token = getattr(tokenizer, "video_token", "<|video|>")
94
+ self.vision_start_token = getattr(tokenizer, "vision_start_token", "<|vision_start|>")
95
+ self.vision_end_token = getattr(tokenizer, "vision_end_token", "<|vision_end|>")
96
+ self.image_token_id = tokenizer.convert_tokens_to_ids(self.image_token)
97
+ self.video_token_id = tokenizer.convert_tokens_to_ids(self.video_token)
98
+ self.vision_start_token_id = tokenizer.convert_tokens_to_ids(self.vision_start_token)
99
+ self.vision_end_token_id = tokenizer.convert_tokens_to_ids(self.vision_end_token)
100
+ super().__init__(image_processor, tokenizer, video_processor, chat_template=chat_template)
101
+
102
+ def replace_image_token(self, image_inputs: dict, image_idx: int, **kwargs) -> str:
103
+ merge_length = self.image_processor.merge_size**2
104
+ num_image_tokens = image_inputs["image_grid_thw"][image_idx].prod() // merge_length
105
+ return self.image_token * num_image_tokens
106
+
107
+ def replace_video_token(self, video_inputs: dict, video_idx: int, **kwargs) -> str:
108
+ metadata = video_inputs["video_metadata"][video_idx]
109
+ if metadata.frames_indices is None:
110
+ raise ValueError("Frame timestamps need the sampled frame indices in `video_metadata`")
111
+ _check_video_fps(metadata)
112
+ merge_length = self.video_processor.merge_size**2
113
+ num_frames = video_inputs["video_grid_thw"][video_idx][0]
114
+ frame_seqlen = video_inputs["video_grid_thw"][video_idx][1:].prod() // merge_length
115
+ metadata = video_inputs["video_metadata"][video_idx]
116
+ video_placeholder = ""
117
+
118
+ if metadata.fps is None:
119
+ logger.warning_once(
120
+ "Lfm3Vl requires frame timestamps to construct prompts, but the `fps` of the input video could not be inferred. "
121
+ "Probably `video_metadata` was missing from inputs and you passed pre-sampled frames. "
122
+ "Defaulting to `fps=24`. Please provide `video_metadata` for more accurate results."
123
+ )
124
+ # a released transformers reads torchcodec's scanned average fps, which carries float noise
125
+ # (30.000000000000004) where the fork reads the container header
126
+ metadata.fps = 24 if metadata.fps is None else round(metadata.fps, 6)
127
+
128
+ # if timestamps are not provided, calculate them
129
+ curr_timestamp = self._calculate_timestamps(
130
+ metadata.frames_indices,
131
+ metadata.fps,
132
+ self.video_processor.temporal_patch_size,
133
+ )
134
+
135
+ for frame_idx in range(num_frames):
136
+ curr_time = curr_timestamp[frame_idx]
137
+ video_placeholder += f"<{curr_time:.1f} seconds>"
138
+ video_placeholder += self.vision_start_token + self.video_token * frame_seqlen + self.vision_end_token
139
+ return video_placeholder
140
+
141
+ def _get_num_multimodal_tokens(self, image_sizes=None, video_sizes=None, **kwargs):
142
+ """
143
+ Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
144
+
145
+ Args:
146
+ image_sizes (`list[list[int]]`, *optional*):
147
+ The input sizes formatted as (height, width) per each image.
148
+ video_sizes (`list[list[int]]`, *optional*):
149
+ The input sizes formatted as (num_frames, height, width) per each video.
150
+
151
+ Returns:
152
+ `MultiModalData`: the number of tokens per provided modality.
153
+ """
154
+ vision_data = {}
155
+ if image_sizes is not None:
156
+ # copy: `update` on the class-level defaults would leak kwargs into every later call
157
+ images_kwargs = dict(Lfm3VlProcessorKwargs._defaults.get("images_kwargs", {}))
158
+ images_kwargs.update(kwargs)
159
+ merge_size = images_kwargs.get("merge_size") or self.image_processor.merge_size
160
+
161
+ num_image_patches = [
162
+ self.image_processor.get_number_of_image_patches(*image_size, images_kwargs)
163
+ for image_size in image_sizes
164
+ ]
165
+ num_image_tokens = [(num_patches // merge_size**2) for num_patches in num_image_patches]
166
+ vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
167
+
168
+ if video_sizes is not None:
169
+ videos_kwargs = dict(Lfm3VlProcessorKwargs._defaults.get("videos_kwargs", {}))
170
+ videos_kwargs.update(kwargs)
171
+ merge_size = videos_kwargs.get("merge_size") or self.video_processor.merge_size
172
+ num_video_patches = [
173
+ self.video_processor.get_num_of_video_patches(*video_size, videos_kwargs) for video_size in video_sizes
174
+ ]
175
+ num_video_tokens = [(num_patches // merge_size**2) for num_patches in num_video_patches]
176
+ vision_data["num_video_tokens"] = num_video_tokens
177
+
178
+ return MultiModalData(**vision_data)
179
+
180
+ def post_process_image_text_to_text(
181
+ self, generated_outputs, skip_special_tokens=True, clean_up_tokenization_spaces=False, **kwargs
182
+ ):
183
+ """
184
+ Post-process the output of the model to decode the text.
185
+
186
+ Args:
187
+ generated_outputs (`torch.Tensor` or `np.ndarray`):
188
+ The output of the model `generate` function. The output is expected to be a tensor of shape `(batch_size, sequence_length)`
189
+ or `(sequence_length,)`.
190
+ skip_special_tokens (`bool`, *optional*, defaults to `True`):
191
+ Whether or not to remove special tokens in the output. Argument passed to the tokenizer's `batch_decode` method.
192
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
193
+ Whether or not to clean up the tokenization spaces. Argument passed to the tokenizer's `batch_decode` method.
194
+ **kwargs:
195
+ Additional arguments to be passed to the tokenizer's `batch_decode method`.
196
+
197
+ Returns:
198
+ `list[str]`: The decoded text.
199
+ """
200
+ return self.tokenizer.batch_decode(
201
+ generated_outputs,
202
+ skip_special_tokens=skip_special_tokens,
203
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
204
+ **kwargs,
205
+ )
206
+
207
+ @property
208
+ def model_input_names(self):
209
+ return list(
210
+ dict.fromkeys(
211
+ self.tokenizer.model_input_names
212
+ + self.image_processor.model_input_names
213
+ + self.video_processor.model_input_names
214
+ )
215
+ )
216
+
217
+ def _calculate_timestamps(self, indices: list[int] | np.ndarray, video_fps: float, merge_size: int = 2):
218
+ if not isinstance(indices, list):
219
+ indices = indices.tolist()
220
+ if len(indices) % merge_size != 0:
221
+ indices.extend(indices[-1] for _ in range(merge_size - len(indices) % merge_size))
222
+ timestamps = [idx / video_fps for idx in indices]
223
+ # @JJJYmmm frames are merged by self.merge_size, \
224
+ # so we need to average the timestamps between the first/last frame within the temporal patch
225
+ timestamps = [
226
+ (timestamps[i] + timestamps[i + merge_size - 1]) / 2 for i in range(0, len(timestamps), merge_size)
227
+ ]
228
+ return timestamps
229
+
230
+ def prepare_inputs_layout(self, images=None, text=None, videos=None, audio=None, **kwargs):
231
+ for name, media in (("images", images), ("videos", videos)):
232
+ if isinstance(media, (list, tuple)) and len(media) == 0:
233
+ raise ValueError(f"`{name}` must hold at least one item; pass `{name}=None` for prompts without one")
234
+ return super().prepare_inputs_layout(images=images, text=text, videos=videos, audio=audio, **kwargs)
235
+
236
+ def validate_inputs(self, images=None, text=None, videos=None, audio=None, **kwargs):
237
+ super().validate_inputs(images=images, text=text, videos=videos, audio=audio, **kwargs)
238
+ if text is not None:
239
+ _check_vision_placeholder_counts(self, [text] if isinstance(text, str) else text, images, videos)
240
+
241
+ def _process_videos(self, videos, **kwargs):
242
+ # the frame timestamps need the metadata whatever the caller's `return_metadata`; `__call__` drops it from
243
+ # the output unless it was asked for
244
+ kwargs["return_metadata"] = True
245
+ return super()._process_videos(videos, **kwargs)
246
+
247
+
248
+ __all__ = ["Lfm3VlProcessor"]
lora_adapter/processor_config.json ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoProcessor": "processing_lfm3_vl.Lfm3VlProcessor"
4
+ },
5
+ "image_processor": {
6
+ "auto_map": {
7
+ "AutoImageProcessor": "image_processing_lfm3_vl.Lfm3VlImageProcessor",
8
+ "AutoProcessor": "processing_lfm3_vl.Lfm3VlProcessor"
9
+ },
10
+ "do_convert_rgb": true,
11
+ "do_normalize": true,
12
+ "do_rescale": true,
13
+ "do_resize": true,
14
+ "image_mean": [
15
+ 0.5,
16
+ 0.5,
17
+ 0.5
18
+ ],
19
+ "image_processor_type": "Lfm3VlImageProcessor",
20
+ "image_std": [
21
+ 0.5,
22
+ 0.5,
23
+ 0.5
24
+ ],
25
+ "merge_size": 2,
26
+ "patch_size": 16,
27
+ "resample": 3,
28
+ "rescale_factor": 0.00392156862745098,
29
+ "size": {
30
+ "longest_edge": 774400,
31
+ "shortest_edge": 65536
32
+ },
33
+ "temporal_patch_size": 2
34
+ },
35
+ "processor_class": "Lfm3VlProcessor",
36
+ "video_processor": {
37
+ "auto_map": {
38
+ "AutoProcessor": "processing_lfm3_vl.Lfm3VlProcessor",
39
+ "AutoVideoProcessor": "video_processing_lfm3_vl.Lfm3VlVideoProcessor"
40
+ },
41
+ "cap_pixels_per_frame": false,
42
+ "do_convert_rgb": true,
43
+ "do_normalize": true,
44
+ "do_rescale": true,
45
+ "do_resize": true,
46
+ "do_sample_frames": true,
47
+ "fps": 2.0,
48
+ "image_mean": [
49
+ 0.5,
50
+ 0.5,
51
+ 0.5
52
+ ],
53
+ "image_std": [
54
+ 0.5,
55
+ 0.5,
56
+ 0.5
57
+ ],
58
+ "max_frames": 768,
59
+ "max_video_tokens": 768,
60
+ "merge_size": 2,
61
+ "min_frames": 4,
62
+ "patch_size": 16,
63
+ "resample": 3,
64
+ "rescale_factor": 0.00392156862745098,
65
+ "return_metadata": false,
66
+ "size": {
67
+ "longest_edge": 774400,
68
+ "shortest_edge": 65536
69
+ },
70
+ "temporal_patch_size": 2,
71
+ "video_processor_type": "Lfm3VlVideoProcessor"
72
+ }
73
+ }
lora_adapter/tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a39eed58008cbcbc09e5b629b81338a654269c64cd13348aaa6090f4db75c7e7
3
+ size 17908258
lora_adapter/tokenizer_config.json ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoProcessor": "processing_lfm3_vl.Lfm3VlProcessor"
4
+ },
5
+ "backend": "tokenizers",
6
+ "bos_token": "<|startoftext|>",
7
+ "eos_token": "<|im_end|>",
8
+ "extra_special_tokens": [],
9
+ "image_token": "<|image|>",
10
+ "is_local": false,
11
+ "local_files_only": false,
12
+ "model_max_length": 1000000000000000019884624838656,
13
+ "model_specific_special_tokens": {
14
+ "image_token": "<|image|>",
15
+ "video_token": "<|video|>",
16
+ "vision_end_token": "<|vision_end|>",
17
+ "vision_start_token": "<|vision_start|>"
18
+ },
19
+ "pad_token": "<|pad|>",
20
+ "processor_class": "Lfm3VlProcessor",
21
+ "response_template": {
22
+ "defaults": {
23
+ "role": "assistant"
24
+ },
25
+ "fields": {
26
+ "content": {
27
+ "close_pattern": "<\\|im_end\\|>\\s*",
28
+ "content": "text"
29
+ },
30
+ "reasoning_content": {
31
+ "close_pattern": "</think>\\s*",
32
+ "content": "text",
33
+ "open_pattern": "<think>\\n?"
34
+ },
35
+ "tool_calls": {
36
+ "close_pattern": "</tool_call>\\s*",
37
+ "content": "xml-inline",
38
+ "content_args": {
39
+ "tag_pattern": "<parameter=(?P<key>[^>\\n]+)>\\n?(?P<value>.*?)\\n?</parameter>(?=\\s*(?:<parameter=|</function>\\s*\\Z|\\Z))",
40
+ "value_parser": {
41
+ "args": {
42
+ "strip": false
43
+ },
44
+ "name": "text"
45
+ }
46
+ },
47
+ "open_pattern": "<tool_call>\\s*<function=(?P<name>[^\\n>]+)>",
48
+ "repeats": true,
49
+ "transform": {
50
+ "function": {
51
+ "arguments": "{content}",
52
+ "name": "{name}"
53
+ },
54
+ "type": "function"
55
+ }
56
+ }
57
+ },
58
+ "start_anchor_pattern": "<\\|im_start\\|>assistant\\n"
59
+ },
60
+ "size": {
61
+ "longest_edge": 774400,
62
+ "shortest_edge": 65536
63
+ },
64
+ "tokenizer_class": "TokenizersBackend",
65
+ "video_token": "<|video|>",
66
+ "vision_end_token": "<|vision_end|>",
67
+ "vision_start_token": "<|vision_start|>"
68
+ }
lora_adapter/training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:38b4eb765dafbc19bcb685dcd31d765a895857707a5af492e2950aa7563e151f
3
+ size 5777
lora_adapter/video_processing_lfm3_vl.py ADDED
@@ -0,0 +1,396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Team. All rights reserved.
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
+ import math
15
+
16
+ import numpy as np
17
+ import torch
18
+ from torchvision.transforms.v2 import functional as tvF
19
+
20
+ from transformers.image_processing_utils import BatchFeature
21
+ from transformers.image_utils import PILImageResampling, SizeDict
22
+ from transformers.processing_utils import Unpack, VideosKwargs
23
+ from transformers.utils import TensorType, auto_docstring, logging
24
+ from transformers.video_processing_utils import BaseVideoProcessor
25
+ from transformers.video_utils import (
26
+ VideoMetadata,
27
+ group_videos_by_shape,
28
+ make_batched_metadata,
29
+ make_batched_videos,
30
+ reorder_videos,
31
+ )
32
+
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ class Lfm3VlVideoProcessorInitKwargs(VideosKwargs, total=False):
38
+ r"""
39
+ patch_size (`int`, *optional*, defaults to 16):
40
+ The spatial patch size of the vision encoder.
41
+ temporal_patch_size (`int`, *optional*, defaults to 2):
42
+ The temporal patch size of the vision encoder.
43
+ merge_size (`int`, *optional*, defaults to 2):
44
+ The merge size of the vision encoder to llm encoder.
45
+ min_frames (`int`, *optional*, defaults to 4):
46
+ The minimum number of frames to sample from video.
47
+ max_frames (`int`, *optional*, defaults to 768):
48
+ The maximum number of frames to sample from video.
49
+ cap_pixels_per_frame (`bool`, *optional*):
50
+ Whether to cap each frame's pixel cost the way the reference implementation (qwen-vl-utils) does:
51
+ per-frame pixels are limited to `min(max_video_tokens * factor**2, size["longest_edge"] / num_frames)`
52
+ and floored at `1.05 * size["shortest_edge"]`, so token cost scales with clip duration. Without the
53
+ cap, videos that sample few frames spend the whole `size["longest_edge"]` budget on those frames and
54
+ keep near-native per-frame resolution, so a short clip can cost almost as many tokens as a long
55
+ video. If unset, the current uncapped behavior is kept and a warning is emitted: the default will
56
+ change to `True` in v5.22, after which the argument will be removed.
57
+ max_video_tokens (`int`, *optional*, defaults to 768):
58
+ The per-frame token ceiling applied by `cap_pixels_per_frame`, in vision tokens per frame
59
+ (qwen-vl-utils' `VIDEO_MAX_TOKEN_NUM`).
60
+ """
61
+
62
+ patch_size: int
63
+ temporal_patch_size: int
64
+ merge_size: int
65
+ min_frames: int
66
+ max_frames: int
67
+ cap_pixels_per_frame: bool
68
+ max_video_tokens: int
69
+
70
+
71
+ def smart_resize(
72
+ num_frames: int,
73
+ height: int,
74
+ width: int,
75
+ temporal_factor: int = 2,
76
+ factor: int = 28,
77
+ min_pixels: int = 112 * 112,
78
+ max_pixels: int = 14 * 14 * 2 * 2 * 2 * 6144,
79
+ ):
80
+ if num_frames < temporal_factor:
81
+ raise ValueError(f"t:{num_frames} must be larger than temporal_factor:{temporal_factor}")
82
+ if height < factor or width < factor:
83
+ scale = max(factor / height, factor / width)
84
+ height = int(height * scale)
85
+ width = int(width * scale)
86
+
87
+ if max(height, width) / min(height, width) > 200:
88
+ raise ValueError(
89
+ f"absolute aspect ratio must be smaller than 200, got {max(height, width) / min(height, width)}"
90
+ )
91
+ h_bar = round(height / factor) * factor
92
+ w_bar = round(width / factor) * factor
93
+ t_bar = round(num_frames / temporal_factor) * temporal_factor
94
+
95
+ if t_bar * h_bar * w_bar > max_pixels:
96
+ beta = math.sqrt((num_frames * height * width) / max_pixels)
97
+ h_bar = max(factor, math.floor(height / beta / factor) * factor)
98
+ w_bar = max(factor, math.floor(width / beta / factor) * factor)
99
+ elif t_bar * h_bar * w_bar < min_pixels:
100
+ beta = math.sqrt(min_pixels / (num_frames * height * width))
101
+ h_bar = math.ceil(height * beta / factor) * factor
102
+ w_bar = math.ceil(width * beta / factor) * factor
103
+
104
+ return h_bar, w_bar
105
+
106
+
107
+ def _check_video_fps(metadata: VideoMetadata) -> None:
108
+ if metadata.fps is not None and not (math.isfinite(metadata.fps) and metadata.fps > 0):
109
+ raise ValueError(f"`video_metadata.fps` must be a positive number, got {metadata.fps}")
110
+
111
+
112
+ def _check_video_metadata_count(videos, video_metadata) -> None:
113
+ # the shared sampler pairs clips with metadata by `zip`, which drops the clips past the last entry
114
+ if video_metadata is None:
115
+ return
116
+ videos = make_batched_videos(videos)
117
+ entries = make_batched_metadata(videos, video_metadata) if video_metadata != [] else []
118
+ if len(entries) != len(videos):
119
+ raise ValueError(
120
+ f"Received {len(videos)} videos but {len(entries)} `video_metadata` entries; pass one entry per video"
121
+ )
122
+
123
+
124
+ @auto_docstring
125
+ class Lfm3VlVideoProcessor(BaseVideoProcessor):
126
+ resample = PILImageResampling.BICUBIC
127
+ size = {"shortest_edge": 4_096, "longest_edge": 25_165_824}
128
+ image_mean = [0.5, 0.5, 0.5]
129
+ image_std = [0.5, 0.5, 0.5]
130
+ do_resize = True
131
+ do_rescale = True
132
+ do_normalize = True
133
+ do_convert_rgb = True
134
+ patch_size = 16
135
+ temporal_patch_size = 2
136
+ merge_size = 2
137
+ min_frames = 4
138
+ max_frames = 768
139
+ do_sample_frames = True
140
+ cap_pixels_per_frame = False
141
+ max_video_tokens = 768
142
+ valid_kwargs = Lfm3VlVideoProcessorInitKwargs
143
+ model_input_names = ["pixel_values_videos", "video_grid_thw"]
144
+ max_image_size = {"longest_edge": 28 * 28 * 2 * 30000}
145
+ max_duration = None
146
+ num_frames = None
147
+ fps = 2.0
148
+
149
+ def __init__(self, **kwargs: Unpack[Lfm3VlVideoProcessorInitKwargs]):
150
+ super().__init__(**kwargs)
151
+
152
+ def sample_frames(
153
+ self, metadata: VideoMetadata, num_frames: int | None = None, fps: int | float | None = None, **kwargs
154
+ ):
155
+ """Decoded frames whose metadata carries no fps are sampled and timestamped at the 24 fps the shared sampler
156
+ assumes (with a warning); pass `video_metadata` with the clip's fps for accurate timestamps."""
157
+ _check_video_fps(metadata)
158
+ if fps is not None and not (math.isfinite(fps) and fps > 0):
159
+ raise ValueError(f"`fps` must be a positive number, got {fps}")
160
+ if fps is not None and num_frames is not None:
161
+ raise ValueError("`num_frames` and `fps` are mutually exclusive arguments, please use only one!")
162
+
163
+ total_num_frames = metadata.total_num_frames
164
+ fps = fps if fps is not None else self.fps
165
+
166
+ # If num_frames is not given but fps is, calculate num_frames from fps
167
+ if num_frames is None and fps is not None:
168
+ if metadata.fps is None:
169
+ metadata.fps = 24
170
+ logger.warning_once(
171
+ "Asked to sample `fps` frames per second but no video metadata was provided which is required when sampling with `fps`. "
172
+ "Defaulting to `fps=24`. Please provide `video_metadata` for more accurate results."
173
+ )
174
+ num_frames = int(total_num_frames / metadata.fps * fps)
175
+ num_frames = min(max(num_frames, self.min_frames), self.max_frames, total_num_frames)
176
+
177
+ if num_frames is None:
178
+ num_frames = min(max(total_num_frames, self.min_frames), self.max_frames)
179
+
180
+ indices = np.linspace(0, total_num_frames - 1, num_frames).round().astype(int)
181
+
182
+ return indices
183
+
184
+ def resize(
185
+ self,
186
+ videos: "torch.Tensor",
187
+ size: SizeDict,
188
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None",
189
+ factor: int,
190
+ temporal_factor: int,
191
+ cap_pixels_per_frame: bool | None = None,
192
+ **kwargs,
193
+ ) -> "torch.Tensor":
194
+ """Resize dynamically based on input video aspect ratio."""
195
+ if not size.shortest_edge or not size.longest_edge:
196
+ raise ValueError(f"`size` dict must contain 'shortest_edge' and 'longest_edge' keys but got {size}.")
197
+
198
+ num_frames = videos.shape[1]
199
+ max_pixels = size.longest_edge
200
+ if cap_pixels_per_frame:
201
+ # per-frame pixels are capped at `max_video_tokens` patches or the budget's even share per frame
202
+ frame_cap = self.max_video_tokens * factor * factor
203
+ pixels_per_frame = max(min(frame_cap, size.longest_edge // num_frames), int(size.shortest_edge * 1.05))
204
+ max_pixels = pixels_per_frame * num_frames
205
+
206
+ height, width = videos.shape[-2:]
207
+ resized_height, resized_width = smart_resize(
208
+ height=height,
209
+ width=width,
210
+ num_frames=num_frames,
211
+ factor=factor,
212
+ temporal_factor=temporal_factor,
213
+ min_pixels=size.shortest_edge,
214
+ max_pixels=max_pixels,
215
+ )
216
+ return super().resize(
217
+ image=videos,
218
+ size=SizeDict(height=resized_height, width=resized_width),
219
+ resample=resample,
220
+ )
221
+
222
+ def patchify(
223
+ self,
224
+ videos: "torch.Tensor",
225
+ patch_size: int,
226
+ merge_size: int,
227
+ temporal_patch_size: int,
228
+ ) -> tuple["torch.Tensor", int, int]:
229
+ "Patchifies each video into flat layout of shape (`seq_len`, `patch_dim`) so we can concat dynamically shaped pixels."
230
+ batch_size, num_frames, channel, resized_height, resized_width = videos.shape
231
+
232
+ # Check that videos have `num_frames` divisible by `temporal_patch_size`
233
+ if pad := -num_frames % temporal_patch_size:
234
+ repeats = videos[:, -1:].expand(-1, pad, -1, -1, -1)
235
+ videos = torch.cat((videos, repeats), dim=1)
236
+ num_frames += pad
237
+
238
+ grid_t = num_frames // temporal_patch_size
239
+ grid_h, grid_w = resized_height // patch_size, resized_width // patch_size
240
+
241
+ patches = videos.view(
242
+ batch_size,
243
+ grid_t,
244
+ temporal_patch_size,
245
+ channel,
246
+ grid_h // merge_size,
247
+ merge_size,
248
+ patch_size,
249
+ grid_w // merge_size,
250
+ merge_size,
251
+ patch_size,
252
+ )
253
+ patches = patches.permute(0, 1, 4, 7, 5, 8, 3, 2, 6, 9)
254
+ flatten_patches = patches.reshape(
255
+ batch_size,
256
+ grid_t * grid_h * grid_w,
257
+ channel * temporal_patch_size * patch_size * patch_size,
258
+ )
259
+
260
+ return flatten_patches, grid_t, grid_h, grid_w
261
+
262
+ def _preprocess(
263
+ self,
264
+ videos: list["torch.Tensor"],
265
+ do_resize: bool,
266
+ size: SizeDict,
267
+ resample: "PILImageResampling | tvF.InterpolationMode | int | None",
268
+ do_rescale: bool,
269
+ rescale_factor: float,
270
+ do_normalize: bool,
271
+ image_mean: float | list[float] | None,
272
+ image_std: float | list[float] | None,
273
+ patch_size: int | None = None,
274
+ temporal_patch_size: int | None = None,
275
+ merge_size: int | None = None,
276
+ cap_pixels_per_frame: bool | None = None,
277
+ return_tensors: str | TensorType | None = None,
278
+ **kwargs,
279
+ ):
280
+ if cap_pixels_per_frame is None:
281
+ logger.warning_once(
282
+ "Lfm3Vl video processing does not apply the per-frame pixel cap the reference "
283
+ "implementation (qwen-vl-utils) applies, so some videos cost far more tokens than they "
284
+ "would there. In v5.22 the capped behavior will become the default and "
285
+ "`cap_pixels_per_frame` will be removed. Pass `cap_pixels_per_frame=True` to adopt the "
286
+ "reference behavior now, or `False` to keep the current behavior and silence this "
287
+ "warning."
288
+ )
289
+ cap_pixels_per_frame = False
290
+ # Group videos by size for batched resizing
291
+ grouped_videos, grouped_videos_index = group_videos_by_shape(videos)
292
+ resized_videos_grouped = {}
293
+ for shape, stacked_videos in grouped_videos.items():
294
+ if do_resize:
295
+ stacked_videos = self.resize(
296
+ videos=stacked_videos,
297
+ size=size,
298
+ resample=resample,
299
+ factor=patch_size * merge_size,
300
+ temporal_factor=temporal_patch_size,
301
+ cap_pixels_per_frame=cap_pixels_per_frame,
302
+ )
303
+ resized_videos_grouped[shape] = stacked_videos
304
+ resized_videos = reorder_videos(resized_videos_grouped, grouped_videos_index)
305
+
306
+ # Group videos by size for further processing
307
+ # Needed in case do_resize is False, or resize returns videos with different sizes
308
+ grouped_videos, grouped_videos_index = group_videos_by_shape(resized_videos)
309
+ processed_videos_grouped = {}
310
+ processed_grids = {}
311
+ for shape, stacked_videos in grouped_videos.items():
312
+ # Fused rescale and normalize
313
+ stacked_videos = self.rescale_and_normalize(
314
+ stacked_videos, do_rescale, rescale_factor, do_normalize, image_mean, image_std
315
+ )
316
+ patches, grid_t, grid_h, grid_w = self.patchify(
317
+ stacked_videos,
318
+ patch_size=patch_size,
319
+ merge_size=merge_size,
320
+ temporal_patch_size=temporal_patch_size,
321
+ )
322
+
323
+ processed_videos_grouped[shape] = patches
324
+ processed_grids[shape] = [[grid_t, grid_h, grid_w]] * len(stacked_videos)
325
+
326
+ processed_videos = reorder_videos(processed_videos_grouped, grouped_videos_index)
327
+ processed_grids = reorder_videos(processed_grids, grouped_videos_index)
328
+ pixel_values_videos = torch.cat(processed_videos, dim=0)
329
+ video_grid_thw = torch.tensor(processed_grids)
330
+
331
+ return BatchFeature(
332
+ data={"pixel_values_videos": pixel_values_videos, "video_grid_thw": video_grid_thw},
333
+ tensor_type=return_tensors,
334
+ )
335
+
336
+ def get_num_of_video_patches(self, num_frames: int, height: int, width: int, videos_kwargs=None):
337
+ """
338
+ A utility that returns number of video patches a given video size.
339
+
340
+ Args:
341
+ num_frames (`int`):
342
+ Number of frames in the input video.
343
+ height (`int`):
344
+ Height of the input video.
345
+ width (`int`):
346
+ Width of the input video.
347
+ videos_kwargs (`dict`, *optional*)
348
+ Any kwargs to override defaults of the video processor.
349
+ Returns:
350
+ `int`: Number of video patches per video.
351
+ """
352
+ videos_kwargs = videos_kwargs if videos_kwargs is not None else {}
353
+ size = videos_kwargs.get("size", None) or self.size
354
+ min_pixels = size["shortest_edge"]
355
+ max_pixels = size["longest_edge"]
356
+ patch_size = videos_kwargs.get("patch_size", None) or self.patch_size
357
+ merge_size = videos_kwargs.get("merge_size", None) or self.merge_size
358
+ temporal_patch_size = videos_kwargs.get("temporal_patch_size", None) or self.temporal_patch_size
359
+ cap_pixels_per_frame = videos_kwargs.get("cap_pixels_per_frame", None) or self.cap_pixels_per_frame
360
+
361
+ factor = patch_size * merge_size
362
+ if cap_pixels_per_frame:
363
+ # Keep the count in sync with `resize` when the per-frame cap is active.
364
+ frame_cap = self.max_video_tokens * factor * factor
365
+ pixels_per_frame = max(min(frame_cap, max_pixels // num_frames), int(min_pixels * 1.05))
366
+ max_pixels = pixels_per_frame * num_frames
367
+
368
+ resized_height, resized_width = smart_resize(
369
+ num_frames,
370
+ height,
371
+ width,
372
+ temporal_factor=temporal_patch_size,
373
+ factor=factor,
374
+ min_pixels=min_pixels,
375
+ max_pixels=max_pixels,
376
+ )
377
+ grid_h, grid_w = resized_height // patch_size, resized_width // patch_size
378
+ grid_t = (num_frames + -num_frames % temporal_patch_size) // temporal_patch_size
379
+ return grid_t * grid_h * grid_w
380
+
381
+ def preprocess(self, videos, **kwargs):
382
+ _check_video_metadata_count(videos, kwargs.get("video_metadata"))
383
+ # the shared `preprocess` fills every unset option from the instance before `sample_frames` runs, so the
384
+ # caller's options are told apart from the instance ones here: a caller option beats an instance one, and a
385
+ # configured `num_frames` beats the default fps
386
+ num_frames, fps = kwargs.get("num_frames"), kwargs.get("fps")
387
+ if num_frames is not None and fps is not None:
388
+ raise ValueError("`num_frames` and `fps` are mutually exclusive arguments, please use only one!")
389
+ if num_frames is not None or (fps is None and self.num_frames is not None):
390
+ kwargs["fps"] = None
391
+ elif fps is not None:
392
+ kwargs["num_frames"] = None
393
+ return super().preprocess(videos, **kwargs)
394
+
395
+
396
+ __all__ = ["Lfm3VlVideoProcessor"]