Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: route models by CONFIG_MAPPING_NAMES instead of hardcoded tables (#7043)

Daniel Han97161c89d6fd
diff --git a/studio/backend/utils/transformers_version.py b/studio/backend/utils/transformers_version.py
index 81d534a7c2e..a69673f0815 100644
--- a/studio/backend/utils/transformers_version.py
+++ b/studio/backend/utils/transformers_version.py
@@ -28,7 +28,9 @@ Strategy:
sys.path swap using the same directories pre-installed by setup.sh.
"""
+import ast
import importlib
+import importlib.util
import json
import structlog
from loggers import get_logger
@@ -872,6 +874,116 @@ def _cached_config_json(model_name: str, hf_token: str | None) -> dict | None:
return _config_json_cache.get(_token_cache_key(model_name, hf_token))
+# --- Static tier from CONFIG_MAPPING_NAMES (AST only: no import/network/exec) ---
+# A model_type absent from an overlay's mapping can't load there. Parse each sidecar's
+# config map from source and pick the lowest tier that ships it, so a new arch routes
+# correctly with no per-model table edit. Only ever upgrades default, never lowers.
+_config_mapping_cache: dict[str, frozenset[str]] = {}
+
+
+def _overlay_transformers_dir(tier: str) -> str | None:
+ """transformers source dir for a tier, located without importing it."""
+ if tier != "default":
+ root = {"530": _VENV_T5_530_DIR, "550": _VENV_T5_550_DIR, "510": _VENV_T5_510_DIR}.get(tier)
+ src = os.path.join(root, "transformers") if root else None
+ return src if src and _safe_is_dir(Path(src)) else None
+ # default: the base 4.x transformers. find_spec resolves to a 5.x sidecar if one
+ # is already on sys.path, so skip any .venv_t5_* / llmcompressor overlay dir.
+ sidecars = tuple(
+ os.path.abspath(d) + os.sep
+ for d in (_VENV_T5_530_DIR, _VENV_T5_550_DIR, _VENV_T5_510_DIR, _VENV_LLMCOMPRESSOR_DIR)
+ )
+ candidates = []
+ try:
+ spec = importlib.util.find_spec("transformers")
+ if spec and spec.origin:
+ candidates.append(os.path.dirname(spec.origin))
+ except Exception:
+ pass
+ candidates += [os.path.join(e, "transformers") for e in sys.path if e]
+ for c in candidates:
+ if _safe_is_dir(Path(c)) and not os.path.abspath(c).startswith(sidecars):
+ return c
+ return None
+
+
+def _mapping_first_keys(value: ast.AST) -> set[str]:
+ """First keys of a dict literal, or of an OrderedDict(...)/dict(...)/.update(...)
+ built from 2-tuple lists and **{...} unpacking."""
+
+ def keys_of(node):
+ if isinstance(node, ast.Dict):
+ return list(node.keys)
+ if isinstance(node, (ast.List, ast.Tuple)):
+ return [
+ el.elts[0] for el in node.elts if isinstance(el, (ast.Tuple, ast.List)) and el.elts
+ ]
+ return []
+
+ nodes = keys_of(value)
+ if isinstance(value, ast.Call):
+ for a in value.args:
+ nodes += keys_of(a)
+ for kw in value.keywords: # **{...} unpacking has kw.arg is None
+ if kw.arg is None:
+ nodes += keys_of(kw.value)
+ return {n.value for n in nodes if isinstance(n, ast.Constant) and isinstance(n.value, str)}
+
+
+def _config_model_types(tier: str) -> frozenset[str]:
+ """model_type keys in a tier's CONFIG_MAPPING_NAMES (5.10 moved it to auto_mappings.py)."""
+ cached = _config_mapping_cache.get(tier)
+ if cached is not None:
+ return cached
+ tdir = _overlay_transformers_dir(tier)
+ if tdir is None:
+ return frozenset() # overlay not provisioned yet; do not cache so a later call re-reads
+ keys: set[str] = set()
+ for rel in ("models/auto/configuration_auto.py", "models/auto/auto_mappings.py"):
+ path = Path(tdir) / rel
+ if not _safe_is_file(path):
+ continue
+ try:
+ tree = ast.parse(path.read_text(encoding = "utf-8"))
+ for node in ast.walk(tree):
+ # direct binding, or a CONFIG_MAPPING_NAMES.update({...}) mutation
+ if isinstance(node, ast.Assign) and any(
+ isinstance(t, ast.Name) and t.id == "CONFIG_MAPPING_NAMES" for t in node.targets
+ ):
+ keys |= _mapping_first_keys(node.value)
+ elif isinstance(node, ast.Expr) and isinstance(node.value, ast.Call):
+ fn = node.value.func
+ if (
+ isinstance(fn, ast.Attribute)
+ and fn.attr == "update"
+ and isinstance(fn.value, ast.Name)
+ and fn.value.id == "CONFIG_MAPPING_NAMES"
+ ):
+ keys |= _mapping_first_keys(node.value)
+ except Exception:
+ continue
+ result = frozenset(keys)
+ _config_mapping_cache[tier] = result
+ return result
+
+
+def _tier_from_config_mapping(cfg: dict) -> str | None:
+ """Lowest tier whose transformers ships cfg's model_type, or None if unknown."""
+ model_type = cfg.get("model_type")
+ if not isinstance(model_type, str):
+ for key in _NESTED_CONFIG_KEYS:
+ sub = cfg.get(key)
+ if isinstance(sub, dict) and isinstance(sub.get("model_type"), str):
+ model_type = sub["model_type"]
+ break
+ if not isinstance(model_type, str):
+ return None
+ for tier in sorted(_TIER_RANK, key = _TIER_RANK.get):
+ if model_type in _config_model_types(tier):
+ return tier
+ return None
+
+
# --- AutoConfig probe: general tier resolution for ambiguous models ----------
# When the cheap signals only say "needs some 5.x", parse config.json with the built-in
# parser in each candidate sidecar (lowest first) instead of guessing. Generalizes beyond
@@ -1212,6 +1324,14 @@ def get_transformers_tier(
match,
)
return tier
+ static = _tier_from_config_mapping(cfg)
+ if static is not None and static != "default":
+ logger.info(
+ "Transformers tier %s selected for %s (config mapping: model_type absent below)",
+ static,
+ model_name,
+ )
+ return static
local_tc = Path(model_name) / "tokenizer_config.json"
if _safe_is_file(local_tc) and _check_tokenizer_config_needs_v5(model_name, hf_token):
if not probe:
@@ -1271,6 +1391,18 @@ def get_transformers_tier(
return override
logger.info("Transformers tier 530 selected for %s (config.json check)", model_name)
return "530"
+ # _load_config_json (not the cache-only reader) so a config served from the hub
+ # cache during a transient outage still feeds the mapping resolver.
+ remote_cfg = _load_config_json(model_name, hf_token)
+ if remote_cfg is not None:
+ static = _tier_from_config_mapping(remote_cfg)
+ if static is not None and static != "default":
+ logger.info(
+ "Transformers tier %s selected for %s (config mapping: model_type absent below)",
+ static,
+ model_name,
+ )
+ return static
if _check_tokenizer_config_needs_v5(model_name, hf_token):
if not probe:
return "530"