File size: 5,883 Bytes
f882f26 | 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 | # SPDX-License-Identifier: Apache-2.0
"""Checkpoints (compile-time profiles), their location and their configuration.
The Hub repo ``convaiinnovations/laya`` holds three classic-encoder checkpoints: the English one at the root (what
``laya.Agent("convaiinnovations/laya")`` loads), ``multilingual/`` and ``typed-decisions/``. Each directory has
``rl_agent_config.json`` (decision engine + calibration), ``encoder/config.json`` (ModernBERT architecture),
``tokenizer/`` and ``model.safetensors`` (fp16). Nothing here imports torch or ttnn.
"""
from __future__ import annotations
import json
import os
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Tuple
HF_REPO = "convaiinnovations/laya"
HF_REVISION = "246177e5cb70334c9831c0730864a93c836aac8f"
PROFILES: Dict[str, str] = {"english": "", "multilingual": "multilingual", "typed-decisions": "typed-decisions"}
DEFAULT_PROFILE = "english"
FILES = ("rl_agent_config.json", "model.safetensors", "encoder/config.json", "tokenizer/tokenizer.json",
"tokenizer/tokenizer_config.json")
def allow_patterns(profiles=None) -> List[str]:
out = []
for p in (profiles or PROFILES):
sub = PROFILES[p]
out += [(sub + "/" if sub else "") + f for f in FILES]
return out
@dataclass(frozen=True)
class Arch:
"""The decision model's shapes (ModernBERT encoder + 2-layer decision head)."""
hidden: int
layers: int
heads: int
inter: int # GeGLU half width (Wi is [2 * inter, hidden])
vocab: int
max_positions: int
layer_types: Tuple[str, ...]
theta_global: float
theta_local: float
window: int # |q - k| <= window on sliding layers (local_attention // 2)
norm_eps: float
head_layers: int
head_ffn: int
n_act: int
@property
def head_dim(self) -> int:
return self.hidden // self.heads
def is_global(self, l: int) -> bool:
return self.layer_types[l] == "full_attention"
@dataclass
class Checkpoint:
profile: str
path: str
cfg: dict
ecfg: dict
arch: Arch
revision: Optional[str] = None
@property
def max_len(self) -> int:
return int(self.cfg.get("max_len", 512))
@property
def head_max_len(self) -> int:
return int(self.cfg.get("head_max_len", 192))
def arch_from(cfg: dict, ecfg: dict) -> Arch:
rope = ecfg.get("rope_parameters") or {}
tg = (rope.get("full_attention") or {}).get("rope_theta", ecfg.get("global_rope_theta", 160000.0))
tl = (rope.get("sliding_attention") or {}).get("rope_theta", ecfg.get("local_rope_theta", 10000.0))
n = int(ecfg["num_hidden_layers"])
types = ecfg.get("layer_types") or ["full_attention" if i % int(ecfg.get("global_attn_every_n_layers", 3)) == 0
else "sliding_attention" for i in range(n)]
d = int(ecfg["hidden_size"])
if ecfg.get("hidden_activation", "gelu") != "gelu" or ecfg.get("attention_bias") or ecfg.get("mlp_bias") \
or ecfg.get("norm_bias"):
raise ValueError("unsupported ModernBERT variant (activation / biases): %r" % {k: ecfg.get(k) for k in (
"hidden_activation", "attention_bias", "mlp_bias", "norm_bias")})
if cfg.get("option_layout", "sequential") != "sequential":
raise ValueError("option_layout=%r is not supported (only the sequential layout every published checkpoint "
"uses)" % cfg.get("option_layout"))
return Arch(hidden=d, layers=n, heads=int(ecfg["num_attention_heads"]), inter=int(ecfg["intermediate_size"]),
vocab=int(ecfg["vocab_size"]), max_positions=int(ecfg.get("max_position_embeddings", 8192)),
layer_types=tuple(types), theta_global=float(tg), theta_local=float(tl),
window=int(ecfg.get("local_attention", 128)) // 2, norm_eps=float(ecfg.get("norm_eps", 1e-5)),
head_layers=int(cfg.get("head_layers", 2)), head_ffn=4 * d,
n_act=len(cfg.get("act_costs", {})) + 1)
def resolve_dir(profile: str, root: Optional[str] = None, revision: Optional[str] = None,
download: bool = True) -> Tuple[str, Optional[str]]:
"""The checkpoint directory of ``profile``: ``root`` (a local snapshot of the repo, e.g. LAYA_WEIGHTS_DIR) or
the pinned Hub snapshot (downloaded once into the HF cache, or from the cache only with ``download=False``)."""
if profile not in PROFILES:
raise ValueError("unknown profile %r: one of %s" % (profile, sorted(PROFILES)))
sub = PROFILES[profile]
if root:
d = os.path.join(root, sub) if sub and os.path.isdir(os.path.join(root, sub)) else root
return d, None
from huggingface_hub import snapshot_download
rev = revision or HF_REVISION
snap = snapshot_download(HF_REPO, revision=rev, allow_patterns=allow_patterns([profile]),
local_files_only=not download)
return (os.path.join(snap, sub) if sub else snap), rev
def load_checkpoint(profile: str, root: Optional[str] = None, revision: Optional[str] = None,
download: bool = True) -> Checkpoint:
d, rev = resolve_dir(profile, root, revision, download)
with open(os.path.join(d, "rl_agent_config.json")) as f:
cfg = json.load(f)
with open(os.path.join(d, "encoder", "config.json")) as f:
ecfg = json.load(f)
return Checkpoint(profile=profile, path=d, cfg=cfg, ecfg=ecfg, arch=arch_from(cfg, ecfg), revision=rev)
def load_state_dict(ck: Checkpoint, dtype: str = "float32") -> Dict[str, "object"]:
"""The checkpoint's tensors as torch tensors (fp16 on disk -> ``dtype``)."""
import torch
from safetensors.torch import load_file
sd = load_file(os.path.join(ck.path, "model.safetensors"))
dt = getattr(torch, dtype)
return {k: v.to(dt) for k, v in sd.items()}
|