ldov
/

ldov caipeng328 commited on
Commit
6bf4a3d
·
0 Parent(s):

Duplicate from XingChen-AGI/TeleOCR

Browse files

Co-authored-by: caipeng <caipeng328@users.noreply.huggingface.co>

.gitattributes ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ assets/code.png filter=lfs diff=lfs merge=lfs -text
37
+ assets/icon.png filter=lfs diff=lfs merge=lfs -text
38
+ assets/layout.jpg filter=lfs diff=lfs merge=lfs -text
39
+ assets/layout_distorted.jpg filter=lfs diff=lfs merge=lfs -text
40
+ assets/score.png filter=lfs diff=lfs merge=lfs -text
41
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,433 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ tags:
4
+ - ocr
5
+ - document-parsing
6
+ - multimodal
7
+ library_name: transformers
8
+ pipeline_tag: image-text-to-text
9
+ language:
10
+ - zh
11
+ - en
12
+ ---
13
+ <div align="center">
14
+
15
+ <h1 align="center">
16
+ TeleOCR: Navigating Document Parsing Across Digital and Camera-Captured Documents
17
+
18
+ </h1>
19
+
20
+ [![License](https://img.shields.io/badge/License-Apache--2.0-blue.svg)](LICENSE)
21
+ [![GitHub](https://img.shields.io/badge/GitHub-Repository-black?logo=github)](https://github.com/caipeng328/TeleOCR)
22
+ [![TeleAI](https://img.shields.io/badge/webapp_on_teleai.com-blue?logo=data:image/png;base64,UklGRpICAABXRUJQVlA4WAoAAAAQAAAAFQAAGAAAQUxQSEwBAAABkGvb2rFXb5zauQCbVTrbNjt1tm3bObZt6zeObdvft4v30yVExASwkqKChaQVLH6f2vcKeHqAunMTHz9x/D9Y/+2cVtX1+dAbjLX8lck4cH1c37S4Z3DT/NznjkmlWs6lXv26sf/K0rFlmWzkwIGHOo6/qhvqaxdlN+Vnrt9Q6a8pvnPpNRqtTqPV6bUajUar/cXB/xsChfT71DISHCg+UzIjweRb5uOO/2KuLxw5duTS4w96Qf+aS89/BfBe193AUFXUFbuftx4DeHkELnsB/A0EZfPs1j0Ar099tz8D4LfbfQDsQuHmW3+Yv/pN5f0sgIcWS6Cf7dq1t2XHnu13Qc8R1/cUsOU1vq2C84sXIUm/OC6EzMXu5PiVQwghUW8prAUMM9SrLMLpvPwf/D9WnQl/2FGW67g/EWwQefw/cDnNlIg1StxXYE74AVZQOCAgAQAAkAcAnQEqFgAZAD7RVKZNqCQjojAYCAEAGglsAJ0zND+A2rdxh/l2DrrSwNZEPJb8c9uqnP90eUrVexSs2yAJSFsrsI8AAP03X4scCDMKfncvKAr9aIf33A4Lc9xfcBVOo9hotIZIL1kpgEs0hdr2CPz/BVzkPcV5X2+ZdiEn0NWI16mvKRFSI/HYHhAAT9NP3KwVp1une4gB+ernhg1Ly0KuLdqCAZXWQHJzTrrR8RNz79tgl7Aq8WHqxbOTfguubnUbMPaD4DfKY71NjLtozHqNKPSC6gxIS3UNlbGZT3m3zEus+sjwYwucztbFfyH6n4U8VoWfQf4UdhLuoylwhqzt+FoCGwH4pHiWv/pkL2Z/bt9h755P3YDljRFfAAAA&labelColor=white)](https://www.teleai.com.cn/docparse/DocumentParsing)
23
+ [![arXiv](https://img.shields.io/badge/TeleOCR-Technical%20Report-b31b1b.svg?logo=arXiv)](https://arxiv.org/abs/2608.12898)
24
+ </div>
25
+
26
+ <div align="center">
27
+ <img src="https://raw.githubusercontent.com/caipeng328/TeleOCR/refs/heads/main/assets/score.png" width="800">
28
+ </div>
29
+
30
+ ## 🔥 News
31
+ - **2026/09/10** - We have renamed NaviDC-OCR to TeleOCR, and all subsequent model iterations will be developed and released under the TeleOCR version.
32
+ - **2026/09/01** - We noticed that EMNLP 2026 is hosting the [Dr.DocBench Challenge](https://eval.ai/web/challenges/challenge-page/2717/overview), a document parsing competition. We evaluated NaviDC-OCR with its native weights, achieving better results than MinerU 2.5 Pro and PaddleOCR-VL 1.6. Detailed results are shown below **dr.docbench-challenge**. We welcome the use of NaviDC‑OCR for competitions. Going forward, we will continue to deliver competitive parsing models for the community.
33
+ - **2026/08/29** — Thanks to Nandraj for the GGUF conversion and llama.cpp support [🔗 NaviDC-OCR-GGUF](https://huggingface.co/nandraj/NaviDC-OCR-GGUF), and to the community for sharing their experience deploying NaviDC-OCR on [Ascend 910B!](https://zhuanlan.zhihu.com/p/2078516899093155893)
34
+ - **2026/08/17** — NaviDC-OCR [model weights](https://huggingface.co/StarDoc-AI/NaviDC-OCR) and [technical report](https://arxiv.org/pdf/2608.12898) have been released.
35
+
36
+ ## 📖 Introduction
37
+
38
+ **TeleOCR** is a lightweight (~1.2B parameters), open-source Vision-Language Model designed specifically for document parsing.
39
+
40
+ Unlike existing methods that mainly target either digital documents or camera-captured documents, TeleOCR unifies both scenarios within a single framework.
41
+
42
+ Compared with previous document parsing models, TeleOCR introduces
43
+
44
+ - Multi-node Consensus Voting (MCV) for automatic pseudo-label generation
45
+ - Geometry-aware document modeling for camera-captured documents
46
+ - Curvature-Guided Douglas-Peucker Sampling (CGDP)
47
+ - Image-to-image self-verification for automatic data refinement
48
+ - Progressive four-stage training pipeline
49
+ - Content-Structure Decoupled Learning for tables and formulas
50
+
51
+ These techniques enable TeleOCR to achieve state-of-the-art performance on both digital and camera-captured document benchmarks while remaining lightweight enough for practical deployment.
52
+
53
+ ## 📊 Experimental Results
54
+
55
+ TeleOCR achieves state-of-the-art performance on multiple public document parsing benchmarks.
56
+
57
+ ### Layout Visualization of Distorted Documents
58
+ To evaluate the model's ability to understand complex document deformations, we conduct a visual evaluation on the public dewarping datasets DocUNet and DIR300, with representative results shown in Figure. TeleOCR directly performs layout and content parsing on distorted documents without dewarping preprocessing or a dedicated rectification model, demonstrating robust parsing under complex geometric deformations.
59
+ <div align="center">
60
+
61
+ <img src="https://raw.githubusercontent.com/caipeng328/TeleOCR/refs/heads/main/assets/dir300.png" width="800" alt="Parsing evaluation on the DIR300 dataset.">
62
+ <img src="https://raw.githubusercontent.com/caipeng328/TeleOCR/refs/heads/main/assets/docunet.png" width="800" alt="Parsing evaluation on the DocUNet dataset.">
63
+ </div>
64
+
65
+ ---
66
+
67
+ ## Dr.DocBench Challenge
68
+
69
+ |模型|overall ↑|Text edit ↓|formula cdm ↑|Table teds ↑|order edit ↓|
70
+ |---|---|---|---|---|---|
71
+ |**Specialized VLMs**| | | | | |
72
+ |TeleOCR|67.96|0.1903|0.02|64.97|0.398|
73
+ |Mineru 2.5 pro|62.26|0.3402|0.04|67.75|0.356|
74
+ |OvisOCR2|59.25|0.3883|0.00|61.59|0.3791|
75
+ |PaddleOCRvl 1.6|55.11 | 0.4364 | 0.21 | 51.34 |0.412 |
76
+
77
+
78
+ ---
79
+
80
+ ### [OmniDocBench v1.6](https://github.com/opendatalab/OmniDocBench)
81
+
82
+ | Model Type | Methods | Param | Overall ↑ | Text Edit ↓ | Formula CDM ↑ | Table TEDS ↑ | Table TEDS-S ↑ | Read Order Edit ↓ |
83
+ |---|---|---:|---:|---:|---:|---:|---:|---:|
84
+ | **Specialized VLMs** | **TeleOCR** | **1.2B** | **96.87** | <u>0.027</u> | 96.36 | **97.05** | **98.52** | <u>0.122</u> |
85
+ | | OvisOCR2 | 0.8B | <u>96.58</u> | **0.025** | **97.53** | <u>94.76</u> | <u>97.16</u> | **0.111** |
86
+ | | PaddleOCR-VL-1.6 | 0.9B | 96.33 | 0.033 | <u>97.49</u> | <u>94.76</u> | 97.11 | 0.127 |
87
+ | | MinerU2.5-Pro | 1.2B | 95.75 | 0.036 | 97.45 | 93.42 | 95.92 | 0.120 |
88
+ | | GLM-OCR | 0.9B | 95.22 | 0.044 | 97.18 | 92.83 | 95.39 | 0.133 |
89
+ | | PaddleOCR-VL-1.5 | 0.9B | 94.87 | 0.038 | 96.69 | 91.67 | 94.37 | 0.130 |
90
+ | | HunyuanOCR-1.5 | 1B | 94.74 | 0.033 | 97.49 | 94.76 | 97.11 | 0.127 |
91
+ | | PaddleOCR-VL | 0.9B | 94.11 | 0.040 | 95.70 | 90.65 | 93.74 | 0.135 |
92
+ | | Youtu-Parsing | 2.5B | 93.68 | 0.044 | 93.45 | 92.02 | 95.00 | 0.116 |
93
+ | | Logics-Parsing-v2 | 4B | 93.27 | 0.041 | 95.47 | 88.42 | 91.98 | 0.137 |
94
+ | | FireRed-OCR | 2B | 93.20 | 0.037 | 95.27 | 88.04 | 91.06 | 0.131 |
95
+ | | MinerU2.5 | 1.2B | 92.98 | 0.045 | 95.59 | 87.88 | 91.47 | 0.130 |
96
+ | | OpenDoc-0.1B | 0.1B | 90.64 | 0.049 | 92.93 | 83.88 | 87.45 | 0.140 |
97
+ | | dots.ocr | 3B | 90.50 | 0.048 | 89.12 | 87.18 | 90.58 | 0.138 |
98
+ | | DeepSeek-OCR 2 | 3B | 90.17 | 0.050 | 91.59 | 83.89 | 87.75 | 0.144 |
99
+ | | HunyuanOCR | 1B | 89.87 | 0.089 | 87.44 | 91.01 | 93.23 | 0.171 |
100
+ | | Dolphin-v2 | 3B | 89.34 | 0.069 | 90.53 | 84.40 | 87.44 | 0.150 |
101
+ | | OCRVerse | 4B | 88.44 | 0.063 | 89.14 | 82.44 | 86.27 | 0.163 |
102
+ | | MonkeyOCR-pro-3B | 3B | 88.43 | 0.074 | 88.33 | 84.35 | 88.62 | 0.189 |
103
+ | **General VLMs** | Ovis2.6-30B-A3B | 30B | 93.62 | 0.035 | 94.93 | 89.44 | 92.40 | 0.135 |
104
+ | | Gemini 3 Pro | -- | 92.85 | 0.064 | 95.83 | 89.15 | 92.96 | 0.165 |
105
+ | | Gemini 3 Flash | -- | 92.58 | 0.066 | 95.03 | 89.29 | 93.51 | 0.173 |
106
+ | | Qwen3-VL-235B | 235B | 89.78 | 0.063 | 92.53 | 83.07 | 86.75 | 0.166 |
107
+ | | GPT-5.2 | -- | 86.52 | 0.114 | 88.00 | 82.95 | 87.93 | 0.193 |
108
+ | | InternVL3.5-241B | 241B | 83.61 | 0.130 | 89.52 | 74.35 | 79.78 | 0.215 |
109
+
110
+ ---
111
+
112
+
113
+ ### [Wild_OmniDocBench](https://github.com/VirtualLUOUCAS/Wild_OmniDocBench)
114
+ | Model Type | Methods | Param | Overall ↑ | Text Edit ↓ | Formula CDM ↑ | Table TEDS ↑ | Table TEDS-S ↑ | Read Order Edit ↓ |
115
+ | ------------------- | ----------------- | ----: | -----------: | ----------: | ------------: | -----------: | -------------: | ----------------: |
116
+ | **Decoupled VLMs** | **TeleOCR** | 1.2B | **88.53** | **0.1173** | 88.26 | **89.05** | **92.14** | **0.2011** |
117
+ | | PaddleOCR-VL-1.6 | 0.9B | 87.36 | 0.1369 | 88.42 | <u>85.76</u> | <u>90.14</u> | 0.2057 |
118
+ | | MinerU2.5-Pro | 1.2B | 87.33 | 0.1362 | <u>90.15</u> | 85.46 | 90.12 | <u>0.2013</u> |
119
+ | | GLM-OCR | 0.9B | 85.08 | 0.1514 | 89.09 | 81.31 | 85.90 | 0.2228 |
120
+ | | PaddleOCR-VL-1.5 | 0.9B | 84.64 | 0.1461 | 86.72 | 81.80 | 86.52 | 0.2138 |
121
+ | **End-to-End VLMs** | OvisOCR2 | 0.8B | <u>87.91</u> | 0.129 | **90.37** | 85.13 | 89.11 | 0.2021 |
122
+ | | dots.ocr | 3B | 81.84 | 0.1483 | 85.0 | 75.32 | 80.20 | 0.2200 |
123
+ | | HunyuanOCR-1.5 | 1B | 77.62 | 0.1979 | 85.12 | 67.54 | 70.67 | 0.2750 |
124
+ | | Logics-Parsing-v2 | 4B | 77.10 | 0.4029 | 91.4 | 80.19 | 87.16 | 0.2355 |
125
+
126
+ ---
127
+
128
+
129
+ ### [PureDocBench](https://github.com/zhihengli-casia/puredocbench/)
130
+ | Model Type | Model | Clean Overall ↑ | Clean Text ↓ | Clean Formula ↑ | Clean Table ↑ | Digital Degraded Overall ↑ | Digital Degraded Text ↓ | Digital Degraded Formula ↑ | Digital Degraded Table ↑ | Real Degraded Overall ↑ | Real Degraded Text ↓ | Real Degraded Formula ↑ | Real Degraded Table ↑ |
131
+ | ------------------ | ----------------- | --------------: | -----------: | --------------: | ------------: | -------------------------: | ----------------------: | -------------------------: | -----------------------: | ----------------------: | -------------------: | ----------------------: | --------------------: |
132
+ | **Decoupled VLM** | **TeleOCR** | **86.90** | **0.111** | **81.01** | **91.09** | <u>77.47</u> | 0.206 | **72.59** | 80.45 | **70.85** | <u>0.302</u> | **65.11** | **77.66** |
133
+ | | DotsMOCR | 76.27 | 0.151 | 66.23 | 77.65 | 73.16 | <u>0.198</u> | 64.32 | 74.95 | 61.73 | 0.312 | 54.39 | 61.97 |
134
+ | | MinerU2.5-Pro | 75.87 | 0.222 | 65.14 | 84.68 | 71.77 | 0.272 | 61.79 | 80.73 | 62.56 | 0.375 | 52.70 | 72.47 |
135
+ | | YouTu-Parsing | 75.02 | 0.230 | 67.34 | 80.74 | 69.66 | 0.270 | 61.44 | 74.49 | 60.29 | 0.360 | 52.20 | 64.69 |
136
+ | | PaddleOCR-VL-1.5 | 73.01 | 0.266 | 63.53 | 82.12 | 66.73 | 0.339 | 58.03 | 76.07 | 60.50 | 0.398 | 54.00 | 67.33 |
137
+ | | GLM-OCR | 68.65 | 0.314 | 57.89 | 79.44 | 63.06 | 0.383 | 53.23 | 74.21 | 58.31 | 0.433 | 50.34 | 67.83 |
138
+ | | Dolphin-v2 | 65.90 | 0.342 | 59.80 | 72.12 | 60.24 | 0.393 | 52.20 | 67.86 | 44.92 | 0.553 | 39.98 | 50.04 |
139
+ | | MonkeyOCR-pro-3B | 62.23 | 0.346 | 48.46 | 72.83 | 57.40 | 0.397 | 45.57 | 66.32 | 46.49 | 0.511 | 38.18 | 52.43 |
140
+ | **End-to-End VLM** | OvisOCR2 | <u>82.14</u> | <u>0.149</u> | <u>71.29</u> | <u>90.12</u> | **77.77** | **0.192** | <u>67.87</u> | **84.71** | 66.61 | 0.316 | 57.64 | <u>73.79</u> |
141
+ | | FD-RL | 78.38 | 0.193 | 68.21 | 86.22 | 76.33 | 0.214 | 67.16 | <u>83.22</u> | <u>67.04</u> | **0.298** | 58.82 | 72.08 |
142
+ | | Logics-Parsing-v2 | 76.35 | 0.213 | 67.67 | 82.67 | 73.85 | 0.248 | 67.33 | 79.02 | 67.64 | 0.304 | <u>61.65</u> | 71.64 |
143
+ | | dots.ocr | 72.01 | 0.248 | 61.37 | 79.51 | 65.95 | 0.307 | 56.67 | 71.86 | 55.68 | 0.403 | 47.70 | 59.63 |
144
+ | | Qianfan-OCR | 57.22 | 0.370 | 49.79 | 58.83 | 50.85 | 0.438 | 44.41 | 51.96 | 45.06 | 0.494 | 39.08 | 45.53 |
145
+ | **General VLMs** | Qwen3-VL-8B | 72.44 | 0.261 | 65.10 | 78.35 | 72.03 | 0.266 | 64.88 | 77.82 | 62.73 | 0.342 | 55.55 | 66.81 |
146
+ | | Kimi K2.6 | 72.32 | 0.303 | 66.93 | 80.30 | 69.95 | 0.322 | 64.69 | 77.31 | 68.02 | 0.335 | 62.44 | 75.14 |
147
+ | | Gemini-3.1-Pro | 70.04 | 0.306 | 65.63 | 75.08 | 69.28 | 0.322 | 65.81 | 74.24 | **71.98** | 0.300 | 68.62 | 77.26 |
148
+ | | Qwen3.5-397B-A17B | 69.12 | 0.233 | 65.26 | 65.40 | 68.34 | 0.244 | 63.91 | 65.53 | 62.70 | 0.287 | 60.70 | 56.12 |
149
+
150
+ ---
151
+
152
+
153
+ ### [ICDAR2026 Sci-ImageMiner](https://sites.google.com/view/sci-imageminer/)
154
+ | # | Team | RMS | TEDS | Weighted |
155
+ | ----: | --------------- | --------: | --------: | --------: |
156
+ | **1** | **TeleOCR** | **17.23** | **66.39** | **41.81** |
157
+ | 2 | VLMinators | 17.29 | 64.31 | 40.80 |
158
+ | 3 | Ricoh_SRCB | 16.23 | 61.12 | 38.67 |
159
+ | 4 | Vassilis Sioros | 14.94 | 55.20 | 35.07 |
160
+ | 5 | DocMiner | 12.67 | 53.72 | 33.19 |
161
+ | 6 | Qwen3 VL 8B | 14.08 | 57.86 | 35.97 |
162
+
163
+ ---
164
+
165
+ ## 🚀 Installation
166
+
167
+ ```bash
168
+ pip install transformers torch pillow
169
+ ```
170
+
171
+ ## Quick Start
172
+
173
+ ```python
174
+ import html
175
+ import itertools
176
+ import json
177
+ import re
178
+ from dataclasses import dataclass
179
+
180
+ from PIL import Image
181
+ import torch
182
+ from transformers import AutoProcessor, AutoModel
183
+
184
+ @dataclass
185
+ class ContentBlock:
186
+ type: str
187
+ bbox: list[float]
188
+ angle: int | None = None
189
+ content: str | None = None
190
+
191
+
192
+ @dataclass
193
+ class TableCell:
194
+ text: str
195
+ start_row_offset_idx: int
196
+ end_row_offset_idx: int
197
+ start_col_offset_idx: int
198
+ end_col_offset_idx: int
199
+ row_span: int = 1
200
+ col_span: int = 1
201
+
202
+
203
+ OTSL_NL = "<nl>"
204
+ OTSL_FCEL = "<fcel>"
205
+ OTSL_ECEL = "<ecel>"
206
+ OTSL_LCEL = "<lcel>"
207
+ OTSL_UCEL = "<ucel>"
208
+ OTSL_XCEL = "<xcel>"
209
+ OTSL_TOKENS = [OTSL_NL, OTSL_FCEL, OTSL_ECEL, OTSL_LCEL, OTSL_UCEL, OTSL_XCEL]
210
+
211
+
212
+ def _otsl_extract_tokens_and_text(text: str):
213
+ pattern = "(" + "|".join(map(re.escape, OTSL_TOKENS)) + ")"
214
+ tokens = re.findall(pattern, text)
215
+ parts = [part for part in re.split(pattern, text) if part.strip()]
216
+ return tokens, parts
217
+
218
+
219
+ def _count_right(rows, row_idx, col_idx, tokens):
220
+ span = 0
221
+ while col_idx < len(rows[row_idx]) and rows[row_idx][col_idx] in tokens:
222
+ span += 1
223
+ col_idx += 1
224
+ return span
225
+
226
+
227
+ def _count_down(rows, row_idx, col_idx, tokens):
228
+ span = 0
229
+ while row_idx < len(rows) and col_idx < len(rows[row_idx]) and rows[row_idx][col_idx] in tokens:
230
+ span += 1
231
+ row_idx += 1
232
+ return span
233
+
234
+
235
+ def _otsl_parse_texts(parts, tokens):
236
+ rows = [list(row) for is_nl, row in itertools.groupby(tokens, lambda token: token == OTSL_NL) if not is_nl]
237
+ if not rows:
238
+ return [], []
239
+
240
+ max_cols = max(len(row) for row in rows)
241
+ for row in rows:
242
+ row.extend([OTSL_ECEL] * (max_cols - len(row)))
243
+
244
+ cells = []
245
+ row_idx = 0
246
+ col_idx = 0
247
+ for idx, part in enumerate(parts):
248
+ if part in (OTSL_FCEL, OTSL_ECEL):
249
+ cell_text = ""
250
+ right_offset = 1
251
+ if part != OTSL_ECEL and idx + 1 < len(parts) and parts[idx + 1] not in OTSL_TOKENS:
252
+ cell_text = parts[idx + 1].strip()
253
+ right_offset = 2
254
+
255
+ next_right = parts[idx + right_offset] if idx + right_offset < len(parts) else ""
256
+ next_bottom = rows[row_idx + 1][col_idx] if row_idx + 1 < len(rows) and col_idx < len(rows[row_idx + 1]) else ""
257
+ col_span = 1 + (_count_right(rows, row_idx, col_idx + 1, {OTSL_LCEL, OTSL_XCEL}) if next_right in {OTSL_LCEL, OTSL_XCEL} else 0)
258
+ row_span = 1 + (_count_down(rows, row_idx + 1, col_idx, {OTSL_UCEL, OTSL_XCEL}) if next_bottom in {OTSL_UCEL, OTSL_XCEL} else 0)
259
+ cells.append(TableCell(
260
+ text=cell_text,
261
+ row_span=row_span,
262
+ col_span=col_span,
263
+ start_row_offset_idx=row_idx,
264
+ end_row_offset_idx=row_idx + row_span,
265
+ start_col_offset_idx=col_idx,
266
+ end_col_offset_idx=col_idx + col_span,
267
+ ))
268
+ if part in (OTSL_FCEL, OTSL_ECEL, OTSL_LCEL, OTSL_UCEL, OTSL_XCEL):
269
+ col_idx += 1
270
+ elif part == OTSL_NL:
271
+ row_idx += 1
272
+ col_idx = 0
273
+ return cells, rows
274
+
275
+
276
+ def convert_otsl_to_html(otsl_content: str) -> str:
277
+ if otsl_content.startswith("<table") and otsl_content.endswith("</table>"):
278
+ return otsl_content
279
+
280
+ tokens, parts = _otsl_extract_tokens_and_text(otsl_content)
281
+ cells, rows = _otsl_parse_texts(parts, tokens)
282
+ if not cells or not rows:
283
+ return ""
284
+
285
+ grid = [[None for _ in range(len(rows[0]))] for _ in range(len(rows))]
286
+ for cell in cells:
287
+ for row_idx in range(cell.start_row_offset_idx, min(cell.end_row_offset_idx, len(rows))):
288
+ for col_idx in range(cell.start_col_offset_idx, min(cell.end_col_offset_idx, len(rows[0]))):
289
+ grid[row_idx][col_idx] = cell
290
+
291
+ html_rows = []
292
+ for row_idx, row in enumerate(grid):
293
+ html_rows.append("<tr>")
294
+ for col_idx, cell in enumerate(row):
295
+ if cell is None or cell.start_row_offset_idx != row_idx or cell.start_col_offset_idx != col_idx:
296
+ continue
297
+ attrs = ""
298
+ if cell.row_span > 1:
299
+ attrs += f' rowspan="{cell.row_span}"'
300
+ if cell.col_span > 1:
301
+ attrs += f' colspan="{cell.col_span}"'
302
+ html_rows.append(f"<td{attrs}>{html.escape(cell.text.strip())}</td>")
303
+ html_rows.append("</tr>")
304
+ return "<table>" + "".join(html_rows) + "</table>"
305
+
306
+
307
+ def post_process(blocks: list[ContentBlock]) -> list[ContentBlock]:
308
+ for block in blocks:
309
+ if block.type == "table" and block.content:
310
+ block.content = convert_otsl_to_html(block.content)
311
+ elif block.type == "equation" and block.content:
312
+ content = block.content.strip()
313
+ content = content.removeprefix("\\[").removesuffix("\\]").strip()
314
+ if not (content.startswith("$") and content.endswith("$")):
315
+ content = f"$${content}$$"
316
+ block.content = content
317
+ return [block for block in blocks if block.type != "equation_block"]
318
+
319
+ def infer(image: Image.Image, prompt: str) -> str:
320
+ messages = [
321
+ {"role": "system", "content": "You are a helpful assistant."},
322
+ {"role": "user", "content": [
323
+ {"type": "image"},
324
+ {"type": "text", "text": prompt},
325
+ ]},
326
+ ]
327
+ chat_prompt = processor.apply_chat_template(
328
+ messages,
329
+ tokenize=False,
330
+ add_generation_prompt=True,
331
+ )
332
+ inputs = processor(
333
+ text=[chat_prompt],
334
+ images=[image.convert("RGB")],
335
+ padding=True,
336
+ return_tensors="pt",
337
+ ).to(device=model.device, dtype=model.dtype)
338
+ output_ids = model.generate(
339
+ **inputs,
340
+ use_cache=True,
341
+ max_new_tokens=4096,
342
+ do_sample=False,
343
+ )
344
+ output_ids = output_ids.cpu().tolist()[0][len(inputs.input_ids[0]):]
345
+ return processor.batch_decode(
346
+ [output_ids],
347
+ skip_special_tokens=True,
348
+ clean_up_tokenization_spaces=False,
349
+ )[0].strip()
350
+
351
+
352
+
353
+ processor = AutoProcessor.from_pretrained("StarDoc-AI/TeleOCR", trust_remote_code=True, use_fast=True)
354
+ model = AutoModel.from_pretrained(
355
+ "StarDoc-AI/TeleOCR",
356
+ trust_remote_code=True,
357
+ torch_dtype=torch.bfloat16,
358
+ ).cuda().eval()
359
+
360
+ # text
361
+ image=Image.open("./assets/text.png").convert("RGB")
362
+ raw_text = infer(image, "Please output the text content from the image.")
363
+ print(raw_text.strip())
364
+
365
+ # table
366
+ image=Image.open("./assets/table.png").convert("RGB")
367
+ raw_otsl = infer(image, "This is the image of a table. Please output the table in OTSL format.")
368
+ print(convert_otsl_to_html(raw_otsl))
369
+
370
+ # formula
371
+ image=Image.open("./assets/formula.png").convert("RGB")
372
+ raw_formula = infer(image, "Please write out the expression of the formula in the image using LaTeX format.")
373
+ formula_block = ContentBlock("equation", [0.0, 0.0, 1.0, 1.0], content=raw_formula)
374
+ formula = post_process([formula_block])[0].content
375
+ print(formula)
376
+
377
+ #code
378
+ image=Image.open("./assets/code.png").convert("RGB")
379
+ raw_code = infer(image,"The image contains a code snippet, please output the parsing result.")
380
+ print(raw_code.strip())
381
+
382
+ # layout
383
+ image=Image.open("./assets/layout.jpg").convert("RGB")
384
+ image = image.resize((1036, 1036), Image.Resampling.BICUBIC)
385
+ raw_layout = infer(image, "Analyze the image layout.")
386
+ print(raw_layout.strip())
387
+
388
+ # Distorted document layout
389
+ layout_image = Image.open("./assets/layout_distorted.jpg").convert("RGB")
390
+ layout_image = layout_image.resize((1036, 1036), Image.Resampling.BICUBIC)
391
+ raw_layout = infer(layout_image, "\nMulti-point Layout Segmentation Analysis.")
392
+ print(raw_layout.strip())
393
+
394
+ #scientific figure
395
+ image=Image.open("./assets/scientific_figure.png").convert("RGB")
396
+ raw_scientific_figure = infer(image, "This is a scientific figure. Please extract the table implied by this figure.")
397
+ print(convert_otsl_to_html(raw_scientific_figure))
398
+ ```
399
+
400
+ If you would like to perform complete document parsing, please refer to our GitHub repository: https://github.com/caipeng328/NaviDC-OCR.
401
+
402
+ ## Citation
403
+
404
+ ```bibtex
405
+ @article{teleocr,
406
+ title={TeleOCR: Navigating Document Parsing Across Digital and Camera-Captured Documents},
407
+ author={Cai, Peng and Zou, Zhaofan and Liu, Shifa and Wang, Yikun and Tang, Jiawei and Yang, Kaicheng and Tong, Meng and He, Zhongjiang and Sun, Hao},
408
+ journal={arXiv preprint arXiv:2608.12898},
409
+ year={2026}
410
+ }
411
+ ```
412
+ ## Community Contributions
413
+
414
+ Thanks to Nandraj for the GGUF conversion and llama.cpp support! [🔗 NaviDC-OCR-GGUF](https://huggingface.co/nandraj/NaviDC-OCR-GGUF)
415
+
416
+ ## Acknowledgements
417
+
418
+ TeleOCR is built upon
419
+
420
+ - MinerU
421
+ - Qwen2.5-VL
422
+ - Qwen3
423
+ - Transformers
424
+ - PyTorch
425
+ - FlashAttention
426
+
427
+ We sincerely thank these excellent open-source projects.
428
+
429
+ ---
430
+
431
+ ## Contact
432
+
433
+ If you have any questions, feel free to open an issue or contact us.
added_tokens.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</tool_call>": 151658,
3
+ "<tool_call>": 151657,
4
+ "<|box_end|>": 151649,
5
+ "<|box_start|>": 151648,
6
+ "<|endoftext|>": 151643,
7
+ "<|file_sep|>": 151664,
8
+ "<|fim_middle|>": 151660,
9
+ "<|fim_pad|>": 151662,
10
+ "<|fim_prefix|>": 151659,
11
+ "<|fim_suffix|>": 151661,
12
+ "<|im_end|>": 151645,
13
+ "<|im_start|>": 151644,
14
+ "<|image_pad|>": 151655,
15
+ "<|object_ref_end|>": 151647,
16
+ "<|object_ref_start|>": 151646,
17
+ "<|quad_end|>": 151651,
18
+ "<|quad_start|>": 151650,
19
+ "<|repo_name|>": 151663,
20
+ "<|video_pad|>": 151656,
21
+ "<|vision_end|>": 151653,
22
+ "<|vision_pad|>": 151654,
23
+ "<|vision_start|>": 151652
24
+ }
assets/code.png ADDED

Git LFS Details

  • SHA256: 741314175f5bbf26dbaa7e4f35a4294d4f81525aa8d4a1c361a1ee3ff95de956
  • Pointer size: 131 Bytes
  • Size of remote file: 195 kB
assets/formula.png ADDED
assets/icon.png ADDED

Git LFS Details

  • SHA256: 0aaf2740dfb42e01e4f6b8d3889714979113d7e4314e4db7ebb5be4c3c9bcf29
  • Pointer size: 131 Bytes
  • Size of remote file: 590 kB
assets/layout.jpg ADDED

Git LFS Details

  • SHA256: 2ae27f3a9284810bf7ce479ac8921359ccf00b7ebee1017b5e8da3e28ebe4af4
  • Pointer size: 131 Bytes
  • Size of remote file: 749 kB
assets/layout_distorted.jpg ADDED

Git LFS Details

  • SHA256: 86000b5847dca0464838c9672650b7688fa942d92c241b2ec778ca613cd25dcd
  • Pointer size: 131 Bytes
  • Size of remote file: 613 kB
assets/scientific_figure.png ADDED
assets/score.png ADDED

Git LFS Details

  • SHA256: b51176d58fe15b8aae04d092640ec675e41b992c51de0082fca164aecdb0792c
  • Pointer size: 131 Bytes
  • Size of remote file: 349 kB
assets/table.png ADDED
assets/text.png ADDED
chat_template.jinja ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {% set image_count = namespace(value=0) %}{% set video_count = namespace(value=0) %}{% for message in messages %}{% if loop.first and message['role'] != 'system' %}<|im_start|>system
2
+ You are a helpful assistant.<|im_end|>
3
+ {% endif %}<|im_start|>{{ message['role'] }}
4
+ {% if message['content'] is string %}{{ message['content'] }}<|im_end|>
5
+ {% else %}{% for content in message['content'] %}{% if content['type'] == 'image' or 'image' in content or 'image_url' in content %}{% set image_count.value = image_count.value + 1 %}{% if add_vision_id %}Picture {{ image_count.value }}: {% endif %}<|vision_start|><|image_pad|><|vision_end|>{% elif content['type'] == 'video' or 'video' in content %}{% set video_count.value = video_count.value + 1 %}{% if add_vision_id %}Video {{ video_count.value }}: {% endif %}<|vision_start|><|video_pad|><|vision_end|>{% elif 'text' in content %}{{ content['text'] }}{% endif %}{% endfor %}<|im_end|>
6
+ {% endif %}{% endfor %}{% if add_generation_prompt %}<|im_start|>assistant
7
+ {% endif %}
config.json ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Qwen2_5_VLForConditionalGeneration"
4
+ ],
5
+ "attention_dropout": 0.0,
6
+ "bos_token_id": 151643,
7
+ "dtype": "bfloat16",
8
+ "eos_token_id": 151645,
9
+ "head_dim": 128,
10
+ "hidden_act": "silu",
11
+ "hidden_size": 1024,
12
+ "image_token_id": 151655,
13
+ "initializer_range": 0.02,
14
+ "intermediate_size": 3072,
15
+ "max_position_embeddings": 128000,
16
+ "max_window_layers": 28,
17
+ "model_type": "qwen2_5_vl",
18
+ "num_attention_heads": 16,
19
+ "num_hidden_layers": 28,
20
+ "num_key_value_heads": 8,
21
+ "rms_norm_eps": 1e-06,
22
+ "rope_scaling": {
23
+ "mrope_section": [
24
+ 16,
25
+ 24,
26
+ 24
27
+ ],
28
+ "rope_type": "default",
29
+ "type": "default"
30
+ },
31
+ "rope_theta": 1000000.0,
32
+ "sliding_window": 32768,
33
+ "text_config": {
34
+ "_name_or_path": "",
35
+ "architectures": [
36
+ "Qwen2_5_VLForConditionalGeneration"
37
+ ],
38
+ "attention_dropout": 0.0,
39
+ "dtype": "bfloat16",
40
+ "eos_token_id": 151645,
41
+ "head_dim": 128,
42
+ "hidden_act": "silu",
43
+ "hidden_size": 1024,
44
+ "initializer_range": 0.02,
45
+ "intermediate_size": 3072,
46
+ "layer_types": [
47
+ "full_attention",
48
+ "full_attention",
49
+ "full_attention",
50
+ "full_attention",
51
+ "full_attention",
52
+ "full_attention",
53
+ "full_attention",
54
+ "full_attention",
55
+ "full_attention",
56
+ "full_attention",
57
+ "full_attention",
58
+ "full_attention",
59
+ "full_attention",
60
+ "full_attention",
61
+ "full_attention",
62
+ "full_attention",
63
+ "full_attention",
64
+ "full_attention",
65
+ "full_attention",
66
+ "full_attention",
67
+ "full_attention",
68
+ "full_attention",
69
+ "full_attention",
70
+ "full_attention",
71
+ "full_attention",
72
+ "full_attention",
73
+ "full_attention",
74
+ "full_attention"
75
+ ],
76
+ "max_position_embeddings": 128000,
77
+ "max_window_layers": 28,
78
+ "model_type": "qwen2_5_vl_text",
79
+ "num_attention_heads": 16,
80
+ "num_hidden_layers": 28,
81
+ "num_key_value_heads": 8,
82
+ "pad_token_id": 151643,
83
+ "rms_norm_eps": 1e-06,
84
+ "rope_scaling": {
85
+ "mrope_section": [
86
+ 16,
87
+ 24,
88
+ 24
89
+ ],
90
+ "rope_type": "default",
91
+ "type": "default"
92
+ },
93
+ "rope_theta": 1000000.0,
94
+ "sliding_window": null,
95
+ "tie_word_embeddings": true,
96
+ "use_cache": false,
97
+ "use_sliding_window": false,
98
+ "vision_token_id": 151654,
99
+ "vocab_size": 151936
100
+ },
101
+ "transformers_version": "4.57.1",
102
+ "use_cache": true,
103
+ "use_sliding_window": false,
104
+ "video_token_id": 151656,
105
+ "vision_config": {
106
+ "depth": 32,
107
+ "dtype": "bfloat16",
108
+ "fullatt_block_indexes": [
109
+ 7,
110
+ 15,
111
+ 23,
112
+ 31
113
+ ],
114
+ "hidden_act": "silu",
115
+ "hidden_size": 1280,
116
+ "in_channels": 3,
117
+ "in_chans": 3,
118
+ "initializer_range": 0.02,
119
+ "intermediate_size": 3420,
120
+ "model_type": "qwen2_5_vl",
121
+ "num_heads": 16,
122
+ "out_hidden_size": 1024,
123
+ "pad_token_id": 151643,
124
+ "patch_size": 14,
125
+ "spatial_merge_size": 2,
126
+ "spatial_patch_size": 14,
127
+ "temporal_patch_size": 2,
128
+ "tokens_per_second": 2,
129
+ "window_size": 112
130
+ },
131
+ "vision_end_token_id": 151653,
132
+ "vision_start_token_id": 151652,
133
+ "vision_token_id": 151654,
134
+ "vocab_size": 151936,
135
+ "auto_map": {
136
+ "AutoModel": "modeling_naviocr.Qwen2_5_VLForConditionalGeneration",
137
+ "AutoModelForCausalLM": "modeling_naviocr.Qwen2_5_VLForConditionalGeneration",
138
+ "AutoModelForImageTextToText": "modeling_naviocr.Qwen2_5_VLForConditionalGeneration",
139
+ "AutoModelForVision2Seq": "modeling_naviocr.Qwen2_5_VLForConditionalGeneration"
140
+ }
141
+ }
generation_config.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 151643,
3
+ "do_sample": true,
4
+ "eos_token_id": [
5
+ 151645,
6
+ 151643
7
+ ],
8
+ "pad_token_id": 151643,
9
+ "repetition_penalty": 1.05,
10
+ "temperature": 0.1,
11
+ "top_k": 1,
12
+ "top_p": 0.001,
13
+ "transformers_version": "4.57.1"
14
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9817b18041bd96403f75e38a33b28ed0cd5fb2641f67eead673afabd3c408109
3
+ size 2830223488
modeling_naviocr.py ADDED
@@ -0,0 +1,1754 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/qwen2_5_vl/modular_qwen2_5_vl.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_qwen2_5_vl.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2025 The Qwen Team and The HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
11
+ # and OPT implementations in this library. It has been modified from its
12
+ # original forms to accommodate minor architectural differences compared
13
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
14
+ #
15
+ # Licensed under the Apache License, Version 2.0 (the "License");
16
+ # you may not use this file except in compliance with the License.
17
+ # You may obtain a copy of the License at
18
+ #
19
+ # http://www.apache.org/licenses/LICENSE-2.0
20
+ #
21
+ # Unless required by applicable law or agreed to in writing, software
22
+ # distributed under the License is distributed on an "AS IS" BASIS,
23
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24
+ # See the License for the specific language governing permissions and
25
+ # limitations under the License.
26
+
27
+ from dataclasses import dataclass
28
+ from typing import Any, Callable, Optional, Union
29
+
30
+ import torch
31
+ import torch.nn as nn
32
+ import torch.nn.functional as F
33
+
34
+ from transformers.activations import ACT2FN
35
+ from transformers.cache_utils import Cache, DynamicCache
36
+ from transformers.generation import GenerationMixin
37
+ from transformers.integrations import use_kernel_forward_from_hub
38
+ from transformers.masking_utils import create_causal_mask, create_sliding_window_causal_mask
39
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
40
+ from transformers.modeling_layers import GradientCheckpointingLayer
41
+ from transformers.modeling_outputs import BaseModelOutputWithPast, ModelOutput
42
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
43
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
44
+ from transformers.processing_utils import Unpack
45
+ from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple, is_torchdynamo_compiling, logging
46
+ from transformers.utils.deprecation import deprecate_kwarg
47
+ from transformers.models.qwen2.modeling_qwen2 import Qwen2RMSNorm
48
+ from transformers.models.qwen2_5_vl.configuration_qwen2_5_vl import Qwen2_5_VLConfig, Qwen2_5_VLTextConfig, Qwen2_5_VLVisionConfig
49
+
50
+
51
+ logger = logging.get_logger(__name__)
52
+
53
+
54
+ class Qwen2_5_VLMLP(nn.Module):
55
+ def __init__(self, config, bias: bool = False):
56
+ super().__init__()
57
+ self.hidden_size = config.hidden_size
58
+ self.intermediate_size = config.intermediate_size
59
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=bias)
60
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=bias)
61
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=bias)
62
+ self.act_fn = ACT2FN[config.hidden_act]
63
+
64
+ def forward(self, hidden_state):
65
+ return self.down_proj(self.act_fn(self.gate_proj(hidden_state)) * self.up_proj(hidden_state))
66
+
67
+
68
+ class Qwen2_5_VisionPatchEmbed(nn.Module):
69
+ def __init__(
70
+ self,
71
+ patch_size: int = 14,
72
+ temporal_patch_size: int = 2,
73
+ in_channels: int = 3,
74
+ embed_dim: int = 1152,
75
+ ) -> None:
76
+ super().__init__()
77
+ self.patch_size = patch_size
78
+ self.temporal_patch_size = temporal_patch_size
79
+ self.in_channels = in_channels
80
+ self.embed_dim = embed_dim
81
+
82
+ kernel_size = [temporal_patch_size, patch_size, patch_size]
83
+ self.proj = nn.Conv3d(in_channels, embed_dim, kernel_size=kernel_size, stride=kernel_size, bias=False)
84
+
85
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
86
+ target_dtype = self.proj.weight.dtype
87
+ hidden_states = hidden_states.view(
88
+ -1, self.in_channels, self.temporal_patch_size, self.patch_size, self.patch_size
89
+ )
90
+ hidden_states = self.proj(hidden_states.to(dtype=target_dtype)).view(-1, self.embed_dim)
91
+ return hidden_states
92
+
93
+
94
+ class Qwen2_5_VisionRotaryEmbedding(nn.Module):
95
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
96
+
97
+ def __init__(self, dim: int, theta: float = 10000.0) -> None:
98
+ super().__init__()
99
+ inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim))
100
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
101
+
102
+ def forward(self, seqlen: int) -> torch.Tensor:
103
+ seq = torch.arange(seqlen, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
104
+ freqs = torch.outer(seq, self.inv_freq)
105
+ return freqs
106
+
107
+
108
+ class Qwen2_5_VLPatchMerger(nn.Module):
109
+ def __init__(self, dim: int, context_dim: int, spatial_merge_size: int = 2) -> None:
110
+ super().__init__()
111
+ self.hidden_size = context_dim * (spatial_merge_size**2)
112
+ self.ln_q = Qwen2RMSNorm(context_dim, eps=1e-6)
113
+ self.mlp = nn.Sequential(
114
+ nn.Linear(self.hidden_size, self.hidden_size),
115
+ nn.GELU(),
116
+ nn.Linear(self.hidden_size, dim),
117
+ )
118
+
119
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
120
+ x = self.mlp(self.ln_q(x).view(-1, self.hidden_size))
121
+ return x
122
+
123
+
124
+ def rotate_half(x):
125
+ """Rotates half the hidden dims of the input."""
126
+ x1 = x[..., : x.shape[-1] // 2]
127
+ x2 = x[..., x.shape[-1] // 2 :]
128
+ return torch.cat((-x2, x1), dim=-1)
129
+
130
+
131
+ def apply_rotary_pos_emb_vision(
132
+ q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor
133
+ ) -> tuple[torch.Tensor, torch.Tensor]:
134
+ orig_q_dtype = q.dtype
135
+ orig_k_dtype = k.dtype
136
+ q, k = q.float(), k.float()
137
+ cos, sin = cos.unsqueeze(-2).float(), sin.unsqueeze(-2).float()
138
+ q_embed = (q * cos) + (rotate_half(q) * sin)
139
+ k_embed = (k * cos) + (rotate_half(k) * sin)
140
+ q_embed = q_embed.to(orig_q_dtype)
141
+ k_embed = k_embed.to(orig_k_dtype)
142
+ return q_embed, k_embed
143
+
144
+
145
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
146
+ """
147
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
148
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
149
+ """
150
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
151
+ if n_rep == 1:
152
+ return hidden_states
153
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
154
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
155
+
156
+
157
+ def eager_attention_forward(
158
+ module: nn.Module,
159
+ query: torch.Tensor,
160
+ key: torch.Tensor,
161
+ value: torch.Tensor,
162
+ attention_mask: Optional[torch.Tensor],
163
+ scaling: float,
164
+ dropout: float = 0.0,
165
+ **kwargs,
166
+ ):
167
+ key_states = repeat_kv(key, module.num_key_value_groups)
168
+ value_states = repeat_kv(value, module.num_key_value_groups)
169
+
170
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
171
+ if attention_mask is not None:
172
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
173
+ attn_weights = attn_weights + causal_mask
174
+
175
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
176
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
177
+ attn_output = torch.matmul(attn_weights, value_states)
178
+ attn_output = attn_output.transpose(1, 2).contiguous()
179
+
180
+ return attn_output, attn_weights
181
+
182
+
183
+ class Qwen2_5_VLVisionAttention(nn.Module):
184
+ def __init__(self, config: Qwen2_5_VLVisionConfig) -> None:
185
+ super().__init__()
186
+ self.dim = config.hidden_size
187
+ self.num_heads = config.num_heads
188
+ self.head_dim = self.dim // self.num_heads
189
+ self.num_key_value_groups = 1 # needed for eager attention
190
+ self.qkv = nn.Linear(self.dim, self.dim * 3, bias=True)
191
+ self.proj = nn.Linear(self.dim, self.dim)
192
+ self.scaling = self.head_dim**-0.5
193
+ self.config = config
194
+ self.attention_dropout = 0.0
195
+ self.is_causal = False
196
+
197
+ def forward(
198
+ self,
199
+ hidden_states: torch.Tensor,
200
+ cu_seqlens: torch.Tensor,
201
+ rotary_pos_emb: Optional[torch.Tensor] = None,
202
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
203
+ **kwargs,
204
+ ) -> torch.Tensor:
205
+ seq_length = hidden_states.shape[0]
206
+ query_states, key_states, value_states = (
207
+ self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0)
208
+ )
209
+ cos, sin = position_embeddings
210
+ query_states, key_states = apply_rotary_pos_emb_vision(query_states, key_states, cos, sin)
211
+
212
+ query_states = query_states.transpose(0, 1).unsqueeze(0)
213
+ key_states = key_states.transpose(0, 1).unsqueeze(0)
214
+ value_states = value_states.transpose(0, 1).unsqueeze(0)
215
+
216
+ attention_interface: Callable = eager_attention_forward
217
+ if self.config._attn_implementation != "eager":
218
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
219
+
220
+ if self.config._attn_implementation == "flash_attention_2":
221
+ # Flash Attention 2: Use cu_seqlens for variable length attention
222
+ max_seqlen = (cu_seqlens[1:] - cu_seqlens[:-1]).max()
223
+ attn_output, _ = attention_interface(
224
+ self,
225
+ query_states,
226
+ key_states,
227
+ value_states,
228
+ attention_mask=None,
229
+ scaling=self.scaling,
230
+ dropout=0.0 if not self.training else self.attention_dropout,
231
+ cu_seq_lens_q=cu_seqlens,
232
+ cu_seq_lens_k=cu_seqlens,
233
+ max_length_q=max_seqlen,
234
+ max_length_k=max_seqlen,
235
+ is_causal=False,
236
+ **kwargs,
237
+ )
238
+ else:
239
+ # Other implementations: Process each chunk separately
240
+ lengths = cu_seqlens[1:] - cu_seqlens[:-1]
241
+ splits = [
242
+ torch.split(tensor, lengths.tolist(), dim=2) for tensor in (query_states, key_states, value_states)
243
+ ]
244
+
245
+ attn_outputs = [
246
+ attention_interface(
247
+ self,
248
+ q,
249
+ k,
250
+ v,
251
+ attention_mask=None,
252
+ scaling=self.scaling,
253
+ dropout=0.0 if not self.training else self.attention_dropout,
254
+ is_causal=False,
255
+ **kwargs,
256
+ )[0]
257
+ for q, k, v in zip(*splits)
258
+ ]
259
+ attn_output = torch.cat(attn_outputs, dim=1)
260
+
261
+ attn_output = attn_output.reshape(seq_length, -1).contiguous()
262
+ attn_output = self.proj(attn_output)
263
+ return attn_output
264
+
265
+
266
+ class Qwen2_5_VLVisionBlock(GradientCheckpointingLayer):
267
+ def __init__(self, config, attn_implementation: str = "sdpa") -> None:
268
+ super().__init__()
269
+ self.norm1 = Qwen2RMSNorm(config.hidden_size, eps=1e-6)
270
+ self.norm2 = Qwen2RMSNorm(config.hidden_size, eps=1e-6)
271
+ self.attn = Qwen2_5_VLVisionAttention(config=config)
272
+ self.mlp = Qwen2_5_VLMLP(config, bias=True)
273
+
274
+ def forward(
275
+ self,
276
+ hidden_states: torch.Tensor,
277
+ cu_seqlens: torch.Tensor,
278
+ rotary_pos_emb: Optional[torch.Tensor] = None,
279
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
280
+ **kwargs,
281
+ ) -> torch.Tensor:
282
+ hidden_states = hidden_states + self.attn(
283
+ self.norm1(hidden_states),
284
+ cu_seqlens=cu_seqlens,
285
+ rotary_pos_emb=rotary_pos_emb,
286
+ position_embeddings=position_embeddings,
287
+ **kwargs,
288
+ )
289
+ hidden_states = hidden_states + self.mlp(self.norm2(hidden_states))
290
+ return hidden_states
291
+
292
+
293
+ @auto_docstring
294
+ class Qwen2_5_VLPreTrainedModel(PreTrainedModel):
295
+ config: Qwen2_5_VLConfig
296
+ base_model_prefix = "model"
297
+ supports_gradient_checkpointing = True
298
+ _no_split_modules = ["Qwen2_5_VLDecoderLayer", "Qwen2_5_VLVisionBlock"]
299
+ _skip_keys_device_placement = "past_key_values"
300
+ _supports_flash_attn = True
301
+ _supports_sdpa = True
302
+
303
+ _can_compile_fullgraph = True
304
+ _supports_attention_backend = True
305
+
306
+
307
+ class Qwen2_5_VisionTransformerPretrainedModel(Qwen2_5_VLPreTrainedModel):
308
+ config: Qwen2_5_VLVisionConfig
309
+ _no_split_modules = ["Qwen2_5_VLVisionBlock"]
310
+
311
+ def __init__(self, config, *inputs, **kwargs) -> None:
312
+ super().__init__(config, *inputs, **kwargs)
313
+ self.spatial_merge_size = config.spatial_merge_size
314
+ self.patch_size = config.patch_size
315
+ self.fullatt_block_indexes = config.fullatt_block_indexes
316
+ self.window_size = config.window_size
317
+ self.spatial_merge_unit = self.spatial_merge_size * self.spatial_merge_size
318
+
319
+ self.patch_embed = Qwen2_5_VisionPatchEmbed(
320
+ patch_size=config.patch_size,
321
+ temporal_patch_size=config.temporal_patch_size,
322
+ in_channels=config.in_channels,
323
+ embed_dim=config.hidden_size,
324
+ )
325
+
326
+ head_dim = config.hidden_size // config.num_heads
327
+ self.rotary_pos_emb = Qwen2_5_VisionRotaryEmbedding(head_dim // 2)
328
+
329
+ self.blocks = nn.ModuleList([Qwen2_5_VLVisionBlock(config) for _ in range(config.depth)])
330
+ self.merger = Qwen2_5_VLPatchMerger(
331
+ dim=config.out_hidden_size,
332
+ context_dim=config.hidden_size,
333
+ spatial_merge_size=config.spatial_merge_size,
334
+ )
335
+ self.gradient_checkpointing = False
336
+
337
+ def rot_pos_emb(self, grid_thw):
338
+ pos_ids = []
339
+ for t, h, w in grid_thw:
340
+ hpos_ids = torch.arange(h).unsqueeze(1).expand(-1, w)
341
+ hpos_ids = hpos_ids.reshape(
342
+ h // self.spatial_merge_size,
343
+ self.spatial_merge_size,
344
+ w // self.spatial_merge_size,
345
+ self.spatial_merge_size,
346
+ )
347
+ hpos_ids = hpos_ids.permute(0, 2, 1, 3)
348
+ hpos_ids = hpos_ids.flatten()
349
+
350
+ wpos_ids = torch.arange(w).unsqueeze(0).expand(h, -1)
351
+ wpos_ids = wpos_ids.reshape(
352
+ h // self.spatial_merge_size,
353
+ self.spatial_merge_size,
354
+ w // self.spatial_merge_size,
355
+ self.spatial_merge_size,
356
+ )
357
+ wpos_ids = wpos_ids.permute(0, 2, 1, 3)
358
+ wpos_ids = wpos_ids.flatten()
359
+ pos_ids.append(torch.stack([hpos_ids, wpos_ids], dim=-1).repeat(t, 1))
360
+ pos_ids = torch.cat(pos_ids, dim=0)
361
+ max_grid_size = grid_thw[:, 1:].max()
362
+ rotary_pos_emb_full = self.rotary_pos_emb(max_grid_size)
363
+ rotary_pos_emb = rotary_pos_emb_full[pos_ids].flatten(1)
364
+ return rotary_pos_emb
365
+
366
+ def get_window_index(self, grid_thw):
367
+ window_index: list = []
368
+ cu_window_seqlens: list = [0]
369
+ window_index_id = 0
370
+ vit_merger_window_size = self.window_size // self.spatial_merge_size // self.patch_size
371
+
372
+ for grid_t, grid_h, grid_w in grid_thw:
373
+ llm_grid_h, llm_grid_w = (
374
+ grid_h // self.spatial_merge_size,
375
+ grid_w // self.spatial_merge_size,
376
+ )
377
+ index = torch.arange(grid_t * llm_grid_h * llm_grid_w).reshape(grid_t, llm_grid_h, llm_grid_w)
378
+ pad_h = vit_merger_window_size - llm_grid_h % vit_merger_window_size
379
+ pad_w = vit_merger_window_size - llm_grid_w % vit_merger_window_size
380
+ num_windows_h = (llm_grid_h + pad_h) // vit_merger_window_size
381
+ num_windows_w = (llm_grid_w + pad_w) // vit_merger_window_size
382
+ index_padded = F.pad(index, (0, pad_w, 0, pad_h), "constant", -100)
383
+ index_padded = index_padded.reshape(
384
+ grid_t,
385
+ num_windows_h,
386
+ vit_merger_window_size,
387
+ num_windows_w,
388
+ vit_merger_window_size,
389
+ )
390
+ index_padded = index_padded.permute(0, 1, 3, 2, 4).reshape(
391
+ grid_t,
392
+ num_windows_h * num_windows_w,
393
+ vit_merger_window_size,
394
+ vit_merger_window_size,
395
+ )
396
+ seqlens = (index_padded != -100).sum([2, 3]).reshape(-1)
397
+ index_padded = index_padded.reshape(-1)
398
+ index_new = index_padded[index_padded != -100]
399
+ window_index.append(index_new + window_index_id)
400
+ cu_seqlens_tmp = seqlens.cumsum(0) * self.spatial_merge_unit + cu_window_seqlens[-1]
401
+ cu_window_seqlens.extend(cu_seqlens_tmp.tolist())
402
+ window_index_id += (grid_t * llm_grid_h * llm_grid_w).item()
403
+ window_index = torch.cat(window_index, dim=0)
404
+
405
+ return window_index, cu_window_seqlens
406
+
407
+ def forward(self, hidden_states: torch.Tensor, grid_thw: torch.Tensor, **kwargs) -> torch.Tensor:
408
+ """
409
+ Args:
410
+ hidden_states (`torch.Tensor` of shape `(seq_len, hidden_size)`):
411
+ The final hidden states of the model.
412
+ grid_thw (`torch.Tensor` of shape `(num_images_or_videos, 3)`):
413
+ The temporal, height and width of feature shape of each image in LLM.
414
+
415
+ Returns:
416
+ `torch.Tensor`: hidden_states.
417
+ """
418
+ hidden_states = self.patch_embed(hidden_states)
419
+ rotary_pos_emb = self.rot_pos_emb(grid_thw)
420
+ window_index, cu_window_seqlens = self.get_window_index(grid_thw)
421
+ cu_window_seqlens = torch.tensor(
422
+ cu_window_seqlens,
423
+ device=hidden_states.device,
424
+ dtype=grid_thw.dtype if torch.jit.is_tracing() else torch.int32,
425
+ )
426
+ cu_window_seqlens = torch.unique_consecutive(cu_window_seqlens)
427
+
428
+ seq_len, _ = hidden_states.size()
429
+ hidden_states = hidden_states.reshape(seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1)
430
+ hidden_states = hidden_states[window_index, :, :]
431
+ hidden_states = hidden_states.reshape(seq_len, -1)
432
+ rotary_pos_emb = rotary_pos_emb.reshape(seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1)
433
+ rotary_pos_emb = rotary_pos_emb[window_index, :, :]
434
+ rotary_pos_emb = rotary_pos_emb.reshape(seq_len, -1)
435
+ emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1)
436
+ position_embeddings = (emb.cos(), emb.sin())
437
+
438
+ cu_seqlens = torch.repeat_interleave(grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0]).cumsum(
439
+ dim=0,
440
+ # Select dtype based on the following factors:
441
+ # - FA2 requires that cu_seqlens_q must have dtype int32
442
+ # - torch.onnx.export requires that cu_seqlens_q must have same dtype as grid_thw
443
+ # See https://github.com/huggingface/transformers/pull/34852 for more information
444
+ dtype=grid_thw.dtype if torch.jit.is_tracing() else torch.int32,
445
+ )
446
+ cu_seqlens = F.pad(cu_seqlens, (1, 0), value=0)
447
+
448
+ for layer_num, blk in enumerate(self.blocks):
449
+ if layer_num in self.fullatt_block_indexes:
450
+ cu_seqlens_now = cu_seqlens
451
+ else:
452
+ cu_seqlens_now = cu_window_seqlens
453
+
454
+ hidden_states = blk(
455
+ hidden_states,
456
+ cu_seqlens=cu_seqlens_now,
457
+ position_embeddings=position_embeddings,
458
+ **kwargs,
459
+ )
460
+
461
+ hidden_states = self.merger(hidden_states)
462
+ reverse_indices = torch.argsort(window_index)
463
+ hidden_states = hidden_states[reverse_indices, :]
464
+
465
+ return hidden_states
466
+
467
+
468
+ @dataclass
469
+ @auto_docstring(
470
+ custom_intro="""
471
+ Base class for Llava outputs, with hidden states and attentions.
472
+ """
473
+ )
474
+ class Qwen2_5_VLModelOutputWithPast(ModelOutput):
475
+ r"""
476
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
477
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
478
+
479
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
480
+ `past_key_values` input) to speed up sequential decoding.
481
+ rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
482
+ The rope index difference between sequence length and multimodal rope.
483
+ """
484
+
485
+ last_hidden_state: Optional[torch.FloatTensor] = None
486
+ past_key_values: Optional[Cache] = None
487
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
488
+ attentions: Optional[tuple[torch.FloatTensor]] = None
489
+ rope_deltas: Optional[torch.LongTensor] = None
490
+
491
+
492
+ class Qwen2_5_VLRotaryEmbedding(nn.Module):
493
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
494
+
495
+ def __init__(self, config: Qwen2_5_VLTextConfig, device=None):
496
+ super().__init__()
497
+ # BC: "rope_type" was originally "type"
498
+
499
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
500
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
501
+ else:
502
+ self.rope_type = "default"
503
+ self.max_seq_len_cached = config.max_position_embeddings
504
+ self.original_max_seq_len = config.max_position_embeddings
505
+
506
+ self.config = config
507
+ # assert False, self.rope_type
508
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
509
+
510
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
511
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
512
+ self.original_inv_freq = self.inv_freq
513
+
514
+ @torch.no_grad()
515
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
516
+ def forward(self, x, position_ids):
517
+ # In contrast to other models, Qwen2_5_VL has different position ids for the grids
518
+ # So we expand the inv_freq to shape (3, ...)
519
+ inv_freq_expanded = self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1)
520
+ position_ids_expanded = position_ids[:, :, None, :].float() # shape (3, bs, 1, positions)
521
+
522
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
523
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
524
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(2, 3)
525
+ emb = torch.cat((freqs, freqs), dim=-1)
526
+ cos = emb.cos() * self.attention_scaling
527
+ sin = emb.sin() * self.attention_scaling
528
+ # torch.Size([3, 1, 16358, 128]) torch.Size([64]) torch.Size([3, 1, 64, 1])
529
+ # assert False, f'{cos.shape} {self.inv_freq.shape} {inv_freq_expanded.shape}'
530
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
531
+
532
+
533
+ class Qwen2MLP(nn.Module):
534
+ def __init__(self, config):
535
+ super().__init__()
536
+ self.config = config
537
+ self.hidden_size = config.hidden_size
538
+ self.intermediate_size = config.intermediate_size
539
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
540
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
541
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
542
+ self.act_fn = ACT2FN[config.hidden_act]
543
+
544
+ def forward(self, x):
545
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
546
+ return down_proj
547
+
548
+
549
+ def apply_multimodal_rotary_pos_emb(q, k, cos, sin, mrope_section, unsqueeze_dim=1):
550
+ """Applies Rotary Position Embedding with Multimodal Sections to the query and key tensors (https://qwenlm.github.io/blog/qwen2-vl/).
551
+
552
+ Explanation:
553
+ Multimodal 3D rotary position embedding is an extension to 1D rotary position embedding. The input embedding
554
+ sequence contains vision (images / videos) embedding and text embedding or just contains text embedding. For
555
+ vision embedding part, we apply rotary position embedding on temporal, height and width dimension separately.
556
+ Here we split the channel dimension to 3 chunks for the temporal, height and width rotary position embedding.
557
+ For text embedding part, we just apply 1D rotary position embedding. The three rotary position index (temporal,
558
+ height and width) of text embedding is always the same, so the text embedding rotary position embedding has no
559
+ difference with modern LLMs.
560
+
561
+ Args:
562
+ q (`torch.Tensor`): The query tensor.
563
+ k (`torch.Tensor`): The key tensor.
564
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
565
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
566
+ position_ids (`torch.Tensor`):
567
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
568
+ used to pass offsetted position ids when working with a KV-cache.
569
+ mrope_section(`List(int)`):
570
+ Multimodal rope section is for channel dimension of temporal, height and width in rope calculation.
571
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
572
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
573
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
574
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
575
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
576
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
577
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
578
+ Returns:
579
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
580
+ """
581
+ mrope_section = mrope_section * 2
582
+ cos = torch.cat([m[i % 3] for i, m in enumerate(cos.split(mrope_section, dim=-1))], dim=-1).unsqueeze(
583
+ unsqueeze_dim
584
+ )
585
+ sin = torch.cat([m[i % 3] for i, m in enumerate(sin.split(mrope_section, dim=-1))], dim=-1).unsqueeze(
586
+ unsqueeze_dim
587
+ )
588
+
589
+
590
+ q_embed = (q * cos) + (rotate_half(q) * sin)
591
+ k_embed = (k * cos) + (rotate_half(k) * sin)
592
+ return q_embed, k_embed
593
+
594
+ @use_kernel_forward_from_hub("RMSNorm")
595
+ class Qwen3RMSNorm(nn.Module):
596
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
597
+ """
598
+ Qwen3RMSNorm is equivalent to T5LayerNorm
599
+ """
600
+ super().__init__()
601
+ self.weight = nn.Parameter(torch.ones(hidden_size))
602
+ self.variance_epsilon = eps
603
+
604
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
605
+ input_dtype = hidden_states.dtype
606
+ hidden_states = hidden_states.to(torch.float32)
607
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
608
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
609
+ return self.weight * hidden_states.to(input_dtype)
610
+
611
+ def extra_repr(self):
612
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
613
+
614
+
615
+ class Qwen2_5_VLAttention(nn.Module):
616
+ """
617
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
618
+ and "Generating Long Sequences with Sparse Transformers".
619
+ """
620
+
621
+ def __init__(self, config: Qwen2_5_VLTextConfig, layer_idx: Optional[int] = None):
622
+ super().__init__()
623
+ self.config = config
624
+ self.layer_idx = layer_idx
625
+ if layer_idx is None:
626
+ logger.warning_once(
627
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
628
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
629
+ "when creating this class."
630
+ )
631
+
632
+ self.hidden_size = config.hidden_size
633
+ self.num_heads = config.num_attention_heads
634
+ # assert False, config
635
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // self.num_heads)
636
+ self.num_key_value_heads = config.num_key_value_heads
637
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
638
+ self.is_causal = True
639
+ self.attention_dropout = config.attention_dropout
640
+ self.rope_scaling = config.rope_scaling
641
+ self.scaling = self.head_dim**-0.5
642
+
643
+ # if (self.head_dim * self.num_heads) != self.hidden_size:
644
+ # raise ValueError(
645
+ # f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
646
+ # f" and `num_heads`: {self.num_heads})."
647
+ # )
648
+ # 16 64 8
649
+ # assert False, f'{self.num_heads} {self.head_dim} {self.num_key_value_heads}'
650
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
651
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
652
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
653
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
654
+ self.sliding_window = config.sliding_window if config.layer_types[layer_idx] == "sliding_attention" else None
655
+
656
+ self.q_norm = Qwen3RMSNorm(self.head_dim, eps=config.rms_norm_eps) # unlike olmo, only on the head dim!
657
+ self.k_norm = Qwen3RMSNorm(self.head_dim, eps=config.rms_norm_eps) # thus post q_norm does not need reshape
658
+
659
+ self.rotary_emb = Qwen2_5_VLRotaryEmbedding(config=config)
660
+
661
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
662
+ def forward(
663
+ self,
664
+ hidden_states: torch.Tensor,
665
+ attention_mask: Optional[torch.Tensor] = None,
666
+ position_ids: Optional[torch.LongTensor] = None,
667
+ past_key_values: Optional[Cache] = None,
668
+ output_attentions: bool = False,
669
+ use_cache: bool = False,
670
+ cache_position: Optional[torch.LongTensor] = None,
671
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
672
+ **kwargs: Unpack[FlashAttentionKwargs],
673
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
674
+ bsz, q_len, _ = hidden_states.size()
675
+ query_states = self.q_proj(hidden_states)
676
+ key_states = self.k_proj(hidden_states)
677
+ value_states = self.v_proj(hidden_states)
678
+
679
+ query_states = self.q_norm(query_states.view(bsz, q_len, -1, self.head_dim)).transpose(1, 2)
680
+ key_states = self.k_norm(key_states.view(bsz, q_len, -1, self.head_dim)).transpose(1, 2)
681
+ value_states = value_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
682
+
683
+ cos, sin = position_embeddings
684
+ query_states, key_states = apply_multimodal_rotary_pos_emb(
685
+ query_states, key_states, cos, sin, self.rope_scaling["mrope_section"]
686
+ )
687
+
688
+ if past_key_values is not None:
689
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
690
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
691
+
692
+ attention_interface: Callable = eager_attention_forward
693
+ if self.config._attn_implementation != "eager":
694
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
695
+
696
+ attn_output, attn_weights = attention_interface(
697
+ self,
698
+ query_states,
699
+ key_states,
700
+ value_states,
701
+ attention_mask,
702
+ dropout=0.0 if not self.training else self.attention_dropout,
703
+ scaling=self.scaling,
704
+ sliding_window=self.sliding_window,
705
+ position_ids=position_ids, # pass positions for FA2
706
+ **kwargs,
707
+ )
708
+
709
+ attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
710
+ attn_output = self.o_proj(attn_output)
711
+ return attn_output, attn_weights
712
+
713
+
714
+ class Qwen2_5_VLDecoderLayer(GradientCheckpointingLayer):
715
+ def __init__(self, config: Qwen2_5_VLTextConfig, layer_idx: int):
716
+ super().__init__()
717
+ self.hidden_size = config.hidden_size
718
+
719
+ if config.use_sliding_window and config._attn_implementation != "flash_attention_2":
720
+ logger.warning_once(
721
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
722
+ "unexpected results may be encountered."
723
+ )
724
+ self.self_attn = Qwen2_5_VLAttention(config, layer_idx)
725
+
726
+ self.mlp = Qwen2MLP(config)
727
+ self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
728
+ self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
729
+ self.attention_type = config.layer_types[layer_idx]
730
+
731
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
732
+ def forward(
733
+ self,
734
+ hidden_states: torch.Tensor,
735
+ attention_mask: Optional[torch.Tensor] = None,
736
+ position_ids: Optional[torch.LongTensor] = None,
737
+ past_key_values: Optional[Cache] = None,
738
+ output_attentions: Optional[bool] = False,
739
+ use_cache: Optional[bool] = False,
740
+ cache_position: Optional[torch.LongTensor] = None,
741
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
742
+ **kwargs: Unpack[FlashAttentionKwargs],
743
+ ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
744
+ """
745
+ Args:
746
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
747
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
748
+ `(batch, sequence_length)` where padding elements are indicated by 0.
749
+ output_attentions (`bool`, *optional*):
750
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
751
+ returned tensors for more detail.
752
+ use_cache (`bool`, *optional*):
753
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
754
+ (see `past_key_values`).
755
+ past_key_values (`Cache`, *optional*): cached past key and value projection states
756
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
757
+ Indices depicting the position of the input sequence tokens in the sequence.
758
+ position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
759
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
760
+ with `head_dim` being the embedding dimension of each attention head.
761
+ kwargs (`dict`, *optional*):
762
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
763
+ into the model
764
+ """
765
+
766
+ residual = hidden_states
767
+
768
+ hidden_states = self.input_layernorm(hidden_states)
769
+
770
+ # Self Attention
771
+ hidden_states, self_attn_weights = self.self_attn(
772
+ hidden_states=hidden_states,
773
+ attention_mask=attention_mask,
774
+ position_ids=position_ids,
775
+ past_key_values=past_key_values,
776
+ output_attentions=output_attentions,
777
+ use_cache=use_cache,
778
+ cache_position=cache_position,
779
+ position_embeddings=position_embeddings,
780
+ **kwargs,
781
+ )
782
+ hidden_states = residual + hidden_states
783
+
784
+ # Fully Connected
785
+ residual = hidden_states
786
+ hidden_states = self.post_attention_layernorm(hidden_states)
787
+ hidden_states = self.mlp(hidden_states)
788
+ hidden_states = residual + hidden_states
789
+
790
+ outputs = (hidden_states,)
791
+
792
+ if output_attentions:
793
+ outputs += (self_attn_weights,)
794
+
795
+ return outputs
796
+
797
+
798
+ @auto_docstring
799
+ class Qwen2_5_VLTextModel(Qwen2_5_VLPreTrainedModel):
800
+ config: Qwen2_5_VLTextConfig
801
+
802
+ def __init__(self, config: Qwen2_5_VLTextConfig):
803
+ super().__init__(config)
804
+ self.padding_idx = config.pad_token_id
805
+ self.vocab_size = config.vocab_size
806
+
807
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
808
+ self.layers = nn.ModuleList(
809
+ [Qwen2_5_VLDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
810
+ )
811
+ self._attn_implementation = config._attn_implementation
812
+ self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
813
+ self.rotary_emb = Qwen2_5_VLRotaryEmbedding(config=config)
814
+ self.has_sliding_layers = "sliding_attention" in self.config.layer_types
815
+
816
+ self.gradient_checkpointing = False
817
+ # Initialize weights and apply final processing
818
+ self.post_init()
819
+
820
+ @auto_docstring
821
+ def forward(
822
+ self,
823
+ input_ids: Optional[torch.LongTensor] = None,
824
+ attention_mask: Optional[torch.Tensor] = None,
825
+ position_ids: Optional[torch.LongTensor] = None,
826
+ past_key_values: Optional[Cache] = None,
827
+ inputs_embeds: Optional[torch.FloatTensor] = None,
828
+ use_cache: Optional[bool] = None,
829
+ output_attentions: Optional[bool] = None,
830
+ output_hidden_states: Optional[bool] = None,
831
+ return_dict: Optional[bool] = None,
832
+ cache_position: Optional[torch.LongTensor] = None,
833
+ **kwargs: Unpack[FlashAttentionKwargs],
834
+ ) -> Union[tuple, BaseModelOutputWithPast]:
835
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
836
+ output_hidden_states = (
837
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
838
+ )
839
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
840
+
841
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
842
+
843
+ if (input_ids is None) ^ (inputs_embeds is not None):
844
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
845
+
846
+ if self.gradient_checkpointing and self.training:
847
+ if use_cache:
848
+ logger.warning_once(
849
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
850
+ )
851
+ use_cache = False
852
+
853
+ # torch.jit.trace() doesn't support cache objects in the output
854
+ if use_cache and past_key_values is None and not torch.jit.is_tracing():
855
+ past_key_values = DynamicCache(config=self.config)
856
+
857
+ if inputs_embeds is None:
858
+ inputs_embeds = self.embed_tokens(input_ids)
859
+
860
+ if cache_position is None:
861
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
862
+ cache_position = torch.arange(
863
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
864
+ )
865
+
866
+ # the hard coded `3` is for temporal, height and width.
867
+ if position_ids is None:
868
+ position_ids = cache_position.view(1, 1, -1).expand(3, inputs_embeds.shape[0], -1)
869
+ elif position_ids.ndim == 2:
870
+ position_ids = position_ids[None, ...].expand(3, position_ids.shape[0], -1)
871
+
872
+ # NOTE: we need to pass text position ids for packing. Qwen2-VL uses 3D positions
873
+ # where each dim indicates visual spatial positions for temporal/height/width grids.
874
+ # There are two scenarios when FA2-like packed masking might be activated.
875
+ # 1. User specifically passed packed `position_ids` and no attention mask.
876
+ # In this case we expect the useer to create correct position ids for all 3 grids
877
+ # and prepend text-only position ids to it. The final tensor will be [4, bs, seq-len]
878
+ # 2. User runs forward with no attention mask and no position ids. In this case, position ids
879
+ # are prepared by the model (`get_rope_index`) as `[4, bs, seq-len]` tensor. Text-only positions are
880
+ # prepended by us when creating positions so that the mask is constructed correctly. NOTE: failing to pass
881
+ # text-only positions will cause incorrect mask construction, do not change `prepare_input_for_generation`
882
+ if position_ids.ndim == 3 and position_ids.shape[0] == 4:
883
+ text_position_ids = position_ids[0]
884
+ position_ids = position_ids[1:]
885
+ else:
886
+ # If inputs are not packed (usual 3D positions), do not prepare mask from position_ids
887
+ text_position_ids = None
888
+
889
+ # It may already have been prepared by e.g. `generate`
890
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
891
+ # Prepare mask arguments
892
+ mask_kwargs = {
893
+ "config": self.config,
894
+ "input_embeds": inputs_embeds,
895
+ "attention_mask": attention_mask,
896
+ "cache_position": cache_position,
897
+ "past_key_values": past_key_values,
898
+ "position_ids": text_position_ids,
899
+ }
900
+ # Create the masks
901
+ causal_mask_mapping = {
902
+ "full_attention": create_causal_mask(**mask_kwargs),
903
+ }
904
+ # The sliding window alternating layers are not always activated depending on the config
905
+ if self.has_sliding_layers:
906
+ causal_mask_mapping["sliding_attention"] = create_sliding_window_causal_mask(**mask_kwargs)
907
+
908
+ hidden_states = inputs_embeds
909
+
910
+ # create position embeddings to be shared across the decoder layers
911
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
912
+
913
+ # decoder layers
914
+ all_hidden_states = () if output_hidden_states else None
915
+ all_self_attns = () if output_attentions else None
916
+
917
+ for decoder_layer in self.layers:
918
+ if output_hidden_states:
919
+ all_hidden_states += (hidden_states,)
920
+
921
+ layer_outputs = decoder_layer(
922
+ hidden_states,
923
+ attention_mask=causal_mask_mapping[decoder_layer.attention_type],
924
+ position_ids=text_position_ids,
925
+ past_key_values=past_key_values,
926
+ output_attentions=output_attentions,
927
+ use_cache=use_cache,
928
+ cache_position=cache_position,
929
+ position_embeddings=position_embeddings,
930
+ **kwargs,
931
+ )
932
+
933
+ hidden_states = layer_outputs[0]
934
+
935
+ if output_attentions:
936
+ all_self_attns += (layer_outputs[1],)
937
+
938
+ hidden_states = self.norm(hidden_states)
939
+
940
+ # add hidden states from the last decoder layer
941
+ if output_hidden_states:
942
+ all_hidden_states += (hidden_states,)
943
+
944
+ if not return_dict:
945
+ return tuple(
946
+ v for v in [hidden_states, past_key_values, all_hidden_states, all_self_attns] if v is not None
947
+ )
948
+ return BaseModelOutputWithPast(
949
+ last_hidden_state=hidden_states,
950
+ past_key_values=past_key_values,
951
+ hidden_states=all_hidden_states,
952
+ attentions=all_self_attns,
953
+ )
954
+
955
+
956
+ @auto_docstring
957
+ class Qwen2_5_VLModel(Qwen2_5_VLPreTrainedModel):
958
+ base_model_prefix = ""
959
+ _checkpoint_conversion_mapping = {"^model": "language_model"}
960
+ # Reference: fix gemma3 grad acc #37208
961
+ accepts_loss_kwargs = False
962
+ config: Qwen2_5_VLConfig
963
+ _no_split_modules = ["Qwen2_5_VLDecoderLayer", "Qwen2_5_VLVisionBlock"]
964
+
965
+ def __init__(self, config):
966
+ super().__init__(config)
967
+ self.visual = Qwen2_5_VisionTransformerPretrainedModel._from_config(config.vision_config)
968
+ self.language_model = Qwen2_5_VLTextModel._from_config(config.text_config)
969
+ self.rope_deltas = None # cache rope_deltas here
970
+
971
+ # Initialize weights and apply final processing
972
+ self.post_init()
973
+
974
+ def get_input_embeddings(self):
975
+ return self.language_model.get_input_embeddings()
976
+
977
+ def set_input_embeddings(self, value):
978
+ self.language_model.set_input_embeddings(value)
979
+
980
+ def set_decoder(self, decoder):
981
+ self.language_model = decoder
982
+
983
+ def get_decoder(self):
984
+ return self.language_model
985
+
986
+ def get_rope_index(
987
+ self,
988
+ input_ids: Optional[torch.LongTensor] = None,
989
+ image_grid_thw: Optional[torch.LongTensor] = None,
990
+ video_grid_thw: Optional[torch.LongTensor] = None,
991
+ second_per_grid_ts: Optional[torch.Tensor] = None,
992
+ attention_mask: Optional[torch.Tensor] = None,
993
+ ) -> tuple[torch.Tensor, torch.Tensor]:
994
+ """
995
+ Calculate the 3D rope index based on image and video's temporal, height and width in LLM.
996
+
997
+ Explanation:
998
+ Each embedding sequence contains vision embedding and text embedding or just contains text embedding.
999
+
1000
+ For pure text embedding sequence, the rotary position embedding has no difference with modern LLMs.
1001
+ Examples:
1002
+ input_ids: [T T T T T], here T is for text.
1003
+ temporal position_ids: [0, 1, 2, 3, 4]
1004
+ height position_ids: [0, 1, 2, 3, 4]
1005
+ width position_ids: [0, 1, 2, 3, 4]
1006
+
1007
+ For vision and text embedding sequence, we calculate 3D rotary position embedding for vision part
1008
+ and 1D rotary position embedding for text part.
1009
+ Examples:
1010
+ Temporal (Time): 3 patches, representing different segments of the video in time.
1011
+ Height: 2 patches, dividing each frame vertically.
1012
+ Width: 2 patches, dividing each frame horizontally.
1013
+ We also have some important parameters:
1014
+ fps (Frames Per Second): The video's frame rate, set to 1. This means one frame is processed each second.
1015
+ tokens_per_second: This is a crucial parameter. It dictates how many "time-steps" or "temporal tokens" are conceptually packed into a one-second interval of the video. In this case, we have 25 tokens per second. So each second of the video will be represented with 25 separate time points. It essentially defines the temporal granularity.
1016
+ temporal_patch_size: The number of frames that compose one temporal patch. Here, it's 2 frames.
1017
+ interval: The step size for the temporal position IDs, calculated as tokens_per_second * temporal_patch_size / fps. In this case, 25 * 2 / 1 = 50. This means that each temporal patch will be have a difference of 50 in the temporal position IDs.
1018
+ input_ids: [V V V V V V V V V V V V T T T T T], here V is for vision.
1019
+ vision temporal position_ids: [0, 0, 0, 0, 50, 50, 50, 50, 100, 100, 100, 100]
1020
+ vision height position_ids: [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1]
1021
+ vision width position_ids: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
1022
+ text temporal position_ids: [101, 102, 103, 104, 105]
1023
+ text height position_ids: [101, 102, 103, 104, 105]
1024
+ text width position_ids: [101, 102, 103, 104, 105]
1025
+ Here we calculate the text start position_ids as the max vision position_ids plus 1.
1026
+
1027
+ Args:
1028
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1029
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1030
+ it.
1031
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
1032
+ The temporal, height and width of feature shape of each image in LLM.
1033
+ video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
1034
+ The temporal, height and width of feature shape of each video in LLM.
1035
+ second_per_grid_ts (`torch.Tensor` of shape `(num_videos)`, *optional*):
1036
+ The time interval (in seconds) for each grid along the temporal dimension in the 3D position IDs.
1037
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1038
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1039
+
1040
+ - 1 for tokens that are **not masked**,
1041
+ - 0 for tokens that are **masked**.
1042
+
1043
+ Returns:
1044
+ position_ids (`torch.LongTensor` of shape `(3, batch_size, sequence_length)`)
1045
+ mrope_position_deltas (`torch.Tensor` of shape `(batch_size)`)
1046
+ """
1047
+ spatial_merge_size = self.config.vision_config.spatial_merge_size
1048
+ image_token_id = self.config.image_token_id
1049
+ video_token_id = self.config.video_token_id
1050
+ vision_start_token_id = self.config.vision_start_token_id
1051
+ mrope_position_deltas = []
1052
+ if input_ids is not None and (image_grid_thw is not None or video_grid_thw is not None):
1053
+ total_input_ids = input_ids
1054
+ if attention_mask is not None:
1055
+ attention_mask = attention_mask == 1
1056
+ position_ids = torch.ones(
1057
+ 3,
1058
+ input_ids.shape[0],
1059
+ input_ids.shape[1],
1060
+ dtype=input_ids.dtype,
1061
+ device=input_ids.device,
1062
+ )
1063
+ image_index, video_index = 0, 0
1064
+ for i, input_ids in enumerate(total_input_ids):
1065
+ if attention_mask is not None:
1066
+ input_ids = input_ids[attention_mask[i]]
1067
+ image_nums, video_nums = 0, 0
1068
+ vision_start_indices = torch.argwhere(input_ids == vision_start_token_id).squeeze(1)
1069
+ vision_tokens = input_ids[vision_start_indices + 1]
1070
+ image_nums = (vision_tokens == image_token_id).sum()
1071
+ video_nums = (vision_tokens == video_token_id).sum()
1072
+ input_tokens = input_ids.tolist()
1073
+ llm_pos_ids_list: list = []
1074
+ st = 0
1075
+ remain_images, remain_videos = image_nums, video_nums
1076
+ for _ in range(image_nums + video_nums):
1077
+ if image_token_id in input_tokens and remain_images > 0:
1078
+ ed_image = input_tokens.index(image_token_id, st)
1079
+ else:
1080
+ ed_image = len(input_tokens) + 1
1081
+ if video_token_id in input_tokens and remain_videos > 0:
1082
+ ed_video = input_tokens.index(video_token_id, st)
1083
+ else:
1084
+ ed_video = len(input_tokens) + 1
1085
+ if ed_image < ed_video:
1086
+ t, h, w = (
1087
+ image_grid_thw[image_index][0],
1088
+ image_grid_thw[image_index][1],
1089
+ image_grid_thw[image_index][2],
1090
+ )
1091
+ second_per_grid_t = 0
1092
+ image_index += 1
1093
+ remain_images -= 1
1094
+ ed = ed_image
1095
+
1096
+ else:
1097
+ t, h, w = (
1098
+ video_grid_thw[video_index][0],
1099
+ video_grid_thw[video_index][1],
1100
+ video_grid_thw[video_index][2],
1101
+ )
1102
+ if second_per_grid_ts is not None:
1103
+ second_per_grid_t = second_per_grid_ts[video_index]
1104
+ else:
1105
+ second_per_grid_t = 1.0
1106
+ video_index += 1
1107
+ remain_videos -= 1
1108
+ ed = ed_video
1109
+ llm_grid_t, llm_grid_h, llm_grid_w = (
1110
+ t.item(),
1111
+ h.item() // spatial_merge_size,
1112
+ w.item() // spatial_merge_size,
1113
+ )
1114
+ text_len = ed - st
1115
+
1116
+ st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0
1117
+ llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx)
1118
+
1119
+ range_tensor = torch.arange(llm_grid_t).view(-1, 1)
1120
+ expanded_range = range_tensor.expand(-1, llm_grid_h * llm_grid_w)
1121
+
1122
+ ## normalize type, send to device.
1123
+ second_per_grid_t = torch.as_tensor(
1124
+ second_per_grid_t, dtype=range_tensor.dtype, device=range_tensor.device
1125
+ )
1126
+
1127
+ time_tensor = expanded_range * second_per_grid_t * self.config.vision_config.tokens_per_second
1128
+
1129
+ time_tensor_long = time_tensor.long()
1130
+ t_index = time_tensor_long.flatten()
1131
+
1132
+ h_index = torch.arange(llm_grid_h).view(1, -1, 1).expand(llm_grid_t, -1, llm_grid_w).flatten()
1133
+ w_index = torch.arange(llm_grid_w).view(1, 1, -1).expand(llm_grid_t, llm_grid_h, -1).flatten()
1134
+ llm_pos_ids_list.append(torch.stack([t_index, h_index, w_index]) + text_len + st_idx)
1135
+ st = ed + llm_grid_t * llm_grid_h * llm_grid_w
1136
+
1137
+ if st < len(input_tokens):
1138
+ st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0
1139
+ text_len = len(input_tokens) - st
1140
+ llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx)
1141
+
1142
+ llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(3, -1)
1143
+ if attention_mask is not None:
1144
+ position_ids[..., i, attention_mask[i]] = llm_positions.to(position_ids.device)
1145
+ else:
1146
+ position_ids[..., i, :] = llm_positions.to(position_ids.device)
1147
+ mrope_position_deltas.append(llm_positions.max() + 1 - len(total_input_ids[i]))
1148
+ mrope_position_deltas = torch.tensor(mrope_position_deltas).unsqueeze(1).to(device=input_ids.device)
1149
+ return position_ids, mrope_position_deltas
1150
+ else:
1151
+ if attention_mask is not None:
1152
+ position_ids = attention_mask.long().cumsum(-1) - 1
1153
+ position_ids.masked_fill_(attention_mask == 0, 1)
1154
+ position_ids = position_ids.unsqueeze(0).expand(3, -1, -1).to(attention_mask.device)
1155
+ max_position_ids = position_ids.max(0, keepdim=False)[0].max(-1, keepdim=True)[0]
1156
+ mrope_position_deltas = max_position_ids + 1 - attention_mask.shape[-1]
1157
+ else:
1158
+ position_ids = (
1159
+ torch.arange(input_ids.shape[1], device=input_ids.device)
1160
+ .view(1, 1, -1)
1161
+ .expand(3, input_ids.shape[0], -1)
1162
+ )
1163
+ mrope_position_deltas = torch.zeros(
1164
+ [input_ids.shape[0], 1],
1165
+ device=input_ids.device,
1166
+ dtype=input_ids.dtype,
1167
+ )
1168
+
1169
+ return position_ids, mrope_position_deltas
1170
+
1171
+ def get_video_features(
1172
+ self, pixel_values_videos: torch.FloatTensor, video_grid_thw: Optional[torch.LongTensor] = None
1173
+ ):
1174
+ """
1175
+ Encodes videos into continuous embeddings that can be forwarded to the language model.
1176
+
1177
+ Args:
1178
+ pixel_values_videos (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
1179
+ The tensors corresponding to the input videos.
1180
+ video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
1181
+ The temporal, height and width of feature shape of each video in LLM.
1182
+ """
1183
+ pixel_values_videos = pixel_values_videos.type(self.visual.dtype)
1184
+ video_embeds = self.visual(pixel_values_videos, grid_thw=video_grid_thw)
1185
+ split_sizes = (video_grid_thw.prod(-1) // self.visual.spatial_merge_size**2).tolist()
1186
+ video_embeds = torch.split(video_embeds, split_sizes)
1187
+ return video_embeds
1188
+
1189
+ def get_image_features(self, pixel_values: torch.FloatTensor, image_grid_thw: Optional[torch.LongTensor] = None):
1190
+ """
1191
+ Encodes images into continuous embeddings that can be forwarded to the language model.
1192
+
1193
+ Args:
1194
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
1195
+ The tensors corresponding to the input images.
1196
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
1197
+ The temporal, height and width of feature shape of each image in LLM.
1198
+ """
1199
+ pixel_values = pixel_values.type(self.visual.dtype)
1200
+ image_embeds = self.visual(pixel_values, grid_thw=image_grid_thw)
1201
+ split_sizes = (image_grid_thw.prod(-1) // self.visual.spatial_merge_size**2).tolist()
1202
+ image_embeds = torch.split(image_embeds, split_sizes)
1203
+ return image_embeds
1204
+
1205
+ def get_placeholder_mask(
1206
+ self,
1207
+ input_ids: torch.LongTensor,
1208
+ inputs_embeds: torch.FloatTensor,
1209
+ image_features: Optional[torch.FloatTensor] = None,
1210
+ video_features: Optional[torch.FloatTensor] = None,
1211
+ ):
1212
+ """
1213
+ Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
1214
+ equal to the length of multimodal features. If the lengths are different, an error is raised.
1215
+ """
1216
+ if input_ids is None:
1217
+ special_image_mask = inputs_embeds == self.get_input_embeddings()(
1218
+ torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
1219
+ )
1220
+ special_image_mask = special_image_mask.all(-1)
1221
+ special_video_mask = inputs_embeds == self.get_input_embeddings()(
1222
+ torch.tensor(self.config.video_token_id, dtype=torch.long, device=inputs_embeds.device)
1223
+ )
1224
+ special_video_mask = special_video_mask.all(-1)
1225
+ else:
1226
+ special_image_mask = input_ids == self.config.image_token_id
1227
+ special_video_mask = input_ids == self.config.video_token_id
1228
+
1229
+ n_image_tokens = special_image_mask.sum()
1230
+ special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
1231
+ if image_features is not None and inputs_embeds[special_image_mask].numel() != image_features.numel():
1232
+ raise ValueError(
1233
+ f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {image_features.shape[0]}"
1234
+ )
1235
+
1236
+ n_video_tokens = special_video_mask.sum()
1237
+ special_video_mask = special_video_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
1238
+ if video_features is not None and inputs_embeds[special_video_mask].numel() != video_features.numel():
1239
+ raise ValueError(
1240
+ f"Videos features and video tokens do not match: tokens: {n_video_tokens}, features {video_features.shape[0]}"
1241
+ )
1242
+
1243
+ return special_image_mask, special_video_mask
1244
+
1245
+ @auto_docstring
1246
+ def forward(
1247
+ self,
1248
+ input_ids: Optional[torch.LongTensor] = None,
1249
+ attention_mask: Optional[torch.Tensor] = None,
1250
+ position_ids: Optional[torch.LongTensor] = None,
1251
+ past_key_values: Optional[Cache] = None,
1252
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1253
+ use_cache: Optional[bool] = None,
1254
+ output_attentions: Optional[bool] = None,
1255
+ output_hidden_states: Optional[bool] = None,
1256
+ return_dict: Optional[bool] = None,
1257
+ pixel_values: Optional[torch.Tensor] = None,
1258
+ pixel_values_videos: Optional[torch.FloatTensor] = None,
1259
+ image_grid_thw: Optional[torch.LongTensor] = None,
1260
+ video_grid_thw: Optional[torch.LongTensor] = None,
1261
+ rope_deltas: Optional[torch.LongTensor] = None,
1262
+ cache_position: Optional[torch.LongTensor] = None,
1263
+ second_per_grid_ts: Optional[torch.Tensor] = None,
1264
+ **kwargs: Unpack[TransformersKwargs],
1265
+ ) -> Union[tuple, Qwen2_5_VLModelOutputWithPast]:
1266
+ r"""
1267
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
1268
+ The temporal, height and width of feature shape of each image in LLM.
1269
+ video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
1270
+ The temporal, height and width of feature shape of each video in LLM.
1271
+ rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
1272
+ The rope index difference between sequence length and multimodal rope.
1273
+ second_per_grid_ts (`torch.Tensor` of shape `(num_videos)`, *optional*):
1274
+ The time interval (in seconds) for each grid along the temporal dimension in the 3D position IDs.
1275
+ """
1276
+
1277
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1278
+ output_hidden_states = (
1279
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1280
+ )
1281
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1282
+
1283
+ if inputs_embeds is None:
1284
+ inputs_embeds = self.get_input_embeddings()(input_ids)
1285
+
1286
+ if pixel_values is not None:
1287
+ image_embeds = self.get_image_features(pixel_values, image_grid_thw)
1288
+ image_embeds = torch.cat(image_embeds, dim=0).to(inputs_embeds.device, inputs_embeds.dtype)
1289
+ image_mask, _ = self.get_placeholder_mask(
1290
+ input_ids, inputs_embeds=inputs_embeds, image_features=image_embeds
1291
+ )
1292
+ inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds)
1293
+
1294
+ if pixel_values_videos is not None:
1295
+ video_embeds = self.get_video_features(pixel_values_videos, video_grid_thw)
1296
+ video_embeds = torch.cat(video_embeds, dim=0).to(inputs_embeds.device, inputs_embeds.dtype)
1297
+ _, video_mask = self.get_placeholder_mask(
1298
+ input_ids, inputs_embeds=inputs_embeds, video_features=video_embeds
1299
+ )
1300
+ inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds)
1301
+
1302
+ if position_ids is None:
1303
+ # Calculate RoPE index once per generation in the pre-fill stage only.
1304
+ # When compiling, we can't check tensor values thus we check only input length
1305
+ # It is safe to assume that `length!=1` means we're in pre-fill because compiled
1306
+ # models currently cannot do asssisted decoding
1307
+ prefill_compiled_stage = is_torchdynamo_compiling() and (
1308
+ (input_ids is not None and input_ids.shape[1] != 1)
1309
+ or (inputs_embeds is not None and inputs_embeds.shape[1] != 1)
1310
+ )
1311
+ prefill_noncompiled_stage = not is_torchdynamo_compiling() and (
1312
+ (cache_position is not None and cache_position[0] == 0)
1313
+ or (past_key_values is None or past_key_values.get_seq_length() == 0)
1314
+ )
1315
+ if (prefill_compiled_stage or prefill_noncompiled_stage) or self.rope_deltas is None:
1316
+ position_ids, rope_deltas = self.get_rope_index(
1317
+ input_ids,
1318
+ image_grid_thw,
1319
+ video_grid_thw,
1320
+ second_per_grid_ts=second_per_grid_ts,
1321
+ attention_mask=attention_mask,
1322
+ )
1323
+ self.rope_deltas = rope_deltas
1324
+ else:
1325
+ batch_size, seq_length, _ = inputs_embeds.shape
1326
+ position_ids = torch.arange(seq_length, device=inputs_embeds.device)
1327
+ position_ids = position_ids.view(1, 1, -1).expand(3, batch_size, -1)
1328
+ if cache_position is not None:
1329
+ delta = (cache_position[0] + self.rope_deltas).to(inputs_embeds.device)
1330
+ else:
1331
+ delta = torch.zeros((batch_size, seq_length), device=inputs_embeds.device)
1332
+ delta = delta.repeat_interleave(batch_size // delta.shape[0], dim=1)
1333
+ position_ids = position_ids + delta.to(position_ids.device)
1334
+
1335
+ outputs = self.language_model(
1336
+ input_ids=None,
1337
+ position_ids=position_ids,
1338
+ attention_mask=attention_mask,
1339
+ past_key_values=past_key_values,
1340
+ inputs_embeds=inputs_embeds,
1341
+ use_cache=use_cache,
1342
+ output_attentions=output_attentions,
1343
+ output_hidden_states=output_hidden_states,
1344
+ return_dict=True,
1345
+ cache_position=cache_position,
1346
+ **kwargs,
1347
+ )
1348
+
1349
+ output = Qwen2_5_VLModelOutputWithPast(
1350
+ last_hidden_state=outputs.last_hidden_state,
1351
+ past_key_values=outputs.past_key_values,
1352
+ hidden_states=outputs.hidden_states,
1353
+ attentions=outputs.attentions,
1354
+ rope_deltas=self.rope_deltas,
1355
+ )
1356
+ return output if return_dict else output.to_tuple()
1357
+
1358
+
1359
+ @dataclass
1360
+ @auto_docstring(
1361
+ custom_intro="""
1362
+ Base class for Qwen2_5_VL causal language model (or autoregressive) outputs.
1363
+ """
1364
+ )
1365
+ class Qwen2_5_VLCausalLMOutputWithPast(ModelOutput):
1366
+ r"""
1367
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
1368
+ Language modeling loss (for next-token prediction).
1369
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
1370
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
1371
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
1372
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
1373
+
1374
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
1375
+ `past_key_values` input) to speed up sequential decoding.
1376
+ rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
1377
+ The rope index difference between sequence length and multimodal rope.
1378
+ """
1379
+
1380
+ loss: Optional[torch.FloatTensor] = None
1381
+ logits: Optional[torch.FloatTensor] = None
1382
+ past_key_values: Optional[Cache] = None
1383
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
1384
+ attentions: Optional[tuple[torch.FloatTensor]] = None
1385
+ rope_deltas: Optional[torch.LongTensor] = None
1386
+
1387
+
1388
+ class Qwen2_5_VLForConditionalGeneration(Qwen2_5_VLPreTrainedModel, GenerationMixin):
1389
+ _checkpoint_conversion_mapping = {
1390
+ "^visual": "model.visual",
1391
+ r"^model(?!\.(language_model|visual))": "model.language_model",
1392
+ }
1393
+ _tied_weights_keys = ["lm_head.weight"]
1394
+ # Reference: fix gemma3 grad acc #37208
1395
+ accepts_loss_kwargs = False
1396
+
1397
+ def __init__(self, config):
1398
+ super().__init__(config)
1399
+ self.model = Qwen2_5_VLModel(config)
1400
+ self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
1401
+
1402
+ self.post_init()
1403
+
1404
+ def get_input_embeddings(self):
1405
+ return self.model.get_input_embeddings()
1406
+
1407
+ def set_input_embeddings(self, value):
1408
+ self.model.set_input_embeddings(value)
1409
+
1410
+ def set_decoder(self, decoder):
1411
+ self.model.set_decoder(decoder)
1412
+
1413
+ def get_decoder(self):
1414
+ return self.model.get_decoder()
1415
+
1416
+ def get_video_features(
1417
+ self, pixel_values_videos: torch.FloatTensor, video_grid_thw: Optional[torch.LongTensor] = None
1418
+ ):
1419
+ return self.model.get_video_features(pixel_values_videos, video_grid_thw)
1420
+
1421
+ def get_image_features(self, pixel_values: torch.FloatTensor, image_grid_thw: Optional[torch.LongTensor] = None):
1422
+ return self.model.get_image_features(pixel_values, image_grid_thw)
1423
+
1424
+ # Make modules available through conditional class for BC
1425
+ @property
1426
+ def language_model(self):
1427
+ return self.model.language_model
1428
+
1429
+ @property
1430
+ def visual(self):
1431
+ return self.model.visual
1432
+
1433
+ @can_return_tuple
1434
+ @auto_docstring
1435
+ def forward(
1436
+ self,
1437
+ input_ids: Optional[torch.LongTensor] = None,
1438
+ attention_mask: Optional[torch.Tensor] = None,
1439
+ position_ids: Optional[torch.LongTensor] = None,
1440
+ past_key_values: Optional[Cache] = None,
1441
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1442
+ labels: Optional[torch.LongTensor] = None,
1443
+ use_cache: Optional[bool] = None,
1444
+ output_attentions: Optional[bool] = None,
1445
+ output_hidden_states: Optional[bool] = None,
1446
+ pixel_values: Optional[torch.Tensor] = None,
1447
+ pixel_values_videos: Optional[torch.FloatTensor] = None,
1448
+ image_grid_thw: Optional[torch.LongTensor] = None,
1449
+ video_grid_thw: Optional[torch.LongTensor] = None,
1450
+ rope_deltas: Optional[torch.LongTensor] = None,
1451
+ cache_position: Optional[torch.LongTensor] = None,
1452
+ second_per_grid_ts: Optional[torch.Tensor] = None,
1453
+ logits_to_keep: Union[int, torch.Tensor] = 0,
1454
+ **kwargs: Unpack[TransformersKwargs],
1455
+ ) -> Union[tuple, Qwen2_5_VLCausalLMOutputWithPast]:
1456
+ r"""
1457
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1458
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1459
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1460
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1461
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
1462
+ The temporal, height and width of feature shape of each image in LLM.
1463
+ video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
1464
+ The temporal, height and width of feature shape of each video in LLM.
1465
+ rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
1466
+ The rope index difference between sequence length and multimodal rope.
1467
+ second_per_grid_ts (`torch.Tensor` of shape `(num_videos)`, *optional*):
1468
+ The time interval (in seconds) for each grid along the temporal dimension in the 3D position IDs.
1469
+
1470
+ Example:
1471
+
1472
+ ```python
1473
+ >>> from PIL import Image
1474
+ >>> import requests
1475
+ >>> from transformers import AutoProcessor, Qwen2_5_VLForConditionalGeneration
1476
+
1477
+ >>> model = Qwen2_5_VLForConditionalGeneration.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct")
1478
+ >>> processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct")
1479
+
1480
+ >>> messages = [
1481
+ {
1482
+ "role": "user",
1483
+ "content": [
1484
+ {"type": "image"},
1485
+ {"type": "text", "text": "What is shown in this image?"},
1486
+ ],
1487
+ },
1488
+ ]
1489
+ >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
1490
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1491
+
1492
+ >>> text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
1493
+ >>> inputs = processor(text=[text], images=[image], vision_infos=[vision_infos])
1494
+
1495
+ >>> # Generate
1496
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1497
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1498
+ "The image shows a street scene with a red stop sign in the foreground. In the background, there is a large red gate with Chinese characters ..."
1499
+ ```"""
1500
+
1501
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1502
+ output_hidden_states = (
1503
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1504
+ )
1505
+
1506
+ outputs = self.model(
1507
+ input_ids=input_ids,
1508
+ pixel_values=pixel_values,
1509
+ pixel_values_videos=pixel_values_videos,
1510
+ image_grid_thw=image_grid_thw,
1511
+ video_grid_thw=video_grid_thw,
1512
+ second_per_grid_ts=second_per_grid_ts,
1513
+ position_ids=position_ids,
1514
+ attention_mask=attention_mask,
1515
+ past_key_values=past_key_values,
1516
+ inputs_embeds=inputs_embeds,
1517
+ use_cache=use_cache,
1518
+ output_attentions=output_attentions,
1519
+ output_hidden_states=output_hidden_states,
1520
+ return_dict=True,
1521
+ cache_position=cache_position,
1522
+ **kwargs,
1523
+ )
1524
+
1525
+ hidden_states = outputs[0]
1526
+
1527
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1528
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1529
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
1530
+
1531
+ loss = None
1532
+ if labels is not None:
1533
+ loss = self.loss_function(
1534
+ logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
1535
+ )
1536
+
1537
+ return Qwen2_5_VLCausalLMOutputWithPast(
1538
+ loss=loss,
1539
+ logits=logits,
1540
+ past_key_values=outputs.past_key_values,
1541
+ hidden_states=outputs.hidden_states,
1542
+ attentions=outputs.attentions,
1543
+ rope_deltas=outputs.rope_deltas,
1544
+ )
1545
+
1546
+ def prepare_inputs_for_generation(
1547
+ self,
1548
+ input_ids,
1549
+ past_key_values=None,
1550
+ attention_mask=None,
1551
+ inputs_embeds=None,
1552
+ cache_position=None,
1553
+ position_ids=None,
1554
+ use_cache=True,
1555
+ pixel_values=None,
1556
+ pixel_values_videos=None,
1557
+ image_grid_thw=None,
1558
+ video_grid_thw=None,
1559
+ second_per_grid_ts=None,
1560
+ **kwargs,
1561
+ ):
1562
+ # Overwritten -- in specific circumstances we don't want to forward image inputs to the model
1563
+
1564
+ model_inputs = super().prepare_inputs_for_generation(
1565
+ input_ids,
1566
+ past_key_values=past_key_values,
1567
+ attention_mask=attention_mask,
1568
+ inputs_embeds=inputs_embeds,
1569
+ cache_position=cache_position,
1570
+ position_ids=position_ids,
1571
+ pixel_values=pixel_values,
1572
+ pixel_values_videos=pixel_values_videos,
1573
+ image_grid_thw=image_grid_thw,
1574
+ video_grid_thw=video_grid_thw,
1575
+ second_per_grid_ts=second_per_grid_ts,
1576
+ use_cache=use_cache,
1577
+ **kwargs,
1578
+ )
1579
+
1580
+ # Qwen2-5-VL position_ids are prepared with rope_deltas
1581
+ if position_ids is None:
1582
+ # Calculate RoPE index once per generation in the pre-fill stage only.
1583
+ # When compiling, we can't check tensor values thus we check only input length
1584
+ # It is safe to assume that `length!=1` means we're in pre-fill because compiled
1585
+ # models currently cannot do assisted decoding
1586
+ if cache_position[0] == 0 or self.model.rope_deltas is None:
1587
+ vision_positions, rope_deltas = self.model.get_rope_index(
1588
+ model_inputs.get("input_ids", None),
1589
+ image_grid_thw=image_grid_thw,
1590
+ video_grid_thw=video_grid_thw,
1591
+ second_per_grid_ts=second_per_grid_ts,
1592
+ attention_mask=attention_mask,
1593
+ )
1594
+ self.model.rope_deltas = rope_deltas
1595
+ # then use the prev pre-calculated rope-deltas to get the correct position ids
1596
+ elif "position_ids" in model_inputs:
1597
+ batch_size, seq_length = model_inputs["position_ids"].shape
1598
+ device = model_inputs["position_ids"].device
1599
+ position_ids = torch.arange(seq_length, device=device)
1600
+ position_ids = position_ids.view(1, 1, -1).expand(3, batch_size, -1)
1601
+ delta = cache_position[0] + self.model.rope_deltas
1602
+ delta = delta.repeat_interleave(batch_size // delta.shape[0], dim=0)
1603
+ vision_positions = position_ids + delta.expand_as(position_ids)
1604
+
1605
+ # Concatenate "text + vision" positions into [4, bs, seq-len]
1606
+ text_positions = model_inputs["position_ids"][None, ...]
1607
+ model_inputs["position_ids"] = torch.cat([text_positions, vision_positions], dim=0)
1608
+
1609
+ if cache_position[0] != 0:
1610
+ model_inputs["pixel_values"] = None
1611
+ model_inputs["pixel_values_videos"] = None
1612
+
1613
+ return model_inputs
1614
+
1615
+ def _get_image_nums_and_video_nums(
1616
+ self,
1617
+ input_ids: Optional[torch.LongTensor],
1618
+ inputs_embeds: Optional[torch.Tensor] = None,
1619
+ ) -> tuple[torch.Tensor, torch.Tensor]:
1620
+ """
1621
+ Get the number of images and videos for each sample to calculate the separation length of the sample tensor.
1622
+ These parameters are not passed through the processor to avoid unpredictable impacts from interface modifications.
1623
+
1624
+ Args:
1625
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1626
+ Indices of input sequence tokens in the vocabulary.
1627
+
1628
+ Returns:
1629
+ image_nums (`torch.LongTensor` of shape `(batch_size, num_images_sample)`)
1630
+ video_nums (`torch.LongTensor` of shape `(batch_size, num_videos_sample)`)
1631
+ """
1632
+ image_token_id = self.config.image_token_id
1633
+ video_token_id = self.config.video_token_id
1634
+ vision_start_token_id = self.config.vision_start_token_id
1635
+
1636
+ if inputs_embeds is not None:
1637
+ vision_start_mask = (
1638
+ inputs_embeds
1639
+ == self.get_input_embeddings()(
1640
+ torch.tensor(vision_start_token_id, dtype=torch.long, device=inputs_embeds.device)
1641
+ )
1642
+ )[..., 0]
1643
+ image_mask = (
1644
+ inputs_embeds
1645
+ == self.get_input_embeddings()(
1646
+ torch.tensor(image_token_id, dtype=torch.long, device=inputs_embeds.device)
1647
+ )
1648
+ )[..., 0]
1649
+ video_mask = (
1650
+ inputs_embeds
1651
+ == self.get_input_embeddings()(
1652
+ torch.tensor(video_token_id, dtype=torch.long, device=inputs_embeds.device)
1653
+ )
1654
+ )[..., 0]
1655
+ else:
1656
+ vision_start_mask = input_ids == vision_start_token_id
1657
+ image_mask = input_ids == image_token_id
1658
+ video_mask = input_ids == video_token_id
1659
+
1660
+ vision_first_mask = torch.roll(vision_start_mask, shifts=1, dims=1)
1661
+ image_nums = torch.sum(vision_first_mask & image_mask, dim=1)
1662
+ video_nums = torch.sum(vision_first_mask & video_mask, dim=1)
1663
+
1664
+ return image_nums, video_nums
1665
+
1666
+ def _expand_inputs_for_generation(
1667
+ self,
1668
+ expand_size: int = 1,
1669
+ is_encoder_decoder: bool = False,
1670
+ input_ids: Optional[torch.LongTensor] = None,
1671
+ **model_kwargs,
1672
+ ) -> tuple[torch.LongTensor, dict[str, Any]]:
1673
+ # Overwritten -- Support for expanding tensors without a batch size dimension
1674
+ # e.g., pixel_values, image_grid_thw, pixel_values_videos, video_grid_thw, second_per_grid_t
1675
+ # pixel_values.shape[0] is sum(seqlen_images for samples)
1676
+ # image_grid_thw.shape[0] is sum(num_images for samples)
1677
+
1678
+ if expand_size == 1:
1679
+ return input_ids, model_kwargs
1680
+
1681
+ visual_keys = ["pixel_values", "image_grid_thw", "pixel_values_videos", "video_grid_thw", "second_per_grid_ts"]
1682
+
1683
+ def _expand_dict_for_generation_visual(dict_to_expand):
1684
+ image_grid_thw = model_kwargs.get("image_grid_thw", None)
1685
+ video_grid_thw = model_kwargs.get("video_grid_thw", None)
1686
+ image_nums, video_nums = self._get_image_nums_and_video_nums(
1687
+ input_ids, inputs_embeds=model_kwargs.get("inputs_embeds", None)
1688
+ )
1689
+
1690
+ def _repeat_interleave_samples(x, lengths, repeat_times):
1691
+ samples = torch.split(x, lengths)
1692
+ repeat_args = [repeat_times] + [1] * (x.dim() - 1)
1693
+ result = torch.cat([sample.repeat(*repeat_args) for sample in samples], dim=0)
1694
+ return result
1695
+
1696
+ for key in dict_to_expand:
1697
+ if key == "pixel_values":
1698
+ # split images into samples
1699
+ samples = torch.split(image_grid_thw, list(image_nums))
1700
+ # compute the sequence length of images for each sample
1701
+ lengths = [torch.prod(sample, dim=1).sum() for sample in samples]
1702
+ dict_to_expand[key] = _repeat_interleave_samples(
1703
+ dict_to_expand[key], lengths=lengths, repeat_times=expand_size
1704
+ )
1705
+ elif key == "image_grid_thw":
1706
+ # get the num of images for each sample
1707
+ lengths = list(image_nums)
1708
+ dict_to_expand[key] = _repeat_interleave_samples(
1709
+ dict_to_expand[key], lengths=lengths, repeat_times=expand_size
1710
+ )
1711
+ elif key == "pixel_values_videos":
1712
+ samples = torch.split(video_grid_thw, list(video_nums))
1713
+ lengths = [torch.prod(sample, dim=1).sum() for sample in samples]
1714
+ dict_to_expand[key] = _repeat_interleave_samples(
1715
+ dict_to_expand[key], lengths=lengths, repeat_times=expand_size
1716
+ )
1717
+ elif key == "video_grid_thw":
1718
+ lengths = list(video_nums)
1719
+ dict_to_expand[key] = _repeat_interleave_samples(
1720
+ dict_to_expand[key], lengths=lengths, repeat_times=expand_size
1721
+ )
1722
+ elif key == "second_per_grid_ts":
1723
+ dict_to_expand[key] = _repeat_interleave_samples(
1724
+ dict_to_expand[key], lengths=list(video_nums), repeat_times=expand_size
1725
+ )
1726
+ return dict_to_expand
1727
+
1728
+ def _expand_dict_for_generation(dict_to_expand):
1729
+ for key in dict_to_expand:
1730
+ if (
1731
+ key != "cache_position"
1732
+ and dict_to_expand[key] is not None
1733
+ and isinstance(dict_to_expand[key], torch.Tensor)
1734
+ and key not in visual_keys
1735
+ ):
1736
+ dict_to_expand[key] = dict_to_expand[key].repeat_interleave(expand_size, dim=0)
1737
+ return dict_to_expand
1738
+
1739
+ model_kwargs = _expand_dict_for_generation_visual(model_kwargs)
1740
+
1741
+ if input_ids is not None:
1742
+ input_ids = input_ids.repeat_interleave(expand_size, dim=0)
1743
+
1744
+ model_kwargs = _expand_dict_for_generation(model_kwargs)
1745
+
1746
+ if is_encoder_decoder:
1747
+ if model_kwargs.get("encoder_outputs") is None:
1748
+ raise ValueError("If `is_encoder_decoder` is True, make sure that `encoder_outputs` is defined.")
1749
+ model_kwargs["encoder_outputs"] = _expand_dict_for_generation(model_kwargs["encoder_outputs"])
1750
+
1751
+ return input_ids, model_kwargs
1752
+
1753
+
1754
+ __all__ = ["Qwen2_5_VLForConditionalGeneration", "Qwen2_5_VLModel", "Qwen2_5_VLPreTrainedModel", "Qwen2_5_VLTextModel"]
preprocessor_config.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "min_pixels": 3136,
3
+ "max_pixels": 12845056,
4
+ "patch_size": 14,
5
+ "temporal_patch_size": 2,
6
+ "merge_size": 2,
7
+ "image_mean": [
8
+ 0.48145466,
9
+ 0.4578275,
10
+ 0.40821073
11
+ ],
12
+ "image_std": [
13
+ 0.26862954,
14
+ 0.26130258,
15
+ 0.27577711
16
+ ],
17
+ "image_processor_type": "Qwen2VLImageProcessor",
18
+ "processor_class": "Qwen2_5_VLProcessor"
19
+ }
special_tokens_map.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>",
5
+ "<|object_ref_start|>",
6
+ "<|object_ref_end|>",
7
+ "<|box_start|>",
8
+ "<|box_end|>",
9
+ "<|quad_start|>",
10
+ "<|quad_end|>",
11
+ "<|vision_start|>",
12
+ "<|vision_end|>",
13
+ "<|vision_pad|>",
14
+ "<|image_pad|>",
15
+ "<|video_pad|>"
16
+ ],
17
+ "eos_token": {
18
+ "content": "<|im_end|>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ },
24
+ "pad_token": {
25
+ "content": "<|endoftext|>",
26
+ "lstrip": false,
27
+ "normalized": false,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ }
31
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9c5ae00e602b8860cbd784ba82a8aa14e8feecec692e7076590d014d7b7fdafa
3
+ size 11421896
tokenizer_config.json ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_prefix_space": false,
4
+ "added_tokens_decoder": {
5
+ "151643": {
6
+ "content": "<|endoftext|>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "151644": {
14
+ "content": "<|im_start|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "151645": {
22
+ "content": "<|im_end|>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "151646": {
30
+ "content": "<|object_ref_start|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "151647": {
38
+ "content": "<|object_ref_end|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "151648": {
46
+ "content": "<|box_start|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "151649": {
54
+ "content": "<|box_end|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "151650": {
62
+ "content": "<|quad_start|>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "151651": {
70
+ "content": "<|quad_end|>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "151652": {
78
+ "content": "<|vision_start|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "151653": {
86
+ "content": "<|vision_end|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "151654": {
94
+ "content": "<|vision_pad|>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": false,
98
+ "single_word": false,
99
+ "special": true
100
+ },
101
+ "151655": {
102
+ "content": "<|image_pad|>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": false,
106
+ "single_word": false,
107
+ "special": true
108
+ },
109
+ "151656": {
110
+ "content": "<|video_pad|>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": false,
114
+ "single_word": false,
115
+ "special": true
116
+ },
117
+ "151657": {
118
+ "content": "<tool_call>",
119
+ "lstrip": false,
120
+ "normalized": false,
121
+ "rstrip": false,
122
+ "single_word": false,
123
+ "special": false
124
+ },
125
+ "151658": {
126
+ "content": "</tool_call>",
127
+ "lstrip": false,
128
+ "normalized": false,
129
+ "rstrip": false,
130
+ "single_word": false,
131
+ "special": false
132
+ },
133
+ "151659": {
134
+ "content": "<|fim_prefix|>",
135
+ "lstrip": false,
136
+ "normalized": false,
137
+ "rstrip": false,
138
+ "single_word": false,
139
+ "special": false
140
+ },
141
+ "151660": {
142
+ "content": "<|fim_middle|>",
143
+ "lstrip": false,
144
+ "normalized": false,
145
+ "rstrip": false,
146
+ "single_word": false,
147
+ "special": false
148
+ },
149
+ "151661": {
150
+ "content": "<|fim_suffix|>",
151
+ "lstrip": false,
152
+ "normalized": false,
153
+ "rstrip": false,
154
+ "single_word": false,
155
+ "special": false
156
+ },
157
+ "151662": {
158
+ "content": "<|fim_pad|>",
159
+ "lstrip": false,
160
+ "normalized": false,
161
+ "rstrip": false,
162
+ "single_word": false,
163
+ "special": false
164
+ },
165
+ "151663": {
166
+ "content": "<|repo_name|>",
167
+ "lstrip": false,
168
+ "normalized": false,
169
+ "rstrip": false,
170
+ "single_word": false,
171
+ "special": false
172
+ },
173
+ "151664": {
174
+ "content": "<|file_sep|>",
175
+ "lstrip": false,
176
+ "normalized": false,
177
+ "rstrip": false,
178
+ "single_word": false,
179
+ "special": false
180
+ }
181
+ },
182
+ "additional_special_tokens": [
183
+ "<|im_start|>",
184
+ "<|im_end|>",
185
+ "<|object_ref_start|>",
186
+ "<|object_ref_end|>",
187
+ "<|box_start|>",
188
+ "<|box_end|>",
189
+ "<|quad_start|>",
190
+ "<|quad_end|>",
191
+ "<|vision_start|>",
192
+ "<|vision_end|>",
193
+ "<|vision_pad|>",
194
+ "<|image_pad|>",
195
+ "<|video_pad|>"
196
+ ],
197
+ "bos_token": null,
198
+ "clean_up_tokenization_spaces": false,
199
+ "eos_token": "<|im_end|>",
200
+ "errors": "replace",
201
+ "extra_special_tokens": {},
202
+ "model_max_length": 131072,
203
+ "pad_token": "<|endoftext|>",
204
+ "processor_class": "Qwen2_5_VLProcessor",
205
+ "split_special_tokens": false,
206
+ "tokenizer_class": "Qwen2Tokenizer",
207
+ "unk_token": null
208
+ }
video_preprocessor_config.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "crop_size": null,
3
+ "data_format": "channels_first",
4
+ "default_to_square": true,
5
+ "device": null,
6
+ "do_center_crop": null,
7
+ "do_convert_rgb": true,
8
+ "do_normalize": true,
9
+ "do_rescale": true,
10
+ "do_resize": true,
11
+ "do_sample_frames": false,
12
+ "fps": null,
13
+ "image_mean": [
14
+ 0.48145466,
15
+ 0.4578275,
16
+ 0.40821073
17
+ ],
18
+ "image_std": [
19
+ 0.26862954,
20
+ 0.26130258,
21
+ 0.27577711
22
+ ],
23
+ "input_data_format": null,
24
+ "max_frames": 768,
25
+ "max_pixels": 12845056,
26
+ "merge_size": 2,
27
+ "min_frames": 4,
28
+ "min_pixels": 3136,
29
+ "num_frames": null,
30
+ "pad_size": null,
31
+ "patch_size": 14,
32
+ "processor_class": "Qwen2_5_VLProcessor",
33
+ "resample": 3,
34
+ "rescale_factor": 0.00392156862745098,
35
+ "return_metadata": false,
36
+ "size": {
37
+ "longest_edge": 12845056,
38
+ "shortest_edge": 3136
39
+ },
40
+ "temporal_patch_size": 2,
41
+ "video_metadata": null,
42
+ "video_processor_type": "Qwen2VLVideoProcessor"
43
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff