Download backend/models.py from localailb/assistant: direct link, hf CLI and curl.
- Browser
- Download file 128 kB
-
https://huggingface.co/spaces/localailb/assistant/resolve/main/backend/models.py
- Command line
-
hf download hf://spaces/localailb/assistant/backend/models.py
-
curl -L -o models.py https://huggingface.co/spaces/localailb/assistant/resolve/main/backend/models.py
128 kB
"""
models.py β Lazy-loaded model backends: embedding model, ChromaDB handle,
text LLM (HuggingFace or GGUF via llama_backend), Vision LLM, and
Speech-to-Text pipeline. Each model type keeps its own module-level cache
and lock, following the lazy-load/lock pattern used throughout the app.
"""
import gc
import os
import threading
import time
from pathlib import Path
from typing import Any, Optional
import torch
from backend import llama_backend
from backend import model_registry as mr
from backend import whisper_cpp_backend
from backend.hardware import DEVICE, TORCH_DTYPE, is_illegal_instruction_error
from backend.live_stream import get_bus
from backend.metadata_hardening import harden_metadata
from ui import i18n
from ui.i18n import LANGUAGES
harden_metadata()
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Patch transformers' Gemma-4 RoPE device-mismatch bug:
# In transformers, Gemma4TextRotaryEmbedding.forward does matrix
# multiplication `@` with position_ids on CPU and inv_freq on CUDA when
# device_map="cuda" is used, causing "Expected all tensors to be on the
# same device" RuntimeError.
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
try:
from transformers.models.gemma4 import modeling_gemma4
_orig_gemma4_rotary_forward = modeling_gemma4.Gemma4TextRotaryEmbedding.forward
def _patched_gemma4_rotary_forward(self, x, position_ids, layer_type=None):
if position_ids is not None and position_ids.device != x.device:
position_ids = position_ids.to(x.device)
return _orig_gemma4_rotary_forward(self, x, position_ids, layer_type=layer_type)
modeling_gemma4.Gemma4TextRotaryEmbedding.forward = _patched_gemma4_rotary_forward
print("[Gemma4] Applied RoPE device-alignment patch for Gemma4TextRotaryEmbedding.")
except Exception:
pass
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Download size estimation β BF16 download sizes in GB for each model
# (from Google's official docs and HuggingFace model cards). Used to
# warn the user before downloading large models they haven't cached yet.
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
_DOWNLOAD_SIZE_GB = mr.DOWNLOAD_SIZE_GB
def _hf_snapshot_has_weights(model_id: str) -> bool:
"""True when the model's local HF cache snapshot contains at least one
real weight file.
Metadata alone proves nothing: ``snapshot_download`` fetches the tiny
config/tokenizer files FIRST, so an interrupted download still caches
config.json / generation_config.json β which made ``is_model_cached``
report "cached" while the multi-GB safetensors were still downloading
(the false "Download complete" popup). Weight files are only linked into
``snapshots/`` once their blob is complete; an in-progress download lives
in ``blobs/*.incomplete`` and never appears here."""
if not model_id:
return False
try:
# huggingface_hub 1.x keeps the constant in .constants (no top-level export)
from huggingface_hub.constants import HF_HUB_CACHE
cache_root = HF_HUB_CACHE
except Exception:
cache_root = os.environ.get("HF_HUB_CACHE") or os.path.join(
os.environ.get("HF_HOME") or os.path.join(os.path.expanduser("~"), ".cache"),
"huggingface", "hub",
)
repo_dir = os.path.join(cache_root, "models--" + str(model_id).replace("/", "--"))
snaps = os.path.join(repo_dir, "snapshots")
if not os.path.isdir(snaps):
return False
weight_exts = (".safetensors", ".bin", ".gguf", ".pt", ".th", ".msgpack", ".h5", ".onnx")
try:
for root, _dirs, files in os.walk(snaps):
for fn in files:
if fn.lower().endswith(weight_exts):
return True
try:
if os.stat(os.path.join(root, fn)).st_size >= 1024 * 1024:
return True
except OSError:
continue
except OSError:
return False
return False
def is_model_cached(model_id: str) -> bool:
"""Check if a HuggingFace model or GGUF model is already cached locally."""
if not model_id:
return False
if str(model_id).lower().endswith(".gguf") and os.path.isfile(model_id):
return True
# GGUF quant-pinned id form "repo#filename.gguf"
if "#" in model_id:
parts = model_id.split("#", 2)
repo_id = parts[0]
filename = parts[1] if len(parts) > 1 else None
if filename:
try:
from backend import llama_backend
# Search EVERY standard model folder β the configured GGUF
# dir, the whisper.cpp dir and the user_data/gguf_models
# fallback. The old llama-dir-only check never saw a model
# downloaded into the fallback (no folder configured), so
# the download popup re-appeared on every pick.
if llama_backend.find_downloaded_model_file(filename):
return True
except Exception:
pass
try:
from huggingface_hub import try_to_load_from_cache
res = try_to_load_from_cache(repo_id, filename)
if res is not None and not isinstance(res, type(None)):
return True
except Exception:
pass
return False
# Check known GGUF repos
try:
from backend import llama_backend
if model_id in llama_backend.KNOWN_GGUF_REPOS:
info = llama_backend.KNOWN_GGUF_REPOS[model_id]
fn = info.get("main")
if fn:
mdir = Path(llama_backend.LLAMA_CPP_MODEL_DIR)
if mdir.exists() and llama_backend._find_gguf_in_model_tree(mdir, fn):
return True
from huggingface_hub import try_to_load_from_cache
res = try_to_load_from_cache(model_id, fn)
if res is not None and not isinstance(res, type(None)):
return True
except Exception:
pass
try:
# A cached config.json / generation_config.json alone proves NOTHING β
# snapshot_download fetches small metadata first, so an interrupted
# download still has them and the old check reported "cached" while
# the multi-GB weights were still downloading (the false "Download
# complete" popup). Require a real weight file in the snapshot.
return _hf_snapshot_has_weights(model_id)
except Exception:
return False
def get_download_size_gb(model_id: str) -> Optional[float]:
"""Return estimated BF16 download size in GB, or None if unknown."""
return _DOWNLOAD_SIZE_GB.get(model_id)
def check_model_download(model_id: str) -> Optional[str]:
"""Return a warning message if the model needs downloading, or None
if it's already cached or is a GGUF/local file."""
if is_model_cached(model_id):
return None
size_gb = get_download_size_gb(model_id)
if size_gb is None:
return f"Model '{model_id}' will be downloaded (size unknown)."
if size_gb >= 20:
return (
f"β οΈ '{model_id}' is NOT cached locally and will download "
f"~{size_gb:.0f} GB. This may take a while depending on your "
f"internet speed."
)
return (
f"Model '{model_id}' will download ~{size_gb:.0f} GB."
)
_embed_model = None
_embed_model_id = None
_embed_provider = None
_embed_lock = threading.Lock()
_chroma_col = None
_chroma_client = None
_llm = None
_llm_model_id = mr.DEFAULT_LLM_MODEL
# Context window (n_ctx) the currently-loaded LLM was built with β only
# meaningful for the GGUF/llama.cpp backend (see model_registry.py's
# CONTEXT_WINDOW_OPTIONS). None until a GGUF model has actually been
# loaded at least once; HF/transformers models leave this as None too,
# since n_ctx doesn't apply to them.
_llm_n_ctx = None
# Backend key the currently-loaded LLM was (or was attempted to be) built
# for β the (model, provider, backend-mode) discriminator that must match
# for get_llm()'s early-return cache to be valid. Records the REQUESTED
# backend (not necessarily what was actually built: when llama-cpp-python
# is missing, the in-process request auto-falls back to llama-server, and
# recording the request rather than the fallback avoids a rebuild loop on
# every call). See _llm_backend_key_for().
_llm_backend_key = None
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Some newer HuggingFace checkpoints ship architectures that only
# `transformers` releases from a certain version onward know how to
# build (as opposed to older custom-arch models that ship their own
# `trust_remote_code` modeling file and work on any transformers
# version). deepreinforce-ai/Ornith-1.0-9B is one of these: it's a
# Qwen3.5 hybrid linear-/full-attention ("qwen35") architecture that
# requires transformers >= 5.8.1 to even recognize the config class β
# on an older install this fails with a confusing
# "Unrecognized configuration class" / KeyError deep inside
# AutoModelForCausalLM.from_pretrained() instead of a clear message.
# Keyed by the model ids in model_registry.ORNITH_IDS so this stays a
# single source of truth if more Ornith-family models are added later.
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
_MIN_TRANSFORMERS_VERSION = {
"ornith": "5.8.1",
# Qwen3.6 (dense Qwen3.6-27B, MoE Qwen3.6-35B-A3B) uses the "qwen3_5"
# architecture β confirmed via community reports that transformers
# <5.2.0 doesn't recognize it (same "config class not found" failure
# mode as Ornith above). Now wired into BASE_MODEL_OPTIONS (see
# model_registry.QWEN36_IDS) β loading it with an older transformers
# fails with a clear upgrade message rather than a cryptic AutoModel
# crash.
"qwen36": "5.2.0",
# Gemma 4 (E2B/E4B/12B/26B-A4B/31B) introduced the "gemma4" model type
# in transformers 5.5.0 β confirmed directly via huggingface/transformers
# issue #45376 and multiple vLLM/llm-compressor compatibility reports.
# Google's own docs recommend >=5.10.1. Below 5.5.0, AutoConfig can't
# even parse the checkpoint's config.json (fails with a confusing
# "'list' object has no attribute 'keys'" deep in tokenizer setup,
# not a clear version message) β this guard replaces that with an
# actionable error. Applies to google/gemma-4-E2B-it (the app's
# existing default!) as much as any newly-registered Gemma 4 size.
"gemma4": "5.10.1",
# Qwen3-VL (Qwen3VLForConditionalGeneration / Qwen3VLProcessor) only
# exists in transformers 5.x β the Qwen3-VL classes landed with v5.0.0.
# Below that the AutoModelForImageTextToText fallback in get_vlm() is
# used, which may not map the Qwen3-VL architecture β the guard replaces
# that gamble with a clear upgrade message.
"qwen3vl": "5.0.0",
}
# Model-id-set -> (version-guard key, human-readable architecture note).
# Checked in order; first matching set wins. Table-driven so adding a new
# guarded family is one line here instead of another elif branch.
def _version_guard_families():
return (
(mr.ORNITH_IDS, "ornith", "Qwen3.5 hybrid linear-/full-attention architecture"),
(mr.QWEN36_IDS, "qwen36", "Qwen3.6 (qwen3_5) architecture"),
(mr.GEMMA4_IDS, "gemma4", "Gemma 4 (gemma4) multimodal architecture"),
(mr.QWEN3_VL_IDS, "qwen3vl", "Qwen3-VL (qwen3_vl) multimodal architecture"),
)
def _version_tuple(version_str: str) -> tuple:
"""Parse a dotted version string into a comparable tuple of ints,
ignoring any non-numeric suffix (e.g. 'dev0', 'rc1') per component."""
parts = []
for p in str(version_str).split(".")[:3]:
digits = "".join(ch for ch in p if ch.isdigit())
parts.append(int(digits) if digits else 0)
while len(parts) < 3:
parts.append(0)
return tuple(parts)
def _check_transformers_version_for(model_id: str) -> None:
"""Raise a clear, actionable RuntimeError if the installed
`transformers` version is too old to load `model_id`, instead of
letting a cryptic internal AutoModel error surface first."""
min_version = None
arch_note = None
for id_set, guard_key, note in _version_guard_families():
if model_id in id_set:
min_version = _MIN_TRANSFORMERS_VERSION[guard_key]
arch_note = note
break
if min_version is None:
return
import transformers as _tf
installed = getattr(_tf, "__version__", "0")
if _version_tuple(installed) < _version_tuple(min_version):
raise RuntimeError(
f"'{model_id}' needs transformers >= {min_version} β it's a "
f"{arch_note} that older "
f"transformers releases don't recognize. You have {installed} "
f"installed.\n\n"
f"Upgrade with:\n"
f' pip install --upgrade "transformers>={min_version}"\n\n'
f"Then restart the app and try loading the model again."
)
_vlm_model = None
_vlm_processor = None
_vlm_model_id = None
_vlm_n_ctx = None
# Backend key the currently-loaded VLM was (or was attempted to be) built
# for β the Vision-tab analog of _llm_backend_key (see
# _vlm_backend_key_for()). Same semantics: records the REQUESTED backend so
# get_vlm()'s early-return cache can detect a provider switch that must
# rebuild (releasing a stale server-backed VLM / stopping llama-server).
_vlm_backend_key = None
_llm_lock = threading.Lock()
_vlm_lock = threading.Lock()
_stt_pipeline = None
_stt_model_id = None
_stt_lock = threading.Lock()
def _release_and_clear(global_attr: str):
"""Drop a model-holder module global BEFORE releasing the object, so
_release_model's `del obj` + gc.collect() + torch.cuda.empty_cache()
can ACTUALLY collect it.
The old order (release-then-clear) kept the module global referencing
the object while _release_model ran: `del obj` only dropped the local
param reference, gc.collect() found the object still alive, and
empty_cache() had no freed blocks to reclaim. For a transformers VLM
the outcome was worse than a no-op β `.to("cpu")` is BLOCKED by
accelerate on device_map-loaded models (Gemma-4 uses device_map="auto",
Qwen/SmolVLM device_map=DEVICE), so no weight ever left the GPU and
the whole model stayed resident: the "Free All VRAM still shows ~43%
after vision chat" leak. Returns the released object (None when the
global was already empty) so callers that need its id read it first."""
obj = globals().get(global_attr)
globals()[global_attr] = None
if obj is not None:
_release_model(obj)
return obj
def _release_model(obj):
"""Explicitly free memory held by a model before dropping the last
Python reference to it.
Just setting a global cache variable to None does NOT free GPU/CPU
memory right away:
- transformers/torch models: the CUDA caching allocator keeps the
freed blocks around until torch.cuda.empty_cache() runs (and that
can only reclaim memory from tensors that have already been
garbage-collected).
- llama.cpp (llama-cpp-python) models: the native context / KV-cache
lives in a C++ object. Its Python wrapper's __del__ will eventually
close it, but only once the GC actually runs the finalizer β which
is not guaranteed to happen before the next model tries to load,
causing an OOM when switching models back-to-back.
- Subprocess-hosted models (LlamaServerModel / LlamaServerVLMModel /
EmbeddingServerModel via llama-server.exe, WhisperServerModel via
whisper-server.exe): the real weights live in a SEPARATE process,
so no Python cleanup helps β releasing these objects stops the
managed subprocess instead (see the branches below).
Calling this before overwriting/loading a new model avoids the
"previous model didn't offload, so the next one fails to load" issue.
"""
if obj is None:
return
# llama-server (external process) backend: LlamaServerModel /
# LlamaServerVLMModel ride the CHAT llama-server subprocess, while
# EmbeddingServerModel (a GGUF embedding model) has its OWN dedicated
# embedding subprocess since the port-collision fix (a shared server
# let a RAG retrieval replace the chat GGUF with an embedding GGUF on
# the SAME port mid-conversation). None of these wrappers have an
# in-process model/KV-cache to release β the real memory lives in the
# separate llama-server subprocess. "Releasing" the object means
# stopping THAT wrapper's own server slot, not any of the
# torch/llama.cpp cleanup below (which doesn't apply β there's no
# `.llm`/`.model` attribute holding real weights in this Python
# process). EmbeddingServerModel was previously MISSED by this branch,
# so "Free All VRAM" dropped its Python wrapper while the
# llama-server.exe subprocess kept the embedding GGUF loaded in VRAM.
if isinstance(obj, EmbeddingServerModel):
# Stop ONLY the dedicated embedding server β never the chat/VLM
# server (independent slots; releasing embeddings must not take
# the chat model down).
llama_backend.stop_embed_server()
del obj
return
if isinstance(obj, (
llama_backend.LlamaServerModel,
llama_backend.LlamaServerVLMModel,
)):
llama_backend.stop_llama_server()
del obj
return
# whisper-server (external process) backend: WhisperServerModel posts to
# a separate whisper-server subprocess that holds the GGML model in VRAM
# β same story as the llama-server branch above: dropping the wrapper
# without stopping the subprocess leaves the model resident in GPU
# memory, so stopping the managed server IS the "release".
if isinstance(obj, whisper_cpp_backend.WhisperServerModel):
whisper_cpp_backend.stop_whisper_server()
del obj
return
try:
# llama.cpp backend: LlamaCppModel wraps the native llama_cpp.Llama
# instance as `.llm` β close it explicitly to free the KV-cache /
# context right now instead of waiting on GC.
inner = getattr(obj, "llm", None)
if inner is not None and hasattr(inner, "close"):
try:
inner.close()
except Exception:
pass
# transformers / smolagents TransformersModel: move the module off
# the GPU so CUDA's allocator can reclaim it. Try the WHOLE module
# first (moves every submodule incl. a VLM's .visual / .lm_head),
# then the underlying `.model` β accelerate blocks `.to()` on
# device_map-loaded models, so both attempts can fail; in that case
# the caller's _release_and_clear() ordering is what actually frees
# the object (del + gc + empty_cache with no surviving reference).
moved = False
for candidate in (obj, getattr(obj, "model", None)):
if candidate is None or not hasattr(candidate, "to") or isinstance(candidate, str):
continue
try:
candidate.to("cpu")
moved = True
break
except Exception:
continue
except Exception:
pass
del obj
gc.collect()
try:
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.cuda.ipc_collect()
elif hasattr(torch, "xpu") and torch.xpu.is_available():
torch.xpu.empty_cache()
torch.xpu.synchronize()
elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
torch.mps.empty_cache()
except Exception:
pass
def get_embed_model(model_id: Optional[str] = None, provider: Optional[str] = None):
"""Lazily build (or rebuild, if the model id or provider changed) the shared
embedding model instance.
`model_id` lets the "π§© Embedding Model" control on the Knowledge Base
tab switch models at runtime, the same way get_llm()/get_vlm() already do
for their tabs. If not given, falls back to whatever embedding model was
saved in user_config or hardware-tier recommendation for the active provider.
"""
global _embed_model, _embed_model_id, _embed_provider
prov = provider or mr.get_saved_provider("embed")
target = model_id or mr.get_default_embed_model(prov)
if _embed_model is not None and target == _embed_model_id and _embed_provider == prov:
return _embed_model
with _embed_lock:
if _embed_model is not None and target == _embed_model_id and _embed_provider == prov:
return _embed_model
if _embed_model is not None:
print(f"[RAG] Unloading previous embedding model '{_embed_model_id}' before loading '{target}' ({prov}) β¦")
_release_and_clear("_embed_model")
# ββ HF Inference API ββββββββββββββββββββββββββββββββββββββ
if target == mr.HF_INFERENCE_API_SENTINEL or prov == mr.PROVIDER_HF_API:
hf_model_id = mr.get_hf_api_model_id_for("embed")
if not hf_model_id:
raise ValueError(
"Hugging Face Inference API selected for Embedding, but no "
"model ID is configured."
)
_embed_model = InferenceApiEmbeddingModel(model_id=hf_model_id)
_embed_model_id = target
_embed_provider = prov
return _embed_model
# ββ llama.cpp server embeddings ββββββββββββββββββββββββββ
is_gguf = (
str(target).lower().endswith(".gguf")
or target in mr.PRESET_GGUF_EMBED_MODELS
or target in mr.PRESET_GGUF_EMBED_MODELS.values()
or prov in (mr.PROVIDER_SERVER, mr.PROVIDER_LLAMA_CPP_PYTHON)
)
if is_gguf:
print(f"[RAG] Starting dedicated embedding llama-server with '{target}' β¦")
base_url = llama_backend.get_or_start_embed_server(
model_path=target,
n_ctx=mr.get_saved_context_window(),
n_gpu_layers=-1, # external llama-server has its own GPU support
)
_embed_model = EmbeddingServerModel(
model_path=target, base_url=base_url,
n_ctx=mr.get_saved_context_window(),
)
_embed_model_id = target
_embed_provider = prov
return _embed_model
# ββ Local HuggingFace SentenceTransformer ββββββββββββββββ
print(f"[RAG] Loading embedding model '{target}' on {DEVICE.upper()} β¦")
from sentence_transformers import SentenceTransformer
try:
_embed_model = SentenceTransformer(target, device=DEVICE, trust_remote_code=True)
except TypeError:
_embed_model = SentenceTransformer(target, device=DEVICE)
_embed_model_id = target
_embed_provider = prov
return _embed_model
def force_reload_embed_model(target_model_id: str, provider: Optional[str] = None):
"""Used by the Knowledge Base tab's "π§© Embedding Model" Load button:
fully release whatever embedding model is currently loaded (regardless
of id) and load `target_model_id` fresh β mirrors force_reload_llm()/
force_reload_vlm()/force_reload_stt()."""
global _embed_model, _embed_model_id, _embed_provider
_release_and_clear("_embed_model")
_embed_model_id = None
_embed_provider = None
return get_embed_model(target_model_id, provider=provider)
def unload_embed_model_fn(lang_key: str = "kh") -> str:
"""Explicit "force unload from VRAM" action for the embedding model β
mirrors unload_llm_fn()/unload_vlm_fn()/unload_stt_fn()."""
global _embed_model, _embed_model_id, _embed_provider
l = LANGUAGES.get(lang_key, LANGUAGES["kh"])
if _embed_model is None:
return l["btn_unload_none"]
mid = _embed_model_id
_release_and_clear("_embed_model")
_embed_model_id = None
_embed_provider = None
return l["msg_unloaded"].format(model=mid)
def encode_texts(texts: list, normalize: bool = True, model_id: Optional[str] = None, provider: Optional[str] = None):
embed = get_embed_model(model_id=model_id, provider=provider)
# InferenceApiEmbeddingModel and EmbeddingServerModel have their own
# encode() with a different signature.
if hasattr(embed, "encode") and hasattr(embed, "model_id"):
return embed.encode(texts, normalize=normalize)
vecs = embed.encode(texts, normalize_embeddings=normalize,
show_progress_bar=False)
return vecs.tolist() if hasattr(vecs, "tolist") else vecs
def get_chroma_collection(name: str = "rag_docs"):
# NOTE: deliberately no "[RAG] ChromaDB ready β N chunks indexed."
# print here anymore. This function is called from ui.py's
# demo.load(kb.get_index_stats, ...) right after the UI mounts (see
# ui.py's comment on why that's deferred rather than eager), so the
# line used to show up in the terminal on every single app startup β
# it did NOT mean an LLM/embedding model was being preloaded, only
# that the ChromaDB persistent client had opened. Removed as pure
# console noise; the same info is already visible in the UI's status
# bar (kb.get_index_stats()) without needing a terminal print.
global _chroma_col
# Use a dimension-aware collection name so that switching to a
# different embedding model automatically gets its own ChromaDB
# collection instead of reusing one built with a different vector
# dimension (which causes the "Collection expecting embedding with
# dimension of 1024, got 2560" error).
# When no embedding model is loaded yet, fall back to the hardcoded
# dimensions table in model_registry.py for the saved/active embed
# model id.
_dim_name = None
if _embed_model is not None:
mid = getattr(_embed_model, 'model_name', None) or getattr(_embed_model, 'name', None)
_dim_name = mr.EMBED_MODEL_DIMENSIONS.get(mid)
if _dim_name is None and hasattr(_embed_model, 'get_sentence_transformer_model'):
try:
cfg = _embed_model.get_sentence_transformer_model().config
_dim_name = getattr(cfg, 'hidden_size', None) or getattr(cfg, 'projection_dim', None)
except Exception:
pass
if _dim_name is None:
_dim_name = mr.EMBED_MODEL_DIMENSIONS.get(_embed_model_id, None)
if _dim_name is None:
_dim_name = mr.EMBED_MODEL_DIMENSIONS.get(mr.get_default_embed_model(), 1024)
_dim_name = f"rag_docs_{_dim_name}d"
if _chroma_col is not None:
old_name = getattr(_chroma_col, 'name', None)
if old_name is not None and old_name != _dim_name:
try:
import chromadb
chromadb.PersistentClient(
path=mr.CHROMA_PERSIST_DIR,
settings=chromadb.Settings(anonymized_telemetry=False),
).delete_collection(old_name)
except Exception:
pass
print(f"[RAG] Old ChromaDB collection '{old_name}' removed after embedding model switch.")
_chroma_col = None
if _chroma_col is None:
import chromadb
_chroma_client_new = chromadb.PersistentClient(
path=mr.CHROMA_PERSIST_DIR,
settings=chromadb.Settings(anonymized_telemetry=False),
)
_chroma_col = _chroma_client_new.get_or_create_collection(
name=_dim_name, metadata={"hnsw:space": "cosine"})
global _chroma_client
_chroma_client = _chroma_client_new
return _chroma_col
def reset_chroma_collection():
"""Used by clear_index() in knowledge_base.py to drop and recreate the
collection object after deleting it from disk.
On Windows, ChromaDB's PersistentClient holds SQLite file locks on the
chroma_db/ directory β closing the client releases those locks so the
subsequent shutil.rmtree() can actually delete the files."""
global _chroma_col, _chroma_client
if _chroma_client is not None:
try:
_chroma_client.close()
except Exception:
pass
_chroma_client = None
_chroma_col = None
def _is_gptq_or_awq(model_id: str) -> bool:
"""Check if a model id is a pre-quantized GPTQ, AWQ, BnB, or MLX checkpoint.
These models ship with quantized weights and must NOT be re-quantized
by bitsandbytes β doing so breaks loading and wastes time."""
mid = str(model_id).lower()
return "gptq" in mid or "awq" in mid or "bnb" in mid or "mlx" in mid or model_id in mr.GPTQ_AWQ_IDS
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# HF Inference API tool-schema sanitizer β smolagents serializes each
# agent Tool into an OpenAI-style function JSON schema for remote
# providers. Multimodal tool inputs (e.g. the stock SpeechToTextTool's
# {"audio": {"type": "audio"}}) use types that are NOT valid JSON Schema
# for function calling, and strict HF Inference API providers (DeepInfra,
# Novita, β¦) reject the ENTIRE request with
# 'audio' is not valid under any of the given schemas.
# general_agent.py also ships a fixed local SpeechToTextTool (string
# schema) β this sanitizer is the boundary guard so ANY tool with an
# invalid schema type can never break a remote call again.
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
_JSON_SCHEMA_TYPES = {"string", "number", "integer", "boolean", "array", "object", "null"}
def sanitize_tool_json_schema(tool_dict: dict) -> dict:
"""Deep-copy an OpenAI-style tool/function schema with every property
`type` outside the JSON-Schema set (e.g. "audio", "image") rewritten to
"string". Returns a NEW dict; the input is never mutated.
The tool wrapper's OWN top-level `"type": "function"` marker is
preserved: it is the OpenAI-compatible API discriminant, NOT a
JSON-Schema type, and rewriting it ("function" β JSON-Schema) sent
every tool as `{"type": "string", ...}` β strict providers rejected
the whole request with "Input should be 'function'" per tool."""
import copy
out = copy.deepcopy(tool_dict)
def _walk(node):
if isinstance(node, dict):
t = node.get("type")
# Only rewrite non-JSON-Schema PROPERTY types. The OpenAI tool
# wrapper's `"type": "function"` marker is exempted so it can
# never be corrupted to "string" (the regression that broke
# every remote tool-calling request).
if isinstance(t, str) and t not in _JSON_SCHEMA_TYPES and t != "function":
node["type"] = "string"
for v in node.values():
_walk(v)
elif isinstance(node, list):
for v in node:
_walk(v)
_walk(out)
return out
def install_tool_schema_sanitizer(llm) -> None:
"""Install the tool-schema sanitizer as an instance-level override on a
remote smolagents LLM (InferenceClientModel / LiteLLMModel β both
inherit `ApiModel._prepare_completion_kwargs`, which serializes the
agent's tools into the OpenAI-style `tools` array of the request).
Every tool property `type` outside JSON Schema (e.g. smolagents' stock
"audio"/"image" inputs) is rewritten to "string" so strict providers
(DeepInfra, Novita, β¦) never reject the whole request with
"'audio' is not valid under any of the given schemas" β see
sanitize_tool_json_schema(). The instance-level override keeps the
class identity (type name / isinstance checks elsewhere) intact.
If a future smolagents renames/removes the hook, this SILENTLY NO-OPS
(the app's own tools already carry valid schemas), rather than crashing
the remote branch of get_llm() at load time.
"""
import types
_orig = getattr(llm, "_prepare_completion_kwargs", None)
if _orig is None:
return
_orig_func = getattr(_orig, "__func__", _orig)
def _prepare_sanitized(self, *args, **kwargs):
kw = _orig_func(self, *args, **kwargs)
if kw.get("tools"):
kw["tools"] = [sanitize_tool_json_schema(t) for t in kw["tools"]]
return kw
llm._prepare_completion_kwargs = types.MethodType(_prepare_sanitized, llm)
def _install_live_streaming(model):
"""Wire a smolagents remote/local model (HF Inference API, LiteLLM,
transformers) into the live token-streaming bus.
The GGUF backends already stream their generated tokens to the bus
(`live` WS events β the growing answer bubble in the web UI). The
smolagents remote/local models were the gap: their stock `generate()`
blocks until the whole response arrives, so tabs using the HF API /
LiteLLM / transformers providers showed NOTHING live β the answer just
popped in at the end. This wraps `generate` so that, while a WS chat
run owns the bus (`get_bus().running`), it consumes the model's own
`generate_stream()` and pushes every text delta to the bus β the same
terminal-style live typing the GGUF backends have.
The streamed result is converted with smolagents' own
`agglomerate_stream_deltas` (its official stream β ChatMessage
converter, which merges tool-call deltas correctly), so agentic
tool-calling runs keep working β the returned message is the exact
shape the non-streaming path would produce. ANY hiccup (a provider
whose streaming path differs, a version that renames the helper)
falls back to the original blocking `generate`: live tokens are a
delivery nicety, never a correctness risk.
"""
orig_generate = getattr(model, "generate", None)
stream_gen = getattr(model, "generate_stream", None)
if not callable(orig_generate) or not callable(stream_gen):
return model
try:
from smolagents.models import agglomerate_stream_deltas
except Exception: # noqa: BLE001 β a version without the helper: no live streaming
return model
from backend.live_stream import get_bus
def _generate(messages, stop_sequences=None, **kwargs):
bus = get_bus()
if not bus.running:
# Outside a WS chat run (STT analysis, memory compaction, β¦)
# keep the original blocking path β nothing is listening.
return orig_generate(messages, stop_sequences=stop_sequences, **kwargs)
deltas = []
try:
bus.begin_generation()
for delta in stream_gen(messages, stop_sequences=stop_sequences, **kwargs):
deltas.append(delta)
frag = (
getattr(delta, "content", None)
or getattr(delta, "reasoning_content", None)
or getattr(delta, "reasoning", None)
or getattr(delta, "thought", None)
or ""
)
if frag:
bus.push(frag)
bus.end_generation()
return agglomerate_stream_deltas(deltas)
except Exception as e: # noqa: BLE001
try:
bus.end_generation()
except Exception: # noqa: BLE001
pass
print(f"[Model] live streaming unavailable for {type(model).__name__} "
f"({e}) β falling back to blocking generate β¦")
return orig_generate(messages, stop_sequences=stop_sequences, **kwargs)
model.generate = _generate
return model
def _llm_backend_key_for(target, provider: Optional[str] = None) -> str:
"""The backend key the REQUESTED (model, provider) config implies β the
discriminator that must match the loaded LLM for get_llm()'s
early-return cache to be valid.
The cache used to be keyed on (model id, n_ctx) only: switching the
per-tab provider from 'π₯οΈ llama.cpp server' to 'π¦ llama-cpp-python
(in-process)' β or to a remote backend β while keeping the same model
label returned the STALE server-backed model and, worse, left the
llama-server.exe subprocess running with its model resident in VRAM.
Same model id + same n_ctx but a different backend β different key β
get_llm() rebuilds, which releases the old model β stopping the
subprocess for a server-backed LLM via _release_model().
Returns 'gguf:<mode>' (mode 'server' | 'inprocess'), 'hf_api',
'litellm', or 'transformers'."""
is_gguf = (
str(target).lower().endswith(".gguf")
or target in mr.PRESET_GGUF_MODELS
or target in mr.PRESET_GGUF_MODELS.values()
# VLM-only GGUF presets (gguf_models.csv 'vlm' category, e.g. the
# Qwen3-VL GGUF repos) are GGUF models too β without this, such an id
# (which doesn't end in '.gguf' and isn't a text-LLM preset) would
# fall through to the transformers branch and crash.
or target in mr.PRESET_GGUF_VLM_MODELS
or target in mr.PRESET_GGUF_VLM_MODELS.values()
or provider in (mr.PROVIDER_SERVER, mr.PROVIDER_LLAMA_CPP_PYTHON)
)
if is_gguf:
backend_mode = mr.get_saved_llm_backend_mode()
if provider == mr.PROVIDER_SERVER:
backend_mode = "server"
elif provider == mr.PROVIDER_LLAMA_CPP_PYTHON:
backend_mode = "inprocess"
return f"gguf:{backend_mode}"
# A curated HF Inference API model id (hf_api_models.csv) under the HF
# API provider routes to the remote backend just like the sentinel β the
# per-tab model dropdown now lists real remote model ids, not only the
# single Settings-backed entry.
if target == mr.HF_INFERENCE_API_SENTINEL or provider == mr.PROVIDER_HF_API:
return "hf_api"
if target == mr.LITELLM_SENTINEL:
return "litellm"
return "transformers"
def get_llm(model_id: Optional[str] = None, n_ctx: Optional[int] = None, provider: Optional[str] = None):
"""Lazily build (or rebuild, if the model id, the requested context
window, OR the requested backend changed) the shared LLM instance.
"""
global _llm, _llm_model_id, _llm_n_ctx, _llm_backend_key
target = model_id or _llm_model_id
is_gguf = (
str(target).lower().endswith(".gguf")
or target in mr.PRESET_GGUF_MODELS
or target in mr.PRESET_GGUF_MODELS.values()
# VLM-only GGUF presets (gguf_models.csv 'vlm' category, e.g. the
# Qwen3-VL GGUF repos) are GGUF models too β without this, such an id
# (which doesn't end in '.gguf' and isn't a text-LLM preset) would
# fall through to the transformers branch and crash.
or target in mr.PRESET_GGUF_VLM_MODELS
or target in mr.PRESET_GGUF_VLM_MODELS.values()
or provider in (mr.PROVIDER_SERVER, mr.PROVIDER_LLAMA_CPP_PYTHON)
)
target_ctx = n_ctx if n_ctx is not None else (_llm_n_ctx or mr.get_saved_context_window())
ctx_changed = is_gguf and target_ctx != _llm_n_ctx
# Backend (server vs in-process vs remote) the REQUESTED config implies β
# must match the loaded LLM or the cache is stale (e.g. the user switched
# the provider from llama.cpp server to in-process / HF API / LiteLLM
# while keeping the same model label: returning the old server-backed
# model would keep the llama-server subprocess alive in VRAM). A None
# provider expresses NO preference (the documented _call_llm contract:
# 'None = use the currently selected/saved provider') β such calls (e.g.
# memory compaction) must reuse whatever is loaded, never force a rebuild
# that would swap the backend out from under the chat path.
requested_backend = _llm_backend_key_for(target, provider)
backend_changed = (
_llm is not None and provider is not None
and _llm_backend_key != requested_backend
)
if _llm is not None and target == _llm_model_id and not ctx_changed and not backend_changed:
return _llm
with _llm_lock:
if _llm is not None and target == _llm_model_id and not ctx_changed and not backend_changed:
return _llm
if _llm is not None:
if ctx_changed:
reason = f"context window changed to {target_ctx} tokens"
elif backend_changed:
reason = f"backend switched to {requested_backend}"
else:
reason = f"loading '{target}'"
print(f"[Model] Unloading previous LLM '{_llm_model_id}' before {reason} β¦")
_release_and_clear("_llm")
if is_gguf:
backend_mode = mr.get_saved_llm_backend_mode()
if provider == mr.PROVIDER_SERVER:
backend_mode = "server"
elif provider == mr.PROVIDER_LLAMA_CPP_PYTHON:
backend_mode = "inprocess"
if backend_mode == "server":
print(f"[Model] Starting/reusing llama-server for '{target}' with "
f"context window {target_ctx} tokens β¦")
base_url = llama_backend.get_or_start_llama_server(
model_path=target,
n_ctx=target_ctx,
n_gpu_layers=-1, # external llama-server has its own GPU support
)
_llm = llama_backend.LlamaServerModel(
base_url=base_url,
model_path=target,
temperature=0.6,
top_p=0.95,
max_new_tokens=mr.get_saved_max_new_tokens(),
# Per-request HTTP timeout (seconds) β user-configurable
# via the "β±οΈ llama-server Request Timeout" dropdown (see
# model_registry.get_saved_llm_server_timeout()) instead
# of silently using LlamaServerModel's hardcoded 300s
# default. A large/slow model with a long agentic prompt
# (e.g. Deep Research's manager+sub-agent history) can
# easily need more than 300s per generation β see that
# function's docstring for the full "Error in code
# parsing" failure mode this fixes.
timeout=mr.get_saved_llm_server_timeout(),
)
_llm_n_ctx = target_ctx
_llm_backend_key = requested_backend
_llm_model_id = target
return _llm
else:
def _use_llama_server(reason: str):
"""Start/reuse the external llama-server for `target` and
return the wrapped model β the shared fallback for both
'llama-cpp-python not installed' and 'the installed wheel
crashes on this CPU' (AVX-512 wheel on a non-AVX-512 CPU).
llama-server release binaries ship per-architecture CPU
DLLs, so they work on CPUs the in-process wheel can't."""
# Explicit global here β nested functions don't inherit
# get_llm's `global` declaration, and the module-level
# _llm cache + _release_and_clear rely on these globals.
global _llm, _llm_n_ctx, _llm_backend_key, _llm_model_id
print(f"[Model] {reason} β auto-fallbacking to llama-server "
f"(external process) for '{target}' β¦")
base_url = llama_backend.get_or_start_llama_server(
model_path=target,
n_ctx=target_ctx,
n_gpu_layers=-1, # external llama-server has its own GPU support
)
_llm = llama_backend.LlamaServerModel(
base_url=base_url,
model_path=target,
temperature=0.6,
top_p=0.95,
max_new_tokens=mr.get_saved_max_new_tokens(),
timeout=mr.get_saved_llm_server_timeout(),
)
_llm_n_ctx = target_ctx
_llm_backend_key = requested_backend
_llm_model_id = target
return _llm
if not llama_backend.LLAMA_CPP_AVAILABLE:
if llama_backend.LLAMA_SERVER_EXE_PATH:
return _use_llama_server(
"llama-cpp-python not installed")
raise RuntimeError(
"llama-cpp-python is not installed, and no llama-server "
"executable is configured.\n\n"
"Option 1: Run SETUP.bat to install llama-cpp-python "
"(supports GPU offload).\n"
"Option 2: Set the 'π₯οΈ llama-server.exe Path' under Model "
"Settings to point at a llama-server.exe binary from "
"https://github.com/ggml-org/llama.cpp/releases β then "
"GGUF models run via the external server instead."
)
print(f"[Model] Loading GGUF LLM '{target}' with context window "
f"{target_ctx} tokens on {DEVICE.upper()} β¦")
try:
_llm = llama_backend.LlamaCppModel(
model_path=target,
n_ctx=target_ctx,
n_gpu_layers=-1 if llama_backend.LLAMA_CPP_GPU_AVAILABLE else 0,
flash_attn=llama_backend.LLAMA_CPP_GPU_AVAILABLE and mr.get_saved_flash_attn_llama(),
temperature=0.6,
top_p=0.95,
max_new_tokens=mr.get_saved_max_new_tokens(),
)
except Exception as e:
if target_ctx > 16384 and ("memory" in str(e).lower() or "alloc" in str(e).lower()):
raise RuntimeError(
f"Failed to load '{target}' with a {target_ctx}-token context "
f"window β this likely ran out of VRAM/RAM, since the KV-cache "
f"size grows with n_ctx. Try a smaller context window from the "
f"'π§ Context Window' dropdown, or a smaller/more-quantized model.\n\n"
f"Original error: {e}"
) from e
# The installed llama-cpp-python wheel crashed on this CPU
# with an ILLEGAL CPU INSTRUCTION (0xc000001d) β the
# AVX-512 CUDA wheels cannot run on Intel consumer CPUs
# (no AVX-512), where EVERY GGUF load dies this way. The
# wheel is unusable here, so route around it via
# llama-server instead of surfacing the confusing raw
# error (see is_illegal_instruction_error).
if is_illegal_instruction_error(e) and llama_backend.LLAMA_SERVER_EXE_PATH:
return _use_llama_server(
"the installed llama-cpp-python wheel crashed with an "
"illegal CPU instruction (0xc000001d β AVX-512 build "
"on a CPU without AVX-512)")
raise
_llm_n_ctx = target_ctx
_llm_backend_key = requested_backend
_llm_model_id = target
return _llm
elif target == mr.HF_INFERENCE_API_SENTINEL or provider == mr.PROVIDER_HF_API:
from smolagents import InferenceClientModel
# A curated catalog id is the model itself; the sentinel (or a
# custom Settings id) falls back to the per-type remote default.
hf_model_id = target if target != mr.HF_INFERENCE_API_SENTINEL else mr.get_hf_api_model_id_for("llm")
hf_token = mr.get_saved_hf_token() or None
hf_provider = mr.get_saved_hf_provider() or None
if not hf_model_id:
raise ValueError(
"Hugging Face Inference API selected, but no model ID is configured. "
"Enter a model ID in the 'π€ HF Model ID' field under Model Settings."
)
if ":" in hf_model_id and not hf_provider:
hf_model_id, hf_provider = hf_model_id.rsplit(":", 1)
print(f"[Model] Using Hugging Face Inference API: model={hf_model_id} provider={hf_provider or 'auto'}")
_llm = InferenceClientModel(
model_id=hf_model_id,
token=hf_token,
provider=hf_provider,
max_tokens=mr.get_saved_max_new_tokens(),
)
# Boundary guard: rewrite any non-JSON-Schema tool property types
# (smolagents' stock "audio"/"image" tool inputs) to "string"
# before the payload reaches the provider β strict providers
# reject the whole request otherwise (see
# install_tool_schema_sanitizer / sanitize_tool_json_schema).
install_tool_schema_sanitizer(_llm)
_install_live_streaming(_llm)
_llm_n_ctx = None
elif target == mr.LITELLM_SENTINEL:
try:
from smolagents import LiteLLMModel
except ImportError:
raise RuntimeError(
"LiteLLM is not installed. Run: pip install 'smolagents[litellm]'"
)
litellm_model_id = mr.get_saved_litellm_model_id()
litellm_api_key = mr.get_saved_litellm_api_key() or None
litellm_api_base = mr.get_saved_litellm_api_base() or None
if not litellm_model_id:
raise ValueError(
"LiteLLM selected, but no model ID is configured. "
"Enter a model ID in the 'π LiteLLM Model ID' field "
"under Model Settings."
)
print(f"[Model] Using LiteLLM: model={litellm_model_id} base={litellm_api_base or 'default'}")
_llm = LiteLLMModel(
model_id=litellm_model_id,
api_key=litellm_api_key,
api_base=litellm_api_base,
max_completion_tokens=mr.get_saved_max_new_tokens(),
)
# Same tool-schema boundary guard as the HF Inference API branch
# β LiteLLMModel inherits ApiModel._prepare_completion_kwargs, so
# a strict provider behind LiteLLM (e.g. DeepInfra) would reject
# an invalid tool schema identically.
install_tool_schema_sanitizer(_llm)
_install_live_streaming(_llm)
_llm_n_ctx = None
else:
_check_transformers_version_for(target)
import inspect
import importlib.metadata
from smolagents import TransformersModel
print(f"[Model] Loading LLM '{target}' on {DEVICE.upper()} β¦")
# ββ Proactive torch-metadata check βββββββββββββββββββββββββββββ
# In frozen/MSIX builds, torch may be installed but its
# .dist-info directory is missing (version strings with '+' are
# illegal in MSIX/OPC filenames). accelerate.utils.versions
# calls importlib.metadata.version('torch') at MODULE LEVEL
# during the TransformersModel.__init__ β transformers β
# accelerate import chain, and a missing .dist-info raises
# PackageNotFoundError that cascades into a confusing
# 'Please install transformers extra' error.
#
# harden_metadata() should patch this, but in PyInstaller
# frozen builds the patch may not propagate. Check NOW β
# before we even create TransformersModel β and surface a
# clear, actionable message if the metadata is broken.
try:
importlib.metadata.version("torch")
except importlib.metadata.PackageNotFoundError:
# Attempt one more harden_metadata() call in case the
# runtime hook silently failed (file missing from bundle).
try:
from backend.metadata_hardening import harden_metadata
harden_metadata()
importlib.metadata.version("torch") # retry
except Exception:
raise RuntimeError(
"Could not read torch package metadata β needed by "
"the HuggingFace Transformers backend.\n\n"
"In a packaged (MSIX/PyInstaller) build, GPU PyTorch "
"is NOT bundled. Please:\n"
" 1. Open the βοΈ Settings tab\n"
' 2. Click "Detect & Install GPU PyTorch"\n\n'
"Or switch the provider to 'π€ Local llama.cpp' "
"to use GGUF models (no torch needed)."
)
base_kwargs = dict(
model_id=target,
device_map=DEVICE,
max_new_tokens=mr.get_saved_max_new_tokens(),
temperature=0.6,
top_p=0.95,
trust_remote_code=True,
)
# smolagents' TransformersModel constructor only recognizes a
# fixed set of named parameters for MODEL LOADING (model_id,
# device_map, torch_dtype, trust_remote_code, model_kwargs,
# max_new_tokens, ...) β see
# https://huggingface.co/docs/smolagents/en/reference/models.
# Anything passed that ISN'T one of those named parameters
# does NOT raise a TypeError; it's silently absorbed into
# TransformersModel's own **kwargs, which it then re-forwards
# into EVERY subsequent model.generate() call, not just at
# load time. Passing `dtype=` here (a name TransformersModel's
# constructor doesn't define) used to slip through this way β
# load succeeded with no error, and the model only blew up the
# first time an agent actually tried to generate, with
# "The following `model_kwargs` are not used by the model:
# ['dtype']" β easy to misread as a tool-calling problem
# rather than a stale kwarg name. Detect the real parameter
# name instead of guessing, so this fails loudly at load time
# (a clear, immediate error) if some future smolagents version
# renames it again.
ctor_params = inspect.signature(TransformersModel.__init__).parameters
if "torch_dtype" in ctor_params:
base_kwargs["torch_dtype"] = _load_dtype()
elif "dtype" in ctor_params:
base_kwargs["dtype"] = _load_dtype()
else:
print(
"[Model] Warning: installed smolagents' TransformersModel exposes "
"neither 'torch_dtype' nor 'dtype' as a constructor parameter β "
"loading without an explicit dtype (will use the model's default)."
)
# Pre-quantized GPTQ/AWQ models β these ship with quantized
# weights and must NOT be re-quantized by bitsandbytes. They
# load via the same AutoModelForCausalLM path but the
# quantization config is embedded in the model's config.json.
# transformers auto-detects GPTQ/AWQ from the config and
# loads the right quantized linear layers.
model_kw = {}
if DEVICE == "cuda" and mr.get_saved_flash_attn_pytorch():
model_kw["attn_implementation"] = "sdpa"
if _is_gptq_or_awq(target):
print(
f"[Model] Loading pre-quantized GPTQ/AWQ model '{target}' β "
f"no additional quantization applied."
)
base_kwargs["model_kwargs"] = model_kw
else:
base_kwargs["model_kwargs"] = model_kw
try:
_llm = TransformersModel(**base_kwargs)
except (ModuleNotFoundError, ImportError) as _e:
_msg = str(_e)
# In frozen/MSIX builds where torch is installed but its
# .dist-info is missing (version strings with '+' are
# illegal in MSIX/OPC), accelerate's
# importlib.metadata.version('torch') raises
# PackageNotFoundError which cascades into a
# ModuleNotFoundError from smolagents. Surface a clear
# message pointing the user to the Settings tab.
if "torch" in _msg.lower() or "transformers" in _msg.lower():
raise RuntimeError(
f"{_msg}\n\n"
f"In a packaged (MSIX/PyInstaller) build, GPU PyTorch "
f"is NOT bundled β it must be installed via the "
f"βοΈ Settings tab (\"Detect & Install GPU PyTorch\").\n\n"
f"If you only need GGUF/llama.cpp models, switch the "
f"provider to 'π€ Local llama.cpp' instead."
) from _e
raise
# Live token streaming for the local transformers backend too
# (smolagents' TransformersModel has a generate_stream; the
# wrapper pushes deltas to the live bus while a WS run is
# active β same as the GGUF/remote backends).
_install_live_streaming(_llm)
# Opt-in torch.compile on the underlying HF model (CUDA only).
_inner = getattr(_llm, "model", None)
if _inner is not None:
_llm.model = _maybe_torch_compile(_inner)
# n_ctx doesn't apply to the HF backend β clear it so a later
# switch back to a GGUF model doesn't skip a reload it needs
# by comparing against a stale value from a previous GGUF load.
_llm_n_ctx = None
_llm_backend_key = requested_backend
_llm_model_id = target
return _llm
def _estimate_tokens(text: str) -> int:
"""Rough token count from answer text β a character-based heuristic
(β 4 chars per token for English / code, β 2 for Khmer / CJK). Used
when the model backend did not report usage (smolagents token_usage is
None). Never returns 0 for non-empty text."""
if not text:
return 0
n = len(text)
# Heuristic: Khmer/CJK/Devanagari are roughly 2 chars per token;
# Latin/code is roughly 4. We count non-ASCII chars to guess the mix.
non_ascii = sum(1 for c in text if ord(c) > 127)
ascii_chars = n - non_ascii
return max(1, int(non_ascii / 2 + ascii_chars / 4))
def _call_llm(model_id: str, system: str, user: str, history: Optional[list] = None,
provider: Optional[str] = None, n_ctx: Optional[int] = None,
max_tokens: Optional[int] = None) -> tuple[str, float, int]:
"""Direct (non-agentic) single-turn-or-multi-turn LLM call, shared by
General Chat's and RAG Chat's *direct* paths (chat.py), and by agent
memory compaction (agent_memory.compact_agent_memory()).
Built as a plain list of smolagents `ChatMessage`s β the same message
object smolagents' own `CodeAgent`/`TransformersModel`/`LlamaCppModel`
machinery uses internally β so this goes through the exact same
`model(messages)` call contract as the agentic paths, just without a
CodeAgent wrapped around it. `role` is passed via smolagents'
`MessageRole` enum rather than a bare string, matching how smolagents
documents/constructs `ChatMessage` itself.
`history` (optional): prior turns as `[{"role": "user"|"assistant",
"content": str}, ...]`, coming from chat.py's `_recent_memory_messages()`.
Folded in between the system prompt and the current `user` message so
follow-up questions can refer back to earlier turns β see chat.py's
"π§ Conversation Memory" checkbox.
`provider` (optional): a per-call provider override forwarded to
get_llm() (None = use the currently selected/saved provider).
`n_ctx` (optional): a per-call context-window override forwarded to
get_llm(), for the GGUF backend (None = whatever the loaded model
was built with, or the saved context window).
`max_tokens` (optional): a per-call cap on the generated tokens (used
by memory compaction so its summary call stays short instead of
inheriting the model's full MAX_NEW_TOKENS budget). Not every backend's
Model wrapper accepts a `max_tokens` kwarg β the TypeError fallback
re-runs with the model's own default budget.
"""
from smolagents.models import ChatMessage, MessageRole
llm = get_llm(model_id, provider=provider, n_ctx=n_ctx)
messages = [
ChatMessage(role=MessageRole.SYSTEM, content=[{"type": "text", "text": system}])
]
for turn in (history or []):
role = turn.get("role")
content = turn.get("content", "")
if not content:
continue
if role == "user":
msg_role = MessageRole.USER
elif role == "assistant":
msg_role = MessageRole.ASSISTANT
else:
continue
messages.append(ChatMessage(role=msg_role, content=[{"type": "text", "text": content}]))
messages.append(ChatMessage(role=MessageRole.USER, content=[{"type": "text", "text": user}]))
t0 = time.time()
if max_tokens is not None:
try:
out = llm(messages, max_tokens=max_tokens)
except TypeError:
out = llm(messages)
else:
out = llm(messages)
if hasattr(out, "content"):
c = out.content
if isinstance(c, list):
ans = " ".join(b.get("text", "") if isinstance(b, dict) else str(b) for b in c)
else:
ans = str(c)
else:
ans = str(out)
# Extract output token count from the smolagents ChatMessage; fall back
# to a rough character-based estimate when the backend did not report usage.
n_tokens = 0
try:
tok = getattr(out, "token_usage", None)
if tok is not None:
n_tokens = getattr(tok, "output_tokens", 0) or 0
except Exception:
pass
if not n_tokens:
n_tokens = _estimate_tokens(ans)
return ans.strip(), time.time() - t0, n_tokens
def _is_local_gguf_file(path: Any) -> bool:
"""True when *path* points at an actual local .gguf file (as opposed to
a preset GGUF repo ID like 'google/gemma-4-E2B-it-qat-q4_0-gguf' whose
mmproj is auto-downloaded by llama_backend.resolve_or_download_gguf_model).
Only genuinely local .gguf files need a registered mmproj from the scan."""
s = str(path or "")
if not s.lower().endswith(".gguf"):
return False
try:
return os.path.isfile(s)
except Exception:
return False
def _is_quantized_uint8_init_error(exc: Exception) -> bool:
"""True when the failure is transformers trying to torch-init a packed
uint8 quantized weight β the signature of a corrupt/partial Gemma-4 QAT
checkpoint (missing keys re-initialized with `init.normal_`, which has
no uint8 kernel). Matches both the CPU RuntimeError and the CUDA
NotImplementedError variants."""
msg = str(exc)
return (
"expected a floating-point or complex dtype" in msg
or "not implemented for 'Byte'" in msg
or "dtype=torch.uint8" in msg
)
def _clear_hf_model_cache(model_id: str) -> None:
"""Delete every locally cached revision of a HF repo so the next
`from_pretrained` performs a fresh download. Used to recover from a
corrupt/partial model.safetensors. Never raises."""
try:
from huggingface_hub import scan_cache_dir
cache_info = scan_cache_dir()
hashes = [
revision.commit_hash
for repo in cache_info.repos
if repo.repo_id == model_id
for revision in repo.revisions
]
if not hashes:
print(f"[VLM] No cached revisions found for '{model_id}' to clear.")
return
strategy = cache_info.delete_revisions(*hashes)
strategy.execute()
print(
f"[VLM] Cleared {len(hashes)} cached revision(s) of '{model_id}' "
f"(freed {strategy.expected_freed_size_str})."
)
except Exception as exc:
print(f"[VLM] Failed to clear HF cache for '{model_id}': {exc}")
def _vlm_backend_key_for(target, provider: Optional[str] = None) -> str:
"""The backend key the REQUESTED (model, provider) config implies for the
Vision loader β the discriminator that must match the loaded VLM for
get_vlm()'s early-return cache to be valid. Same idea as
_llm_backend_key_for(): the cache used to be keyed on (model id, n_ctx)
only, so switching the Vision provider from 'π₯οΈ llama.cpp server' to
'π¦ llama-cpp-python (in-process)' (or to the HF Inference API) while
keeping the same model label returned the STALE server-backed VLM and
left llama-server.exe running with the model resident in VRAM.
Mirrors get_vlm()'s own routing: a GGUF target under the server provider
(or with llama-cpp-python unavailable and a server configured) runs via
the external subprocess ('gguf:server'), otherwise in-process
('gguf:inprocess'); the HF Inference API sentinel is 'hf_api'; any local
transformers VLM is 'transformers'."""
is_gguf = (
str(target).lower().endswith(".gguf")
or target in mr.PRESET_GGUF_MODELS
or target in mr.PRESET_GGUF_MODELS.values()
# VLM-only GGUF presets (gguf_models.csv 'vlm' category, e.g. the
# Qwen3-VL GGUF repos) are GGUF models too β without this, such an id
# (which doesn't end in '.gguf' and isn't a text-LLM preset) would
# fall through to the transformers branch and crash.
or target in mr.PRESET_GGUF_VLM_MODELS
or target in mr.PRESET_GGUF_VLM_MODELS.values()
or provider in (mr.PROVIDER_SERVER, mr.PROVIDER_LLAMA_CPP_PYTHON)
)
if is_gguf:
use_server = (
provider == mr.PROVIDER_SERVER
or (not provider and not llama_backend.LLAMA_CPP_GPU_AVAILABLE
and bool(llama_backend.LLAMA_SERVER_EXE_PATH))
)
return "gguf:server" if use_server else "gguf:inprocess"
# A curated HF Inference API VLM id under the HF API provider routes to
# the remote backend just like the sentinel β the Vision tab's model
# dropdown now lists real remote model ids, not only the single
# Settings-backed entry.
if target == mr.HF_INFERENCE_API_SENTINEL or provider == mr.PROVIDER_HF_API:
return "hf_api"
return "transformers"
def get_vlm(model_id: Optional[str] = None, mmproj_path: Optional[str] = None, provider: Optional[str] = None, n_ctx: Optional[int] = None):
global _vlm_model, _vlm_processor, _vlm_model_id, _vlm_n_ctx, _vlm_backend_key
target = model_id or mr.DEFAULT_VLM_MODEL
target_ctx = n_ctx if n_ctx is not None else (_vlm_n_ctx or mr.get_saved_context_window())
ctx_changed = target_ctx != _vlm_n_ctx
# Backend (server vs in-process vs remote) the REQUESTED config implies β
# must match the loaded VLM or the cache is stale (e.g. the user switched
# the Vision provider from llama.cpp server to in-process / HF API while
# keeping the same model label: returning the old server-backed VLM
# would keep llama-server.exe alive in VRAM). A None provider expresses
# NO preference (vlm_answer()'s cache-hit call) and must reuse whatever
# is loaded.
requested_backend = _vlm_backend_key_for(target, provider)
backend_changed = (
_vlm_model is not None and provider is not None
and _vlm_backend_key != requested_backend
)
if _vlm_model is not None and target == _vlm_model_id and not ctx_changed and not backend_changed:
return _vlm_model, _vlm_processor
if _vlm_model is not None:
if ctx_changed:
reason = f"context window changed to {target_ctx} tokens"
elif backend_changed:
reason = f"backend switched to {requested_backend}"
else:
reason = f"loading '{target}'"
print(f"[VLM] Unloading previous VLM '{_vlm_model_id}' before {reason} β¦")
_release_and_clear("_vlm_model")
_vlm_processor = None
# ββ HF Inference API ββββββββββββββββββββββββββββββββββββββββββ
if target == mr.HF_INFERENCE_API_SENTINEL or provider == mr.PROVIDER_HF_API:
# A curated catalog id is the model itself; the sentinel (or a
# custom Settings id) falls back to the per-type remote default.
hf_model_id = target if target != mr.HF_INFERENCE_API_SENTINEL else mr.get_hf_api_model_id_for("vlm")
if not hf_model_id:
raise ValueError(
"Hugging Face Inference API selected for Vision, but no "
"model ID is configured. Enter a model ID in the "
"'π€ HF Model ID' field under Model Settings."
)
_vlm_model = InferenceApiVLMModel(model_id=hf_model_id)
_vlm_processor = None
_vlm_backend_key = requested_backend
_vlm_model_id = target
_vlm_n_ctx = None
return _vlm_model, _vlm_processor
# ββ GGUF vision model (llama.cpp) βββββββββββββββββββββββββββββ
# Treat a model as GGUF when the id is a local .gguf file, a known
# preset GGUF repo (e.g. 'google/gemma-4-E2B-it-qat-q4_0-gguf' β the
# id itself does NOT end in '.gguf'), or the provider is llama.cpp β
# mirroring get_llm()'s is_gguf detection so the Vision tab routes
# preset GGUF models to llama.cpp instead of the HuggingFace branch.
is_gguf = (
str(target).lower().endswith(".gguf")
or target in mr.PRESET_GGUF_MODELS
or target in mr.PRESET_GGUF_MODELS.values()
# VLM-only GGUF presets (gguf_models.csv 'vlm' category, e.g. the
# Qwen3-VL GGUF repos) are GGUF models too β without this, such an id
# (which doesn't end in '.gguf' and isn't a text-LLM preset) would
# fall through to the transformers branch and crash.
or target in mr.PRESET_GGUF_VLM_MODELS
or target in mr.PRESET_GGUF_VLM_MODELS.values()
or provider in (mr.PROVIDER_SERVER, mr.PROVIDER_LLAMA_CPP_PYTHON)
)
if is_gguf:
use_server = (provider == mr.PROVIDER_SERVER) or (not provider and not llama_backend.LLAMA_CPP_GPU_AVAILABLE and bool(llama_backend.LLAMA_SERVER_EXE_PATH))
if use_server:
if llama_backend.LLAMA_SERVER_EXE_PATH:
if not mmproj_path:
mmproj_path = mr.GGUF_VLM_MMPROJ_MAP.get(target)
if not mmproj_path and _is_local_gguf_file(target):
raise RuntimeError(
f"No mmproj (vision projector) file is registered for "
f"'{target}'. Select one from the mmproj dropdown in the "
f"sidebar, or click 'π Scan' on the GGUF model folder so "
f"it can be paired with a matching mmproj .gguf file."
)
print(f"[VLM] llama-cpp-python not available β routing GGUF vision "
f"through external llama-server β¦")
base_url = llama_backend.get_or_start_llama_server(target, n_ctx=target_ctx, mmproj_path=mmproj_path)
_vlm_model = llama_backend.LlamaServerVLMModel(
base_url=base_url,
model_path=target,
timeout=mr.get_saved_llm_server_timeout(),
)
_vlm_processor = None
_vlm_backend_key = requested_backend
_vlm_model_id = target
_vlm_n_ctx = target_ctx
return _vlm_model, _vlm_processor
raise RuntimeError(
"llama-cpp-python is not installed β GGUF vision models "
"unavailable. Run SETUP.bat, or install it manually."
)
if not mmproj_path:
mmproj_path = mr.GGUF_VLM_MMPROJ_MAP.get(target)
if not mmproj_path and _is_local_gguf_file(target):
raise RuntimeError(
f"No mmproj (vision projector) file is registered for "
f"'{target}'. Select one from the mmproj dropdown in the "
f"sidebar, or click 'π Scan' on the GGUF model folder so "
f"it can be paired with a matching mmproj .gguf file."
)
_vlm_model = llama_backend.LlamaCppVLMModel(
model_path=target,
mmproj_path=mmproj_path,
n_ctx=target_ctx,
n_gpu_layers=-1 if llama_backend.LLAMA_CPP_GPU_AVAILABLE else 0,
)
_vlm_processor = None
_vlm_backend_key = requested_backend
_vlm_model_id = target
_vlm_n_ctx = target_ctx
return _vlm_model, _vlm_processor
# ββ Local HuggingFace VLM βββββββββββββββββββββββββββββββββββββ
print(f"[VLM] Loading '{target}' on {DEVICE.upper()} β¦")
from transformers import AutoProcessor
if target in mr.QWEN_VL_IDS:
from transformers import Qwen2_5_VLForConditionalGeneration
_vlm_processor = AutoProcessor.from_pretrained(
target,
trust_remote_code=True,
min_pixels=256 * 28 * 28,
max_pixels=1280 * 28 * 28,
)
_vlm_kwargs = dict(
torch_dtype=_load_dtype(),
device_map=DEVICE,
trust_remote_code=True,
**_vlm_attn_kwargs(),
)
_vlm_model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
target, **_vlm_kwargs
)
_vlm_model._arch = "qwen_vl"
elif target in mr.QWEN3_VL_IDS:
# Qwen3-VL β current-gen Qwen vision family (dense 2B/4B/8B).
# Qwen3VLForConditionalGeneration exists in transformers 5.x (the
# _MIN_TRANSFORMERS_VERSION["qwen3vl"] guard gives a clear upgrade
# message below 5.0); AutoModelForImageTextToText is the fallback
# for the rare 5.x build where the explicit class is missing.
try:
from transformers import Qwen3VLForConditionalGeneration
ModelClass = Qwen3VLForConditionalGeneration
except ImportError:
from transformers import AutoModelForImageTextToText
ModelClass = AutoModelForImageTextToText
print("[VLM] Qwen3VLForConditionalGeneration unavailable β "
"using AutoModelForImageTextToText")
_vlm_processor = AutoProcessor.from_pretrained(
target,
trust_remote_code=True,
min_pixels=256 * 28 * 28,
max_pixels=1280 * 28 * 28,
)
_vlm_kwargs = dict(
torch_dtype=_load_dtype(),
device_map=DEVICE,
trust_remote_code=True,
**_vlm_attn_kwargs(),
)
_vlm_model = ModelClass.from_pretrained(
target, **_vlm_kwargs
)
_vlm_model._arch = "qwen3vl"
elif target in mr.SMOL_VLM_IDS:
try:
from transformers import AutoModelForImageTextToText
ModelClass = AutoModelForImageTextToText
print("[VLM] Using AutoModelForImageTextToText")
except ImportError:
try:
from transformers import AutoModelForVision2Seq
ModelClass = AutoModelForVision2Seq
print("[VLM] Using AutoModelForVision2Seq")
except ImportError:
from transformers import AutoModel
ModelClass = AutoModel
print("[VLM] Falling back to AutoModel")
_vlm_processor = AutoProcessor.from_pretrained(
target,
trust_remote_code=True,
)
_vlm_kwargs = dict(
torch_dtype=_load_dtype(),
device_map=DEVICE,
trust_remote_code=True,
**_vlm_attn_kwargs(),
)
_vlm_model = ModelClass.from_pretrained(target, **_vlm_kwargs)
_vlm_model._arch = "smolvlm"
elif target in mr.GEMMA4_IDS:
# Gemma 4 (incl. Mobile QAT) is a multimodal family, loaded the
# same way smolagents' own TransformersModel picks it up β the
# AutoModelForImageTextToText mapping resolves to
# Gemma4ForConditionalGeneration (verified in the Phase 0 smoke
# test). AutoModelForMultimodalLM is tried first per the official
# integration guide; both classes resolve to the same model.
# NOTE: these pre-quantized (QAT) checkpoints store packed integer
# weights as uint8/int8 tensors. If a cached model.safetensors is
# corrupt or partially downloaded, `from_pretrained` loads with
# MISSING keys; transformers then re-initializes the missing
# QuantizedLinear/QuantizedEmbedding weight via `init.normal_`,
# which has no uint8 kernel β the exact
# RuntimeError: expected a floating-point or complex dtype,
# but got dtype=torch.uint8
# (CPU) / `NotImplementedError: "normal_kernel_cuda" not implemented
# for 'Byte'` (CUDA) crash. Recover by clearing the bad cache and
# retrying the load once.
try:
from transformers import AutoModelForMultimodalLM
ModelClass = AutoModelForMultimodalLM
print("[VLM] Using AutoModelForMultimodalLM")
except ImportError:
from transformers import AutoModelForImageTextToText
ModelClass = AutoModelForImageTextToText
print("[VLM] Using AutoModelForImageTextToText")
_vlm_processor = AutoProcessor.from_pretrained(
target,
trust_remote_code=True,
)
load_kwargs = dict(trust_remote_code=True)
if DEVICE == "cpu":
load_kwargs["low_cpu_mem_usage"] = True
else:
load_kwargs["torch_dtype"] = "auto"
load_kwargs["device_map"] = "auto"
load_kwargs.update(_vlm_attn_kwargs())
try:
_vlm_model = ModelClass.from_pretrained(target, **load_kwargs)
except Exception as e:
if _is_quantized_uint8_init_error(e):
print(
f"[VLM] '{target}' failed to load from a corrupt/partial "
f"HF cache ({type(e).__name__}: {e}). Clearing the cache "
f"and retrying the load once β¦"
)
_clear_hf_model_cache(target)
_vlm_model = ModelClass.from_pretrained(target, **load_kwargs)
else:
raise
_vlm_model._arch = "gemma4"
else:
raise ValueError(f"Unknown VLM: {target}")
_vlm_backend_key = requested_backend
_vlm_model_id = target
_vlm_n_ctx = None
return _maybe_torch_compile(_vlm_model), _vlm_processor
def _vlm_attn_kwargs() -> dict:
"""Attention-implementation kwargs for the local transformers VLM loaders.
The VLM loaders previously left ``attn_implementation`` unset, so they ran
EAGER attention on CUDA β missing the PyTorch-native FlashAttention (SDPA)
kernel the text LLM already uses. We now mirror the LLM guard: on CUDA
with PyTorch FlashAttention enabled, request SDPA (which dispatches to
PyTorch-native FlashAttention-2 on fp16). On CPU / non-CUDA we leave it
unset (SDPA gives no benefit and the eager path is the safe fallback)."""
if DEVICE == "cuda" and mr.get_saved_flash_attn_pytorch():
return {"attn_implementation": "sdpa"}
return {}
def _maybe_torch_compile(model):
"""Opt-in ``torch.compile`` for the local transformers backends (CUDA only).
Fully guarded: any failure silently returns the uncompiled model so the app
always launches. The first real forward pays the compile cost (one-time);
subsequent calls are faster. No-op when the setting is off or on non-CUDA.
The mode (default / reduce-overhead / max-autotune / max-autotune-no-
cudagraphs) comes from the acceleration Settings toggle."""
if DEVICE != "cuda" or not mr.get_saved_torch_compile():
return model
try:
import torch
if not hasattr(torch, "compile"):
return model
mode = mr.get_saved_torch_compile_mode() or "default"
if mode not in mr.TORCH_COMPILE_MODES:
mode = "default"
print(f"[Model] Compiling model with torch.compile (one-time cost, mode={mode})β¦")
return torch.compile(model, mode=mode, fullgraph=False)
except Exception as e:
print(f"[Model] torch.compile skipped ({e}); running uncompiled.")
return model
def _load_dtype():
"""The torch dtype for local transformers LLM/VLM model loads β the
opt-in bfloat16 fastpath (Ampere+ CUDA GPUs: faster, no fp16 overflow
risk, best paired with SDPA FlashAttention) when enabled, else the
hardware default (fp16 on GPU, fp32 on CPU)."""
if DEVICE == "cuda" and mr.get_saved_torch_bf16():
try:
import torch
if torch.cuda.is_bf16_supported():
return torch.bfloat16
except Exception:
pass
return TORCH_DTYPE
def _infer_vlm_arch(model_id: Optional[str]) -> Optional[str]:
"""The transformers architecture key for a known multimodal model id
(the `_arch` value models.get_vlm() stamps on its VLM instances), or
None when the id isn't a registered multimodal transformers model. Used
by vlm_answer()'s same-model reuse branch to stamp the shared LLM
model without loading a second copy."""
if model_id in mr.QWEN_VL_IDS:
return "qwen_vl"
if model_id in mr.QWEN3_VL_IDS:
return "qwen3vl"
if model_id in mr.SMOL_VLM_IDS:
return "smolvlm"
if model_id in mr.GEMMA4_IDS:
return "gemma4"
return None
def vlm_answer(question: str, images: list, context: str = "", model_id: Optional[str] = None, mmproj_path: Optional[str] = None, lang_key: str = "kh", n_ctx: Optional[int] = None, provider: Optional[str] = None) -> str:
try:
# ββ Same-model reuse (VRAM) ββββββββββββββββββββββββββββββββββ
# When the requested VLM is the SAME model the text LLM already
# loaded as a transformers wrapper (e.g. a Gemma-4 / Qwen-VL RAG
# model on the local-HF provider), reuse its live `.model` +
# `.processor` instead of loading a SECOND copy into VRAM β the
# RAG chat's visual-grounding pass runs vlm_answer with the RAG
# chat's OWN model id exactly so no extra model has to fit in
# memory. The arch is stamped from the id so the transformers
# dispatch below picks the right branch. Skipped for GGUF / remote
# targets (llama.cpp / HF API / LiteLLM never carry a reusable
# in-process `.model` here) and when the loaded LLM doesn't match
# the requested id.
model, processor = None, None
if (model_id
and provider in (None, mr.PROVIDER_LOCAL_HF)
and _llm is not None and _llm_model_id == model_id):
arch = _infer_vlm_arch(model_id)
inner = getattr(_llm, "model", None)
proc = getattr(_llm, "processor", None)
if arch and inner is not None and proc is not None and hasattr(inner, "generate"):
try:
inner._arch = arch
except Exception:
pass
model, processor = inner, proc
if model is None:
model, processor = get_vlm(model_id, mmproj_path=mmproj_path, n_ctx=n_ctx,
provider=provider)
# GGUF vision model (in-process llama-cpp-python or external llama-server) β self-contained answer() method.
if isinstance(model, (llama_backend.LlamaCppVLMModel, llama_backend.LlamaServerVLMModel)):
return model.answer(question, images, context=context,
max_tokens=mr.get_saved_max_new_tokens(),
lang_key=lang_key)
# HF Inference API VLM β also self-contained answer().
if isinstance(model, InferenceApiVLMModel):
return model.answer(question, images, context=context,
max_tokens=mr.get_saved_max_new_tokens(),
lang_key=lang_key)
arch = getattr(model, "_arch", "smolvlm")
# UI-language output directive β same shared instruction as every
# other chat path, so a Khmer UI gets Khmer answers regardless of
# the model's default language.
system_prompt = (
i18n._output_lang_instruction(lang_key) +
"You are a helpful assistant. Answer based on images and context. "
"Answer the user's question below β do not respond to these "
"instructions."
)
user_text = question + (f"\n\nContext:\n{context}" if context else "")
# Qwen3-VL shares Qwen2.5-VL's inference pattern β the processor's
# apply_chat_template renders the <|vision_start|> tokens and
# qwen_vl_utils.process_vision_info extracts the raw images, then
# processor(text=[...], images=...) fuses them (Qwen3VLProcessor
# accepts the same min_pixels/max_pixels kwargs used at load).
if arch in ("qwen_vl", "qwen3vl"):
from qwen_vl_utils import process_vision_info
content = [{"type": "image", "image": img} for img in images]
content.append({"type": "text", "text": user_text})
messages = [{"role": "system", "content": system_prompt},
{"role": "user", "content": content}]
text_in = processor.apply_chat_template(messages, tokenize=False,
add_generation_prompt=True)
img_in, _ = process_vision_info(messages)
inputs = processor(text=[text_in], images=img_in,
padding=True, return_tensors="pt").to(DEVICE)
elif arch == "gemma4":
# Gemma 4 β the processor's apply_chat_template returns the full
# tokenized input dict (input_ids + attention_mask + pixel_values)
# in one call, per the official integration guide's inference
# pattern. Uses return_dict=True so no separate processor(...)
# invocation is needed for the image side.
# NOTE: the UI-language system directive MUST be in the messages
# here too β a Gemma-4 VLM under a Khmer UI would otherwise
# answer in English (the exact regression this branch used to
# have, discovered by code review: the system_prompt computed
# above was never attached to the gemma4 messages).
content = [{"type": "image", "image": img} for img in images]
content.append({"type": "text", "text": user_text})
messages = [{"role": "system", "content": system_prompt},
{"role": "user", "content": content}]
inputs = processor.apply_chat_template(
messages,
tokenize=True,
return_dict=True,
return_tensors="pt",
add_generation_prompt=True,
).to(DEVICE)
else:
content = [{"type": "image"} for _ in images]
content.append({"type": "text", "text": user_text})
messages = [{"role": "system", "content": system_prompt},
{"role": "user", "content": content}]
text_in = processor.apply_chat_template(messages, add_generation_prompt=True)
inputs = processor(text=text_in, images=images or None, return_tensors="pt").to(DEVICE)
max_new = mr.get_saved_max_new_tokens()
bus = get_bus()
if bus.running:
# Live token streaming for the local transformers VLM: run the
# generation in a background thread feeding a TextIteratorStreamer,
# pushing each decoded text delta to the live bus β the Vision
# answer grows from REAL tokens like the GGUF VLM backends. Any
# hiccup (no tokenizer, unsupported streamer) falls back to the
# plain blocking generate below.
try:
from transformers import TextIteratorStreamer
import threading
tok = getattr(processor, "tokenizer", None) or getattr(processor, "chat_template", None) or processor
streamer = TextIteratorStreamer(
tok, skip_prompt=True, skip_special_tokens=True)
gen_kwargs = dict(inputs)
gen_kwargs["max_new_tokens"] = max_new
gen_kwargs["streamer"] = streamer
thread = threading.Thread(
target=model.generate, kwargs=gen_kwargs, daemon=True)
thread.start()
bus.begin_generation()
pieces = []
with torch.no_grad():
for piece in streamer:
if piece:
pieces.append(piece)
bus.push(piece)
thread.join()
bus.end_generation()
return "".join(pieces)
except Exception as e:
try:
bus.end_generation()
except Exception: # noqa: BLE001
pass
print(f"[VLM] transformers live streaming unavailable ({e}) β "
"using blocking generate β¦")
with torch.no_grad():
out = model.generate(**inputs, max_new_tokens=max_new)
trimmed = out[0][inputs["input_ids"].shape[-1]:]
return processor.decode(trimmed, skip_special_tokens=True)
except Exception as e:
import traceback
return f"β Error during VLM generation: {str(e)}\n\n{traceback.format_exc()}"
def get_stt_pipeline(model_id: Optional[str] = None):
global _stt_pipeline, _stt_model_id
target = model_id or mr.DEFAULT_STT_MODEL
if _stt_pipeline is not None and target == _stt_model_id:
return _stt_pipeline
with _stt_lock:
if _stt_pipeline is not None and target == _stt_model_id:
return _stt_pipeline
if _stt_pipeline is not None:
print(f"[STT] Unloading previous STT model '{_stt_model_id}' before loading '{target}' β¦")
_release_and_clear("_stt_pipeline")
# ββ HF Inference API ββββββββββββββββββββββββββββββββββββββ
if target == mr.HF_INFERENCE_API_SENTINEL:
hf_model_id = mr.get_hf_api_model_id_for("stt")
if not hf_model_id:
raise ValueError(
"Hugging Face Inference API selected for Speech, but no "
"model ID is configured."
)
_stt_pipeline = InferenceApiSTTModel(model_id=hf_model_id)
_stt_model_id = target
return _stt_pipeline
# ββ whisper.cpp server ββββββββββββββββββββββββββββββββββββ
suffix = str(target).lower()
if suffix.endswith(".ggml") or suffix.endswith(".bin"):
base_url = whisper_cpp_backend.get_or_start_whisper_server(target)
_stt_pipeline = whisper_cpp_backend.WhisperServerModel(
base_url=base_url, model_path=target,
)
_stt_model_id = target
return _stt_pipeline
# ββ Local HuggingFace Whisper pipeline ββββββββββββββββββββ
print(f"[STT] Loading '{target}' on {DEVICE.upper()} β¦")
# Stub `av` (PyAV) if its native DLLs are missing (frozen/MSIX
# builds). transformers.pipelines.__init__ unconditionally imports
# VideoClassificationPipeline β `av`, but we only need ASR.
import sys as _sys
if "av" not in _sys.modules:
try:
import av as _av_probe # noqa: F401
except Exception:
import types as _types
import importlib.machinery as _machinery
_av_stub = _types.ModuleType("av")
_av_stub.__path__ = []
_av_stub.__spec__ = _machinery.ModuleSpec("av", None, is_package=True)
_av_stub.__spec__.submodule_search_locations = []
_sys.modules["av"] = _av_stub
print("[STT] Stubbed missing 'av' (PyAV) β video classification disabled, ASR unaffected.")
from transformers import pipeline as hf_pipeline
if DEVICE == "cuda":
device_arg = 0
elif DEVICE == "xpu":
device_arg = "xpu"
elif DEVICE == "mps":
device_arg = "mps"
else:
device_arg = -1
_stt_pipeline = hf_pipeline(
"automatic-speech-recognition",
model=target,
dtype=TORCH_DTYPE,
device=device_arg,
)
# NOTE: the pipeline is built WITHOUT chunk_length_s/stride_length_s:
# transformers flags that experimental seq2seq windowing as
# inaccurate, and the app no longer feeds 30s manual chunks through
# it β transcribe_audio_stream drives the model's NATIVE long-form
# generate() instead (the path the transformers warning recommends).
if hasattr(_stt_pipeline, "model") and hasattr(_stt_pipeline.model, "generation_config"):
gen_cfg = _stt_pipeline.model.generation_config
gen_cfg.forced_decoder_ids = None
# Some community Whisper fine-tunes (e.g. the Khmer-tuned
# checkpoints in STT_OPTIONS) ship a generation_config.json
# predating transformers' current language-forcing mechanism β
# it's missing lang_to_id/task_to_id, which makes
# generate(language=...) raise "generation config is outdated"
# the moment a specific language (not auto-detect) is picked.
# Patch the missing multilingual mapping in from the matching
# stock openai/whisper checkpoint of the same size β same
# tokenizer/architecture, so the mapping is valid β instead of
# only discovering this the first time someone picks a language.
if getattr(gen_cfg, "lang_to_id", None) is None:
try:
from transformers import GenerationConfig
size_hint = next(
(s for s in ("large-v3", "large-v2", "large", "medium", "small", "base", "tiny")
if s in target.lower()),
"small",
)
base_id = f"openai/whisper-{size_hint}"
base_cfg = GenerationConfig.from_pretrained(base_id)
for attr in ("lang_to_id", "task_to_id", "is_multilingual"):
if hasattr(base_cfg, attr):
setattr(gen_cfg, attr, getattr(base_cfg, attr))
gen_cfg.forced_decoder_ids = None
print(f"[STT] '{target}' had an outdated generation_config β "
f"patched language mapping from '{base_id}'.")
except Exception as e:
print(f"[STT] Could not patch outdated generation_config for '{target}': {e}")
_stt_model_id = target
return _stt_pipeline
def _is_khmer_asr_target(language: Optional[str], model_id: Optional[str]) -> bool:
"""Identify if the target audio transcription is Khmer (by language selection or Khmer fine-tuned model)."""
lang = str(language or "").strip().lower()
mid = str(model_id or "").strip().lower()
if lang in ("khmer", "km"):
return True
if any(k in mid for k in ("khmer", "metythorn", "seanghay")):
return True
return False
def _transcribe_khmer_whisper(
model, feature_extractor, tokenizer, audio_array, target_sr: int,
total_samples: int, language: Optional[str] = None, model_id: Optional[str] = None
):
"""Dedicated transcription pipeline for Khmer language and Khmer fine-tuned checkpoints.
Khmer is a multi-byte unspaced abugida script with frequent subword overlap. It must NOT
use n-gram repetition bans or repetition penalties during generation, as those penalize
legitimate Khmer syllables and trigger random multilingual token swaps.
"""
import re
import threading
from transformers import TextIteratorStreamer
# Khmer generation setup
gen_kwargs = {"task": "transcribe"}
# Force "km" if not auto or if explicit
if language and language != "auto":
gen_kwargs["language"] = "km" if language.lower() in ("khmer", "km") else language
inputs = feature_extractor(
audio_array, sampling_rate=target_sr,
return_tensors="pt", return_attention_mask=True,
)
try:
inputs = {k: v.to(model.device) for k, v in inputs.items()}
inputs = {
k: (v.to(model.dtype) if v.is_floating_point() else v)
for k, v in inputs.items()
}
except Exception:
pass
def _clean_khmer_output(t_str: str) -> str:
if not t_str:
return ""
# Deduplicate consecutive repeated Khmer words
t_str = re.sub(r'(\b[\u1780-\u17FF\w]+\b)(?:\s+\1){2,}', r'\1', t_str)
t_str = re.sub(r'\s{2,}', ' ', t_str)
return t_str.strip()
# 1. Try real-time token streaming
try:
streamer = TextIteratorStreamer(
tokenizer, skip_prompt=True, skip_special_tokens=True
)
gen_dict = dict(inputs, **gen_kwargs, streamer=streamer)
if total_samples > 30 * target_sr:
gen_dict["return_segments"] = True
gen_dict["condition_on_prev_tokens"] = True
# The generation thread MUST always signal streamer.end() β if
# model.generate raises inside the thread (OOM, unsupported kwarg,
# outdated generation config β¦), an un-signalled streamer leaves the
# `for piece in streamer` loop below blocked on its queue FOREVER
# (a frozen STT tab). On failure we fall through to the batch path.
gen_error = []
def _streaming_generate():
try:
model.generate(**gen_dict)
except Exception as e:
gen_error.append(e)
print(f"[STT-Khmer] Streaming generate failed ({e})")
finally:
streamer.end()
thread = threading.Thread(target=_streaming_generate, daemon=True)
thread.start()
acc = []
for piece in streamer:
if piece:
acc.append(piece)
yield "".join(acc).strip()
thread.join()
final_res = _clean_khmer_output("".join(acc))
if not gen_error:
yield final_res if final_res else "(No speech detected)"
return
print("[STT-Khmer] Streaming fallback β running batch generate β¦")
if "generation config is outdated" in str(gen_error[0]):
# Don't replay the poisoned kwargs into the batch path β go
# straight to the plain auto-detect generate (the known-good
# recovery for an outdated generation config).
outputs = model.generate(**inputs)
seqs = outputs["sequences"] if isinstance(outputs, dict) else outputs
text = _clean_khmer_output(" ".join(
t.strip() for t in tokenizer.batch_decode(
seqs, skip_special_tokens=True)
if t.strip()))
yield text if text else "(No speech detected)"
return
except Exception as e:
print(f"[STT-Khmer] Streaming fallback ({e}) β running batch generate β¦")
# 2. Batch generate fallback
try:
if total_samples > 30 * target_sr:
outputs = model.generate(
**inputs, return_segments=True,
condition_on_prev_tokens=True, **gen_kwargs,
)
else:
outputs = model.generate(**inputs, **gen_kwargs)
except ValueError as e:
if "generation config is outdated" in str(e):
outputs = model.generate(**inputs)
else:
raise
sequences = outputs["sequences"] if isinstance(outputs, dict) else outputs
text = " ".join(
t.strip()
for t in tokenizer.batch_decode(sequences, skip_special_tokens=True)
if t.strip()
)
text = _clean_khmer_output(text)
yield text if text else "(No speech detected)"
def _transcribe_english_and_multilingual_whisper(
model, feature_extractor, tokenizer, audio_array, target_sr: int,
total_samples: int, language: Optional[str] = None, model_id: Optional[str] = None
):
"""Dedicated transcription pipeline for English and standard international languages."""
import re
import threading
from transformers import TextIteratorStreamer
gen_kwargs = {}
if language and language != "auto":
gen_kwargs["language"] = language
gen_kwargs["task"] = "transcribe"
inputs = feature_extractor(
audio_array, sampling_rate=target_sr,
return_tensors="pt", return_attention_mask=True,
)
try:
inputs = {k: v.to(model.device) for k, v in inputs.items()}
inputs = {
k: (v.to(model.dtype) if v.is_floating_point() else v)
for k, v in inputs.items()
}
except Exception:
pass
def _clean_standard_output(t_str: str) -> str:
if not t_str:
return ""
t_str = re.sub(r'(\b\S+\b)(?:\s+\1){3,}', r'\1', t_str)
return t_str.strip()
# 1. Try real-time token streaming
try:
streamer = TextIteratorStreamer(
tokenizer, skip_prompt=True, skip_special_tokens=True
)
gen_dict = dict(inputs, **gen_kwargs, streamer=streamer)
if total_samples > 30 * target_sr:
gen_dict["return_segments"] = True
gen_dict["condition_on_prev_tokens"] = True
# Same end-signal guarantee as _transcribe_khmer_whisper: a generate
# that raises inside its thread must never leave the streamer loop
# below blocked forever β fall through to the batch path instead.
gen_error = []
def _streaming_generate():
try:
model.generate(**gen_dict)
except Exception as e:
gen_error.append(e)
print(f"[STT-Multilingual] Streaming generate failed ({e})")
finally:
streamer.end()
thread = threading.Thread(target=_streaming_generate, daemon=True)
thread.start()
acc = []
for piece in streamer:
if piece:
acc.append(piece)
yield "".join(acc).strip()
thread.join()
final_res = _clean_standard_output("".join(acc))
if not gen_error:
yield final_res if final_res else "(No speech detected)"
return
print("[STT-Multilingual] Streaming fallback β running batch generate β¦")
if "generation config is outdated" in str(gen_error[0]):
# Same poisoned-kwargs rule as the Khmer path: an outdated
# generation config recovers via the plain auto-detect generate.
outputs = model.generate(**inputs)
seqs = outputs["sequences"] if isinstance(outputs, dict) else outputs
text = _clean_standard_output(" ".join(
t.strip() for t in tokenizer.batch_decode(
seqs, skip_special_tokens=True)
if t.strip()))
yield text if text else "(No speech detected)"
return
except Exception as e:
print(f"[STT-Multilingual] Streaming fallback ({e}) β running batch generate β¦")
# 2. Batch generate fallback
try:
if total_samples > 30 * target_sr:
outputs = model.generate(
**inputs, return_segments=True,
condition_on_prev_tokens=True, **gen_kwargs,
)
else:
outputs = model.generate(**inputs, **gen_kwargs)
except ValueError as e:
if gen_kwargs and "generation config is outdated" in str(e):
outputs = model.generate(**inputs)
else:
raise
sequences = outputs["sequences"] if isinstance(outputs, dict) else outputs
text = " ".join(
t.strip()
for t in tokenizer.batch_decode(sequences, skip_special_tokens=True)
if t.strip()
)
text = _clean_standard_output(text)
yield text if text else "(No speech detected)"
def transcribe_audio_stream(audio_path: Optional[str], language: Optional[str] = None,
model_id: Optional[str] = None):
"""Generator version of transcribe_audio β yields intermediate status and chunked
transcription text in real-time for live UI streaming."""
if not audio_path:
return
yield "β³ Preparing speech-to-text model..."
try:
asr = get_stt_pipeline(model_id)
if hasattr(asr, "transcribe") and callable(asr.transcribe):
yield "π Transcribing via server/remote API..."
res = asr.transcribe(audio_path, language=language)
yield res
return
gen_kwargs = {}
if language and language != "auto":
gen_kwargs["language"] = language
gen_kwargs["task"] = "transcribe"
yield "π΅ Loading and decoding audio file..."
import numpy as np
target_sr = getattr(getattr(asr, "feature_extractor", None), "sampling_rate", 16000)
try:
import soundfile as sf
audio_array, src_sr = sf.read(audio_path, dtype="float32", always_2d=False)
except Exception:
import librosa
audio_array, src_sr = librosa.load(audio_path, sr=None, mono=False)
audio_array = np.asarray(audio_array, dtype="float32")
if audio_array.ndim == 2:
channel_axis = 0 if audio_array.shape[0] < audio_array.shape[1] else 1
audio_array = audio_array.mean(axis=channel_axis).astype("float32")
if src_sr != target_sr:
import librosa
audio_array = librosa.resample(audio_array, orig_sr=src_sr, target_sr=target_sr)
total_samples = len(audio_array)
# ββ Native Whisper long-form transcription (model.generate) ββββββ
from transformers import WhisperForConditionalGeneration
model = getattr(asr, "model", None)
feature_extractor = getattr(asr, "feature_extractor", None)
tokenizer = getattr(asr, "tokenizer", None)
if (isinstance(model, WhisperForConditionalGeneration)
and feature_extractor is not None and tokenizer is not None):
yield "ποΈ Transcribing audio..."
if _is_khmer_asr_target(language, model_id):
yield from _transcribe_khmer_whisper(
model, feature_extractor, tokenizer, audio_array,
target_sr, total_samples, language, model_id
)
else:
yield from _transcribe_english_and_multilingual_whisper(
model, feature_extractor, tokenizer, audio_array,
target_sr, total_samples, language, model_id
)
return
# ββ Fallback (non-Whisper HF ASR models) β the old per-chunk path ββ
gen_kwargs = {}
if language and language != "auto":
gen_kwargs["language"] = language
gen_kwargs["task"] = "transcribe"
chunk_samples = 30 * target_sr # 30-second audio chunks
if total_samples > chunk_samples:
transcripts = []
num_chunks = int(np.ceil(total_samples / chunk_samples))
for i in range(num_chunks):
start = i * chunk_samples
end = min((i + 1) * chunk_samples, total_samples)
chunk_data = audio_array[start:end]
yield f"ποΈ Transcribing chunk {i+1}/{num_chunks} ({len(chunk_data)/target_sr:.1f}s)..."
try:
res = asr({"array": chunk_data, "sampling_rate": target_sr}, generate_kwargs=gen_kwargs)
except ValueError as e:
if gen_kwargs and "generation config is outdated" in str(e):
res = asr({"array": chunk_data, "sampling_rate": target_sr})
else:
raise
chunk_text = (res.get("text", "") if isinstance(res, dict) else str(res)).strip()
if chunk_text:
transcripts.append(chunk_text)
yield "\n".join(transcripts)
final_text = "\n".join(transcripts).strip()
yield final_text if final_text else "(No speech detected)"
else:
yield "ποΈ Transcribing audio..."
try:
result = asr({"array": audio_array, "sampling_rate": target_sr}, generate_kwargs=gen_kwargs)
except ValueError as e:
if gen_kwargs and "generation config is outdated" in str(e):
result = asr({"array": audio_array, "sampling_rate": target_sr})
else:
raise
text = (result.get("text", "") if isinstance(result, dict) else str(result)).strip()
yield text if text else "(No speech detected)"
except Exception as e:
import traceback
yield f"β {e}\n\n{traceback.format_exc()}"
def transcribe_audio(audio_path: Optional[str], language: Optional[str] = None,
model_id: Optional[str] = None) -> str:
if not audio_path:
return ""
last_text = ""
for chunk in transcribe_audio_stream(audio_path, language=language, model_id=model_id):
last_text = chunk
return last_text
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# HF Inference API model proxies β thin wrappers that call
# huggingface_hub.InferenceClient for model types that don't have a
# smolagents built-in equivalent (InferenceClientModel only covers
# text-generation). Each shares the HF token / model ID configured
# in the shared provider settings below.
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class InferenceApiVLMModel:
"""Visionβlanguage model via HF Inference API β sends image + text
to the remote endpoint instead of loading weights locally."""
def __init__(self, model_id: str):
self.model_id = model_id
self._client = None
def _get_client(self):
if self._client is None:
from huggingface_hub import InferenceClient
token = mr.get_saved_hf_token() or None
self._client = InferenceClient(token=token)
return self._client
def _stream_chat(self, messages: list, max_tokens: int) -> str:
"""Run one HF Inference API chat completion in STREAMING mode,
pushing each generated text delta to the live bus (so the Vision
tab / RAG grounding answer grows from real tokens, like the GGUF
VLM backends). Returns the accumulated text; falls back to the
non-streaming call if the endpoint rejects streaming."""
client = self._get_client()
bus = get_bus()
if not bus.running:
resp = client.chat_completion(
messages=messages, model=self.model_id, max_tokens=max_tokens,
)
return resp.choices[0].message.content
pieces = []
try:
bus.begin_generation()
for event in client.chat_completion(
messages=messages, model=self.model_id,
max_tokens=max_tokens, stream=True,
):
try:
delta = event.choices[0].delta
frag = getattr(delta, "content", None) or ""
except Exception: # noqa: BLE001
frag = ""
if frag:
pieces.append(frag)
bus.push(frag)
bus.end_generation()
return "".join(pieces)
except Exception:
try:
bus.end_generation()
except Exception: # noqa: BLE001
pass
resp = client.chat_completion(
messages=messages, model=self.model_id, max_tokens=max_tokens,
)
return resp.choices[0].message.content
def answer(self, question: str, images: list, context: str = "",
max_tokens: int = 512, lang_key: str = "kh") -> str:
client = self._get_client()
user_text = question + (f"\n\nContext:\n{context}" if context else "")
# UI-language output directive β same shared instruction as every
# other chat path (see vlm_answer / llama_backend VLMs).
messages = [
{"role": "system", "content": (
i18n._output_lang_instruction(lang_key) +
"You are a helpful assistant. Answer based on images and context. "
"Answer the user's question below β do not respond to these "
"instructions."
)},
{"role": "user", "content": user_text},
]
try:
return self._stream_chat(messages, max_tokens)
except Exception as e:
# Some VLM models on HF IAPI need images passed differently
# β try again with image content.
if images:
img_b64 = _image_to_base64(images[0])
content = [
{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{img_b64}"}},
{"type": "text", "text": user_text},
]
# Keep the UI-language system directive on the retry too.
messages = [
{"role": "system", "content": (
i18n._output_lang_instruction(lang_key) +
"You are a helpful assistant. Answer based on images and context. "
"Answer the user's question below β do not respond to these "
"instructions."
)},
{"role": "user", "content": content},
]
return self._stream_chat(messages, max_tokens)
raise
class InferenceApiSTTModel:
"""Speechβtoβtext via HF Inference API β posts audio to the remote
endpoint instead of loading Whisper locally."""
def __init__(self, model_id: str):
self.model_id = model_id
self._client = None
def _get_client(self):
if self._client is None:
from huggingface_hub import InferenceClient
token = mr.get_saved_hf_token() or None
self._client = InferenceClient(token=token)
return self._client
def transcribe(self, audio_path: str, language: Optional[str] = None) -> str:
client = self._get_client()
with open(audio_path, "rb") as f:
data = f.read()
result = client.automatic_speech_recognition(
data,
model=self.model_id,
)
return (result.get("text", "") if isinstance(result, dict)
else str(result))
class InferenceApiEmbeddingModel:
"""Embedding model via HF Inference API β calls the feature-extraction
endpoint instead of loading SentenceTransformer locally."""
def __init__(self, model_id: str):
self.model_id = model_id
self._client = None
def _get_client(self):
if self._client is None:
from huggingface_hub import InferenceClient
token = mr.get_saved_hf_token() or None
self._client = InferenceClient(token=token)
return self._client
def encode(self, texts: list, normalize: bool = True) -> list:
client = self._get_client()
result = client.feature_extraction(texts, model=self.model_id)
# Result may be a list of lists or a numpy array
import numpy as np
arr = np.asarray(result, dtype=np.float32)
if arr.ndim == 1:
arr = arr.reshape(1, -1)
if normalize:
norms = np.linalg.norm(arr, axis=1, keepdims=True)
norms = np.where(norms == 0, 1.0, norms)
arr = arr / norms
return arr.tolist()
class EmbeddingServerModel:
"""Embedding model via llama.cpp server's /v1/embeddings endpoint
(OpenAI-compatible). Spawns/reuses the DEDICATED embedding llama-server
process managed by llama_backend.get_or_start_embed_server() β its own
subprocess on its own port, fully independent of the chat/VLM server."""
def __init__(self, model_path: str, base_url: str, n_ctx: int = 16384):
self.model_id = model_path
self.model_path = model_path
self.base_url = base_url.rstrip("/")
# Remembered so a dead-server restart re-requests the SAME config
# (a different n_ctx would needlessly relaunch the server).
self.n_ctx = int(n_ctx or 16384)
def encode(self, texts: list, normalize: bool = True) -> list:
import requests
import numpy as np
# For a single string, wrap it
if isinstance(texts, str):
texts = [texts]
payload = {
"input": texts,
"model": self.model_path,
}
try:
resp = requests.post(
f"{self.base_url}/v1/embeddings",
json=payload,
timeout=120,
)
resp.raise_for_status()
except requests.exceptions.ConnectionError:
# The dedicated embedding server died or was stopped (Free All
# VRAM, an exe-path change, a crash) while this cached wrapper
# survived. Restart it ONCE on its own slot and retry β the
# chat/VLM server is never touched.
print(f"[RAG] Embedding server unreachable at {self.base_url} β "
f"restarting the dedicated embedding llama-server β¦")
base_url = llama_backend.get_or_start_embed_server(
model_path=self.model_path,
n_ctx=self.n_ctx,
)
self.base_url = base_url.rstrip("/")
resp = requests.post(
f"{self.base_url}/v1/embeddings",
json=payload,
timeout=120,
)
resp.raise_for_status()
data = resp.json()
# Extract embeddings in order of the input indices
embeddings = [d["embedding"] for d in sorted(data["data"], key=lambda x: x["index"])]
arr = np.asarray(embeddings, dtype=np.float32)
if normalize:
norms = np.linalg.norm(arr, axis=1, keepdims=True)
norms = np.where(norms == 0, 1.0, norms)
arr = arr / norms
return arr.tolist()
def _image_to_base64(img) -> str:
"""Convert a PIL image to a base64-encoded JPEG string."""
import base64
from io import BytesIO
buf = BytesIO()
img.convert("RGB").save(buf, format="JPEG", quality=85)
return base64.b64encode(buf.getvalue()).decode("utf-8")
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Explicit "force unload / offload from VRAM" actions β wired to an
# "Unload from VRAM" button on each relevant tab. These free memory
# immediately via _release_model() without loading any replacement,
# unlike get_llm()/get_vlm()/get_stt_pipeline() which only release the
# *previous* model right before loading a new one.
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def unload_llm_fn(lang_key: str = "kh") -> str:
global _llm, _llm_model_id, _llm_backend_key
l = LANGUAGES.get(lang_key, LANGUAGES["kh"])
if _llm is None:
return l["btn_unload_none"]
mid = _llm_model_id
_release_and_clear("_llm")
_llm_backend_key = None
return l["msg_unloaded"].format(model=mid)
def unload_vlm_fn(lang_key: str = "kh") -> str:
global _vlm_model, _vlm_processor, _vlm_model_id, _vlm_n_ctx, _vlm_backend_key
l = LANGUAGES.get(lang_key, LANGUAGES["kh"])
if _vlm_model is None:
return l["btn_unload_none"]
mid = _vlm_model_id
_release_and_clear("_vlm_model")
_vlm_processor = None
_vlm_model_id = None
_vlm_n_ctx = None
_vlm_backend_key = None
return l["msg_unloaded"].format(model=mid)
def unload_stt_fn(lang_key: str = "kh") -> str:
global _stt_pipeline, _stt_model_id
l = LANGUAGES.get(lang_key, LANGUAGES["kh"])
if _stt_pipeline is None:
return l["btn_unload_none"]
mid = _stt_model_id
_release_and_clear("_stt_pipeline")
_stt_model_id = None
return l["msg_unloaded"].format(model=mid)
def force_reload_llm(target_model_id: str, n_ctx: Optional[int] = None, provider: Optional[str] = None):
"""Used by the tab-level 'Load' buttons and the global 'π§ Context
Window' control: fully release whatever LLM is currently loaded
(regardless of id) and load `target_model_id` fresh β optionally with
a specific context window (GGUF backend only; ignored for HF models)."""
global _llm
_release_and_clear("_llm")
return get_llm(target_model_id, n_ctx=n_ctx, provider=provider)
def force_reload_vlm(target_model_id: str, mmproj_path: Optional[str] = None, provider: Optional[str] = None, n_ctx: Optional[int] = None):
global _vlm_model, _vlm_processor
_release_and_clear("_vlm_model")
_vlm_processor = None
return get_vlm(target_model_id, mmproj_path=mmproj_path, provider=provider, n_ctx=n_ctx)
def force_reload_stt(target_model_id: str):
global _stt_pipeline, _stt_model_id
_release_and_clear("_stt_pipeline")
_stt_model_id = None
return get_stt_pipeline(target_model_id)
"""
models.py β Lazy-loaded model backends: embedding model, ChromaDB handle,
text LLM (HuggingFace or GGUF via llama_backend), Vision LLM, and
Speech-to-Text pipeline. Each model type keeps its own module-level cache
and lock, following the lazy-load/lock pattern used throughout the app.
"""
import gc
import os
import threading
import time
from pathlib import Path
from typing import Any, Optional
import torch
from backend import llama_backend
from backend import model_registry as mr
from backend import whisper_cpp_backend
from backend.hardware import DEVICE, TORCH_DTYPE, is_illegal_instruction_error
from backend.live_stream import get_bus
from backend.metadata_hardening import harden_metadata
from ui import i18n
from ui.i18n import LANGUAGES
harden_metadata()
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Patch transformers' Gemma-4 RoPE device-mismatch bug:
# In transformers, Gemma4TextRotaryEmbedding.forward does matrix
# multiplication `@` with position_ids on CPU and inv_freq on CUDA when
# device_map="cuda" is used, causing "Expected all tensors to be on the
# same device" RuntimeError.
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
try:
from transformers.models.gemma4 import modeling_gemma4
_orig_gemma4_rotary_forward = modeling_gemma4.Gemma4TextRotaryEmbedding.forward
def _patched_gemma4_rotary_forward(self, x, position_ids, layer_type=None):
if position_ids is not None and position_ids.device != x.device:
position_ids = position_ids.to(x.device)
return _orig_gemma4_rotary_forward(self, x, position_ids, layer_type=layer_type)
modeling_gemma4.Gemma4TextRotaryEmbedding.forward = _patched_gemma4_rotary_forward
print("[Gemma4] Applied RoPE device-alignment patch for Gemma4TextRotaryEmbedding.")
except Exception:
pass
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Download size estimation β BF16 download sizes in GB for each model
# (from Google's official docs and HuggingFace model cards). Used to
# warn the user before downloading large models they haven't cached yet.
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
_DOWNLOAD_SIZE_GB = mr.DOWNLOAD_SIZE_GB
def _hf_snapshot_has_weights(model_id: str) -> bool:
"""True when the model's local HF cache snapshot contains at least one
real weight file.
Metadata alone proves nothing: ``snapshot_download`` fetches the tiny
config/tokenizer files FIRST, so an interrupted download still caches
config.json / generation_config.json β which made ``is_model_cached``
report "cached" while the multi-GB safetensors were still downloading
(the false "Download complete" popup). Weight files are only linked into
``snapshots/`` once their blob is complete; an in-progress download lives
in ``blobs/*.incomplete`` and never appears here."""
if not model_id:
return False
try:
# huggingface_hub 1.x keeps the constant in .constants (no top-level export)
from huggingface_hub.constants import HF_HUB_CACHE
cache_root = HF_HUB_CACHE
except Exception:
cache_root = os.environ.get("HF_HUB_CACHE") or os.path.join(
os.environ.get("HF_HOME") or os.path.join(os.path.expanduser("~"), ".cache"),
"huggingface", "hub",
)
repo_dir = os.path.join(cache_root, "models--" + str(model_id).replace("/", "--"))
snaps = os.path.join(repo_dir, "snapshots")
if not os.path.isdir(snaps):
return False
weight_exts = (".safetensors", ".bin", ".gguf", ".pt", ".th", ".msgpack", ".h5", ".onnx")
try:
for root, _dirs, files in os.walk(snaps):
for fn in files:
if fn.lower().endswith(weight_exts):
return True
try:
if os.stat(os.path.join(root, fn)).st_size >= 1024 * 1024:
return True
except OSError:
continue
except OSError:
return False
return False