abtonmoy commited on
Commit
b37f54b
·
verified ·
1 Parent(s): 2b5bcc8

inference.py: install URL points at the renamed family repo

Browse files
Files changed (1) hide show
  1. inference.py +183 -183
inference.py CHANGED
@@ -1,183 +1,183 @@
1
- """fusion-embedding inference — one embedding space for text, images, and audio.
2
-
3
- Serves BOTH architecture generations: fusion-embedding-1 (frozen base + trained
4
- resampler) and fusion-embedding-2 (adds modality-gated deep adapters — in-layer audio
5
- capacity whose gate leaves every text/image/video forward bitwise identical to the
6
- frozen base). The checkpoint's own config selects the architecture; an adapter
7
- checkpoint refuses to load without its adapters.
8
-
9
- Loads the frozen Qwen3-VL-Embedding base (native paths for text and images), the frozen
10
- Qwen2.5-Omni audio tower, and this repository's trained connector checkpoint. All inputs
11
- use the base model's official chat-template format; embedding quality is sensitive to
12
- this formatting, so use the templates provided here rather than constructing your own.
13
-
14
- from inference import FusionEmbedder
15
- fe = FusionEmbedder.from_pretrained("EximiusLabs/fusion-embedding-2-2b-preview")
16
- a, t, i = fe.embed_audio("dog.wav"), fe.embed_text("a dog barks"), fe.embed_image("dog.jpg")
17
-
18
- Requires: fusion_embedding (pip install git+https://github.com/Eximius-Labs/fusion-embedding-1),
19
- transformers>=4.46, torchvision, pillow, soundfile, librosa.
20
- """
21
-
22
- from __future__ import annotations
23
-
24
- import dataclasses
25
- import os
26
- from typing import TYPE_CHECKING, Optional, Union
27
-
28
- if TYPE_CHECKING:
29
- import numpy as np
30
-
31
- import torch
32
-
33
- BASE_MODEL = "Qwen/Qwen3-VL-Embedding-2B"
34
- AUDIO_MODEL = "Qwen/Qwen2.5-Omni-7B"
35
- DEFAULT_QUERY_INSTRUCTION = "Retrieve images or text relevant to the user's query."
36
- DOC_INSTRUCTION = "Represent the user's input."
37
- CKPT_FILES = ("fusion-embedding-2-2b-preview.pt", "fusion-embedding-1-2b-preview.pt")
38
-
39
-
40
- def _chat(instruction: str, user_content: str) -> str:
41
- """The base's official embedding format: system-turn instruction, assistant opener."""
42
- return (f"<|im_start|>system\n{instruction}<|im_end|>\n"
43
- f"<|im_start|>user\n{user_content}<|im_end|>\n"
44
- f"<|im_start|>assistant\n")
45
-
46
-
47
- class FusionEmbedder:
48
- def __init__(self, ckpt_path: str, device: str = "cuda", dtype=torch.bfloat16):
49
- from transformers import AutoFeatureExtractor, AutoModel, AutoProcessor
50
-
51
- from fusion_embedding.config import FusionConfig
52
- from fusion_embedding.hf_components import BaseLMAdapter, load_audio_tower
53
- from fusion_embedding.model import FusionEmbeddingModel, last_token_pool
54
-
55
- self.device = device
56
- self._pool = last_token_pool
57
- ck = torch.load(ckpt_path, map_location="cpu", weights_only=False)
58
- flds = {f.name for f in dataclasses.fields(FusionConfig)}
59
- self.cfg = FusionConfig(**{k: v for k, v in ck["config"].items() if k in flds})
60
-
61
- self.full = AutoModel.from_pretrained(BASE_MODEL, trust_remote_code=True, dtype=dtype)
62
- self.full = self.full.to(device).eval()
63
- for p in self.full.parameters():
64
- p.requires_grad_(False)
65
- self.proc = AutoProcessor.from_pretrained(BASE_MODEL, trust_remote_code=True)
66
- self.tok = self.proc.tokenizer
67
-
68
- tower, _, _ = load_audio_tower(AUDIO_MODEL, device=device, dtype=dtype)
69
- self.fe_audio = AutoFeatureExtractor.from_pretrained(AUDIO_MODEL, trust_remote_code=True)
70
-
71
- self.model = FusionEmbeddingModel(self.cfg, self.full.get_input_embeddings(),
72
- BaseLMAdapter(self.full.language_model),
73
- audio_encoder=tower)
74
- self.model.resampler.to(device).float()
75
- self.model.resampler.load_state_dict(ck["resampler"])
76
- # fusion-embedding-2: the gated adapters are part of the model — running an
77
- # adapter checkpoint without them would silently produce the unadapted model,
78
- # so any presence mismatch is a hard error.
79
- if ("adapters" in ck) != (self.model.audio_adapters is not None):
80
- raise RuntimeError(
81
- f"adapter presence mismatch: checkpoint has_adapters={'adapters' in ck} "
82
- f"but config adapter_rank={self.cfg.adapter_rank} — corrupted artifact?")
83
- if self.model.audio_adapters is not None:
84
- self.model.audio_adapters.to(device).float()
85
- self.model.audio_adapters.load_state_dict(ck["adapters"])
86
- self.model.text_whitening.load_state_dict(ck["text_whitening"]) # identity if unfitted
87
- self.model.eval()
88
-
89
- # ------------------------------------------------------------------ loading
90
- @classmethod
91
- def from_pretrained(cls, repo_or_path: str, device: str = "cuda",
92
- revision: Optional[str] = None, **kw) -> "FusionEmbedder":
93
- """Load from a local checkpoint path or an HF repo. ``revision`` pins a repo
94
- tag/commit (e.g. ``"v0.1-preview"``, ``"v0.2-preview"``); default is latest."""
95
- if os.path.exists(repo_or_path):
96
- path = repo_or_path
97
- else:
98
- from huggingface_hub import hf_hub_download
99
- from huggingface_hub.utils import EntryNotFoundError
100
- path = None
101
- for name in CKPT_FILES: # repo generation decides the name
102
- try:
103
- path = hf_hub_download(repo_or_path, name, revision=revision)
104
- break
105
- except EntryNotFoundError:
106
- continue
107
- if path is None:
108
- raise FileNotFoundError(f"no known checkpoint file in {repo_or_path} "
109
- f"(looked for {CKPT_FILES})")
110
- return cls(path, device=device, **kw)
111
-
112
- # ------------------------------------------------------------------ helpers
113
- def _finish(self, pooled: torch.Tensor, dim: Optional[int]) -> torch.Tensor:
114
- from fusion_embedding.model import mrl_truncate_normalize
115
- return mrl_truncate_normalize(pooled.float(), dim or self.cfg.mrl_default).squeeze(0).cpu()
116
-
117
- # ------------------------------------------------------------------ audio
118
- @torch.no_grad()
119
- def embed_audio(self, audio: Union[str, "np.ndarray"], sr: Optional[int] = None,
120
- dim: Optional[int] = None) -> torch.Tensor:
121
- import librosa
122
- import soundfile as sf
123
- if isinstance(audio, (str, os.PathLike)):
124
- wav, sr = sf.read(str(audio), dtype="float32")
125
- else:
126
- wav = audio
127
- assert sr is not None, "pass sr= when embedding a raw array"
128
- if getattr(wav, "ndim", 1) > 1:
129
- wav = wav.mean(axis=1)
130
- target_sr = self.fe_audio.sampling_rate
131
- if sr != target_sr:
132
- wav = librosa.resample(wav, orig_sr=sr, target_sr=target_sr)
133
- feats = self.fe_audio(wav, sampling_rate=target_sr, return_tensors="pt",
134
- return_attention_mask=True, padding="max_length", truncation=True)
135
- mel = feats["input_features"][0]
136
- am = feats.get("attention_mask")
137
- if am is not None:
138
- mel = mel[:, : int(am[0].sum().item())]
139
- audio_tok = self.model.audio_tokens(
140
- mel.unsqueeze(0).to(self.device),
141
- torch.ones(1, mel.shape[1], dtype=torch.bool, device=self.device))
142
- ids = torch.tensor([[self.cfg.audio_pad_id] * self.cfg.n_query + [self.cfg.eos_id]],
143
- device=self.device)
144
- pooled = self.model.encode_audio(ids, torch.ones_like(ids), audio_tok)
145
- return self._finish(pooled, dim)
146
-
147
- # ------------------------------------------------------------------ text
148
- @torch.no_grad()
149
- def embed_text(self, text: str, instruction: str = DEFAULT_QUERY_INSTRUCTION,
150
- dim: Optional[int] = None) -> torch.Tensor:
151
- ids = self.tok.encode(_chat(instruction, text), add_special_tokens=False)[:512]
152
- ids_t = torch.tensor([ids], device=self.device)
153
- pooled = self.model.encode_text(ids_t, torch.ones_like(ids_t))
154
- return self._finish(self.model.text_whitening(pooled), dim)
155
-
156
- # ------------------------------------------------------------------ image
157
- @torch.no_grad()
158
- def embed_image(self, image, dim: Optional[int] = None) -> torch.Tensor:
159
- from PIL import Image
160
- gate = getattr(self.model, "_adapter_gate", None)
161
- if gate is not None and gate.active:
162
- # The vision path runs through the same (hook-carrying) decoder layers;
163
- # non-audio inputs must execute with the gate closed so the adapter
164
- # branch never runs. Mirrors the encode_text guard.
165
- raise RuntimeError("adapter gate is open during an image embed — "
166
- "non-audio inputs must run with the gate closed")
167
- if isinstance(image, (str, os.PathLike)):
168
- image = Image.open(str(image))
169
- image = image.convert("RGB")
170
- text = _chat(DOC_INSTRUCTION, "<|vision_start|><|image_pad|><|vision_end|>")
171
- inputs = self.proc(text=[text], images=[image], return_tensors="pt").to(self.device)
172
- h = self.full(**inputs).last_hidden_state
173
- pooled = self._pool(h, inputs["attention_mask"])
174
- return self._finish(pooled, dim)
175
-
176
- # ------------------------------------------------------------------ cross-modal readout
177
- @staticmethod
178
- def center(embs: torch.Tensor) -> torch.Tensor:
179
- """Per-modality mean-centering followed by renormalization. Recommended when ranking
180
- a gallery of one modality against queries of another; improves cross-modal R@1 by
181
- roughly two points across modality pairs in our evaluation."""
182
- c = embs - embs.mean(dim=0, keepdim=True)
183
- return torch.nn.functional.normalize(c, dim=-1)
 
