Instructions to use AlekseyCalvin/LFM3-VL-2B-3D-Coder with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Local Apps Settings
- Unsloth Desktop
add checkpoints/step-00320
Browse files- .gitattributes +1 -0
- checkpoints/step-00320/README.md +210 -0
- checkpoints/step-00320/adapter_config.json +47 -0
- checkpoints/step-00320/adapter_model.safetensors +3 -0
- checkpoints/step-00320/chat_template.jinja +280 -0
- checkpoints/step-00320/image_processing_lfm3_vl.py +293 -0
- checkpoints/step-00320/processing_lfm3_vl.py +248 -0
- checkpoints/step-00320/processor_config.json +73 -0
- checkpoints/step-00320/tokenizer.json +3 -0
- checkpoints/step-00320/tokenizer_config.json +64 -0
- checkpoints/step-00320/trainer_state.json +321 -0
- checkpoints/step-00320/training_args.bin +3 -0
- checkpoints/step-00320/video_processing_lfm3_vl.py +396 -0
.gitattributes
CHANGED
|
@@ -68,3 +68,4 @@ checkpoints/step-00280/tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
|
| 68 |
checkpoints/step-00290/tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
| 69 |
checkpoints/step-00300/tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
| 70 |
checkpoints/step-00310/tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 68 |
checkpoints/step-00290/tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
| 69 |
checkpoints/step-00300/tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
| 70 |
checkpoints/step-00310/tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
| 71 |
+
checkpoints/step-00320/tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
checkpoints/step-00320/README.md
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
- unsloth
|
| 12 |
+
---
|
| 13 |
+
|
| 14 |
+
# Model Card for Model ID
|
| 15 |
+
|
| 16 |
+
<!-- Provide a quick summary of what the model is/does. -->
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
## Model Details
|
| 21 |
+
|
| 22 |
+
### Model Description
|
| 23 |
+
|
| 24 |
+
<!-- Provide a longer summary of what this model is. -->
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
- **Developed by:** [More Information Needed]
|
| 29 |
+
- **Funded by [optional]:** [More Information Needed]
|
| 30 |
+
- **Shared by [optional]:** [More Information Needed]
|
| 31 |
+
- **Model type:** [More Information Needed]
|
| 32 |
+
- **Language(s) (NLP):** [More Information Needed]
|
| 33 |
+
- **License:** [More Information Needed]
|
| 34 |
+
- **Finetuned from model [optional]:** [More Information Needed]
|
| 35 |
+
|
| 36 |
+
### Model Sources [optional]
|
| 37 |
+
|
| 38 |
+
<!-- Provide the basic links for the model. -->
|
| 39 |
+
|
| 40 |
+
- **Repository:** [More Information Needed]
|
| 41 |
+
- **Paper [optional]:** [More Information Needed]
|
| 42 |
+
- **Demo [optional]:** [More Information Needed]
|
| 43 |
+
|
| 44 |
+
## Uses
|
| 45 |
+
|
| 46 |
+
<!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
|
| 47 |
+
|
| 48 |
+
### Direct Use
|
| 49 |
+
|
| 50 |
+
<!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
|
| 51 |
+
|
| 52 |
+
[More Information Needed]
|
| 53 |
+
|
| 54 |
+
### Downstream Use [optional]
|
| 55 |
+
|
| 56 |
+
<!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
|
| 57 |
+
|
| 58 |
+
[More Information Needed]
|
| 59 |
+
|
| 60 |
+
### Out-of-Scope Use
|
| 61 |
+
|
| 62 |
+
<!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
|
| 63 |
+
|
| 64 |
+
[More Information Needed]
|
| 65 |
+
|
| 66 |
+
## Bias, Risks, and Limitations
|
| 67 |
+
|
| 68 |
+
<!-- This section is meant to convey both technical and sociotechnical limitations. -->
|
| 69 |
+
|
| 70 |
+
[More Information Needed]
|
| 71 |
+
|
| 72 |
+
### Recommendations
|
| 73 |
+
|
| 74 |
+
<!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
|
| 75 |
+
|
| 76 |
+
Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
|
| 77 |
+
|
| 78 |
+
## How to Get Started with the Model
|
| 79 |
+
|
| 80 |
+
Use the code below to get started with the model.
|
| 81 |
+
|
| 82 |
+
[More Information Needed]
|
| 83 |
+
|
| 84 |
+
## Training Details
|
| 85 |
+
|
| 86 |
+
### Training Data
|
| 87 |
+
|
| 88 |
+
<!-- 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. -->
|
| 89 |
+
|
| 90 |
+
[More Information Needed]
|
| 91 |
+
|
| 92 |
+
### Training Procedure
|
| 93 |
+
|
| 94 |
+
<!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
|
| 95 |
+
|
| 96 |
+
#### Preprocessing [optional]
|
| 97 |
+
|
| 98 |
+
[More Information Needed]
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
#### Training Hyperparameters
|
| 102 |
+
|
| 103 |
+
- **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
|
| 104 |
+
|
| 105 |
+
#### Speeds, Sizes, Times [optional]
|
| 106 |
+
|
| 107 |
+
<!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
|
| 108 |
+
|
| 109 |
+
[More Information Needed]
|
| 110 |
+
|
| 111 |
+
## Evaluation
|
| 112 |
+
|
| 113 |
+
<!-- This section describes the evaluation protocols and provides the results. -->
|
| 114 |
+
|
| 115 |
+
### Testing Data, Factors & Metrics
|
| 116 |
+
|
| 117 |
+
#### Testing Data
|
| 118 |
+
|
| 119 |
+
<!-- This should link to a Dataset Card if possible. -->
|
| 120 |
+
|
| 121 |
+
[More Information Needed]
|
| 122 |
+
|
| 123 |
+
#### Factors
|
| 124 |
+
|
| 125 |
+
<!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
|
| 126 |
+
|
| 127 |
+
[More Information Needed]
|
| 128 |
+
|
| 129 |
+
#### Metrics
|
| 130 |
+
|
| 131 |
+
<!-- These are the evaluation metrics being used, ideally with a description of why. -->
|
| 132 |
+
|
| 133 |
+
[More Information Needed]
|
| 134 |
+
|
| 135 |
+
### Results
|
| 136 |
+
|
| 137 |
+
[More Information Needed]
|
| 138 |
+
|
| 139 |
+
#### Summary
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
## Model Examination [optional]
|
| 144 |
+
|
| 145 |
+
<!-- Relevant interpretability work for the model goes here -->
|
| 146 |
+
|
| 147 |
+
[More Information Needed]
|
| 148 |
+
|
| 149 |
+
## Environmental Impact
|
| 150 |
+
|
| 151 |
+
<!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
|
| 152 |
+
|
| 153 |
+
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).
|
| 154 |
+
|
| 155 |
+
- **Hardware Type:** [More Information Needed]
|
| 156 |
+
- **Hours used:** [More Information Needed]
|
| 157 |
+
- **Cloud Provider:** [More Information Needed]
|
| 158 |
+
- **Compute Region:** [More Information Needed]
|
| 159 |
+
- **Carbon Emitted:** [More Information Needed]
|
| 160 |
+
|
| 161 |
+
## Technical Specifications [optional]
|
| 162 |
+
|
| 163 |
+
### Model Architecture and Objective
|
| 164 |
+
|
| 165 |
+
[More Information Needed]
|
| 166 |
+
|
| 167 |
+
### Compute Infrastructure
|
| 168 |
+
|
| 169 |
+
[More Information Needed]
|
| 170 |
+
|
| 171 |
+
#### Hardware
|
| 172 |
+
|
| 173 |
+
[More Information Needed]
|
| 174 |
+
|
| 175 |
+
#### Software
|
| 176 |
+
|
| 177 |
+
[More Information Needed]
|
| 178 |
+
|
| 179 |
+
## Citation [optional]
|
| 180 |
+
|
| 181 |
+
<!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
|
| 182 |
+
|
| 183 |
+
**BibTeX:**
|
| 184 |
+
|
| 185 |
+
[More Information Needed]
|
| 186 |
+
|
| 187 |
+
**APA:**
|
| 188 |
+
|
| 189 |
+
[More Information Needed]
|
| 190 |
+
|
| 191 |
+
## Glossary [optional]
|
| 192 |
+
|
| 193 |
+
<!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
|
| 194 |
+
|
| 195 |
+
[More Information Needed]
|
| 196 |
+
|
| 197 |
+
## More Information [optional]
|
| 198 |
+
|
| 199 |
+
[More Information Needed]
|
| 200 |
+
|
| 201 |
+
## Model Card Authors [optional]
|
| 202 |
+
|
| 203 |
+
[More Information Needed]
|
| 204 |
+
|
| 205 |
+
## Model Card Contact
|
| 206 |
+
|
| 207 |
+
[More Information Needed]
|
| 208 |
+
### Framework versions
|
| 209 |
+
|
| 210 |
+
- PEFT 0.21.2
|
checkpoints/step-00320/adapter_config.json
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"alora_invocation_tokens": null,
|
| 3 |
+
"alpha_pattern": {},
|
| 4 |
+
"arrow_config": null,
|
| 5 |
+
"auto_mapping": {
|
| 6 |
+
"base_model_class": "Lfm3VlForConditionalGeneration",
|
| 7 |
+
"parent_library": "transformers_modules.LiquidAI.LFM3_hyphen_VL_hyphen_2B.23387beda43c60310348e83e25f78f33c3140d3a.modeling_lfm3_vl",
|
| 8 |
+
"unsloth_fixed": true
|
| 9 |
+
},
|
| 10 |
+
"base_model_name_or_path": "LiquidAI/LFM3-VL-2B",
|
| 11 |
+
"bias": "none",
|
| 12 |
+
"corda_config": null,
|
| 13 |
+
"ensure_weight_tying": false,
|
| 14 |
+
"eva_config": null,
|
| 15 |
+
"exclude_modules": null,
|
| 16 |
+
"fan_in_fan_out": false,
|
| 17 |
+
"inference_mode": true,
|
| 18 |
+
"init_lora_weights": true,
|
| 19 |
+
"kasa_config": null,
|
| 20 |
+
"layer_replication": null,
|
| 21 |
+
"layers_pattern": null,
|
| 22 |
+
"layers_to_transform": null,
|
| 23 |
+
"loftq_config": {},
|
| 24 |
+
"lora_alpha": 128,
|
| 25 |
+
"lora_bias": false,
|
| 26 |
+
"lora_dropout": 0.0,
|
| 27 |
+
"lora_ga_config": null,
|
| 28 |
+
"megatron_config": null,
|
| 29 |
+
"megatron_core": "megatron.core",
|
| 30 |
+
"modules_to_save": null,
|
| 31 |
+
"monteclora_config": null,
|
| 32 |
+
"peft_type": "LORA",
|
| 33 |
+
"peft_version": "0.21.2",
|
| 34 |
+
"qalora_group_size": 16,
|
| 35 |
+
"r": 64,
|
| 36 |
+
"rank_pattern": {},
|
| 37 |
+
"revision": null,
|
| 38 |
+
"target_modules": ".*language_model.*\\.(q_proj|k_proj|v_proj|o_proj|gate_proj|in_proj|out_proj|w1|w2|w3)",
|
| 39 |
+
"target_parameters": null,
|
| 40 |
+
"task_type": "CAUSAL_LM",
|
| 41 |
+
"trainable_token_indices": null,
|
| 42 |
+
"use_bdlora": null,
|
| 43 |
+
"use_dora": false,
|
| 44 |
+
"use_qalora": false,
|
| 45 |
+
"use_rslora": false,
|
| 46 |
+
"velora_config": null
|
| 47 |
+
}
|
checkpoints/step-00320/adapter_model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:364db4b68fd7624e9925a947c767e6622d29a0d1420360f49ed80d64d75293d3
|
| 3 |
+
size 263545648
|
checkpoints/step-00320/chat_template.jinja
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 -%}
|
checkpoints/step-00320/image_processing_lfm3_vl.py
ADDED
|
@@ -0,0 +1,293 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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"]
|
checkpoints/step-00320/processing_lfm3_vl.py
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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"]
|
checkpoints/step-00320/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": 16777216,
|
| 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": 25165824,
|
| 68 |
+
"shortest_edge": 4096
|
| 69 |
+
},
|
| 70 |
+
"temporal_patch_size": 2,
|
| 71 |
+
"video_processor_type": "Lfm3VlVideoProcessor"
|
| 72 |
+
}
|
| 73 |
+
}
|
checkpoints/step-00320/tokenizer.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a39eed58008cbcbc09e5b629b81338a654269c64cd13348aaa6090f4db75c7e7
|
| 3 |
+
size 17908258
|
checkpoints/step-00320/tokenizer_config.json
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"tokenizer_class": "TokenizersBackend",
|
| 61 |
+
"video_token": "<|video|>",
|
| 62 |
+
"vision_end_token": "<|vision_end|>",
|
| 63 |
+
"vision_start_token": "<|vision_start|>"
|
| 64 |
+
}
|
checkpoints/step-00320/trainer_state.json
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"best_global_step": null,
|
| 3 |
+
"best_metric": null,
|
| 4 |
+
"best_model_checkpoint": null,
|
| 5 |
+
"epoch": 0.23559727590649734,
|
| 6 |
+
"eval_steps": 50,
|
| 7 |
+
"global_step": 320,
|
| 8 |
+
"is_hyper_param_search": false,
|
| 9 |
+
"is_local_process_zero": true,
|
| 10 |
+
"is_world_process_zero": true,
|
| 11 |
+
"log_history": [
|
| 12 |
+
{
|
| 13 |
+
"epoch": 0,
|
| 14 |
+
"eval_loss": 0.11390484869480133,
|
| 15 |
+
"eval_runtime": 20.5163,
|
| 16 |
+
"eval_samples_per_second": 0.78,
|
| 17 |
+
"eval_steps_per_second": 0.78,
|
| 18 |
+
"step": 0
|
| 19 |
+
},
|
| 20 |
+
{
|
| 21 |
+
"epoch": 0.0007362414872078042,
|
| 22 |
+
"grad_norm": 0.25277823209762573,
|
| 23 |
+
"learning_rate": 0.0,
|
| 24 |
+
"loss": 0.11856091022491455,
|
| 25 |
+
"step": 1
|
| 26 |
+
},
|
| 27 |
+
{
|
| 28 |
+
"epoch": 0.007362414872078042,
|
| 29 |
+
"grad_norm": 0.1885928213596344,
|
| 30 |
+
"learning_rate": 1.5254237288135596e-05,
|
| 31 |
+
"loss": 0.11453930536905925,
|
| 32 |
+
"step": 10
|
| 33 |
+
},
|
| 34 |
+
{
|
| 35 |
+
"epoch": 0.014724829744156084,
|
| 36 |
+
"grad_norm": 0.10124507546424866,
|
| 37 |
+
"learning_rate": 3.2203389830508473e-05,
|
| 38 |
+
"loss": 0.08519152998924255,
|
| 39 |
+
"step": 20
|
| 40 |
+
},
|
| 41 |
+
{
|
| 42 |
+
"epoch": 0.022087244616234125,
|
| 43 |
+
"grad_norm": 0.08935669809579849,
|
| 44 |
+
"learning_rate": 4.915254237288136e-05,
|
| 45 |
+
"loss": 0.040150302648544314,
|
| 46 |
+
"step": 30
|
| 47 |
+
},
|
| 48 |
+
{
|
| 49 |
+
"epoch": 0.029449659488312168,
|
| 50 |
+
"grad_norm": 0.06916698068380356,
|
| 51 |
+
"learning_rate": 6.610169491525424e-05,
|
| 52 |
+
"loss": 0.0316935271024704,
|
| 53 |
+
"step": 40
|
| 54 |
+
},
|
| 55 |
+
{
|
| 56 |
+
"epoch": 0.03681207436039021,
|
| 57 |
+
"grad_norm": 0.06203220784664154,
|
| 58 |
+
"learning_rate": 8.305084745762712e-05,
|
| 59 |
+
"loss": 0.030584955215454103,
|
| 60 |
+
"step": 50
|
| 61 |
+
},
|
| 62 |
+
{
|
| 63 |
+
"epoch": 0.03681207436039021,
|
| 64 |
+
"eval_loss": 0.0280052088201046,
|
| 65 |
+
"eval_runtime": 16.659,
|
| 66 |
+
"eval_samples_per_second": 0.96,
|
| 67 |
+
"eval_steps_per_second": 0.96,
|
| 68 |
+
"step": 50
|
| 69 |
+
},
|
| 70 |
+
{
|
| 71 |
+
"epoch": 0.04417448923246825,
|
| 72 |
+
"grad_norm": 0.07732830941677094,
|
| 73 |
+
"learning_rate": 0.0001,
|
| 74 |
+
"loss": 0.027473923563957215,
|
| 75 |
+
"step": 60
|
| 76 |
+
},
|
| 77 |
+
{
|
| 78 |
+
"epoch": 0.05153690410454629,
|
| 79 |
+
"grad_norm": 0.07388576120138168,
|
| 80 |
+
"learning_rate": 9.998540070400966e-05,
|
| 81 |
+
"loss": 0.026318195462226867,
|
| 82 |
+
"step": 70
|
| 83 |
+
},
|
| 84 |
+
{
|
| 85 |
+
"epoch": 0.058899318976624336,
|
| 86 |
+
"grad_norm": 0.08208851516246796,
|
| 87 |
+
"learning_rate": 9.994161134161634e-05,
|
| 88 |
+
"loss": 0.02552647590637207,
|
| 89 |
+
"step": 80
|
| 90 |
+
},
|
| 91 |
+
{
|
| 92 |
+
"epoch": 0.06626173384870238,
|
| 93 |
+
"grad_norm": 0.07567381858825684,
|
| 94 |
+
"learning_rate": 9.986865748457457e-05,
|
| 95 |
+
"loss": 0.024400721490383147,
|
| 96 |
+
"step": 90
|
| 97 |
+
},
|
| 98 |
+
{
|
| 99 |
+
"epoch": 0.07362414872078042,
|
| 100 |
+
"grad_norm": 0.09747316688299179,
|
| 101 |
+
"learning_rate": 9.976658173588244e-05,
|
| 102 |
+
"loss": 0.022965249419212342,
|
| 103 |
+
"step": 100
|
| 104 |
+
},
|
| 105 |
+
{
|
| 106 |
+
"epoch": 0.07362414872078042,
|
| 107 |
+
"eval_loss": 0.02190309390425682,
|
| 108 |
+
"eval_runtime": 16.6583,
|
| 109 |
+
"eval_samples_per_second": 0.96,
|
| 110 |
+
"eval_steps_per_second": 0.96,
|
| 111 |
+
"step": 100
|
| 112 |
+
},
|
| 113 |
+
{
|
| 114 |
+
"epoch": 0.08098656359285845,
|
| 115 |
+
"grad_norm": 0.09270897507667542,
|
| 116 |
+
"learning_rate": 9.96354437049027e-05,
|
| 117 |
+
"loss": 0.023063759505748748,
|
| 118 |
+
"step": 110
|
| 119 |
+
},
|
| 120 |
+
{
|
| 121 |
+
"epoch": 0.0883489784649365,
|
| 122 |
+
"grad_norm": 0.08489587903022766,
|
| 123 |
+
"learning_rate": 9.947531997255256e-05,
|
| 124 |
+
"loss": 0.02435874342918396,
|
| 125 |
+
"step": 120
|
| 126 |
+
},
|
| 127 |
+
{
|
| 128 |
+
"epoch": 0.09571139333701455,
|
| 129 |
+
"grad_norm": 0.0834401398897171,
|
| 130 |
+
"learning_rate": 9.928630404658255e-05,
|
| 131 |
+
"loss": 0.02255440652370453,
|
| 132 |
+
"step": 130
|
| 133 |
+
},
|
| 134 |
+
{
|
| 135 |
+
"epoch": 0.10307380820909258,
|
| 136 |
+
"grad_norm": 0.07860592007637024,
|
| 137 |
+
"learning_rate": 9.906850630697068e-05,
|
| 138 |
+
"loss": 0.02299370467662811,
|
| 139 |
+
"step": 140
|
| 140 |
+
},
|
| 141 |
+
{
|
| 142 |
+
"epoch": 0.11043622308117063,
|
| 143 |
+
"grad_norm": 0.0797109380364418,
|
| 144 |
+
"learning_rate": 9.882205394146361e-05,
|
| 145 |
+
"loss": 0.021973945200443268,
|
| 146 |
+
"step": 150
|
| 147 |
+
},
|
| 148 |
+
{
|
| 149 |
+
"epoch": 0.11043622308117063,
|
| 150 |
+
"eval_loss": 0.021159205585718155,
|
| 151 |
+
"eval_runtime": 16.6654,
|
| 152 |
+
"eval_samples_per_second": 0.96,
|
| 153 |
+
"eval_steps_per_second": 0.96,
|
| 154 |
+
"step": 150
|
| 155 |
+
},
|
| 156 |
+
{
|
| 157 |
+
"epoch": 0.11779863795324867,
|
| 158 |
+
"grad_norm": 0.08942675590515137,
|
| 159 |
+
"learning_rate": 9.85470908713026e-05,
|
| 160 |
+
"loss": 0.02212696224451065,
|
| 161 |
+
"step": 160
|
| 162 |
+
},
|
| 163 |
+
{
|
| 164 |
+
"epoch": 0.12516105282532672,
|
| 165 |
+
"grad_norm": 0.08564750105142593,
|
| 166 |
+
"learning_rate": 9.824377766717759e-05,
|
| 167 |
+
"loss": 0.021176578104496004,
|
| 168 |
+
"step": 170
|
| 169 |
+
},
|
| 170 |
+
{
|
| 171 |
+
"epoch": 0.13252346769740475,
|
| 172 |
+
"grad_norm": 0.07962562143802643,
|
| 173 |
+
"learning_rate": 9.791229145545831e-05,
|
| 174 |
+
"loss": 0.02140930891036987,
|
| 175 |
+
"step": 180
|
| 176 |
+
},
|
| 177 |
+
{
|
| 178 |
+
"epoch": 0.13988588256948278,
|
| 179 |
+
"grad_norm": 0.08212776482105255,
|
| 180 |
+
"learning_rate": 9.755282581475769e-05,
|
| 181 |
+
"loss": 0.022258555889129637,
|
| 182 |
+
"step": 190
|
| 183 |
+
},
|
| 184 |
+
{
|
| 185 |
+
"epoch": 0.14724829744156084,
|
| 186 |
+
"grad_norm": 0.09344960749149323,
|
| 187 |
+
"learning_rate": 9.716559066288715e-05,
|
| 188 |
+
"loss": 0.021730823814868926,
|
| 189 |
+
"step": 200
|
| 190 |
+
},
|
| 191 |
+
{
|
| 192 |
+
"epoch": 0.14724829744156084,
|
| 193 |
+
"eval_loss": 0.02074412629008293,
|
| 194 |
+
"eval_runtime": 16.6852,
|
| 195 |
+
"eval_samples_per_second": 0.959,
|
| 196 |
+
"eval_steps_per_second": 0.959,
|
| 197 |
+
"step": 200
|
| 198 |
+
},
|
| 199 |
+
{
|
| 200 |
+
"epoch": 0.15461071231363888,
|
| 201 |
+
"grad_norm": 0.09182336181402206,
|
| 202 |
+
"learning_rate": 9.675081213427076e-05,
|
| 203 |
+
"loss": 0.021804860234260558,
|
| 204 |
+
"step": 210
|
| 205 |
+
},
|
| 206 |
+
{
|
| 207 |
+
"epoch": 0.1619731271857169,
|
| 208 |
+
"grad_norm": 0.0867530107498169,
|
| 209 |
+
"learning_rate": 9.630873244788883e-05,
|
| 210 |
+
"loss": 0.020811836421489715,
|
| 211 |
+
"step": 220
|
| 212 |
+
},
|
| 213 |
+
{
|
| 214 |
+
"epoch": 0.16933554205779497,
|
| 215 |
+
"grad_norm": 0.07895562052726746,
|
| 216 |
+
"learning_rate": 9.583960976582913e-05,
|
| 217 |
+
"loss": 0.02166871726512909,
|
| 218 |
+
"step": 230
|
| 219 |
+
},
|
| 220 |
+
{
|
| 221 |
+
"epoch": 0.176697956929873,
|
| 222 |
+
"grad_norm": 0.08922504633665085,
|
| 223 |
+
"learning_rate": 9.534371804252728e-05,
|
| 224 |
+
"loss": 0.02083375006914139,
|
| 225 |
+
"step": 240
|
| 226 |
+
},
|
| 227 |
+
{
|
| 228 |
+
"epoch": 0.18406037180195103,
|
| 229 |
+
"grad_norm": 0.08715999126434326,
|
| 230 |
+
"learning_rate": 9.482134686478519e-05,
|
| 231 |
+
"loss": 0.020784498751163484,
|
| 232 |
+
"step": 250
|
| 233 |
+
},
|
| 234 |
+
{
|
| 235 |
+
"epoch": 0.18406037180195103,
|
| 236 |
+
"eval_loss": 0.019665982574224472,
|
| 237 |
+
"eval_runtime": 23.36,
|
| 238 |
+
"eval_samples_per_second": 0.685,
|
| 239 |
+
"eval_steps_per_second": 0.685,
|
| 240 |
+
"step": 250
|
| 241 |
+
},
|
| 242 |
+
{
|
| 243 |
+
"epoch": 0.1914227866740291,
|
| 244 |
+
"grad_norm": 0.09428243339061737,
|
| 245 |
+
"learning_rate": 9.42728012826605e-05,
|
| 246 |
+
"loss": 0.02026109993457794,
|
| 247 |
+
"step": 260
|
| 248 |
+
},
|
| 249 |
+
{
|
| 250 |
+
"epoch": 0.19878520154610713,
|
| 251 |
+
"grad_norm": 0.08258358389139175,
|
| 252 |
+
"learning_rate": 9.36984016313259e-05,
|
| 253 |
+
"loss": 0.02014337033033371,
|
| 254 |
+
"step": 270
|
| 255 |
+
},
|
| 256 |
+
{
|
| 257 |
+
"epoch": 0.20614761641818516,
|
| 258 |
+
"grad_norm": 0.09497354179620743,
|
| 259 |
+
"learning_rate": 9.309848334400246e-05,
|
| 260 |
+
"loss": 0.020521189272403716,
|
| 261 |
+
"step": 280
|
| 262 |
+
},
|
| 263 |
+
{
|
| 264 |
+
"epoch": 0.21351003129026322,
|
| 265 |
+
"grad_norm": 0.08938208222389221,
|
| 266 |
+
"learning_rate": 9.247339675607605e-05,
|
| 267 |
+
"loss": 0.019297249615192413,
|
| 268 |
+
"step": 290
|
| 269 |
+
},
|
| 270 |
+
{
|
| 271 |
+
"epoch": 0.22087244616234125,
|
| 272 |
+
"grad_norm": 0.09245641529560089,
|
| 273 |
+
"learning_rate": 9.182350690051133e-05,
|
| 274 |
+
"loss": 0.020193299651145934,
|
| 275 |
+
"step": 300
|
| 276 |
+
},
|
| 277 |
+
{
|
| 278 |
+
"epoch": 0.22087244616234125,
|
| 279 |
+
"eval_loss": 0.01902087777853012,
|
| 280 |
+
"eval_runtime": 23.3988,
|
| 281 |
+
"eval_samples_per_second": 0.684,
|
| 282 |
+
"eval_steps_per_second": 0.684,
|
| 283 |
+
"step": 300
|
| 284 |
+
},
|
| 285 |
+
{
|
| 286 |
+
"epoch": 0.22823486103441928,
|
| 287 |
+
"grad_norm": 0.09447222948074341,
|
| 288 |
+
"learning_rate": 9.114919329468282e-05,
|
| 289 |
+
"loss": 0.02030704468488693,
|
| 290 |
+
"step": 310
|
| 291 |
+
},
|
| 292 |
+
{
|
| 293 |
+
"epoch": 0.23559727590649734,
|
| 294 |
+
"grad_norm": 0.08741063624620438,
|
| 295 |
+
"learning_rate": 9.045084971874738e-05,
|
| 296 |
+
"loss": 0.020242883265018462,
|
| 297 |
+
"step": 320
|
| 298 |
+
}
|
| 299 |
+
],
|
| 300 |
+
"logging_steps": 10,
|
| 301 |
+
"max_steps": 1359,
|
| 302 |
+
"num_input_tokens_seen": 0,
|
| 303 |
+
"num_train_epochs": 1,
|
| 304 |
+
"save_steps": 10,
|
| 305 |
+
"stateful_callbacks": {
|
| 306 |
+
"TrainerControl": {
|
| 307 |
+
"args": {
|
| 308 |
+
"should_epoch_stop": false,
|
| 309 |
+
"should_evaluate": false,
|
| 310 |
+
"should_log": false,
|
| 311 |
+
"should_save": true,
|
| 312 |
+
"should_training_stop": false
|
| 313 |
+
},
|
| 314 |
+
"attributes": {}
|
| 315 |
+
}
|
| 316 |
+
},
|
| 317 |
+
"total_flos": 3.263825988242473e+17,
|
| 318 |
+
"train_batch_size": 1,
|
| 319 |
+
"trial_name": null,
|
| 320 |
+
"trial_params": null
|
| 321 |
+
}
|
checkpoints/step-00320/training_args.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:291a571c1fa7c89726a3014d83d26423e33750aad097c449e216ad0e045576b6
|
| 3 |
+
size 6161
|
checkpoints/step-00320/video_processing_lfm3_vl.py
ADDED
|
@@ -0,0 +1,396 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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"]
|