flow3rdown commited on
Commit
e096bf2
·
verified ·
1 Parent(s): c64408c

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ assets/architecture.png filter=lfs diff=lfs merge=lfs -text
37
+ assets/overview.png filter=lfs diff=lfs merge=lfs -text
38
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ __pycache__/
2
+ *.py[cod]
3
+ .cache/
4
+ *.log
README.md CHANGED
@@ -1,3 +1,166 @@
1
  ---
2
- license: apache-2.0
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ library_name: transformers
3
+ pipeline_tag: image-text-to-text
4
+ language:
5
+ - en
6
+ - zh
7
+ tags:
8
+ - ocr
9
+ - document-parsing
10
+ - vision-language-model
11
+ - formula-recognition
12
+ - table-recognition
13
+ - speculative-decoding
14
+ - ptp2
15
+ - vllm
16
  ---
17
+
18
+ <div align="center">
19
+
20
+ # VenusOCR 2.0
21
+
22
+ ### Towards Efficient and Effective Document Parsing
23
+
24
+ [![GitHub](https://img.shields.io/badge/GitHub-VenusOCR-181717?logo=github)](https://github.com/flow3rdown/VenusOCR)
25
+ [![Paper](https://img.shields.io/badge/Paper-Coming%20Soon-b31b1b?logo=arxiv)](#citation)
26
+
27
+ </div>
28
+
29
+ **VenusOCR 2.0** is a 1B vision-language OCR model built for high-accuracy document recognition. It supports both standard autoregressive inference and optional **PTPv2** parallel speculative decoding for faster lossless generation.
30
+
31
+ This repository hosts the **region-level recognition weights**. For full-page PDF/image parsing (layout detection, reading-order recovery, and Markdown export), please use the companion [**VenusOCR SDK**](https://github.com/flow3rdown/VenusOCR).
32
+
33
+ <div align="center">
34
+ <img src="assets/overview.png" alt="VenusOCR 2.0 Overview" width="100%">
35
+ </div>
36
+
37
+ ## Highlights
38
+
39
+ - **Unified Region Recognition:** Recognizes multi-column text, LaTeX mathematical formulas, and complex tables.
40
+ - **Compact & Fast:** Lightweight 1B-class recognizer designed for efficient single-GPU deployment.
41
+ - **Optional PTPv2 Acceleration:** Bundled parallel draft module (`ptp2/`) enables lossless speedup in vLLM serving.
42
+
43
+ ## Architecture
44
+
45
+ <div align="center">
46
+ <img src="assets/architecture.png" alt="VenusOCR 2.0 Architecture" width="100%">
47
+ </div>
48
+
49
+ ## Usage
50
+
51
+ ### 1. Transformers Inference
52
+
53
+ Install dependencies (pinned `transformers==5.5.4` is recommended):
54
+
55
+ ```bash
56
+ pip install transformers==5.5.4
57
+ ```
58
+
59
+ Run quick inference on a cropped document region image:
60
+
61
+ ```bash
62
+ python scripts/infer_transformers.py --image /path/to/region.png --task text
63
+ ```
64
+
65
+ Or load directly in Python:
66
+
67
+ ```python
68
+ import torch
69
+ from PIL import Image
70
+ from transformers import AutoModelForCausalLM, AutoProcessor
71
+
72
+ model_path = "./VenusOCR2-1B"
73
+ processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
74
+ model = AutoModelForCausalLM.from_pretrained(
75
+ model_path,
76
+ dtype=torch.bfloat16,
77
+ attn_implementation="sdpa",
78
+ trust_remote_code=True,
79
+ ).to("cuda:0").eval()
80
+
81
+ image = Image.open("/path/to/region.png").convert("RGB")
82
+ messages = [
83
+ {
84
+ "role": "user",
85
+ "content": [
86
+ {"type": "image"},
87
+ {"type": "text", "text": "Text Recognition:"},
88
+ ],
89
+ }
90
+ ]
91
+ prompt = processor.apply_chat_template(
92
+ messages, tokenize=False, add_generation_prompt=True
93
+ )
94
+ inputs = processor(images=image, text=prompt, return_tensors="pt").to(model.device)
95
+
96
+ with torch.inference_mode():
97
+ output_ids = model.generate(**inputs, max_new_tokens=2048, do_sample=False)
98
+
99
+ generated_ids = output_ids[:, inputs["input_ids"].shape[1]:]
100
+ print(processor.batch_decode(generated_ids, skip_special_tokens=True)[0])
101
+ ```
102
+
103
+ #### Task Prompts
104
+
105
+ | Task | Prompt | Output Format |
106
+ | --- | --- | --- |
107
+ | Text | `Text Recognition:` | Plain text / Markdown |
108
+ | Formula | `Formula Recognition:` | LaTeX |
109
+ | Table | `Table Recognition:` | OTSL structure |
110
+
111
+ ### 2. vLLM
112
+
113
+ #### Standard Mode (AR)
114
+
115
+ If you have the [VenusOCR SDK](https://github.com/flow3rdown/VenusOCR) installed, launch the OpenAI-compatible server directly:
116
+
117
+ ```bash
118
+ venusocr serve ./VenusOCR2-1B --host 127.0.0.1 --port 8000
119
+ ```
120
+
121
+ Or launch standalone without the SDK (using `vllm==0.20.0` and `transformers==5.5.4`):
122
+
123
+ ```bash
124
+ pip install "vllm==0.20.0" "transformers==5.5.4"
125
+ bash scripts/patch_vllm_v0_20_ptp2.sh
126
+ USE_PTP2=0 HOST=127.0.0.1 PORT=8000 bash scripts/vllm_serve_ptp2.sh
127
+ ```
128
+
129
+ #### Accelerated Mode (Optional PTPv2)
130
+
131
+ With the vLLM patch applied (`bash scripts/patch_vllm_v0_20_ptp2.sh --reverse` to undo):
132
+
133
+ ```bash
134
+ HOST=127.0.0.1 PORT=8000 bash scripts/vllm_serve_ptp2.sh
135
+ ```
136
+
137
+ Common environment overrides: `CUDA_VISIBLE_DEVICES`, `HOST`, `PORT`, `USE_PTP2` (`1` by default, `0` for AR), `GPU_MEMORY_UTILIZATION`, `MAX_MODEL_LEN`, `MAX_NUM_SEQS`.
138
+
139
+ ### 4. End-to-End Document Parsing
140
+
141
+ For full-page PDF and image parsing (layout detection, reading order, and Markdown export), use the [VenusOCR SDK](https://github.com/flow3rdown/VenusOCR):
142
+
143
+ ```bash
144
+ git clone https://github.com/flow3rdown/VenusOCR.git
145
+ cd VenusOCR
146
+ pip install -e '.[transformers,serve]'
147
+
148
+ venusocr parse document.pdf -o ./output --server-url http://127.0.0.1:8000/v1
149
+ ```
150
+
151
+ ## Citation
152
+
153
+ If you find VenusOCR 2.0 useful in your research or applications, please consider citing:
154
+
155
+ ```bibtex
156
+ @misc{venusocr2026,
157
+ title={VenusOCR 2.0: Towards Efficient and Effective Document Parsing},
158
+ author={{VenusOCR Team}},
159
+ year={2026},
160
+ howpublished={\url{https://github.com/flow3rdown/VenusOCR}}
161
+ }
162
+ ```
163
+
164
+ ## Acknowledgements
165
+
166
+ We thank the SigLIP2, Qwen3, PaddleOCR / PP-DocLayoutV3, vLLM, and OmniDocBench communities.
assets/architecture.png ADDED

Git LFS Details

  • SHA256: 83691402bbe19f750ef981e65177b2812935db1a64196c02b30a24705eeca455
  • Pointer size: 131 Bytes
  • Size of remote file: 288 kB
assets/overview.png ADDED

Git LFS Details

  • SHA256: f48e7cd201ff6583ca73b8b2be165556de9adc5e10a50022506a9bf43143560c
  • Pointer size: 131 Bytes
  • Size of remote file: 371 kB
chat_template.jinja ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- if tools %}
2
+ {{- '<|im_start|>system\n' }}
3
+ {%- if messages[0].role == 'system' %}
4
+ {%- if messages[0].content is string %}
5
+ {{- messages[0].content }}
6
+ {%- else %}
7
+ {%- for content in messages[0].content %}
8
+ {%- if 'text' in content %}
9
+ {{- content.text }}
10
+ {%- endif %}
11
+ {%- endfor %}
12
+ {%- endif %}
13
+ {{- '\n\n' }}
14
+ {%- endif %}
15
+ {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
16
+ {%- for tool in tools %}
17
+ {{- "\n" }}
18
+ {{- tool | tojson }}
19
+ {%- endfor %}
20
+ {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
21
+ {%- else %}
22
+ {%- if messages[0].role == 'system' %}
23
+ {{- '<|im_start|>system\n' }}
24
+ {%- if messages[0].content is string %}
25
+ {{- messages[0].content }}
26
+ {%- else %}
27
+ {%- for content in messages[0].content %}
28
+ {%- if 'text' in content %}
29
+ {{- content.text }}
30
+ {%- endif %}
31
+ {%- endfor %}
32
+ {%- endif %}
33
+ {{- '<|im_end|>\n' }}
34
+ {%- endif %}
35
+ {%- endif %}
36
+ {%- set image_count = namespace(value=0) %}
37
+ {%- set video_count = namespace(value=0) %}
38
+ {%- for message in messages %}
39
+ {%- if message.role == "user" %}
40
+ {{- '<|im_start|>' + message.role + '\n' }}
41
+ {%- if message.content is string %}
42
+ {{- message.content }}
43
+ {%- else %}
44
+ {%- for content in message.content %}
45
+ {%- if content.type == 'image' or 'image' in content or 'image_url' in content %}
46
+ {%- set image_count.value = image_count.value + 1 %}
47
+ {%- if add_vision_id %}Picture {{ image_count.value }}: {% endif -%}
48
+ <|vision_start|><|image_pad|><|vision_end|>
49
+ {%- elif content.type == 'video' or 'video' in content %}
50
+ {%- set video_count.value = video_count.value + 1 %}
51
+ {%- if add_vision_id %}Video {{ video_count.value }}: {% endif -%}
52
+ <|vision_start|><|video_pad|><|vision_end|>
53
+ {%- elif 'text' in content %}
54
+ {{- content.text }}
55
+ {%- endif %}
56
+ {%- endfor %}
57
+ {%- endif %}
58
+ {{- '<|im_end|>\n' }}
59
+ {%- elif message.role == "assistant" %}
60
+ {{- '<|im_start|>' + message.role + '\n' }}
61
+ {%- if message.content is string %}
62
+ {{- message.content }}
63
+ {%- else %}
64
+ {%- for content_item in message.content %}
65
+ {%- if 'text' in content_item %}
66
+ {{- content_item.text }}
67
+ {%- endif %}
68
+ {%- endfor %}
69
+ {%- endif %}
70
+ {%- if message.tool_calls %}
71
+ {%- for tool_call in message.tool_calls %}
72
+ {%- if (loop.first and message.content) or (not loop.first) %}
73
+ {{- '\n' }}
74
+ {%- endif %}
75
+ {%- if tool_call.function %}
76
+ {%- set tool_call = tool_call.function %}
77
+ {%- endif %}
78
+ {{- '<tool_call>\n{"name": "' }}
79
+ {{- tool_call.name }}
80
+ {{- '", "arguments": ' }}
81
+ {%- if tool_call.arguments is string %}
82
+ {{- tool_call.arguments }}
83
+ {%- else %}
84
+ {{- tool_call.arguments | tojson }}
85
+ {%- endif %}
86
+ {{- '}\n</tool_call>' }}
87
+ {%- endfor %}
88
+ {%- endif %}
89
+ {{- '<|im_end|>\n' }}
90
+ {%- elif message.role == "tool" %}
91
+ {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
92
+ {{- '<|im_start|>user' }}
93
+ {%- endif %}
94
+ {{- '\n<tool_response>\n' }}
95
+ {%- if message.content is string %}
96
+ {{- message.content }}
97
+ {%- else %}
98
+ {%- for content in message.content %}
99
+ {%- if content.type == 'image' or 'image' in content or 'image_url' in content %}
100
+ {%- set image_count.value = image_count.value + 1 %}
101
+ {%- if add_vision_id %}Picture {{ image_count.value }}: {% endif -%}
102
+ <|vision_start|><|image_pad|><|vision_end|>
103
+ {%- elif content.type == 'video' or 'video' in content %}
104
+ {%- set video_count.value = video_count.value + 1 %}
105
+ {%- if add_vision_id %}Video {{ video_count.value }}: {% endif -%}
106
+ <|vision_start|><|video_pad|><|vision_end|>
107
+ {%- elif 'text' in content %}
108
+ {{- content.text }}
109
+ {%- endif %}
110
+ {%- endfor %}
111
+ {%- endif %}
112
+ {{- '\n</tool_response>' }}
113
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
114
+ {{- '<|im_end|>\n' }}
115
+ {%- endif %}
116
+ {%- endif %}
117
+ {%- endfor %}
118
+ {%- if add_generation_prompt %}
119
+ {{- '<|im_start|>assistant\n' }}
120
+ {%- endif %}
config.json ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "VenusOCRForConditionalGeneration"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_venusocr.VenusOCRConfig",
7
+ "AutoModel": "modeling_venusocr.VenusOCRModel",
8
+ "AutoModelForCausalLM": "modeling_venusocr.VenusOCRForConditionalGeneration"
9
+ },
10
+ "dtype": "bfloat16",
11
+ "eos_token_id": 151645,
12
+ "image_token_id": 151655,
13
+ "model_type": "venusocr",
14
+ "pad_token_id": 151643,
15
+ "text_config": {
16
+ "attention_bias": false,
17
+ "attention_dropout": 0.0,
18
+ "bos_token_id": 151643,
19
+ "dtype": "bfloat16",
20
+ "eos_token_id": 151645,
21
+ "head_dim": 128,
22
+ "hidden_act": "silu",
23
+ "hidden_size": 1024,
24
+ "initializer_range": 0.02,
25
+ "intermediate_size": 3072,
26
+ "max_position_embeddings": 40960,
27
+ "max_window_layers": 28,
28
+ "model_type": "venusocr_text",
29
+ "num_attention_heads": 16,
30
+ "num_hidden_layers": 28,
31
+ "num_key_value_heads": 8,
32
+ "pad_token_id": 151643,
33
+ "rms_norm_eps": 1e-06,
34
+ "rope_parameters": {
35
+ "mrope_section": [
36
+ 16,
37
+ 24,
38
+ 24
39
+ ],
40
+ "rope_theta": 1000000.0,
41
+ "rope_type": "default"
42
+ },
43
+ "rope_theta": 1000000.0,
44
+ "sliding_window": 4096,
45
+ "tie_word_embeddings": true,
46
+ "use_cache": true,
47
+ "use_sliding_window": false,
48
+ "vocab_size": 151677
49
+ },
50
+ "tie_word_embeddings": true,
51
+ "transformers_version": "5.5.0",
52
+ "use_cache": true,
53
+ "vision_config": {
54
+ "attention_dropout": 0.0,
55
+ "dtype": "bfloat16",
56
+ "hidden_act": "gelu_pytorch_tanh",
57
+ "hidden_size": 1152,
58
+ "image_size": 384,
59
+ "intermediate_size": 4304,
60
+ "layer_norm_eps": 1e-06,
61
+ "model_type": "venusocr_vision",
62
+ "num_attention_heads": 16,
63
+ "num_channels": 3,
64
+ "num_hidden_layers": 27,
65
+ "patch_size": 14,
66
+ "spatial_merge_size": 2
67
+ },
68
+ "vision_end_token_id": 151653,
69
+ "vision_start_token_id": 151652
70
+ }
configuration_venusocr.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The VenusOCR Authors and the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """VenusOCR model configuration."""
15
+
16
+ import inspect
17
+
18
+ from transformers.configuration_utils import PreTrainedConfig
19
+ from transformers.modeling_rope_utils import RopeParameters
20
+ from transformers.utils import logging
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+
26
+ class VenusOCRVisionConfig(PreTrainedConfig):
27
+ r"""Configuration for the VenusOCR vision encoder (SigLIP-based ViT).
28
+
29
+ Matches the architecture of ``google/siglip-so400m-patch14-384`` with the
30
+ following extensions:
31
+
32
+ * ``spatial_merge_size``: used by the projector to group ``m×m`` adjacent
33
+ patch tokens before projecting into the LLM embedding space.
34
+ * ``num_channels``: number of input image channels (default 3 for RGB).
35
+
36
+ Args:
37
+ hidden_size (`int`, *optional*, defaults to 1152):
38
+ Dimensionality of patch embeddings and encoder hidden states.
39
+ intermediate_size (`int`, *optional*, defaults to 4304):
40
+ Dimensionality of the MLP inner layer inside each encoder block.
41
+ num_hidden_layers (`int`, *optional*, defaults to 27):
42
+ Number of Transformer encoder layers.
43
+ num_attention_heads (`int`, *optional*, defaults to 16):
44
+ Number of attention heads per encoder layer.
45
+ num_channels (`int`, *optional*, defaults to 3):
46
+ Number of input image channels.
47
+ image_size (`int`, *optional*, defaults to 384):
48
+ Training resolution (height = width = image_size). Used to
49
+ determine the base number of position-embedding slots before
50
+ interpolation.
51
+ patch_size (`int`, *optional*, defaults to 14):
52
+ Side length of each image patch in pixels.
53
+ hidden_act (`str`, *optional*, defaults to ``"gelu_pytorch_tanh"``):
54
+ Activation function used in the vision MLP blocks.
55
+ layer_norm_eps (`float`, *optional*, defaults to 1e-6):
56
+ Epsilon for all LayerNorm operations in the vision encoder.
57
+ attention_dropout (`float`, *optional*, defaults to 0.0):
58
+ Dropout probability applied to attention weights.
59
+ spatial_merge_size (`int`, *optional*, defaults to 2):
60
+ Number of patch rows (= columns) to merge in the projector.
61
+ Each group of ``spatial_merge_size × spatial_merge_size`` patches
62
+ is concatenated and projected as a single LLM token.
63
+
64
+ Example::
65
+
66
+ >>> from transformers import AutoConfig
67
+ >>> cfg = AutoConfig.from_pretrained("VenusOCR/VenusOCR2-1B", trust_remote_code=True)
68
+ >>> cfg.vision_config.hidden_size
69
+ 1152
70
+ """
71
+
72
+ model_type = "venusocr_vision"
73
+ base_config_key = "vision_config"
74
+
75
+ hidden_size: int = 1152
76
+ intermediate_size: int = 4304
77
+ num_hidden_layers: int = 27
78
+ num_attention_heads: int = 16
79
+ num_channels: int = 3
80
+ image_size: int = 384
81
+ patch_size: int = 14
82
+ hidden_act: str = "gelu_pytorch_tanh"
83
+ layer_norm_eps: float = 1e-6
84
+ attention_dropout: float = 0.0
85
+ spatial_merge_size: int = 2
86
+
87
+
88
+ class VenusOCRTextConfig(PreTrainedConfig):
89
+ r"""Configuration for the VenusOCR text decoder.
90
+
91
+ Subclasses :class:`transformers.Qwen3Config` so that ``Qwen3Model`` can be
92
+ used directly without any adapter layer. All Qwen3-0.6B defaults are
93
+ inherited and can be overridden via keyword arguments.
94
+
95
+ The key differences from the base ``Qwen3Config`` defaults:
96
+
97
+ * ``use_sliding_window = False`` – VenusOCR does **not** use sliding-window
98
+ attention (consistent with PaddleOCR-VL and GLM-OCR).
99
+
100
+ Example::
101
+
102
+ >>> from transformers import AutoConfig
103
+ >>> cfg = AutoConfig.from_pretrained("VenusOCR/VenusOCR2-1B", trust_remote_code=True)
104
+ >>> cfg.text_config.hidden_size
105
+ 1024
106
+ """
107
+
108
+ model_type = "venusocr_text"
109
+ base_config_key = "text_config"
110
+ default_theta = 500000.0
111
+
112
+ hidden_size: int = 4096
113
+ intermediate_size: int = 22016
114
+ num_hidden_layers: int = 32
115
+ num_attention_heads: int = 32
116
+ num_key_value_heads: int = 32
117
+ head_dim: int = 128
118
+ hidden_act: str = "silu"
119
+ max_position_embeddings: int = 128000
120
+ vocab_size: int = 151936
121
+ rms_norm_eps: float = 1e-6
122
+ use_cache: bool = True
123
+ pad_token_id: int | None = 151643
124
+ bos_token_id: int | None = 151643
125
+ eos_token_id: int | list[int] | None = 151645
126
+ tie_word_embeddings: bool = True
127
+ attention_bias: bool = False
128
+ attention_dropout: float = 0.0
129
+ use_sliding_window: bool = False
130
+ sliding_window: int = 4096
131
+ max_window_layers: int = 28
132
+ rope_theta: float = 1_000_000.0
133
+ initializer_range: float = 0.02
134
+ rope_parameters: RopeParameters | dict | None = None
135
+
136
+ def __post_init__(self, **kwargs):
137
+ if self.num_key_value_heads is None:
138
+ self.num_key_value_heads = self.num_attention_heads
139
+
140
+ self.head_dim = self.head_dim if self.head_dim is not None else self.hidden_size // self.num_attention_heads
141
+ super().__post_init__(**kwargs)
142
+
143
+
144
+ class VenusOCRConfig(PreTrainedConfig):
145
+ r"""Configuration class for the VenusOCR multimodal model.
146
+
147
+ VenusOCR consists of three components:
148
+
149
+ 1. **Vision encoder** – SigLIP-based ViT (→ :class:`VenusOCRVisionConfig`)
150
+ 2. **Spatial-merge projector** – groups ``spatial_merge_size²`` patches
151
+ and projects them into the LLM embedding space
152
+ 3. **Language decoder** – Qwen3-based causal LM (→ :class:`VenusOCRTextConfig`)
153
+
154
+ Args:
155
+ vision_config (`dict` or :class:`VenusOCRVisionConfig`, *optional*):
156
+ Configuration for the vision encoder. If ``None``, defaults to
157
+ ``VenusOCRVisionConfig()`` (so400m/14 @ 384 settings).
158
+ text_config (`dict` or :class:`VenusOCRTextConfig`, *optional*):
159
+ Configuration for the text decoder. If ``None``, defaults to
160
+ ``VenusOCRTextConfig()`` (Qwen3-0.6B settings).
161
+ image_token_id (`int`, *optional*, defaults to 151655):
162
+ Token id used as the ``<image>`` placeholder in input sequences.
163
+ spatial_merge_size (`int`, *optional*, defaults to 2):
164
+ Passed through to :class:`VenusOCRVisionConfig` **and** used
165
+ directly by :class:`VenusOCRProjector`.
166
+ Setting it here keeps a single source of truth.
167
+
168
+ Example::
169
+
170
+ >>> from transformers import AutoConfig, AutoModelForCausalLM
171
+
172
+ >>> config = AutoConfig.from_pretrained("VenusOCR/VenusOCR2-1B", trust_remote_code=True)
173
+ >>> model = AutoModelForCausalLM.from_config(config, trust_remote_code=True)
174
+ """
175
+
176
+ model_type = "venusocr"
177
+ sub_configs = {
178
+ "vision_config": VenusOCRVisionConfig,
179
+ "text_config": VenusOCRTextConfig,
180
+ }
181
+ keys_to_ignore_at_inference = ["past_key_values"]
182
+
183
+ text_config: dict | PreTrainedConfig | None = None
184
+ vision_config: dict | PreTrainedConfig | None = None
185
+
186
+ image_token_id: int = 151655
187
+ vision_start_token_id: int = 151652
188
+ vision_end_token_id: int = 151653
189
+ tie_word_embeddings: bool = True
190
+
191
+ def __post_init__(self, **kwargs):
192
+ if isinstance(self.vision_config, dict):
193
+ self.vision_config = self.sub_configs["vision_config"](**self.vision_config)
194
+ elif self.vision_config is None:
195
+ self.vision_config = self.sub_configs["vision_config"]()
196
+
197
+ # Hub configs are saved as flat dicts so we pop some of kwargs to init `TextConfig`
198
+ text_params = inspect.signature(self.sub_configs["text_config"].__init__).parameters.keys()
199
+ text_params = list(text_params) + ["rope_parameters", "rope_scaling", "rope_theta"]
200
+ text_kwargs = {key: kwargs.pop(key) for key in text_params if key in kwargs}
201
+
202
+ if isinstance(self.text_config, dict):
203
+ self.text_config = self.sub_configs["text_config"](**self.text_config)
204
+ elif self.text_config is None:
205
+ # Hub configs are saved as flat dicts so we pop some of kwargs to init `TextConfig`
206
+ text_kwargs["dtype"] = kwargs.get("torch_dtype", kwargs.get("dtype")) # don't pop the dtype
207
+ self.text_config = self.sub_configs["text_config"](**text_kwargs)
208
+
209
+ super().__post_init__(**kwargs)
210
+
211
+
212
+ __all__ = [
213
+ "VenusOCRVisionConfig",
214
+ "VenusOCRTextConfig",
215
+ "VenusOCRConfig",
216
+ ]
generation_config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "eos_token_id": 151645,
4
+ "output_attentions": false,
5
+ "output_hidden_states": false,
6
+ "pad_token_id": 151643,
7
+ "transformers_version": "5.5.0",
8
+ "use_cache": true
9
+ }
image_processing_venusocr.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The VenusOCR Authors and the HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import math
16
+ from collections.abc import Iterable
17
+
18
+ import torch
19
+
20
+ from transformers.image_processing_backends import TorchvisionBackend
21
+ from transformers.image_processing_utils import BatchFeature
22
+ from transformers.image_transforms import group_images_by_shape, reorder_images
23
+ from transformers.image_utils import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ImageInput, PILImageResampling, SizeDict
24
+ from transformers.processing_utils import ImagesKwargs, Unpack
25
+ from transformers.utils import TensorType
26
+ from transformers.utils.auto_docstring import auto_docstring
27
+
28
+
29
+ class VenusOCRImageProcessorKwargs(ImagesKwargs, total=False):
30
+ r"""
31
+ patch_size (`int`, *optional*, defaults to 14):
32
+ The spatial patch size of the vision encoder.
33
+ temporal_patch_size (`int`, *optional*, defaults to 1):
34
+ The temporal patch size of the vision encoder.
35
+ merge_size (`int`, *optional*, defaults to 2):
36
+ The merge size of the vision encoder to llm encoder.
37
+ """
38
+
39
+ min_pixels: int
40
+ max_pixels: int
41
+ patch_size: int
42
+ temporal_patch_size: int
43
+ merge_size: int
44
+
45
+
46
+ def smart_resize(
47
+ height: int,
48
+ width: int,
49
+ factor: int = 28,
50
+ min_pixels: int = 384 * 384,
51
+ # max_pixels: int = 1536 * 1536,
52
+ max_pixels: int = 1267 * 1267,
53
+ ):
54
+ if height < factor:
55
+ width = round((width * factor) / height)
56
+ height = factor
57
+
58
+ if width < factor:
59
+ height = round((height * factor) / width)
60
+ width = factor
61
+
62
+ if max(height, width) / min(height, width) > 200:
63
+ raise ValueError(
64
+ f"absolute aspect ratio must be smaller than 200, got {max(height, width) / min(height, width)}"
65
+ )
66
+ h_bar = round(height / factor) * factor
67
+ w_bar = round(width / factor) * factor
68
+ if h_bar * w_bar > max_pixels:
69
+ beta = math.sqrt((height * width) / max_pixels)
70
+ h_bar = max(factor, math.floor(height / beta / factor) * factor)
71
+ w_bar = max(factor, math.floor(width / beta / factor) * factor)
72
+ elif h_bar * w_bar < min_pixels:
73
+ beta = math.sqrt(min_pixels / (height * width))
74
+ h_bar = math.ceil(height * beta / factor) * factor
75
+ w_bar = math.ceil(width * beta / factor) * factor
76
+ return h_bar, w_bar
77
+
78
+
79
+ @auto_docstring
80
+ class VenusOCRImageProcessor(TorchvisionBackend):
81
+ do_resize = True
82
+ resample = PILImageResampling.BICUBIC
83
+ size = {"shortest_edge": 384 * 384, "longest_edge": 1536 * 1536}
84
+ default_to_square = False
85
+ do_rescale = True
86
+ do_normalize = True
87
+ image_mean = OPENAI_CLIP_MEAN
88
+ image_std = OPENAI_CLIP_STD
89
+ do_convert_rgb = True
90
+ patch_size = 14
91
+ temporal_patch_size = 1
92
+ merge_size = 2
93
+ valid_kwargs = VenusOCRImageProcessorKwargs
94
+ model_input_names = ["pixel_values", "image_grid_thw"]
95
+
96
+ def __init__(self, **kwargs: Unpack[VenusOCRImageProcessorKwargs]):
97
+ size = kwargs.pop("size", None)
98
+ min_pixels = kwargs.pop("min_pixels", None)
99
+ max_pixels = kwargs.pop("max_pixels", None)
100
+ # backward compatibility: override size with min_pixels and max_pixels if they are provided
101
+ size = self.size if size is None else size
102
+ if min_pixels is not None:
103
+ size["shortest_edge"] = min_pixels
104
+ size.pop("min_pixels", None)
105
+ if max_pixels is not None:
106
+ size["longest_edge"] = max_pixels
107
+ size.pop("max_pixels", None)
108
+ if "shortest_edge" not in size or "longest_edge" not in size:
109
+ raise ValueError("size must contain 'shortest_edge' and 'longest_edge' keys.")
110
+
111
+ super().__init__(size=size, **kwargs)
112
+
113
+ def _standardize_kwargs(
114
+ self,
115
+ size: int | Iterable[int] | dict[str, int] | SizeDict | None = None,
116
+ min_pixels: int | None = None,
117
+ max_pixels: int | None = None,
118
+ **kwargs,
119
+ ) -> dict:
120
+ if min_pixels is not None and max_pixels is not None:
121
+ size = SizeDict(shortest_edge=min_pixels, longest_edge=max_pixels)
122
+ kwargs = super()._standardize_kwargs(size=size, **kwargs)
123
+ size = kwargs.get("size", self.size)
124
+ if not size.shortest_edge or not size.longest_edge:
125
+ raise ValueError("size must contain 'shortest_edge' and 'longest_edge' keys.")
126
+ return kwargs
127
+
128
+ @auto_docstring
129
+ def preprocess(
130
+ self,
131
+ images: ImageInput,
132
+ **kwargs: Unpack[VenusOCRImageProcessorKwargs],
133
+ ) -> BatchFeature:
134
+ return super().preprocess(images, **kwargs)
135
+
136
+ def _preprocess(
137
+ self,
138
+ images: list["torch.Tensor"],
139
+ do_resize: bool,
140
+ size: SizeDict,
141
+ resample: "PILImageResampling | int | None",
142
+ do_rescale: bool,
143
+ rescale_factor: float,
144
+ do_normalize: bool,
145
+ image_mean: float | list[float] | None,
146
+ image_std: float | list[float] | None,
147
+ patch_size: int,
148
+ temporal_patch_size: int,
149
+ merge_size: int,
150
+ disable_grouping: bool | None,
151
+ return_tensors: str | TensorType | None,
152
+ **kwargs,
153
+ ) -> BatchFeature:
154
+ grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
155
+ resized_images_grouped = {}
156
+ for shape, stacked_images in grouped_images.items():
157
+ height, width = stacked_images.shape[-2:]
158
+ if do_resize:
159
+ resized_height, resized_width = smart_resize(
160
+ height,
161
+ width,
162
+ factor=patch_size * merge_size,
163
+ min_pixels=size.shortest_edge,
164
+ max_pixels=size.longest_edge,
165
+ )
166
+ stacked_images = self.resize(
167
+ image=stacked_images,
168
+ size=SizeDict(height=resized_height, width=resized_width),
169
+ resample=resample,
170
+ )
171
+ resized_images_grouped[shape] = stacked_images
172
+ resized_images = reorder_images(resized_images_grouped, grouped_images_index)
173
+
174
+ grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping)
175
+ processed_images_grouped = {}
176
+ processed_grids = {}
177
+ for shape, stacked_images in grouped_images.items():
178
+ resized_height, resized_width = stacked_images.shape[-2:]
179
+ patches = self.rescale_and_normalize(
180
+ stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
181
+ )
182
+ if patches.ndim == 4:
183
+ patches = patches.unsqueeze(1)
184
+ if patches.shape[1] % temporal_patch_size != 0:
185
+ repeats = patches[:, -1:].repeat(1, temporal_patch_size - 1, 1, 1, 1)
186
+ patches = torch.cat([patches, repeats], dim=1)
187
+
188
+ batch_size, grid_t, channel = patches.shape[:3]
189
+ grid_t = grid_t // temporal_patch_size
190
+ grid_h, grid_w = resized_height // patch_size, resized_width // patch_size
191
+
192
+ patches = patches.view(
193
+ batch_size,
194
+ grid_t,
195
+ temporal_patch_size,
196
+ channel,
197
+ grid_h,
198
+ patch_size,
199
+ grid_w,
200
+ patch_size,
201
+ )
202
+ patches = patches.permute(0, 1, 4, 6, 3, 2, 5, 7)
203
+ flatten_patches = patches.reshape(batch_size, grid_t * grid_h * grid_w, channel, patch_size, patch_size)
204
+
205
+ processed_images_grouped[shape] = flatten_patches
206
+ processed_grids[shape] = [[grid_t, grid_h, grid_w]] * batch_size
207
+
208
+ processed_images = reorder_images(processed_images_grouped, grouped_images_index)
209
+ processed_grids = reorder_images(processed_grids, grouped_images_index)
210
+ pixel_values = torch.cat(processed_images, dim=0)
211
+ image_grid_thw = torch.tensor(processed_grids)
212
+
213
+ return BatchFeature(
214
+ data={"pixel_values": pixel_values, "image_grid_thw": image_grid_thw}, tensor_type=return_tensors
215
+ )
216
+
217
+ def get_number_of_image_patches(self, height: int, width: int, images_kwargs=None):
218
+ """
219
+ A utility that returns number of image patches for a given image size.
220
+
221
+ Args:
222
+ height (`int`):
223
+ Height of the input image.
224
+ width (`int`):
225
+ Width of the input image.
226
+ images_kwargs (`dict`, *optional*)
227
+ Any kwargs to override defaults of the image processor.
228
+ Returns:
229
+ `int`: Number of image patches per image.
230
+ """
231
+ min_pixels = images_kwargs["min_pixels"] if "min_pixels" in images_kwargs else self.size["shortest_edge"]
232
+ max_pixels = images_kwargs["max_pixels"] if "max_pixels" in images_kwargs else self.size["longest_edge"]
233
+ patch_size = images_kwargs.get("patch_size", self.patch_size)
234
+ merge_size = images_kwargs.get("merge_size", self.merge_size)
235
+
236
+ factor = patch_size * merge_size
237
+ resized_height, resized_width = smart_resize(
238
+ height, width, factor, min_pixels=min_pixels, max_pixels=max_pixels
239
+ )
240
+ grid_h, grid_w = resized_height // patch_size, resized_width // patch_size
241
+ return grid_h * grid_w
242
+
243
+
244
+ __all__ = ["VenusOCRImageProcessor"]
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:29661ba58197750e616fa7310eba9964251bb459ef0d1b0bdba136def48c1b1e
3
+ size 2380194328
modeling_venusocr.py ADDED
@@ -0,0 +1,1881 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The VenusOCR Authors and the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """PyTorch VenusOCR model."""
15
+
16
+ import itertools
17
+ from collections.abc import Callable
18
+ from dataclasses import dataclass
19
+ from typing import Optional, Union
20
+
21
+ import torch
22
+ import torch.nn.functional as F
23
+ from torch import nn
24
+
25
+ from transformers.activations import ACT2FN, GELUActivation
26
+ from transformers.cache_utils import Cache
27
+ from transformers.generation.utils import GenerationMixin
28
+ from transformers.modeling_layers import GradientCheckpointingLayer
29
+ from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPast, BaseModelOutputWithPooling
30
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
31
+ from transformers.utils import logging
32
+ from transformers.utils.auto_docstring import auto_docstring
33
+ from transformers.utils.generic import (
34
+ ModelOutput, maybe_autocast, can_return_tuple,
35
+ is_flash_attention_requested, merge_with_config_defaults
36
+ )
37
+ from transformers.utils.import_utils import torch_compilable_check
38
+ from transformers.masking_utils import create_bidirectional_mask, create_causal_mask
39
+ from transformers.cache_utils import DynamicCache
40
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
41
+ from transformers.integrations.hub_kernels import use_kernel_forward_from_hub
42
+ from transformers.utils.output_capturing import capture_outputs
43
+ from .configuration_venusocr import VenusOCRConfig
44
+
45
+
46
+ logger = logging.get_logger(__name__)
47
+
48
+ _IGNORE_INDEX = -100
49
+
50
+
51
+ def _cross_entropy_loss(
52
+ hidden_states: torch.Tensor,
53
+ lm_head: nn.Module,
54
+ position_ids: torch.Tensor,
55
+ labels: torch.Tensor,
56
+ reduction_scope: str = "sequence",
57
+ **loss_kwargs,
58
+ ) -> torch.Tensor:
59
+ """Compute next-token prediction loss (inline copy, no external VenusOCR dependency).
60
+
61
+ Args:
62
+ hidden_states: ``[B, T, C]``
63
+ lm_head: linear projection to vocab logits
64
+ position_ids: ``[B, T]``
65
+ labels: ``[B, T]``
66
+ reduction_scope: ``"sequence"`` (per-sample normalisation, recommended for
67
+ packing) or ``"batch"`` (divide by total valid tokens in batch).
68
+ """
69
+ batch_size = hidden_states.size(0)
70
+
71
+ shift_hidden = hidden_states[..., :-1, :].contiguous()
72
+ shift_labels = labels[..., 1:].contiguous()
73
+ mask = shift_labels != _IGNORE_INDEX
74
+
75
+ if mask.sum() == 0:
76
+ pseudo = lm_head(hidden_states[:, 0:1])
77
+ return 0.0 * pseudo.mean()
78
+
79
+ valid_hidden = shift_hidden[mask]
80
+ valid_labels = shift_labels[mask]
81
+
82
+ if "num_items_in_batch" not in loss_kwargs:
83
+ logits = lm_head(valid_hidden)
84
+ return F.cross_entropy(logits, valid_labels, reduction="mean")
85
+
86
+ if reduction_scope == "batch":
87
+ logits = lm_head(valid_hidden)
88
+ loss = F.cross_entropy(logits, valid_labels, reduction="sum")
89
+ return loss / loss_kwargs["num_items_in_batch"]
90
+
91
+ if reduction_scope == "sequence":
92
+ if batch_size == 1:
93
+ starts = torch.nonzero(position_ids[0] == 0)[:, 0]
94
+ ends = F.pad(starts[1:], (0, 1), value=position_ids.size(1))
95
+ seq_ids = torch.cat([
96
+ torch.full((int(e - s),), i, device=position_ids.device, dtype=torch.long)
97
+ for i, (s, e) in enumerate(zip(starts.tolist(), ends.tolist()))
98
+ ]).unsqueeze(0)
99
+ else:
100
+ seq_ids = torch.arange(batch_size, device=position_ids.device)
101
+ seq_ids = seq_ids.unsqueeze(1).expand(-1, hidden_states.size(1))
102
+
103
+ shift_seq_ids = seq_ids[..., :-1][mask]
104
+ num_tokens = F.one_hot(shift_seq_ids).sum(dim=0)
105
+ denominator = num_tokens[shift_seq_ids] * loss_kwargs["num_items_in_batch"]
106
+
107
+ logits = lm_head(valid_hidden)
108
+ loss = F.cross_entropy(logits, valid_labels, reduction="none")
109
+ return (loss / denominator).sum()
110
+
111
+ raise ValueError(f"Unknown reduction_scope: {reduction_scope!r}")
112
+
113
+
114
+ @dataclass
115
+ @auto_docstring(
116
+ custom_intro="""
117
+ Base class for VenusOCR model outputs, with hidden states and attentions.
118
+ """
119
+ )
120
+ class VenusOCRModelOutputWithPast(BaseModelOutputWithPast):
121
+ r"""
122
+ image_hidden_states (`torch.FloatTensor`, *optional*):
123
+ A ``torch.FloatTensor`` of size ``(total_image_tokens, hidden_size)``.
124
+ Image hidden states produced by the vision encoder and projected by the
125
+ multimodal projector.
126
+ rope_deltas (`torch.LongTensor`, *optional*):
127
+ Per-sample offset (shape ``(batch_size, 1)``) that accounts for the
128
+ difference between the 2D RoPE position span and the number of image
129
+ tokens actually inserted. Used during incremental decoding to restore
130
+ correct position ids from the KV-cache length.
131
+ """
132
+
133
+ image_hidden_states: Optional[torch.FloatTensor] = None
134
+ rope_deltas: Optional[torch.LongTensor] = None
135
+
136
+
137
+ @dataclass
138
+ @auto_docstring(
139
+ custom_intro="""
140
+ Base class for VenusOCR causal language model outputs.
141
+ """
142
+ )
143
+ class VenusOCRCausalLMOutputWithPast(ModelOutput):
144
+ r"""
145
+ loss (`torch.FloatTensor` of shape ``(1,)``, *optional*, returned when ``labels`` is provided):
146
+ Language modelling loss (next-token prediction).
147
+ logits (`torch.FloatTensor` of shape ``(batch_size, sequence_length, config.vocab_size)``):
148
+ Prediction scores of the language modelling head (before SoftMax).
149
+ past_key_values (`Cache`, *optional*, returned when ``use_cache=True``):
150
+ Pre-computed key/value hidden states that can be used to speed up auto-regressive decoding.
151
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when ``output_hidden_states=True``):
152
+ Hidden states at each layer of the decoder.
153
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when ``output_attentions=True``):
154
+ Attention weights at each layer of the decoder.
155
+ image_hidden_states (`torch.FloatTensor`, *optional*):
156
+ Projected image features that were merged into the input embeddings.
157
+ rope_deltas (`torch.LongTensor`, *optional*):
158
+ Stored 2D RoPE offset for incremental decoding.
159
+ """
160
+
161
+ loss: Optional[torch.FloatTensor] = None
162
+ logits: Optional[torch.FloatTensor] = None
163
+ past_key_values: Optional[Cache] = None
164
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
165
+ attentions: Optional[tuple[torch.FloatTensor]] = None
166
+ image_hidden_states: Optional[torch.FloatTensor] = None
167
+ rope_deltas: Optional[torch.LongTensor] = None
168
+
169
+
170
+ class VenusOCRVisionRotaryEmbedding(nn.Module):
171
+ """1D RoPE for the vision encoder, applied over 2D patch grids.
172
+
173
+ Returns ``freqs`` of shape ``(seqlen, dim // 2)`` which are then indexed
174
+ by per-patch ``(h, w)`` coordinates and concatenated to form the full
175
+ rotary embeddings used in attention.
176
+ """
177
+
178
+ inv_freq: torch.Tensor # type annotation for register_buffer
179
+
180
+ def __init__(self, dim: int, theta: float = 10000.0) -> None:
181
+ super().__init__()
182
+ self.dim = dim
183
+ self.theta = theta
184
+ inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim))
185
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
186
+
187
+ def forward(self, seqlen: int) -> torch.Tensor:
188
+ seq = torch.arange(seqlen, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
189
+ freqs = torch.outer(seq, self.inv_freq) # (seqlen, dim // 2)
190
+ return freqs
191
+
192
+
193
+ def rotate_half(x: torch.Tensor) -> torch.Tensor:
194
+ """Rotates half the hidden dims of the input."""
195
+ x1 = x[..., : x.shape[-1] // 2]
196
+ x2 = x[..., x.shape[-1] // 2 :]
197
+ return torch.cat((-x2, x1), dim=-1)
198
+
199
+
200
+ def apply_multimodal_rotary_pos_emb(q, k, cos, sin, mrope_section, unsqueeze_dim=1):
201
+ """Applies Rotary Position Embedding with Multimodal Sections to the query and key tensors (https://qwenlm.github.io/blog/qwen2-vl/).
202
+
203
+ Explanation:
204
+ Multimodal 3D rotary position embedding is an extension to 1D rotary position embedding. The input embedding
205
+ sequence contains vision (images / videos) embedding and text embedding or just contains text embedding. For
206
+ vision embedding part, we apply rotary position embedding on temporal, height and width dimension separately.
207
+ Here we split the channel dimension to 3 chunks for the temporal, height and width rotary position embedding.
208
+ For text embedding part, we just apply 1D rotary position embedding. The three rotary position index (temporal,
209
+ height and width) of text embedding is always the same, so the text embedding rotary position embedding has no
210
+ difference with modern LLMs.
211
+
212
+ Args:
213
+ q (`torch.Tensor`): The query tensor.
214
+ k (`torch.Tensor`): The key tensor.
215
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
216
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
217
+ position_ids (`torch.Tensor`):
218
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
219
+ used to pass offsetted position ids when working with a KV-cache.
220
+ mrope_section(`List(int)`):
221
+ Multimodal rope section is for channel dimension of temporal, height and width in rope calculation.
222
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
223
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
224
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
225
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
226
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
227
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
228
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
229
+ Returns:
230
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
231
+ """
232
+ mrope_section = mrope_section * 2
233
+ cos = torch.cat([m[i % 3] for i, m in enumerate(cos.split(mrope_section, dim=-1))], dim=-1).unsqueeze(
234
+ unsqueeze_dim
235
+ )
236
+ sin = torch.cat([m[i % 3] for i, m in enumerate(sin.split(mrope_section, dim=-1))], dim=-1).unsqueeze(
237
+ unsqueeze_dim
238
+ )
239
+
240
+ q_embed = (q * cos) + (rotate_half(q) * sin)
241
+ k_embed = (k * cos) + (rotate_half(k) * sin)
242
+ return q_embed, k_embed
243
+
244
+
245
+ def apply_rotary_pos_emb_vision(
246
+ q: torch.Tensor,
247
+ k: torch.Tensor,
248
+ cos: torch.Tensor,
249
+ sin: torch.Tensor,
250
+ ) -> tuple[torch.Tensor, torch.Tensor]:
251
+ """Apply RoPE to vision query/key tensors.
252
+
253
+ Args:
254
+ q, k: ``(seq_len, num_heads, head_dim)``
255
+ cos, sin: ``(seq_len, head_dim)`` – note: **no** batch/head dimension.
256
+ """
257
+ orig_q_dtype = q.dtype
258
+ orig_k_dtype = k.dtype
259
+ q, k = q.float(), k.float()
260
+ cos = cos.unsqueeze(-2).float() # (seq_len, 1, head_dim)
261
+ sin = sin.unsqueeze(-2).float()
262
+ q_embed = (q * cos) + (rotate_half(q) * sin)
263
+ k_embed = (k * cos) + (rotate_half(k) * sin)
264
+ q_embed = q_embed.to(orig_q_dtype)
265
+ k_embed = k_embed.to(orig_k_dtype)
266
+ return q_embed, k_embed
267
+
268
+
269
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
270
+ """
271
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
272
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
273
+ """
274
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
275
+ if n_rep == 1:
276
+ return hidden_states
277
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
278
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
279
+
280
+
281
+ def eager_attention_forward(
282
+ module: nn.Module,
283
+ query: torch.Tensor,
284
+ key: torch.Tensor,
285
+ value: torch.Tensor,
286
+ attention_mask: torch.Tensor | None,
287
+ scaling: float,
288
+ dropout: float = 0.0,
289
+ **kwargs,
290
+ ):
291
+ key_states = repeat_kv(key, module.num_key_value_groups)
292
+ value_states = repeat_kv(value, module.num_key_value_groups)
293
+
294
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
295
+ if attention_mask is not None:
296
+ attn_weights = attn_weights + attention_mask
297
+
298
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
299
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
300
+ attn_output = torch.matmul(attn_weights, value_states)
301
+ attn_output = attn_output.transpose(1, 2).contiguous()
302
+
303
+ return attn_output, attn_weights
304
+
305
+
306
+ @auto_docstring
307
+ class VenusOCRPreTrainedModel(PreTrainedModel):
308
+ """Base class for VenusOCR models. Handles weight initialisation and
309
+ gradient-checkpointing boilerplate.
310
+ """
311
+
312
+ config_class = VenusOCRConfig
313
+ base_model_prefix = "model"
314
+ supports_gradient_checkpointing = True
315
+ _skip_keys_device_placement = "past_key_values"
316
+ _supports_flash_attn = True
317
+ _supports_sdpa = True
318
+ _supports_flex_attn = True
319
+ _supports_attention_backend = True
320
+
321
+ def _init_weights(self, module: nn.Module) -> None:
322
+ super()._init_weights(module)
323
+ if isinstance(module, VenusOCRVisionRotaryEmbedding):
324
+ inv_freq = 1.0 / (
325
+ module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)
326
+ )
327
+ module.inv_freq.data.copy_(inv_freq)
328
+ elif isinstance(module, VenusOCRVisionEmbeddings):
329
+ # Re-initialise position_ids buffer to identity arange
330
+ n = module.num_patches # plain int attribute
331
+ module.position_ids.data.copy_(torch.arange(n).expand((1, -1))) # type: ignore[arg-type]
332
+
333
+
334
+ class VenusOCRVisionEmbeddings(nn.Module):
335
+ """Patch embedding + interpolated 2D absolute position embedding.
336
+
337
+ Key differences from the original ``SiglipVisionEmbeddings``:
338
+
339
+ 1. **Input format** – accepts pre-patchified tensors of shape
340
+ ``(total_patches, C, patch_h, patch_w)`` (as produced by the VenusOCR
341
+ processor via the same tiling scheme as PaddleOCR-VL / Qwen2-VL),
342
+ rather than a raw ``(B, C, H, W)`` image.
343
+
344
+ 2. **Dynamic position interpolation** – for each image the position
345
+ embedding is bilinearly interpolated from the training resolution
346
+ ``(image_size // patch_size) ** 2`` to the actual ``(h, w)`` grid,
347
+ enabling arbitrary-resolution inputs. This matches the approach used
348
+ in PaddleOCR-VL and differs from the standard SiglipVisionEmbeddings
349
+ which only optionally interpolates via ``interpolate_pos_encoding=True``.
350
+
351
+ 3. **Per-image processing** – images in a batch may have different grid
352
+ sizes; they are processed individually and concatenated, producing a
353
+ flat ``(total_tokens, embed_dim)`` sequence ready for the packed-sequence
354
+ attention in the encoder.
355
+ """
356
+
357
+ def __init__(self, config) -> None: # type: ignore[name-defined]
358
+ super().__init__()
359
+ self.config = config
360
+ self.embed_dim = config.hidden_size
361
+ self.image_size = config.image_size
362
+ self.patch_size = config.patch_size
363
+
364
+ self.patch_embedding = nn.Conv2d(
365
+ in_channels=config.num_channels,
366
+ out_channels=self.embed_dim,
367
+ kernel_size=self.patch_size,
368
+ stride=self.patch_size,
369
+ padding="valid",
370
+ )
371
+
372
+ self.num_patches = (self.image_size // self.patch_size) ** 2
373
+ self.num_positions = self.num_patches
374
+ self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
375
+ self.register_buffer(
376
+ "position_ids",
377
+ torch.arange(self.num_positions).expand((1, -1)),
378
+ persistent=False,
379
+ )
380
+
381
+ def interpolate_pos_encoding(
382
+ self, embeddings: torch.Tensor, height: int, width: int
383
+ ) -> torch.Tensor:
384
+ """Bilinearly interpolate position embedding to ``(height, width)`` patch grid.
385
+
386
+ Adapted from DINO / DINOv2 and PaddleOCR-VL. Always uses bilinear
387
+ interpolation (as opposed to the bicubic used in the original
388
+ ``SiglipVisionEmbeddings``).
389
+
390
+ Args:
391
+ embeddings: unused except for device / dtype information
392
+ height, width: target grid dimensions **in patches** (not pixels)
393
+
394
+ Returns:
395
+ ``(1, height * width, embed_dim)`` interpolated position embeddings.
396
+ """
397
+ num_positions = self.position_embedding.weight.shape[0]
398
+ patch_pos_embed = self.position_embedding.weight.unsqueeze(0) # (1, N, D)
399
+ dim = embeddings.shape[-1]
400
+ sqrt_num_positions = int(num_positions ** 0.5)
401
+
402
+ patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
403
+ patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2) # (1, D, H, W)
404
+
405
+ patch_pos_embed = nn.functional.interpolate(
406
+ patch_pos_embed,
407
+ size=(height, width),
408
+ mode="bilinear",
409
+ align_corners=False,
410
+ )
411
+
412
+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim) # (1, h*w, D)
413
+ return patch_pos_embed
414
+
415
+ def forward(
416
+ self,
417
+ pixel_values: torch.FloatTensor,
418
+ image_grid_thw: Optional[torch.LongTensor] = None,
419
+ ) -> torch.Tensor:
420
+ """
421
+ Args:
422
+ pixel_values: ``(total_patches, C, patch_size, patch_size)`` – pre-patchified
423
+ tensor where the batch and temporal dimensions are merged.
424
+ image_grid_thw: ``(num_images, 3)`` containing ``(t, h, w)`` for each image.
425
+ Must be provided to correctly add per-image position embeddings.
426
+
427
+ Returns:
428
+ Flat ``(total_tokens, embed_dim)`` embedding tensor.
429
+ """
430
+ target_dtype = self.patch_embedding.weight.dtype
431
+ # pixel_values: (total_patches, C, patch_h, patch_w)
432
+ patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype))
433
+ # patch_embeds: (total_patches, embed_dim, 1, 1) → squeeze → (total_patches, embed_dim)
434
+ embeddings = patch_embeds.flatten(1) # (total_patches, embed_dim)
435
+
436
+ if image_grid_thw is None:
437
+ # Fallback: add default position embedding (assumes fixed-resolution square images)
438
+ embeddings = embeddings + self.position_embedding(self.position_ids).squeeze(0)
439
+ return embeddings
440
+
441
+ # Add per-image interpolated position embeddings
442
+ processed = []
443
+ offset = 0
444
+ for grid in image_grid_thw:
445
+ t, h, w = int(grid[0]), int(grid[1]), int(grid[2])
446
+ n_tokens = t * h * w
447
+ img_emb = embeddings[offset : offset + n_tokens] # (t*h*w, D)
448
+
449
+ # Interpolate position encoding to the current (h, w) grid
450
+ pos_enc = self.interpolate_pos_encoding(img_emb, h, w) # (1, h*w, D)
451
+ pos_enc = pos_enc.squeeze(0).repeat(t, 1) # (t*h*w, D)
452
+
453
+ processed.append(img_emb + pos_enc)
454
+ offset += n_tokens
455
+
456
+ embeddings = torch.concat(processed, dim=0)
457
+ return embeddings # (total_tokens, D)
458
+
459
+
460
+ class VenusOCRVisionAttention(nn.Module):
461
+ """Full-attention (non-causal) multi-head attention for the vision encoder.
462
+
463
+ Compared with the original ``SiglipAttention``:
464
+
465
+ * Uses **2D rotary position embeddings** (computed per-image from patch
466
+ ``(h, w)`` coordinates) instead of the learned absolute position
467
+ embeddings added in ``VenusOCRVisionEmbeddings.forward``.
468
+ * Accepts **packed sequences** via ``cu_seqlens`` + Flash Attention 2, or
469
+ falls back to chunked eager attention for shorter sequences / other
470
+ backends.
471
+ * The projection layer is still a single ``out_proj`` (same as Siglip),
472
+ not a split ``q/k/v_proj + o_proj`` (same weight shapes, just naming).
473
+ """
474
+
475
+ def __init__(self, config) -> None: # type: ignore[name-defined]
476
+ super().__init__()
477
+ self.config = config
478
+ self.embed_dim = config.hidden_size
479
+ self.num_heads = config.num_attention_heads
480
+ self.head_dim = self.embed_dim // self.num_heads
481
+ self.scaling = self.head_dim ** -0.5
482
+ self.attention_dropout = config.attention_dropout
483
+ self.is_causal = False
484
+
485
+ # keep the same Siglip naming convention (q/k/v/out_proj)
486
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
487
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
488
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
489
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
490
+ self.num_key_value_groups = 1 # required by eager_attention_forward
491
+
492
+ def forward(
493
+ self,
494
+ hidden_states: torch.Tensor,
495
+ cu_seqlens: torch.Tensor,
496
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
497
+ **kwargs,
498
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor] | None]:
499
+ """
500
+ Args:
501
+ hidden_states: ``(seq_len, embed_dim)`` – packed (all images concatenated).
502
+ cu_seqlens: ``(num_images + 1,)`` cumulative sequence lengths.
503
+ position_embeddings: ``(cos, sin)`` each of shape ``(seq_len, head_dim)``.
504
+ """
505
+ seq_len = hidden_states.shape[0]
506
+ query = self.q_proj(hidden_states).view(seq_len, self.num_heads, self.head_dim)
507
+ key = self.k_proj(hidden_states).view(seq_len, self.num_heads, self.head_dim)
508
+ value = self.v_proj(hidden_states).view(seq_len, self.num_heads, self.head_dim)
509
+
510
+ cos, sin = position_embeddings
511
+ query, key = apply_rotary_pos_emb_vision(query, key, cos, sin)
512
+
513
+ # Reshape to (1, num_heads, seq_len, head_dim) for attention backends
514
+ query = query.transpose(0, 1).unsqueeze(0) # (1, H, S, D)
515
+ key = key.transpose(0, 1).unsqueeze(0)
516
+ value = value.transpose(0, 1).unsqueeze(0)
517
+
518
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
519
+ self.config._attn_implementation, eager_attention_forward
520
+ )
521
+
522
+ if is_flash_attention_requested(self.config):
523
+ # Flash Attention 2: packed variable-length attention
524
+ max_seqlen = int((cu_seqlens[1:] - cu_seqlens[:-1]).max())
525
+ attn_output, _ = attention_interface(
526
+ self,
527
+ query, key, value,
528
+ attention_mask=None,
529
+ scaling=self.scaling,
530
+ dropout=0.0 if not self.training else self.attention_dropout,
531
+ cu_seq_lens_q=cu_seqlens,
532
+ cu_seq_lens_k=cu_seqlens,
533
+ max_length_q=max_seqlen,
534
+ max_length_k=max_seqlen,
535
+ is_causal=False,
536
+ **kwargs,
537
+ )
538
+ else:
539
+ # Chunked eager attention: process each image independently
540
+ lengths = (cu_seqlens[1:] - cu_seqlens[:-1]).tolist()
541
+ q_chunks = torch.split(query, lengths, dim=2)
542
+ k_chunks = torch.split(key, lengths, dim=2)
543
+ v_chunks = torch.split(value, lengths, dim=2)
544
+
545
+ attn_outputs = []
546
+ for q, k, v in zip(q_chunks, k_chunks, v_chunks):
547
+ out, _ = attention_interface(
548
+ self, q, k, v,
549
+ attention_mask=None,
550
+ scaling=self.scaling,
551
+ dropout=0.0 if not self.training else self.attention_dropout,
552
+ is_causal=False,
553
+ **kwargs,
554
+ )
555
+ attn_outputs.append(out)
556
+ attn_output = torch.cat(attn_outputs, dim=1)
557
+
558
+ attn_output = attn_output.reshape(seq_len, -1).contiguous() # (S, embed_dim)
559
+ attn_output = self.out_proj(attn_output)
560
+ return attn_output
561
+
562
+
563
+ class VenusOCRVisionMLP(nn.Module):
564
+ """Feed-forward block for the vision encoder (identical to ``SiglipMLP``)."""
565
+
566
+ def __init__(self, config) -> None: # type: ignore[name-defined]
567
+ super().__init__()
568
+ self.activation_fn = ACT2FN[config.hidden_act]
569
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
570
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
571
+
572
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
573
+ hidden_states = self.fc1(hidden_states)
574
+ hidden_states = self.activation_fn(hidden_states)
575
+ hidden_states = self.fc2(hidden_states)
576
+ return hidden_states
577
+
578
+
579
+ class VenusOCRVisionEncoderLayer(GradientCheckpointingLayer):
580
+ """Single Transformer encoder layer for the vision encoder.
581
+
582
+ Structurally identical to ``SiglipEncoderLayer``
583
+ (pre-norm, self-attn, pre-norm, MLP with residuals), but uses
584
+ ``VenusOCRVisionAttention`` which supports 2D RoPE and packed sequences.
585
+ """
586
+
587
+ def __init__(self, config) -> None: # type: ignore[name-defined]
588
+ super().__init__()
589
+ self.embed_dim = config.hidden_size
590
+ self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
591
+ self.self_attn = VenusOCRVisionAttention(config)
592
+ self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
593
+ self.mlp = VenusOCRVisionMLP(config)
594
+
595
+ def forward(
596
+ self,
597
+ hidden_states: torch.Tensor,
598
+ cu_seqlens: torch.Tensor,
599
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
600
+ **kwargs,
601
+ ) -> torch.Tensor:
602
+ residual = hidden_states
603
+
604
+ hidden_states = self.layer_norm1(hidden_states)
605
+ hidden_states = self.self_attn(
606
+ hidden_states,
607
+ cu_seqlens=cu_seqlens,
608
+ position_embeddings=position_embeddings,
609
+ **kwargs,
610
+ )
611
+ hidden_states = residual + hidden_states
612
+
613
+ residual = hidden_states
614
+ hidden_states = self.layer_norm2(hidden_states)
615
+ hidden_states = self.mlp(hidden_states)
616
+ hidden_states = residual + hidden_states
617
+ return hidden_states
618
+
619
+
620
+ class VenusOCRVisionEncoder(nn.Module):
621
+ """Stack of ``VenusOCRVisionEncoderLayer`` with 2D RoPE pre-computation.
622
+
623
+ Before passing through the layers, height/width position indices are
624
+ extracted from ``image_grid_thw`` and used to look up the rotary
625
+ embeddings from ``VenusOCRVisionRotaryEmbedding``, following the same
626
+ approach as PaddleOCR-VL.
627
+ """
628
+
629
+ def __init__(self, config) -> None: # type: ignore[name-defined]
630
+ super().__init__()
631
+ self.config = config
632
+ self.layers = nn.ModuleList(
633
+ [VenusOCRVisionEncoderLayer(config) for _ in range(config.num_hidden_layers)]
634
+ )
635
+ self.gradient_checkpointing = False
636
+ head_dim = config.hidden_size // config.num_attention_heads
637
+ self.rotary_pos_emb = VenusOCRVisionRotaryEmbedding(head_dim // 2)
638
+
639
+ def forward(
640
+ self,
641
+ inputs_embeds: torch.FloatTensor,
642
+ cu_seqlens: torch.Tensor,
643
+ image_grid_thw: Optional[torch.LongTensor] = None,
644
+ attention_mask: Optional[torch.Tensor] = None,
645
+ **kwargs,
646
+ ) -> BaseModelOutput:
647
+ """
648
+ Args:
649
+ inputs_embeds: ``(total_tokens, hidden_size)`` packed sequence.
650
+ cu_seqlens: ``(num_images + 1,)`` cumulative lengths for FA2.
651
+ image_grid_thw: ``(num_images, 3)`` grid metadata used to build
652
+ 2D position ids for rotary embeddings.
653
+ """
654
+ device = inputs_embeds.device
655
+ hidden_states = inputs_embeds
656
+
657
+ # ── Build 2D rotary position embeddings ───────────────────────────────
658
+ # For each token, compute its (h_id, w_id) within its image.
659
+ h_ids_list, w_ids_list = [], []
660
+ for t, h, w in image_grid_thw:
661
+ t, h, w = int(t), int(h), int(w)
662
+ patch_ids = torch.arange(t * h * w, device=device) % (h * w)
663
+ h_ids_list.append(patch_ids // w)
664
+ w_ids_list.append(patch_ids % w)
665
+ height_ids = torch.cat(h_ids_list, dim=0) # (total_tokens,)
666
+ width_ids = torch.cat(w_ids_list, dim=0)
667
+
668
+ # Stack to (total_tokens, 2) for lookup
669
+ pids = torch.stack([height_ids, width_ids], dim=-1)
670
+ max_grid_size = int(pids.max().item()) + 1
671
+ rotary_freqs = self.rotary_pos_emb(max_grid_size) # (max_grid, dim//2)
672
+ rotary_emb = rotary_freqs[pids].flatten(1) # (total_tokens, dim)
673
+ rotary_emb = rotary_emb.repeat(1, 2) # (total_tokens, head_dim)
674
+ position_embeddings = (rotary_emb.cos(), rotary_emb.sin())
675
+
676
+ # ── Bidirectional attention mask (for non-FA2 backends) ───────────────
677
+ attention_mask = create_bidirectional_mask(
678
+ config=self.config,
679
+ inputs_embeds=inputs_embeds,
680
+ attention_mask=attention_mask,
681
+ )
682
+
683
+ for layer in self.layers:
684
+ hidden_states = layer(
685
+ hidden_states,
686
+ cu_seqlens=cu_seqlens,
687
+ position_embeddings=position_embeddings,
688
+ **kwargs,
689
+ )
690
+
691
+ return BaseModelOutput(last_hidden_state=hidden_states)
692
+
693
+
694
+ class VenusOCRVisionTransformer(VenusOCRPreTrainedModel):
695
+ """Vision Transformer backbone (encoder-only, non-causal).
696
+
697
+ Pipeline: ``VenusOCRVisionEmbeddings → VenusOCRVisionEncoder → LayerNorm``
698
+ """
699
+
700
+ def __init__(self, config) -> None:
701
+ super().__init__(config)
702
+ self.config = config
703
+ self.embeddings = VenusOCRVisionEmbeddings(config)
704
+ self.encoder = VenusOCRVisionEncoder(config)
705
+ self.post_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
706
+
707
+ @auto_docstring
708
+ def forward(
709
+ self,
710
+ pixel_values: torch.FloatTensor,
711
+ cu_seqlens: torch.Tensor,
712
+ image_grid_thw: Optional[torch.LongTensor] = None,
713
+ attention_mask: Optional[torch.Tensor] = None,
714
+ **kwargs,
715
+ ) -> BaseModelOutputWithPooling:
716
+ r"""
717
+ pixel_values (`torch.FloatTensor` of shape `(total_patches, C, patch_size, patch_size)`):
718
+ Pre-patchified pixel tensor.
719
+ cu_seqlens (`torch.Tensor` of shape `(num_images + 1,)`):
720
+ Cumulative sequence lengths for packed attention (FA2).
721
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
722
+ ``(temporal, height, width)`` grid metadata for each image.
723
+ """
724
+ hidden_states = self.embeddings(pixel_values, image_grid_thw=image_grid_thw)
725
+
726
+ encoder_outputs: BaseModelOutput = self.encoder(
727
+ inputs_embeds=hidden_states,
728
+ cu_seqlens=cu_seqlens,
729
+ image_grid_thw=image_grid_thw,
730
+ attention_mask=attention_mask,
731
+ **kwargs,
732
+ )
733
+
734
+ last_hidden_state = encoder_outputs.last_hidden_state
735
+ last_hidden_state = self.post_layernorm(last_hidden_state)
736
+
737
+ return BaseModelOutputWithPooling(
738
+ last_hidden_state=last_hidden_state,
739
+ pooler_output=None,
740
+ )
741
+
742
+
743
+ class VenusOCRProjector(nn.Module):
744
+ """Spatial-merge MLP projector that maps vision encoder features into the
745
+ LLM embedding space.
746
+
747
+ Architecture (following PaddleOCR-VL)::
748
+
749
+ input: (total_tokens, vision_hidden_size)
750
+ ↓ group spatial_merge_size × spatial_merge_size patches
751
+ ↓ pre_norm (LayerNorm over vision_hidden_size)
752
+ ↓ reshape: (N_blocks, vision_hidden_size * merge_size²)
753
+ ↓ Linear → GELU → Linear
754
+ output: (N_blocks, text_hidden_size)
755
+
756
+ This reduces the total token count by ``merge_size²``.
757
+ """
758
+
759
+ def __init__(self, config: VenusOCRConfig) -> None:
760
+ super().__init__()
761
+ m = config.vision_config.spatial_merge_size
762
+ vision_dim = config.vision_config.hidden_size
763
+ merged_dim = vision_dim * m * m
764
+ text_dim = config.text_config.hidden_size
765
+
766
+ self.merge_size = m
767
+ self.pre_norm = nn.LayerNorm(vision_dim, eps=1e-5)
768
+ self.linear_1 = nn.Linear(merged_dim, merged_dim, bias=True)
769
+ self.act = GELUActivation()
770
+ self.linear_2 = nn.Linear(merged_dim, text_dim, bias=True)
771
+
772
+ def forward(
773
+ self,
774
+ image_features: torch.Tensor,
775
+ image_grid_thw: torch.LongTensor,
776
+ ) -> torch.Tensor:
777
+ """
778
+ Args:
779
+ image_features: ``(total_tokens, vision_hidden_size)`` flat sequence.
780
+ image_grid_thw: ``(num_images, 3)`` grid metadata.
781
+
782
+ Returns:
783
+ ``(total_merged_tokens, text_hidden_size)``
784
+ """
785
+ m = self.merge_size
786
+ chunks = image_features.split(image_grid_thw.prod(dim=1).tolist(), dim=0)
787
+ processed = []
788
+ for feat, grid in zip(chunks, image_grid_thw):
789
+ feat = self.pre_norm(feat)
790
+ t, h, w = int(grid[0]), int(grid[1]), int(grid[2])
791
+ d = feat.shape[-1]
792
+ h_block, w_block = h // m, w // m
793
+
794
+ # Reshape to group (m × m) spatial blocks
795
+ feat = feat.reshape(t, h_block, m, w_block, m, d)
796
+ feat = feat.transpose(2, 3) # (t, h_block, w_block, m, m, d)
797
+ feat = feat.reshape(t * h_block * w_block, m * m * d)
798
+
799
+ hidden = self.linear_1(feat)
800
+ hidden = self.act(hidden)
801
+ hidden = self.linear_2(hidden)
802
+ processed.append(hidden)
803
+
804
+ return torch.cat(processed, dim=0)
805
+
806
+
807
+ class VenusOCRRotaryEmbedding(nn.Module):
808
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
809
+
810
+ def __init__(self, config, device=None):
811
+ super().__init__()
812
+ self.max_seq_len_cached = config.max_position_embeddings
813
+ self.original_max_seq_len = config.max_position_embeddings
814
+
815
+ self.config = config
816
+
817
+ self.rope_type = self.config.rope_parameters["rope_type"]
818
+ rope_init_fn: Callable = self.compute_default_rope_parameters
819
+ if self.rope_type != "default":
820
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
821
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
822
+
823
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
824
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
825
+
826
+ @staticmethod
827
+ def compute_default_rope_parameters(
828
+ config: VenusOCRConfig | None = None,
829
+ device: Optional["torch.device"] = None,
830
+ seq_len: int | None = None,
831
+ ) -> tuple["torch.Tensor", float]:
832
+ """
833
+ Computes the inverse frequencies according to the original RoPE implementation
834
+ Args:
835
+ config ([`~transformers.PreTrainedConfig`]):
836
+ The model configuration.
837
+ device (`torch.device`):
838
+ The device to use for initialization of the inverse frequencies.
839
+ seq_len (`int`, *optional*):
840
+ The current sequence length. Unused for this type of RoPE.
841
+ Returns:
842
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
843
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
844
+ """
845
+ base = config.rope_parameters["rope_theta"]
846
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
847
+
848
+ attention_factor = 1.0 # Unused in this type of RoPE
849
+
850
+ # Compute the inverse frequencies
851
+ inv_freq = 1.0 / (
852
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
853
+ )
854
+ return inv_freq, attention_factor
855
+
856
+ # Ignore copy
857
+ def forward(self, x, position_ids):
858
+ # In contrast to other models, PaddleOCR has different position ids for the grids
859
+ # So we expand the inv_freq to shape (3, ...)
860
+ inv_freq_expanded = self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1)
861
+ position_ids_expanded = position_ids[:, :, None, :].float() # shape (3, bs, 1, positions)
862
+
863
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
864
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
865
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(2, 3)
866
+ emb = torch.cat((freqs, freqs), dim=-1)
867
+ cos = emb.cos() * self.attention_scaling
868
+ sin = emb.sin() * self.attention_scaling
869
+
870
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
871
+
872
+
873
+ @use_kernel_forward_from_hub("RMSNorm")
874
+ class VenusOCRRMSNorm(nn.Module):
875
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
876
+ """
877
+ Qwen3VLTextRMSNorm is equivalent to T5LayerNorm
878
+ """
879
+ super().__init__()
880
+ self.weight = nn.Parameter(torch.ones(hidden_size))
881
+ self.variance_epsilon = eps
882
+
883
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
884
+ input_dtype = hidden_states.dtype
885
+ hidden_states = hidden_states.to(torch.float32)
886
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
887
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
888
+ return self.weight * hidden_states.to(input_dtype)
889
+
890
+ def extra_repr(self):
891
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
892
+
893
+
894
+ class VenusOCRTextAttention(nn.Module):
895
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
896
+
897
+ def __init__(self, config, layer_idx: int):
898
+ super().__init__()
899
+ self.layer_type = config.layer_types[layer_idx] if hasattr(config, "layer_types") else None
900
+
901
+ self.config = config
902
+ self.layer_idx = layer_idx
903
+
904
+ self.hidden_size = config.hidden_size
905
+ self.num_heads = config.num_attention_heads
906
+ self.head_dim = getattr(config, "head_dim", self.hidden_size // self.num_heads)
907
+ self.num_key_value_heads = config.num_key_value_heads
908
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
909
+ self.scaling = self.head_dim**-0.5
910
+ self.attention_dropout = config.attention_dropout
911
+ self.rope_parameters = config.rope_parameters
912
+ self.is_causal = True
913
+
914
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
915
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
916
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
917
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
918
+ self.q_norm = VenusOCRRMSNorm(self.head_dim, eps=config.rms_norm_eps) # unlike olmo, only on the head dim!
919
+ self.k_norm = VenusOCRRMSNorm(self.head_dim, eps=config.rms_norm_eps) # thus post q_norm does not need reshape
920
+
921
+ def forward(
922
+ self,
923
+ hidden_states: torch.Tensor,
924
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
925
+ attention_mask: torch.Tensor | None,
926
+ past_key_values: Cache | None = None,
927
+ **kwargs,
928
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
929
+ input_shape = hidden_states.shape[:-1]
930
+ hidden_shape = (*input_shape, -1, self.head_dim)
931
+
932
+ query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
933
+ key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
934
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
935
+
936
+ cos, sin = position_embeddings
937
+ query_states, key_states = apply_multimodal_rotary_pos_emb(query_states, key_states, cos, sin, self.config.rope_parameters["mrope_section"])
938
+
939
+ if past_key_values is not None:
940
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
941
+
942
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
943
+ self.config._attn_implementation, eager_attention_forward
944
+ )
945
+
946
+ attn_output, attn_weights = attention_interface(
947
+ self,
948
+ query_states,
949
+ key_states,
950
+ value_states,
951
+ attention_mask,
952
+ dropout=0.0 if not self.training else self.attention_dropout,
953
+ scaling=self.scaling,
954
+ **kwargs,
955
+ )
956
+
957
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
958
+ attn_output = self.o_proj(attn_output)
959
+ return attn_output, attn_weights
960
+
961
+
962
+ class VenusOCRTextMLP(nn.Module):
963
+ def __init__(self, config):
964
+ super().__init__()
965
+ self.config = config
966
+ self.hidden_size = config.hidden_size
967
+ self.intermediate_size = config.intermediate_size
968
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
969
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
970
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
971
+ self.act_fn = ACT2FN[config.hidden_act]
972
+
973
+ def forward(self, x):
974
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
975
+ return down_proj
976
+
977
+
978
+ class VenusOCRTextDecoderLayer(GradientCheckpointingLayer):
979
+ def __init__(self, config, layer_idx: int):
980
+ super().__init__()
981
+ self.hidden_size = config.hidden_size
982
+
983
+ self.self_attn = VenusOCRTextAttention(config=config, layer_idx=layer_idx)
984
+
985
+ self.mlp = VenusOCRTextMLP(config)
986
+ self.input_layernorm = VenusOCRRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
987
+ self.post_attention_layernorm = VenusOCRRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
988
+
989
+ def forward(
990
+ self,
991
+ hidden_states: torch.Tensor,
992
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
993
+ attention_mask: torch.Tensor | None = None,
994
+ position_ids: torch.LongTensor | None = None,
995
+ past_key_values: Cache | None = None,
996
+ use_cache: bool | None = False,
997
+ **kwargs,
998
+ ) -> torch.Tensor:
999
+ residual = hidden_states
1000
+ hidden_states = self.input_layernorm(hidden_states)
1001
+ # Self Attention
1002
+ hidden_states, _ = self.self_attn(
1003
+ hidden_states=hidden_states,
1004
+ attention_mask=attention_mask,
1005
+ position_ids=position_ids,
1006
+ past_key_values=past_key_values,
1007
+ use_cache=use_cache,
1008
+ position_embeddings=position_embeddings,
1009
+ **kwargs,
1010
+ )
1011
+ hidden_states = residual + hidden_states
1012
+
1013
+ # Fully Connected
1014
+ residual = hidden_states
1015
+ hidden_states = self.post_attention_layernorm(hidden_states)
1016
+ hidden_states = self.mlp(hidden_states)
1017
+ hidden_states = residual + hidden_states
1018
+ return hidden_states
1019
+
1020
+
1021
+ class VenusOCRTextModel(VenusOCRPreTrainedModel):
1022
+ input_modalities = ("text",)
1023
+ def __init__(self, config) -> None:
1024
+ super().__init__(config)
1025
+ self.padding_idx = config.pad_token_id
1026
+ self.vocab_size = config.vocab_size
1027
+
1028
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1029
+ self.layers = nn.ModuleList(
1030
+ [VenusOCRTextDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1031
+ )
1032
+ self.norm = VenusOCRRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1033
+ self.rotary_emb = VenusOCRRotaryEmbedding(config=config)
1034
+ self.gradient_checkpointing = False
1035
+
1036
+ # Initialize weights and apply final processing
1037
+ self.post_init()
1038
+
1039
+ @merge_with_config_defaults
1040
+ @capture_outputs
1041
+ @auto_docstring
1042
+ def forward(
1043
+ self,
1044
+ input_ids: torch.LongTensor | None = None,
1045
+ attention_mask: torch.Tensor | None = None,
1046
+ position_ids: torch.LongTensor | None = None,
1047
+ past_key_values: Cache | None = None,
1048
+ inputs_embeds: torch.FloatTensor | None = None,
1049
+ use_cache: bool | None = None,
1050
+ **kwargs,
1051
+ ) -> BaseModelOutputWithPast:
1052
+ if (input_ids is None) ^ (inputs_embeds is not None):
1053
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
1054
+
1055
+ if inputs_embeds is None:
1056
+ inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
1057
+
1058
+ if use_cache and past_key_values is None and not torch.jit.is_tracing():
1059
+ past_key_values = DynamicCache(config=self.config)
1060
+
1061
+ if inputs_embeds is None:
1062
+ inputs_embeds = self.embed_tokens(input_ids)
1063
+
1064
+ # the hard coded `4` is for text, temporal, height and width.
1065
+ if position_ids is None:
1066
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1067
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
1068
+ position_ids = position_ids.view(1, 1, -1).expand(3, inputs_embeds.shape[0], -1)
1069
+ elif position_ids.ndim == 2:
1070
+ position_ids = position_ids[None, ...].expand(3, position_ids.shape[0], -1)
1071
+
1072
+ if position_ids.ndim == 3 and position_ids.shape[0] == 4:
1073
+ text_position_ids = position_ids[0]
1074
+ position_ids = position_ids[1:]
1075
+ else:
1076
+ text_position_ids = None
1077
+
1078
+ causal_mask = create_causal_mask(
1079
+ config=self.config,
1080
+ inputs_embeds=inputs_embeds,
1081
+ attention_mask=attention_mask,
1082
+ past_key_values=past_key_values,
1083
+ position_ids=text_position_ids,
1084
+ )
1085
+
1086
+ hidden_states = inputs_embeds
1087
+
1088
+ # create position embeddings to be shared across the decoder layers
1089
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
1090
+
1091
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
1092
+ hidden_states = decoder_layer(
1093
+ hidden_states,
1094
+ attention_mask=causal_mask,
1095
+ position_embeddings=position_embeddings,
1096
+ position_ids=text_position_ids,
1097
+ past_key_values=past_key_values,
1098
+ use_cache=use_cache,
1099
+ **kwargs,
1100
+ )
1101
+
1102
+ hidden_states = self.norm(hidden_states)
1103
+ return BaseModelOutputWithPast(
1104
+ last_hidden_state=hidden_states,
1105
+ past_key_values=past_key_values,
1106
+ )
1107
+
1108
+
1109
+ @auto_docstring
1110
+ class VenusOCRModel(VenusOCRPreTrainedModel):
1111
+ base_model_prefix = "model"
1112
+ # Reference: fix gemma3 grad acc #37208
1113
+ accepts_loss_kwargs = False
1114
+ config: VenusOCRConfig
1115
+
1116
+ def __init__(self, config) -> None:
1117
+ super().__init__(config)
1118
+ # Propagate _attn_implementation to vision_config so that
1119
+ # VenusOCRVisionAttention.forward() correctly enters the FA2 branch.
1120
+ attn_impl = getattr(config, "_attn_implementation", "eager")
1121
+ config.vision_config._attn_implementation = attn_impl
1122
+ self.visual = VenusOCRVisionTransformer._from_config(config.vision_config)
1123
+ self.projector = VenusOCRProjector(config)
1124
+ self.language_model = VenusOCRTextModel._from_config(config.text_config)
1125
+
1126
+ # Cached rope offset for incremental decoding with 2D M-RoPE.
1127
+ # Shape: (batch_size, 1) – set during prefill, reused during decode.
1128
+ self.rope_deltas = None
1129
+
1130
+ self.post_init()
1131
+
1132
+ def get_input_embeddings(self) -> nn.Module:
1133
+ return self.language_model.get_input_embeddings()
1134
+
1135
+ def set_input_embeddings(self, value: nn.Module) -> None:
1136
+ self.language_model.set_input_embeddings(value)
1137
+
1138
+ def get_vision_position_ids(
1139
+ self,
1140
+ start_position: int,
1141
+ grid_thw: list[int, int, int] | torch.Tensor,
1142
+ temp_merge_size: int = 1,
1143
+ spatial_merge_size: int = 1,
1144
+ time_interval: int = 1,
1145
+ device: str | torch.device | None = None,
1146
+ ):
1147
+ """
1148
+ Compute 3D positional indices for vision tokens derived from a single image or video input.
1149
+
1150
+ The positions are generated from the input grid defined by temporal (T), height (H), and
1151
+ width (W) dimensions. Temporal and spatial dimensions can be downscaled according to the
1152
+ merge sizes used in the vision backbone. The resulting positions are offset by `start_position`.
1153
+
1154
+ Args:
1155
+ start_position (`int`):
1156
+ Offset added to all computed positional indices.
1157
+ grid_thw (`Sequence[int]` or `torch.Tensor` of shape `(3,)`):
1158
+ The (T, H, W) grid representing the feature layout of the current image or video after patch embedding.
1159
+ temp_merge_size (`int`, *optional*):
1160
+ Factor by which the temporal dimension is reduced in the backbone. The temporal grid size is divided
1161
+ by this value. Defaults to 1.
1162
+ spatial_merge_size (`int`, *optional*):
1163
+ Factor by which the spatial dimensions (H and W) are reduced in the backbone. Both H and W are divided
1164
+ by this value. Defaults to 1.
1165
+ time_interval (`int`, *optional*):
1166
+ Spacing factor applied between consecutive temporal position indices.Defaults to 1.
1167
+ device (`str` or `torch.device`, *optional*):
1168
+ Device on which the resulting tensor is allocated. If `None`, uses the current default device.
1169
+
1170
+ Returns:
1171
+ torch.LongTensor of shape (3, sequence_length):
1172
+ Positional indices for temporal, height, and width dimensions,
1173
+ flattened into sequence form and offset by `start_position`.
1174
+ """
1175
+ llm_grid_t, llm_grid_h, llm_grid_w = (
1176
+ grid_thw[0].item() // temp_merge_size,
1177
+ grid_thw[1].item() // spatial_merge_size,
1178
+ grid_thw[2].item() // spatial_merge_size,
1179
+ )
1180
+
1181
+ image_seq_length = llm_grid_h * llm_grid_w * llm_grid_t
1182
+ position_width = torch.arange(start_position, start_position + llm_grid_w, device=device).repeat(
1183
+ llm_grid_h * llm_grid_t
1184
+ )
1185
+ position_height = torch.arange(start_position, start_position + llm_grid_h, device=device).repeat_interleave(
1186
+ llm_grid_w * llm_grid_t
1187
+ )
1188
+ position_temporal = torch.full((image_seq_length,), start_position, device=device, dtype=torch.long)
1189
+ position_temporal = position_temporal * time_interval
1190
+ vision_position_ids = torch.stack([position_temporal, position_height, position_width], dim=0)
1191
+
1192
+ return vision_position_ids
1193
+
1194
+ def get_rope_index(
1195
+ self,
1196
+ input_ids: torch.LongTensor,
1197
+ mm_token_type_ids: torch.IntTensor,
1198
+ image_grid_thw: torch.LongTensor | None = None,
1199
+ video_grid_thw: torch.LongTensor | None = None,
1200
+ attention_mask: torch.Tensor | None = None,
1201
+ seq_ids: torch.LongTensor | None = None,
1202
+ **kwargs,
1203
+ ) -> tuple[torch.Tensor, torch.Tensor]:
1204
+ """Compute 4D M-RoPE position ids with optional sub-sequence (packing) awareness.
1205
+
1206
+ Channels of the returned ``position_ids`` (shape ``(4, B, T)``):
1207
+ - ``[0]`` text 1D axis – advances by 1 per token regardless of modality;
1208
+ **resets to 0 at every sub-sequence boundary** when ``seq_ids`` is
1209
+ provided. Consumed by the LLM's attention layer for FA2 varlen
1210
+ ``cu_seqlens`` reset detection and for ``create_causal_mask``.
1211
+ - ``[1]`` temporal axis (vision tokens use ``start_position`` constant,
1212
+ text tokens advance like the text axis).
1213
+ - ``[2]`` height axis (varies inside an image, constant for text).
1214
+ - ``[3]`` width axis (varies inside an image, constant for text).
1215
+
1216
+ Args:
1217
+ input_ids: ``(B, T)`` token ids.
1218
+ mm_token_type_ids: ``(B, T)`` modality ids (0=text, 1=image, 2=video).
1219
+ image_grid_thw: ``(num_images, 3)`` ``(T, H, W)`` per image.
1220
+ video_grid_thw: ``(num_videos, 3)`` ``(T, H, W)`` per video.
1221
+ attention_mask: optional ``(B, T)`` mask to ignore padding.
1222
+ seq_ids: optional ``(B, T)`` sub-sequence id per token (for
1223
+ sequence packing). Same value within a sub-seq, different value
1224
+ between adjacent sub-seqs marks a boundary at which BOTH the
1225
+ text axis and the vision ``start_position`` reset to 0. When
1226
+ ``None`` (default / non-packing), the whole row is treated as a
1227
+ single sub-sequence – behaviour matches the original
1228
+ non-packing path.
1229
+
1230
+ Returns:
1231
+ position_ids: ``(4, B, T)`` LongTensor.
1232
+ mrope_position_deltas: ``(B, 1)`` – ``max(position) + 1 - seq_len``.
1233
+ """
1234
+ spatial_merge_size = self.config.vision_config.spatial_merge_size
1235
+
1236
+ mrope_position_deltas = []
1237
+ # 4 channels: text(0), temporal(1), height(2), width(3)
1238
+ position_ids = torch.zeros(
1239
+ 4,
1240
+ input_ids.shape[0],
1241
+ input_ids.shape[1],
1242
+ dtype=input_ids.dtype,
1243
+ device=input_ids.device,
1244
+ )
1245
+ grid_iters = {
1246
+ 1: iter(image_grid_thw) if image_grid_thw is not None else None,
1247
+ 2: iter(video_grid_thw) if video_grid_thw is not None else None,
1248
+ }
1249
+
1250
+ for batch_idx, current_input_ids in enumerate(input_ids):
1251
+ input_token_type = mm_token_type_ids[batch_idx]
1252
+ current_seq_ids = seq_ids[batch_idx] if seq_ids is not None else None
1253
+ if attention_mask is not None:
1254
+ mask_bool = attention_mask[batch_idx].bool()
1255
+ current_input_ids = current_input_ids[mask_bool]
1256
+ input_token_type = input_token_type[mask_bool]
1257
+ if current_seq_ids is not None:
1258
+ current_seq_ids = current_seq_ids[mask_bool]
1259
+
1260
+ # Group by (modality, seq_id) so that runs are split BOTH at modality
1261
+ # changes and sub-seq boundaries. When seq_ids is None we fall back
1262
+ # to grouping by modality alone (one sub-seq for the whole row).
1263
+ if current_seq_ids is not None:
1264
+ pair_iter = zip(input_token_type.tolist(), current_seq_ids.tolist())
1265
+ key_fn = lambda x: x[1] # group by (modality, seq_id) tuple
1266
+ else:
1267
+ pair_iter = ((m, 0) for m in input_token_type.tolist())
1268
+ key_fn = lambda x: x[1][0] # group by modality only
1269
+
1270
+ input_type_group = []
1271
+ for key, group in itertools.groupby(enumerate(pair_iter), key_fn):
1272
+ group = list(group)
1273
+ start_index = group[0][0]
1274
+ end_index = group[-1][0] + 1
1275
+ if isinstance(key, tuple):
1276
+ modality_type, seg_seq_id = key
1277
+ else:
1278
+ modality_type, seg_seq_id = key, 0
1279
+ input_type_group.append((modality_type, seg_seq_id, start_index, end_index))
1280
+
1281
+ text_pos = 0 # text 1D axis counter (advances 1 per token)
1282
+ vision_pos = 0 # vision-axes start_position counter (matches legacy current_pos)
1283
+ prev_seq_id = None
1284
+ llm_pos_ids_list = [] # each element: (4, seg_len) tensor
1285
+ for modality_type, seg_seq_id, start_idx, end_idx in input_type_group:
1286
+ # Reset BOTH counters at every sub-seq boundary.
1287
+ if prev_seq_id is not None and seg_seq_id != prev_seq_id:
1288
+ text_pos = 0
1289
+ vision_pos = 0
1290
+ prev_seq_id = seg_seq_id
1291
+
1292
+ seg_len = end_idx - start_idx
1293
+ if modality_type == 0:
1294
+ # ---- text segment ----
1295
+ text_axis = (
1296
+ torch.arange(seg_len, device=input_ids.device, dtype=position_ids.dtype) + text_pos
1297
+ )
1298
+ vision_axis = (
1299
+ torch.arange(seg_len, device=input_ids.device, dtype=position_ids.dtype) + vision_pos
1300
+ )
1301
+ seg_pos = torch.stack(
1302
+ [text_axis, vision_axis, vision_axis, vision_axis], dim=0
1303
+ )
1304
+ llm_pos_ids_list.append(seg_pos)
1305
+ text_pos += seg_len
1306
+ vision_pos += seg_len
1307
+ else:
1308
+ # ---- image / video segment ----
1309
+ grid_thw = next(grid_iters[modality_type])
1310
+ vision_position_ids = self.get_vision_position_ids(
1311
+ vision_pos, grid_thw, 1, spatial_merge_size, device=input_ids.device
1312
+ ) # (3, seg_len) channels = (T, H, W)
1313
+ text_axis = (
1314
+ torch.arange(seg_len, device=input_ids.device, dtype=position_ids.dtype) + text_pos
1315
+ )
1316
+ seg_pos = torch.cat(
1317
+ [text_axis.unsqueeze(0), vision_position_ids.to(position_ids.dtype)], dim=0
1318
+ ) # (4, seg_len)
1319
+ llm_pos_ids_list.append(seg_pos)
1320
+ text_pos += seg_len
1321
+ vision_pos += max(grid_thw[1], grid_thw[2]) // spatial_merge_size
1322
+
1323
+ llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(4, -1)
1324
+ if attention_mask is not None:
1325
+ position_ids[:, batch_idx, attention_mask[batch_idx].bool()] = llm_positions.to(position_ids.device)
1326
+ else:
1327
+ position_ids[:, batch_idx] = llm_positions.to(position_ids.device)
1328
+ mrope_position_deltas.append(llm_positions.max() + 1 - len(current_input_ids))
1329
+ mrope_position_deltas = torch.tensor(mrope_position_deltas, device=input_ids.device).unsqueeze(1)
1330
+ return position_ids, mrope_position_deltas
1331
+
1332
+ def get_image_features(
1333
+ self,
1334
+ pixel_values: torch.FloatTensor,
1335
+ image_grid_thw: torch.LongTensor,
1336
+ **kwargs,
1337
+ ) -> torch.Tensor:
1338
+ """Run the vision encoder + projector, returning merged patch tokens.
1339
+
1340
+ Args:
1341
+ pixel_values: ``(total_patches, C, patch_size, patch_size)``
1342
+ pre-patchified tensor produced by the VenusOCR processor.
1343
+ image_grid_thw: ``(num_images, 3)`` grid metadata ``(t, h, w)``.
1344
+
1345
+ Returns:
1346
+ ``(total_merged_tokens, text_hidden_size)`` projected features.
1347
+ """
1348
+ pixel_values = pixel_values.to(dtype=self.visual.dtype) # type: ignore[assignment]
1349
+
1350
+ # Compute cumulative sequence lengths for packed attention (FA2)
1351
+ cu_seqlens = torch.repeat_interleave(
1352
+ image_grid_thw[:, 1] * image_grid_thw[:, 2],
1353
+ image_grid_thw[:, 0],
1354
+ ).cumsum(
1355
+ dim=0,
1356
+ dtype=image_grid_thw.dtype if torch.jit.is_tracing() else torch.int32, # type: ignore[attr-defined]
1357
+ )
1358
+ cu_seqlens = F.pad(cu_seqlens, (1, 0), value=0)
1359
+
1360
+ vision_outputs = self.visual(
1361
+ pixel_values=pixel_values,
1362
+ cu_seqlens=cu_seqlens,
1363
+ image_grid_thw=image_grid_thw,
1364
+ return_dict=True,
1365
+ **kwargs,
1366
+ )
1367
+ image_embeds = vision_outputs.last_hidden_state
1368
+ image_embeds = self.projector(image_embeds, image_grid_thw)
1369
+ vision_outputs.pooler_output = image_embeds
1370
+
1371
+ return vision_outputs
1372
+
1373
+ def get_placeholder_mask(
1374
+ self,
1375
+ input_ids: torch.LongTensor,
1376
+ inputs_embeds: torch.FloatTensor,
1377
+ image_features: torch.FloatTensor,
1378
+ ):
1379
+ """
1380
+ Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
1381
+ equal to the length of multimodal features. If the lengths are different, an error is raised.
1382
+ """
1383
+ if input_ids is None:
1384
+ special_image_mask = inputs_embeds == self.get_input_embeddings()(
1385
+ torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
1386
+ )
1387
+ special_image_mask = special_image_mask.all(-1)
1388
+ else:
1389
+ special_image_mask = input_ids == self.config.image_token_id
1390
+
1391
+ n_image_tokens = special_image_mask.sum()
1392
+ special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
1393
+ n_image_features = image_features.shape[0] * image_features.shape[1]
1394
+ torch_compilable_check(
1395
+ inputs_embeds[special_image_mask].numel() == image_features.numel(),
1396
+ f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}",
1397
+ )
1398
+ return special_image_mask
1399
+
1400
+ def compute_3d_position_ids(
1401
+ self,
1402
+ input_ids: torch.Tensor | None,
1403
+ inputs_embeds: torch.Tensor | None,
1404
+ image_grid_thw: torch.Tensor | None = None,
1405
+ video_grid_thw: torch.Tensor | None = None,
1406
+ attention_mask: torch.Tensor | None = None,
1407
+ past_key_values: torch.Tensor | None = None,
1408
+ mm_token_type_ids: torch.IntTensor | None = None,
1409
+ seq_ids: torch.LongTensor | None = None,
1410
+ ) -> torch.Tensor | None:
1411
+ past_key_values_length = 0 if past_key_values is None else past_key_values.get_seq_length()
1412
+ has_multimodal = image_grid_thw is not None or video_grid_thw is not None
1413
+ if has_multimodal and mm_token_type_ids is None and input_ids is not None:
1414
+ raise ValueError(
1415
+ "Multimodal data was passed (via `image_grid_thw` or `video_grid_thw`) but `mm_token_type_ids` is "
1416
+ "missing. Please pass `mm_token_type_ids` to the model so that multimodal RoPE (M-RoPE) can be "
1417
+ "computed correctly. `mm_token_type_ids` is returned by the processor alongside `input_ids`."
1418
+ )
1419
+ can_compute_mrope = input_ids is not None and mm_token_type_ids is not None and has_multimodal
1420
+
1421
+ if can_compute_mrope and (self.rope_deltas is None or past_key_values_length == 0):
1422
+ position_ids, rope_deltas = self.get_rope_index(
1423
+ input_ids,
1424
+ image_grid_thw=image_grid_thw,
1425
+ video_grid_thw=video_grid_thw,
1426
+ attention_mask=attention_mask,
1427
+ mm_token_type_ids=mm_token_type_ids,
1428
+ seq_ids=seq_ids,
1429
+ )
1430
+ self.rope_deltas = rope_deltas
1431
+ # Use pre-calculated rope-deltas to infer correct 4D position ids during incremental
1432
+ # generation (past_key_values_length > 0) or when only inputs_embeds is provided (no input_ids
1433
+ # to recompute from). Skip when input_ids is provided without past_key_values to avoid shape
1434
+ # mismatches from stale rope_deltas (e.g., training forward pass after generation).
1435
+ elif self.rope_deltas is not None and (past_key_values_length > 0 or input_ids is None):
1436
+ batch_size, seq_length, _ = inputs_embeds.shape
1437
+ if attention_mask is not None:
1438
+ position_ids = attention_mask.long().cumsum(-1) - 1
1439
+ position_ids = position_ids.masked_fill(attention_mask == 0, 0)
1440
+ # 4 channels: text(0), temporal(1), height(2), width(3)
1441
+ position_ids = position_ids.view(1, batch_size, -1).repeat(4, 1, 1).to(inputs_embeds.device)
1442
+ else:
1443
+ position_ids = torch.arange(past_key_values_length, past_key_values_length + seq_length)
1444
+ position_ids = position_ids.view(1, 1, -1).expand(4, batch_size, -1).to(inputs_embeds.device)
1445
+ delta = self.rope_deltas.repeat_interleave(batch_size // self.rope_deltas.shape[0], dim=0)
1446
+ position_ids = position_ids + delta.to(device=inputs_embeds.device)
1447
+ else:
1448
+ # Can't build correct M-RoPE positions. Let the model infer it.
1449
+ position_ids = None
1450
+ return position_ids
1451
+
1452
+ @can_return_tuple
1453
+ @auto_docstring
1454
+ def forward(
1455
+ self,
1456
+ input_ids: Optional[torch.LongTensor] = None,
1457
+ attention_mask: Optional[torch.Tensor] = None,
1458
+ position_ids: Optional[torch.LongTensor] = None,
1459
+ past_key_values: Optional[Cache] = None,
1460
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1461
+ use_cache: Optional[bool] = None,
1462
+ pixel_values: Optional[torch.FloatTensor] = None,
1463
+ image_grid_thw: Optional[torch.LongTensor] = None,
1464
+ mm_token_type_ids: Optional[torch.IntTensor] = None,
1465
+ seq_ids: Optional[torch.LongTensor] = None,
1466
+ **kwargs,
1467
+ ) -> Union[tuple, VenusOCRModelOutputWithPast]:
1468
+ r"""
1469
+ pixel_values (`torch.FloatTensor`, *optional*):
1470
+ Pre-patchified tensor ``(total_patches, C, patch_size, patch_size)``.
1471
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
1472
+ ``(temporal, height, width)`` grid size for each image.
1473
+ mm_token_type_ids (`torch.IntTensor` of shape `(batch_size, seq_len)`, *optional*):
1474
+ Modality type ids: 0=text, 1=image. Returned by the processor.
1475
+ seq_ids (`torch.LongTensor` of shape `(batch_size, seq_len)`, *optional*):
1476
+ Per-token sub-sequence id used by sequence packing. Different
1477
+ values delimit packed sub-sequences and trigger M-RoPE position
1478
+ resets at their boundaries (see ``get_rope_index``). When
1479
+ ``None`` the whole row is treated as a single sub-sequence.
1480
+ """
1481
+ if (input_ids is None) ^ (inputs_embeds is not None):
1482
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
1483
+
1484
+ if inputs_embeds is None:
1485
+ inputs_embeds = self.get_input_embeddings()(input_ids)
1486
+
1487
+ if pixel_values is not None:
1488
+ image_outputs = self.get_image_features(
1489
+ pixel_values=pixel_values,
1490
+ image_grid_thw=image_grid_thw,
1491
+ )
1492
+ image_embeds = image_outputs.pooler_output
1493
+ image_embeds = image_embeds.to(inputs_embeds.device, inputs_embeds.dtype)
1494
+ image_mask = self.get_placeholder_mask(
1495
+ input_ids=input_ids,
1496
+ inputs_embeds=inputs_embeds,
1497
+ image_features=image_embeds,
1498
+ )
1499
+ inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds) # type: ignore[assignment]
1500
+
1501
+ if position_ids is None:
1502
+ position_ids = self.compute_3d_position_ids( # type: ignore[assignment]
1503
+ input_ids=input_ids,
1504
+ inputs_embeds=inputs_embeds,
1505
+ image_grid_thw=image_grid_thw,
1506
+ attention_mask=attention_mask,
1507
+ past_key_values=past_key_values,
1508
+ mm_token_type_ids=mm_token_type_ids,
1509
+ seq_ids=seq_ids,
1510
+ )
1511
+
1512
+ outputs = self.language_model(
1513
+ input_ids=None,
1514
+ attention_mask=attention_mask,
1515
+ position_ids=position_ids,
1516
+ past_key_values=past_key_values,
1517
+ inputs_embeds=inputs_embeds,
1518
+ use_cache=use_cache,
1519
+ **kwargs,
1520
+ )
1521
+
1522
+ return VenusOCRModelOutputWithPast(
1523
+ **outputs,
1524
+ rope_deltas=self.rope_deltas, # type: ignore[arg-type]
1525
+ )
1526
+
1527
+
1528
+ @auto_docstring(
1529
+ custom_intro="""
1530
+ VenusOCR multimodal model with a language modelling head on top, suitable
1531
+ for conditional text generation from image-text interleaved sequences.
1532
+
1533
+ The model architecture is:
1534
+
1535
+ 1. **Vision encoder** – SigLIP-based ViT (customised with 2D RoPE + packed-sequence attention)
1536
+ 2. **Spatial-merge projector** – groups spatial_merge_size² patches, MLP to LLM hidden size
1537
+ 3. **Language decoder** – Qwen3-0.6B causal language model
1538
+ """
1539
+ )
1540
+ class VenusOCRForConditionalGeneration(VenusOCRPreTrainedModel, GenerationMixin):
1541
+ _tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"}
1542
+ # Tell HF Trainer to pass num_items_in_batch (and other loss kwargs) into forward().
1543
+ accepts_loss_kwargs = True
1544
+
1545
+ def __init__(self, config: VenusOCRConfig) -> None:
1546
+ super().__init__(config)
1547
+ self.model = VenusOCRModel(config)
1548
+ self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
1549
+ self.post_init()
1550
+
1551
+ def get_input_embeddings(self) -> nn.Module:
1552
+ return self.model.get_input_embeddings()
1553
+
1554
+ def set_input_embeddings(self, value: nn.Module) -> None:
1555
+ self.model.set_input_embeddings(value)
1556
+
1557
+ def get_image_features(
1558
+ self,
1559
+ pixel_values: torch.FloatTensor,
1560
+ image_grid_thw: torch.LongTensor,
1561
+ **kwargs,
1562
+ ) -> torch.Tensor:
1563
+ """Convenience wrapper – see :meth:`VenusOCRModel.get_image_features`."""
1564
+ return self.model.get_image_features(pixel_values=pixel_values, image_grid_thw=image_grid_thw, **kwargs,)
1565
+
1566
+ @can_return_tuple
1567
+ @auto_docstring
1568
+ def forward(
1569
+ self,
1570
+ input_ids: Optional[torch.LongTensor] = None,
1571
+ pixel_values: Optional[torch.FloatTensor] = None,
1572
+ image_grid_thw: Optional[torch.LongTensor] = None,
1573
+ attention_mask: Optional[torch.Tensor] = None,
1574
+ position_ids: Optional[torch.LongTensor] = None,
1575
+ past_key_values: Optional[Cache] = None,
1576
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1577
+ mm_token_type_ids: Optional[torch.IntTensor] = None,
1578
+ seq_ids: Optional[torch.LongTensor] = None,
1579
+ labels: Optional[torch.LongTensor] = None,
1580
+ logits_to_keep: Union[int, torch.Tensor] = 0,
1581
+ num_items_in_batch: Optional[int] = None,
1582
+ **kwargs,
1583
+ ) -> Union[tuple, VenusOCRCausalLMOutputWithPast]:
1584
+ r"""
1585
+ pixel_values (`torch.FloatTensor`, *optional*):
1586
+ Pre-patchified tensor ``(total_patches, C, patch_size, patch_size)``.
1587
+ image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
1588
+ ``(temporal, height, width)`` grid size. Required for 2D M-RoPE.
1589
+ mm_token_type_ids (`torch.IntTensor`, *optional*):
1590
+ Modality type ids (0=text, 1=image). Returned by the processor.
1591
+ seq_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1592
+ Per-token sub-sequence id used by sequence packing. Different
1593
+ values delimit packed sub-sequences and trigger M-RoPE position
1594
+ resets at their boundaries (see ``VenusOCRModel.get_rope_index``).
1595
+ ``None`` (default) means the whole row is treated as a single
1596
+ sub-sequence (non-packing inference / training).
1597
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1598
+ Target token ids. Positions set to ``-100`` are ignored.
1599
+ logits_to_keep (`int` or `torch.Tensor`, *optional*, defaults to 0):
1600
+ If an ``int``, compute logits for only the last ``logits_to_keep`` tokens.
1601
+ ``0`` computes logits for all tokens.
1602
+ num_items_in_batch (`int`, *optional*):
1603
+ Number of sequences (or tokens, depending on loss_reduction_scope) in
1604
+ the full gradient-accumulation window across all devices. Supplied by
1605
+ VenusOCRTrainer.get_batch_samples and used by cross_entropy_loss for
1606
+ consistent normalisation regardless of world size.
1607
+
1608
+ Example::
1609
+
1610
+ >>> from transformers import AutoModelForCausalLM, AutoProcessor
1611
+
1612
+ >>> model = AutoModelForCausalLM.from_pretrained("VenusOCR/VenusOCR2-1B", trust_remote_code=True)
1613
+ >>> processor = AutoProcessor.from_pretrained("VenusOCR/VenusOCR2-1B", trust_remote_code=True)
1614
+
1615
+ >>> inputs = processor(images=image, text=prompt, return_tensors="pt")
1616
+ >>> output = model.generate(**inputs, max_new_tokens=256)
1617
+ """
1618
+ outputs = self.model(
1619
+ input_ids=input_ids,
1620
+ pixel_values=pixel_values,
1621
+ image_grid_thw=image_grid_thw,
1622
+ attention_mask=attention_mask,
1623
+ position_ids=position_ids,
1624
+ past_key_values=past_key_values,
1625
+ inputs_embeds=inputs_embeds,
1626
+ mm_token_type_ids=mm_token_type_ids,
1627
+ seq_ids=seq_ids,
1628
+ **kwargs,
1629
+ )
1630
+
1631
+ hidden_states = outputs[0]
1632
+
1633
+ slice_indices = (
1634
+ slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1635
+ )
1636
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
1637
+
1638
+ loss = None
1639
+ if labels is not None:
1640
+ reduction_scope = getattr(self.config, "loss_reduction_scope", "batch")
1641
+ loss_kwargs = {}
1642
+ if num_items_in_batch is not None:
1643
+ loss_kwargs["num_items_in_batch"] = num_items_in_batch
1644
+ # position_ids may be 3D (M-RoPE): take first row for sequence boundary detection
1645
+ _pos = outputs.get("position_ids", position_ids) if hasattr(outputs, "get") else position_ids
1646
+ if _pos is not None and _pos.dim() == 3:
1647
+ _pos = _pos[0] # (seq_len,) or (1, seq_len)
1648
+ loss = _cross_entropy_loss(
1649
+ hidden_states=hidden_states,
1650
+ lm_head=self.lm_head,
1651
+ position_ids=_pos if _pos is not None else torch.zeros(
1652
+ hidden_states.shape[:2], dtype=torch.long, device=hidden_states.device
1653
+ ),
1654
+ labels=labels,
1655
+ reduction_scope=reduction_scope,
1656
+ **loss_kwargs,
1657
+ )
1658
+
1659
+ return VenusOCRCausalLMOutputWithPast(
1660
+ loss=loss,
1661
+ logits=logits,
1662
+ past_key_values=outputs.past_key_values,
1663
+ hidden_states=outputs.hidden_states,
1664
+ attentions=outputs.attentions,
1665
+ rope_deltas=outputs.rope_deltas,
1666
+ )
1667
+
1668
+ def prepare_inputs_for_generation(
1669
+ self,
1670
+ input_ids,
1671
+ next_sequence_length=None,
1672
+ past_key_values=None,
1673
+ attention_mask=None,
1674
+ inputs_embeds=None,
1675
+ is_first_iteration=False,
1676
+ **kwargs,
1677
+ ):
1678
+ # Overwritten -- in specific circumstances we don't want to forward image inputs to the model
1679
+
1680
+ model_inputs = super().prepare_inputs_for_generation(
1681
+ input_ids,
1682
+ next_sequence_length=next_sequence_length,
1683
+ past_key_values=past_key_values,
1684
+ attention_mask=attention_mask,
1685
+ inputs_embeds=inputs_embeds,
1686
+ is_first_iteration=is_first_iteration,
1687
+ **kwargs,
1688
+ )
1689
+
1690
+ # Only pass pixel_values and image_grid_thw on the first generation step;
1691
+ # afterwards the image features are already in the KV-cache.
1692
+ if not is_first_iteration and model_inputs.get("use_cache", True):
1693
+ model_inputs["pixel_values"] = None
1694
+ model_inputs["image_grid_thw"] = None
1695
+
1696
+ return model_inputs
1697
+
1698
+ def _prepare_position_ids_for_generation(self, inputs_tensor, model_kwargs):
1699
+ # Overwritten -- requires 4D position ids for M-RoPE (text + temporal + height + width)
1700
+
1701
+ text_positions = super()._prepare_position_ids_for_generation(inputs_tensor, model_kwargs)
1702
+
1703
+ # Early exit in case we are continuing generation from past kv
1704
+ past_length = 0
1705
+ if (cache := model_kwargs.get("past_key_values")) is not None:
1706
+ past_length = cache.get_seq_length()
1707
+ if past_length != 0 and self.model.rope_deltas is not None:
1708
+ # Incremental decode: text_positions is (B, T), expand to (4, B, T) + delta
1709
+ position_ids = text_positions[None, ...].expand(4, -1, -1) + self.model.rope_deltas
1710
+ return position_ids
1711
+
1712
+ # Otherwise compute 4D position ids for vision tokens
1713
+ if "input_ids" in model_kwargs and model_kwargs["input_ids"].shape[1] > 0:
1714
+ inputs_tensor = model_kwargs["input_ids"]
1715
+
1716
+ is_input_ids = len(inputs_tensor.shape) == 2 and inputs_tensor.dtype in [torch.int, torch.long]
1717
+ if (
1718
+ is_input_ids
1719
+ and model_kwargs.get("mm_token_type_ids") is not None
1720
+ and model_kwargs.get("image_grid_thw") is not None
1721
+ ):
1722
+ model_kwargs = {k: v for k, v in model_kwargs.items() if k != "input_ids"}
1723
+ # get_rope_index returns (4, B, T) position_ids already containing
1724
+ # [text_axis, temporal, height, width]
1725
+ position_ids, rope_deltas = self.model.get_rope_index(inputs_tensor, **model_kwargs)
1726
+ self.model.rope_deltas = rope_deltas
1727
+ else:
1728
+ # Pure text: all 4 channels use the same text_positions
1729
+ position_ids = text_positions[None, ...].expand(4, -1, -1).contiguous()
1730
+ self.model.rope_deltas = torch.zeros(
1731
+ inputs_tensor.shape[0], 1, dtype=torch.long, device=inputs_tensor.device
1732
+ )
1733
+
1734
+ return position_ids
1735
+
1736
+ def _get_image_nums(
1737
+ self,
1738
+ input_ids: Optional[torch.LongTensor],
1739
+ inputs_embeds: Optional[torch.Tensor] = None,
1740
+ ) -> torch.Tensor:
1741
+ """
1742
+ Get the number of images for each sample in the batch.
1743
+
1744
+ Args:
1745
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1746
+ Indices of input sequence tokens in the vocabulary.
1747
+ inputs_embeds (`torch.Tensor`, *optional*):
1748
+ Optional input embeddings (used when input_ids is None).
1749
+
1750
+ Returns:
1751
+ image_nums (`torch.LongTensor` of shape `(batch_size,)`)
1752
+ """
1753
+ image_token_id = self.config.image_token_id
1754
+
1755
+ if inputs_embeds is not None:
1756
+ image_mask = (
1757
+ inputs_embeds
1758
+ == self.get_input_embeddings()(
1759
+ torch.tensor(image_token_id, dtype=torch.long, device=inputs_embeds.device)
1760
+ )
1761
+ )[..., 0]
1762
+ device = inputs_embeds.device
1763
+ batch_size = inputs_embeds.shape[0]
1764
+ else:
1765
+ image_mask = input_ids == image_token_id
1766
+ device = input_ids.device
1767
+ batch_size = input_ids.shape[0]
1768
+
1769
+ # Count number of contiguous image-token blocks per sample (= number of images)
1770
+ image_nums = torch.zeros(batch_size, dtype=torch.long, device=device)
1771
+ for b in range(batch_size):
1772
+ mask_b = image_mask[b]
1773
+ if mask_b.any():
1774
+ padded = torch.cat([mask_b.new_zeros(1), mask_b])
1775
+ rising_edges = (padded[1:].long() - padded[:-1].long()).clamp(min=0)
1776
+ image_nums[b] = rising_edges.sum()
1777
+ return image_nums
1778
+
1779
+ @staticmethod
1780
+ def _expand_inputs_for_generation(
1781
+ expand_size: int = 1,
1782
+ is_encoder_decoder: bool = False,
1783
+ input_ids: Optional[torch.LongTensor] = None,
1784
+ **model_kwargs,
1785
+ ) -> tuple:
1786
+ # Overwritten -- support for expanding tensors without a batch size dimension
1787
+ # e.g., pixel_values (shape: [total_patches, C, pH, pW]) and image_grid_thw (shape: [num_images, 3])
1788
+ # whose first dimension is NOT the batch size.
1789
+
1790
+ if expand_size == 1:
1791
+ return input_ids, model_kwargs
1792
+
1793
+ visual_keys = ["pixel_values", "image_grid_thw"]
1794
+
1795
+ def _get_image_nums_static(input_ids_local, model_kwargs_local):
1796
+ """Count contiguous image-token groups per sample."""
1797
+ from .configuration_venusocr import VenusOCRConfig # avoid circular at module level
1798
+ # Obtain image_token_id via model_kwargs if possible; fall back to searching input_ids
1799
+ image_grid_thw = model_kwargs_local.get("image_grid_thw", None)
1800
+ if image_grid_thw is None or input_ids_local is None:
1801
+ return None
1802
+ # Simple heuristic: total images = image_grid_thw.shape[0], assume evenly distributed
1803
+ # across batch. For expand we just need per-sample image counts.
1804
+ # Use mm_token_type_ids if available, otherwise count from input_ids.
1805
+ mm_token_type_ids = model_kwargs_local.get("mm_token_type_ids", None)
1806
+ batch_size = input_ids_local.shape[0]
1807
+ if mm_token_type_ids is not None:
1808
+ # Count runs of type 1 (image) per sample
1809
+ image_nums = torch.zeros(batch_size, dtype=torch.long, device=input_ids_local.device)
1810
+ for b in range(batch_size):
1811
+ mask_b = (mm_token_type_ids[b] == 1)
1812
+ if mask_b.any():
1813
+ padded = torch.cat([mask_b.new_zeros(1), mask_b])
1814
+ rising = (padded[1:].long() - padded[:-1].long()).clamp(min=0)
1815
+ image_nums[b] = rising.sum()
1816
+ return image_nums
1817
+ return None
1818
+
1819
+ def _expand_dict_for_generation_visual(dict_to_expand):
1820
+ image_grid_thw = model_kwargs.get("image_grid_thw", None)
1821
+ if image_grid_thw is None:
1822
+ return dict_to_expand
1823
+
1824
+ image_nums = _get_image_nums_static(input_ids, model_kwargs)
1825
+ if image_nums is None:
1826
+ return dict_to_expand
1827
+
1828
+ def _repeat_interleave_samples(x, lengths, repeat_times):
1829
+ samples = torch.split(x, lengths)
1830
+ repeat_args = [repeat_times] + [1] * (x.dim() - 1)
1831
+ result = torch.cat([sample.repeat(*repeat_args) for sample in samples], dim=0)
1832
+ return result
1833
+
1834
+ for key in list(dict_to_expand.keys()):
1835
+ if key == "pixel_values" and dict_to_expand[key] is not None:
1836
+ samples = torch.split(image_grid_thw, image_nums.tolist())
1837
+ lengths = [int(s.prod(dim=1).sum().item()) for s in samples]
1838
+ dict_to_expand[key] = _repeat_interleave_samples(
1839
+ dict_to_expand[key], lengths=lengths, repeat_times=expand_size
1840
+ )
1841
+ elif key == "image_grid_thw" and dict_to_expand[key] is not None:
1842
+ lengths = image_nums.tolist()
1843
+ dict_to_expand[key] = _repeat_interleave_samples(
1844
+ dict_to_expand[key], lengths=lengths, repeat_times=expand_size
1845
+ )
1846
+ return dict_to_expand
1847
+
1848
+ def _expand_dict_for_generation(dict_to_expand):
1849
+ for key in dict_to_expand:
1850
+ if key == "position_ids" and dict_to_expand[key] is not None and dict_to_expand[key].ndim == 3:
1851
+ dict_to_expand[key] = dict_to_expand[key].repeat_interleave(expand_size, dim=1)
1852
+ elif (
1853
+ dict_to_expand[key] is not None
1854
+ and isinstance(dict_to_expand[key], torch.Tensor)
1855
+ and key not in visual_keys
1856
+ ):
1857
+ dict_to_expand[key] = dict_to_expand[key].repeat_interleave(expand_size, dim=0)
1858
+ return dict_to_expand
1859
+
1860
+ model_kwargs = _expand_dict_for_generation_visual(model_kwargs)
1861
+
1862
+ if input_ids is not None:
1863
+ input_ids = input_ids.repeat_interleave(expand_size, dim=0)
1864
+
1865
+ model_kwargs = _expand_dict_for_generation(model_kwargs)
1866
+
1867
+ if is_encoder_decoder:
1868
+ if model_kwargs.get("encoder_outputs") is None:
1869
+ raise ValueError("If `is_encoder_decoder` is True, make sure that `encoder_outputs` is defined.")
1870
+ model_kwargs["encoder_outputs"] = _expand_dict_for_generation(model_kwargs["encoder_outputs"])
1871
+
1872
+ return input_ids, model_kwargs
1873
+
1874
+
1875
+ __all__ = [
1876
+ "VenusOCRPreTrainedModel",
1877
+ "VenusOCRModel",
1878
+ "VenusOCRForConditionalGeneration",
1879
+ "VenusOCRVisionTransformer",
1880
+ "VenusOCRTextModel",
1881
+ ]
preprocessor_config.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoImageProcessor": "image_processing_venusocr.VenusOCRImageProcessor",
4
+ "AutoProcessor": "processing_venusocr.VenusOCRProcessor"
5
+ },
6
+ "do_convert_rgb": true,
7
+ "do_normalize": true,
8
+ "do_rescale": true,
9
+ "do_resize": true,
10
+ "image_mean": [
11
+ 0.5,
12
+ 0.5,
13
+ 0.5
14
+ ],
15
+ "image_processor_type": "VenusOCRImageProcessor",
16
+ "image_std": [
17
+ 0.5,
18
+ 0.5,
19
+ 0.5
20
+ ],
21
+ "max_pixels": 1605632,
22
+ "merge_size": 2,
23
+ "min_pixels": 147384,
24
+ "patch_size": 14,
25
+ "processor_class": "VenusOCRProcessor",
26
+ "resample": 3,
27
+ "rescale_factor": 0.00392156862745098,
28
+ "temporal_patch_size": 1
29
+ }
processing_venusocr.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The VenusOCR Authors and the HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from transformers.feature_extraction_utils import BatchFeature
16
+ from transformers.image_utils import ImageInput
17
+ from transformers.processing_utils import MultiModalData, ProcessingKwargs, ProcessorMixin, Unpack
18
+ from transformers.tokenization_utils_base import PreTokenizedInput, TextInput
19
+ from transformers.utils import logging
20
+ from transformers.utils.auto_docstring import auto_docstring
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+
26
+ class VenusOCRProcessorKwargs(ProcessingKwargs, total=False):
27
+ _defaults = {
28
+ "text_kwargs": {
29
+ "padding": False,
30
+ "return_token_type_ids": False,
31
+ "return_mm_token_type_ids": True,
32
+ },
33
+ }
34
+
35
+
36
+ @auto_docstring
37
+ class VenusOCRProcessor(ProcessorMixin):
38
+ r"""
39
+ Processor for VenusOCR. Wraps an image processor and a tokenizer into a single
40
+ processor for image-text interleaved inputs.
41
+
42
+ Args:
43
+ image_processor (`VenusOCRImageProcessor`, *optional*):
44
+ The image processor for vision inputs.
45
+ tokenizer (`PreTrainedTokenizerBase`, *optional*):
46
+ The tokenizer for text inputs.
47
+ chat_template (`str`, *optional*):
48
+ A Jinja2 template string for formatting chat messages.
49
+ """
50
+
51
+ attributes = ["image_processor", "tokenizer"]
52
+ image_processor_class = "AutoImageProcessor"
53
+ tokenizer_class = "AutoTokenizer"
54
+
55
+ def __init__(self, image_processor=None, tokenizer=None, chat_template=None, **kwargs):
56
+ self.image_token = "<|image_pad|>" if not hasattr(tokenizer, "image_token") else tokenizer.image_token
57
+ self.image_token_id = (
58
+ tokenizer.image_token_id
59
+ if getattr(tokenizer, "image_token_id", None)
60
+ else tokenizer.convert_tokens_to_ids(self.image_token)
61
+ )
62
+ super().__init__(image_processor, tokenizer, chat_template=chat_template)
63
+
64
+ @auto_docstring
65
+ def __call__(
66
+ self,
67
+ images: ImageInput = None,
68
+ text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] = None,
69
+ **kwargs: Unpack[VenusOCRProcessorKwargs],
70
+ ) -> BatchFeature:
71
+ r"""
72
+ Returns:
73
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
74
+
75
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
76
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
77
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
78
+ `None`).
79
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
80
+ - **image_grid_thw** -- List of image 3D grid in LLM. Returned when `images` is not `None`.
81
+ """
82
+ output_kwargs = self._merge_kwargs(
83
+ VenusOCRProcessorKwargs,
84
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
85
+ **kwargs,
86
+ )
87
+
88
+ if images is not None:
89
+ image_inputs = self.image_processor(images=images, **output_kwargs["images_kwargs"])
90
+ image_grid_thw = image_inputs["image_grid_thw"]
91
+ else:
92
+ image_inputs = {}
93
+ image_grid_thw = None
94
+
95
+ if not isinstance(text, list):
96
+ text = [text]
97
+
98
+ text = text.copy() # below lines change text in-place
99
+ if image_grid_thw is not None:
100
+ merge_length = self.image_processor.merge_size ** 2
101
+ index = 0
102
+ for i in range(len(text)):
103
+ while self.image_token in text[i]:
104
+ num_image_tokens = image_grid_thw[index].prod() // merge_length
105
+ text[i] = text[i].replace(self.image_token, "<|placeholder|>" * num_image_tokens, 1)
106
+ index += 1
107
+ text[i] = text[i].replace("<|placeholder|>", self.image_token)
108
+
109
+ return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
110
+ return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", None)
111
+ text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"], return_tensors=None)
112
+ self._check_special_mm_tokens(text, text_inputs, modalities=["image"])
113
+
114
+ if return_mm_token_type_ids:
115
+ text_inputs["mm_token_type_ids"] = self.create_mm_token_type_ids(text_inputs["input_ids"])
116
+ return BatchFeature(data={**text_inputs, **image_inputs}, tensor_type=return_tensors)
117
+
118
+
119
+ __all__ = ["VenusOCRProcessor"]
processor_config.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoProcessor": "processing_venusocr.VenusOCRProcessor"
4
+ },
5
+ "image_processor": {
6
+ "auto_map": {
7
+ "AutoImageProcessor": "image_processing_venusocr.VenusOCRImageProcessor",
8
+ "AutoProcessor": "processing_venusocr.VenusOCRProcessor"
9
+ },
10
+ "do_convert_rgb": true,
11
+ "do_normalize": true,
12
+ "do_rescale": true,
13
+ "do_resize": true,
14
+ "image_mean": [
15
+ 0.5,
16
+ 0.5,
17
+ 0.5
18
+ ],
19
+ "image_processor_type": "VenusOCRImageProcessor",
20
+ "image_std": [
21
+ 0.5,
22
+ 0.5,
23
+ 0.5
24
+ ],
25
+ "merge_size": 2,
26
+ "patch_size": 14,
27
+ "resample": 3,
28
+ "rescale_factor": 0.00392156862745098,
29
+ "size": {
30
+ "longest_edge": 1605632,
31
+ "shortest_edge": 147384
32
+ },
33
+ "temporal_patch_size": 1
34
+ },
35
+ "processor_class": "VenusOCRProcessor"
36
+ }
ptp2/config.json ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "PTP2DraftModel"
4
+ ],
5
+ "auto_map": {
6
+ "": "config.PTP2SpeculatorConfig"
7
+ },
8
+ "aux_hidden_state_layer_ids": [
9
+ 2,
10
+ 10,
11
+ 18,
12
+ 26
13
+ ],
14
+ "block_size": 5,
15
+ "draft_vocab_size": 151677,
16
+ "dtype": "bfloat16",
17
+ "init_layer_ids": [
18
+ 2,
19
+ 10,
20
+ 18,
21
+ 26
22
+ ],
23
+ "init_layer_strategy": "none",
24
+ "mask_token_id": 151677,
25
+ "sample_from_anchor": true,
26
+ "sliding_window_non_causal": false,
27
+ "speculators_config": {
28
+ "algorithm": "ptp2",
29
+ "default_proposal_method": "greedy",
30
+ "proposal_methods": [
31
+ {
32
+ "accept_tolerance": 0.0,
33
+ "proposal_type": "greedy",
34
+ "speculative_tokens": 5,
35
+ "verifier_accept_k": 1
36
+ }
37
+ ],
38
+ "verifier": {
39
+ "architectures": [
40
+ "VenusOCRForConditionalGeneration"
41
+ ],
42
+ "name_or_path": "VenusOCR/VenusOCR2-1B"
43
+ }
44
+ },
45
+ "speculators_model_type": "ptp2",
46
+ "speculators_version": "0.7.0.dev148",
47
+ "target_hidden_size": null,
48
+ "tie_word_embeddings": false,
49
+ "transformer_layer_config": {
50
+ "attention_bias": false,
51
+ "attention_dropout": 0.0,
52
+ "bos_token_id": null,
53
+ "eos_token_id": null,
54
+ "head_dim": 128,
55
+ "hidden_act": "silu",
56
+ "hidden_size": 1024,
57
+ "initializer_range": 0.02,
58
+ "intermediate_size": 3072,
59
+ "layer_types": [
60
+ "sliding_attention",
61
+ "sliding_attention",
62
+ "sliding_attention",
63
+ "sliding_attention"
64
+ ],
65
+ "max_position_embeddings": 40960,
66
+ "max_window_layers": 28,
67
+ "model_type": "qwen3",
68
+ "num_attention_heads": 16,
69
+ "num_hidden_layers": 4,
70
+ "num_key_value_heads": 8,
71
+ "pad_token_id": null,
72
+ "rms_norm_eps": 1e-06,
73
+ "rope_parameters": {
74
+ "mrope_section": [
75
+ 16,
76
+ 24,
77
+ 24
78
+ ],
79
+ "rope_theta": 1000000.0,
80
+ "rope_type": "default"
81
+ },
82
+ "sliding_window": 2048,
83
+ "tie_word_embeddings": false,
84
+ "use_cache": true,
85
+ "use_sliding_window": true,
86
+ "vocab_size": 151677
87
+ },
88
+ "transformers_version": "5.9.0"
89
+ }
ptp2/config.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Literal
2
+
3
+ from pydantic import Field
4
+
5
+ from speculators import SpeculatorModelConfig
6
+ from speculators.models.dflash.config import DFlashSpeculatorConfig
7
+
8
+ __all__ = [
9
+ "PTP2SpeculatorConfig",
10
+ ]
11
+
12
+
13
+ @SpeculatorModelConfig.register("ptp2")
14
+ class PTP2SpeculatorConfig(DFlashSpeculatorConfig):
15
+ """PTP2 (Parallel Token Prediction v2) speculator config.
16
+
17
+ Same anchored-block draft recipe as DFlash, with three key differences:
18
+
19
+ 1. The mask token is a *dedicated, learnable* embedding that is injected
20
+ into the target model as an extra token (default id: one past the
21
+ verifier vocabulary), rather than reusing a frozen verifier token.
22
+ 2. The draft decoder layers are initialized from the target model's
23
+ corresponding layers (``init_layer_ids``) instead of random init.
24
+ 3. Intra-block attention is causal instead of bidirectional.
25
+ """
26
+
27
+ speculators_model_type: Literal["ptp2"] = "ptp2" # type: ignore[assignment]
28
+ architectures: list[str] = Field(
29
+ default_factory=lambda: ["PTP2Speculator"],
30
+ description="Model architectures that can load these weights",
31
+ )
32
+
33
+ init_layer_ids: list[int] | None = Field(
34
+ default=None,
35
+ description=(
36
+ "Verifier layer ids used to initialize the draft decoder layers. "
37
+ "With init_layer_strategy='copy': draft layer i <- verifier layer "
38
+ "init_layer_ids[i]. With init_layer_strategy='average': the ids are "
39
+ "interval cut points and draft layer i averages verifier layers "
40
+ "(init_layer_ids[i-1], init_layer_ids[i]] (e.g. ids 2 10 18 26 give "
41
+ "layer ranges 0-2, 3-10, 11-18, 19-26). Defaults to "
42
+ "aux_hidden_state_layer_ids (i.e. --target-layer-ids)."
43
+ ),
44
+ )
45
+
46
+ init_layer_strategy: Literal["copy", "average", "none"] = Field(
47
+ default="copy",
48
+ description=(
49
+ "How to initialize each draft decoder layer from the verifier: "
50
+ "'copy' copies verifier layer init_layer_ids[i] into draft layer i; "
51
+ "'average' averages all verifier layers in the interval ending at "
52
+ "init_layer_ids[i] (previous cut point exclusive); "
53
+ "'none' skips verifier initialization entirely — draft layers and "
54
+ "the final norm keep random init, matching DFlash."
55
+ ),
56
+ )
57
+
58
+ # PTP2 trains every block position (including the anchor) to maximize
59
+ # token utilization, so its default differs from DFlash's False.
60
+ sample_from_anchor: bool = Field(
61
+ default=True,
62
+ description=(
63
+ "Whether to sample from the anchor position. "
64
+ "False: anchor is the bonus token, only mask tokens predict "
65
+ "(block_size-1 speculative tokens). "
66
+ "True: sample from anchor and all mask positions "
67
+ "(block_size speculative tokens). "
68
+ ),
69
+ )
ptp2/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:27b6387c9774d4dae4273a839d28ab34399b9491ec43da8ae6882438c915d825
3
+ size 755516568
scripts/infer_transformers.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ from pathlib import Path
3
+
4
+ import torch
5
+ from PIL import Image
6
+ from transformers import AutoModelForCausalLM, AutoProcessor
7
+
8
+
9
+ def main():
10
+ parser = argparse.ArgumentParser(description="Recognize a document region with VenusOCR.")
11
+ parser.add_argument("--model", default=str(Path(__file__).resolve().parents[1]))
12
+ parser.add_argument("--image", required=True)
13
+ parser.add_argument("--task", choices=["text", "formula", "table"], default="text")
14
+ parser.add_argument("--device", default="cuda:0")
15
+ parser.add_argument("--max-new-tokens", type=int, default=2048)
16
+ parser.add_argument("--output")
17
+ args = parser.parse_args()
18
+
19
+ processor = AutoProcessor.from_pretrained(args.model, trust_remote_code=True)
20
+ model = AutoModelForCausalLM.from_pretrained(
21
+ args.model,
22
+ dtype=torch.float32 if args.device == "cpu" else torch.bfloat16,
23
+ attn_implementation="sdpa",
24
+ trust_remote_code=True,
25
+ ).to(args.device).eval()
26
+ image = Image.open(args.image).convert("RGB")
27
+ messages = [
28
+ {
29
+ "role": "user",
30
+ "content": [
31
+ {"type": "image"},
32
+ {"type": "text", "text": f"{args.task.capitalize()} Recognition:"},
33
+ ],
34
+ }
35
+ ]
36
+ prompt = processor.apply_chat_template(
37
+ messages, tokenize=False, add_generation_prompt=True
38
+ )
39
+ inputs = processor(images=image, text=prompt, return_tensors="pt").to(model.device)
40
+ with torch.inference_mode():
41
+ output_ids = model.generate(
42
+ **inputs, max_new_tokens=args.max_new_tokens, do_sample=False
43
+ )
44
+ generated_ids = output_ids[:, inputs["input_ids"].shape[1] :]
45
+ text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
46
+ if args.output:
47
+ output_path = Path(args.output)
48
+ output_path.parent.mkdir(parents=True, exist_ok=True)
49
+ output_path.write_text(text + "\n", encoding="utf-8")
50
+ print(text)
51
+
52
+
53
+ if __name__ == "__main__":
54
+ main()
scripts/patch_vllm_v0_20_ptp2.sh ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Patch vLLM v0.20.x for Speculators PTPv2 + VenusOCR support.
3
+ #
4
+ # Usage:
5
+ # bash scripts/patch_vllm_v0_20_ptp2.sh
6
+ # bash scripts/patch_vllm_v0_20_ptp2.sh --package-dir /path/to/site-packages/vllm
7
+ # bash scripts/patch_vllm_v0_20_ptp2.sh --check
8
+ # bash scripts/patch_vllm_v0_20_ptp2.sh --reverse
9
+
10
+ set -euo pipefail
11
+
12
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
13
+ ASSETS_DIR="$SCRIPT_DIR/patches/vllm_v0_20_ptp2"
14
+
15
+ usage() {
16
+ echo "Usage: $0 [--vllm-root PATH | --package-dir PATH] [--venusocr-source PATH] [--no-venusocr] [--check | --reverse]"
17
+ }
18
+
19
+ PACKAGE_DIR="${VLLM_PACKAGE:-}"
20
+ VENUSOCR_SOURCE="${VENUSOCR_SOURCE:-$ASSETS_DIR/venusocr.py}"
21
+ WITH_VENUSOCR=1
22
+ MODE="patch"
23
+
24
+ while [[ $# -gt 0 ]]; do
25
+ case "$1" in
26
+ --vllm-root) PACKAGE_DIR="$2/vllm"; shift 2 ;;
27
+ --package-dir) PACKAGE_DIR="$2"; shift 2 ;;
28
+ --venusocr-source) VENUSOCR_SOURCE="$2"; shift 2 ;;
29
+ --no-venusocr) WITH_VENUSOCR=0; shift ;;
30
+ --check) MODE="check"; shift ;;
31
+ --reverse) MODE="reverse"; shift ;;
32
+ -h|--help) usage; exit 0 ;;
33
+ *) echo "[ERROR] Unknown argument: $1" >&2; usage >&2; exit 2 ;;
34
+ esac
35
+ done
36
+
37
+ PATCH_PYTHON="${PATCH_PYTHON:-python}"
38
+ if [[ -z "$PACKAGE_DIR" ]]; then
39
+ PACKAGE_DIR="$("$PATCH_PYTHON" -c 'import importlib.util, pathlib; spec = importlib.util.find_spec("vllm"); assert spec and spec.origin, "vllm not found"; print(pathlib.Path(spec.origin).parent)')"
40
+ fi
41
+ if [[ ! -f "$PACKAGE_DIR/config/speculative.py" ]]; then
42
+ echo "[ERROR] Not a vLLM package directory: $PACKAGE_DIR" >&2
43
+ exit 1
44
+ fi
45
+
46
+ ARGS=("$PACKAGE_DIR" --assets "$ASSETS_DIR")
47
+ if [[ "$MODE" == "check" ]]; then
48
+ ARGS+=(--check)
49
+ elif [[ "$MODE" == "reverse" ]]; then
50
+ ARGS+=(--reverse)
51
+ elif [[ "$WITH_VENUSOCR" -eq 1 ]]; then
52
+ if [[ ! -f "$VENUSOCR_SOURCE" ]]; then
53
+ echo "[ERROR] VenusOCR source not found: $VENUSOCR_SOURCE" >&2
54
+ echo " Pass --venusocr-source PATH or --no-venusocr." >&2
55
+ exit 1
56
+ fi
57
+ ARGS+=(--venusocr-source "$VENUSOCR_SOURCE")
58
+ fi
59
+
60
+ "$PATCH_PYTHON" "$ASSETS_DIR/patch_vllm.py" "${ARGS[@]}"
61
+
62
+ if [[ "$MODE" == "patch" ]]; then
63
+ VLLM_PYTHON="${VLLM_PYTHON:-$PATCH_PYTHON}"
64
+ "$VLLM_PYTHON" -m py_compile \
65
+ "$PACKAGE_DIR/model_executor/models/qwen3_ptp2.py" \
66
+ "$PACKAGE_DIR/v1/spec_decode/ptp2.py" \
67
+ "$PACKAGE_DIR/transformers_utils/configs/speculators/algos.py" \
68
+ "$PACKAGE_DIR/config/speculative.py" \
69
+ "$PACKAGE_DIR/v1/worker/gpu_model_runner.py"
70
+ echo "[OK] Static compilation passed with $VLLM_PYTHON"
71
+ fi
scripts/patches/vllm_v0_20_ptp2/patch_vllm.py ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Idempotently patch a vLLM v0.20.x source/package tree for PTP2."""
3
+
4
+ import argparse
5
+ import json
6
+ import re
7
+ import shutil
8
+ import sys
9
+ from datetime import datetime
10
+ from pathlib import Path
11
+
12
+ MARKER = "PTP2_VLLM_V0_20_PATCH"
13
+
14
+
15
+ def replace_once(path: Path, old: str, new: str) -> None:
16
+ text = path.read_text()
17
+ if new in text:
18
+ return
19
+ if old not in text:
20
+ raise RuntimeError(f"Cannot find patch anchor in {path}: {old[:100]!r}")
21
+ path.write_text(text.replace(old, new, 1))
22
+
23
+
24
+ def backup(path: Path, backup_root: Path, root: Path) -> None:
25
+ dest = backup_root / path.relative_to(root)
26
+ dest.parent.mkdir(parents=True, exist_ok=True)
27
+ shutil.copy2(path, dest)
28
+
29
+
30
+ def patch(root, assets, venusocr_source):
31
+ required = [
32
+ root / "config/speculative.py",
33
+ root / "transformers_utils/configs/speculators/algos.py",
34
+ root / "model_executor/models/qwen3_dflash.py",
35
+ root / "model_executor/models/registry.py",
36
+ root / "v1/spec_decode/dflash.py",
37
+ root / "v1/spec_decode/llm_base_proposer.py",
38
+ root / "v1/worker/gpu_model_runner.py",
39
+ ]
40
+ missing = [str(p) for p in required if not p.is_file()]
41
+ if missing:
42
+ raise RuntimeError("Not a compatible vLLM tree; missing: " + ", ".join(missing))
43
+ if (root / "model_executor/models/qwen3_ptp2.py").is_file():
44
+ check(root, assets)
45
+ print(f"[SKIP] PTP2 patch is already present in {root}")
46
+ return None
47
+
48
+ stamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
49
+ backup_root = root / f".ptp2_patch_backup_{stamp}"
50
+ changed_paths = list(required)
51
+ added_paths = [
52
+ root / "model_executor/models/qwen3_ptp2.py",
53
+ root / "v1/spec_decode/ptp2.py",
54
+ ]
55
+ if venusocr_source is not None:
56
+ venus_dest = root / "model_executor/models/venusocr.py"
57
+ if venus_dest.exists():
58
+ changed_paths.append(venus_dest)
59
+ else:
60
+ added_paths.append(venus_dest)
61
+ for path in changed_paths:
62
+ if path.exists():
63
+ backup(path, backup_root, root)
64
+
65
+ (root / ".ptp2_patch_backup_latest").write_text(str(backup_root) + "\n")
66
+ (root / ".ptp2_patch_added_latest").write_text(
67
+ json.dumps([str(path.relative_to(root)) for path in added_paths]) + "\n"
68
+ )
69
+ try:
70
+ apply_changes(root, assets, venusocr_source)
71
+ check(root)
72
+ except Exception:
73
+ reverse(root)
74
+ raise
75
+ return backup_root
76
+
77
+
78
+ def apply_changes(root: Path, assets: Path, venusocr_source: Path | None) -> None:
79
+ shutil.copy2(assets / "qwen3_ptp2.py", root / "model_executor/models/qwen3_ptp2.py")
80
+ shutil.copy2(assets / "ptp2.py", root / "v1/spec_decode/ptp2.py")
81
+
82
+ algos = root / "transformers_utils/configs/speculators/algos.py"
83
+ replace_once(
84
+ algos,
85
+ '@register_speculator("dflash")\ndef update_dflash',
86
+ f'''# {MARKER}
87
+ @register_speculator("ptp2")
88
+ def update_ptp2(config_dict: dict, pre_trained_config: dict) -> None:
89
+ pre_trained_config["architectures"] = ["PTP2DraftModel"]
90
+ pre_trained_config["draft_vocab_size"] = config_dict.get("draft_vocab_size")
91
+ if config_dict.get("target_hidden_size") is not None:
92
+ pre_trained_config["target_hidden_size"] = config_dict["target_hidden_size"]
93
+ # PTP2 training uses a single scalar position per token. VenusOCR's text
94
+ # config carries mrope_section for the verifier, but the draft must stay 1D.
95
+ rope_parameters = pre_trained_config.get("rope_parameters")
96
+ if isinstance(rope_parameters, dict):
97
+ rope_parameters.pop("mrope_section", None)
98
+ aux_layer_ids = config_dict["aux_hidden_state_layer_ids"]
99
+ pre_trained_config["eagle_aux_hidden_state_layer_ids"] = aux_layer_ids
100
+ pre_trained_config["ptp2_config"] = {{
101
+ "mask_token_id": config_dict["mask_token_id"],
102
+ "target_layer_ids": aux_layer_ids,
103
+ "sample_from_anchor": config_dict.get("sample_from_anchor", True),
104
+ "block_size": config_dict["block_size"],
105
+ }}
106
+
107
+
108
+ @register_speculator("dflash")
109
+ def update_dflash''',
110
+ )
111
+
112
+ registry = root / "model_executor/models/registry.py"
113
+ replace_once(
114
+ registry,
115
+ ' "DFlashDraftModel": ("qwen3_dflash", "DFlashQwen3ForCausalLM"),',
116
+ ' "DFlashDraftModel": ("qwen3_dflash", "DFlashQwen3ForCausalLM"),\n'
117
+ ' "PTP2DraftModel": ("qwen3_ptp2", "PTP2Qwen3ForCausalLM"), # '
118
+ + MARKER,
119
+ )
120
+
121
+ speculative = root / "config/speculative.py"
122
+ replacements = [
123
+ ('DFlashModelTypes = Literal["dflash"]', 'DFlashModelTypes = Literal["dflash", "ptp2"]'),
124
+ (' "dflash",\n )', ' "dflash",\n "ptp2",\n )'),
125
+ ('elif "dflash" in self.draft_model_config.model.lower():\n self.method = "dflash"', 'elif "ptp2" in self.draft_model_config.model.lower():\n self.method = "ptp2"\n elif "dflash" in self.draft_model_config.model.lower():\n self.method = "dflash"'),
126
+ ('if self.method == "dflash":\n self.parallel_drafting = True', 'if self.method in ("dflash", "ptp2"):\n self.parallel_drafting = True'),
127
+ ('return self.method in ("eagle", "eagle3", "mtp", "dflash")', 'return self.method in ("eagle", "eagle3", "mtp", "dflash", "ptp2")'),
128
+ (' def use_dflash(self) -> bool:\n return self.method == "dflash"', ' def use_dflash(self) -> bool:\n return self.method == "dflash"\n\n def use_ptp2(self) -> bool:\n return self.method == "ptp2"'),
129
+ ]
130
+ for old, new in replacements:
131
+ replace_once(speculative, old, new)
132
+ replace_once(
133
+ speculative,
134
+ " hash_str = safe_hash(str(factors).encode(), usedforsecurity=False).hexdigest()",
135
+ ''' if self.method == "ptp2":
136
+ # The target and draft share a compile cache directory. Include
137
+ # draft source changes so an older draft graph cannot be reused.
138
+ from pathlib import Path
139
+
140
+ package = Path(__file__).resolve().parents[1]
141
+ source = b"".join(
142
+ (package / relative).read_bytes()
143
+ for relative in (
144
+ "model_executor/models/qwen3_dflash.py",
145
+ "model_executor/models/qwen3_ptp2.py",
146
+ "v1/spec_decode/ptp2.py",
147
+ )
148
+ )
149
+ factors.append(safe_hash(source, usedforsecurity=False).hexdigest())
150
+
151
+ hash_str = safe_hash(str(factors).encode(), usedforsecurity=False).hexdigest()''',
152
+ )
153
+ text = speculative.read_text()
154
+ old_family = 'if self.method in ("eagle", "eagle3", "dflash"):'
155
+ if old_family not in text and 'if self.method in ("eagle", "eagle3", "dflash", "ptp2"):' not in text:
156
+ raise RuntimeError("Cannot find EAGLE-family method checks in speculative.py")
157
+ speculative.write_text(
158
+ text.replace(
159
+ old_family,
160
+ 'if self.method in ("eagle", "eagle3", "dflash", "ptp2"):')
161
+ )
162
+ replace_once(
163
+ speculative,
164
+ ' self.method in ("eagle3", "extract_hidden_states", "dflash")',
165
+ ' self.method in ("eagle3", "extract_hidden_states", "dflash", "ptp2")',
166
+ )
167
+ replace_once(
168
+ speculative,
169
+ ' "gemma4",\n ]',
170
+ ' "gemma4",\n "venusocr", # ' + MARKER + '\n ]',
171
+ )
172
+
173
+ dflash = root / "v1/spec_decode/dflash.py"
174
+ replace_once(
175
+ dflash,
176
+ 'assert vllm_config.speculative_config.method == "dflash"',
177
+ 'assert vllm_config.speculative_config.method in ("dflash", "ptp2")',
178
+ )
179
+
180
+ draft_model = root / "model_executor/models/qwen3_dflash.py"
181
+ replace_once(
182
+ draft_model,
183
+ " def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:\n"
184
+ " return self.embed_tokens(input_ids)",
185
+ " def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:\n"
186
+ ' ptp2_config = getattr(self.config, "ptp2_config", None)\n'
187
+ " if ptp2_config is None:\n"
188
+ " return self.embed_tokens(input_ids)\n"
189
+ ' is_mask = input_ids == ptp2_config["mask_token_id"]\n'
190
+ " inputs_embeds = self.embed_tokens(input_ids.masked_fill(is_mask, 0))\n"
191
+ " return torch.where(\n"
192
+ " is_mask.unsqueeze(-1), self.mask_embedding.weight[0], inputs_embeds\n"
193
+ " )",
194
+ )
195
+
196
+ base = root / "v1/spec_decode/llm_base_proposer.py"
197
+ replace_once(
198
+ base,
199
+ ' "GlmOcrForConditionalGeneration",',
200
+ ' "GlmOcrForConditionalGeneration",\n'
201
+ ' "VenusOCRForConditionalGeneration",',
202
+ )
203
+ replace_once(
204
+ base,
205
+ 'from vllm.model_executor.models.qwen3_dflash import DFlashQwen3ForCausalLM',
206
+ 'from vllm.model_executor.models.qwen3_dflash import DFlashQwen3ForCausalLM\n'
207
+ 'from vllm.model_executor.models.qwen3_ptp2 import PTP2Qwen3ForCausalLM',
208
+ )
209
+ for old, new in [
210
+ (
211
+ '1 if (self.pass_hidden_states_to_model and self.method != "dflash") else 0',
212
+ '1 if (self.pass_hidden_states_to_model and '
213
+ 'self.method not in ("dflash", "ptp2")) else 0',
214
+ ),
215
+ ('if self.method in ("eagle3", "dflash"):', 'if self.method in ("eagle3", "dflash", "ptp2"):'),
216
+ (' DFlashQwen3ForCausalLM,\n', ' DFlashQwen3ForCausalLM,\n PTP2Qwen3ForCausalLM,\n'),
217
+ ('return self.method not in ("mtp", "draft_model", "dflash")', 'return self.method not in ("mtp", "draft_model", "dflash", "ptp2")'),
218
+ (' # DFlash stores mask_token_id in dflash_config\n dflash_config', ' # DFlash/PTP2 store mask_token_id in their method config\n ptp2_config = getattr(model_hf_config, "ptp2_config", None)\n if ptp2_config and "mask_token_id" in ptp2_config:\n self.parallel_drafting_token_id = ptp2_config["mask_token_id"]\n return\n dflash_config'),
219
+ ]:
220
+ replace_once(base, old, new)
221
+
222
+ runner = root / "v1/worker/gpu_model_runner.py"
223
+ replace_once(
224
+ runner,
225
+ 'from vllm.v1.spec_decode.dflash import DFlashProposer',
226
+ 'from vllm.v1.spec_decode.dflash import DFlashProposer\n'
227
+ 'from vllm.v1.spec_decode.ptp2 import PTP2Proposer',
228
+ )
229
+ replace_once(
230
+ runner,
231
+ ' elif self.speculative_config.use_dflash():\n'
232
+ ' self.drafter = DFlashProposer(self.vllm_config, self.device, self)\n'
233
+ ' self.use_aux_hidden_state_outputs = True',
234
+ ' elif self.speculative_config.use_dflash():\n'
235
+ ' self.drafter = DFlashProposer(self.vllm_config, self.device, self)\n'
236
+ ' self.use_aux_hidden_state_outputs = True\n'
237
+ ' elif self.speculative_config.use_ptp2():\n'
238
+ ' self.drafter = PTP2Proposer(self.vllm_config, self.device, self)\n'
239
+ ' self.use_aux_hidden_state_outputs = True',
240
+ )
241
+ # Type unions appear several times; extending all occurrences is harmless.
242
+ text = runner.read_text()
243
+ text = re.sub(
244
+ r'^(?P<indent>\s*)\| DFlashProposer$',
245
+ r'\g<indent>| DFlashProposer\n\g<indent>| PTP2Proposer',
246
+ text,
247
+ flags=re.MULTILINE,
248
+ )
249
+ text = text.replace(
250
+ "EagleProposer | DFlashProposer",
251
+ "EagleProposer | DFlashProposer | PTP2Proposer",
252
+ )
253
+ text = text.replace(
254
+ "(EagleProposer, DFlashProposer)",
255
+ "(EagleProposer, DFlashProposer, PTP2Proposer)",
256
+ )
257
+ runner.write_text(text)
258
+
259
+ if venusocr_source is not None:
260
+ venus_dest = root / "model_executor/models/venusocr.py"
261
+ shutil.copy2(venusocr_source, venus_dest)
262
+ replace_once(
263
+ venus_dest,
264
+ "from .interfaces import MultiModalEmbeddings, SupportsMRoPE, SupportsMultiModal",
265
+ "from .interfaces import (\n"
266
+ " MultiModalEmbeddings,\n"
267
+ " SupportsEagle3,\n"
268
+ " SupportsMRoPE,\n"
269
+ " SupportsMultiModal,\n"
270
+ ")",
271
+ )
272
+ replace_once(
273
+ venus_dest,
274
+ "class VenusOCRForConditionalGeneration(nn.Module, SupportsMultiModal, SupportsMRoPE):",
275
+ "class VenusOCRForConditionalGeneration(\n"
276
+ " nn.Module, SupportsMultiModal, SupportsMRoPE, SupportsEagle3\n"
277
+ "):",
278
+ )
279
+ replace_once(
280
+ registry,
281
+ ' "PaliGemmaForConditionalGeneration": (',
282
+ ' "VenusOCRForConditionalGeneration": (\n'
283
+ ' "venusocr",\n'
284
+ ' "VenusOCRForConditionalGeneration",\n'
285
+ ' ), # ' + MARKER + '\n'
286
+ ' "PaliGemmaForConditionalGeneration": (',
287
+ )
288
+ def check(root: Path, assets: Path | None = None) -> None:
289
+ checks = {
290
+ root / "model_executor/models/qwen3_ptp2.py": [
291
+ "class PTP2Qwen3ForCausalLM", "class PTP2FlashAttentionImpl"
292
+ ],
293
+ root / "model_executor/models/qwen3_dflash.py": [
294
+ 'ptp2_config = getattr(self.config, "ptp2_config", None)'
295
+ ],
296
+ root / "v1/spec_decode/ptp2.py": [
297
+ "class PTP2Proposer", "starts = cad.seq_lens - query_lens"
298
+ ],
299
+ root / "transformers_utils/configs/speculators/algos.py": [
300
+ '@register_speculator("ptp2")', '"block_size": config_dict["block_size"]'
301
+ ],
302
+ root / "model_executor/models/registry.py": ['"PTP2DraftModel"'],
303
+ root / "config/speculative.py": [
304
+ "def use_ptp2",
305
+ 'DFlashModelTypes = Literal["dflash", "ptp2"]',
306
+ 'factors.append(safe_hash(source, usedforsecurity=False).hexdigest())',
307
+ ],
308
+ root / "v1/spec_decode/llm_base_proposer.py": [
309
+ '"VenusOCRForConditionalGeneration"', 'PTP2Qwen3ForCausalLM'
310
+ ],
311
+ root / "v1/spec_decode/dflash.py": ['method in ("dflash", "ptp2")'],
312
+ root / "v1/worker/gpu_model_runner.py": [
313
+ "PTP2Proposer", "self.speculative_config.use_ptp2()"
314
+ ],
315
+ }
316
+ failed = []
317
+ for path, needles in checks.items():
318
+ source = path.read_text() if path.is_file() else ""
319
+ for needle in needles:
320
+ if needle not in source:
321
+ failed.append(f"{path}: missing {needle!r}")
322
+ if source:
323
+ compile(source, str(path), "exec")
324
+ if assets is not None:
325
+ for relative, asset in [
326
+ ("model_executor/models/qwen3_ptp2.py", "qwen3_ptp2.py"),
327
+ ("v1/spec_decode/ptp2.py", "ptp2.py"),
328
+ ]:
329
+ installed = root / relative
330
+ if installed.is_file() and installed.read_bytes() != (assets / asset).read_bytes():
331
+ failed.append("Installed PTP2 assets differ. Run --reverse, then reapply.")
332
+ if failed:
333
+ raise RuntimeError("PTP2 patch check failed:\n" + "\n".join(failed))
334
+
335
+
336
+ def reverse(root: Path) -> None:
337
+ pointer = root / ".ptp2_patch_backup_latest"
338
+ if not pointer.is_file():
339
+ raise RuntimeError(f"No backup pointer found: {pointer}")
340
+ backup_root = Path(pointer.read_text().strip())
341
+ if not backup_root.is_dir():
342
+ raise RuntimeError(f"Backup directory does not exist: {backup_root}")
343
+ for source in backup_root.rglob("*"):
344
+ if source.is_file():
345
+ dest = root / source.relative_to(backup_root)
346
+ dest.parent.mkdir(parents=True, exist_ok=True)
347
+ shutil.copy2(source, dest)
348
+ added_pointer = root / ".ptp2_patch_added_latest"
349
+ added_relpaths = (
350
+ json.loads(added_pointer.read_text()) if added_pointer.is_file() else []
351
+ )
352
+ for relative in added_relpaths:
353
+ added = root / relative
354
+ if added.exists():
355
+ added.unlink()
356
+ pointer.unlink()
357
+ if added_pointer.exists():
358
+ added_pointer.unlink()
359
+
360
+
361
+ def main() -> int:
362
+ parser = argparse.ArgumentParser()
363
+ parser.add_argument("vllm_package_dir", type=Path)
364
+ parser.add_argument("--assets", required=True, type=Path)
365
+ parser.add_argument("--venusocr-source", type=Path)
366
+ parser.add_argument("--check", action="store_true")
367
+ parser.add_argument("--reverse", action="store_true")
368
+ args = parser.parse_args()
369
+ root = args.vllm_package_dir.resolve()
370
+ if args.reverse:
371
+ reverse(root)
372
+ print(f"[OK] Restored backup for {root}")
373
+ return 0
374
+ if args.check:
375
+ check(root, args.assets.resolve())
376
+ print(f"[OK] PTP2 patch is present in {root}")
377
+ return 0
378
+ backup_root = patch(root, args.assets.resolve(), args.venusocr_source)
379
+ check(root)
380
+ print(f"[OK] PTP2 patch applied to {root}")
381
+ if backup_root is not None:
382
+ print(f"[INFO] Backup: {backup_root}")
383
+ return 0
384
+
385
+
386
+ if __name__ == "__main__":
387
+ try:
388
+ raise SystemExit(main())
389
+ except Exception as exc:
390
+ print(f"[ERROR] {exc}", file=sys.stderr)
391
+ raise SystemExit(1) from exc
scripts/patches/vllm_v0_20_ptp2/ptp2.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """PTP2 proposer for vLLM v0.20.x."""
3
+
4
+ import torch
5
+ from typing_extensions import override
6
+
7
+ from vllm.config import VllmConfig
8
+ from vllm.triton_utils import triton
9
+ from vllm.v1.attention.backend import CommonAttentionMetadata
10
+ from vllm.v1.spec_decode.dflash import DFlashProposer
11
+ from vllm.v1.spec_decode.llm_base_proposer import SpecDecodeBaseProposer
12
+ from vllm.v1.spec_decode.utils import copy_and_expand_dflash_inputs_kernel
13
+
14
+
15
+ class PTP2Proposer(DFlashProposer):
16
+ """DFlash KV precomputation with PTP2 query/sampling semantics.
17
+
18
+ DFlash generates N drafts from [bonus, mask x N] and skips the bonus
19
+ output. PTP2 generates N drafts from [bonus, mask x (N - 1)] and samples
20
+ every output. PTP2 also uses causal attention inside that query block.
21
+ """
22
+
23
+ def __init__(
24
+ self, vllm_config: VllmConfig, device: torch.device, runner=None
25
+ ):
26
+ assert vllm_config.speculative_config is not None
27
+ assert vllm_config.speculative_config.method == "ptp2"
28
+ super().__init__(vllm_config=vllm_config, device=device, runner=runner)
29
+ self.max_query_tokens = self.max_batch_size * self.num_speculative_tokens
30
+ self._ptp2_target_positions_buffer = torch.zeros(
31
+ self.max_num_tokens, dtype=torch.int64, device=device
32
+ )
33
+
34
+ @override
35
+ def set_inputs_first_pass(
36
+ self,
37
+ target_token_ids: torch.Tensor,
38
+ next_token_ids: torch.Tensor,
39
+ target_positions: torch.Tensor,
40
+ target_hidden_states: torch.Tensor,
41
+ token_indices_to_sample: torch.Tensor | None,
42
+ cad: CommonAttentionMetadata,
43
+ num_rejected_tokens_gpu: torch.Tensor | None,
44
+ ) -> tuple[int, torch.Tensor, CommonAttentionMetadata]:
45
+ batch_size = cad.batch_size()
46
+ num_context = target_token_ids.shape[0]
47
+ num_query_per_req = self.num_speculative_tokens
48
+ num_query_total = batch_size * num_query_per_req
49
+
50
+ self._dflash_num_context = num_context
51
+ self._dflash_hidden_states = target_hidden_states
52
+
53
+ # Reuse the DFlash preparation kernel with one fewer mask. Its sampling
54
+ # indices are intentionally ignored because PTP2 samples every query.
55
+ ignored_sample_indices = torch.empty(
56
+ batch_size * max(self.num_speculative_tokens - 1, 1),
57
+ dtype=torch.int32,
58
+ device=self.device,
59
+ )
60
+ max_ctx_per_req = cad.max_query_len
61
+ max_tokens_per_req = max_ctx_per_req + num_query_per_req
62
+ block_size = min(256, triton.next_power_of_2(max_tokens_per_req))
63
+ num_blocks = triton.cdiv(max_tokens_per_req, block_size)
64
+ has_num_rejected = num_rejected_tokens_gpu is not None
65
+ draft_target_positions = target_positions
66
+ if target_positions.dim() > 1:
67
+ # VenusOCR uses M-RoPE in the verifier, while this PTP2 checkpoint
68
+ # was trained with scalar arange position ids. Reconstruct the
69
+ # logical per-request positions without a CPU synchronization.
70
+ query_lens = cad.query_start_loc[1:] - cad.query_start_loc[:-1]
71
+ request_ids = torch.repeat_interleave(
72
+ torch.arange(batch_size, device=self.device),
73
+ query_lens,
74
+ output_size=num_context,
75
+ )
76
+ offsets = self.arange[:num_context] - cad.query_start_loc[request_ids]
77
+ # Both lengths include the padded rejected suffix. The kernel
78
+ # removes that suffix when it chooses the last valid position.
79
+ starts = cad.seq_lens - query_lens
80
+ draft_target_positions = self._ptp2_target_positions_buffer[
81
+ :num_context
82
+ ]
83
+ draft_target_positions.copy_(starts[request_ids] + offsets)
84
+ copy_and_expand_dflash_inputs_kernel[(batch_size, num_blocks)](
85
+ next_token_ids_ptr=next_token_ids,
86
+ target_positions_ptr=draft_target_positions,
87
+ out_input_ids_ptr=self.input_ids,
88
+ out_context_positions_ptr=self._context_positions_buffer,
89
+ out_query_positions_ptr=self.positions,
90
+ out_context_slot_mapping_ptr=self._context_slot_mapping_buffer,
91
+ out_query_slot_mapping_ptr=self._slot_mapping_buffer,
92
+ out_token_indices_ptr=ignored_sample_indices,
93
+ block_table_ptr=cad.block_table_tensor,
94
+ block_table_stride=cad.block_table_tensor.stride(0),
95
+ query_start_loc_ptr=cad.query_start_loc,
96
+ num_rejected_tokens_ptr=(
97
+ num_rejected_tokens_gpu if has_num_rejected else 0
98
+ ),
99
+ parallel_drafting_token_id=self.parallel_drafting_token_id,
100
+ block_size=self.block_size,
101
+ num_query_per_req=num_query_per_req,
102
+ num_speculative_tokens=max(self.num_speculative_tokens - 1, 0),
103
+ total_input_tokens=num_context,
104
+ BLOCK_SIZE=block_size,
105
+ HAS_NUM_REJECTED=has_num_rejected,
106
+ )
107
+
108
+ token_indices_to_sample = self.arange[:num_query_total]
109
+ query_slot_mapping = self._slot_mapping_buffer[:num_query_total]
110
+ new_query_start_loc = self.arange[: batch_size + 1] * num_query_per_req
111
+
112
+ effective_seq_lens = cad.seq_lens
113
+ if has_num_rejected:
114
+ effective_seq_lens = effective_seq_lens - num_rejected_tokens_gpu
115
+ new_seq_lens_cpu_upper_bound = (
116
+ cad.seq_lens_cpu_upper_bound + num_query_per_req
117
+ if cad.seq_lens_cpu_upper_bound is not None
118
+ else None
119
+ )
120
+ new_cad = CommonAttentionMetadata(
121
+ query_start_loc=new_query_start_loc,
122
+ seq_lens=effective_seq_lens + num_query_per_req,
123
+ query_start_loc_cpu=(
124
+ torch.from_numpy(self.token_arange_np[: batch_size + 1]).clone()
125
+ * num_query_per_req
126
+ ),
127
+ _seq_lens_cpu=None,
128
+ _num_computed_tokens_cpu=None,
129
+ seq_lens_cpu_upper_bound=new_seq_lens_cpu_upper_bound,
130
+ num_reqs=cad.num_reqs,
131
+ num_actual_tokens=num_query_total,
132
+ max_query_len=num_query_per_req,
133
+ max_seq_len=cad.max_seq_len + num_query_per_req,
134
+ block_table_tensor=cad.block_table_tensor,
135
+ slot_mapping=query_slot_mapping,
136
+ causal=True,
137
+ )
138
+ return num_query_total, token_indices_to_sample, new_cad
139
+
140
+ @override
141
+ def build_per_group_and_layer_attn_metadata(
142
+ self, cad: CommonAttentionMetadata, draft_index: int = 0
143
+ ) -> tuple[list[object], dict[str, object]]:
144
+ per_group, per_layer = (
145
+ SpecDecodeBaseProposer.build_per_group_and_layer_attn_metadata(
146
+ self, cad, draft_index
147
+ )
148
+ )
149
+ for layer_name, attn_metadata in per_layer.items():
150
+ assert getattr(attn_metadata, "causal", None) is True, (
151
+ f"Attention metadata for PTP2 layer {layer_name} must be causal."
152
+ )
153
+ return per_group, per_layer
154
+
155
+ @override
156
+ def _get_eagle3_use_aux_hidden_state_from_config(self):
157
+ ptp2_config = getattr(
158
+ self.draft_model_config.hf_config, "ptp2_config", None
159
+ )
160
+ if ptp2_config is None:
161
+ return True
162
+ return ptp2_config.get("use_aux_hidden_state", True)
scripts/patches/vllm_v0_20_ptp2/qwen3_ptp2.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # ruff: noqa: INP001
3
+ """PTP2 draft model support for vLLM v0.20.x.
4
+
5
+ PTP2 reuses the Qwen3 DFlash draft backbone with a standalone learned mask
6
+ embedding and the fixed context window used by anchored-block training.
7
+ """
8
+
9
+ from collections.abc import Iterable
10
+
11
+ import torch
12
+ from torch import nn
13
+ from vllm.model_executor.models.qwen3_dflash import DFlashQwen3ForCausalLM
14
+ from vllm.v1.attention.backends.flash_attn import FlashAttentionImpl
15
+ from vllm.vllm_flash_attn import flash_attn_varlen_func
16
+
17
+
18
+ class PTP2FlashAttentionImpl(FlashAttentionImpl):
19
+ """Match the training mask's fixed context window before the anchor.
20
+
21
+ The window is shared by every query in the block. FlashAttention's
22
+ ordinary sliding window moves with each query, so long contexts use
23
+ one batched attention call per query offset with an adjusted window.
24
+ Short contexts retain the single parallel FlashAttention call.
25
+ """
26
+
27
+ def forward( # noqa: PLR0917 - AttentionImpl interface
28
+ self,
29
+ layer,
30
+ query,
31
+ key,
32
+ value,
33
+ kv_cache,
34
+ attn_metadata,
35
+ output,
36
+ output_scale=None,
37
+ output_block_scale=None,
38
+ ):
39
+ window = self.ptp2_window
40
+ block_size = self.ptp2_block_size
41
+ if attn_metadata is None or attn_metadata.max_seq_len <= window + block_size:
42
+ return super().forward(
43
+ layer,
44
+ query,
45
+ key,
46
+ value,
47
+ kv_cache,
48
+ attn_metadata,
49
+ output,
50
+ output_scale,
51
+ output_block_scale,
52
+ )
53
+ if output_scale is not None or output_block_scale is not None:
54
+ raise NotImplementedError("PTP2 requires an unquantized attention output")
55
+ if self.kv_cache_dtype not in ("auto", "bfloat16", "float16"):
56
+ raise NotImplementedError(
57
+ "PTP2 fixed-window attention requires FP16/BF16 KV"
58
+ )
59
+ if self.dcp_world_size != 1:
60
+ raise NotImplementedError("PTP2 fixed-window attention requires DCP size 1")
61
+ num_tokens = attn_metadata.num_actual_tokens
62
+ num_reqs = num_tokens // block_size
63
+ query_blocks = query[:num_tokens].view(
64
+ num_reqs, block_size, self.num_heads, self.head_size
65
+ )
66
+ output_blocks = output[:num_tokens].view_as(query_blocks)
67
+ key_cache, value_cache = kv_cache.unbind(0)
68
+ query_start_loc = torch.arange(
69
+ num_reqs + 1, dtype=torch.int32, device=query.device
70
+ )
71
+ for offset in range(block_size):
72
+ # One query per request. Its left window grows with the offset
73
+ # to keep the earliest visible context token at anchor - window.
74
+ seq_lens = attn_metadata.seq_lens - block_size + offset + 1
75
+ flash_attn_varlen_func(
76
+ q=query_blocks[:, offset],
77
+ k=key_cache,
78
+ v=value_cache,
79
+ out=output_blocks[:, offset],
80
+ cu_seqlens_q=query_start_loc,
81
+ max_seqlen_q=1,
82
+ seqused_k=seq_lens,
83
+ max_seqlen_k=attn_metadata.max_seq_len,
84
+ softmax_scale=self.scale,
85
+ causal=True,
86
+ window_size=[window + offset, 0],
87
+ block_table=attn_metadata.block_table,
88
+ fa_version=self.vllm_flash_attn_version,
89
+ )
90
+ return output
91
+
92
+
93
+ class PTP2Qwen3ForCausalLM(DFlashQwen3ForCausalLM):
94
+ """DFlash Qwen3 backbone with PTP2's learned mask embedding."""
95
+
96
+ def __init__(self, *, vllm_config, prefix: str = ""):
97
+ config = vllm_config.speculative_config.draft_model_config.hf_config
98
+ config.dflash_config = config.ptp2_config
99
+ if not config.ptp2_config.get("sample_from_anchor", True):
100
+ raise ValueError("This PTP2 proposer requires sample_from_anchor=True")
101
+ block_size = config.ptp2_config["block_size"]
102
+ if vllm_config.speculative_config.num_speculative_tokens != block_size:
103
+ raise ValueError(
104
+ f"PTP2 checkpoint requires {block_size} speculative tokens"
105
+ )
106
+ super().__init__(vllm_config=vllm_config, prefix=prefix)
107
+ # Embedding runs inside the compiled backbone so CUDA graph replay
108
+ # reads the current input_ids from the proposer's stable input buffer.
109
+ self.model.mask_embedding = nn.Embedding(1, self.config.hidden_size)
110
+ for index, layer in enumerate(self.model.layers):
111
+ if self.config.layer_types[index] != "sliding_attention":
112
+ continue
113
+ attn = layer.self_attn.attn
114
+ if not isinstance(attn.impl, FlashAttentionImpl):
115
+ raise ValueError("PTP2 fixed-window attention requires FLASH_ATTN")
116
+ attn.impl = PTP2FlashAttentionImpl(
117
+ num_heads=attn.num_heads,
118
+ head_size=attn.head_size,
119
+ scale=layer.self_attn.scaling,
120
+ num_kv_heads=attn.num_kv_heads,
121
+ alibi_slopes=None,
122
+ sliding_window=None,
123
+ kv_cache_dtype=attn.kv_cache_dtype,
124
+ )
125
+ attn.impl.ptp2_window = self.config.sliding_window
126
+ attn.impl.ptp2_block_size = block_size
127
+
128
+ def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]):
129
+ mask_weight = None
130
+ mask_loaded = False
131
+
132
+ def base_weights():
133
+ nonlocal mask_weight, mask_loaded
134
+ for name, loaded_weight in weights:
135
+ if name == "mask_embedding.weight":
136
+ mask_weight = loaded_weight
137
+ if tuple(mask_weight.shape) != tuple(
138
+ self.model.mask_embedding.weight.shape
139
+ ):
140
+ raise ValueError(
141
+ "PTP2 mask_embedding.weight shape mismatch: "
142
+ f"checkpoint={tuple(mask_weight.shape)}, "
143
+ f"model={tuple(self.model.mask_embedding.weight.shape)}"
144
+ )
145
+ self.model.mask_embedding.weight.data.copy_(
146
+ mask_weight.to(
147
+ device=self.model.mask_embedding.weight.device,
148
+ dtype=self.model.mask_embedding.weight.dtype,
149
+ )
150
+ )
151
+ mask_loaded = True
152
+ continue
153
+ yield name, loaded_weight
154
+
155
+ loaded = super().load_weights(base_weights())
156
+ if not mask_loaded:
157
+ raise ValueError(
158
+ "PTP2 checkpoint is missing required mask_embedding.weight"
159
+ )
160
+ return loaded
scripts/patches/vllm_v0_20_ptp2/venusocr.py ADDED
@@ -0,0 +1,1206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
+ # Copyright (c) 2025 PaddlePaddle Authors. All Rights Reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import math
18
+ from collections.abc import Iterable, Mapping, Sequence
19
+ from functools import partial
20
+ from typing import Annotated, Literal
21
+
22
+ import numpy as np
23
+ import torch
24
+ import torch.nn as nn
25
+ from einops import rearrange
26
+ from transformers import BaseImageProcessor, BatchFeature, PretrainedConfig
27
+ from transformers.activations import GELUActivation
28
+ from transformers.image_utils import ChannelDimension
29
+ from transformers.modeling_outputs import (
30
+ BaseModelOutputWithPooling,
31
+ )
32
+ from transformers.utils import torch_int
33
+
34
+ from vllm.config import VllmConfig
35
+ from vllm.config.multimodal import BaseDummyOptions
36
+ from vllm.distributed import parallel_state
37
+ from vllm.distributed import utils as dist_utils
38
+ from vllm.inputs import MultiModalDataDict
39
+ from vllm.model_executor.layers.attention import (
40
+ MMEncoderAttention,
41
+ )
42
+ from vllm.model_executor.layers.conv import Conv2dLayer
43
+ from vllm.model_executor.layers.linear import (
44
+ QKVParallelLinear,
45
+ RowParallelLinear,
46
+ )
47
+ from vllm.model_executor.layers.quantization import QuantizationConfig
48
+ from vllm.model_executor.layers.rotary_embedding.common import (
49
+ ApplyRotaryEmb,
50
+ )
51
+ from vllm.model_executor.model_loader.weight_utils import (
52
+ default_weight_loader,
53
+ maybe_remap_kv_scale_name,
54
+ )
55
+ from vllm.multimodal import MULTIMODAL_REGISTRY
56
+ from vllm.multimodal.inputs import (
57
+ MultiModalFeatureSpec,
58
+ MultiModalFieldConfig,
59
+ MultiModalKwargsItems,
60
+ )
61
+ from vllm.multimodal.parse import (
62
+ ImageProcessorItems,
63
+ ImageSize,
64
+ MultiModalDataItems,
65
+ )
66
+ from vllm.multimodal.processing import (
67
+ BaseDummyInputsBuilder,
68
+ BaseMultiModalProcessor,
69
+ BaseProcessingInfo,
70
+ PromptReplacement,
71
+ PromptUpdate,
72
+ )
73
+ from vllm.sequence import IntermediateTensors
74
+ from vllm.utils.tensor_schema import TensorSchema, TensorShape
75
+ from vllm.v1.attention.backends.registry import AttentionBackendEnum
76
+
77
+ from .interfaces import MultiModalEmbeddings, SupportsMRoPE, SupportsMultiModal
78
+ from .qwen3 import Qwen3ForCausalLM
79
+ from .siglip import SiglipMLP
80
+ from .utils import (
81
+ AutoWeightsLoader,
82
+ WeightsMapper,
83
+ is_pp_missing_parameter,
84
+ maybe_prefix,
85
+ )
86
+ from .vision import get_vit_attn_backend
87
+
88
+
89
+ def smart_resize(
90
+ height: int,
91
+ width: int,
92
+ factor: int = 28,
93
+ min_pixels: int = 28 * 28 * 130,
94
+ max_pixels: int = 28 * 28 * 1280,
95
+ ):
96
+ """Rescales the image so that the following conditions are met:
97
+
98
+ 1. Both dimensions (height and width) are divisible by 'factor'.
99
+
100
+ 2. The total number of pixels is within the range ['min_pixels', 'max_pixels'].
101
+
102
+ 3. The aspect ratio of the image is maintained as closely as possible.
103
+
104
+ """
105
+
106
+ if height < factor:
107
+ width = round((width * factor) / height)
108
+ height = factor
109
+
110
+ if width < factor:
111
+ height = round((height * factor) / width)
112
+ width = factor
113
+
114
+ if max(height, width) / min(height, width) > 200:
115
+ raise ValueError(
116
+ f"absolute aspect ratio must be smaller than 200, "
117
+ f"got {max(height, width) / min(height, width)}"
118
+ )
119
+ h_bar = round(height / factor) * factor
120
+ w_bar = round(width / factor) * factor
121
+ if h_bar * w_bar > max_pixels:
122
+ beta = math.sqrt((height * width) / max_pixels)
123
+ h_bar = math.floor(height / beta / factor) * factor
124
+ w_bar = math.floor(width / beta / factor) * factor
125
+ elif h_bar * w_bar < min_pixels:
126
+ beta = math.sqrt(min_pixels / (height * width))
127
+ h_bar = math.ceil(height * beta / factor) * factor
128
+ w_bar = math.ceil(width * beta / factor) * factor
129
+ return h_bar, w_bar
130
+
131
+
132
+ class VenusOCRProcessingInfo(BaseProcessingInfo):
133
+ def get_hf_config(self):
134
+ return self.ctx.get_hf_config()
135
+
136
+ def get_hf_processor(self, **kwargs: object):
137
+ # trust_remote_code is already injected by the framework via
138
+ # model_config.trust_remote_code in cached_processor_from_config;
139
+ # passing it again through kwargs would cause a "multiple values"
140
+ # TypeError, so we strip it here and rely on --trust-remote-code.
141
+ kwargs.pop("trust_remote_code", None)
142
+ return self.ctx.get_hf_processor(**kwargs)
143
+
144
+ def get_image_processor(self, **kwargs: object):
145
+ return self.get_hf_processor(**kwargs).image_processor
146
+
147
+ def get_supported_mm_limits(self):
148
+ return {"image": None}
149
+
150
+ def get_num_image_tokens(
151
+ self,
152
+ *,
153
+ image_width: int,
154
+ image_height: int,
155
+ image_processor: BaseImageProcessor,
156
+ mm_kwargs: Mapping[str, object],
157
+ ) -> int:
158
+ hf_config = self.get_hf_config()
159
+ vision_config = hf_config.vision_config
160
+ patch_size = vision_config.patch_size
161
+ merge_size = vision_config.spatial_merge_size
162
+
163
+ mm_kwargs = self.ctx.get_merged_mm_kwargs(mm_kwargs)
164
+ size = dict(image_processor.size)
165
+ min_pixels_key = "min_pixels" if "min_pixels" in size else "shortest_edge"
166
+ max_pixels_key = "max_pixels" if "max_pixels" in size else "longest_edge"
167
+
168
+ if override_size := mm_kwargs.get("size"):
169
+ size = size | dict(override_size)
170
+ min_pixels_key = "min_pixels" if "min_pixels" in size else "shortest_edge"
171
+ max_pixels_key = "max_pixels" if "max_pixels" in size else "longest_edge"
172
+ if (override_min_pixels := mm_kwargs.get("min_pixels")) is not None:
173
+ size[min_pixels_key] = override_min_pixels
174
+ if (override_max_pixels := mm_kwargs.get("max_pixels")) is not None:
175
+ size[max_pixels_key] = override_max_pixels
176
+
177
+ resized_height, resized_width = smart_resize(
178
+ height=image_height,
179
+ width=image_width,
180
+ factor=patch_size * merge_size,
181
+ min_pixels=size[min_pixels_key],
182
+ max_pixels=size[max_pixels_key],
183
+ )
184
+ preprocessed_size = ImageSize(width=resized_width, height=resized_height)
185
+
186
+ grid_t = 1
187
+ grid_h = preprocessed_size.height // patch_size
188
+ grid_w = preprocessed_size.width // patch_size
189
+
190
+ num_patches = grid_t * grid_h * grid_w
191
+ num_image_tokens = num_patches // (merge_size**2)
192
+
193
+ return num_image_tokens
194
+
195
+ def get_image_size_with_most_features(self) -> ImageSize:
196
+ hf_config = self.get_hf_config()
197
+ image_processor = self.get_image_processor()
198
+
199
+ # See `smart_resize` for the calculation of the image size.
200
+ merge_size = hf_config.vision_config.spatial_merge_size
201
+ patch_size = hf_config.vision_config.patch_size
202
+ factor = merge_size * patch_size
203
+ size = dict(image_processor.size)
204
+ max_pixels = size.get("max_pixels", size.get("longest_edge"))
205
+ if max_pixels is None:
206
+ raise ValueError("VenusOCR image processor size must define max pixels")
207
+ max_num_tokens = max_pixels // (factor**2)
208
+ # Find factors of max_num_tokens close to its square root
209
+ # to create a dummy image with a reasonable aspect ratio.
210
+ h_patches = int(math.sqrt(max_num_tokens))
211
+ max_num_tokens -= max_num_tokens % h_patches
212
+ w_patches = max_num_tokens // h_patches
213
+ return ImageSize(height=h_patches * factor, width=w_patches * factor)
214
+
215
+
216
+ class VenusOCRDummyInputsBuilder(BaseDummyInputsBuilder[VenusOCRProcessingInfo]):
217
+ def get_dummy_text(self, mm_counts: Mapping[str, int]) -> str:
218
+ num_images = mm_counts.get("image", 0)
219
+
220
+ processor = self.info.get_hf_processor()
221
+ image_token = processor.image_token
222
+
223
+ return image_token * num_images
224
+
225
+ def get_dummy_mm_data(
226
+ self,
227
+ seq_len: int,
228
+ mm_counts: Mapping[str, int],
229
+ mm_options: Mapping[str, BaseDummyOptions],
230
+ ) -> MultiModalDataDict:
231
+ num_images = mm_counts.get("image", 0)
232
+
233
+ max_image_size = self.info.get_image_size_with_most_features()
234
+ image_overrides = mm_options.get("image")
235
+
236
+ return {
237
+ "image": self._get_dummy_images(
238
+ width=max_image_size.width,
239
+ height=max_image_size.height,
240
+ num_images=num_images,
241
+ overrides=image_overrides,
242
+ )
243
+ }
244
+
245
+
246
+ class VenusOCRMultiModalProcessor(
247
+ BaseMultiModalProcessor[VenusOCRProcessingInfo]
248
+ ):
249
+ def _call_hf_processor(
250
+ self,
251
+ prompt: str,
252
+ mm_data: Mapping[str, object],
253
+ mm_kwargs: Mapping[str, object],
254
+ tok_kwargs: Mapping[str, object],
255
+ ) -> BatchFeature:
256
+ if mm_data:
257
+ final_mm_kwargs = dict(mm_kwargs or {})
258
+ final_mm_kwargs.setdefault("images_kwargs", {})
259
+ # vLLM use PIL.Image, always set channel_last
260
+ final_mm_kwargs["input_data_format"] = ChannelDimension.LAST
261
+ processed_outputs = self.info.ctx.call_hf_processor(
262
+ self.info.get_hf_processor(**final_mm_kwargs),
263
+ dict(text=prompt, **mm_data),
264
+ dict(**mm_kwargs, **tok_kwargs),
265
+ )
266
+ num_patches_per_image = processed_outputs["image_grid_thw"].prod(-1)
267
+ processed_outputs["pixel_values"] = processed_outputs["pixel_values"].split(
268
+ num_patches_per_image.tolist()
269
+ )
270
+ else:
271
+ tokenizer = self.info.get_tokenizer()
272
+ processed_outputs = tokenizer(
273
+ prompt, add_special_tokens=True, return_tensors="pt"
274
+ )
275
+ return processed_outputs
276
+
277
+ def _get_mm_fields_config(
278
+ self,
279
+ hf_inputs: BatchFeature,
280
+ hf_processor_mm_kwargs: Mapping[str, object],
281
+ ) -> Mapping[str, MultiModalFieldConfig]:
282
+ return dict(
283
+ pixel_values=MultiModalFieldConfig.batched("image"),
284
+ image_grid_thw=MultiModalFieldConfig.batched("image"),
285
+ )
286
+
287
+ def _get_prompt_updates(
288
+ self,
289
+ mm_items: MultiModalDataItems,
290
+ hf_processor_mm_kwargs: Mapping[str, object],
291
+ out_mm_kwargs: MultiModalKwargsItems,
292
+ ) -> Sequence[PromptUpdate]:
293
+ image_processor = self.info.get_image_processor(**hf_processor_mm_kwargs)
294
+ hf_config = self.info.get_hf_config()
295
+ image_token_id = hf_config.image_token_id
296
+
297
+ def get_replacement(item_idx: int, image_processor):
298
+ images = mm_items.get_items("image", ImageProcessorItems)
299
+
300
+ image_size = images.get_image_size(item_idx)
301
+ num_image_tokens = self.info.get_num_image_tokens(
302
+ image_width=image_size.width,
303
+ image_height=image_size.height,
304
+ image_processor=image_processor,
305
+ mm_kwargs=hf_processor_mm_kwargs,
306
+ )
307
+
308
+ return [image_token_id] * num_image_tokens
309
+
310
+ return [
311
+ PromptReplacement(
312
+ modality="image",
313
+ target=[image_token_id],
314
+ replacement=partial(get_replacement, image_processor=image_processor),
315
+ ),
316
+ ]
317
+
318
+
319
+ class Projector(nn.Module):
320
+ def __init__(
321
+ self,
322
+ text_config: PretrainedConfig,
323
+ vision_config: PretrainedConfig,
324
+ prefix: str = "",
325
+ ):
326
+ super().__init__()
327
+ self.text_config = text_config
328
+ self.vision_config = vision_config
329
+ self.merge_kernel_size = (2, 2)
330
+
331
+ self.hidden_size = (
332
+ self.vision_config.hidden_size
333
+ * self.merge_kernel_size[0]
334
+ * self.merge_kernel_size[1]
335
+ )
336
+
337
+ self.pre_norm = torch.nn.LayerNorm(self.vision_config.hidden_size, eps=1e-05)
338
+ self.linear_1 = nn.Linear(self.hidden_size, self.hidden_size, bias=True)
339
+ self.act = GELUActivation()
340
+ self.linear_2 = nn.Linear(
341
+ self.hidden_size, self.text_config.hidden_size, bias=True
342
+ )
343
+
344
+ def forward(
345
+ self,
346
+ image_features: torch.Tensor,
347
+ image_grid_thw: torch.Tensor,
348
+ ) -> torch.Tensor:
349
+ m1, m2 = self.merge_kernel_size
350
+ if isinstance(image_features, list | tuple):
351
+ processed_features = list()
352
+ for image_feature, image_grid in zip(image_features, image_grid_thw):
353
+ image_feature = self.pre_norm(image_feature)
354
+ t, h, w = image_grid
355
+
356
+ image_feature = rearrange(
357
+ image_feature,
358
+ "(t h p1 w p2) d -> (t h w) (p1 p2 d)",
359
+ t=t,
360
+ h=h // m1,
361
+ p1=m1,
362
+ w=w // m2,
363
+ p2=m2,
364
+ )
365
+ hidden_states = self.linear_1(image_feature)
366
+ hidden_states = self.act(hidden_states)
367
+ hidden_states = self.linear_2(hidden_states)
368
+ processed_features.append(hidden_states)
369
+
370
+ return processed_features
371
+
372
+ dims = image_features.shape[:-1]
373
+ dim = image_features.shape[-1]
374
+ image_features = image_features.view(np.prod(dims), dim)
375
+ hidden_states = self.pre_norm(image_features).view(-1, self.hidden_size)
376
+ hidden_states = self.linear_1(hidden_states)
377
+ hidden_states = self.act(hidden_states)
378
+ hidden_states = self.linear_2(hidden_states)
379
+
380
+ return hidden_states.view(*dims, -1)
381
+
382
+
383
+ class VenusOCRImagePixelInputs(TensorSchema):
384
+ type: Literal["pixel_values"]
385
+ pixel_values: Annotated[
386
+ torch.Tensor,
387
+ TensorShape("bn", "p", 3, "patch_size", "patch_size", dynamic_dims={"p"}),
388
+ ]
389
+ image_grid_thw: Annotated[
390
+ torch.Tensor,
391
+ TensorShape("bn", 3),
392
+ ]
393
+
394
+
395
+ class SiglipVisionEmbeddings(nn.Module):
396
+ def __init__(self, config: PretrainedConfig):
397
+ super().__init__()
398
+ self.config = config
399
+ self.embed_dim = config.hidden_size
400
+ self.image_size = config.image_size
401
+ self.patch_size = config.patch_size
402
+
403
+ self.patch_embedding = Conv2dLayer(
404
+ in_channels=config.num_channels,
405
+ out_channels=self.embed_dim,
406
+ kernel_size=self.patch_size,
407
+ stride=self.patch_size,
408
+ padding="valid",
409
+ )
410
+
411
+ self.num_patches = (self.image_size // self.patch_size) ** 2
412
+ self.num_positions = self.num_patches
413
+ self.cache_position_embedding = dict()
414
+ self.cache_position_count = dict()
415
+ self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
416
+
417
+ self.register_buffer(
418
+ "position_ids",
419
+ torch.arange(self.num_positions).expand((1, -1)),
420
+ persistent=False,
421
+ )
422
+
423
+ def interpolate_pos_encoding(
424
+ self,
425
+ embeddings: torch.Tensor,
426
+ height: int,
427
+ width: int,
428
+ is_after_patchify: bool = False,
429
+ ) -> torch.Tensor:
430
+ num_positions = self.position_embedding.weight.shape[0]
431
+
432
+ patch_pos_embed = self.position_embedding.weight.unsqueeze(0)
433
+
434
+ dim = embeddings.shape[-1]
435
+
436
+ if is_after_patchify:
437
+ new_height = height
438
+ new_width = width
439
+ else:
440
+ new_height = height // self.patch_size
441
+ new_width = width // self.patch_size
442
+
443
+ sqrt_num_positions = torch_int(num_positions**0.5)
444
+ patch_pos_embed = patch_pos_embed.reshape(
445
+ 1, sqrt_num_positions, sqrt_num_positions, dim
446
+ )
447
+ patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
448
+
449
+ patch_pos_embed = nn.functional.interpolate(
450
+ patch_pos_embed,
451
+ size=(new_height, new_width),
452
+ mode="bilinear",
453
+ align_corners=False,
454
+ )
455
+
456
+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
457
+ return patch_pos_embed
458
+
459
+ def fetch_position_embedding_lfu_cache(
460
+ self, embeddings: torch.Tensor, h: int, w: int, max_cache: int = 20
461
+ ):
462
+ grid = (h, w)
463
+ if grid in self.cache_position_embedding:
464
+ self.cache_position_count[grid] += 1
465
+ return self.cache_position_embedding[grid]
466
+
467
+ if len(self.cache_position_embedding) >= max_cache:
468
+ min_hit_grid = min(
469
+ self.cache_position_count,
470
+ key=self.cache_position_count.get,
471
+ )
472
+ self.cache_position_count.pop(min_hit_grid)
473
+ self.cache_position_embedding.pop(min_hit_grid)
474
+
475
+ position_embedding = self.interpolate_pos_encoding(embeddings, h, w, True)
476
+ self.cache_position_count[grid] = 1
477
+ self.cache_position_embedding[grid] = position_embedding
478
+ return position_embedding
479
+
480
+ def forward(
481
+ self,
482
+ pixel_values: torch.FloatTensor,
483
+ position_ids: torch.Tensor | None = None,
484
+ image_grid_thw: list[tuple[int, int, int] | list[tuple[int, int, int]]]
485
+ | None = None,
486
+ interpolate_pos_encoding=False,
487
+ ) -> torch.Tensor:
488
+ if pixel_values.dim() == 4:
489
+ pixel_values = pixel_values.unsqueeze(0)
490
+ if pixel_values.dim() == 5:
491
+ if position_ids is None:
492
+ raise ValueError(
493
+ "position_ids cannot be None when pixel_values.dim() is 5."
494
+ )
495
+ (
496
+ batch_size,
497
+ sequence_len,
498
+ channel,
499
+ height,
500
+ width,
501
+ ) = pixel_values.shape
502
+ target_dtype = self.patch_embedding.weight.dtype
503
+ pixel_values = rearrange(pixel_values, "b l c h w -> (b l) c h w")
504
+ patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype))
505
+ embeddings = patch_embeds.flatten(-2).squeeze(-1)
506
+
507
+ start = 0
508
+ tmp_embeddings = list()
509
+ for image_grid in image_grid_thw:
510
+ t, h, w = image_grid
511
+ end = start + t * h * w
512
+ image_embeddings = embeddings[start:end, :]
513
+ position_embedding = (
514
+ self.interpolate_pos_encoding(image_embeddings, h, w, True)
515
+ .squeeze(0)
516
+ .repeat(t, 1)
517
+ )
518
+ image_embeddings = image_embeddings + position_embedding
519
+ tmp_embeddings.append(image_embeddings)
520
+ start = end
521
+ embeddings = torch.concat(tmp_embeddings, dim=0).unsqueeze(0)
522
+
523
+ return embeddings
524
+ else:
525
+ raise ValueError(
526
+ "Unsupported pixel_values dimension:"
527
+ f" {pixel_values.dim()}. Expected 4 or 5."
528
+ )
529
+
530
+
531
+ def all_gather_interleave(local_tensor: torch.Tensor, hidden_size: int, tp_size: int):
532
+ """All-gather the input tensor interleavely across model parallel group."""
533
+ import torch.distributed as dist
534
+
535
+ gathered_tensors = [torch.zeros_like(local_tensor) for _ in range(tp_size)]
536
+ dist.all_gather(
537
+ gathered_tensors, local_tensor, group=parallel_state.get_tp_group().device_group
538
+ )
539
+
540
+ gathered_tensors_split = [
541
+ torch.split(tensor, hidden_size // tp_size, -1) for tensor in gathered_tensors
542
+ ]
543
+ ordered_tensors = [
544
+ tensor for pair in zip(*gathered_tensors_split) for tensor in pair
545
+ ]
546
+ result_tensor = torch.cat(ordered_tensors, dim=-1)
547
+ return result_tensor
548
+
549
+
550
+ class SiglipAttention(nn.Module):
551
+ """SigLIP vision attention adapted from Qwen2.5-VisionAttention."""
552
+
553
+ def __init__(
554
+ self,
555
+ *,
556
+ embed_dim: int,
557
+ num_heads: int,
558
+ projection_size: int,
559
+ quant_config: QuantizationConfig | None = None,
560
+ prefix: str = "",
561
+ ) -> None:
562
+ super().__init__()
563
+
564
+ self.tp_size = parallel_state.get_tensor_model_parallel_world_size()
565
+ self.tp_rank = parallel_state.get_tensor_model_parallel_rank()
566
+ self.hidden_size_per_attention_head = dist_utils.divide(
567
+ projection_size, num_heads
568
+ )
569
+ self.num_attention_heads_per_partition = dist_utils.divide(
570
+ num_heads, self.tp_size
571
+ )
572
+
573
+ self.qkv_proj = QKVParallelLinear(
574
+ hidden_size=embed_dim,
575
+ head_size=self.hidden_size_per_attention_head,
576
+ total_num_heads=num_heads,
577
+ total_num_kv_heads=num_heads,
578
+ bias=True,
579
+ quant_config=quant_config,
580
+ prefix=f"{prefix}.qkv_proj",
581
+ )
582
+ self.out_proj = RowParallelLinear(
583
+ input_size=projection_size,
584
+ output_size=embed_dim,
585
+ quant_config=quant_config,
586
+ prefix=f"{prefix}.out_proj",
587
+ )
588
+ self.attn = MMEncoderAttention(
589
+ num_heads=self.num_attention_heads_per_partition,
590
+ head_size=self.hidden_size_per_attention_head,
591
+ scale=self.hidden_size_per_attention_head**-0.5,
592
+ prefix=f"{prefix}.attn",
593
+ )
594
+ self.apply_rotary_emb = ApplyRotaryEmb(
595
+ enforce_enable=True,
596
+ enable_fp32_compute=True,
597
+ )
598
+
599
+ def split_qkv(self, qkv: torch.Tensor) -> tuple[torch.Tensor, ...]:
600
+ seq_len, bs, _ = qkv.shape
601
+ if self.tp_size > 1:
602
+ qkv = all_gather_interleave(qkv, self.qkv_proj.hidden_size, self.tp_size)
603
+
604
+ q, k, v = qkv.chunk(3, dim=2)
605
+
606
+ if self.tp_size > 1:
607
+ splitter = partial(
608
+ dist_utils.split_tensor_along_last_dim, num_partitions=self.tp_size
609
+ )
610
+ q = splitter(q)[self.tp_rank]
611
+ k = splitter(k)[self.tp_rank]
612
+ v = splitter(v)[self.tp_rank]
613
+
614
+ new_shape = (
615
+ seq_len,
616
+ bs,
617
+ self.num_attention_heads_per_partition,
618
+ self.hidden_size_per_attention_head,
619
+ )
620
+ q, k, v = (x.view(*new_shape) for x in (q, k, v))
621
+ return q, k, v
622
+
623
+ def forward(
624
+ self,
625
+ hidden_states: torch.Tensor,
626
+ *,
627
+ cu_seqlens: torch.Tensor,
628
+ rotary_pos_emb: torch.Tensor | None,
629
+ max_seqlen: torch.Tensor | None,
630
+ ) -> torch.Tensor:
631
+ batch_size, _, _ = hidden_states.shape
632
+
633
+ x = rearrange(hidden_states, "b s d -> s b d")
634
+ x, _ = self.qkv_proj(x)
635
+ q, k, v = self.split_qkv(x)
636
+ q, k, v = (rearrange(t, "s b h d -> b s h d") for t in (q, k, v))
637
+
638
+ if rotary_pos_emb is not None:
639
+ qk_concat = torch.cat([q, k], dim=0)
640
+ qk_rotated = self.apply_rotary_emb(
641
+ qk_concat,
642
+ rotary_pos_emb.cos(),
643
+ rotary_pos_emb.sin(),
644
+ )
645
+ q, k = torch.chunk(qk_rotated, 2, dim=0)
646
+
647
+ context_layer = self.attn(
648
+ query=q,
649
+ key=k,
650
+ value=v,
651
+ cu_seqlens=cu_seqlens,
652
+ max_seqlen=max_seqlen,
653
+ )
654
+ context_layer = rearrange(context_layer, "b s h d -> b s (h d)")
655
+
656
+ output, _ = self.out_proj(context_layer)
657
+ return output
658
+
659
+
660
+ class SigLIPRotaryEmbedding(nn.Module):
661
+ def __init__(self, dim: int, theta: float = 10000.0) -> None:
662
+ super().__init__()
663
+ self.dim = dim
664
+ self.theta = theta
665
+ self.rope_init()
666
+
667
+ def rope_init(self):
668
+ inv_freq = 1.0 / (
669
+ self.theta ** (torch.arange(0, self.dim, 2, dtype=torch.float) / self.dim)
670
+ )
671
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
672
+
673
+ def forward(self, seqlen: int) -> torch.Tensor:
674
+ seq = torch.arange(
675
+ seqlen,
676
+ device=self.inv_freq.device,
677
+ dtype=self.inv_freq.dtype,
678
+ )
679
+ freqs = torch.outer(seq, self.inv_freq)
680
+ return freqs
681
+
682
+
683
+ class SiglipEncoderLayer(nn.Module):
684
+ def __init__(
685
+ self,
686
+ config: PretrainedConfig,
687
+ quant_config: QuantizationConfig | None = None,
688
+ prefix: str = "",
689
+ ):
690
+ super().__init__()
691
+ self.embed_dim = config.hidden_size
692
+ self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
693
+ self.self_attn = SiglipAttention(
694
+ embed_dim=config.hidden_size,
695
+ num_heads=config.num_attention_heads,
696
+ projection_size=config.hidden_size,
697
+ quant_config=quant_config,
698
+ prefix=f"{prefix}.self_attn",
699
+ )
700
+ self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
701
+ self.mlp = SiglipMLP(
702
+ config,
703
+ quant_config=quant_config,
704
+ prefix=f"{prefix}.mlp",
705
+ )
706
+
707
+ def forward(
708
+ self,
709
+ hidden_states: torch.Tensor,
710
+ *,
711
+ cu_seqlens: torch.Tensor,
712
+ rotary_pos_emb: torch.Tensor | None,
713
+ max_seqlen: torch.Tensor | None,
714
+ ) -> torch.Tensor:
715
+ residual = hidden_states
716
+
717
+ hidden_states = self.layer_norm1(hidden_states)
718
+ hidden_states = self.self_attn(
719
+ hidden_states=hidden_states,
720
+ cu_seqlens=cu_seqlens,
721
+ rotary_pos_emb=rotary_pos_emb,
722
+ max_seqlen=max_seqlen,
723
+ )
724
+
725
+ hidden_states = residual + hidden_states
726
+
727
+ residual = hidden_states
728
+ hidden_states = self.layer_norm2(hidden_states)
729
+ hidden_states = self.mlp(hidden_states)
730
+
731
+ hidden_states = residual + hidden_states
732
+
733
+ return hidden_states
734
+
735
+
736
+ class SiglipEncoder(nn.Module):
737
+ def __init__(
738
+ self,
739
+ config: PretrainedConfig,
740
+ quant_config: QuantizationConfig | None = None,
741
+ prefix: str = "",
742
+ ):
743
+ super().__init__()
744
+ self.config = config
745
+ embed_dim = config.hidden_size
746
+ num_heads = config.num_attention_heads
747
+ head_dim = embed_dim // num_heads
748
+
749
+ self.attn_backend = get_vit_attn_backend(
750
+ head_size=head_dim,
751
+ dtype=torch.get_default_dtype(),
752
+ )
753
+
754
+ self.layers = nn.ModuleList(
755
+ [
756
+ SiglipEncoderLayer(
757
+ config,
758
+ quant_config=quant_config,
759
+ prefix=f"{prefix}.layers.{layer_idx}",
760
+ )
761
+ for layer_idx in range(config.num_hidden_layers)
762
+ ]
763
+ )
764
+ self.rotary_pos_emb = SigLIPRotaryEmbedding(head_dim // 2)
765
+
766
+ @staticmethod
767
+ def flatten_list(image_grid_thw):
768
+ tmp_image_grid_thw = list()
769
+ for image_grid in image_grid_thw:
770
+ if isinstance(image_grid, list):
771
+ tmp_image_grid_thw.extend(image_grid)
772
+ else:
773
+ tmp_image_grid_thw.append(image_grid)
774
+ return tmp_image_grid_thw
775
+
776
+ def forward(
777
+ self,
778
+ inputs_embeds,
779
+ cu_seqlens: torch.Tensor | None = None,
780
+ image_grid_thw: list[tuple[int, int, int] | list[tuple[int, int, int]]]
781
+ | None = None,
782
+ height_position_ids: torch.Tensor | None = None,
783
+ width_position_ids: torch.Tensor | None = None,
784
+ ) -> torch.Tensor:
785
+ device = inputs_embeds.device
786
+ hidden_states = inputs_embeds
787
+
788
+ flatten_image_grid_thw = self.flatten_list(image_grid_thw)
789
+
790
+ if width_position_ids is None or height_position_ids is None:
791
+ split_hids = list()
792
+ split_wids = list()
793
+ for t, h, w in flatten_image_grid_thw:
794
+ image_pids = torch.arange(t * h * w, device=device) % (h * w)
795
+ sample_hids = image_pids // w
796
+ sample_wids = image_pids % w
797
+ split_hids.append(sample_hids)
798
+ split_wids.append(sample_wids)
799
+ width_position_ids = torch.concat(split_wids, dim=0)
800
+ height_position_ids = torch.concat(split_hids, dim=0)
801
+
802
+ pids = torch.stack(
803
+ [height_position_ids, width_position_ids],
804
+ dim=-1,
805
+ )
806
+ max_grid_size = pids.max() + 1
807
+ rope_emb_max_grid = self.rotary_pos_emb(max_grid_size)
808
+ rotary_pos_emb = rope_emb_max_grid[pids].flatten(1)
809
+
810
+ if cu_seqlens is None:
811
+ raise ValueError("cu_seqlens cannot be None for SiglipEncoder.")
812
+ if not isinstance(cu_seqlens, torch.Tensor):
813
+ cu_seqlens = torch.tensor(cu_seqlens, dtype=torch.int32, device=device)
814
+ else:
815
+ cu_seqlens = cu_seqlens.to(device=device)
816
+
817
+ max_seqlen = None
818
+ if self.attn_backend in {
819
+ AttentionBackendEnum.FLASH_ATTN,
820
+ AttentionBackendEnum.ROCM_AITER_FA,
821
+ AttentionBackendEnum.TRITON_ATTN,
822
+ }:
823
+ max_seqlen = (cu_seqlens[1:] - cu_seqlens[:-1]).max()
824
+
825
+ hidden_states = inputs_embeds
826
+ for encoder_layer in self.layers:
827
+ hidden_states = encoder_layer(
828
+ hidden_states,
829
+ cu_seqlens=cu_seqlens,
830
+ rotary_pos_emb=rotary_pos_emb,
831
+ max_seqlen=max_seqlen,
832
+ )
833
+ return hidden_states
834
+
835
+
836
+ class SiglipVisionTransformer(nn.Module):
837
+ def __init__(
838
+ self,
839
+ config: PretrainedConfig,
840
+ quant_config: QuantizationConfig | None = None,
841
+ prefix: str = "",
842
+ ):
843
+ super().__init__()
844
+ self.config = config
845
+ embed_dim = config.hidden_size
846
+
847
+ self.embeddings = SiglipVisionEmbeddings(config)
848
+ self.encoder = SiglipEncoder(
849
+ config,
850
+ quant_config=quant_config,
851
+ prefix=f"{prefix}.encoder",
852
+ )
853
+ self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
854
+
855
+ def forward(
856
+ self,
857
+ pixel_values: torch.Tensor,
858
+ interpolate_pos_encoding: bool | None = False,
859
+ position_ids: torch.Tensor | None = None,
860
+ height_position_ids: torch.Tensor | None = None,
861
+ width_position_ids: torch.Tensor | None = None,
862
+ cu_seqlens: torch.Tensor | None = None,
863
+ image_grid_thw: torch.Tensor | None = None,
864
+ ) -> torch.Tensor:
865
+ hidden_states = self.embeddings(
866
+ pixel_values,
867
+ interpolate_pos_encoding=interpolate_pos_encoding,
868
+ position_ids=position_ids,
869
+ image_grid_thw=image_grid_thw,
870
+ )
871
+
872
+ last_hidden_state = self.encoder(
873
+ inputs_embeds=hidden_states,
874
+ cu_seqlens=cu_seqlens,
875
+ image_grid_thw=image_grid_thw,
876
+ height_position_ids=height_position_ids,
877
+ width_position_ids=width_position_ids,
878
+ )
879
+
880
+ last_hidden_state = self.post_layernorm(last_hidden_state)
881
+ return last_hidden_state
882
+
883
+
884
+ class SiglipVisionModel(nn.Module):
885
+ def __init__(
886
+ self,
887
+ config,
888
+ quant_config: QuantizationConfig | None = None,
889
+ prefix: str = "",
890
+ ):
891
+ super().__init__()
892
+
893
+ self.vision_model = SiglipVisionTransformer(
894
+ config,
895
+ quant_config=quant_config,
896
+ prefix=f"{prefix}.vision_model",
897
+ )
898
+ self.quant_config = quant_config
899
+
900
+ @property
901
+ def dtype(self) -> torch.dtype:
902
+ return self.vision_model.embeddings.patch_embedding.weight.dtype
903
+
904
+ @property
905
+ def device(self) -> torch.device:
906
+ return self.vision_model.embeddings.patch_embedding.weight.device
907
+
908
+ def get_input_embeddings(self) -> nn.Module:
909
+ return self.vision_model.embeddings.patch_embedding
910
+
911
+ def forward(
912
+ self,
913
+ pixel_values,
914
+ interpolate_pos_encoding: bool = False,
915
+ position_ids: torch.Tensor | None = None,
916
+ image_grid_thw: list[tuple[int, int, int] | list[tuple[int, int, int]]]
917
+ | None = None,
918
+ cu_seqlens: torch.Tensor | None = None,
919
+ ) -> BaseModelOutputWithPooling:
920
+ return self.vision_model(
921
+ pixel_values=pixel_values,
922
+ interpolate_pos_encoding=interpolate_pos_encoding,
923
+ position_ids=position_ids,
924
+ image_grid_thw=image_grid_thw,
925
+ cu_seqlens=cu_seqlens,
926
+ )
927
+
928
+ def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
929
+ stacked_params_mapping = [
930
+ ("qkv_proj", "q_proj", "q"),
931
+ ("qkv_proj", "k_proj", "k"),
932
+ ("qkv_proj", "v_proj", "v"),
933
+ ]
934
+ params_dict = dict(self.named_parameters(remove_duplicate=False))
935
+ loaded_params: set[str] = set()
936
+ for name, loaded_weight in weights:
937
+ if "rotary_emb.inv_freq" in name:
938
+ continue
939
+ if "head.attention" in name or "head.layernorm" in name:
940
+ continue
941
+ if "head.mlp" in name or "head.probe" in name:
942
+ continue
943
+ if "packing_position_embedding" in name:
944
+ continue
945
+ if self.quant_config is not None and (
946
+ scale_name := self.quant_config.get_cache_scale(name)
947
+ ):
948
+ param = params_dict[scale_name]
949
+ weight_loader = getattr(
950
+ param,
951
+ "weight_loader",
952
+ default_weight_loader,
953
+ )
954
+ loaded_weight = (
955
+ loaded_weight if loaded_weight.dim() == 0 else loaded_weight[0]
956
+ )
957
+ weight_loader(param, loaded_weight)
958
+ loaded_params.add(scale_name)
959
+ continue
960
+ for (
961
+ param_name,
962
+ weight_name,
963
+ shard_id,
964
+ ) in stacked_params_mapping:
965
+ if weight_name not in name:
966
+ continue
967
+ name = name.replace(weight_name, param_name)
968
+ if name.endswith(".bias") and name not in params_dict:
969
+ continue
970
+ if is_pp_missing_parameter(name, self):
971
+ continue
972
+ param = params_dict[name]
973
+ weight_loader = param.weight_loader
974
+ weight_loader(param, loaded_weight, shard_id)
975
+ break
976
+ else:
977
+ if name.endswith(".bias") and name not in params_dict:
978
+ continue
979
+ name = maybe_remap_kv_scale_name(name, params_dict)
980
+ if name is None:
981
+ continue
982
+ if is_pp_missing_parameter(name, self):
983
+ continue
984
+ param = params_dict[name]
985
+ weight_loader = getattr(
986
+ param,
987
+ "weight_loader",
988
+ default_weight_loader,
989
+ )
990
+ weight_loader(param, loaded_weight)
991
+ loaded_params.add(name)
992
+ return loaded_params
993
+
994
+
995
+ @MULTIMODAL_REGISTRY.register_processor(
996
+ VenusOCRMultiModalProcessor,
997
+ info=VenusOCRProcessingInfo,
998
+ dummy_inputs=VenusOCRDummyInputsBuilder,
999
+ )
1000
+ class VenusOCRForConditionalGeneration(nn.Module, SupportsMultiModal, SupportsMRoPE):
1001
+ hf_to_vllm_mapper = WeightsMapper(
1002
+ orig_to_new_prefix={
1003
+ "model.visual.": "visual.vision_model.",
1004
+ "model.projector.": "projector.",
1005
+ "model.language_model.": "language_model.model.",
1006
+ "lm_head.": "language_model.lm_head.",
1007
+ }
1008
+ )
1009
+
1010
+ @classmethod
1011
+ def get_placeholder_str(cls, modality: str, i: int) -> str | None:
1012
+ if modality.startswith("image"):
1013
+ return "<|vision_start|><|image_pad|><|vision_end|>"
1014
+
1015
+ raise ValueError("Only image modality is supported")
1016
+
1017
+ def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
1018
+ super().__init__()
1019
+ config = vllm_config.model_config.hf_config
1020
+ if hasattr(config, "text_config"):
1021
+ text_config = config.text_config.to_dict()
1022
+ unsafe_keys = ["model_type", "architectures"]
1023
+ for key in unsafe_keys:
1024
+ text_config.pop(key, None)
1025
+ config.update(text_config)
1026
+ config.model_type = "qwen3"
1027
+
1028
+ quant_config = vllm_config.quant_config
1029
+
1030
+ self.config = config
1031
+
1032
+ with self._mark_tower_model(vllm_config, "image"):
1033
+ self.visual = SiglipVisionModel(
1034
+ config=config.vision_config,
1035
+ quant_config=quant_config,
1036
+ prefix=maybe_prefix(prefix, "visual"),
1037
+ )
1038
+ self.projector = Projector(config, config.vision_config)
1039
+
1040
+ with self._mark_language_model(vllm_config):
1041
+ self.language_model = Qwen3ForCausalLM(
1042
+ vllm_config=vllm_config,
1043
+ prefix=maybe_prefix(prefix, "language_model"),
1044
+ )
1045
+
1046
+ self.make_empty_intermediate_tensors = (
1047
+ self.language_model.make_empty_intermediate_tensors
1048
+ )
1049
+
1050
+ def compute_logits(
1051
+ self,
1052
+ hidden_states: torch.Tensor,
1053
+ ) -> torch.Tensor | None:
1054
+ return self.language_model.compute_logits(hidden_states)
1055
+
1056
+ def get_mrope_input_positions(
1057
+ self,
1058
+ input_tokens: list[int],
1059
+ mm_features: list[MultiModalFeatureSpec],
1060
+ ) -> tuple[torch.Tensor, int]:
1061
+ spatial_merge_size = self.config.vision_config.spatial_merge_size
1062
+ llm_pos_ids_list: list[torch.Tensor] = []
1063
+ st = 0
1064
+
1065
+ image_features = sorted(
1066
+ (feature for feature in mm_features if feature.modality == "image"),
1067
+ key=lambda feature: feature.mm_position.offset,
1068
+ )
1069
+ for feature in image_features:
1070
+ offset = feature.mm_position.offset
1071
+ t, h, w = feature.data["image_grid_thw"].data.tolist()
1072
+ llm_grid_t, llm_grid_h, llm_grid_w = (
1073
+ t,
1074
+ h // spatial_merge_size,
1075
+ w // spatial_merge_size,
1076
+ )
1077
+ image_token_len = llm_grid_t * llm_grid_h * llm_grid_w
1078
+ text_len = offset - st
1079
+
1080
+ st_idx = llm_pos_ids_list[-1].max() + 1 if llm_pos_ids_list else 0
1081
+ if text_len > 0:
1082
+ llm_pos_ids_list.append(
1083
+ torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx
1084
+ )
1085
+
1086
+ t_index = (
1087
+ torch.arange(llm_grid_t)
1088
+ .view(-1, 1)
1089
+ .expand(-1, llm_grid_h * llm_grid_w)
1090
+ .flatten()
1091
+ )
1092
+ h_index = (
1093
+ torch.arange(llm_grid_h)
1094
+ .view(1, -1, 1)
1095
+ .expand(llm_grid_t, -1, llm_grid_w)
1096
+ .flatten()
1097
+ )
1098
+ w_index = (
1099
+ torch.arange(llm_grid_w)
1100
+ .view(1, 1, -1)
1101
+ .expand(llm_grid_t, llm_grid_h, -1)
1102
+ .flatten()
1103
+ )
1104
+ llm_pos_ids_list.append(
1105
+ torch.stack([t_index, h_index, w_index]) + text_len + st_idx
1106
+ )
1107
+ st = offset + image_token_len
1108
+
1109
+ if st < len(input_tokens):
1110
+ st_idx = llm_pos_ids_list[-1].max() + 1 if llm_pos_ids_list else 0
1111
+ text_len = len(input_tokens) - st
1112
+ llm_pos_ids_list.append(
1113
+ torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx
1114
+ )
1115
+
1116
+ llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(3, -1)
1117
+ mrope_position_delta = (llm_positions.max() + 1 - len(input_tokens)).item()
1118
+
1119
+ return llm_positions, mrope_position_delta
1120
+
1121
+ def _parse_and_validate_image_input(
1122
+ self, **kwargs: object
1123
+ ) -> VenusOCRImagePixelInputs | None:
1124
+ pixel_values = kwargs.pop("pixel_values", None)
1125
+ image_grid_thw = kwargs.pop("image_grid_thw", None)
1126
+
1127
+ if pixel_values is None:
1128
+ return None
1129
+
1130
+ return VenusOCRImagePixelInputs(
1131
+ type="pixel_values",
1132
+ pixel_values=pixel_values,
1133
+ image_grid_thw=image_grid_thw,
1134
+ )
1135
+
1136
+ def forward(
1137
+ self,
1138
+ input_ids: torch.Tensor | None,
1139
+ positions: torch.Tensor,
1140
+ intermediate_tensors: IntermediateTensors | None = None,
1141
+ inputs_embeds: torch.Tensor | None = None,
1142
+ **kwargs,
1143
+ ):
1144
+ if intermediate_tensors is not None:
1145
+ inputs_embeds = None
1146
+
1147
+ return self.language_model(
1148
+ input_ids, positions, intermediate_tensors, inputs_embeds
1149
+ )
1150
+
1151
+ def encode_image(
1152
+ self, pixel_values: torch.Tensor, image_grid_thw: torch.Tensor
1153
+ ) -> torch.Tensor:
1154
+ pixel_values = pixel_values.type(self.visual.dtype)
1155
+ siglip_position_ids = list()
1156
+ image_grid_hws = list()
1157
+ cu_seqlens = [0]
1158
+
1159
+ thw_tuple = tuple(image_grid_thw.tolist())
1160
+ numel = np.prod(thw_tuple)
1161
+ image_grid_hws.append(thw_tuple)
1162
+ image_position_ids = torch.arange(numel) % np.prod(thw_tuple[1:])
1163
+ siglip_position_ids.append(image_position_ids)
1164
+ cu_seqlens.append(cu_seqlens[-1] + numel)
1165
+
1166
+ siglip_position_ids = torch.concat(siglip_position_ids, dim=0).to(
1167
+ pixel_values.device
1168
+ )
1169
+ cu_seqlens = torch.tensor(cu_seqlens, dtype=torch.int32).to(pixel_values.device)
1170
+
1171
+ vision_outputs = self.visual(
1172
+ pixel_values=pixel_values,
1173
+ image_grid_thw=image_grid_hws,
1174
+ position_ids=siglip_position_ids,
1175
+ interpolate_pos_encoding=True,
1176
+ cu_seqlens=cu_seqlens,
1177
+ )
1178
+ return vision_outputs
1179
+
1180
+ def _process_image_input(
1181
+ self, image_input: VenusOCRImagePixelInputs
1182
+ ) -> MultiModalEmbeddings:
1183
+ pixel_values = image_input.pixel_values
1184
+ image_grid_thw = image_input.image_grid_thw
1185
+ vision_outputs = tuple(
1186
+ self.encode_image(pixel, grid).squeeze(0)
1187
+ for pixel, grid in zip(pixel_values, image_grid_thw)
1188
+ )
1189
+ image_embeds = self.projector(vision_outputs, image_grid_thw)
1190
+ return image_embeds
1191
+
1192
+ def embed_multimodal(self, **kwargs) -> MultiModalEmbeddings:
1193
+ image_input = self._parse_and_validate_image_input(**kwargs)
1194
+ if image_input is None:
1195
+ return ()
1196
+
1197
+ multimodal_embeddings: tuple[torch.Tensor, ...] = ()
1198
+ image_embeds = self._process_image_input(image_input)
1199
+ multimodal_embeddings += tuple(image_embeds)
1200
+
1201
+ return multimodal_embeddings
1202
+
1203
+ def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
1204
+ loader = AutoWeightsLoader(self)
1205
+ autoloaded_weights = loader.load_weights(weights, mapper=self.hf_to_vllm_mapper)
1206
+ return autoloaded_weights
scripts/vllm_serve_ptp2.sh ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Launch an OpenAI-compatible vLLM server for VenusOCR2-1B with optional PTPv2 speculative decoding.
3
+ #
4
+ # Usage:
5
+ # bash scripts/vllm_serve_ptp2.sh
6
+ # USE_PTP2=0 bash scripts/vllm_serve_ptp2.sh
7
+ # CUDA_VISIBLE_DEVICES=0 PORT=8000 bash scripts/vllm_serve_ptp2.sh
8
+
9
+ set -euo pipefail
10
+
11
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
12
+ MODEL_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
13
+
14
+ MODEL="${VENUSOCR_MODEL:-$MODEL_DIR}"
15
+ DRAFT="${PTP2_MODEL:-$MODEL_DIR/ptp2}"
16
+ VLLM_PYTHON="${VLLM_PYTHON:-python}"
17
+
18
+ export CUDA_VISIBLE_DEVICES="${CUDA_VISIBLE_DEVICES:-0}"
19
+ export VLLM_PLUGINS="${VLLM_PLUGINS-}"
20
+ export VLLM_BATCH_INVARIANT="${VLLM_BATCH_INVARIANT:-1}"
21
+
22
+ ARGS=(
23
+ --model "$MODEL"
24
+ --trust-remote-code
25
+ --served-model-name "${SERVED_MODEL_NAME:-venusocr}"
26
+ --host "${HOST:-0.0.0.0}"
27
+ --port "${PORT:-8000}"
28
+ --max-model-len "${MAX_MODEL_LEN:-10240}"
29
+ --max-num-seqs "${MAX_NUM_SEQS:-8}"
30
+ --max-num-batched-tokens "${MAX_NUM_BATCHED_TOKENS:-4096}"
31
+ --gpu-memory-utilization "${GPU_MEMORY_UTILIZATION:-0.75}"
32
+ --attention-backend FLASH_ATTN
33
+ )
34
+
35
+ if [[ "${ENFORCE_EAGER:-0}" == 1 ]]; then
36
+ ARGS+=(--enforce-eager)
37
+ fi
38
+
39
+ if [[ "${USE_PTP2:-1}" == 1 ]]; then
40
+ SPEC_CONFIG="$("$VLLM_PYTHON" -c 'import json,sys; print(json.dumps({"model":sys.argv[1],"method":"ptp2","num_speculative_tokens":5,"draft_tensor_parallel_size":1}))' "$DRAFT")"
41
+ ARGS+=(--speculative-config "$SPEC_CONFIG")
42
+ fi
43
+
44
+ exec "$VLLM_PYTHON" -m vllm.entrypoints.openai.api_server "${ARGS[@]}" "$@"
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:025223b330d17e7a06512b550e30086b06e96bd66c6fb0b640aeee4d8f05d10b
3
+ size 11424280
tokenizer_config.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "auto_map": {
4
+ "AutoProcessor": "processing_venusocr.VenusOCRProcessor"
5
+ },
6
+ "backend": "tokenizers",
7
+ "bos_token": null,
8
+ "clean_up_tokenization_spaces": false,
9
+ "eos_token": "<|im_end|>",
10
+ "errors": "replace",
11
+ "extra_special_tokens": [
12
+ "<image>"
13
+ ],
14
+ "model_max_length": 16384,
15
+ "pad_token": "<|endoftext|>",
16
+ "padding_side": "left",
17
+ "processor_class": "VenusOCRProcessor",
18
+ "split_special_tokens": false,
19
+ "tokenizer_class": "Qwen2Tokenizer",
20
+ "unk_token": null
21
+ }