2"""Family-based model resolution for LLMs beyond the catalog."""
4from __future__
import annotations
8from pathlib
import Path
11_RUNTIME_LLM: dict[str, dict[str, Any]] = {}
12FAMILY_MODEL_DIR = Path.home() /
".aquin" /
"family_models"
15_MODEL_TYPE_TO_FAMILY: dict[str, str] = {
27_ARCH_HINTS: tuple[tuple[str, str], ...] = (
33 (
"GPTNeoX",
"pythia"),
38LLM_FAMILIES: list[dict[str, Any]] = [
42 "hf_patterns": (re.compile(
r"^(?:openai/)?gpt2(?:-|$)", re.I),),
43 "lora_target_modules": [
"c_attn",
"c_fc"],
44 "hook":
"blocks.{layer}.hook_resid_post",
45 "examples": [
"gpt2",
"gpt2-medium",
"gpt2-large",
"gpt2-xl"],
46 "trust_remote_code":
False,
51 "hf_patterns": (re.compile(
r"^EleutherAI/pythia", re.I),),
52 "slug_prefix":
"EleutherAI/",
53 "lora_target_modules": [
"query_key_value",
"dense"],
54 "hook":
"blocks.{layer}.hook_resid_post",
56 "EleutherAI/pythia-160m-deduped",
57 "EleutherAI/pythia-410m-deduped",
58 "EleutherAI/pythia-1.4b-deduped",
59 "EleutherAI/pythia-2.8b",
61 "trust_remote_code":
False,
67 re.compile(
r"^meta-llama/Llama", re.I),
68 re.compile(
r"^meta-llama/Meta-Llama", re.I),
70 "lora_target_modules": [
"q_proj",
"v_proj"],
71 "hook":
"blocks.{layer}.hook_resid_post",
73 "meta-llama/Llama-3.2-1B-Instruct",
74 "meta-llama/Llama-3.2-3B-Instruct",
75 "meta-llama/Llama-3.1-8B-Instruct",
77 "trust_remote_code":
False,
81 "label":
"LFM (Liquid AI)",
82 "hf_patterns": (re.compile(
r"^LiquidAI/LFM", re.I),),
83 "lora_target_modules": [
"q_proj",
"v_proj"],
84 "hook":
"blocks.{layer}.hook_resid_post",
86 "LiquidAI/LFM2.5-1.2B-Instruct",
87 "LiquidAI/LFM2.5-1.2B-Thinking",
88 "LiquidAI/LFM2.5-230M",
90 "trust_remote_code":
False,
98 re.compile(
r"^Qwen/Qwen", re.I),
99 re.compile(
r"(?i)(?:^|/)[^/\s]*qwen"),
101 "lora_target_modules": [
"q_proj",
"v_proj"],
102 "hook":
"blocks.{layer}.hook_resid_post",
105 "Qwen/Qwen2.5-7B-Instruct",
106 "Qwen/Qwen2.5-0.5B-Instruct",
108 "trust_remote_code":
False,
116 """Stable Aquin slug from a HuggingFace repo id."""
117 part = hf_name.split(
"/")[-1].lower()
118 part = re.sub(
r"[^a-z0-9._-]+",
"-", part).strip(
"-")
119 return part
or "model"
122def _match_family(hf_name: str, families: list[dict[str, Any]]) -> dict[str, Any] |
None:
124 for pat
in fam.get(
"hf_patterns", ()):
125 if pat.search(hf_name):
131 for fam
in LLM_FAMILIES:
132 if fam[
"id"] == family_id:
138 """Infer LLM family from HuggingFace config when the repo id is not an official org prefix.
140 Covers fine-tunes (e.g. Hahmdong/*-qwen3-*) that keep the base architecture in config.json.
143 from transformers
import AutoConfig
145 cfg = AutoConfig.from_pretrained(hf_name, trust_remote_code=
True)
149 model_type = str(getattr(cfg,
"model_type",
"")
or "").lower()
150 fam_id = _MODEL_TYPE_TO_FAMILY.get(model_type)
154 arches = getattr(cfg,
"architectures",
None)
or []
157 for hint, fid
in _ARCH_HINTS:
158 if hint.lower()
in name.lower():
164 raw = (model_id
or "").strip()
169 if re.match(
r"^gpt2(?:-|$)", raw, re.I):
171 if raw.lower().startswith(
"pythia"):
172 return f
"EleutherAI/{raw}"
177def _infer_llm_dims(hf_name: str, *, trust_remote_code: bool) -> tuple[int, int]:
178 from transformers
import AutoConfig
180 cfg = AutoConfig.from_pretrained(hf_name, trust_remote_code=trust_remote_code)
182 getattr(cfg,
"num_hidden_layers",
None)
183 or getattr(cfg,
"n_layer",
None)
184 or getattr(cfg,
"n_layers", 0)
187 getattr(cfg,
"hidden_size",
None)
188 or getattr(cfg,
"n_embd",
None)
189 or getattr(cfg,
"d_model", 0)
191 if n_layers < 1
or d_model < 1:
192 raise ValueError(f
"Could not infer layer count / width for {hf_name}")
193 return d_model, n_layers
198 from transformers
import AutoConfig
200 trust = bool(family.get(
"trust_remote_code",
False))
202 hcfg = AutoConfig.from_pretrained(hf_name, trust_remote_code=trust)
204 getattr(hcfg,
"num_attention_heads",
None)
205 or getattr(hcfg,
"n_head",
None)
208 sae_layer = max(0, n_layers // 2)
210 cfg: dict[str, Any] = {
213 "n_layers": n_layers,
215 "sae_layer": sae_layer,
216 "sae_source":
"user",
218 "family": family[
"id"],
219 "hook_template": family.get(
"hook",
"blocks.{layer}.hook_resid_post"),
220 "lora_target_modules": list(family.get(
"lora_target_modules", [
"q_proj",
"v_proj"])),
221 "trust_remote_code": trust,
225 if family.get(
"hf_only"):
226 cfg[
"hf_only"] =
True
227 if family.get(
"hf_first"):
228 cfg[
"hf_first"] =
True
234 FAMILY_MODEL_DIR.mkdir(parents=
True, exist_ok=
True)
235 payload = {k: v
for k, v
in cfg.items()
if not str(k).startswith(
"_")}
236 path = FAMILY_MODEL_DIR / f
"{slug}.json"
237 path.write_text(json.dumps(payload, indent=2), encoding=
"utf-8")
241 path = FAMILY_MODEL_DIR / f
"{slug}.json"
242 if not path.is_file():
245 data = json.loads(path.read_text(encoding=
"utf-8"))
248 return data
if isinstance(data, dict)
else None
252 if slug
in _RUNTIME_LLM:
253 return _RUNTIME_LLM[slug]
256 _RUNTIME_LLM[slug] = cfg
262 """Resolve catalog-external LLM slug or HF id via family rules. Raises ValueError if unsupported."""
263 raw = (model_id
or "").strip()
265 raise ValueError(
"model_id required")
274 if not family
and "/" in hf_name:
276 if not family
and "/" not in hf_name:
278 f
"Unknown LLM '{model_id}'. Pass a HuggingFace repo id "
279 f
"(e.g. gpt2-medium, EleutherAI/pythia-410m-deduped, meta-llama/Llama-3.2-3B-Instruct)."
283 f
"LLM '{hf_name}' is not in a supported family yet. "
284 f
"Supported: GPT-2, Pythia (EleutherAI/pythia-*), Llama (meta-llama/Llama*), "
285 f
"LFM (LiquidAI/LFM*), Qwen (Qwen/Qwen* and fine-tunes with qwen in the name / "
286 f
"qwen2|qwen3 architecture)."
295 _RUNTIME_LLM[slug] = cfg
303 raw = (model_id
or "").strip()
307 if "/" not in hf_name
and not re.match(
r"^gpt2", raw, re.I):
314 lines = [
"Model families (pass HuggingFace repo id to aquin load --model):",
""]
315 lines.append(
"LLMs:")
316 for fam
in LLM_FAMILIES:
317 ex =
", ".join(fam.get(
"examples", [])[:3])
318 lines.append(f
" {fam['label']}: {ex}")
320 lines.append(
"Load SAEs with: aquin load sae <model-l{n}> or --path <file.pt>")
321 lines.append(
"Family models use inspection tools; self-train SAE: aquin sae train (see /docs/sae-training).")
tuple[int, int] _infer_llm_dims(str hf_name, *, bool trust_remote_code)
dict[str, Any] build_llm_family_config(str hf_name, dict[str, Any] family)
dict[str, Any]|None _match_family_from_hf_config(str hf_name)
None _persist_family_config(str slug, dict[str, Any] cfg)
dict[str, Any]|None _load_family_config_from_disk(str slug)
str _slug_from_hf(str hf_name)
bool is_llm_family_candidate(str model_id)
tuple[str, dict[str, Any]] resolve_llm_family(str model_id)
str|None normalize_llm_hf_id(str model_id)
dict[str, Any]|None _family_by_id(str family_id)
dict[str, Any]|None get_runtime_llm_config(str slug)
dict[str, Any]|None _match_family(str hf_name, list[dict[str, Any]] families)
list[str] family_help_lines()