Skip to content

Studio: bundle Gemma 4 chat templates (E2B/E4B + larger) and auto-apply to unsloth/gemma-4-*-GGUF - #6245

Merged
danielhanchen merged 8 commits into
mainfrom
gemma4-studio-chat-template-override
Jun 12, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
gemma4-studio-chat-template-override

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Jun 12, 2026 •

Copy link
Copy Markdown
Member

What

Studio now ships bundled Gemma 4 chat templates and applies them to unsloth/gemma-4-*-GGUF models at llama-server launch via --chat-template-file. The templates are based on Google's Gemma 4 chat-template update (HF google/gemma-4-31B-it discussion #118), which adds the preserve_thinking flag. We default preserve_thinking to off.

Why

The chat templates baked into the already-shipped unsloth/gemma-4-*-GGUF quants predate the preserve_thinking flag. Studio only renders the "Preserve thinking" toggle when the active template contains preserve_thinking, so the control was missing for Gemma 4. Overriding the template at launch fixes this without asking users to re-download multi-GB quants, so a Studio update alone is enough.

Two templates, matching Google's per-family behavior

Google ships two distinct gemma-4 chat templates, and they differ in exactly one block: the 12b / 26B-A4B / 31B family emits an empty <|channel>thought<channel|> block when enable_thinking is false, while E2B / E4B deliberately omit it (verified against google/gemma-4-E2B-it, -E4B-it, -12b-it, -26B-A4B-it, -31B-it). We preserve that distinction:

  • studio/backend/assets/chat_templates/gemma-4.jinja -> 12b / 26B-A4B / 31B GGUFs (emits the empty thought block on thinking-off).
  • studio/backend/assets/chat_templates/gemma-4-edge.jinja -> E2B / E4B GGUFs (omits it). Identical to gemma-4.jinja apart from that block.

Both add preserve_thinking (default false) and the upstream PR #118 robustness fixes. The one deliberate divergence from upstream is preserve_thinking | default(false).

How

  • studio/backend/core/inference/chat_templates.py: gemma-4 GGUF matcher, an E2B/E4B edge matcher, and an effective-override resolver that picks the right template per family. An explicit user chat_template_override still wins.
  • studio/backend/routes/inference.py: resolves the effective override once, ahead of the reload-dedup check and both load_model calls, so the live backend and the incoming request compare against the same template text (no spurious reloads).
  • studio/backend/core/inference/llama_cpp.py: defaults preserve_thinking off in the launch-time chat_template_kwargs, so direct OpenAI-compatible callers match the UI default. The frontend already defaults the toggle off and forwards preserve_thinking per request, so no frontend change is needed.
  • pyproject.toml: ship the assets via package-data.

Tests

studio/backend/tests/test_gemma4_chat_template_override.py covers the matcher and edge matcher, per-family resolver routing, user-override precedence, asset capability detection (detect_reasoning_flags -> supports_preserve_thinking), the preserve_thinking Jinja gate, the empty-thought-block difference between the two templates, and reload-dedup consistency.

Verified live

Loaded unsloth/gemma-4-E2B-it-GGUF (Q4_K_M) in Studio:

  • llama-server launched with --chat-template-file <bundled> --chat-template-kwargs {"enable_thinking": true, "preserve_thinking": false}
  • /status reports supports_preserve_thinking: true
  • the "Preserve thinking" toggle appears in the composer thinking dropdown and is off by default
  • the GGUF loaded from cache, confirming no quant re-download is required

…d gemma-4.jinja

The chat templates baked into the shipped unsloth/gemma-4-*-GGUF quants predate
Google's gemma-4 chat-template PR #118 and lack the preserve_thinking flag, so
Studio cannot surface the "Preserve thinking" toggle for Gemma 4. Bundle the updated
template and override the embedded one at llama-server launch via --chat-template-file,
scoped to the gemma-4 GGUF family, so users do not need to re-download any quant.

- Add studio/backend/assets/chat_templates/gemma-4.jinja (PR #118 based;
  preserve_thinking defaults false, the one deliberate divergence from upstream).
