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
Stop capping unsloth chat at 512 on any backend and /v1/chat/completions at 2048 on transformers/MLX (#10665)
Nilaybf87e2917c1b
diff --git a/studio/backend/core/inference/inference.py b/studio/backend/core/inference/inference.pyindex fb0f8d7aab0..f9ea15e672b 100644--- a/studio/backend/core/inference/inference.py+++ b/studio/backend/core/inference/inference.py@@ -29,7 +29,10 @@ from utils.hardware import (get_visible_gpu_count,)from core.inference.audio_codecs import AudioCodecManager-from core.inference.runtime_context import runtime_context_length+from core.inference.runtime_context import (+ generation_budget_within_context,+ runtime_context_length,+)from core.inference.message_content import content_to_textfrom core.inference.chat_eos import (chat_eos_repair,@@ -900,7 +903,7 @@ class InferenceBackend:top_p: float = 0.9,top_k: int = 40,min_p: float = 0.0,- max_new_tokens: int = 2048,+ max_new_tokens: Optional[int] = 2048,repetition_penalty: float = 1.0,cancel_event = None,enable_thinking: Optional[bool] = None,@@ -1026,7 +1029,7 @@ class InferenceBackend:top_p: float = 0.9,top_k: int = 40,min_p: float = 0.0,- max_new_tokens: int = 256,+ max_new_tokens: Optional[int] = 256,repetition_penalty: float = 1.0,cancel_event = None,tools: Optional[list] = None,@@ -1073,7 +1076,7 @@ class InferenceBackend:top_p: float = 0.9,top_k: int = 40,min_p: float = 0.0,- max_new_tokens: int = 256,+ max_new_tokens: Optional[int] = 256,repetition_penalty: float = 1.0,cancel_event = None,_adapter_state = None,@@ -1501,6 +1504,12 @@ class InferenceBackend:preserve_tool_tokens = _preserve_tool_tokens,)+ _vision_input_ids = inputs.get("input_ids") if hasattr(inputs, "get") else None+ prompt_len = int(_vision_input_ids.shape[1]) if _vision_input_ids is not None else None+ max_new_tokens = generation_budget_within_context(+ model, prompt_len or 0, max_new_tokens+ )+generation_kwargs = dict(**inputs,streamer = streamer,@@ -1513,8 +1522,6 @@ class InferenceBackend:min_p = min_p,)# Presence penalty (GGUF parity) for VLM chat.- _vision_input_ids = inputs.get("input_ids") if hasattr(inputs, "get") else None- prompt_len = int(_vision_input_ids.shape[1]) if _vision_input_ids is not None else None_pp = (_make_presence_penalty_processor(presence_penalty, prompt_len)if _vision_input_ids is not None@@ -1716,6 +1723,12 @@ class InferenceBackend:timeout = 0.2,)+ _audio_input_ids = inputs.get("input_ids") if hasattr(inputs, "get") else None+ prompt_len = int(_audio_input_ids.shape[1]) if _audio_input_ids is not None else None+ max_new_tokens = generation_budget_within_context(+ model, prompt_len or 0, max_new_tokens+ )+# Notebook uses do_sample=False (greedy) for ASR accuracygeneration_kwargs = dict(**inputs,@@ -1725,8 +1738,6 @@ class InferenceBackend:do_sample = False,)- _audio_input_ids = inputs.get("input_ids") if hasattr(inputs, "get") else None- prompt_len = int(_audio_input_ids.shape[1]) if _audio_input_ids is not None else Nonetimer = GenerationTimer()generation_kwargs["logits_processor"] = with_prefill_boundary_processor(None, timer)active_stop_token_ids = self._generation_stop_token_ids(model, generation_kwargs)@@ -1936,7 +1947,7 @@ class InferenceBackend:top_p: float = 0.9,top_k: int = 40,min_p: float = 0.0,- max_new_tokens: int = 256,+ max_new_tokens: Optional[int] = 256,repetition_penalty: float = 1.0,cancel_event = None,_adapter_state = None,@@ -2009,6 +2020,9 @@ class InferenceBackend:preserve_tool_tokens = preserve_tool_tokens,)+ prompt_len = int(inputs["input_ids"].shape[1])+ max_new_tokens = generation_budget_within_context(model, prompt_len, max_new_tokens)+generation_kwargs = dict(**inputs,streamer = streamer,@@ -2026,7 +2040,6 @@ class InferenceBackend:else tokenizer.pad_token_id,)active_stop_token_ids = self._generation_stop_token_ids(model, generation_kwargs)- prompt_len = int(inputs["input_ids"].shape[1])# Presence penalty (GGUF parity); prompt_len excludes prompt tokens._pp = _make_presence_penalty_processor(presence_penalty, prompt_len)timer = GenerationTimer()diff --git a/studio/backend/core/inference/mlx_inference.py b/studio/backend/core/inference/mlx_inference.pyindex 71b029a35e5..ce869160287 100644--- a/studio/backend/core/inference/mlx_inference.py+++ b/studio/backend/core/inference/mlx_inference.py@@ -21,6 +21,8 @@ from core.inference.native_tool_tokens import ()from core.inference.runtime_context import (MAX_REQUESTABLE_CONTEXT,+ UNSET_GENERATION_BUDGET,+ generation_budget_for_window,runtime_context_length,)from core.inference.chat_template_helpers import (@@ -1937,6 +1939,7 @@ class MLXInferenceBackend:# Bound now so a load that fails before installing leaves readers a dict rather than raising.self._kv_quant = _kv_quant_status(None, None, False)self._kv_cache_window = None+ self._served_context = Noneself._template_override = _template_override_status(None, None, None)[1]self._prompt_cache_history = None@@ -2110,6 +2113,23 @@ class MLXInferenceBackend:return prompt, None, None, None, 0return rest, cache, key, tokens, len(tokens) - len(rest)+ def _unset_generation_budget(+ self,+ prompt,+ prompt_tokens = None,+ ):+ """Free context for an unset limit, or the default if the prompt cannot be counted."""+ try:+ prompt_n = (+ len(prompt_tokens)+ if prompt_tokens is not None+ else self._count_prompt_tokens(prompt)+ )+ except Exception as exc:+ logger.debug("MLX prompt count for an unset budget failed: %s", exc)+ return UNSET_GENERATION_BUDGET+ return generation_budget_for_window(self._served_context, prompt_n, None)+def _kv_quant_generate_kwargs(self):"""Load-time runtime knobs for a generate call, empty when unset. quantized_kv_start isdeliberately not passed: mlx-lm and mlx-vlm ship different defaults (0 and 5000) and each@@ -2135,6 +2155,14 @@ class MLXInferenceBackend:))+ def _count_prompt_tokens(self, prompt):+ """Prompt length as generation tokenizes it; vision models follow mlx_vlm's marker rule."""+ if not self._is_vlm:+ return len(self._encode_prompt(prompt))+ model_type = getattr(getattr(self._model, "config", None), "model_type", None)+ add_special = _vlm_add_special_tokens(model_type, self._processor)+ return len(self._tokenizer.encode(prompt, add_special_tokens = add_special))+def _configure_memory_limits(self):"""Apply Metal memory caps before loading a model. memory_limit = 85% of recommendedworking-set; wired_limit = min(recommended, memory_limit). Recorded so unload can lower@@ -2353,6 +2381,7 @@ class MLXInferenceBackend:_served_ctx, _native_ctx, _max_ctx = self._resolve_context_lengths(self._model, max_seq_length)+ self._served_context = _served_ctx# Classify before the first generation: an ineligible cache would otherwise raise inside# maybe_quantize_kv_cache mid-stream, after converting the leading entries.self._kv_quant, self._kv_cache_window, _ctx_enforced = self._resolve_kv_policy(@@ -2646,12 +2675,7 @@ class MLXInferenceBackend:reasoning_effort = reasoning_effort,preserve_thinking = preserve_thinking,)- # Whether the markers belong to the template or to tokenization is a per-model answer mlx_vlm makes for- # every generation; ask it rather than guess, or the count is off by whatever the generation's own choice- # would have added.- _model_type = getattr(getattr(self._model, "config", None), "model_type", None)- add_special = _vlm_add_special_tokens(_model_type, self._processor)- return len(self._tokenizer.encode(prompt, add_special_tokens = add_special))+ return self._count_prompt_tokens(prompt)render_result = self._render_text_prompt(full_messages,@@ -2660,7 +2684,7 @@ class MLXInferenceBackend:reasoning_effort = reasoning_effort,preserve_thinking = preserve_thinking,)- return len(self._encode_prompt(render_result.prompt))+ return self._count_prompt_tokens(render_result.prompt)def generate_chat_response(self,@@ -2891,6 +2915,8 @@ class MLXInferenceBackend:prompt_tokens,cached_n,) = self._prepare_prompt_cache(prompt, _adapter_state)+ if max_new_tokens is None:+ max_new_tokens = self._unset_generation_budget(prompt, prompt_tokens)logger.info("Generating: prompt_len=%d, cached=%d, max_tokens=%d, model=%s, tokenizer=%s",len(prompt),@@ -3207,6 +3233,12 @@ class MLXInferenceBackend:# Matched on the sampled text, for the reason _generate_text gives.sequences = _mlx_stop_sequences(stop)stopped = False+ if max_new_tokens is None:+ max_new_tokens = self._unset_generation_budget(prompt)+ if image is not None:+ # An image expands past its one placeholder token, so the counted prompt is short+ # of the real one: cap at the default, but stay under the rotating cache window.+ max_new_tokens = min(max_new_tokens, UNSET_GENERATION_BUDGET)logger.info("VLM generating: prompt_len=%d, has_image=%s",len(prompt),@@ -3444,6 +3476,11 @@ class MLXInferenceBackend:"cannot build an audio prompt.")+ if max_new_tokens is None:+ # Audio expands past its placeholder token exactly as an image does, so the counted+ # prompt is short of the real one: cap at the default, but stay under the window.+ max_new_tokens = min(self._unset_generation_budget(prompt), UNSET_GENERATION_BUDGET)+logger.info("MLX audio-input generating: prompt_len=%d", len(prompt))markers = detect_reasoning_channel_markers(self._processor)normalizer = make_reasoning_normalizer(markers) if markers is not None else Nonediff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.pyindex af1565fd66a..17e3ae930bb 100644--- a/studio/backend/core/inference/orchestrator.py+++ b/studio/backend/core/inference/orchestrator.py@@ -2116,7 +2116,8 @@ class InferenceOrchestrator:from core.inference.safetensors_agentic import run_safetensors_tool_loopfrom core.inference.tools import execute_tool- max_new_tokens = max_tokens if max_tokens and max_tokens > 0 else 2048+ # None lets the backend size an unset limit once it has counted the prompt.+ max_new_tokens = max_tokens if max_tokens and max_tokens > 0 else None# The worker's usage for the LATEST turn only. Hoisted out of the turn so the loop can size a conversation# search against a real prompt count, and cleared on the way in rather than on each way out, so a turn thatdiff --git a/studio/backend/core/inference/runtime_context.py b/studio/backend/core/inference/runtime_context.pyindex 3acca130e2e..2e10967b9e1 100644--- a/studio/backend/core/inference/runtime_context.py+++ b/studio/backend/core/inference/runtime_context.py@@ -14,6 +14,9 @@ from typing import Any, Optional#: window from the model reports it as native but does not serve past it.MAX_REQUESTABLE_CONTEXT = 1048576+#: Budget for an unset limit when there is no free context to size it from.+UNSET_GENERATION_BUDGET = 2048+def _field(source: Any, name: str) -> Any:"""Key or attribute, since mlx.nn.Module is a dict; a raiser is absent, never a failed load."""@@ -71,3 +74,30 @@ def runtime_context_length(model: Any, fallback: Optional[int] = None) -> Optionif value_int > 0:return value_intreturn None+++def generation_budget_for_window(+ window: Optional[int], prompt_length: int, max_new_tokens: Optional[int]+) -> Optional[int]:+ """Resolve a generation budget, where ``None`` means the caller set no limit.++ An unset limit becomes the context the prompt leaves free. An explicit one is returned+ untouched, so asking for more than fits still gets the backend's overflow error.+ """+ if max_new_tokens is not None:+ return max_new_tokens+ if not window:+ return UNSET_GENERATION_BUDGET+ free = int(window) - int(prompt_length)+ # No room left: take the default and let the backend's overflow check decide. A floor+ # of 1 would pass that check on a model loaded narrower than its checkpoint.+ return free if free > 0 else UNSET_GENERATION_BUDGET+++def generation_budget_within_context(+ model: Any, prompt_length: int, max_new_tokens: Optional[int]+) -> Optional[int]:+ """``generation_budget_for_window`` against the window a loaded model declares."""+ return generation_budget_for_window(+ runtime_context_length(model), prompt_length, max_new_tokens+ )diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 971fe716d6c..458c16d0005 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -22142,7 +22142,7 @@ async def produce_openai_chat_completions(top_p = payload.top_p,top_k = payload.top_k,min_p = payload.min_p,- max_new_tokens = _effective_max_tokens(payload) or 2048,+ max_new_tokens = _effective_max_tokens(payload),repetition_penalty = payload.repetition_penalty,# Compare sends audio_base64 and use_adapter in one body.use_adapter = payload.use_adapter,@@ -24979,7 +24979,7 @@ async def produce_openai_chat_completions(top_p = payload.top_p,top_k = payload.top_k,min_p = payload.min_p,- max_new_tokens = effective_max_tokens or 2048,+ max_new_tokens = effective_max_tokens,repetition_penalty = payload.repetition_penalty,presence_penalty = payload.presence_penalty,seed = payload.seed,diff --git a/studio/backend/tests/test_conversation_search_safetensors_loop.py b/studio/backend/tests/test_conversation_search_safetensors_loop.pyindex 3f8d7e7a641..b54975589fc 100644--- a/studio/backend/tests/test_conversation_search_safetensors_loop.py+++ b/studio/backend/tests/test_conversation_search_safetensors_loop.py@@ -326,6 +326,38 @@ def test_the_orchestrator_gives_the_loop_a_holder_of_its_own(monkeypatch):assert seen["generation_stats_holder"] == {}+def _tool_loop_max_tokens(monkeypatch, max_tokens):+ import core.inference.safetensors_agentic as agentic+ from core.inference.orchestrator import InferenceOrchestrator++ seen = {}++ def capture_loop(**kwargs):+ seen.update(kwargs)+ return iter(())++ monkeypatch.setattr(agentic, "run_safetensors_tool_loop", capture_loop)+ backend = InferenceOrchestrator.__new__(InferenceOrchestrator)+ backend.active_model_name = "sf-model"+ backend.models = {"sf-model": {"context_length": 4096}}++ list(+ backend.generate_chat_completion_with_tools(+ messages = list(MESSAGES),+ tools = [],+ max_tokens = max_tokens,+ )+ )+ return seen["max_tokens"]+++def test_an_absent_client_limit_stays_absent_through_the_loop(monkeypatch):+ """Zero counts as absent too; only a positive limit is forwarded."""+ assert _tool_loop_max_tokens(monkeypatch, None) is None+ assert _tool_loop_max_tokens(monkeypatch, 0) is None+ assert _tool_loop_max_tokens(monkeypatch, 512) == 512++def test_the_loop_omits_the_budget_when_the_context_is_unknown():"""An absent budget must not become a budget of zero, which would refuse every search."""seen = {}diff --git a/studio/backend/tests/test_generation_budget.py b/studio/backend/tests/test_generation_budget.pynew file mode 100644index 00000000000..5d33104733d--- /dev/null+++ b/studio/backend/tests/test_generation_budget.py@@ -0,0 +1,321 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""An unset generation limit (``None``) resolves to the context the prompt leaves free.++unsloth_fast_generate raises once ``input_length + max_new_tokens`` passes the window, so no+flat default fits every prompt. An explicit limit is never reduced.+"""++import sys+import threading+from pathlib import Path+from types import SimpleNamespace++import pytest++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++from core.inference.runtime_context import (+ UNSET_GENERATION_BUDGET,+ generation_budget_within_context,+)++_WINDOW = 2048+_PROMPT_LEN = 37+++def _model(window = _WINDOW):+ return SimpleNamespace(config = SimpleNamespace(max_position_embeddings = window))+++def test_an_unset_budget_becomes_the_free_context():+ assert generation_budget_within_context(_model(), _PROMPT_LEN, None) == _WINDOW - _PROMPT_LEN+++def test_an_explicit_budget_is_never_reduced():+ # A request that does not fit must raise, not come back shortened.+ assert generation_budget_within_context(_model(), _PROMPT_LEN, 512) == 512+ assert generation_budget_within_context(_model(), _PROMPT_LEN, _WINDOW) == _WINDOW+ wide = SimpleNamespace(+ max_seq_length = 1024, config = SimpleNamespace(max_position_embeddings = 32768)+ )+ assert generation_budget_within_context(wide, _PROMPT_LEN, 4096) == 4096+++def test_a_prompt_with_no_room_left_gets_the_default_not_a_token():+ # A floor of 1 clears a native 32768 guard on a 1024 load and returns one token.+ assert generation_budget_within_context(_model(window = 32), 64, None) == UNSET_GENERATION_BUDGET+ narrow = SimpleNamespace(+ max_seq_length = 1024, config = SimpleNamespace(max_position_embeddings = 32768)+ )+ assert generation_budget_within_context(narrow, 1100, None) == UNSET_GENERATION_BUDGET+ assert generation_budget_within_context(_model(window = 32), 31, None) == 1+++def test_the_selected_window_wins_over_a_wider_checkpoint():+ # from_pretrained keeps config.max_position_embeddings at max(requested, native), so the+ # config alone would serve a --max-seq-length 1024 load the whole 32768.+ model = SimpleNamespace(+ max_seq_length = 1024,+ config = SimpleNamespace(max_position_embeddings = 32768),+ )+ assert generation_budget_within_context(model, _PROMPT_LEN, None) == 1024 - _PROMPT_LEN+++def test_a_model_declaring_no_window_falls_back():+ assert (+ generation_budget_within_context(SimpleNamespace(), _PROMPT_LEN, None)+ == UNSET_GENERATION_BUDGET+ )+ for unusable in (None, "n/a", True):+ assert (+ generation_budget_within_context(_model(window = unusable), 1, None)+ == UNSET_GENERATION_BUDGET+ )+ assert generation_budget_within_context(SimpleNamespace(), _PROMPT_LEN, 256) == 256+++def test_a_zero_budget_is_a_value_not_an_absence():+ assert generation_budget_within_context(_model(), _PROMPT_LEN, 0) == 0+++# The call-site tests below import the backend, which pulls unsloth/unsloth_zoo: absent on CPU CI.+++class _FakeTensor:+ def __init__(self, length):+ self.shape = (1, length)++ def to(self, _device):+ return self++ def __getitem__(self, _idx):+ return 2+++class _FakeEncoding(dict):+ def to(self, _device):+ return self+++class _FakeTokenizer:+ eos_token_id = 2+ pad_token_id = 2+ all_special_tokens: list = []++ def __call__(+ self,+ _prompt,+ return_tensors = None,+ add_special_tokens = True,+ ):+ return _FakeEncoding(input_ids = _FakeTensor(_PROMPT_LEN))+++class _FakeModel:+ """Carries the one guard unsloth_fast_generate applies before generating."""++ def __init__(self, window):+ self.max_seq_length = window+ self.config = SimpleNamespace(max_position_embeddings = window)+ self.device = "cpu"+ self.calls = []++ def generate(self, **kwargs):+ ids, budget = kwargs.get("input_ids"), kwargs.get("max_new_tokens")+ if ids is not None and budget is not None:+ if ids.shape[-1] + budget > self.config.max_position_embeddings:+ raise ValueError(+ f"Unsloth: input length {ids.shape[-1]} + max_new_tokens {budget} "+ "exceeds the maximum sequence length of "+ f"{self.config.max_position_embeddings}!"+ )+ self.calls.append(kwargs)+ return _FakeTensor(ids.shape[-1] + 1)+++class _EmptyStreamer:+ def __iter__(self):+ return self++ def __next__(self):+ raise StopIteration++ def end(self):+ pass+++def _streaming_backend(monkeypatch, window = _WINDOW):+ try:+ from core.inference.inference import InferenceBackend+ except (ImportError, RuntimeError) as exc: # pragma: no cover - env-dependent+ # Skips because the CPU job installs no unsloth; the helper tests above cover+ # the same bound, so the budget itself is never left unasserted.+ pytest.skip(f"full inference backend unavailable ({type(exc).__name__}: {exc})")++ backend = InferenceBackend.__new__(InferenceBackend)+ backend.active_model_name = "unsloth/tinyllama-chat-bnb-4bit"+ backend.last_generation_stats = None+ backend._generation_lock = threading.Lock()+ model = _FakeModel(window)+ backend.models = {+ backend.active_model_name: {+ "model": model,+ "tokenizer": _FakeTokenizer(),+ "is_vision": False,+ "chat_turn_end_eos_ids": [2],+ }+ }+ monkeypatch.setattr(+ backend, "_make_text_streamer", lambda *a, **k: _EmptyStreamer(), raising = False+ )+ return backend, model+++def _run(backend, max_new_tokens):+ return list(+ backend.generate_stream(+ "PROMPT",+ temperature = 0.0,+ max_new_tokens = max_new_tokens,+ repetition_penalty = 1.0,+ )+ )+++def test_generate_stream_resolves_an_unset_budget(monkeypatch):+ backend, model = _streaming_backend(monkeypatch)++ _run(backend, None)++ assert model.calls, "generate was never reached"+ assert model.calls[0]["max_new_tokens"] == _WINDOW - _PROMPT_LEN+++def test_generate_stream_passes_a_fitting_budget_through(monkeypatch):+ backend, model = _streaming_backend(monkeypatch)++ _run(backend, 512)++ assert model.calls[0]["max_new_tokens"] == 512+++def _vision_backend(monkeypatch, window = _WINDOW):+ try:+ from core.inference.inference import InferenceBackend+ except (ImportError, RuntimeError) as exc: # pragma: no cover - env-dependent+ pytest.skip(f"full inference backend unavailable ({type(exc).__name__}: {exc})")++ backend = InferenceBackend.__new__(InferenceBackend)+ backend.active_model_name = "vision-model"+ backend.last_generation_stats = None+ backend._generation_lock = threading.Lock()+ model = _FakeModel(window)+ tokenizer = _FakeTokenizer()+ backend.models = {+ backend.active_model_name: {+ "model": model,+ "tokenizer": tokenizer,+ "processor": tokenizer,+ "is_vision": True,+ "chat_turn_end_eos_ids": [2],+ }+ }+ monkeypatch.setattr(+ backend, "_make_text_streamer", lambda *a, **k: _EmptyStreamer(), raising = False+ )+ monkeypatch.setattr(backend, "format_chat_prompt", lambda *a, **k: "PROMPT", raising = False)+ return backend, model+++def test_the_vision_path_resolves_an_unset_budget(monkeypatch):+ """Without this, a VLM turn reaches generate() with max_new_tokens=None, which+ transformers reads as its own tiny max_length default rather than no limit."""+ backend, model = _vision_backend(monkeypatch)++ list(+ backend._generate_vision_response(+ [{"role": "user", "content": "hi"}],+ "",+ None,+ 0.0,+ 1.0,+ 0,+ 0.0,+ None,+ 1.0,+ )+ )++ assert model.calls, "generate was never reached"+ assert model.calls[0]["max_new_tokens"] == _WINDOW - _PROMPT_LEN+++def _audio_backend(monkeypatch, window = _WINDOW):+ try:+ from core.inference.inference import InferenceBackend+ except (ImportError, RuntimeError) as exc: # pragma: no cover - env-dependent+ pytest.skip(f"full inference backend unavailable ({type(exc).__name__}: {exc})")++ backend = InferenceBackend.__new__(InferenceBackend)+ backend.active_model_name = "audio-model"+ backend.last_generation_stats = None+ backend._generation_lock = threading.Lock()+ model = _FakeModel(window)++ class _AudioProcessor(_FakeTokenizer):+ def apply_chat_template(self, *_a, **_k):+ return _FakeEncoding(input_ids = _FakeTensor(_PROMPT_LEN))++ processor = _AudioProcessor()+ backend.models = {+ backend.active_model_name: {+ "model": model,+ "tokenizer": processor,+ "processor": processor,+ "audio_type": "audio_vlm",+ "chat_turn_end_eos_ids": [2],+ }+ }+ monkeypatch.setattr(+ backend, "_make_text_streamer", lambda *a, **k: _EmptyStreamer(), raising = False+ )+ return backend, model+++def _run_audio(backend, max_new_tokens):+ list(+ backend.generate_audio_input_response(+ [{"role": "user", "content": "hi"}],+ "",+ object(),+ 0.0,+ 1.0,+ 0,+ 0.0,+ max_new_tokens,+ 1.0,+ )+ )+++def test_the_audio_input_path_resolves_an_unset_budget(monkeypatch):+ """The OpenAI route sends no cap when the client sent none, on the audio branch as on+ the text one. Reaching generate() with None would take transformers' own tiny default."""+ backend, model = _audio_backend(monkeypatch)++ _run_audio(backend, None)++ assert model.calls, "generate was never reached"+ assert model.calls[0]["max_new_tokens"] == _WINDOW - _PROMPT_LEN+++def test_an_explicit_audio_budget_is_untouched(monkeypatch):+ backend, model = _audio_backend(monkeypatch)++ _run_audio(backend, 128)++ assert model.calls[0]["max_new_tokens"] == 128diff --git a/studio/backend/tests/test_mlx_inference_backend.py b/studio/backend/tests/test_mlx_inference_backend.pyindex 1816cb9cd73..dbc65c883b9 100644--- a/studio/backend/tests/test_mlx_inference_backend.py+++ b/studio/backend/tests/test_mlx_inference_backend.py@@ -4898,3 +4898,159 @@ def test_mlx_keeps_a_think_closer_whose_opener_came_from_the_prefill(monkeypatchfinal = snapshots[-1]assert final.startswith("<think>"), finalassert "</think>" in final, f"the closer was trimmed, leaving the block open: {final!r}"+++# ── Unset generation budget ──────────────────────────────────────────────++_BUDGET_WINDOW = 2048+_BUDGET_PROMPT_N = 37+_BUDGET_BOS = "<s>"+_IMAGE_TURN = [{"role": "user", "content": [{"type": "image"}]}]+_TEXT_TURN = [{"role": "user", "content": "hi"}]+++def _budget_backend(+ monkeypatch,+ served = _BUDGET_WINDOW,+ marker_tokens = 0,+):+ from core.inference import mlx_inference++ @contextmanager+ def _adapter_state(_model, _state):+ yield++ monkeypatch.setattr(mlx_inference, "_temporary_mlx_adapter_state", _adapter_state)+ backend = mlx_inference.MLXInferenceBackend()+ backend._model = SimpleNamespace(config = {"model_type": "llama"})+ backend._tokenizer = SimpleNamespace(+ all_special_tokens = [],+ # The text and vision marker rules only disagree once the template emits the BOS.+ bos_token = _BUDGET_BOS if marker_tokens else None,+ encode = lambda _p, add_special_tokens = True: list(+ range(_BUDGET_PROMPT_N + (marker_tokens if add_special_tokens else 0))+ ),+ decode = lambda _ids, **_k: "ok",+ )+ backend._served_context = served+ return backend+++def _run_text_budget(+ monkeypatch,+ max_new_tokens,+ served = _BUDGET_WINDOW,+ cached = None,+):+ from core.inference import mlx_inference++ seen = {}+ mlx_lm = types.ModuleType("mlx_lm")+ sample_utils = types.ModuleType("mlx_lm.sample_utils")+ sample_utils.make_sampler = lambda **_k: object()+ mlx_lm.sample_utils = sample_utils++ def _stream(_model, _tokenizer, **kwargs):+ seen["max_tokens"] = kwargs.get("max_tokens")+ yield _Resp("ok", 1)++ mlx_lm.stream_generate = _stream+ monkeypatch.setitem(sys.modules, "mlx_lm", mlx_lm)+ monkeypatch.setitem(sys.modules, "mlx_lm.sample_utils", sample_utils)+ monkeypatch.setattr(mlx_inference, "_mlx_sampling_processors", lambda **_k: None)++ backend = _budget_backend(monkeypatch, served = served)+ monkeypatch.setattr(+ backend,+ "_render_text_prompt",+ lambda *_a, **_k: SimpleNamespace(prompt = "P", reasoning_channel_markers = None),+ raising = False,+ )+ if cached is not None:+ # A cache hit: the full token list beside the uncached remainder.+ monkeypatch.setattr(+ backend,+ "_prepare_prompt_cache",+ lambda _p, _a: ("TAIL", object(), "k", cached, len(cached) - 4),+ )+ list(backend._generate_text(_TEXT_TURN, 0.0, 1.0, 0, 0.0, max_new_tokens, 1.0, None))+ return seen["max_tokens"]+++def _run_vlm_budget(+ monkeypatch,+ messages,+ image,+ max_new_tokens,+ served = _BUDGET_WINDOW,+ marker_tokens = 0,+):+ seen = {}+ mlx_vlm = types.ModuleType("mlx_vlm")++ def _stream(*_a, **kwargs):+ seen["max_tokens"] = kwargs.get("max_tokens")+ yield SimpleNamespace(text = "ok", prompt_tokens = 3, generation_tokens = 1)++ mlx_vlm.stream_generate = _stream+ monkeypatch.setitem(sys.modules, "mlx_vlm", mlx_vlm)+ monkeypatch.setattr(+ "core.inference.chat_template_helpers.apply_chat_template_for_generation",+ lambda _t, _m, **_k: f"{_BUDGET_BOS}<image> p",+ )++ backend = _budget_backend(monkeypatch, served = served, marker_tokens = marker_tokens)+ backend._is_vlm = True+ backend._model = SimpleNamespace()+ backend._processor = SimpleNamespace(tokenizer = backend._tokenizer)+ args = (messages, image, 0, 1, 0, 0, max_new_tokens, 1, None)+ list(backend._generate_vlm(*args, _adapter_state = False))+ return seen["max_tokens"]+++def test_mlx_text_resolves_an_unset_budget_against_the_served_window(monkeypatch):+ assert _run_text_budget(monkeypatch, None) == _BUDGET_WINDOW - _BUDGET_PROMPT_N+++def test_mlx_text_budget_counts_the_cached_prefix_too(monkeypatch):+ # Sizing from the 4-token uncached tail would treat the cached prefix as free room.+ budget = _run_text_budget(monkeypatch, None, served = 4096, cached = list(range(300)))++ assert budget == 4096 - 300+++def test_mlx_vlm_does_not_size_a_budget_from_a_prompt_carrying_an_image(monkeypatch):+ # An image is one placeholder token in the rendered prompt and many once expanded.+ from core.inference.runtime_context import UNSET_GENERATION_BUDGET+ budget = _run_vlm_budget(monkeypatch, _IMAGE_TURN, object(), None, served = 32768)++ assert budget == UNSET_GENERATION_BUDGET+++def test_mlx_vlm_image_budget_stays_inside_a_narrow_served_window(monkeypatch):+ # A load pinned below the default rotates its KV cache at the served window, so a flat+ # 2048 would evict the image it is still answering about.+ budget = _run_vlm_budget(monkeypatch, _IMAGE_TURN, object(), None, served = 1024)++ assert budget == 1024 - _BUDGET_PROMPT_N+++def test_mlx_vlm_counts_a_text_only_turn_by_the_vision_marker_rule(monkeypatch):+ # A vision model still counts a text-only turn, by mlx_vlm's marker rule, not the text one.+ budget = _run_vlm_budget(monkeypatch, _TEXT_TURN, None, None, served = 32768, marker_tokens = 1)++ assert budget == 32768 - _BUDGET_PROMPT_N - 1+++def test_mlx_passes_an_explicit_budget_through_both_paths(monkeypatch):+ assert _run_text_budget(monkeypatch, 4096) == 4096+ assert _run_vlm_budget(monkeypatch, _IMAGE_TURN, object(), 4096) == 4096+++def test_mlx_unset_budget_falls_back_when_the_prompt_cannot_be_counted(monkeypatch):+ from core.inference.runtime_context import UNSET_GENERATION_BUDGET++ backend = _budget_backend(monkeypatch)+ backend._tokenizer = None++ assert backend._unset_generation_budget("P") == UNSET_GENERATION_BUDGETdiff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.pyindex 1dd7750b268..79d1b0adfd0 100644--- a/studio/backend/tests/test_openai_auto_switch.py+++ b/studio/backend/tests/test_openai_auto_switch.py@@ -1942,8 +1942,17 @@ def test_idle_loop_resets_timer_for_same_repo_different_variant(monkeypatch):task = asyncio.create_task(kw.idle_unload_loop(poll_seconds = 0.01))await asyncio.sleep(0.03)assert unloads == []- kw._last_active = time.monotonic() - 60 # force idle- backend.hf_variant = "Q8_0" # same id, new quant -> fresh identity+ # Under the gate the loop itself holds: it reads the identity and decides idleness+ # inside one _unload_gate, so an unguarded write can land between the two, be judged+ # against the old identity, and unload on the forced idle -- the reset under test+ # never happening. Acquired off the loop, never with a plain `with`: the loop awaits+ # inside that gate, so blocking this thread on the lock it holds deadlocks both.+ await asyncio.to_thread(kw._lifecycle_lock.acquire)+ try:+ kw._last_active = time.monotonic() - 60 # force idle+ backend.hf_variant = "Q8_0" # same id, new quant -> fresh identity+ finally:+ kw._lifecycle_lock.release()await asyncio.sleep(0.03)assert unloads == [] # timer reset by the variant change, not unloadedtask.cancel()diff --git a/unsloth_cli/_inference.py b/unsloth_cli/_inference.pyindex ae04ccd77f9..48210252e8b 100644--- a/unsloth_cli/_inference.py+++ b/unsloth_cli/_inference.py@@ -348,12 +348,23 @@ def render_columns((console or Console()).print(table)+def stats_hit_token_limit(stats) -> bool:+ """Whether a backend's end-of-generation stats say the reply ran out of budget.++ Safetensors reports ``truncated``; MLX and llama-server report a finish reason.+ """+ if not isinstance(stats, dict):+ return False+ return bool(stats.get("truncated")) or stats.get("finish_reason") == "length"++class ChatBackend:"""Uniform stream()/close() over the llama-server and Unsloth backends."""def __init__(self, kind: str, backend) -> None:self._kind = kind # "gguf" | "unsloth"self._backend = backend+ self.reply_hit_token_limit = Falsedef stream(self,@@ -363,25 +374,29 @@ class ChatBackend:temperature: float,top_p: float,top_k: int,- max_new_tokens: int,+ max_new_tokens: Optional[int],repetition_penalty: float,enable_thinking: bool,use_adapter: Optional[bool] = None,):+ self.reply_hit_token_limit = Falseif self._kind == "gguf":# llama-server takes the system prompt as the first message.msgs = list(messages)if system_prompt:msgs = [{"role": "system", "content": system_prompt}, *msgs]- return self._backend.generate_chat_completion(- messages = msgs,- temperature = temperature,- top_p = top_p,- top_k = top_k,- max_tokens = max_new_tokens,- repetition_penalty = repetition_penalty,- enable_thinking = enable_thinking,+ return self._watch_metadata(+ self._backend.generate_chat_completion(+ messages = msgs,+ temperature = temperature,+ top_p = top_p,+ top_k = top_k,+ max_tokens = max_new_tokens,+ repetition_penalty = repetition_penalty,+ enable_thinking = enable_thinking,+ ))+ holder: dict = {}gen_kwargs = dict(messages = messages,system_prompt = system_prompt,@@ -391,12 +406,27 @@ class ChatBackend:max_new_tokens = max_new_tokens,repetition_penalty = repetition_penalty,enable_thinking = enable_thinking,+ stats_holder = holder,)if use_adapter is not None:- return self._backend.generate_with_adapter_control(+ stream = self._backend.generate_with_adapter_control(use_adapter = use_adapter, **gen_kwargs)- return self._backend.generate_chat_response(**gen_kwargs)+ else:+ stream = self._backend.generate_chat_response(**gen_kwargs)+ return self._watch_stats(stream, holder)++ def _watch_metadata(self, stream):+ """llama-server closes a turn with a metadata event carrying the finish reason."""+ for chunk in stream:+ if isinstance(chunk, dict) and chunk.get("type") == "metadata":+ self.reply_hit_token_limit = chunk.get("finish_reason") == "length"+ yield chunk++ def _watch_stats(self, stream, holder: dict):+ """The worker fills the holder once the turn is done, so read it at the end."""+ yield from stream+ self.reply_hit_token_limit = stats_hit_token_limit(holder.get("stats"))def close(self) -> None:# Shut the worker down directly: the graceful unload_model waits for an ack that compare mode can@@ -725,6 +755,7 @@ class HttpChatBackend:def __init__(self, base_url: str, token: str) -> None:self._base = base_urlself._token = token+ self.reply_hit_token_limit = Falsedef _request(self,@@ -794,7 +825,7 @@ class HttpChatBackend:temperature: float,top_p: float,top_k: int,- max_new_tokens: int,+ max_new_tokens: Optional[int],repetition_penalty: float,enable_thinking: bool,use_adapter: Optional[bool] = None,@@ -804,21 +835,21 @@ class HttpChatBackend:msgs = list(messages)if system_prompt:msgs = [{"role": "system", "content": system_prompt}, *msgs]- resp = self._request(- "POST",- "/v1/chat/completions",- {- "model": "default",- "messages": msgs,- "stream": True,- "temperature": temperature,- "top_p": top_p,- "top_k": top_k,- "max_tokens": max_new_tokens,- "repetition_penalty": repetition_penalty,- "enable_thinking": enable_thinking,- },- )+ body = {+ "model": "default",+ "messages": msgs,+ "stream": True,+ "temperature": temperature,+ "top_p": top_p,+ "top_k": top_k,+ "repetition_penalty": repetition_penalty,+ "enable_thinking": enable_thinking,+ }+ if max_new_tokens is not None:+ body["max_tokens"] = max_new_tokens+ resp = self._request("POST", "/v1/chat/completions", body)++ self.reply_hit_token_limit = Falsedef cumulative():# Accumulate SSE deltas into the full-text-so-far convention the stream helpers expect.@@ -840,9 +871,16 @@ class HttpChatBackend:f"Server error: {parsed['error'].get('message', 'Unknown server error')}")try:- delta = parsed["choices"][0]["delta"].get("content")+ choice = parsed["choices"][0]except (KeyError, IndexError):continue+ # Read before the delta: the finish-reason chunk may carry no content.+ if choice.get("finish_reason") is not None:+ self.reply_hit_token_limit = choice["finish_reason"] == "length"+ try:+ delta = choice["delta"].get("content")+ except (KeyError, AttributeError, TypeError):+ continueif not delta:continuetext += deltadiff --git a/unsloth_cli/commands/chat.py b/unsloth_cli/commands/chat.pyindex dc96ba410b2..37b39332b84 100644--- a/unsloth_cli/commands/chat.py+++ b/unsloth_cli/commands/chat.py@@ -167,7 +167,12 @@ def chat(temperature: float = typer.Option(0.7, "--temperature"),top_p: float = typer.Option(0.9, "--top-p"),top_k: int = typer.Option(40, "--top-k"),- max_new_tokens: int = typer.Option(512, "--max-new-tokens"),+ max_new_tokens: Optional[int] = typer.Option(+ None,+ "--max-new-tokens",+ help = "Cap on generated tokens. Unset lets a reply use whatever the "+ "model's context window leaves free after the conversation.",+ ),repetition_penalty: float = typer.Option(1.1, "--repetition-penalty"),system_prompt: str = typer.Option("", "--system-prompt", help = "Optional system prompt for the conversation."@@ -465,6 +470,17 @@ def chat(raise typer.Exit(code = 1)continue+ if should_print and getattr(chat_backend, "reply_hit_token_limit", False):+ hint = (+ "raise or omit --max-new-tokens"+ if max_new_tokens is not None+ else "/reset to clear the history, or reload with a larger --max-seq-length"+ )+ console.print(+ f"(reply stopped at the token limit — {hint})",+ style = "bright_black",+ )+messages.append({"role": "assistant", "content": visible_text(answer, show_thinking = False)})diff --git a/unsloth_cli/commands/inference.py b/unsloth_cli/commands/inference.pyindex ca15d79bdeb..e40678611b6 100644--- a/unsloth_cli/commands/inference.py+++ b/unsloth_cli/commands/inference.py@@ -27,7 +27,12 @@ def inference(temperature: float = typer.Option(0.7, "--temperature"),top_p: float = typer.Option(0.9, "--top-p"),top_k: int = typer.Option(40, "--top-k"),- max_new_tokens: int = typer.Option(256, "--max-new-tokens"),+ max_new_tokens: Optional[int] = typer.Option(+ None,+ "--max-new-tokens",+ help = "Cap on generated tokens. Unset lets a reply use whatever the "+ "model's context window leaves free after the conversation.",+ ),repetition_penalty: float = typer.Option(1.1, "--repetition-penalty"),system_prompt: str = typer.Option("",diff --git a/unsloth_cli/tests/test_inference_chat.py b/unsloth_cli/tests/test_inference_chat.pyindex c593e772759..50a5ce059da 100644--- a/unsloth_cli/tests/test_inference_chat.py+++ b/unsloth_cli/tests/test_inference_chat.py@@ -264,6 +264,102 @@ def test_chatbackend_normal_path_skips_adapter_control():assert fake.calls[0][0] == "plain"+class _FakeGgufBackend:+ def __init__(self):+ self.calls = []++ def generate_chat_completion(self, **kwargs):+ self.calls.append(kwargs)+ return iter(["hi"])+++def test_chat_max_new_tokens_is_unset_by_default():+ opt = _option(chatmod.chat, "max_new_tokens")+ assert getattr(opt, "default", "missing") is None+ assert "--max-new-tokens" in (getattr(opt, "param_decls", None) or [])+++def test_chatbackend_forwards_an_unset_max_new_tokens_unset():+ # Only the backend, once it has counted the prompt, can size an unset limit.+ fake = _FakeBackend()+ backend = ChatBackend("unsloth", fake)++ list(+ backend.stream(+ [{"role": "user", "content": "x"}],+ **{**_STREAM_KWARGS, "max_new_tokens": None},+ )+ )++ assert fake.calls[0][2]["max_new_tokens"] is None+++def test_chatbackend_honours_an_explicit_max_new_tokens():+ fake = _FakeBackend()+ backend = ChatBackend("unsloth", fake)++ list(backend.stream([{"role": "user", "content": "x"}], **_STREAM_KWARGS))++ assert fake.calls[0][2]["max_new_tokens"] == 8+++def test_chatbackend_gguf_leaves_max_tokens_unset_for_llama_server():+ fake = _FakeGgufBackend()+ backend = ChatBackend("gguf", fake)++ list(+ backend.stream(+ [{"role": "user", "content": "x"}],+ **{**_STREAM_KWARGS, "max_new_tokens": None},+ )+ )+ list(backend.stream([{"role": "user", "content": "x"}], **_STREAM_KWARGS))++ assert [call["max_tokens"] for call in fake.calls] == [None, 8]+++class _FakeStatsBackend:+ def __init__(self, stats):+ self._stats = stats++ def generate_chat_response(self, **kwargs):+ holder = kwargs.get("stats_holder")++ def stream():+ yield "hi"+ if holder is not None:+ holder["stats"] = self._stats++ return stream()+++def _drain_unsloth(stats):+ backend = ChatBackend("unsloth", _FakeStatsBackend(stats))+ list(backend.stream([{"role": "user", "content": "x"}], **_STREAM_KWARGS))+ return backend.reply_hit_token_limit+++def test_chatbackend_reports_whether_a_reply_ran_out_of_budget():+ assert _drain_unsloth({"truncated": True}) is True+ assert _drain_unsloth({"finish_reason": "length"}) is True+ assert _drain_unsloth({"truncated": False}) is False+ assert _drain_unsloth({"finish_reason": "stop"}) is False+ assert _drain_unsloth(None) is False+++def test_chatbackend_gguf_reports_a_length_finish_from_the_metadata_event():+ class _Meta:+ def generate_chat_completion(self, **kwargs):+ return iter(["hi", {"type": "metadata", "finish_reason": "length"}])++ backend = ChatBackend("gguf", _Meta())+ chunks = list(backend.stream([{"role": "user", "content": "x"}], **_STREAM_KWARGS))++ assert backend.reply_hit_token_limit is True+ # The metadata event still reaches the stream helpers, which skip non-strings.+ assert chunks[0] == "hi"++def test_collect_stream_returns_last_cumulative_think_stripped():stream = iter(["<think>r</think>hel", "<think>r</think>hello"])assert collect_stream(stream, show_thinking = False) == "hello"@@ -922,6 +1018,59 @@ def test_http_backend_streams_cumulative_text(monkeypatch):assert out == ["He", "Hello"]+def _http_stream_body(monkeypatch, max_new_tokens):+ backend = HttpChatBackend("http://localhost:8888", "token")+ bodies = []++ def fake_request(+ method,+ path,+ payload = None,+ timeout = None,+ ):+ bodies.append(payload)+ return _FakeSSEResponse([b"data: [DONE]\n"])++ monkeypatch.setattr(backend, "_request", fake_request)+ list(+ backend.stream(+ [{"role": "user", "content": "hi"}],+ **{**_STREAM_KWARGS, "max_new_tokens": max_new_tokens},+ )+ )+ return bodies[0]+++def test_http_backend_omits_max_tokens_when_unset(monkeypatch):+ # The server documents max_tokens=None as "generate until EOS"; sending a cap+ # the user never asked for truncates every reply.+ assert "max_tokens" not in _http_stream_body(monkeypatch, None)+++def test_http_backend_sends_an_explicit_max_tokens(monkeypatch):+ assert _http_stream_body(monkeypatch, 128)["max_tokens"] == 128+++def _http_finish(monkeypatch, finish_reason):+ backend = HttpChatBackend("http://localhost:8888", "token")+ chunk = json.dumps({"choices": [{"delta": {"content": "hi"}, "finish_reason": finish_reason}]})+ monkeypatch.setattr(+ backend,+ "_request",+ lambda *a, **k: _FakeSSEResponse([f"data: {chunk}\n".encode(), b"data: [DONE]\n"]),+ )+ out = list(backend.stream([{"role": "user", "content": "hi"}], **_STREAM_KWARGS))+ return backend.reply_hit_token_limit, out+++def test_http_backend_reports_whether_a_reply_ran_out_of_budget(monkeypatch):+ hit, out = _http_finish(monkeypatch, "length")+ assert hit is True+ # The finish-reason chunk carries a delta too; it must not be dropped.+ assert out == ["hi"]+ assert _http_finish(monkeypatch, "stop")[0] is False++class _FakeLoadResponse:"""A /api/inference/load reply that records whether its body was drained.@@ -1426,6 +1575,41 @@ def test_chat_prefers_running_studio_server(monkeypatch):assert closed == ["http"]+def _chat_run_with_limit_flag(monkeypatch, hit, *flags):+ class _FakeHttpBackend:+ def __init__(self):+ self.reply_hit_token_limit = False++ def stream(self, *a, **k):+ self.reply_hit_token_limit = hit+ return iter(["hello"])++ def close(self):+ pass++ monkeypatch.setattr(chatmod, "resolve_model_config", lambda *a, **k: _FakeConfig())+ monkeypatch.setattr(chatmod, "connect_studio_server", lambda *a, **k: _FakeHttpBackend())+ monkeypatch.setattr(chatmod, "load_chat_backend", lambda *a, **k: None)+ monkeypatch.setattr(chatmod, "_compare_needs_second_model", lambda: False)++ result = CliRunner().invoke(_chat_app(), ["fake-model", *flags], input = "hi\n/exit\n")+ assert result.exit_code == 0, result.output+ return result.output+++def test_chat_tells_the_user_when_a_reply_stopped_at_the_token_limit(monkeypatch):+ unset = _chat_run_with_limit_flag(monkeypatch, True)+ capped = _chat_run_with_limit_flag(monkeypatch, True, "--max-new-tokens", "8")++ # Only an unset limit grows with the context; a chosen one has to be raised itself.+ assert "--max-seq-length" in unset and "--max-new-tokens" not in unset+ assert "--max-new-tokens" in capped and "--max-seq-length" not in capped+++def test_chat_stays_quiet_when_a_reply_ended_on_its_own(monkeypatch):+ assert "token limit" not in _chat_run_with_limit_flag(monkeypatch, False)++def test_chat_forwards_gguf_runtime_options_to_loader(monkeypatch):loads = []