File size: 13,873 Bytes
5c33f00
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# 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", "?")

    @classmethod
    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