# SPDX-License-Identifier: Apache-2.0 """Server-start configuration (the COMPILE-TIME surface of research/laya/ARCH.md section 5): every ``LAYA_*`` variable is read once here; a bad value raises ``ValueError`` naming the variable. Standard library only.""" from __future__ import annotations import json import os from dataclasses import asdict, dataclass, field from typing import Dict, Mapping, Optional, Tuple REPO = "changh95/laya" ENGINES = ("mk", "ttnn", "cpu") FIDELITIES = ("HiFi4", "HiFi3", "HiFi2") PROFILES = ("english", "typed-decisions", "multilingual") MK_MAX_TOKENS = 512 # rows the megakernel runs (16 row tiles); longer rows use the ttnn engine @dataclass(frozen=True) class ServeConfig: profile: str = "english" engine: str = "mk" max_len: int = 0 # 0 = the checkpoint's (512 english, 1024 others); per-request max_len <= this max_batch: int = 32 # states per device batch (runtime batch is 1 .. max_batch) max_inputs: int = 1024 # states per HTTP request max_questions: int = 64 # questions per request (official laya-serve limit) max_options: int = 100 # options per question (the official laya-serve limit; device engines <= 127) fidelity: str = "HiFi4" weights: str = "bf16" seq_buckets: Tuple[int, ...] = (64, 128, 256, 512) # ttnn engine batch_buckets: Tuple[int, ...] = (1, 2, 4, 8, 16, 32) # ttnn engine batch_window_ms: float = 0.0 queue_depth: int = 256 queue_timeout_s: float = 60.0 trace: bool = True warmup: bool = True dispatch: str = "eth" weights_dir: Optional[str] = None revision: Optional[str] = None calibration: Optional[str] = None # JSON file: temperature / temperature_by_options (official format) lang_temperatures: Optional[str] = None # JSON text or file: {lang: {temperature, temperature_by_options}} api_key: Optional[str] = None max_body_mb: float = 32.0 max_state_chars: int = 50000 # characters of one state's text (official laya-serve: 50,000 -> 413); 0 = no cap warmup_long_tokens: int = 8192 # start-up: compile the long-row (tt-nn) buckets with batch x length <= this cpu_threads: int = 0 extra: Dict[str, str] = field(default_factory=dict) def as_dict(self) -> Dict: d = asdict(self) d["seq_buckets"] = list(self.seq_buckets) d["batch_buckets"] = list(self.batch_buckets) d["api_key"] = "set" if self.api_key else None 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}: expected 0/1") 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 v = v.strip() for c in choices: if v.lower() == c.lower(): return c raise ValueError(f"{k}={v!r}: expected one of {', '.join(choices)}") def _ints(env: Mapping[str, str], k: str, d: Tuple[int, ...], lo: int, hi: int, mult: int = 1) -> 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(not lo <= x <= hi or x % mult for x in xs): raise ValueError(f"{k}={v!r}: values in [{lo}, {hi}]" + (f", multiples of {mult}" if mult > 1 else "")) return xs def _json_opt(env: Mapping[str, str], k: str) -> Optional[str]: v = env.get(k) if v is None or v.strip() == "": return None v = v.strip() try: if os.path.isfile(v): with open(v) as f: json.load(f) else: json.loads(v) except (OSError, ValueError) as e: raise ValueError(f"{k}: not a JSON file or JSON text ({e})") from None return v DEFAULT_MAX_LEN = {"english": 512, "typed-decisions": 1024, "multilingual": 1024} def resolve_config(env: Optional[Mapping[str, str]] = None) -> ServeConfig: env = os.environ if env is None else env profile = _choice(env, "LAYA_PROFILE", "english", PROFILES) max_len = _int(env, "LAYA_MAX_LEN", DEFAULT_MAX_LEN[profile], 64, 8192) engine = _choice(env, "LAYA_ENGINE", "mk", ENGINES) seq_default = tuple(s for s in (64, 128, 256, 512, 1024, 2048, 4096, 8192) if s <= max(512, max_len)) if max_len > max(seq_default): seq_default = seq_default + (max_len + (-max_len) % 32,) cfg = ServeConfig( profile=profile, engine=engine, max_len=max_len, max_batch=_int(env, "LAYA_MAX_BATCH", 32, 1, 256), max_inputs=_int(env, "LAYA_MAX_INPUTS", 1024, 1, 65536), max_questions=_int(env, "LAYA_MAX_QUESTIONS", 64, 1, 256), max_options=_int(env, "LAYA_MAX_OPTIONS", 100, 1, 127), fidelity=_choice(env, "LAYA_FIDELITY", "HiFi4", FIDELITIES), weights=_choice(env, "LAYA_WEIGHTS", "bf16", ("bf16",)), seq_buckets=_ints(env, "LAYA_SEQ_BUCKETS", seq_default, 64, 8192, 32), # >= 64: an even SDPA key-chunk count batch_buckets=_ints(env, "LAYA_BATCH_BUCKETS", (1, 2, 4, 8, 16, 32), 1, 256), batch_window_ms=_float(env, "LAYA_BATCH_WINDOW_MS", 0.0, 0.0, 100.0), queue_depth=_int(env, "LAYA_QUEUE_DEPTH", 256, 1, 100000), queue_timeout_s=_float(env, "LAYA_QUEUE_TIMEOUT_S", 60.0, 1.0, 3600.0), trace=_bool(env, "LAYA_TRACE", True), warmup=_bool(env, "LAYA_WARMUP", True), dispatch=_choice(env, "LAYA_DISPATCH", "eth", ("eth", "worker", "auto")), weights_dir=(env.get("LAYA_WEIGHTS_DIR") or None), revision=(env.get("TT_MODEL_WEIGHTS_REVISION") or env.get("TT_WEIGHTS_REVISION") or None), calibration=_json_opt(env, "LAYA_CALIBRATION"), lang_temperatures=_json_opt(env, "LAYA_LANG_TEMPERATURES"), api_key=(env.get("LAYA_API_KEY") or None), max_body_mb=_float(env, "LAYA_MAX_BODY_MB", 32.0, 0.1, 4096.0), max_state_chars=_int(env, "LAYA_MAX_STATE_CHARS", 50000, 0, 100_000_000), warmup_long_tokens=_int(env, "LAYA_WARMUP_LONG_TOKENS", 8192, 0, 262144), cpu_threads=_int(env, "LAYA_CPU_THREADS", 0, 0, 256), ) if cfg.engine == "ttnn" and max(cfg.seq_buckets) < cfg.max_len: raise ValueError(f"LAYA_SEQ_BUCKETS {cfg.seq_buckets}: the largest bucket must cover LAYA_MAX_LEN {cfg.max_len}") return cfg def load_json_opt(v: Optional[str]): if v is None: return None if os.path.isfile(v): with open(v) as f: return json.load(f) return json.loads(v)