# SPDX-License-Identifier: Apache-2.0 """Golden access for device / host tests. Nothing here points into a particular machine: the official float32 goldens (research `gen_golden.py` output) come from ``EMBGEMMA_GOLDEN``, the research golden scripts (`cases.py`, `gen_golden.py`, needed by dev_e2e.py and one front-end test) from ``EMBGEMMA_GOLDEN_SRC``, the weights from ``EMBGEMMA_WEIGHTS_DIR`` or the pinned revision in the local HF cache. Tests skip when a source is missing.""" from __future__ import annotations import json import os import numpy as np WEIGHTS_REPO = "google/embeddinggemma-2" WEIGHTS_REVISION = "f9972ac22e696a105c482202646979e33e4b5a1e" # == tt-model.yaml weights.revision GOLDEN = os.environ.get("EMBGEMMA_GOLDEN", "") GOLDEN_SRC = os.environ.get("EMBGEMMA_GOLDEN_SRC", "") def model_dir() -> str: """``EMBGEMMA_WEIGHTS_DIR`` or the pinned snapshot in the local HF cache (no download); "" when neither exists.""" d = os.environ.get("EMBGEMMA_WEIGHTS_DIR") if d: return d try: from huggingface_hub import snapshot_download return snapshot_download(WEIGHTS_REPO, revision=os.environ.get("TT_MODEL_WEIGHTS_REVISION", WEIGHTS_REVISION), local_files_only=True) except Exception: # noqa: BLE001 -- not cached here return "" MODEL = model_dir() def golden_available(tag: str = "text_fp32_hooks") -> bool: return bool(GOLDEN) and os.path.isfile(os.path.join(GOLDEN, tag + ".json")) def golden_module(name: str): """research/embgemma/golden/.py from ``EMBGEMMA_GOLDEN_SRC`` (None when unset).""" import importlib.util import sys if not GOLDEN_SRC: return None path = os.path.join(GOLDEN_SRC, name + ".py") if not os.path.isfile(path): return None spec = importlib.util.spec_from_file_location(f"embgemma_{name}", path) m = importlib.util.module_from_spec(spec) sys.modules[f"embgemma_{name}"] = m spec.loader.exec_module(m) return m def load(tag): from safetensors.numpy import load_file p = os.path.join(GOLDEN, tag + ".safetensors") return load_file(p), json.load(open(os.path.join(GOLDEN, tag + ".json"))) def cos(a, b): a = np.asarray(a, np.float64).ravel() b = np.asarray(b, np.float64).ravel() return float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b) + 1e-30)) def unit(x): x = np.asarray(x, np.float64) return x / np.linalg.norm(x, axis=-1, keepdims=True)