changh95's picture
tt-model push embeddinggemma-2 (container)
5c33f00 verified
Raw History Blame Contribute Delete
7.7 kB
# SPDX-License-Identifier: Apache-2.0
"""Server-start configuration (the COMPILE-TIME surface, research/embgemma/ARCH.md section 4.2): every
``EMBGEMMA_*`` variable is read once here; a bad value raises ``ValueError`` naming the variable. Standard library
only."""
from __future__ import annotations
import os
from dataclasses import asdict, dataclass, field
from typing import Dict, Mapping, Optional, Tuple
MODEL_NAME = "embeddinggemma-2"
REPO = "changh95/embeddinggemma-2"
WEIGHTS_REPO = "google/embeddinggemma-2"
ENGINES = ("ttnn", "cpu")
VISION_ATTN = ("sdpa", "mk")
MODALITIES = ("text", "image", "video", "audio")
FIDELITIES = ("HiFi4", "HiFi3", "HiFi2")
WEIGHT_FORMATS = ("bf16",) # bfp8 weights fail the accuracy gates (research SPEC D13): not offered
IMAGE_TOKENS = (70, 140, 280, 560, 1120)
VISION_BUCKET_FOR = {70: 864, 140: 1440, 280: 2592, 560: 5184, 1120: 10368} # patches (multiples of 288)
@dataclass(frozen=True)
class ServeConfig:
modalities: Tuple[str, ...] = MODALITIES
text_engine: str = "ttnn" # the engine of EVERY stage (text backbone, vision and audio towers): ttnn | cpu
vision_attn: str = "sdpa" # single-image vision launches: ttnn SDPA or the mk_vattn kernel
max_batch: int = 32 # sequences per text launch
max_inputs: int = 2048 # inputs per HTTP request
max_images: int = 64 # images + video frames per HTTP request (host memory: ~8 MB of patches each)
max_seq_len: int = 2048 # token cap per input (largest bucket)
text_buckets: Tuple[int, ...] = (32, 64, 128, 256, 512, 1024, 2048)
long_buckets: Tuple[int, ...] = (1024, 2048)
image_tokens_max: int = 280
video_max_frames: int = 32
audio_max_seconds: float = 30.0
audio_buckets: Tuple[int, ...] = (512, 1024, 2048, 3072)
weights: str = "bf16"
fidelity: str = "HiFi4"
trace: bool = True
warmup: bool = True
default_prompt: Optional[str] = None
batch_window_ms: float = 2.0
queue_depth: int = 256
queue_timeout_s: float = 120.0
max_body_mb: float = 64.0
dispatch: str = "eth"
weights_dir: Optional[str] = None
cpu_threads: int = 0
extra: Dict[str, str] = field(default_factory=dict)
@property
def vision_buckets(self) -> Tuple[int, ...]:
return tuple(VISION_BUCKET_FOR[t] for t in IMAGE_TOKENS if t <= self.image_tokens_max)
def as_dict(self) -> Dict:
d = asdict(self)
for k in ("modalities", "text_buckets", "long_buckets", "audio_buckets"):
d[k] = list(d[k])
d["vision_buckets"] = list(self.vision_buckets)
return d
def _int(env: Mapping[str, str], k: str, d: int, lo: int, hi: int) -> int:
v = env.get(k)
if v is None or v.strip() == "":
return d
try:
x = int(v)
except ValueError:
raise ValueError(f"{k}={v!r}: not an integer") from None
if not lo <= x <= hi:
raise ValueError(f"{k}={x}: outside [{lo}, {hi}]")
return x
def _float(env: Mapping[str, str], k: str, d: float, lo: float, hi: float) -> float:
v = env.get(k)
if v is None or v.strip() == "":
return d
try:
x = float(v)
except ValueError:
raise ValueError(f"{k}={v!r}: not a number") from None
if not lo <= x <= hi:
raise ValueError(f"{k}={x}: outside [{lo}, {hi}]")
return x
def _bool(env: Mapping[str, str], k: str, d: bool) -> bool:
v = env.get(k)
if v is None or v.strip() == "":
return d
s = v.strip().lower()
if s in ("1", "true", "yes", "on"):
return True
if s in ("0", "false", "no", "off"):
return False
raise ValueError(f"{k}={v!r}: not a boolean")
def _choice(env: Mapping[str, str], k: str, d: str, choices) -> str:
v = env.get(k)
if v is None or v.strip() == "":
return d
if v.strip() not in choices:
raise ValueError(f"{k}={v!r}: one of {list(choices)}")
return v.strip()
def _ints(env: Mapping[str, str], k: str, d: Tuple[int, ...], mult: int, lo: int, hi: int) -> Tuple[int, ...]:
v = env.get(k)
if v is None or v.strip() == "":
return d
try:
xs = tuple(sorted({int(t) for t in v.replace(" ", "").split(",") if t}))
except ValueError:
raise ValueError(f"{k}={v!r}: comma-separated integers") from None
if not xs or any(x % mult or not lo <= x <= hi for x in xs):
raise ValueError(f"{k}={v!r}: multiples of {mult} in [{lo}, {hi}]")
return xs
def resolve_config(env: Optional[Mapping[str, str]] = None) -> ServeConfig:
env = os.environ if env is None else env
mods = env.get("EMBGEMMA_MODALITIES")
modalities = MODALITIES
if mods and mods.strip():
m = tuple(dict.fromkeys(x.strip() for x in mods.split(",") if x.strip()))
bad = [x for x in m if x not in MODALITIES]
if bad:
raise ValueError(f"EMBGEMMA_MODALITIES: unknown {bad}; choose from {list(MODALITIES)}")
modalities = tuple(x for x in MODALITIES if x in m or x == "text")
max_seq = _int(env, "EMBGEMMA_MAX_SEQ_LEN", 2048, 32, 8192)
tb = _ints(env, "EMBGEMMA_TEXT_BUCKETS", tuple(b for b in (32, 64, 128, 256, 512, 1024, 2048, 4096, 8192)
if b <= max(512, max_seq)), 32, 32, 8192)
lb = _ints(env, "EMBGEMMA_LONG_BUCKETS", tuple(b for b in (1024, 2048, 4096, 8192) if b <= max_seq) or (),
32, 544, 8192)
if max_seq > 513 and (not lb or max(lb) < max_seq):
raise ValueError(f"EMBGEMMA_LONG_BUCKETS must reach EMBGEMMA_MAX_SEQ_LEN={max_seq}")
ab = _ints(env, "EMBGEMMA_AUDIO_BUCKETS", (512, 1024, 2048, 3072), 128, 128, 3072)
itm = _int(env, "EMBGEMMA_IMAGE_TOKENS_MAX", 280, 70, 1120)
if itm not in IMAGE_TOKENS:
raise ValueError(f"EMBGEMMA_IMAGE_TOKENS_MAX={itm}: one of {IMAGE_TOKENS}")
dp = env.get("EMBGEMMA_DEFAULT_PROMPT")
for gone in ("EMBGEMMA_VISION_ENGINE", "EMBGEMMA_AUDIO_ENGINE"):
if env.get(gone):
raise ValueError(f"{gone} is not supported: every stage runs on the engine of EMBGEMMA_TEXT_ENGINE")
known = {"text": "ttnn"}
return ServeConfig(
modalities=modalities,
text_engine=_choice(env, "EMBGEMMA_TEXT_ENGINE", known["text"], ENGINES),
vision_attn=_choice(env, "EMBGEMMA_VISION_ATTN", "sdpa", VISION_ATTN),
max_batch=_int(env, "EMBGEMMA_MAX_BATCH", 32, 1, 32),
max_inputs=_int(env, "EMBGEMMA_MAX_INPUTS", 2048, 1, 65536),
max_images=_int(env, "EMBGEMMA_MAX_IMAGES", 64, 1, 4096),
max_seq_len=max_seq, text_buckets=tb, long_buckets=lb,
image_tokens_max=itm,
video_max_frames=_int(env, "EMBGEMMA_VIDEO_MAX_FRAMES", 32, 1, 64),
audio_max_seconds=_float(env, "EMBGEMMA_AUDIO_MAX_SECONDS", 30.0, 0.5, 30.0),
audio_buckets=ab,
weights=_choice(env, "EMBGEMMA_WEIGHTS", "bf16", WEIGHT_FORMATS),
fidelity=_choice(env, "EMBGEMMA_FIDELITY", "HiFi4", FIDELITIES),
trace=_bool(env, "EMBGEMMA_TRACE", True),
warmup=_bool(env, "EMBGEMMA_WARMUP", True),
default_prompt=(dp.strip() or None) if dp else None,
batch_window_ms=_float(env, "EMBGEMMA_BATCH_WINDOW_MS", 2.0, 0.0, 1000.0),
queue_depth=_int(env, "EMBGEMMA_QUEUE_DEPTH", 256, 1, 100000),
queue_timeout_s=_float(env, "EMBGEMMA_QUEUE_TIMEOUT_S", 120.0, 1.0, 3600.0),
max_body_mb=_float(env, "EMBGEMMA_MAX_BODY_MB", 64.0, 1.0, 4096.0),
dispatch=_choice(env, "EMBGEMMA_DISPATCH", "eth", ("eth", "worker", "auto")),
weights_dir=(env.get("EMBGEMMA_WEIGHTS_DIR") or None),
cpu_threads=_int(env, "EMBGEMMA_CPU_THREADS", 0, 0, 256),
)