Xunzhuo commited on
Commit
4769480
·
verified ·
1 Parent(s): 4cc6d9f

Release Vela Omni Nano with multimodal embeddings and evaluation scores

Browse files
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
NOTICE ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Vela Omni
2
+
3
+ This artifact includes components from Google SigLIP (Apache License 2.0), Sentence Transformers (Apache License 2.0), and OpenAI Whisper. OpenAI Whisper is distributed under the following MIT notice.
4
+
5
+ MIT License
6
+
7
+ Copyright (c) 2022 OpenAI
8
+
9
+ Permission is hereby granted, free of charge, to any person obtaining a copy
10
+ of this software and associated documentation files (the "Software"), to deal
11
+ in the Software without restriction, including without limitation the rights
12
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
+ copies of the Software, and to permit persons to whom the Software is
14
+ furnished to do so, subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be included in all
17
+ copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
+ SOFTWARE.
README.md ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: pytorch
3
+ license: apache-2.0
4
+ pipeline_tag: feature-extraction
5
+ tags:
6
+ - vela
7
+ - semantic-router
8
+ - multimodal
9
+ - image-text-retrieval
10
+ - audio-text-retrieval
11
+ ---
12
+
13
+ <div align="center">
14
+ <img src="https://vllm-sr.ai/img/vllm-sr-logo.social.png" alt="vLLM Semantic Router" width="560" />
15
+ <p>
16
+ <a href="https://vllm-sr.ai/"><strong>Docs</strong></a> |
17
+ <a href="https://vllm-sr.ai/blog/"><strong>Blog</strong></a> |
18
+ <a href="https://vllm-dev.slack.com/archives/C09CTGF8KCN"><strong>Slack</strong></a> |
19
+ <a href="https://github.com/vllm-project/semantic-router"><strong>GitHub</strong></a>
20
+ </p>
21
+ </div>
22
+
23
+ # Vela Omni Nano
24
+
25
+ Vela Omni Nano maps text, images, and speech into a shared embedding space for multimodal search and matching.
26
+
27
+ **134M parameters · 384 dimensions · L2-normalized embeddings.**
28
+
29
+ [Try it in Vela Studio](https://huggingface.co/spaces/llm-semantic-router/vela-studio).
30
+
31
+ ## Evaluation
32
+
33
+ Scores use a 0–100 scale; higher is better. All applicable models use the same examples and retrieval pools. N/A denotes a modality the text-only model does not support.
34
+
35
+ | Metric | [Vela-1.0-Encoder-307M-Embedding](https://huggingface.co/llm-semantic-router/Vela-1.0-Encoder-307M-Embedding) | [multi-modal-embed-small](https://huggingface.co/llm-semantic-router/multi-modal-embed-small) | [multi-modal-embed-large](https://huggingface.co/llm-semantic-router/multi-modal-embed-large) | [Vela-1.0-Omni-134M-Nano](https://huggingface.co/llm-semantic-router/Vela-1.0-Omni-134M-Nano) |
36
+ |---|---:|---:|---:|---:|
37
+ | Banking77 · Accuracy | 80.00 | 70.42 | 75.78 | 70.42 |
38
+ | MASSIVE English · Accuracy | 75.64 | 65.95 | 72.31 | 65.95 |
39
+ | COCO · Image → text · R@1 | N/A | 40.83 | 42.53 | 44.23 |
40
+ | COCO · Image → text · R@5 | N/A | 67.19 | 75.21 | 73.03 |
41
+ | COCO · Image → text · R@10 | N/A | 78.49 | 87.61 | 86.03 |
42
+ | COCO · Text → image · R@1 | N/A | 30.18 | 35.04 | 36.11 |
43
+ | COCO · Text → image · R@5 | N/A | 59.42 | 70.09 | 68.72 |
44
+ | COCO · Text → image · R@10 | N/A | 74.29 | 83.91 | 82.02 |
45
+ | LibriSpeech · Audio → text · R@1 | N/A | 4.21 | 56.99 | 5.29 |
46
+ | LibriSpeech · Audio → text · R@5 | N/A | 11.99 | 81.85 | 15.82 |
47
+ | LibriSpeech · Audio → text · R@10 | N/A | 19.03 | 87.94 | 23.90 |
48
+ | LibriSpeech · Text → audio · R@1 | N/A | 9.58 | 78.58 | 11.61 |
49
+ | LibriSpeech · Text → audio · R@5 | N/A | 22.53 | 94.02 | 26.55 |
50
+ | LibriSpeech · Text → audio · R@10 | N/A | 30.69 | 97.01 | 35.44 |
51
+
52
+ Text evaluation uses fixed class prototypes: 3,080 Banking77 and 2,972 MASSIVE English queries. This is nearest-prototype classification, not the MTEB classification protocol.
53
+
54
+ Image retrieval uses the COCO Karpathy CC-BY2 image subset: 823 images and 4,115 captions. Speech retrieval uses 2,611 LibriSpeech test-clean clips and 2,610 unique transcripts, with clips limited to 30 seconds. Recall is measured against each complete candidate pool, accepting all matching positives.
55
+
56
+ Evaluation uses FP32 embeddings, cosine similarity, and a common 128-token text limit. [Full scores and protocol](./scores.json) include model revisions, sample counts, and paired uncertainty.
57
+
58
+ ## Quick start
59
+
60
+ Use PyTorch, Transformers 4.57.6, Hugging Face Hub, safetensors, NumPy, and Pillow:
61
+
62
+ ```python
63
+ import sys
64
+ from huggingface_hub import snapshot_download
65
+
66
+ path = snapshot_download("llm-semantic-router/Vela-1.0-Omni-134M-Nano")
67
+ sys.path.insert(0, path)
68
+ from vela_omni import VelaOmni
69
+
70
+ model = VelaOmni.from_pretrained(path, device="cpu")
71
+ vectors = model.encode_text(["A bicycle beside a building.", "Someone is reading aloud."])
72
+ print(vectors.shape) # (2, 384)
73
+ ```
74
+
75
+ Pass a list of Pillow images to `model.encode_image(images)`. Pass a list of mono NumPy waveforms to `model.encode_audio(waveforms, sampling_rate=16000)`; each waveform must be at most 30 seconds. Compare normalized vectors with their dot product. Similarity scores are rankings, not calibrated probabilities.
76
+
77
+ Cross-modal alignment uses COCO image–caption pairs from the CC-BY 2.0 image subset and [LibriSpeech](https://www.openslr.org/12/) speech–transcript pairs (CC-BY 4.0). COCO annotations are provided under CC-BY 4.0.
78
+
79
+ The repository includes the native model code, component configurations, and tokenizer and processor files. See [NOTICE](./NOTICE) and [LICENSE](./LICENSE) for component attribution and license terms.
80
+
81
+ [Explore the Vela model collection](https://huggingface.co/collections/llm-semantic-router/vela-10-router-models-6aa555ba70cc6997d6d67798)
components/audio/config.json ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "activation_dropout": 0.0,
3
+ "activation_function": "gelu",
4
+ "architectures": [
5
+ "WhisperForConditionalGeneration"
6
+ ],
7
+ "attention_dropout": 0.0,
8
+ "begin_suppress_tokens": [
9
+ 220,
10
+ 50257
11
+ ],
12
+ "bos_token_id": 50257,
13
+ "d_model": 384,
14
+ "decoder_attention_heads": 6,
15
+ "decoder_ffn_dim": 1536,
16
+ "decoder_layerdrop": 0.0,
17
+ "decoder_layers": 4,
18
+ "decoder_start_token_id": 50258,
19
+ "dropout": 0.0,
20
+ "encoder_attention_heads": 6,
21
+ "encoder_ffn_dim": 1536,
22
+ "encoder_layerdrop": 0.0,
23
+ "encoder_layers": 4,
24
+ "eos_token_id": 50257,
25
+ "forced_decoder_ids": [
26
+ [
27
+ 1,
28
+ 50259
29
+ ],
30
+ [
31
+ 2,
32
+ 50359
33
+ ],
34
+ [
35
+ 3,
36
+ 50363
37
+ ]
38
+ ],
39
+ "init_std": 0.02,
40
+ "is_encoder_decoder": true,
41
+ "max_length": 448,
42
+ "max_source_positions": 1500,
43
+ "max_target_positions": 448,
44
+ "model_type": "whisper",
45
+ "num_hidden_layers": 4,
46
+ "num_mel_bins": 80,
47
+ "pad_token_id": 50257,
48
+ "scale_embedding": false,
49
+ "suppress_tokens": [
50
+ 1,
51
+ 2,
52
+ 7,
53
+ 8,
54
+ 9,
55
+ 10,
56
+ 14,
57
+ 25,
58
+ 26,
59
+ 27,
60
+ 28,
61
+ 29,
62
+ 31,
63
+ 58,
64
+ 59,
65
+ 60,
66
+ 61,
67
+ 62,
68
+ 63,
69
+ 90,
70
+ 91,
71
+ 92,
72
+ 93,
73
+ 359,
74
+ 503,
75
+ 522,
76
+ 542,
77
+ 873,
78
+ 893,
79
+ 902,
80
+ 918,
81
+ 922,
82
+ 931,
83
+ 1350,
84
+ 1853,
85
+ 1982,
86
+ 2460,
87
+ 2627,
88
+ 3246,
89
+ 3253,
90
+ 3268,
91
+ 3536,
92
+ 3846,
93
+ 3961,
94
+ 4183,
95
+ 4667,
96
+ 6585,
97
+ 6647,
98
+ 7273,
99
+ 9061,
100
+ 9383,
101
+ 10428,
102
+ 10929,
103
+ 11938,
104
+ 12033,
105
+ 12331,
106
+ 12562,
107
+ 13793,
108
+ 14157,
109
+ 14635,
110
+ 15265,
111
+ 15618,
112
+ 16553,
113
+ 16604,
114
+ 18362,
115
+ 18956,
116
+ 20075,
117
+ 21675,
118
+ 22520,
119
+ 26130,
120
+ 26161,
121
+ 26435,
122
+ 28279,
123
+ 29464,
124
+ 31650,
125
+ 32302,
126
+ 32470,
127
+ 36865,
128
+ 42863,
129
+ 47425,
130
+ 49870,
131
+ 50254,
132
+ 50258,
133
+ 50358,
134
+ 50359,
135
+ 50360,
136
+ 50361,
137
+ 50362
138
+ ],
139
+ "torch_dtype": "float32",
140
+ "transformers_version": "4.27.0.dev0",
141
+ "use_cache": true,
142
+ "vocab_size": 51865
143
+ }
components/audio/preprocessor_config.json ADDED
The diff for this file is too large to render. See raw diff
 
components/image/config.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "SiglipModel"
4
+ ],
5
+ "initializer_factor": 1.0,
6
+ "model_type": "siglip",
7
+ "text_config": {
8
+ "model_type": "siglip_text_model"
9
+ },
10
+ "torch_dtype": "float32",
11
+ "transformers_version": "4.37.0.dev0",
12
+ "vision_config": {
13
+ "image_size": 512,
14
+ "model_type": "siglip_vision_model"
15
+ }
16
+ }
components/image/preprocessor_config.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "do_normalize": true,
3
+ "do_rescale": true,
4
+ "do_resize": true,
5
+ "image_mean": [
6
+ 0.5,
7
+ 0.5,
8
+ 0.5
9
+ ],
10
+ "image_processor_type": "SiglipImageProcessor",
11
+ "image_std": [
12
+ 0.5,
13
+ 0.5,
14
+ 0.5
15
+ ],
16
+ "processor_class": "SiglipProcessor",
17
+ "resample": 3,
18
+ "rescale_factor": 0.00392156862745098,
19
+ "size": {
20
+ "height": 512,
21
+ "width": 512
22
+ }
23
+ }
components/text/1_Pooling/config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "word_embedding_dimension": 384,
3
+ "pooling_mode_cls_token": false,
4
+ "pooling_mode_mean_tokens": true,
5
+ "pooling_mode_max_tokens": false,
6
+ "pooling_mode_mean_sqrt_len_tokens": false
7
+ }
components/text/config.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "BertModel"
4
+ ],
5
+ "attention_probs_dropout_prob": 0.1,
6
+ "gradient_checkpointing": false,
7
+ "hidden_act": "gelu",
8
+ "hidden_dropout_prob": 0.1,
9
+ "hidden_size": 384,
10
+ "initializer_range": 0.02,
11
+ "intermediate_size": 1536,
12
+ "layer_norm_eps": 1e-12,
13
+ "max_position_embeddings": 512,
14
+ "model_type": "bert",
15
+ "num_attention_heads": 12,
16
+ "num_hidden_layers": 6,
17
+ "pad_token_id": 0,
18
+ "position_embedding_type": "absolute",
19
+ "transformers_version": "4.8.2",
20
+ "type_vocab_size": 2,
21
+ "use_cache": true,
22
+ "vocab_size": 30522
23
+ }
components/text/modules.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "idx": 0,
4
+ "name": "0",
5
+ "path": "",
6
+ "type": "sentence_transformers.models.Transformer"
7
+ },
8
+ {
9
+ "idx": 1,
10
+ "name": "1",
11
+ "path": "1_Pooling",
12
+ "type": "sentence_transformers.models.Pooling"
13
+ },
14
+ {
15
+ "idx": 2,
16
+ "name": "2",
17
+ "path": "2_Normalize",
18
+ "type": "sentence_transformers.models.Normalize"
19
+ }
20
+ ]
components/text/sentence_bert_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "max_seq_length": 256,
3
+ "do_lower_case": false
4
+ }
components/text/special_tokens_map.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "unk_token": "[UNK]",
3
+ "sep_token": "[SEP]",
4
+ "pad_token": "[PAD]",
5
+ "cls_token": "[CLS]",
6
+ "mask_token": "[MASK]"
7
+ }
components/text/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
components/text/tokenizer_config.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "do_lower_case": true,
3
+ "unk_token": "[UNK]",
4
+ "sep_token": "[SEP]",
5
+ "pad_token": "[PAD]",
6
+ "cls_token": "[CLS]",
7
+ "mask_token": "[MASK]",
8
+ "tokenize_chinese_chars": true,
9
+ "strip_accents": null,
10
+ "do_basic_tokenize": true,
11
+ "never_split": null,
12
+ "tokenizer_class": "BertTokenizer",
13
+ "model_max_length": 512
14
+ }
components/text/vocab.txt ADDED
The diff for this file is too large to render. See raw diff
 
