EthannW commited on
Commit
01b3ec8
·
1 Parent(s): f6af82e

Add HunyuanOCR-1.5 (target at root, DFlash under dflash/, archive 1.0 under v1.0/) (#30)

Browse files

- Add HunyuanOCR-1.5 (target at root, DFlash under dflash/, archive 1.0 under v1.0/) (7f4662d542acd852b2c71b6b12937d3a541ef585)
- Remove old HunyuanOCR-1.0 shards/index from root (archived under v1.0/) (84129bb47d0b5b937da960d8c121da40d6aa10ac)

README.md CHANGED
@@ -1,236 +1,228 @@
1
  ---
2
  license: other
 
 
3
  language:
4
  - multilingual
5
- pipeline_tag: image-text-to-text
6
- library_name: transformers
7
- base_model:
8
- - tencent/HunyuanOCR
9
  tags:
10
  - ocr
11
- - hunyuan
12
- - vision-language
13
- - image-to-text
14
- - 1B
15
- - end-to-end
 
 
16
  ---
17
 
18
- <p align="center">
19
- <img src="https://github.com/Tencent-Hunyuan/HunyuanOCR/blob/main/assets/hyocr-head-img.png?raw=true" width="80%"/> <br>
20
- </p>
21
 
 
22
 
23
- <p align="center">
24
- <a href="https://hunyuan.tencent.com/chat/HunyuanDefault?modelId=HY-OCR-1.0&mid=308&from=vision-zh"><b>🎯 Demo</b></a> |
25
- <a href="https://huggingface.co/tencent/HunyuanOCR"><b>📥 Model Download</b></a> |
26
- <a href="https://arxiv.org/abs/2511.19575"><b>📄 Technical Report</b></a> |
27
- <a href="https://github.com/Tencent-Hunyuan/HunyuanOCR"><b>🌟 Github</b></a>
28
- </p>
29
 
30
- <h2>
31
- <p align="center">
32
- <a href="https://arxiv.org/abs/2511.19575">HunyuanOCR</a>
33
- </p>
34
- </h2>
35
 
 
 
 
 
 
 
 
 
36
 
37
  ## 📖 Introduction
38
- **HunyuanOCR** stands as a leading end-to-end OCR expert VLM powered by Hunyuan's native multimodal architecture. With a remarkably lightweight 1B parameter design, it has achieved multiple state-of-the-art benchmarks across the industry. The model demonstrates mastery in **complex multilingual document parsing** while excelling in practical applications including **text spotting, open-field information extraction, video subtitle extraction, and photo translation**.
39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
- ## 🚀 Quick Start with Transformers
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
- ### Installation
44
  ```bash
45
- pip install git+https://github.com/huggingface/transformers@82a06db03535c49aa987719ed0746a76093b1ec4
 
 
 
46
  ```
47
- > **Note**: We will merge it into the Transformers main branch later.
48
 
49
- ### Model Inference
 
 
 
 
 
 
50
 
51
  ```python
52
- from transformers import AutoProcessor
53
- from transformers import HunYuanVLForConditionalGeneration
54
- from PIL import Image
55
  import torch
 
56
 
57
- def clean_repeated_substrings(text):
58
- """Clean repeated substrings in text"""
59
- n = len(text)
60
- if n<8000:
61
- return text
62
- for length in range(2, n // 10 + 1):
63
- candidate = text[-length:]
64
- count = 0
65
- i = n - length
66
-
67
- while i >= 0 and text[i:i + length] == candidate:
68
- count += 1
69
- i -= length
70
-
71
- if count >= 10:
72
- return text[:n - length * (count - 1)]
73
-
74
- return text
75
-
76
- model_name_or_path = "tencent/HunyuanOCR"
77
- processor = AutoProcessor.from_pretrained(model_name_or_path, use_fast=False)
78
- img_path = "path/to/your/image.jpg"
79
- image_inputs = Image.open(img_path)
80
- messages1 = [
81
- {"role": "system", "content": ""},
82
- {
83
- "role": "user",
84
- "content": [
85
- {"type": "image", "image": img_path},
86
- {"type": "text", "text": (
87
- "检测并识别图片中的文字,将文本坐标格式化输出。"
88
- )},
89
- ],
90
- }
91
- ]
92
- messages = [messages1]
93
- texts = [
94
- processor.apply_chat_template(msg, tokenize=False, add_generation_prompt=True)
95
- for msg in messages
96
- ]
97
- inputs = processor(
98
- text=texts,
99
- images=image_inputs,
100
- padding=True,
101
- return_tensors="pt",
102
- )
103
  model = HunYuanVLForConditionalGeneration.from_pretrained(
104
- model_name_or_path,
105
- attn_implementation="eager",
106
- dtype=torch.bfloat16,
107
- device_map="auto"
 
 
 
108
  )
109
- with torch.no_grad():
110
- device = next(model.parameters()).device
111
- inputs = inputs.to(device)
112
- generated_ids = model.generate(**inputs, max_new_tokens=16384, do_sample=False)
113
- if "input_ids" in inputs:
114
- input_ids = inputs.input_ids
115
- else:
116
- print("inputs: # fallback", inputs)
117
- input_ids = inputs.inputs
118
- generated_ids_trimmed = [
119
- out_ids[len(in_ids):] for in_ids, out_ids in zip(input_ids, generated_ids)
120
- ]
121
- output_texts = clean_repeated_substrings(processor.batch_decode(
122
- generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
123
- ))
124
- print(output_texts)
125
- ```
126
 
 
 
 
 
 
 
 
127
 
128
- ## 🚀 Quick Start with vLLM
 
 
 
129
 
130
- Checkout [vLLM HunyuanOCR Usage Guide](https://docs.vllm.ai/projects/recipes/en/latest/Tencent-Hunyuan/HunyuanOCR.html).
 
131
 
132
- ### Installation
 
 
 
 
133
 
134
  ```bash
135
- uv venv hunyuanocr
136
- source hunyuanocr/bin/activate
137
 
138
- uv pip install -U vllm --pre --extra-index-url https://wheels.vllm.ai/nightly
 
 
 
139
  ```
140
 
141
- Note: We suggest to install [cuda-compat-12-9](https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2404/x86_64/):
 
142
  ```bash
143
- sudo dpkg -i cuda-compat-12-9_575.57.08-0ubuntu1_amd64.deb
144
- echo 'export LD_LIBRARY_PATH=/usr/local/cuda-12.9/compat:$LD_LIBRARY_PATH' >> ~/.bashrc
145
- source ~/.bashrc
146
- # verify cuda-compat-12-9
147
- ls /usr/local/cuda-12.9/compat
 
 
 
 
 
 
 
 
 
 
 
148
  ```
149
 
150
- ### Model Deploy
 
 
151
  ```bash
152
- vllm serve tencent/HunyuanOCR \
153
- --no-enable-prefix-caching \
154
- --mm-processor-cache-gb 0 \
155
- --gpu-memory-utilization 0.2
156
  ```
157
 
158
- ### Model Inference
159
- ```python
160
- from vllm import LLM, SamplingParams
161
- from PIL import Image
162
- from transformers import AutoProcessor
163
-
164
- def clean_repeated_substrings(text):
165
- """Clean repeated substrings in text"""
166
- n = len(text)
167
- if n<8000:
168
- return text
169
- for length in range(2, n // 10 + 1):
170
- candidate = text[-length:]
171
- count = 0
172
- i = n - length
173
-
174
- while i >= 0 and text[i:i + length] == candidate:
175
- count += 1
176
- i -= length
177
-
178
- if count >= 10:
179
- return text[:n - length * (count - 1)]
180
-
181
- return text
182
-
183
- model_path = "tencent/HunyuanOCR"
184
- llm = LLM(model=model_path, trust_remote_code=True)
185
- processor = AutoProcessor.from_pretrained(model_path)
186
- sampling_params = SamplingParams(temperature=0, max_tokens=16384)
187
-
188
- img_path = "/path/to/image.jpg"
189
- img = Image.open(img_path)
190
- messages = [
191
- {"role": "system", "content": ""},
192
- {"role": "user", "content": [
193
- {"type": "image", "image": img_path},
194
- {"type": "text", "text": "检测并识别图片中的文字,将文本坐标格式化输出。"}
195
- ]}
196
- ]
197
- prompt = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
198
- inputs = {"prompt": prompt, "multi_modal_data": {"image": [img]}}
199
- output = llm.generate([inputs], sampling_params)[0]
200
- print(clean_repeated_substrings(output.outputs[0].text))
201
  ```
202
 
203
- ## 💬 Application-oriented Prompts
 
204
 
205
- | Task | Prompt |
206
- |------|---------|
207
- | **Spotting** | 检测并识别图片中的文字,将文本坐标格式化输出。 |
208
- | **Document Parsing** | • 识别图片中的公式,用LaTeX格式表示。<br><br>• 把图中的表格解析为HTML。<br><br>• 解析图中的图表,对于流程图使用Mermaid格式表示,其他图表使用Markdown格式表示。<br><br>• 提取文档图片中正文的所有信息用markdown格式表示,其中页眉、页脚部分忽略,表格用html格式表达,文档中公式用latex格式表示,按照阅读顺序组织进行解析。|
209
- | **General Parsing** | • 提取图中的文字。|
210
- | **Information Extraction** | • 输出Key的值。<br><br>• 提取图片中的: ['key1','key2', ...] 的字段内容,并按照JSON格式返回。<br><br>• 提取图中的字幕 |
211
- | **Translation** | 先提取文字,再将文字内容翻译为英文。若是文档,则其中页眉、页脚忽略。公式用latex格式表示,表格用html格式表示。 |
212
 
213
- ## 🤝 Join Our Community
214
 
215
- <div align="center">
 
 
 
 
 
216
 
217
- | Wechat Discussion Group | Discord Group |
218
- | :---: | :---: |
219
- | <img src="https://github.com/Tencent-Hunyuan/HunyuanOCR/blob/main/assets/qrcode_for_hunyuanocr_wechat.jpg?raw=true" width="150"> | [Join HunyuanOCR Discord](https://discord.gg/XeD3p2MRDk) |
220
 
221
- </div>
222
 
223
- ## 📚 Citation
224
- ```
225
- @misc{hunyuanvisionteam2025hunyuanocrtechnicalreport,
226
- title={HunyuanOCR Technical Report},
227
- author={Hunyuan Vision Team and Pengyuan Lyu and Xingyu Wan and Gengluo Li and Shangpin Peng and Weinong Wang and Liang Wu and Huawen Shen and Yu Zhou and Canhui Tang and Qi Yang and Qiming Peng and Bin Luo and Hower Yang and Xinsong Zhang and Jinnian Zhang and Houwen Peng and Hongming Yang and Senhao Xie and Longsha Zhou and Ge Pei and Binghong Wu and Kan Wu and Jieneng Yang and Bochao Wang and Kai Liu and Jianchen Zhu and Jie Jiang and Linus and Han Hu and Chengquan Zhang},
228
- year={2025},
229
- journal={arXiv preprint arXiv:2511.19575},
230
- url={https://arxiv.org/abs/2511.19575},
231
- }
232
- ```
233
 
234
- ## 🙏 Acknowledgements
235
- We would like to thank [PaddleOCR](https://github.com/PaddlePaddle/PaddleOCR), [MinerU](https://github.com/opendatalab/MinerU), [MonkeyOCR](https://github.com/Yuliang-Liu/MonkeyOCR), [DeepSeek-OCR](https://github.com/deepseek-ai/DeepSeek-OCR), [dots.ocr](https://github.com/rednote-hilab/dots.ocr) for their valuable models and ideas.
236
- We also appreciate the benchmarks: [OminiDocBench](https://github.com/opendatalab/OmniDocBench), [OCRBench](https://github.com/Yuliang-Liu/MultimodalOCR/tree/main/OCRBench), [DoTA](https://github.com/liangyupu/DIMTDA).
 
1
  ---
2
  license: other
3
+ license_name: tencent-hunyuan-community
4
+ license_link: https://huggingface.co/tencent/HunyuanOCR/blob/main/LICENSE
5
  language:
6
  - multilingual
7
+ - en
8
+ - zh
 
 
9
  tags:
10
  - ocr
11
+ - vision-language-model
12
+ - document-parsing
13
+ - text-spotting
14
+ - information-extraction
15
+ - text-image-translation
16
+ pipeline_tag: image-text-to-text
17
+ library_name: transformers
18
  ---
19
 
20
+ # HunyuanOCR-1.5 &nbsp;·&nbsp; Preview
 
 
21
 
22
+ <div align="center">
23
 
24
+ **Towards Efficient and Effective E2E OCR**
 
 
 
 
 
25
 
26
+ </div>
 
 
 
 
27
 
28
+ > 📝 **Note.** This is a **preview release** of HunyuanOCR-1.5 weights.
29
+ > The **technical report and official weights are coming very soon**; the
30
+ > checkpoint, file layout and interface here may still evolve before the final
31
+ > release. Training / inference toolkit and full documentation live in the
32
+ > GitHub repo (branch **`develop`**):
33
+ > <https://github.com/Tencent-Hunyuan/HunyuanOCR>.
34
+
35
+ ---
36
 
37
  ## 📖 Introduction
 
38
 
39
+ **HunyuanOCR-1.5** is a lightweight, end-to-end OCR-specialized vision-language
40
+ model. It targets a broad range of text-centric visual tasks and unifies
41
+ **document parsing, text spotting, information extraction, and text-image
42
+ translation** within a single end-to-end VLM.
43
+
44
+ Building upon the validated lightweight architecture of **HunyuanOCR-1.0**,
45
+ HunyuanOCR-1.5 does *not* redesign the backbone. Instead, it performs a
46
+ systematic upgrade around two goals — **making the model faster and better**:
47
+
48
+ - ⚡ **Faster — DFlash inference acceleration.**
49
+ A lightweight block-diffusion draft model drafts multiple candidate tokens in
50
+ parallel, verified by the target model in a single pass, significantly
51
+ reducing decoding latency of long structured OCR outputs (dense documents,
52
+ tables, formulas) while **preserving the target model's output distribution**.
53
+ Draft weights: [`tencent/HunyuanOCR/dflash`](https://huggingface.co/tencent/HunyuanOCR/tree/main/dflash).
54
+
55
+ - 💻 **PC-side deployment via llama.cpp.**
56
+ Beyond server-grade vLLM, HunyuanOCR-1.5 also supports **CPU / consumer-GPU /
57
+ laptop** deployment via [`llama.cpp`](https://github.com/ggml-org/llama.cpp)
58
+ with an OpenAI-compatible `llama-server`. A DFlash-adapted `llama.cpp` fork is
59
+ also provided so the same speculative-decoding acceleration is available on
60
+ PC.
61
+
62
+ - 🧠 **Better — Agentic Data Flow + upgraded training recipe.**
63
+ An agent-driven data-construction system (**Agentic Data Flow**) translates
64
+ model weaknesses into executable data requirements, targeting long-tail
65
+ capabilities such as **low-resource OCR, ancient-script OCR, and multi-image
66
+ text-centric QA**. Pretraining Stage-3 is re-planned with **4K resolution** and
67
+ a **128K context window**; post-training refines SFT data and further explores
68
+ RL across different OCR tasks.
69
+
70
+ Together, HunyuanOCR-1.5 achieves both faster inference and broader OCR
71
+ capability coverage while retaining the deployment advantages of a lightweight
72
+ end-to-end model.
73
+
74
+ ---
75
+
76
+ ## ⚙️ Environment
77
 
78
+ - Python 3.10+
79
+ - PyTorch 2.1+ (CUDA 12.1+)
80
+ - **transformers** (ships `HunYuanVLForConditionalGeneration` + `AutoProcessor` for the HunyuanOCR-1.5 series)
81
+ - **vLLM nightly** — for serving and DFlash speculative decoding
82
+
83
+ ### transformers
84
+
85
+ ```bash
86
+ pip install transformers torch pillow accelerate
87
+ # for FlashAttention:
88
+ pip install flash-attn --no-build-isolation
89
+ ```
90
+
91
+ ### vLLM serving
92
+
93
+ We use a dedicated venv for inference to keep vLLM nightly isolated:
94
 
 
95
  ```bash
96
+ uv pip install -U vllm \
97
+ --torch-backend=cu130 \
98
+ --extra-index-url https://wheels.vllm.ai/nightly
99
+ uv pip install runai-model-streamer
100
  ```
 
101
 
102
+ > 💡 On CUDA 12.x, replace `--torch-backend=cu130` with the matching tag
103
+ > (e.g. `cu121`, `cu124`).
104
+ ---
105
+
106
+ ## 🚀 Quick start
107
+
108
+ ### A. HuggingFace transformers
109
 
110
  ```python
 
 
 
111
  import torch
112
+ from transformers import AutoProcessor, HunYuanVLForConditionalGeneration
113
 
114
+ MODEL_ID = "tencent/HunyuanOCR"
115
+
116
+ processor = AutoProcessor.from_pretrained(MODEL_ID, trust_remote_code=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
  model = HunYuanVLForConditionalGeneration.from_pretrained(
118
+ MODEL_ID, torch_dtype=torch.bfloat16, device_map="auto",
119
+ trust_remote_code=True,
120
+ ).eval()
121
+
122
+ prompt = (
123
+ "提取文档图片中正文的所有信息用markdown格式表示,其中页眉、页脚部分忽略,"
124
+ "表格用html格式表达,文档中公式用latex格式表示,按照阅读顺序组织进行解析。"
125
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
 
127
+ messages = [{
128
+ "role": "user",
129
+ "content": [
130
+ {"type": "image", "image": "/path/to/document.png"},
131
+ {"type": "text", "text": prompt},
132
+ ],
133
+ }]
134
 
135
+ inputs = processor.apply_chat_template(
136
+ messages, add_generation_prompt=True, tokenize=True,
137
+ return_dict=True, return_tensors="pt",
138
+ ).to(model.device)
139
 
140
+ with torch.inference_mode():
141
+ out = model.generate(**inputs, max_new_tokens=8000, do_sample=False)
142
 
143
+ gen = out[:, inputs["input_ids"].shape[1]:]
144
+ print(processor.batch_decode(gen, skip_special_tokens=True)[0])
145
+ ```
146
+
147
+ Or use the ready-made single-image script from the repo:
148
 
149
  ```bash
150
+ git clone -b develop https://github.com/Tencent-Hunyuan/HunyuanOCR.git
151
+ cd HunyuanOCR
152
 
153
+ python inference/infer_base.py \
154
+ --model tencent/HunyuanOCR \
155
+ --image /path/to/document.png \
156
+ --max-new-tokens 8000
157
  ```
158
 
159
+ ### B. vLLM
160
+
161
  ```bash
162
+ # Autoregressive baseline
163
+ MODEL_PATH=tencent/HunyuanOCR \
164
+ GPU=0 PORT=8000 GPU_MEM_UTIL=0.9 \
165
+ bash inference/serve_ar.sh
166
+
167
+ # DFlash speculative decoding
168
+ # The draft lives under the `dflash/` subfolder of tencent/HunyuanOCR;
169
+ # download it into a flat local dir first (HF subfolder loading is
170
+ # unsupported by vLLM's speculative-config):
171
+ # python -c "from huggingface_hub import snapshot_download; import shutil, os; \
172
+ # d=snapshot_download('tencent/HunyuanOCR', allow_patterns=['dflash/*']); \
173
+ # shutil.copytree(os.path.join(d,'dflash'), './hunyuanocr_dflash', dirs_exist_ok=True)"
174
+ MODEL_PATH=tencent/HunyuanOCR \
175
+ DFLASH_PATH=./hunyuanocr_dflash \
176
+ GPU=0 PORT=8001 GPU_MEM_UTIL=0.9 NUM_SPEC_TOKENS=15 \
177
+ bash inference/serve_dflash.sh
178
  ```
179
 
180
+ Send one image with the shipped client (streaming + tail-repetition early-stop,
181
+ matches internal bench sampling params):
182
+
183
  ```bash
184
+ python inference/infer_vllm_client.py \
185
+ --host 127.0.0.1 --port 8000 \
186
+ --model tencent/HunyuanOCR \
187
+ --image /path/to/document.png
188
  ```
189
 
190
+ ### C. PC-side deployment via llama.cpp
191
+
192
+ See `docs/llama_cpp.md` in the GitHub repo for GGUF conversion, community
193
+ `llama-server` launch, and the DFlash-adapted fork.
194
+
195
+ ---
196
+
197
+ ## 🎯 Default OCR prompt
198
+
199
+ ```
200
+ 提取文档图片中正文的所有信息用markdown格式表示,其中页眉、页脚部分忽略,
201
+ 表格用html格式表达,文档中公式用latex格式表示,按照阅读顺序组织进行解析。
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
  ```
203
 
204
+ The model also handles text spotting, information extraction, and text-image
205
+ translation — pass a task-specific instruction as the text prompt.
206
 
207
+ ---
 
 
 
 
 
 
208
 
209
+ ## 🔗 Related repositories
210
 
211
+ - **GitHub — training & inference toolkit** (branch `develop`):
212
+ <https://github.com/Tencent-Hunyuan/HunyuanOCR>
213
+ - **DFlash draft weights** (required for speculative-decoding acceleration):
214
+ [`tencent/HunyuanOCR/dflash`](https://huggingface.co/tencent/HunyuanOCR/tree/main/dflash)
215
+ - **HunyuanOCR-1.0** (previous generation, archived under `v1.0/`):
216
+ [`tencent/HunyuanOCR/v1.0`](https://huggingface.co/tencent/HunyuanOCR/tree/main/v1.0)
217
 
218
+ ---
 
 
219
 
220
+ ## 📜 License
221
 
222
+ HunyuanOCR-1.5 is released under the same license as HunyuanOCR 1.0 — the
223
+ **Tencent Hunyuan Community License Agreement**.
224
+
225
+ > ⚠️ **Preview notice.** This checkpoint is a preview snapshot. The technical
226
+ > report and official model release will follow shortly; interfaces and weights
227
+ > may be updated before the final release.
 
 
 
 
228
 
 
 
 
chat_template.jinja ADDED
@@ -0,0 +1 @@
 
 
1
+ {% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}{% if messages[0]['content'] is string %}{% set system_message = messages[0]['content'] %}{% else %}{% set system_message = messages[0]['content']['text'] %}{% endif %}<|hy_begin▁of▁sentence|>{{ system_message }}<|hy_place▁holder▁no▁3|>{% else %}{% set loop_messages = messages %}<|hy_begin▁of▁sentence|>{% endif %}{% for message in loop_messages %}{% if message['role'] == 'user' %}{% if message['content'] is string %}{{ message['content'] }}{% else %}{% for content in message['content'] %}{% if content['type'] == 'image' or 'image' in content or 'image_url' in content %}<|hy_place▁holder▁no▁100|><|hy_place▁holder▁no▁102|><|hy_place▁holder▁no▁101|>{% elif 'text' in content %}{{ content['text'] }}{% endif %}{% endfor %}{% endif %}<|hy_User|>{% elif message['role'] == 'assistant' %}{{ message['content'] }}<|hy_Assistant|>{% endif %}{% endfor %}
config.json CHANGED
@@ -6,18 +6,19 @@
6
  "attention_dropout": 0.0,
7
  "attention_head_dim": 128,
8
  "bos_token_id": 120000,
 
9
  "eod_token_id": 120020,
10
  "eos_token_id": 120020,
11
  "head_dim": 128,
12
  "hidden_act": "silu",
13
  "hidden_size": 1024,
14
- "image_start_token_id": 120118,
15
  "image_end_token_id": 120119,
16
- "image_token_id": 120120,
17
  "image_newline_token_id": 120121,
 
 
18
  "initializer_range": 0.02,
19
  "intermediate_size": 3584,
20
- "max_position_embeddings": 32768,
21
  "mlp_bias": false,
22
  "model_type": "hunyuan_vl",
23
  "norm_type": "rms",
@@ -27,7 +28,7 @@
27
  "num_key_value_heads": 8,
28
  "org_vocab_size": 120818,
29
  "pad_id": 120002,
30
- "pad_token_id": -1,
31
  "pretraining_tp": 1,
32
  "rms_norm_eps": 1e-05,
33
  "rope_scaling": {
@@ -48,33 +49,142 @@
48
  "rope_theta": 10000.0,
49
  "routed_scaling_factor": 1.0,
50
  "sep_token_id": 0,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  "text_end_id": 8,
52
  "text_start_id": 7,
53
- "tie_word_embeddings": true,
54
- "dtype": "bfloat16",
55
- "transformers_version": "4.49.0",
56
  "use_cache": true,
57
- "use_qk_norm": true,
58
  "use_cla": false,
 
 
 
59
  "vision_config": {
60
  "add_patchemb_bias": true,
 
61
  "attention_dropout": 0.0,
62
  "cat_extra_token": 1,
 
63
  "hidden_act": "gelu",
64
  "hidden_dropout": 0.0,
65
  "hidden_size": 1152,
66
- "img_max_token_num": 4096,
67
  "intermediate_size": 4304,
68
  "interpolate_mode": "bilinear",
 
69
  "max_image_size": 2048,
70
- "max_vit_seq_len": 16384,
 
 
71
  "num_attention_heads": 16,
72
  "num_channels": 3,
73
  "num_hidden_layers": 27,
 
74
  "out_hidden_size": 1024,
75
  "patch_size": 16,
 
 
 
 
76
  "rms_norm_eps": 1e-05,
77
- "spatial_merge_size": 2
 
 
 
 
 
 
78
  },
79
  "vocab_size": 120818
80
  }
 
6
  "attention_dropout": 0.0,
7
  "attention_head_dim": 128,
8
  "bos_token_id": 120000,
9
+ "dtype": "bfloat16",
10
  "eod_token_id": 120020,
11
  "eos_token_id": 120020,
12
  "head_dim": 128,
13
  "hidden_act": "silu",
14
  "hidden_size": 1024,
 
15
  "image_end_token_id": 120119,
 
16
  "image_newline_token_id": 120121,
17
+ "image_start_token_id": 120118,
18
+ "image_token_id": 120120,
19
  "initializer_range": 0.02,
20
  "intermediate_size": 3584,
21
+ "max_position_embeddings": 131072,
22
  "mlp_bias": false,
23
  "model_type": "hunyuan_vl",
24
  "norm_type": "rms",
 
28
  "num_key_value_heads": 8,
29
  "org_vocab_size": 120818,
30
  "pad_id": 120002,
31
+ "pad_token_id": 120002,
32
  "pretraining_tp": 1,
33
  "rms_norm_eps": 1e-05,
34
  "rope_scaling": {
 
49
  "rope_theta": 10000.0,
50
  "routed_scaling_factor": 1.0,
51
  "sep_token_id": 0,
52
+ "text_config": {
53
+ "_name_or_path": "/jizhicfs/shangppeng/save_models/hunyuan/HYOCR_1_5/std_hf/HYOCR_v1_5_SFT/0625_sft_stage2_step300",
54
+ "add_classification_head": false,
55
+ "architectures": [
56
+ "HunYuanVLForConditionalGeneration"
57
+ ],
58
+ "attention_bias": false,
59
+ "attention_dropout": 0.0,
60
+ "attention_head_dim": 128,
61
+ "bos_token_id": 120000,
62
+ "class_num": 0,
63
+ "dense_list": [
64
+ 1024,
65
+ 0
66
+ ],
67
+ "dtype": "bfloat16",
68
+ "eod_token_id": 120020,
69
+ "eos_token_id": 120007,
70
+ "expert_hidden_dim": null,
71
+ "first_k_dense_replace": 0,
72
+ "group_limited_greedy": false,
73
+ "head_dim": 128,
74
+ "hidden_act": "silu",
75
+ "hidden_size": 1024,
76
+ "image_newline_token_id": 120121,
77
+ "initializer_range": 0.02,
78
+ "intermediate_size": 3584,
79
+ "kv_lora_rank": 512,
80
+ "mask_init_id": 13,
81
+ "max_position_embeddings": 131072,
82
+ "mlp_bias": false,
83
+ "model_type": "hunyuan_vl_text",
84
+ "moe_drop_tokens": false,
85
+ "moe_intermediate_size": null,
86
+ "moe_layer_num_skipped": 0,
87
+ "moe_random_routing_dropped_token": false,
88
+ "moe_topk": 1,
89
+ "mtp_loss_factor": 0.1,
90
+ "mtp_no_bias": true,
91
+ "n_group": null,
92
+ "norm_topk_prob": true,
93
+ "norm_type": "rms",
94
+ "num_attention_heads": 16,
95
+ "num_experts": 1,
96
+ "num_experts_per_tok": 1,
97
+ "num_hidden_layers": 24,
98
+ "num_key_value_heads": 8,
99
+ "num_nextn_predict_layers": 1,
100
+ "num_predictor_layers": 0,
101
+ "num_shared_expert": 1,
102
+ "num_shared_experts": 1,
103
+ "org_vocab_size": 120818,
104
+ "pad_id": 120002,
105
+ "pad_token_id": 120002,
106
+ "pool_type": "last",
107
+ "pretraining_tp": 1,
108
+ "q_lora_rank": 1536,
109
+ "qk_nope_head_dim": 128,
110
+ "qk_norm": false,
111
+ "qk_rope_head_dim": 64,
112
+ "rms_norm_eps": 1e-05,
113
+ "rope_scaling": {
114
+ "alpha": 1000.0,
115
+ "beta_fast": 32,
116
+ "beta_slow": 1,
117
+ "factor": 1.0,
118
+ "mscale": 1.0,
119
+ "mscale_all_dim": 1.0,
120
+ "type": "xdrope",
121
+ "xdrope_section": [
122
+ 16,
123
+ 16,
124
+ 16,
125
+ 16
126
+ ]
127
+ },
128
+ "rope_theta": 10000.0,
129
+ "routed_scaling_factor": 1.0,
130
+ "sep_token_id": 0,
131
+ "text_end_id": 8,
132
+ "text_start_id": 7,
133
+ "tie_word_embeddings": true,
134
+ "topk_group": null,
135
+ "use_cache": true,
136
+ "use_cla": false,
137
+ "use_mixed_mlp_moe": false,
138
+ "use_mla": false,
139
+ "use_qk_norm": true,
140
+ "use_rotary_pos_emb": true,
141
+ "v_head_dim": 128,
142
+ "vision_full_attention": false,
143
+ "vocab_size": 120818
144
+ },
145
  "text_end_id": 8,
146
  "text_start_id": 7,
147
+ "transformers_version": "4.57.1",
 
 
148
  "use_cache": true,
 
149
  "use_cla": false,
150
+ "use_qk_norm": true,
151
+ "video_end_token_id": 120123,
152
+ "video_start_token_id": 120122,
153
  "vision_config": {
154
  "add_patchemb_bias": true,
155
+ "anyres_vit_max_image_size": 2048,
156
  "attention_dropout": 0.0,
157
  "cat_extra_token": 1,
158
+ "dtype": "bfloat16",
159
  "hidden_act": "gelu",
160
  "hidden_dropout": 0.0,
161
  "hidden_size": 1152,
162
+ "img_max_token_num": 16384,
163
  "intermediate_size": 4304,
164
  "interpolate_mode": "bilinear",
165
+ "learnable_mlp_pooling_size": 0,
166
  "max_image_size": 2048,
167
+ "max_vit_seq_len": 65536,
168
+ "min_image_size": 512,
169
+ "model_type": "hunyuan_vl",
170
  "num_attention_heads": 16,
171
  "num_channels": 3,
172
  "num_hidden_layers": 27,
173
+ "num_key_value_heads": 16,
174
  "out_hidden_size": 1024,
175
  "patch_size": 16,
176
+ "perceive_post_norm": true,
177
+ "perceive_pre_norm": true,
178
+ "remove_prenorm": true,
179
+ "resize_resolution": 2048,
180
  "rms_norm_eps": 1e-05,
181
+ "spatial_merge_size": 2,
182
+ "spatial_patch_size": 1,
183
+ "temporal_patch_size": 1,
184
+ "text_hidden_size": 1024,
185
+ "video_max_image_size": 768,
186
+ "video_min_image_size": 256,
187
+ "vision_full_attention": false
188
  },
189
  "vocab_size": 120818
190
  }
dflash/.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
dflash/README.md ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ license_name: tencent-hunyuan-community
4
+ license_link: https://huggingface.co/tencent/HunyuanOCR/blob/main/LICENSE
5
+ tags:
6
+ - ocr
7
+ - speculative-decoding
8
+ - draft-model
9
+ - dflash
10
+ - block-diffusion
11
+ - vision-language-model
12
+ base_model: tencent/HunyuanOCR
13
+ library_name: transformers
14
+ ---
15
+
16
+ # HunyuanOCR-1.5 · DFlash Draft &nbsp;·&nbsp; Preview
17
+
18
+ <div align="center">
19
+
20
+ **Speculative-decoding draft for [`tencent/HunyuanOCR`](https://huggingface.co/tencent/HunyuanOCR)**
21
+
22
+ </div>
23
+
24
+
25
+ > ⚠️ **This model is not usable standalone.** It is a *draft model* used only
26
+ > for **speculative decoding** together with the target model
27
+ > [`tencent/HunyuanOCR`](https://huggingface.co/tencent/HunyuanOCR).
28
+
29
+ ---
30
+
31
+ ## 📖 What is DFlash?
32
+
33
+ End-to-end OCR is often accompanied by long autoregressive decoding — the major
34
+ bottleneck for dense documents, tables, formulas, and other long structured
35
+ outputs.
36
+
37
+ HunyuanOCR-1.5 adopts a speculative-decoding framework based on **DFlash**:
38
+
39
+ - A lightweight **block-diffusion** draft model (this repo) proposes multiple
40
+ candidate tokens **in parallel**.
41
+ - The target model
42
+ ([`tencent/HunyuanOCR`](https://huggingface.co/tencent/HunyuanOCR))
43
+ verifies them in a **single forward pass**.
44
+ - Accepted tokens are committed as-is, so the **output distribution of the
45
+ target model is preserved** — DFlash is a lossless acceleration.
46
+
47
+ The result is significantly reduced decoding latency for long structured OCR
48
+ outputs, without sacrificing accuracy.
49
+
50
+ Architecture: 5-layer Qwen3-style block-diffusion draft, predicting 16 masked tokens in a single block. The draft is bound to
51
+ target-layer indices `[1, 8, 15, 22]` of the 24-layer HunyuanOCR-1.5 base.
52
+
53
+ ---
54
+
55
+ ## ⚙️ Environment
56
+
57
+ - Python 3.10+
58
+ - PyTorch 2.1+ (CUDA 12.1+)
59
+ - **transformers**
60
+ - **vLLM nightly** — required for real speculative-decoding speedup at
61
+ deployment time. DFlash support is included in the nightly wheel; no separate
62
+ patch is needed.
63
+
64
+ ```bash
65
+ uv pip install -U vllm \
66
+ --torch-backend=cu130 \
67
+ --extra-index-url https://wheels.vllm.ai/nightly
68
+ uv pip install runai-model-streamer
69
+ ```
70
+
71
+ > 💡 On CUDA 12.x, replace `--torch-backend=cu130` with the matching tag
72
+ > (e.g. `cu121`, `cu124`).
73
+ ---
74
+
75
+ ## 🚀 How to use
76
+
77
+ ### A. transformers — draft-load check
78
+
79
+ Use the shipped script from the GitHub repo. It loads the draft, runs it
80
+ alongside the target for one image, and verifies that the AR reference matches:
81
+
82
+ ```bash
83
+ git clone -b develop https://github.com/Tencent-Hunyuan/HunyuanOCR.git
84
+ cd HunyuanOCR
85
+
86
+ python inference/infer_dflash.py \
87
+ --model tencent/HunyuanOCR \
88
+ --dflash-model ./hunyuanocr_dflash \
89
+ --image /path/to/document.png \
90
+ --num-spec-tokens 15
91
+ ```
92
+
93
+ > ℹ️ `infer_dflash.py` only verifies that the DFlash draft loads and
94
+ > produces a matching AR reference on a single image. **Real
95
+ > speculative-decoding acceleration is only realized under vLLM**, see below.
96
+
97
+ > ⬇️ **Preparing the draft directory.** The DFlash draft lives under the
98
+ > `dflash/` subfolder of `tencent/HunyuanOCR`. Because vLLM's
99
+ > `--speculative-config` and `trust_remote_code` custom-code loading do not
100
+ > support HF subfolders, download that subfolder into a **flat local
101
+ > directory** first and point the draft path at it:
102
+ >
103
+ > ```bash
104
+ > python -c "from huggingface_hub import snapshot_download; import shutil, os; \
105
+ > d=snapshot_download('tencent/HunyuanOCR', allow_patterns=['dflash/*']); \
106
+ > shutil.copytree(os.path.join(d,'dflash'), './hunyuanocr_dflash', dirs_exist_ok=True)"
107
+ > ```
108
+ >
109
+ > Then use `./hunyuanocr_dflash` as the draft path in the commands below.
110
+
111
+ ### B. vLLM speculative decoding
112
+
113
+ ```bash
114
+ MODEL_PATH=tencent/HunyuanOCR \
115
+ DFLASH_PATH=./hunyuanocr_dflash \
116
+ GPU=0 PORT=8001 GPU_MEM_UTIL=0.9 \
117
+ NUM_SPEC_TOKENS=15 \
118
+ bash inference/serve_dflash.sh
119
+ ```
120
+
121
+ Under the hood the launch script passes:
122
+
123
+ ```
124
+ --speculative-config '{"method":"dflash","model":"./hunyuanocr_dflash","num_speculative_tokens":15}'
125
+ ```
126
+
127
+ to the vLLM entrypoint. Send an OpenAI-compatible request with the shipped
128
+ single-image client:
129
+
130
+ ```bash
131
+ python inference/infer_vllm_client.py \
132
+ --host 127.0.0.1 --port 8001 \
133
+ --model tencent/HunyuanOCR \
134
+ --image /path/to/document.png
135
+ ```
136
+
137
+ ### C. llama.cpp (PC-side)
138
+
139
+ A DFlash-adapted `llama.cpp` fork is provided for CPU / consumer-GPU / laptop
140
+ speculative decoding. See `docs/llama_cpp.md` in the GitHub repo for the full
141
+ guide (GGUF conversion of both target + draft, `llama-server` launch, and a
142
+ smoke-test client).
143
+
144
+ ---
145
+
146
+ ## 📦 Files in this repo
147
+
148
+ | file | purpose |
149
+ |---|---|
150
+ | `model.safetensors` | draft weights (float32) |
151
+ | `config.json` | draft config; sets `auto_map` to `dflash.DFlashDraftModel` |
152
+ | `dflash.py` | `DFlashDraftModel` implementation (loaded via `trust_remote_code=True`) |
153
+ | `chat_template.jinja`, `tokenizer.json`, `tokenizer_config.json`, `processor_config.json` | tokenizer / processor, kept in sync with the target model |
154
+
155
+ ---
156
+
157
+ ## 🔗 Related repositories
158
+
159
+ - **Target model** (required):
160
+ [`tencent/HunyuanOCR`](https://huggingface.co/tencent/HunyuanOCR)
161
+ - **GitHub — training & inference toolkit** (branch `develop`):
162
+ <https://github.com/Tencent-Hunyuan/HunyuanOCR>
163
+ - **HunyuanOCR-1.0** (previous generation, archived under `v1.0/`):
164
+ [`tencent/HunyuanOCR/v1.0`](https://huggingface.co/tencent/HunyuanOCR/tree/main/v1.0)
165
+
166
+ ---
167
+
168
+ ## 📜 License
169
+
170
+ HunyuanOCR-1.5 (including the DFlash draft) is released under the same license
171
+ as HunyuanOCR 1.0 — the **Tencent Hunyuan Community License Agreement**.
172
+
dflash/chat_template.jinja ADDED
@@ -0,0 +1 @@
 
 
1
+ {% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}{% if messages[0]['content'] is string %}{% set system_message = messages[0]['content'] %}{% else %}{% set system_message = messages[0]['content']['text'] %}{% endif %}<|hy_begin▁of▁sentence|>{{ system_message }}<|hy_place▁holder▁no▁3|>{% else %}{% set loop_messages = messages %}<|hy_begin▁of▁sentence|>{% endif %}{% for message in loop_messages %}{% if message['role'] == 'user' %}{% if message['content'] is string %}{{ message['content'] }}{% else %}{% for content in message['content'] %}{% if content['type'] == 'image' or 'image' in content or 'image_url' in content %}<|hy_place▁holder▁no▁100|><|hy_place▁holder▁no▁102|><|hy_place▁holder▁no▁101|>{% elif 'text' in content %}{{ content['text'] }}{% endif %}{% endfor %}{% endif %}<|hy_User|>{% elif message['role'] == 'assistant' %}{{ message['content'] }}<|hy_Assistant|>{% endif %}{% endfor %}
dflash/config.json ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "DFlashDraftModel"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoModel": "dflash.DFlashDraftModel"
9
+ },
10
+ "block_size": 16,
11
+ "dflash_config": {
12
+ "mask_token_id": 120817,
13
+ "target_layer_ids": [
14
+ 1,
15
+ 8,
16
+ 15,
17
+ 22
18
+ ]
19
+ },
20
+ "dtype": "float32",
21
+ "eos_token_id": 120007,
22
+ "head_dim": 128,
23
+ "hidden_act": "silu",
24
+ "hidden_size": 1024,
25
+ "initializer_range": 0.02,
26
+ "intermediate_size": 3584,
27
+ "layer_types": [
28
+ "full_attention",
29
+ "full_attention",
30
+ "full_attention",
31
+ "full_attention",
32
+ "full_attention"
33
+ ],
34
+ "max_position_embeddings": 131072,
35
+ "max_window_layers": 5,
36
+ "model_type": "qwen3",
37
+ "num_attention_heads": 16,
38
+ "num_hidden_layers": 5,
39
+ "num_key_value_heads": 8,
40
+ "num_target_layers": 24,
41
+ "pad_token_id": 120002,
42
+ "rms_norm_eps": 1e-05,
43
+ "rope_scaling": null,
44
+ "rope_theta": 10000.0,
45
+ "sliding_window": null,
46
+ "tie_word_embeddings": true,
47
+ "transformers_version": "4.57.1",
48
+ "use_cache": true,
49
+ "use_sliding_window": false,
50
+ "vocab_size": 120818
51
+ }
dflash/dflash.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Callable
2
+ from typing_extensions import Unpack, Tuple
3
+ import torch
4
+ from torch import nn
5
+ from transformers.models.qwen3.modeling_qwen3 import (
6
+ Qwen3RMSNorm,
7
+ Qwen3RotaryEmbedding,
8
+ Qwen3Config,
9
+ Qwen3PreTrainedModel,
10
+ Qwen3MLP,
11
+ GradientCheckpointingLayer,
12
+ FlashAttentionKwargs,
13
+ rotate_half,
14
+ eager_attention_forward,
15
+ ALL_ATTENTION_FUNCTIONS,
16
+ )
17
+ from transformers.modeling_outputs import CausalLMOutputWithPast
18
+ from transformers.cache_utils import Cache
19
+
20
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
21
+ cos = cos.unsqueeze(unsqueeze_dim)
22
+ sin = sin.unsqueeze(unsqueeze_dim)
23
+ q_len = q.size(-2)
24
+ q_embed = (q * cos[..., -q_len:, :]) + (rotate_half(q) * sin[..., -q_len:, :])
25
+ k_embed = (k * cos) + (rotate_half(k) * sin)
26
+ return q_embed, k_embed
27
+
28
+ class Qwen3DFlashAttention(nn.Module):
29
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
30
+
31
+ def __init__(self, config: Qwen3Config, layer_idx: int):
32
+ super().__init__()
33
+ self.config = config
34
+ self.layer_idx = layer_idx
35
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
36
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
37
+ self.scaling = self.head_dim**-0.5
38
+ self.attention_dropout = config.attention_dropout
39
+ self.is_causal = False
40
+ self.q_proj = nn.Linear(
41
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
42
+ )
43
+ self.k_proj = nn.Linear(
44
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
45
+ )
46
+ self.v_proj = nn.Linear(
47
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
48
+ )
49
+ self.o_proj = nn.Linear(
50
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
51
+ )
52
+ self.q_norm = Qwen3RMSNorm(self.head_dim, eps=config.rms_norm_eps)
53
+ self.k_norm = Qwen3RMSNorm(self.head_dim, eps=config.rms_norm_eps)
54
+ self.sliding_window = config.sliding_window if config.layer_types[layer_idx] == "sliding_attention" else None
55
+
56
+ def forward(
57
+ self,
58
+ hidden_states: torch.Tensor,
59
+ target_hidden: torch.Tensor,
60
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
61
+ attention_mask: Optional[torch.Tensor],
62
+ past_key_values: Optional[Cache] = None,
63
+ cache_position: Optional[torch.LongTensor] = None,
64
+ **kwargs: Unpack[FlashAttentionKwargs],
65
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
66
+ bsz, q_len = hidden_states.shape[:-1]
67
+ ctx_len = target_hidden.shape[1]
68
+ q = self.q_proj(hidden_states)
69
+ q = q.view(bsz, q_len, -1, self.head_dim)
70
+ q = self.q_norm(q).transpose(1, 2)
71
+ k_ctx = self.k_proj(target_hidden)
72
+ k_noise = self.k_proj(hidden_states)
73
+ v_ctx = self.v_proj(target_hidden)
74
+ v_noise = self.v_proj(hidden_states)
75
+ k = torch.cat([k_ctx, k_noise], dim=1).view(bsz, ctx_len + q_len, -1, self.head_dim)
76
+ v = torch.cat([v_ctx, v_noise], dim=1).view(bsz, ctx_len + q_len, -1, self.head_dim)
77
+ k = self.k_norm(k).transpose(1, 2)
78
+ v = v.transpose(1, 2)
79
+ cos, sin = position_embeddings
80
+ q, k = apply_rotary_pos_emb(q, k, cos, sin)
81
+ if past_key_values is not None:
82
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
83
+ k, v = past_key_values.update(k, v, self.layer_idx, cache_kwargs)
84
+ attn_fn: Callable = eager_attention_forward
85
+ if self.config._attn_implementation != "eager":
86
+ attn_fn = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
87
+ attn_output, attn_weights = attn_fn(
88
+ self,
89
+ q,
90
+ k,
91
+ v,
92
+ attention_mask,
93
+ dropout=0.0 if not self.training else self.attention_dropout,
94
+ scaling=self.scaling,
95
+ sliding_window=self.sliding_window,
96
+ **kwargs,
97
+ )
98
+ attn_output = attn_output.reshape(bsz, q_len, -1)
99
+ attn_output = self.o_proj(attn_output)
100
+ return attn_output, attn_weights
101
+
102
+ class Qwen3DFlashDecoderLayer(GradientCheckpointingLayer):
103
+ def __init__(self, config: Qwen3Config, layer_idx: int):
104
+ super().__init__()
105
+ self.hidden_size = config.hidden_size
106
+ self.self_attn = Qwen3DFlashAttention(config=config, layer_idx=layer_idx)
107
+ self.mlp = Qwen3MLP(config)
108
+ self.input_layernorm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
109
+ self.post_attention_layernorm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
110
+
111
+ def forward(
112
+ self,
113
+ target_hidden: Optional[torch.Tensor] = None,
114
+ hidden_states: Optional[torch.Tensor] = None,
115
+ attention_mask: Optional[torch.Tensor] = None,
116
+ position_ids: Optional[torch.LongTensor] = None,
117
+ past_key_value: Optional[Cache] = None,
118
+ output_attentions: Optional[bool] = False,
119
+ use_cache: Optional[bool] = False,
120
+ cache_position: Optional[torch.LongTensor] = None,
121
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
122
+ **kwargs: Unpack[FlashAttentionKwargs],
123
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
124
+ residual = hidden_states
125
+ hidden_states = self.input_layernorm(hidden_states)
126
+ hidden_states = self.self_attn(
127
+ hidden_states=hidden_states,
128
+ target_hidden=target_hidden,
129
+ attention_mask=attention_mask,
130
+ position_ids=position_ids,
131
+ past_key_values=past_key_value,
132
+ output_attentions=output_attentions,
133
+ use_cache=use_cache,
134
+ cache_position=cache_position,
135
+ position_embeddings=position_embeddings,
136
+ **kwargs,
137
+ )[0]
138
+ hidden_states = residual + hidden_states
139
+ residual = hidden_states
140
+ hidden_states = self.post_attention_layernorm(hidden_states)
141
+ hidden_states = self.mlp(hidden_states)
142
+ hidden_states = residual + hidden_states
143
+ return hidden_states
144
+
145
+ class DFlashDraftModel(Qwen3PreTrainedModel):
146
+ config_class = Qwen3Config
147
+ _no_split_modules = ["Qwen3DFlashDecoderLayer"]
148
+
149
+ def __init__(self, config) -> None:
150
+ super().__init__(config)
151
+ self.config = config
152
+ self.layers = nn.ModuleList(
153
+ [Qwen3DFlashDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
154
+ )
155
+ self.target_layer_ids = self.config.dflash_config.get("target_layer_ids", None)
156
+ self.norm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
157
+ self.rotary_emb = Qwen3RotaryEmbedding(config)
158
+ self.fc = nn.Linear(len(self.target_layer_ids) * config.hidden_size, config.hidden_size, bias=False)
159
+ self.hidden_norm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
160
+ self.block_size = config.block_size
161
+ self.mask_token_id = self.config.dflash_config.get("mask_token_id", None)
162
+ self.post_init()
163
+
164
+ def forward(
165
+ self,
166
+ position_ids: torch.LongTensor,
167
+ attention_mask: Optional[torch.Tensor] = None,
168
+ noise_embedding: Optional[torch.Tensor] = None,
169
+ target_hidden: Optional[torch.Tensor] = None,
170
+ past_key_values: Optional[Cache] = None,
171
+ use_cache: bool = False,
172
+ **kwargs,
173
+ ) -> CausalLMOutputWithPast:
174
+ hidden_states = noise_embedding
175
+ target_hidden = self.hidden_norm(self.fc(target_hidden))
176
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
177
+ for layer in self.layers:
178
+ hidden_states = layer(
179
+ hidden_states=hidden_states,
180
+ target_hidden=target_hidden,
181
+ attention_mask=attention_mask,
182
+ position_ids=position_ids,
183
+ past_key_value=past_key_values,
184
+ use_cache=use_cache,
185
+ position_embeddings=position_embeddings,
186
+ **kwargs,
187
+ )
188
+ return self.norm(hidden_states)
dflash/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9b189f2c0d2b0251d697c19790c2a9b5416da5fc2981edfaab9673ac76b5d513
3
+ size 362867640
dflash/processor_config.json ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "image_processor": {
3
+ "do_convert_rgb": true,
4
+ "do_normalize": true,
5
+ "do_rescale": true,
6
+ "do_resize": true,
7
+ "image_mean": [
8
+ 0.48145466,
9
+ 0.4578275,
10
+ 0.40821073
11
+ ],
12
+ "image_processor_type": "HunYuanVLImageProcessor",
13
+ "image_std": [
14
+ 0.26862954,
15
+ 0.26130258,
16
+ 0.27577711
17
+ ],
18
+ "max_pixels": 16777216,
19
+ "merge_size": 2,
20
+ "min_pixels": 262144,
21
+ "patch_size": 16,
22
+ "resample": 1,
23
+ "rescale_factor": 0.00392156862745098,
24
+ "size": {
25
+ "longest_edge": 16777216,
26
+ "shortest_edge": 262144
27
+ },
28
+ "temporal_patch_size": 1
29
+ },
30
+ "processor_class": "HunYuanVLProcessor",
31
+ "video_processor": {
32
+ "data_format": "channels_first",
33
+ "default_to_square": true,
34
+ "do_convert_rgb": true,
35
+ "do_normalize": true,
36
+ "do_rescale": true,
37
+ "do_resize": true,
38
+ "do_sample_frames": false,
39
+ "image_mean": [
40
+ 0.48145466,
41
+ 0.4578275,
42
+ 0.40821073
43
+ ],
44
+ "image_std": [
45
+ 0.26862954,
46
+ 0.26130258,
47
+ 0.27577711
48
+ ],
49
+ "max_frames": 768,
50
+ "max_pixels": 4194304,
51
+ "merge_size": 2,
52
+ "min_frames": 4,
53
+ "min_pixels": 262144,
54
+ "patch_size": 16,
55
+ "resample": 3,
56
+ "rescale_factor": 0.00392156862745098,
57
+ "return_metadata": false,
58
+ "size": {
59
+ "longest_edge": 4194304,
60
+ "shortest_edge": 262144
61
+ },
62
+ "temporal_patch_size": 1,
63
+ "video_processor_type": "HunYuanVLVideoProcessor"
64
+ }
65
+ }
dflash/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
dflash/tokenizer_config.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backend": "tokenizers",
3
+ "bos_token": "<|hy_begin▁of▁sentence|>",
4
+ "clean_up_tokenization_spaces": true,
5
+ "eos_token": "<|hy_Assistant|>",
6
+ "image_end_token": "<|hy_place▁holder▁no▁101|>",
7
+ "image_start_token": "<|hy_place▁holder▁no▁100|>",
8
+ "image_token": "<|hy_place▁holder▁no▁102|>",
9
+ "is_local": true,
10
+ "local_files_only": false,
11
+ "model_max_length": 1000000000000000019884624838656,
12
+ "model_specific_special_tokens": {
13
+ "image_end_token": "<|hy_place▁holder▁no▁101|>",
14
+ "image_start_token": "<|hy_place▁holder▁no▁100|>",
15
+ "image_token": "<|hy_place▁holder▁no▁102|>",
16
+ "video_end_token": "<|hy_place▁holder▁no▁105|>",
17
+ "video_start_token": "<|hy_place▁holder▁no▁104|>",
18
+ "video_token": "<|hy_place▁holder▁no▁665|>"
19
+ },
20
+ "pad_token": "<|hy_▁pad▁|>",
21
+ "processor_class": "HunYuanVLProcessor",
22
+ "tokenizer_class": "TokenizersBackend",
23
+ "video_end_token": "<|hy_place▁holder▁no▁105|>",
24
+ "video_start_token": "<|hy_place▁holder▁no▁104|>",
25
+ "video_token": "<|hy_place▁holder▁no▁665|>"
26
+ }
generation_config.json CHANGED
@@ -1,13 +1,7 @@
1
  {
 
2
  "bos_token_id": 120000,
 
3
  "pad_token_id": 120002,
4
- "do_sample": true,
5
- "eos_token_id": [
6
- 120007,
7
- 120020
8
- ],
9
- "repetition_penalty": 1.03,
10
- "top_k": 1,
11
- "top_p": 1.0,
12
- "temperature":0.0
13
  }
 
1
  {
2
+ "_from_model_config": true,
3
  "bos_token_id": 120000,
4
+ "eos_token_id": 120020,
5
  "pad_token_id": 120002,
6
+ "transformers_version": "4.57.1"
 
 
 
 
 
 
 
 
7
  }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:632a1e082c4dd5a3284cf1ffcdba2fdaa06f435762c58c2f34aff0f3bd6c0249
3
+ size 2239932512
preprocessor_config.json CHANGED
@@ -1,20 +1,29 @@
1
  {
2
- "min_pixels": 262144,
3
- "max_pixels": 4194304,
4
- "patch_size": 16,
5
- "resample": 1,
6
- "temporal_patch_size": 1,
7
- "merge_size": 2,
8
  "image_mean": [
9
  0.48145466,
10
  0.4578275,
11
  0.40821073
12
  ],
 
13
  "image_std": [
14
  0.26862954,
15
  0.26130258,
16
  0.27577711
17
  ],
18
- "image_processor_type": "HunYuanVLImageProcessor",
19
- "processor_class": "HunYuanVLProcessor"
 
 
 
 
 
 
 
 
 
 
20
  }
 
1
  {
2
+ "do_convert_rgb": true,
3
+ "do_normalize": true,
4
+ "do_rescale": true,
5
+ "do_resize": true,
 
 
6
  "image_mean": [
7
  0.48145466,
8
  0.4578275,
9
  0.40821073
10
  ],
11
+ "image_processor_type": "HunYuanVLImageProcessor",
12
  "image_std": [
13
  0.26862954,
14
  0.26130258,
15
  0.27577711
16
  ],
17
+ "max_pixels": 16777216,
18
+ "merge_size": 2,
19
+ "min_pixels": 262144,
20
+ "patch_size": 16,
21
+ "processor_class": "HunYuanVLProcessor",
22
+ "resample": 1,
23
+ "rescale_factor": 0.00392156862745098,
24
+ "size": {
25
+ "longest_edge": 4194304,
26
+ "shortest_edge": 262144
27
+ },
28
+ "temporal_patch_size": 1
29
  }
special_tokens_map.json CHANGED
@@ -1,5 +1,29 @@
1
  {
2
- "bos_token": "<|hy_begin▁of▁sentence|>",
3
- "eos_token": "<|hy_placeholderno▁2|>",
4
- "pad_token": "<|hy_▁pad▁|>"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  }
 
1
  {
2
+ "bos_token": {
3
+ "content": "<|hy_beginofsentence|>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|hy_Assistant|>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "image_end_token": "<|hy_place▁holder▁no▁101|>",
17
+ "image_start_token": "<|hy_place▁holder▁no▁100|>",
18
+ "image_token": "<|hy_place▁holder▁no▁102|>",
19
+ "pad_token": {
20
+ "content": "<|hy_▁pad▁|>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false
25
+ },
26
+ "video_end_token": "<|hy_place▁holder▁no▁105|>",
27
+ "video_start_token": "<|hy_place▁holder▁no▁104|>",
28
+ "video_token": "<|hy_place▁holder▁no▁665|>"
29
  }
tokenizer.json CHANGED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json CHANGED
@@ -6548,15 +6548,22 @@
6548
  "bos_token": "<|hy_begin▁of▁sentence|>",
6549
  "clean_up_tokenization_spaces": true,
6550
  "eos_token": "<|hy_Assistant|>",
6551
- "model_max_length": 1000000000000000019884624838656,
6552
- "pad_token": "<|hy_▁pad▁|>",
6553
  "extra_special_tokens": {
6554
- "image_token": "<|hy_place▁holder▁no▁102|>",
6555
- "image_start_token": "<|hy_place▁holder▁no▁100|>",
6556
  "image_end_token": "<|hy_place▁holder▁no▁101|>",
 
 
 
6557
  "video_start_token": "<|hy_place▁holder▁no▁104|>",
6558
- "video_end_token": "<|hy_place▁holder▁no▁105|>"
6559
  },
 
 
 
 
 
 
6560
  "tokenizer_class": "PreTrainedTokenizerFast",
6561
- "chat_template": "{% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}{% if messages[0]['content'] is string %}{% set system_message = messages[0]['content'] %}{% else %}{% set system_message = messages[0]['content']['text'] %}{% endif %}<|hy_begin▁of▁sentence|>{{ system_message }}<|hy_place▁holder▁no▁3|>{% else %}{% set loop_messages = messages %}<|hy_begin▁of▁sentence|>{% endif %}{% for message in loop_messages %}{% if message['role'] == 'user' %}{% if message['content'] is string %}{{ message['content'] }}{% else %}{% for content in message['content'] %}{% if content['type'] == 'image' or 'image' in content or 'image_url' in content %}<|hy_place▁holder▁no▁100|><|hy_place▁holder▁no▁102|><|hy_place▁holder▁no▁101|>{% elif 'text' in content %}{{ content['text'] }}{% endif %}{% endfor %}{% endif %}<|hy_User|>{% elif message['role'] == 'assistant' %}{{ message['content'] }}<|hy_Assistant|>{% endif %}{% endfor %}"
 
 
6562
  }
 
6548
  "bos_token": "<|hy_begin▁of▁sentence|>",
6549
  "clean_up_tokenization_spaces": true,
6550
  "eos_token": "<|hy_Assistant|>",
 
 
6551
  "extra_special_tokens": {
 
 
6552
  "image_end_token": "<|hy_place▁holder▁no▁101|>",
6553
+ "image_start_token": "<|hy_place▁holder▁no▁100|>",
6554
+ "image_token": "<|hy_place▁holder▁no▁102|>",
6555
+ "video_end_token": "<|hy_place▁holder▁no▁105|>",
6556
  "video_start_token": "<|hy_place▁holder▁no▁104|>",
6557
+ "video_token": "<|hy_place▁holder▁no▁665|>"
6558
  },
6559
+ "image_end_token": "<|hy_place▁holder▁no▁101|>",
6560
+ "image_start_token": "<|hy_place▁holder▁no▁100|>",
6561
+ "image_token": "<|hy_place▁holder▁no▁102|>",
6562
+ "model_max_length": 1000000000000000019884624838656,
6563
+ "pad_token": "<|hy_▁pad▁|>",
6564
+ "processor_class": "HunYuanVLProcessor",
6565
  "tokenizer_class": "PreTrainedTokenizerFast",
6566
+ "video_end_token": "<|hy_place▁holder▁no▁105|>",
6567
+ "video_start_token": "<|hy_place▁holder▁no▁104|>",
6568
+ "video_token": "<|hy_place▁holder▁no▁665|>"
6569
  }
v1.0/.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
.gitignore → v1.0/.gitignore RENAMED
File without changes
v1.0/LICENSE ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT
2
+ Tencent HunyuanOCR Release Date: November 25, 2025
3
+ THIS LICENSE AGREEMENT DOES NOT APPLY IN THE EUROPEAN UNION, UNITED KINGDOM AND SOUTH KOREA AND IS EXPRESSLY LIMITED TO THE TERRITORY, AS DEFINED BELOW.
4
+ By clicking to agree or by using, reproducing, modifying, distributing, performing or displaying any portion or element of the Tencent Hunyuan Works, including via any Hosted Service, You will be deemed to have recognized and accepted the content of this Agreement, which is effective immediately.
5
+ 1. DEFINITIONS.
6
+ a. “Acceptable Use Policy” shall mean the policy made available by Tencent as set forth in the Exhibit A.
7
+ b. “Agreement” shall mean the terms and conditions for use, reproduction, distribution, modification, performance and displaying of Tencent Hunyuan Works or any portion or element thereof set forth herein.
8
+ c. “Documentation” shall mean the specifications, manuals and documentation for Tencent Hunyuan made publicly available by Tencent.
9
+ d. “Hosted Service” shall mean a hosted service offered via an application programming interface (API), web access, or any other electronic or remote means.
10
+ e. “Licensee,” “You” or “Your” shall mean a natural person or legal entity exercising the rights granted by this Agreement and/or using the Tencent Hunyuan Works for any purpose and in any field of use.
11
+ f. “Materials” shall mean, collectively, Tencent’s proprietary Tencent Hunyuan and Documentation (and any portion thereof) as made available by Tencent under this Agreement.
12
+ g. “Model Derivatives” shall mean all: (i) modifications to Tencent Hunyuan or any Model Derivative of Tencent Hunyuan; (ii) works based on Tencent Hunyuan or any Model Derivative of Tencent Hunyuan; or (iii) any other machine learning model which is created by transfer of patterns of the weights, parameters, operations, or Output of Tencent Hunyuan or any Model Derivative of Tencent Hunyuan, to that model in order to cause that model to perform similarly to Tencent Hunyuan or a Model Derivative of Tencent Hunyuan, including distillation methods, methods that use intermediate data representations, or methods based on the generation of synthetic data Outputs by Tencent Hunyuan or a Model Derivative of Tencent Hunyuan for training that model. For clarity, Outputs by themselves are not deemed Model Derivatives.
13
+ h. “Output” shall mean the information and/or content output of Tencent Hunyuan or a Model Derivative that results from operating or otherwise using Tencent Hunyuan or a Model Derivative, including via a Hosted Service.
14
+ i. “Tencent,” “We” or “Us” shall mean the applicable entity or entities in the Tencent corporate family that own(s) intellectual property or other rights embodied in or utilized by the Materials.
15
+ j. “Tencent Hunyuan” shall mean the large language models, text/image/video/audio/3D generation models, and multimodal large language models and their software and algorithms, including trained model weights, parameters (including optimizer states), machine-learning model code, inference-enabling code, training-enabling code, fine-tuning enabling code and other elements of the foregoing made publicly available by Us, including, without limitation to, Tencent HunyuanOCR released at [https://huggingface.co/tencent/HunyuanOCR].
16
+ k. “Tencent Hunyuan Works” shall mean: (i) the Materials; (ii) Model Derivatives; and (iii) all derivative works thereof.
17
+ l. “Territory” shall mean the worldwide territory, excluding the territory of the European Union, United Kingdom and South Korea.
18
+ m. “Third Party” or “Third Parties” shall mean individuals or legal entities that are not under common control with Us or You.
19
+ n. “including” shall mean including but not limited to.
20
+ 2. GRANT OF RIGHTS.
21
+ We grant You, for the Territory only, a non-exclusive, non-transferable and royalty-free limited license under Tencent’s intellectual property or other rights owned by Us embodied in or utilized by the Materials to use, reproduce, distribute, create derivative works of (including Model Derivatives), and make modifications to the Materials, only in accordance with the terms of this Agreement and the Acceptable Use Policy, and You must not violate (or encourage or permit anyone else to violate) any term of this Agreement or the Acceptable Use Policy.
22
+ 3. DISTRIBUTION.
23
+ You may, subject to Your compliance with this Agreement, distribute or make available to Third Parties the Tencent Hunyuan Works, exclusively in the Territory, provided that You meet all of the following conditions:
24
+ a. You must provide all such Third Party recipients of the Tencent Hunyuan Works or products or services using them a copy of this Agreement;
25
+ b. You must cause any modified files to carry prominent notices stating that You changed the files;
26
+ c. You are encouraged to: (i) publish at least one technology introduction blogpost or one public statement expressing Your experience of using the Tencent Hunyuan Works; and (ii) mark the products or services developed by using the Tencent Hunyuan Works to indicate that the product/service is “Powered by Tencent Hunyuan”; and
27
+ d. All distributions to Third Parties (other than through a Hosted Service) must be accompanied by a “Notice” text file that contains the following notice: “Tencent Hunyuan is licensed under the Tencent Hunyuan Community License Agreement, Copyright © 2025 Tencent. All Rights Reserved. The trademark rights of “Tencent Hunyuan” are owned by Tencent or its affiliate.”
28
+ e. In the event that You use, integrate, implement, or otherwise deploy the Tencent Hunyuan Works, in whole or in part, to provide, enable, or support any service, product, or functionality to third parties, You shall clearly, accurately, and prominently disclose to all end users the full legal name and entity of the actual provider of such service, product, or functionality. You shall expressly and conspicuously state that Tencent is not affiliated with, associated with, sponsoring, or endorsing any such service, product, or functionality. You shall not use or display any name, logo, trademark, trade name, or other indicia of Tencent in any manner that could be construed as, or be likely to create, confusion, deception, or a false impression regarding any relationship, affiliation, sponsorship, or endorsement by Tencent.
29
+ You may add Your own copyright statement to Your modifications and, except as set forth in this Section and in Section 5, may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Model Derivatives as a whole, provided Your use, reproduction, modification, distribution, performance and display of the work otherwise complies with the terms and conditions of this Agreement (including as regards the Territory). If You receive Tencent Hunyuan Works from a Licensee as part of an integrated end user product, then this Section 3 of this Agreement will not apply to You.
30
+ 4. ADDITIONAL COMMERCIAL TERMS.
31
+ If, on the Tencent Hunyuan version release date, the monthly active users of all products or services made available by or for Licensee is greater than 100 million monthly active users in the preceding calendar month, You must request a license from Tencent, which Tencent may grant to You in its sole discretion, and You are not authorized to exercise any of the rights under this Agreement unless or until Tencent otherwise expressly grants You such rights.
32
+ 5. RULES OF USE.
33
+ a. Your use of the Tencent Hunyuan Works must comply with applicable laws and regulations (including trade compliance laws and regulations) and adhere to the Acceptable Use Policy for the Tencent Hunyuan Works, which is hereby incorporated by reference into this Agreement. You must include the use restrictions referenced in these Sections 5(a) and 5(b) as an enforceable provision in any agreement (e.g., license agreement, terms of use, etc.) governing the use and/or distribution of Tencent Hunyuan Works and You must provide notice to subsequent users to whom You distribute that Tencent Hunyuan Works are subject to the use restrictions in these Sections 5(a) and 5(b).
34
+ b. You must not use the Tencent Hunyuan Works or any Output or results of the Tencent Hunyuan Works to improve any other AI model (other than Tencent Hunyuan or Model Derivatives thereof).
35
+ c. You must not use, reproduce, modify, distribute, or display the Tencent Hunyuan Works, Output or results of the Tencent Hunyuan Works outside the Territory. Any such use outside the Territory is unlicensed and unauthorized under this Agreement.
36
+ 6. INTELLECTUAL PROPERTY.
37
+ a. Subject to Tencent’s ownership of Tencent Hunyuan Works made by or for Tencent and intellectual property rights therein, conditioned upon Your compliance with the terms and conditions of this Agreement, as between You and Tencent, You will be the owner of any derivative works and modifications of the Materials and any Model Derivatives that are made by or for You.
38
+ b. No trademark licenses are granted under this Agreement, and in connection with the Tencent Hunyuan Works, Licensee may not use any name or mark owned by or associated with Tencent or any of its affiliates, except as required for reasonable and customary use in describing and distributing the Tencent Hunyuan Works. Tencent hereby grants You a license to use “Tencent Hunyuan” (the “Mark”) in the Territory solely as required to comply with the provisions of Section 3(c), provided that You comply with any applicable laws related to trademark protection. All goodwill arising out of Your use of the Mark will inure to the benefit of Tencent.
39
+ c. If You commence a lawsuit or other proceedings (including a cross-claim or counterclaim in a lawsuit) against Us or any person or entity alleging that the Materials or any Output, or any portion of any of the foregoing, infringe any intellectual property or other right owned or licensable by You, then all licenses granted to You under this Agreement shall terminate as of the date such lawsuit or other proceeding is filed. You will defend, indemnify and hold harmless Us from and against any claim by any Third Party arising out of or related to Your or the Third Party’s use or distribution of the Tencent Hunyuan Works.
40
+ d. Tencent claims no rights in Outputs You generate. You and Your users are solely responsible for Outputs and their subsequent uses.
41
+ 7. DISCLAIMERS OF WARRANTY AND LIMITATIONS OF LIABILITY.
42
+ a. We are not obligated to support, update, provide training for, or develop any further version of the Tencent Hunyuan Works or to grant any license thereto.
43
+ b. UNLESS AND ONLY TO THE EXTENT REQUIRED BY APPLICABLE LAW, THE TENCENT HUNYUAN WORKS AND ANY OUTPUT AND RESULTS THEREFROM ARE PROVIDED “AS IS” WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES OF ANY KIND INCLUDING ANY WARRANTIES OF TITLE, MERCHANTABILITY, NONINFRINGEMENT, COURSE OF DEALING, USAGE OF TRADE, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USING, REPRODUCING, MODIFYING, PERFORMING, DISPLAYING OR DISTRIBUTING ANY OF THE TENCENT HUNYUAN WORKS OR OUTPUTS AND ASSUME ANY AND ALL RISKS ASSOCIATED WITH YOUR OR A THIRD PARTY’S USE OR DISTRIBUTION OF ANY OF THE TENCENT HUNYUAN WORKS OR OUTPUTS AND YOUR EXERCISE OF RIGHTS AND PERMISSIONS UNDER THIS AGREEMENT.
44
+ c. TO THE FULLEST EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL TENCENT OR ITS AFFILIATES BE LIABLE UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, EXEMPLARY, CONSEQUENTIAL OR PUNITIVE DAMAGES, OR LOST PROFITS OF ANY KIND ARISING FROM THIS AGREEMENT OR RELATED TO ANY OF THE TENCENT HUNYUAN WORKS OR OUTPUTS, EVEN IF TENCENT OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF ANY OF THE FOREGOING.
45
+ 8. SURVIVAL AND TERMINATION.
46
+ a. The term of this Agreement shall commence upon Your acceptance of this Agreement or access to the Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein.
47
+ b. We may terminate this Agreement if You breach any of the terms or conditions of this Agreement. Upon termination of this Agreement, You must promptly delete and cease use of the Tencent Hunyuan Works. Sections 6(a), 6(c), 7 and 9 shall survive the termination of this Agreement.
48
+ 9. GOVERNING LAW AND JURISDICTION.
49
+ a. This Agreement and any dispute arising out of or relating to it will be governed by the laws of the Hong Kong Special Administrative Region of the People’s Republic of China, without regard to conflict of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement.
50
+ b. Exclusive jurisdiction and venue for any dispute arising out of or relating to this Agreement will be a court of competent jurisdiction in the Hong Kong Special Administrative Region of the People’s Republic of China, and Tencent and Licensee consent to the exclusive jurisdiction of such court with respect to any such dispute.
51
+
52
+ EXHIBIT A
53
+ ACCEPTABLE USE POLICY
54
+
55
+ Tencent reserves the right to update this Acceptable Use Policy from time to time.
56
+ Last modified: November 5, 2024
57
+
58
+ Tencent endeavors to promote safe and fair use of its tools and features, including Tencent Hunyuan. You agree not to use Tencent Hunyuan or Model Derivatives:
59
+ 1. Outside the Territory;
60
+ 2. In any way that violates any applicable national, federal, state, local, international or any other law or regulation;
61
+ 3. To harm Yourself or others;
62
+ 4. To repurpose or distribute output from Tencent Hunyuan or any Model Derivatives to harm Yourself or others;
63
+ 5. To override or circumvent the safety guardrails and safeguards We have put in place;
64
+ 6. For the purpose of exploiting, harming or attempting to exploit or harm minors in any way;
65
+ 7. To generate or disseminate verifiably false information and/or content with the purpose of harming others or influencing elections;
66
+ 8. To generate or facilitate false online engagement, including fake reviews and other means of fake online engagement;
67
+ 9. To intentionally defame, disparage or otherwise harass others;
68
+ 10. To generate and/or disseminate malware (including ransomware) or any other content to be used for the purpose of harming electronic systems;
69
+ 11. To generate or disseminate personal identifiable information with the purpose of harming others;
70
+ 12. To generate or disseminate information (including images, code, posts, articles), and place the information in any public context (including –through the use of bot generated tweets), without expressly and conspicuously identifying that the information and/or content is machine generated;
71
+ 13. To impersonate another individual without consent, authorization, or legal right;
72
+ 14. To make high-stakes automated decisions in domains that affect an individual’s safety, rights or wellbeing (e.g., law enforcement, migration, medicine/health, management of critical infrastructure, safety components of products, essential services, credit, employment, housing, education, social scoring, or insurance);
73
+ 15. In a manner that violates or disrespects the social ethics and moral standards of other countries or regions;
74
+ 16. To perform, facilitate, threaten, incite, plan, promote or encourage violent extremism or terrorism;
75
+ 17. For any use intended to discriminate against or harm individuals or groups based on protected characteristics or categories, online or offline social behavior or known or predicted personal or personality characteristics;
76
+ 18. To intentionally exploit any of the vulnerabilities of a specific group of persons based on their age, social, physical or mental characteristics, in order to materially distort the behavior of a person pertaining to that group in a manner that causes or is likely to cause that person or another person physical or psychological harm;
77
+ 19. For military purposes;
78
+ 20. To engage in the unauthorized or unlicensed practice of any profession including, but not limited to, financial, legal, medical/health, or other professional practices.
v1.0/README.md ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ language:
4
+ - multilingual
5
+ pipeline_tag: image-text-to-text
6
+ library_name: transformers
7
+ base_model:
8
+ - tencent/HunyuanOCR
9
+ tags:
10
+ - ocr
11
+ - hunyuan
12
+ - vision-language
13
+ - image-to-text
14
+ - 1B
15
+ - end-to-end
16
+ ---
17
+
18
+ <p align="center">
19
+ <img src="https://github.com/Tencent-Hunyuan/HunyuanOCR/blob/main/assets/hyocr-head-img.png?raw=true" width="80%"/> <br>
20
+ </p>
21
+
22
+
23
+ <p align="center">
24
+ <a href="https://hunyuan.tencent.com/chat/HunyuanDefault?modelId=HY-OCR-1.0&mid=308&from=vision-zh"><b>🎯 Demo</b></a> |
25
+ <a href="https://huggingface.co/tencent/HunyuanOCR"><b>📥 Model Download</b></a> |
26
+ <a href="https://arxiv.org/abs/2511.19575"><b>📄 Technical Report</b></a> |
27
+ <a href="https://github.com/Tencent-Hunyuan/HunyuanOCR"><b>🌟 Github</b></a>
28
+ </p>
29
+
30
+ <h2>
31
+ <p align="center">
32
+ <a href="https://arxiv.org/abs/2511.19575">HunyuanOCR</a>
33
+ </p>
34
+ </h2>
35
+
36
+
37
+ ## 📖 Introduction
38
+ **HunyuanOCR** stands as a leading end-to-end OCR expert VLM powered by Hunyuan's native multimodal architecture. With a remarkably lightweight 1B parameter design, it has achieved multiple state-of-the-art benchmarks across the industry. The model demonstrates mastery in **complex multilingual document parsing** while excelling in practical applications including **text spotting, open-field information extraction, video subtitle extraction, and photo translation**.
39
+
40
+
41
+ ## 🚀 Quick Start with Transformers
42
+
43
+ ### Installation
44
+ ```bash
45
+ pip install git+https://github.com/huggingface/transformers@82a06db03535c49aa987719ed0746a76093b1ec4
46
+ ```
47
+ > **Note**: We will merge it into the Transformers main branch later.
48
+
49
+ ### Model Inference
50
+
51
+ ```python
52
+ from transformers import AutoProcessor
53
+ from transformers import HunYuanVLForConditionalGeneration
54
+ from PIL import Image
55
+ import torch
56
+
57
+ def clean_repeated_substrings(text):
58
+ """Clean repeated substrings in text"""
59
+ n = len(text)
60
+ if n<8000:
61
+ return text
62
+ for length in range(2, n // 10 + 1):
63
+ candidate = text[-length:]
64
+ count = 0
65
+ i = n - length
66
+
67
+ while i >= 0 and text[i:i + length] == candidate:
68
+ count += 1
69
+ i -= length
70
+
71
+ if count >= 10:
72
+ return text[:n - length * (count - 1)]
73
+
74
+ return text
75
+
76
+ model_name_or_path = "tencent/HunyuanOCR"
77
+ processor = AutoProcessor.from_pretrained(model_name_or_path, use_fast=False)
78
+ img_path = "path/to/your/image.jpg"
79
+ image_inputs = Image.open(img_path)
80
+ messages1 = [
81
+ {"role": "system", "content": ""},
82
+ {
83
+ "role": "user",
84
+ "content": [
85
+ {"type": "image", "image": img_path},
86
+ {"type": "text", "text": (
87
+ "检测并识别图片中的文字,将文本坐标格式化输出。"
88
+ )},
89
+ ],
90
+ }
91
+ ]
92
+ messages = [messages1]
93
+ texts = [
94
+ processor.apply_chat_template(msg, tokenize=False, add_generation_prompt=True)
95
+ for msg in messages
96
+ ]
97
+ inputs = processor(
98
+ text=texts,
99
+ images=image_inputs,
100
+ padding=True,
101
+ return_tensors="pt",
102
+ )
103
+ model = HunYuanVLForConditionalGeneration.from_pretrained(
104
+ model_name_or_path,
105
+ attn_implementation="eager",
106
+ dtype=torch.bfloat16,
107
+ device_map="auto"
108
+ )
109
+ with torch.no_grad():
110
+ device = next(model.parameters()).device
111
+ inputs = inputs.to(device)
112
+ generated_ids = model.generate(**inputs, max_new_tokens=16384, do_sample=False)
113
+ if "input_ids" in inputs:
114
+ input_ids = inputs.input_ids
115
+ else:
116
+ print("inputs: # fallback", inputs)
117
+ input_ids = inputs.inputs
118
+ generated_ids_trimmed = [
119
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(input_ids, generated_ids)
120
+ ]
121
+ output_texts = clean_repeated_substrings(processor.batch_decode(
122
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
123
+ ))
124
+ print(output_texts)
125
+ ```
126
+
127
+
128
+ ## 🚀 Quick Start with vLLM
129
+
130
+ Checkout [vLLM HunyuanOCR Usage Guide](https://docs.vllm.ai/projects/recipes/en/latest/Tencent-Hunyuan/HunyuanOCR.html).
131
+
132
+ ### Installation
133
+
134
+ ```bash
135
+ uv venv hunyuanocr
136
+ source hunyuanocr/bin/activate
137
+
138
+ uv pip install -U vllm --pre --extra-index-url https://wheels.vllm.ai/nightly
139
+ ```
140
+
141
+ Note: We suggest to install [cuda-compat-12-9](https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2404/x86_64/):
142
+ ```bash
143
+ sudo dpkg -i cuda-compat-12-9_575.57.08-0ubuntu1_amd64.deb
144
+ echo 'export LD_LIBRARY_PATH=/usr/local/cuda-12.9/compat:$LD_LIBRARY_PATH' >> ~/.bashrc
145
+ source ~/.bashrc
146
+ # verify cuda-compat-12-9
147
+ ls /usr/local/cuda-12.9/compat
148
+ ```
149
+
150
+ ### Model Deploy
151
+ ```bash
152
+ vllm serve tencent/HunyuanOCR \
153
+ --no-enable-prefix-caching \
154
+ --mm-processor-cache-gb 0 \
155
+ --gpu-memory-utilization 0.2
156
+ ```
157
+
158
+ ### Model Inference
159
+ ```python
160
+ from vllm import LLM, SamplingParams
161
+ from PIL import Image
162
+ from transformers import AutoProcessor
163
+
164
+ def clean_repeated_substrings(text):
165
+ """Clean repeated substrings in text"""
166
+ n = len(text)
167
+ if n<8000:
168
+ return text
169
+ for length in range(2, n // 10 + 1):
170
+ candidate = text[-length:]
171
+ count = 0
172
+ i = n - length
173
+
174
+ while i >= 0 and text[i:i + length] == candidate:
175
+ count += 1
176
+ i -= length
177
+
178
+ if count >= 10:
179
+ return text[:n - length * (count - 1)]
180
+
181
+ return text
182
+
183
+ model_path = "tencent/HunyuanOCR"
184
+ llm = LLM(model=model_path, trust_remote_code=True)
185
+ processor = AutoProcessor.from_pretrained(model_path)
186
+ sampling_params = SamplingParams(temperature=0, max_tokens=16384)
187
+
188
+ img_path = "/path/to/image.jpg"
189
+ img = Image.open(img_path)
190
+ messages = [
191
+ {"role": "system", "content": ""},
192
+ {"role": "user", "content": [
193
+ {"type": "image", "image": img_path},
194
+ {"type": "text", "text": "检测并识别图片中的文字,将文本坐标格式化输出。"}
195
+ ]}
196
+ ]
197
+ prompt = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
198
+ inputs = {"prompt": prompt, "multi_modal_data": {"image": [img]}}
199
+ output = llm.generate([inputs], sampling_params)[0]
200
+ print(clean_repeated_substrings(output.outputs[0].text))
201
+ ```
202
+
203
+ ## 💬 Application-oriented Prompts
204
+
205
+ | Task | Prompt |
206
+ |------|---------|
207
+ | **Spotting** | 检测并识别图片中的文字,将文本坐标格式化输出。 |
208
+ | **Document Parsing** | • 识别图片中的公式,用LaTeX格式表示。<br><br>• 把图中的表格解析为HTML。<br><br>• 解析图中的图表,对于流程图使用Mermaid格式表示,其他图表使用Markdown格式表示。<br><br>• 提取文档图片中正文的所有信息用markdown格式表示,其中页眉、页脚部分忽略,表格用html格式表达,文档中公式用latex格式表示,按照阅读顺序组织进行解析。|
209
+ | **General Parsing** | • 提取图中的文字。|
210
+ | **Information Extraction** | • 输出Key的值。<br><br>• 提取图片中的: ['key1','key2', ...] 的字段内容,并按照JSON格式返回。<br><br>• 提取图中的字幕 |
211
+ | **Translation** | 先提取文字,再将文字内容翻译为英文。若是文档,则其中页眉、页脚忽略。公式用latex格式表示,表格用html格式表示。 |
212
+
213
+ ## 🤝 Join Our Community
214
+
215
+ <div align="center">
216
+
217
+ | Wechat Discussion Group | Discord Group |
218
+ | :---: | :---: |
219
+ | <img src="https://github.com/Tencent-Hunyuan/HunyuanOCR/blob/main/assets/qrcode_for_hunyuanocr_wechat.jpg?raw=true" width="150"> | [Join HunyuanOCR Discord](https://discord.gg/XeD3p2MRDk) |
220
+
221
+ </div>
222
+
223
+ ## 📚 Citation
224
+ ```
225
+ @misc{hunyuanvisionteam2025hunyuanocrtechnicalreport,
226
+ title={HunyuanOCR Technical Report},
227
+ author={Hunyuan Vision Team and Pengyuan Lyu and Xingyu Wan and Gengluo Li and Shangpin Peng and Weinong Wang and Liang Wu and Huawen Shen and Yu Zhou and Canhui Tang and Qi Yang and Qiming Peng and Bin Luo and Hower Yang and Xinsong Zhang and Jinnian Zhang and Houwen Peng and Hongming Yang and Senhao Xie and Longsha Zhou and Ge Pei and Binghong Wu and Kan Wu and Jieneng Yang and Bochao Wang and Kai Liu and Jianchen Zhu and Jie Jiang and Linus and Han Hu and Chengquan Zhang},
228
+ year={2025},
229
+ journal={arXiv preprint arXiv:2511.19575},
230
+ url={https://arxiv.org/abs/2511.19575},
231
+ }
232
+ ```
233
+
234
+ ## 🙏 Acknowledgements
235
+ We would like to thank [PaddleOCR](https://github.com/PaddlePaddle/PaddleOCR), [MinerU](https://github.com/opendatalab/MinerU), [MonkeyOCR](https://github.com/Yuliang-Liu/MonkeyOCR), [DeepSeek-OCR](https://github.com/deepseek-ai/DeepSeek-OCR), [dots.ocr](https://github.com/rednote-hilab/dots.ocr) for their valuable models and ideas.
236
+ We also appreciate the benchmarks: [OminiDocBench](https://github.com/opendatalab/OmniDocBench), [OCRBench](https://github.com/Yuliang-Liu/MultimodalOCR/tree/main/OCRBench), [DoTA](https://github.com/liangyupu/DIMTDA).
v1.0/config.json ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "HunYuanVLForConditionalGeneration"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "attention_head_dim": 128,
8
+ "bos_token_id": 120000,
9
+ "eod_token_id": 120020,
10
+ "eos_token_id": 120020,
11
+ "head_dim": 128,
12
+ "hidden_act": "silu",
13
+ "hidden_size": 1024,
14
+ "image_start_token_id": 120118,
15
+ "image_end_token_id": 120119,
16
+ "image_token_id": 120120,
17
+ "image_newline_token_id": 120121,
18
+ "initializer_range": 0.02,
19
+ "intermediate_size": 3584,
20
+ "max_position_embeddings": 32768,
21
+ "mlp_bias": false,
22
+ "model_type": "hunyuan_vl",
23
+ "norm_type": "rms",
24
+ "num_attention_heads": 16,
25
+ "num_experts": 1,
26
+ "num_hidden_layers": 24,
27
+ "num_key_value_heads": 8,
28
+ "org_vocab_size": 120818,
29
+ "pad_id": 120002,
30
+ "pad_token_id": -1,
31
+ "pretraining_tp": 1,
32
+ "rms_norm_eps": 1e-05,
33
+ "rope_scaling": {
34
+ "alpha": 1000.0,
35
+ "beta_fast": 32,
36
+ "beta_slow": 1,
37
+ "factor": 1.0,
38
+ "mscale": 1.0,
39
+ "mscale_all_dim": 1.0,
40
+ "type": "xdrope",
41
+ "xdrope_section": [
42
+ 16,
43
+ 16,
44
+ 16,
45
+ 16
46
+ ]
47
+ },
48
+ "rope_theta": 10000.0,
49
+ "routed_scaling_factor": 1.0,
50
+ "sep_token_id": 0,
51
+ "text_end_id": 8,
52
+ "text_start_id": 7,
53
+ "tie_word_embeddings": true,
54
+ "dtype": "bfloat16",
55
+ "transformers_version": "4.49.0",
56
+ "use_cache": true,
57
+ "use_qk_norm": true,
58
+ "use_cla": false,
59
+ "vision_config": {
60
+ "add_patchemb_bias": true,
61
+ "attention_dropout": 0.0,
62
+ "cat_extra_token": 1,
63
+ "hidden_act": "gelu",
64
+ "hidden_dropout": 0.0,
65
+ "hidden_size": 1152,
66
+ "img_max_token_num": 4096,
67
+ "intermediate_size": 4304,
68
+ "interpolate_mode": "bilinear",
69
+ "max_image_size": 2048,
70
+ "max_vit_seq_len": 16384,
71
+ "num_attention_heads": 16,
72
+ "num_channels": 3,
73
+ "num_hidden_layers": 27,
74
+ "out_hidden_size": 1024,
75
+ "patch_size": 16,
76
+ "rms_norm_eps": 1e-05,
77
+ "spatial_merge_size": 2
78
+ },
79
+ "vocab_size": 120818
80
+ }
v1.0/generation_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 120000,
3
+ "pad_token_id": 120002,
4
+ "do_sample": true,
5
+ "eos_token_id": [
6
+ 120007,
7
+ 120020
8
+ ],
9
+ "repetition_penalty": 1.03,
10
+ "top_k": 1,
11
+ "top_p": 1.0,
12
+ "temperature":0.0
13
+ }
model-00001-of-00004.safetensors → v1.0/model-00001-of-00004.safetensors RENAMED
File without changes
model-00002-of-00004.safetensors → v1.0/model-00002-of-00004.safetensors RENAMED
File without changes
model-00003-of-00004.safetensors → v1.0/model-00003-of-00004.safetensors RENAMED
File without changes
model-00004-of-00004.safetensors → v1.0/model-00004-of-00004.safetensors RENAMED
File without changes
model.safetensors.index.json → v1.0/model.safetensors.index.json RENAMED
File without changes
v1.0/preprocessor_config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "min_pixels": 262144,
3
+ "max_pixels": 4194304,
4
+ "patch_size": 16,
5
+ "resample": 1,
6
+ "temporal_patch_size": 1,
7
+ "merge_size": 2,
8
+ "image_mean": [
9
+ 0.48145466,
10
+ 0.4578275,
11
+ 0.40821073
12
+ ],
13
+ "image_std": [
14
+ 0.26862954,
15
+ 0.26130258,
16
+ 0.27577711
17
+ ],
18
+ "image_processor_type": "HunYuanVLImageProcessor",
19
+ "processor_class": "HunYuanVLProcessor"
20
+ }
v1.0/special_tokens_map.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "<|hy_begin▁of▁sentence|>",
3
+ "eos_token": "<|hy_place▁holder▁no▁2|>",
4
+ "pad_token": "<|hy_▁pad▁|>"
5
+ }
v1.0/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
v1.0/tokenizer_config.json ADDED
The diff for this file is too large to render. See raw diff
 
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": 4194304,
26
+ "merge_size": 2,
27
+ "min_frames": 4,
28
+ "min_pixels": 262144,
29
+ "num_frames": null,
30
+ "pad_size": null,
31
+ "patch_size": 16,
32
+ "processor_class": "HunYuanVLProcessor",
33
+ "resample": 3,
34
+ "rescale_factor": 0.00392156862745098,
35
+ "return_metadata": false,
36
+ "size": {
37
+ "longest_edge": 4194304,
38
+ "shortest_edge": 262144
39
+ },
40
+ "temporal_patch_size": 1,
41
+ "video_metadata": null,
42
+ "video_processor_type": "HunYuanVLVideoProcessor"
43
+ }