Skip to content

Enable lstripBlocks and trimBlocks options for chat templates#12

Merged
DePasqualeOrg merged 1 commit intomainfrom
enable-jinja-whitespace-control
Mar 4, 2026
Merged

Enable lstripBlocks and trimBlocks options for chat templates#12
DePasqualeOrg merged 1 commit intomainfrom
enable-jinja-whitespace-control

Conversation

@DePasqualeOrg
Copy link
Copy Markdown
Owner

Cherry-pick of upstream #323.

Problem

Chat templates with Jinja block tags ({% for %}, {% if %}, etc.) produced extra whitespace and newlines in the rendered output. Templates that worked correctly in Python produced different results in Swift.

Fix

Pass lstripBlocks: true and trimBlocks: true when compiling Jinja templates, matching Python transformers which creates its Jinja environment with trim_blocks=True, lstrip_blocks=True (in chat_template_utils.py).

Our swift-jinja dependency (>= 2.0.0) already supports these options via EnvironmentConfig.

Changes

  • One-line change in PreTrainedTokenizer.compiledTemplate(for:): Template(templateString)Template(templateString, with: .init(lstripBlocks: true, trimBlocks: true))
  • New test for whitespace-sensitive templates
  • Fix to an existing test expectation affected by the whitespace change

Aligns with Python transformers, which creates its Jinja environment
with trim_blocks=True, lstrip_blocks=True.

Cherry-picked from huggingface/swift-transformers#323 (4f6c72b).

Co-authored-by: Sachin Desai <smdesai@gmail.com>
@DePasqualeOrg DePasqualeOrg merged commit 40c2211 into main Mar 4, 2026
6 checks passed
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.

2 participants