File size: 7,671 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 | # SPDX-License-Identifier: Apache-2.0
"""Host orchestration shared by every engine: request items -> media preprocessing -> token sequence with media
slots -> encoders (engine) -> inputs_embeds -> text backbone (engine) -> mean pool -> L2 normalize -> MRL.
An *engine* implements three batched stages (see ``reference/engine.py`` for the CPU one):
vision(list[Patches]) -> list[np.ndarray [n_tok, 512] float32] (tower + pooler + embed_vision)
audio(list[(feats, mask)]) -> list[np.ndarray [n_tok, 512] float32] (tower + embed_audio, valid rows)
text(list[np.ndarray [n, 512]]) -> np.ndarray [B, 768] float32 = sum over tokens of the token embeddings
(and the token embeddings when ``want_tokens``)
The token embedding table (268 MB) stays on the host: ids -> rows * sqrt(512) in fp32."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Sequence, Tuple
import numpy as np
from . import model_spec as S
from .preprocess import audio as A
from .preprocess import image as I
from .preprocess import video as V
from .preprocess.text import MediaSlot, Sequence_, Tokenizer, TooLong
@dataclass
class Item:
"""One embedding input: ordered content items (kind, value) with kind in text / image / video / audio.
image value: PIL image or HxWx3 uint8 array; video value: dict(frames=[T,H,W,3] uint8, fps=None, duration=None);
audio value: dict(array=float waveform, sampling_rate=int)."""
content: List[Tuple[str, Any]]
prompt: str = ""
@dataclass
class Options:
image_tokens: int = S.V_DEFAULT_IMAGE_TOKENS
video_tokens: int = S.V_DEFAULT_VIDEO_TOKENS
video_fps: float = 1.0
video_max_frames: int = 32
max_len: int = 0
truncate: str = "right"
dimensions: int = S.EMB_DIM
normalize: bool = True
@dataclass
class Prepared:
seq: Sequence_
images: List[I.Patches] = field(default_factory=list)
videos: List[List[I.Patches]] = field(default_factory=list)
audios: List[Tuple[np.ndarray, np.ndarray]] = field(default_factory=list)
class EmbedTable:
"""Host token embedding table (bf16 numpy view as uint16 -> fp32 rows on lookup)."""
def __init__(self, table):
import torch
t = table if hasattr(table, "dtype") else torch.as_tensor(table)
if t.dtype == torch.bfloat16:
self._u16 = t.view(torch.int16).numpy().view(np.uint16)
else:
self._u16 = None
self._f32 = t.float().numpy()
def rows(self, ids: Sequence[int]) -> np.ndarray:
ids = np.asarray(ids, dtype=np.int64)
if self._u16 is not None:
r = (self._u16[ids].astype(np.uint32) << 16).view(np.float32)
else:
r = self._f32[ids]
return r * np.float32(S.EMBED_SCALE)
def prepare(tok: Tokenizer, item: Item, opt: Options) -> Prepared:
images, videos, audios = [], [], []
media_tokens: Dict = {}
content = []
for kind, v in item.content:
if kind == "text":
content.append(("text", str(v)))
elif kind == "image":
p = I.preprocess_image(v, opt.image_tokens)
media_tokens[("image", len(images))] = p.n_tokens
content.append(("image", len(images)))
images.append(p)
elif kind == "video":
fr = V.preprocess_video(v["frames"], v.get("fps"), v.get("duration"), opt.video_fps,
opt.video_max_frames, opt.video_tokens)
media_tokens[("video", len(videos))] = (len(fr), fr[0].n_tokens)
content.append(("video", len(videos)))
videos.append(fr)
elif kind == "audio":
wav = A.resample(v["array"], int(v.get("sampling_rate", S.A_SR)))
feats, mask = A.log_mel(wav)
n = A.n_tokens(mask)
if n <= 0:
raise ValueError("audio clip too short (needs > 10 ms at 16 kHz)")
media_tokens[("audio", len(audios))] = n
content.append(("audio", len(audios)))
audios.append((feats, mask))
else:
raise ValueError(f"unknown content kind {kind!r}")
seq = tok.build(content, item.prompt, media_tokens, opt.max_len, opt.truncate)
return Prepared(seq, images, videos, audios)
def inputs_embeds(table: EmbedTable, prep: Prepared, vis: List[np.ndarray], vid: List[List[np.ndarray]],
aud: List[np.ndarray]) -> np.ndarray:
ids = np.asarray(prep.seq.ids, dtype=np.int64)
is_mm = (ids == S.IMAGE_TOKEN_ID) | (ids == S.AUDIO_TOKEN_ID) | (ids == S.VIDEO_TOKEN_ID)
e = table.rows(np.where(is_mm, S.PAD_ID, ids))
for sl in prep.seq.slots:
if sl.kind == "image":
rows = vis[sl.index]
elif sl.kind == "audio":
rows = aud[sl.index]
else:
rows = vid[sl.index][sl.frame]
if rows.shape[0] != sl.count:
raise RuntimeError(f"{sl.kind} encoder gave {rows.shape[0]} rows for {sl.count} placeholders")
e[sl.start: sl.start + sl.count] = rows
return e
def finish(pooled_sum: np.ndarray, n_tokens: Sequence[int], dimensions: int, normalize: bool) -> np.ndarray:
"""sum of token embeddings [B, 768] -> mean -> (truncate to ``dimensions``) -> L2 normalize (fp64 math).
MRL (official ``truncate_dim`` + ``normalize_embeddings``): the full vector is L2-normalized by the model's
Normalize module, then truncated and re-normalized; dividing by the norm of the truncated mean is identical."""
m = pooled_sum.astype(np.float64) / np.maximum(np.asarray(n_tokens, np.float64)[:, None], 1e-9)
if dimensions not in S.MRL_DIMS:
raise ValueError(f"dimensions must be one of {S.MRL_DIMS}")
if not normalize:
m = m / np.maximum(np.linalg.norm(m, axis=-1, keepdims=True), 1e-12) # the model's Normalize module
return m[:, :dimensions].astype(np.float32)
m = m[:, :dimensions]
return (m / np.maximum(np.linalg.norm(m, axis=-1, keepdims=True), 1e-12)).astype(np.float32)
def run_prepared(engine, table: EmbedTable, preps: Sequence[Prepared], want_tokens: bool = False):
"""Device part (one thread): encoders for every media item of ``preps``, splice, text backbone.
-> (token-embedding sums [B, 768] float32, n_tokens list, token embeddings or None)."""
all_imgs = [p for pr in preps for p in pr.images]
all_frames = [f for pr in preps for v in pr.videos for f in v]
all_aud = [a for pr in preps for a in pr.audios]
vis_out = engine.vision(all_imgs + all_frames) if (all_imgs or all_frames) else []
aud_out = engine.audio(all_aud) if all_aud else []
xs = []
vi, ai = 0, 0
fi = len(all_imgs)
for pr in preps:
vis = vis_out[vi: vi + len(pr.images)]
vi += len(pr.images)
vid = []
for v in pr.videos:
vid.append(vis_out[fi: fi + len(v)])
fi += len(v)
aud = aud_out[ai: ai + len(pr.audios)]
ai += len(pr.audios)
xs.append(inputs_embeds(table, pr, vis, vid, aud))
sums, toks = engine.text(xs, want_tokens=want_tokens)
return sums, [len(pr.seq) for pr in preps], toks
def embed_items(engine, tok: Tokenizer, table: EmbedTable, items: Sequence[Item], opt: Options,
want_tokens: bool = False):
"""-> (embeddings [B, dims] float32, n_tokens list, optional token embeddings, prepared items)."""
preps = [prepare(tok, it, opt) for it in items]
sums, n, toks = run_prepared(engine, table, preps, want_tokens)
emb = finish(sums, n, opt.dimensions, opt.normalize)
return emb, n, toks, preps
|