Download code/tt_embgemma/api.py from changh95/embeddinggemma-2: direct link, hf CLI and curl.
- Browser
- Download file 13.9 kB
-
https://huggingface.co/changh95/embeddinggemma-2/resolve/main/code/tt_embgemma/api.py
- Command line
-
hf download hf://changh95/embeddinggemma-2/code/tt_embgemma/api.py
-
curl -L -o api.py https://huggingface.co/changh95/embeddinggemma-2/resolve/main/code/tt_embgemma/api.py
13.9 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| """Python API of the EmbeddingGemma 2 port. | |
| from tt_embgemma.api import EmbeddingGemma2 | |
| m = EmbeddingGemma2.from_pretrained() # opens the p150 (ETH dispatch), compiles + traces buckets | |
| q = m.embed(["What causes the northern lights?"], prompt_name="SearchQuery") | |
| d = m.embed([{"text": "Aurora photo", "image": pil_image}], dimensions=256) | |
| m.close() | |
| Inputs: a string, or a dict whose keys (in order) are ``text`` / ``image`` / ``video`` / ``audio`` (lists allowed), | |
| or ``{"content": [{"type": "text", "text": ...}, {"type": "image", "image": ...}, ...]}``. Images: PIL images, | |
| HxWx3 uint8 arrays or encoded bytes / base64; audio: ``{"array": waveform, "sampling_rate": sr}`` or encoded bytes / | |
| base64 (WAV); video: ``{"frames": [...], "fps": ..., "duration": ...}`` or container bytes (PyAV).""" | |
| from __future__ import annotations | |
| import os | |
| import time | |
| from typing import Any, Dict, List, Optional, Sequence, Tuple | |
| import numpy as np | |
| from . import __version__ | |
| from . import config as C | |
| from . import media as MD | |
| from . import model_spec as S | |
| from . import pipeline as P | |
| from .preprocess.text import TooLong | |
| class InputError(ValueError): | |
| pass | |
| def _image(v): | |
| if isinstance(v, (bytes, bytearray)): | |
| return MD.decode_image(bytes(v)) | |
| if isinstance(v, str): | |
| return MD.decode_image(MD.b64bytes(v, "image")) | |
| if isinstance(v, dict) and "data" in v: | |
| return _image(v["data"]) | |
| return v # PIL image / ndarray (validated by the preprocessor) | |
| def _audio(v, sampling_rate=None, fmt=None): | |
| if isinstance(v, dict): | |
| if "array" in v: | |
| a = np.asarray(v["array"], dtype=np.float32) | |
| sr = int(v.get("sampling_rate") or sampling_rate or S.A_SR) | |
| return {"array": a, "sampling_rate": sr} | |
| if "data" in v: | |
| return _audio(v["data"], v.get("sampling_rate", sampling_rate), v.get("format", fmt)) | |
| raise MD.MediaError("audio object needs 'array' (+ 'sampling_rate') or 'data' (base64)") | |
| if isinstance(v, (bytes, bytearray)): | |
| x, sr = MD.decode_audio(bytes(v), fmt, sampling_rate) | |
| return {"array": x, "sampling_rate": sr} | |
| if isinstance(v, str): | |
| x, sr = MD.decode_audio(MD.b64bytes(v, "audio"), fmt, sampling_rate) | |
| return {"array": x, "sampling_rate": sr} | |
| if isinstance(v, (list, np.ndarray)): | |
| return {"array": np.asarray(v, dtype=np.float32), "sampling_rate": int(sampling_rate or S.A_SR)} | |
| raise MD.MediaError("unsupported audio value") | |
| def _video(v, fps=None, duration=None): | |
| if isinstance(v, (bytes, bytearray)): | |
| return MD.decode_video_file(bytes(v)) | |
| if isinstance(v, str): | |
| return MD.decode_video_file(MD.b64bytes(v, "video")) | |
| if isinstance(v, dict): | |
| fr = v.get("frames") | |
| if fr is None: | |
| if "data" in v: | |
| return _video(v["data"]) | |
| raise MD.MediaError("video object needs 'frames' (list of images) or 'data' (container, base64)") | |
| if isinstance(fr, np.ndarray): | |
| frames = fr | |
| else: | |
| frames = [np.asarray(_image(f), dtype=np.uint8) if not isinstance(f, np.ndarray) else f for f in fr] | |
| f_ = v.get("fps", fps) | |
| return {"frames": frames, "fps": float(f_) if f_ else None, | |
| "duration": v.get("duration", duration)} | |
| if isinstance(v, (list, np.ndarray)): | |
| return _video({"frames": v, "fps": fps, "duration": duration}) | |
| raise MD.MediaError("unsupported video value") | |
| def parse_input(obj, prompt: str = "") -> P.Item: | |
| """One request input -> pipeline Item (raises InputError / MediaError).""" | |
| if isinstance(obj, str): | |
| return P.Item([("text", obj)], prompt) | |
| if not isinstance(obj, dict) or not obj: | |
| if hasattr(obj, "convert") or isinstance(obj, np.ndarray): | |
| return P.Item([("image", obj)], prompt) | |
| raise InputError("an input is a string or an object with text / image / video / audio / content") | |
| content: List[Tuple[str, Any]] = [] | |
| if "content" in obj: | |
| items = obj["content"] | |
| if not isinstance(items, list) or not items: | |
| raise InputError("content must be a non-empty list") | |
| for it in items: | |
| if not isinstance(it, dict) or "type" not in it: | |
| raise InputError("content items are objects with a 'type'") | |
| t = it["type"] | |
| if t == "text": | |
| content.append(("text", str(it.get("text", "")))) | |
| elif t == "image": | |
| content.append(("image", _image(it.get("image", it.get("data"))))) | |
| elif t == "audio": | |
| content.append(("audio", _audio(it.get("audio", it.get("data")) if "array" not in it else it, | |
| it.get("sampling_rate"), it.get("format")))) | |
| elif t == "video": | |
| content.append(("video", _video(it.get("video", it), it.get("fps"), it.get("duration")))) | |
| else: | |
| raise InputError(f"unknown content type {t!r}") | |
| return P.Item(content, prompt) | |
| extra = set(obj) - {"text", "image", "video", "audio", "sampling_rate", "format", "fps", "duration"} | |
| if extra: | |
| raise InputError(f"unknown input keys {sorted(extra)}") | |
| for k, v in obj.items(): | |
| vals = v if isinstance(v, list) and k in ("image", "video", "audio") and not ( | |
| k == "audio" and v and isinstance(v[0], (int, float))) else [v] | |
| for x in vals: | |
| if k == "text": | |
| content.append(("text", str(x))) | |
| elif k == "image": | |
| content.append(("image", _image(x))) | |
| elif k == "audio": | |
| content.append(("audio", _audio(x, obj.get("sampling_rate"), obj.get("format")))) | |
| elif k == "video": | |
| content.append(("video", _video(x, obj.get("fps"), obj.get("duration")))) | |
| if not content: | |
| raise InputError("empty input") | |
| return P.Item(content, prompt) | |
| class EmbeddingGemma2: | |
| def __init__(self, cfg: C.ServeConfig, tok, table, engine, device=None, info: Optional[Dict] = None, | |
| owns_device: bool = False): | |
| self.cfg, self.tok, self.table, self.engine, self.device = cfg, tok, table, engine, device | |
| self.owns_device = owns_device # close() closes the chip only when from_pretrained opened it | |
| self.info = info or {} | |
| self.engine_name = getattr(engine, "name", "?") | |
| def from_pretrained(cls, model_dir: Optional[str] = None, config: Optional[C.ServeConfig] = None, device=None): | |
| from .preprocess.text import Tokenizer | |
| from .weights import load_embed_table, load_state, resolve_model_dir | |
| cfg = config or C.resolve_config() | |
| t0 = time.time() | |
| md = resolve_model_dir(model_dir or cfg.weights_dir) | |
| S.check_config(md) | |
| tok = Tokenizer(md) | |
| if cfg.default_prompt is not None and cfg.default_prompt not in tok.prompts: | |
| raise ValueError(f"EMBGEMMA_DEFAULT_PROMPT={cfg.default_prompt!r}: not a prompt of this model " | |
| f"({', '.join(sorted(tok.prompts))})") | |
| table = P.EmbedTable(load_embed_table(md)) | |
| comps = ["text"] | |
| if "image" in cfg.modalities or "video" in cfg.modalities: | |
| comps.append("vision") | |
| if "audio" in cfg.modalities: | |
| comps.append("audio") | |
| W = load_state(md, comps, skip_embed=True) | |
| owns = False | |
| info: Dict[str, Any] = {"model_dir": md, "modalities": list(cfg.modalities), "version": __version__} | |
| if cfg.text_engine == "cpu": | |
| from .reference.engine import CpuEngine | |
| engine = CpuEngine(W, cfg.cpu_threads) | |
| info["engine"] = "cpu" | |
| else: | |
| from .device import describe_device, open_device | |
| from .tt.engine import EngineConfig, TtnnEngine | |
| if device is None: | |
| device = open_device(dispatch=cfg.dispatch) | |
| owns = True | |
| ecfg = EngineConfig(modalities=cfg.modalities, max_batch=cfg.max_batch, text_buckets=cfg.text_buckets, | |
| long_buckets=cfg.long_buckets, vision_buckets=cfg.vision_buckets, | |
| audio_buckets=cfg.audio_buckets, weights=cfg.weights, fidelity=cfg.fidelity, | |
| trace=cfg.trace, vision_attn=cfg.vision_attn) | |
| engine = TtnnEngine(device, W, ecfg) | |
| if cfg.warmup: | |
| engine.warmup() | |
| info["engine"] = engine.describe() | |
| info["device"] = describe_device(device) | |
| del W | |
| info["load_s"] = round(time.time() - t0, 2) | |
| return cls(cfg, tok, table, engine, device, info, owns_device=owns) | |
| # ------------------------------------------------------------------------------------------ host side | |
| def options(self, dimensions: int = S.EMB_DIM, normalize: bool = True, max_length: Optional[int] = None, | |
| truncate: str = "right", image_tokens: int = S.V_DEFAULT_IMAGE_TOKENS, | |
| video_tokens: int = S.V_DEFAULT_VIDEO_TOKENS, video_fps: float = 1.0, | |
| video_max_frames: Optional[int] = None) -> P.Options: | |
| cfg = self.cfg | |
| if dimensions not in S.MRL_DIMS: | |
| raise InputError(f"dimensions={dimensions}: one of {list(S.MRL_DIMS)} (Matryoshka sizes)") | |
| ml = cfg.max_seq_len if max_length is None else int(max_length) | |
| if not 3 <= ml <= cfg.max_seq_len: | |
| raise InputError(f"max_length={ml}: outside [3, {cfg.max_seq_len}] (EMBGEMMA_MAX_SEQ_LEN)") | |
| if truncate not in ("right", "error"): | |
| raise InputError("truncate: 'right' or 'error'") | |
| for name, v in (("image_tokens", image_tokens), ("video_tokens", video_tokens)): | |
| if v not in C.IMAGE_TOKENS: | |
| raise InputError(f"{name}={v}: one of {list(C.IMAGE_TOKENS)}") | |
| if v > cfg.image_tokens_max: | |
| raise InputError(f"{name}={v} > EMBGEMMA_IMAGE_TOKENS_MAX={cfg.image_tokens_max}") | |
| mf = cfg.video_max_frames if video_max_frames is None else int(video_max_frames) | |
| if not 1 <= mf <= cfg.video_max_frames: | |
| raise InputError(f"video_max_frames={mf}: outside [1, {cfg.video_max_frames}]") | |
| if not (video_fps > 0): | |
| raise InputError("video_fps must be > 0") | |
| return P.Options(image_tokens=image_tokens, video_tokens=video_tokens, video_fps=float(video_fps), | |
| video_max_frames=mf, max_len=ml, truncate=truncate, dimensions=dimensions, | |
| normalize=normalize) | |
| def resolve_prompt(self, prompt: Optional[str], prompt_name: Optional[str]) -> str: | |
| try: | |
| return self.tok.resolve_prompt(prompt, prompt_name) | |
| except ValueError as e: | |
| raise InputError(str(e)) from None | |
| def prepare(self, item: P.Item, opt: P.Options) -> P.Prepared: | |
| """Host preprocessing of one input (thread-safe).""" | |
| for kind, v in item.content: | |
| if kind in ("image", "video") and not ({"image", "video"} & set(self.cfg.modalities)): | |
| raise InputError(f"{kind} inputs are disabled (EMBGEMMA_MODALITIES={','.join(self.cfg.modalities)})") | |
| if kind == "image" and "image" not in self.cfg.modalities: | |
| raise InputError("image inputs are disabled (EMBGEMMA_MODALITIES)") | |
| if kind == "video" and "video" not in self.cfg.modalities: | |
| raise InputError("video inputs are disabled (EMBGEMMA_MODALITIES)") | |
| if kind == "audio" and "audio" not in self.cfg.modalities: | |
| raise InputError("audio inputs are disabled (EMBGEMMA_MODALITIES)") | |
| if kind == "audio": | |
| n = len(v["array"]) / max(int(v.get("sampling_rate", S.A_SR)), 1) | |
| if n > self.cfg.audio_max_seconds + 1e-6 and self.cfg.audio_max_seconds < 30.0: | |
| v["array"] = np.asarray(v["array"])[: int(self.cfg.audio_max_seconds * v["sampling_rate"])] | |
| try: | |
| return P.prepare(self.tok, item, opt) | |
| except TooLong as e: | |
| raise InputError(f"{e} (EMBGEMMA_MAX_SEQ_LEN={self.cfg.max_seq_len}; truncate='right' applies to " | |
| "text-only inputs)") from None | |
| except MD.MediaError: | |
| raise | |
| except ValueError as e: | |
| raise InputError(str(e)) from None | |
| # ------------------------------------------------------------------------------------------ device side | |
| def run(self, preps: Sequence[P.Prepared], want_tokens: bool = False): | |
| return P.run_prepared(self.engine, self.table, preps, want_tokens) | |
| # ------------------------------------------------------------------------------------------ convenience | |
| def embed(self, inputs: Sequence[Any], prompt_name: Optional[str] = None, prompt: Optional[str] = None, | |
| output: str = "sentence", **opts): | |
| """-> embeddings [B, dimensions] float32 (output='sentence') or a list of token-embedding arrays.""" | |
| if isinstance(inputs, (str, dict)): | |
| inputs = [inputs] | |
| opt = self.options(**opts) | |
| pr = self.resolve_prompt(prompt, prompt_name) | |
| preps = [self.prepare(parse_input(x, pr), opt) for x in inputs] | |
| sums, n, toks = self.run(preps, want_tokens=output == "tokens") | |
| if output == "tokens": | |
| return toks | |
| return P.finish(sums, n, opt.dimensions, opt.normalize) | |
| def close(self): | |
| try: | |
| if self.engine is not None: | |
| self.engine.close() | |
| finally: | |
| if self.device is not None and self.owns_device: | |
| from .device import close_device | |
| close_device(self.device) | |
| self.device = None | |