1
+ """fusion-embedding inference — one embedding space for text, images, and audio.
2
+
3
+ Serves BOTH architecture generations: fusion-embedding-1 (frozen base + trained
4
+ resampler) and fusion-embedding-2 (adds modality-gated deep adapters — in-layer audio
5
+ capacity whose gate leaves every text/image/video forward bitwise identical to the
6
+ frozen base). The checkpoint's own config selects the architecture; an adapter
7
+ checkpoint refuses to load without its adapters.
8
+
9
+ Loads the frozen Qwen3-VL-Embedding base (native paths for text and images), the frozen
10
+ Qwen2.5-Omni audio tower, and this repository's trained connector checkpoint. All inputs
11
+ use the base model's official chat-template format; embedding quality is sensitive to
12
+ this formatting, so use the templates provided here rather than constructing your own.
13
+
14
+ from inference import FusionEmbedder
15
+ fe = FusionEmbedder.from_pretrained("EximiusLabs/fusion-embedding-2-2b-preview")
16
+ a, t, i = fe.embed_audio("dog.wav"), fe.embed_text("a dog barks"), fe.embed_image("dog.jpg")
17
+
18
+ Requires: fusion_embedding (pip install git+https://github.com/Eximius-Labs/fusion-embedding),
19
+ transformers>=4.46, torchvision, pillow, soundfile, librosa.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import dataclasses
25
+ import os
26
+ from typing import TYPE_CHECKING, Optional, Union
27
+
28
+ if TYPE_CHECKING:
29
+ import numpy as np
30
+
31
+ import torch
32
+
33
+ BASE_MODEL = "Qwen/Qwen3-VL-Embedding-2B"
34
+ AUDIO_MODEL = "Qwen/Qwen2.5-Omni-7B"
35
+ DEFAULT_QUERY_INSTRUCTION = "Retrieve images or text relevant to the user's query."
36
+ DOC_INSTRUCTION = "Represent the user's input."
37
+ CKPT_FILES = ("fusion-embedding-2-2b-preview.pt", "fusion-embedding-1-2b-preview.pt")
38
+
39
+
40
+ def _chat(instruction: str, user_content: str) -> str:
41
+ """The base's official embedding format: system-turn instruction, assistant opener."""
42
+ return (f"<|im_start|>system\n{instruction}<|im_end|>\n"
43
+ f"<|im_start|>user\n{user_content}<|im_end|>\n"
44
+ f"<|im_start|>assistant\n")
45
+
46
+
47
+ class FusionEmbedder:
48
+ def __init__(self, ckpt_path: str, device: str = "cuda", dtype=torch.bfloat16):
49
+ from transformers import AutoFeatureExtractor, AutoModel, AutoProcessor
50
+
51
+ from fusion_embedding.config import FusionConfig
52
+ from fusion_embedding.hf_components import BaseLMAdapter, load_audio_tower
53
+ from fusion_embedding.model import FusionEmbeddingModel, last_token_pool
54
+
55
+ self.device = device
56
+ self._pool = last_token_pool
57
+ ck = torch.load(ckpt_path, map_location="cpu", weights_only=False)
58
+ flds = {f.name for f in dataclasses.fields(FusionConfig)}
59
+ self.cfg = FusionConfig(**{k: v for k, v in ck["config"].items() if k in flds})
60
+
61
+ self.full = AutoModel.from_pretrained(BASE_MODEL, trust_remote_code=True, dtype=dtype)
62
+ self.full = self.full.to(device).eval()
63
+ for p in self.full.parameters():
64
+ p.requires_grad_(False)
65
+ self.proc = AutoProcessor.from_pretrained(BASE_MODEL, trust_remote_code=True)
66
+ self.tok = self.proc.tokenizer
67
+
68
+ tower, _, _ = load_audio_tower(AUDIO_MODEL, device=device, dtype=dtype)
69
+ self.fe_audio = AutoFeatureExtractor.from_pretrained(AUDIO_MODEL, trust_remote_code=True)
70
+
71
+ self.model = FusionEmbeddingModel(self.cfg, self.full.get_input_embeddings(),
72
+ BaseLMAdapter(self.full.language_model),
73
+ audio_encoder=tower)
74
+ self.model.resampler.to(device).float()
75
+ self.model.resampler.load_state_dict(ck["resampler"])
76
+ # fusion-embedding-2: the gated adapters are part of the model — running an
77
+ # adapter checkpoint without them would silently produce the unadapted model,
78
+ # so any presence mismatch is a hard error.
79
+ if ("adapters" in ck) != (self.model.audio_adapters is not None):
80
+ raise RuntimeError(
81
+ f"adapter presence mismatch: checkpoint has_adapters={'adapters' in ck} "
82
+ f"but config adapter_rank={self.cfg.adapter_rank} — corrupted artifact?")
83
+ if self.model.audio_adapters is not None:
84
+ self.model.audio_adapters.to(device).float()
85
+ self.model.audio_adapters.load_state_dict(ck["adapters"])
86
+ self.model.text_whitening.load_state_dict(ck["text_whitening"]) # identity if unfitted
87
+ self.model.eval()
88
+
89
+ # ------------------------------------------------------------------ loading
90
+ @classmethod
91
+ def from_pretrained(cls, repo_or_path: str, device: str = "cuda",
92
+ revision: Optional[str] = None, **kw) -> "FusionEmbedder":
93
+ """Load from a local checkpoint path or an HF repo. ``revision`` pins a repo
94
+ tag/commit (e.g. ``"v0.1-preview"``, ``"v0.2-preview"``); default is latest."""
95
+ if os.path.exists(repo_or_path):
96
+ path = repo_or_path
97
+ else:
98
+ from huggingface_hub import hf_hub_download
99
+ from huggingface_hub.utils import EntryNotFoundError
100
+ path = None
101
+ for name in CKPT_FILES: # repo generation decides the name
102
+ try:
103
+ path = hf_hub_download(repo_or_path, name, revision=revision)
104
+ break
105
+ except EntryNotFoundError:
106
+ continue
107
+ if path is None:
108
+ raise FileNotFoundError(f"no known checkpoint file in {repo_or_path} "
109
+ f"(looked for {CKPT_FILES})")
110
+ return cls(path, device=device, **kw)
111
+
112
+ # ------------------------------------------------------------------ helpers
113
+ def _finish(self, pooled: torch.Tensor, dim: Optional[int]) -> torch.Tensor:
114
+ from fusion_embedding.model import mrl_truncate_normalize
115
+ return mrl_truncate_normalize(pooled.float(), dim or self.cfg.mrl_default).squeeze(0).cpu()
116
+
117
+ # ------------------------------------------------------------------ audio
118
+ @torch.no_grad()
119
+ def embed_audio(self, audio: Union[str, "np.ndarray"], sr: Optional[int] = None,
120
+ dim: Optional[int] = None) -> torch.Tensor:
121
+ import librosa
122
+ import soundfile as sf
123
+ if isinstance(audio, (str, os.PathLike)):
124
+ wav, sr = sf.read(str(audio), dtype="float32")
125
+ else:
126
+ wav = audio
127
+ assert sr is not None, "pass sr= when embedding a raw array"
128
+ if getattr(wav, "ndim", 1) > 1:
129
+ wav = wav.mean(axis=1)
130
+ target_sr = self.fe_audio.sampling_rate
131
+ if sr != target_sr:
132
+ wav = librosa.resample(wav, orig_sr=sr, target_sr=target_sr)
133
+ feats = self.fe_audio(wav, sampling_rate=target_sr, return_tensors="pt",
134
+ return_attention_mask=True, padding="max_length", truncation=True)
135
+ mel = feats["input_features"][0]
136
+ am = feats.get("attention_mask")
137
+ if am is not None:
138
+ mel = mel[:, : int(am[0].sum().item())]
139
+ audio_tok = self.model.audio_tokens(
140
+ mel.unsqueeze(0).to(self.device),
141
+ torch.ones(1, mel.shape[1], dtype=torch.bool, device=self.device))
142
+ ids = torch.tensor([[self.cfg.audio_pad_id] * self.cfg.n_query + [self.cfg.eos_id]],
143
+ device=self.device)
144
+ pooled = self.model.encode_audio(ids, torch.ones_like(ids), audio_tok)
145
+ return self._finish(pooled, dim)
146
+
147
+ # ------------------------------------------------------------------ text
148
+ @torch.no_grad()
149
+ def embed_text(self, text: str, instruction: str = DEFAULT_QUERY_INSTRUCTION,
150
+ dim: Optional[int] = None) -> torch.Tensor:
151
+ ids = self.tok.encode(_chat(instruction, text), add_special_tokens=False)[:512]
152
+ ids_t = torch.tensor([ids], device=self.device)
153
+ pooled = self.model.encode_text(ids_t, torch.ones_like(ids_t))
154
+ return self._finish(self.model.text_whitening(pooled), dim)
155
+
156
+ # ------------------------------------------------------------------ image
157
+ @torch.no_grad()
158
+ def embed_image(self, image, dim: Optional[int] = None) -> torch.Tensor:
159
+ from PIL import Image
160
+ gate = getattr(self.model, "_adapter_gate", None)
161
+ if gate is not None and gate.active:
162
+ # The vision path runs through the same (hook-carrying) decoder layers;
163
+ # non-audio inputs must execute with the gate closed so the adapter
164
+ # branch never runs. Mirrors the encode_text guard.
165
+ raise RuntimeError("adapter gate is open during an image embed — "
166
+ "non-audio inputs must run with the gate closed")
167
+ if isinstance(image, (str, os.PathLike)):
168
+ image = Image.open(str(image))
169
+ image = image.convert("RGB")
170
+ text = _chat(DOC_INSTRUCTION, "<|vision_start|><|image_pad|><|vision_end|>")
171
+ inputs = self.proc(text=[text], images=[image], return_tensors="pt").to(self.device)
172
+ h = self.full(**inputs).last_hidden_state
173
+ pooled = self._pool(h, inputs["attention_mask"])
174
+ return self._finish(pooled, dim)
175
+
176
+ # ------------------------------------------------------------------ cross-modal readout
177
+ @staticmethod
178
+ def center(embs: torch.Tensor) -> torch.Tensor:
179
+ """Per-modality mean-centering followed by renormalization. Recommended when ranking
180
+ a gallery of one modality against queries of another; improves cross-modal R@1 by
181
+ roughly two points across modality pairs in our evaluation."""
182
+ c = embs - embs.mean(dim=0, keepdim=True)
183
+ return torch.nn.functional.normalize(c, dim=-1)