config.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "format_version": 2,
3
+ "variant": "nano",
4
+ "parameter_count": 133907328,
5
+ "embedding_dim": 384,
6
+ "max_text_length": 128,
7
+ "architectures": [
8
+ "VelaOmni"
9
+ ],
10
+ "torch_dtype": "float32",
11
+ "library_name": "pytorch",
12
+ "audio_sampling_rate": 16000,
13
+ "audio_max_seconds": 30,
14
+ "audio_projection": "linear"
15
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aa28600e25bdfb3796fc173fd9504c5a4687c07211d7e3dbb751dceef1a8c341
3
+ size 535689632
omni_components/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .embedder import MultimodalEmbedder
omni_components/audio_encoder.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Audio encoder based on Whisper architecture."""
2
+
3
+ import logging
4
+ from typing import Any
5
+
6
+ import numpy as np
7
+ import torch
8
+ from torch import nn
9
+ from torch.nn import functional
10
+ from transformers import WhisperConfig, WhisperFeatureExtractor, WhisperModel
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ class AudioEncoder(nn.Module):
16
+ """
17
+ Audio encoder using Whisper encoder architecture.
18
+
19
+ Whisper's encoder is a sequential transformer stack, making it
20
+ compatible with adaptive layer exit (2DMSE).
21
+ """
22
+
23
+ def __init__(self, model_name_or_path, revision=None, output_dim=384,
24
+ pooling_mode="mean", normalize=True, enable_layer_outputs=True):
25
+ super().__init__()
26
+ from transformers.models.whisper.modeling_whisper import WhisperEncoder
27
+ self.model_name = str(model_name_or_path)
28
+ self.revision = revision
29
+ self.output_dim = output_dim
30
+ self.pooling_mode = pooling_mode
31
+ self.normalize = normalize
32
+ self.enable_layer_outputs = enable_layer_outputs
33
+ self.config = WhisperConfig.from_pretrained(model_name_or_path, local_files_only=True)
34
+ self.config._attn_implementation = "sdpa"
35
+ self.encoder = WhisperEncoder(self.config)
36
+ self.feature_extractor = WhisperFeatureExtractor.from_pretrained(
37
+ model_name_or_path, local_files_only=True)
38
+ self.hidden_size = self.config.d_model
39
+ self.num_layers = self.config.encoder_layers
40
+ self.projection = nn.Linear(self.hidden_size, output_dim) if self.hidden_size != output_dim else nn.Identity()
41
+ self.layer_projections = nn.ModuleList([
42
+ nn.Linear(self.hidden_size, output_dim) for _ in range(self.num_layers)
43
+ ]) if enable_layer_outputs else None
44
+ self.layer_norms = nn.ModuleList([
45
+ nn.LayerNorm(self.hidden_size) for _ in range(self.num_layers)
46
+ ]) if enable_layer_outputs else None
47
+
48
+
49
+ def _pool(self, hidden_states: torch.Tensor) -> torch.Tensor:
50
+ """Pool hidden states to get audio embedding."""
51
+ if self.pooling_mode == "mean":
52
+ return hidden_states.mean(dim=1)
53
+ elif self.pooling_mode == "first":
54
+ return hidden_states[:, 0]
55
+ elif self.pooling_mode == "last":
56
+ return hidden_states[:, -1]
57
+ else:
58
+ raise ValueError(f"Unknown pooling mode: {self.pooling_mode}")
59
+
60
+ def preprocess(
61
+ self,
62
+ audio: np.ndarray | list[np.ndarray] | torch.Tensor,
63
+ sampling_rate: int = 16000,
64
+ ) -> torch.Tensor:
65
+ """
66
+ Preprocess audio for the encoder.
67
+
68
+ Args:
69
+ audio: Audio waveform(s) as numpy arrays or tensors
70
+ sampling_rate: Audio sampling rate (should be 16kHz for Whisper)
71
+
72
+ Returns:
73
+ input_features: Mel spectrogram features
74
+ """
75
+ if isinstance(audio, torch.Tensor):
76
+ audio = audio.cpu().numpy()
77
+
78
+ if isinstance(audio, np.ndarray) and audio.ndim == 1:
79
+ audio = [audio]
80
+
81
+ # Use feature extractor to get mel spectrograms
82
+ features = self.feature_extractor(
83
+ audio,
84
+ sampling_rate=sampling_rate,
85
+ return_tensors="pt",
86
+ )
87
+ return features["input_features"]
88
+
89
+ def _prepare_input_features(
90
+ self,
91
+ input_features: torch.Tensor | None,
92
+ audio: np.ndarray | list[np.ndarray] | None,
93
+ sampling_rate: int,
94
+ ) -> torch.Tensor | None:
95
+ """Preprocess raw audio and move it to the encoder device."""
96
+ if input_features is not None or audio is None:
97
+ return input_features
98
+ prepared = self.preprocess(audio, sampling_rate)
99
+ parameter = next(self.parameters(), None)
100
+ device = (
101
+ parameter.device
102
+ if parameter is not None
103
+ else torch.device("cuda" if torch.cuda.is_available() else "cpu")
104
+ )
105
+ return prepared.to(device)
106
+
107
+ @staticmethod
108
+ def _hidden_states(outputs: Any) -> tuple[torch.Tensor, ...] | None:
109
+ """Return encoder-layer states without the input embedding state."""
110
+ hidden_states = getattr(outputs, "hidden_states", None)
111
+ return hidden_states[1:] if hidden_states is not None else None
112
+
113
+ def _project_layer(
114
+ self,
115
+ hidden_states: torch.Tensor,
116
+ layer_idx: int,
117
+ ) -> torch.Tensor:
118
+ """Pool and project one intermediate encoder layer."""
119
+ if self.layer_norms is not None and self.layer_projections is not None:
120
+ normalized = self.layer_norms[layer_idx](hidden_states)
121
+ return self.layer_projections[layer_idx](self._pool(normalized))
122
+ return self.projection(self._pool(hidden_states))
123
+
124
+ def _select_embedding(
125
+ self,
126
+ outputs: Any,
127
+ all_hidden_states: tuple[torch.Tensor, ...] | None,
128
+ target_layer: int | None,
129
+ ) -> torch.Tensor:
130
+ """Select either an intermediate 2DMSE layer or the final layer."""
131
+ if target_layer is None or all_hidden_states is None:
132
+ return self.projection(self._pool(outputs.last_hidden_state))
133
+ layer_idx = min(target_layer, len(all_hidden_states) - 1)
134
+ return self._project_layer(all_hidden_states[layer_idx], layer_idx)
135
+
136
+ def _all_layer_embeddings(
137
+ self,
138
+ all_hidden_states: tuple[torch.Tensor, ...],
139
+ ) -> list[torch.Tensor]:
140
+ """Project every encoder layer for confidence-based exit training."""
141
+ embeddings = []
142
+ for layer_idx, layer_hidden_states in enumerate(all_hidden_states):
143
+ embedding = self._project_layer(layer_hidden_states, layer_idx)
144
+ if self.normalize:
145
+ embedding = functional.normalize(embedding, p=2, dim=-1)
146
+ embeddings.append(embedding)
147
+ return embeddings
148
+
149
+ def forward(
150
+ self,
151
+ input_features: torch.Tensor | None = None,
152
+ audio: np.ndarray | list[np.ndarray] | None = None,
153
+ sampling_rate: int = 16000,
154
+ target_layer: int | None = None, # For 2DMSE
155
+ target_dim: int | None = None, # For MRL
156
+ return_all_layers: bool = False,
157
+ ) -> torch.Tensor | tuple[torch.Tensor, list[torch.Tensor]]:
158
+ """
159
+ Forward pass for audio encoding.
160
+
161
+ Args:
162
+ input_features: Preprocessed mel spectrogram features
163
+ audio: Raw audio waveforms (will be preprocessed if input_features not provided)
164
+ sampling_rate: Audio sampling rate
165
+ target_layer: Exit at this layer (None = full model)
166
+ target_dim: Truncate to this dimension (None = full dim)
167
+ return_all_layers: Return embeddings from all layers
168
+
169
+ Returns:
170
+ embeddings: [batch_size, output_dim] or truncated
171
+ all_layer_embeddings: (optional) List of [batch_size, output_dim]
172
+ """
173
+ input_features = self._prepare_input_features(
174
+ input_features,
175
+ audio,
176
+ sampling_rate,
177
+ )
178
+
179
+ # Forward through encoder
180
+ outputs = self.encoder(
181
+ input_features=input_features,
182
+ output_hidden_states=self.enable_layer_outputs or return_all_layers,
183
+ )
184
+
185
+ all_hidden_states = self._hidden_states(outputs)
186
+ embedding = self._select_embedding(outputs, all_hidden_states, target_layer)
187
+
188
+ # Dimension truncation (MRL)
189
+ if target_dim is not None:
190
+ embedding = embedding[:, :target_dim]
191
+
192
+ # Normalize
193
+ if self.normalize:
194
+ embedding = functional.normalize(embedding, p=2, dim=-1)
195
+
196
+ # Return all layer embeddings if requested
197
+ if return_all_layers and all_hidden_states is not None:
198
+ return embedding, self._all_layer_embeddings(all_hidden_states)
199
+
200
+ return embedding
201
+
202
+ def encode(
203
+ self,
204
+ audio_list: list[np.ndarray],
205
+ batch_size: int = 16,
206
+ sampling_rate: int = 16000,
207
+ show_progress: bool = True,
208
+ **kwargs,
209
+ ) -> torch.Tensor:
210
+ """Encode a list of audio waveforms into embeddings."""
211
+ all_embeddings = []
212
+
213
+ for i in range(0, len(audio_list), batch_size):
214
+ batch_audio = audio_list[i : i + batch_size]
215
+ with torch.no_grad():
216
+ embeddings = self.forward(
217
+ audio=batch_audio,
218
+ sampling_rate=sampling_rate,
219
+ **kwargs,
220
+ )
221
+ all_embeddings.append(embeddings.cpu())
222
+
223
+ return torch.cat(all_embeddings, dim=0)
omni_components/audio_io.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Optional file decoding; waveform inference does not require a codec package."""
2
+ class _AudioFiles:
3
+ @staticmethod
4
+ def load(*args, **kwargs):
5
+ try:
6
+ from librosa import load
7
+ except ImportError as exc:
8
+ raise ImportError("Install librosa for direct audio-file loading, or pass mono waveforms to encode_audio") from exc
9
+ return load(*args, **kwargs)
10
+
11
+ librosa = _AudioFiles()
omni_components/embedder.py ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Main multimodal embedder combining all modality encoders."""
2
+
3
+ import json
4
+ import logging
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ import numpy as np
9
+ import torch
10
+ from PIL import Image
11
+ from torch import nn
12
+ from torch.nn import functional
13
+
14
+ from .audio_encoder import AudioEncoder
15
+ from .fusion import ModalityFusion
16
+ from .image_encoder import ImageEncoder
17
+ from .text_encoder import TextEncoder
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+
22
+ class MultimodalEmbedder(nn.Module):
23
+ """
24
+ Multimodal embedding model combining text, image, and audio encoders.
25
+
26
+ Supports:
27
+ - Single modality encoding
28
+ - Multimodal fusion
29
+ - Adaptive layer exit (2DMSE)
30
+ - Dimension truncation (MRL)
31
+ """
32
+
33
+ def __init__(self, component_dir, legacy=False):
34
+ super().__init__()
35
+ root = Path(component_dir)
36
+ self.output_dim = 384
37
+ self.normalize = True
38
+ self.enable_layer_outputs = True
39
+ self.fusion_type = "transformer"
40
+ self.num_fusion_layers = 2
41
+ self.max_text_length = 128
42
+ self.text_encoder_revision = None
43
+ self.image_encoder_revision = None
44
+ self.audio_encoder_revision = None
45
+ self.text_encoder = TextEncoder(root / "text", output_dim=384, normalize=False,
46
+ max_length=128, enable_layer_outputs=True)
47
+ self.image_encoder = ImageEncoder(root / "image", output_dim=384, normalize=False,
48
+ enable_layer_outputs=True, legacy=legacy)
49
+ self.audio_encoder = AudioEncoder(root / "audio", output_dim=384, normalize=False,
50
+ enable_layer_outputs=True)
51
+ self.fusion = ModalityFusion(input_dim=384, hidden_dim=384, output_dim=384,
52
+ fusion_type="transformer", num_fusion_layers=2, enable_layer_outputs=True)
53
+ self.encoder_layers = {"text": self.text_encoder.num_layers,
54
+ "image": self.image_encoder.num_layers,
55
+ "audio": self.audio_encoder.num_layers, "fusion": 2}
56
+
57
+
58
+ def encode_text(
59
+ self,
60
+ texts: str | list[str],
61
+ target_layer: int | None = None,
62
+ target_dim: int | None = None,
63
+ ) -> torch.Tensor:
64
+ """Encode text into embeddings."""
65
+ if isinstance(texts, str):
66
+ texts = [texts]
67
+
68
+ embedding = self.text_encoder(
69
+ texts=texts,
70
+ target_layer=target_layer,
71
+ target_dim=target_dim,
72
+ )
73
+
74
+ if self.normalize:
75
+ embedding = functional.normalize(embedding, p=2, dim=-1)
76
+
77
+ return embedding
78
+
79
+ def encode_image(
80
+ self,
81
+ images: Image.Image | list[Image.Image] | torch.Tensor,
82
+ target_layer: int | None = None,
83
+ target_dim: int | None = None,
84
+ ) -> torch.Tensor:
85
+ """Encode images into embeddings."""
86
+ if isinstance(images, Image.Image):
87
+ images = [images]
88
+
89
+ embedding = self.image_encoder(
90
+ images=images,
91
+ target_layer=target_layer,
92
+ target_dim=target_dim,
93
+ )
94
+
95
+ if self.normalize:
96
+ embedding = functional.normalize(embedding, p=2, dim=-1)
97
+
98
+ return embedding
99
+
100
+ def encode_audio(
101
+ self,
102
+ audio: np.ndarray | list[np.ndarray] | torch.Tensor,
103
+ sampling_rate: int = 16000,
104
+ target_layer: int | None = None,
105
+ target_dim: int | None = None,
106
+ ) -> torch.Tensor:
107
+ """Encode audio into embeddings."""
108
+ if isinstance(audio, np.ndarray) and audio.ndim == 1:
109
+ audio = [audio]
110
+
111
+ embedding = self.audio_encoder(
112
+ audio=audio,
113
+ sampling_rate=sampling_rate,
114
+ target_layer=target_layer,
115
+ target_dim=target_dim,
116
+ )
117
+
118
+ if self.normalize:
119
+ embedding = functional.normalize(embedding, p=2, dim=-1)
120
+
121
+ return embedding
122
+
123
+ def encode_multimodal(
124
+ self,
125
+ texts: str | list[str] | None = None,
126
+ images: Image.Image | list[Image.Image] | torch.Tensor | None = None,
127
+ audio: np.ndarray | list[np.ndarray] | torch.Tensor | None = None,
128
+ sampling_rate: int = 16000,
129
+ target_layer: int | None = None,
130
+ target_dim: int | None = None,
131
+ encoder_target_layers: dict[str, int] | None = None,
132
+ ) -> torch.Tensor:
133
+ """
134
+ Encode multimodal inputs into a fused embedding.
135
+
136
+ Args:
137
+ texts: Text input(s)
138
+ images: Image input(s)
139
+ audio: Audio input(s)
140
+ sampling_rate: Audio sampling rate
141
+ target_layer: Fusion layer to exit at (2DMSE)
142
+ target_dim: Output dimension to truncate to (MRL)
143
+ encoder_target_layers: Dict of encoder-specific layer exits
144
+ """
145
+ embeddings = {}
146
+ enc_layers = encoder_target_layers or {}
147
+
148
+ if texts is not None:
149
+ if isinstance(texts, str):
150
+ texts = [texts]
151
+ text_layer = enc_layers.get("text", None)
152
+ embeddings["text"] = self.text_encoder(
153
+ texts=texts,
154
+ target_layer=text_layer,
155
+ )
156
+
157
+ if images is not None:
158
+ if isinstance(images, Image.Image):
159
+ images = [images]
160
+ image_layer = enc_layers.get("image", None)
161
+ embeddings["image"] = self.image_encoder(
162
+ images=images,
163
+ target_layer=image_layer,
164
+ )
165
+
166
+ if audio is not None:
167
+ if isinstance(audio, np.ndarray) and audio.ndim == 1:
168
+ audio = [audio]
169
+ audio_layer = enc_layers.get("audio", None)
170
+ embeddings["audio"] = self.audio_encoder(
171
+ audio=audio,
172
+ sampling_rate=sampling_rate,
173
+ target_layer=audio_layer,
174
+ )
175
+
176
+ if not embeddings:
177
+ raise ValueError("At least one modality must be provided")
178
+
179
+ fused = self.fusion(
180
+ embeddings=embeddings,
181
+ target_layer=target_layer,
182
+ target_dim=target_dim,
183
+ normalize=self.normalize,
184
+ )
185
+ return fused
186
+
187
+ def forward(
188
+ self,
189
+ texts: str | list[str] | None = None,
190
+ images: Image.Image | list[Image.Image] | torch.Tensor | None = None,
191
+ audio: np.ndarray | list[np.ndarray] | torch.Tensor | None = None,
192
+ modality: str | None = None,
193
+ target_layer: int | None = None,
194
+ target_dim: int | None = None,
195
+ **kwargs,
196
+ ) -> torch.Tensor:
197
+ """Forward pass - encode inputs into embeddings."""
198
+ provided = sum([texts is not None, images is not None, audio is not None])
199
+
200
+ if provided == 0:
201
+ raise ValueError("At least one input must be provided")
202
+
203
+ if provided == 1 or modality is not None:
204
+ if texts is not None or modality == "text":
205
+ return self.encode_text(texts, target_layer, target_dim)
206
+ elif images is not None or modality == "image":
207
+ return self.encode_image(images, target_layer, target_dim)
208
+ elif audio is not None or modality == "audio":
209
+ return self.encode_audio(
210
+ audio, target_layer=target_layer, target_dim=target_dim, **kwargs
211
+ )
212
+
213
+ return self.encode_multimodal(
214
+ texts=texts,
215
+ images=images,
216
+ audio=audio,
217
+ target_layer=target_layer,
218
+ target_dim=target_dim,
219
+ **kwargs,
220
+ )
221
+
222
+ def get_layer_info(self) -> dict[str, int]:
223
+ """Get number of layers for each encoder."""
224
+ return self.encoder_layers.copy()
225
+
226
+ def _adaptive_embedding(
227
+ self,
228
+ encoder: nn.Module,
229
+ encoder_kwargs: dict[str, Any],
230
+ exit_layers: list[int],
231
+ confidence_threshold: float,
232
+ ) -> tuple[torch.Tensor, dict[str, int | float]]:
233
+ """Select the first candidate layer that satisfies the confidence gate."""
234
+ final_embedding, layer_embeddings = encoder(
235
+ **encoder_kwargs,
236
+ return_all_layers=True,
237
+ )
238
+ selected_layer = encoder.num_layers
239
+ selected_embedding = final_embedding
240
+ selected_confidence = 1.0
241
+ for layer in exit_layers:
242
+ if layer > len(layer_embeddings):
243
+ continue
244
+ candidate = layer_embeddings[layer - 1]
245
+ confidence = self._estimate_confidence(candidate)
246
+ if confidence >= confidence_threshold:
247
+ selected_layer = layer
248
+ selected_embedding = candidate
249
+ selected_confidence = confidence
250
+ break
251
+ return selected_embedding, {
252
+ "layer": selected_layer,
253
+ "confidence": selected_confidence,
254
+ }
255
+
256
+ def encode_adaptive(
257
+ self,
258
+ texts: str | list[str] | None = None,
259
+ images: Image.Image | list[Image.Image] | torch.Tensor | None = None,
260
+ audio: np.ndarray | list[np.ndarray] | torch.Tensor | None = None,
261
+ confidence_threshold: float = 0.8,
262
+ return_exit_info: bool = False,
263
+ **kwargs,
264
+ ):
265
+ """
266
+ Encode with confidence-based adaptive layer exit.
267
+
268
+ Each modality independently decides when to exit based on confidence.
269
+ Uses single forward pass with all layer outputs for efficiency.
270
+
271
+ Args:
272
+ texts: Text input(s)
273
+ images: Image input(s)
274
+ audio: Audio input(s)
275
+ confidence_threshold: Minimum confidence to exit early (0-1)
276
+ return_exit_info: If True, return (embedding, exit_info_dict)
277
+
278
+ Returns:
279
+ embedding or (embedding, exit_info) with layer/confidence per modality
280
+ """
281
+ embeddings = {}
282
+ exit_info = {}
283
+
284
+ text_exit_layers = [6, 11, 16, min(22, self.text_encoder.num_layers)]
285
+ image_exit_layers = [6, 13, 20, min(27, self.image_encoder.num_layers)]
286
+
287
+ if texts is not None:
288
+ if isinstance(texts, str):
289
+ texts = [texts]
290
+
291
+ embedding, info = self._adaptive_embedding(
292
+ self.text_encoder,
293
+ {"texts": texts},
294
+ text_exit_layers,
295
+ confidence_threshold,
296
+ )
297
+ embeddings["text"] = embedding
298
+ exit_info["text"] = info
299
+
300
+ if images is not None:
301
+ if isinstance(images, Image.Image):
302
+ images = [images]
303
+
304
+ embedding, info = self._adaptive_embedding(
305
+ self.image_encoder,
306
+ {"images": images},
307
+ image_exit_layers,
308
+ confidence_threshold,
309
+ )
310
+ embeddings["image"] = embedding
311
+ exit_info["image"] = info
312
+
313
+ if audio is not None:
314
+ emb = self.audio_encoder(audio=audio, **kwargs)
315
+ embeddings["audio"] = emb
316
+ exit_info["audio"] = {
317
+ "layer": self.audio_encoder.num_layers,
318
+ "confidence": 1.0,
319
+ }
320
+
321
+ # Combine embeddings
322
+ if len(embeddings) == 0:
323
+ raise ValueError("At least one modality must be provided")
324
+ elif len(embeddings) == 1:
325
+ result = next(iter(embeddings.values()))
326
+ else:
327
+ result = self.fusion(embeddings=embeddings, normalize=self.normalize)
328
+
329
+ if self.normalize and len(embeddings) == 1:
330
+ result = functional.normalize(result, p=2, dim=-1)
331
+
332
+ if return_exit_info:
333
+ return result, exit_info
334
+ return result
335
+
336
+ def encode_with_fixed_layers(
337
+ self,
338
+ texts: str | list[str] | None = None,
339
+ images: Image.Image | list[Image.Image] | torch.Tensor | None = None,
340
+ audio: np.ndarray | list[np.ndarray] | torch.Tensor | None = None,
341
+ text_layer: int | None = None,
342
+ image_layer: int | None = None,
343
+ audio_layer: int | None = None,
344
+ target_dim: int | None = None,
345
+ **kwargs,
346
+ ) -> torch.Tensor:
347
+ """
348
+ Encode with explicit layer selection per modality.
349
+
350
+ This is the most efficient method when you know which layers to use,
351
+ as it only computes up to the specified layer (true early exit).
352
+
353
+ Args:
354
+ text_layer: Exit layer for text encoder (None = full)
355
+ image_layer: Exit layer for image encoder (None = full)
356
+ audio_layer: Exit layer for audio encoder (None = full)
357
+ target_dim: Output dimension truncation (MRL)
358
+ """
359
+ return self.encode_multimodal(
360
+ texts=texts,
361
+ images=images,
362
+ audio=audio,
363
+ encoder_target_layers={
364
+ "text": text_layer,
365
+ "image": image_layer,
366
+ "audio": audio_layer,
367
+ },
368
+ target_dim=target_dim,
369
+ **kwargs,
370
+ )
371
+
372
+ def _estimate_confidence(self, embedding: torch.Tensor) -> float:
373
+ """
374
+ Estimate confidence based on embedding properties.
375
+
376
+ For production, replace with trained ConfidenceEstimator
377
+ that learns to predict when early layers are sufficient.
378
+ """
379
+ with torch.no_grad():
380
+ # Variance-based: lower variance = more confident/stable
381
+ variance = embedding.var(dim=-1).mean().item()
382
+ conf_from_var = 1.0 / (1.0 + variance)
383
+
384
+ # Norm-based: well-normalized = good embedding
385
+ norm = embedding.norm(dim=-1).mean().item()
386
+ conf_from_norm = min(1.0, norm)
387
+
388
+ return (conf_from_var + conf_from_norm) / 2
389
+
390
+
391
+
392
+
393
+ # Legacy alias for backward compatibility
394
+ DiffusionMultimodalEmbedder = MultimodalEmbedder # Deprecated
omni_components/fusion.py ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Modality fusion module for combining embeddings from different modalities."""
2
+
3
+ import logging
4
+
5
+ import torch
6
+ from torch import nn
7
+ from torch.nn import functional
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ class ModalityProjector(nn.Module):
13
+ """Projects modality-specific embeddings to a common dimension."""
14
+
15
+ def __init__(
16
+ self,
17
+ input_dim: int,
18
+ output_dim: int,
19
+ num_layers: int = 2,
20
+ dropout: float = 0.1,
21
+ ):
22
+ super().__init__()
23
+
24
+ layers = []
25
+ current_dim = input_dim
26
+
27
+ for _i in range(num_layers - 1):
28
+ layers.extend(
29
+ [
30
+ nn.Linear(current_dim, output_dim),
31
+ nn.LayerNorm(output_dim),
32
+ nn.GELU(),
33
+ nn.Dropout(dropout),
34
+ ]
35
+ )
36
+ current_dim = output_dim
37
+
38
+ # Final projection without activation
39
+ layers.append(nn.Linear(current_dim, output_dim))
40
+
41
+ self.projector = nn.Sequential(*layers)
42
+
43
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
44
+ return self.projector(x)
45
+
46
+
47
+ class CrossModalAttention(nn.Module):
48
+ """Cross-modal attention for fusing different modality embeddings."""
49
+
50
+ def __init__(
51
+ self,
52
+ hidden_dim: int,
53
+ num_heads: int = 8,
54
+ dropout: float = 0.1,
55
+ ):
56
+ super().__init__()
57
+
58
+ self.attention = nn.MultiheadAttention(
59
+ embed_dim=hidden_dim,
60
+ num_heads=num_heads,
61
+ dropout=dropout,
62
+ batch_first=True,
63
+ )
64
+ self.norm1 = nn.LayerNorm(hidden_dim)
65
+ self.norm2 = nn.LayerNorm(hidden_dim)
66
+
67
+ self.ffn = nn.Sequential(
68
+ nn.Linear(hidden_dim, hidden_dim * 4),
69
+ nn.GELU(),
70
+ nn.Dropout(dropout),
71
+ nn.Linear(hidden_dim * 4, hidden_dim),
72
+ nn.Dropout(dropout),
73
+ )
74
+
75
+ def forward(
76
+ self,
77
+ query: torch.Tensor,
78
+ key: torch.Tensor,
79
+ value: torch.Tensor,
80
+ ) -> torch.Tensor:
81
+ """
82
+ Args:
83
+ query: [batch, seq_q, dim]
84
+ key: [batch, seq_k, dim]
85
+ value: [batch, seq_v, dim]
86
+ """
87
+ # Cross attention
88
+ attn_output, _ = self.attention(query, key, value)
89
+ x = self.norm1(query + attn_output)
90
+
91
+ # FFN
92
+ ffn_output = self.ffn(x)
93
+ x = self.norm2(x + ffn_output)
94
+
95
+ return x
96
+
97
+
98
+ class FusionTransformerBlock(nn.Module):
99
+ """Transformer block for multimodal fusion."""
100
+
101
+ def __init__(
102
+ self,
103
+ hidden_dim: int,
104
+ num_heads: int = 8,
105
+ dropout: float = 0.1,
106
+ ):
107
+ super().__init__()
108
+
109
+ self.self_attention = nn.MultiheadAttention(
110
+ embed_dim=hidden_dim,
111
+ num_heads=num_heads,
112
+ dropout=dropout,
113
+ batch_first=True,
114
+ )
115
+ self.norm1 = nn.LayerNorm(hidden_dim)
116
+ self.norm2 = nn.LayerNorm(hidden_dim)
117
+
118
+ self.ffn = nn.Sequential(
119
+ nn.Linear(hidden_dim, hidden_dim * 4),
120
+ nn.GELU(),
121
+ nn.Dropout(dropout),
122
+ nn.Linear(hidden_dim * 4, hidden_dim),
123
+ nn.Dropout(dropout),
124
+ )
125
+
126
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
127
+ # Self attention
128
+ attn_output, _ = self.self_attention(x, x, x)
129
+ x = self.norm1(x + attn_output)
130
+
131
+ # FFN
132
+ ffn_output = self.ffn(x)
133
+ x = self.norm2(x + ffn_output)
134
+
135
+ return x
136
+
137
+
138
+ class ModalityFusion(nn.Module):
139
+ """
140
+ Fuses embeddings from multiple modalities into a unified representation.
141
+
142
+ Supports:
143
+ - Simple concatenation + projection
144
+ - Attention-based fusion
145
+ - Transformer-based fusion with early exit support
146
+ """
147
+
148
+ def __init__(
149
+ self,
150
+ input_dim: int = 1024,
151
+ hidden_dim: int = 1024,
152
+ output_dim: int = 1024,
153
+ num_modalities: int = 3, # text, image, audio
154
+ fusion_type: str = "attention", # simple, attention, transformer
155
+ num_fusion_layers: int = 4,
156
+ num_heads: int = 8,
157
+ dropout: float = 0.1,
158
+ enable_layer_outputs: bool = True,
159
+ ):
160
+ super().__init__()
161
+
162
+ self.input_dim = input_dim
163
+ self.hidden_dim = hidden_dim
164
+ self.output_dim = output_dim
165
+ self.num_modalities = num_modalities
166
+ self.fusion_type = fusion_type
167
+ self.num_fusion_layers = num_fusion_layers
168
+ self.enable_layer_outputs = enable_layer_outputs
169
+
170
+ # Modality type embeddings
171
+ self.modality_embeddings = nn.Embedding(num_modalities, hidden_dim)
172
+
173
+ # Input projections for each modality
174
+ self.input_projections = nn.ModuleDict(
175
+ {
176
+ "text": ModalityProjector(input_dim, hidden_dim),
177
+ "image": ModalityProjector(input_dim, hidden_dim),
178
+ "audio": ModalityProjector(input_dim, hidden_dim),
179
+ }
180
+ )
181
+
182
+ if fusion_type == "simple":
183
+ # Simple concatenation + MLP
184
+ self.fusion = nn.Sequential(
185
+ nn.Linear(hidden_dim * num_modalities, hidden_dim),
186
+ nn.LayerNorm(hidden_dim),
187
+ nn.GELU(),
188
+ nn.Linear(hidden_dim, output_dim),
189
+ )
190
+
191
+ elif fusion_type == "attention":
192
+ # Cross-modal attention
193
+ self.cross_attention = CrossModalAttention(
194
+ hidden_dim=hidden_dim,
195
+ num_heads=num_heads,
196
+ dropout=dropout,
197
+ )
198
+ self.output_projection = nn.Linear(hidden_dim, output_dim)
199
+
200
+ elif fusion_type == "transformer":
201
+ # Full transformer fusion
202
+ self.fusion_layers = nn.ModuleList(
203
+ [
204
+ FusionTransformerBlock(
205
+ hidden_dim=hidden_dim,
206
+ num_heads=num_heads,
207
+ dropout=dropout,
208
+ )
209
+ for _ in range(num_fusion_layers)
210
+ ]
211
+ )
212
+ self.output_projection = nn.Linear(hidden_dim, output_dim)
213
+
214
+ # Per-layer projections for 2DMSE
215
+ if enable_layer_outputs:
216
+ self.layer_projections = nn.ModuleList(
217
+ [
218
+ nn.Linear(hidden_dim, output_dim)
219
+ for _ in range(num_fusion_layers)
220
+ ]
221
+ )
222
+ self.layer_norms = nn.ModuleList(
223
+ [nn.LayerNorm(hidden_dim) for _ in range(num_fusion_layers)]
224
+ )
225
+
226
+ else:
227
+ raise ValueError(f"Unknown fusion type: {fusion_type}")
228
+
229
+ def _project_modalities(
230
+ self,
231
+ embeddings: dict[str, torch.Tensor],
232
+ ) -> tuple[dict[str, torch.Tensor], int, torch.device]:
233
+ """Project available modalities and attach learned modality embeddings."""
234
+ available = {
235
+ name: value for name, value in embeddings.items() if value is not None
236
+ }
237
+ if not available:
238
+ raise ValueError("At least one modality embedding must be provided")
239
+
240
+ first_embedding = next(iter(available.values()))
241
+ batch_size = first_embedding.shape[0]
242
+ device = first_embedding.device
243
+ modality_idx = {"text": 0, "image": 1, "audio": 2}
244
+ projected = {}
245
+ for modality, embedding in available.items():
246
+ if embedding.shape[0] != batch_size:
247
+ raise ValueError(
248
+ "All modality embeddings must have the same batch size"
249
+ )
250
+ projection = self.input_projections[modality](embedding)
251
+ type_embedding = self.modality_embeddings(
252
+ torch.tensor([modality_idx[modality]], device=device)
253
+ ).expand(batch_size, -1)
254
+ projected[modality] = projection + type_embedding
255
+ return projected, batch_size, device
256
+
257
+ def _simple_fusion(
258
+ self,
259
+ projected: dict[str, torch.Tensor],
260
+ batch_size: int,
261
+ device: torch.device,
262
+ ) -> torch.Tensor:
263
+ """Concatenate projected modalities, padding missing inputs with zeros."""
264
+ modality_list = [
265
+ projected.get(
266
+ modality,
267
+ torch.zeros(batch_size, self.hidden_dim, device=device),
268
+ )
269
+ for modality in ("text", "image", "audio")
270
+ ]
271
+ return self.fusion(torch.cat(modality_list, dim=-1))
272
+
273
+ def _attention_fusion(
274
+ self,
275
+ projected: dict[str, torch.Tensor],
276
+ ) -> torch.Tensor:
277
+ """Fuse available modalities with cross-modal attention."""
278
+ available = list(projected.values())
279
+ if len(available) == 1:
280
+ return self.output_projection(available[0])
281
+ stacked = torch.stack(available, dim=1)
282
+ query = stacked.mean(dim=1, keepdim=True)
283
+ fused = self.cross_attention(query, stacked, stacked)
284
+ return self.output_projection(fused.squeeze(1))
285
+
286
+ def _transformer_fusion(
287
+ self,
288
+ projected: dict[str, torch.Tensor],
289
+ target_layer: int | None,
290
+ ) -> torch.Tensor:
291
+ """Fuse available modalities through the transformer stack."""
292
+ available = list(projected.values())
293
+ x = (
294
+ available[0].unsqueeze(1)
295
+ if len(available) == 1
296
+ else torch.stack(available, dim=1)
297
+ )
298
+ for layer_idx, layer in enumerate(self.fusion_layers):
299
+ x = layer(x)
300
+ if target_layer is None or layer_idx != target_layer:
301
+ continue
302
+ pooled = x.mean(dim=1)
303
+ if self.enable_layer_outputs:
304
+ normalized = self.layer_norms[layer_idx](x)
305
+ return self.layer_projections[layer_idx](normalized.mean(dim=1))
306
+ return self.output_projection(pooled)
307
+ return self.output_projection(x.mean(dim=1))
308
+
309
+ def forward(
310
+ self,
311
+ embeddings: dict[str, torch.Tensor],
312
+ target_layer: int | None = None, # For 2DMSE
313
+ target_dim: int | None = None, # For MRL
314
+ normalize: bool = True,
315
+ ) -> torch.Tensor:
316
+ """
317
+ Fuse modality embeddings.
318
+
319
+ Args:
320
+ embeddings: Dict with keys 'text', 'image', 'audio' and embedding tensors
321
+ target_layer: Exit at this fusion layer (transformer mode only)
322
+ target_dim: Truncate output to this dimension
323
+ normalize: Whether to L2 normalize output
324
+
325
+ Returns:
326
+ fused_embedding: [batch_size, output_dim]
327
+ """
328
+ projected, batch_size, device = self._project_modalities(embeddings)
329
+ if self.fusion_type == "simple":
330
+ output = self._simple_fusion(projected, batch_size, device)
331
+ elif self.fusion_type == "attention":
332
+ output = self._attention_fusion(projected)
333
+ else:
334
+ output = self._transformer_fusion(projected, target_layer)
335
+
336
+ # Dimension truncation (MRL)
337
+ if target_dim is not None:
338
+ output = output[:, :target_dim]
339
+
340
+ # Normalize
341
+ if normalize:
342
+ output = functional.normalize(output, p=2, dim=-1)
343
+
344
+ return output
omni_components/image_encoder.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Image encoder based on SigLIP 2 / ViT architecture."""
2
+
3
+ import logging
4
+ from typing import Any
5
+
6
+ import torch
7
+ from PIL import Image
8
+ from torch import nn
9
+ from torch.nn import functional
10
+ from transformers import AutoConfig, AutoModel, AutoProcessor
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ class ImageEncoder(nn.Module):
16
+ """
17
+ Image encoder using SigLIP 2 / ViT architecture.
18
+
19
+ Default: SigLIP 2 SO400M (384px, 400M params)
20
+ - SOTA vision encoder for multimodal learning
21
+ - Multilingual support
22
+ - Apache 2.0 license
23
+
24
+ Supports adaptive layer exit (2DMSE) and dimension truncation (MRL).
25
+ """
26
+
27
+ def __init__(self, model_name_or_path, revision=None, output_dim=384,
28
+ pooling_mode="mean", normalize=True, enable_layer_outputs=True,
29
+ legacy=False):
30
+ super().__init__()
31
+ from transformers import AutoImageProcessor, SiglipVisionModel
32
+ self.model_name = str(model_name_or_path)
33
+ self.revision = revision
34
+ self.output_dim = output_dim
35
+ self.pooling_mode = pooling_mode
36
+ self.normalize = normalize
37
+ self.enable_layer_outputs = enable_layer_outputs
38
+ self.is_siglip = True
39
+ self.is_siglip2 = False
40
+ self.config = AutoConfig.from_pretrained(model_name_or_path,
41
+ local_files_only=True, trust_remote_code=False)
42
+ self.processor = AutoImageProcessor.from_pretrained(model_name_or_path,
43
+ local_files_only=True, trust_remote_code=False, use_fast=False)
44
+ if legacy:
45
+ self.encoder = AutoModel.from_config(self.config, attn_implementation="sdpa")
46
+ self.vision_encoder = self.encoder.vision_model
47
+ else:
48
+ self.config.vision_config._attn_implementation = "sdpa"
49
+ self.vision_encoder = SiglipVisionModel(self.config.vision_config).vision_model
50
+ self.hidden_size = self.config.vision_config.hidden_size
51
+ self.num_layers = self.config.vision_config.num_hidden_layers
52
+ self.projection = nn.Linear(self.hidden_size, output_dim) if self.hidden_size != output_dim else nn.Identity()
53
+ self.layer_projections = nn.ModuleList([
54
+ nn.Linear(self.hidden_size, output_dim) for _ in range(self.num_layers)
55
+ ]) if enable_layer_outputs else None
56
+
57
+
58
+ def _pool(self, hidden_states: torch.Tensor) -> torch.Tensor:
59
+ """Pool hidden states to get image embedding."""
60
+ if self.pooling_mode == "mean":
61
+ # Skip CLS token if present, average over patches
62
+ if hidden_states.shape[1] > 1:
63
+ return hidden_states[:, 1:].mean(dim=1)
64
+ return hidden_states.mean(dim=1)
65
+ elif self.pooling_mode == "cls":
66
+ return hidden_states[:, 0]
67
+ else:
68
+ raise ValueError(f"Unknown pooling mode: {self.pooling_mode}")
69
+
70
+ def preprocess(
71
+ self,
72
+ images: Image.Image | list[Image.Image] | torch.Tensor,
73
+ ) -> torch.Tensor:
74
+ """Preprocess images for the encoder."""
75
+ if isinstance(images, torch.Tensor):
76
+ return images
77
+
78
+ if isinstance(images, Image.Image):
79
+ images = [images]
80
+
81
+ processed = self.processor(images=images, return_tensors="pt")
82
+ return processed["pixel_values"]
83
+
84
+ def _prepare_pixel_values(
85
+ self,
86
+ pixel_values: torch.Tensor | None,
87
+ images: Image.Image | list[Image.Image] | None,
88
+ ) -> torch.Tensor | None:
89
+ """Preprocess raw images and move them to the encoder device."""
90
+ if pixel_values is not None or images is None:
91
+ return pixel_values
92
+ prepared = self.preprocess(images)
93
+ parameter = next(self.parameters(), None)
94
+ device = (
95
+ parameter.device
96
+ if parameter is not None
97
+ else torch.device("cuda" if torch.cuda.is_available() else "cpu")
98
+ )
99
+ return prepared.to(device)
100
+
101
+ @staticmethod
102
+ def _hidden_states(outputs: Any) -> tuple[torch.Tensor, ...] | None:
103
+ """Return encoder-layer states without the input embedding state."""
104
+ hidden_states = getattr(outputs, "hidden_states", None)
105
+ return hidden_states[1:] if hidden_states is not None else None
106
+
107
+ def _project_layer(
108
+ self,
109
+ hidden_states: torch.Tensor,
110
+ layer_idx: int,
111
+ ) -> torch.Tensor:
112
+ """Pool and project one intermediate vision layer."""
113
+ pooled = self._pool(hidden_states)
114
+ if self.layer_projections is not None:
115
+ return self.layer_projections[layer_idx](pooled)
116
+ return self.projection(pooled)
117
+
118
+ def _select_embedding(
119
+ self,
120
+ outputs: Any,
121
+ all_hidden_states: tuple[torch.Tensor, ...] | None,
122
+ target_layer: int | None,
123
+ ) -> torch.Tensor:
124
+ """Select either an intermediate 2DMSE layer or the final output."""
125
+ if target_layer is not None and all_hidden_states is not None:
126
+ layer_idx = min(target_layer, len(all_hidden_states) - 1)
127
+ return self._project_layer(all_hidden_states[layer_idx], layer_idx)
128
+ pooled = getattr(outputs, "pooler_output", None)
129
+ if pooled is None:
130
+ pooled = self._pool(outputs.last_hidden_state)
131
+ return self.projection(pooled)
132
+
133
+ def _all_layer_embeddings(
134
+ self,
135
+ all_hidden_states: tuple[torch.Tensor, ...],
136
+ ) -> list[torch.Tensor]:
137
+ """Project every vision layer for confidence-based exit training."""
138
+ embeddings = []
139
+ for layer_idx, hidden_states in enumerate(all_hidden_states):
140
+ embedding = self._project_layer(hidden_states, layer_idx)
141
+ if self.normalize:
142
+ embedding = functional.normalize(embedding, p=2, dim=-1)
143
+ embeddings.append(embedding)
144
+ return embeddings
145
+
146
+ def forward(
147
+ self,
148
+ pixel_values: torch.Tensor | None = None,
149
+ images: Image.Image | list[Image.Image] | None = None,
150
+ target_layer: int | None = None,
151
+ target_dim: int | None = None,
152
+ return_all_layers: bool = False,
153
+ ) -> torch.Tensor | tuple[torch.Tensor, list[torch.Tensor]]:
154
+ """
155
+ Forward pass for image encoding.
156
+
157
+ Args:
158
+ pixel_values: Preprocessed image tensors
159
+ images: Raw PIL images
160
+ target_layer: Exit at this layer (2DMSE)
161
+ target_dim: Truncate to this dimension (MRL)
162
+ return_all_layers: Return embeddings from all layers
163
+ """
164
+ pixel_values = self._prepare_pixel_values(pixel_values, images)
165
+
166
+ # Forward through encoder
167
+ outputs = self.vision_encoder(
168
+ pixel_values=pixel_values,
169
+ output_hidden_states=self.enable_layer_outputs or return_all_layers,
170
+ )
171
+
172
+ all_hidden_states = self._hidden_states(outputs)
173
+ embedding = self._select_embedding(outputs, all_hidden_states, target_layer)
174
+
175
+ # Dimension truncation (MRL)
176
+ if target_dim is not None:
177
+ embedding = embedding[:, :target_dim]
178
+
179
+ # Normalize
180
+ if self.normalize:
181
+ embedding = functional.normalize(embedding, p=2, dim=-1)
182
+
183
+ # Return all layer embeddings if requested
184
+ if return_all_layers and all_hidden_states is not None:
185
+ return embedding, self._all_layer_embeddings(all_hidden_states)
186
+
187
+ return embedding
188
+
189
+ def encode(
190
+ self,
191
+ images: list[Image.Image],
192
+ batch_size: int = 32,
193
+ target_layer: int | None = None,
194
+ target_dim: int | None = None,
195
+ **kwargs,
196
+ ) -> torch.Tensor:
197
+ """Encode images into embeddings."""
198
+ all_embeddings = []
199
+
200
+ for i in range(0, len(images), batch_size):
201
+ batch_images = images[i : i + batch_size]
202
+ with torch.no_grad():
203
+ embeddings = self.forward(
204
+ images=batch_images,
205
+ target_layer=target_layer,
206
+ target_dim=target_dim,
207
+ **kwargs,
208
+ )
209
+ all_embeddings.append(embeddings.cpu())
210
+
211
+ return torch.cat(all_embeddings, dim=0)
212
+
213
+
214
+ # Legacy alias for backward compatibility
215
+ DiffusionImageEncoder = ImageEncoder # Deprecated
omni_components/mini.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import defaultdict
2
+ from collections.abc import Callable
3
+ from typing import Any
4
+
5
+ from .audio_io import librosa
6
+ import torch
7
+ from PIL import Image
8
+ from torch import nn
9
+ from torch.nn import functional
10
+ from torch.nn.utils.rnn import pad_sequence
11
+ from transformers import AutoModel, AutoProcessor, WhisperFeatureExtractor, WhisperModel
12
+
13
+ from .records import PairItem
14
+
15
+
16
+ class MultiModalSentenceEmbedder(nn.Module):
17
+ def __init__(self, component_dir, legacy=False):
18
+ super().__init__()
19
+ from pathlib import Path
20
+ from transformers import AutoConfig, AutoImageProcessor, SiglipVisionModel, Siglip2VisionModel, WhisperConfig
21
+ from transformers.models.whisper.modeling_whisper import WhisperEncoder
22
+ from .text_backbone import TextBackbone
23
+ root = Path(component_dir)
24
+ self.text_model = TextBackbone(root / "text", max_length=32768)
25
+ image_config = AutoConfig.from_pretrained(root / "image", local_files_only=True,
26
+ trust_remote_code=False)
27
+ if legacy:
28
+ self.image_model = AutoModel.from_config(image_config, attn_implementation="sdpa")
29
+ else:
30
+ image_config.vision_config._attn_implementation = "sdpa"
31
+ vision_class = {"siglip": SiglipVisionModel, "siglip2": Siglip2VisionModel}[image_config.model_type]
32
+ self.image_model = vision_class(image_config.vision_config)
33
+ self.image_processor = AutoImageProcessor.from_pretrained(root / "image",
34
+ local_files_only=True, trust_remote_code=False, use_fast=False)
35
+ audio_config = WhisperConfig.from_pretrained(root / "audio", local_files_only=True)
36
+ audio_config._attn_implementation = "sdpa"
37
+ self.audio_model = WhisperEncoder(audio_config)
38
+ self.audio_processor = WhisperFeatureExtractor.from_pretrained(root / "audio",
39
+ local_files_only=True)
40
+ self.text_proj = nn.Identity()
41
+ self.image_proj = nn.Linear(image_config.vision_config.hidden_size, 768)
42
+ self.audio_proj = nn.Linear(audio_config.d_model, 768)
43
+
44
+
45
+ @staticmethod
46
+ def _get_vision_dim(model: nn.Module) -> int:
47
+ if hasattr(model, "vision_model") and hasattr(model.config, "vision_config"):
48
+ return int(model.config.vision_config.hidden_size)
49
+ if hasattr(model.config, "hidden_size"):
50
+ return int(model.config.hidden_size)
51
+ raise ValueError("Could not infer image hidden size")
52
+
53
+ def _encode_text(self, texts: list[Any]) -> torch.Tensor:
54
+ device = next(self.parameters()).device
55
+ normalized: list[torch.Tensor | None] = [None] * len(texts)
56
+
57
+ dict_positions = [
58
+ idx for idx, item in enumerate(texts) if isinstance(item, dict)
59
+ ]
60
+ if dict_positions:
61
+ pad_values = {
62
+ "input_ids": 0,
63
+ "attention_mask": 0,
64
+ "token_type_ids": 0,
65
+ }
66
+ dict_items = [texts[idx] for idx in dict_positions]
67
+ features = {
68
+ key: pad_sequence(
69
+ [item[key].detach().cpu() for item in dict_items],
70
+ batch_first=True,
71
+ padding_value=pad_values.get(key, 0),
72
+ ).to(device)
73
+ for key in dict_items[0]
74
+ }
75
+ out = self.text_model(features)
76
+ emb = functional.normalize(
77
+ self.text_proj(out["sentence_embedding"]), p=2, dim=-1
78
+ )
79
+ for loc, row in zip(dict_positions, emb, strict=False):
80
+ normalized[loc] = row
81
+
82
+ raw_positions = [
83
+ idx for idx, item in enumerate(texts) if not isinstance(item, dict)
84
+ ]
85
+ if raw_positions:
86
+ raw_texts = [texts[idx] for idx in raw_positions]
87
+ features = self.text_model.tokenize(raw_texts)
88
+ features = {
89
+ k: (v.to(device) if hasattr(v, "to") else v)
90
+ for k, v in features.items()
91
+ }
92
+ out = self.text_model(features)
93
+ emb = functional.normalize(
94
+ self.text_proj(out["sentence_embedding"]), p=2, dim=-1
95
+ )
96
+ for loc, row in zip(raw_positions, emb, strict=False):
97
+ normalized[loc] = row
98
+
99
+ return torch.stack([row for row in normalized if row is not None], dim=0)
100
+
101
+ def _encode_image_paths(self, paths: list[str]) -> torch.Tensor:
102
+ images = [Image.open(path).convert("RGB") for path in paths]
103
+ proc = self.image_processor(images=images, return_tensors="pt")
104
+ device = next(self.parameters()).device
105
+ proc = {k: v.to(device) for k, v in proc.items()}
106
+ return self._encode_image_pixel_values(proc["pixel_values"])
107
+
108
+ def _encode_image_pixel_values(self, pixel_values: torch.Tensor) -> torch.Tensor:
109
+ device = next(self.parameters()).device
110
+ proc = {"pixel_values": pixel_values.to(device)}
111
+ if hasattr(self.image_model, "vision_model"):
112
+ out = self.image_model.vision_model(**proc, output_hidden_states=False)
113
+ hidden = out.last_hidden_state
114
+ else:
115
+ out = self.image_model(**proc, output_hidden_states=False)
116
+ hidden = out.last_hidden_state
117
+ pooled = (
118
+ hidden[:, 1:].mean(dim=1) if hidden.shape[1] > 1 else hidden.mean(dim=1)
119
+ )
120
+ emb = self.image_proj(pooled)
121
+ return functional.normalize(emb, p=2, dim=-1)
122
+
123
+ def _encode_audio_paths(self, paths: list[str]) -> torch.Tensor:
124
+ waves = [librosa.load(path, sr=16000, mono=True)[0] for path in paths]
125
+ proc = self.audio_processor(waves, sampling_rate=16000, return_tensors="pt")
126
+ return self._encode_audio_features(proc["input_features"])
127
+
128
+ def _encode_audio_features(self, input_features: torch.Tensor) -> torch.Tensor:
129
+ device = next(self.parameters()).device
130
+ input_features = input_features.to(device)
131
+ input_features = input_features.to(self.audio_model.conv1.weight.dtype)
132
+ out = self.audio_model(
133
+ input_features=input_features, output_hidden_states=False
134
+ )
135
+ pooled = out.last_hidden_state.mean(dim=1)
136
+ emb = self.audio_proj(pooled)
137
+ return functional.normalize(emb, p=2, dim=-1)
138
+
139
+ @staticmethod
140
+ def _stack_tensor_values(values: list[Any]) -> torch.Tensor:
141
+ tensors = []
142
+ for value in values:
143
+ if not torch.is_tensor(value):
144
+ raise TypeError("Expected tensor payload in cached item")
145
+ tensor = value.detach().cpu()
146
+ if tensor.dim() > 0 and tensor.shape[0] == 1:
147
+ tensor = tensor.squeeze(0)
148
+ tensors.append(tensor)
149
+ return torch.stack(tensors, dim=0)
150
+
151
+ @staticmethod
152
+ def _assign_embeddings(
153
+ output: list[torch.Tensor | None],
154
+ positions: tuple[int, ...],
155
+ embeddings: torch.Tensor,
156
+ ) -> None:
157
+ for position, embedding in zip(positions, embeddings, strict=True):
158
+ output[position] = embedding
159
+
160
+ @staticmethod
161
+ def _partition_payloads(
162
+ pairs: list[tuple[int, Any]],
163
+ ) -> tuple[list[tuple[int, Any]], list[tuple[int, Any]]]:
164
+ tensor_pairs = [(idx, value) for idx, value in pairs if torch.is_tensor(value)]
165
+ path_pairs = [
166
+ (idx, value) for idx, value in pairs if not torch.is_tensor(value)
167
+ ]
168
+ return tensor_pairs, path_pairs
169
+
170
+ def _encode_text_group(
171
+ self, output: list[torch.Tensor | None], pairs: list[tuple[int, Any]]
172
+ ) -> None:
173
+ positions, values = zip(*pairs, strict=True)
174
+ self._assign_embeddings(output, positions, self._encode_text(list(values)))
175
+
176
+ def _encode_media_group(
177
+ self,
178
+ output: list[torch.Tensor | None],
179
+ pairs: list[tuple[int, Any]],
180
+ path_encoder: Callable[[list[Any]], torch.Tensor],
181
+ tensor_encoder: Callable[[torch.Tensor], torch.Tensor],
182
+ ) -> None:
183
+ tensor_pairs, path_pairs = self._partition_payloads(pairs)
184
+ if path_pairs:
185
+ positions, values = zip(*path_pairs, strict=True)
186
+ self._assign_embeddings(output, positions, path_encoder(list(values)))
187
+ if tensor_pairs:
188
+ positions, values = zip(*tensor_pairs, strict=True)
189
+ tensors = self._stack_tensor_values(list(values))
190
+ self._assign_embeddings(output, positions, tensor_encoder(tensors))
191
+
192
+ def encode_items(self, items: list[PairItem]) -> torch.Tensor:
193
+ grouped: dict[str, list[tuple[int, Any]]] = defaultdict(list)
194
+ for idx, item in enumerate(items):
195
+ grouped[item.modality].append((idx, item.value))
196
+
197
+ device = next(self.parameters()).device
198
+ output: list[torch.Tensor | None] = [None] * len(items)
199
+
200
+ if grouped["text"]:
201
+ self._encode_text_group(output, grouped["text"])
202
+
203
+ if grouped["image"]:
204
+ self._encode_media_group(
205
+ output,
206
+ grouped["image"],
207
+ self._encode_image_paths,
208
+ self._encode_image_pixel_values,
209
+ )
210
+
211
+ if grouped["audio"]:
212
+ self._encode_media_group(
213
+ output,
214
+ grouped["audio"],
215
+ self._encode_audio_paths,
216
+ self._encode_audio_features,
217
+ )
218
+
219
+ if any(embedding is None for embedding in output):
220
+ raise ValueError("Every item must use a supported modality")
221
+ stacked = torch.stack(output, dim=0).to(device=device, dtype=torch.float32)
222
+ return functional.normalize(stacked, p=2, dim=-1)
223
+
224
+
225
+ def multiple_negatives_ranking_loss(
226
+ anchor: torch.Tensor, positive: torch.Tensor, scale: float = 20.0
227
+ ) -> torch.Tensor:
228
+ scores = torch.matmul(anchor, positive.T) * scale
229
+ labels = torch.arange(scores.shape[0], device=scores.device)
230
+ loss_a = torch.nn.functional.cross_entropy(scores, labels)
231
+ loss_b = torch.nn.functional.cross_entropy(scores.T, labels)
232
+ return (loss_a + loss_b) * 0.5
omni_components/records.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from typing import Any
3
+
4
+ @dataclass
5
+ class PairItem:
6
+ modality: str
7
+ value: Any
omni_components/text_backbone.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Native encoder and mean pooling with the Sentence Transformers state layout."""
2
+ import json
3
+ from pathlib import Path
4
+
5
+ import torch
6
+ from torch import nn
7
+ from transformers import AutoConfig, AutoModel, AutoTokenizer
8
+
9
+ class Transformer(nn.Module):
10
+ def __init__(self, config):
11
+ super().__init__()
12
+ self.model = AutoModel.from_config(config, attn_implementation="sdpa")
13
+
14
+ class TextBackbone(nn.Sequential):
15
+ def __init__(self, directory, max_length):
16
+ directory = Path(directory)
17
+ raw = json.loads((directory / "config.json").read_text())
18
+ config = AutoConfig.from_pretrained(directory, local_files_only=True,
19
+ trust_remote_code=False)
20
+ if config.model_type != "modernbert":
21
+ raise ValueError("Mini requires a ModernBERT text encoder")
22
+ # Saved current foundation uses native 4.57 fields. Refuse ambiguous v5 RoPE.
23
+ if raw.get("rope_parameters"):
24
+ if raw.get("rope_scaling"):
25
+ raise ValueError("Ambiguous saved rotary configuration")
26
+ for layer, field in (("full_attention", "global_rope_theta"),
27
+ ("sliding_attention", "local_rope_theta")):
28
+ block = raw["rope_parameters"][layer]
29
+ if block.get("rope_type", "default") != "default":
30
+ raise ValueError("Unsupported nested rotary configuration")
31
+ theta = float(block["rope_theta"])
32
+ if not torch.isfinite(torch.tensor(theta)) or theta <= 0:
33
+ raise ValueError("Invalid rotary theta")
34
+ if field in raw and float(raw[field]) != theta:
35
+ raise ValueError("Conflicting rotary theta")
36
+ setattr(config, field, theta)
37
+ config.reference_compile = False
38
+ pool = json.loads((directory / "1_Pooling/config.json").read_text())
39
+ enabled = [key for key, value in pool.items() if key.startswith("pooling_mode_") and value]
40
+ if enabled != ["pooling_mode_mean_tokens"] or pool.get("include_prompt", True) is not True:
41
+ raise ValueError("Unsupported saved pooling contract")
42
+ super().__init__(Transformer(config))
43
+ self.tokenizer = AutoTokenizer.from_pretrained(directory, local_files_only=True,
44
+ trust_remote_code=False)
45
+ self.max_seq_length = max_length
46
+ sentence_config = json.loads((directory / "sentence_bert_config.json").read_text())
47
+ self.do_lower_case = sentence_config.get("do_lower_case", False)
48
+
49
+ def tokenize(self, texts):
50
+ texts = [str(text).strip() for text in texts]
51
+ if self.do_lower_case:
52
+ texts = [text.lower() for text in texts]
53
+ return self.tokenizer(texts, padding=True, truncation="longest_first",
54
+ max_length=self.max_seq_length, return_tensors="pt")
55
+
56
+ def forward(self, features):
57
+ outputs = self[0].model(**features)
58
+ tokens = outputs.last_hidden_state
59
+ mask = features["attention_mask"].unsqueeze(-1).expand(tokens.size()).to(tokens.dtype)
60
+ return {"sentence_embedding": torch.sum(tokens * mask, 1) / torch.clamp(mask.sum(1), min=1e-9)}
omni_components/text_encoder.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Text encoder supporting 2D Matryoshka (layer exit + dimension truncation)."""
2
+
3
+ import logging
4
+ from typing import Any
5
+
6
+ import torch
7
+ from torch import nn
8
+ from torch.nn import functional
9
+ from transformers import AutoConfig, AutoModel, AutoTokenizer
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ class TextEncoder(nn.Module):
15
+ """
16
+ Text encoder with 2D Matryoshka support.
17
+
18
+ Default model: mmbert-embed-32k-2d-matryoshka
19
+ - 32K context length
20
+ - 1800+ languages
21
+ - Built-in layer exit (2DMSE)
22
+ - Built-in dimension truncation (MRL)
23
+ """
24
+
25
+ def __init__(self, model_name_or_path, revision=None, output_dim=384,
26
+ pooling_mode="mean", normalize=True, max_length=128,
27
+ enable_layer_outputs=True):
28
+ super().__init__()
29
+ self.model_name = str(model_name_or_path)
30
+ self.revision = revision
31
+ self.output_dim = output_dim
32
+ self.pooling_mode = pooling_mode
33
+ self.normalize = normalize
34
+ self.max_length = max_length
35
+ self.enable_layer_outputs = enable_layer_outputs
36
+ self.is_mmbert = False
37
+ self.config = AutoConfig.from_pretrained(model_name_or_path, local_files_only=True,
38
+ trust_remote_code=False)
39
+ self.encoder = AutoModel.from_config(self.config, attn_implementation="sdpa")
40
+ self.tokenizer = AutoTokenizer.from_pretrained(model_name_or_path,
41
+ local_files_only=True, trust_remote_code=False)
42
+ self.hidden_size = self.config.hidden_size
43
+ self.num_layers = self.config.num_hidden_layers
44
+ self.layer_projections = None
45
+ if self.hidden_size != output_dim:
46
+ self.projection = nn.Linear(self.hidden_size, output_dim)
47
+ if enable_layer_outputs:
48
+ self.layer_projections = nn.ModuleList([
49
+ nn.Linear(self.hidden_size, output_dim) for _ in range(self.num_layers)])
50
+ else:
51
+ self.projection = nn.Identity()
52
+
53
+
54
+ def _pool(
55
+ self,
56
+ hidden_states: torch.Tensor,
57
+ attention_mask: torch.Tensor | None = None,
58
+ ) -> torch.Tensor:
59
+ """Pool hidden states to get sentence embedding."""
60
+ if self.pooling_mode == "mean":
61
+ if attention_mask is not None:
62
+ mask = attention_mask.unsqueeze(-1).float()
63
+ hidden_states = hidden_states * mask
64
+ return hidden_states.sum(dim=1) / mask.sum(dim=1).clamp(min=1e-9)
65
+ return hidden_states.mean(dim=1)
66
+ elif self.pooling_mode == "cls":
67
+ return hidden_states[:, 0]
68
+ elif self.pooling_mode == "last":
69
+ if attention_mask is not None:
70
+ seq_lens = attention_mask.sum(dim=1) - 1
71
+ batch_size = hidden_states.shape[0]
72
+ return hidden_states[
73
+ torch.arange(batch_size, device=hidden_states.device), seq_lens
74
+ ]
75
+ return hidden_states[:, -1]
76
+ else:
77
+ raise ValueError(f"Unknown pooling mode: {self.pooling_mode}")
78
+
79
+ def _apply_final_norm(self, hidden_states: torch.Tensor) -> torch.Tensor:
80
+ """Apply final layer norm if available (for mmBERT layer exit)."""
81
+ if hasattr(self.encoder, "final_norm"):
82
+ return self.encoder.final_norm(hidden_states)
83
+ elif hasattr(self.encoder, "norm"):
84
+ return self.encoder.norm(hidden_states)
85
+ return hidden_states
86
+
87
+ def _prepare_inputs(
88
+ self,
89
+ input_ids: torch.Tensor | None,
90
+ attention_mask: torch.Tensor | None,
91
+ texts: list[str] | None,
92
+ ) -> tuple[torch.Tensor | None, torch.Tensor | None]:
93
+ """Tokenize raw text and move tensors to the encoder device."""
94
+ if input_ids is not None or texts is None:
95
+ return input_ids, attention_mask
96
+ encoded = self.tokenizer(
97
+ texts,
98
+ padding=True,
99
+ truncation=True,
100
+ max_length=self.max_length,
101
+ return_tensors="pt",
102
+ )
103
+ parameter = next(self.parameters(), None)
104
+ device = (
105
+ parameter.device
106
+ if parameter is not None
107
+ else torch.device("cuda" if torch.cuda.is_available() else "cpu")
108
+ )
109
+ return encoded["input_ids"].to(device), encoded["attention_mask"].to(device)
110
+
111
+ @staticmethod
112
+ def _hidden_states(outputs: Any) -> tuple[torch.Tensor, ...] | None:
113
+ """Return encoder-layer states without the input embedding state."""
114
+ hidden_states = getattr(outputs, "hidden_states", None)
115
+ return hidden_states[1:] if hidden_states else None
116
+
117
+ def _project_layer(
118
+ self,
119
+ hidden_states: torch.Tensor,
120
+ attention_mask: torch.Tensor | None,
121
+ layer_idx: int | None = None,
122
+ ) -> torch.Tensor:
123
+ """Normalize, pool, and project one encoder layer."""
124
+ normalized = self._apply_final_norm(hidden_states)
125
+ pooled = self._pool(normalized, attention_mask)
126
+ if layer_idx is not None and self.layer_projections is not None:
127
+ return self.layer_projections[layer_idx](pooled)
128
+ return self.projection(pooled)
129
+
130
+ def _select_embedding(
131
+ self,
132
+ outputs: Any,
133
+ all_hidden_states: tuple[torch.Tensor, ...] | None,
134
+ attention_mask: torch.Tensor | None,
135
+ target_layer: int | None,
136
+ ) -> torch.Tensor:
137
+ """Select either an intermediate 2DMSE layer or the final layer."""
138
+ if target_layer is not None and all_hidden_states is not None:
139
+ layer_idx = min(target_layer, len(all_hidden_states) - 1)
140
+ return self._project_layer(
141
+ all_hidden_states[layer_idx],
142
+ attention_mask,
143
+ layer_idx,
144
+ )
145
+ return self.projection(self._pool(outputs.last_hidden_state, attention_mask))
146
+
147
+ def _all_layer_embeddings(
148
+ self,
149
+ all_hidden_states: tuple[torch.Tensor, ...],
150
+ attention_mask: torch.Tensor | None,
151
+ ) -> list[torch.Tensor]:
152
+ """Project every encoder layer for confidence-based exit training."""
153
+ embeddings = []
154
+ for layer_idx, hidden_states in enumerate(all_hidden_states):
155
+ embedding = self._project_layer(
156
+ hidden_states,
157
+ attention_mask,
158
+ layer_idx,
159
+ )
160
+ if self.normalize:
161
+ embedding = functional.normalize(embedding, p=2, dim=-1)
162
+ embeddings.append(embedding)
163
+ return embeddings
164
+
165
+ def forward(
166
+ self,
167
+ input_ids: torch.Tensor | None = None,
168
+ attention_mask: torch.Tensor | None = None,
169
+ texts: list[str] | None = None,
170
+ target_layer: int | None = None,
171
+ target_dim: int | None = None,
172
+ return_all_layers: bool = False,
173
+ ) -> torch.Tensor | tuple[torch.Tensor, list[torch.Tensor]]:
174
+ """
175
+ Forward pass for text encoding.
176
+
177
+ Args:
178
+ input_ids: Tokenized input IDs
179
+ attention_mask: Attention mask
180
+ texts: Raw text strings (tokenized if input_ids not provided)
181
+ target_layer: Exit at this layer (2DMSE)
182
+ target_dim: Truncate to this dimension (MRL)
183
+ return_all_layers: Return embeddings from all layers
184
+ """
185
+ input_ids, attention_mask = self._prepare_inputs(
186
+ input_ids,
187
+ attention_mask,
188
+ texts,
189
+ )
190
+
191
+ # Forward through encoder
192
+ outputs = self.encoder(
193
+ input_ids=input_ids,
194
+ attention_mask=attention_mask,
195
+ output_hidden_states=True,
196
+ )
197
+
198
+ all_hidden_states = self._hidden_states(outputs)
199
+ embedding = self._select_embedding(
200
+ outputs,
201
+ all_hidden_states,
202
+ attention_mask,
203
+ target_layer,
204
+ )
205
+
206
+ # Dimension truncation (MRL)
207
+ if target_dim is not None:
208
+ embedding = embedding[:, :target_dim]
209
+
210
+ # Normalize
211
+ if self.normalize:
212
+ embedding = functional.normalize(embedding, p=2, dim=-1)
213
+
214
+ # Return all layer embeddings if requested
215
+ if return_all_layers and all_hidden_states is not None:
216
+ return embedding, self._all_layer_embeddings(
217
+ all_hidden_states,
218
+ attention_mask,
219
+ )
220
+
221
+ return embedding
222
+
223
+ def encode(
224
+ self,
225
+ texts: list[str],
226
+ batch_size: int = 32,
227
+ target_layer: int | None = None,
228
+ target_dim: int | None = None,
229
+ **kwargs,
230
+ ) -> torch.Tensor:
231
+ """Encode texts into embeddings."""
232
+ all_embeddings = []
233
+
234
+ for i in range(0, len(texts), batch_size):
235
+ batch_texts = texts[i : i + batch_size]
236
+ with torch.no_grad():
237
+ embeddings = self.forward(
238
+ texts=batch_texts,
239
+ target_layer=target_layer,
240
+ target_dim=target_dim,
241
+ **kwargs,
242
+ )
243
+ all_embeddings.append(embeddings.cpu())
244
+
245
+ return torch.cat(all_embeddings, dim=0)
246
+
247
+
248
+ # Legacy alias for backward compatibility
249
+ DiffusionTextEncoder = TextEncoder # Deprecated
scores.json ADDED
@@ -0,0 +1,420 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "model": "llm-semantic-router/Vela-1.0-Omni-134M-Nano",
4
+ "revision_semantics": "self denotes the Hugging Face snapshot containing this file; the native artifact fingerprint binds its evaluated model files.",
5
+ "score_scale": "0-1; multiply by 100 for percentages",
6
+ "matrix": {
7
+ "embedding": {
8
+ "model": "llm-semantic-router/Vela-1.0-Encoder-307M-Embedding",
9
+ "revision": "972c180aecd2aa3fca97159098ab00d25d53fffb",
10
+ "artifact_fingerprint_sha256": "2b4747393b1e3e477fb1391a5d6817917362ab68fc5ae2436c769a7357a541ce",
11
+ "metrics": {
12
+ "text.banking77.accuracy": {
13
+ "numerator": 2464,
14
+ "denominator": 3080,
15
+ "value": 0.8
16
+ },
17
+ "text.massive-en.accuracy": {
18
+ "numerator": 2248,
19
+ "denominator": 2972,
20
+ "value": 0.756393001345895
21
+ }
22
+ },
23
+ "not_applicable": [
24
+ "image",
25
+ "audio"
26
+ ]
27
+ },
28
+ "small": {
29
+ "model": "llm-semantic-router/multi-modal-embed-small",
30
+ "revision": "fdf8e01b7b0f3a69ac1ac8e2a64dcb1ede177ba4",
31
+ "artifact_fingerprint_sha256": "684fe0c48a4ddd3944167f6e5dc75e97ada24e5b120bd9a2921f00dc03112eeb",
32
+ "metrics": {
33
+ "text.banking77.accuracy": {
34
+ "numerator": 2169,
35
+ "denominator": 3080,
36
+ "value": 0.7042207792207792
37
+ },
38
+ "text.massive-en.accuracy": {
39
+ "numerator": 1960,
40
+ "denominator": 2972,
41
+ "value": 0.6594885598923284
42
+ },
43
+ "image.image_to_text.recall@1": {
44
+ "numerator": 336,
45
+ "denominator": 823,
46
+ "value": 0.4082624544349939
47
+ },
48
+ "image.image_to_text.recall@5": {
49
+ "numerator": 553,
50
+ "denominator": 823,
51
+ "value": 0.6719319562575942
52
+ },
53
+ "image.image_to_text.recall@10": {
54
+ "numerator": 646,
55
+ "denominator": 823,
56
+ "value": 0.7849331713244229
57
+ },
58
+ "image.text_to_image.recall@1": {
59
+ "numerator": 1242,
60
+ "denominator": 4115,
61
+ "value": 0.3018226002430134
62
+ },
63
+ "image.text_to_image.recall@5": {
64
+ "numerator": 2445,
65
+ "denominator": 4115,
66
+ "value": 0.5941676792223572
67
+ },
68
+ "image.text_to_image.recall@10": {
69
+ "numerator": 3057,
70
+ "denominator": 4115,
71
+ "value": 0.7428918590522479
72
+ },
73
+ "audio.audio_to_text.recall@1": {
74
+ "numerator": 110,
75
+ "denominator": 2611,
76
+ "value": 0.04212945231711988
77
+ },
78
+ "audio.audio_to_text.recall@5": {
79
+ "numerator": 313,
80
+ "denominator": 2611,
81
+ "value": 0.11987744159325929
82
+ },
83
+ "audio.audio_to_text.recall@10": {
84
+ "numerator": 497,
85
+ "denominator": 2611,
86
+ "value": 0.1903485254691689
87
+ },
88
+ "audio.text_to_audio.recall@1": {
89
+ "numerator": 250,
90
+ "denominator": 2610,
91
+ "value": 0.09578544061302682
92
+ },
93
+ "audio.text_to_audio.recall@5": {
94
+ "numerator": 588,
95
+ "denominator": 2610,
96
+ "value": 0.22528735632183908
97
+ },
98
+ "audio.text_to_audio.recall@10": {
99
+ "numerator": 801,
100
+ "denominator": 2610,
101
+ "value": 0.30689655172413793
102
+ }
103
+ }
104
+ },
105
+ "large": {
106
+ "model": "llm-semantic-router/multi-modal-embed-large",
107
+ "revision": "e21cde3ccc414c56f504b322662f42c603a939ee",
108
+ "artifact_fingerprint_sha256": "8439b0c46c36d13a6371081cf7e40cf2c1cc7df68a2bf69e41d514452f65d549",
109
+ "metrics": {
110
+ "text.banking77.accuracy": {
111
+ "numerator": 2334,
112
+ "denominator": 3080,
113
+ "value": 0.7577922077922078
114
+ },
115
+ "text.massive-en.accuracy": {
116
+ "numerator": 2149,
117
+ "denominator": 2972,
118
+ "value": 0.7230820995962315
119
+ },
120
+ "image.image_to_text.recall@1": {
121
+ "numerator": 350,
122
+ "denominator": 823,
123
+ "value": 0.425273390036452
124
+ },
125
+ "image.image_to_text.recall@5": {
126
+ "numerator": 619,
127
+ "denominator": 823,
128
+ "value": 0.7521263669501823
129
+ },
130
+ "image.image_to_text.recall@10": {
131
+ "numerator": 721,
132
+ "denominator": 823,
133
+ "value": 0.8760631834750912
134
+ },
135
+ "image.text_to_image.recall@1": {
136
+ "numerator": 1442,
137
+ "denominator": 4115,
138
+ "value": 0.35042527339003643
139
+ },
140
+ "image.text_to_image.recall@5": {
141
+ "numerator": 2884,
142
+ "denominator": 4115,
143
+ "value": 0.7008505467800729
144
+ },
145
+ "image.text_to_image.recall@10": {
146
+ "numerator": 3453,
147
+ "denominator": 4115,
148
+ "value": 0.8391251518833536
149
+ },
150
+ "audio.audio_to_text.recall@1": {
151
+ "numerator": 1488,
152
+ "denominator": 2611,
153
+ "value": 0.5698965913443125
154
+ },
155
+ "audio.audio_to_text.recall@5": {
156
+ "numerator": 2137,
157
+ "denominator": 2611,
158
+ "value": 0.8184603600153199
159
+ },
160
+ "audio.audio_to_text.recall@10": {
161
+ "numerator": 2296,
162
+ "denominator": 2611,
163
+ "value": 0.8793565683646113
164
+ },
165
+ "audio.text_to_audio.recall@1": {
166
+ "numerator": 2051,
167
+ "denominator": 2610,
168
+ "value": 0.785823754789272
169
+ },
170
+ "audio.text_to_audio.recall@5": {
171
+ "numerator": 2454,
172
+ "denominator": 2610,
173
+ "value": 0.9402298850574713
174
+ },
175
+ "audio.text_to_audio.recall@10": {
176
+ "numerator": 2532,
177
+ "denominator": 2610,
178
+ "value": 0.9701149425287356
179
+ }
180
+ }
181
+ },
182
+ "candidate": {
183
+ "model": "llm-semantic-router/Vela-1.0-Omni-134M-Nano",
184
+ "revision": "self",
185
+ "artifact_fingerprint_sha256": "32f410c3febdbd02e3f790b907db482e4ae1d493e6a1c4eaab375ebada234f8b",
186
+ "metrics": {
187
+ "text.banking77.accuracy": {
188
+ "numerator": 2169,
189
+ "denominator": 3080,
190
+ "value": 0.7042207792207792
191
+ },
192
+ "text.massive-en.accuracy": {
193
+ "numerator": 1960,
194
+ "denominator": 2972,
195
+ "value": 0.6594885598923284
196
+ },
197
+ "image.image_to_text.recall@1": {
198
+ "numerator": 364,
199
+ "denominator": 823,
200
+ "value": 0.4422843256379101
201
+ },
202
+ "image.image_to_text.recall@5": {
203
+ "numerator": 601,
204
+ "denominator": 823,
205
+ "value": 0.7302551640340219
206
+ },
207
+ "image.image_to_text.recall@10": {
208
+ "numerator": 708,
209
+ "denominator": 823,
210
+ "value": 0.8602673147023087
211
+ },
212
+ "image.text_to_image.recall@1": {
213
+ "numerator": 1486,
214
+ "denominator": 4115,
215
+ "value": 0.3611178614823815
216
+ },
217
+ "image.text_to_image.recall@5": {
218
+ "numerator": 2828,
219
+ "denominator": 4115,
220
+ "value": 0.6872417982989064
221
+ },
222
+ "image.text_to_image.recall@10": {
223
+ "numerator": 3375,
224
+ "denominator": 4115,
225
+ "value": 0.8201701093560145
226
+ },
227
+ "audio.audio_to_text.recall@1": {
228
+ "numerator": 138,
229
+ "denominator": 2611,
230
+ "value": 0.05285331290693221
231
+ },
232
+ "audio.audio_to_text.recall@5": {
233
+ "numerator": 413,
234
+ "denominator": 2611,
235
+ "value": 0.1581769436997319
236
+ },
237
+ "audio.audio_to_text.recall@10": {
238
+ "numerator": 624,
239
+ "denominator": 2611,
240
+ "value": 0.23898889314438912
241
+ },
242
+ "audio.text_to_audio.recall@1": {
243
+ "numerator": 303,
244
+ "denominator": 2610,
245
+ "value": 0.11609195402298851
246
+ },
247
+ "audio.text_to_audio.recall@5": {
248
+ "numerator": 693,
249
+ "denominator": 2610,
250
+ "value": 0.2655172413793103
251
+ },
252
+ "audio.text_to_audio.recall@10": {
253
+ "numerator": 925,
254
+ "denominator": 2610,
255
+ "value": 0.3544061302681992
256
+ }
257
+ }
258
+ }
259
+ },
260
+ "datasets": {
261
+ "banking77": {
262
+ "source": "https://github.com/PolyAI-LDN/task-specific-datasets",
263
+ "revision": "57ec275d8078af65b7731c2a98be812d844a6d6b",
264
+ "license": "CC-BY-4.0",
265
+ "split": "test",
266
+ "queries": 3080,
267
+ "classes": 77
268
+ },
269
+ "massive-en": {
270
+ "source": "https://huggingface.co/datasets/AmazonScience/massive",
271
+ "revision": "ff6bd8e4b27c3543e4f8fe2108f32bb95a6f8740",
272
+ "license": "CC-BY-4.0",
273
+ "configuration": "en-US",
274
+ "split": "test",
275
+ "queries": 2972,
276
+ "prototype_classes": 60
277
+ },
278
+ "image": {
279
+ "source": "https://cocodataset.org/",
280
+ "caption_split_source": "https://cs.stanford.edu/people/karpathy/deepimagesent/",
281
+ "split": "Karpathy test, CC-BY 2.0 image subset",
282
+ "images": 823,
283
+ "captions": 4115,
284
+ "image_license": "CC-BY-2.0",
285
+ "caption_license": "CC-BY-4.0"
286
+ },
287
+ "audio": {
288
+ "source": "https://www.openslr.org/12",
289
+ "split": "test-clean",
290
+ "archive_sha256": "39fde525e59672dc6d1551919b1478f724438a95aa55f874b576be21967e6c23",
291
+ "license": "CC-BY-4.0",
292
+ "clips": 2611,
293
+ "unique_transcripts": 2610,
294
+ "maximum_seconds": 30
295
+ }
296
+ },
297
+ "protocol": {
298
+ "embedding_dtype": "float32",
299
+ "attention": "SDPA",
300
+ "autocast": false,
301
+ "tf32": false,
302
+ "transformers_version": "4.57.6",
303
+ "torch_version_family": "2.12",
304
+ "text_max_tokens": 128,
305
+ "truncation": "right, native tokenizer including special tokens",
306
+ "batch_sizes": {
307
+ "text": 64,
308
+ "image": 8,
309
+ "audio": 8
310
+ },
311
+ "pooling": "native full-dimension model pooling",
312
+ "similarity": "FP32 cosine of L2-normalized embeddings",
313
+ "ties": "lexicographic candidate ID",
314
+ "retrieval": "complete candidate pools; all annotated positives",
315
+ "classification": "nearest normalized mean class prototype; fixed prototype split",
316
+ "aggregation": "Each family is the mean of its two primary metrics; utility is the mean of all six primaries. Retrieval primaries are R@1; R@5 and R@10 are reported separately.",
317
+ "evaluation_scope": "fixed test-split evaluation pools"
318
+ },
319
+ "paired_uncertainty": {
320
+ "comparison": {
321
+ "candidate": "llm-semantic-router/Vela-1.0-Omni-134M-Nano",
322
+ "baseline": "llm-semantic-router/multi-modal-embed-small"
323
+ },
324
+ "seed": 20260918,
325
+ "replicates": 2000,
326
+ "method": "paired stratified group percentile; PCG64; fixed candidate pools",
327
+ "intervals": {
328
+ "audio.audio_to_text.recall@1": {
329
+ "point_delta": 0.010723860589812333,
330
+ "lower": 0.005401297417205939,
331
+ "upper": 0.016930329895273797
332
+ },
333
+ "audio.audio_to_text.recall@10": {
334
+ "point_delta": 0.048640367675220224,
335
+ "lower": 0.03862647576747038,
336
+ "upper": 0.057686079679882395
337
+ },
338
+ "audio.audio_to_text.recall@5": {
339
+ "point_delta": 0.038299502106472615,
340
+ "lower": 0.028966882934863172,
341
+ "upper": 0.04718931610578753
342
+ },
343
+ "audio.text_to_audio.recall@1": {
344
+ "point_delta": 0.020306513409961684,
345
+ "lower": 0.01207735759631001,
346
+ "upper": 0.029131333167300467
347
+ },
348
+ "audio.text_to_audio.recall@10": {
349
+ "point_delta": 0.0475095785440613,
350
+ "lower": 0.036695309471507946,
351
+ "upper": 0.05838249564916254
352
+ },
353
+ "audio.text_to_audio.recall@5": {
354
+ "point_delta": 0.040229885057471264,
355
+ "lower": 0.027551627678505008,
356
+ "upper": 0.05248271039052227
357
+ },
358
+ "family.audio": {
359
+ "point_delta": 0.015515186999887009,
360
+ "lower": 0.010126625706639377,
361
+ "upper": 0.021365285246569197
362
+ },
363
+ "family.image": {
364
+ "point_delta": 0.04665856622114216,
365
+ "lower": 0.031831713244228434,
366
+ "upper": 0.061849939246658554
367
+ },
368
+ "family.text": {
369
+ "point_delta": 0.0,
370
+ "lower": 0.0,
371
+ "upper": 0.0
372
+ },
373
+ "image.image_to_text.recall@1": {
374
+ "point_delta": 0.03402187120291616,
375
+ "lower": 0.009720534629404616,
376
+ "upper": 0.05953827460510328
377
+ },
378
+ "image.image_to_text.recall@10": {
379
+ "point_delta": 0.07533414337788578,
380
+ "lower": 0.05103280680437424,
381
+ "upper": 0.10085054678007291
382
+ },
383
+ "image.image_to_text.recall@5": {
384
+ "point_delta": 0.0583232077764277,
385
+ "lower": 0.031591737545565005,
386
+ "upper": 0.08383961117861483
387
+ },
388
+ "image.text_to_image.recall@1": {
389
+ "point_delta": 0.059295261239368166,
390
+ "lower": 0.04325637910085055,
391
+ "upper": 0.07630619684082625
392
+ },
393
+ "image.text_to_image.recall@10": {
394
+ "point_delta": 0.07727825030376671,
395
+ "lower": 0.061482381530984204,
396
+ "upper": 0.0928311057108141
397
+ },
398
+ "image.text_to_image.recall@5": {
399
+ "point_delta": 0.09307411907654921,
400
+ "lower": 0.07606318347509113,
401
+ "upper": 0.11009113001215064
402
+ },
403
+ "text.banking77.accuracy": {
404
+ "point_delta": 0.0,
405
+ "lower": 0.0,
406
+ "upper": 0.0
407
+ },
408
+ "text.massive-en.accuracy": {
409
+ "point_delta": 0.0,
410
+ "lower": 0.0,
411
+ "upper": 0.0
412
+ },
413
+ "utility": {
414
+ "point_delta": 0.020724584407009722,
415
+ "lower": 0.015571272805177982,
416
+ "upper": 0.026256156724631264
417
+ }
418
+ }
419
+ }
420
+ }
vela_omni.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Self-contained Vela Omni text, image, and audio embeddings."""
2
+ import json
3
+ from pathlib import Path
4
+
5
+ import numpy as np
6
+ import torch
7
+ from safetensors.torch import load_file
8
+ from torch import nn
9
+ from torch.nn import functional as F
10
+
11
+ from omni_components.embedder import MultimodalEmbedder
12
+ from omni_components.mini import MultiModalSentenceEmbedder
13
+
14
+
15
+ class VelaOmni(nn.Module):
16
+ def __init__(self, root, variant, legacy=False, audio_projection="identity"):
17
+ super().__init__()
18
+ self.variant = variant
19
+ self.embedding_dim = 384 if variant == "nano" else 768
20
+ self.max_text_length = 128 if variant == "nano" else 32768
21
+ if variant == "nano":
22
+ self.model = MultimodalEmbedder(Path(root) / "components", legacy=legacy)
23
+ self.tokenizer = self.model.text_encoder.tokenizer
24
+ if audio_projection == "linear":
25
+ self.model.audio_encoder.projection = nn.Linear(384, 384)
26
+ elif audio_projection != "identity":
27
+ raise ValueError("Unsupported Nano audio projection")
28
+ elif variant == "mini":
29
+ if audio_projection != "identity":
30
+ raise ValueError("Mini uses its native audio projection")
31
+ self.model = MultiModalSentenceEmbedder(Path(root) / "components", legacy=legacy)
32
+ self.tokenizer = self.model.text_model.tokenizer
33
+ else:
34
+ raise ValueError("Unknown Vela Omni variant")
35
+
36
+ @classmethod
37
+ def from_pretrained(cls, repo_id, revision=None, device="cpu", dtype=torch.float32):
38
+ root = Path(repo_id)
39
+ if not root.is_dir():
40
+ from huggingface_hub import snapshot_download
41
+ root = Path(snapshot_download(repo_id, revision=revision,
42
+ allow_patterns=["config.json", "model.safetensors", "components/*"]))
43
+ config = json.loads((root / "config.json").read_text())
44
+ if config.get("format_version") not in (1, 2):
45
+ raise ValueError("Unsupported Vela Omni artifact format")
46
+ instance = cls(root, config["variant"], audio_projection=config.get("audio_projection", "identity"))
47
+ weights = load_file(str(root / "model.safetensors"), device="cpu")
48
+ result = instance.model.load_state_dict(weights, strict=True, assign=True)
49
+ if result.missing_keys or result.unexpected_keys:
50
+ raise ValueError("Incomplete Vela Omni weights")
51
+ if any(p.is_meta for p in instance.parameters()):
52
+ raise ValueError("Uninitialized model parameters")
53
+ if sum(p.numel() for p in instance.model.parameters()) != config["parameter_count"]:
54
+ raise ValueError("Parameter count does not match the artifact")
55
+ instance.to(device=device, dtype=dtype).eval()
56
+ return instance
57
+
58
+ @torch.inference_mode()
59
+ def encode_text(self, texts):
60
+ if isinstance(texts, str):
61
+ texts = [texts]
62
+ if not texts or any(not isinstance(text, str) for text in texts):
63
+ raise ValueError("Provide at least one text string")
64
+ lengths = self.tokenizer(texts, truncation=False, padding=False, return_length=True)["length"]
65
+ if max(lengths) > self.max_text_length:
66
+ raise ValueError(f"Text exceeds {self.max_text_length} tokens; shorten or explicitly chunk it")
67
+ if self.variant == "nano":
68
+ values = self.model.encode_text(texts)
69
+ else:
70
+ values = self.model._encode_text(list(texts))
71
+ return F.normalize(values.float(), dim=-1)
72
+
73
+ @torch.inference_mode()
74
+ def encode_image(self, images):
75
+ images = list(images)
76
+ if not images:
77
+ raise ValueError("Provide at least one image")
78
+ if self.variant == "nano":
79
+ values = self.model.encode_image(images)
80
+ else:
81
+ pixels = self.model.image_processor(images=images, return_tensors="pt")["pixel_values"]
82
+ pixels = pixels.to(device=next(self.parameters()).device, dtype=next(self.model.image_model.parameters()).dtype)
83
+ values = self.model._encode_image_pixel_values(pixels)
84
+ return F.normalize(values.float(), dim=-1)
85
+
86
+ @torch.inference_mode()
87
+ def encode_audio(self, waveforms, sampling_rate=16000):
88
+ if sampling_rate != 16000:
89
+ raise ValueError("Resample audio to 16000 Hz before encoding")
90
+ waveforms = [np.asarray(w, dtype=np.float32) for w in waveforms]
91
+ if not waveforms or any(w.ndim != 1 or not w.size or not np.isfinite(w).all() for w in waveforms):
92
+ raise ValueError("Audio must contain finite nonempty mono waveforms")
93
+ if any(len(w) > 30 * sampling_rate for w in waveforms):
94
+ raise ValueError("Audio inputs must be at most 30 seconds")
95
+ if self.variant == "nano":
96
+ values = self.model.encode_audio(waveforms, sampling_rate=sampling_rate)
97
+ else:
98
+ features = self.model.audio_processor(waveforms, sampling_rate=sampling_rate,
99
+ return_tensors="pt")["input_features"]
100
+ values = self.model._encode_audio_features(features)
101
+ return F.normalize(values.float(), dim=-1)