splatoonWooo shreyask commited on
Commit
4d7148d
·
0 Parent(s):

Duplicate from onnx-community/jina-embeddings-v5-omni-nano-ONNX

Browse files

Co-authored-by: Shreyas Karnik <shreyask@users.noreply.huggingface.co>

.gitattributes ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
37
+ onnx/text_model.onnx.data filter=lfs diff=lfs merge=lfs -text
38
+ onnx/text_model_fp16.onnx_data filter=lfs diff=lfs merge=lfs -text
39
+ onnx/text_model_q4f16.onnx_data filter=lfs diff=lfs merge=lfs -text
40
+ onnx/vision_model.onnx.data filter=lfs diff=lfs merge=lfs -text
41
+ onnx/vision_model_fp16.onnx_data filter=lfs diff=lfs merge=lfs -text
42
+ onnx/vision_model_q4f16.onnx_data filter=lfs diff=lfs merge=lfs -text
43
+ onnx/audio_model.onnx.data filter=lfs diff=lfs merge=lfs -text
44
+ onnx/audio_model_fp16.onnx_data filter=lfs diff=lfs merge=lfs -text
45
+ onnx/audio_model_q4f16.onnx_data filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-nc-4.0
3
+ base_model: jinaai/jina-embeddings-v5-omni-nano
4
+ base_model_relation: quantized
5
+ library_name: transformers.js
6
+ pipeline_tag: feature-extraction
7
+ tags:
8
+ - feature-extraction
9
+ - sentence-similarity
10
+ - multimodal
11
+ - cross-modal-retrieval
12
+ - onnx
13
+ - webgpu
14
+ - transformers.js
15
+ - jina-embeddings
16
+ - embeddings
17
+ language:
18
+ - multilingual
19
+ ---
20
+
21
+ # jina-embeddings-v5-omni-nano · ONNX
22
+
23
+ ONNX exports of [`jinaai/jina-embeddings-v5-omni-nano`](https://huggingface.co/jinaai/jina-embeddings-v5-omni-nano) for in-browser inference via [transformers.js](https://huggingface.co/docs/transformers.js) **v4** with WebGPU.
24
+
25
+ `jina-embeddings-v5-omni-nano` is a ~1.04 B-parameter multimodal embedding model that maps **text, images, audio, and video** into a single shared 768-dimensional L2-normalized space, enabling cross-modal retrieval without reindexing.
26
+
27
+ ## Architecture
28
+
29
+ The base model is a LLaVA-style composition of three frozen encoders plus small trainable projectors, with per-task LoRA adapters. This repo's exports have the **`retrieval`** task adapter merged into the static weights.
30
+
31
+ | Tower | Backbone | Role |
32
+ |---|---|---|
33
+ | Text | EuroBERT-210m (loaded as a bidirectional Llama) | Text encoder |
34
+ | Vision | Qwen3-VL vision tower + spatial merger | Image and video frames |
35
+ | Audio | Whisper-large-v3 encoder + Qwen2.5-Omni audio adapter | Audio (16 kHz mono) |
36
+
37
+ Each tower is bundled with its retrieval projector AND a copy of the language model (which performs the final cross-modal fusion + last-token pooling), so the three ONNX graphs are independently loadable.
38
+
39
+ ## Files
40
+
41
+ Three ONNX graphs, three quantization variants each. Every variant ships as a small `.onnx` schema + a large `.onnx.data` or `.onnx_data` external-weight sidecar (HF Hub-friendly layout, no 2 GB protobuf limits).
42
+
43
+ | Modality | fp32 | fp16 | q4f16 | Verified parity vs fp32 (fp16) |
44
+ |---|---:|---:|---:|---|
45
+ | Text | 849 MB | 424 MB | 263 MB | cos = 1.000000 |
46
+ | Vision | 1247 MB | 622 MB | 460 MB | cos = 0.999998 |
47
+ | Audio | 3400 MB | 1700 MB | 1465 MB | (fp16 doesn't load on CPU EP; verify on WebGPU) |
48
+
49
+ **For desktop WebGPU, use `q4f16`** — it's the smallest and runs natively on shader-int4 hardware. Use `fp16` if you need higher numerical fidelity or your GPU lacks int4 paths.
50
+
51
+ Every graph outputs a single tensor `sentence_embedding` of shape `[batch, 768]`, already L2-normalized — cosine similarity reduces to a dot product.
52
+
53
+ ## Input constraints
54
+
55
+ **Text** (`text_model*.onnx`): inputs `input_ids` and `attention_mask`, both `[batch, seq]` with `seq` fully dynamic. Apply the asymmetric retrieval prefix convention before tokenizing: `Query: …` for queries, `Document: …` for corpus items.
56
+
57
+ **Vision** (`vision_model*.onnx`): the graph is traced at a fixed image-patch layout. `image_grid_thw` is folded as a constant (it drives `torch.linspace` inside Qwen3-VL's `fast_pos_embed_interpolate`, which dynamo cannot symbolicate). Resize every image to **224×224** before passing through `LlavaEuroBertProcessor` — that yields the exact shapes the graph expects:
58
+
59
+ ```
60
+ input_ids [batch, 271] int64
61
+ attention_mask [batch, 271] int64
62
+ pixel_values [1024, 1536] float32
63
+ ```
64
+
65
+ `image_grid_thw` is NOT an ONNX input (it's a constant). Don't pass it.
66
+
67
+ **Audio** (`audio_model*.onnx`): traced with a 5-second 16 kHz mono clip. The graph expects exactly:
68
+
69
+ ```
70
+ input_ids [batch, 125] int64 (audio_token_id placeholders)
71
+ attention_mask [batch, 125] int64
72
+ input_features [1, 128, 3000] float32 (Whisper log-mel, 30s padded)
73
+ feature_attention_mask [1, 3000] int64 (frame-level, 500 ones for 5s of real audio)
74
+ ```
75
+
76
+ Pad or truncate every clip to 5 s. Longer-clip chunking (sliding 5 s windows, average pooled embeddings) is a v2 follow-up.
77
+
78
+ ## Use with transformers.js v4
79
+
80
+ ### Text
81
+
82
+ ```js
83
+ import { AutoTokenizer } from "@huggingface/transformers";
84
+ import * as ort from "onnxruntime-web";
85
+
86
+ const REPO = "shreyask/jina-embeddings-v5-omni-nano-ONNX";
87
+
88
+ const tok = await AutoTokenizer.from_pretrained(REPO);
89
+ const sess = await ort.InferenceSession.create(
90
+ `https://huggingface.co/${REPO}/resolve/main/onnx/text_model_q4f16.onnx`,
91
+ { executionProviders: ["webgpu", "wasm"] },
92
+ );
93
+
94
+ const { input_ids, attention_mask } = await tok(
95
+ "Query: a saxophone solo",
96
+ { return_tensors: "ort" },
97
+ );
98
+ const { sentence_embedding } = await sess.run({ input_ids, attention_mask });
99
+ // Float32Array of length 768, already L2-normalized.
100
+ ```
101
+
102
+ ### Vision
103
+
104
+ ```js
105
+ import { AutoProcessor } from "@huggingface/transformers";
106
+ import * as ort from "onnxruntime-web";
107
+
108
+ const proc = await AutoProcessor.from_pretrained(REPO);
109
+ const sess = await ort.InferenceSession.create(
110
+ `https://huggingface.co/${REPO}/resolve/main/onnx/vision_model_q4f16.onnx`,
111
+ { executionProviders: ["webgpu", "wasm"] },
112
+ );
113
+
114
+ // Resize to 224x224 before passing in.
115
+ const inputs = await proc.apply_chat_template(
116
+ [{ role: "user", content: [{ type: "image", image: imageBlob }] }],
117
+ { add_generation_prompt: false, tokenize: true, return_dict: true, return_tensors: "ort" },
118
+ );
119
+ const { sentence_embedding } = await sess.run({
120
+ input_ids: inputs.input_ids,
121
+ attention_mask: inputs.attention_mask,
122
+ pixel_values: inputs.pixel_values,
123
+ });
124
+ ```
125
+
126
+ ### Audio
127
+
128
+ Audio preprocessing isn't bundled in `LlavaEuroBertProcessor` — use Whisper's feature extractor directly and stamp `audio_token_id` placeholders into `input_ids`. See the [reference implementation](https://huggingface.co/jinaai/jina-embeddings-v5-omni-nano/blob/main/modeling_jina_embeddings_v5_omni.py) for the exact mel-spec → placeholder count plumbing.
129
+
130
+ ## Cross-modal retrieval
131
+
132
+ All three towers project into the same 768-dim space, so a text query can rank images / audio / video corpus items (and vice versa) without re-indexing. Embeddings are L2-normalized, so cosine similarity is a dot product:
133
+
134
+ ```js
135
+ const score = textVec.reduce((s, v, i) => s + v * imageVec[i], 0);
136
+ ```
137
+
138
+ ## How these were exported
139
+
140
+ - `torch` 2.11, `transformers` 5.8, `onnx` 1.21, `onnxruntime` 1.26
141
+ - **Text**: `torch.onnx.export(..., dynamo=True)`. The LlamaModel-based encoder exports cleanly through the dynamo path
142
+ - **Vision and audio**: `torch.onnx.export(..., dynamo=False)` (legacy TorchScript tracer). Dynamo refuses to specialize Qwen3-VL's data-dependent `torch.linspace`, and the GQA-aware SDPA is monkey-patched with a manual MatMul+Softmax for the trace's duration
143
+ - PEFT LoRA fused via `merge_and_unload(safe_merge=True)` so the `retrieval` task adapter is baked in
144
+ - fp16 cast via `onnxruntime.transformers.float16.convert_float_to_float16` (the `onnxconverter_common` path mishandles dynamo's `_to_copy` nodes)
145
+ - 4-bit quant via `onnxruntime.quantization.matmul_nbits_quantizer.MatMulNBitsQuantizer` (`bits=4, block_size=32, accuracy_level=4`)
146
+ - Two graph post-patches required for the audio tower's ORT-loadability: `Cast(to=int64)` inserted before every `Slice` index input (366 inserts), and `Unsqueeze(0)`/`Squeeze(0)` wrapped around the rank-2-input `AveragePool` (1 site)
147
+
148
+ ## License
149
+
150
+ Inherited from the base model: **CC BY-NC 4.0**. Commercial use requires reaching out to `sales@jina.ai`.
151
+
152
+ ## Citation
153
+
154
+ ```bibtex
155
+ @misc{jina-embeddings-v5-omni-nano,
156
+ author = {Jina AI},
157
+ title = {jina-embeddings-v5-omni-nano},
158
+ year = {2025},
159
+ url = {https://huggingface.co/jinaai/jina-embeddings-v5-omni-nano}
160
+ }
161
+ ```
chat_template.jinja ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- set image_count = namespace(value=0) %}
2
+ {%- set video_count = namespace(value=0) %}
3
+ {%- macro render_content(content, do_vision_count, is_system_content=false) %}
4
+ {%- if content is string %}
5
+ {{- content }}
6
+ {%- elif content is iterable and content is not mapping %}
7
+ {%- for item in content %}
8
+ {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}
9
+ {%- if is_system_content %}
10
+ {{- raise_exception('System message cannot contain images.') }}
11
+ {%- endif %}
12
+ {%- if do_vision_count %}
13
+ {%- set image_count.value = image_count.value + 1 %}
14
+ {%- endif %}
15
+ {%- if add_vision_id %}
16
+ {{- 'Picture ' ~ image_count.value ~ ': ' }}
17
+ {%- endif %}
18
+ {{- '<|vision_start|><|image_pad|><|vision_end|>' }}
19
+ {%- elif 'video' in item or item.type == 'video' %}
20
+ {%- if is_system_content %}
21
+ {{- raise_exception('System message cannot contain videos.') }}
22
+ {%- endif %}
23
+ {%- if do_vision_count %}
24
+ {%- set video_count.value = video_count.value + 1 %}
25
+ {%- endif %}
26
+ {%- if add_vision_id %}
27
+ {{- 'Video ' ~ video_count.value ~ ': ' }}
28
+ {%- endif %}
29
+ {{- '<|vision_start|><|video_pad|><|vision_end|>' }}
30
+ {%- elif 'text' in item %}
31
+ {{- item.text }}
32
+ {%- else %}
33
+ {{- raise_exception('Unexpected item type in content.') }}
34
+ {%- endif %}
35
+ {%- endfor %}
36
+ {%- elif content is none or content is undefined %}
37
+ {{- '' }}
38
+ {%- else %}
39
+ {{- raise_exception('Unexpected content type.') }}
40
+ {%- endif %}
41
+ {%- endmacro %}
42
+ {%- if not messages %}
43
+ {{- raise_exception('No messages provided.') }}
44
+ {%- endif %}
45
+ {%- if tools and tools is iterable and tools is not mapping %}
46
+ {{- '<|im_start|>system\n' }}
47
+ {{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }}
48
+ {%- for tool in tools %}
49
+ {{- "\n" }}
50
+ {{- tool | tojson }}
51
+ {%- endfor %}
52
+ {{- "\n</tools>" }}
53
+ {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
54
+ {%- if messages[0].role == 'system' %}
55
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
56
+ {%- if content %}
57
+ {{- '\n\n' + content }}
58
+ {%- endif %}
59
+ {%- endif %}
60
+ {{- '<|im_end|>\n' }}
61
+ {%- else %}
62
+ {%- if messages[0].role == 'system' %}
63
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
64
+ {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }}
65
+ {%- endif %}
66
+ {%- endif %}
67
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
68
+ {%- for message in messages[::-1] %}
69
+ {%- set index = (messages|length - 1) - loop.index0 %}
70
+ {%- if ns.multi_step_tool and message.role == "user" %}
71
+ {%- set content = render_content(message.content, false)|trim %}
72
+ {%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %}
73
+ {%- set ns.multi_step_tool = false %}
74
+ {%- set ns.last_query_index = index %}
75
+ {%- endif %}
76
+ {%- endif %}
77
+ {%- endfor %}
78
+ {%- if ns.multi_step_tool %}
79
+ {{- raise_exception('No user query found in messages.') }}
80
+ {%- endif %}
81
+ {%- for message in messages %}
82
+ {%- set content = render_content(message.content, true)|trim %}
83
+ {%- if message.role == "system" %}
84
+ {%- if not loop.first %}
85
+ {{- raise_exception('System message must be at the beginning.') }}
86
+ {%- endif %}
87
+ {%- elif message.role == "user" %}
88
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
89
+ {%- elif message.role == "assistant" %}
90
+ {%- set reasoning_content = '' %}
91
+ {%- if message.reasoning_content is string %}
92
+ {%- set reasoning_content = message.reasoning_content %}
93
+ {%- else %}
94
+ {%- if '</think>' in content %}
95
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
96
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
97
+ {%- endif %}
98
+ {%- endif %}
99
+ {%- set reasoning_content = reasoning_content|trim %}
100
+ {%- if loop.index0 > ns.last_query_index %}
101
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n\n' + content }}
102
+ {%- else %}
103
+ {{- '<|im_start|>' + message.role + '\n' + content }}
104
+ {%- endif %}
105
+ {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
106
+ {%- for tool_call in message.tool_calls %}
107
+ {%- if tool_call.function is defined %}
108
+ {%- set tool_call = tool_call.function %}
109
+ {%- endif %}
110
+ {%- if loop.first %}
111
+ {%- if content|trim %}
112
+ {{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
113
+ {%- else %}
114
+ {{- '<tool_call>\n<function=' + tool_call.name + '>\n' }}
115
+ {%- endif %}
116
+ {%- else %}
117
+ {{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
118
+ {%- endif %}
119
+ {%- if tool_call.arguments is defined %}
120
+ {%- for args_name, args_value in tool_call.arguments|items %}
121
+ {{- '<parameter=' + args_name + '>\n' }}
122
+ {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %}
123
+ {{- args_value }}
124
+ {{- '\n</parameter>\n' }}
125
+ {%- endfor %}
126
+ {%- endif %}
127
+ {{- '</function>\n</tool_call>' }}
128
+ {%- endfor %}
129
+ {%- endif %}
130
+ {{- '<|im_end|>\n' }}
131
+ {%- elif message.role == "tool" %}
132
+ {%- if loop.previtem and loop.previtem.role != "tool" %}
133
+ {{- '<|im_start|>user' }}
134
+ {%- endif %}
135
+ {{- '\n<tool_response>\n' }}
136
+ {{- content }}
137
+ {{- '\n</tool_response>' }}
138
+ {%- if not loop.last and loop.nextitem.role != "tool" %}
139
+ {{- '<|im_end|>\n' }}
140
+ {%- elif loop.last %}
141
+ {{- '<|im_end|>\n' }}
142
+ {%- endif %}
143
+ {%- else %}
144
+ {{- raise_exception('Unexpected message role.') }}
145
+ {%- endif %}
146
+ {%- endfor %}
147
+ {%- if add_generation_prompt %}
148
+ {{- '<|im_start|>assistant\n' }}
149
+ {%- if enable_thinking is defined and enable_thinking is true %}
150
+ {{- '<think>\n' }}
151
+ {%- else %}
152
+ {{- '<think>\n\n</think>\n\n' }}
153
+ {%- endif %}
154
+ {%- endif %}
config.json ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "JinaEmbeddingsV5OmniModel"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "modeling_jina_embeddings_v5_omni.JinaEmbeddingsV5OmniConfig",
7
+ "AutoModel": "modeling_jina_embeddings_v5_omni.JinaEmbeddingsV5OmniModel"
8
+ },
9
+ "model_type": "jina_embeddings_v5_omni",
10
+ "task_names": [
11
+ "retrieval",
12
+ "text-matching",
13
+ "clustering",
14
+ "classification"
15
+ ],
16
+ "special_token_ids": [
17
+ 128256,
18
+ 128257,
19
+ 128258,
20
+ 128259
21
+ ],
22
+ "vision_config": {
23
+ "deepstack_visual_indexes": [],
24
+ "depth": 12,
25
+ "dtype": "bfloat16",
26
+ "hidden_act": "gelu_pytorch_tanh",
27
+ "hidden_size": 768,
28
+ "in_channels": 3,
29
+ "initializer_range": 0.02,
30
+ "intermediate_size": 3072,
31
+ "model_type": "",
32
+ "num_heads": 12,
33
+ "num_position_embeddings": 2304,
34
+ "out_hidden_size": 1024,
35
+ "patch_size": 16,
36
+ "spatial_merge_size": 2,
37
+ "temporal_patch_size": 2
38
+ },
39
+ "text_config": {
40
+ "attention_bias": false,
41
+ "attention_dropout": 0.0,
42
+ "bos_token_id": 1,
43
+ "eos_token_id": 2,
44
+ "head_dim": 64,
45
+ "hidden_act": "silu",
46
+ "hidden_size": 768,
47
+ "initializer_range": 0.02,
48
+ "intermediate_size": 3072,
49
+ "is_causal": false,
50
+ "max_position_embeddings": 8192,
51
+ "mlp_bias": false,
52
+ "model_type": "",
53
+ "num_attention_heads": 12,
54
+ "num_hidden_layers": 12,
55
+ "num_key_value_heads": 12,
56
+ "pad_token_id": null,
57
+ "pretraining_tp": 1,
58
+ "rms_norm_eps": 1e-05,
59
+ "rope_parameters": {
60
+ "rope_theta": 1000000.0,
61
+ "rope_type": "default"
62
+ },
63
+ "tie_word_embeddings": false,
64
+ "vocab_size": 128260
65
+ },
66
+ "audio_config": {
67
+ "activation_dropout": 0.0,
68
+ "activation_function": "gelu",
69
+ "attention_dropout": 0.0,
70
+ "d_model": 1280,
71
+ "dropout": 0.0,
72
+ "dtype": "float32",
73
+ "encoder_attention_heads": 20,
74
+ "encoder_ffn_dim": 5120,
75
+ "encoder_layers": 32,
76
+ "initializer_range": 0.02,
77
+ "max_source_positions": 1500,
78
+ "num_mel_bins": 128,
79
+ "scale_embedding": false,
80
+ "n_window": 100,
81
+ "output_dim": 3584
82
+ },
83
+ "image_token_index": 128259,
84
+ "audio_token_id": 128256,
85
+ "audio_start_token_id": 128257,
86
+ "audio_end_token_id": 128258,
87
+ "projector_hidden_act": "gelu",
88
+ "tie_word_embeddings": false,
89
+ "dtype": "bfloat16",
90
+ "transformers_version": "5.4.0",
91
+ "torch_dtype": "bfloat16",
92
+ "is_matryoshka": true,
93
+ "matryoshka_dimensions": [
94
+ 32,
95
+ 64,
96
+ 128,
97
+ 256,
98
+ 512,
99
+ 768
100
+ ]
101
+ }
modeling_jina_embeddings_v5_omni.py ADDED
@@ -0,0 +1,616 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Unified jina-embeddings-v5-omni-nano: vision + audio + text with task-specific routing.
3
+
4
+ Shared: Qwen3VLVisionModel + Qwen2.5-Omni audio encoder + LlamaModel (EuroBERT, bidirectional)
5
+ Per-task: vision merger, audio projector, special token embeddings, LoRA adapter
6
+
7
+ Modality loading:
8
+ model = AutoModel.from_pretrained(path, trust_remote_code=True) # all components (default)
9
+ model = AutoModel.from_pretrained(path, trust_remote_code=True, modality="vision") # no audio tower/projectors
10
+ model = AutoModel.from_pretrained(path, trust_remote_code=True, modality="audio") # no vision tower/mergers
11
+
12
+ Usage:
13
+ model = AutoModel.from_pretrained("jinaai/jina-embeddings-v5-omni-nano", trust_remote_code=True)
14
+ embeddings = model.encode(["hello world"], task="retrieval")
15
+ """
16
+
17
+ from typing import List, Optional
18
+ import os
19
+
20
+ import torch
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+
24
+ from huggingface_hub import snapshot_download
25
+ from transformers import AutoTokenizer, LlamaConfig, PreTrainedModel, PretrainedConfig
26
+ from transformers.modeling_outputs import BaseModelOutputWithPast
27
+ from transformers.models.llama.modeling_llama import LlamaModel
28
+ from transformers.models.qwen3_vl.configuration_qwen3_vl import Qwen3VLVisionConfig
29
+ from transformers.models.qwen3_vl.modeling_qwen3_vl import Qwen3VLVisionModel
30
+ from transformers.models.qwen2_5_omni.configuration_qwen2_5_omni import Qwen2_5OmniAudioEncoderConfig
31
+ from transformers.models.qwen2_5_omni.modeling_qwen2_5_omni import Qwen2_5OmniAudioEncoder
32
+ from peft import PeftMixedModel, PeftConfig
33
+
34
+ TASK_NAMES = ["retrieval", "text-matching", "clustering", "classification"]
35
+ _VALID_MODALITIES = ("omni", "vision", "audio", "text")
36
+
37
+
38
+ def _key(task):
39
+ return task.replace("-", "_")
40
+
41
+
42
+ class PretrainedMerger(nn.Module):
43
+ def __init__(self, hidden_size, out_hidden_size, spatial_merge_size=2):
44
+ super().__init__()
45
+ self.hidden_size = hidden_size * (spatial_merge_size ** 2)
46
+ self.norm = nn.LayerNorm(hidden_size, eps=1e-6)
47
+ self.linear_fc1 = nn.Linear(self.hidden_size, self.hidden_size)
48
+ self.act = nn.GELU()
49
+ self.linear_fc2 = nn.Linear(self.hidden_size, out_hidden_size)
50
+
51
+ def forward(self, x):
52
+ x = self.norm(x)
53
+ x = x.view(-1, self.hidden_size)
54
+ x = self.linear_fc2(self.act(self.linear_fc1(x)))
55
+ return x
56
+
57
+
58
+ class JinaEmbeddingsV5OmniConfig(PretrainedConfig):
59
+ model_type = "jina_embeddings_v5_omni"
60
+
61
+ def __init__(
62
+ self,
63
+ vision_config=None,
64
+ text_config=None,
65
+ audio_config=None,
66
+ task_names=None,
67
+ special_token_ids=None,
68
+ image_token_index=None,
69
+ audio_token_id=None,
70
+ audio_start_token_id=None,
71
+ audio_end_token_id=None,
72
+ projector_hidden_act="gelu",
73
+ tie_word_embeddings=False,
74
+ modality="omni",
75
+ **kwargs,
76
+ ):
77
+ if isinstance(vision_config, dict):
78
+ vision_config = PretrainedConfig(**vision_config)
79
+ self.vision_config = vision_config or PretrainedConfig()
80
+ if isinstance(text_config, dict):
81
+ text_config = PretrainedConfig(**text_config)
82
+ self.text_config = text_config or PretrainedConfig()
83
+ if isinstance(audio_config, dict):
84
+ audio_config = PretrainedConfig(**audio_config)
85
+ self.audio_config = audio_config or PretrainedConfig()
86
+ self.task_names = task_names or TASK_NAMES
87
+ self.special_token_ids = special_token_ids or []
88
+ self.image_token_index = image_token_index
89
+ self.audio_token_id = audio_token_id
90
+ self.audio_start_token_id = audio_start_token_id
91
+ self.audio_end_token_id = audio_end_token_id
92
+ self.projector_hidden_act = projector_hidden_act
93
+ if modality not in _VALID_MODALITIES:
94
+ raise ValueError(f"modality must be one of {_VALID_MODALITIES}, got '{modality}'")
95
+ self.modality = modality
96
+ super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
97
+
98
+ def get_text_config(self, **kwargs):
99
+ return self.text_config
100
+
101
+
102
+ class JinaEmbeddingsV5OmniBase(PreTrainedModel):
103
+ config_class = JinaEmbeddingsV5OmniConfig
104
+ supports_gradient_checkpointing = True
105
+ _supports_sdpa = True
106
+ _supports_flash_attn_2 = True
107
+ _supports_attention_backend = True
108
+ _tied_weights_keys = []
109
+ _keys_to_ignore_on_load_missing = ["lm_head.weight"]
110
+ _keys_to_ignore_on_load_unexpected = []
111
+
112
+ def __init__(self, config: JinaEmbeddingsV5OmniConfig):
113
+ super().__init__(config)
114
+
115
+ modality = getattr(config, "modality", "omni")
116
+ if modality not in _VALID_MODALITIES:
117
+ raise ValueError(f"modality must be one of {_VALID_MODALITIES}, got '{modality}'")
118
+ self._modality = modality
119
+
120
+ vision_cfg = config.vision_config
121
+ if not isinstance(vision_cfg, Qwen3VLVisionConfig):
122
+ d = vision_cfg.to_dict() if hasattr(vision_cfg, "to_dict") else dict(vision_cfg)
123
+ d.pop("model_type", None)
124
+ d.pop("transformers_version", None)
125
+ vision_cfg = Qwen3VLVisionConfig(**d)
126
+ vision_cfg.deepstack_visual_indexes = []
127
+
128
+ spatial_merge_size = getattr(vision_cfg, "spatial_merge_size", 2)
129
+ self._spatial_merge_size = spatial_merge_size
130
+ self._vision_hidden_size = vision_cfg.hidden_size
131
+
132
+ text_cfg = config.text_config
133
+ txt_dict = text_cfg.to_dict() if hasattr(text_cfg, "to_dict") else text_cfg
134
+ if not isinstance(text_cfg, LlamaConfig):
135
+ text_cfg = LlamaConfig(**txt_dict)
136
+ text_hidden = text_cfg.hidden_size
137
+
138
+ if modality not in ("audio", "text"):
139
+ self.vision_tower = Qwen3VLVisionModel(vision_cfg)
140
+ self.vision_tower.merger = nn.Identity()
141
+ self.vision_tower.deepstack_merger_list = nn.ModuleList()
142
+ self.vision_tower.deepstack_visual_indexes = []
143
+ self.mergers = nn.ModuleDict({
144
+ _key(t): PretrainedMerger(vision_cfg.hidden_size, text_hidden, spatial_merge_size)
145
+ for t in config.task_names
146
+ })
147
+
148
+ self.language_model = LlamaModel(text_cfg)
149
+ for layer in self.language_model.layers:
150
+ layer.self_attn.is_causal = False
151
+
152
+ self.multi_modal_projector = nn.Identity()
153
+ self.lm_head = nn.Identity()
154
+
155
+ if modality not in ("vision", "text"):
156
+ aud_cfg = config.audio_config
157
+ aud_dict = aud_cfg.to_dict() if hasattr(aud_cfg, "to_dict") else aud_cfg
158
+ audio_encoder_config = Qwen2_5OmniAudioEncoderConfig(**aud_dict)
159
+ self.audio_tower = Qwen2_5OmniAudioEncoder(audio_encoder_config)
160
+ self.audio_tower.proj = nn.Identity() # fused into audio_projector(s)
161
+ output_dim = aud_dict.get('d_model', 1280) # fused: audio_projector(s) now take d_model
162
+ self.audio_projectors = nn.ModuleDict({
163
+ _key(t): nn.Linear(output_dim, text_hidden) for t in config.task_names
164
+ })
165
+
166
+ ignore = []
167
+ if modality in ("audio", "text"):
168
+ ignore.extend([r"^vision_tower\.", r"^mergers\."])
169
+ if modality in ("vision", "text"):
170
+ ignore.extend([r"^audio_tower\.", r"^audio_projectors\."])
171
+ if ignore:
172
+ self._keys_to_ignore_on_load_unexpected = ignore
173
+
174
+ n_special = len(config.special_token_ids)
175
+ self.task_token_embeddings = nn.ParameterDict({
176
+ _key(t): nn.Parameter(torch.zeros(n_special, text_hidden))
177
+ for t in config.task_names
178
+ })
179
+
180
+ self._active_task_key = _key(config.task_names[0])
181
+ self._special_token_ids = config.special_token_ids
182
+ self.post_init()
183
+
184
+ @property
185
+ def modality(self) -> str:
186
+ return self._modality
187
+
188
+ def set_task(self, task):
189
+ k = _key(task)
190
+ self._active_task_key = k
191
+ with torch.no_grad():
192
+ w = self.language_model.embed_tokens.weight.data
193
+ te = self.task_token_embeddings[k]
194
+ for i, tid in enumerate(self._special_token_ids):
195
+ w[tid] = te[i]
196
+
197
+ def get_input_embeddings(self):
198
+ return self.language_model.embed_tokens
199
+
200
+ def set_input_embeddings(self, value):
201
+ self.language_model.embed_tokens = value
202
+
203
+ def get_output_embeddings(self):
204
+ return None
205
+
206
+ def get_image_features(self, pixel_values, image_grid_thw, num_image_tokens=None):
207
+ if self._modality in ("audio", "text"):
208
+ raise ValueError(
209
+ f"Vision inputs are not available in {self._modality}-only mode. "
210
+ "Load with modality='omni' or modality='vision'."
211
+ )
212
+
213
+ out = self.vision_tower(hidden_states=pixel_values, grid_thw=image_grid_thw)
214
+ raw = out[0] if isinstance(out, tuple) else getattr(out, "last_hidden_state", out[0])
215
+ merged = self.mergers[self._active_task_key](raw)
216
+
217
+ merge = self._spatial_merge_size
218
+ sizes = []
219
+ for i in range(image_grid_thw.shape[0]):
220
+ t, h, w = image_grid_thw[i].tolist()
221
+ sizes.append(int(t) * (int(h) // merge) * (int(w) // merge))
222
+
223
+ # Default: return the un-padded per-image feature slices. Their
224
+ # concatenation has exactly sum(sizes) rows == number of <image>
225
+ # placeholder tokens in input_ids, which is what masked_scatter
226
+ # consumes. Padding is only meaningful when callers want a square
227
+ # [N, max_tok, dim] block (e.g. multi-sample batched forward where
228
+ # each row owns its own image), and that path passes
229
+ # num_image_tokens explicitly to opt in.
230
+ dim = merged.shape[-1]
231
+ features, offset = [], 0
232
+ if num_image_tokens is not None:
233
+ max_tok = num_image_tokens
234
+ for n in sizes:
235
+ feat = merged[offset:offset + n]
236
+ if n < max_tok:
237
+ feat = torch.cat([feat, feat.new_zeros(max_tok - n, dim)], dim=0)
238
+ features.append(feat)
239
+ offset += n
240
+ else:
241
+ for n in sizes:
242
+ features.append(merged[offset:offset + n])
243
+ offset += n
244
+ return features
245
+
246
+ def get_audio_features(self, input_features, feature_attention_mask=None):
247
+ if self._modality in ("vision", "text"):
248
+ raise ValueError(
249
+ f"Audio inputs are not available in {self._modality}-only mode. "
250
+ "Load with modality='omni' or modality='audio'."
251
+ )
252
+
253
+ batch_size = input_features.shape[0]
254
+ if batch_size > 1:
255
+ # Serialize per-sample so the packed-frames GEMM shape stays invariant
256
+ # across batch sizes. Makes batched audio bit-exact to B=1 in bf16,
257
+ # and is substantially faster for B>=16 because B=1 hits a
258
+ # well-optimized kernel while the packed-B=N path thrashes on a
259
+ # (total_frames)^2 sdpa matrix.
260
+ outs = [
261
+ self.get_audio_features(
262
+ input_features[i : i + 1],
263
+ feature_attention_mask[i : i + 1] if feature_attention_mask is not None else None,
264
+ )
265
+ for i in range(batch_size)
266
+ ]
267
+ return torch.cat(outs, dim=0)
268
+ if feature_attention_mask is not None:
269
+ feature_lens = feature_attention_mask.sum(-1).long()
270
+ packed = input_features.permute(0, 2, 1)[feature_attention_mask.bool()].permute(1, 0)
271
+ else:
272
+ feature_lens = torch.full(
273
+ (batch_size,), input_features.shape[2],
274
+ device=input_features.device, dtype=torch.long,
275
+ )
276
+ packed = input_features.transpose(1, 2).reshape(-1, input_features.shape[1]).T
277
+ aftercnn_lens, _ = self.audio_tower._get_feat_extract_output_lengths(feature_lens)
278
+ audio_output = self.audio_tower(
279
+ packed, feature_lens=feature_lens, aftercnn_lens=aftercnn_lens,
280
+ )
281
+ return self.audio_projectors[self._active_task_key](audio_output.last_hidden_state)
282
+
283
+ def forward(
284
+ self,
285
+ input_ids=None,
286
+ pixel_values=None,
287
+ attention_mask=None,
288
+ position_ids=None,
289
+ past_key_values=None,
290
+ inputs_embeds=None,
291
+ input_features=None,
292
+ feature_attention_mask=None,
293
+ cache_position=None,
294
+ output_hidden_states=None,
295
+ **kwargs,
296
+ ):
297
+ image_grid_thw = kwargs.pop("image_grid_thw", None)
298
+ num_image_tokens = kwargs.pop("num_image_tokens", None)
299
+ pixel_values_videos = kwargs.pop("pixel_values_videos", None)
300
+ video_grid_thw = kwargs.pop("video_grid_thw", None)
301
+ num_video_tokens = kwargs.pop("num_video_tokens", None)
302
+ kwargs.pop("spatial_shapes", None)
303
+ kwargs.pop("pixel_attention_mask", None)
304
+
305
+ if pixel_values is not None and self._modality in ("audio", "text"):
306
+ raise ValueError(
307
+ f"Vision inputs are not available in {self._modality}-only mode. "
308
+ "Load with modality='omni' or modality='vision'."
309
+ )
310
+ if input_features is not None and self._modality in ("vision", "text"):
311
+ raise ValueError(
312
+ f"Audio inputs are not available in {self._modality}-only mode. "
313
+ "Load with modality='omni' or modality='audio'."
314
+ )
315
+
316
+ if (input_ids is None) ^ (inputs_embeds is not None):
317
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
318
+
319
+ if inputs_embeds is None:
320
+ inputs_embeds = self.get_input_embeddings()(input_ids)
321
+
322
+ # Image and video both use config.image_token_index (the processor
323
+ # remaps <|video_pad|> to <image>). When a single forward pass mixes
324
+ # both modalities, the mask matches both sets of placeholders, so we
325
+ # build one combined source with image features first then video
326
+ # features, matching the order of placeholders in input_ids.
327
+ all_feats = []
328
+ if pixel_values is not None and image_grid_thw is not None:
329
+ all_feats.extend(self.get_image_features(pixel_values, image_grid_thw, num_image_tokens))
330
+ if pixel_values_videos is not None and video_grid_thw is not None:
331
+ all_feats.extend(self.get_image_features(pixel_values_videos, video_grid_thw, num_video_tokens))
332
+ if all_feats:
333
+ feats = torch.cat(all_feats, dim=0).to(inputs_embeds.device, inputs_embeds.dtype)
334
+ mask = (input_ids == self.config.image_token_index).unsqueeze(-1).expand_as(inputs_embeds)
335
+ inputs_embeds = inputs_embeds.masked_scatter(mask, feats)
336
+
337
+ if input_features is not None:
338
+ aud = self.get_audio_features(input_features, feature_attention_mask)
339
+ aud_flat = aud.reshape(-1, aud.shape[-1]).to(inputs_embeds.device, inputs_embeds.dtype)
340
+ mask = (input_ids == self.config.audio_token_id).unsqueeze(-1).expand_as(inputs_embeds)
341
+ inputs_embeds = inputs_embeds.masked_scatter(mask, aud_flat)
342
+
343
+ if attention_mask is not None and attention_mask.dim() == 2:
344
+ dtype = inputs_embeds.dtype
345
+ seq_len = inputs_embeds.shape[1]
346
+ bidi = attention_mask[:, None, None, :].to(dtype=dtype)
347
+ bidi = (1.0 - bidi) * torch.finfo(dtype).min
348
+ attention_mask = bidi.expand(-1, -1, seq_len, -1)
349
+
350
+ out = self.language_model(
351
+ attention_mask=attention_mask,
352
+ position_ids=position_ids,
353
+ past_key_values=past_key_values,
354
+ inputs_embeds=inputs_embeds,
355
+ cache_position=cache_position,
356
+ output_hidden_states=output_hidden_states,
357
+ )
358
+
359
+ return BaseModelOutputWithPast(
360
+ last_hidden_state=self.lm_head(out[0]),
361
+ past_key_values=out.past_key_values,
362
+ hidden_states=out.hidden_states,
363
+ attentions=out.attentions,
364
+ )
365
+
366
+
367
+ class JinaEmbeddingsV5OmniModel(PeftMixedModel):
368
+ config_class = JinaEmbeddingsV5OmniConfig
369
+
370
+ @classmethod
371
+ def register_for_auto_class(cls, auto_class="AutoModel"):
372
+ return PreTrainedModel.register_for_auto_class.__func__(cls, auto_class)
373
+
374
+ @classmethod
375
+ def from_pretrained(cls, pretrained_model_name_or_path, *args, **kwargs):
376
+ modality = kwargs.pop("modality", None)
377
+ task_kwarg = kwargs.pop("task", None)
378
+ config = kwargs.pop("config", None)
379
+ if config is None:
380
+ config = JinaEmbeddingsV5OmniConfig.from_pretrained(pretrained_model_name_or_path)
381
+ if modality is not None:
382
+ config.modality = modality
383
+ elif not hasattr(config, "modality") or config.modality is None:
384
+ config.modality = "omni"
385
+
386
+ default_dtype = getattr(config, "torch_dtype", None) or torch.float32
387
+ base_model = JinaEmbeddingsV5OmniBase.from_pretrained(
388
+ pretrained_model_name_or_path,
389
+ config=config,
390
+ torch_dtype=kwargs.pop("torch_dtype", kwargs.pop("dtype", default_dtype)),
391
+ )
392
+
393
+ if os.path.isdir(pretrained_model_name_or_path):
394
+ adapters_dir = os.path.join(pretrained_model_name_or_path, "adapters")
395
+ else:
396
+ cache = snapshot_download(
397
+ repo_id=pretrained_model_name_or_path,
398
+ allow_patterns=["adapters/*"],
399
+ )
400
+ adapters_dir = os.path.join(cache, "adapters")
401
+
402
+ adapter_paths = {
403
+ name: os.path.join(adapters_dir, name) for name in config.task_names
404
+ }
405
+
406
+ peft_config = PeftConfig.from_pretrained(adapter_paths["retrieval"], **kwargs)
407
+ model = cls(base_model, peft_config, adapter_name="retrieval")
408
+ model._pretrained_path = pretrained_model_name_or_path
409
+ for name in config.task_names:
410
+ model.load_adapter(adapter_paths[name], adapter_name=name, **kwargs)
411
+
412
+ model.tokenizer = AutoTokenizer.from_pretrained(
413
+ pretrained_model_name_or_path, trust_remote_code=True,
414
+ )
415
+ # Task precedence: kwarg > config.task (hf_overrides path) > env var > default.
416
+ task = task_kwarg
417
+ if task is None:
418
+ task = getattr(config, "task", None)
419
+ if task is None:
420
+ task = os.environ.get("JINA_V5_TASK")
421
+ if task is None:
422
+ task = config.task_names[0]
423
+ if task not in config.task_names:
424
+ raise ValueError(
425
+ f"task must be one of {config.task_names}, got '{task}'"
426
+ )
427
+ model.set_adapter(task)
428
+ return model
429
+
430
+ @property
431
+ def modality(self) -> str:
432
+ return self.base_model.model.modality
433
+
434
+ def set_adapter(self, adapters):
435
+ super().set_adapter(adapters)
436
+ task = adapters[0] if isinstance(adapters, list) else adapters
437
+ self.base_model.model.set_task(task)
438
+
439
+ def encode(
440
+ self,
441
+ texts: List[str],
442
+ task: str,
443
+ prompt_name: Optional[str] = "document",
444
+ truncate_dim: Optional[int] = None,
445
+ max_length: Optional[int] = None,
446
+ ) -> torch.Tensor:
447
+ cfg = self.base_model.model.config
448
+ if task not in cfg.task_names:
449
+ raise ValueError(f"Unknown task: {task}")
450
+ if prompt_name is None:
451
+ prompt_name = "document"
452
+ if prompt_name not in {"query", "document"}:
453
+ raise ValueError(f"Unknown prompt_name: {prompt_name}")
454
+
455
+ prefix = "Query: " if prompt_name == "query" else "Document: "
456
+ inputs = [f"{prefix}{t}" for t in texts]
457
+
458
+ max_length = max_length or cfg.text_config.max_position_embeddings
459
+ batch = self.tokenizer(
460
+ inputs, return_tensors="pt", padding=True, truncation=True, max_length=max_length,
461
+ )
462
+ device = next(self.parameters()).device
463
+ batch = {k: v.to(device) for k, v in batch.items()}
464
+ self.set_adapter([task])
465
+ self.eval()
466
+ with torch.no_grad():
467
+ hidden = self(**batch).last_hidden_state
468
+ mask = batch.get("attention_mask")
469
+ if mask is None:
470
+ pooled = hidden[:, -1]
471
+ else:
472
+ seq_lens = mask.sum(dim=1) - 1
473
+ pooled = hidden[torch.arange(hidden.shape[0], device=hidden.device), seq_lens]
474
+ if truncate_dim is not None:
475
+ pooled = pooled[:, :truncate_dim]
476
+ return F.normalize(pooled, p=2, dim=-1)
477
+
478
+ def embed(self, truncate_dim: Optional[int] = None, **inputs):
479
+ """Encode processor outputs into L2-normalized last-token embeddings.
480
+
481
+ Matryoshka: pass `truncate_dim=N` to get an N-dim unit-norm vector
482
+ (truncation is applied before L2-normalization).
483
+ """
484
+ attention_mask = inputs.get("attention_mask", None)
485
+ self.eval()
486
+ with torch.no_grad():
487
+ out = self(**inputs)
488
+ hidden = out.last_hidden_state
489
+ if attention_mask is not None and attention_mask.dim() == 2:
490
+ idx = attention_mask.sum(dim=1) - 1
491
+ else:
492
+ idx = torch.full(
493
+ (hidden.shape[0],), hidden.shape[1] - 1,
494
+ device=hidden.device, dtype=torch.long,
495
+ )
496
+ pooled = hidden[torch.arange(hidden.shape[0], device=hidden.device), idx]
497
+ if truncate_dim is not None:
498
+ pooled = pooled[:, :truncate_dim]
499
+ return torch.nn.functional.normalize(pooled, dim=-1)
500
+
501
+
502
+
503
+ # ---------------------------------------------------------------------------
504
+ # vLLM registration (side-effect on module import).
505
+ #
506
+ # Triggered via config.json "auto_map.AutoConfig" -> this module.
507
+ # HF / sentence-transformers path unaffected: any failure is silently swallowed
508
+ # so that pure transformers users never see a vLLM error.
509
+ # ---------------------------------------------------------------------------
510
+
511
+ def _register_vllm() -> None:
512
+ # All vLLM references are resolved via importlib so transformers'
513
+ # static check_imports does NOT flag vllm as a required dependency.
514
+ # Pure-HF / sentence-transformers usage is unaffected.
515
+ #
516
+ # When loaded via transformers' `trust_remote_code=True`, only the
517
+ # modeling_*.py referenced in auto_map is fetched into the
518
+ # transformers_modules cache — sibling vLLM adapter files are NOT.
519
+ # We pull them from HF Hub before registering; otherwise vLLM falls
520
+ # back to its transformers backend (wrong attention semantics) and
521
+ # multi-request batches collapse.
522
+ import importlib.util as _iu
523
+ if _iu.find_spec("vllm") is None:
524
+ return
525
+ try:
526
+ import os
527
+ import sys
528
+ import importlib
529
+ import inspect
530
+ import shutil
531
+
532
+ pkg = __package__ or ""
533
+ current_dir = os.path.dirname(os.path.abspath(__file__))
534
+ siblings = ("vllm_llava_eurobert_audio", "vllm_jina_v5_omni")
535
+
536
+ for sibling_name in siblings:
537
+ sibling_path = os.path.join(current_dir, sibling_name + ".py")
538
+ if os.path.exists(sibling_path):
539
+ continue
540
+ parts = pkg.split(".")
541
+ if len(parts) < 4 or parts[0] != "transformers_modules":
542
+ continue
543
+ from huggingface_hub import hf_hub_download
544
+ repo_name = parts[2].replace("_hyphen_", "-").replace("_dot_", ".")
545
+ repo_id = f"{parts[1]}/{repo_name}"
546
+ downloaded = hf_hub_download(
547
+ repo_id=repo_id,
548
+ filename=sibling_name + ".py",
549
+ revision=parts[3],
550
+ )
551
+ shutil.copy(downloaded, sibling_path)
552
+
553
+ os.environ.setdefault("VLLM_ENABLE_V1_MULTIPROCESSING", "0")
554
+
555
+ _kvc = importlib.import_module("vllm.v1.core.kv_cache_coordinator")
556
+ _orig = _kvc.get_kv_cache_coordinator
557
+ _NoPrefix = _kvc.KVCacheCoordinatorNoPrefixCache
558
+
559
+ _orig_sig = inspect.signature(_orig)
560
+ _noprefix_sig = inspect.signature(_NoPrefix)
561
+
562
+ def _patched(kv_cache_config, max_model_len, *args, **kwargs):
563
+ if len(kv_cache_config.kv_cache_groups) == 0:
564
+ bound = _orig_sig.bind(kv_cache_config, max_model_len, *args, **kwargs)
565
+ return _NoPrefix(**{
566
+ name: bound.arguments[name]
567
+ for name in _noprefix_sig.parameters
568
+ if name in bound.arguments
569
+ })
570
+ return _orig(kv_cache_config, max_model_len, *args, **kwargs)
571
+
572
+ _kvc.get_kv_cache_coordinator = _patched
573
+
574
+ # Make sibling-dir importable from a fresh subprocess too — vLLM's
575
+ # inspect_model_cls runs in a child Python process that doesn't
576
+ # inherit our sys.modules. Without this on PYTHONPATH the
577
+ # string-spec model registration below can't be resolved.
578
+ if current_dir not in sys.path:
579
+ sys.path.insert(0, current_dir)
580
+ existing = os.environ.get("PYTHONPATH", "")
581
+ if current_dir not in existing.split(os.pathsep):
582
+ os.environ["PYTHONPATH"] = (
583
+ current_dir if not existing else current_dir + os.pathsep + existing
584
+ )
585
+
586
+ if pkg:
587
+ _lla = importlib.import_module(".vllm_llava_eurobert_audio", package=pkg)
588
+ _omni = importlib.import_module(".vllm_jina_v5_omni", package=pkg)
589
+ else:
590
+ _lla = importlib.import_module("vllm_llava_eurobert_audio")
591
+ _omni = importlib.import_module("vllm_jina_v5_omni")
592
+ _ = _lla.LlavaEuroBertAudioForVLLMEmbedding # keep reference
593
+
594
+ ModelRegistry = importlib.import_module(
595
+ "vllm.model_executor.models"
596
+ ).ModelRegistry
597
+ # String spec ("module:Class") — survives vLLM's cloudpickle-into-
598
+ # subprocess flow because the child re-imports by name. Passing the
599
+ # class object directly registers __module__ as the qualified
600
+ # transformers_modules.jinaai.<...> path, which the subprocess
601
+ # can't resolve without HF's dynamic-module setup.
602
+ ModelRegistry.register_model(
603
+ "JinaEmbeddingsV5OmniModel",
604
+ "vllm_jina_v5_omni:JinaV5OmniForVLLMEmbedding",
605
+ )
606
+ except Exception as e:
607
+ import warnings
608
+ warnings.warn(
609
+ f"jina-embeddings-v5-omni base: vLLM registration failed "
610
+ f"({type(e).__name__}: {e}); embeddings will fall back to "
611
+ f"vLLM's generic transformers backend (wrong tensor layout).",
612
+ stacklevel=2,
613
+ )
614
+
615
+
616
+ _register_vllm()
modeling_llava_eurobert_audio.py ADDED
@@ -0,0 +1,400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ LlavaEuroBertAudioForEmbedding: Qwen3VL vision + Qwen2.5-Omni audio + EuroBERT text.
3
+
4
+ Architecture:
5
+ - Vision: Qwen3VLVisionModel (with RoPE, 3D Conv3d patch embed, all layers)
6
+ - Merger: PretrainedMerger (top-level, NOT inside vision_tower)
7
+ - Audio: Qwen2_5OmniAudioEncoder (Qwen2.5-Omni) + Linear projector
8
+ - Text: LlamaModel (EuroBERT, bidirectional)
9
+ - LM head: Identity (embedding model, no vocab projection)
10
+
11
+ Modality loading:
12
+ model = AutoModel.from_pretrained(path, trust_remote_code=True, modality="omni") # all components (default)
13
+ model = AutoModel.from_pretrained(path, trust_remote_code=True, modality="vision") # no audio tower/projector
14
+ model = AutoModel.from_pretrained(path, trust_remote_code=True, modality="audio") # no vision tower/merger
15
+ """
16
+
17
+ from typing import List, Optional, Union
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+ from transformers import LlamaConfig, PreTrainedModel, PretrainedConfig
22
+ from transformers.modeling_outputs import BaseModelOutputWithPast
23
+ from transformers.models.llama.modeling_llama import LlamaModel
24
+ from transformers.models.qwen3_vl.configuration_qwen3_vl import Qwen3VLVisionConfig
25
+ from transformers.models.qwen3_vl.modeling_qwen3_vl import Qwen3VLVisionModel
26
+ from transformers.models.qwen2_5_omni.configuration_qwen2_5_omni import Qwen2_5OmniAudioEncoderConfig
27
+ from transformers.models.qwen2_5_omni.modeling_qwen2_5_omni import Qwen2_5OmniAudioEncoder
28
+
29
+
30
+ _VALID_MODALITIES = ("omni", "vision", "audio", "text")
31
+
32
+
33
+ class PretrainedMerger(nn.Module):
34
+ def __init__(self, hidden_size, out_hidden_size, spatial_merge_size=2):
35
+ super().__init__()
36
+ self.hidden_size = hidden_size * (spatial_merge_size**2)
37
+ self.norm = nn.LayerNorm(hidden_size, eps=1e-6)
38
+ self.linear_fc1 = nn.Linear(self.hidden_size, self.hidden_size)
39
+ self.act = nn.GELU()
40
+ self.linear_fc2 = nn.Linear(self.hidden_size, out_hidden_size)
41
+
42
+ def forward(self, x):
43
+ x = self.norm(x)
44
+ x = x.view(-1, self.hidden_size)
45
+ x = self.linear_fc2(self.act(self.linear_fc1(x)))
46
+ return x
47
+
48
+
49
+ class LlavaEuroBertAudioConfig(PretrainedConfig):
50
+ model_type = "llava_eurobert_audio"
51
+
52
+ def __init__(
53
+ self,
54
+ vision_config=None,
55
+ text_config=None,
56
+ audio_config=None,
57
+ image_token_index=None,
58
+ audio_token_id=None,
59
+ audio_start_token_id=None,
60
+ audio_end_token_id=None,
61
+ projector_hidden_act="gelu",
62
+ tie_word_embeddings=False,
63
+ modality="omni",
64
+ **kwargs,
65
+ ):
66
+ if isinstance(vision_config, dict):
67
+ vision_config = PretrainedConfig(**vision_config)
68
+ self.vision_config = vision_config or PretrainedConfig()
69
+ if isinstance(text_config, dict):
70
+ text_config = PretrainedConfig(**text_config)
71
+ self.text_config = text_config or PretrainedConfig()
72
+ if isinstance(audio_config, dict):
73
+ audio_config = PretrainedConfig(**audio_config)
74
+ self.audio_config = audio_config or PretrainedConfig()
75
+ self.image_token_index = image_token_index
76
+ self.audio_token_id = audio_token_id
77
+ self.audio_start_token_id = audio_start_token_id
78
+ self.audio_end_token_id = audio_end_token_id
79
+ self.projector_hidden_act = projector_hidden_act
80
+ if modality not in _VALID_MODALITIES:
81
+ raise ValueError(f"modality must be one of {_VALID_MODALITIES}, got '{modality}'")
82
+ self.modality = modality
83
+ super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
84
+
85
+ def get_text_config(self, **kwargs):
86
+ return self.text_config
87
+
88
+
89
+ class LlavaEuroBertAudioForEmbedding(PreTrainedModel):
90
+ config_class = LlavaEuroBertAudioConfig
91
+ supports_gradient_checkpointing = True
92
+ _supports_sdpa = True
93
+ _supports_flash_attn_2 = True
94
+ _supports_attention_backend = True
95
+ _tied_weights_keys = []
96
+ _keys_to_ignore_on_load_missing = ["lm_head.weight"]
97
+ _keys_to_ignore_on_load_unexpected = []
98
+
99
+ def __init__(self, config: LlavaEuroBertAudioConfig):
100
+ super().__init__(config)
101
+
102
+ modality = getattr(config, "modality", "omni")
103
+ if modality not in _VALID_MODALITIES:
104
+ raise ValueError(f"modality must be one of {_VALID_MODALITIES}, got '{modality}'")
105
+ self._modality = modality
106
+
107
+ vision_cfg = config.vision_config
108
+ if not isinstance(vision_cfg, Qwen3VLVisionConfig):
109
+ if hasattr(vision_cfg, "to_dict"):
110
+ d = vision_cfg.to_dict()
111
+ else:
112
+ d = dict(vision_cfg)
113
+ d.pop("model_type", None)
114
+ d.pop("transformers_version", None)
115
+ vision_cfg = Qwen3VLVisionConfig(**d)
116
+
117
+ vision_cfg.deepstack_visual_indexes = []
118
+ spatial_merge_size = getattr(vision_cfg, "spatial_merge_size", 2)
119
+
120
+ text_cfg = config.text_config
121
+ if not isinstance(text_cfg, LlamaConfig):
122
+ txt_dict = text_cfg.to_dict() if hasattr(text_cfg, 'to_dict') else dict(text_cfg)
123
+ _saved_attn_impl = getattr(text_cfg, "_attn_implementation", None)
124
+ text_cfg = LlamaConfig(**txt_dict)
125
+ if _saved_attn_impl is not None:
126
+ text_cfg._attn_implementation = _saved_attn_impl
127
+ text_hidden = text_cfg.hidden_size
128
+
129
+ self._spatial_merge_size = spatial_merge_size
130
+ self._vision_hidden_size = getattr(vision_cfg, "hidden_size", 768)
131
+
132
+ if modality not in ("audio", "text"):
133
+ self.vision_tower = Qwen3VLVisionModel(vision_cfg)
134
+ self.vision_tower.merger = nn.Identity()
135
+ self.vision_tower.deepstack_merger_list = nn.ModuleList()
136
+ self.vision_tower.deepstack_visual_indexes = []
137
+ self.merger = PretrainedMerger(
138
+ vision_cfg.hidden_size, text_hidden, spatial_merge_size
139
+ )
140
+
141
+ self.multi_modal_projector = nn.Identity()
142
+ self.language_model = LlamaModel(text_cfg)
143
+ self.lm_head = nn.Identity()
144
+
145
+ for layer in self.language_model.layers:
146
+ layer.self_attn.is_causal = False
147
+
148
+ if modality not in ("vision", "text"):
149
+ aud_cfg = config.audio_config
150
+ aud_dict = aud_cfg.to_dict() if hasattr(aud_cfg, 'to_dict') else aud_cfg
151
+ audio_encoder_config = Qwen2_5OmniAudioEncoderConfig(**aud_dict)
152
+ self.audio_tower = Qwen2_5OmniAudioEncoder(audio_encoder_config)
153
+ output_dim = aud_dict.get('output_dim', 3584)
154
+ self.audio_projector = nn.Linear(output_dim, text_hidden)
155
+
156
+ ignore = []
157
+ if modality in ("audio", "text"):
158
+ ignore.extend([r"^vision_tower\.", r"^merger\."])
159
+ if modality in ("vision", "text"):
160
+ ignore.extend([r"^audio_tower\.", r"^audio_projector\."])
161
+ if ignore:
162
+ self._keys_to_ignore_on_load_unexpected = ignore
163
+
164
+ self.post_init()
165
+
166
+ @property
167
+ def modality(self) -> str:
168
+ return self._modality
169
+
170
+ def get_input_embeddings(self):
171
+ return self.language_model.embed_tokens
172
+
173
+ def set_input_embeddings(self, value):
174
+ self.language_model.embed_tokens = value
175
+
176
+ def get_output_embeddings(self):
177
+ return None
178
+
179
+ def get_image_features(
180
+ self,
181
+ pixel_values: torch.FloatTensor,
182
+ image_grid_thw: torch.LongTensor,
183
+ num_image_tokens: Optional[int] = None,
184
+ ) -> List[torch.Tensor]:
185
+ if self._modality in ("audio", "text"):
186
+ raise ValueError(
187
+ f"Vision inputs are not available in {self._modality}-only mode. "
188
+ "Load with modality='omni' or modality='vision'."
189
+ )
190
+
191
+ vision_output = self.vision_tower(
192
+ hidden_states=pixel_values, grid_thw=image_grid_thw
193
+ )
194
+ if isinstance(vision_output, tuple):
195
+ raw_hidden = vision_output[0]
196
+ elif hasattr(vision_output, "pooler_output") and vision_output.pooler_output is not None:
197
+ raw_hidden = vision_output.pooler_output
198
+ else:
199
+ raw_hidden = vision_output[0]
200
+
201
+ image_features = self.merger(raw_hidden)
202
+
203
+ merge_sq = self._spatial_merge_size ** 2
204
+ split_sizes = (image_grid_thw.prod(-1) // merge_sq).tolist()
205
+ return list(torch.split(image_features, split_sizes))
206
+
207
+ def get_audio_features(
208
+ self,
209
+ input_features: torch.FloatTensor,
210
+ feature_attention_mask: Optional[torch.LongTensor] = None,
211
+ ) -> torch.Tensor:
212
+ if self._modality in ("vision", "text"):
213
+ raise ValueError(
214
+ f"Audio inputs are not available in {self._modality}-only mode. "
215
+ "Load with modality='omni' or modality='audio'."
216
+ )
217
+
218
+ batch_size = input_features.shape[0]
219
+ if batch_size > 1:
220
+ # Serialize per-sample so the packed-frames GEMM shape stays invariant
221
+ # across batch sizes. Makes batched audio bit-exact to B=1 in bf16,
222
+ # and is substantially faster for B>=16 because B=1 hits a
223
+ # well-optimized kernel while the packed-B=N path thrashes on a
224
+ # (total_frames)^2 sdpa matrix.
225
+ outs = [
226
+ self.get_audio_features(
227
+ input_features[i : i + 1],
228
+ feature_attention_mask[i : i + 1] if feature_attention_mask is not None else None,
229
+ )
230
+ for i in range(batch_size)
231
+ ]
232
+ return torch.cat(outs, dim=0)
233
+ if feature_attention_mask is not None:
234
+ feature_lens = feature_attention_mask.sum(-1).long()
235
+ packed = input_features.permute(0, 2, 1)[feature_attention_mask.bool()].permute(1, 0)
236
+ else:
237
+ feature_lens = torch.full(
238
+ (batch_size,), input_features.shape[2],
239
+ device=input_features.device, dtype=torch.long,
240
+ )
241
+ packed = input_features.transpose(1, 2).reshape(-1, input_features.shape[1]).T
242
+ aftercnn_lens, _ = self.audio_tower._get_feat_extract_output_lengths(feature_lens)
243
+ audio_output = self.audio_tower(
244
+ packed, feature_lens=feature_lens, aftercnn_lens=aftercnn_lens,
245
+ )
246
+ return self.audio_projector(audio_output.last_hidden_state)
247
+
248
+ def forward(
249
+ self,
250
+ input_ids: Optional[torch.LongTensor] = None,
251
+ pixel_values: Optional[torch.FloatTensor] = None,
252
+ attention_mask: Optional[torch.Tensor] = None,
253
+ position_ids: Optional[torch.LongTensor] = None,
254
+ past_key_values=None,
255
+ inputs_embeds: Optional[torch.FloatTensor] = None,
256
+ input_features: Optional[torch.FloatTensor] = None,
257
+ feature_attention_mask: Optional[torch.LongTensor] = None,
258
+ cache_position: Optional[torch.LongTensor] = None,
259
+ output_hidden_states: Optional[bool] = None,
260
+ **kwargs,
261
+ ):
262
+ image_grid_thw = kwargs.pop("image_grid_thw", None)
263
+ num_image_tokens = kwargs.pop("num_image_tokens", None)
264
+ kwargs.pop("spatial_shapes", None)
265
+ kwargs.pop("pixel_attention_mask", None)
266
+
267
+ if pixel_values is not None and self._modality in ("audio", "text"):
268
+ raise ValueError(
269
+ f"Vision inputs are not available in {self._modality}-only mode. "
270
+ "Load with modality='omni' or modality='vision'."
271
+ )
272
+ if input_features is not None and self._modality in ("vision", "text"):
273
+ raise ValueError(
274
+ f"Audio inputs are not available in {self._modality}-only mode. "
275
+ "Load with modality='omni' or modality='audio'."
276
+ )
277
+
278
+ if (input_ids is None) ^ (inputs_embeds is not None):
279
+ raise ValueError(
280
+ "You must specify exactly one of input_ids or inputs_embeds"
281
+ )
282
+
283
+ if inputs_embeds is None:
284
+ inputs_embeds = self.get_input_embeddings()(input_ids)
285
+
286
+ if pixel_values is not None and image_grid_thw is not None:
287
+ image_features = self.get_image_features(
288
+ pixel_values=pixel_values,
289
+ image_grid_thw=image_grid_thw,
290
+ num_image_tokens=num_image_tokens,
291
+ )
292
+ image_features = torch.cat(image_features, dim=0).to(
293
+ inputs_embeds.device, inputs_embeds.dtype
294
+ )
295
+ special_image_mask = (
296
+ (input_ids == self.config.image_token_index)
297
+ .unsqueeze(-1)
298
+ .expand_as(inputs_embeds)
299
+ )
300
+ inputs_embeds = inputs_embeds.masked_scatter(
301
+ special_image_mask, image_features
302
+ )
303
+
304
+ if input_features is not None:
305
+ audio_embeds = self.get_audio_features(
306
+ input_features, feature_attention_mask
307
+ )
308
+ audio_embeds_flat = audio_embeds.reshape(
309
+ -1, audio_embeds.shape[-1]
310
+ ).to(inputs_embeds.device, inputs_embeds.dtype)
311
+ audio_mask = (
312
+ (input_ids == self.config.audio_token_id)
313
+ .unsqueeze(-1)
314
+ .expand_as(inputs_embeds)
315
+ )
316
+ inputs_embeds = inputs_embeds.masked_scatter(
317
+ audio_mask, audio_embeds_flat
318
+ )
319
+
320
+ if attention_mask is not None and attention_mask.dim() == 2:
321
+ dtype = inputs_embeds.dtype
322
+ seq_len = inputs_embeds.shape[1]
323
+ bidi_mask = attention_mask[:, None, None, :].to(dtype=dtype)
324
+ bidi_mask = (1.0 - bidi_mask) * torch.finfo(dtype).min
325
+ attention_mask = bidi_mask.expand(-1, -1, seq_len, -1)
326
+
327
+ # vLLM's transformers backend passes `return_dict=False` + `attention_instances`.
328
+ # Force dict-style output internally, and forward remaining kwargs so the
329
+ # vllm attention hook receives its `attention_instances` dict.
330
+ kwargs.pop("return_dict", None)
331
+ outputs = self.language_model(
332
+ attention_mask=attention_mask,
333
+ position_ids=position_ids,
334
+ past_key_values=past_key_values,
335
+ inputs_embeds=inputs_embeds,
336
+ cache_position=cache_position,
337
+ output_hidden_states=output_hidden_states,
338
+ return_dict=True,
339
+ **kwargs,
340
+ )
341
+
342
+ hidden_states = outputs[0]
343
+ logits = self.lm_head(hidden_states)
344
+
345
+ return BaseModelOutputWithPast(
346
+ last_hidden_state=logits,
347
+ past_key_values=outputs.past_key_values,
348
+ hidden_states=outputs.hidden_states,
349
+ attentions=outputs.attentions,
350
+ )
351
+
352
+
353
+ def _register_vllm() -> None:
354
+ import importlib.util as _iu
355
+ if _iu.find_spec("vllm") is None:
356
+ return
357
+ try:
358
+ import os, sys, importlib, shutil
359
+ pkg = __package__ or ""
360
+ current_dir = os.path.dirname(os.path.abspath(__file__))
361
+ sibling_name = "vllm_llava_eurobert_audio"
362
+ sibling_path = os.path.join(current_dir, sibling_name + ".py")
363
+ if not os.path.exists(sibling_path):
364
+ parts = pkg.split(".")
365
+ if len(parts) >= 4 and parts[0] == "transformers_modules":
366
+ from huggingface_hub import hf_hub_download
367
+ repo_name = parts[2].replace("_hyphen_", "-").replace("_dot_", ".")
368
+ repo_id = f"{parts[1]}/{repo_name}"
369
+ downloaded = hf_hub_download(
370
+ repo_id=repo_id,
371
+ filename=sibling_name + ".py",
372
+ revision=parts[3],
373
+ )
374
+ shutil.copy(downloaded, sibling_path)
375
+ if current_dir not in sys.path:
376
+ sys.path.insert(0, current_dir)
377
+ existing = os.environ.get("PYTHONPATH", "")
378
+ if current_dir not in existing.split(os.pathsep):
379
+ os.environ["PYTHONPATH"] = (
380
+ current_dir if not existing else current_dir + os.pathsep + existing
381
+ )
382
+ if pkg:
383
+ _lla = importlib.import_module("." + sibling_name, package=pkg)
384
+ else:
385
+ _lla = importlib.import_module(sibling_name)
386
+ from vllm import ModelRegistry
387
+ ModelRegistry.register_model(
388
+ "LlavaEuroBertAudioForEmbedding",
389
+ _lla.LlavaEuroBertAudioForVLLMEmbedding,
390
+ )
391
+ except Exception as e:
392
+ import warnings
393
+ warnings.warn(
394
+ f"jina-embeddings-v5-omni nano: vLLM registration failed "
395
+ f"({type(e).__name__}: {e}); falling back to Transformers backend.",
396
+ stacklevel=2,
397
+ )
398
+
399
+
400
+ _register_vllm()
onnx/audio_model.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9a39f40bf85201779d7af2a03b9c1467a6d998261ed976d27e2d4f955e4c1cca
3
+ size 8820515
onnx/audio_model.onnx.data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:48d0d710789d9d84b13e676a4302260f1b83cd968692fedd1d3c47d41e0dbb9e
3
+ size 3391207424
onnx/audio_model_fp16.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:957dd6285e916c9027095c662a7a06c6d18b6a53be3cdf0c8b9399f5897f2406
3
+ size 4983121
onnx/audio_model_fp16.onnx_data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:59cbc12ea47bfa69f72b0b2546d6a04e5c7b1434efd2a6258d42417f3f605900
3
+ size 1695603712
onnx/audio_model_q4f16.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:70f8898f6ff52e89b03385ce82f6ce393d157e8bdfa03f5af521ae12fbebd82e
3
+ size 5030426
onnx/audio_model_q4f16.onnx_data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8f769529695b56378267238c2300525d8a4e6476710ecf626f9afc50df70bf5d
3
+ size 1460034560
onnx/text_model.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f47feec56eea10e323e1faeb8ab83a0feaacaf6256670bc851187aa4a2a68752
3
+ size 2008672
onnx/text_model.onnx.data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cde38ab39a4d39d7133b28a6989fdaf21dd717711028e65cd79b1ece50c503a5
3
+ size 847130624
onnx/text_model_fp16.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f59419cb1d33e7bf66e11b336c618b61f1430349bdbd09180c49f7c934956cfe
3
+ size 125318
onnx/text_model_fp16.onnx_data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c02e2e7503b898e3c3f5f7e37aeee96415a6e33f9fd1d3813c69f95ea2172f5b
3
+ size 423538176
onnx/text_model_q4f16.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1eec254d70f37bef242263514190ec76ea792546c520aa83b005639b5a36b817
3
+ size 155687
onnx/text_model_q4f16.onnx_data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cb70fcc7788a81338fce0cfde62ff2c81559e0e6ddd01004f2d73d8488869aab
3
+ size 262516224
onnx/vision_model.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5af7a25cbad96b514d8b6f94bb6d56f28cb23ca5a8dffefc491c5e1a2388edd9
3
+ size 696459
onnx/vision_model.onnx.data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ceb559e9e7ff81fa03dee7028fc28c7df18f3f4cdf284b7014960272d9b3f393
3
+ size 1246301184
onnx/vision_model_fp16.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7ef6d300523d024a7fa764685ef7e975ff9b1e291bdf0cf4bcde84ca322fd851
3
+ size 496172
onnx/vision_model_fp16.onnx_data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:77c4b4e8000e1548fa7a2268360c855d00871b5bbed92b86b364be4af901b48e
3
+ size 621516032
onnx/vision_model_q4f16.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:05cdfefc21ebe04cf5af7a60939f51cab8d1e8250b4853d940b818f1f8e9e4f0
3
+ size 530266
onnx/vision_model_q4f16.onnx_data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eb4b0d512bc7e92ed5e9f59fca75fd37d51e5b21b59d0e0e85b9462178063ef1
3
+ size 460494080
preprocessor_config.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "do_convert_rgb": true,
3
+ "do_normalize": true,
4
+ "do_rescale": true,
5
+ "do_resize": true,
6
+ "image_mean": [
7
+ 0.5,
8
+ 0.5,
9
+ 0.5
10
+ ],
11
+ "image_processor_type": "Qwen2VLImageProcessor",
12
+ "image_std": [
13
+ 0.5,
14
+ 0.5,
15
+ 0.5
16
+ ],
17
+ "merge_size": 2,
18
+ "patch_size": 16,
19
+ "resample": 3,
20
+ "rescale_factor": 0.00392156862745098,
21
+ "temporal_patch_size": 2,
22
+ "min_pixels": 262144,
23
+ "max_pixels": 1310720
24
+ }
processor_config.json ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "processor_class": "LlavaEuroBertProcessor",
3
+ "auto_map": {
4
+ "AutoProcessor": "processing_llava_eurobert.LlavaEuroBertProcessor"
5
+ },
6
+ "image_processor": {
7
+ "image_processor_type": "Qwen2VLImageProcessorFast",
8
+ "do_convert_rgb": true,
9
+ "do_normalize": true,
10
+ "do_rescale": true,
11
+ "do_resize": true,
12
+ "image_mean": [
13
+ 0.5,
14
+ 0.5,
15
+ 0.5
16
+ ],
17
+ "image_std": [
18
+ 0.5,
19
+ 0.5,
20
+ 0.5
21
+ ],
22
+ "min_pixels": 262144,
23
+ "max_pixels": 1310720,
24
+ "size": {
25
+ "longest_edge": 16777216,
26
+ "shortest_edge": 65536
27
+ },
28
+ "merge_size": 2,
29
+ "patch_size": 16,
30
+ "resample": 3,
31
+ "rescale_factor": 0.00392156862745098,
32
+ "temporal_patch_size": 2
33
+ },
34
+ "video_processor": {
35
+ "video_processor_type": "Qwen3VLVideoProcessor",
36
+ "do_convert_rgb": true,
37
+ "do_normalize": true,
38
+ "do_rescale": true,
39
+ "do_resize": true,
40
+ "do_sample_frames": true,
41
+ "fps": 2,
42
+ "image_mean": [
43
+ 0.5,
44
+ 0.5,
45
+ 0.5
46
+ ],
47
+ "image_std": [
48
+ 0.5,
49
+ 0.5,
50
+ 0.5
51
+ ],
52
+ "max_frames": 768,
53
+ "min_frames": 4,
54
+ "merge_size": 2,
55
+ "patch_size": 16,
56
+ "resample": 3,
57
+ "rescale_factor": 0.00392156862745098,
58
+ "size": {
59
+ "longest_edge": 25165824,
60
+ "shortest_edge": 4096
61
+ },
62
+ "temporal_patch_size": 2
63
+ },
64
+ "image_token": "<image>",
65
+ "num_additional_image_tokens": 0,
66
+ "patch_size": null,
67
+ "vision_feature_select_strategy": null
68
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b8135ff0f019acbce7c4b93d1fb24cb8325b5fb0d76c57bbde8101a73cba7fa9
3
+ size 17211089
tokenizer_config.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backend": "tokenizers",
3
+ "bos_token": "<|begin_of_text|>",
4
+ "clean_up_tokenization_spaces": true,
5
+ "eos_token": "<|end_of_text|>",
6
+ "is_local": false,
7
+ "mask_token": "<|mask|>",
8
+ "max_length": null,
9
+ "model_input_names": [
10
+ "input_ids",
11
+ "attention_mask"
12
+ ],
13
+ "model_max_length": 1000000000000000019884624838656,
14
+ "pad_to_multiple_of": null,
15
+ "pad_token": "<|pad|>",
16
+ "pad_token_type_id": 0,
17
+ "padding_side": "right",
18
+ "processor_class": "LlavaEuroBertProcessor",
19
+ "tokenizer_class": "TokenizersBackend",
20
+ "auto_map": {
21
+ "AutoProcessor": "processing_llava_eurobert.LlavaEuroBertProcessor"
22
+ }
23
+ }
video_preprocessor_config.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "do_sample_frames": false,
3
+ "fps": 2,
4
+ "min_frames": 4,
5
+ "max_frames": 32,
6
+ "size": {
7
+ "longest_edge": 12845056,
8
+ "shortest_edge": 262144
9
+ },
10
+ "patch_size": 16,
11
+ "merge_size": 2,
12
+ "temporal_patch_size": 2,
13
+ "do_convert_rgb": true,
14
+ "do_normalize": true,
15
+ "do_rescale": true,
16
+ "do_resize": true,
17
+ "image_mean": [
18
+ 0.5,
19
+ 0.5,
20
+ 0.5
21
+ ],
22
+ "image_std": [
23
+ 0.5,
24
+ 0.5,
25
+ 0.5
26
+ ],
27
+ "rescale_factor": 0.00392156862745098,
28
+ "resample": 3
29
+ }