Skip to content

Fix UnicodeEncodeError when printing emoji on legacy Windows consoles - #5948

Merged
danielhanchen merged 2 commits into
mainfrom
fix/windows-console-utf8
Jun 3, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
fix/windows-console-utf8

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Problem

On Windows, stdout often uses a legacy code page (e.g. cp1252) that cannot encode the emoji / box-drawing glyphs Unsloth prints. A direct finetune then dies with:

UnicodeEncodeError: 'charmap' codec can't encode character '\U0001f9a5' in position 0: character maps to <undefined>

Repro: a direct unsloth/gemma-3-270m-it LoRA finetune on a default Windows console crashes at SFTTrainer init (unsloth/trainer.py, the "Padding-free auto-enabled" print) — before training starts. (Unsloth Studio is unaffected because its worker already runs with UTF-8 stdout.)

Fix

At unsloth import, on Windows only, reconfigure sys.stdout/sys.stderr to UTF-8 — but only when they are not already UTF-8:

  • no-op on Linux/macOS (platform.system() == "Windows" guard),
  • no-op when PYTHONUTF8/PYTHONIOENCODING is already set (Studio worker, modern terminals — encoding already contains utf),
  • guarded with hasattr(stream, "reconfigure") + try/except, errors="replace" so it can never itself raise.

One reconfigure at import covers every emoji print across unsloth + unsloth-zoo (shared process stdout), so no per-call-site edits are needed. Independent of transformers / TRL / vLLM versions.

No regressions

  • Linux/macOS: code path skipped entirely.
  • Windows where stdout is already UTF-8 (Studio, PYTHONUTF8): no-op (guard skips).
  • Applies to all Windows GPU types (NVIDIA/AMD/Intel/CPU) — it only ever fixes the same crash, never changes already-working output.

Verification

Direct gemma-3-270m-it LoRA finetune on a cp1252 Windows console: previously crashed at SFTTrainer init; with this change it prints fine and trains to completion (torch.compile path included).

danielhanchen and others added 2 commits June 2, 2026 06:02
On Windows, the console/stdout often uses a legacy code page (e.g. cp1252)
that cannot encode the emoji and box-drawing glyphs Unsloth prints. A bare
print of a sloth-emoji message then raises UnicodeEncodeError and aborts the
run -- e.g. SFTTrainer init in unsloth/trainer.py
("Padding-free auto-enabled") kills a direct finetune before training starts:

    UnicodeEncodeError: 'charmap' codec can't encode character '\U0001f9a5'

Fix: at unsloth import, on Windows ONLY, reconfigure sys.stdout/sys.stderr to
UTF-8 -- but ONLY when they are not already UTF-8. This is:
  * a no-op on Linux/macOS (guarded by platform.system() == "Windows"),
  * a no-op when PYTHONUTF8 / PYTHONIOENCODING is already set (Unsloth Studio
    worker, modern terminals) since the encoding already contains "utf",
  * guarded by hasattr(stream, "reconfigure") + try/except, with
    errors="replace" so it can never itself raise.

A single reconfigure at import covers every emoji print across unsloth and
unsloth-zoo (they share the process stdout), so no per-call-site changes are
needed. Independent of transformers / TRL / vLLM versions.

Verified: a direct `unsloth/gemma-3-270m-it` LoRA finetune on a cp1252 Windows
console previously crashed at SFTTrainer init; with this change it prints fine
and trains to completion (torch.compile path included).

Co-Authored-By: Claude Opus 4.8 <[email protected]>

@gemini-code-assist gemini-code-assist Bot 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.

Code Review

This pull request adds a Windows console UTF-8 safety check in unsloth/__init__.py to reconfigure stdout and stderr to UTF-8, preventing crashes due to unencodable glyphs on legacy Windows consoles. The review feedback suggests refactoring the stream check to perform the None check before accessing any attributes, which improves defensive programming and code clarity.

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.

Comment thread unsloth/__init__.py
Comment on lines +31 to +37
for _name in ("stdout", "stderr"):
_s = getattr(_sys, _name, None)
try:
_enc = (getattr(_s, "encoding", None) or "").lower()
if _s is not None and hasattr(_s, "reconfigure") and "utf" not in _enc:
_s.reconfigure(encoding = "utf-8", errors = "replace")
except Exception:

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

Defensive programming check: _s is checked for None on line 34, but its attribute is already accessed on line 33 via getattr(_s, "encoding", None). To prevent potential issues and follow proper defensive programming practices, the None check should be performed before any attribute access or helper calls on _s.

Suggested change
for _name in ("stdout", "stderr"):
_s = getattr(_sys, _name, None)
try:
_enc = (getattr(_s, "encoding", None) or "").lower()
if _s is not None and hasattr(_s, "reconfigure") and "utf" not in _enc:
_s.reconfigure(encoding = "utf-8", errors = "replace")
except Exception:
_s = getattr(_sys, _name, None)
if _s is not None:
try:
_enc = (getattr(_s, "encoding", None) or "").lower()
if hasattr(_s, "reconfigure") and "utf" not in _enc:
_s.reconfigure(encoding = "utf-8", errors = "replace")
except Exception:
pass

@danielhanchen
danielhanchen merged commit 9a6f404 into main Jun 3, 2026
44 of 45 checks passed
@danielhanchen
danielhanchen deleted the fix/windows-console-utf8 branch June 3, 2026 13:15
LeoBorcherding pushed a commit to LeoBorcherding/unsloth that referenced this pull request Jun 5, 2026
…unslothai#5948)

On Windows only, at unsloth import, reconfigure stdout/stderr to UTF-8 when they are not already, so emoji and box-drawing glyphs do not crash legacy code-page consoles (e.g. cp1252) at SFTTrainer init. No-op on Linux/macOS and when output is already UTF-8 (PYTHONUTF8, modern terminals), and fully guarded so it can never raise.
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.

1 participant