Other
Transformers
Safetensors
English
qwen2_5_omni_composite
text-generation
multimodal
qwen2.5-omni
remote-sensing
earth-observation
ecg
cardiac-mri
speech-recognition
lipreading
custom_code
Instructions to use dvps/dvps-fm-v1 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use dvps/dvps-fm-v1 with Transformers:
# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("dvps/dvps-fm-v1", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Riccardo Corrente commited on
Add files using upload-large-folder tool
Browse files- README.md +575 -0
- modeling_omni.py +662 -0
README.md
ADDED
|
@@ -0,0 +1,575 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
base_model: Qwen/Qwen2.5-Omni-7B
|
| 3 |
+
base_model_relation: finetune
|
| 4 |
+
library_name: transformers
|
| 5 |
+
pipeline_tag: other
|
| 6 |
+
license: cc-by-nc-sa-4.0
|
| 7 |
+
language:
|
| 8 |
+
- en
|
| 9 |
+
tags:
|
| 10 |
+
- multimodal
|
| 11 |
+
- qwen2.5-omni
|
| 12 |
+
- custom_code
|
| 13 |
+
- remote-sensing
|
| 14 |
+
- earth-observation
|
| 15 |
+
- ecg
|
| 16 |
+
- cardiac-mri
|
| 17 |
+
- speech-recognition
|
| 18 |
+
- lipreading
|
| 19 |
+
---
|
| 20 |
+
|
| 21 |
+
# DVPS-FM-v1
|
| 22 |
+
|
| 23 |
+
## Overview
|
| 24 |
+
|
| 25 |
+
### Introduction
|
| 26 |
+
|
| 27 |
+
DVPS-FM-v1 is a multi-modal model based on the Qwen2.5-Omni-7B.
|
| 28 |
+
In addition to Qwen's vision and audio towers, it uses four frozen domain encoders
|
| 29 |
+
(TerraMind, a version of MedGemma SigLIP finetuned on ECGs, and the Auto-AVSR audio and video encoders), each
|
| 30 |
+
connected to the language model through a trained projector. It accepts text, images,
|
| 31 |
+
video, audio, Sentinel-1/2 rasters, ECG plots and cardiac MRI slices, lip-region
|
| 32 |
+
video and produces text.
|
| 33 |
+
|
| 34 |
+
The model was finetuned on a mixture of 17 datasets from three application domains:
|
| 35 |
+
geo-intelligence, cardiology, and language communication. It is released as a single
|
| 36 |
+
checkpoint with the language model, encoders, and projectors in one set of weights.
|
| 37 |
+
|
| 38 |
+
* **Parameters**: 10.08B (22.4 GB of safetensors; language model in BF16, encoders in
|
| 39 |
+
FP32).
|
| 40 |
+
* **Input modalities**: text, RGB image, video, audio, Sentinel-1 GRD + Sentinel-2
|
| 41 |
+
L2A, ECG or cardiac MRI image, lip-region video. TODO
|
| 42 |
+
* **Output**: text only.
|
| 43 |
+
* **Loading**: a single `from_pretrained` call with `trust_remote_code=True`.
|
| 44 |
+
|
| 45 |
+
### Model Architecture
|
| 46 |
+
|
| 47 |
+
```
|
| 48 |
+
┌───────────────────────── frozen encoders ────────────────────────────┐
|
| 49 |
+
text ─────────► │ Qwen tokenizer │
|
| 50 |
+
RGB image/video │ Qwen2.5-Omni vision tower │
|
| 51 |
+
raw audio ────► │ Qwen2.5-Omni audio tower │
|
| 52 |
+
S1GRD + S2L2A ─►│ TerraMind v1 Large ──────────► projector ─► 128 × <|terramind|> │──► Qwen2.5-Omni-7B Thinker ──► text
|
| 53 |
+
ECG / MRI ────► │ MedGemma-4B SigLIP ──────────► projector ─► 256 × <|medgemma|> │ (28 layers, finetuned)
|
| 54 |
+
speech ───────► │ Auto-AVSR audio encoder ─────► projector ─► 80 × <|autoavsr_audio|> │
|
| 55 |
+
mouth video ──► │ Auto-AVSR visual encoder ────► projector ─► 80 × <|autoavsr_video|> │
|
| 56 |
+
└──────────────────────────────────────────────────────────────────────┘
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
| Component | Source | Finetuned |
|
| 60 |
+
|---|---|---|
|
| 61 |
+
| Language model | Qwen2.5-Omni-7B Thinker | Yes, all attention and MLP projections |
|
| 62 |
+
| Vision and audio towers | Qwen2.5-Omni-7B | No |
|
| 63 |
+
| `terramind` | TerraMind v1 Large, S1GRD (2 ch) + S2L2A (12 ch), 128×128 px | Projector only |
|
| 64 |
+
| `medgemma` | `convaiinnovations/medgemma-4b-ecginstruct` SigLIP, 896 px | Projector only |
|
| 65 |
+
| `autoavsr_audio` | Auto-AVSR ASR base (LRS3 + VoxCeleb2), 16 s window | Projector only |
|
| 66 |
+
| `autoavsr_video` | Auto-AVSR VSR base, 88×88 grayscale mouth ROI | Projector only |
|
| 67 |
+
|
| 68 |
+
### Supported Tasks
|
| 69 |
+
|
| 70 |
+
| Domain | Task | Input | Example prompt |
|
| 71 |
+
|---|---|---|---|
|
| 72 |
+
| Geo-intelligence | Multispectral captioning, QA, grounding | `<terramind>` S1 + S2 patch | "Describe the land cover in this Sentinel scene." |
|
| 73 |
+
| | High-resolution remote-sensing VQA | RGB image | "Is there a road next to the residential area?" |
|
| 74 |
+
| | Counting and area estimation | RGB image | "How many buildings are there?" |
|
| 75 |
+
| Cardiology | ECG question answering | `<medgemma>` ECG plot (one per marker) | "Does this ECG show atrial fibrillation?" |
|
| 76 |
+
| | ECG diagnosis and explanation | `<medgemma>` ECG plot | "List the diagnoses supported by this ECG and explain why." |
|
| 77 |
+
| | Cardiac MRI view, sequence, and structures | `<medgemma>` MRI slice | "Which cardiac structures are visible in this slice?" |
|
| 78 |
+
| Language communication | Speech recognition | audio | "Transcribe the audio into text." |
|
| 79 |
+
| | Video-speech recognition / lipreading | `<autoavsr_video>` | "Transcribe what the speaker says." |
|
| 80 |
+
| | Audio-visual speech recognition | `<autoavsr_audio>` + `<autoavsr_video>` | "Transcribe what the speaker says." |
|
| 81 |
+
| | Spoken language understanding | audio | "What is the speaker's intent?" |
|
| 82 |
+
| | Spoken math to LaTeX | audio | "Write the spoken equation in LaTeX." |
|
| 83 |
+
| | Multilingual instruction following | text | Any text instruction |
|
| 84 |
+
| General | Image question answering | RGB image | Any question about the image |
|
| 85 |
+
|
| 86 |
+
## QuickStart
|
| 87 |
+
|
| 88 |
+
### Model Description and Download
|
| 89 |
+
|
| 90 |
+
| Model | Description |
|
| 91 |
+
|---|---|
|
| 92 |
+
| **DVPS-FM-v1** | The Qwen2.5-Omni-7B Thinker with the TerraMind, MedGemma, and Auto-AVSR encoders and their projectors, supporting text, image, audio, video, multispectral EO, ECG, and lip-video input, with text output. |
|
| 93 |
+
|
| 94 |
+
```bash
|
| 95 |
+
hf download CamelShirt43/dvps-fm-v1 --local-dir dvps-fm-v1
|
| 96 |
+
```
|
| 97 |
+
|
| 98 |
+
The repository contains the weights (`model-0000X-of-00005.safetensors` and the index),
|
| 99 |
+
`config.json`, the processor and tokenizer files, the custom code
|
| 100 |
+
(`modeling_omni.py`, `configuration_omni.py`, `processor_omni.py`, `encoders_*.py`),
|
| 101 |
+
and two support files:
|
| 102 |
+
|
| 103 |
+
- `terramind_mask_token.pt`: TerraMind's pretrained missing-modality token, loaded on
|
| 104 |
+
the first single-modality TerraMind input.
|
| 105 |
+
- `auto_avsr/`: the `espnet` modules of [Auto-AVSR](https://github.com/mpc001/auto_avsr)
|
| 106 |
+
(Apache-2.0, see `auto_avsr/LICENSE`) that define the Auto-AVSR encoder architecture.
|
| 107 |
+
|
| 108 |
+
All paths in the configs are relative to the repository. The custom code resolves them
|
| 109 |
+
in the local directory, or downloads them from the Hub repo the model was loaded from.
|
| 110 |
+
|
| 111 |
+
### Transformers Usage
|
| 112 |
+
|
| 113 |
+
#### Installation
|
| 114 |
+
|
| 115 |
+
The model was tested with Transformers 5.2.0, plus the libraries used by the extra encoders. We
|
| 116 |
+
strongly recommend a fresh environment.
|
| 117 |
+
|
| 118 |
+
```bash
|
| 119 |
+
pip install "transformers==5.2.0" accelerate
|
| 120 |
+
pip install qwen-omni-utils -U # native image/audio/video handling
|
| 121 |
+
pip install terratorch # TerraMind backbone
|
| 122 |
+
pip install av librosa soundfile torchaudio torchvision # Auto-AVSR and audio I/O
|
| 123 |
+
```
|
| 124 |
+
|
| 125 |
+
All encoder weights are already in the checkpoint, and the Auto-AVSR code is bundled,
|
| 126 |
+
so nothing else needs to be cloned or downloaded.
|
| 127 |
+
|
| 128 |
+
#### Code Snippet
|
| 129 |
+
|
| 130 |
+
```python
|
| 131 |
+
import torch
|
| 132 |
+
from transformers import AutoModelForCausalLM, AutoProcessor
|
| 133 |
+
|
| 134 |
+
MODEL_PATH = "CamelShirt43/dvps-fm-v1" # or a local download
|
| 135 |
+
|
| 136 |
+
processor = AutoProcessor.from_pretrained(MODEL_PATH, trust_remote_code=True)
|
| 137 |
+
processor.tokenizer.padding_side = "left"
|
| 138 |
+
|
| 139 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 140 |
+
MODEL_PATH, trust_remote_code=True, dtype=torch.bfloat16
|
| 141 |
+
).to("cuda").eval()
|
| 142 |
+
|
| 143 |
+
conversation = [
|
| 144 |
+
{
|
| 145 |
+
"role": "user",
|
| 146 |
+
"content": [
|
| 147 |
+
{"type": "text", "text": "<medgemma>\nDoes this ECG show signs of myocardial infarction?"},
|
| 148 |
+
],
|
| 149 |
+
},
|
| 150 |
+
]
|
| 151 |
+
|
| 152 |
+
text = processor.apply_chat_template(conversation, add_generation_prompt=True, tokenize=False)
|
| 153 |
+
inputs = processor(
|
| 154 |
+
text=text,
|
| 155 |
+
encoder_samples={"medgemma": "/path/to/ecg_plot.png"},
|
| 156 |
+
return_tensors="pt",
|
| 157 |
+
padding=True,
|
| 158 |
+
).to("cuda")
|
| 159 |
+
|
| 160 |
+
output_ids = model.generate(**inputs, max_new_tokens=256, do_sample=False)
|
| 161 |
+
print(processor.batch_decode(output_ids[:, inputs["input_ids"].shape[1]:], skip_special_tokens=True)[0])
|
| 162 |
+
```
|
| 163 |
+
|
| 164 |
+
The model code builds TerraMind outside the meta device and recomputes the rotary
|
| 165 |
+
buffers after loading, so no loading workarounds are needed.
|
| 166 |
+
|
| 167 |
+
<details>
|
| 168 |
+
<summary>Batch inference across domains</summary>
|
| 169 |
+
|
| 170 |
+
`encoder_samples` maps each encoder name to a list with one entry per conversation in
|
| 171 |
+
the batch. Use `None` for conversations that don't use that encoder. Native Qwen
|
| 172 |
+
images and audio go through `qwen_omni_utils.process_mm_info` as usual.
|
| 173 |
+
|
| 174 |
+
```python
|
| 175 |
+
import numpy as np
|
| 176 |
+
from qwen_omni_utils import process_mm_info
|
| 177 |
+
|
| 178 |
+
# Multispectral Sentinel patch through TerraMind
|
| 179 |
+
conversation1 = [
|
| 180 |
+
{"role": "user", "content": [
|
| 181 |
+
{"type": "text", "text": "<terramind>\nDescribe the land cover in this scene."},
|
| 182 |
+
]},
|
| 183 |
+
]
|
| 184 |
+
|
| 185 |
+
# Two ECGs compared in one question: two markers, two payloads, in order
|
| 186 |
+
conversation2 = [
|
| 187 |
+
{"role": "user", "content": [
|
| 188 |
+
{"type": "text", "text": "<medgemma>\n<medgemma>\nDid the QRS duration change between these two ECGs?"},
|
| 189 |
+
]},
|
| 190 |
+
]
|
| 191 |
+
|
| 192 |
+
# Audio-visual speech recognition through Auto-AVSR
|
| 193 |
+
conversation3 = [
|
| 194 |
+
{"role": "user", "content": [
|
| 195 |
+
{"type": "text", "text": "<autoavsr_audio><autoavsr_video>\nTranscribe what the speaker says."},
|
| 196 |
+
]},
|
| 197 |
+
]
|
| 198 |
+
|
| 199 |
+
# Native RGB image through Qwen's vision tower
|
| 200 |
+
conversation4 = [
|
| 201 |
+
{"role": "user", "content": [
|
| 202 |
+
{"type": "image", "image": "/path/to/aerial.png"},
|
| 203 |
+
{"type": "text", "text": "How many buildings are there?"},
|
| 204 |
+
]},
|
| 205 |
+
]
|
| 206 |
+
|
| 207 |
+
conversations = [conversation1, conversation2, conversation3, conversation4]
|
| 208 |
+
|
| 209 |
+
encoder_samples = {
|
| 210 |
+
"terramind": [
|
| 211 |
+
{"S1GRD": np.load("s1.npy"), "S2L2A": np.load("s2.npy")}, # (2, 128, 128), (12, 128, 128)
|
| 212 |
+
None, None, None,
|
| 213 |
+
],
|
| 214 |
+
"medgemma": [None, ["ecg_t0.png", "ecg_t1.png"], None, None],
|
| 215 |
+
"autoavsr_audio": [None, None, "clip.wav", None],
|
| 216 |
+
"autoavsr_video": [None, None, "clip_mouth.mp4", None], # 88x88 mouth crops
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
text = processor.apply_chat_template(conversations, add_generation_prompt=True, tokenize=False)
|
| 220 |
+
audios, images, videos = process_mm_info(conversations, use_audio_in_video=False)
|
| 221 |
+
inputs = processor(
|
| 222 |
+
text=text,
|
| 223 |
+
audio=audios,
|
| 224 |
+
images=images,
|
| 225 |
+
videos=videos,
|
| 226 |
+
encoder_samples=encoder_samples,
|
| 227 |
+
return_tensors="pt",
|
| 228 |
+
padding=True,
|
| 229 |
+
).to("cuda")
|
| 230 |
+
|
| 231 |
+
output_ids = model.generate(**inputs, max_new_tokens=256, do_sample=False)
|
| 232 |
+
print(processor.batch_decode(output_ids[:, inputs["input_ids"].shape[1]:], skip_special_tokens=True))
|
| 233 |
+
```
|
| 234 |
+
</details>
|
| 235 |
+
|
| 236 |
+
### Usage Tips (Recommended Reading)
|
| 237 |
+
|
| 238 |
+
#### GPU memory
|
| 239 |
+
|
| 240 |
+
The model has 10.08B parameters: 8.93B in BF16 (the Qwen Thinker) and 1.15B in FP32
|
| 241 |
+
(the extra encoders and projectors), about 22.4 GB of weights. Activations come on top:
|
| 242 |
+
a MedGemma image adds 256 tokens, a TerraMind patch 128, and each Auto-AVSR stream 80
|
| 243 |
+
per 16 s window. Inference fits on one 64 GB A100; training used 4 samples per 64 GB
|
| 244 |
+
A100 at a 4,096-token cutoff.
|
| 245 |
+
|
| 246 |
+
#### Encoder markers
|
| 247 |
+
|
| 248 |
+
Every extra-encoder input needs a text marker. The processor expands each marker into
|
| 249 |
+
the encoder's placeholder tokens:
|
| 250 |
+
|
| 251 |
+
| Marker | Expands to | Payload |
|
| 252 |
+
|---|---|---|
|
| 253 |
+
| `<terramind>` | 128 × `<\|terramind\|>` | `dict` with `S1GRD` and/or `S2L2A` (array or `.npy` path). One modality may be missing; it is replaced by the TerraMind mask token. |
|
| 254 |
+
| `<medgemma>` | 256 × `<\|medgemma\|>` | Image path, bytes, or PIL image |
|
| 255 |
+
| `<autoavsr_audio>` | 80 × `<\|autoavsr_audio\|>` | Audio path, `(array, sampling_rate)`, or array at 16 kHz |
|
| 256 |
+
| `<autoavsr_video>` or `<lipread>` | 80 × `<\|autoavsr_video\|>` | Mouth-crop video path or array |
|
| 257 |
+
|
| 258 |
+
The number of markers in a conversation must equal the number of payloads for that
|
| 259 |
+
encoder, and payloads are consumed in marker order. Place markers **before** the
|
| 260 |
+
question, as in training.
|
| 261 |
+
|
| 262 |
+
#### Structured answers
|
| 263 |
+
|
| 264 |
+
Several training tasks used fixed answer formats. Prompts that request the same
|
| 265 |
+
format match the training distribution:
|
| 266 |
+
|
| 267 |
+
- ECG-QA: `Return your answer in JSON with the format {'answer': '<answer>', 'reason': '<reason>'}`
|
| 268 |
+
- RSVQA-HR and BigEarthNet binary/MCQA: a single word, or a letter `a`–`d`.
|
| 269 |
+
- BigEarthNet grounding: unit-normalized boxes, as in the training data.
|
| 270 |
+
|
| 271 |
+
## Evaluation
|
| 272 |
+
|
| 273 |
+
### Performance of DVPS-FM-v1
|
| 274 |
+
|
| 275 |
+
DVPS-FM-v1 is the best model in our comparison on RSVQA-HR presence, comparison and
|
| 276 |
+
count, ECG-Instruct, ECG-QA, Speech2LaTeX, and LNQA. It beats base Qwen2.5-Omni-7B by
|
| 277 |
+
large margins on almost every in-domain task. Our single-domain specialists remain
|
| 278 |
+
stronger on BigEarthNet.txt, VRSBench-VQA, and LipCrops. General text ability is
|
| 279 |
+
largely kept, but Qwen's native visual grounding (RefCOCO, VRSBench in the benchmark's
|
| 280 |
+
box format) is TODO (see [Limitations](#limitations)).
|
| 281 |
+
|
| 282 |
+
Columns:
|
| 283 |
+
|
| 284 |
+
- **Qwen2.5-Omni-7B**: the untuned base model.
|
| 285 |
+
- **Specialist**: the best single-domain DVPS model for that benchmark (see footnotes).
|
| 286 |
+
- **DVPS-FM-v1**: this release.
|
| 287 |
+
|
| 288 |
+
The best score in each row is in bold. ↓ means lower is better.
|
| 289 |
+
|
| 290 |
+
<details open>
|
| 291 |
+
<summary>Geo-intelligence</summary>
|
| 292 |
+
|
| 293 |
+
| Benchmark | Metric | Qwen2.5-Omni-7B | Specialist | **DVPS-FM-v1** |
|
| 294 |
+
|---|---|---|---|---|
|
| 295 |
+
| **RSVQA-HR** | Presence acc. | 63.84 | 91.80 ᵃ | **92.04** |
|
| 296 |
+
| | Comparison acc. | 72.40 | 89.28 ᵃ | **91.52** |
|
| 297 |
+
| | Count acc. | 33.26 | 68.10 ᵃ | **69.10** |
|
| 298 |
+
| | Area acc. | 4.74 | **61.28** ᵃ | 59.08 |
|
| 299 |
+
| **VRSBench-VQA** | Accuracy | 43.62 | **53.68** ᵃ | 49.36 |
|
| 300 |
+
| | LLM-judge acc. | — | — | 59.36 |
|
| 301 |
+
| **VRSBench-Caption** | BLEU-1 | 13.59 | 19.10 ᵃ | **19.67** |
|
| 302 |
+
| | METEOR | **23.94** | 13.72 ᵃ | 13.81 |
|
| 303 |
+
| | CIDEr | 0.02 | 2.07 ᵃ | **2.60** |
|
| 304 |
+
| **VRSBench-Grounding** (benchmark JSON, percent boxes) | acc@0.5 | **39.10** | 0.00 ᵃ | 4.52 |
|
| 305 |
+
| | mIoU | **37.09** | 0.00 ᵃ | 0.00 |
|
| 306 |
+
| **VRSBench-Grounding** (GeoChat refer prompt and boxes) | acc@0.5 | — | — | 36.74 |
|
| 307 |
+
| | mIoU | — | — | 37.57 |
|
| 308 |
+
| **BigEarthNet.txt (S1+S2)** | Binary QA acc. | 58.36 ᶜ | **77.46** ᵇ | 70.04 |
|
| 309 |
+
| | MCQA acc. | 30.66 ᶜ | **79.48** ᵇ | 59.92 |
|
| 310 |
+
| | Caption BLEU-2 | 5.40 ᶜ | **51.60** ᵇ | 42.92 |
|
| 311 |
+
| | Caption BLEU-4 | 0.90 ᶜ | **42.12** ᵇ | 32.20 |
|
| 312 |
+
| | Bounding-box mIoU | 9.17 ᶜ | **57.92** ᵇ | 17.09 |
|
| 313 |
+
|
| 314 |
+
</details>
|
| 315 |
+
|
| 316 |
+
<details open>
|
| 317 |
+
<summary>Language communication</summary>
|
| 318 |
+
|
| 319 |
+
| Benchmark | Metric | Qwen2.5-Omni-7B | Specialist | **DVPS-FM-v1** |
|
| 320 |
+
|---|---|---|---|---|
|
| 321 |
+
| **LipCrops, audio** (Qwen audio tower) | WER ↓ | 12.62 | **6.70** ᵈ | 8.85 |
|
| 322 |
+
| | CER ↓ | 8.89 | **4.76** ᵈ | 6.25 |
|
| 323 |
+
| | Word F1 | 92.22 | **95.62** ᵈ | 94.43 |
|
| 324 |
+
| **LipCrops, audio + video** (Qwen towers) | WER ↓ | 21.35 | **6.83** ᵉ | 7.93 |
|
| 325 |
+
| | CER ↓ | 18.88 | **4.87** ᵉ | 5.58 |
|
| 326 |
+
| **LipCrops, Auto-AVSR audio + video** | WER ↓ | — | **17.33** ᶠ | 20.44 |
|
| 327 |
+
| | CER ↓ | — | **12.61** ᶠ | 15.17 |
|
| 328 |
+
| | Word F1 | — | **88.38** ᶠ | 87.21 |
|
| 329 |
+
| **LipCrops, Auto-AVSR audio only** | WER ↓ | — | — | 22.57 |
|
| 330 |
+
| **Speech2LaTeX, sentences** | TeXBLEU | 82.92 | — | **86.04** |
|
| 331 |
+
| | CER ↓ | 28.87 | — | **13.70** |
|
| 332 |
+
| **Speech2LaTeX, equations** | TeXBLEU | 79.78 | — | **90.05** |
|
| 333 |
+
| | CER ↓ | 138.68 | — | **30.30** |
|
| 334 |
+
| **LNQA** | LLM-judge binary acc. | 69.54 | — | **77.98** |
|
| 335 |
+
| | Content-word F1 | 37.81 | — | **65.56** |
|
| 336 |
+
| **Aya** | LLM-judge acc. | — | — | 41.85 |
|
| 337 |
+
| | ROUGE-L | — | — | 17.07 |
|
| 338 |
+
|
| 339 |
+
</details>
|
| 340 |
+
|
| 341 |
+
<details open>
|
| 342 |
+
<summary>Cardiology</summary>
|
| 343 |
+
|
| 344 |
+
| Benchmark | Metric | Qwen2.5-Omni-7B | Specialist | **DVPS-FM-v1** |
|
| 345 |
+
|---|---|---|---|---|
|
| 346 |
+
| **ECG-Instruct PTB-XL** | MCQA acc. | 57.04 | 47.72 ᵍ | **93.97** |
|
| 347 |
+
| | Diagnosis set acc. | 30.08 | 18.18 ᵍ | **61.92** |
|
| 348 |
+
| | Diagnosis set F1 | 46.77 | — | **75.90** |
|
| 349 |
+
| | Superclass macro AUC | 50.90 | — | **82.01** |
|
| 350 |
+
| | METEOR (open) | 17.27 | 33.16 ᵍ | **33.96** |
|
| 351 |
+
| | LLM-judge acc. (explained) | 42.07 | — | **64.58** |
|
| 352 |
+
| | LLM-judge acc. (open) | 33.36 | — | **38.07** |
|
| 353 |
+
| **ECG-Instruct MIMIC** | MCQA acc. | 37.03 | — | **89.99** |
|
| 354 |
+
| | Diagnosis set acc. | 29.60 | — | **72.34** |
|
| 355 |
+
| | Diagnosis macro F1 | 20.25 | — | **55.07** |
|
| 356 |
+
| | METEOR (open) | 19.85 | 36.21 ᵍ | **44.72** |
|
| 357 |
+
| | CIDEr (open) | 5.18 | — | **63.44** |
|
| 358 |
+
| | LLM-judge acc. (explained) | 33.51 | — | **67.47** |
|
| 359 |
+
| | LLM-judge acc. (open) | 19.14 | — | **43.24** |
|
| 360 |
+
| **ECG-QA PTB-XL** | Single-verify set acc. | 54.45 | — | **73.00** |
|
| 361 |
+
| | Single-choose set acc. | 27.02 | — | **62.42** |
|
| 362 |
+
| | Single-query set acc. | — | — | **27.56** |
|
| 363 |
+
| | Comparison-consecutive-verify set acc. | 56.19 | — | **74.42** |
|
| 364 |
+
| | Comparison-irrelevant-verify set acc. | 46.72 | — | **82.86** |
|
| 365 |
+
| **ECG-QA MIMIC-IV** | Single-verify set acc. | — | 63.30 ᵍ | **73.10** |
|
| 366 |
+
| | Single-choose set acc. | — | 29.00 ᵍ | **59.72** |
|
| 367 |
+
| | Single-query set acc. | — | — | **12.66** |
|
| 368 |
+
| **M&Ms-2** (cardiac MRI) | View acc. | 51.30 ʰ | — | **99.38** |
|
| 369 |
+
| | LV / RV cavity presence acc. | — | — | 94.28 / 94.30 |
|
| 370 |
+
| | Structures exact match | 35.73 ʰ | — | **94.17** |
|
| 371 |
+
| | Caption ROUGE-L | 34.82 ʰ | — | **98.43** |
|
| 372 |
+
|
| 373 |
+
</details>
|
| 374 |
+
|
| 375 |
+
ᵃ `qwen25omni_lora_16_GI_all/checkpoint-20000`: Qwen LoRA on 4 RGB geo datasets.
|
| 376 |
+
ᵇ `bentxt_s1s2_projector_evalsize_500/checkpoint-23000`: TerraMind projector + LoRA, BigEarthNet only.
|
| 377 |
+
ᶜ Base Qwen on RGB renders of the S1/S2 patches, so not directly comparable.
|
| 378 |
+
ᵈ `qwen25_omni_lipcrops_audio/checkpoint-8000`: Qwen LoRA on LipCrops audio.
|
| 379 |
+
ᵉ `qwen25_omni_lipcrops_av/checkpoint-8000`: Qwen LoRA on LipCrops audio + video.
|
| 380 |
+
ᶠ `autoavsr_av_lora/checkpoint-9000`: Auto-AVSR projectors + LoRA on LipCrops.
|
| 381 |
+
ᵍ `Qwen2.5-Omni-7B-CD-LoRA-checkpoint-6000`: Qwen LoRA on 4 ECG datasets, ECGs fed as native images.
|
| 382 |
+
ʰ Base Qwen with the MRI slices as native images; DVPS-FM-v1 reads them through `<medgemma>`.
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
<details open>
|
| 386 |
+
<summary>General capabilities (forgetting)</summary>
|
| 387 |
+
|
| 388 |
+
How much of the Qwen2.5-Omni-7B backbone's general ability survives DVPS training.
|
| 389 |
+
Text benchmarks are scored with lm-evaluation-harness.
|
| 390 |
+
|
| 391 |
+
| Benchmark | Metric | Qwen2.5-Omni-7B | **DVPS-FM-v1** |
|
| 392 |
+
|---|---|---|---|
|
| 393 |
+
| **MMLU-redux** | Exact match | **74.17** | 73.51 |
|
| 394 |
+
| **MMLU-Pro** | Exact match | 45.62 | pending |
|
| 395 |
+
| **GPQA Diamond** (CoT, 0-shot) | Exact match (flexible) | 28.79 | **29.80** |
|
| 396 |
+
| **GSM8K** (CoT) | Exact match (flexible) | **78.09** | 74.98 |
|
| 397 |
+
| **MATH** | math-verify | 71.60 | pending |
|
| 398 |
+
| **HumanEval** (instruct) | pass@1 | 68.90 | **73.17** |
|
| 399 |
+
| **MBPP** (instruct) | pass@1 | **62.20** | 59.60 |
|
| 400 |
+
| **MMBench** | Accuracy | **87.69** | 86.00 |
|
| 401 |
+
| **MMMU** | MCQA accuracy | **54.31** | 53.60 |
|
| 402 |
+
| **OmniBench** | Accuracy | **49.56** | 43.61 |
|
| 403 |
+
| **MMAU** | Accuracy | — | 75.70 |
|
| 404 |
+
| **LibriSpeech** test-clean / test-other | WER ↓ | — | 2.01 / 3.96 |
|
| 405 |
+
| **RefCOCO** | acc@0.5 | **92.35** | 1.70 |
|
| 406 |
+
| **RefCOCO+** | acc@0.5 | **84.35** | 2.85 |
|
| 407 |
+
| **RefCOCOg** | acc@0.5 | **88.80** | 1.15 |
|
| 408 |
+
|
| 409 |
+
</details>
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
<details>
|
| 413 |
+
<summary>Validation loss by dataset</summary>
|
| 414 |
+
|
| 415 |
+
Probability-weighted mean validation loss: **0.5868**.
|
| 416 |
+
|
| 417 |
+
| Dataset | Loss |
|
| 418 |
+
|---|---|
|
| 419 |
+
| BigEarthNet S1+S2 | 0.347 |
|
| 420 |
+
| GeoChat | 0.470 |
|
| 421 |
+
| RSVQA-HR | 0.218 |
|
| 422 |
+
| RSTeller | 1.459 |
|
| 423 |
+
| Aya | 1.427 |
|
| 424 |
+
| LipCrops video (Auto-AVSR) | 1.647 |
|
| 425 |
+
| LipCrops AV (Auto-AVSR) | 0.415 |
|
| 426 |
+
| Audio-FLAN SLU | 0.567 |
|
| 427 |
+
| Speech2LaTeX sentences | 0.322 |
|
| 428 |
+
| Speech2LaTeX equations | 0.362 |
|
| 429 |
+
| ECG-QA PTB-XL | 0.286 |
|
| 430 |
+
| ECG-QA MIMIC-IV | 0.299 |
|
| 431 |
+
| ECG-Instruct PTB-XL | 0.453 |
|
| 432 |
+
| ECG-Instruct MIMIC | 0.424 |
|
| 433 |
+
| ACDC | 0.018 |
|
| 434 |
+
| M&Ms-2 | 0.013 |
|
| 435 |
+
| EMIDEC | 0.123 |
|
| 436 |
+
| LNQA | 0.428 |
|
| 437 |
+
|
| 438 |
+
</details>
|
| 439 |
+
|
| 440 |
+
### Setting for Evaluation
|
| 441 |
+
|
| 442 |
+
* **Decoding strategy**: All models use greedy decoding (`do_sample=False`).
|
| 443 |
+
* **Harness**: DVPS-BENCH (`evals/DVPS-BENCH`). Raw predictions and configs for
|
| 444 |
+
this checkpoint are stored with the DVPS-BENCH results.
|
| 445 |
+
* **Sample counts**: Up to 5,000 test samples per benchmark or question type.
|
| 446 |
+
BigEarthNet captioning uses 970, BigEarthNet grounding 1,582, LipCrops 2,298, and
|
| 447 |
+
Speech2LaTeX about 2,850 per split.
|
| 448 |
+
* **Generation length**: 32 tokens for RSVQA-HR; 64 for VRSBench VQA/grounding and
|
| 449 |
+
ECG-QA; 256 for captions and transcription; 512 for BigEarthNet and Speech2LaTeX
|
| 450 |
+
sentences.
|
| 451 |
+
* **Task instructions**: The benchmark prompts are used as given. Some tasks append
|
| 452 |
+
an output-format instruction:
|
| 453 |
+
|
| 454 |
+
| Task | Appended instruction |
|
| 455 |
+
|---|---|
|
| 456 |
+
| ECG-QA | `Return your answer in JSON with the format {'answer': '<answer>', 'reason': '<reason>'}` |
|
| 457 |
+
| VRSBench grounding | `Return your answer in JSON with the format {bbox_format}` (percent coordinates) |
|
| 458 |
+
| RSVQA-HR | Per question type, a short-answer instruction (yes/no, number, or area bucket) |
|
| 459 |
+
|
| 460 |
+
* **Answer parsing**: Binary and MCQA answers match by prefix (`yes`/`no`, `a`–`d`).
|
| 461 |
+
Boxes are parsed in unit (BigEarthNet) or percent (VRSBench) coordinates. LLM-judge
|
| 462 |
+
metrics score free-text answers as correct or incorrect against the reference.
|
| 463 |
+
* **Majority baselines**: Always predicting the most frequent answer scores 35.18
|
| 464 |
+
(PTB-XL) and 47.18 (MIMIC) on ECG-Instruct MCQA, 93.75 / 92.14 on M&Ms-2 LV / RV
|
| 465 |
+
presence, and 48.60 on OmniBench.
|
| 466 |
+
* **Held-out caveat**: Speech2LaTeX has no validation split. Its test splits were used
|
| 467 |
+
to monitor loss during training, so those scores are not fully held out.
|
| 468 |
+
|
| 469 |
+
### Notes on the results
|
| 470 |
+
|
| 471 |
+
- **Grounding**: note on bboxes.
|
| 472 |
+
- **VRSBench captioning**: METEOR is 13.9, against 23.9 for the base model. Captions
|
| 473 |
+
follow the short style of the training data.
|
| 474 |
+
- **ECG-QA question types**: set accuracy is 3–29 on query-type questions and 74–85 on
|
| 475 |
+
yes/no verify questions.
|
| 476 |
+
- **Speech2LaTeX**: CER is 40.4 on equations and 17.8 on sentences. Validation loss on
|
| 477 |
+
equations is 0.593.
|
| 478 |
+
|
| 479 |
+
## Limitations
|
| 480 |
+
|
| 481 |
+
- **Early stop.** Training ended at step 34,000 of a 60,000-step cosine schedule, with
|
| 482 |
+
the learning rate at 4.7e-5. TODO
|
| 483 |
+
- **Data coverage.** The ECGs come from PTB-XL (Germany) and MIMIC-IV-ECG (one US
|
| 484 |
+
hospital system), and the Sentinel data is mostly European (BigEarthNet).
|
| 485 |
+
- **Task coverage.** See the notes on the results above for tasks with low scores,
|
| 486 |
+
including bounding-box grounding on RGB images and open-ended ECG questions.
|
| 487 |
+
- **Cross-domain prompts.** The model accepts inputs that go through different
|
| 488 |
+
encoders in one prompt, such as an ECG (`<medgemma>`) and a Sentinel-1/Sentinel-2
|
| 489 |
+
patch (`<terramind>`). Training examples use a single domain, so an answer that has
|
| 490 |
+
to reason over both is not reliable. Several payloads for one encoder, as in the
|
| 491 |
+
two-ECG comparison prompts, and Auto-AVSR audio together with lip video for the
|
| 492 |
+
same utterance, are the combinations the training mixture covers.
|
| 493 |
+
- **Not for clinical or operational use.** Cardiology outputs are not clinically
|
| 494 |
+
validated and must not be used for diagnosis, triage, or treatment. Earth
|
| 495 |
+
observation outputs should not drive safety-critical decisions without independent
|
| 496 |
+
verification.
|
| 497 |
+
|
| 498 |
+
## Training
|
| 499 |
+
|
| 500 |
+
<details>
|
| 501 |
+
<summary>Data mixture (18 datasets, interleaved sampling)</summary>
|
| 502 |
+
|
| 503 |
+
| Domain | Dataset | Input path | Prob. |
|
| 504 |
+
|---|---|---|---|
|
| 505 |
+
| Geo-intelligence | BigEarthNet S1+S2 | `<terramind>` | 0.145 |
|
| 506 |
+
| | GeoChat | RGB image | 0.06 |
|
| 507 |
+
| | RSVQA-HR | RGB image | 0.065 |
|
| 508 |
+
| | RSTeller | RGB image | 0.06 |
|
| 509 |
+
| Language communication | Aya | text | 0.07 |
|
| 510 |
+
| | LipCrops video | `<autoavsr_video>` | 0.073 |
|
| 511 |
+
| | LipCrops audio + video | `<autoavsr_audio>` + `<autoavsr_video>` | 0.037 |
|
| 512 |
+
| | Audio-FLAN SLU | audio | 0.075 |
|
| 513 |
+
| | Speech2LaTeX sentences | audio | 0.03 |
|
| 514 |
+
| | Speech2LaTeX equations | audio | 0.02 |
|
| 515 |
+
| Cardiology | ECG-QA PTB-XL (paraphrased) | `<medgemma>` | 0.055 |
|
| 516 |
+
| | ECG-QA MIMIC-IV-ECG (paraphrased) | `<medgemma>` | 0.06 |
|
| 517 |
+
| | ECG-Instruct PTB-XL | `<medgemma>` | 0.045 |
|
| 518 |
+
| | ECG-Instruct MIMIC | `<medgemma>` | 0.055 |
|
| 519 |
+
| | ACDC | `<medgemma>` | 0.03 |
|
| 520 |
+
| | M&Ms-2 | `<medgemma>` | 0.02 |
|
| 521 |
+
| | EMIDEC | `<medgemma>` | 0.03 |
|
| 522 |
+
| General | LNQA | RGB image | 0.07 |
|
| 523 |
+
|
| 524 |
+
</details>
|
| 525 |
+
|
| 526 |
+
<details>
|
| 527 |
+
<summary>Hyperparameters and compute</summary>
|
| 528 |
+
|
| 529 |
+
| Setting | Value |
|
| 530 |
+
|---|---|
|
| 531 |
+
| Framework | custom version of LLaMA-Factory SFT |
|
| 532 |
+
| Schedule | cosine schedule |
|
| 533 |
+
| Method | LoRA (r=16, α=32, dropout 0) on all Thinker linear layers, plus full training of the 4 projectors; 107.8M trainable parameters. LoRA weights are merged into the released checkpoint. |
|
| 534 |
+
| Precision | BF16 mixed; trainable parameters in FP32 |
|
| 535 |
+
| Batch | 4 per GPU × 16 GPUs × 4 gradient accumulation = 256 |
|
| 536 |
+
| Learning rate | 1e-4 peak, cosine to 60,000 steps, 1% warmup; 9.87e-5 at this checkpoint |
|
| 537 |
+
| Sequence length | 4,096 tokens, no packing, streaming |
|
| 538 |
+
| Image / video limits | 262,144 / 16,384 pixels |
|
| 539 |
+
| Samples seen | ~1.28M (5,000 steps × batch 256) |
|
| 540 |
+
| Model selection | Lowest probability-weighted validation loss, evaluated every 500 steps on up to 1,024 samples per dataset |
|
| 541 |
+
| Hardware | 4 nodes, 16xNVIDIA A100 64 GB (Leonardo Booster, CINECA) |
|
| 542 |
+
| Wall-clock | ~55 h on 16× A100 (~890 GPU-hours), estimated from the measured ~90 steps/h |
|
| 543 |
+
| Tracking | W&B [DVPS-ai/dvps-fm/5xifbe5h](https://wandb.ai/DVPS-ai/dvps-fm/runs/5xifbe5h) |
|
| 544 |
+
|
| 545 |
+
</details>
|
| 546 |
+
|
| 547 |
+
## License
|
| 548 |
+
|
| 549 |
+
[CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/). You may share
|
| 550 |
+
and adapt the model for non-commercial use with attribution, and derivatives must
|
| 551 |
+
stay under the same license.
|
| 552 |
+
|
| 553 |
+
The weights also depend on components and training data with their own terms:
|
| 554 |
+
Qwen2.5-Omni-7B (Apache-2.0), TerraMind v1 (Apache-2.0), MedGemma (Health AI
|
| 555 |
+
Developer Foundations terms), the Auto-AVSR checkpoints and code (Apache-2.0), and the
|
| 556 |
+
datasets listed above. MIMIC-IV-ECG is under a PhysioNet credentialed data use
|
| 557 |
+
agreement.
|
| 558 |
+
|
| 559 |
+
## Citation
|
| 560 |
+
|
| 561 |
+
```BibTeX
|
| 562 |
+
@misc{dvpsfm2026,
|
| 563 |
+
title = {DVPS-FM-v1},
|
| 564 |
+
author = {{DVPS Consortium}},
|
| 565 |
+
year = {2026},
|
| 566 |
+
howpublished = {\url{https://huggingface.co/dvps-ai/dvps-fm-v1}},
|
| 567 |
+
note = {Hugging Face model repository, version v1}
|
| 568 |
+
}
|
| 569 |
+
```
|
| 570 |
+
|
| 571 |
+
### Framework versions
|
| 572 |
+
|
| 573 |
+
- Transformers 5.2.0
|
| 574 |
+
- PyTorch 2.10.0
|
| 575 |
+
- PEFT 0.18.1
|
modeling_omni.py
ADDED
|
@@ -0,0 +1,662 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Generic Qwen2.5-Omni shell for plugin-style extra encoders."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
from torch.utils.checkpoint import checkpoint
|
| 11 |
+
from transformers import (
|
| 12 |
+
AutoTokenizer,
|
| 13 |
+
GenerationMixin,
|
| 14 |
+
PreTrainedModel,
|
| 15 |
+
Qwen2_5OmniConfig,
|
| 16 |
+
Qwen2_5OmniForConditionalGeneration,
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
try:
|
| 20 |
+
# Hugging Face copies only one hop of relative imports from this file.
|
| 21 |
+
from .configuration_omni import QwenOmniCompositeConfig
|
| 22 |
+
from .encoders_base import EncoderProjector, build_encoder
|
| 23 |
+
from .encoders_terramind import TerraMindEncoder as _TerraMindEncoder
|
| 24 |
+
from .encoders_medgemma import MedGemmaEncoder as _MedGemmaEncoder
|
| 25 |
+
from .encoders_autoavsr import AutoAVSREncoder as _AutoAVSREncoder
|
| 26 |
+
except ImportError:
|
| 27 |
+
# Hugging Face remote-code loading can import this as a flat module.
|
| 28 |
+
from configuration_omni import QwenOmniCompositeConfig
|
| 29 |
+
from encoders_base import EncoderProjector, build_encoder
|
| 30 |
+
from encoders_terramind import TerraMindEncoder as _TerraMindEncoder
|
| 31 |
+
from encoders_medgemma import MedGemmaEncoder as _MedGemmaEncoder
|
| 32 |
+
from encoders_autoavsr import AutoAVSREncoder as _AutoAVSREncoder
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
_LOSS_CHUNK_TOKENS = 4096
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _cross_entropy_sum(logits: torch.Tensor, labels: torch.Tensor, ignore_index: int) -> torch.Tensor:
|
| 39 |
+
return nn.functional.cross_entropy(
|
| 40 |
+
logits.float(),
|
| 41 |
+
labels,
|
| 42 |
+
ignore_index=ignore_index,
|
| 43 |
+
reduction="sum",
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def chunked_causal_lm_loss(
|
| 48 |
+
logits: torch.Tensor,
|
| 49 |
+
labels: torch.Tensor,
|
| 50 |
+
vocab_size: int,
|
| 51 |
+
num_items_in_batch: torch.Tensor | None = None,
|
| 52 |
+
ignore_index: int = -100,
|
| 53 |
+
shift_labels: torch.Tensor | None = None,
|
| 54 |
+
**kwargs,
|
| 55 |
+
) -> torch.Tensor:
|
| 56 |
+
"""Same value as transformers' ``ForCausalLMLoss``, computed in token chunks.
|
| 57 |
+
|
| 58 |
+
The stock loss upcasts the whole ``(tokens, vocab)`` logits to float32, which
|
| 59 |
+
for a full 8 x 4096 batch is ~18 GiB on top of the bf16 logits, and keeps
|
| 60 |
+
float32 copies for backward. Each chunk is upcast inside a checkpoint, so
|
| 61 |
+
backward recomputes it one chunk at a time instead.
|
| 62 |
+
"""
|
| 63 |
+
if shift_labels is None:
|
| 64 |
+
labels = nn.functional.pad(labels, (0, 1), value=ignore_index)
|
| 65 |
+
shift_labels = labels[..., 1:]
|
| 66 |
+
|
| 67 |
+
logits = logits.reshape(-1, vocab_size)
|
| 68 |
+
shift_labels = shift_labels.reshape(-1).to(logits.device)
|
| 69 |
+
total = logits.new_zeros((), dtype=torch.float32)
|
| 70 |
+
for start in range(0, logits.shape[0], _LOSS_CHUNK_TOKENS):
|
| 71 |
+
end = start + _LOSS_CHUNK_TOKENS
|
| 72 |
+
total = total + checkpoint(
|
| 73 |
+
_cross_entropy_sum,
|
| 74 |
+
logits[start:end],
|
| 75 |
+
shift_labels[start:end],
|
| 76 |
+
ignore_index,
|
| 77 |
+
use_reentrant=False,
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
if num_items_in_batch is None:
|
| 81 |
+
return total / shift_labels.ne(ignore_index).sum()
|
| 82 |
+
if torch.is_tensor(num_items_in_batch):
|
| 83 |
+
num_items_in_batch = num_items_in_batch.to(total.device)
|
| 84 |
+
return total / num_items_in_batch
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def scatter_encoder_tokens(
|
| 88 |
+
inputs_embeds: torch.Tensor,
|
| 89 |
+
input_ids: torch.Tensor,
|
| 90 |
+
*,
|
| 91 |
+
token_id: int,
|
| 92 |
+
encoder_tokens: torch.Tensor,
|
| 93 |
+
batch_indices: torch.Tensor | list[int],
|
| 94 |
+
encoder_name: str,
|
| 95 |
+
) -> torch.Tensor:
|
| 96 |
+
"""Validate row routing and scatter `(P, N, D)` encoder tokens.
|
| 97 |
+
|
| 98 |
+
``P`` counts payloads, not rows: a row with two payloads (for example a
|
| 99 |
+
two-ECG comparison question) appears twice in ``batch_indices``, in the
|
| 100 |
+
same order as its prompt markers.
|
| 101 |
+
"""
|
| 102 |
+
if input_ids.ndim != 2 or inputs_embeds.ndim != 3:
|
| 103 |
+
raise ValueError("input_ids and inputs_embeds must be rank 2 and 3.")
|
| 104 |
+
if input_ids.shape != inputs_embeds.shape[:2]:
|
| 105 |
+
raise ValueError("input_ids and inputs_embeds sequence shapes differ.")
|
| 106 |
+
if encoder_tokens.ndim != 3:
|
| 107 |
+
raise ValueError(
|
| 108 |
+
f"Encoder {encoder_name!r} returned shape "
|
| 109 |
+
f"{tuple(encoder_tokens.shape)}, expected (B_sub, N, D)."
|
| 110 |
+
)
|
| 111 |
+
if encoder_tokens.shape[-1] != inputs_embeds.shape[-1]:
|
| 112 |
+
raise ValueError(
|
| 113 |
+
f"Encoder {encoder_name!r} projected width "
|
| 114 |
+
f"{encoder_tokens.shape[-1]} != Qwen width "
|
| 115 |
+
f"{inputs_embeds.shape[-1]}."
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
indices = torch.as_tensor(
|
| 119 |
+
batch_indices,
|
| 120 |
+
dtype=torch.long,
|
| 121 |
+
device=input_ids.device,
|
| 122 |
+
).flatten()
|
| 123 |
+
if indices.numel() != encoder_tokens.shape[0]:
|
| 124 |
+
raise ValueError(
|
| 125 |
+
f"Encoder {encoder_name!r} has {encoder_tokens.shape[0]} feature "
|
| 126 |
+
f"rows but {indices.numel()} batch indices."
|
| 127 |
+
)
|
| 128 |
+
if indices.numel() == 0:
|
| 129 |
+
raise ValueError(
|
| 130 |
+
f"Encoder {encoder_name!r} received an empty sub-batch."
|
| 131 |
+
)
|
| 132 |
+
if indices.min().item() < 0 or indices.max().item() >= input_ids.shape[0]:
|
| 133 |
+
raise IndexError(
|
| 134 |
+
f"Encoder {encoder_name!r} batch indices {indices.tolist()} are "
|
| 135 |
+
f"outside batch size {input_ids.shape[0]}."
|
| 136 |
+
)
|
| 137 |
+
# Rows may repeat, once per payload. A stable sort groups payloads by row
|
| 138 |
+
# while keeping each row's payloads in marker order.
|
| 139 |
+
order = torch.argsort(indices, stable=True)
|
| 140 |
+
indices = indices[order]
|
| 141 |
+
encoder_tokens = encoder_tokens.index_select(
|
| 142 |
+
0,
|
| 143 |
+
order.to(encoder_tokens.device),
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
mask = input_ids.eq(token_id)
|
| 147 |
+
rows_with_tokens = torch.where(mask.any(dim=1))[0]
|
| 148 |
+
payload_rows = torch.unique_consecutive(indices)
|
| 149 |
+
if not torch.equal(rows_with_tokens, payload_rows):
|
| 150 |
+
raise ValueError(
|
| 151 |
+
f"Encoder {encoder_name!r} payload rows {payload_rows.tolist()} "
|
| 152 |
+
f"do not match placeholder rows {rows_with_tokens.tolist()}."
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
tokens_per_payload = encoder_tokens.shape[1]
|
| 156 |
+
payloads_per_row = torch.bincount(indices, minlength=input_ids.shape[0])
|
| 157 |
+
expected_per_row = payloads_per_row * tokens_per_payload
|
| 158 |
+
actual_per_row = mask.sum(dim=1)
|
| 159 |
+
if not torch.equal(actual_per_row, expected_per_row):
|
| 160 |
+
counts = {
|
| 161 |
+
int(row): (int(actual_per_row[row]), int(expected_per_row[row]))
|
| 162 |
+
for row in rows_with_tokens.tolist()
|
| 163 |
+
}
|
| 164 |
+
raise ValueError(
|
| 165 |
+
f"Encoder {encoder_name!r} expects {tokens_per_payload} "
|
| 166 |
+
f"placeholder tokens per payload; per-row (actual, expected) "
|
| 167 |
+
f"placeholder counts are {counts}."
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
expanded_mask = mask.unsqueeze(-1).expand_as(inputs_embeds)
|
| 171 |
+
flat_tokens = encoder_tokens.reshape(-1, encoder_tokens.shape[-1]).to(
|
| 172 |
+
device=inputs_embeds.device,
|
| 173 |
+
dtype=inputs_embeds.dtype,
|
| 174 |
+
)
|
| 175 |
+
return inputs_embeds.masked_scatter(expanded_mask, flat_tokens)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def _reinit_derived_buffers(model: nn.Module) -> None:
|
| 179 |
+
"""Recompute non-persistent rotary and sinusoid buffers after loading.
|
| 180 |
+
|
| 181 |
+
They are derived from the config and absent from the checkpoint, and the
|
| 182 |
+
non-meta init above can leave them as uninitialized memory.
|
| 183 |
+
"""
|
| 184 |
+
try:
|
| 185 |
+
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
|
| 186 |
+
except ImportError:
|
| 187 |
+
ROPE_INIT_FUNCTIONS = {}
|
| 188 |
+
|
| 189 |
+
for module in model.modules():
|
| 190 |
+
sinusoids = getattr(module, "positional_embedding", None)
|
| 191 |
+
if isinstance(sinusoids, torch.Tensor) and hasattr(module, "max_timescale"):
|
| 192 |
+
log_increment = math.log(module.max_timescale) / (module.channels // 2 - 1)
|
| 193 |
+
inv_timescales = torch.exp(-log_increment * torch.arange(module.channels // 2).float())
|
| 194 |
+
scaled_time = torch.arange(module.length)[:, None] * inv_timescales[None, :]
|
| 195 |
+
table = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], dim=1)
|
| 196 |
+
module.register_buffer(
|
| 197 |
+
"positional_embedding",
|
| 198 |
+
table.to(device=sinusoids.device, dtype=sinusoids.dtype),
|
| 199 |
+
persistent=False,
|
| 200 |
+
)
|
| 201 |
+
continue
|
| 202 |
+
inv_freq = getattr(module, "inv_freq", None)
|
| 203 |
+
if not isinstance(inv_freq, torch.Tensor):
|
| 204 |
+
continue
|
| 205 |
+
device = inv_freq.device
|
| 206 |
+
new_inv = scaling = None
|
| 207 |
+
config = getattr(module, "config", None)
|
| 208 |
+
rope_type = getattr(module, "rope_type", None)
|
| 209 |
+
if config is not None and rope_type is not None:
|
| 210 |
+
init_fn = None
|
| 211 |
+
if rope_type == "default" and hasattr(module, "compute_default_rope_parameters"):
|
| 212 |
+
init_fn = module.compute_default_rope_parameters
|
| 213 |
+
elif rope_type in ROPE_INIT_FUNCTIONS:
|
| 214 |
+
init_fn = ROPE_INIT_FUNCTIONS[rope_type]
|
| 215 |
+
if init_fn is not None:
|
| 216 |
+
# Transformers 5.24 dropped the positional `device` argument.
|
| 217 |
+
try:
|
| 218 |
+
new_inv, scaling = init_fn(config, device)
|
| 219 |
+
except TypeError:
|
| 220 |
+
new_inv, scaling = init_fn(config)
|
| 221 |
+
elif hasattr(module, "theta") and hasattr(module, "dim"):
|
| 222 |
+
dim = module.dim
|
| 223 |
+
new_inv = 1.0 / (
|
| 224 |
+
module.theta ** (torch.arange(0, dim, 2, dtype=torch.float, device=device) / dim)
|
| 225 |
+
)
|
| 226 |
+
if new_inv is None:
|
| 227 |
+
continue
|
| 228 |
+
new_inv = new_inv.to(device=device, dtype=inv_freq.dtype)
|
| 229 |
+
module.register_buffer("inv_freq", new_inv, persistent=False)
|
| 230 |
+
if getattr(module, "original_inv_freq", None) is not None:
|
| 231 |
+
module.register_buffer("original_inv_freq", new_inv.clone(), persistent=False)
|
| 232 |
+
if scaling is not None:
|
| 233 |
+
module.attention_scaling = scaling
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
class QwenOmniCompositeForConditionalGeneration(
|
| 237 |
+
PreTrainedModel,
|
| 238 |
+
GenerationMixin,
|
| 239 |
+
):
|
| 240 |
+
"""Qwen Thinker with a configurable collection of extra encoders."""
|
| 241 |
+
|
| 242 |
+
config_class = QwenOmniCompositeConfig
|
| 243 |
+
main_input_name = "input_ids"
|
| 244 |
+
supports_gradient_checkpointing = True
|
| 245 |
+
|
| 246 |
+
def __init__(self, config: QwenOmniCompositeConfig) -> None:
|
| 247 |
+
super().__init__(config)
|
| 248 |
+
self.qwen = self._build_qwen(config)
|
| 249 |
+
self._validate_thinker_only()
|
| 250 |
+
|
| 251 |
+
thinker = self.qwen.thinker
|
| 252 |
+
thinker.loss_function = chunked_causal_lm_loss
|
| 253 |
+
qwen_hidden_dim = thinker.config.text_config.hidden_size
|
| 254 |
+
|
| 255 |
+
self.encoders = nn.ModuleDict()
|
| 256 |
+
self.projectors = nn.ModuleDict()
|
| 257 |
+
self.expected_num_tokens: dict[str, int] = {}
|
| 258 |
+
|
| 259 |
+
for spec in config.encoders:
|
| 260 |
+
name = spec["name"]
|
| 261 |
+
encoder = build_encoder(
|
| 262 |
+
spec,
|
| 263 |
+
pretrained=config.load_encoders_from_pretrained,
|
| 264 |
+
model_dir=config.name_or_path or None,
|
| 265 |
+
revision=getattr(config, "_commit_hash", None),
|
| 266 |
+
)
|
| 267 |
+
encoder.freeze_backbone()
|
| 268 |
+
self.encoders[name] = encoder
|
| 269 |
+
self.projectors[name] = EncoderProjector(
|
| 270 |
+
encoder_dim=encoder.feature_dim,
|
| 271 |
+
qwen_dim=qwen_hidden_dim,
|
| 272 |
+
hidden_mult=spec["hidden_mult"],
|
| 273 |
+
)
|
| 274 |
+
self.expected_num_tokens[name] = encoder.expected_num_tokens
|
| 275 |
+
spec["hidden_dim"] = encoder.feature_dim
|
| 276 |
+
spec["num_tokens"] = encoder.expected_num_tokens
|
| 277 |
+
|
| 278 |
+
self._register_tied_encoder_weights()
|
| 279 |
+
self._configure_placeholders(config)
|
| 280 |
+
self._mirror_text_config()
|
| 281 |
+
self.generation_config = thinker.generation_config
|
| 282 |
+
|
| 283 |
+
self.post_init()
|
| 284 |
+
for encoder in self.encoders.values():
|
| 285 |
+
fusion_gate = getattr(encoder, "fusion_gate", None)
|
| 286 |
+
if fusion_gate is not None:
|
| 287 |
+
fusion_gate.reset_gate_parameters()
|
| 288 |
+
self._apply_freeze_contract()
|
| 289 |
+
|
| 290 |
+
@classmethod
|
| 291 |
+
def get_init_context(cls, *args, **kwargs):
|
| 292 |
+
# The TerraMind backbone calls Tensor.item() in its constructor, which
|
| 293 |
+
# the meta device used by Transformers >= 5 forbids.
|
| 294 |
+
contexts = super().get_init_context(*args, **kwargs)
|
| 295 |
+
return [
|
| 296 |
+
ctx for ctx in contexts
|
| 297 |
+
if not (isinstance(ctx, torch.device) and ctx.type == "meta")
|
| 298 |
+
]
|
| 299 |
+
|
| 300 |
+
@classmethod
|
| 301 |
+
def from_pretrained(cls, *args, **kwargs):
|
| 302 |
+
model = super().from_pretrained(*args, **kwargs)
|
| 303 |
+
_reinit_derived_buffers(model)
|
| 304 |
+
model._apply_freeze_contract()
|
| 305 |
+
return model
|
| 306 |
+
|
| 307 |
+
def _apply_freeze_contract(self) -> None:
|
| 308 |
+
"""Keep Qwen and encoder backbones frozen after init and reload.
|
| 309 |
+
|
| 310 |
+
Hugging Face may rematerialize parameters during ``from_pretrained``,
|
| 311 |
+
which resets ``requires_grad`` to True. Re-apply the contract after
|
| 312 |
+
load so the projector (and optional fusion gate) stay trainable.
|
| 313 |
+
"""
|
| 314 |
+
for parameter in self.qwen.parameters():
|
| 315 |
+
parameter.requires_grad = False
|
| 316 |
+
for encoder in self.encoders.values():
|
| 317 |
+
encoder.freeze_backbone()
|
| 318 |
+
|
| 319 |
+
def _build_qwen(
|
| 320 |
+
self,
|
| 321 |
+
config: QwenOmniCompositeConfig,
|
| 322 |
+
) -> Qwen2_5OmniForConditionalGeneration:
|
| 323 |
+
if config.load_qwen_from_pretrained:
|
| 324 |
+
return Qwen2_5OmniForConditionalGeneration.from_pretrained(
|
| 325 |
+
config.qwen_model_name_or_path,
|
| 326 |
+
torch_dtype=torch.bfloat16,
|
| 327 |
+
enable_audio_output=False,
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
if config.qwen_model_config is None:
|
| 331 |
+
raise ValueError(
|
| 332 |
+
"qwen_model_config is required when reloading a composite "
|
| 333 |
+
"checkpoint."
|
| 334 |
+
)
|
| 335 |
+
qwen_config = config.qwen_model_config
|
| 336 |
+
if isinstance(qwen_config, dict):
|
| 337 |
+
qwen_config = Qwen2_5OmniConfig.from_dict(qwen_config)
|
| 338 |
+
qwen_config.enable_audio_output = False
|
| 339 |
+
return Qwen2_5OmniForConditionalGeneration(qwen_config)
|
| 340 |
+
|
| 341 |
+
def _validate_thinker_only(self) -> None:
|
| 342 |
+
if getattr(self.qwen, "talker", None) is not None:
|
| 343 |
+
raise RuntimeError("Qwen Talker must not be instantiated.")
|
| 344 |
+
if getattr(self.qwen, "token2wav", None) is not None:
|
| 345 |
+
raise RuntimeError("Qwen Token2Wav must not be instantiated.")
|
| 346 |
+
|
| 347 |
+
def _configure_placeholders(
|
| 348 |
+
self,
|
| 349 |
+
config: QwenOmniCompositeConfig,
|
| 350 |
+
) -> None:
|
| 351 |
+
if config.load_qwen_from_pretrained:
|
| 352 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 353 |
+
config.qwen_model_name_or_path
|
| 354 |
+
)
|
| 355 |
+
tokens = [
|
| 356 |
+
spec["placeholder_token"] for spec in config.encoders
|
| 357 |
+
]
|
| 358 |
+
tokenizer.add_special_tokens(
|
| 359 |
+
{"additional_special_tokens": tokens}
|
| 360 |
+
)
|
| 361 |
+
self.qwen.thinker.resize_token_embeddings(len(tokenizer))
|
| 362 |
+
config.placeholder_token_ids = {
|
| 363 |
+
spec["name"]: tokenizer.convert_tokens_to_ids(
|
| 364 |
+
spec["placeholder_token"]
|
| 365 |
+
)
|
| 366 |
+
for spec in config.encoders
|
| 367 |
+
}
|
| 368 |
+
self.tokenizer = tokenizer
|
| 369 |
+
else:
|
| 370 |
+
missing = [
|
| 371 |
+
spec["name"]
|
| 372 |
+
for spec in config.encoders
|
| 373 |
+
if spec["name"] not in config.placeholder_token_ids
|
| 374 |
+
]
|
| 375 |
+
if missing:
|
| 376 |
+
raise ValueError(
|
| 377 |
+
"Saved config is missing placeholder ids for "
|
| 378 |
+
f"encoders {missing}."
|
| 379 |
+
)
|
| 380 |
+
self.tokenizer = None
|
| 381 |
+
|
| 382 |
+
self.placeholder_token_ids = {
|
| 383 |
+
name: int(token_id)
|
| 384 |
+
for name, token_id in config.placeholder_token_ids.items()
|
| 385 |
+
}
|
| 386 |
+
|
| 387 |
+
def _mirror_text_config(self) -> None:
|
| 388 |
+
text_config = self.qwen.thinker.config.text_config
|
| 389 |
+
for attribute in (
|
| 390 |
+
"num_hidden_layers",
|
| 391 |
+
"num_attention_heads",
|
| 392 |
+
"num_key_value_heads",
|
| 393 |
+
"hidden_size",
|
| 394 |
+
"head_dim",
|
| 395 |
+
"vocab_size",
|
| 396 |
+
):
|
| 397 |
+
if hasattr(text_config, attribute):
|
| 398 |
+
setattr(
|
| 399 |
+
self.config,
|
| 400 |
+
attribute,
|
| 401 |
+
getattr(text_config, attribute),
|
| 402 |
+
)
|
| 403 |
+
|
| 404 |
+
def _register_tied_encoder_weights(self) -> None:
|
| 405 |
+
existing = getattr(self, "_tied_weights_keys", {})
|
| 406 |
+
if not isinstance(existing, dict):
|
| 407 |
+
existing = {}
|
| 408 |
+
self._tied_weights_keys = dict(existing)
|
| 409 |
+
|
| 410 |
+
state = self.encoders.state_dict()
|
| 411 |
+
for key in state:
|
| 412 |
+
if not key.endswith(".to_logits.weight"):
|
| 413 |
+
continue
|
| 414 |
+
token_key = key.replace(
|
| 415 |
+
".to_logits.weight",
|
| 416 |
+
".token_emb.weight",
|
| 417 |
+
)
|
| 418 |
+
if (
|
| 419 |
+
token_key in state
|
| 420 |
+
and state[key].data_ptr() == state[token_key].data_ptr()
|
| 421 |
+
):
|
| 422 |
+
self._tied_weights_keys[f"encoders.{key}"] = (
|
| 423 |
+
f"encoders.{token_key}"
|
| 424 |
+
)
|
| 425 |
+
|
| 426 |
+
@staticmethod
|
| 427 |
+
def _is_prefill(past_key_values: Any) -> bool:
|
| 428 |
+
if past_key_values is None:
|
| 429 |
+
return True
|
| 430 |
+
if hasattr(past_key_values, "get_seq_length"):
|
| 431 |
+
return past_key_values.get_seq_length() == 0
|
| 432 |
+
return False
|
| 433 |
+
|
| 434 |
+
def get_input_embeddings(self):
|
| 435 |
+
return self.qwen.thinker.get_input_embeddings()
|
| 436 |
+
|
| 437 |
+
def set_input_embeddings(self, value):
|
| 438 |
+
self.qwen.thinker.set_input_embeddings(value)
|
| 439 |
+
|
| 440 |
+
def get_output_embeddings(self):
|
| 441 |
+
return self.qwen.thinker.get_output_embeddings()
|
| 442 |
+
|
| 443 |
+
def _inject_extra_encoders(
|
| 444 |
+
self,
|
| 445 |
+
input_ids: torch.Tensor,
|
| 446 |
+
inputs_embeds: torch.Tensor,
|
| 447 |
+
encoder_inputs: dict[str, Any] | None,
|
| 448 |
+
) -> torch.Tensor:
|
| 449 |
+
encoder_inputs = encoder_inputs or {}
|
| 450 |
+
unknown = sorted(set(encoder_inputs) - set(self.encoders))
|
| 451 |
+
if unknown:
|
| 452 |
+
raise ValueError(f"Inputs provided for unknown encoders: {unknown}.")
|
| 453 |
+
|
| 454 |
+
for name, encoder in self.encoders.items():
|
| 455 |
+
token_id = self.placeholder_token_ids[name]
|
| 456 |
+
mask = input_ids.eq(token_id)
|
| 457 |
+
payload = encoder_inputs.get(name)
|
| 458 |
+
if payload is None:
|
| 459 |
+
if mask.any():
|
| 460 |
+
raise ValueError(
|
| 461 |
+
f"Encoder {name!r} placeholders exist without inputs."
|
| 462 |
+
)
|
| 463 |
+
continue
|
| 464 |
+
if not mask.any():
|
| 465 |
+
raise ValueError(
|
| 466 |
+
f"Encoder {name!r} inputs exist without placeholders."
|
| 467 |
+
)
|
| 468 |
+
|
| 469 |
+
if isinstance(payload, dict) and "inputs" in payload:
|
| 470 |
+
raw_inputs = payload["inputs"]
|
| 471 |
+
batch_indices = payload.get("batch_indices")
|
| 472 |
+
else:
|
| 473 |
+
raw_inputs = payload
|
| 474 |
+
batch_indices = None
|
| 475 |
+
|
| 476 |
+
if batch_indices is None:
|
| 477 |
+
batch_indices = torch.where(mask.any(dim=1))[0]
|
| 478 |
+
|
| 479 |
+
hidden_states = encoder.encode(raw_inputs)
|
| 480 |
+
if (
|
| 481 |
+
hidden_states.shape[1]
|
| 482 |
+
!= self.expected_num_tokens[name]
|
| 483 |
+
):
|
| 484 |
+
raise ValueError(
|
| 485 |
+
f"Encoder {name!r} returned {hidden_states.shape[1]} "
|
| 486 |
+
f"tokens; configured expectation is "
|
| 487 |
+
f"{self.expected_num_tokens[name]}."
|
| 488 |
+
)
|
| 489 |
+
|
| 490 |
+
projector_parameter = next(self.projectors[name].parameters())
|
| 491 |
+
hidden_states = hidden_states.to(
|
| 492 |
+
device=projector_parameter.device,
|
| 493 |
+
dtype=projector_parameter.dtype,
|
| 494 |
+
)
|
| 495 |
+
projected = self.projectors[name](hidden_states)
|
| 496 |
+
inputs_embeds = scatter_encoder_tokens(
|
| 497 |
+
inputs_embeds,
|
| 498 |
+
input_ids,
|
| 499 |
+
token_id=token_id,
|
| 500 |
+
encoder_tokens=projected,
|
| 501 |
+
batch_indices=batch_indices,
|
| 502 |
+
encoder_name=name,
|
| 503 |
+
)
|
| 504 |
+
|
| 505 |
+
return inputs_embeds
|
| 506 |
+
|
| 507 |
+
def forward(
|
| 508 |
+
self,
|
| 509 |
+
input_ids=None,
|
| 510 |
+
attention_mask=None,
|
| 511 |
+
inputs_embeds=None,
|
| 512 |
+
encoder_inputs=None,
|
| 513 |
+
labels=None,
|
| 514 |
+
past_key_values=None,
|
| 515 |
+
pixel_values=None,
|
| 516 |
+
image_grid_thw=None,
|
| 517 |
+
pixel_values_videos=None,
|
| 518 |
+
video_grid_thw=None,
|
| 519 |
+
video_second_per_grid=None,
|
| 520 |
+
input_features=None,
|
| 521 |
+
feature_attention_mask=None,
|
| 522 |
+
**kwargs,
|
| 523 |
+
):
|
| 524 |
+
# generate() rejects inputs that forward does not name, so the processor's
|
| 525 |
+
# video_second_per_grid has to be an explicit parameter to reach the Thinker.
|
| 526 |
+
thinker = self.qwen.thinker
|
| 527 |
+
if inputs_embeds is None:
|
| 528 |
+
if input_ids is None:
|
| 529 |
+
raise ValueError(
|
| 530 |
+
"Either input_ids or inputs_embeds must be provided."
|
| 531 |
+
)
|
| 532 |
+
inputs_embeds = thinker.get_input_embeddings()(input_ids)
|
| 533 |
+
|
| 534 |
+
if (
|
| 535 |
+
encoder_inputs is not None
|
| 536 |
+
and self._is_prefill(past_key_values)
|
| 537 |
+
):
|
| 538 |
+
if input_ids is None:
|
| 539 |
+
raise ValueError(
|
| 540 |
+
"Extra encoders require input_ids during prefill."
|
| 541 |
+
)
|
| 542 |
+
inputs_embeds = self._inject_extra_encoders(
|
| 543 |
+
input_ids,
|
| 544 |
+
inputs_embeds,
|
| 545 |
+
encoder_inputs,
|
| 546 |
+
)
|
| 547 |
+
|
| 548 |
+
# Native image/video/audio processing remains entirely owned by the
|
| 549 |
+
# Qwen Thinker. The composite only injects extra encoder spans.
|
| 550 |
+
outputs = thinker(
|
| 551 |
+
input_ids=input_ids,
|
| 552 |
+
inputs_embeds=inputs_embeds,
|
| 553 |
+
attention_mask=attention_mask,
|
| 554 |
+
labels=labels,
|
| 555 |
+
past_key_values=past_key_values,
|
| 556 |
+
pixel_values=pixel_values,
|
| 557 |
+
image_grid_thw=image_grid_thw,
|
| 558 |
+
pixel_values_videos=pixel_values_videos,
|
| 559 |
+
video_grid_thw=video_grid_thw,
|
| 560 |
+
video_second_per_grid=video_second_per_grid,
|
| 561 |
+
input_features=input_features,
|
| 562 |
+
feature_attention_mask=feature_attention_mask,
|
| 563 |
+
**kwargs,
|
| 564 |
+
)
|
| 565 |
+
if self.training:
|
| 566 |
+
outputs = self._attach_projector_graph(outputs)
|
| 567 |
+
return outputs
|
| 568 |
+
|
| 569 |
+
def _attach_projector_graph(self, outputs):
|
| 570 |
+
"""Keep projector-only freeze backwards valid on native-only rows.
|
| 571 |
+
|
| 572 |
+
Thinker and encoder backbones are frozen. A mixed batch can be LNQA
|
| 573 |
+
or text-only, which never touches ``projectors.*``, so Thinker CE
|
| 574 |
+
``loss`` does not require grad. Add a zero-scale projector term to
|
| 575 |
+
``loss`` (what Trainer backprops), or to ``logits`` when no loss was
|
| 576 |
+
computed (labels consumed by a custom loss function). Unused
|
| 577 |
+
projectors in extra-encoder rows get the same treatment.
|
| 578 |
+
"""
|
| 579 |
+
terms = [
|
| 580 |
+
parameter.reshape(-1)[:1].sum() * 0
|
| 581 |
+
for projector in self.projectors.values()
|
| 582 |
+
for parameter in projector.parameters()
|
| 583 |
+
if parameter.requires_grad
|
| 584 |
+
]
|
| 585 |
+
if not terms:
|
| 586 |
+
return outputs
|
| 587 |
+
dummy = sum(terms)
|
| 588 |
+
|
| 589 |
+
def _add(tensor):
|
| 590 |
+
if tensor is None or not torch.is_tensor(tensor):
|
| 591 |
+
return tensor
|
| 592 |
+
return tensor + dummy.to(device=tensor.device, dtype=tensor.dtype)
|
| 593 |
+
|
| 594 |
+
# Trainer backprops outputs.loss (Thinker CE), not logits.
|
| 595 |
+
loss = getattr(outputs, "loss", None)
|
| 596 |
+
logits = getattr(outputs, "logits", None)
|
| 597 |
+
if loss is None and logits is None:
|
| 598 |
+
return outputs
|
| 599 |
+
if loss is not None:
|
| 600 |
+
# Full-vocab logits are as large as the rest of the step. Copying them
|
| 601 |
+
# here and again in DDP's output clone (find_unused_parameters) OOMs
|
| 602 |
+
# long batches, so a training output that already has a loss keeps
|
| 603 |
+
# only the loss.
|
| 604 |
+
return type(outputs)(loss=_add(loss))
|
| 605 |
+
outputs.logits = _add(logits)
|
| 606 |
+
return outputs
|
| 607 |
+
|
| 608 |
+
def prepare_inputs_for_generation(
|
| 609 |
+
self,
|
| 610 |
+
input_ids,
|
| 611 |
+
*args,
|
| 612 |
+
**kwargs,
|
| 613 |
+
):
|
| 614 |
+
encoder_inputs = kwargs.pop("encoder_inputs", None)
|
| 615 |
+
model_inputs = self.qwen.thinker.prepare_inputs_for_generation(
|
| 616 |
+
input_ids,
|
| 617 |
+
*args,
|
| 618 |
+
**kwargs,
|
| 619 |
+
)
|
| 620 |
+
past_key_values = model_inputs.get(
|
| 621 |
+
"past_key_values",
|
| 622 |
+
kwargs.get("past_key_values"),
|
| 623 |
+
)
|
| 624 |
+
is_prefill = self._is_prefill(past_key_values)
|
| 625 |
+
if is_prefill and model_inputs.get("input_ids") is None:
|
| 626 |
+
model_inputs["input_ids"] = input_ids
|
| 627 |
+
if is_prefill and encoder_inputs is not None:
|
| 628 |
+
model_inputs["encoder_inputs"] = encoder_inputs
|
| 629 |
+
return model_inputs
|
| 630 |
+
|
| 631 |
+
def can_generate(self) -> bool:
|
| 632 |
+
return True
|
| 633 |
+
|
| 634 |
+
def get_rope_index(self, *args, **kwargs):
|
| 635 |
+
return self.qwen.thinker.get_rope_index(*args, **kwargs)
|
| 636 |
+
|
| 637 |
+
def gradient_checkpointing_enable(
|
| 638 |
+
self,
|
| 639 |
+
gradient_checkpointing_kwargs=None,
|
| 640 |
+
):
|
| 641 |
+
if gradient_checkpointing_kwargs is None:
|
| 642 |
+
self.qwen.thinker.gradient_checkpointing_enable()
|
| 643 |
+
else:
|
| 644 |
+
self.qwen.thinker.gradient_checkpointing_enable(
|
| 645 |
+
gradient_checkpointing_kwargs=(
|
| 646 |
+
gradient_checkpointing_kwargs
|
| 647 |
+
)
|
| 648 |
+
)
|
| 649 |
+
|
| 650 |
+
def gradient_checkpointing_disable(self):
|
| 651 |
+
self.qwen.thinker.gradient_checkpointing_disable()
|
| 652 |
+
|
| 653 |
+
def enable_input_require_grads(self):
|
| 654 |
+
self.qwen.thinker.enable_input_require_grads()
|
| 655 |
+
|
| 656 |
+
def disable_input_require_grads(self):
|
| 657 |
+
self.qwen.thinker.disable_input_require_grads()
|
| 658 |
+
|
| 659 |
+
@property
|
| 660 |
+
def is_gradient_checkpointing(self):
|
| 661 |
+
return self.qwen.thinker.is_gradient_checkpointing
|
| 662 |
+
|