- Add core/inference/chat_templates.py: gemma-4 GGUF matcher plus an
  effective-override resolver (explicit user template still wins).
- Wire the resolver into routes/inference.py ahead of the reload-dedup check and
  both load_model calls so the live backend and the incoming request compare against
  the same template text (no spurious reloads).
- Default preserve_thinking off in the launch-time chat_template_kwargs so direct
  API callers match the UI default.
- Ship the asset via package-data and add unit tests.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a bundled Gemma 4 chat template override for Unsloth Gemma 4 GGUF models to support the preserve_thinking flag without requiring users to re-download quants. It adds the Jinja template asset, implements resolution logic to handle overrides during model loading and reload-deduplication checks, and includes comprehensive unit tests. Feedback on the tests suggests using unittest.mock.patch.dict instead of globally modifying sys.modules with setdefault to prevent test pollution and ensure proper isolation.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +44 to +64
def _detect_reasoning_flags():
_loggers_stub = _types.ModuleType("loggers")
_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)
sys.modules.setdefault("loggers", _loggers_stub)
_structlog_stub = _types.ModuleType("structlog")
_structlog_stub.get_logger = lambda *a, **k: __import__("logging").getLogger("stub")
sys.modules.setdefault("structlog", _structlog_stub)
_httpx_stub = _types.ModuleType("httpx")
for _exc in (
"ConnectError", "TimeoutException", "ReadTimeout", "ReadError",
"RemoteProtocolError", "CloseError",
):
setattr(_httpx_stub, _exc, type(_exc, (Exception,), {}))
_httpx_stub.Timeout = type("T", (), {"__init__": lambda s, *a, **k: None})
_httpx_stub.Client = type(
"C", (), {"__init__": lambda s, **kw: None,
"__enter__": lambda s: s, "__exit__": lambda s, *a: None},
)
sys.modules.setdefault("httpx", _httpx_stub)
from core.inference.llama_cpp import detect_reasoning_flags
return detect_reasoning_flags

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Modifying sys.modules globally using setdefault pollutes the global module registry for the entire test session. This can lead to flaky tests or unexpected failures in other test files that run after this one and rely on the real httpx or structlog modules.

To ensure proper test isolation, consider using unittest.mock.patch.dict to temporarily mock these modules only during the import scope, or simply import them normally since the test environment already has these dependencies installed.

Suggested change
def _detect_reasoning_flags():
_loggers_stub = _types.ModuleType("loggers")
_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)
sys.modules.setdefault("loggers", _loggers_stub)
_structlog_stub = _types.ModuleType("structlog")
_structlog_stub.get_logger = lambda *a, **k: __import__("logging").getLogger("stub")
sys.modules.setdefault("structlog", _structlog_stub)
_httpx_stub = _types.ModuleType("httpx")
for _exc in (
"ConnectError", "TimeoutException", "ReadTimeout", "ReadError",
"RemoteProtocolError", "CloseError",
):
setattr(_httpx_stub, _exc, type(_exc, (Exception,), {}))
_httpx_stub.Timeout = type("T", (), {"__init__": lambda s, *a, **k: None})
_httpx_stub.Client = type(
"C", (), {"__init__": lambda s, **kw: None,
"__enter__": lambda s: s, "__exit__": lambda s, *a: None},
)
sys.modules.setdefault("httpx", _httpx_stub)
from core.inference.llama_cpp import detect_reasoning_flags
return detect_reasoning_flags
def _detect_reasoning_flags():
from unittest.mock import patch
_loggers_stub = _types.ModuleType("loggers")
_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)
_structlog_stub = _types.ModuleType("structlog")
_structlog_stub.get_logger = lambda *a, **k: __import__("logging").getLogger("stub")
_httpx_stub = _types.ModuleType("httpx")
for _exc in (
"ConnectError", "TimeoutException", "ReadTimeout", "ReadError",
"RemoteProtocolError", "CloseError",
):
setattr(_httpx_stub, _exc, type(_exc, (Exception,), {}))
_httpx_stub.Timeout = type("T", (), {"__init__": lambda s, *a, **k: None})
_httpx_stub.Client = type(
"C", (), {"__init__": lambda s, **kw: None,
"__enter__": lambda s: s, "__exit__": lambda s, *a: None},
)
with patch.dict(sys.modules, {"loggers": _loggers_stub, "structlog": _structlog_stub, "httpx": _httpx_stub}):
from core.inference.llama_cpp import detect_reasoning_flags
return detect_reasoning_flags

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3a883ce9e5

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".



