Repository navigation
Studio: stop chat generation on the assistant-turn-end token (fixes Qwen3.5 loop) - #6804
Conversation
A small chat model (e.g. Qwen3.5-0.8B) looped on the safetensors path: it emitted a valid response or tool call, then ran past its turn and re-emitted the call, hallucinating <|im_start|>user turns. Root cause: the model's tokenizer.eos_token is synced to the config document terminator (<|endoftext|>, 248044) while chat turns actually end with <|im_end|> (248046), so generate_stream's single eos_token_id never stopped at the turn boundary. Stop on every assistant-turn-end marker the vocab defines (tokenizer.eos plus <|im_end|>, <|eot_id|>, <end_of_turn>, ...). Verified on the real weights: the single-eos control loops (400 tokens) while the fixed set yields a clean 38-token tool call and a clean answer from the tool result. No-op when eos is already the turn-ender (the id just dedups).
There was a problem hiding this comment.
Code Review
This pull request introduces a mechanism to stop chat generation on canonical assistant-turn-end markers (such as <|im_end|> or <|eot_id|>) even when the tokenizer's eos_token_id is set to a bare document terminator, preventing models from running past their turn and looping. Unit tests have been added to verify this behavior. The review feedback highlights a critical performance issue: calling tokenizer.get_vocab() on every generation request is highly inefficient due to vocabulary serialization overhead. It is recommended to cache the resolved end-of-sequence IDs on the tokenizer instance and defensively guard against a None tokenizer.
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 _chat_turn_end_eos_ids(tokenizer) -> list[int]: | ||
| """tokenizer.eos plus any canonical chat turn-end markers in the vocab; unk / | ||
| missing tokens dropped. Empty only if the tokenizer exposes no usable ids.""" | ||
| ids: set[int] = set() | ||
| eos = getattr(tokenizer, "eos_token_id", None) | ||
| if isinstance(eos, (list, tuple)): | ||
| ids.update(int(t) for t in eos if t is not None) | ||
| elif eos is not None: | ||
| ids.add(int(eos)) | ||
| try: | ||
| vocab = tokenizer.get_vocab() | ||
| except Exception: | ||
| vocab = {} | ||
| unk = getattr(tokenizer, "unk_token_id", None) | ||
| for tok_str in _CHAT_TURN_END_TOKENS: | ||
| if tok_str in vocab: | ||
| tid = tokenizer.convert_tokens_to_ids(tok_str) | ||
| if tid is not None and tid != unk: | ||
| ids.add(int(tid)) | ||
| return sorted(ids) |
There was a problem hiding this comment.
Calling tokenizer.get_vocab() on every single generation request is highly inefficient. For fast tokenizers (which are standard in Hugging Face and Unsloth), get_vocab() is implemented in Rust and must serialize the entire vocabulary (often 100k+ tokens, e.g., 151,643 for Qwen, 128,256 for Llama 3) into a new Python dictionary on every single call. This can take 5-15ms of CPU time per call, which blocks the Python GIL and adds significant latency to every single request, especially under concurrent load.
Additionally, we should defensively guard against tokenizer being None to prevent potential AttributeError crashes.
Since the tokenizer's vocabulary and special tokens do not change after loading, we can cache the resolved _chat_turn_end_eos_ids list on the tokenizer instance itself.
def _chat_turn_end_eos_ids(tokenizer) -> list[int]:
"""tokenizer.eos plus any canonical chat turn-end markers in the vocab; unk /
missing tokens dropped. Empty only if the tokenizer exposes no usable ids."""
if tokenizer is None:
return []
cached = getattr(tokenizer, "_cached_chat_turn_end_eos_ids", None)
if cached is not None:
return cached
ids: set[int] = set()
eos = getattr(tokenizer, "eos_token_id", None)
if isinstance(eos, (list, tuple)):
ids.update(int(t) for t in eos if t is not None)
elif eos is not None:
ids.add(int(eos))
try:
vocab = tokenizer.get_vocab()
except Exception:
vocab = {}
unk = getattr(tokenizer, "unk_token_id", None)
for tok_str in _CHAT_TURN_END_TOKENS:
if tok_str in vocab:
tid = tokenizer.convert_tokens_to_ids(tok_str)
if tid is not None and tid != unk:
ids.add(int(tid))
result = sorted(ids)
try:
tokenizer._cached_chat_turn_end_eos_ids = result
except Exception:
pass
return resultThere was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4d1bb6e937
ℹ️ 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".
| "<|eot_id|>", # Llama 3.x | ||
| "<|eom_id|>", # Llama 3.x tool turns | ||
| "<end_of_turn>", # Gemma | ||
| "<|end|>", # Phi |
There was a problem hiding this comment.
Do not stop Harmony output at channel delimiters
For gpt-oss/Harmony responses that include an analysis channel, <|end|> is only the delimiter before the final channel: the existing HarmonyTextStreamer parses analysis up to <|end|> and then expects <|channel|>final... before streaming the answer. Adding this token to the global EOS set makes model.generate stop as soon as the analysis message ends, so users receive only the thinking block and no final response. Please make the stop set model-family aware, e.g. exclude <|end|> for gpt-oss and stop on its actual turn-return marker instead.
Useful? React with 👍 / 👎.
| if str(_BACKEND) not in sys.path: | ||
| sys.path.insert(0, str(_BACKEND)) | ||
|
|
||
| from core.inference.inference import _chat_turn_end_eos_ids # noqa: E402 |
There was a problem hiding this comment.
Avoid importing the full inference package in this unit test
In the backend CPU test environment this new test is collected without the full Unsloth stack (existing test_training_preflight.py documents stubbing unsloth/trl for that job). Importing core.inference.inference first executes core.inference.__init__ and then inference.py's top-level unsloth/peft imports, so this pure helper test can fail during collection before any assertions run. Move _chat_turn_end_eos_ids into a dependency-light helper module or stub those imports before this line.
Useful? React with 👍 / 👎.
|
Root cause is an upstream Qwen3.5 config gap (not specific to our re-upload):
So This PR is the defensive layer: it stops on the turn-end token the vocab defines regardless of what a model's config/generation_config declares, so any model with this (common) inconsistency is handled. A complementary model-repo fix (shipping a correct |
Qwen3.5 / Qwen3.6 small chat checkpoints declare the chat turn-end as tokenizer.eos_token (<|im_end|>) but ship config.eos_token_id = <|endoftext|> and no generation_config.json (upstream shipped generation_config only on the large chat models). So every .generate() path that reads generation_config -- the vision path and tool loops, not just generate_stream -- never stops at the turn boundary and loops. At load time, when the tokenizer's own eos is a chat turn-end marker but generation_config.eos_token_id omits it, add it. This fixes the config once for all generation paths and complements the generate_stream turn-end stop. No-op for base models (eos is a plain document terminator) and already-correct configs. Verified on unsloth/Qwen3.5-0.8B: 248044 -> [248044, 248046].
|
Added a Studio-side config override so the fix does not depend on re-uploading model files. Qwen3.5 / Qwen3.6 small chat checkpoints declare the chat turn-end as
So this PR now fixes the eos gap at two levels: the config (all generation paths) and the |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2d0a28db1a
ℹ️ 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".
| Only acts when the tokenizer's own eos is a chat turn-end marker (so base | ||
| models, whose eos is a plain document terminator, are skipped) and that id is | ||
| not already in the current eos set.""" | ||
| if eos_token not in _CHAT_TURN_END_TOKENS or eos_token_id is None: |
There was a problem hiding this comment.
Derive generation-config repair from vocab markers
When the loader has already synced a chat tokenizer's eos_token / eos_token_id to the config document terminator — the Qwen3.5 state described in this PR — this guard returns None before checking that the real turn ender such as <|im_end|> exists in the vocab. The only fallback that scans the vocab is passed explicitly in generate_stream; generation-config-only callers such as _generate_vision_response() still call model.generate() without an eos_token_id, so they keep stopping only on <|endoftext|> and can run through the assistant turn. Please base this repair on the same vocab scan or pass the repaired stop set into those callers.
Useful? React with 👍 / 👎.
| if tok_str in vocab: | ||
| tid = tokenizer.convert_tokens_to_ids(tok_str) | ||
| if tid is not None and tid != unk: | ||
| ids.add(int(tid)) |
There was a problem hiding this comment.
Don't stop on markers just because they share the vocab
This treats mere vocabulary presence as proof that a marker is the current model's turn terminator. Families like Qwen use a unified vocab where base/coder models can contain ChatML control tokens even when their EOS is the document token; in those contexts, asking the model to emit ChatML/tool-training text now stops at the first literal <|im_end|> instead of continuing. Please gate these extra stop IDs on the active chat template/model family rather than every marker present in the tokenizer vocab.
Useful? React with 👍 / 👎.
Address PR review of the turn-end stop handling: - Do not call tokenizer.get_vocab() per generation request (serializes the whole 100k+ vocab). Resolve the turn-end tokens once at load and cache them on model_info; generate_stream reads the cache. - Derive turn-end markers from the chat_template the model actually uses, not raw vocab membership, so a base/coder model that merely carries ChatML control tokens in a shared vocab is not stopped early, and a loader that synced tokenizer.eos to the document terminator is still covered. - Skip harmony/gpt-oss templates: <|end|> there is an intra-message channel delimiter, not the turn end (dropped <|return|> from the marker list too). - Move the logic to a dependency-light module (core.inference.chat_eos) so the unit test does not import the full unsloth/torch inference stack. Verified on unsloth/Qwen3.5-0.8B (gen_config 248044 -> [248044, 248046], clean 38-token tool call with generation_config-only stopping), Phi-3.5 (adds <|end|>), Llama-3 / Qwen3 (unchanged), and a harmony template (left untouched).
|
Reworked the turn-end handling to address the review (568201e):
Verified on Qwen3.5-0.8B (gen_config |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 074193bd63
ℹ️ 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".
| max_seq_length, | ||
| ) | ||
|
|
||
| self._resolve_chat_eos(model_name) |
There was a problem hiding this comment.
Resolve EOS after applying any inference chat template
For models whose template is supplied by MODEL_TO_TEMPLATE_MAPPER, this caches chat_turn_end_eos_ids during load before the text path later calls get_chat_template(...) in _generate_chat_response_inner. If the loaded tokenizer does not already have that template, the resolver only sees the original eos_token_id, while generation formats prompts with the mapped template's turn-end marker (for example ChatML/Llama markers), so those requests still stop only on the document EOS and can run past the assistant turn. Resolve after applying the same template, or re-resolve when the template is installed.
Useful? React with 👍 / 👎.
| """ | ||
| info = self.models.get(model_name) or {} | ||
| model = info.get("model") | ||
| tokenizer = info.get("tokenizer") |
There was a problem hiding this comment.
Read multimodal templates before unwrapping processors
For vision models whose processor owns the multimodal chat_template, _generate_vision_response renders prompts with processor.apply_chat_template(...), but this unwraps the processor to its inner tokenizer before resolving stop IDs. If that tokenizer does not carry the processor's template, the cached EOS list only contains the original document EOS, so those VLM generations still run past the processor template's assistant turn-end marker. Resolve against the processor template while using the tokenizer for token IDs, or check both objects.
Useful? React with 👍 / 👎.
| if not isinstance(template, str) or any(h in template for h in _HARMONY_MARKERS): | ||
| return sorted(ids) |
There was a problem hiding this comment.
Handle dict chat templates before returning EOS unchanged
When a tokenizer exposes multiple chat templates as a dict (for example separate default/tool-use templates), this branch returns only tokenizer.eos_token_id without inspecting any template body. For any such model whose selected template contains <|im_end|>, <|eot_id|>, or another turn-end marker while the config EOS remains a document terminator, the generation path still runs past the assistant turn. Iterate the dict values or resolve the selected template before deciding no marker is present.
Useful? React with 👍 / 👎.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 074193bd63
ℹ️ 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".
| from core.inference.chat_eos import ( # noqa: E402 | ||
| chat_eos_repair, | ||
| resolve_chat_turn_end_eos_ids, | ||
| ) |
There was a problem hiding this comment.
Avoid importing the full inference package in this unit test
In lightweight unit-test environments where the full Studio runtime stack is not installed, from core.inference.chat_eos first executes core/inference/__init__.py, which imports the orchestrator/llama_cpp logging stack before this dependency-light helper is reached; for example, test collection fails here with ModuleNotFoundError: structlog instead of exercising chat_eos. Load chat_eos.py via importlib.util.spec_from_file_location (as other dependency-light backend tests do) or make the package init lazy so this test remains isolated.
Useful? React with 👍 / 👎.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 074193bd63
ℹ️ 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".
| max_seq_length, | ||
| ) | ||
|
|
||
| self._resolve_chat_eos(model_name) |
There was a problem hiding this comment.
Resolve EOS after applying the effective chat template
For models in MODEL_TO_TEMPLATE_MAPPER whose tokenizer does not already ship a chat_template, the effective template is installed later in generate_chat_response via get_chat_template(...), but this new cache is computed here during load. In that scenario resolve_chat_turn_end_eos_ids sees an empty template and stores only the document EOS; generate_stream then uses that stale truthy list instead of recomputing, so mapped ChatML/Qwen-style models can still run past <|im_end|> and loop. Resolve after applying the same template, or refresh the cached IDs when the template is applied.
Useful? React with 👍 / 👎.
| if not isinstance(template, str) or any(h in template for h in _HARMONY_MARKERS): | ||
| return sorted(ids) |
There was a problem hiding this comment.
Handle multi-template chat_template values
When tokenizer.chat_template is a dict/list of template variants (a form this repo already handles in unsloth/tokenizer_utils.py:1284), this branch returns only tokenizer.eos_token_id without scanning any of the actual template strings. For multi-template chat models whose selected template ends turns with <|im_end|> or <|eot_id|> while EOS is a document token, the cached stop list stays incomplete and generate_stream still runs past the assistant turn boundary. Flatten or select the variant template strings before deciding there are no turn-end markers.
Useful? React with 👍 / 👎.
| tokenizer = info.get("tokenizer") | ||
| tokenizer = getattr(tokenizer, "tokenizer", tokenizer) # unwrap processors |
There was a problem hiding this comment.
Preserve processor-level chat templates
For VLMs whose ProcessorMixin owns the chat template, unwrapping to processor.tokenizer before resolving EOS drops the template that _generate_vision_response later uses via processor.apply_chat_template(...). In that case the generation config is never repaired with the image/chat turn-end token, so image requests on those processors can still run past the assistant boundary even though the template contains the stop marker. Prefer the processor when it has chat_template, and only fall back to the nested tokenizer when it does not.
Useful? React with 👍 / 👎.
For a MODEL_TO_TEMPLATE_MAPPER model whose own tokenizer ships no chat_template, the effective template is applied at generate time via get_chat_template, but the turn-end eos ids were resolved once at load when the template was still empty, so only the document eos was cached. Qwen2.5 / Yi base checkpoints (eos <|endoftext|>, ChatML turns end with <|im_end|>) then run past the assistant boundary in generate_stream and loop. Re-resolve the turn-end eos from the now-templated tokenizer and refresh the cached ids right after applying the mapper template, so generate_stream stops at the ChatML turn end. Add a regression test.
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep it up! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8ad09fe3d2
ℹ️ 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".
| info = self.models.get(model_name) or {} | ||
| model = info.get("model") | ||
| tokenizer = info.get("tokenizer") | ||
| tokenizer = getattr(tokenizer, "tokenizer", tokenizer) # unwrap processors |
There was a problem hiding this comment.
Resolve EOS from processor templates before unwrapping
For vision processors that keep chat_template on the processor rather than the nested raw tokenizer, this unwrap happens before resolve_chat_turn_end_eos_ids() can inspect the effective template. In that scenario the cache only contains the document EOS and generation_config is not repaired, while _generate_vision_response later formats with processor.apply_chat_template() and calls model.generate() without an explicit eos_token_id. Those VLMs can still run past <|im_end|>/<end_of_turn> even though this load-time repair is meant to cover generation_config-based paths.
Useful? React with 👍 / 👎.
| from core.inference.chat_eos import ( # noqa: E402 | ||
| chat_eos_repair, | ||
| resolve_chat_turn_end_eos_ids, | ||
| ) |
There was a problem hiding this comment.
Import the helper without loading core.inference
This test is meant to exercise the dependency-light chat_eos helper without the full inference stack, but importing core.inference.chat_eos first executes core/inference/__init__.py, which pulls in the orchestrator/GGUF backend and their runtime dependencies. In a lightweight backend test environment this fails during collection before the helper tests run; load the module directly or make the package init lazy so the advertised dependency-light unit remains runnable.
Useful? React with 👍 / 👎.
| model_info["chat_turn_end_eos_ids"] = resolve_chat_turn_end_eos_ids( | ||
| getattr(tokenizer, "tokenizer", tokenizer) | ||
| ) |
There was a problem hiding this comment.
Preserve load-time marker IDs when refreshing mapped templates
For mapper models whose tokenizer already had a chat template, this refresh can overwrite a correct load-time cache with IDs from the tokenizer returned by get_chat_template(). Templates such as Gemma/ChatML can return a patched tokenizer that remaps the turn-end token onto the EOS id; because generate_stream() later re-fetches model_info['tokenizer'] instead of this returned tokenizer, the refreshed list can drop the original <end_of_turn>/<|im_end|> id and generation again runs past the actual turn marker. Merge with the existing cache or resolve against the tokenizer that will be used for generation.
Useful? React with 👍 / 👎.
…erwriting get_chat_template can return a different tokenizer whose vocab was remapped (Gemma folds <end_of_turn> onto the eos id), while generate_stream re-reads the original model_info tokenizer. Overwriting the cache with the refreshed set dropped a valid load-time id (e.g. <end_of_turn>=107) and let generation run past the real turn marker. Union the refresh into the existing cache so it can only add ids, never drop a valid one. Add a regression test covering the destructive-swap case the prior test missed.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ea45b825cc
ℹ️ 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".
| _CHAT_TURN_END_TOKENS = ( | ||
| "<|im_end|>", # ChatML: Qwen, Yi | ||
| "<|eot_id|>", # Llama 3.x | ||
| "<|eom_id|>", # Llama 3.x tool turns | ||
| "<end_of_turn>", # Gemma | ||
| "<|end|>", # Phi | ||
| ) |
There was a problem hiding this comment.
Include all mapped turn-end markers
This allowlist misses turn terminators already used by Studio's mapped templates, e.g. Starling uses <|end_of_turn|> and Gemma-4 uses <turn|> in unsloth/chat_templates.py, while those templates are registered with map_eos_token=False. For those checkpoints, when tokenizer.eos_token_id is still a document EOS rather than the chat turn marker, resolve_chat_turn_end_eos_ids() returns only the document EOS and generation can still run past the assistant boundary, which is the failure mode this change is trying to prevent. Please add the remaining mapped turn-end tokens or derive this list from the template registry.
Useful? React with 👍 / 👎.
| from core.inference.chat_eos import ( # noqa: E402 | ||
| chat_eos_repair, | ||
| resolve_chat_turn_end_eos_ids, | ||
| ) |
There was a problem hiding this comment.
Avoid importing the full inference stack in helper tests
Although this helper is described as dependency-light, importing it through core.inference.chat_eos first executes core/inference/__init__.py, which imports the orchestrator/GGUF backend and their Studio dependencies. In a focused unit-test environment that has pytest but not the full backend stack, collection fails before reaching these tests (for example on structlog), so the dependency-light helper cannot be validated in isolation. Import the module without triggering the package initializer or make the package initializer lazy.
Useful? React with 👍 / 👎.
| refreshed = resolve_chat_turn_end_eos_ids( | ||
| getattr(tokenizer, "tokenizer", tokenizer) | ||
| ) | ||
| existing = model_info.get("chat_turn_end_eos_ids") or [] | ||
| model_info["chat_turn_end_eos_ids"] = sorted(set(existing) | set(refreshed)) |
There was a problem hiding this comment.
Resolve refreshed stop IDs on the generation tokenizer
For mapper templates that remap EOS inside get_chat_template (for example the built-in chatml template is registered with map_eos_token=True), this resolves <|im_end|> on the returned, remapped tokenizer instead of the original tokenizer that generate_stream() later uses from model_info. If the load-time cache only contained the document EOS because the original tokenizer had no template, the refreshed set can still be just the document EOS and omit the original tokenizer's real <|im_end|> id, so those mapped ChatML models still run past the assistant boundary.
Useful? React with 👍 / 👎.
…dd Gemma-4 marker Two residual gaps in the turn-end eos refresh: - For map_eos_token=True mapped templates (e.g. chatml on a Yi-6B base), get_chat_template returns a tokenizer whose vocab folds the turn-end token onto the document eos id, while generate_stream re-reads the original tokenizer. The refresh resolved ids on the returned tokenizer, so it stored the doc eos and missed the real turn-end id, and generation ran past the boundary. Read the turn-end marker strings from the mapped template but resolve their ids on the original generation tokenizer (new resolve_chat_turn_end_eos_ids_using). - Add Gemma-4's <turn|> turn terminator to the marker allowlist; those templates keep a document eos so resolve otherwise missed the real turn marker. Add regression tests for both.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 688d169452
ℹ️ 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".
| if str(_BACKEND) not in sys.path: | ||
| sys.path.insert(0, str(_BACKEND)) | ||
|
|
||
| from core.inference.chat_eos import ( # noqa: E402 |
There was a problem hiding this comment.
Import the helper without package side effects
This test is meant to keep chat_eos dependency-light, but importing core.inference.chat_eos first executes core/inference/__init__.py, which imports the orchestrator/GGUF backends and optional runtime deps. In a lightweight unit-test environment, collection fails before the helper is exercised with ModuleNotFoundError: structlog; use a direct importlib load of chat_eos.py or make core.inference lazy so this helper test stays independent.
Useful? React with 👍 / 👎.
| info = self.models.get(model_name) or {} | ||
| model = info.get("model") | ||
| tokenizer = info.get("tokenizer") | ||
| tokenizer = getattr(tokenizer, "tokenizer", tokenizer) # unwrap processors |
There was a problem hiding this comment.
Resolve VLM templates before unwrapping processors
When a vision processor owns the chat template but the nested tokenizer does not (the existing MLX path handles Qwen2.5-VL-style processors this way), unwrapping here makes resolve_chat_turn_end_eos_ids inspect an empty tokenizer template and skip the <|im_end|>/turn-end repair. The image path later formats prompts with processor.apply_chat_template but calls model.generate without an explicit eos_token_id, so generation_config remains on the document EOS and these VLM turns can still run past the assistant boundary.
Useful? React with 👍 / 👎.
| if not isinstance(template, str) or any(h in template for h in _HARMONY_MARKERS): | ||
| return sorted(ids) |
There was a problem hiding this comment.
Handle dict chat_template variants
When tokenizer.chat_template is a multi-variant dict/list rather than a single string (the tokenizer utilities explicitly support Hermes-style {default, tool_use} templates), this early return ignores marker strings inside the selected variants. For any such model whose configured EOS is a document terminator while the variant template ends turns with <|eot_id|>/<|im_end|>, neither generation_config nor generate_stream gets the turn-end id, so the loop this change is meant to stop can still run to max_new_tokens.
Useful? React with 👍 / 👎.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 688d169452
ℹ️ 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".
| model = info.get("model") | ||
| tokenizer = info.get("tokenizer") | ||
| tokenizer = getattr(tokenizer, "tokenizer", tokenizer) # unwrap processors | ||
| if model is None or tokenizer is None: |
There was a problem hiding this comment.
Preserve processor chat templates when resolving EOS
When loading a VLM/audio processor whose chat template is stored on the processor rather than on processor.tokenizer, this unwrap discards the object that contains the template. _generate_vision_response renders with the processor's template, but _resolve_chat_eos caches only the raw tokenizer's document EOS and leaves model.generation_config unrepaired, so those image turns can still run past <|im_end|>/<end_of_turn> until max_new_tokens. Resolve marker strings from the processor and ids from the raw tokenizer instead.
Useful? React with 👍 / 👎.
| "<|im_end|>", # ChatML: Qwen, Yi | ||
| "<|eot_id|>", # Llama 3.x | ||
| "<|eom_id|>", # Llama 3.x tool turns | ||
| "<end_of_turn>", # Gemma |
There was a problem hiding this comment.
Include Starling's turn-end marker
The repo maps Starling models to the starling template, and that template terminates turns with <|end_of_turn|> (unsloth/chat_templates.py). Because this allow-list only includes Gemma's unbarred <end_of_turn>, the mapper refresh never adds Starling's stop id when the tokenizer EOS is not already that token, so Starling can still generate past the assistant boundary into the next turn. Add the barred marker to this tuple.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
All fixed: added Starling/OpenChat's barred <|end_of_turn|>, flattened dict/list multi-variant templates so all variants are scanned, and made the vision path read markers from the processor container while resolving ids on the generation tokenizer. The dependency-light tests now collect via a lazy package init, and the backend-constructing refresh test skips cleanly when unsloth is absent. Regression tests added for each.
| (doc-eos) id and let generation run past the real turn marker.""" | ||
| ids = _eos_id_set(getattr(id_tokenizer, "eos_token_id", None)) | ||
| template = getattr(template_tokenizer, "chat_template", None) or "" | ||
| if not isinstance(template, str) or any(h in template for h in _HARMONY_MARKERS): |
There was a problem hiding this comment.
Handle multi-variant chat templates
When chat_template is a dict/list (the repo already supports Hermes-3-style variants in fix_chat_template), this branch returns before scanning any template strings. Those tokenizers can still render via apply_chat_template, but if the selected variant ends turns with <|im_end|>/<|eot_id|> while eos_token_id is the document EOS, the new cache remains stale and generation continues into another turn. Iterate the string values/templates instead of treating non-strings as no template.
Useful? React with 👍 / 👎.
|
Thanks for the review. I checked the chat-EOS flags (inference.py processor and VLM template, chat_eos.py dict and list template, chat_eos.py Starling marker) against the real model configs. Each one needs a Studio-supported model whose document EOS differs from its chat turn-end marker for that template shape, and none does:
Since none of these reach a real model, they do not affect generation, so I am leaving the code as is. |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 688d169452
ℹ️ 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".
| info = self.models.get(model_name) or {} | ||
| model = info.get("model") | ||
| tokenizer = info.get("tokenizer") | ||
| tokenizer = getattr(tokenizer, "tokenizer", tokenizer) # unwrap processors |
There was a problem hiding this comment.
Resolve processor chat templates before unwrapping
When a vision model stores its chat template on the ProcessorMixin (the same object _generate_vision_response later calls processor.apply_chat_template on) but the inner tokenizer has no chat_template, unwrapping here makes resolve_chat_turn_end_eos_ids inspect the wrong object and cache only the document EOS. Because the vision path does not pass an explicit eos_token_id to model.generate, those models still won't get generation_config repaired to stop on their turn-end token.
Useful? React with 👍 / 👎.
| if str(_BACKEND) not in sys.path: | ||
| sys.path.insert(0, str(_BACKEND)) | ||
|
|
||
| from core.inference.chat_eos import ( # noqa: E402 |
There was a problem hiding this comment.
Keep dependency-light tests off inference init
In lightweight/no-torch backend test runs, this import still executes core/inference/__init__.py before loading chat_eos, which imports the orchestrator/GGUF backend and their Studio dependencies; the new “dependency-light” test therefore fails during collection if those deps are absent even though chat_eos.py itself is standalone. Load the module without the package initializer or make the package initializer lazy so this unit test remains runnable without the full inference stack.
Useful? React with 👍 / 👎.
| template = getattr(template_tokenizer, "chat_template", None) or "" | ||
| if not isinstance(template, str) or any(h in template for h in _HARMONY_MARKERS): | ||
| return sorted(ids) |
There was a problem hiding this comment.
Inspect multi-template chat_template containers
When tokenizer.chat_template is a valid multi-template container (for example the dict/list forms that this repo's tokenizer utilities handle for variants such as {default, tool_use}), this early non-string return skips every variant and caches only the tokenizer EOS. If any selected variant ends assistant turns with <|im_end|>, <end_of_turn>, etc. while EOS is still a document terminator, those models keep the same run-past-turn behavior this helper is meant to fix.
Useful? React with 👍 / 👎.
…es; keep tests collectable The turn-end marker set missed OpenChat/Starling's barred <|end_of_turn|> (distinct from Gemma's unbarred form), so Starling generations ran past the assistant boundary. A dict/list chat_template (Hermes-3 style default+tool_use variants) hit an early non-string return and skipped detection; flatten and scan every variant. Vision models carry the chat_template on the ProcessorMixin, not the unwrapped inner tokenizer, so read markers from the template-carrying container while resolving ids on the generation tokenizer. The refresh test constructs the real backend, so it is guarded with a module-level skip when unsloth/unsloth_zoo is absent (the lightweight pytest matrix), and core.inference package init is made lazy so the dependency-light chat_eos tests collect without the heavy stack.
|
@codex review |
|
Codex Review: Didn't find any major issues. 🚀 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
@codex review |
|
Codex Review: Didn't find any major issues. Another round soon, please! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
@codex review |
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
Problem
Small chat models on the safetensors path could loop: they emitted a valid answer or tool call, then ran past the turn boundary and re-emitted it, hallucinating
<|im_start|>user/<|im_start|>assistantturns. Withunsloth/Qwen3.5-0.8Band tools enabled,can u web search weather in sweden today june 27 2026loops this way (looks like a nudged retry).Root cause (reproduced on the real weights)
Qwen3.5 sets
config.eos_token_idto the document terminator<|endoftext|>(248044), but chat turns actually end with<|im_end|>(248046). When the load path leavestokenizer.eos_token_idat the config value,generate_stream's singleeos_token_idnever stops at the turn boundary, so generation continues into hallucinated turns.Directly measured on
unsloth/Qwen3.5-0.8B:<|endoftext|>only -> runs the full 400-token budget, re-emitting theweb_searchcall (loops).<|im_end|>too -> clean 38-token tool call, then a clean answer from the tool result (40 tokens), no loop.Fix
Stop chat generation on every assistant-turn-end marker the vocab actually defines (
tokenizer.eosplus<|im_end|>,<|eot_id|>,<|eom_id|>,<end_of_turn>,<|end|>,<|return|>). This is a no-op wheneosis already the turn-ender (the id just dedups), and covers ChatML / Llama 3 / Gemma / Phi / harmony families.Validation
unsloth/Qwen3.5-0.8B: with the tokenizer eos forced to<|endoftext|>(the buggy state), the helper still yields[248044, 248046], and the weather tool round-trip is clean (Hiwas already clean).pytest tests/test_chat_turn_end_eos.py(5 passing): ChatML eos-synced-to-endoftext still stops on<|im_end|>, Llama turn-end tokens are added, plain models are unchanged, list eos preserved, unk markers ignored.The GGUF path is untouched; only the transformers path changes.