Skip to content

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

Expose runtime context length for hub models (#6154)

alkinun672d8f058199
diff --git a/studio/backend/core/inference/inference.py b/studio/backend/core/inference/inference.py
index 55c2c551a39..2b9517692ff 100644
--- a/studio/backend/core/inference/inference.py
+++ b/studio/backend/core/inference/inference.py
@@ -25,6 +25,7 @@ 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 io import StringIO
import structlog
from loggers import get_logger
@@ -405,6 +406,10 @@ class InferenceBackend:
# Reject CPU/disk offload for audio models too
raise_if_offloaded(self.models[model_name]["model"], device_map, "Inference")
+ self.models[model_name]["context_length"] = runtime_context_length(
+ self.models[model_name].get("model"),
+ max_seq_length,
+ )
self.active_model_name = model_name
self.loading_models.discard(model_name)
@@ -485,6 +490,10 @@ class InferenceBackend:
self.models[model_name]["tokenizer"] = tokenizer
raise_if_offloaded(self.models[model_name]["model"], device_map, "Inference")
+ self.models[model_name]["context_length"] = runtime_context_length(
+ self.models[model_name].get("model"),
+ max_seq_length,
+ )
self._load_chat_template_info(model_name)
diff --git a/studio/backend/core/inference/mlx_inference.py b/studio/backend/core/inference/mlx_inference.py
index fbbdb9a7734..5c7799152f2 100644
--- a/studio/backend/core/inference/mlx_inference.py
+++ b/studio/backend/core/inference/mlx_inference.py
@@ -7,6 +7,7 @@ instead of torch/transformers for model loading and generation.
import threading
from typing import Optional, Generator
+from core.inference.runtime_context import runtime_context_length
from loggers import get_logger
logger = get_logger(__name__)
@@ -175,6 +176,7 @@ class MLXInferenceBackend:
"is_audio": False,
"audio_type": None,
"has_audio_input": False,
+ "context_length": runtime_context_length(self._model, max_seq_length),
}
# Capture chat_template_info so the worker IPC reply ships it back and
# the route layer classifies capabilities like the other paths.
diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.py
index 32bb25c9769..4e4788ace92 100644
--- a/studio/backend/core/inference/orchestrator.py
+++ b/studio/backend/core/inference/orchestrator.py
@@ -727,6 +727,7 @@ class InferenceOrchestrator:
"is_audio": model_info.get("is_audio", False),
"audio_type": model_info.get("audio_type"),
"has_audio_input": model_info.get("has_audio_input", False),
+ "context_length": model_info.get("context_length"),
}
# Mirror chat_template_info so routes can classify caps
# without re-entering the subprocess.
diff --git a/studio/backend/core/inference/runtime_context.py b/studio/backend/core/inference/runtime_context.py
new file mode 100644
index 00000000000..8b881628be2
--- /dev/null
+++ b/studio/backend/core/inference/runtime_context.py
@@ -0,0 +1,22 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Runtime context length helpers shared by inference backends."""
+
+from __future__ import annotations
+
+from typing import Any, Optional
+
+
+def runtime_context_length(model: Any, fallback: Optional[int] = None) -> Optional[int]:
+ """Return the effective context length Unsloth attached to a loaded model."""
+ for value in (getattr(model, "max_seq_length", None), fallback):
+ if isinstance(value, bool):
+ continue
+ try:
+ value_int = int(value)
+ except (TypeError, ValueError):
+ continue
+ if value_int > 0:
+ return value_int
+ return None
diff --git a/studio/backend/core/inference/worker.py b/studio/backend/core/inference/worker.py
index 4f5b985234b..cc796540873 100644
--- a/studio/backend/core/inference/worker.py
+++ b/studio/backend/core/inference/worker.py
@@ -315,6 +315,18 @@ def _handle_load(backend, config: dict, resp_queue: Any) -> None:
"audio_type": getattr(mc, "audio_type", None),
"has_audio_input": getattr(mc, "has_audio_input", False),
}
+ try:
+ _bm = getattr(backend, "models", {}) or {}
+ _entry = (
+ _bm.get(mc.identifier)
+ or _bm.get(getattr(backend, "active_model_name", None))
+ or {}
+ )
+ _context_length = _entry.get("context_length")
+ if _context_length is not None:
+ model_info["context_length"] = int(_context_length)
+ except Exception as _ctx_exc:
+ logger.warning("context_length forward failed: %s", _ctx_exc)
# Forward chat_template_info so the parent can classify capabilities.
try:
_bm = getattr(backend, "models", {}) or {}
@@ -881,6 +893,7 @@ def run_inference_process(*, cmd_queue: Any, resp_queue: Any, cancel_event, conf
name: {
"is_vision": info.get("is_vision", False),
"is_lora": info.get("is_lora", False),
+ "context_length": info.get("context_length"),
}
for name, info in backend.models.items()
},
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index f94d5366eb1..b70202d6ffa 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -171,7 +171,7 @@ class LoadResponse(BaseModel):
description = "Whether the model defaults require trust_remote_code to be enabled for loading.",
)
context_length: Optional[int] = Field(
- None, description = "Model's native context length (from GGUF metadata)"
+ None, description = "Runtime context length in tokens for the loaded model"
)
max_context_length: Optional[int] = Field(
None, description = "Maximum context length currently available on this hardware"
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 3333db9d073..3850d0cbb28 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -29,6 +29,16 @@ from utils.models import extract_model_size_b as _extract_model_size_b
from utils.api_errors import openai_error_body, anthropic_error_body
+def _positive_int_or_none(value: Any) -> Optional[int]:
+ if isinstance(value, bool):
+ return None
+ try:
+ value_int = int(value)
+ except (TypeError, ValueError):
+ return None
+ return value_int if value_int > 0 else None
+
+
def _install_httpcore_asyncgen_silencer() -> None:
"""Silence benign httpx/httpcore asyncgen GC noise on Python 3.13.
@@ -1390,6 +1400,7 @@ async def load_model(
reasoning_always_on = _sf_flags["reasoning_always_on"],
supports_preserve_thinking = _sf_flags["supports_preserve_thinking"],
supports_tools = _sf_flags["supports_tools"],
+ context_length = _positive_int_or_none(_model_info.get("context_length")),
chat_template = _chat_template,
)
@@ -1731,6 +1742,7 @@ async def load_model(
reasoning_always_on = _sf_flags["reasoning_always_on"],
supports_preserve_thinking = _sf_flags["supports_preserve_thinking"],
supports_tools = _sf_flags["supports_tools"],
+ context_length = _positive_int_or_none(_model_info.get("context_length")),
chat_template = _chat_template,
)
@@ -2119,6 +2131,7 @@ async def get_status(current_subject: str = Depends(get_current_subject)):
reasoning_always_on = _sf_flags["reasoning_always_on"],
supports_preserve_thinking = _sf_flags["supports_preserve_thinking"],
supports_tools = _sf_flags["supports_tools"],
+ context_length = _positive_int_or_none(model_info.get("context_length")),
chat_template = chat_template,
llama_cpp_supports_mtp = _supports_mtp,
llama_cpp_prebuilt_stale = _stale,
@@ -4625,28 +4638,38 @@ def _openai_model_objects() -> list[dict]:
"created": _created,
"owned_by": "local",
}
- # Extension fields: the real per-request window (post /props readback)
- # so clients can budget/compact against the enforced limit.
- if llama_backend.context_length:
- entry["context_length"] = llama_backend.context_length
- if llama_backend.max_context_length:
- entry["max_context_length"] = llama_backend.max_context_length
+ _ctx = _positive_int_or_none(getattr(llama_backend, "context_length", None))
+ if _ctx is not None:
+ entry["context_length"] = _ctx
+ _max_ctx = _positive_int_or_none(getattr(llama_backend, "max_context_length", None))
+ if _max_ctx is not None:
+ entry["max_context_length"] = _max_ctx
+ _native_ctx = _positive_int_or_none(getattr(llama_backend, "native_context_length", None))
+ if _native_ctx is not None:
+ entry["native_context_length"] = _native_ctx
models.append(entry)
# Check Unsloth backend
backend = get_inference_backend()
if backend.active_model_name:
+ model_info = backend.models.get(backend.active_model_name, {})
entry = {
"id": backend.active_model_name,
"object": "model",
"created": _created,
"owned_by": "local",
}
- _sf_ctx = getattr(backend, "context_length", None) or getattr(
- backend, "max_seq_length", None
- )
- if _sf_ctx:
- entry["context_length"] = _sf_ctx
+ _ctx = _positive_int_or_none(model_info.get("context_length"))
+ if _ctx is None:
+ for _candidate in (
+ getattr(backend, "context_length", None),
+ getattr(backend, "max_seq_length", None),
+ ):
+ _ctx = _positive_int_or_none(_candidate)
+ if _ctx is not None:
+ break
+ if _ctx is not None:
+ entry["context_length"] = _ctx
models.append(entry)
return models
diff --git a/studio/backend/tests/test_native_context_length.py b/studio/backend/tests/test_native_context_length.py
index 0290bb13088..de1ca0649e4 100644
--- a/studio/backend/tests/test_native_context_length.py
+++ b/studio/backend/tests/test_native_context_length.py
@@ -271,6 +271,7 @@ class TestPydanticModels:
def test_load_response_has_field(self):
"""Field exists in LoadResponse.model_fields."""
assert "native_context_length" in LoadResponse.model_fields
+ assert "context_length" in LoadResponse.model_fields
def test_load_response_defaults_none(self):
"""Omitting native_context_length defaults to None."""
@@ -319,6 +320,7 @@ class TestPydanticModels:
def test_status_response_has_field(self):
"""Field exists in InferenceStatusResponse.model_fields."""
assert "native_context_length" in InferenceStatusResponse.model_fields
+ assert "context_length" in InferenceStatusResponse.model_fields
def test_status_response_has_chat_template_field(self):
"""Status includes chat_template so the UI can rehydrate after refresh."""
@@ -347,6 +349,18 @@ class TestPydanticModels:
roundtripped = LoadResponse.model_validate_json(resp.model_dump_json())
assert roundtripped.native_context_length == 131072
+ def test_context_length_roundtrip(self):
+ """Runtime context_length serializes for non-GGUF/hub models."""
+ resp = LoadResponse(
+ status = "loaded",
+ model = "test",
+ display_name = "Test",
+ inference = {},
+ context_length = 8192,
+ )
+ roundtripped = LoadResponse.model_validate_json(resp.model_dump_json())
+ assert roundtripped.context_length == 8192
+
# =====================================================================
# D. TestRouteCompleteness -- source-level verification
@@ -408,6 +422,16 @@ class TestRouteCompleteness:
"native_context_length" not in block
), f"Non-GGUF LoadResponse should not set native_context_length:\n{block[:200]}"
+ def test_non_gguf_load_responses_set_runtime_context_length(self):
+ """Non-GGUF LoadResponse blocks report runtime context_length."""
+ blocks = self._find_construction_blocks("LoadResponse")
+ non_gguf = [b for b in blocks if "is_gguf = True" not in b and "is_gguf=True" not in b]
+ assert non_gguf, "Expected at least one non-GGUF LoadResponse block"
+ for block in non_gguf:
+ assert (
+ "context_length" in block
+ ), f"Non-GGUF LoadResponse should set context_length:\n{block[:200]}"
+
def test_status_path(self):
"""InferenceStatusResponse construction with llama_backend has the field."""
blocks = self._find_construction_blocks("InferenceStatusResponse")
@@ -420,6 +444,21 @@ class TestRouteCompleteness:
found
), "No InferenceStatusResponse block with llama_backend has native_context_length"
+ def test_non_gguf_status_path_reports_runtime_context_length(self):
+ """Non-GGUF InferenceStatusResponse reports context_length from model_info."""
+ blocks = self._find_construction_blocks("InferenceStatusResponse")
+ found = False
+ for block in blocks:
+ if "is_gguf = False" in block and "context_length" in block:
+ found = True
+ break
+ assert found, "No non-GGUF InferenceStatusResponse block with context_length"
+
+ def test_openai_models_listing_reports_context_length(self):
+ """/v1/models includes context_length when the backend knows it."""
+ assert 'entry["context_length"]' in self._source
+ assert 'model_info.get("context_length")' in self._source
+
# =====================================================================
# E. TestEdgeCases
diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.py
index 7493b87eee8..fb63fbf2086 100644
--- a/unsloth_cli/commands/studio.py
+++ b/unsloth_cli/commands/studio.py
@@ -570,6 +570,19 @@ def _load_model_via_http(
raise RuntimeError(f"Model load failed (HTTP {exc.code}): {body}") from exc
+def _format_context_length_line(load_result: dict) -> Optional[str]:
+ value = load_result.get("context_length")
+ if isinstance(value, bool):
+ return None
+ try:
+ value_int = int(value)
+ except (TypeError, ValueError):
+ return None
+ if value_int <= 0:
+ return None
+ return f" Context length: {value_int} tokens"
+
+
# ── unsloth studio (server) ──────────────────────────────────────────
@@ -841,7 +854,10 @@ def run(
None, "--gguf-variant", help = "GGUF quant variant (e.g. UD-Q4_K_XL)"
),
max_seq_length: int = typer.Option(
- 0, "--max-seq-length", help = "Max sequence length (0 = model default)"
+ 0,
+ "--max-seq-length",
+ "--context-length",
+ help = "Runtime context length in tokens (0 = model default for GGUF; 2048 for hub models)",
),
load_in_4bit: bool = typer.Option(True, "--load-in-4bit/--no-load-in-4bit"),
api_key_name: str = typer.Option(
@@ -1080,6 +1096,7 @@ def run(
loaded_model = result.get("model", model)
display_variant = f" ({gguf_variant})" if gguf_variant else ""
+ context_length_line = _format_context_length_line(result)
# 6. Print banner.
display_host = _resolve_external_ip() if host == "0.0.0.0" else host
@@ -1119,6 +1136,8 @@ def run(
if _cf_url:
typer.echo(f" Secure link access via Cloudflare: {_cf_url}")
typer.echo(f" Model loaded: {loaded_model}{display_variant}")
+ if context_length_line:
+ typer.echo(context_length_line)
typer.echo(f" API Key: {api_key}")
typer.echo("")
typer.echo(" OpenAI / Anthropic SDK base URL:")
@@ -1153,6 +1172,8 @@ def run(
typer.echo(f"URL: {base_url}")
if _cf_url:
typer.echo(f"Secure link access via Cloudflare: {_cf_url}")
+ if context_length_line:
+ typer.echo(context_length_line.strip())
typer.echo(f"API Key: {api_key}")
typer.secho(_tool_notice, fg = _tool_notice_fg, bold = True)
diff --git a/unsloth_cli/tests/test_studio_run_parallel_flag.py b/unsloth_cli/tests/test_studio_run_parallel_flag.py
index abc0b3c7c4a..8870fa348de 100644
--- a/unsloth_cli/tests/test_studio_run_parallel_flag.py
+++ b/unsloth_cli/tests/test_studio_run_parallel_flag.py
@@ -51,6 +51,18 @@ def test_parallel_option_is_registered():
assert required in flags, f"flag {required!r} missing from --parallel option"
+def test_context_length_alias_is_registered():
+ """`--context-length` is an operator-facing alias for --max-seq-length."""
+ studio_mod = _load_run_command()
+ import inspect
+
+ sig = inspect.signature(studio_mod.run)
+ opt = sig.parameters["max_seq_length"].default
+ flags = set(getattr(opt, "param_decls", None) or [])
+ assert "--max-seq-length" in flags
+ assert "--context-length" in flags
+
+
def test_parallel_default_is_four():
"""Default must stay at 4 so plain `unsloth studio run` is unchanged."""
studio_mod = _load_run_command()
@@ -249,6 +261,15 @@ def test_reexec_np_is_first_class_alias(monkeypatch):
assert _value_after(argv, "--port") == "8888", argv
+def test_reexec_forwards_context_length_alias(monkeypatch):
+ """Alias should normalize to the existing child --max-seq-length flag."""
+ result, captured = _invoke_run(monkeypatch, _BASE + ["--context-length", "8192"])
+ assert len(captured) == 1, result.output
+ argv = captured[0]["argv"]
+ assert _value_after(argv, "--max-seq-length") == "8192", argv
+ assert "--context-length" not in argv, argv
+
+
def test_reexec_mixed_parallel_with_passthrough(monkeypatch):
"""--parallel + llama-server pass-through flags must all reach the child."""
result, captured = _invoke_run(
@@ -262,6 +283,22 @@ def test_reexec_mixed_parallel_with_passthrough(monkeypatch):
assert _value_after(argv, "--temp") == "0.7", argv
+def test_context_length_banner_line_formats_ints():
+ studio_mod = _load_run_command()
+ assert studio_mod._format_context_length_line({"context_length": 4096}) == (
+ " Context length: 4096 tokens"
+ )
+ assert studio_mod._format_context_length_line({"context_length": "8192"}) == (
+ " Context length: 8192 tokens"
+ )
+
+
[email protected]("value", [None, 0, -1, True, ""])
+def test_context_length_banner_line_omits_unknown_values(value):
+ studio_mod = _load_run_command()
+ assert studio_mod._format_context_length_line({"context_length": value}) is None
+
+
@pytest.mark.parametrize(
"user_flag,expected_in_child",
[