def _render(messages, **kw):
from jinja2 import Environment, BaseLoader

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid requiring undeclared Jinja2 in tests

When the backend tests run in an environment built from the repo's declared requirements without an unrelated transitive jinja2 install, these new render tests fail with ModuleNotFoundError: No module named 'jinja2' at this import; I checked pyproject.toml and studio/backend/requirements with rg -i jinja, and there is no dependency declaration other than the new .jinja package-data glob. Please either add jinja2 to the test/runtime requirements or guard these tests with pytest.importorskip("jinja2") so the suite remains runnable in minimal Studio environments.

Useful? React with 👍 / 👎.

Comment on lines +1325 to +1327
effective_chat_template_override = resolve_effective_chat_template_override(
model_identifier = model_identifier,
user_override = request.chat_template_override,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Normalize shorthand IDs before resolving templates

For supported shorthand loads like gemma-4-E2B-it-GGUF, ModelConfig.from_identifier() later prefixes unsloth/, but the bundled-template resolver runs before that normalization and only matches unsloth/gemma-4-*-GGUF. In that shorthand path the model still loads as the same Unsloth Gemma 4 GGUF repo, but effective_chat_template_override stays None, so the old embedded template is used and the preserve-thinking capability remains missing. Resolve after canonicalizing the identifier or teach the matcher the same shorthand normalization.

Useful? React with 👍 / 👎.

Google ships two distinct gemma-4 chat templates: E2B and E4B omit the empty
"<|channel>thought<channel|>" block on enable_thinking=false, while the
12b/26B-A4B/31B family emits it (confirmed against google/gemma-4-E2B-it,
-E4B-it, -12b-it, -26B-A4B-it, -31B-it; the two families differ only in that
one block). The single PR #118 based template followed the larger-model
behavior, which is wrong for the E2B/E4B GGUFs this feature most targets.

- Add studio/backend/assets/chat_templates/gemma-4-edge.jinja: identical to
  gemma-4.jinja minus the empty-thought-block, matching E2B/E4B behavior.
- Route unsloth/gemma-4-E2B-it-GGUF and -E4B-it-GGUF to the edge template;
  12b/26B-A4B/31B keep gemma-4.jinja.
- Extend tests for the edge matcher, per-family routing, and the empty-thought
  block difference (off for edge, on for standard).
@danielhanchen danielhanchen changed the title Studio: bundle Gemma 4 chat template and auto-apply it to unsloth/gemma-4-*-GGUF Studio: bundle Gemma 4 chat templates (E2B/E4B + larger) and auto-apply to unsloth/gemma-4-*-GGUF Jun 12, 2026
danielhanchen and others added 3 commits June 12, 2026 11:54
…mplate-override

# Conflicts:
#	studio/backend/routes/inference.py
- Normalize owner-less shorthand model ids in the template matcher: a bare
  "gemma-4-E2B-it-GGUF" is canonicalized to "unsloth/" the same way
  ModelConfig.from_identifier does, so shorthand loads still get the override
  (and the preserve_thinking capability) instead of falling back to the
  embedded template.
- Scope the test's module stubs with unittest.mock.patch.dict instead of
  sys.modules.setdefault, and only stub deps that are missing, so the global
  module registry is not polluted for tests that run afterwards.
- Guard the Jinja render tests with pytest.importorskip("jinja2") so the suite
  stays runnable in minimal Studio environments where jinja2 is not present.
- Add tests for shorthand resolution.
@danielhanchen

Copy link
Copy Markdown
Member Author

Rebased onto latest main (resolved the routes/inference.py conflict: the load path was refactored into _common_load_kwargs, so the resolved override now flows through there, and kept the new _should_strip_split_mode helper).

Addressed the review feedback, all three were valid:

  • Shorthand model ids: confirmed ModelConfig.from_identifier prefixes unsloth/ for owner-less ids while the resolver runs on the raw request.model_path. The matcher now applies the same normalization, so a bare gemma-4-E2B-it-GGUF still gets the override. Added tests.
  • Test module stubs: switched from sys.modules.setdefault to a scoped patch.dict, and only stub deps that are actually missing, so real httpx/structlog are kept and nothing leaks into later tests.
  • Jinja2 in tests: guarded the render tests with pytest.importorskip("jinja2") so the suite stays runnable in minimal environments.

Tests: 36 pass for the new suite; test_llama_server_args.py and test_gguf_reload_inheritance.py still green.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0aa707e854

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

is_vision = config.is_vision,
n_ctx = request.max_seq_length,
chat_template_override = request.chat_template_override,
chat_template_override = effective_chat_template_override,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Strip inherited template flags before applying bundled template

When a same-model Gemma GGUF reload omits llama_extra_args after a previous load supplied --chat-template-file in extra args, the inheritance block keeps that flag because chat_template_override was not set by the caller. This line then passes the bundled template, but LlamaCppBackend appends inherited extra_args after its own --chat-template-file, so the stale user file wins while the backend records/detects capabilities from the bundled override. Treat a non-empty effective_chat_template_override as owning the template group when stripping inherited extras so the bundled Gemma template actually takes effect.

Useful? React with 👍 / 👎.

Comment on lines +260 to +264
{%- else -%}
{{- raise_exception(
"chat_template: tool_calls[].function.arguments must be a "
"JSON object (mapping), not a string. Deserialize arguments "
"before passing to the template."

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Accept OpenAI string tool arguments in the bundled template

In any Gemma 4 tool-call loop, the next request after the first tool executes will hit this branch because Studio appends assistant history with ToolCallDecision.as_assistant_tool_call(), which serializes function.arguments with json.dumps(...); OpenAI-compatible clients also send historical tool_calls[].function.arguments as JSON strings. Since the bundled templates advertise tool support but now raise instead of parsing those strings, Gemma 4 local tools fail as soon as a tool result is fed back to the model. Deserialize before rendering or make the template accept JSON strings.

Useful? React with 👍 / 👎.

is_vision = config.is_vision,
n_ctx = request.max_seq_length,
chat_template_override = request.chat_template_override,
chat_template_override = effective_chat_template_override,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid persisting the auto template as a user override

Passing the bundled template through the regular chat_template_override field stores it on llama_backend.chat_template_override; the status endpoint exposes that value, and the frontend hydrates a null custom override from status.chat_template_override, so after loading an auto-overridden Gemma 4 model the store starts treating the bundled template as an explicit user override. Subsequent model loads then send that non-empty template back as chat_template_override, which can apply the Gemma template to unrelated GGUF models. Track the bundled override separately or suppress it from the user-facing override status.

Useful? React with 👍 / 👎.

{%- set captured_content -%}
{%- if message.get('content') is string -%}
{%- if role == 'model' -%}
{{- strip_thinking(message['content']) -}}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve prior thinking when the toggle is enabled

When preserve_thinking=true and a normal prior assistant turn is sent back with <think>...</think> in its content, this unconditional strip_thinking() call removes the reasoning before llama-server sees the history. The local GGUF stream wraps reasoning tokens in these tags, so the advertised Preserve thinking toggle remains ineffective for ordinary multi-turn chats that did not involve a tool call; skip stripping when preserve_thinking is enabled or re-emit those thoughts through the template.

Useful? React with 👍 / 👎.

- /status no longer surfaces Studio's auto-applied bundled template as a
  user-authored chat_template_override. The frontend adopts that field as
  editable state and would otherwise re-send the gemma-4 template as an explicit
  override for a later, unrelated model. /status now reports None when the live
  override equals the model's auto-resolved bundled template.
- When a bundled family template is in effect, strip an inherited
  --chat-template-file from llama_extra_args too (not only when the raw request
  set chat_template_override). Otherwise a stale inherited template, appended
  last, shadows the bundled one while Studio reports the bundled template's
  capabilities.
- Write the temp chat-template file as UTF-8 explicitly, and keep the bundled
  templates ASCII (replaced em dashes), so non-UTF-8 Windows locales cannot raise
  UnicodeEncodeError or emit a mis-encoded template. Added an ASCII guard test.
@danielhanchen

Copy link
Copy Markdown
Member Author

Ran a 10-reviewer pass over this PR and addressed the three P1 findings it surfaced. All are in the latest commits, with a regression test added for each:

  1. /status leaked the bundled template as a user override. The auto-applied Gemma 4 template was stored in llama_backend.chat_template_override and returned verbatim by /status, so a refresh while a Gemma 4 GGUF was loaded could persist the bundled template into frontend state and then send it as an explicit override for a later non-Gemma model. get_status() now suppresses the reported override when it equals what the resolver would auto-apply for the loaded model (reports None), while supports_preserve_thinking stays True so the toggle still appears.

  2. Inherited --chat-template-file could shadow the bundled override. Reload/apply of the same Gemma 4 GGUF after a prior load that carried --chat-template-file in llama_extra_args left the stale arg in place; since extra args are appended after Studio's generated --chat-template-file, llama.cpp last-wins parsing could run the stale template while Studio reported bundled-template capabilities. The inherited extra-args strip now also triggers when an effective (auto) override is present, not only when the raw request field was set.

  3. Bundled templates were written with the platform default encoding. The temp file for --chat-template-file used NamedTemporaryFile(mode="w", ...) with no explicit encoding. The templates are now ASCII (em dashes replaced with hyphens) and the temp write pins encoding="utf-8", with an ASCII guard test so this cannot regress.

All Gemma 4 template-override tests pass (38), along with the test_llama_server_args and test_gguf_reload_inheritance suites (221), and the /status fix was verified live: loading unsloth/gemma-4-E2B-it-GGUF returns chat_template_override: null with supports_preserve_thinking: true.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8b84fcdd84

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +1236 to +1241
_effective_cto = (
effective_chat_template_override
if effective_chat_template_override is not None
else request.chat_template_override
)
if (_effective_cto or None) != (llama_backend.chat_template_override or None):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Strip stale template extras before deduping

When a same-model Gemma 4 load was started with llama_extra_args containing --chat-template-file, LlamaCppBackend stores the bundled chat_template_override even though the later extra arg wins on the llama-server CLI. This new effective-template comparison can therefore match, and the later inherited-extra stale check still calls strip_shadowing_flags without strip_template, so an Apply that omits llama_extra_args returns already_loaded and never reaches the fixed reload-time stripping. Fresh evidence: the current _request_matches_loaded_settings path still omits template stripping in its stale-extra check, leaving the stale file active while Studio reports bundled-template capabilities.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The inherit-path stale check right below this (the if request.llama_extra_args is None branch) already covers it. It calls strip_shadowing_flags(backend_extra, strip_split_mode=...), and strip_template defaults to True in that helper, so an inherited --chat-template-file is stripped from backend_extra. The stripped list then differs from backend_extra, the check returns False, and the load reloads instead of returning already_loaded, so the reload-time stripping does run and the stale template never stays active.

The effective-template equality on this line only short-circuits the template comparison itself; it does not skip the stale-extra check beneath it.

Verified directly: strip_shadowing_flags(['--chat-template-file', '/tmp/old.jinja'], strip_split_mode=False) returns [], which is != backend_extra, so _request_matches_loaded_settings returns False and forces the reload.

@danielhanchen
danielhanchen merged commit a70146d into main Jun 12, 2026
50 of 51 checks passed
@danielhanchen
danielhanchen deleted the gemma4-studio-chat-template-override branch June 12, 2026 12:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant