Feature Extraction
Transformers
embedding_gemma2
embeddings
multimodal
quantization
awq
quarot
dare
lazy-loading
vision
audio
text
Instructions to use lethalbeats/embeddinggemma-2-3.3bpw-multimodal with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use lethalbeats/embeddinggemma-2-3.3bpw-multimodal with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("feature-extraction", model="lethalbeats/embeddinggemma-2-3.3bpw-multimodal")# pip install -U transformers accelerate # Load model directly from transformers import AutoProcessor, AutoModel processor = AutoProcessor.from_pretrained("lethalbeats/embeddinggemma-2-3.3bpw-multimodal") model = AutoModel.from_pretrained("lethalbeats/embeddinggemma-2-3.3bpw-multimodal", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Download modeling_embeddinggemma2.py from lethalbeats/embeddinggemma-2-3.3bpw-multimodal: direct link, hf CLI and curl.
- Browser
- Download file 11.3 kB
-
https://huggingface.co/lethalbeats/embeddinggemma-2-3.3bpw-multimodal/resolve/main/modeling_embeddinggemma2.py
- Command line
-
hf download hf://lethalbeats/embeddinggemma-2-3.3bpw-multimodal/modeling_embeddinggemma2.py
-
curl -L -o modeling_embeddinggemma2.py https://huggingface.co/lethalbeats/embeddinggemma-2-3.3bpw-multimodal/resolve/main/modeling_embeddinggemma2.py
11.3 kB
| """Unified 3-shard Lazy-Tower inference wrapper for EmbeddingGemma-2 3.30 BPW Multimodal. | |
| Supports selective download & on-demand loading/unloading of modality towers: | |
| - core_text.safetensors (~89.7 MiB): always resident | |
| - tower_vision.safetensors (~68.0 MiB): loaded on demand for image/video | |
| - tower_audio.safetensors (~135.3 MiB): loaded on demand for audio | |
| """ | |
| import gc | |
| import hashlib | |
| import json | |
| from pathlib import Path | |
| import numpy as np | |
| import torch | |
| import torch.nn.functional as F | |
| def sha256_file(path: Path) -> str: | |
| h = hashlib.sha256() | |
| with open(path, "rb") as stream: | |
| for block in iter(lambda: stream.read(8 * 1024 * 1024), b""): | |
| h.update(block) | |
| return h.hexdigest() | |
| class EmbeddingGemma2LazyMultimodal: | |
| """Single unified multimodal embedding model with on-demand Lazy Towers.""" | |
| _CONFIG_FILES = ( | |
| "config.json", | |
| "config_sentence_transformers.json", | |
| "quantization_manifest.json", | |
| "quantization_config.json", | |
| "tokenizer.json", | |
| "tokenizer.model", | |
| "tokenizer_config.json", | |
| "processor_config.json", | |
| "preprocessor_config.json", | |
| "chat_template.jinja", | |
| ) | |
| def from_pretrained(cls, model_path, modalities=("text",), device="cpu", verify=True): | |
| """Loads EmbeddingGemma-2 3.30 BPW with only the requested modality shards. | |
| Args: | |
| model_path: Local directory or Hugging Face Hub repo ID. | |
| modalities: Sequence of {"text", "vision", "audio"} or "all". Defaults to ("text",). | |
| device: Target device ("cpu", "cuda", etc.). | |
| verify: Verify SHA-256 checksum of every loaded shard against quantization_manifest.json. | |
| """ | |
| if modalities == "all": | |
| req_mods = ("text", "vision", "audio") | |
| else: | |
| req_mods = tuple(dict.fromkeys(("text",) + tuple(modalities))) | |
| local_dir = Path(model_path) | |
| is_local = local_dir.is_dir() | |
| if not is_local: | |
| from huggingface_hub import hf_hub_download | |
| manifest_file = Path(hf_hub_download(str(model_path), "quantization_manifest.json")) | |
| for fname in cls._CONFIG_FILES: | |
| try: | |
| hf_hub_download(str(model_path), fname) | |
| except Exception: | |
| pass | |
| root = manifest_file.parent | |
| else: | |
| root = local_dir | |
| manifest = json.loads((root / "quantization_manifest.json").read_text(encoding="utf-8")) | |
| if manifest.get("format") != "packed_lazy_multimodal_v3": | |
| raise ValueError(f"Unsupported format: {manifest.get('format')}") | |
| from accelerate import init_empty_weights | |
| from transformers import AutoConfig, AutoModel, AutoTokenizer | |
| config = AutoConfig.from_pretrained(root, local_files_only=True) | |
| with init_empty_weights(include_buffers=False): | |
| model = AutoModel.from_config(config) | |
| obj = cls() | |
| obj._source = str(model_path) | |
| obj._is_local = is_local | |
| obj._root = root | |
| obj._config = config | |
| obj.manifest = manifest | |
| obj.device = torch.device(device) | |
| obj.verify = verify | |
| obj.model = model | |
| obj.tokenizer = AutoTokenizer.from_pretrained(root, local_files_only=True) | |
| obj._processor = None | |
| obj.embedding_dim = config.text_config.embedding_dim | |
| obj.loaded_towers = set() | |
| obj.mean_shifts = {} | |
| # Always load core_text; keep vision/audio on meta until requested | |
| obj.load_tower("text") | |
| if "vision" in req_mods: | |
| obj.load_tower("vision") | |
| if "audio" in req_mods: | |
| obj.load_tower("audio") | |
| return obj | |
| def processor(self): | |
| """Lazily instantiates AutoProcessor only when image/video/audio encoding is needed.""" | |
| if self._processor is None: | |
| from transformers import AutoProcessor | |
| self._processor = AutoProcessor.from_pretrained(self._root, local_files_only=True) | |
| return self._processor | |
| def _resolve_shard_path(self, shard_name: str) -> Path: | |
| fname = self.manifest["shards"][shard_name]["file"] | |
| if self._is_local: | |
| path = self._root / fname | |
| if not path.is_file(): | |
| raise FileNotFoundError(f"Shard file missing: {path}") | |
| return path | |
| from huggingface_hub import hf_hub_download | |
| return Path(hf_hub_download(self._source, fname)) | |
| def _submodules_for_shard(self, shard_name: str) -> list: | |
| if shard_name == "text": | |
| return [self.model.language_model] | |
| if shard_name == "vision": | |
| return [self.model.vision_tower, self.model.embed_vision] | |
| if shard_name == "audio": | |
| return [self.model.audio_tower, self.model.embed_audio] | |
| raise ValueError(f"Unknown shard: {shard_name}") | |
| def load_tower(self, shard_name: str): | |
| """Loads a shard ('text', 'vision', or 'audio') on demand with optional SHA-256 verification.""" | |
| if shard_name in self.loaded_towers: | |
| return | |
| from safetensors.torch import load_file | |
| from quant_weights import ( | |
| install_shard_modules, | |
| PackedQuantLinear, | |
| PackedQuantEmbedding, | |
| PackedQuantPatchEmbedder, | |
| ) | |
| shard_path = self._resolve_shard_path(shard_name) | |
| expected_sha = self.manifest["shards"][shard_name]["sha256"] | |
| if self.verify and sha256_file(shard_path) != expected_sha: | |
| raise ValueError(f"SHA-256 checksum mismatch for shard '{shard_name}' ({shard_path.name})") | |
| tensors = load_file(str(shard_path)) | |
| mu_src = tensors.pop("mean_shift.mu_src", None) | |
| mu_tgt = tensors.pop("mean_shift.mu_tgt", None) | |
| if mu_src is not None and mu_tgt is not None: | |
| self.mean_shifts[shard_name] = ( | |
| mu_src.float().to(self.device), | |
| mu_tgt.float().to(self.device), | |
| ) | |
| install_shard_modules(self.model, self.manifest["modules"][shard_name], tensors) | |
| # Assign remaining dense FP16 parameters (norms, convs, connectors, DARE projection) | |
| # strictly to the target shard submodules | |
| self.model.load_state_dict(tensors, strict=False, assign=True) | |
| packed_types = (PackedQuantLinear, PackedQuantEmbedding, PackedQuantPatchEmbedder) | |
| for root_mod in self._submodules_for_shard(shard_name): | |
| for mod in root_mod.modules(): | |
| if isinstance(mod, packed_types): | |
| continue | |
| for p in mod.parameters(recurse=False): | |
| if p.is_floating_point() and not p.is_meta: | |
| p.data = p.data.float() | |
| for b_name, buf in mod.named_buffers(recurse=False): | |
| if buf.is_floating_point() and not buf.is_meta: | |
| setattr(mod, b_name, buf.float()) | |
| root_mod.to(self.device).eval() | |
| self.loaded_towers.add(shard_name) | |
| def unload_tower(self, shard_name: str): | |
| """Unloads 'vision' or 'audio' tower back to empty meta tensors to immediately reclaim RAM/VRAM.""" | |
| if shard_name == "text": | |
| raise ValueError("Cannot unload core 'text' backbone.") | |
| if shard_name not in self.loaded_towers: | |
| return | |
| from accelerate import init_empty_weights | |
| from transformers import AutoModel | |
| with init_empty_weights(include_buffers=False): | |
| empty_model = AutoModel.from_config(self._config) | |
| if shard_name == "vision": | |
| self.model.vision_tower = empty_model.vision_tower | |
| self.model.embed_vision = empty_model.embed_vision | |
| elif shard_name == "audio": | |
| self.model.audio_tower = empty_model.audio_tower | |
| self.model.embed_audio = empty_model.embed_audio | |
| del empty_model | |
| self.loaded_towers.discard(shard_name) | |
| self.mean_shifts.pop(shard_name, None) | |
| gc.collect() | |
| if self.device.type == "cuda": | |
| torch.cuda.empty_cache() | |
| def _pool_norm(self, hidden: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: | |
| m = mask.unsqueeze(-1).float() | |
| pooled = (hidden.float() * m).sum(dim=1) / m.sum(dim=1).clamp_min(1.0) | |
| return F.normalize(pooled, dim=-1) | |
| def _apply_shift(self, vecs: torch.Tensor, shard_name: str, enabled: bool) -> torch.Tensor: | |
| if not enabled or shard_name not in self.mean_shifts: | |
| return vecs | |
| mu_src, mu_tgt = self.mean_shifts[shard_name] | |
| return F.normalize(vecs - mu_src + mu_tgt, dim=-1) | |
| def encode_text(self, texts, prompt_prefix: str = "", max_length: int = 512, batch_size: int = 32) -> np.ndarray: | |
| """Encodes text using only the resident core_text shard (~90.1 MiB, zero image/audio deps).""" | |
| if isinstance(texts, str): | |
| texts = [texts] | |
| outs = [] | |
| tok = self.tokenizer | |
| for i in range(0, len(texts), batch_size): | |
| vals = [prompt_prefix + t for t in texts[i:i + batch_size]] | |
| b = tok(vals, padding=True, truncation=True, max_length=max_length, return_tensors="pt") | |
| b = {k: v.to(self.device) for k, v in b.items()} | |
| r = self.model.language_model(**b) | |
| outs.append(self._pool_norm(r.last_hidden_state, b["attention_mask"]).cpu().numpy()) | |
| return np.concatenate(outs, axis=0).astype(np.float32) | |
| def encode_image(self, images, apply_mean_shift: bool = True) -> np.ndarray: | |
| """Encodes PIL image(s), lazily loading tower_vision (~68 MiB) on first call.""" | |
| self.load_tower("vision") | |
| if not isinstance(images, (list, tuple)): | |
| images = [images] | |
| outs = [] | |
| for img in images: | |
| b = self.processor(images=[img], return_tensors="pt") | |
| b = {k: (v.to(self.device) if isinstance(v, torch.Tensor) else v) for k, v in b.items()} | |
| r = self.model(**b) | |
| vec = self._pool_norm(r.last_hidden_state, b["attention_mask"]) | |
| vec = self._apply_shift(vec, "vision", apply_mean_shift) | |
| outs.append(vec.cpu().numpy()) | |
| return np.concatenate(outs, axis=0).astype(np.float32) | |
| def encode_audio(self, waveforms, sampling_rate: int = 16000, apply_mean_shift: bool = False) -> np.ndarray: | |
| """Encodes 16 kHz mono waveform(s), lazily loading tower_audio (~135.3 MiB) on first call.""" | |
| self.load_tower("audio") | |
| if isinstance(waveforms, np.ndarray) and waveforms.ndim == 1: | |
| waveforms = [waveforms] | |
| outs = [] | |
| for wav in waveforms: | |
| b = self.processor(audio=[wav], sampling_rate=sampling_rate, return_tensors="pt") | |
| b = {k: (v.to(self.device) if isinstance(v, torch.Tensor) else v) for k, v in b.items()} | |
| r = self.model(**b) | |
| vec = self._pool_norm(r.last_hidden_state, b["attention_mask"]) | |
| vec = self._apply_shift(vec, "audio", apply_mean_shift) | |
| outs.append(vec.cpu().numpy()) | |
| return np.concatenate(outs, axis=0).astype(np.float32) | |