Skip to content

feat(backends): Adds native thinking parser with truncated-reasoning fallback - #1801

Open
rafvasq wants to merge 3 commits into
generative-computing:mainfrom
rafvasq:feat/native-thinking-parser
Open

rafvasq wants to merge 3 commits into
generative-computing:mainfrom
rafvasq:feat/native-thinking-parser

Conversation

@rafvasq

@rafvasq rafvasq commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Pull Request

Issue

Closes #1604, with follow-up issues opened #1799 and #1800.

Description

Improves thinking/answer parsing on the non-streaming LocalHFBackend chat path:

  1. Transformers-native parsing — _native_parse_thinking() calls tokenizer.parse_response() when the tokenizer declares a response_template, falling back to string splitting on no template, parse error, tool calls, or no reasoning to handle any future model that declares a template. post_processing() tries the native parse first, then the string splitter. Remaining #1604 doc/comment pointers are repointed to:

  2. Truncated-reasoning fallback — _prompt_opens_think() detects a prompt that ends inside an unclosed <think> block (e.g. granite-4.2). When generation stops on length before </think>, the unfinished reasoning goes to mot.thinking with an empty mot.value instead of leaking into the answer. Both signals are required: the prompt (or output) opened a <think> block, and generation stopped on length. The prompt-open check decodes the whole prompt, so it is evaluated lazily, only when the splitter would use it.

  3. Structured output guard — the split gate now includes _format is None, so structured output is never split.

  4. Finish-reason ordering — token count and finish-reason derivation now run before the split gate in post_processing(), so mot.generation.finish_reasons is available for the truncation decision.

  5. Length stop detected from every cap source — the finish-reason derivation previously read only ModelOption.MAX_NEW_TOKENS from the per-call options, so a cap set anywhere else produced no "length" and partial reasoning leaked into mot.value. It now resolves the cap the way generate() merges it (_resolve_generation_caps): per-call option or max_length, then a per-call generation_config=, then the model's generation_config. max_new_tokens wins over max_length, and max_length is compared against total sequence length, since it counts the prompt. When nothing is set anywhere, transformers' built-in default cap (20 new tokens) applies.

  6. Small cleanups — a shared _input_ids_tensor() helper replaces five copies of the tensor-vs-mapping idiom, and the two new try sites now treat a mapping without input_ids as the documented fallback instead of raising KeyError.

The how-to (configure-model-options.md) now documents the empty-result.value behavior on a length stop and where the limit can be set.

Testing

  • Tests added to the respective file if code was changed
  • New code has 100% coverage if code was added
  • Ensure existing tests and github automation passes (a maintainer will kick off the github automation when the rest of the PR is populated)

Attribution

  • AI coding assistants used

Adding a new component, requirement, sampling strategy, or tool?

If your PR adds or modifies one of the types below, check the matching box. A checklist of type-specific review items will be posted as a comment.

  • Component
  • Requirement
  • Sampling Strategy
  • Tool

NOTE: Please ensure you have an issue that has been acknowledged by a core contributor and routed you to open a pull request against this repository. Otherwise, please open an issue before continuing with this pull request.

Assisted-by: Claude Code
Signed-off-by: Rafael Vasquez <[email protected]>
@rafvasq
rafvasq requested a review from a team as a code owner November 9, 2026 18:44
@rafvasq rafvasq changed the title Adds native thinking parser with truncated-reasoning fallback feat(backends): Adds native thinking parser with truncated-reasoning fallbackx Nov 9, 2026
@github-actions github-actions Bot added the enhancement New feature or request label Nov 9, 2026
@rafvasq rafvasq changed the title feat(backends): Adds native thinking parser with truncated-reasoning fallbackx feat(backends): Adds native thinking parser with truncated-reasoning fallback Nov 9, 2026

@ajbozarth ajbozarth left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Some feedback from Claude: one regression in the truncation fallback, details inline.

Comment thread mellea/backends/huggingface.py Resolved
Comment thread mellea/backends/huggingface.py Resolved
Comment thread mellea/backends/huggingface.py Resolved
Assisted-by: Claude Code
Signed-off-by: Rafael Vasquez <[email protected]>
@rafvasq
rafvasq requested a review from ajbozarth November 11, 2026 18:11
@ajbozarth
ajbozarth dismissed their stale review November 11, 2026 20:47

Dismissing my changes requested as all my items have been addressed, but I would rather defer approval to Jake

@markstur markstur 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.

Re-checked at debb394a. One correctness gap, one should-fix, and a few smaller items.

Request change

Truncation fallback doesn't fire unless MAX_NEW_TOKENS is in model_options — mellea/backends/huggingface.py:2661-2675 derives "length" only when mot._call.model_options contains MAX_NEW_TOKENS. When the cap comes from model.generation_config (or transformers' default max_length) instead — i.e. the user set it neither per-call nor at backend construction — generation stops mid-reasoning with no EOS, finish_reasons stays None, truncated is False, and the partial reasoning lands in mot.value. That's the scenario this PR exists to fix. The tests always set the option explicitly (test_huggingface_thinking.py:439, 469, 502), so only the option-present path is covered, and the new paragraph in docs/docs/how-to/configure-model-options.md states the empty-result.value behavior unconditionally. Suggested fix: fall back to self._model.generation_config.max_new_tokens when the per-call option is absent.

Should fix

_prompt_opens_think is evaluated eagerly — huggingface.py:2733 computes _prompt_opens_think(tokenizer, input_ids) as an argument on every eligible non-streaming call, but _split_think_tags only reads it when the close tag is absent from the output (:397). In the common case that's a full-prompt tokenizer.decode wasted per call. Computing it only when native is None and truncated and _THINK_CLOSE_TAG not in raw_value keeps it off the hot path.

Comments

  • huggingface.py:2749 — cache_key = id(mot.value) collides across thunks whenever the split yields an empty string: the truncated branch returns the literal "" (:401), which CPython interns as a singleton, so two truncated generations share a cache key. Today cache_get has no production callers (only test_huggingface_thinking.py:686), so the practical effect is an overwritten LRU entry rather than a wrong lookup — but the keying scheme will bite if cache_get gains a caller. Worth keying on something per-thunk.
  • huggingface.py:302 — input_ids["input_ids"] sits outside the try: at 303, so a mapping without that key raises KeyError instead of taking the documented False fallback. Same shape at :332. Hypothetical today (the only caller passes a real BatchEncoding); moving the subscript inside the try would match the contract.
  • huggingface.py:380, 2692, 2709 — the new #1799/#1800 references extend issue-number pointers in mellea/ source comments and docstrings. Per this repo's convention that history belongs in commits, PR descriptions, and tests, these would read better as plain statements of the limitation. The pre-existing #1604 refs are inherited; the new lines add more.
  • The tensor-vs-dict normalization idiom (input_ids if isinstance(input_ids, torch.Tensor) else input_ids["input_ids"]) now appears five times (:302, :332, :2466, :2593, :2634), two of them added here. A module-level helper would keep any future fix (e.g. the KeyError guard above) in one place.
  • For the record, since the docstring marks it deliberate: a stop string firing inside the think block (or EOS mid-think) yields "stop", not truncation, so partial reasoning stays in mot.value. The two-signal design documents this tradeoff; fine to leave as is.

🤖 Generated with Claude Code

Signed-off-by: Rafael Vasquez <[email protected]>
Assisted-by: Claude Code
@rafvasq
rafvasq requested a review from markstur November 23, 2026 20:54
@markstur
markstur dismissed their stale review November 24, 2026 22:05

Blockers are fixed

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: implement better hugging face output parsing

3 participants