Feature Extraction
Transformers
Safetensors
Korean
English
embeddings
text-to-image-retrieval
query-encoder
distillation
int8
embeddinggemma-2
research-release
8-bit precision
Instructions to use ThakiCloud/eg2-tiny-query-a1 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use ThakiCloud/eg2-tiny-query-a1 with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("feature-extraction", model="ThakiCloud/eg2-tiny-query-a1")# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("ThakiCloud/eg2-tiny-query-a1", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Download a1_query.py from ThakiCloud/eg2-tiny-query-a1: direct link, hf CLI and curl.
- Browser
- Download file 3.02 kB
-
https://huggingface.co/ThakiCloud/eg2-tiny-query-a1/resolve/main/a1_query.py
- Command line
-
hf download hf://ThakiCloud/eg2-tiny-query-a1/a1_query.py
-
curl -L -o a1_query.py https://huggingface.co/ThakiCloud/eg2-tiny-query-a1/resolve/main/a1_query.py
3.02 kB
| """A1 query encoder for EmbeddingGemma 2 image indexes. | |
| Korean or English search text -> L2-normalized 768-d vector that you compare (dot product) | |
| with image vectors produced by google/embeddinggemma-2. The image index does not change. | |
| Weights are stored as row-wise INT8 (`<name>.__scale` holds one fp16 scale per row) and are | |
| dequantized to float32 when loaded. | |
| """ | |
| import json | |
| from pathlib import Path | |
| import numpy as np | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from safetensors.torch import load_file | |
| from transformers import AutoTokenizer, CLIPTextConfig, CLIPTextModel | |
| def _resolve(path_or_repo, revision=None): | |
| p = Path(path_or_repo) | |
| if p.is_dir(): | |
| return p | |
| from huggingface_hub import snapshot_download | |
| return Path(snapshot_download(str(path_or_repo), revision=revision)) | |
| class A1QueryEncoder(nn.Module): | |
| def __init__(self, text_config, out_dim=768, max_tokens=64): | |
| super().__init__() | |
| self.enc = CLIPTextModel(text_config) | |
| self.align = nn.Linear(text_config.hidden_size, out_dim) | |
| self.max_tokens = max_tokens | |
| self.tok = None | |
| def from_pretrained(cls, path_or_repo="ThakiCloud/eg2-tiny-query-a1", revision=None, device="cpu"): | |
| root = _resolve(path_or_repo, revision) | |
| meta = json.loads((root / "config.json").read_text()) | |
| base = json.loads((root / "base_config.json").read_text()) | |
| text_cfg = CLIPTextConfig.from_dict(base["text_config"] if base.get("model_type") == "clip" else base) | |
| m = cls(text_cfg, out_dim=meta["out_dim"], max_tokens=meta["max_tokens"]) | |
| raw = load_file(str(root / "model.safetensors")) | |
| sd = {k: (v.float() * raw[f"{k}.__scale"].float()[:, None]) if f"{k}.__scale" in raw else v.float() | |
| for k, v in raw.items() if not k.endswith(".__scale")} | |
| missing, unexpected = m.load_state_dict(sd, strict=False) | |
| ref = m.state_dict() | |
| if unexpected or any(ref[k].dtype.is_floating_point for k in missing): | |
| raise RuntimeError(f"weight mismatch: missing={missing} unexpected={unexpected}") | |
| m.tok = AutoTokenizer.from_pretrained(str(root)) | |
| return m.to(device).eval() | |
| def forward(self, batch): | |
| return self.align(self.enc(**batch).pooler_output) | |
| def encode(self, texts, batch_size=256): | |
| """texts: list[str] -> np.ndarray (n, 768), float32, L2-normalized. No query prefix.""" | |
| if isinstance(texts, str): | |
| texts = [texts] | |
| dev = next(self.parameters()).device | |
| out = [] | |
| for i in range(0, len(texts), batch_size): | |
| b = self.tok(list(texts[i:i + batch_size]), padding=True, truncation=True, | |
| max_length=min(self.max_tokens, 77), return_tensors="pt") | |
| b = {k: v.to(dev) for k, v in b.items()} | |
| out.append(F.normalize(self(b).float(), dim=1).cpu().numpy()) | |
| return np.concatenate(out) if out else np.zeros((0, 768), np.float32) | |