Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
merge nightly into audio branch (mock test)
Roland Tannous1435dbaf59e5
diff --cc studio/backend/core/training/trainer.pyindex eded0664cb4,aa4b551dd4a..d50431b0357--- a/studio/backend/core/training/trainer.py+++ b/studio/backend/core/training/trainer.py@@@ -108,221 -109,14 +110,224 @@@ class UnslothTrainerexcept Exception as e:logger.error(f"Error in progress callback: {e}")+ def _create_progress_callback(self):+ """Create a TrainerCallback for progress tracking. Reused by all training branches."""+ from transformers import TrainerCallback+ trainer_ref = self++ class _ProgressCallback(TrainerCallback):+ def on_log(self, args, state, control, logs=None, **kwargs):+ if not logs:+ return+ loss_value = logs.get('loss', logs.get('train_loss', 0.0))+ current_step = state.global_step+ grad_norm = logs.get('grad_norm', None)++ elapsed_seconds = None+ if trainer_ref.training_start_time is not None:+ elapsed_seconds = time.time() - trainer_ref.training_start_time++ eta_seconds = None+ if elapsed_seconds is not None and current_step > 0:+ total_steps = trainer_ref.training_progress.total_steps+ if total_steps > 0:+ steps_remaining = total_steps - current_step+ if steps_remaining > 0:+ eta_seconds = (elapsed_seconds / current_step) * steps_remaining++ num_tokens = getattr(state, "num_input_tokens_seen", None)++ trainer_ref._update_progress(+ step=current_step,+ epoch=round(state.epoch, 2) if state.epoch else 0,+ loss=loss_value,+ learning_rate=logs.get('learning_rate', 0.0),+ elapsed_seconds=elapsed_seconds,+ eta_seconds=eta_seconds,+ grad_norm=grad_norm,+ num_tokens=num_tokens,+ eval_loss=logs.get('eval_loss', None),+ status_message="",+ )++ def on_epoch_end(self, args, state, control, **kwargs):+ trainer_ref._update_progress(epoch=state.epoch, step=state.global_step)++ def on_step_end(self, args, state, control, **kwargs):+ if trainer_ref.should_stop:+ print(f"Stop detected at step {state.global_step}\n")+ control.should_training_stop = True+ return control++ return _ProgressCallback()++ def _calculate_total_steps(self, num_samples, batch_size, grad_accum, num_epochs, max_steps):+ """Calculate total training steps from dataset size and training params."""+ if max_steps and max_steps > 0:+ return max_steps+ len_dataloader = math.ceil(num_samples / batch_size)+ steps_per_epoch = max(len_dataloader // grad_accum + int(len_dataloader % grad_accum > 0), 1)+ return steps_per_epoch * num_epochs++ def _build_audio_training_args(self, training_args, output_dir, *, extra_args=None):+ """Build training args dict for audio branches.++ Constructs the common config (batch size, lr, warmup, fp16/bf16, etc.)+ and applies per-branch overrides via extra_args.+ """+ batch_size = training_args.get('batch_size', 2)+ gradient_accumulation_steps = training_args.get('gradient_accumulation_steps', 4)+ warmup_steps_val = training_args.get('warmup_steps', 5)+ max_steps_val = training_args.get('max_steps', 0)+ learning_rate = training_args.get('learning_rate', 2e-4)+ weight_decay = training_args.get('weight_decay', 0.001)+ lr_scheduler_type = training_args.get('lr_scheduler_type', 'linear')+ random_seed = training_args.get('random_seed', 3407)+ optim_value = training_args.get('optim', 'adamw_8bit')++ config = {+ "per_device_train_batch_size": batch_size,+ "gradient_accumulation_steps": gradient_accumulation_steps,+ "warmup_steps": warmup_steps_val if warmup_steps_val is not None else 5,+ "learning_rate": learning_rate,+ "fp16": not is_bfloat16_supported(),+ "bf16": is_bfloat16_supported(),+ "logging_steps": 1,+ "optim": optim_value,+ "weight_decay": weight_decay,+ "lr_scheduler_type": lr_scheduler_type,+ "seed": random_seed,+ "output_dir": output_dir,+ "report_to": ["wandb"] if training_args.get('enable_wandb', False) else "none",+ }++ # max_steps vs epochs+ if max_steps_val and max_steps_val > 0:+ config["max_steps"] = max_steps_val+ else:+ config["num_train_epochs"] = training_args.get('num_epochs', 3)++ # save_steps+ save_steps_val = training_args.get('save_steps', 0)+ if save_steps_val and save_steps_val > 0:+ config["save_steps"] = save_steps_val+ config["save_strategy"] = "steps"++ # Apply per-branch overrides+ if extra_args:+ config.update(extra_args)++ return config++ def _finalize_training(self, output_dir, label=""):+ """Save model after training and update progress. Used by all training branches."""+ if self.should_stop and self.save_on_stop:+ self.trainer.save_model()+ self.tokenizer.save_pretrained(output_dir)++ self._patch_adapter_config(output_dir)+ msg = f"{label} training stopped" if label else "Training stopped"+ print(f"\n{msg}. Model saved to {output_dir}\n")+ self._update_progress(+ is_training=False,+ status_message=f"Training stopped. Model saved to {output_dir}",+ )+ elif self.should_stop:+ msg = f"{label} training cancelled" if label else "Training cancelled"+ print(f"\n{msg}.\n")+ self._update_progress(is_training=False, status_message="Training cancelled.")+ else:+ self.trainer.save_model()+ self.tokenizer.save_pretrained(output_dir)++ self._patch_adapter_config(output_dir)+ msg = f"{label} training completed" if label else "Training completed"+ print(f"\n{msg}! Model saved to {output_dir}\n")+ self._update_progress(+ is_training=False,+ is_completed=True,+ status_message=f"Training completed! Model saved to {output_dir}",+ )++ def _cleanup_audio_artifacts(self):+ """Remove sys.path entries and sys.modules from previous audio preprocessing.++ After audio training, cloned repo dirs (OuteTTS, Spark-TTS) remain on+ sys.path and heavy audio modules (snac, whisper, sparktts, outetts) stay+ in sys.modules. When the next training run calls dataset.map(num_proc=N),+ forked child processes inherit this stale state and deadlock.+ """+ import sys as _sys++ # Remove cloned audio repo paths from sys.path+ base_dir = os.path.dirname(os.path.abspath(__file__))+ audio_paths = [+ os.path.join(base_dir, "inference", "OuteTTS"), # DAC/OuteTTS+ ]+ # Spark-TTS path is relative to the downloaded repo+ if self._spark_tts_repo_dir:+ spark_code_dir = os.path.join(os.path.dirname(self._spark_tts_repo_dir), "Spark-TTS")+ audio_paths.append(spark_code_dir)++ removed_paths = []+ for path in audio_paths:+ if path in _sys.path:+ _sys.path.remove(path)+ removed_paths.append(path)++ # Remove stale audio modules from sys.modules+ prefixes = ('snac', 'whisper', 'sparktts', 'outetts')+ removed_modules = [key for key in _sys.modules if key.startswith(prefixes)]+ for key in removed_modules:+ del _sys.modules[key]++ if removed_paths or removed_modules:+ print(f"Cleaned up audio artifacts: {len(removed_paths)} paths, "+ f"{len(removed_modules)} modules\n")++ def _resolve_audio_columns(self, dataset, custom_format_mapping: dict = None):+ """Resolve audio, text, and speaker columns from user mapping or hardcoded fallback.++ Returns:+ dict with keys: audio_col, text_col, speaker_col (speaker_col may be None)+ """+ cols = dataset.column_names++ if custom_format_mapping:+ audio_col = None+ text_col = None+ speaker_col = None+ for col, role in custom_format_mapping.items():+ if role == "audio":+ audio_col = col+ elif role == "text":+ text_col = col+ elif role == "speaker_id":+ speaker_col = col+ # Use mapping if both required columns exist in the dataset+ if audio_col and audio_col in cols and text_col and text_col in cols:+ return {"audio_col": audio_col, "text_col": text_col, "speaker_col": speaker_col}++ # Hardcoded fallback (existing behavior)+ audio_col = next((c for c in cols if c.lower() in ("audio", "speech")), None)+ text_col = next((c for c in cols if c.lower() in ("text", "sentence", "transcript", "transcription")), None)++ speaker_col = None+ if "source" in cols:+ speaker_col = "source"+ elif "speaker_id" in cols:+ speaker_col = "speaker_id"++ return {"audio_col": audio_col, "text_col": text_col, "speaker_col": speaker_col}++def load_model(self,model_name: str,max_seq_length: int = 2048,load_in_4bit: bool = True,hf_token: Optional[str] = None,- is_dataset_multimodal: bool = False) -> bool:+ is_dataset_image: bool = False,+ is_dataset_audio: bool = False) -> bool:"""Load model for training (supports both text and vision models)"""+ self.load_in_4bit = load_in_4bit # Store for training_meta.jsontry:if self.model is not None:del self.model@@@ -2330,9 -751,15 +2335,16 @@@"output_dir": output_dir,"report_to": ["wandb"] if training_args.get('enable_wandb', False) else "none","include_num_input_tokens_seen": True, # Enable token counting- "dataset_num_proc": safe_num_proc(max(1, os.cpu_count() // 4)),+ "dataset_num_proc": 1 if (self.is_audio or self.is_audio_vlm or self._cuda_audio_used) else safe_num_proc(max(1, os.cpu_count() // 4)),+ "max_seq_length": training_args.get('max_seq_length', 2048),}++ # On Windows with transformers 5.x, disable DataLoader multiprocessing+ # to avoid issues with modified sys.path (.venv_t5) in spawned workers.+ if sys.platform == "win32":+ import transformers as _tf+ if _tf.__version__.startswith("5."):+ config_args["dataloader_num_workers"] = 0# Add warmup parameter - use warmup_ratio if provided, otherwise warmup_stepsif warmup_ratio_val is not None:diff --cc studio/backend/core/training/worker.pyindex 00000000000,e4b833cb9af..4c823479369mode 000000,100644..100644--- a/studio/backend/core/training/worker.py+++ b/studio/backend/core/training/worker.py@@@ -1,0 -1,358 +1,359 @@@+ """+ Training subprocess entry point.++ Each training job runs in a fresh subprocess (mp.get_context("spawn")).+ This gives us a clean Python interpreter with no stale module state —+ solving the transformers version-switching problem completely.++ Pattern follows core/data_recipe/jobs/worker.py.+ """+ from __future__ import annotations++ import logging+ import os+ import sys+ import time+ import traceback+ from pathlib import Path+ from typing import Any++ logger = logging.getLogger(__name__)+++ def _activate_transformers_version(model_name: str, project_root: str) -> None:+ """Activate the correct transformers version BEFORE any ML imports.++ If the model needs transformers 5.x, prepend the pre-installed .venv_t5/+ directory to sys.path. Otherwise do nothing (default 4.57.x in .venv/).+ """+ # Ensure backend is on path for utils imports+ backend_path = os.path.join(project_root, "studio", "backend")+ if backend_path not in sys.path:+ sys.path.insert(0, backend_path)++ from utils.transformers_version import needs_transformers_5, _resolve_base_model++ resolved = _resolve_base_model(model_name)+ if needs_transformers_5(resolved):+ venv_t5 = os.path.join(project_root, ".venv_t5")+ if os.path.isdir(venv_t5):+ sys.path.insert(0, venv_t5)+ logger.info("Activated transformers 5.x from %s", venv_t5)+ else:+ # Fallback: pip install at runtime (slower, ~10-15s)+ logger.warning(".venv_t5 not found at %s — installing at runtime", venv_t5)+ import subprocess as sp+ os.makedirs(venv_t5, exist_ok=True)+ r1 = sp.run(+ [sys.executable, "-m", "pip", "install", "--target", venv_t5,+ "--no-deps", "transformers==5.2.0"],+ stdout=sp.PIPE, stderr=sp.STDOUT,+ )+ r2 = sp.run(+ [sys.executable, "-m", "pip", "install", "--target", venv_t5,+ "--no-deps", "huggingface_hub==1.3.0"],+ stdout=sp.PIPE, stderr=sp.STDOUT,+ )+ if r1.returncode != 0 or r2.returncode != 0:+ raise RuntimeError(+ f"Failed to install transformers 5.x into {venv_t5}. "+ f"pip returncode: transformers={r1.returncode}, huggingface_hub={r2.returncode}"+ )+ sys.path.insert(0, venv_t5)+ # Propagate to child subprocesses (e.g. GGUF converter)+ _pp = os.environ.get("PYTHONPATH", "")+ os.environ["PYTHONPATH"] = venv_t5 + (os.pathsep + _pp if _pp else "")+ else:+ logger.info("Using default transformers (4.57.x) for %s", model_name)+++ def run_training_process(+ *,+ event_queue: Any,+ stop_queue: Any,+ config: dict,+ ) -> None:+ """Subprocess entrypoint. Fresh Python — no stale module state.++ Args:+ event_queue: mp.Queue for sending progress/status/error events to parent.+ stop_queue: mp.Queue for receiving stop commands from parent.+ config: Training configuration dict with all parameters.+ """+ os.environ["TOKENIZERS_PARALLELISM"] = "false"++ project_root = config["project_root"]+ model_name = config["model_name"]++ # ── 1. Activate correct transformers version BEFORE any ML imports ──+ try:+ _activate_transformers_version(model_name, project_root)+ except Exception as exc:+ event_queue.put({+ "type": "error",+ "error": f"Failed to activate transformers version: {exc}",+ "stack": traceback.format_exc(limit=20),+ "ts": time.time(),+ })+ return++ # ── 1b. On Windows, check Triton availability (must be before import torch) ──+ if sys.platform == "win32":+ try:+ import triton # noqa: F401+ logger.info("Triton available — torch.compile enabled")+ except ImportError:+ os.environ["TORCHDYNAMO_DISABLE"] = "1"+ logger.warning(+ "Triton not found on Windows — torch.compile disabled. "+ 'Install for better performance: pip install "triton-windows<3.7"'+ )++ # ── 2. Now import ML libraries (fresh in this clean process) ──+ try:+ _send_status(event_queue, "Importing ML libraries...")++ backend_path = os.path.join(project_root, "studio", "backend")+ if backend_path not in sys.path:+ sys.path.insert(0, backend_path)++ from core.training.trainer import UnslothTrainer, TrainingProgress++ import transformers+ logger.info("Subprocess loaded transformers %s", transformers.__version__)+ except Exception as exc:+ event_queue.put({+ "type": "error",+ "error": f"Failed to import ML libraries: {exc}",+ "stack": traceback.format_exc(limit=20),+ "ts": time.time(),+ })+ return++ # ── 3. Create a fresh trainer instance ──+ trainer = UnslothTrainer()++ # Wire up progress callback → event_queue+ def _on_progress(progress: TrainingProgress):+ if progress.step >= 0 and progress.loss > 0:+ event_queue.put({+ "type": "progress",+ "step": progress.step,+ "epoch": progress.epoch,+ "loss": progress.loss,+ "learning_rate": progress.learning_rate,+ "total_steps": progress.total_steps,+ "elapsed_seconds": progress.elapsed_seconds,+ "eta_seconds": progress.eta_seconds,+ "grad_norm": progress.grad_norm,+ "num_tokens": progress.num_tokens,+ "eval_loss": progress.eval_loss,+ "status_message": progress.status_message,+ "ts": time.time(),+ })+ if progress.status_message:+ _send_status(event_queue, progress.status_message)++ trainer.add_progress_callback(_on_progress)++ # Wire up stop_queue polling to trainer.should_stop+ import threading+ import queue as _queue++ def _poll_stop():+ while True:+ try:+ msg = stop_queue.get(timeout=1.0)+ if msg and msg.get("type") == "stop":+ save = msg.get("save", True)+ trainer.should_stop = True+ trainer.save_on_stop = save+ logger.info("Stop signal received (save=%s)", save)+ return+ except _queue.Empty:+ continue+ except (EOFError, OSError):+ return++ stop_thread = threading.Thread(target=_poll_stop, daemon=True)+ stop_thread.start()++ # ── 4. Execute the training pipeline ──+ try:+ hf_token = config.get("hf_token", "")+ hf_token = hf_token if hf_token and hf_token.strip() else None++ # Load model+ _send_status(event_queue, "Loading model...")+ success = trainer.load_model(+ model_name=model_name,+ max_seq_length=config["max_seq_length"],+ load_in_4bit=config["load_in_4bit"],+ hf_token=hf_token,- is_dataset_multimodal=config.get("is_dataset_multimodal", False),++ is_dataset_image=config.get("is_dataset_image", False),++ is_dataset_audio=config.get("is_dataset_audio", False),+ )+ if not success or trainer.should_stop:+ if trainer.should_stop:+ event_queue.put({"type": "complete", "output_dir": None, "ts": time.time()})+ else:+ event_queue.put({+ "type": "error",+ "error": trainer.training_progress.error or "Failed to load model",+ "stack": "", "ts": time.time(),+ })+ return++ # Prepare model (LoRA or full finetuning)+ training_type = config.get("training_type", "LoRA/QLoRA")+ use_lora = (training_type == "LoRA/QLoRA")+ if use_lora:+ _send_status(event_queue, "Configuring LoRA adapters...")+ success = trainer.prepare_model_for_training(+ use_lora=True,+ finetune_vision_layers=config.get("finetune_vision_layers", True),+ finetune_language_layers=config.get("finetune_language_layers", True),+ finetune_attention_modules=config.get("finetune_attention_modules", True),+ finetune_mlp_modules=config.get("finetune_mlp_modules", True),+ target_modules=config.get("target_modules"),+ lora_r=config.get("lora_r", 16),+ lora_alpha=config.get("lora_alpha", 16),+ lora_dropout=config.get("lora_dropout", 0.0),+ use_gradient_checkpointing=config.get("gradient_checkpointing", "unsloth"),+ use_rslora=config.get("use_rslora", False),+ use_loftq=config.get("use_loftq", False),+ )+ else:+ _send_status(event_queue, "Preparing model for full finetuning...")+ success = trainer.prepare_model_for_training(use_lora=False)++ if not success or trainer.should_stop:+ if trainer.should_stop:+ event_queue.put({"type": "complete", "output_dir": None, "ts": time.time()})+ else:+ event_queue.put({+ "type": "error",+ "error": trainer.training_progress.error or "Failed to prepare model",+ "stack": "", "ts": time.time(),+ })+ return++ # Load dataset+ _send_status(event_queue, "Loading and formatting dataset...")+ hf_dataset = config.get("hf_dataset", "")+ dataset_result = trainer.load_and_format_dataset(+ dataset_source=hf_dataset if hf_dataset and hf_dataset.strip() else None,+ format_type=config.get("format_type", ""),+ local_datasets=config.get("local_datasets") or None,+ custom_format_mapping=config.get("custom_format_mapping"),+ subset=config.get("subset"),+ train_split=config.get("train_split", "train"),+ eval_split=config.get("eval_split"),+ eval_steps=config.get("eval_steps", 0.00),+ dataset_slice_start=config.get("dataset_slice_start"),+ dataset_slice_end=config.get("dataset_slice_end"),+ )++ if isinstance(dataset_result, tuple):+ dataset, eval_dataset = dataset_result+ else:+ dataset = dataset_result+ eval_dataset = None++ # Disable eval if eval_steps <= 0+ eval_steps = config.get("eval_steps", 0.00)+ if eval_steps is not None and float(eval_steps) <= 0:+ eval_dataset = None++ if dataset is None or trainer.should_stop:+ if trainer.should_stop:+ event_queue.put({"type": "complete", "output_dir": None, "ts": time.time()})+ else:+ event_queue.put({+ "type": "error",+ "error": trainer.training_progress.error or "Failed to load dataset",+ "stack": "", "ts": time.time(),+ })+ return++ # Convert learning rate+ try:+ lr_value = float(config.get("learning_rate", "2e-4"))+ except ValueError:+ event_queue.put({+ "type": "error",+ "error": f"Invalid learning rate: {config.get('learning_rate')}",+ "stack": "", "ts": time.time(),+ })+ return++ # Generate output dir+ output_dir = config.get("output_dir")+ if not output_dir:+ output_dir = f"./outputs/{model_name.replace('/', '_')}_{int(time.time())}"++ # Start training (directly — no inner thread, we ARE the subprocess)+ _send_status(event_queue, "Starting training...")+ max_steps = config.get("max_steps", 0)+ save_steps = config.get("save_steps", 0)++ trainer._train_worker(+ dataset,+ output_dir=output_dir,+ num_epochs=config.get("num_epochs", 3),+ learning_rate=lr_value,+ batch_size=config.get("batch_size", 2),+ gradient_accumulation_steps=config.get("gradient_accumulation_steps", 4),+ warmup_steps=config.get("warmup_steps"),+ warmup_ratio=config.get("warmup_ratio"),+ max_steps=max_steps if max_steps and max_steps > 0 else 0,+ save_steps=save_steps if save_steps and save_steps > 0 else 0,+ weight_decay=config.get("weight_decay", 0.01),+ random_seed=config.get("random_seed", 3407),+ packing=config.get("packing", False),+ train_on_completions=config.get("train_on_completions", False),+ enable_wandb=config.get("enable_wandb", False),+ wandb_project=config.get("wandb_project", "unsloth-training"),+ wandb_token=config.get("wandb_token"),+ enable_tensorboard=config.get("enable_tensorboard", False),+ tensorboard_dir=config.get("tensorboard_dir", "runs"),+ eval_dataset=eval_dataset,+ eval_steps=eval_steps,+ max_seq_length=config.get("max_seq_length", 2048),+ optim=config.get("optim", "adamw_8bit"),+ lr_scheduler_type=config.get("lr_scheduler_type", "linear"),+ )++ # Check final state+ progress = trainer.get_training_progress()+ if progress.error:+ event_queue.put({+ "type": "error",+ "error": progress.error,+ "stack": "",+ "ts": time.time(),+ })+ else:+ event_queue.put({+ "type": "complete",+ "output_dir": output_dir,+ "status_message": progress.status_message or "Training completed",+ "ts": time.time(),+ })++ except Exception as exc:+ event_queue.put({+ "type": "error",+ "error": str(exc),+ "stack": traceback.format_exc(limit=20),+ "ts": time.time(),+ })+++ def _send_status(event_queue: Any, message: str) -> None:+ """Send a status update to the parent process."""+ event_queue.put({+ "type": "status",+ "message": message,+ "ts": time.time(),+ })diff --cc studio/backend/utils/models/model_config.pyindex 222017ce00d,e7b92651be3..05817e8ccd0--- a/studio/backend/utils/models/model_config.py+++ b/studio/backend/utils/models/model_config.py@@@ -434,118 -543,8 +558,117 @@@ def is_vision_model(model_name: str, hfexcept Exception as e:logger.warning(f"Could not determine if {model_name} is vision model: {e}")return False- pass+VALID_AUDIO_TYPES = ('snac', 'csm', 'bicodec', 'dac', 'whisper', 'audio_vlm')++# Cache detection results per session to avoid repeated API calls+_audio_detection_cache: Dict[str, Optional[str]] = {}++# Tokenizer token patterns → audio_type (all 6 types detected from tokenizer_config.json)+_AUDIO_TOKEN_PATTERNS = {+ 'csm': lambda tokens: '<|AUDIO|>' in tokens and '<|audio_eos|>' in tokens,+ 'whisper': lambda tokens: '<|startoftranscript|>' in tokens,+ 'audio_vlm': lambda tokens: '<audio_soft_token>' in tokens,+ 'bicodec': lambda tokens: any(t.startswith('<|bicodec_') for t in tokens),+ 'dac': lambda tokens: '<|audio_start|>' in tokens and '<|audio_end|>' in tokens,+ 'snac': lambda tokens: sum(1 for t in tokens if t.startswith('<custom_token_')) > 10000,+}+++def detect_audio_type(model_name: str, hf_token: Optional[str] = None) -> Optional[str]:+ """+ Dynamically detect if a model is an audio model and return its type.++ Fully dynamic — works for any model, not just known ones.+ Uses tokenizer_config.json special tokens to detect all 6 audio types.++ Returns: audio_type string ('snac', 'csm', 'bicodec', 'dac', 'whisper', 'audio_vlm') or None.+ """+ if model_name in _audio_detection_cache:+ return _audio_detection_cache[model_name]++ result = _detect_audio_from_tokenizer(model_name, hf_token)++ _audio_detection_cache[model_name] = result+ if result:+ logger.info(f"Model {model_name} detected as audio model: audio_type={result}")+ return result+++def _detect_audio_from_tokenizer(model_name: str, hf_token: Optional[str] = None) -> Optional[str]:+ """Detect audio type from tokenizer special tokens (for LLM-based audio models).++ First checks local HF cache, then fetches tokenizer_config.json from HuggingFace.+ Checks added_tokens_decoder for distinctive patterns.+ """+ def _check_token_patterns(tok_config: dict) -> Optional[str]:+ added = tok_config.get('added_tokens_decoder', {})+ if not added:+ return None+ token_contents = [v.get('content', '') for v in added.values()]+ for audio_type, check_fn in _AUDIO_TOKEN_PATTERNS.items():+ if check_fn(token_contents):+ return audio_type+ return None++ # 1) Check local HF cache first (works for gated/offline models)+ try:+ from huggingface_hub.constants import HF_HUB_CACHE+ cache_dir = Path(HF_HUB_CACHE)+ repo_dir_name = f"models--{model_name.replace('/', '--')}"+ repo_dir = cache_dir / repo_dir_name+ if repo_dir.exists():+ snapshots_dir = repo_dir / "snapshots"+ if snapshots_dir.exists():+ for snapshot in snapshots_dir.iterdir():+ for tok_path in ['tokenizer_config.json', 'LLM/tokenizer_config.json']:+ tok_file = snapshot / tok_path+ if tok_file.exists():+ tok_config = json.loads(tok_file.read_text())+ result = _check_token_patterns(tok_config)+ if result:+ return result+ except Exception as e:+ logger.debug(f"Could not check local cache for {model_name}: {e}")++ # 2) Fall back to HuggingFace API+ try:+ import requests+ import os++ paths_to_try = ['tokenizer_config.json', 'LLM/tokenizer_config.json']+ # Use provided token, or fall back to env+ token = hf_token or os.environ.get('HF_TOKEN')+ headers = {}+ if token:+ headers['Authorization'] = f'Bearer {token}'++ for tok_path in paths_to_try:+ url = f"https://huggingface.co/{model_name}/resolve/main/{tok_path}"+ resp = requests.get(url, headers=headers, timeout=15)+ if not resp.ok:+ continue++ tok_config = resp.json()+ result = _check_token_patterns(tok_config)+ if result:+ return result++ return None+ except Exception as e:+ logger.debug(f"Could not detect audio type from tokenizer for {model_name}: {e}")+ return None+++def is_audio_input_type(audio_type: Optional[str]) -> bool:+ """Check if an audio_type accepts audio input (ASR/speech understanding).++ Whisper (ASR) and audio_vlm (Gemma3n) accept audio input.+ """+ return audio_type in ('whisper', 'audio_vlm')++def _is_mmproj(filename: str) -> bool:"""Check if a GGUF filename is a vision projection (mmproj) file."""return "mmproj" in filename.lower()