Skip to content

fix(tokenizer): add add_generation_prompt (fixes #4150)#4298

Open
alphadl wants to merge 2 commits into
unslothai:mainfrom
alphadl:fix/4150-hermes-chat-template
Open

fix(tokenizer): add add_generation_prompt (fixes #4150)#4298
alphadl wants to merge 2 commits into
unslothai:mainfrom
alphadl:fix/4150-hermes-chat-template

Conversation

@alphadl
Copy link
Copy Markdown

@alphadl alphadl commented Mar 14, 2026

fix(tokenizer): add add_generation_prompt to templates with whitespace after endfor

Fixes #4150

What

In _fix_chat_template, the substring after {% endfor %} or {% endif %} is now normalized by stripping leading/trailing whitespace for the condition check. When we insert the {% if add_generation_prompt %}...{% endif %} wrapper, we preserve the original prefix and suffix whitespace so the patched template string keeps the same formatting.

Before: We required after_endfor.startswith("{{"). Templates like {% endfor %}\n{{ '<|im_start|>assistant\n' }} failed the check and were not patched → RuntimeError when loading LoRA for chat.

After: We use after_endfor = after_endfor_raw.strip() for the condition and reassemble as chosen_end + prefix_ws + wrapped + suffix_ws, so ChatML-style templates with newlines or spaces after the loop are correctly patched.

Why

When loading a LoRA adapter (e.g. Hermes fine-tuned with Llama Factory) from a local path, the saved tokenizer's chat template can have a single {{ ... }} block after {% endfor %} with leading/trailing whitespace. The previous logic only patched when the content immediately after the loop started with {{, so these templates were left without add_generation_prompt and fix_chat_template raised:

RuntimeError: Unsloth: The tokenizer `...` does not have a {% if add_generation_prompt %} for generation purposes.

Stripping for the check and preserving whitespace when rebuilding the template fixes this without changing behaviour for templates that already have no surrounding whitespace.

Impact

  • Users loading Hermes (or similar ChatML) LoRA for chat/inference: No more RuntimeError when the saved tokenizer template has newlines or spaces after {% endfor %}.
  • Existing templates without surrounding whitespace: Behaviour unchanged; the condition and the inserted block are the same as before.

@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request resolves a critical bug in the _fix_chat_template function, which previously failed to correctly insert the add_generation_prompt wrapper into chat templates containing whitespace immediately after {% endfor %} or {% endif %}. By introducing a mechanism to strip whitespace for conditional checks while preserving it during template reconstruction, the change ensures that ChatML-style templates, particularly those used with LoRA adapters like Hermes, are properly patched. This eliminates RuntimeError issues for users and improves the robustness of template processing without affecting existing templates that lack such whitespace.

Highlights

  • Template Patching Logic: Updated the _fix_chat_template function to correctly process chat templates that include leading or trailing whitespace after {% endfor %} or {% endif %} blocks.
  • Whitespace Handling: Implemented a change where whitespace is now stripped from the after_endfor substring for condition checks, but the original whitespace is preserved when reassembling the patched template string.
  • Error Resolution: Resolved a RuntimeError that occurred when loading LoRA adapters with chat templates that previously failed the add_generation_prompt patching due to unhandled whitespace.
Changelog
  • unsloth/tokenizer_utils.py
    • Modified the _fix_chat_template function to correctly handle chat templates with whitespace after {% endfor %} or {% endif %} by stripping whitespace for condition checks and preserving it during template reassembly.
Activity
  • No human activity has been recorded on this pull request yet.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown
Contributor

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

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 addresses an issue where chat templates with leading or trailing whitespace around the final generation prompt were not being correctly patched. The change to strip the string before checking conditions and then preserving the original whitespace is a good fix. I've added one suggestion to improve the efficiency of how the prefix and suffix whitespace is extracted.

Comment on lines +670 to +672
prefix = after_endfor[: len(after_endfor) - len(after_endfor.lstrip())]
suffix = after_endfor[len(after_endfor.rstrip()) :]
inner = after_stripped
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

The current implementation uses lstrip() and rstrip() to extract the prefix and suffix whitespace. This can be made more efficient by using str.find() on the already-stripped string (after_stripped) to determine the boundaries of the content, and then slicing to get the prefix and suffix. This avoids creating extra temporary strings from lstrip() and rstrip().

        prefix_len = after_endfor.find(after_stripped)
        prefix = after_endfor[:prefix_len]
        suffix = after_endfor[prefix_len + len(after_stripped):]
        inner = after_stripped

@alphadl
Copy link
Copy Markdown
Author

alphadl commented Mar 14, 2026

Hi @mmathew23 @danielhanchen, This PR addresses #4150: ChatML-style templates with leading/trailing whitespace after {% endfor %} were not patched by _fix_chat_template, causing RuntimeError when loading Hermes LoRA for chat. The fix strips the "after endfor" segment for the condition check and preserves prefix/suffix whitespace when inserting the add_generation_prompt block. Happy to adjust if you'd like any tweaks. Thanks for maintaining Unsloth.

@alphadl alphadl force-pushed the fix/4150-hermes-chat-template branch from ad5472e to 9988f66 Compare March 16, 2026 14:43
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.

[Bug] Hermes Lora chat test bug: does not have a {% if add_generation_prompt %} for generation purposes

1 participant