Repository navigation
Studio: bundle Gemma 4 chat templates (E2B/E4B + larger) and auto-apply to unsloth/gemma-4-*-GGUF - #6245
Conversation
…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.
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
💡 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 |
There was a problem hiding this comment.
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 👍 / 👎.
| effective_chat_template_override = resolve_effective_chat_template_override( | ||
| model_identifier = model_identifier, | ||
| user_override = request.chat_template_override, |
There was a problem hiding this comment.
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).
…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.
|
Rebased onto latest Addressed the review feedback, all three were valid:
Tests: 36 pass for the new suite; |
There was a problem hiding this comment.
💡 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, |
There was a problem hiding this comment.
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 👍 / 👎.
| {%- 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." |
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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']) -}} |
There was a problem hiding this comment.
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.
….com/unslothai/unsloth into gemma4-studio-chat-template-override
|
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:
All Gemma 4 template-override tests pass (38), along with the |
There was a problem hiding this comment.
💡 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".
| _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): |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
What
Studio now ships bundled Gemma 4 chat templates and applies them to
unsloth/gemma-4-*-GGUFmodels at llama-server launch via--chat-template-file. The templates are based on Google's Gemma 4 chat-template update (HFgoogle/gemma-4-31B-itdiscussion #118), which adds thepreserve_thinkingflag. We defaultpreserve_thinkingto off.Why
The chat templates baked into the already-shipped
unsloth/gemma-4-*-GGUFquants predate thepreserve_thinkingflag. Studio only renders the "Preserve thinking" toggle when the active template containspreserve_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/31Bfamily emits an empty<|channel>thought<channel|>block whenenable_thinkingis false, whileE2B/E4Bdeliberately omit it (verified againstgoogle/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/31BGGUFs (emits the empty thought block on thinking-off).studio/backend/assets/chat_templates/gemma-4-edge.jinja->E2B/E4BGGUFs (omits it). Identical togemma-4.jinjaapart from that block.Both add
preserve_thinking(default false) and the upstream PR #118 robustness fixes. The one deliberate divergence from upstream ispreserve_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 userchat_template_overridestill wins.studio/backend/routes/inference.py: resolves the effective override once, ahead of the reload-dedup check and bothload_modelcalls, so the live backend and the incoming request compare against the same template text (no spurious reloads).studio/backend/core/inference/llama_cpp.py: defaultspreserve_thinkingoff in the launch-timechat_template_kwargs, so direct OpenAI-compatible callers match the UI default. The frontend already defaults the toggle off and forwardspreserve_thinkingper request, so no frontend change is needed.pyproject.toml: ship the assets viapackage-data.Tests
studio/backend/tests/test_gemma4_chat_template_override.pycovers the matcher and edge matcher, per-family resolver routing, user-override precedence, asset capability detection (detect_reasoning_flags->supports_preserve_thinking), thepreserve_thinkingJinja 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:--chat-template-file <bundled> --chat-template-kwargs {"enable_thinking": true, "preserve_thinking": false}/statusreportssupports_preserve_thinking: true