-
Notifications
You must be signed in to change notification settings - Fork 778
fix(inference): handle null content and propagate reasoning from thinking models #2353
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jgreer013
wants to merge
2
commits into
main
Choose a base branch
from
jgreer013/fix-null-content-thinking-models
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -14,9 +14,11 @@ | |
|
|
||
| import copy | ||
| from collections.abc import Callable | ||
| from functools import lru_cache | ||
| from pathlib import Path | ||
| from typing import Any | ||
|
|
||
| import jinja2 | ||
| import PIL.Image | ||
| import transformers | ||
| from typing_extensions import override | ||
|
|
@@ -29,6 +31,38 @@ | |
| from oumi.utils.logging import logger | ||
| from oumi.utils.str_utils import truncate_to_max_tokens_limit | ||
|
|
||
| _REASONING_FIELD_NAMES = frozenset({"reasoning", "reasoning_content"}) | ||
| _jinja_env = jinja2.Environment() | ||
|
|
||
|
|
||
| @lru_cache(maxsize=8) | ||
| def _template_references_reasoning(template: str) -> bool: | ||
| """Check if a Jinja2 template references reasoning fields on messages. | ||
|
|
||
| Parses the template AST and walks it to find attribute access | ||
| (``message.reasoning_content``) or item access | ||
| (``message['reasoning']``) nodes that reference reasoning fields. | ||
| This avoids false positives from comments or unrelated text. | ||
| """ | ||
| from jinja2.nodes import Const, Getattr, Getitem, Node | ||
|
|
||
| try: | ||
| ast = _jinja_env.parse(template) | ||
| except jinja2.TemplateSyntaxError: | ||
| return False | ||
|
|
||
| pending: list[Node] = [ast] | ||
| while pending: | ||
| node = pending.pop() | ||
| if isinstance(node, Getattr): | ||
| if node.attr in _REASONING_FIELD_NAMES: | ||
| return True | ||
| elif isinstance(node, Getitem): | ||
| if isinstance(node.arg, Const) and node.arg.value in _REASONING_FIELD_NAMES: | ||
| return True | ||
| pending.extend(node.iter_child_nodes()) | ||
| return False | ||
|
|
||
|
|
||
| class DefaultProcessor(BaseProcessor): | ||
| """Default implementation of processor that wraps a worker processor. | ||
|
|
@@ -226,12 +260,48 @@ def __call__( | |
| ) | ||
| return result | ||
|
|
||
| def _template_supports_reasoning(self) -> bool: | ||
| """Check if the chat template natively handles reasoning fields. | ||
|
|
||
| Parses the Jinja2 AST to find actual variable references to | ||
| ``reasoning`` or ``reasoning_content`` on message objects, avoiding | ||
| false positives from comments or unrelated text. | ||
| """ | ||
| return _template_references_reasoning(self.chat_template) | ||
|
|
||
| def _convert_messages_to_dicts(self, messages: list[Message]) -> list[dict]: | ||
| """Converts Message objects to dict format for HuggingFace compatibility.""" | ||
| return [ | ||
| msg.model_dump(mode="json", exclude_none=True, exclude_unset=True) | ||
| for msg in messages | ||
| ] | ||
| """Converts Message objects to dict format for HuggingFace compatibility. | ||
|
|
||
| When a message has ``reasoning_content``, the behavior depends on | ||
| whether the chat template natively supports reasoning fields: | ||
|
|
||
| - **Template supports reasoning** (e.g., Qwen3): both | ||
| ``reasoning_content`` and ``reasoning`` keys are included so the | ||
| template can render them natively (typically inside ``<think>`` | ||
| tags). | ||
| - **Template does not support reasoning** (e.g., Llama, DeepSeek): | ||
| reasoning is prepended to ``content`` wrapped in ``<think>`` tags | ||
| so it appears in the tokenized sequence. | ||
| """ | ||
| template_supports = self._template_supports_reasoning() | ||
| result = [] | ||
| for msg in messages: | ||
| d = msg.model_dump(mode="json", exclude_none=True, exclude_unset=True) | ||
| if msg.reasoning_content is not None: | ||
| if template_supports: | ||
| # Pass as separate keys — template handles formatting. | ||
| if "reasoning" not in d: | ||
| d["reasoning"] = msg.reasoning_content | ||
| else: | ||
| # Fold into content — template doesn't know about | ||
| # reasoning, so we prepend it with <think> tags. | ||
| d.pop("reasoning_content", None) | ||
| content = d.get("content", "") | ||
| d["content"] = ( | ||
| f"<think>\n{msg.reasoning_content}\n</think>\n\n{content}" | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Do all models use |
||
| ) | ||
|
jgreer013 marked this conversation as resolved.
|
||
| result.append(d) | ||
| return result | ||
|
|
||
| @override | ||
| def apply_chat_template( | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nit: is it possible to move imports to the top?