Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Fix UnicodeEncodeError when printing emoji on legacy Windows consoles (#5948)

Daniel Han9a6f40483775
diff --git a/unsloth/__init__.py b/unsloth/__init__.py
index 75fb169e83e..fb11f1f649b 100644
--- a/unsloth/__init__.py
+++ b/unsloth/__init__.py
@@ -16,6 +16,27 @@ import os, importlib.util, platform
os.environ["UNSLOTH_IS_PRESENT"] = "1"
+# ── Windows console UTF-8 safety ─────────────────────────────────────────────
+# Legacy Windows consoles use a non-UTF-8 code page (e.g. cp1252) that cannot
+# encode the emoji / box-drawing glyphs Unsloth prints, so a bare
+# print("\U0001f9a5 ...") raises UnicodeEncodeError and aborts (observed at
+# SFTTrainer init, unsloth/trainer.py). Reconfigure stdout/stderr to UTF-8 ONLY
+# on Windows and ONLY when they are not already UTF-8 -- this is a no-op when
+# PYTHONUTF8 / PYTHONIOENCODING is set (Unsloth Studio worker, modern terminals)
+# and is never touched on Linux/macOS, so it cannot change their behaviour.
+# errors="replace" guarantees we can never crash on an unencodable glyph.
+if platform.system() == "Windows":
+ import sys as _sys
+
+ 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:
+ pass
+
def _is_mlx_available():
# Transitional import barrier: while the paired unsloth-zoo MLX runtime